Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of FFG26 custom v1.0.4
BepInEx/plugins/AltDyrnwyn.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace AltDyrnwyn; [BepInPlugin("local.altdyrnwyn", "Alt Dyrnwyn", "0.1.1")] public sealed class Plugin : BaseUnityPlugin { private sealed class CraftContext { internal Inventory Inventory; internal bool Repeat; } [HarmonyPatch(typeof(ObjectDB), "Awake")] private static class DatabaseReady { [HarmonyPostfix] [HarmonyPriority(0)] private static void Postfix(ObjectDB __instance) { Register(__instance); } } [HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")] private static class DatabaseCopied { [HarmonyPostfix] [HarmonyPriority(0)] private static void Postfix(ObjectDB __instance) { Register(__instance); } } [HarmonyPatch(typeof(ZNetScene), "Awake")] private static class WorldReady { [HarmonyPriority(0)] [HarmonyPostfix] private static void Postfix() { Register(ObjectDB.instance); } } [HarmonyPatch(typeof(Player), "HaveRequirements", new Type[] { typeof(Recipe), typeof(bool), typeof(int), typeof(int) })] private static class UnlockCheck { [HarmonyPrefix] private static bool Prefix(Player __instance, Recipe __0, int __2, ref bool __result) { if (!IsRepeat(__0) || (Discovered(__instance) && __2 <= 1)) { return true; } __result = false; return false; } } [HarmonyPatch(typeof(Player), "GetAvailableRecipes")] private static class HideLockedRecipe { [HarmonyPostfix] private static void Postfix(Player __instance, ref List<Recipe> __0) { if (!Discovered(__instance)) { __0.RemoveAll(IsRepeat); } } } [HarmonyPatch(typeof(InventoryGui), "AddRecipeToList")] private static class NoDuplicateUpgrade { [HarmonyPrefix] private static bool Prefix(Recipe __1, ItemData __2) { if (IsRepeat(__1)) { return __2 == null; } return true; } } [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] private static class CraftingOrigin { [HarmonyPrefix] private static bool Prefix(Player __0, Recipe ___m_craftRecipe, ItemData ___m_craftUpgradeItem, out CraftContext __state) { __state = crafting; crafting = null; if (IsRepeat(___m_craftRecipe) && (!Discovered(__0) || ___m_craftUpgradeItem != null)) { return false; } if ((Object)(object)___m_craftRecipe != (Object)null && (Object)(object)___m_craftRecipe.m_item != (Object)null && ((Object)((Component)___m_craftRecipe.m_item).gameObject).name == "SwordDyrnwyn") { CraftContext craftContext = new CraftContext(); craftContext.Inventory = ((Humanoid)__0).GetInventory(); craftContext.Repeat = ((___m_craftUpgradeItem == null) ? IsRepeat(___m_craftRecipe) : FromRepeat(___m_craftUpgradeItem)); crafting = craftContext; } return true; } [HarmonyFinalizer] private static void Finalizer(CraftContext __state) { crafting = __state; } } [HarmonyPatch] private static class StampCraftedItem { private static MethodBase TargetMethod() { foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(typeof(Inventory))) { ParameterInfo[] parameters = declaredMethod.GetParameters(); if (declaredMethod.Name == "AddItem" && declaredMethod.ReturnType == typeof(ItemData) && parameters.Length == 8 && parameters[0].ParameterType == typeof(string)) { return declaredMethod; } } throw new MissingMethodException("Inventory.AddItem(string, ..., Vector2i, bool)"); } [HarmonyPostfix] private static void Postfix(Inventory __instance, string __0, ItemData __result) { if (crafting != null && crafting.Inventory == __instance && !(__0 != "SwordDyrnwyn") && __result != null) { if (crafting.Repeat) { __result.m_customData["local.altdyrnwyn.repeat"] = "1"; } else { __result.m_customData.Remove("local.altdyrnwyn.repeat"); } } } } [HarmonyPatch(typeof(ObjectDB), "GetRecipe")] private static class MatchRefundRecipe { [HarmonyPostfix] private static void Postfix(ItemData __0, ref Recipe __result) { if ((Object)(object)repeatRecipe != (Object)null && FromRepeat(__0) && __0.m_shared.m_name == repeatRecipe.m_item.m_itemData.m_shared.m_name) { __result = repeatRecipe; } } } public const string PluginId = "local.altdyrnwyn"; private const string RepeatName = "Recipe_AltDyrnwyn_Repeat"; private const string OriginKey = "local.altdyrnwyn.repeat"; private static Plugin instance; private static Recipe repeatRecipe; [ThreadStatic] private static CraftContext crafting; private void Awake() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) instance = this; new Harmony("local.altdyrnwyn").PatchAll(typeof(Plugin).Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Alt Dyrnwyn loaded."); } private static ItemDrop Item(ObjectDB db, string id) { GameObject itemPrefab = db.GetItemPrefab(id); ItemDrop val = (((Object)(object)itemPrefab == (Object)null) ? null : itemPrefab.GetComponent<ItemDrop>()); if ((Object)(object)val == (Object)null) { throw new InvalidOperationException("Missing item: " + id); } return val; } private static Requirement Copy(Requirement source) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown Requirement val = new Requirement(); FieldInfo[] fields = typeof(Requirement).GetFields(BindingFlags.Instance | BindingFlags.Public); foreach (FieldInfo fieldInfo in fields) { fieldInfo.SetValue(val, fieldInfo.GetValue(source)); } return val; } private static void Register(ObjectDB db) { //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Expected O, but got Unknown if ((Object)(object)instance == (Object)null || (Object)(object)db == (Object)null || (Object)(object)db.GetItemPrefab("SwordDyrnwyn") == (Object)null) { return; } try { Recipe val = db.m_recipes.Find((Recipe r) => (Object)(object)r != (Object)null && ((Object)r).name == "Recipe_AltDyrnwyn_Repeat"); if ((Object)(object)val != (Object)null) { repeatRecipe = val; return; } ItemDrop sword = Item(db, "SwordDyrnwyn"); ItemDrop resItem = Item(db, "MoltenCore"); ItemDrop resItem2 = Item(db, "FlametalNew"); Recipe val2 = db.m_recipes.Find((Recipe r) => (Object)(object)r != (Object)null && ((Object)r).name == "Recipe_SwordFire" && (Object)(object)r.m_item == (Object)(object)sword); if ((Object)(object)val2 == (Object)null) { throw new InvalidOperationException("Vanilla Recipe_SwordFire was not found."); } List<Requirement> list = new List<Requirement>(); Requirement val3 = null; Requirement[] resources = val2.m_resources; foreach (Requirement val4 in resources) { string name = ((Object)((Component)val4.m_resItem).gameObject).name; if (!(name == "FlametalNew") && !(name == "Flametal")) { Requirement val5 = Copy(val4); if (name == "GemstoneRed" || name == "MoltenCore") { val5.m_resItem = resItem; val3 = val5; } list.Add(val5); } } if (val3 == null) { throw new InvalidOperationException("Dyrnwyn's Bloodstone requirement was not found."); } Recipe val6 = Object.Instantiate<Recipe>(val2); ((Object)val6).name = "Recipe_AltDyrnwyn_Repeat"; val6.m_enabled = true; val6.m_amount = 1; val6.m_requireOnlyOneIngredient = false; Requirement val7 = Copy(val3); val7.m_amount = 1; Requirement[] array = (Requirement[])(object)new Requirement[2]; Requirement val8 = new Requirement(); val8.m_resItem = resItem2; val8.m_amount = 40; val8.m_amountPerLevel = 0; val8.m_recover = true; array[0] = val8; array[1] = val7; val6.m_resources = array; val2.m_resources = list.ToArray(); db.m_recipes.Add(val6); repeatRecipe = val6; } catch (Exception ex) { ((BaseUnityPlugin)instance).Logger.LogError((object)("Dyrnwyn recipes were not registered: " + ex)); } } private static bool IsRepeat(Recipe recipe) { if ((Object)(object)recipe != (Object)null) { return ((Object)recipe).name == "Recipe_AltDyrnwyn_Repeat"; } return false; } private static bool Discovered(Player player) { if ((Object)(object)player != (Object)null && (Object)(object)repeatRecipe != (Object)null) { return player.IsMaterialKnown(repeatRecipe.m_item.m_itemData.m_shared.m_name); } return false; } private static bool FromRepeat(ItemData item) { if (item != null && item.m_customData != null && item.m_customData.TryGetValue("local.altdyrnwyn.repeat", out var value)) { return value == "1"; } return false; } }
BepInEx/plugins/AltStonePortal.dll
Decompiled 2 weeks agousing System; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using HarmonyLib; using UnityEngine; [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace AltStonePortal; [BepInPlugin("local.altstoneportal", "Alt Stone Portal", "0.1.6")] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(TeleportWorld), "Awake")] private static class PortalReady { [HarmonyPostfix] private static void Postfix(TeleportWorld __instance) { string name = ((Object)((Component)__instance).gameObject).name; if ((!(name != "portal_stone") || !(name != "portal_stone(Clone)")) && (Object)(object)((Component)__instance).GetComponent<PortalRecolor>() == (Object)null) { ((Component)__instance).gameObject.AddComponent<PortalRecolor>(); } } } [HarmonyPatch(typeof(EffectList), "Create")] private static class ConnectionEffectReady { [HarmonyPostfix] private static void Postfix(GameObject[] __result) { if (__result == null) { return; } foreach (GameObject val in __result) { if (!((Object)(object)val != (Object)null) || !(((Object)val).name == "fx_portal_stone_connected(Clone)")) { continue; } try { PortalRecolor.TintEffects(val); } catch (Exception ex) { if ((Object)(object)instance != (Object)null) { ((BaseUnityPlugin)instance).Logger.LogError((object)("Connection recolor failed: " + ex)); } } } } } [HarmonyPatch(typeof(ZNetScene), "Awake")] private static class SceneReady { [HarmonyPostfix] [HarmonyPriority(0)] private static void Postfix(ZNetScene __instance) { if ((Object)(object)instance != (Object)null) { instance.Configure(__instance); } } } [HarmonyPatch(typeof(Piece), "Awake")] private static class PieceReady { [HarmonyPrefix] private static void Prefix(Piece __instance) { if (!((Object)(object)instance == (Object)null) && instance.requirements != null) { string name = ((Object)((Component)__instance).gameObject).name; if (name == "portal_stone" || name == "portal_stone(Clone)") { instance.Apply(__instance); } } } } [HarmonyPatch(typeof(ZNetScene), "OnDestroy")] private static class SceneClosed { [HarmonyPostfix] private static void Postfix() { if (!((Object)(object)instance == (Object)null)) { instance.requirements = null; instance.craftingStation = null; } } } public const string PluginId = "local.altstoneportal"; private static Plugin instance; private const string StationPrefab = "piece_stonecutter"; private Requirement[] requirements; private CraftingStation craftingStation; private void Awake() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) instance = this; new Harmony("local.altstoneportal").PatchAll(typeof(Plugin).Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Alt Stone Portal loaded; waiting for world prefabs."); } private void Configure(ZNetScene scene) { requirements = null; craftingStation = null; try { GameObject prefab = scene.GetPrefab("portal_stone"); Piece val = ((!((Object)(object)prefab == (Object)null)) ? prefab.GetComponent<Piece>() : null); if ((Object)(object)val == (Object)null) { throw new InvalidOperationException("portal_stone Piece was not found."); } GameObject prefab2 = scene.GetPrefab("piece_stonecutter"); CraftingStation val2 = ((!((Object)(object)prefab2 == (Object)null)) ? prefab2.GetComponent<CraftingStation>() : null); if ((Object)(object)val2 == (Object)null) { throw new InvalidOperationException("Unknown crafting station: piece_stonecutter"); } Requirement[] array = (Requirement[])(object)new Requirement[3] { Resource(scene, "Stone", 30), Resource(scene, "GreydwarfEye", 10), Resource(scene, "Wishbone", 1) }; requirements = array; craftingStation = val2; Apply(val); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Applied portal_stone recipe: Stone:30,GreydwarfEye:10,Wishbone:1; station: piece_stonecutter"); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Stone Portal recipe was not applied. " + ex.Message)); } } private static Requirement Resource(ZNetScene scene, string id, int amount) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown GameObject prefab = scene.GetPrefab(id); ItemDrop val = ((!((Object)(object)prefab == (Object)null)) ? prefab.GetComponent<ItemDrop>() : null); if ((Object)(object)val == (Object)null) { throw new InvalidOperationException("Unknown item prefab: " + id); } Requirement val2 = new Requirement(); val2.m_resItem = val; val2.m_amount = amount; val2.m_amountPerLevel = 0; val2.m_recover = true; return val2; } private void Apply(Piece piece) { piece.m_resources = requirements; piece.m_craftingStation = craftingStation; } } public sealed class PortalRecolor : MonoBehaviour { private static readonly Color Hue = new Color(0.07352942f, 1f, 0.73164296f, 1f); private Material ownedMaterial; private Texture2D ownedMask; private void Start() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_0015: 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_001f: 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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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_00e7: Expected O, but got Unknown //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) if ((int)SystemInfo.graphicsDeviceType == 4) { return; } try { TeleportWorld component = ((Component)this).GetComponent<TeleportWorld>(); component.m_colorTargetfound = Tint(component.m_colorTargetfound); component.m_colorUnconnected = Tint(component.m_colorUnconnected); Transform val = ((Component)this).transform.Find("_target_found_red"); if ((Object)(object)val != (Object)null) { TintEffects(((Component)val).gameObject); } Renderer model = (Renderer)(object)component.m_model; if ((Object)(object)model == (Object)null) { throw new InvalidOperationException("Missing portal model."); } Material sharedMaterial = model.sharedMaterial; if ((Object)(object)sharedMaterial == (Object)null || !sharedMaterial.HasProperty("_EmissiveTex")) { throw new InvalidOperationException("Missing portal emission material."); } Texture texture = sharedMaterial.GetTexture("_EmissiveTex"); if ((Object)(object)texture == (Object)null) { throw new InvalidOperationException("Missing portal emission texture."); } ownedMask = MakeMask(texture); ownedMaterial = new Material(sharedMaterial); ((Object)ownedMaterial).name = "AltStonePortal_Wishbone_Test"; ownedMaterial.SetTexture("_EmissiveTex", (Texture)(object)ownedMask); ownedMaterial.SetColor("_EmissionColor", Tint(sharedMaterial.GetColor("_EmissionColor"))); model.sharedMaterial = ownedMaterial; Debug.Log((object)"AltStonePortal: Applied wishbone recolor to stone portal."); } catch (Exception ex) { Debug.LogError((object)("AltStonePortal recolor failed: " + ex)); } } private static Color Tint(Color color) { //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_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_003e: 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_0054: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Max(color.r, Mathf.Max(color.g, color.b)); Color hue = Hue; float num2 = hue.r * num; Color hue2 = Hue; float num3 = hue2.g * num; Color hue3 = Hue; return new Color(num2, num3, hue3.b * num, color.a); } private static Gradient TintGradient(Gradient original) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) if (original == null) { return null; } GradientColorKey[] colorKeys = original.colorKeys; for (int i = 0; i < colorKeys.Length; i++) { colorKeys[i].color = Tint(colorKeys[i].color); } Gradient val = new Gradient(); val.SetKeys(colorKeys, original.alphaKeys); val.mode = original.mode; return val; } private static MinMaxGradient TintGradient(MinMaxGradient original) { //IL_0002: 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_0008: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown //IL_0027: 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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0052: 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_00a9: Unknown result type (might be due to invalid IL or missing references) ParticleSystemGradientMode mode = ((MinMaxGradient)(ref original)).mode; switch ((int)mode) { case 0: ((MinMaxGradient)(ref original)).color = Tint(((MinMaxGradient)(ref original)).color); break; case 2: ((MinMaxGradient)(ref original)).colorMin = Tint(((MinMaxGradient)(ref original)).colorMin); ((MinMaxGradient)(ref original)).colorMax = Tint(((MinMaxGradient)(ref original)).colorMax); break; case 3: ((MinMaxGradient)(ref original)).gradientMin = TintGradient(((MinMaxGradient)(ref original)).gradientMin); ((MinMaxGradient)(ref original)).gradientMax = TintGradient(((MinMaxGradient)(ref original)).gradientMax); break; default: ((MinMaxGradient)(ref original)).gradient = TintGradient(((MinMaxGradient)(ref original)).gradient); break; } return original; } public static void TintEffects(GameObject root) { //IL_0014: 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) //IL_0062: 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_006a: 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_0081: Invalid comparison between Unknown and I4 //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Invalid comparison between Unknown and I4 //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: 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_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Invalid comparison between Unknown and I4 //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: 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_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) Light[] componentsInChildren = root.GetComponentsInChildren<Light>(true); foreach (Light val in componentsInChildren) { val.color = Hue; } ParticleSystem[] componentsInChildren2 = root.GetComponentsInChildren<ParticleSystem>(true); foreach (ParticleSystem val2 in componentsInChildren2) { if (((Object)val2).name == "Black_suck") { continue; } MainModule main = val2.main; CustomDataModule customData = val2.customData; bool flag = ((CustomDataModule)(ref customData)).enabled && ((int)((CustomDataModule)(ref customData)).GetMode((ParticleSystemCustomData)0) == 2 || (int)((CustomDataModule)(ref customData)).GetMode((ParticleSystemCustomData)1) == 2); if (flag) { ParticleSystemCustomData[] array = (ParticleSystemCustomData[])(object)new ParticleSystemCustomData[2] { default(ParticleSystemCustomData), (ParticleSystemCustomData)1 }; foreach (ParticleSystemCustomData val3 in array) { if ((int)((CustomDataModule)(ref customData)).GetMode(val3) == 2) { ((CustomDataModule)(ref customData)).SetColor(val3, TintGradient(((CustomDataModule)(ref customData)).GetColor(val3))); } } } else { ((MainModule)(ref main)).startColor = TintGradient(((MainModule)(ref main)).startColor); } TrailModule trails = val2.trails; if (((TrailModule)(ref trails)).enabled) { ((TrailModule)(ref trails)).colorOverTrail = TintGradient(((TrailModule)(ref trails)).colorOverTrail); } Particle[] array2 = (Particle[])(object)new Particle[val2.particleCount]; int particles = val2.GetParticles(array2); if (!flag) { for (int l = 0; l < particles; l++) { ((Particle)(ref array2[l])).startColor = Color32.op_Implicit(Tint(Color32.op_Implicit(((Particle)(ref array2[l])).startColor))); } } val2.SetParticles(array2, particles); } } private static Texture2D MakeMask(Texture source) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) RenderTexture active = RenderTexture.active; bool sRGBWrite = GL.sRGBWrite; RenderTexture val = null; Texture2D val2 = null; try { val = RenderTexture.GetTemporary(source.width, source.height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)1); GL.sRGBWrite = false; Graphics.Blit(source, val); RenderTexture.active = val; val2 = new Texture2D(source.width, source.height, (TextureFormat)4, true, true); val2.ReadPixels(new Rect(0f, 0f, (float)source.width, (float)source.height), 0, 0); Color[] pixels = val2.GetPixels(); for (int i = 0; i < pixels.Length; i++) { Color val3 = pixels[i]; float num = Mathf.Max(val3.r, Mathf.Max(val3.g, val3.b)); ref Color reference = ref pixels[i]; reference = new Color(num, num, num, val3.a); } val2.SetPixels(pixels); ((Object)val2).name = "AltStonePortal_EmissionMask"; ((Texture)val2).wrapMode = source.wrapMode; ((Texture)val2).filterMode = source.filterMode; val2.Apply(true, true); return val2; } catch { if ((Object)(object)val2 != (Object)null) { Object.Destroy((Object)(object)val2); } throw; } finally { RenderTexture.active = active; GL.sRGBWrite = sRGBWrite; if ((Object)(object)val != (Object)null) { RenderTexture.ReleaseTemporary(val); } } } private void OnDestroy() { if ((Object)(object)ownedMaterial != (Object)null) { Object.Destroy((Object)(object)ownedMaterial); } if ((Object)(object)ownedMask != (Object)null) { Object.Destroy((Object)(object)ownedMask); } } }
BepInEx/plugins/AltStonecutter.dll
Decompiled 2 weeks agousing System; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace AltStonecutter; [BepInPlugin("local.altstonecutter", "Alt Stonecutter", "0.1.0")] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(ZNetScene), "Awake")] private static class SceneReady { [HarmonyPriority(0)] [HarmonyPostfix] private static void Postfix(ZNetScene __instance) { if ((Object)(object)instance != (Object)null) { instance.Configure(__instance); } } } [HarmonyPatch(typeof(Piece), "Awake")] private static class PieceReady { [HarmonyPrefix] private static void Prefix(Piece __instance) { if (!((Object)(object)instance == (Object)null)) { string name = ((Object)((Component)__instance).gameObject).name; if (name == "piece_stonecutter" || name == "piece_stonecutter(Clone)") { instance.ReplaceIron(__instance); } } } } [HarmonyPatch(typeof(ZNetScene), "OnDestroy")] private static class SceneClosed { [HarmonyPostfix] private static void Postfix() { if ((Object)(object)instance != (Object)null) { instance.bronze = null; } } } public const string PluginId = "local.altstonecutter"; private static Plugin instance; private ItemDrop bronze; private void Awake() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) instance = this; new Harmony("local.altstonecutter").PatchAll(typeof(Plugin).Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Alt Stonecutter loaded."); } private void Configure(ZNetScene scene) { bronze = null; try { GameObject prefab = scene.GetPrefab("piece_stonecutter"); Piece val = (((Object)(object)prefab == (Object)null) ? null : prefab.GetComponent<Piece>()); GameObject prefab2 = scene.GetPrefab("Bronze"); ItemDrop val2 = (((Object)(object)prefab2 == (Object)null) ? null : prefab2.GetComponent<ItemDrop>()); if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null) { throw new InvalidOperationException("Stonecutter or Bronze prefab was not found."); } bronze = val2; ReplaceIron(val); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Stonecutter recipe configured to use bronze instead of iron."); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Stonecutter recipe was not applied: " + ex)); } } private void ReplaceIron(Piece piece) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown if ((Object)(object)bronze == (Object)null || piece.m_resources == null) { return; } Requirement[] array = (Requirement[])piece.m_resources.Clone(); bool flag = false; for (int i = 0; i < array.Length; i++) { Requirement val = array[i]; if (val != null && !((Object)(object)val.m_resItem == (Object)null) && !(((Object)((Component)val.m_resItem).gameObject).name != "Iron")) { Requirement val2 = new Requirement(); FieldInfo[] fields = typeof(Requirement).GetFields(BindingFlags.Instance | BindingFlags.Public); foreach (FieldInfo fieldInfo in fields) { fieldInfo.SetValue(val2, fieldInfo.GetValue(val)); } val2.m_resItem = bronze; array[i] = val2; flag = true; } } if (flag) { piece.m_resources = array; } } }
BepInEx/plugins/BetterChestStatus.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using BepInEx; using HarmonyLib; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace BetterChestStatus; [BepInPlugin("local.bettercheststatus", "Better Chest Status", "0.1.0")] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(Container), "GetHoverText")] private static class HoverText { [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Expected O, but got Unknown //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); foreach (CodeInstruction instruction in instructions) { list.Add(new CodeInstruction(instruction)); } FieldInfo fieldInfo = AccessTools.Field(typeof(Container), "m_name"); MethodInfo methodInfo = AccessTools.Method(typeof(Plugin), "AddStatus", (Type[])null, (Type[])null); int num = -1; int num2 = 0; int num3 = 0; for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldstr && object.Equals(list[i].operand, " ( $piece_container_empty )")) { num3++; } if (i > 0 && i + 1 < list.Count && list[i - 1].opcode == OpCodes.Ldarg_0 && CodeInstructionExtensions.LoadsField(list[i], fieldInfo, false) && list[i + 1].opcode == OpCodes.Stloc_0) { num = i; num2++; } } if (num2 != 1 || num3 != 1) { throw new InvalidOperationException("Expected one nonempty name assignment and one vanilla EMPTY marker."); } list.InsertRange(num + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Call, (object)methodInfo) }); return list; } } public const string PluginId = "local.bettercheststatus"; private Harmony harmony; private void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown harmony = new Harmony("local.bettercheststatus"); try { harmony.PatchAll(typeof(Plugin).Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Better Chest Status loaded."); } catch (Exception ex) { harmony.UnpatchSelf(); ((BaseUnityPlugin)this).Logger.LogError((object)("Better Chest Status disabled: incompatible hover text IL. " + ex)); } } private void OnDestroy() { if (harmony != null) { harmony.UnpatchSelf(); } } private static string AddStatus(string name, Container container) { Inventory inventory = container.GetInventory(); if (inventory == null || inventory.HaveEmptySlot()) { return name; } List<ItemData> allItems = inventory.GetAllItems(); if (allItems.Count == 0) { return name; } foreach (ItemData item in allItems) { if (item.m_stack < item.m_shared.m_maxStackSize) { return name + " ( NO SLOTS )"; } } return name + " ( FULL )"; } }
BepInEx/plugins/BetterCraftingList.dll
Decompiled 2 weeks agousing System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using BepInEx; using HarmonyLib; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace BetterCraftingList; [BepInPlugin("local.bettercraftinglist", "Better Crafting List", "0.1.2")] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(InventoryGui), "AddRecipeToList")] private static class FilterRecipes { [HarmonyPriority(0)] private static bool Prefix(InventoryGui __instance, Recipe __1, ItemData __2, bool __3) { if (!Matches(__1)) { return false; } if ((Object)(object)instance == (Object)null || (Object)(object)instance.gui != (Object)(object)__instance || (Object)(object)instance.scroll == (Object)null) { return true; } return !RecipeRows.Add(__instance, __1, __2, __3); } } [HarmonyPatch(typeof(InventoryGui), "UpdateRecipeList")] private static class KeepScrollPosition { private static void Prefix(InventoryGui __instance, ref List<Recipe> __0, out float __state) { ScrollRect componentInParent = ((Component)__instance.m_recipeListRoot).GetComponentInParent<ScrollRect>(); __state = (IsCraftingScroll(componentInParent) ? ((1f - Mathf.Clamp01(componentInParent.verticalNormalizedPosition)) * Travel(componentInParent)) : 0f); RecipeRows.Begin(__instance); if ((Object)(object)instance != (Object)null && instance.query.Length > 0) { __0 = __0.FindAll(Matches); } } private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { MethodInfo destroy = AccessTools.Method(typeof(Object), "Destroy", new Type[1] { typeof(Object) }, (Type[])null); int replaced = 0; foreach (CodeInstruction instruction in instructions) { if (CodeInstructionExtensions.Calls(instruction, destroy)) { instruction.operand = AccessTools.Method(typeof(RecipeRows), "Release", (Type[])null, (Type[])null); replaced++; } yield return instruction; } if (replaced != 1) { throw new InvalidOperationException("Recipe row release call changed."); } } private static void Postfix(InventoryGui __instance, float __state) { ScrollRect componentInParent = ((Component)__instance.m_recipeListRoot).GetComponentInParent<ScrollRect>(); if (IsCraftingScroll(componentInParent)) { componentInParent.StopMovement(); float num = Travel(componentInParent); componentInParent.verticalNormalizedPosition = ((num > 0f) ? Mathf.Clamp01(1f - __state / num) : 1f); __instance.m_recipeListScroll.numberOfSteps = 0; } } } [HarmonyPatch(typeof(ScrollRect), "OnScroll")] private static class ScrollOneRow { private static bool Prefix(ScrollRect __instance, PointerEventData __0) { //IL_0018: 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) //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) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009a: 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) if (!IsCraftingScroll(__instance)) { return true; } if (!((UIBehaviour)__instance).IsActive() || __0 == null) { return false; } float y = __0.scrollDelta.y; float num = ((y == 0f) ? 0f : Mathf.Sign(y)); float num2 = Travel(__instance); __instance.StopMovement(); if (num2 > 0f && num != 0f) { RectTransform val = (RectTransform)(((Object)(object)__instance.viewport != (Object)null) ? ((object)__instance.viewport) : ((object)/*isinst with value type is only supported in some contexts*/)); Vector3 val2 = ((Transform)__instance.content).TransformVector(Vector3.up * InventoryGui.instance.m_recipeListSpace); float num3 = Mathf.Abs(((Transform)val).InverseTransformVector(val2).y); __instance.verticalNormalizedPosition = Mathf.Clamp01(__instance.verticalNormalizedPosition + num * num3 / num2); } ((AbstractEventData)__0).Use(); return false; } } [HarmonyPatch(typeof(ScrollRectEnsureVisible), "CenterOnItem")] private static class CenterRecipe { private static bool Prefix(ScrollRectEnsureVisible __instance, RectTransform __0) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: 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_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_00bc: Unknown result type (might be due to invalid IL or missing references) InventoryGui instance = InventoryGui.instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.m_recipeEnsureVisible != (Object)(object)__instance || (Object)(object)__0 == (Object)null) { return true; } ScrollRect componentInParent = ((Component)instance.m_recipeListRoot).GetComponentInParent<ScrollRect>(); if (!IsCraftingScroll(componentInParent)) { return true; } RectTransform val = (RectTransform)(((Object)(object)componentInParent.viewport != (Object)null) ? ((object)componentInParent.viewport) : ((object)/*isinst with value type is only supported in some contexts*/)); float num = Travel(componentInParent); componentInParent.StopMovement(); if (num <= 0f) { componentInParent.verticalNormalizedPosition = 1f; return false; } Rect rect = __0.rect; Vector3 val2 = ((Transform)val).InverseTransformPoint(((Transform)__0).TransformPoint(Vector2.op_Implicit(((Rect)(ref rect)).center))); float verticalNormalizedPosition = componentInParent.verticalNormalizedPosition; float y = val2.y; Rect rect2 = val.rect; componentInParent.verticalNormalizedPosition = Mathf.Clamp01(verticalNormalizedPosition + (y - ((Rect)(ref rect2)).center.y) / num); return false; } } [HarmonyPatch(typeof(InventoryGui), "Update")] private static class TypingKeys { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { MethodInfo button = AccessTools.Method(typeof(ZInput), "GetButtonDown", new Type[1] { typeof(string) }, (Type[])null); MethodInfo key = AccessTools.Method(typeof(ZInput), "GetKeyDown", new Type[2] { typeof(KeyCode), typeof(bool) }, (Type[])null); foreach (CodeInstruction instruction in instructions) { if (CodeInstructionExtensions.Calls(instruction, button)) { instruction.operand = AccessTools.Method(typeof(Plugin), "InventoryButtonDown", (Type[])null, (Type[])null); } if (CodeInstructionExtensions.Calls(instruction, key)) { instruction.operand = AccessTools.Method(typeof(Plugin), "InventoryKeyDown", (Type[])null, (Type[])null); } yield return instruction; } } } [HarmonyPatch(typeof(InventoryGui), "UpdateGamepad")] private static class TypingGamepad { private static bool Prefix() { return !Editing(); } } [HarmonyPatch(typeof(Player), "TakeInput")] private static class TypingPlayerInput { private static void Postfix(Player __instance, ref bool __result) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && Editing()) { __result = false; } } } [HarmonyPatch(typeof(Player), "SetControls")] private static class TypingPlayerControls { [HarmonyPriority(0)] private static void Prefix(Player __instance, ref Vector3 movedir, ref bool attack, ref bool attackHold, ref bool secondaryAttack, ref bool secondaryAttackHold, ref bool block, ref bool blockHold, ref bool jump, ref bool crouch, ref bool run, ref bool autoRun, ref bool dodge, ref bool ___m_autoRun) { //IL_0016: 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) if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && Editing()) { movedir = Vector3.zero; attack = (attackHold = (secondaryAttack = (secondaryAttackHold = (block = (blockHold = false))))); jump = (crouch = (run = (autoRun = (dodge = false)))); ___m_autoRun = false; } } } [HarmonyPatch(typeof(InventoryGui), "Hide")] private static class ClearSearch { private static void Postfix() { if (!((Object)(object)instance == (Object)null)) { instance.query = ""; instance.pendingQuery = ""; instance.searchPending = false; instance.localizedNames.Clear(); if ((Object)(object)instance.search != (Object)null) { instance.search.DeactivateInputField(false); instance.search.SetTextWithoutNotify(""); } } } } public const string Id = "local.bettercraftinglist"; private static Plugin instance; private static readonly Action<InventoryGui, bool> Refresh = AccessTools.MethodDelegate<Action<InventoryGui, bool>>(AccessTools.Method(typeof(InventoryGui), "UpdateCraftingPanel", (Type[])null, (Type[])null), (object)null, true); private Harmony harmony; private InventoryGui gui; private ScrollRect scroll; private RectTransform viewport; private RectTransform originalViewport; private TMP_InputField search; private Vector2 originalMax; private int originalSteps; private bool originalInertia; private MovementType originalMovement; private string query = ""; private string pendingQuery = ""; private bool searchPending; private float searchAfter; private readonly Dictionary<string, string> localizedNames = new Dictionary<string, string>(); private int suppressFrame = -1; private void Awake() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown instance = this; harmony = new Harmony("local.bettercraftinglist"); harmony.PatchAll(typeof(Plugin).Assembly); } private void LateUpdate() { if ((Object)(object)InventoryGui.instance == (Object)null || !InventoryGui.IsVisible()) { return; } if ((Object)(object)gui != (Object)(object)InventoryGui.instance || (Object)(object)search == (Object)null) { Attach(InventoryGui.instance); } if (searchPending && Time.unscaledTime >= searchAfter && (Object)(object)gui != (Object)null && (Object)(object)Player.m_localPlayer != (Object)null) { query = pendingQuery; searchPending = false; Refresh(gui, arg2: false); if ((Object)(object)scroll != (Object)null) { scroll.StopMovement(); scroll.verticalNormalizedPosition = 1f; } } RecipeRows.Render(scroll); } private void Attach(InventoryGui source) { //IL_00bd: 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_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: 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_0389: Unknown result type (might be due to invalid IL or missing references) Detach(); ScrollRect componentInParent = ((Component)source.m_recipeListRoot).GetComponentInParent<ScrollRect>(); if ((Object)(object)componentInParent == (Object)null || (Object)(object)componentInParent.content != (Object)(object)source.m_recipeListRoot) { return; } RectTransform val = componentInParent.viewport; if ((Object)(object)val == (Object)null) { Mask componentInParent2 = ((Component)source.m_recipeListRoot).GetComponentInParent<Mask>(); RectMask2D componentInParent3 = ((Component)source.m_recipeListRoot).GetComponentInParent<RectMask2D>(); val = (((Object)(object)componentInParent2 != (Object)null) ? componentInParent2.rectTransform : (((Object)(object)componentInParent3 != (Object)null) ? componentInParent3.rectTransform : null)); } if ((Object)(object)val == (Object)null || (Object)(object)((Transform)val).parent == (Object)null) { return; } gui = source; scroll = componentInParent; viewport = val; originalViewport = componentInParent.viewport; componentInParent.viewport = val; originalMax = val.offsetMax; originalSteps = gui.m_recipeListScroll.numberOfSteps; originalInertia = scroll.inertia; originalMovement = scroll.movementType; scroll.inertia = false; scroll.movementType = (MovementType)2; scroll.StopMovement(); gui.m_recipeListScroll.numberOfSteps = 0; RectTransform val2 = NewRect("CraftingSearch", ((Transform)val).parent); val2.anchorMin = new Vector2(val.anchorMin.x, val.anchorMax.y); val2.anchorMax = val.anchorMax; val2.pivot = new Vector2(0.5f, 1f); val2.offsetMin = new Vector2(val.offsetMin.x, originalMax.y - 34f); val2.offsetMax = originalMax; Image val3 = ((Component)val2).gameObject.AddComponent<Image>(); ((Graphic)val3).color = new Color(0.08f, 0.08f, 0.08f, 1f); RectTransform val4 = NewRect("TextArea", (Transform)(object)val2); Stretch(val4, 8f, 4f); ((Component)val4).gameObject.AddComponent<RectMask2D>(); TMP_Text textComponent = NewText("Text", (Transform)(object)val4); TMP_Text val5 = NewText("Search", (Transform)(object)val4); val5.text = "Search"; ((Graphic)val5).color = new Color(0.7f, 0.7f, 0.7f, 1f); search = ((Component)val2).gameObject.AddComponent<TMP_InputField>(); search.textViewport = val4; search.textComponent = textComponent; search.placeholder = (Graphic)(object)val5; ((Selectable)search).targetGraphic = (Graphic)(object)val3; search.lineType = (LineType)0; search.characterLimit = 100; search.richText = false; ((Selectable)search).transition = (Transition)0; TMP_InputField obj = search; Navigation navigation = default(Navigation); ((Navigation)(ref navigation)).mode = (Mode)0; ((Selectable)obj).navigation = navigation; ((UnityEvent<string>)(object)search.onValueChanged).AddListener((UnityAction<string>)OnSearch); ((UnityEvent<string>)(object)search.onSelect).AddListener((UnityAction<string>)delegate { suppressFrame = Time.frameCount; }); ((UnityEvent<string>)(object)search.onDeselect).AddListener((UnityAction<string>)delegate { suppressFrame = Time.frameCount; }); ((UnityEvent<string>)(object)search.onSubmit).AddListener((UnityAction<string>)delegate { search.DeactivateInputField(false); if ((Object)(object)EventSystem.current != (Object)null) { EventSystem.current.SetSelectedGameObject((GameObject)null); } suppressFrame = Time.frameCount; }); viewport.offsetMax = new Vector2(originalMax.x, originalMax.y - 40f); ((Transform)val2).SetAsLastSibling(); } private TMP_Text NewText(string name, Transform parent) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) RectTransform val = NewRect(name, parent); Stretch(val, 0f, 0f); TextMeshProUGUI val2 = ((Component)val).gameObject.AddComponent<TextMeshProUGUI>(); ((TMP_Text)val2).font = gui.m_recipeName.font; ((TMP_Text)val2).fontSize = 18f; ((Graphic)val2).color = Color.white; ((TMP_Text)val2).alignment = (TextAlignmentOptions)4097; ((TMP_Text)val2).textWrappingMode = (TextWrappingModes)0; ((TMP_Text)val2).richText = false; ((Graphic)val2).raycastTarget = false; return (TMP_Text)(object)val2; } private static RectTransform NewRect(string name, Transform parent) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) RectTransform component = new GameObject(name, new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>(); ((Transform)component).SetParent(parent, false); return component; } private static void Stretch(RectTransform rect, float x, float y) { //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(x, y); rect.offsetMax = new Vector2(0f - x, 0f - y); } private void OnSearch(string value) { pendingQuery = value.Trim(); searchPending = query != pendingQuery; searchAfter = Time.unscaledTime + 0.075f; } private static bool Matches(Recipe recipe) { if ((Object)(object)instance == (Object)null || instance.query.Length == 0 || (Object)(object)recipe == (Object)null || (Object)(object)recipe.m_item == (Object)null) { return true; } string name = recipe.m_item.m_itemData.m_shared.m_name; if (!instance.localizedNames.TryGetValue(name, out var value)) { value = ((Localization.instance != null) ? Localization.instance.Localize(name) : name); instance.localizedNames[name] = value; } name = value; return name.IndexOf(instance.query, StringComparison.OrdinalIgnoreCase) >= 0; } private static bool Editing() { if ((Object)(object)instance != (Object)null && (Object)(object)instance.search != (Object)null) { if (!instance.search.isFocused) { return instance.suppressFrame >= Time.frameCount; } return true; } return false; } private static bool InventoryButtonDown(string name) { if (!Editing()) { return ZInput.GetButtonDown(name); } return false; } private static bool InventoryKeyDown(KeyCode key, bool logWarning) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) if (!Editing()) { return ZInput.GetKeyDown(key, logWarning); } return false; } private static bool IsCraftingScroll(ScrollRect target) { if ((Object)(object)InventoryGui.instance != (Object)null && (Object)(object)target != (Object)null) { return (Object)(object)target.content == (Object)(object)InventoryGui.instance.m_recipeListRoot; } return false; } private static float Travel(ScrollRect target) { //IL_0037: 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) //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_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) RectTransform val = target.viewport; if ((Object)(object)val == (Object)null) { Transform transform = ((Component)target).transform; val = (RectTransform)(object)((transform is RectTransform) ? transform : null); } Vector3[] array = (Vector3[])(object)new Vector3[4]; target.content.GetWorldCorners(array); float num = Mathf.Abs(((Transform)val).InverseTransformPoint(array[1]).y - ((Transform)val).InverseTransformPoint(array[0]).y); Rect rect = val.rect; return Mathf.Max(0f, num - ((Rect)(ref rect)).height); } private void Detach() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)viewport != (Object)null) { viewport.offsetMax = originalMax; } if ((Object)(object)scroll != (Object)null) { scroll.viewport = originalViewport; scroll.inertia = originalInertia; scroll.movementType = originalMovement; } if ((Object)(object)gui != (Object)null && (Object)(object)gui.m_recipeListScroll != (Object)null) { gui.m_recipeListScroll.numberOfSteps = originalSteps; } if ((Object)(object)search != (Object)null) { ((Component)search).gameObject.SetActive(false); Object.Destroy((Object)(object)((Component)search).gameObject); } search = null; viewport = null; scroll = null; gui = null; query = ""; pendingQuery = ""; searchPending = false; localizedNames.Clear(); } private void OnDestroy() { if (harmony != null) { harmony.UnpatchSelf(); } Detach(); RecipeRows.Clear(); instance = null; } } internal static class RecipeRows { private sealed class Row { internal RectTransform rect; internal GameObject selected; internal Recipe recipe; internal ItemData item; internal bool canCraft; internal bool dirty; internal View view; } private sealed class View { internal GameObject go; internal Image icon; internal TMP_Text name; internal TMP_Text quality; internal GuiBar durability; internal GameObject selected; internal Row row; } private static readonly FieldInfo Available = AccessTools.Field(typeof(InventoryGui), "m_availableRecipes"); private static readonly Action<InventoryGui, GameObject> Select = AccessTools.MethodDelegate<Action<InventoryGui, GameObject>>(AccessTools.Method(typeof(InventoryGui), "OnSelectedRecipe", (Type[])null, (Type[])null), (object)null, true); private static readonly Func<Recipe, ItemData, GameObject, bool, object> Pair = CreatePairFactory(); private static readonly Dictionary<GameObject, Row> rows = new Dictionary<GameObject, Row>(); private static readonly Stack<Row> spareRows = new Stack<Row>(); private static readonly Stack<View> spareViews = new Stack<View>(); private static readonly List<Row> active = new List<Row>(); private static readonly Vector3[] corners = (Vector3[])(object)new Vector3[4]; private static InventoryGui owner; private static RectTransform pool; private static Func<Recipe, ItemData, GameObject, bool, object> CreatePairFactory() { Type type = AccessTools.Inner(typeof(InventoryGui), "RecipeDataPair"); Type[] array = new Type[4] { typeof(Recipe), typeof(ItemData), typeof(GameObject), typeof(bool) }; ConstructorInfo con = AccessTools.Constructor(type, array, false); DynamicMethod dynamicMethod = new DynamicMethod("CreateRecipePair", typeof(object), array, typeof(RecipeRows), skipVisibility: true); ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); for (int i = 0; i < array.Length; i++) { iLGenerator.Emit(OpCodes.Ldarg, (short)i); } iLGenerator.Emit(OpCodes.Newobj, con); iLGenerator.Emit(OpCodes.Box, type); iLGenerator.Emit(OpCodes.Ret); return (Func<Recipe, ItemData, GameObject, bool, object>)dynamicMethod.CreateDelegate(typeof(Func<Recipe, ItemData, GameObject, bool, object>)); } internal static void Begin(InventoryGui gui) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)owner != (Object)(object)gui) { Clear(); owner = gui; pool = new GameObject("CraftingRowPool", new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>(); ((Transform)pool).SetParent(((Transform)gui.m_recipeListRoot).parent, false); ((Component)pool).gameObject.SetActive(false); } active.Clear(); } internal static bool Add(InventoryGui gui, Recipe recipe, ItemData item, bool canCraft) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown //IL_0078: 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_009e: 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_00b6: 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_00e4: Expected O, but got Unknown //IL_0160: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)owner != (Object)(object)gui || (Object)(object)pool == (Object)null) { return false; } IList list = (IList)Available.GetValue(gui); Row row; if (spareRows.Count > 0) { row = spareRows.Pop(); } else { RectTransform val = (RectTransform)gui.m_recipeElementPrefab.transform; RectTransform component = new GameObject("RecipeRow", new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>(); ((Transform)component).SetParent((Transform)(object)gui.m_recipeListRoot, false); component.anchorMin = val.anchorMin; component.anchorMax = val.anchorMax; component.pivot = val.pivot; component.sizeDelta = val.sizeDelta; GameObject val2 = new GameObject("selected", new Type[1] { typeof(RectTransform) }); val2.transform.SetParent((Transform)(object)component, false); Row row2 = new Row(); row2.rect = component; row2.selected = val2; row = row2; rows.Add(((Component)component).gameObject, row); } row.recipe = recipe; row.item = item; row.canCraft = canCraft; row.dirty = true; row.selected.SetActive(false); row.rect.anchoredPosition = new Vector2(0f, (float)(-list.Count) * gui.m_recipeListSpace); ((Component)row.rect).gameObject.SetActive(true); active.Add(row); list.Add(Pair(recipe, item, ((Component)row.rect).gameObject, canCraft)); return true; } internal static void Release(Object value) { GameObject val = (GameObject)(object)((value is GameObject) ? value : null); if ((Object)(object)val == (Object)null || !rows.TryGetValue(val, out var value2)) { Object.Destroy(value); return; } ReturnView(value2); val.SetActive(false); spareRows.Push(value2); } private static void ReturnView(Row row) { if (row.view != null) { row.view.go.SetActive(false); row.view.go.transform.SetParent((Transform)(object)pool, false); row.view.row = null; spareViews.Push(row.view); row.view = null; } } private static View CreateView() { //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Expected O, but got Unknown GameObject val = Object.Instantiate<GameObject>(owner.m_recipeElementPrefab, (Transform)(object)pool); val.SetActive(false); View view = new View { go = val, icon = ((Component)val.transform.Find("icon")).GetComponent<Image>(), name = ((Component)val.transform.Find("name")).GetComponent<TMP_Text>(), quality = ((Component)val.transform.Find("QualityLevel")).GetComponent<TMP_Text>(), durability = ((Component)val.transform.Find("Durability")).GetComponent<GuiBar>(), selected = ((Component)val.transform.Find("selected")).gameObject }; Button component = val.GetComponent<Button>(); ((UnityEventBase)component.onClick).RemoveAllListeners(); ((UnityEvent)component.onClick).AddListener((UnityAction)delegate { if ((Object)(object)owner != (Object)null && view.row != null) { Select(owner, ((Component)view.row.rect).gameObject); } }); RecipeRowClicks recipeRowClicks = val.AddComponent<RecipeRowClicks>(); recipeRowClicks.Target = () => (view.row != null) ? ((Component)view.row.rect).gameObject : null; return view; } private static void Bind(Row row) { //IL_0050: 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_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) View view = row.view; view.icon.sprite = row.recipe.m_item.m_itemData.GetIcon(); ((Graphic)view.icon).color = (Color)(row.canCraft ? Color.white : new Color(1f, 0f, 1f, 0f)); string text = Localization.instance.Localize(row.recipe.m_item.m_itemData.m_shared.m_name); if (row.recipe.m_amount > 1) { text = text + " x" + row.recipe.m_amount; } view.name.text = text; ((Graphic)view.name).color = (Color)(row.canCraft ? Color.white : new Color(0.66f, 0.66f, 0.66f, 1f)); bool flag = row.item != null && row.item.m_shared.m_useDurability && row.item.m_durability < row.item.GetMaxDurability(); ((Component)view.durability).gameObject.SetActive(flag); if (flag) { view.durability.SetValue(row.item.GetDurabilityPercentage()); } ((Component)view.quality).gameObject.SetActive(row.item != null); if (row.item != null) { view.quality.text = row.item.m_quality.ToString(); } row.dirty = false; } internal static void Render(ScrollRect scroll) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: 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_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Expected O, but got Unknown //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: 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_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)owner == (Object)null || (Object)(object)pool == (Object)null || (Object)(object)scroll == (Object)null || !InventoryGui.IsVisible()) { return; } _ = owner.m_recipeListRoot; RectTransform val = (RectTransform)(((Object)(object)scroll.viewport != (Object)null) ? ((object)scroll.viewport) : ((object)(RectTransform)((Component)scroll).transform)); Rect rect = val.rect; float bottom = ((Rect)(ref rect)).yMin - owner.m_recipeListSpace; Rect rect2 = val.rect; float top = ((Rect)(ref rect2)).yMax + owner.m_recipeListSpace; foreach (Row item in active) { if (!IsVisible(item.rect, val, bottom, top)) { ReturnView(item); } } int num = 4; foreach (Row item2 in active) { if (!IsVisible(item2.rect, val, bottom, top)) { continue; } if (item2.view == null) { if (spareViews.Count > 0) { item2.view = spareViews.Pop(); } else { if (num == 0) { continue; } num--; item2.view = CreateView(); } item2.view.row = item2; item2.view.go.transform.SetParent((Transform)(object)item2.rect, false); RectTransform val2 = (RectTransform)item2.view.go.transform; val2.anchorMin = Vector2.zero; val2.anchorMax = Vector2.one; Vector2 offsetMin = (val2.offsetMax = Vector2.zero); val2.offsetMin = offsetMin; item2.dirty = true; } if (item2.dirty) { Bind(item2); } item2.view.selected.SetActive(item2.selected.activeSelf); item2.view.go.SetActive(true); } } private static bool IsVisible(RectTransform row, RectTransform viewport, float bottom, float top) { //IL_0027: 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) row.GetWorldCorners(corners); float num = float.PositiveInfinity; float num2 = float.NegativeInfinity; for (int i = 0; i < corners.Length; i++) { float y = ((Transform)viewport).InverseTransformPoint(corners[i]).y; num = Mathf.Min(num, y); num2 = Mathf.Max(num2, y); } if (num2 >= bottom) { return num <= top; } return false; } internal static void Clear() { foreach (Row value in rows.Values) { if ((Object)(object)value.rect != (Object)null) { Object.Destroy((Object)(object)((Component)value.rect).gameObject); } } if ((Object)(object)pool != (Object)null) { Object.Destroy((Object)(object)((Component)pool).gameObject); } rows.Clear(); spareRows.Clear(); spareViews.Clear(); active.Clear(); owner = null; pool = null; } } public sealed class RecipeRowClicks : MonoBehaviour, IPointerClickHandler, IEventSystemHandler { internal Func<GameObject> Target; public void OnPointerClick(PointerEventData eventData) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)eventData.button == 2 && Target != null) { GameObject val = Target(); if ((Object)(object)val != (Object)null) { ExecuteEvents.Execute<IPointerClickHandler>(val, (BaseEventData)(object)eventData, ExecuteEvents.pointerClickHandler); } } } }
BepInEx/plugins/BetterNoStamina.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using BepInEx; using HarmonyLib; using UnityEngine; [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyVersion("0.0.0.0")] namespace BetterNoStamina; [BepInIncompatibility("Basil_NoStamCosts")] [BepInPlugin("local.betternostamina", "Better No Stamina", "0.1.0")] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(Player), "UpdatePlacement", new Type[] { typeof(bool), typeof(float) })] private static class Placement { [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { return Rewrite(instructions, 2, 2); } } [HarmonyPatch(typeof(Player), "Repair", new Type[] { typeof(ItemData), typeof(Piece) })] private static class Repair { [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { return Rewrite(instructions, 0, 1); } } public const string PluginId = "local.betternostamina"; private Harmony harmony; private static FieldInfo rightItem; private void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown harmony = new Harmony("local.betternostamina"); try { rightItem = AccessTools.Field(typeof(Humanoid), "m_rightItem"); if (rightItem == null) { throw new MissingFieldException(typeof(Humanoid).FullName, "m_rightItem"); } harmony.PatchAll(typeof(Plugin).Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Better No Stamina loaded: hammer, hoe and cultivator actions are stamina-free."); } catch (Exception ex) { harmony.UnpatchSelf(); ((BaseUnityPlugin)this).Logger.LogError((object)("Better No Stamina disabled: incompatible action IL. " + ex)); } } private void OnDestroy() { if (harmony != null) { harmony.UnpatchSelf(); } } private static bool IsSupportedTool(Character character) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown Player val = (Player)(object)((character is Player) ? character : null); if ((Object)(object)val == (Object)null) { return false; } ItemData val2 = (ItemData)rightItem.GetValue(val); if (val2 == null || (Object)(object)val2.m_dropPrefab == (Object)null) { return false; } string name = ((Object)val2.m_dropPrefab).name; if (!(name == "Hammer") && !(name == "Hoe")) { return name == "Cultivator"; } return true; } private static bool HaveActionStamina(Character character, float amount) { if (!IsSupportedTool(character)) { return character.HaveStamina(amount); } return true; } private static void UseActionStamina(Character character, float amount) { if (!IsSupportedTool(character)) { character.UseStamina(amount); } } private static IEnumerable<CodeInstruction> Rewrite(IEnumerable<CodeInstruction> instructions, int expectedChecks, int expectedUses) { //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); MethodInfo methodInfo = AccessTools.Method(typeof(Character), "HaveStamina", new Type[1] { typeof(float) }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(Character), "UseStamina", new Type[1] { typeof(float) }, (Type[])null); MethodInfo operand = AccessTools.Method(typeof(Plugin), "HaveActionStamina", (Type[])null, (Type[])null); MethodInfo operand2 = AccessTools.Method(typeof(Plugin), "UseActionStamina", (Type[])null, (Type[])null); int num = 0; int num2 = 0; foreach (CodeInstruction instruction in instructions) { CodeInstruction val = new CodeInstruction(instruction); if (CodeInstructionExtensions.Calls(instruction, methodInfo)) { val.opcode = OpCodes.Call; val.operand = operand; num++; } else if (CodeInstructionExtensions.Calls(instruction, methodInfo2)) { val.opcode = OpCodes.Call; val.operand = operand2; num2++; } list.Add(val); } if (num != expectedChecks || num2 != expectedUses) { throw new InvalidOperationException($"Expected {expectedChecks} checks/{expectedUses} deductions; found {num}/{num2}."); } return list; } }
BepInEx/plugins/CalmTheStorms.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Text; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace CalmTheStorms; [BepInPlugin("local.calmthestorms", "Calm the Storms", "0.2.1")] public sealed class Plugin : BaseUnityPlugin { private sealed class Tile { internal readonly float[] Vanilla = new float[4]; internal readonly bool[] Ocean = new bool[4]; } private sealed class Peer { internal ZNetPeer Net; internal bool Hello; internal int Ack = -1; internal float Deadline; } [HarmonyPatch(typeof(WaterVolume), "DetectWaterDepth")] private static class WaterDepthPatch { [HarmonyPostfix] private static void Postfix(WaterVolume __instance) { if ((Object)(object)instance != (Object)null) { instance.Capture(__instance); } } } [HarmonyPatch(typeof(Heightmap), "Regenerate")] private static class TerrainPatch { [HarmonyPostfix] private static void Postfix(Heightmap __instance) { if ((Object)(object)instance != (Object)null) { instance.dirtyTerrain.Add(__instance); } } } [HarmonyPatch(typeof(WaterVolume), "CalcWave", new Type[] { typeof(Vector3), typeof(float), typeof(Vector4), typeof(float), typeof(float), typeof(float) })] private static class WaveAmplitudePatch { [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(typeof(Mathf), "Lerp", new Type[3] { typeof(float), typeof(float), typeof(float) }, (Type[])null); MethodInfo operand = AccessTools.Method(typeof(Mathf), "LerpUnclamped", new Type[3] { typeof(float), typeof(float), typeof(float) }, (Type[])null); List<CodeInstruction> list = new List<CodeInstruction>(); int num = 0; foreach (CodeInstruction instruction in instructions) { CodeInstruction val = new CodeInstruction(instruction); if (CodeInstructionExtensions.Calls(val, methodInfo)) { val.opcode = OpCodes.Call; val.operand = operand; num++; } list.Add(val); } if (num != 1) { throw new InvalidOperationException("Water wave depth scaling changed; expected one Lerp."); } return list; } } public const string PluginId = "local.calmthestorms"; private const string RpcName = "CalmTheStorms_Config_v2"; private const int Protocol = 2; private const float GraceSeconds = 30f; private static Plugin instance; private static readonly FieldInfo DepthField = AccessTools.Field(typeof(WaterVolume), "m_normalizedDepth"); private static readonly FieldInfo OneDepthField = AccessTools.Field(typeof(WaterVolume), "m_oneDepth"); private static readonly FieldInfo BiomesField = AccessTools.Field(typeof(Heightmap), "m_cornerBiomes"); private static readonly int[] BiomeCornerOrder = new int[4] { 2, 3, 1, 0 }; private static readonly int DepthShader = Shader.PropertyToID("_depth"); private readonly Dictionary<WaterVolume, Tile> tiles = new Dictionary<WaterVolume, Tile>(); private readonly Dictionary<ZRpc, Peer> peers = new Dictionary<ZRpc, Peer>(); private readonly HashSet<Heightmap> dirtyTerrain = new HashSet<Heightmap>(); private ConfigEntry<bool> enabledSetting; private ConfigEntry<bool> overlaySetting; private string overlayText = ""; private GUIStyle overlayStyle; private ConfigEntry<float> nonOceanSetting; private ConfigEntry<float> oceanSetting; private Harmony harmony; private ZNet session; private ZRpc serverRpc; private bool active; private bool received; private bool wasServer; private float nonOceanMultiplier = 0.1f; private float oceanMultiplier = 1f; private float nextTick; private float nextHello; private float connectedAt; private int revision; private FileSystemWatcher configWatcher; private bool configReloadPending; private float configReloadAfter; private int configReloadRetries; private void Awake() { //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown instance = this; enabledSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("Server", "Enabled", true, "Server-authoritative non-Ocean wave suppression."); nonOceanSetting = ((BaseUnityPlugin)this).Config.Bind<float>("Server", "NonOceanMultiplier", 0.1f, "Non-Ocean wave multiplier: 0 to 1.5 (0% to 150%). 1 is vanilla. Server authoritative."); oceanSetting = ((BaseUnityPlugin)this).Config.Bind<float>("Server", "OceanMultiplier", 1f, "Ocean wave multiplier: 0 to 1.5 (0% to 150%). 1 is vanilla. Server authoritative."); overlaySetting = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowOverlay", false, "Show live tile diagnostics on this client. Reloads when the local config is saved."); ((BaseUnityPlugin)this).Config.Save(); if (DepthField == null || OneDepthField == null || BiomesField == null) { throw new MissingFieldException("Water/terrain fields changed."); } harmony = new Harmony("local.calmthestorms"); try { harmony.PatchAll(typeof(Plugin).Assembly); } catch { harmony.UnpatchSelf(); instance = null; throw; } StartConfigWatcher(); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Calm the Storms test loaded. Server config: " + ((BaseUnityPlugin)this).Config.ConfigFilePath)); } private void Update() { if (Time.realtimeSinceStartup < nextTick) { return; } nextTick = Time.realtimeSinceStartup + 0.5f; try { ReloadConfig(); ZNet val = ZNet.instance; bool flag = (Object)(object)val != (Object)null && val.IsServer(); if ((Object)(object)session != (Object)(object)val || wasServer != flag) { ClearNetwork(); session = val; wasServer = flag; SetEffective(enabled: false, 0.1f, 1f); } if ((Object)(object)val != (Object)null) { if (flag) { ServerTick(val); } else { ClientTick(val); } } RefreshTerrain(); UpdateOverlay(); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Calm the Storms update: " + ex)); } } private void ReloadConfig() { if (!configReloadPending || Time.realtimeSinceStartup < configReloadAfter) { return; } configReloadPending = false; try { if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath)) { throw new IOException("Config temporarily missing."); } ((BaseUnityPlugin)this).Config.Reload(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Config reloaded. Multiplayer clients use server wave settings."); } catch (IOException error) { RetryConfigReload(error); } catch (UnauthorizedAccessException error2) { RetryConfigReload(error2); } } private void StartConfigWatcher() { if (configWatcher != null) { configWatcher.Dispose(); } configWatcher = new FileSystemWatcher(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath)); configWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite; configWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; configWatcher.Changed += ConfigFileChanged; configWatcher.Created += ConfigFileChanged; configWatcher.Renamed += ConfigFileChanged; configWatcher.Error += ConfigWatchFailed; configWatcher.EnableRaisingEvents = true; QueueConfigReload(); } private void ConfigFileChanged(object sender, FileSystemEventArgs args) { if (sender == configWatcher) { QueueConfigReload(); } } private void QueueConfigReload() { configReloadPending = true; configReloadAfter = Time.realtimeSinceStartup + 0.25f; configReloadRetries = 0; } private void ConfigWatchFailed(object sender, ErrorEventArgs args) { if (sender == configWatcher) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Config watcher error; restarting: " + args.GetException().Message)); StartConfigWatcher(); } } private void RetryConfigReload(Exception error) { if (++configReloadRetries <= 5) { configReloadPending = true; configReloadAfter = Time.realtimeSinceStartup + 0.5f; } else { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Config reload failed; save again to retry: " + error.Message)); } } private void SetEffective(bool enabled, float nonOcean, float ocean) { if (active == enabled && nonOceanMultiplier == nonOcean && oceanMultiplier == ocean) { return; } active = enabled; nonOceanMultiplier = nonOcean; oceanMultiplier = ocean; foreach (KeyValuePair<WaterVolume, Tile> tile in tiles) { if ((Object)(object)tile.Key != (Object)null) { Apply(tile.Key, tile.Value); } } } private void ServerTick(ZNet net) { float value = nonOceanSetting.Value; float value2 = oceanSetting.Value; if (WaveRules.ValidMultiplier(value) && WaveRules.ValidMultiplier(value2) && (active != enabledSetting.Value || nonOceanMultiplier != value || oceanMultiplier != value2 || revision == 0)) { SetEffective(enabledSetting.Value, value, value2); revision++; foreach (Peer value3 in peers.Values) { if (value3.Ack == revision - 1) { value3.Deadline = Time.realtimeSinceStartup + 30f; } if (value3.Hello) { SendSettings(value3.Net.m_rpc); } } ((BaseUnityPlugin)this).Logger.LogInfo((object)("Server settings revision " + revision + ": enabled=" + active + ", non-Ocean=" + nonOceanMultiplier + ", Ocean=" + oceanMultiplier)); } ZNetPeer[] array = net.GetPeers().ToArray(); foreach (ZNetPeer val in array) { if (val.IsReady() && !val.m_server && !peers.ContainsKey(val.m_rpc)) { peers.Add(val.m_rpc, new Peer { Net = val, Deadline = Time.realtimeSinceStartup + 30f }); val.m_rpc.Register<ZPackage>("CalmTheStorms_Config_v2", (Action<ZRpc, ZPackage>)ReceiveServer); } } foreach (KeyValuePair<ZRpc, Peer> item in new List<KeyValuePair<ZRpc, Peer>>(peers)) { if (!net.GetPeers().Contains(item.Value.Net)) { item.Key.Unregister("CalmTheStorms_Config_v2"); peers.Remove(item.Key); } else if (item.Value.Ack != revision && Time.realtimeSinceStartup > item.Value.Deadline) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Disconnecting " + item.Value.Net.m_playerName + ": compatible Calm the Storms config acknowledgement missing.")); net.Disconnect(item.Value.Net); peers.Remove(item.Key); } } } private void ClientTick(ZNet net) { //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Expected O, but got Unknown ZNetPeer serverPeer = net.GetServerPeer(); if (serverPeer == null || !serverPeer.IsReady()) { if (serverRpc != null) { serverRpc.Unregister("CalmTheStorms_Config_v2"); serverRpc = null; } received = false; SetEffective(enabled: false, 0.1f, 1f); return; } if (serverRpc != serverPeer.m_rpc) { if (serverRpc != null) { serverRpc.Unregister("CalmTheStorms_Config_v2"); } serverRpc = serverPeer.m_rpc; received = false; revision = 0; connectedAt = Time.realtimeSinceStartup; nextHello = 0f; SetEffective(enabled: false, 0.1f, 1f); serverRpc.Register<ZPackage>("CalmTheStorms_Config_v2", (Action<ZRpc, ZPackage>)ReceiveClient); } if (!received && Time.realtimeSinceStartup >= nextHello) { nextHello = Time.realtimeSinceStartup + 2f; ZPackage val = new ZPackage(); val.Write(0); val.Write(2); Send(serverRpc, val); } if (!received && Time.realtimeSinceStartup > connectedAt + 30f) { ((BaseUnityPlugin)this).Logger.LogError((object)"Server did not supply compatible Calm the Storms settings; disconnecting."); net.Disconnect(serverPeer); } } private static void Send(ZRpc rpc, ZPackage package) { rpc.Invoke("CalmTheStorms_Config_v2", new object[1] { package }); } private void SendSettings(ZRpc rpc) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(1); val.Write(2); val.Write(revision); val.Write(active); val.Write(nonOceanMultiplier); val.Write(oceanMultiplier); Send(rpc, val); } private void ReceiveServer(ZRpc rpc, ZPackage package) { if ((Object)(object)session == (Object)null || !session.IsServer() || !peers.TryGetValue(rpc, out var value)) { return; } try { if (package.Size() != 8 && package.Size() != 12) { return; } int num = package.ReadInt(); int num2 = package.ReadInt(); if (num2 != 2) { return; } if (num == 0 && package.Size() == 8) { value.Hello = true; SendSettings(rpc); } else if (num == 2 && package.Size() == 12 && value.Hello) { int num3 = package.ReadInt(); if (num3 == revision) { value.Ack = num3; } } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Invalid config handshake: " + ex.Message)); } } private void ReceiveClient(ZRpc rpc, ZPackage package) { //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown if ((Object)(object)session == (Object)null || session.IsServer() || rpc != serverRpc) { return; } try { if (package.Size() == 21 && package.ReadInt() == 1 && package.ReadInt() == 2) { int num = package.ReadInt(); bool enabled = package.ReadBool(); float num2 = package.ReadSingle(); float num3 = package.ReadSingle(); if (WaveRules.ValidMultiplier(num2) && WaveRules.ValidMultiplier(num3) && num >= 1 && num >= revision) { SetEffective(enabled, num2, num3); revision = num; received = true; ZPackage val = new ZPackage(); val.Write(2); val.Write(2); val.Write(revision); Send(rpc, val); } } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Invalid server config: " + ex.Message)); } } private void ClearNetwork() { foreach (ZRpc key in peers.Keys) { key.Unregister("CalmTheStorms_Config_v2"); } peers.Clear(); if (serverRpc != null) { serverRpc.Unregister("CalmTheStorms_Config_v2"); } serverRpc = null; received = false; revision = 0; } private void Capture(WaterVolume water) { //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Invalid comparison between Unknown and I4 if ((Object)(object)water.m_heightmap == (Object)null || water.m_forceDepth >= 0f || !water.m_useGlobalWind) { return; } BiomeSector[] array = (BiomeSector[])BiomesField.GetValue(water.m_heightmap); if (array == null || array.Length != 4) { return; } for (int i = 0; i < 4; i++) { if (array[i] == null) { return; } } if (!tiles.TryGetValue(water, out var value)) { value = new Tile(); tiles.Add(water, value); } float[] oceanDepth = water.m_heightmap.GetOceanDepth(); for (int j = 0; j < 4; j++) { value.Vanilla[j] = Mathf.Clamp01(oceanDepth[j] / 10f); value.Ocean[j] = (int)array[BiomeCornerOrder[j]].Biome == 256; } Apply(water, value); } private void Apply(WaterVolume water, Tile tile) { float[] array = (float[])DepthField.GetValue(water); for (int i = 0; i < 4; i++) { array[i] = WaveRules.Scale(tile.Vanilla[i], tile.Ocean[i], active, nonOceanMultiplier, oceanMultiplier); } OneDepthField.SetValue(water, WaveRules.ConstantDepth(array)); if ((Object)(object)water.m_waterSurface != (Object)null) { ((Renderer)water.m_waterSurface).material.SetFloatArray(DepthShader, array); } } private void RefreshTerrain() { foreach (KeyValuePair<WaterVolume, Tile> item in new List<KeyValuePair<WaterVolume, Tile>>(tiles)) { if ((Object)(object)item.Key == (Object)null) { tiles.Remove(item.Key); } else if (dirtyTerrain.Contains(item.Key.m_heightmap)) { Capture(item.Key); } } dirtyTerrain.Clear(); } private void UpdateOverlay() { //IL_0030: 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_0036: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_02f9: Unknown result type (might be due to invalid IL or missing references) //IL_033f: Unknown result type (might be due to invalid IL or missing references) overlayText = ""; if (!overlaySetting.Value || (Object)(object)Player.m_localPlayer == (Object)null) { return; } Vector3 position = ((Component)Player.m_localPlayer).transform.position; Heightmap val = Heightmap.FindHeightmap(position); StringBuilder stringBuilder = new StringBuilder(); string arg = (((Object)(object)session == (Object)null) ? "Waiting for world" : (session.IsServer() ? "Local host" : (received ? "Server enforced" : "Waiting for server settings"))); stringBuilder.AppendFormat("{0} Revision: {1}\n", arg, revision); stringBuilder.AppendFormat("Enabled: {0} Non-Ocean: {1:0.##}x Ocean: {2:0.##}x\n", active, nonOceanMultiplier, oceanMultiplier); if ((Object)(object)val == (Object)null) { overlayText = string.Concat(stringBuilder, "Tile: not loaded"); return; } Vector3 position2 = ((Component)val).transform.position; float num = (float)val.m_width * val.m_scale; stringBuilder.AppendFormat("Tile center: {0:0}, {1:0} Size: {2:0} m\n", position2.x, position2.z, num); WaterVolume val2 = null; Tile tile = null; foreach (KeyValuePair<WaterVolume, Tile> tile2 in tiles) { if ((Object)(object)tile2.Key != (Object)null && (Object)(object)tile2.Key.m_heightmap == (Object)(object)val) { val2 = tile2.Key; tile = tile2.Value; break; } } if ((Object)(object)val2 == (Object)null) { overlayText = string.Concat(stringBuilder, "Water: no tracked volume"); return; } float[] array = (float[])DepthField.GetValue(val2); string[] array2 = new string[4] { "NW", "NE", "SE", "SW" }; for (int i = 0; i < 4; i++) { stringBuilder.AppendFormat("{0} {1} {2:0.000} -> {3:0.000}\n", array2[i], tile.Ocean[i] ? "Ocean" : "Non-Ocean", tile.Vanilla[i], array[i]); } float num2 = WaveRules.Interpolate(tile.Vanilla, (position.x - position2.x) / num + 0.5f, (position.z - position2.z) / num + 0.5f); float num3 = val2.Depth(position); stringBuilder.AppendFormat("At player: {0:0.000} -> {1:0.000} Strength: {2}\n", num2, num3, (num2 > 0f) ? ((100f * num3 / num2).ToString("0.0") + "%") : "n/a"); float waterSurface = val2.GetWaterSurface(position, 1f); stringBuilder.AppendFormat("Wind: {0:0.000} Water Y: {1:0.00} Offset: {2:+0.00;-0.00;0.00} m", ((Object)(object)EnvMan.instance != (Object)null) ? EnvMan.instance.GetWindIntensity() : 0f, waterSurface, waterSurface - ((Component)val2).transform.position.y - val2.m_surfaceOffset); overlayText = stringBuilder.ToString(); } private void OnGUI() { //IL_0070: 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_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: 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_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0129: 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 (overlaySetting != null && overlaySetting.Value && !((Object)(object)Player.m_localPlayer == (Object)null) && !string.IsNullOrEmpty(overlayText)) { if (overlayStyle == null) { GUIStyle val = new GUIStyle(GUI.skin.label); val.fontSize = 14; val.wordWrap = false; val.richText = false; overlayStyle = val; } overlayStyle.normal.textColor = Color.white; Rect val2 = default(Rect); ((Rect)(ref val2))..ctor(16f, Mathf.Max(16f, (float)Screen.height - 250f), 520f, 230f); Color color = GUI.color; GUI.color = new Color(0f, 0f, 0f, 0.85f); GUI.DrawTexture(val2, (Texture)(object)Texture2D.whiteTexture); GUI.color = Color.white; GUI.Label(new Rect(((Rect)(ref val2)).x + 10f, ((Rect)(ref val2)).y + 8f, ((Rect)(ref val2)).width - 20f, ((Rect)(ref val2)).height - 16f), overlayText, overlayStyle); GUI.color = color; } } private void OnDestroy() { if (configWatcher != null) { configWatcher.Dispose(); configWatcher = null; } ClearNetwork(); SetEffective(enabled: false, nonOceanMultiplier, oceanMultiplier); if (harmony != null) { harmony.UnpatchSelf(); } tiles.Clear(); instance = null; } } internal static class WaveRules { internal static bool ValidMultiplier(float value) { if (!float.IsNaN(value) && !float.IsInfinity(value) && value >= 0f) { return value <= 1.5f; } return false; } internal static float Scale(float vanilla, bool ocean, bool enabled, float nonOceanMultiplier, float oceanMultiplier) { if (!enabled) { return vanilla; } return vanilla * (ocean ? oceanMultiplier : nonOceanMultiplier); } internal static float Interpolate(float[] corners, float x, float z) { x = Math.Max(0f, Math.Min(1f, x)); z = Math.Max(0f, Math.Min(1f, z)); float num = corners[3] + (corners[2] - corners[3]) * x; float num2 = corners[0] + (corners[1] - corners[0]) * x; return num + (num2 - num) * z; } internal static float ConstantDepth(float[] corners) { if (corners[0] != corners[1] || corners[0] != corners[2] || corners[0] != corners[3]) { return -1f; } return corners[0]; } }
BepInEx/plugins/CameraBasedAutoWalk.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace CameraBasedAutoWalk; [BepInPlugin("local.camerabasedautowalk", "Camera Based Auto Walk", "1.1.0")] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(Player), "SetControls")] private static class AutoWalkDirection { [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(instructions); int num = -1; int num2 = -1; for (int i = 0; i + 6 < list.Count; i++) { if (CodeInstructionExtensions.IsLdarg(list[i], (int?)2) && CodeInstructionExtensions.IsLdarg(list[i + 1], (int?)8) && list[i + 2].opcode == OpCodes.Or && CodeInstructionExtensions.IsLdarg(list[i + 3], (int?)12) && list[i + 4].opcode == OpCodes.Or && CodeInstructionExtensions.IsLdarg(list[i + 5], (int?)9) && list[i + 6].opcode == OpCodes.Or) { if (num >= 0) { throw new InvalidOperationException("Ambiguous auto-walk cancellation expression."); } num = i; } } if (num < 0) { throw new MissingMethodException("Auto-walk cancellation expression not found."); } for (int j = num; j + 2 < list.Count; j++) { if (list[j].opcode == OpCodes.Ldarg_0 && list[j + 1].opcode == OpCodes.Ldc_I4_0 && CodeInstructionExtensions.StoresField(list[j + 2], AccessTools.Field(typeof(Player), "m_autoRun"))) { num2 = j; break; } } if (num2 < 0) { throw new MissingMethodException("Auto-walk cancellation assignment not found."); } int num3 = 0; MethodInfo methodInfo = AccessTools.Method(typeof(AutoWalkDirection), "ShouldCancelForAttack", (Type[])null, (Type[])null); for (int num4 = num2 - 1; num4 >= num; num4--) { if (CodeInstructionExtensions.IsLdarg(list[num4], (int?)2) || CodeInstructionExtensions.IsLdarg(list[num4], (int?)3) || CodeInstructionExtensions.IsLdarg(list[num4], (int?)5)) { list.InsertRange(num4 + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Call, (object)methodInfo) }); num3++; } } if (num3 != 3) { throw new InvalidOperationException("Unexpected auto-walk attack conditions."); } return list; } private static bool ShouldCancelForAttack(bool attack, Player player) { if (attack) { if (!((Object)(object)player != (Object)(object)Player.m_localPlayer)) { return attacksStopAutoWalk.Value; } return true; } return false; } [HarmonyPostfix] private static void Postfix(Player __instance, bool ___m_autoRun, Vector3 ___m_lookDir, ref Vector3 ___m_moveDir) { //IL_0018: 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_0037: 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) if (cameraSteering.Value && ___m_autoRun && CanSteer(__instance)) { Vector3 val = ___m_lookDir; val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude > 0.0001f) { ___m_moveDir = ((Vector3)(ref val)).normalized; } } } } public const string PluginId = "local.camerabasedautowalk"; private static ConfigEntry<bool> cameraSteering; private static ConfigEntry<bool> attacksStopAutoWalk; private FileSystemWatcher configWatcher; private bool configReloadPending; private float configReloadAfter; private int configReloadRetries; private ConfigEntry<KeyboardShortcut> toggleKey; private Harmony harmony; private static readonly MethodInfo TakeInput = AccessTools.Method(typeof(Player), "TakeInput", (Type[])null, (Type[])null); private void Awake() { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected O, but got Unknown cameraSteering = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "CameraSteering", true, "Make auto-walk follow the camera. The toggle key changes and saves this setting."); attacksStopAutoWalk = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AttacksStopAutoWalk", true, "Stop auto-walk when attacking. Changes apply immediately; false allows attacking while auto-walking."); toggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Controls", "ToggleKey", new KeyboardShortcut((KeyCode)289, (KeyCode[])(object)new KeyCode[0]), "Toggle camera steering during gameplay. Supports modifier keys; None disables the shortcut."); harmony = new Harmony("local.camerabasedautowalk"); try { if (TakeInput == null) { throw new MissingMethodException("Player.TakeInput"); } harmony.PatchAll(typeof(Plugin).Assembly); StartConfigWatcher(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Camera Based Auto Walk loaded."); } catch (Exception ex) { harmony.UnpatchSelf(); ((Behaviour)this).enabled = false; ((BaseUnityPlugin)this).Logger.LogError((object)("Camera Based Auto Walk disabled: " + ex)); } } private static bool CanSteer(Player player) { if ((Object)(object)player != (Object)null && (Object)(object)player == (Object)(object)Player.m_localPlayer && Application.isFocused && (Object)(object)Hud.instance != (Object)null && !((Character)player).IsAttached() && player.GetDoodadController() == null) { return (bool)TakeInput.Invoke(player, null); } return false; } private void Update() { //IL_000c: 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) ReloadConfig(); KeyboardShortcut value = toggleKey.Value; if (((KeyboardShortcut)(ref value)).IsDown() && CanSteer(Player.m_localPlayer)) { cameraSteering.Value = !cameraSteering.Value; ((BaseUnityPlugin)this).Config.Save(); ((Character)Player.m_localPlayer).Message((MessageType)1, "Auto-walk camera steering: " + (cameraSteering.Value ? "On" : "Off"), 0, (Sprite)null, false); } } private void OnDestroy() { if (configWatcher != null) { configWatcher.Dispose(); } if (harmony != null) { harmony.UnpatchSelf(); } } private void ReloadConfig() { if (!configReloadPending || Time.realtimeSinceStartup < configReloadAfter) { return; } configReloadPending = false; try { if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath)) { throw new IOException("Config temporarily missing."); } ((BaseUnityPlugin)this).Config.Reload(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Auto-walk config reloaded."); } catch (IOException error) { RetryConfigReload(error); } catch (UnauthorizedAccessException error2) { RetryConfigReload(error2); } } private void StartConfigWatcher() { if (configWatcher != null) { configWatcher.Dispose(); } configWatcher = new FileSystemWatcher(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath)); configWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite; configWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; configWatcher.Changed += ConfigFileChanged; configWatcher.Created += ConfigFileChanged; configWatcher.Renamed += ConfigFileChanged; configWatcher.Error += ConfigWatchFailed; configWatcher.EnableRaisingEvents = true; QueueConfigReload(); } private void ConfigFileChanged(object sender, FileSystemEventArgs args) { if (sender == configWatcher) { QueueConfigReload(); } } private void QueueConfigReload() { configReloadPending = true; configReloadAfter = Time.realtimeSinceStartup + 0.25f; configReloadRetries = 0; } private void ConfigWatchFailed(object sender, ErrorEventArgs args) { if (sender == configWatcher) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Config watcher error; restarting: " + args.GetException().Message)); StartConfigWatcher(); } } private void RetryConfigReload(Exception error) { if (++configReloadRetries <= 5) { configReloadPending = true; configReloadAfter = Time.realtimeSinceStartup + 0.5f; } else { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Config reload failed; save again to retry: " + error.Message)); } } }
BepInEx/plugins/CustomTameTimer.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace CustomTameTimer; [BepInPlugin("local.customtametimer", "Custom Tame Timer", "0.1.0")] public sealed class Plugin : BaseUnityPlugin { private sealed class Peer { internal ZNetPeer Net; internal bool Hello; internal int Ack = -1; internal float Deadline; } [HarmonyPatch(typeof(Tameable), "DecreaseRemainingTime")] private static class TamingRatePatch { [HarmonyPrefix] private static void Prefix(Tameable __instance, ref float time) { if (!((Object)(object)instance == (Object)null) && !(__instance.m_tamingTime <= 0f)) { time = ScaleCountdown(time, __instance.m_tamingTime, instance.tameMinutes); } } } [HarmonyPatch(typeof(Tameable), "TamingUpdate")] private static class AwaitServerSettingsPatch { [HarmonyPrefix] private static bool Prefix() { ZNet instance = ZNet.instance; if ((Object)(object)Plugin.instance != (Object)null && (Object)(object)instance != (Object)null) { if (!instance.IsServer()) { if ((Object)(object)Plugin.instance.session == (Object)(object)instance) { return Plugin.instance.received; } return false; } if ((Object)(object)Plugin.instance.session == (Object)(object)instance) { return Plugin.instance.revision > 0; } return false; } return false; } } public const string PluginId = "local.customtametimer"; private const string RpcName = "CustomTameTimer_Config_v1"; private const int Protocol = 1; private const float GraceSeconds = 30f; private static Plugin instance; private readonly Dictionary<ZRpc, Peer> peers = new Dictionary<ZRpc, Peer>(); private ConfigEntry<float> minutesSetting; private Harmony harmony; private ZNet session; private ZRpc serverRpc; private bool received; private bool wasServer; private float tameMinutes = 30f; private float nextTick; private float nextHello; private float connectedAt; private int revision; private FileSystemWatcher configWatcher; private bool configReloadPending; private float configReloadAfter; private int configReloadRetries; private static bool ValidMinutes(float value) { if (value >= 0.05f) { return value <= 1440f; } return false; } private void Awake() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown instance = this; minutesSetting = ((BaseUnityPlugin)this).Config.Bind<float>("Server", "TamingMinutes", 30f, new ConfigDescription("Base active taming minutes for all tameable animals. Vanilla: 30. Suggested: 15 (half), 10 (fast), 5 (very fast). Food, calmness, active-area requirements and taming boosts still apply. Server enforced; updates live and preserves earned progress.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1440f), new object[0])); ((BaseUnityPlugin)this).Config.Save(); harmony = new Harmony("local.customtametimer"); try { harmony.PatchAll(typeof(Plugin).Assembly); } catch { harmony.UnpatchSelf(); instance = null; throw; } StartConfigWatcher(); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Custom Tame Timer loaded. Server config: " + ((BaseUnityPlugin)this).Config.ConfigFilePath)); } private void Update() { if (Time.realtimeSinceStartup < nextTick) { return; } nextTick = Time.realtimeSinceStartup + 0.5f; try { ReloadConfig(); ZNet val = ZNet.instance; bool flag = (Object)(object)val != (Object)null && val.IsServer(); if ((Object)(object)session != (Object)(object)val || wasServer != flag) { ClearNetwork(); session = val; wasServer = flag; SetEffective(30f); } if ((Object)(object)val != (Object)null) { if (flag) { ServerTick(val); } else { ClientTick(val); } } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Custom Tame Timer update: " + ex)); } } private void ReloadConfig() { if (!configReloadPending || Time.realtimeSinceStartup < configReloadAfter) { return; } configReloadPending = false; try { if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath)) { throw new IOException("Config temporarily missing."); } ((BaseUnityPlugin)this).Config.Reload(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Config reloaded. Multiplayer clients use server taming settings."); } catch (IOException error) { RetryConfigReload(error); } catch (UnauthorizedAccessException error2) { RetryConfigReload(error2); } } private void StartConfigWatcher() { if (configWatcher != null) { configWatcher.Dispose(); } configWatcher = new FileSystemWatcher(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath)); configWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite; configWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; configWatcher.Changed += ConfigFileChanged; configWatcher.Created += ConfigFileChanged; configWatcher.Renamed += ConfigFileChanged; configWatcher.Error += ConfigWatchFailed; configWatcher.EnableRaisingEvents = true; QueueConfigReload(); } private void ConfigFileChanged(object sender, FileSystemEventArgs args) { if (sender == configWatcher) { QueueConfigReload(); } } private void QueueConfigReload() { configReloadPending = true; configReloadAfter = Time.realtimeSinceStartup + 0.25f; configReloadRetries = 0; } private void ConfigWatchFailed(object sender, ErrorEventArgs args) { if (sender == configWatcher) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Config watcher error; restarting: " + args.GetException().Message)); StartConfigWatcher(); } } private void RetryConfigReload(Exception error) { if (++configReloadRetries <= 5) { configReloadPending = true; configReloadAfter = Time.realtimeSinceStartup + 0.5f; } else { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Config reload failed; save again to retry: " + error.Message)); } } private void SetEffective(float minutes) { tameMinutes = minutes; } private void ServerTick(ZNet net) { float value = minutesSetting.Value; if (ValidMinutes(value) && (tameMinutes != value || revision == 0)) { SetEffective(value); revision++; foreach (Peer value2 in peers.Values) { if (value2.Ack == revision - 1) { value2.Deadline = Time.realtimeSinceStartup + 30f; } if (value2.Hello) { SendSettings(value2.Net.m_rpc); } } ((BaseUnityPlugin)this).Logger.LogInfo((object)("Server settings revision " + revision + ": taming minutes=" + tameMinutes)); } ZNetPeer[] array = net.GetPeers().ToArray(); foreach (ZNetPeer val in array) { if (val.IsReady() && !val.m_server && !peers.ContainsKey(val.m_rpc)) { peers.Add(val.m_rpc, new Peer { Net = val, Deadline = Time.realtimeSinceStartup + 30f }); val.m_rpc.Register<ZPackage>("CustomTameTimer_Config_v1", (Action<ZRpc, ZPackage>)ReceiveServer); } } foreach (KeyValuePair<ZRpc, Peer> item in new List<KeyValuePair<ZRpc, Peer>>(peers)) { if (!net.GetPeers().Contains(item.Value.Net)) { item.Key.Unregister("CustomTameTimer_Config_v1"); peers.Remove(item.Key); } else if (item.Value.Ack != revision && Time.realtimeSinceStartup > item.Value.Deadline) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Disconnecting " + item.Value.Net.m_playerName + ": compatible Custom Tame Timer config acknowledgement missing.")); net.Disconnect(item.Value.Net); peers.Remove(item.Key); } } } private void ClientTick(ZNet net) { //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Expected O, but got Unknown ZNetPeer serverPeer = net.GetServerPeer(); if (serverPeer == null || !serverPeer.IsReady()) { if (serverRpc != null) { serverRpc.Unregister("CustomTameTimer_Config_v1"); serverRpc = null; } received = false; SetEffective(30f); return; } if (serverRpc != serverPeer.m_rpc) { if (serverRpc != null) { serverRpc.Unregister("CustomTameTimer_Config_v1"); } serverRpc = serverPeer.m_rpc; received = false; revision = 0; connectedAt = Time.realtimeSinceStartup; nextHello = 0f; SetEffective(30f); serverRpc.Register<ZPackage>("CustomTameTimer_Config_v1", (Action<ZRpc, ZPackage>)ReceiveClient); } if (!received && Time.realtimeSinceStartup >= nextHello) { nextHello = Time.realtimeSinceStartup + 2f; ZPackage val = new ZPackage(); val.Write(0); val.Write(1); Send(serverRpc, val); } if (!received && Time.realtimeSinceStartup > connectedAt + 30f) { ((BaseUnityPlugin)this).Logger.LogError((object)"Server did not supply compatible Custom Tame Timer settings; disconnecting."); net.Disconnect(serverPeer); } } private static void Send(ZRpc rpc, ZPackage package) { rpc.Invoke("CustomTameTimer_Config_v1", new object[1] { package }); } private void SendSettings(ZRpc rpc) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(1); val.Write(1); val.Write(revision); val.Write(tameMinutes); Send(rpc, val); } private void ReceiveServer(ZRpc rpc, ZPackage package) { if ((Object)(object)session == (Object)null || !session.IsServer() || !peers.TryGetValue(rpc, out var value)) { return; } try { if (package.Size() != 8 && package.Size() != 12) { return; } int num = package.ReadInt(); int num2 = package.ReadInt(); if (num2 != 1) { return; } if (num == 0 && package.Size() == 8) { value.Hello = true; SendSettings(rpc); } else if (num == 2 && package.Size() == 12 && value.Hello) { int num3 = package.ReadInt(); if (num3 == revision) { value.Ack = num3; } } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Invalid config handshake: " + ex.Message)); } } private void ReceiveClient(ZRpc rpc, ZPackage package) { //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown if ((Object)(object)session == (Object)null || session.IsServer() || rpc != serverRpc) { return; } try { if (package.Size() == 16 && package.ReadInt() == 1 && package.ReadInt() == 1) { int num = package.ReadInt(); float num2 = package.ReadSingle(); if (ValidMinutes(num2) && num >= 1 && num >= revision) { SetEffective(num2); revision = num; received = true; ZPackage val = new ZPackage(); val.Write(2); val.Write(1); val.Write(revision); Send(rpc, val); } } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Invalid server config: " + ex.Message)); } } private void ClearNetwork() { foreach (ZRpc key in peers.Keys) { key.Unregister("CustomTameTimer_Config_v1"); } peers.Clear(); if (serverRpc != null) { serverRpc.Unregister("CustomTameTimer_Config_v1"); } serverRpc = null; received = false; revision = 0; } private void OnDestroy() { if (configWatcher != null) { configWatcher.Dispose(); configWatcher = null; } ClearNetwork(); if (harmony != null) { harmony.UnpatchSelf(); } instance = null; } internal static float ScaleCountdown(float seconds, float originalDuration, float minutes) { return seconds * (originalDuration / (minutes * 60f)); } }
BepInEx/plugins/DontPunchMyBoat.dll
Decompiled 2 weeks agousing System; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using HarmonyLib; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace DontPunchMyBoat; [BepInPlugin("local.dontpunchmyboat", "Don't Punch My Boat", "0.1.0")] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(Player), "SetControls")] private static class SeatedControls { [HarmonyPrefix] private static void Prefix(Player __instance, ref bool attack, ref bool attackHold, ref bool secondaryAttack, ref bool secondaryAttackHold, ref bool block, ref bool blockHold) { if (((Character)__instance).IsAttached() || ((Character)__instance).IsSitting() || __instance.GetDoodadController() is ShipControlls) { attack = false; attackHold = false; secondaryAttack = false; secondaryAttackHold = false; block = false; blockHold = false; } } } public const string PluginId = "local.dontpunchmyboat"; private Harmony harmony; private void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown harmony = new Harmony("local.dontpunchmyboat"); try { harmony.PatchAll(typeof(Plugin).Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Don't Punch My Boat loaded: seated attack and block inputs suppressed."); } catch (Exception ex) { harmony.UnpatchSelf(); ((BaseUnityPlugin)this).Logger.LogError((object)("Don't Punch My Boat disabled: " + ex)); } } private void OnDestroy() { if (harmony != null) { harmony.UnpatchSelf(); } } }
BepInEx/plugins/GetOffMyLawn.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using UnityEngine; using UnityEngine.Rendering; [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyVersion("0.0.0.0")] namespace GetOffMyLawn; internal static class Rules { internal static readonly string[] Keys = new string[8] { "", "defeated_eikthyr", "defeated_gdking", "defeated_bonemass", "defeated_dragon", "defeated_goblinking", "defeated_queen", "defeated_fader" }; internal static readonly string[] BossNames = new string[9] { "None", "Eikthyr", "The Elder", "Bonemass", "Moder", "Yagluth", "The Queen", "Fader", "Hidden" }; internal static int Map(int faction, string prefab) { if (faction == 2) { switch (prefab) { case "Greyling": case "Neck": case "Boar": case "Boar_piggy": return 1; } } return faction switch { 2 => 2, 3 => 3, 5 => 4, 7 => 5, 9 => 6, 4 => 7, 13 => 8, _ => 0, }; } internal static HashSet<string> Names(string text) { HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); string[] array = text.Split(','); foreach (string text2 in array) { if (text2.Trim().Length > 0) { hashSet.Add(text2.Trim()); } } return hashSet; } internal static bool CanOverride(bool enabled, bool excluded, bool tamed, bool boss, bool monster, bool owner, int tier, bool defeated) { if (enabled && !excluded && !tamed && !boss && monster && owner && tier > 0) { return defeated; } return false; } internal static string StateName(int state) { return state switch { 1 => "ignoring protected target", 2 => "avoiding protection", 3 => "leaving protection", 4 => "retreating", 5 => "retreat blocked", 6 => "pathing around protection", 7 => "combat route blocked", _ => "default", }; } internal static bool Valid(float value, float min, float max) { if (!float.IsNaN(value) && !float.IsInfinity(value) && value >= min) { return value <= max; } return false; } internal static bool SegmentHitsSphere(float x, float y, float z, float dx, float dy, float dz, float radius) { float num = dx * dx + dy * dy + dz * dz; float num2 = ((num < 1E-05f) ? 0f : Math.Max(0f, Math.Min(1f, (0f - (x * dx + y * dy + z * dz)) / num))); x += dx * num2; y += dy * num2; z += dz * num2; return x * x + y * y + z * z <= radius * radius; } } internal static class RouteSearch { internal static List<int> Shortest(int count, Func<int, int, float> cost) { float[] array = new float[count]; int[] array2 = new int[count]; bool[] array3 = new bool[count]; for (int i = 0; i < count; i++) { array[i] = float.PositiveInfinity; array2[i] = -1; } array[0] = 0f; for (int j = 0; j < count; j++) { int num = -1; for (int k = 0; k < count; k++) { if (!array3[k] && (num < 0 || array[k] < array[num])) { num = k; } } if (num < 0 || float.IsPositiveInfinity(array[num])) { break; } if (num == 1) { List<int> list = new List<int>(); for (int num2 = 1; num2 != 0; num2 = array2[num2]) { list.Add(num2); } list.Reverse(); return list; } array3[num] = true; for (int l = 0; l < count; l++) { if (!array3[l] && l != num) { float num3 = array[num] + cost(num, l); if (num3 < array[l]) { array[l] = num3; array2[l] = num; } } } } return new List<int>(); } } [BepInPlugin("local.getoffmylawn", "Get Off My Lawn", "0.1.2")] public sealed class Plugin : BaseUnityPlugin { internal sealed class Mind { internal int State; internal int Published; internal double PublishAt; internal Vector3 Threat; internal Vector3 Destination; internal float NextPlan; internal double RetreatUntil; internal bool HasDestination; internal bool Moving; internal bool PendingAvoid; internal bool Blocked; internal bool CombatDetour; internal Character CombatTarget; internal Vector3 CombatGoal; internal float NextCombatPlan; internal List<Vector3> CombatRoute = new List<Vector3>(); } private sealed class ScaledArea { internal EffectArea Source; internal EffectArea Proxy; internal Collider Original; internal Collider Scaled; } [HarmonyPatch(typeof(Projectile), "Setup")] private static class ProjectileSetup { private static void Postfix(Projectile __instance, Character __0) { //IL_004b: 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) Plugin instance = Instance; if (!((Object)(object)instance == (Object)null) && __0 is Player) { ZNetView component = ((Component)__instance).GetComponent<ZNetView>(); if (!((Object)(object)component == (Object)null) && component.IsOwner() && component.GetZDO() != null) { component.GetZDO().Set(ShotProtectedKey, instance.Protected(((Component)__0).transform.position, 0f)); component.GetZDO().Set(ShotOriginKey, ((Component)__0).transform.position); } } } } [HarmonyPatch(typeof(Projectile), "OnHit")] private static class ProjectileHit { private static void Prefix(Projectile __instance, out Projectile __state) { __state = hitProjectile; hitProjectile = __instance; } private static Exception Finalizer(Exception __exception, Projectile __state) { hitProjectile = __state; return __exception; } } [HarmonyPatch(typeof(MonsterAI), "Awake")] private static class RegisterAttack { private static void Postfix(MonsterAI __instance) { if ((Object)(object)Instance == (Object)null) { return; } ZNetView view = ((Component)__instance).GetComponent<ZNetView>(); if ((Object)(object)view == (Object)null || !view.IsValid()) { return; } MonsterAI ai = __instance; view.Register<ZDOID, Vector3, bool>("GOML_Attack_v1", (Action<long, ZDOID, Vector3, bool>)delegate(long sender, ZDOID attacker, Vector3 origin, bool launchedProtected) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) Plugin instance = Instance; if (!((Object)(object)instance == (Object)null) && view.IsOwner() && instance.Eligible(Body((BaseAI)(object)ai), requireOwner: true)) { GameObject val = (((Object)(object)ZNetScene.instance == (Object)null) ? null : ZNetScene.instance.FindInstance(attacker)); Player val2 = (((Object)(object)val == (Object)null) ? null : val.GetComponent<Player>()); if (!((Object)(object)val2 == (Object)null)) { ZNetView component = ((Component)val2).GetComponent<ZNetView>(); if (!((Object)(object)component == (Object)null) && component.GetZDO() != null && component.GetZDO().GetOwner() == sender && Rules.Valid(origin.x, -20000f, 20000f) && Rules.Valid(origin.y, -10000f, 10000f) && Rules.Valid(origin.z, -20000f, 20000f) && (launchedProtected || instance.Protected(((Component)val2).transform.position, 0f))) { instance.BeginRetreat(ai, origin); } } } }); } } [HarmonyPatch(typeof(Character), "Damage")] private static class AttackNotification { private static void Prefix(Character __instance, HitData __0) { //IL_0049: 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_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: 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_009d: 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_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0104: 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_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0127: 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) Plugin instance = Instance; if ((Object)(object)instance == (Object)null || !instance.Active || __0 == null) { return; } Character attacker = __0.GetAttacker(); Player val = (Player)(object)((attacker is Player) ? attacker : null); if ((Object)(object)val == (Object)null || !((Character)val).IsOwner() || !instance.Eligible(__instance, requireOwner: false)) { return; } Vector3 val2 = ((Component)val).transform.position; bool flag = false; if ((Object)(object)hitProjectile != (Object)null) { ZNetView component = ((Component)hitProjectile).GetComponent<ZNetView>(); ZDO val3 = (((Object)(object)component == (Object)null) ? null : component.GetZDO()); if (val3 != null && val3.GetBool(ShotProtectedKey, false)) { flag = true; val2 = val3.GetVec3(ShotOriginKey, val2); } } if (!flag && !instance.Protected(((Component)val).transform.position, 0f)) { return; } SendRetreat(__instance, val, val2, flag); if (!instance.GroupRetreat) { return; } foreach (Character allCharacter in Character.GetAllCharacters()) { if ((Object)(object)allCharacter != (Object)null && (Object)(object)allCharacter != (Object)(object)__instance && allCharacter.GetFaction() == __instance.GetFaction()) { Vector3 val4 = ((Component)allCharacter).transform.position - ((Component)__instance).transform.position; if (((Vector3)(ref val4)).sqrMagnitude <= instance.GroupRetreatRadius * instance.GroupRetreatRadius && instance.Eligible(allCharacter, requireOwner: false)) { SendRetreat(allCharacter, val, val2, flag); } } } } private static void SendRetreat(Character enemy, Player attacker, Vector3 origin, bool shot) { //IL_003e: 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) ZNetView component = ((Component)enemy).GetComponent<ZNetView>(); ZNetView component2 = ((Component)attacker).GetComponent<ZNetView>(); if (!((Object)(object)component == (Object)null) && !((Object)(object)component2 == (Object)null) && component2.GetZDO() != null) { component.InvokeRPC("GOML_Attack_v1", new object[3] { component2.GetZDO().m_uid, origin, shot }); } } } private sealed class DebugRow { internal string Name; internal string Faction; internal string Boss; internal string State; internal float Distance; } public const string Id = "local.getoffmylawn"; private const string AttackRpc = "GOML_Attack_v1"; private const string ConfigRpc = "GOML_Config_v2"; internal static Plugin Instance; private Harmony harmony; private ConfigEntry<bool> enabledConfig; private ConfigEntry<bool> debugConfig; private ConfigEntry<bool> groupConfig; private ConfigEntry<string> exclusionsConfig; private ConfigEntry<float> distanceConfig; private ConfigEntry<float> bufferConfig; private ConfigEntry<float> debugRangeConfig; private ConfigEntry<float> radiusConfig; private ConfigEntry<float> groupRadiusConfig; internal float GroupRetreatRadius = 25f; internal bool Active; internal bool GroupRetreat; internal float RetreatDistance = 45f; internal float Buffer = 1.5f; internal float RadiusMultiplier = 1f; internal HashSet<string> Exclusions = Rules.Names("Deer,Seagal,Crow"); private FileSystemWatcher watcher; private bool reload; private float reloadAt; private float nextMaintenance; private int reloadRetries; private string hiddenKey; private ZNetScene mappedScene; internal readonly Dictionary<MonsterAI, Mind> Minds = new Dictionary<MonsterAI, Mind>(); private readonly Dictionary<int, string> tierKeys = new Dictionary<int, string>(); internal static readonly int StateKey = StringExtensionMethods.GetStableHashCode("goml.state"); internal static readonly int StampKey = StringExtensionMethods.GetStableHashCode("goml.stamp"); internal static readonly int ThreatKey = StringExtensionMethods.GetStableHashCode("goml.threat"); internal static readonly int UntilKey = StringExtensionMethods.GetStableHashCode("goml.until"); internal readonly List<Collider> Areas = new List<Collider>(); private readonly Dictionary<EffectArea, ScaledArea> scaledAreas = new Dictionary<EffectArea, ScaledArea>(); private readonly HashSet<EffectArea> proxies = new HashSet<EffectArea>(); private bool unsupportedWarning; private static readonly int ShotProtectedKey = StringExtensionMethods.GetStableHashCode("goml.shotProtected"); private static readonly int ShotOriginKey = StringExtensionMethods.GetStableHashCode("goml.shotOrigin"); [ThreadStatic] private static Projectile hitProjectile; private ZNet session; private ZRpc server; private readonly Dictionary<ZRpc, ZNetPeer> clients = new Dictionary<ZRpc, ZNetPeer>(); private readonly Dictionary<ZRpc, float> deadlines = new Dictionary<ZRpc, float>(); private float nextRequest; private float connectedAt; private bool received; private Rect window = new Rect(20f, 100f, 760f, 440f); private Vector2 scroll; private readonly List<string> playerRows = new List<string>(); private readonly List<DebugRow> mobRows = new List<DebugRow>(); private readonly List<GameObject> lines = new List<GameObject>(); private Material lineMaterial; private Texture2D windowTexture; private GUIStyle windowStyle; private bool shaderWarning; internal static double Now { get { if (!((Object)(object)ZNet.instance == (Object)null)) { return ZNet.instance.GetTimeSeconds(); } return 0.0; } } private bool CombatRoute(MonsterAI ai, Character c, Character target, Mind mind, float dt, float margin) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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_0154: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) Vector3 position = ((Component)c).transform.position; Vector3 position2 = ((Component)target).transform.position; if ((Object)(object)mind.CombatTarget != (Object)(object)target) { mind.CombatTarget = target; mind.CombatDetour = false; mind.CombatRoute.Clear(); mind.NextCombatPlan = 0f; } if (Time.time >= mind.NextCombatPlan) { mind.NextCombatPlan = Time.time + 1.25f; List<Vector3> path = new List<Vector3>(); if (NativeLeg(ai, c, position, position2, margin, path)) { mind.CombatDetour = false; mind.CombatRoute.Clear(); mind.HasDestination = false; mind.PendingAvoid = false; return false; } if (!mind.CombatDetour && !mind.PendingAvoid && SegmentClear(position, position2, margin)) { return false; } mind.CombatDetour = true; if (mind.CombatRoute.Count == 0 || mind.Blocked || Vector3.Distance(position2, mind.CombatGoal) > 4f || !RouteClear(position, mind.CombatRoute, margin, exiting: false)) { mind.CombatRoute = PlanCombat(ai, c, position2, margin); mind.CombatGoal = position2; } } if (!mind.CombatDetour) { return false; } while (mind.CombatRoute.Count > 0 && Vector3.Distance(position, mind.CombatRoute[0]) < 1.5f) { mind.CombatRoute.RemoveAt(0); } mind.Moving = true; mind.Blocked = false; try { if (mind.CombatRoute.Count > 0) { Hooks.Move((BaseAI)(object)ai, dt, mind.CombatRoute[0], 0.5f, run: true); if (mind.Blocked) { mind.CombatRoute.Clear(); } Mark(ai, mind.Blocked ? 7 : 6); } else { c.StopMovement(); Hooks.Face((BaseAI)(object)ai, position2); Mark(ai, 7); } } finally { mind.Moving = false; } return true; } private bool NativeLeg(MonsterAI ai, Character c, Vector3 from, Vector3 to, float margin, List<Vector3> path) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0027: 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_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0042: 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_0048: Unknown result type (might be due to invalid IL or missing references) if (Protected(to, margin)) { return false; } path.Clear(); if (c.IsFlying() || c.IsSwimming()) { path.Add(to); } else if ((Object)(object)Pathfinding.instance == (Object)null || !Pathfinding.instance.GetPath(from, to, path, ((BaseAI)ai).m_pathAgentType, false, true, false) || path.Count == 0) { return false; } return RouteClear(from, path, margin, Protected(from, margin)); } private List<Vector3> PlanCombat(MonsterAI ai, Character c, Vector3 goal, float margin) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0027: 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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: 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_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: 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_00e4: 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_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_026b: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0259: 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_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_0284: 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_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_0353: Unknown result type (might be due to invalid IL or missing references) //IL_0361: Unknown result type (might be due to invalid IL or missing references) //IL_02d6: Unknown result type (might be due to invalid IL or missing references) //IL_02de: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_03c7: Unknown result type (might be due to invalid IL or missing references) Vector3 start = ((Component)c).transform.position; List<Vector3> list = new List<Vector3>(); list.Add(start); list.Add(goal); List<Vector3> list2 = list; List<Collider> list3 = new List<Collider>(); foreach (Collider area in Areas) { if (Live(area) && Vector3.Distance(area.ClosestPoint(start), start) < 150f) { list3.Add(area); } } list3.Sort(delegate(Collider a, Collider b) { //IL_0002: 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_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: 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_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) Vector3 val4 = a.ClosestPoint(start) - start; float sqrMagnitude = ((Vector3)(ref val4)).sqrMagnitude; Vector3 val5 = b.ClosestPoint(start) - start; return sqrMagnitude.CompareTo(((Vector3)(ref val5)).sqrMagnitude); }); Vector3 val3 = default(Vector3); float num6 = default(float); for (int num = 0; num < Mathf.Min(8, list3.Count); num++) { Collider val = list3[num]; Bounds bounds = val.bounds; float num2; if (!(val is SphereCollider)) { Vector2 val2 = new Vector2(((Bounds)(ref bounds)).extents.x, ((Bounds)(ref bounds)).extents.z); num2 = ((Vector2)(ref val2)).magnitude; } else { num2 = Mathf.Max(((Bounds)(ref bounds)).extents.x, ((Bounds)(ref bounds)).extents.z); } float num3 = num2; num3 = (num3 + margin + 3f) / Mathf.Cos((float)Math.PI / 16f); for (int num4 = 0; num4 < 16; num4++) { float num5 = (float)num4 * (float)Math.PI * 2f / 16f; ((Vector3)(ref val3))..ctor(((Bounds)(ref bounds)).center.x + Mathf.Cos(num5) * num3, start.y, ((Bounds)(ref bounds)).center.z + Mathf.Sin(num5) * num3); if (!c.IsFlying() && !c.IsSwimming()) { if (!Heightmap.GetHeight(val3, ref num6)) { continue; } val3.y = num6; if ((((BaseAI)ai).m_avoidWater && num6 < 30f) || (((BaseAI)ai).m_avoidLavaFlee && (Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.IsLava(val3, false))) { continue; } } if (!Protected(val3, margin)) { list2.Add(val3); } } } int count = list2.Count; float[,] edges = new float[count, count]; for (int num7 = 0; num7 < count; num7++) { for (int num8 = num7 + 1; num8 < count; num8++) { bool flag = ((num7 == 0 && Protected(start, margin)) ? RouteClear(start, (IList<Vector3>)(object)new Vector3[1] { list2[num8] }, margin, exiting: true) : SegmentClear(list2[num7], list2[num8], margin)); edges[num7, num8] = (edges[num8, num7] = (flag ? Vector3.Distance(list2[num7], list2[num8]) : float.PositiveInfinity)); } } for (int num9 = 0; num9 < 4; num9++) { List<int> list4 = RouteSearch.Shortest(count, (int a, int b) => edges[a, b]); if (list4.Count == 0) { break; } List<Vector3> path = new List<Vector3>(); if (!NativeLeg(ai, c, start, list2[list4[0]], margin, path)) { edges[0, list4[0]] = (edges[list4[0], 0] = float.PositiveInfinity); continue; } List<Vector3> list5 = new List<Vector3>(); { foreach (int item in list4) { list5.Add(list2[item]); } return list5; } } return new List<Vector3>(); } private void Awake() { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Expected O, but got Unknown //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Expected O, but got Unknown //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Expected O, but got Unknown //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Expected O, but got Unknown Instance = this; enabledConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Behavior", "Enabled", true, "Enable boss-gated avoidance. Server authoritative; live reload."); exclusionsConfig = ((BaseUnityPlugin)this).Config.Bind<string>("Behavior", "ExcludedPrefabs", "Deer,Seagal,Crow", "Comma-separated prefab exclusions. Bosses, tames, summons and bird AI are always excluded."); groupConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Behavior", "GroupRetreat", true, "Attacks from protection also repel nearby eligible same-faction creatures."); groupRadiusConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Behavior", "GroupRetreatRadius", 25f, new ConfigDescription("Radius around the struck enemy for group retreat, in metres. Server enforced; live reload.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 200f), new object[0])); distanceConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Behavior", "RetreatDistance", 45f, new ConfigDescription("Required separation from the attack/refuge point, in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(15f, 150f), new object[0])); bufferConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Behavior", "BoundaryBuffer", 1.5f, new ConfigDescription("Extra movement clearance beyond protection, in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 8f), new object[0])); radiusConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Protection", "RadiusMultiplier", 1f, new ConfigDescription("Server-enforced spawn protection size multiplier. Affects native spawn protection even when Behavior.Enabled is false. Live reload.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), new object[0])); debugConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "Enabled", false, "Local live toggle: diagnostic window and world protection wireframes."); debugRangeConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Debug", "Range", 50f, new ConfigDescription("Local nearby-mob and protection visualization range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(20f, 200f), new object[0])); ((BaseUnityPlugin)this).Config.Save(); harmony = new Harmony("local.getoffmylawn"); try { Hooks.Validate(); harmony.PatchAll(typeof(Plugin).Assembly); } catch { harmony.UnpatchSelf(); Instance = null; throw; } watcher = new FileSystemWatcher(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath)); watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite; watcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; watcher.Changed += ConfigChanged; watcher.Created += ConfigChanged; watcher.Renamed += ConfigChanged; watcher.EnableRaisingEvents = true; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Get Off My Lawn 0.1.2 loaded. Test build; all peers require the mod."); } private void ConfigChanged(object sender, FileSystemEventArgs args) { reload = true; reloadAt = Time.realtimeSinceStartup + 0.3f; reloadRetries = 0; } private void Update() { if (reload && Time.realtimeSinceStartup >= reloadAt) { reload = false; try { ((BaseUnityPlugin)this).Config.Reload(); } catch (IOException) { if (++reloadRetries <= 5) { reload = true; reloadAt = Time.realtimeSinceStartup + 0.5f; } } } if (Time.realtimeSinceStartup >= nextMaintenance) { nextMaintenance = Time.realtimeSinceStartup + 0.5f; NetworkTick(); DiscoverBossKeys(); ScaleProtection(); RefreshAreas(); foreach (KeyValuePair<MonsterAI, Mind> item in new List<KeyValuePair<MonsterAI, Mind>>(Minds)) { if ((Object)(object)item.Key == (Object)null) { Minds.Remove(item.Key); } } RefreshDebug(); } if (!debugConfig.Value || (Object)(object)Player.m_localPlayer == (Object)null) { ClearLines(); } } private void DiscoverBossKeys() { if ((Object)(object)mappedScene == (Object)(object)ZNetScene.instance) { return; } mappedScene = ZNetScene.instance; hiddenKey = null; tierKeys.Clear(); if ((Object)(object)mappedScene == (Object)null) { return; } int num = -1; foreach (GameObject prefab in mappedScene.m_prefabs) { Character component = prefab.GetComponent<Character>(); if ((Object)(object)component == (Object)null || !component.IsBoss()) { continue; } for (int i = 1; i < Rules.Keys.Length; i++) { if (component.m_defeatSetGlobalKey == Rules.Keys[i]) { tierKeys[i] = component.m_defeatSetGlobalKey; if (i == 7) { num = component.BossOrder(); } } } } int num2 = int.MaxValue; if (num < 0) { return; } foreach (GameObject prefab2 in mappedScene.m_prefabs) { Character component2 = prefab2.GetComponent<Character>(); if (!((Object)(object)component2 == (Object)null) && component2.IsBoss() && !string.IsNullOrEmpty(component2.m_defeatSetGlobalKey) && Array.IndexOf(Rules.Keys, component2.m_defeatSetGlobalKey) < 0 && component2.BossOrder() > num && component2.BossOrder() < num2) { num2 = component2.BossOrder(); hiddenKey = component2.m_defeatSetGlobalKey; } } if (hiddenKey != null) { tierKeys[8] = hiddenKey; } } internal static string Prefab(GameObject go) { return Utils.GetPrefabName(go); } internal int Tier(Character c) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected I4, but got Unknown return Rules.Map((int)c.GetFaction(), Prefab(((Component)c).gameObject)); } internal bool Excluded(Character c) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Invalid comparison between Unknown and I4 if (!((Object)(object)c == (Object)null) && !c.IsPlayer() && !c.IsTamed() && !c.IsBoss() && (int)c.GetFaction() != 8 && !((Object)(object)c.GetBaseAI() == (Object)null) && c.GetBaseAI() is MonsterAI && !Exclusions.Contains(Prefab(((Component)c).gameObject))) { return (Object)(object)((Component)c).GetComponent<RandomFlyingBird>() != (Object)null; } return true; } internal bool Eligible(Character c, bool requireOwner) { if ((Object)(object)c == (Object)null) { return false; } int num = Tier(c); string value; bool defeated = (Object)(object)ZoneSystem.instance != (Object)null && tierKeys.TryGetValue(num, out value) && ZoneSystem.instance.GetGlobalKey(value); return Rules.CanOverride(Active, Excluded(c), c.IsTamed(), c.IsBoss(), c.GetBaseAI() is MonsterAI, !requireOwner || c.IsOwner(), num, defeated); } internal static Character Body(BaseAI ai) { if (!((Object)(object)ai == (Object)null)) { return ((Component)ai).GetComponent<Character>(); } return null; } internal Mind GetMind(MonsterAI ai) { //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_0075: Unknown result type (might be due to invalid IL or missing references) if (!Minds.TryGetValue(ai, out var value)) { value = new Mind(); Minds.Add(ai, value); ZNetView component = ((Component)ai).GetComponent<ZNetView>(); ZDO val = (((Object)(object)component == (Object)null) ? null : component.GetZDO()); if (val != null) { value.RetreatUntil = (double)val.GetLong(UntilKey, 0L) / 1000.0; value.Threat = val.GetVec3(ThreatKey, ((Component)ai).transform.position); } } return value; } internal void Mark(MonsterAI ai, int state) { GetMind(ai).State = state; } internal void Publish(MonsterAI ai) { Character val = Body((BaseAI)(object)ai); if ((Object)(object)val == (Object)null || !val.IsOwner()) { Minds.Remove(ai); } else { if (!Minds.TryGetValue(ai, out var value)) { return; } if (!Eligible(val, requireOwner: true)) { value.State = 0; value.RetreatUntil = 0.0; value.HasDestination = false; } ZNetView component = ((Component)ai).GetComponent<ZNetView>(); ZDO val2 = (((Object)(object)component == (Object)null) ? null : component.GetZDO()); if (val2 != null) { if (value.Published != value.State || (value.State != 0 && Now >= value.PublishAt)) { val2.Set(StateKey, value.State, false); val2.Set(StampKey, (long)(Now * 1000.0)); value.Published = value.State; value.PublishAt = Now + 0.5; } if (value.RetreatUntil == 0.0 && val2.GetLong(UntilKey, 0L) != 0) { val2.Set(UntilKey, 0L); } } } } private void OnDestroy() { Active = false; foreach (KeyValuePair<MonsterAI, Mind> item in new List<KeyValuePair<MonsterAI, Mind>>(Minds)) { if ((Object)(object)item.Key != (Object)null) { Publish(item.Key); } } if (watcher != null) { watcher.Dispose(); } ClearNetwork(); RestoreProtection(); ClearLines(); if ((Object)(object)lineMaterial != (Object)null) { Object.Destroy((Object)(object)lineMaterial); } if ((Object)(object)windowTexture != (Object)null) { Object.Destroy((Object)(object)windowTexture); } if (harmony != null) { harmony.UnpatchSelf(); } Instance = null; } private void RefreshAreas() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) Areas.Clear(); foreach (EffectArea allArea in EffectArea.GetAllAreas()) { if (!((Object)(object)allArea == (Object)null) && (byte)(allArea.m_type & 4) != 0) { Collider component = ((Component)allArea).GetComponent<Collider>(); if (Live(component)) { Areas.Add(component); } } } } internal static bool Live(Collider c) { if ((Object)(object)c != (Object)null && c.enabled) { return ((Component)c).gameObject.activeInHierarchy; } return false; } internal bool Protected(Vector3 position, float margin) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_003a: 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_0040: 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_0046: Unknown result type (might be due to invalid IL or missing references) if (margin <= 0f) { return (Object)(object)EffectArea.IsPointInsideArea(position, (Type)4, 0f) != (Object)null; } foreach (Collider area in Areas) { if (Live(area)) { Vector3 val = area.ClosestPoint(position) - position; if (((Vector3)(ref val)).sqrMagnitude <= margin * margin) { return true; } } } return false; } internal float Clearance(Vector3 point) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0027: 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) float num = float.MaxValue; foreach (Collider area in Areas) { if (Live(area)) { num = Mathf.Min(num, Vector3.Distance(area.ClosestPoint(point), point)); } } return num; } internal Vector3 ThreatAt(Vector3 position) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: 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_0034: 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_0079: 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) //IL_0069: 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_0072: Unknown result type (might be due to invalid IL or missing references) Collider val = null; float num = float.MaxValue; foreach (Collider area in Areas) { if (Live(area)) { Vector3 val2 = area.ClosestPoint(position) - position; float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude; if (sqrMagnitude < num) { num = sqrMagnitude; val = area; } } } if (!((Object)(object)val == (Object)null)) { Bounds bounds = val.bounds; return ((Bounds)(ref bounds)).center; } return position - Vector3.forward; } internal bool SegmentClear(Vector3 from, Vector3 to, float margin) { //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_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: 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) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: 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_0044: 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_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_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0090: 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_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0098: 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_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) float num = default(float); foreach (Collider area in Areas) { if (!Live(area)) { continue; } SphereCollider val = (SphereCollider)(object)((area is SphereCollider) ? area : null); if ((Object)(object)val != (Object)null) { Vector3 val2 = ((Component)val).transform.TransformPoint(val.center); Vector3 lossyScale = ((Component)val).transform.lossyScale; float radius = val.radius * Mathf.Max(Mathf.Abs(lossyScale.x), Mathf.Max(Mathf.Abs(lossyScale.y), Mathf.Abs(lossyScale.z))) + margin; Vector3 val3 = to - from; Vector3 val4 = from - val2; if (Rules.SegmentHitsSphere(val4.x, val4.y, val4.z, val3.x, val3.y, val3.z, radius)) { return false; } } else { Bounds bounds = area.bounds; ((Bounds)(ref bounds)).Expand(margin * 2f); Vector3 val5 = to - from; if (((Bounds)(ref bounds)).Contains(from) || ((Bounds)(ref bounds)).Contains(to) || (((Vector3)(ref val5)).sqrMagnitude > 0f && ((Bounds)(ref bounds)).IntersectRay(new Ray(from, ((Vector3)(ref val5)).normalized), ref num) && num <= ((Vector3)(ref val5)).magnitude)) { return false; } } } return true; } internal bool RouteClear(Vector3 from, IList<Vector3> path, float margin, bool exiting) { //IL_0001: 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_0023: 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) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: 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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_006c: 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_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: 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_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) bool flag = !Protected(from, margin); float num = Clearance(from); foreach (Vector3 item in path) { if (flag) { if (!SegmentClear(from, item, margin)) { return false; } } else { if (!exiting) { return false; } int num2 = Mathf.Max(1, Mathf.CeilToInt(Vector3.Distance(from, item) / 0.5f)); for (int i = 1; i <= num2; i++) { Vector3 val = Vector3.Lerp(from, item, (float)i / (float)num2); float num3 = Clearance(val); if (flag && Protected(val, margin)) { return false; } if (num3 + 0.2f < num) { return false; } if (!Protected(val, margin)) { flag = true; } num = num3; } } from = item; } return true; } internal void BeginRetreat(MonsterAI ai, Vector3 threat) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) Character c = Body((BaseAI)(object)ai); if (Eligible(c, requireOwner: true)) { Mind mind = GetMind(ai); mind.Threat = threat; mind.RetreatUntil = Now + 60.0; mind.HasDestination = false; mind.NextPlan = 0f; mind.CombatDetour = false; mind.CombatRoute.Clear(); mind.NextCombatPlan = 0f; ZDO zDO = ((Component)ai).GetComponent<ZNetView>().GetZDO(); if (zDO != null) { zDO.Set(ThreatKey, threat); zDO.Set(UntilKey, (long)(mind.RetreatUntil * 1000.0)); } } } internal void BeforeTargets(MonsterAI ai) { //IL_0030: 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) Character c = Body((BaseAI)(object)ai); if (Eligible(c, requireOwner: true)) { Mind mind = GetMind(ai); Character targetCreature = ((BaseAI)ai).GetTargetCreature(); if (targetCreature is Player && Protected(((Component)targetCreature).transform.position, 0f)) { BeginRetreat(ai, ((Component)targetCreature).transform.position); } else if (mind.CombatDetour && (Object)(object)targetCreature != (Object)null && ((BaseAI)ai).CanSenseTarget(targetCreature)) { Hooks.KeepCombat(ai); } if (mind.RetreatUntil > Now) { Hooks.ClearTargets(ai); } } } internal bool RunOverride(MonsterAI ai, float dt) { //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_0048: 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) //IL_00b5: 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) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_0240: 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_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) Character val = Body((BaseAI)(object)ai); if (!Eligible(val, requireOwner: true)) { return false; } Mind mind = GetMind(ai); Vector3 position = ((Component)val).transform.position; float margin = Buffer + val.GetRadius(); bool flag = mind.RetreatUntil > Now; if (flag && Vector3.Distance(position, mind.Threat) >= RetreatDistance && Clearance(position) >= 12f) { mind.RetreatUntil = 0.0; mind.HasDestination = false; flag = false; Hooks.Calm((BaseAI)(object)ai); } if (!flag && mind.RetreatUntil != 0.0) { mind.RetreatUntil = 0.0; mind.HasDestination = false; } bool flag2 = Protected(position, margin); if (!flag && Protected(position, 0f)) { BeginRetreat(ai, ThreatAt(position)); flag = true; } Character targetCreature = ((BaseAI)ai).GetTargetCreature(); if (!flag && (Object)(object)targetCreature != (Object)null && ((BaseAI)ai).IsAlerted() && !Protected(((Component)targetCreature).transform.position, 0f)) { if (CombatRoute(ai, val, targetCreature, mind, dt, margin)) { return true; } return false; } if (mind.CombatDetour) { mind.CombatDetour = false; mind.CombatRoute.Clear(); mind.NextCombatPlan = 0f; mind.HasDestination = false; mind.PendingAvoid = false; } if (!flag && !flag2 && !mind.HasDestination && !mind.PendingAvoid) { return false; } if (!flag && mind.HasDestination && Vector3.Distance(position, mind.Destination) < 2f) { mind.HasDestination = false; mind.PendingAvoid = false; return false; } if (flag || flag2) { Hooks.ClearTargets(ai); } if (Time.time >= mind.NextPlan) { mind.NextPlan = Time.time + 1.25f; if (!mind.HasDestination || Protected(mind.Destination, margin) || !RouteClear(position, (IList<Vector3>)(object)new Vector3[1] { mind.Destination }, margin, flag2)) { mind.HasDestination = Plan(ai, val, mind, flag, flag2, margin); } } mind.Moving = true; mind.Blocked = false; try { if (mind.HasDestination) { Hooks.Move((BaseAI)(object)ai, dt, mind.Destination, 1f, flag || flag2); Mark(ai, (!flag) ? (flag2 ? 3 : 2) : (mind.Blocked ? 5 : 4)); } else { val.StopMovement(); Mark(ai, flag ? 5 : (flag2 ? 3 : 2)); } } finally { mind.Moving = false; } return true; } private bool Plan(MonsterAI ai, Character c, Mind mind, bool retreat, bool inside, float margin) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: 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_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: 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_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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: 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_00b8: 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_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0161: 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_011e: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0181: 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_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: 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_01be: 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_01ec: 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) Vector3 position = ((Component)c).transform.position; Vector3 val = position - (retreat ? mind.Threat : ThreatAt(position)); val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude < 0.01f) { val = Vector3.forward; } ((Vector3)(ref val)).Normalize(); List<Vector3> list = new List<Vector3>(); float[] array = new float[10] { 0f, 35f, -35f, 70f, -70f, 110f, -110f, 150f, -150f, 180f }; float num = float.MinValue; bool result = false; float[] array2 = array; float num4 = default(float); foreach (float num2 in array2) { float num3 = (retreat ? Mathf.Max(20f, RetreatDistance) : (inside ? 25f : 10f)); Vector3 val2 = position + Quaternion.Euler(0f, num2, 0f) * val * num3; if (!c.IsFlying()) { if (!Heightmap.GetHeight(val2, ref num4)) { continue; } val2.y = num4; if ((((BaseAI)ai).m_avoidWater && num4 < 30f) || (((BaseAI)ai).m_avoidLavaFlee && (Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.IsLava(val2, false))) { continue; } } else { val2.y = position.y; } if (Protected(val2, margin)) { continue; } list.Clear(); if (c.IsFlying() || c.IsSwimming()) { list.Add(val2); } else if ((Object)(object)Pathfinding.instance == (Object)null || !Pathfinding.instance.GetPath(position, val2, list, ((BaseAI)ai).m_pathAgentType, false, true, false) || list.Count == 0) { continue; } if (RouteClear(position, list, margin, inside)) { float num5 = Clearance(val2); float num6; if (!retreat) { Vector3 val3 = val2 - position; num6 = Vector3.Dot(((Vector3)(ref val3)).normalized, val) * 10f; } else { num6 = Vector3.Distance(val2, mind.Threat); } float num7 = num5 + num6; if (!(num7 <= num)) { num = num7; mind.Destination = val2; result = true; } } } return result; } internal void AvoidStep(MonsterAI ai) { Mind mind = GetMind(ai); mind.Blocked = true; if (!mind.Moving) { mind.HasDestination = false; mind.PendingAvoid = true; mind.NextPlan = 0f; } Mark(ai, (mind.RetreatUntil > Now) ? 5 : 2); } private void ScaleProtection() { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Expected O, but got Unknown //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)session == (Object)null || (!session.IsServer() && !received)) { RestoreProtection(); return; } if (Mathf.Approximately(RadiusMultiplier, 1f)) { RestoreProtection(); return; } foreach (EffectArea item in new List<EffectArea>(EffectArea.GetAllAreas())) { if ((Object)(object)item == (Object)null || proxies.Contains(item) || scaledAreas.ContainsKey(item) || (byte)(item.m_type & 4) == 0) { continue; } Collider component = ((Component)item).GetComponent<Collider>(); if (!(component is SphereCollider) && !(component is BoxCollider) && !(component is CapsuleCollider)) { if (!unsupportedWarning) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"Unsupported spawn-protection collider left unchanged."); } unsupportedWarning = true; continue; } GameObject val = new GameObject("GOML spawn protection"); val.SetActive(false); val.layer = ((Component)item).gameObject.layer; val.transform.SetParent(((Component)item).transform, false); ((Object)val).hideFlags = (HideFlags)52; Collider val2 = (Collider)((component is SphereCollider) ? val.AddComponent<SphereCollider>() : ((component is BoxCollider) ? ((object)val.AddComponent<BoxCollider>()) : ((object)val.AddComponent<CapsuleCollider>()))); val2.isTrigger = true; EffectArea val3 = val.AddComponent<EffectArea>(); val3.m_type = (Type)4; ScaledArea scaledArea = new ScaledArea(); scaledArea.Source = item; scaledArea.Proxy = val3; scaledArea.Original = component; scaledArea.Scaled = val2; ScaledArea scaledArea2 = scaledArea; CopyShape(scaledArea2); scaledAreas.Add(item, scaledArea2); proxies.Add(val3); item.m_type = (Type)(byte)(item.m_type & 0xFB); val.SetActive(true); } foreach (KeyValuePair<EffectArea, ScaledArea> item2 in new List<KeyValuePair<EffectArea, ScaledArea>>(scaledAreas)) { ScaledArea value = item2.Value; if ((Object)(object)value.Source == (Object)null || (Object)(object)value.Original == (Object)null || (Object)(object)value.Proxy == (Object)null) { if ((Object)(object)value.Source != (Object)null) { EffectArea source = value.Source; source.m_type = (Type)(byte)(source.m_type | 4); } if ((Object)(object)value.Proxy != (Object)null) { value.Scaled.enabled = false; Object.Destroy((Object)(object)((Component)value.Proxy).gameObject); } proxies.Remove(value.Proxy); scaledAreas.Remove(item2.Key); } else { CopyShape(value); } } } private void CopyShape(ScaledArea area) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown //IL_0044: 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_0078: Expected O, but got Unknown //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) float radiusMultiplier = RadiusMultiplier; Collider original = area.Original; SphereCollider val = (SphereCollider)(object)((original is SphereCollider) ? original : null); Collider original2 = area.Original; BoxCollider val2 = (BoxCollider)(object)((original2 is BoxCollider) ? original2 : null); Collider original3 = area.Original; CapsuleCollider val3 = (CapsuleCollider)(object)((original3 is CapsuleCollider) ? original3 : null); if ((Object)(object)val != (Object)null) { SphereCollider val4 = (SphereCollider)area.Scaled; val4.center = val.center; val4.radius = val.radius * radiusMultiplier; } else if ((Object)(object)val2 != (Object)null) { BoxCollider val5 = (BoxCollider)area.Scaled; val5.center = val2.center; val5.size = val2.size * radiusMultiplier; } else if ((Object)(object)val3 != (Object)null) { CapsuleCollider val6 = (CapsuleCollider)area.Scaled; val6.center = val3.center; val6.radius = val3.radius * radiusMultiplier; val6.height = val3.height * radiusMultiplier; val6.direction = val3.direction; } area.Scaled.enabled = area.Original.enabled; } private void RestoreProtection() { //IL_0030: 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_0038: Unknown result type (might be due to invalid IL or missing references) foreach (ScaledArea value in scaledAreas.Values) { if ((Object)(object)value.Source != (Object)null) { EffectArea source = value.Source; source.m_type = (Type)(byte)(source.m_type | 4); } if ((Object)(object)value.Proxy != (Object)null) { if ((Object)(object)value.Scaled != (Object)null) { value.Scaled.enabled = false; } Object.Destroy((Object)(object)((Component)value.Proxy).gameObject); } } scaledAreas.Clear(); proxies.Clear(); } private void NetworkTick() { //IL_03b4: Unknown result type (might be due to invalid IL or missing references) //IL_03bb: Expected O, but got Unknown ZNet instance = ZNet.instance; if ((Object)(object)session != (Object)(object)instance) { ClearNetwork(); RestoreProtection(); session = instance; Active = false; RadiusMultiplier = 1f; mappedScene = null; Minds.Clear(); Areas.Clear(); } if ((Object)(object)instance == (Object)null) { return; } if (instance.IsServer()) { Active = enabledConfig.Value; GroupRetreat = groupConfig.Value; GroupRetreatRadius = (Rules.Valid(groupRadiusConfig.Value, 0f, 200f) ? groupRadiusConfig.Value : 25f); RetreatDistance = (Rules.Valid(distanceConfig.Value, 15f, 150f) ? distanceConfig.Value : 45f); Buffer = (Rules.Valid(bufferConfig.Value, 0.25f, 8f) ? bufferConfig.Value : 1.5f); RadiusMultiplier = (Rules.Valid(radiusConfig.Value, 0.5f, 2f) ? radiusConfig.Value : 1f); Exclusions = Rules.Names(exclusionsConfig.Value); foreach (ZNetPeer peer in instance.GetPeers()) { if (peer.IsReady() && !peer.m_server && !clients.ContainsKey(peer.m_rpc)) { clients.Add(peer.m_rpc, peer); deadlines[peer.m_rpc] = Time.realtimeSinceStartup + 30f; peer.m_rpc.Register<ZPackage>("GOML_Config_v2", (Action<ZRpc, ZPackage>)ReceiveRequest); } } { foreach (KeyValuePair<ZRpc, ZNetPeer> item in new List<KeyValuePair<ZRpc, ZNetPeer>>(clients)) { if (!instance.GetPeers().Contains(item.Value)) { item.Key.Unregister("GOML_Config_v2"); clients.Remove(item.Key); deadlines.Remove(item.Key); } else if (Time.realtimeSinceStartup > deadlines[item.Key]) { instance.Disconnect(item.Value); item.Key.Unregister("GOML_Config_v2"); clients.Remove(item.Key); deadlines.Remove(item.Key); } } return; } } ZNetPeer serverPeer = instance.GetServerPeer(); if (serverPeer == null || !serverPeer.IsReady()) { Active = false; received = false; RadiusMultiplier = 1f; return; } if (server != serverPeer.m_rpc) { if (server != null) { server.Unregister("GOML_Config_v2"); } server = serverPeer.m_rpc; server.Register<ZPackage>("GOML_Config_v2", (Action<ZRpc, ZPackage>)ReceiveConfig); received = false; Active = false; connectedAt = Time.realtimeSinceStartup; nextRequest = 0f; } if (Time.realtimeSinceStartup >= nextRequest) { nextRequest = Time.realtimeSinceStartup + 2f; ZPackage val = new ZPackage(); val.Write(1); server.Invoke("GOML_Config_v2", new object[1] { val }); } if (Time.realtimeSinceStartup > connectedAt + 30f) { Active = false; ((BaseUnityPlugin)this).Logger.LogWarning((object)"Compatible server settings missing; disconnecting test client."); instance.Disconnect(serverPeer); } } private void ReceiveRequest(ZRpc rpc, ZPackage package) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown if (!((Object)(object)session == (Object)null) && session.IsServer() && clients.ContainsKey(rpc) && package.Size() == 4 && package.ReadInt() == 1) { deadlines[rpc] = Time.realtimeSinceStartup + 30f; ZPackage val = new ZPackage(); val.Write(1); val.Write(Active); val.Write(GroupRetreat); val.Write(RetreatDistance); val.Write(Buffer); val.Write(RadiusMultiplier); val.Write(GroupRetreatRadius); val.Write(exclusionsConfig.Value); rpc.Invoke("GOML_Config_v2", new object[1] { val }); } } private void ReceiveConfig(ZRpc rpc, ZPackage package) { if ((Object)(object)session == (Object)null || session.IsServer() || rpc != server || package.Size() > 8192) { return; } try { if (package.ReadInt() == 1) { bool active = package.ReadBool(); bool groupRetreat = package.ReadBool(); float num = package.ReadSingle(); float num2 = package.ReadSingle(); float num3 = package.ReadSingle(); float num4 = package.ReadSingle(); string text = package.ReadString(); if (Rules.Valid(num, 15f, 150f) && Rules.Valid(num2, 0.25f, 8f) && Rules.Valid(num3, 0.5f, 2f) && Rules.Valid(num4, 0f, 200f) && text.Length <= 4096) { GroupRetreatRadius = num4; Active = active; GroupRetreat = groupRetreat; RetreatDistance = num; Buffer = num2; RadiusMultiplier = num3; Exclusions = Rules.Names(text); received = true; connectedAt = Time.realtimeSinceStartup; } } } catch (Exception) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"Invalid server configuration ignored."); } } private void ClearNetwork() { foreach (ZRpc key in clients.Keys) { key.Unregister("GOML_Config_v2"); } clients.Clear(); deadlines.Clear(); if (server != null) { server.Unregister("GOML_Config_v2"); } server = null; received = false; } private bool Hidden(Character c) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 if ((int)c.GetFaction() <= 11) { if (c.IsBoss() && !string.IsNullOrEmpty(c.m_defeatSetGlobalKey)) { return Array.IndexOf(Rules.Keys, c.m_defeatSetGlobalKey) < 0; } return false; } return true; } private void RefreshDebug() { //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) //IL_0069: 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_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_02d1: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: 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) if (!debugConfig.Value || (Object)(object)Player.m_localPlayer == (Object)null) { return; } Vector3 position = ((Component)Player.m_localPlayer).transform.position; playerRows.Clear(); mobRows.Clear(); float value = debugRangeConfig.Value; foreach (Player allPlayer in Player.GetAllPlayers()) { Vector3 position2 = ((Component)allPlayer).transform.position; playerRows.Add(allPlayer.GetPlayerName() + " " + ((Vector3)(ref position2)).ToString("F1") + " " + (Protected(position2, 0f) ? "protected" : "unprotected")); } foreach (Character allCharacter in Character.GetAllCharacters()) { if ((Object)(object)allCharacter == (Object)null || allCharacter.IsPlayer()) { continue; } float num = Vector3.Distance(position, ((Component)allCharacter).transform.position); if (num > value) { continue; } bool flag = Hidden(allCharacter); int state = 0; if (Eligible(allCharacter, requireOwner: false)) { BaseAI baseAI = allCharacter.GetBaseAI(); MonsterAI key = (MonsterAI)(object)((baseAI is MonsterAI) ? baseAI : null); if (allCharacter.IsOwner() && Minds.TryGetValue(key, out var value2)) { state = value2.State; } else { ZNetView component = ((Component)allCharacter).GetComponent<ZNetView>(); ZDO val = (((Object)(object)component == (Object)null) ? null : component.GetZDO()); if (val != null && Math.Abs(Now - (double)val.GetLong(StampKey, 0L) / 1000.0) < 2.0) { state = val.GetInt(StateKey, 0); } } } mobRows.Add(new DebugRow { Name = (flag ? "Hidden creature" : Localization.instance.Localize(allCharacter.m_name)), Distance = num, Faction = (flag ? "Hidden" : ((object)allCharacter.GetFaction()).ToString()), Boss = Rules.BossNames[Tier(allCharacter)], State = Rules.StateName(state) }); } foreach (IMonoUpdater instance in RandomFlyingBird.Instances) { RandomFlyingBird val2 = (RandomFlyingBird)(object)((instance is RandomFlyingBird) ? instance : null); if (!((Object)(object)val2 == (Object)null) && !((Object)(object)((Component)val2).GetComponent<Character>() != (Object)null)) { float num2 = Vector3.Distance(position, ((Component)val2).transform.position); if (!(num2 > value)) { string text = Prefab(((Component)val2).gameObject); mobRows.Add(new DebugRow { Name = ((text == "Seagal" || text == "Crow") ? text : "Hidden bird"), Distance = num2, Faction = "None (bird AI)", Boss = "None", State = "default" }); } } } mobRows.Sort((DebugRow a, DebugRow b) => a.Distance.CompareTo(b.Distance)); DrawBoundaries(position, value); } private void OnGUI() { //IL_01e4: 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_0205: Expected O, but got Unknown //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown if (debugConfig.Value && !((Object)(object)Player.m_localPlayer == (Object)null)) { if (windowStyle == null) { windowTexture = new Texture2D(1, 1); windowTexture.SetPixel(0, 0, new Color(0.09f, 0.09f, 0.09f, 1f)); windowTexture.Apply(); windowStyle = new GUIStyle(GUI.skin.window); windowStyle.normal.background = windowTexture; windowStyle.onNormal.background = windowTexture; windowStyle.hover.background = windowTexture; windowStyle.onHover.background = windowTexture; windowStyle.active.background = windowTexture; windowStyle.onActive.background = windowTexture; windowStyle.focused.background = windowTexture; windowStyle.onFocused.background = windowTexture; } ((Rect)(ref window)).width = Mathf.Min(900, Screen.width - 30); ((Rect)(ref window)).height = Mathf.Min(520, Screen.height - 40); ((Rect)(ref window)).x = Mathf.Clamp(((Rect)(ref window)).x, 0f, Mathf.Max(0f, (float)Screen.width - ((Rect)(ref window)).width)); ((Rect)(ref window)).y = Mathf.Clamp(((Rect)(ref window)).y, 0f, Mathf.Max(0f, (float)Screen.height - ((Rect)(ref window)).height)); window = GUI.Window(187541, window, new WindowFunction(DebugWindow), "Get Off My Lawn", windowStyle); } } private void DebugWindow(int id) { //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("Behavior: " + (Active ? "enabled" : "disabled") + " Config: " + (((Object)(object)session != (Object)null && session.IsServer()) ? "host" : (received ? "server" : "waiting")) + " Radius: " + RadiusMultiplier.ToString("F2") + "x Boss mappings: " + tierKeys.Count + "/8", (GUILayoutOption[])(object)new GUILayoutOption[0]); scroll = GUILayout.BeginScrollView(scroll, (GUILayoutOption[])(object)new GUILayoutOption[0]); foreach (string playerRow in playerRows) { GUILayout.Label(playerRow, (GUILayoutOption[])(object)new GUILayoutOption[0]); } GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); Cell("Name", 190f); Cell("Metres", 55f); Cell("Faction", 145f); Cell("Mapped boss", 95f); Cell("State", 220f); GUILayout.EndHorizontal(); foreach (DebugRow mobRow in mobRows) { GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); Cell(mobRow.Name, 190f); Cell(mobRow.Distance.ToString("F1"), 55f); Cell(mobRow.Faction, 145f); Cell(mobRow.Boss, 95f); Cell(mobRow.State, 220f); GUILayout.EndHorizontal(); } GUILayout.EndScrollView(); GUI.DragWindow(new Rect(0f, 0f, ((Rect)(ref window)).width, 22f)); } private static void Cell(string text, float width) { GUILayout.Label(text, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(width) }); } private void DrawBoundaries(Vector3 center, float range) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown //IL_006e: 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_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_018d: 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_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0304: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_0316: Unknown result type (might be due to invalid IL or missing references) //IL_030f: Unknown result type (might be due to invalid IL or missing references) //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_0324: Unknown result type (might be due to invalid IL or missing references) //IL_0326: Unknown result type (might be due to invalid IL or missing references) //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_033d: Unknown result type (might be due to invalid IL or missing references) //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0344: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_034d: Unknown result type (might be due to invalid IL or missing references) //IL_034f: Unknown result type (might be due to invalid IL or missing references) //IL_0351: Unknown result type (might be due to invalid IL or missing references) //IL_0353: Unknown result type (might be due to invalid IL or missing references) //IL_0358: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_029b: 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_0233: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_043b: Unknown result type (might be due to invalid IL or missing references) //IL_0440: Unknown result type (might be due to invalid IL or missing references) //IL_0445: Unknown result type (might be due to invalid IL or missing references) //IL_0447: Unknown result type (might be due to invalid IL or missing references) //IL_0449: Unknown result type (might be due to invalid IL or missing references) //IL_044d: Unknown result type (might be due to invalid IL or missing references) //IL_0452: Unknown result type (might be due to invalid IL or missing references) //IL_0457: Unknown result type (might be due to invalid IL or missing references) //IL_0459: Unknown result type (might be due to invalid IL or missing references) //IL_045b: Unknown result type (might be due to invalid IL or missing references) //IL_045f: Unknown result type (might be due to invalid IL or missing references) //IL_0464: Unknown result type (might be due to invalid IL or missing references) //IL_0469: Unknown result type (might be due to invalid IL or missing references) //IL_046c: Unknown result type (might be due to invalid IL or missing references) //IL_0470: Unknown result type (might be due to invalid IL or missing references) //IL_0472: Unknown result type (might be due to invalid IL or missing references) //IL_047a: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Unknown result type (might be due to invalid IL or missing references) //IL_0480: Unknown result type (might be due to invalid IL or missing references) //IL_0488: Unknown result type (might be due to invalid IL or missing references) //IL_048a: Unknown result type (might be due to invalid IL or missing references) //IL_048e: Unknown result type (might be due to invalid IL or missing references) //IL_0490: Unknown result type (might be due to invalid IL or missing references) //IL_0498: Unknown result type (might be due to invalid IL or missing references) //IL_049a: Unknown result type (might be due to invalid IL or missing references) //IL_049e: Unknown result type (might be due to invalid IL or missing references) //IL_04a0: Unknown result type (might be due to invalid IL or missing references) ClearLines(); if ((Object)(object)lineMaterial == (Object)null) { Shader val = Shader.Find("Sprites/Default"); if ((Object)(object)val == (Object)null) { val = Shader.Find("Unlit/Color"); } if ((Object)(object)val == (Object)null) { if (!shaderWarning) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"Debug boundary shader unavailable."); } shaderWarning = true; return; } lineMaterial = new Material(val); lineMaterial.color = Color.cyan; } foreach (Collider area in Areas) { if (!Live(area) || Vector3.Distance(area.ClosestPoint(center), center) > range) { continue; } SphereCollider val2 = (SphereCollider)(object)((area is SphereCollider) ? area : null); if ((Object)(object)val2 != (Object)null) { Vector3 center2 = ((Component)val2).transform.TransformPoint(val2.center); Vector3 lossyScale = ((Component)val2).transform.lossyScale; float num = val2.radius * Mathf.Max(Mathf.Abs(lossyScale.x), Mathf.Max(Mathf.Abs(lossyScale.y), Mathf.Abs(lossyScale.z))); Circle(center2, num, Vector3.right, Vector3.forward); Circle(center2, num, Vector3.up, Vector3.right); Circle(center2, num, Vector3.up, Vector3.forward); float num2 = center.y - center2.y; if (Mathf.Abs(num2) < num) { Circle(new Vector3(center2.x, center.y + 0.08f, center2.z), Mathf.Sqrt(num * num - num2 * num2), Vector3.right, Vector3.forward); } continue; } BoxCollider val3 = (BoxCollider)(object)((area is BoxCollider) ? area : null); CapsuleCollider val4 = (CapsuleCollider)(object)((area is CapsuleCollider) ? area : null); if ((Object)(object)val3 != (Object)null) { Vector3[] array = (Vector3[])(object)new Vector3[8]; for (int i = 0; i < 8; i++) { ref Vector3 reference = ref array[i]; reference = ((Component)val3).transform.TransformPoint(val3.center + Vector3.Scale(val3.size * 0.5f, new Vector3((float)(((i & 1) != 0) ? 1 : (-1)), (float)(((i & 2) != 0) ? 1 : (-1)), (float)(((i & 4) != 0) ? 1 : (-1))))); } for (int j = 0; j < 8; j++) { for (int num3 = 1; num3 <= 4; num3 *= 2) { if ((j & num3) == 0) { Line((Vector3[])(object)new Vector3[2] { array[j], array[j | num3] }, loop: false); } } } } else if ((Object)(object)val4 != (Object)null) { Vector3 lossyScale2 = ((Component)val4).transform.lossyScale; Vector3 val5 = ((val4.direction == 0) ? Vector3.right : ((val4.direction == 1) ? Vector3.up : Vector3.forward)); Vector3 val6 = ((val4.direction == 0) ? Vector3.up : Vector3.right); Vector3 val7 = ((Component)val4).transform.TransformDirection(val5); Vector3 normalized = ((Vector3)(ref val7)).normalized; Vector3 val8 = ((Component)val4).transform.TransformDirection(val6); Vector3 normalized2 = ((Vector3)(ref val8)).normalized; Vector3 val9 = Vector3.Cross(normalized, normalized2); float num4 = ((val4.direction == 0) ? Mathf.Abs(lossyScale2.x) : ((val4.direction == 1) ? Mathf.Abs(lossyScale2.y) : Mathf.Abs(lossyScale2.z))); float num5 = ((val4.direction == 0) ? Mathf.Max(Mathf.Abs(lossyScale2.y), Mathf.Abs(lossyScale2.z)) : ((val4.direction == 1) ? Mathf.Max(Mathf.Abs(lossyScale2.x), Mathf.Abs(lossyScale2.z)) : Mathf.Max(Mathf.Abs(lossyScale2.x), Mathf.Abs(lossyScale2.y)))); float num6 = val4.radius * num5; float num7 = Mathf.Max(0f, val4.height * num4 * 0.5f - num6); Vector3 val10 = ((Component)val4).transform.TransformPoint(val4.center); Vector3 val11 = val10 + normalized * num7; Vector3 val12 = val10 - normalized * num7; Circle(val11, num6, normalized2, val9); Circle(val12, num6, normalized2, val9); CapsuleOutline(val11, val12, num6, normalized, normalized2); CapsuleOutline(val11, val12, num6, normalized, val9); } } } private void Circle(Vector3 center, float radius, Vector3 a, Vector3 b) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: 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_004c: 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) Vector3[] array = (Vector3[])(object)new Vector3[80]; for (int i = 0; i < array.Length; i++) { float num = (float)i * (float)Math.PI * 2f / (float)array.Length; ref Vector3 reference = ref array[i]; reference = center + radius * (a * Mathf.Cos(num) + b * Mathf.Sin(num)); } Line(array, loop: true); } private void CapsuleOutline(Vector3 top, Vector3 bottom, float radius, Vector3 axis, Vector3 side) { //IL_0039: 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_003e: 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_004b: 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_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) Vector3[] array = (Vector3[])(object)new Vector3[80]; for (int i = 0; i < array.Length; i++) { float num = (float)i * (float)Math.PI * 2f / (float)array.Length; float num2 = Mathf.Sin(num); ref Vector3 reference = ref array[i]; reference = ((num2 >= 0f) ? top : bottom) + radius * (axis * num2 + side * Mathf.Cos(num)); } Line(array, loop: true); } private void Line(Vector3[] points, bool loop) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("GOML debug boundary"); ((Object)val).hideFlags = (HideFlags)52; LineRenderer val2 = val.AddComponent<LineRenderer>(); ((Renderer)val2).sharedMaterial = lineMaterial; val2.useWorldSpace = true; val2.loop = loop; val2.startWidth = 0.08f; val2.endWidth = 0.08f; val2.startColor = Color.cyan; val2.endColor = Color.cyan; ((Renderer)val2).shadowCastingMode = (ShadowCastingMode)0; ((Renderer)val2).receiveShadows = false; val2.positionCount = points.Length; val2.SetPositions(points); lines.Add(val); } private void ClearLines() { foreach (GameObject line in lines) { if ((Object)(object)line != (Object)null) { Object.Destroy((Object)(object)line); } } lines.Clear(); } } internal static class Hooks { [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] private static class UpdateAI { private static void Prefix(MonsterAI __instance) { Plugin instance = Plugin.Instance; if (!((Object)(object)instance == (Object)null) && instance.Minds.TryGetValue(__instance, out var value)) { value.State = 0; } } private static void Postfix(MonsterAI __instance) { if ((Object)(object)Plugin.Instance != (Object)null) { Plugin.Instance.Publish(__instance); } } private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> source, ILGenerator generator) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Expected O, but got Unknown //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Expected O, but got Unknown //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(typeof(MonsterAI), "UpdateTarget", (Type[])null, (Type[])null); List<CodeInstruction> list = new List<CodeInstruction>(); int num = 0; foreach (CodeInstruction item in source) { list.Add(new CodeInstruction(item)); if (CodeInstructionExtensions.Calls(item, methodInfo)) { num++; Label label = generator.DefineLabel(); list.Add(new CodeInstruction(OpCodes.Ldarg_0, (object)null)); list.Add(new CodeInstruction(OpCodes.Ldarg_1, (object)null)); list.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Hooks), "Override", (Type[])null, (Type[])null))); list.Add(new CodeInstruction(OpCodes.Brfalse, (object)label)); list.Add(new CodeInstruction(OpCodes.Ldc_I4_1, (object)null)); list.Add(new CodeInstruction(OpCodes.Ret, (object)null)); CodeInstruction val = new CodeInstruction(OpCodes.Nop, (object)null); val.labels.Add(label); list.Add(val); } } if (num != 1) { throw new InvalidOperationException("Expected one native AI target update."); } return list; } } [HarmonyPatch(typeof(MonsterAI), "UpdateTarget")] private static class UpdateTarget { private static void Prefix(MonsterAI __instance) { if ((Object)(object)Plugin.Instance != (Object)null) { Plugin.Instance.BeforeTargets(__instance); } } private static void Postfix(MonsterAI __instance) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) Plugin instance = Plugin.Instance; if (!((Object)(object)instance == (Object)null) && instance.Eligible(Plugin.Body((BaseAI)(object)__instance), requireOwner: true)) { Character targetCreature = ((BaseAI)__instance).GetTargetCreature(); if ((Object)(object)targetCreature != (Object)null && Filter(__instance, targetCreature)) { ClearTargets(__instance); } StaticTarget staticTarget = __instance.GetStaticTarget(); if ((Object)(object)staticTarget != (Object)null && instance.Protected(((Component)staticTarget).transform.position, 0f)) { StaticTargetField.SetValue(__instance, null); instance.Mark(__instance, 1); } } } } [HarmonyPatch(typeof(BaseAI), "FindEnemy")] private static class FindEnemy { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> source) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); int num = 0; MethodInfo methodInfo = AccessTools.Method(typeof(BaseAI), "IsEnemy", new Type[2] { typeof(Character), typeof(Character) }, (Type[])null); foreach (CodeInstruction item in source) { CodeInstruction val = new CodeInstruction(item); if (CodeInstructionExtensions.Calls(val, methodInfo)) { val.operand = AccessTools.Method(typeof(Hooks), "AcquisitionEnemy", (Type[])null, (Type[])null); num++; } list.Add(val); } if (num != 1) { throw new InvalidOperationException("Native enemy acquisition changed."); } return list; } private static void Postfix(BaseAI __instance, ref Character __result) { MonsterAI val = (MonsterAI)(object)((__instance is MonsterAI) ? __instance : null); if ((Object)(object)val != (Object)null && (Object)(object)__result != (Object)null && Filter(val, __result)) { __result = null; } } } [HarmonyPatch(typeof(MonsterAI), "SetTarget")] private static class SetTarget { private static bool Prefix(MonsterAI __instance, Character __0) { if (!((Object)(object)__0 == (Object)null)) { return !Filter(__instance, __0); } return true; } } [HarmonyPatch(typeof(BaseAI), "FindPath")] private static class FindPath { private static void Postfix(BaseAI __instance, ref bool __result) { //IL_0053: 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) Plugin instance = Plugin.Instance; MonsterAI val = (MonsterAI)(object)((__instance is MonsterAI) ? __instance : null); Character val2 = Plugin.Body((BaseAI)(object)val); if (__result && !((Object)(object)instance == (Object)null) && instance.Eligible(val2, requireOwner: true)) { float margin = instance.Buffer + val2.GetRadius(); List<Vector3> list = (List<Vector3>)Path.GetValue(val); if (!instance.RouteClear(((Component)val2).transform.position, list, margin, instance.GetMind(val).Moving && instance.Protected(((Component)val2).transform.position, margin))) { __result = false; list.Clear(); PathResult.SetValue(val, false); PathTime.SetValue(val, Time.time - 10f); instance.AvoidStep(val); } } } } [HarmonyPatch(typeof(BaseAI), "MoveTo")] private static class MoveTo { private static bool Prefix(BaseAI __instance, Vector3 __1, ref bool __result) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) Plugin instance = Plugin.Instance; MonsterAI ai = (MonsterAI)(object)((__instance is MonsterAI) ? __instance : null); Character val = Plugin.Body((BaseAI)(object)ai); if ((Object)(object)instance == (Object)null || !instance.Eligible(val, requireOwner: true) || instance.GetMind(ai).Moving) { return true; } if (!instance.Protected(__1, instance.Buffer + val.GetRadius())) { return true; } val.StopMovement(); instance.AvoidStep(ai); __result = false; return false; } } [HarmonyPatch(typeof(BaseAI), "MoveTowards")] private static class MoveTowards { private static bool Prefix(BaseAI __instance, Vector3 __0) { //IL_0046: 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_0062: 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_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_008a: 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_00a4: Unknown result type (might be due to invalid IL or missing references) Plugin instance = Plugin.Instance; MonsterAI ai = (MonsterAI)(object)((__instance is MonsterAI) ? __instance : null); Character val = Plugin.Body((BaseAI)(object)ai); if ((Object)(object)instance == (Object)null || !instance.Eligible(val, requireOwner: true)) { return true; } float margin = instance.Buffer + val.GetRadius(); Plugin.Mind mind = instance.GetMind(ai); Vector3 val2 = ((Component)val).transform.position + ((Vector3)(ref __0)).normalized * Mathf.Max(2f, val.GetRadius()); if (instance.RouteClear(((Component)val).transform.position, (IList<Vector3>)(object)new Vector3[1] { val2 }, margin, mind.Moving && instance.Protected(((Component)val).transform.position, margin))) { return true; } val.StopMovement(); instance.AvoidStep(ai); return false; } } [HarmonyPatch(typeof(MonsterAI), "OnDamaged")] private static class OnDamaged { private static void Prefix(MonsterAI __instance, Character __1) { //IL_001e: 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) Plugin instance = Plugin.Instance; if ((Object)(object)instance != (Object)null && __1 is Player && instance.Protected(((Component)__1).transform.position, 0f)) { instance.BeginRetreat(__instance, ((Component)__1).transform.position); } } } [HarmonyPatch(typeof(MonsterAI), "DoAttack")] private static class DoAttack { private static bool Prefix(MonsterAI __instance, ref bool __result) { //IL_0050: 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) Plugin instance = Plugin.Instance; if ((Object)(object)instance == (Object)null || !instance.Eligible(Plugin.Body((BaseAI)(object)__instance), requireOwner: true)) { return true; } Character targetCreature = ((BaseAI)__instance).GetTargetCreature(); StaticTarget staticTarget = __instance.GetStaticTarget(); if (instance.GetMind(__instance).RetreatUntil <= Plugin.Now && (!(targetCreature is Player) || !instance.Protected(((Component)targetCreature).transform.position, 0f)) && (!((Object)(object)staticTarget != (Object)null) || !instance.Protected(((Component)staticTarget).transform.position, 0f))) { return true; } ClearTargets(__instance); instance.Mark(__instance, 1); __result = false; return false; } } internal static readonly FieldInfo CreatureTarget = AccessTools.Field(typeof(MonsterAI), "m_targetCreature"); internal static readonly FieldInfo StaticTargetField = AccessTools.Field(typeof(MonsterAI), "m_targetStatic"); private static readonly FieldInfo Sensed = AccessTools.Field(typeof(MonsterAI), "m_timeSinceSensedTargetCreature"); private static readonly FieldInfo BeenAtLast = AccessTools.Field(typeof(MonsterAI), "m_beenAtLastPos"); private static readonly FieldInfo Path = AccessTools.Field(typeof(BaseAI), "m_path"); private static readonly FieldInfo PathResult = AccessTools.Field(typeof(BaseAI), "m_lastFindPathResult"); private static readonly FieldInfo PathTime = AccessTools.Field(typeof(BaseAI), "m_lastFindPathTime"); private static readonly MethodInfo MoveMethod = AccessTools.Method(typeof(BaseAI), "MoveTo", (Type[])null, (Type[])null); private static readonly MethodInfo TargetInfo = AccessTools.Method(typeof(BaseAI), "SetTargetInfo", (Type[])null, (Type[])null); private static readonly MethodInfo Alerted = AccessTools.Method(typeof(BaseAI), "SetAlerted", (Type[])null, (Type[])null); private static readonly MethodInfo Look = AccessTools.Method(typeof(BaseAI), "LookAt", new Type[1] { typeof(Vector3) }, (Type[])null); private static readonly FieldInfo AttackAge = AccessTools.Field(typeof(MonsterAI), "m_timeSinceAttacking"); private static readonly FieldInfo UnableAge = AccessTools.Field(typeof(MonsterAI), "m_unableToAttackTargetTimer"); internal static void Face(BaseAI ai, Vector3 target) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) Look.Invoke(ai, new object[1] { target }); } internal static void KeepCombat(MonsterAI ai) { AttackAge.SetValue(ai, 0f); UnableAge.SetValue(ai, 0f); } internal static void Calm(BaseAI ai) { Alerted.Invoke(ai, new object[1] { false }); } internal static void Validate() { if (CreatureTarget == null || StaticTargetField == null || Sensed == null || BeenAtLast == null || Path == null || PathResult == null || PathTime == null || Alerted == null || MoveMethod == null || TargetInfo == null || Look == null || AttackAge == null || UnableAge == null) { throw new MissingMemberException("Required AI members changed."); } } internal static void Move(BaseAI ai, float dt, Vector3 destination, float distance, bool run) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) MoveMethod.Invoke(ai, new object[4] { dt, destination, distance, run });
BepInEx/plugins/hex/AzuAutoStore.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
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.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using AzuAutoStore.APIs; using AzuAutoStore.APIs.Compatibility.WardIsLove; using AzuAutoStore.APIs.MUC; using AzuAutoStore.APIs.MUC.MUCSrc.Data; using AzuAutoStore.APIs.MUC.MUCSrc.Helper; using AzuAutoStore.APIs.MUC.MUCSrc.Patches; using AzuAutoStore.APIs.MUC.MUCSrc.Patches.Compatibility; using AzuAutoStore.Interfaces; using AzuAutoStore.Patches; using AzuAutoStore.Patches.Favoriting; using AzuAutoStore.Util; using AzuEPI; using AzuEPI.Core.Slots; using AzuExtendedPlayerInventory; using Backpacks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using ItemDataManager; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; 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: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: ComVisible(false)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyProduct("AzuAutoStore")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyDescription("")] [assembly: AssemblyTitle("AzuAutoStore")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyFileVersion("3.1.7")] [assembly: AssemblyCompany("Azumatt")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("3.1.7.0")] [module: <51048665-098b-49e5-b1b9-96c0b27f287d>RefSafetyRules(11)] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<807bf496-c81f-4d74-8330-ba5be723f914>Embedded] internal sealed class <807bf496-c81f-4d74-8330-ba5be723f914>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [<807bf496-c81f-4d74-8330-ba5be723f914>Embedded] [CompilerGenerated] internal sealed class <31f19a94-c784-4aab-bc2b-6331c6b22707>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <31f19a94-c784-4aab-bc2b-6331c6b22707>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <31f19a94-c784-4aab-bc2b-6331c6b22707>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [<807bf496-c81f-4d74-8330-ba5be723f914>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [CompilerGenerated] internal sealed class <5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContextAttribute : Attribute { public readonly byte Flag; public <5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [<807bf496-c81f-4d74-8330-ba5be723f914>Embedded] internal sealed class <51048665-098b-49e5-b1b9-96c0b27f287d>RefSafetyRulesAttribute : Attribute { public readonly int Version; public <51048665-098b-49e5-b1b9-96c0b27f287d>RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LocalizationManager { [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(1)] [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] [PublicAPI] public class Localizer { private static readonly Dictionary<string, Dictionary<string, Func<string>>> PlaceholderProcessors; private static readonly Dictionary<string, Dictionary<string, string>> loadedTexts; private static readonly ConditionalWeakTable<Localization, string> localizationLanguage; private static readonly List<WeakReference<Localization>> localizationObjects; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] private static BaseUnityPlugin _plugin; private static readonly List<string> 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<TypeInfo> 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([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] [method: <5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(2)] [field: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] public static event Action OnLocalizationComplete; private static void UpdatePlaceholderText(Localization localization, string key) { localizationLanguage.TryGetValue(localization, out var value); string text = loadedTexts[value][key]; if (PlaceholderProcessors.TryGetValue(key, out var value2)) { text = value2.Aggregate(text, [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (string current, KeyValuePair<string, Func<string>> kv) => current.Replace("{" + kv.Key + "}", kv.Value())); } localization.AddWord(key, text); } public static void AddPlaceholder<T>(string key, string placeholder, ConfigEntry<T> config, [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1, 1 })] Func<T, string> convertConfigValue = null) { if (convertConfigValue == null) { convertConfigValue = (T val) => val.ToString(); } if (!PlaceholderProcessors.ContainsKey(key)) { PlaceholderProcessors[key] = new Dictionary<string, Func<string>>(); } config.SettingChanged += [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (object _, EventArgs _) => { 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<WeakReference<Localization>> list = new List<WeakReference<Localization>>(); foreach (WeakReference<Localization> localizationObject in localizationObjects) { if (localizationObject.TryGetTarget(out var target)) { Dictionary<string, string> dictionary = loadedTexts[localizationLanguage.GetOrCreateValue(target)]; if (!target.m_translations.ContainsKey(key)) { dictionary[key] = text; target.AddWord(key, text); } } else { list.Add(localizationObject); } } foreach (WeakReference<Localization> 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<Localization>(__instance)); } localizationLanguage.Add(__instance, language); Dictionary<string, string> dictionary = new Dictionary<string, string>(); 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<string, string> dictionary2 = new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>>(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<string, string> item2 in new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>>(text2) ?? new Dictionary<string, string>()) { dictionary2[item2.Key] = item2.Value; } } loadedTexts[language] = dictionary2; foreach (KeyValuePair<string, string> 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<string, Dictionary<string, Func<string>>>(); loadedTexts = new Dictionary<string, Dictionary<string, string>>(); localizationLanguage = new ConditionalWeakTable<Localization, string>(); localizationObjects = new List<WeakReference<Localization>>(); fileExtensions = new List<string>(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); } [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] private static byte[] LoadTranslationFromAssembly(string language) { foreach (string fileExtension in fileExtensions) { byte[] array = ReadEmbeddedFileBytes("translations." + language + fileExtension); if (array != null) { return array; } } return null; } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(2)] public static byte[] ReadEmbeddedFileBytes([<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(1)] string resourceFileName, Assembly containingAssembly = null) { using MemoryStream memoryStream = new MemoryStream(); if ((object)containingAssembly == null) { containingAssembly = Assembly.GetCallingAssembly(); } string text = containingAssembly.GetManifestResourceNames().FirstOrDefault([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (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 { [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(1)] public const string Version = "1.4.1"; } } namespace ItemDataManager { [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] [PublicAPI] [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(1)] public abstract class ItemData { internal static WeakReference<<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo> constructingInfo = null; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1 })] internal WeakReference<<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo> info; private static readonly FieldInfo parameterInfoClassImpl = AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl"); private static Dictionary<Type, Dictionary<string, FieldInfo>> serializedFields = new Dictionary<Type, Dictionary<string, FieldInfo>>(); public string CustomDataKey { get; internal set; } protected virtual bool AllowStackingIdenticalValues { get; set; } public string Value { get { if (!Item.m_customData.TryGetValue(CustomDataKey, out var value)) { return ""; } return value; } set { Item.m_customData[CustomDataKey] = value; } } public string Key { get; internal set; } public bool IsCloned => Info.isCloned.Contains(CustomDataKey); public bool IsAlive { get { <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo target; return (info ?? constructingInfo).TryGetTarget(out target); } } public ItemData Item => Info.ItemData; public <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo Info { get { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown if (!(info ?? constructingInfo).TryGetTarget(out var target)) { return new <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo(new ItemData()); } return target; } } public virtual void FirstLoad() { } public virtual void Load() { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown Dictionary<string, FieldInfo> dictionary = fetchSerializedFields(); if (dictionary == null || dictionary.Count <= 0 || Value == "") { return; } List<object> list = new List<object>(); string[] array = Value.Split(new char[1] { '|' }); for (int i = 0; i < array.Length; i++) { string[] array2 = array[i].Split(new char[1] { ':' }); if (array2.Length == 2 && dictionary.TryGetValue(array2[0], out var value)) { ZPackage val = new ZPackage(array2[1]); ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); parameterInfoClassImpl.SetValue(parameterInfo, value.FieldType); list.Clear(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, val, ref list); if (list.Count > 0) { value.SetValue(this, list[0]); } } } } public virtual void Save() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown Dictionary<string, FieldInfo> dictionary = fetchSerializedFields(); if (dictionary == null || dictionary.Count <= 0) { return; } StringBuilder stringBuilder = new StringBuilder(); foreach (FieldInfo value in dictionary.Values) { ZPackage val = new ZPackage(); ZRpc.Serialize(new object[1] { value.GetValue(this) }, ref val); stringBuilder.Append(value.Name); stringBuilder.Append(':'); stringBuilder.Append(val.GetBase64()); stringBuilder.Append('|'); } int length = stringBuilder.Length - 1; stringBuilder.Length = length; Value = stringBuilder.ToString(); } public virtual void Unload() { } public virtual void Upgraded() { } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(2)] public virtual string TryStack(ItemData data) { if (!AllowStackingIdenticalValues || !(data?.Value == Value)) { return null; } return Value; } private Dictionary<string, FieldInfo> fetchSerializedFields() { Type type = GetType(); if (serializedFields.TryGetValue(type, out var value)) { return value; } return serializedFields[type] = (from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where f.GetCustomAttributes(typeof(SerializeField), inherit: true).Length != 0 select f).ToDictionary([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (FieldInfo f) => f.Name, [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (FieldInfo f) => f); } } public sealed class <eb0313fd-caea-4e6f-b583-2e689a3d665d>StringItemData : ItemData { } [PublicAPI] [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(1)] public class <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo : IEnumerable<ItemData>, IEnumerable { public static HashSet<Type> ForceLoadTypes; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] internal static string _modGuid; private static Dictionary<Type, HashSet<Type>> typeInheritorsCache; private static HashSet<string> knownTypes; private Dictionary<string, ItemData> data = new Dictionary<string, ItemData>(); [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1 })] private WeakReference<<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo> selfReference; internal HashSet<string> isCloned = new HashSet<string>(); [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] private static ItemData awakeningItem; private static Assembly primaryAssembly; private static Dictionary<Assembly, string> assemblyNameCache; private static Dictionary<Type, string> classKeyCache; private HashSet<string> fetchedClassKeys = new HashSet<string>(); private static MethodInfo removeMethod; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] private static ItemData checkingForStackableItemData; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1, 1 })] private static Dictionary<string, string> newValuesOnStackable; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] private static ItemData currentlyUpgradingItem; internal static string modGuid => _modGuid ?? (_modGuid = ((Func<string>)delegate { //IL_0091: Unknown result type (might be due to invalid IL or missing references) IEnumerable<TypeInfo> source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } return ((BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)))).Info.Metadata.GUID; })()); public string Mod => modGuid; public ItemData ItemData { get; private set; } [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] public string this[string key] { [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] get { return Get<<eb0313fd-caea-4e6f-b583-2e689a3d665d>StringItemData>(key)?.Value; } [param: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] set { GetOrCreate<<eb0313fd-caea-4e6f-b583-2e689a3d665d>StringItemData>(key).Value = value ?? ""; } } internal static void addTypeToInheritorsCache(Type type, string typeKey) { if (!knownTypes.Contains(typeKey)) { knownTypes.Add(typeKey); Type type2 = type; while ((object)type2 != null) { AddInterfaces(type2); type2 = type2.BaseType; } } void AddInterfaces(Type baseType) { if (!typeInheritorsCache.TryGetValue(baseType, out var value)) { HashSet<Type> hashSet = (typeInheritorsCache[baseType] = new HashSet<Type>()); value = hashSet; } value.Add(type); Type[] interfaces = baseType.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { AddInterfaces(interfaces[i]); } } } private static string cachedAssemblyName(Assembly assembly) { if (assemblyNameCache.TryGetValue(assembly, out var value)) { return value; } return assemblyNameCache[assembly] = assembly.GetName().Name; } internal static string classKey(Type type, string key) { if (!classKeyCache.TryGetValue(type, out var value)) { value = type.FullName + ((type.Assembly != primaryAssembly) ? ("," + cachedAssemblyName(type.Assembly)) : ""); addTypeToInheritorsCache(type, value); } if (key == "") { return value; } return value + "#" + key; } internal static string dataKey(string key) { return modGuid + "#" + key; } internal <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo(ItemData itemData) { ItemData = itemData; string text = dataKey(""); foreach (string item in ItemData.m_customData.Keys.ToList()) { if (!item.StartsWith(text)) { continue; } string[] array = item.Substring(text.Length).Split(new char[1] { '#' }, 2); if (!knownTypes.Contains(array[0])) { Type type = Type.GetType(array[0]); if ((object)type != null && typeof(ItemData).IsAssignableFrom(type)) { addTypeToInheritorsCache(type, array[0]); } } } } public T GetOrCreate<[<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] T>(string key = "") where T : ItemData, new() { return Add<T>(key) ?? Get<T>(key); } [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] public T Add<[<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] T>(string key = "") where T : ItemData, new() { string text = classKey(typeof(T), key); if (fetchedClassKeys.Contains(text) && data.ContainsKey(text)) { return null; } string text2 = dataKey(text); if (ItemData.m_customData.ContainsKey(text2) || (awakeningItem != ItemData && data.ContainsKey(text))) { return null; } ItemData.m_customData[text2] = ""; ItemDataManager.ItemData.constructingInfo = selfReference ?? (selfReference = new WeakReference<<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo>(this)); T val = new T { info = selfReference, Key = key, CustomDataKey = text2 }; data[text] = val; val.Value = ""; val.FirstLoad(); return val; } [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] public T Get<T>(string key = "") where T : class { if (!typeInheritorsCache.TryGetValue(typeof(T), out var value)) { if (!typeof(ItemData).IsAssignableFrom(typeof(T)) || typeof(T) == typeof(ItemData)) { throw new Exception("Trying to get value from ItemDataManager for class not inheriting from ItemData"); } return null; } foreach (Type item in value) { string text = classKey(item, key); if (data.TryGetValue(text, out var value2)) { return (T)(object)value2; } if (!fetchedClassKeys.Contains(text) && awakeningItem != ItemData) { string text2 = dataKey(text); fetchedClassKeys.Add(text); if (ItemData.m_customData.ContainsKey(text2)) { return (T)(object)constructDataObj(text2, text); } } } return null; } public Dictionary<string, T> GetAll<[<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] T>() where T : ItemData { LoadAll(); return data.Values.Where([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (ItemData o) => o is T).ToDictionary([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (ItemData o) => o.Key, [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (ItemData o) => (T)o); } public bool Remove(string key = "") { return Remove<<eb0313fd-caea-4e6f-b583-2e689a3d665d>StringItemData>(key); } public bool Remove<[<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] T>(string key = "") where T : ItemData { string key2 = classKey(typeof(T), key); string key3 = dataKey(key2); if (ItemData.m_customData.Remove(key3)) { if (data.TryGetValue(key2, out var value)) { value.Unload(); data.Remove(key2); } return true; } return false; } public bool Remove<[<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] T>(T itemData) where T : ItemData { if (typeof(T) == itemData.GetType()) { return Remove<T>(itemData.Key); } return (bool)removeMethod.MakeGenericMethod(itemData.GetType()).Invoke(this, new object[1] { itemData.Key }); } [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] private ItemData constructDataObj(string fullkey, string key) { string[] array = key.Split(new char[1] { '#' }, 2); Type type = Type.GetType(array[0]); if ((object)type == null || !typeof(ItemData).IsAssignableFrom(type)) { return null; } ItemDataManager.ItemData.constructingInfo = selfReference ?? (selfReference = new WeakReference<<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo>(this)); ItemData itemData = (ItemData)Activator.CreateInstance(type); data[key] = itemData; itemData.info = selfReference; itemData.Key = ((array.Length > 1) ? array[1] : ""); itemData.CustomDataKey = fullkey; itemData.Load(); return itemData; } public void Save() { foreach (ItemData value in data.Values) { value.Save(); } } public void LoadAll() { if (awakeningItem == ItemData) { return; } string text = dataKey(""); foreach (string item in ItemData.m_customData.Keys.ToList()) { if (item.StartsWith(text)) { string key = item.Substring(text.Length); if (!data.ContainsKey(key)) { constructDataObj(item, key); } } } } public IEnumerator<ItemData> GetEnumerator() { LoadAll(); return data.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private static void SavePrefix(ItemData __instance) { SaveItem(__instance); } private static void SaveInventoryPrefix(Inventory __instance) { foreach (ItemData item in __instance.m_inventory) { SaveItem(item); } } private static void SaveItem(ItemData item) { if (<35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.itemInfo.TryGetValue(item, out var value)) { value.Save(); } } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(2)] [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1, 1 })] public Dictionary<string, string> IsStackableWithOtherInfo(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo info) { LoadAll(); Dictionary<string, string> dictionary = new Dictionary<string, string>(); if (info != null) { info.LoadAll(); foreach (string item in new HashSet<string>(info.data.Keys.Intersect(data.Keys))) { string text = data[item].TryStack(info.data[item]); if (text == null) { return null; } dictionary[item] = text; } foreach (KeyValuePair<string, ItemData> datum in info.data) { if (!dictionary.ContainsKey(datum.Key)) { string text2 = info.data[datum.Key].TryStack(null); if (text2 == null) { return null; } dictionary[datum.Key] = text2; } } } foreach (KeyValuePair<string, ItemData> datum2 in data) { if (!dictionary.ContainsKey(datum2.Key)) { string text3 = data[datum2.Key].TryStack(null); if (text3 == null) { return null; } dictionary[datum2.Key] = text3; } } return dictionary.ToDictionary([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (KeyValuePair<string, string> kv) => dataKey(kv.Key), [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (KeyValuePair<string, string> kv) => kv.Value); } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(2)] private static void RegisterForceLoadedTypesAddItem(ItemData __result) { awakeningItem = null; if (__result != null) { RegisterForceLoadedTypes(__result); } } private static void RegisterForceLoadedTypes(ItemData itemData) { foreach (Type forceLoadType in ForceLoadTypes) { string key = classKey(forceLoadType, ""); string text = dataKey(key); if (itemData.m_customData.ContainsKey(text)) { <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2 = <35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.Data(itemData); if (!<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2.data.ContainsKey(key)) { <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2.constructDataObj(text, key); } } } } private static void ItemDropAwake(ItemDrop __instance) { GameObject dropPrefab = __instance.m_itemData.m_dropPrefab; if (dropPrefab != null && <35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.itemInfo.TryGetValue(dropPrefab.GetComponent<ItemDrop>().m_itemData, out var value)) { <35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.Data(__instance.m_itemData).isCloned = new HashSet<string>(value.data.Values.Select([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (ItemData i) => i.CustomDataKey)); } } private static void ItemDropAwakeDelayed(ItemDrop __instance) { if (!ZNetView.m_forceDisableInit) { RegisterForceLoadedTypes(__instance.m_itemData); } } private static void ItemDataClonePrefix(ItemData __instance, ItemData __result) { SaveItem(__instance); } private static void ItemDataClonePostfix(ItemData __instance, ItemData __result) { if (<35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.itemInfo.TryGetValue(__instance, out var value)) { <35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.Data(__result).isCloned = new HashSet<string>(value.data.Values.Select([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (ItemData i) => i.CustomDataKey)); } } private static void ItemDataClonePostfixDelayed(ItemData __result) { RegisterForceLoadedTypes(__result); } private static void RegisterForceLoadedTypesOnPlayerLoaded(Player __instance) { foreach (Food food in __instance.m_foods) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(food.m_name); if (itemPrefab.GetComponent<ItemDrop>().m_itemData == food.m_item) { food.m_item = food.m_item.Clone(); food.m_item.m_dropPrefab = itemPrefab; } RegisterForceLoadedTypes(food.m_item); } } private static void SaveCheckingForStackableItemData(ItemData item) { if (item == awakeningItem) { awakeningItem = null; } checkingForStackableItemData = item; } private static void ResetCheckingForStackableItemData() { checkingForStackableItemData = null; } private static IEnumerable<CodeInstruction> CheckStackableInFindFreeStackMethods(IEnumerable<CodeInstruction> instructionsEnumerable) { CodeInstruction[] instructions = instructionsEnumerable.ToArray(); Label target = (Label)instructions.First([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (CodeInstruction val) => val.opcode == OpCodes.Br || val.opcode == OpCodes.Br_S).operand; CodeInstruction targetedInstr = instructions.First([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (CodeInstruction val) => val.labels.Contains(target)); Label? label = default(Label?); CodeInstruction lastBranch = instructions.Reverse().First([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (CodeInstruction val) => CodeInstructionExtensions.Branches(val, ref label) && targetedInstr.labels.Contains(label.Value)); CodeInstruction loadingInstruction = null; int i = 0; while (i < instructions.Length) { yield return instructions[i]; if (loadingInstruction == null && instructions[i].opcode == OpCodes.Call && ((MethodInfo)instructions[i].operand).Name == "get_Current") { loadingInstruction = instructions[i + 1].Clone(); loadingInstruction.opcode = new Dictionary<OpCode, OpCode> { { OpCodes.Stloc_0, OpCodes.Ldloc_0 }, { OpCodes.Stloc_1, OpCodes.Ldloc_1 }, { OpCodes.Stloc_2, OpCodes.Ldloc_2 }, { OpCodes.Stloc_3, OpCodes.Ldloc_3 }, { OpCodes.Stloc_S, OpCodes.Ldloc_S } }[loadingInstruction.opcode]; } if (instructions[i] == lastBranch) { yield return loadingInstruction; yield return new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.DeclaredField(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "checkingForStackableItemData")); yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "CheckItemDataIsStackableFindFree", (Type[])null, (Type[])null)); yield return new CodeInstruction(OpCodes.Brfalse, (object)target); } int num = i + 1; i = num; } } private static bool CheckItemDataIsStackableFindFree(ItemData item, [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] ItemData target) { if (target == null) { return true; } Dictionary<string, string> dictionary = IsStackable(item, target); if (dictionary != null) { newValuesOnStackable = dictionary; return true; } return false; } private static void ResetNewValuesOnStackable() { newValuesOnStackable = null; } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(2)] private static void ApplyNewValuesOnStackable(ItemData __result) { if (__result == null || newValuesOnStackable == null) { return; } foreach (KeyValuePair<string, string> item in newValuesOnStackable) { __result.m_customData[item.Key] = item.Value; } } [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1, 1 })] private static Dictionary<string, string> IsStackable(ItemData a, ItemData b) { <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2 = <35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.Data(a); if (<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2 != null) { return <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2.IsStackableWithOtherInfo(<35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.Data(b)); } <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo3 = <35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.Data(b); if (<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo3 != null) { return <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo3.IsStackableWithOtherInfo(null); } return new Dictionary<string, string>(); } private static bool CheckItemDataStackableAddItem(Inventory __instance, ItemData item, int x, int y, [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary<string, string> __state, ref bool __result) { ItemData itemAt = __instance.GetItemAt(x, y); if (itemAt != null) { Dictionary<string, string> dictionary = IsStackable(item, itemAt); if (dictionary == null) { __result = false; return false; } __state = dictionary; } return true; } private static void ApplyCustomItemDataStackableAddItem(Inventory __instance, int x, int y, [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1, 1 })] Dictionary<string, string> __state, bool __result) { if (!__result || __state == null) { return; } foreach (KeyValuePair<string, string> item in __state) { __instance.GetItemAt(x, y).m_customData[item.Key] = item.Value; } } private static void ApplyCustomItemDataStackableAutoStack(ItemDrop item, Dictionary<string, string> customData) { item.m_itemData.m_customData = customData; } [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1, 1 })] private static Dictionary<string, string> IsStackableItemDrop(ItemDrop drop, ItemData item) { return IsStackable(drop.m_itemData, item); } private static IEnumerable<CodeInstruction> HandleAutostackableItems(IEnumerable<CodeInstruction> instructionList, ILGenerator ilg) { //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Expected O, but got Unknown //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Expected O, but got Unknown //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Expected O, but got Unknown //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Expected O, but got Unknown //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Expected O, but got Unknown //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Expected O, but got Unknown //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Expected O, but got Unknown //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Expected O, but got Unknown //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Expected O, but got Unknown //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Expected O, but got Unknown //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Expected O, but got Unknown List<CodeInstruction> list = instructionList.ToList(); FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ItemData), "m_stack"); FieldInfo fieldInfo2 = AccessTools.DeclaredField(typeof(ItemDrop), "m_itemData"); Label? label = default(Label?); for (int i = 0; i < list.Count; i++) { if (!CodeInstructionExtensions.StoresField(list[i], fieldInfo)) { continue; } for (int num = i; num > 0; num--) { if (CodeInstructionExtensions.Branches(list[num], ref label)) { for (int num2 = num; num2 > 0; num2--) { if (CodeInstructionExtensions.LoadsField(list[num2], fieldInfo2, false)) { LocalBuilder localBuilder = ilg.DeclareLocal(typeof(Dictionary<string, string>)); LocalBuilder localBuilder2 = ilg.DeclareLocal(typeof(ItemData)); list.Insert(i + 1, new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ApplyCustomItemDataStackableAutoStack", (Type[])null, (Type[])null))); list.Insert(i + 1, new CodeInstruction(OpCodes.Ldloc, (object)localBuilder.LocalIndex)); list.Insert(i + 1, new CodeInstruction(OpCodes.Ldarg_0, (object)null)); list.Insert(num + 1, new CodeInstruction(OpCodes.Brfalse, (object)label)); list.Insert(num + 1, new CodeInstruction(OpCodes.Stloc, (object)localBuilder.LocalIndex)); list.Insert(num + 1, new CodeInstruction(OpCodes.Dup, (object)localBuilder.LocalIndex)); list.Insert(num + 1, new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "IsStackableItemDrop", (Type[])null, (Type[])null))); list.Insert(num + 1, new CodeInstruction(OpCodes.Ldloc, (object)localBuilder2.LocalIndex)); list.Insert(num + 1, new CodeInstruction(OpCodes.Ldarg_0, (object)null)); list.Insert(num2 + 1, new CodeInstruction(OpCodes.Stloc, (object)localBuilder2.LocalIndex)); list.Insert(num2 + 1, new CodeInstruction(OpCodes.Dup, (object)null)); return list; } } } } } throw new Exception("Found no stack store in a branch"); } private static IEnumerable<CodeInstruction> TransferCustomItemDataOnUpgrade(IEnumerable<CodeInstruction> instructions, ILGenerator ilg) { MethodInfo itemDeleter = AccessTools.DeclaredMethod(typeof(Inventory), "RemoveItem", new Type[1] { typeof(ItemData) }, (Type[])null); foreach (CodeInstruction instruction in instructions) { if (instruction.opcode == OpCodes.Callvirt && CodeInstructionExtensions.OperandIs(instruction, (MemberInfo)itemDeleter)) { yield return new CodeInstruction(OpCodes.Dup, (object)null); yield return new CodeInstruction(OpCodes.Stsfld, (object)AccessTools.DeclaredField(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "currentlyUpgradingItem")); } yield return instruction; } } private static void ResetCurrentlyUpgradingItem() { currentlyUpgradingItem = null; } private static void CopyCustomDataFromUpgradedItem(ItemDrop item) { if (currentlyUpgradingItem != null) { item.m_itemData.m_customData = currentlyUpgradingItem.m_customData; <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2 = <35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.Data(currentlyUpgradingItem); <35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.itemInfo.Remove(currentlyUpgradingItem); <35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions.itemInfo.Add(item.m_itemData, <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2); item.m_itemData.m_quality = currentlyUpgradingItem.m_quality + 1; item.m_itemData.m_variant = currentlyUpgradingItem.m_variant; <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2.ItemData = item.m_itemData; <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2.LoadAll(); foreach (ItemData value in <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo2.data.Values) { value.Upgraded(); } currentlyUpgradingItem = null; awakeningItem = null; return; } GameObject dropPrefab = item.m_itemData.m_dropPrefab; if (dropPrefab == null || item.m_itemData.m_customData.Count != 0) { return; } ZNetView component = ((Component)item).GetComponent<ZNetView>(); ZDO val = ((Object.op_Implicit((Object)(object)component) && component.IsValid()) ? component.GetZDO() : null); if (val != null && val.GetInt(ZDOVars.s_dataCount, -1) != -1) { return; } item.m_itemData.m_customData = new Dictionary<string, string>(dropPrefab.GetComponent<ItemDrop>().m_itemData.m_customData); if (val == null) { return; } int num = 0; val.Set(ZDOVars.s_dataCount, item.m_itemData.m_customData.Count, false); foreach (KeyValuePair<string, string> customDatum in item.m_itemData.m_customData) { val.Set($"data_{num}", customDatum.Key); val.Set($"data__{num++}", customDatum.Value); } } private static IEnumerable<CodeInstruction> ImportCustomDataOnUpgrade(IEnumerable<CodeInstruction> instructionList) { List<CodeInstruction> list = instructionList.ToList(); foreach (CodeInstruction instruction in list) { yield return instruction; if (instruction.opcode == OpCodes.Stfld && CodeInstructionExtensions.OperandIs(instruction, (MemberInfo)AccessTools.DeclaredField(typeof(ItemData), "m_dropPrefab"))) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "CopyCustomDataFromUpgradedItem", (Type[])null, (Type[])null)); } } } private static void TrackAwakeningItem(ItemDrop __instance) { if (ZNetView.m_forceDisableInit) { awakeningItem = __instance.m_itemData; } } static <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo() { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Expected O, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Expected O, but got Unknown //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Expected O, but got Unknown //IL_01dd: Expected O, but got Unknown //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Expected O, but got Unknown //IL_024c: Expected O, but got Unknown //IL_028c: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Expected O, but got Unknown //IL_02ae: Expected O, but got Unknown //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_0312: Unknown result type (might be due to invalid IL or missing references) //IL_031d: Expected O, but got Unknown //IL_031d: Expected O, but got Unknown //IL_034d: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Expected O, but got Unknown //IL_0387: Unknown result type (might be due to invalid IL or missing references) //IL_038e: Expected O, but got Unknown //IL_03a4: Unknown result type (might be due to invalid IL or missing references) //IL_03bf: Unknown result type (might be due to invalid IL or missing references) //IL_03cd: Expected O, but got Unknown //IL_03cd: Expected O, but got Unknown //IL_03fd: Unknown result type (might be due to invalid IL or missing references) //IL_0409: Expected O, but got Unknown //IL_0439: Unknown result type (might be due to invalid IL or missing references) //IL_0454: Unknown result type (might be due to invalid IL or missing references) //IL_045f: Expected O, but got Unknown //IL_045f: Expected O, but got Unknown //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_04bd: Expected O, but got Unknown //IL_0510: Unknown result type (might be due to invalid IL or missing references) //IL_051d: Expected O, but got Unknown //IL_05c9: Unknown result type (might be due to invalid IL or missing references) //IL_05d6: Expected O, but got Unknown //IL_0604: Unknown result type (might be due to invalid IL or missing references) //IL_062f: Unknown result type (might be due to invalid IL or missing references) //IL_0636: Expected O, but got Unknown //IL_065c: Unknown result type (might be due to invalid IL or missing references) //IL_066a: Expected O, but got Unknown //IL_066a: Expected O, but got Unknown //IL_06a9: Unknown result type (might be due to invalid IL or missing references) //IL_06b6: Expected O, but got Unknown //IL_06e4: Unknown result type (might be due to invalid IL or missing references) //IL_070f: Unknown result type (might be due to invalid IL or missing references) //IL_071c: Expected O, but got Unknown //IL_071c: Expected O, but got Unknown //IL_075b: Unknown result type (might be due to invalid IL or missing references) //IL_0768: Expected O, but got Unknown ForceLoadTypes = new HashSet<Type>(); typeInheritorsCache = new Dictionary<Type, HashSet<Type>>(); knownTypes = new HashSet<string>(); awakeningItem = null; primaryAssembly = Assembly.GetExecutingAssembly(); assemblyNameCache = new Dictionary<Assembly, string>(); classKeyCache = new Dictionary<Type, string>(); removeMethod = typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo).GetMethods().Single([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (MethodInfo m) => m.Name == "Remove" && m.IsGenericMethod && m.GetParameters()[0].ParameterType == typeof(string)); Harmony val = new Harmony("org.bepinex.helpers.ItemDataManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Inventory), "Save", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "SaveInventoryPrefix", (Type[])null, (Type[])null), 800, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); foreach (MethodInfo item in from m in typeof(ItemData).GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where m.Name == "SaveToZDO" select m) { val.Patch((MethodBase)item, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "SavePrefix", (Type[])null, (Type[])null), 800, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Inventory), "AddItem", new Type[5] { typeof(ItemData), typeof(int), typeof(int), typeof(int), typeof(bool) }, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "CheckItemDataStackableAddItem", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ApplyCustomItemDataStackableAddItem", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Inventory), "CanAddItem", new Type[2] { typeof(ItemData), typeof(int) }, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "SaveCheckingForStackableItemData", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ResetCheckingForStackableItemData", (Type[])null), (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Inventory), "AddItem", new Type[1] { typeof(ItemData) }, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "SaveCheckingForStackableItemData", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ResetCheckingForStackableItemData", (Type[])null), (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Inventory), "AddItem", new Type[2] { typeof(ItemData), typeof(Vector2i) }, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "SaveCheckingForStackableItemData", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ResetCheckingForStackableItemData", (Type[])null), (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Inventory), "FindFreeStackSpace", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "CheckStackableInFindFreeStackMethods", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null); MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Inventory), "FindFreeStackItem", (Type[])null, (Type[])null); HarmonyMethod val2 = new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "CheckStackableInFindFreeStackMethods", (Type[])null, (Type[])null)); val.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ResetNewValuesOnStackable", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ApplyNewValuesOnStackable", (Type[])null, (Type[])null)), val2, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ItemDrop), "AutoStackItems", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "HandleAutostackableItems", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(InventoryGui), "DoCrafting", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "TransferCustomItemDataOnUpgrade", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ResetCurrentlyUpgradingItem", (Type[])null, (Type[])null)), (HarmonyMethod)null); foreach (MethodInfo item2 in from m in typeof(ItemData).GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where m.Name == "LoadFromZDO" select m) { val.Patch((MethodBase)item2, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "RegisterForceLoadedTypes", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Player), "Load", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "RegisterForceLoadedTypesOnPlayerLoaded", (Type[])null, (Type[])null), 700, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Inventory), "AddItem", new Type[8] { typeof(string), typeof(int), typeof(int), typeof(int), typeof(long), typeof(string), typeof(Vector2i), typeof(bool) }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "RegisterForceLoadedTypesAddItem", (Type[])null, (Type[])null), 800, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(ItemDrop), "Awake", (Type[])null, (Type[])null); HarmonyMethod val3 = new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "TrackAwakeningItem", (Type[])null, (Type[])null)); val2 = new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ImportCustomDataOnUpgrade", (Type[])null, (Type[])null), 800, (string[])null, (string[])null, (bool?)null); val.Patch((MethodBase)methodInfo2, val3, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ItemDropAwake", (Type[])null, (Type[])null), 800, (string[])null, (string[])null, (bool?)null), val2, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ItemDrop), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ItemDropAwakeDelayed", (Type[])null, (Type[])null), 799, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ItemData), "Clone", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ItemDataClonePrefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ItemDataClonePostfix", (Type[])null, (Type[])null), 500, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ItemData), "Clone", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(<27135a16-41db-418a-afd2-7267dbe18137>ItemInfo), "ItemDataClonePostfixDelayed", (Type[])null, (Type[])null), 499, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(1)] [PublicAPI] public class <3679b648-5ca3-43b3-a105-7e87d198b67d>ForeignItemInfo : IEnumerable<object>, IEnumerable { private readonly object foreignItemInfo; public string Mod => ((string)foreignItemInfo.GetType().GetProperty("Mod")?.GetValue(foreignItemInfo)) ?? ""; public ItemData ItemData { get; private set; } [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] public string this[string key] { [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] get { object obj = foreignItemInfo.GetType().InvokeMember("Item", BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty, null, foreignItemInfo, new object[1] { key }); if (obj != null) { return (string)obj.GetType().GetProperty("Value")?.GetValue(obj); } return null; } [param: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] set { foreignItemInfo.GetType().GetMethod("set_Item", BindingFlags.Instance | BindingFlags.Public)?.Invoke(foreignItemInfo, new object[2] { key, value }); } } internal <3679b648-5ca3-43b3-a105-7e87d198b67d>ForeignItemInfo(ItemData itemData, object foreignItemInfo) { ItemData = itemData; this.foreignItemInfo = foreignItemInfo; } public T GetOrCreate<T>(string key = "") where T : class, new() { return Add<T>(key) ?? Get<T>(key); } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(2)] private object call([<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(1)] string name, [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 1, 2 })] object[] values, [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 1, 2 })] Type[] args, Type generic = null) { MethodInfo[] methods = foreignItemInfo.GetType().GetMethods(); foreach (MethodInfo methodInfo in methods) { if (methodInfo.Name == name && (from p in methodInfo.GetParameters() select (!p.ParameterType.IsGenericParameter) ? p.ParameterType : null).SequenceEqual(args) && (object)generic != null == methodInfo.IsGenericMethod) { MethodInfo methodInfo2 = methodInfo; if ((object)generic != null) { methodInfo2 = methodInfo2.MakeGenericMethod(generic); } return methodInfo2.Invoke(foreignItemInfo, values); } } return null; } [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] public T Add<T>(string key = "") where T : class, new() { return call("Add", new object[1] { key }, new Type[1] { typeof(string) }, typeof(T)) as T; } [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] public T Get<T>(string key = "") where T : class { return call("Get", new object[1] { key }, new Type[1] { typeof(string) }, typeof(T)) as T; } public Dictionary<string, T> GetAll<T>() where T : class { return ((call("GetAll", Array.Empty<object>(), Array.Empty<Type>(), typeof(T)) as T) as Dictionary<string, T>) ?? new Dictionary<string, T>(); } public bool Remove(string key = "") { return call("Add", new object[1] { key }, new Type[1] { typeof(string) }) as bool? == true; } public bool Remove<T>(string key = "") where T : class { return call("Remove", new object[1] { key }, new Type[1] { typeof(string) }, typeof(T)) as bool? == true; } public bool Remove<T>(T itemData) where T : class { return call("Remove", new object[1] { itemData }, new Type[1], typeof(T)) as bool? == true; } public void Save() { call("Save", Array.Empty<object>(), Array.Empty<Type>()); } public void LoadAll() { call("LoadAll", Array.Empty<object>(), Array.Empty<Type>()); } public IEnumerator<object> GetEnumerator() { return (IEnumerator<object>)((call("GetEnumerator", Array.Empty<object>(), Array.Empty<Type>()) as IEnumerator<object>) ?? ((object)new List<object>().GetEnumerator())); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [PublicAPI] [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(1)] public static class <35e5ab3c-7099-45c6-ac00-b53ba5a87838>ItemExtensions { private const string className = "ItemDataManager.ItemExtensions"; internal static readonly ConditionalWeakTable<ItemData, <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo> itemInfo = new ConditionalWeakTable<ItemData, <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo>(); [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 1, 1, 1, 1, 2 })] private static readonly ConditionalWeakTable<ItemData, Dictionary<string, <3679b648-5ca3-43b3-a105-7e87d198b67d>ForeignItemInfo>> foreignItemInfo = new ConditionalWeakTable<ItemData, Dictionary<string, <3679b648-5ca3-43b3-a105-7e87d198b67d>ForeignItemInfo>>(); public static <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo Data(this ItemData item) { if (itemInfo.TryGetValue(item, out var value)) { return value; } itemInfo.Add(item, value = new <27135a16-41db-418a-afd2-7267dbe18137>ItemInfo(item)); return value; } [return: <31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] public static <3679b648-5ca3-43b3-a105-7e87d198b67d>ForeignItemInfo Data(this ItemData item, string mod) { Dictionary<string, <3679b648-5ca3-43b3-a105-7e87d198b67d>ForeignItemInfo> orCreateValue = foreignItemInfo.GetOrCreateValue(item); if (orCreateValue.TryGetValue(mod, out var value)) { return value; } if (!Chainloader.PluginInfos.TryGetValue(mod, out var value2)) { return null; } object obj = ((object)value2.Instance).GetType().Assembly.GetType("ItemDataManager.ItemExtensions")?.GetMethod("Data", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(ItemData) }, Array.Empty<ParameterModifier>())?.Invoke(null, new object[1] { item }); if (obj != null) { return orCreateValue[mod] = new <3679b648-5ca3-43b3-a105-7e87d198b67d>ForeignItemInfo(item, obj); } Debug.LogWarning((object)("Mod " + mod + " has an ItemDataManager.ItemExtensions class, but no Data(ItemDrop.ItemData) method could be called on it.")); return orCreateValue[mod] = null; } } } namespace AzuAutoStore { [HarmonyPatch(typeof(Terminal), "InitTerminal")] [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(1)] [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] internal static class TerminalInitTerminalPatch { [Serializable] [CompilerGenerated] private sealed class <>c { [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] public static readonly <>c <>9 = new <>c(); [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] public static Func<Piece, bool> <>9__2_8; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] public static Func<Piece, VanillaContainers> <>9__2_10; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] public static Func<ItemData, int> <>9__2_12; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] public static ConsoleEvent <>9__2_0; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] public static ConsoleOptionsFetcher <>9__2_1; [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] internal void <Postfix>b__2_0(ConsoleEventArgs args) { <>c__DisplayClass2_0 <>c__DisplayClass2_ = new <>c__DisplayClass2_0(); if (args.Length > 1 && Object.op_Implicit((Object)(object)ZNetScene.instance)) { <>c__DisplayClass2_.itemCount = 0; bool flag = <>c__DisplayClass2_.<Postfix>g__SearchNearbyContainersFor|2(args[1]); ((Character)Player.m_localPlayer).Message((MessageType)2, flag ? $"Found {<>c__DisplayClass2_.itemCount} items matching '{args[1]}' in nearby containers." : ("<color=red>No items matching '" + args[1] + "' found in nearby containers.</color>"), 0, (Sprite)null, false); } } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] internal bool <Postfix>b__2_8(Piece p) { return Object.op_Implicit((Object)(object)((Component)p).GetComponent<Container>()); } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] internal VanillaContainers <Postfix>b__2_10(Piece p) { return VanillaContainers.Create(((Component)p).GetComponent<Container>()); } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] internal int <Postfix>b__2_12(ItemData item) { return item.m_stack; } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] internal List<string> <Postfix>b__2_1() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return ZNetScene.instance.GetPrefabNames(); } return new List<string>(); } } [CompilerGenerated] private sealed class <>c__DisplayClass2_0 { public int itemCount; } private const float SearchRadius = 50f; public static void GetAllPiecesInRadius(Vector3 p, float radius, List<Piece> pieces) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (Piece.s_ghostLayer == 0) { Piece.s_ghostLayer = LayerMask.NameToLayer("ghost"); } foreach (Piece s_allPiece in Piece.s_allPieces) { if (((Component)s_allPiece).gameObject.layer != Piece.s_ghostLayer && (double)Vector3.Distance(p, ((Component)s_allPiece).transform.position) < (double)radius) { pieces.Add(s_allPiece); } } } private static void Postfix(Terminal __instance) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_0051: 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_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown object obj = <>c.<>9__2_0; if (obj == null) { ConsoleEvent val = [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (ConsoleEventArgs args) => { int itemCount; if (args.Length > 1 && Object.op_Implicit((Object)(object)ZNetScene.instance)) { itemCount = 0; bool flag = SearchNearbyContainersFor(args[1]); ((Character)Player.m_localPlayer).Message((MessageType)2, flag ? $"Found {itemCount} items matching '{args[1]}' in nearby containers." : ("<color=red>No items matching '" + args[1] + "' found in nearby containers.</color>"), 0, (Sprite)null, false); } IEnumerable<AzuAutoStore.Interfaces.IContainer> GetNearbyMatchingPieces(string query) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) List<Piece> list = new List<Piece>(); GetAllPiecesInRadius(((Component)Player.m_localPlayer).transform.position, 50f, list); IEnumerable<AzuAutoStore.Interfaces.IContainer> second = ItemDrawers_API.AllDrawers.Where([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (ItemDrawers_API.Drawer x) => string.Equals(x.Prefab, query, StringComparison.CurrentCultureIgnoreCase)).Select(kgDrawer.Create); IEnumerable<AzuAutoStore.Interfaces.IContainer> second2 = MkzItemDrawers_API.AllDrawers.Where([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (MkzItemDrawers_API.Drawer x) => string.Equals(x.Prefab, query, StringComparison.CurrentCultureIgnoreCase)).Select(mkzDrawer.Create); return (from p in list where Object.op_Implicit((Object)(object)((Component)p).GetComponent<Container>()) where ContainerContainsMatchingItem((Component)(object)p, query.ToLower(), ref itemCount) select VanillaContainers.Create(((Component)p).GetComponent<Container>())).Concat(second).Concat(second2); } bool SearchNearbyContainersFor(string query) { //IL_003b: 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) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: 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_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) bool result = false; AzuAutoStore.Interfaces.IContainer container = null; float num = float.MaxValue; foreach (AzuAutoStore.Interfaces.IContainer item in GetNearbyMatchingPieces(query)) { Functions.PingContainer(item.gameObject); result = true; float num2 = Vector3.Distance(item.gameObject.transform.position, ((Component)Player.m_localPlayer).transform.position); if (num2 < num) { num = num2; container = item; } } if (container != null) { Vector3 position = container.gameObject.transform.position; ((Character)Player.m_localPlayer).SetLookDir(position - ((Component)Player.m_localPlayer).transform.position, 3.5f); } return result; } }; <>c.<>9__2_0 = val; obj = (object)val; } object obj2 = <>c.<>9__2_1; if (obj2 == null) { ConsoleOptionsFetcher val2 = [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] () => Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefabNames() : new List<string>(); <>c.<>9__2_1 = val2; obj2 = (object)val2; } new ConsoleCommand("azuautostoresearch", "[prefab name/query text] - search for items in chests near the player. It uses the prefab name", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)obj2, false, false, false); static bool ContainerContainsMatchingItem(Component container, string query, ref int count) { IEnumerable<ItemData> source = (from i in container.GetComponent<Container>().GetInventory().GetAllItems() where NormalizedItemName(i).Contains(query) || i.m_shared.m_name.ToLower().Contains(query) select i).ToList(); count += source.Sum([<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (ItemData item) => item.m_stack); return source.Any(); } static string NormalizedItemName(ItemData itemData) { return Utils.GetPrefabName(itemData.m_dropPrefab).ToLower(); } } } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(1)] [BepInDependency(/*Could not decode attribute arguments.*/)] [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("Azumatt.AzuAutoStore", "AzuAutoStore", "3.1.7")] public class AzuAutoStorePlugin : BaseUnityPlugin { [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] public enum Toggle { Off, On } [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(1)] [UsedImplicitly] public string Category; [UsedImplicitly] [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1 })] public Action<ConfigEntryBase> CustomDrawer; } [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(0)] private class AcceptableShortcuts : AcceptableValueBase { public AcceptableShortcuts() : base(typeof(KeyboardShortcut)) { } public override object Clamp(object value) { return value; } public override bool IsValid(object value) { return true; } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", UnityInput.Current.SupportedKeyCodes); } } internal const string ModName = "AzuAutoStore"; internal const string ModVersion = "3.1.7"; internal const string Author = "Azumatt"; internal const string ModGUID = "Azumatt.AzuAutoStore"; internal const string KgGuid = "kg.ItemDrawers"; internal const string BackpacksGuid = "org.bepinex.plugins.backpacks"; private const string ConfigFileName = "Azumatt.AzuAutoStore.cfg"; private static readonly string ConfigFileFullPath; internal static string ConnectionError; private readonly Harmony _harmony = new Harmony("Azumatt.AzuAutoStore"); public static readonly ManualLogSource AzuAutoStoreLogger; private static readonly ConfigSync ConfigSync; internal static bool BackpacksIsLoaded; internal static readonly string yamlFileName; internal static readonly string yamlPath; internal static readonly CustomSyncedValue<string> AzuAutoStoreContainerData; internal static readonly CustomSyncedValue<string> CraftyContainerGroupsData; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 2, 1, 1 })] internal static Dictionary<string, object> yamlData; [<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(new byte[] { 1, 2, 1, 2 })] internal static Dictionary<string, HashSet<string>> groups; internal static AzuAutoStorePlugin self; private static ConfigEntry<Toggle> _serverConfigLocked; internal static ConfigEntry<Toggle> DontStoreToBackpacks; internal static ConfigEntry<Toggle> ChestsPickupFromGround; internal static ConfigEntry<Toggle> MustHaveExistingItemToPull; internal static ConfigEntry<KeyboardShortcut> SingleItemShortcut; private static ConfigEntry<KeyboardShortcut> _storeShortcut; private static ConfigEntry<KeyboardShortcut> _pauseShortcut; internal static ConfigEntry<int> SecondsToWaitBeforeStoring; internal static ConfigEntry<float> IntervalSeconds; internal static ConfigEntry<Toggle> FishSuction; internal static ConfigEntry<float> PlayerRange; internal static ConfigEntry<float> FallbackRange; internal static ConfigEntry<Toggle> PlayerIgnoreHotbar; internal static ConfigEntry<Toggle> PlayerIgnoreQuickSlots; internal static ConfigEntry<string> PingVfxString; internal static ConfigEntry<Toggle> HighlightContainers; internal static ConfigEntry<Toggle> PingContainers; public static ConfigEntry<Color> BorderColorFavoritedItem; public static ConfigEntry<Color> BorderColorFavoritedItemOnFavoritedSlot; public static ConfigEntry<Color> BorderColorFavoritedSlot; public static ConfigEntry<bool> DisplayTooltipHint; public static ConfigEntry<KeyboardShortcut> FavoritingModifierKeybind1; public static ConfigEntry<KeyboardShortcut> FavoritingModifierKeybind2; public static ConfigEntry<KeyboardShortcut> SearchModifierKeybind; public static ConfigEntry<string> FavoritedItemTooltip; public static ConfigEntry<string> FavoritedSlotTooltip; public static ConfigEntry<string> ItemOnFavoritedSlotTooltip; public void Awake() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Expected O, but got Unknown //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Expected O, but got Unknown //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Expected O, but got Unknown //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Expected O, but got Unknown //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0209: 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_027a: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Expected O, but got Unknown //IL_02b6: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Expected O, but got Unknown //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Expected O, but got Unknown //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_031b: Expected O, but got Unknown //IL_0337: Unknown result type (might be due to invalid IL or missing references) //IL_0342: Expected O, but got Unknown //IL_035c: Unknown result type (might be due to invalid IL or missing references) //IL_0385: Unknown result type (might be due to invalid IL or missing references) //IL_0390: Expected O, but got Unknown //IL_03a7: Unknown result type (might be due to invalid IL or missing references) //IL_03d0: Unknown result type (might be due to invalid IL or missing references) //IL_03db: Expected O, but got Unknown //IL_03fb: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_041a: Expected O, but got Unknown //IL_0431: Unknown result type (might be due to invalid IL or missing references) //IL_0445: Unknown result type (might be due to invalid IL or missing references) //IL_0450: Expected O, but got Unknown //IL_0477: Unknown result type (might be due to invalid IL or missing references) //IL_04cb: Unknown result type (might be due to invalid IL or missing references) //IL_04f6: Unknown result type (might be due to invalid IL or missing references) //IL_0531: Unknown result type (might be due to invalid IL or missing references) //IL_055a: Unknown result type (might be due to invalid IL or missing references) self = this; _serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, new ConfigDescription("If on, the configuration is locked and can be changed by server admins only.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 10 } })); ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); DontStoreToBackpacks = config("1 - General", "Dont Store to Backpacks", Toggle.Off, new ConfigDescription("If on, items will not be stored in backpacks or quivers.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 9 } })); ChestsPickupFromGround = config("1 - General", "Chests Pickup From Ground", Toggle.On, new ConfigDescription("If on, chests will pick up items from the ground if they are in range. If off, chests will not begin their periodic checks for items nearby. Reloading zone or logging out might be required.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 8 } })); MustHaveExistingItemToPull = config("1 - General", "Must Have Existing Item To Pull", Toggle.On, new ConfigDescription("If on, the chest must already have the item in its inventory to pull it from the world or player into the chest.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 7 } })); PlayerRange = config("1 - General", "Player Range", 5f, new ConfigDescription("The maximum distance from the player to store items in chests when the Store Shortcut is pressed. Follows storage rules for allowed items.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), new object[1] { new ConfigurationManagerAttributes { Order = 6 } })); FallbackRange = config("1 - General", "Fallback Range", 10f, new ConfigDescription("The range to use if the container has no range set in the yml file. This will be the fallback range for all containers.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 5 } })); PlayerIgnoreHotbar = config("1 - General", "Player Ignore Hotbar", Toggle.On, new ConfigDescription("If on, the player's hotbar will not be stored when the Store Shortcut is pressed.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 4 } }), synchronizedSetting: false); PlayerIgnoreQuickSlots = config("1 - General", "Player Ignore Quick Slots", Toggle.Off, new ConfigDescription("If on, the player's quick slots will not be stored when the Store Shortcut is pressed. (Requires Quick Slots mod, turn on only if you need it!)", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 3 } }), synchronizedSetting: false); PingVfxString = TextEntryConfig("1 - General", "Ping VFX", "vfx_Potion_health_medium", new ConfigDescription("The VFX to play when a chest is pinged. Leave blank to disable and only highlight the chest. (Full prefab list: https://valheim-modding.github.io/Jotunn/data/prefabs/prefab-list.html)", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 2 } })); HighlightContainers = config("1 - General", "Highlight Containers", Toggle.On, new ConfigDescription("If on, the containers will be highlighted when something is stored in them. If off, the containers will not be highlighted if something is stored in them.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 1 } }), synchronizedSetting: false); PingContainers = config("1 - General", "Ping Containers", Toggle.On, new ConfigDescription("If on, the containers will be pinged with the Ping VFX when something is stored in them. If off, the containers will not be pinged if something is stored in them.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 0 } }), synchronizedSetting: false); SecondsToWaitBeforeStoring = config("1 - General", "Seconds To Wait Before Storing", 10, new ConfigDescription("The number of seconds to wait before storing items into chests nearby automatically after you have pressed your hotkey to pause.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 60), Array.Empty<object>())); IntervalSeconds = config("1 - General", "IntervalSeconds", 10f, new ConfigDescription("The number of seconds that must pass before the chest will do an automatic check for items nearby, WARNING: Reducing this will decrease performance!", (AcceptableValueBase)null, Array.Empty<object>())); FishSuction = config("1.5 - Fish", "Fish Suction", Toggle.Off, new ConfigDescription("Allow auto-storing fish that are still in water (boat 'netting'). Off = require fish to be out of the water; On = ignore IsOutOfWater() check.", (AcceptableValueBase)null, Array.Empty<object>())); SingleItemShortcut = config<KeyboardShortcut>("2 - Shortcuts", "Store Single Item Shortcut", new KeyboardShortcut((KeyCode)325, Array.Empty<KeyCode>()), new ConfigDescription("Keyboard shortcut/Hotkey to store a single item that you click from your inventory into nearby containers.", (AcceptableValueBase)(object)new AcceptableShortcuts(), new object[1] { new ConfigurationManagerAttributes { Order = 2 } }), synchronizedSetting: false); _storeShortcut = config<KeyboardShortcut>("2 - Shortcuts", "Store Shortcut", new KeyboardShortcut((KeyCode)46, Array.Empty<KeyCode>()), new ConfigDescription("Keyboard shortcut/Hotkey to store your inventory into nearby containers.", (AcceptableValueBase)(object)new AcceptableShortcuts(), new object[1] { new ConfigurationManagerAttributes { Order = 1 } }), synchronizedSetting: false); _pauseShortcut = config<KeyboardShortcut>("2 - Shortcuts", "Pause Shortcut", new KeyboardShortcut((KeyCode)46, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), new ConfigDescription("Keyboard shortcut/Hotkey to temporarily stop storing items into chests nearby automatically. Does not override the player hotkey store.", (AcceptableValueBase)(object)new AcceptableShortcuts(), Array.Empty<object>()), synchronizedSetting: false); SearchModifierKeybind = config<KeyboardShortcut>("2 - Shortcuts", "SearchModifierKeybind", new KeyboardShortcut((KeyCode)121, Array.Empty<KeyCode>()), new ConfigDescription("While holding this, you can search nearby chests for the prefab you clicked in your inventory.", (AcceptableValueBase)(object)new AcceptableShortcuts(), Array.Empty<object>()), synchronizedSetting: false); string text = "3 - Favoriting"; string text2 = "While holding this, left clicking on items or right clicking on slots favorites them, disallowing storing"; BorderColorFavoritedItem = config<Color>(text, "BorderColorFavoritedItem", new Color(1f, 0.8482759f, 0f), "Color of the border for slots containing favorited items.", synchronizedSetting: false); BorderColorFavoritedItem.SettingChanged += [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(0)] (object a, EventArgs b) => { FavoritingMode.RefreshDisplay(); }; BorderColorFavoritedItemOnFavoritedSlot = config<Color>(text, "BorderColorFavoritedItemOnFavoritedSlot", new Color(0.5f, 0.67413795f, 0.5f), "Color of the border of a favorited slot that also contains a favorited item.", synchronizedSetting: false); BorderColorFavoritedSlot = config<Color>(text, "BorderColorFavoritedSlot", new Color(0f, 0.5f, 1f), "Color of the border for favorited slots.", synchronizedSetting: false); DisplayTooltipHint = config(text, "DisplayTooltipHint", value: true, "Whether to add additional info the item tooltip of a favorited or trash flagged item.", synchronizedSetting: false); FavoritingModifierKeybind1 = config<KeyboardShortcut>(text, "FavoritingModifierKeybind1", new KeyboardShortcut((KeyCode)122, Array.Empty<KeyCode>()), text2 + " Identical to FavoritingModifierKeybind2.", synchronizedSetting: false); FavoritingModifierKeybind2 = config<KeyboardShortcut>(text, "FavoritingModifierKeybind2", new KeyboardShortcut((KeyCode)122, Array.Empty<KeyCode>()), text2 + " Identical to FavoritingModifierKeybind1.", synchronizedSetting: false); FavoritedItemTooltip = config(text, "FavoritedItemTooltip", "Item is favorited and won't be stored", string.Empty, synchronizedSetting: false); FavoritedSlotTooltip = config(text, "FavoritedSlotTooltip", "Slot is favorited and won't be stored", string.Empty, synchronizedSetting: false); ItemOnFavoritedSlotTooltip = config(text, "ItemOnFavoritedSlotTooltip", "Item & Slot are favorited and won't be stored", string.Empty, synchronizedSetting: false); if (!File.Exists(yamlPath)) { WriteConfigFileFromResource(yamlPath); } AzuAutoStoreContainerData.ValueChanged += OnValChangedUpdate; AzuAutoStoreContainerData.AssignLocalValue(File.ReadAllText(yamlPath)); AutoDoc(); Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); SetupWatcher(); } public void Start() { BorderRenderer.Border = loadSprite("border.png"); if (Chainloader.PluginInfos.ContainsKey("org.bepinex.plugins.backpacks")) { BackpacksIsLoaded = true; } Log.Init(AzuAutoStoreLogger); if (!MUCCompat.DoNotPatch && Chainloader.PluginInfos.ContainsKey("mkz.itemdrawers")) { try { _harmony.PatchAll(typeof(ItemDrawerCompat)); } catch (Exception ex) { AzuAutoStoreLogger.LogWarning((object)("Couldn't apply the ItemDrawers compatibility patches: " + ex.Message)); } } } private void AutoDoc() { } private static void WriteConfigFileFromResource(string configFilePath) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); string text = "AzuAutoStore.Example.yml"; using Stream stream = executingAssembly.GetManifestResourceStream(text); if (stream == null) { throw new FileNotFoundException("Resource '" + text + "' not found in the assembly."); } using StreamReader streamReader = new StreamReader(stream); string contents = streamReader.ReadToEnd(); File.WriteAllText(configFilePath, contents); } private void Update() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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_003c: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return; } KeyboardShortcut value = _storeShortcut.Value; if (((KeyboardShortcut)(ref value)).IsDown() && ((Character)Player.m_localPlayer).TakeInput()) { Functions.TryStore(); } value = _pauseShortcut.Value; if (!((KeyboardShortcut)(ref value)).IsDown() || !((Character)Player.m_localPlayer).TakeInput()) { return; } Boxes.StoringPaused = !Boxes.StoringPaused; foreach (Container container in Boxes.Containers) { if (container.m_nview.IsValid()) { container.m_nview.InvokeRPC("RequestPause", new object[1] { Boxes.StoringPaused }); } } } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } private void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, "Azumatt.AzuAutoStore.cfg"); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; FileSystemWatcher fileSystemWatcher2 = new FileSystemWatcher(Paths.ConfigPath, yamlFileName); fileSystemWatcher2.Changed += ReadYamlFiles; fileSystemWatcher2.Created += ReadYamlFiles; fileSystemWatcher2.Renamed += ReadYamlFiles; fileSystemWatcher2.IncludeSubdirectories = true; fileSystemWatcher2.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher2.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { Functions.LogDebug("ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { Functions.LogError("There was an issue loading your Azumatt.AzuAutoStore.cfg"); Functions.LogError("Please check your config entries for spelling and format!"); } } private void ReadYamlFiles(object sender, FileSystemEventArgs e) { if (!File.Exists(yamlPath)) { return; } try { AzuAutoStoreLogger.LogDebug((object)"ReadConfigValues called"); AzuAutoStoreContainerData.AssignLocalValue(File.ReadAllText(yamlPath)); } catch { AzuAutoStoreLogger.LogError((object)("There was an issue loading your " + yamlFileName)); AzuAutoStoreLogger.LogError((object)"Please check your entries for spelling and format!"); } } private static void OnValChangedUpdate() { AzuAutoStoreLogger.LogDebug((object)"OnValChanged called"); try { YamlUtils.ReadYaml(AzuAutoStoreContainerData.Value); YamlUtils.ParseGroups(); Functions.ClearRangeCache(); } catch (Exception arg) { AzuAutoStoreLogger.LogError((object)$"Failed to deserialize {yamlFileName}: {arg}"); } } private static byte[] ReadEmbeddedFileBytes(string name) { using MemoryStream memoryStream = new MemoryStream(); Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream); return memoryStream.ToArray(); } private static Texture2D loadTexture(string name) { //IL_0002: 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_001d: Expected O, but got Unknown //IL_001f: Expected O, but got Unknown Texture2D val = new Texture2D(0, 0); ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("assets." + name)); return val; } internal static Sprite loadSprite(string name) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) Texture2D val = loadTexture(name); if ((Object)(object)val != (Object)null) { return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), Vector2.zero); } return null; } private ConfigEntry<T> config<[<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val); ConfigSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry<T> config<[<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } private ConfigEntry<T> TextEntryConfig<[<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val); ConfigSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry<T> TextEntryConfig<[<31f19a94-c784-4aab-bc2b-6331c6b22707>Nullable(2)] T>(string group, string name, T value, string desc, bool synchronizedSetting = true) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes { CustomDrawer = ConfigExtensions.TextAreaDrawer }; return TextEntryConfig(group, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes }), synchronizedSetting); } static AzuAutoStorePlugin() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + "Azumatt.AzuAutoStore.cfg"; ConnectionError = ""; AzuAutoStoreLogger = Logger.CreateLogSource("AzuAutoStore"); ConfigSync = new ConfigSync("Azumatt.AzuAutoStore") { DisplayName = "AzuAutoStore", CurrentVersion = "3.1.7", MinimumRequiredVersion = "3.1.7" }; BackpacksIsLoaded = false; yamlFileName = "Azumatt.AzuAutoStore.yml"; string configPath2 = Paths.ConfigPath; directorySeparatorChar = Path.DirectorySeparatorChar; yamlPath = configPath2 + directorySeparatorChar + yamlFileName; AzuAutoStoreContainerData = new CustomSyncedValue<string>(ConfigSync, "azuautostoreData", ""); CraftyContainerGroupsData = new CustomSyncedValue<string>(ConfigSync, "azuautostoreGroupsData", ""); groups = null; self = null; _serverConfigLocked = null; DontStoreToBackpacks = null; ChestsPickupFromGround = null; MustHaveExistingItemToPull = null; SingleItemShortcut = null; _storeShortcut = null; _pauseShortcut = null; SecondsToWaitBeforeStoring = null; IntervalSeconds = null; FishSuction = null; PlayerRange = null; FallbackRange = null; PlayerIgnoreHotbar = null; PlayerIgnoreQuickSlots = null; PingVfxString = null; HighlightContainers = null; PingContainers = null; BorderColorFavoritedItem = null; BorderColorFavoritedItemOnFavoritedSlot = null; BorderColorFavoritedSlot = null; DisplayTooltipHint = null; FavoritingModifierKeybind1 = null; FavoritingModifierKeybind2 = null; SearchModifierKeybind = null; FavoritedItemTooltip = null; FavoritedSlotTooltip = null; ItemOnFavoritedSlotTooltip = null; } } public static class ToggleExtensions { public static bool IsOn(this AzuAutoStorePlugin.Toggle toggle) { return toggle == AzuAutoStorePlugin.Toggle.On; } public static bool IsOff(this AzuAutoStorePlugin.Toggle toggle) { return toggle == AzuAutoStorePlugin.Toggle.Off; } } public static class KeyboardExtensions { public static bool IsKeyDown(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } return false; } public static bool IsKeyHeld(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKey(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } return false; } } public static class ConfigExtensions { [<5eccf676-4928-40d6-bd07-ee44b60a7faa>NullableContext(1)] internal static void TextAreaDrawer(ConfigEntr
BepInEx/plugins/hex/MultiUserChest.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using HarmonyLib; using Jotunn.Managers; using Jotunn.Utils; using MultiUserChest.Patches; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("MultiUserChest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MultiUserChest")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: InternalsVisibleTo("UnitTests")] [assembly: InternalsVisibleTo("Tests")] [assembly: ComVisible(false)] [assembly: Guid("FE8B42E3-7082-4DFF-A5CC-6B62B0315ACA")] [assembly: AssemblyFileVersion("0.6.2")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.6.2.0")] [module: UnverifiableCode] namespace MultiUserChest { public static class CodeMatcherExtensions { public static CodeMatcher GetPosition(this CodeMatcher codeMatcher, out int position) { position = codeMatcher.Pos; return codeMatcher; } public static CodeMatcher AddLabel(this CodeMatcher codeMatcher, out Label label) { label = default(Label); codeMatcher.AddLabels((IEnumerable<Label>)new Label[1] { label }); return codeMatcher; } public static CodeMatcher GetOperand(this CodeMatcher codeMatcher, out object operand) { operand = codeMatcher.Operand; return codeMatcher; } internal static CodeMatcher Print(this CodeMatcher codeMatcher, int before, int after) { for (int i = -before; i <= after; i++) { int num = i; int num2 = codeMatcher.Pos + num; if (num2 > 0) { if (num2 >= codeMatcher.Length) { break; } try { CodeInstruction val = codeMatcher.InstructionAt(num); Log.LogCodeInstruction($"[{num}] " + ((object)val).ToString()); } catch (Exception ex) { Log.LogCodeInstruction(ex.Message); } } } return codeMatcher; } public static bool IsVirtCall(this CodeInstruction i, string declaringType, string name) { if (i.opcode == OpCodes.Callvirt && i.operand is MethodInfo methodInfo && methodInfo.DeclaringType?.Name == declaringType) { return methodInfo.Name == name; } return false; } } public static class Compatibility { private static bool IsExtendedInventory(this Inventory inventory, out List<Inventory> inventories) { if (inventory.IsType("ExtendedInventory") && inventory.HasField("_inventories")) { inventories = inventory.GetField<List<Inventory>>("_inventories"); return true; } inventories = null; return false; } public static List<Inventory> GetInventories(this Inventory inventory) { if (inventory.IsExtendedInventory(out var inventories)) { return inventories; } return new List<Inventory> { inventory }; } } public class ContainerExtend : MonoBehaviour { private static readonly ConditionalWeakTable<Inventory, ContainerInventoryOwner> Containers = new ConditionalWeakTable<Inventory, ContainerInventoryOwner>(); private Inventory inventory; private void Awake() { Container container = default(Container); if (!((Component)this).TryGetComponent<Container>(ref container)) { return; } inventory = container.GetInventory(); if (inventory != null) { Containers.TryAdd(inventory, (Inventory i) => new ContainerInventoryOwner(container)); } } private void OnDestroy() { if (inventory != null) { Containers.Remove(inventory); } } public static bool GetContainer(Inventory inventory, out ContainerInventoryOwner container) { return Containers.TryGetValue(inventory, out container); } } public static class ContainerHandler { public static RequestChestAdd AddItemToChest(this Container container, ItemData item, Inventory sourceInventory, Vector2i to, ZDOID sender, int dragAmount = -1) { //IL_0022: 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_0048: 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_008a: 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_00b1: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)container) || !Object.op_Implicit((Object)(object)container.m_nview) || !container.m_nview.HasOwner()) { return new RequestChestAdd(Vector2i.zero, 0, null, null, null); } dragAmount = PossibleDragAmount(container.GetInventory(), item, to, dragAmount); ItemData itemAt = container.GetInventory().GetItemAt(to.x, to.y); bool flag = itemAt != null && dragAmount != item.m_stack && !InventoryHelper.CanStack(itemAt, item); if (dragAmount <= 0 || flag || !sourceInventory.ContainsItem(item)) { return new RequestChestAdd(Vector2i.zero, 0, null, null, null); } RequestChestAdd requestChestAdd = new RequestChestAdd(to, dragAmount, item, sourceInventory, container.GetInventory()); InventoryBlock.Get(sourceInventory).BlockSlot(item.m_gridPos); InventoryPreview.AddPackage(requestChestAdd); sourceInventory.RemoveItem(item, dragAmount); if (container.m_nview.IsOwner()) { RequestChestAddResponse response = container.GetInventory().RequestItemAdd(requestChestAdd); InventoryHandler.RPC_RequestItemAddResponse(sourceInventory, response); return null; } GamePatches.InvokeRPC(container.m_nview, "MUC_RequestItemAdd", requestChestAdd); return requestChestAdd; } internal static int PossibleDragAmount(Inventory inventoryTo, ItemData dragItem, Vector2i to, int dragAmount) { //IL_001c: 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_002f: 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) dragAmount = ((dragAmount >= 0) ? Mathf.Min(dragAmount, dragItem.m_stack) : dragItem.m_stack); if (to.x >= 0 && to.y >= 0) { ItemData itemAt = inventoryTo.GetItemAt(to.x, to.y); if (itemAt != null && dragAmount < dragItem.m_stack) { if (InventoryHelper.CanStack(itemAt, dragItem)) { return Mathf.Min(dragAmount, itemAt.m_shared.m_maxStackSize - itemAt.m_stack); } return 0; } } else if (!inventoryTo.HaveEmptySlot()) { int num = inventoryTo.FindFreeStackSpace(dragItem.m_shared.m_name, (float)dragItem.m_worldLevel); return Mathf.Min(dragAmount, num); } return dragAmount; } public static RequestChestRemove RemoveItemFromChest(this Container container, ItemData item, Inventory destinationInventory, Vector2i to, ZDOID sender, int dragAmount = -1, ItemData switchItem = null) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0052: 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_0079: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)container) || !Object.op_Implicit((Object)(object)container.m_nview) || !container.m_nview.HasOwner()) { return new RequestChestRemove(Vector2i.zero, Vector2i.zero, 0, null, container.GetInventory(), destinationInventory); } dragAmount = PossibleDragAmount(destinationInventory, item, to, dragAmount); if (dragAmount <= 0 || InventoryBlock.Get(destinationInventory).IsSlotBlocked(to)) { return new RequestChestRemove(Vector2i.zero, Vector2i.zero, 0, null, container.GetInventory(), destinationInventory); } RequestChestRemove requestChestRemove = new RequestChestRemove(item.m_gridPos, to, dragAmount, switchItem, container.GetInventory(), destinationInventory); if (switchItem != null && !InventoryHelper.CanStack(item, switchItem)) { if (dragAmount != item.m_stack) { return new RequestChestRemove(Vector2i.zero, Vector2i.zero, 0, null, container.GetInventory(), destinationInventory); } destinationInventory.RemoveItem(switchItem); } InventoryBlock.Get(destinationInventory).BlockSlot(requestChestRemove.toPos); InventoryPreview.AddPackage(requestChestRemove); if (container.m_nview.IsOwner()) { RequestChestRemoveResponse response = container.GetInventory().RequestItemRemove(requestChestRemove); InventoryHandler.RPC_RequestItemRemoveResponse(destinationInventory, response); return null; } GamePatches.InvokeRPC(container.m_nview, "MUC_RequestItemRemove", requestChestRemove); return requestChestRemove; } public static void MoveItemInChest(this Container container, ItemData item, Vector2i toPos, int dragAmount) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) RequestMove package = new RequestMove(item, toPos, dragAmount, container.GetInventory()); InventoryPreview.AddPackage(package); GamePatches.InvokeRPC(container.m_nview, "MUC_RequestItemMove", package); } } public static class ContainerRPCHandler { public static void RPC_RequestItemAdd(long sender, ZDOID containerId, ZPackage package) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) HandleRPC(containerId, sender, "MUC_RequestItemAddResponse", RequestItemAdd, new RequestChestAdd(package)); } public static void RPC_RequestItemRemove(long sender, ZDOID containerId, ZPackage package) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) HandleRPC(containerId, sender, "MUC_RequestItemRemoveResponse", RequestItemRemove, new RequestChestRemove(package)); } public static void RPC_RequestItemConsume(long sender, ZDOID containerId, ZPackage package) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) HandleRPC(containerId, sender, "MUC_RequestItemConsumeResponse", RequestItemConsume, new RequestConsume(package)); } public static void RPC_RequestItemMove(long sender, ZDOID containerId, ZPackage package) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) HandleRPC(containerId, sender, "MUC_RequestItemMoveResponse", RequestItemMove, new RequestMove(package)); } public static void RPC_RequestDrop(long sender, ZDOID containerId, ZPackage package) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) HandleRPC(containerId, sender, "MUC_RequestItemDropResponse", RequestDrop, new RequestDrop(package)); } private static void HandleRPC<TResponse, TInput>(ZDOID containerId, long target, string rpcInvoke, Func<Inventory, TInput, TResponse> message, TInput input) where TResponse : IResponse, new() where TInput : IPackage { //IL_0005: 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) ZDO zDO = ZDOMan.instance.GetZDO(containerId); ZNetView val = ((zDO != null) ? ZNetScene.instance.FindInstance(zDO) : null); TResponse val2; if (!Object.op_Implicit((Object)(object)val) || !val.IsOwner()) { val2 = FallbackResponse<TResponse>(input as IRequest); } else { Container componentInChildren = ((Component)val).GetComponentInChildren<Container>(); if (Object.op_Implicit((Object)(object)componentInChildren)) { val2 = message(componentInChildren.GetInventory(), input); } else { Log.LogWarning(input.GetType().Name + ": not handling RPC, Container component not found on " + ((Object)val).name); val2 = FallbackResponse<TResponse>(input as IRequest); } } ZRoutedRpc.instance.InvokeRoutedRPC(target, rpcInvoke, new object[2] { containerId, val2.WriteToPackage() }); } private static TResponse FallbackResponse<TResponse>(IRequest request) where TResponse : IResponse, new() { //IL_0058: 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_005d: Unknown result type (might be due to invalid IL or missing references) TResponse val = new TResponse { SourceID = (request?.RequestID ?? 0) }; if (request is RequestChestAdd requestChestAdd && val is RequestChestAddResponse requestChestAddResponse) { requestChestAddResponse.switchItem = requestChestAdd.dragItem; requestChestAddResponse.inventoryPos = requestChestAdd.dragItem?.m_gridPos ?? Vector2i.zero; } else if (request is RequestChestRemove requestChestRemove && val is RequestChestRemoveResponse requestChestRemoveResponse) { requestChestRemoveResponse.responseItem = requestChestRemove.switchItem; } return val; } public static RequestChestAddResponse RequestItemAdd(this Inventory inventory, RequestChestAdd request) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (request.dragItem == null) { return new RequestChestAddResponse(request.RequestID, success: false, Vector2i.zero, 0, request.dragItem); } if (request.toPos.x < 0 || request.toPos.y < 0) { return AddToAnySlot(inventory, request); } return AddToSlot(inventory, request); } private static RequestChestAddResponse AddToSlot(Inventory inventory, RequestChestAdd request) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0093: 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_0081: Unknown result type (might be due to invalid IL or missing references) if (!CanStack(inventory, request, out var stackSpace, out var removedItem)) { return new RequestChestAddResponse(request.RequestID, success: false, request.dragItem.m_gridPos, 0, request.dragItem); } bool flag = inventory.AddItemToInventory(request.dragItem, stackSpace, request.toPos); if (!flag) { stackSpace = 0; } if (!flag || stackSpace != request.dragItem.m_stack) { removedItem = request.dragItem; removedItem.m_stack = request.dragItem.m_stack - stackSpace; } if (removedItem != null) { removedItem.m_gridPos = request.dragItem.m_gridPos; } return new RequestChestAddResponse(request.RequestID, flag, request.dragItem.m_gridPos, stackSpace, removedItem); } private static bool CanStack(Inventory inventory, RequestChestAdd request, out int stackSpace, out ItemData removedItem) { ItemData itemAt = inventory.GetItemAt(request.toPos.x, request.toPos.y); removedItem = null; if (itemAt == null) { stackSpace = request.dragItem.m_stack; return true; } if (InventoryHelper.CanStack(itemAt, request.dragItem)) { stackSpace = Mathf.Min(itemAt.m_shared.m_maxStackSize - itemAt.m_stack, request.dragItem.m_stack); return true; } if (request.allowSwitch) { inventory.RemoveItem(itemAt, itemAt.m_stack); removedItem = itemAt; stackSpace = request.dragItem.m_stack; return true; } stackSpace = 0; return false; } private static RequestChestAddResponse AddToAnySlot(Inventory inventory, RequestChestAdd request) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) Inventory val = new Inventory("tmp", (Sprite)null, 1, 1); val.AddItem(request.dragItem.Clone(), request.dragItem.m_stack, 0, 0, false); inventory.MoveItemToThis(val, val.GetItemAt(0, 0)); ItemData itemAt = val.GetItemAt(0, 0); if (itemAt == null) { return new RequestChestAddResponse(request.RequestID, success: true, request.dragItem.m_gridPos, request.dragItem.m_stack, null); } ItemData val2 = request.dragItem.Clone(); int num = request.dragItem.m_stack - itemAt.m_stack; val2.m_stack -= num; bool success = itemAt.m_stack != request.dragItem.m_stack; return new RequestChestAddResponse(request.RequestID, success, request.dragItem.m_gridPos, num, val2); } public static RequestChestRemoveResponse RequestItemRemove(this Inventory inventory, RequestChestRemove request) { //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_00d2: Unknown result type (might be due to invalid IL or missing references) Vector2i fromPos = request.fromPos; int dragAmount = request.dragAmount; ItemData switchItem = request.switchItem; ItemData itemAt = inventory.GetItemAt(request.fromPos.x, request.fromPos.y); if (itemAt == null) { Log.LogDebug("from is null"); return new RequestChestRemoveResponse(request.RequestID, success: false, 0, hasSwitched: false, null); } int num = 0; bool flag = false; bool flag2 = false; if (switchItem == null) { num = Mathf.Min(itemAt.m_stack, dragAmount); flag = inventory.RemoveItem(itemAt, num); } else if (InventoryHelper.CanStack(itemAt, switchItem)) { num = Mathf.Min(switchItem.m_shared.m_maxStackSize - switchItem.m_stack, dragAmount); flag = inventory.RemoveItem(itemAt, num); } else { if (dragAmount < itemAt.m_stack) { return new RequestChestRemoveResponse(request.RequestID, success: false, 0, hasSwitched: false, request.switchItem); } flag = inventory.RemoveItem(itemAt, dragAmount); num = Mathf.Min(itemAt.m_stack, dragAmount); flag2 = inventory.AddItemToInventory(switchItem, switchItem.m_stack, fromPos); if (!flag2) { Log.LogWarning("Could not switch item in Remove Request"); InventoryHandler.DropItem(switchItem, switchItem.m_stack); } } ItemData val = itemAt.Clone(); val.m_stack = num; return new RequestChestRemoveResponse(request.RequestID, flag, num, flag2, val); } public static RequestConsumeResponse RequestItemConsume(this Inventory inventory, RequestConsume request) { ItemData itemAt = inventory.GetItemAt(request.itemPosX, request.itemPosY); if (itemAt == null || itemAt.m_stack <= 0) { return new RequestConsumeResponse(null, success: false, 0); } inventory.RemoveOneItem(itemAt); ItemData val = itemAt.Clone(); val.m_stack = 1; return new RequestConsumeResponse(val, success: true, 1); } public static RequestMoveResponse RequestItemMove(this Inventory inventory, RequestMove request) { //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_0008: 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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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) Vector2i fromPos = request.fromPos; Vector2i toPos = request.toPos; int dragAmount = request.dragAmount; ItemData itemAt = inventory.GetItemAt(fromPos.x, fromPos.y); if (itemAt == null) { return new RequestMoveResponse(request.RequestID, success: false, 0); } if (StringExtensionMethods.GetStableHashCode(itemAt.PrefabName()) != request.itemHash) { return new RequestMoveResponse(request.RequestID, success: false, 0); } int movedAmount; bool success = InventoryHelper.MoveItem(inventory, itemAt, dragAmount, toPos, out movedAmount); return new RequestMoveResponse(request.RequestID, success, movedAmount); } public static RequestDropResponse RequestDrop(this Inventory inventory, RequestDrop request) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_006c: 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) ItemData itemAt = inventory.GetItemAt(request.targetContainerSlot.x, request.targetContainerSlot.y); if (itemAt == null) { return new RequestDropResponse(null, request.sender, success: false, 0); } int num = Mathf.Min(itemAt.m_stack, request.amount); inventory.RemoveItem(itemAt, num); if (num == 0) { return new RequestDropResponse(null, request.sender, success: false, 0); } ItemData val = itemAt.Clone(); val.m_stack = num; return new RequestDropResponse(val, request.sender, success: true, num); } } public interface IPackage { ZPackage WriteToPackage(); } public interface IRequest : IPackage { int RequestID { get; set; } Inventory SourceInventory { get; } Inventory TargetInventory { get; } } public interface IResponse : IPackage { int SourceID { get; set; } bool Success { get; set; } int Amount { get; set; } } public class RequestChestAdd : IRequest, IPackage { public readonly Vector2i toPos; public readonly ItemData dragItem; public readonly bool allowSwitch; public int RequestID { get; set; } public Inventory SourceInventory { get; } public Inventory TargetInventory { get; } public RequestChestAdd(Vector2i toPos, int dragAmount, ItemData dragItem, Inventory sourceInventory, Inventory targetInventory) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) this.toPos = toPos; if (dragItem != null) { this.dragItem = dragItem.Clone(); this.dragItem.m_stack = Mathf.Min(dragAmount, this.dragItem.m_stack); allowSwitch = dragAmount == dragItem.m_stack; } SourceInventory = sourceInventory; TargetInventory = targetInventory; } public RequestChestAdd(ZPackage package) { //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) RequestID = package.ReadInt(); toPos = package.ReadVector2i(); dragItem = InventoryHelper.LoadItemFromPackage(package); allowSwitch = package.ReadBool(); } public ZPackage WriteToPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0014: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); val.Write(RequestID); val.Write(toPos); InventoryHelper.WriteItemToPackage(dragItem, val); val.Write(allowSwitch); return val; } } public class RequestChestAddResponse : IPackage, IResponse { public Vector2i inventoryPos; public ItemData switchItem; public int SourceID { get; set; } public bool Success { get; set; } public int Amount { get; set; } public RequestChestAddResponse(int sourceID, bool success, Vector2i inventoryPos, int amount, ItemData switchItem) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) SourceID = sourceID; Success = success; Amount = amount; this.inventoryPos = inventoryPos; this.switchItem = switchItem.ClampStackSize(); } public RequestChestAddResponse(ZPackage package) { //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) SourceID = package.ReadInt(); inventoryPos = package.ReadVector2i(); Success = package.ReadBool(); Amount = package.ReadInt(); switchItem = InventoryHelper.LoadItemFromPackage(package); } public RequestChestAddResponse() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) SourceID = 0; Success = false; inventoryPos = new Vector2i(-1, -1); Amount = 0; switchItem = null; } public ZPackage WriteToPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0014: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); val.Write(SourceID); val.Write(inventoryPos); val.Write(Success); val.Write(Amount); InventoryHelper.WriteItemToPackage(switchItem, val); return val; } } public class RequestConsume : IPackage { public readonly int itemPosX; public readonly int itemPosY; public RequestConsume(ItemData item) { itemPosX = item.m_gridPos.x; itemPosY = item.m_gridPos.y; } public RequestConsume(ZPackage package) { itemPosX = package.ReadInt(); itemPosY = package.ReadInt(); } public ZPackage WriteToPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(itemPosX); val.Write(itemPosY); return val; } } public class RequestConsumeResponse : IPackage, IResponse { public readonly ItemData item; public int SourceID { get; set; } public bool Success { get; set; } public int Amount { get; set; } public RequestConsumeResponse(ZPackage package) { item = InventoryHelper.LoadItemFromPackage(package); Success = package.ReadBool(); Amount = package.ReadInt(); } public RequestConsumeResponse(ItemData item, bool success, int amount) { this.item = item.ClampStackSize(); Success = success; Amount = amount; } public RequestConsumeResponse() { item = null; } public ZPackage WriteToPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); InventoryHelper.WriteItemToPackage(item, val); val.Write(Success); val.Write(Amount); return val; } } public class RequestDrop : IPackage { public readonly Vector2i targetContainerSlot; public readonly int amount; public readonly ZDOID sender; public RequestDrop(Vector2i targetContainerSlot, int amount, ZDOID sender) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0015: 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) this.targetContainerSlot = targetContainerSlot; this.amount = amount; this.sender = sender; } public RequestDrop(ZPackage package) { //IL_0008: 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_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) targetContainerSlot = package.ReadVector2i(); amount = package.ReadInt(); sender = package.ReadZDOID(); } public ZPackage WriteToPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0008: 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) ZPackage val = new ZPackage(); val.Write(targetContainerSlot); val.Write(amount); val.Write(sender); return val; } } public class RequestDropResponse : IPackage, IResponse { public readonly ItemData responseItem; public readonly ZDOID sender; public int SourceID { get; set; } public bool Success { get; set; } public int Amount { get; set; } public RequestDropResponse(ItemData responseItem, ZDOID sender, bool success, int amount) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) this.responseItem = responseItem.ClampStackSize(); this.sender = sender; Success = success; Amount = amount; } public RequestDropResponse(ZPackage package) { //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) responseItem = InventoryHelper.LoadItemFromPackage(package); sender = package.ReadZDOID(); Success = package.ReadBool(); Amount = package.ReadInt(); } public RequestDropResponse() { responseItem = null; } public ZPackage WriteToPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0014: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); InventoryHelper.WriteItemToPackage(responseItem, val); val.Write(sender); val.Write(Success); val.Write(Amount); return val; } } public class RequestMove : IRequest, IPackage { public readonly Vector2i fromPos; public readonly Vector2i toPos; public readonly int itemHash; public readonly int dragAmount; public readonly ItemData item; public int RequestID { get; set; } public Inventory SourceInventory { get; } public Inventory TargetInventory { get; } public RequestMove(ItemData itemToMove, Vector2i toPos, int dragAmount, Inventory inventory) { //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_0059: 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) //IL_0016: 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_0023: 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) if (itemToMove == null) { Log.LogWarning("Item is null"); fromPos = new Vector2i(-1, -1); this.toPos = new Vector2i(-1, -1); itemHash = 0; this.dragAmount = 0; } else { SourceInventory = inventory; TargetInventory = inventory; fromPos = itemToMove.m_gridPos; this.toPos = toPos; itemHash = StringExtensionMethods.GetStableHashCode(itemToMove.PrefabName()); item = itemToMove.Clone(); this.dragAmount = dragAmount; } } public RequestMove(ZPackage package) { //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_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) RequestID = package.ReadInt(); fromPos = package.ReadVector2i(); toPos = package.ReadVector2i(); itemHash = package.ReadInt(); dragAmount = package.ReadInt(); } public ZPackage WriteToPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0014: 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) ZPackage val = new ZPackage(); val.Write(RequestID); val.Write(fromPos); val.Write(toPos); val.Write(itemHash); val.Write(dragAmount); return val; } } public class RequestChestRemove : IRequest, IPackage { public readonly Vector2i fromPos; public readonly Vector2i toPos; public readonly int dragAmount; public readonly ItemData switchItem; public readonly ItemData item; public int RequestID { get; set; } public Inventory SourceInventory { get; } public Inventory TargetInventory { get; } public RequestChestRemove(Vector2i fromPos, Vector2i toPos, int dragAmount, ItemData switchItem, Inventory sourceInventory, Inventory targetInventory) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: 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_004f: Unknown result type (might be due to invalid IL or missing references) this.fromPos = fromPos; this.toPos = toPos; this.dragAmount = dragAmount; this.switchItem = ((switchItem != null) ? switchItem.Clone() : null); SourceInventory = sourceInventory; TargetInventory = targetInventory; object obj; if (sourceInventory == null) { obj = null; } else { ItemData itemAt = sourceInventory.GetItemAt(fromPos.x, fromPos.y); obj = ((itemAt != null) ? itemAt.Clone() : null); } item = (ItemData)obj; } public RequestChestRemove(ZPackage package) { //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_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) RequestID = package.ReadInt(); fromPos = package.ReadVector2i(); toPos = package.ReadVector2i(); dragAmount = package.ReadInt(); switchItem = InventoryHelper.LoadItemFromPackage(package); } public ZPackage WriteToPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0014: 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) ZPackage val = new ZPackage(); val.Write(RequestID); val.Write(fromPos); val.Write(toPos); val.Write(dragAmount); InventoryHelper.WriteItemToPackage(switchItem, val); return val; } } public class RequestChestRemoveResponse : IPackage, IResponse { public ItemData responseItem; public bool hasSwitched; public int SourceID { get; set; } public bool Success { get; set; } public int Amount { get; set; } public RequestChestRemoveResponse(int sourceID, bool success, int amount, bool hasSwitched, ItemData responseItem) { SourceID = sourceID; Success = success; Amount = amount; this.hasSwitched = hasSwitched; this.responseItem = responseItem.ClampStackSize(); } public RequestChestRemoveResponse(ZPackage package) { SourceID = package.ReadInt(); Success = package.ReadBool(); Amount = package.ReadInt(); hasSwitched = package.ReadBool(); responseItem = InventoryHelper.LoadItemFromPackage(package); } public RequestChestRemoveResponse() { Success = false; Amount = 0; hasSwitched = false; responseItem = null; } public ZPackage WriteToPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(SourceID); val.Write(Success); val.Write(Amount); val.Write(hasSwitched); InventoryHelper.WriteItemToPackage(responseItem, val); return val; } } public class RequestMoveResponse : IPackage, IResponse { public int SourceID { get; set; } public bool Success { get; set; } public int Amount { get; set; } public RequestMoveResponse(int sourceID, bool success, int amount) { SourceID = sourceID; Success = success; Amount = amount; } public RequestMoveResponse() { SourceID = 0; Success = false; Amount = 0; } public RequestMoveResponse(ZPackage package) { SourceID = package.ReadInt(); Success = package.ReadBool(); Amount = package.ReadInt(); } public ZPackage WriteToPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(SourceID); val.Write(Success); val.Write(Amount); return val; } } public class SlotPreview { private Inventory originalInventory; private Inventory inventory; private bool hasChanges; public SlotPreview(Inventory inventory) { originalInventory = inventory; this.inventory = InventoryHelper.CopyInventory(inventory); } public void Add(Vector2i pos, ItemData item, int amount) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001e: 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_0035: Unknown result type (might be due to invalid IL or missing references) if (item != null && amount != 0) { ItemData val = item.Clone(); val.m_stack = amount; if (pos.x >= 0 && pos.y >= 0) { inventory.AddItem(val, amount, pos.x, pos.y, false); } else { inventory.AddItem(val); } hasChanges = true; } } public void Add(Vector2i pos, ItemData item) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Add(pos, item, item?.m_stack ?? 0); } public void Remove(Vector2i pos, ItemData item) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Remove(pos, item, item?.m_stack ?? 0); } public void Remove(Vector2i pos, ItemData item, int amount) { //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_002f: 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) if (item != null && amount != 0) { ItemData itemAt = inventory.GetItemAt(pos.x, pos.y); if (itemAt != null) { inventory.RemoveItem(inventory.GetItemAt(pos.x, pos.y), amount); hasChanges = true; } } } public bool GetSlot(Vector2i pos, out ItemData item) { //IL_0006: 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_001f: 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) ItemData itemAt = originalInventory.GetItemAt(pos.x, pos.y); item = inventory.GetItemAt(pos.x, pos.y); if (itemAt == null && item == null) { return false; } if (itemAt == null || item == null) { return true; } if (!(itemAt.m_shared.m_name != item.m_shared.m_name)) { return itemAt.m_stack != item.m_stack; } return true; } public bool HasChanges() { return hasChanges; } } public static class ConditionalWeakTableExtension { public static void TryAdd<TKey, TValue>(this ConditionalWeakTable<TKey, TValue> table, TKey key, ConditionalWeakTable<TKey, TValue>.CreateValueCallback createCallback) where TKey : class where TValue : class { table.GetValue(key, createCallback); } } public static class InventoryHelper { public delegate void MoveAction(Inventory from, Inventory to); private static MethodBase memberwiseCloneMethod = AccessTools.Method(typeof(object), "MemberwiseClone", (Type[])null, (Type[])null); public static ItemData LoadItemFromPackage(ZPackage pkg) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: 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_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Expected O, but got Unknown //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) if (!pkg.ReadBool()) { return null; } string text = pkg.ReadString(); int num = pkg.ReadInt(); float num2 = pkg.ReadSingle(); Vector2i val = pkg.ReadVector2i(); int num3 = pkg.ReadInt(); int num4 = pkg.ReadInt(); long num5 = pkg.ReadLong(); string text2 = pkg.ReadString(); int num6 = pkg.ReadInt(); bool flag = pkg.ReadBool(); bool flag2 = pkg.ReadBool(); Dictionary<string, string> dictionary = new Dictionary<string, string>(); int num7 = pkg.ReadInt(); for (int i = 0; i < num7; i++) { string key = pkg.ReadString(); string value = pkg.ReadString(); dictionary[key] = value; } Inventory val2 = new Inventory("tmp", (Sprite)null, val.x + 1, val.y + 1); val2.AddItem(text, num, num2, val, false, num3, num4, num5, text2, dictionary, num6, flag, flag2, false); ItemData itemAt = val2.GetItemAt(val.x, val.y); val2.RemoveItem(itemAt); return itemAt; } public static void WriteItemToPackage(ItemData itemData, ZPackage pkg) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) pkg.Write(itemData != null); if (itemData == null) { return; } pkg.Write(itemData.PrefabName()); pkg.Write(itemData.m_stack); pkg.Write(itemData.m_durability); pkg.Write(itemData.m_gridPos); pkg.Write(itemData.m_quality); pkg.Write(itemData.m_variant); pkg.Write(itemData.m_crafterID); pkg.Write(itemData.m_crafterName); pkg.Write(itemData.m_worldLevel); pkg.Write(itemData.m_pickedUp); pkg.Write(itemData.m_cheated); pkg.Write(itemData.m_customData.Count); foreach (KeyValuePair<string, string> customDatum in itemData.m_customData) { pkg.Write(customDatum.Key); pkg.Write(customDatum.Value); } } public static ItemData ClampStackSize(this ItemData item) { if (item == null) { return null; } ItemDrop prefab = Cache.GetPrefab<ItemDrop>(item.PrefabName()); item.m_shared.m_maxStackSize = prefab.m_itemData.m_shared.m_maxStackSize; return item; } public static string PrefabName(this ItemData item) { if ((Object)(object)item.m_dropPrefab != (Object)null) { return ((Object)item.m_dropPrefab).name; } Log.LogWarning("Item missing prefab " + item.m_shared.m_name); return item.m_shared.m_name; } public static bool MoveItem(Inventory inventory, ItemData item, int amount, Vector2i toPos, out int movedAmount) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: 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) movedAmount = 0; if (item == null) { return false; } ItemData itemAt = inventory.GetItemAt(toPos.x, toPos.y); if (itemAt == item) { return true; } if (itemAt == null) { movedAmount = amount; return inventory.MoveItemToThis(inventory, item, amount, toPos.x, toPos.y); } if (CanStack(itemAt, item)) { movedAmount = Mathf.Min(amount, itemAt.m_shared.m_maxStackSize - itemAt.m_stack); return inventory.MoveItemToThis(inventory, item, movedAmount, toPos.x, toPos.y); } if (item.m_stack != amount) { return false; } inventory.RemoveItem(item); inventory.MoveItemToThis(inventory, itemAt, itemAt.m_stack, item.m_gridPos.x, item.m_gridPos.y); inventory.MoveItemToThis(inventory, item, amount, toPos.x, toPos.y); movedAmount = amount; return true; } public static bool CanStack(ItemData itemA, ItemData itemB) { if (itemA.m_shared.m_name == itemB.m_shared.m_name && (itemA.m_shared.m_maxQuality <= 1 || itemB.m_quality == itemA.m_quality)) { return itemA.m_shared.m_maxStackSize != 1; } return false; } public static Vector2i FindEmptySlot(Inventory inventory, List<Vector2i> blockedSlots) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < inventory.m_height; i++) { for (int j = 0; j < inventory.m_width; j++) { if (inventory.GetItemAt(j, i) == null && !blockedSlots.Contains(new Vector2i(j, i))) { return new Vector2i(j, i); } } } return new Vector2i(-1, -1); } public static List<ItemData> GetAllMoveableItems(Inventory from, Inventory to, MoveAction moveAction) { Inventory val = CopyInventory(from); Inventory to2 = CopyInventory(to); moveAction(val, to2); return CountMoved(from, val); } public static List<ItemData> GetAllMoveableItems(Inventory from, Inventory to) { return GetAllMoveableItems(from, to, MoveAll); } public static void MoveAll(Inventory from, Inventory to) { to.MoveAll(from); } private static List<ItemData> CountMoved(Inventory from, Inventory fromCopy) { List<ItemData> list = new List<ItemData>(); foreach (ItemData item in from.m_inventory) { ItemData itemAt = fromCopy.GetItemAt(item.m_gridPos.x, item.m_gridPos.y); if (itemAt == null) { list.Add(item); } else if (item.m_stack > itemAt.m_stack) { ItemData val = item.Clone(); val.m_stack = item.m_stack - itemAt.m_stack; list.Add(val); } } return list; } public static Inventory CopyInventory(Inventory target) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown return new Inventory(target.m_name, target.m_bkg, target.m_width, target.m_height) { m_inventory = new List<ItemData>(from x in target.GetAllItems() select x.Clone()) }; } public static bool AddItemToInventory(this Inventory target, ItemData item, int amount, Vector2i pos) { //IL_0006: 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_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) if (amount == 0) { return false; } ItemData itemAt = target.GetItemAt(pos.x, pos.y); if (itemAt != null) { if (!CanStack(itemAt, item)) { return false; } if (itemAt.m_stack + amount > itemAt.m_shared.m_maxStackSize) { return false; } } ItemData val = item.CloneDeeper(); val.m_stack = amount; return target.AddItem(val, amount, pos.x, pos.y, false); } public static ItemData CloneDeeper(this ItemData itemDrop) { ItemData val = itemDrop.Clone(); ref SharedData shared = ref val.m_shared; object? obj = memberwiseCloneMethod.Invoke(itemDrop.m_shared, null); shared = (SharedData)((obj is SharedData) ? obj : null); return val; } public static void PrintItem(string title, ItemData itemData) { } } public static class Log { private static ManualLogSource logSource; internal static void Init(ManualLogSource manualLogSource) { logSource = manualLogSource; } public static void LogCodeInstruction(object data) { } public static void LogDebug(string data) { } public static void LogError(string data) { if (logSource != null) { logSource.LogError((object)data); } else { Debug.LogError((object)data); } } public static void LogFatal(string data) { if (logSource != null) { logSource.LogFatal((object)data); } else { Debug.LogError((object)data); } } public static void LogInfo(string data) { if (logSource != null) { logSource.LogInfo((object)data); } else { Debug.Log((object)data); } } public static void LogWarning(string data) { if (logSource != null) { logSource.LogWarning((object)data); } else { Debug.LogWarning((object)data); } } } public static class ReflectionHelper { private const BindingFlags allFlags = (BindingFlags)(-1); public static bool IsType(this object target, string name) { return target.GetType().Name == name; } public static bool HasField(this object target, string name) { return target.GetType().GetField(name, (BindingFlags)(-1)) != null; } public static T GetField<T>(this object target, string name) { return (T)(target.GetType().GetField(name, (BindingFlags)(-1))?.GetValue(target)); } public static T InvokeMethod<T>(this object target, string name, params object[] parameter) { parameter = ((parameter.Length == 0) ? null : parameter); return (T)(target.GetType().GetMethod(name, (BindingFlags)(-1))?.Invoke(target, parameter)); } public static T InvokeStaticMethod<T>(string type, string name, params object[] parameter) { parameter = ((parameter.Length == 0) ? null : parameter); return (T)(Type.GetType(type)?.GetMethod(name, (BindingFlags)(-1))?.Invoke(null, parameter)); } } public class HumanoidExtend : MonoBehaviour { private static readonly ConditionalWeakTable<Inventory, HumanoidInventoryOwner> Humanoids = new ConditionalWeakTable<Inventory, HumanoidInventoryOwner>(); private Inventory inventory; private void Awake() { UpdateInventory(); } private void Start() { UpdateInventory(); } private void UpdateInventory() { Humanoid humanoid = default(Humanoid); if (!((Component)this).TryGetComponent<Humanoid>(ref humanoid)) { return; } inventory = humanoid.GetInventory(); if (inventory == null) { return; } foreach (Inventory inventory in inventory.GetInventories()) { Humanoids.TryAdd(inventory, (Inventory i) => new HumanoidInventoryOwner(humanoid, i)); } } private void OnDestroy() { if (inventory == null) { return; } foreach (Inventory inventory in inventory.GetInventories()) { Humanoids.Remove(inventory); } } public static bool GetHumanoid(Inventory inventory, out HumanoidInventoryOwner humanoid) { return Humanoids.TryGetValue(inventory, out humanoid); } } public class InventoryBlock { private static readonly Dictionary<Inventory, InventoryBlock> Inventories = new Dictionary<Inventory, InventoryBlock>(); public bool BlockAllSlots { get; set; } public bool BlockConsume { get; set; } public Dictionary<Vector2i, int> BlockedSlots { get; } = new Dictionary<Vector2i, int>(); public static InventoryBlock Get(Inventory inventory) { if (Inventories.TryGetValue(inventory, out var value)) { return value; } InventoryBlock inventoryBlock = new InventoryBlock(); Inventories.Add(inventory, inventoryBlock); return inventoryBlock; } public void BlockSlot(Vector2i slot) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000f: 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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: 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_0027: Unknown result type (might be due to invalid IL or missing references) if (CanBlockSlot(slot)) { if (BlockedSlots.ContainsKey(slot)) { BlockedSlots[slot]++; } else { BlockedSlots[slot] = 1; } } } public void ReleaseSlot(Vector2i slot) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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) //IL_0037: 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) if (CanBlockSlot(slot) && BlockedSlots.ContainsKey(slot)) { BlockedSlots[slot]--; if (BlockedSlots[slot] <= 0) { BlockedSlots.Remove(slot); } } } public void ReleaseBlockedSlots() { BlockedSlots.Clear(); BlockAllSlots = false; BlockConsume = false; } public bool IsSlotBlocked(Vector2i slot) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (!BlockConsume && !BlockAllSlots) { return BlockedSlots.ContainsKey(slot); } return true; } public bool IsAnySlotBlocked() { if (!BlockConsume && !BlockAllSlots) { return BlockedSlots.Count > 0; } return true; } private static bool CanBlockSlot(Vector2i slot) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (slot.x >= 0) { return slot.y >= 0; } return false; } } public static class InventoryHandler { public static void RPC_RequestItemAddResponse(long sender, ZDOID containerId, ZPackage package) { HandleRPC(new RequestChestAddResponse(package), (RequestChestAddResponse p) => GetSourceInventory(p.SourceID), RPC_RequestItemAddResponse); } public static void RPC_RequestItemRemoveResponse(long sender, ZDOID containerId, ZPackage package) { HandleRPC(new RequestChestRemoveResponse(package), (RequestChestRemoveResponse p) => GetTargetInventory(p.SourceID), RPC_RequestItemRemoveResponse); } public static void RPC_RequestDropResponse(long sender, ZDOID containerId, ZPackage package) { HandleRPC(new RequestDropResponse(package), RPC_RequestDropResponse); } public static void RPC_RequestItemConsumeResponse(long sender, ZDOID containerId, ZPackage package) { HandleRPC(new RequestConsumeResponse(package), RPC_RequestItemConsumeResponse); } public static void RPC_RequestItemMoveResponse(long sender, ZDOID containerId, ZPackage package) { HandleRPC(new RequestMoveResponse(package), RPC_RequestItemMoveResponse); } private static void HandleRPC<T>(T package, Func<T, Inventory> inventory, Container container, Action<Inventory, Container, T> handle) where T : IPackage { CallRPC(handle.Method.Name, package, delegate { handle(inventory(package), container, package); }); } private static void HandleRPC<T>(T package, Func<T, Inventory> inventory, Action<Inventory, T> handle) where T : IPackage { CallRPC(handle.Method.Name, package, delegate { handle(inventory(package), package); }); } private static void HandleRPC<T>(T package, Action<T> handle) where T : IPackage { CallRPC(handle.Method.Name, package, delegate { handle(package); }); } private static void CallRPC(string timerName, IPackage package, Action action) { action?.Invoke(); } public static void RPC_RequestItemRemoveResponse(Inventory inventory, RequestChestRemoveResponse response) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Expected O, but got Unknown //IL_003a: 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_0068: 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) Vector2i toPos = PackageHandler.GetPackage<RequestChestRemove>(response.SourceID).toPos; InventoryBlock.Get(inventory).ReleaseSlot(toPos); InventoryPreview.RemovePackage(response); if (response.Success && toPos.x >= 0 && toPos.y >= 0) { if (!inventory.AddItemToInventory(response.responseItem, response.Amount, toPos)) { int num = response.Amount; ItemData itemAt = inventory.GetItemAt(toPos.x, toPos.y); if (itemAt != null && InventoryHelper.CanStack(response.responseItem, itemAt)) { int maxStackSize = itemAt.m_shared.m_maxStackSize; int stack = itemAt.m_stack; int num2 = maxStackSize - stack; itemAt.m_stack += num2; num -= num2; } DropItem(response.responseItem, num); } } else if (response.responseItem != null) { Inventory val = new Inventory("tmp", (Sprite)null, 1, 1); val.AddItem(response.responseItem); inventory.MoveItemToThis(val, response.responseItem); ItemData itemAt2 = val.GetItemAt(0, 0); if (itemAt2 != null) { DropItem(itemAt2, itemAt2.m_stack); } } UpdateGUIAfterPlayerMove(GetTargetInventory(response.SourceID)); } private static void RPC_RequestDropResponse(RequestDropResponse response) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) DropItem(response.responseItem, response.responseItem?.m_stack ?? 0); UpdateGUIAfterPlayerMove(response.sender); } private static void UpdateGUIAfterPlayerMove(ZDOID sender) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)InventoryGui.instance) && Object.op_Implicit((Object)(object)Player.m_localPlayer) && sender == ((Character)Player.m_localPlayer).GetZDOID()) { InventoryGui.instance.UpdateCraftingPanel(false); } } private static void UpdateGUIAfterPlayerMove(Inventory inventory) { if (Object.op_Implicit((Object)(object)InventoryGui.instance) && Object.op_Implicit((Object)(object)Player.m_localPlayer) && ((Humanoid)Player.m_localPlayer).GetInventory().GetInventories().Contains(inventory)) { InventoryGui.instance.UpdateCraftingPanel(false); } } public static void DropItem(ItemData item, int amount) { if (amount > 0 && item != null) { DropItem(Player.m_localPlayer, item, amount); } } private static void DropItem(Player player, ItemData item, int amount) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: 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_0026: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0052: 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_0078: 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_008c: Unknown result type (might be due to invalid IL or missing references) Transform transform = ((Component)player).transform; ItemDrop val = ItemDrop.DropItem(item, amount, transform.position + transform.forward + transform.up, transform.rotation); val.OnPlayerDrop(); ((Component)val).GetComponent<Rigidbody>().velocity = (transform.forward + Vector3.up) * 5f; ((Character)player).m_zanim.SetTrigger("interact"); ((Humanoid)player).m_dropEffects.Create(transform.position, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID)); ItemData itemData = val.m_itemData; ((Character)player).Message((MessageType)1, "$msg_dropped " + itemData.m_shared.m_name, itemData.m_stack, itemData.GetIcon(), false); } public static void RPC_RequestItemAddResponse(Inventory inventory, RequestChestAddResponse response) { //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_0014: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) Vector2i inventoryPos = response.inventoryPos; ItemData switchItem = response.switchItem; InventoryBlock.Get(inventory).ReleaseSlot(inventoryPos); InventoryPreview.RemovePackage(response); if (switchItem != null && !inventory.AddItemToInventory(switchItem, switchItem.m_stack, inventoryPos)) { DropItem(switchItem, switchItem.m_stack); } UpdateGUIAfterPlayerMove(GetSourceInventory(response.SourceID)); } public static void RPC_RequestItemConsumeResponse(RequestConsumeResponse response) { Player localPlayer = Player.m_localPlayer; InventoryBlock.Get(((Humanoid)localPlayer).GetInventory()).BlockConsume = false; if (response.item != null && ((Humanoid)localPlayer).CanConsumeItem(response.item, false)) { if (Object.op_Implicit((Object)(object)response.item.m_shared.m_consumeStatusEffect)) { ((Character)localPlayer).m_seman.AddStatusEffect(response.item.m_shared.m_consumeStatusEffect, true, 0, 0f, (short)(-1)); } if ((double)response.item.m_shared.m_food > 0.0) { localPlayer.EatFood(response.item); } } } public static void RPC_RequestItemMoveResponse(RequestMoveResponse response) { InventoryPreview.RemovePackage(response); } internal static Inventory GetSourceInventory(int id) { return PackageHandler.GetPackage<IRequest>(id)?.SourceInventory; } internal static Inventory GetTargetInventory(int id) { return PackageHandler.GetPackage<IRequest>(id)?.TargetInventory; } } public abstract class InventoryOwner { public abstract ZNetView ZNetView { get; } public abstract Inventory Inventory { get; } public virtual bool IsValid() { if (Object.op_Implicit((Object)(object)ZNetView) && ZNetView.HasOwner()) { return Inventory != null; } return false; } public static InventoryOwner GetOwner(Inventory inventory) { if (inventory == null) { return null; } if (HumanoidExtend.GetHumanoid(inventory, out var humanoid)) { return humanoid; } if (ContainerExtend.GetContainer(inventory, out var container)) { return container; } return null; } public static InventoryOwner GetOwner(ItemData item) { if (item == null) { return null; } if (InventoryPatch.InventoryOfItem.TryGetValue(item, out var value)) { return GetOwner(value); } return null; } public string GetDescription() { if (!IsValid()) { return "-"; } return $"{Inventory.GetName()} ({GetType().Name}), is owner: {ZNetView.IsOwner()}"; } } public class ContainerInventoryOwner : InventoryOwner { public Container Container { get; } public bool IsItemDrawer { get; } public override ZNetView ZNetView => Container.m_nview; public override Inventory Inventory => Container.GetInventory(); public ContainerInventoryOwner(Container container) { Container = container; IsItemDrawer = ItemDrawerCompat.IsItemDrawer(Container); } } public class HumanoidInventoryOwner : InventoryOwner { private readonly Inventory inventory; public Humanoid Humanoid { get; } public override ZNetView ZNetView => ((Character)Humanoid).m_nview; public override Inventory Inventory => inventory; public HumanoidInventoryOwner(Humanoid humanoid, Inventory inventory) { Humanoid = humanoid; this.inventory = inventory; } } public static class InventoryPreview { public static readonly ConditionalWeakTable<Inventory, List<IRequest>> PackageChanges = new ConditionalWeakTable<Inventory, List<IRequest>>(); public static readonly ConditionalWeakTable<Inventory, List<IRequest>> ToRemovePackages = new ConditionalWeakTable<Inventory, List<IRequest>>(); private static WaitForSeconds removeQueuedPackagesDelay = new WaitForSeconds(0.2f); public static void AddPackage(IRequest package) { package.RequestID = PackageHandler.AddPackage(package); AppendPackage(package.SourceInventory, package); AppendPackage(package.TargetInventory, package); } private static void AppendPackage(Inventory inventory, IRequest package) { if (PackageChanges.TryGetValue(inventory, out var value)) { if (!value.Contains(package)) { value.Add(package); } Log.LogDebug($"InventoryPreview: Appended package {package.RequestID} to inventory {inventory.m_name}, total packages: {value.Count}"); return; } PackageChanges.Add(inventory, new List<IRequest> { package }); Inventory obj = inventory; obj.m_onChanged = (Action)Delegate.Combine(obj.m_onChanged, (Action)delegate { RemoveQueuedPackages(inventory); }); Log.LogDebug($"InventoryPreview: Added package {package.RequestID} to inventory {inventory.m_name}, total packages: 1 (new)"); } public static void RemovePackage(IResponse package) { RemovePackage(InventoryHandler.GetSourceInventory(package.SourceID), package); RemovePackage(InventoryHandler.GetTargetInventory(package.SourceID), package); PackageHandler.RemovePackage(package.SourceID); } private static void RemovePackage(Inventory inventory, IResponse package) { if (inventory == null) { return; } InventoryOwner owner = InventoryOwner.GetOwner(inventory); IRequest request = null; if (PackageChanges.TryGetValue(inventory, out var value)) { request = value.Find((IRequest p) => p.RequestID == package.SourceID); } if (request != null) { if (ToRemovePackages.TryGetValue(inventory, out var value2)) { value2.Add(request); } else { ToRemovePackages.Add(inventory, new List<IRequest> { request }); } if (owner != null && owner.IsValid() && owner.ZNetView.IsOwner()) { RemoveQueuedPackages(inventory); } else if (!package.Success) { ((MonoBehaviour)ThreadingHelper.Instance).StartCoroutine(RemoveQueuedPackagesDelayed(inventory)); } } } private static void RemoveQueuedPackages(Inventory inventory) { if (!ToRemovePackages.TryGetValue(inventory, out var value) || value.Count <= 0) { return; } foreach (IRequest item in new List<IRequest>(value)) { if (PackageChanges.TryGetValue(inventory, out var value2)) { value2.Remove(item); } value.Remove(item); Log.LogDebug($"InventoryPreview: Removed package {item.RequestID} from inventory {inventory.m_name}, total packages: {value.Count}"); } } private static IEnumerator RemoveQueuedPackagesDelayed(Inventory inventory) { yield return removeQueuedPackagesDelay; RemoveQueuedPackages(inventory); } public static bool GetChanges(Inventory inventory, out SlotPreview preview) { //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: 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_0155: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: 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_0128: 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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: 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_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_021b: 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_0249: Unknown result type (might be due to invalid IL or missing references) if (inventory == null) { preview = null; return false; } if (PackageChanges.TryGetValue(inventory, out var value)) { preview = new SlotPreview(inventory); foreach (IRequest item3 in value) { if (item3 is RequestChestAdd requestChestAdd) { if (requestChestAdd.dragItem != null) { ItemData item = null; if (requestChestAdd.allowSwitch) { item = item3.TargetInventory.GetItemAt(requestChestAdd.toPos.x, requestChestAdd.toPos.y); } if (inventory == item3.SourceInventory) { preview.Add(requestChestAdd.dragItem.m_gridPos, item); } if (inventory == item3.TargetInventory) { preview.Remove(requestChestAdd.toPos, item); preview.Add(requestChestAdd.toPos, requestChestAdd.dragItem); } } } else if (item3 is RequestChestRemove { fromPos: var fromPos, toPos: var toPos } requestChestRemove) { if (inventory == item3.SourceInventory) { preview.Remove(fromPos, requestChestRemove.item, requestChestRemove.dragAmount); preview.Add(fromPos, requestChestRemove.switchItem); } if (inventory == item3.TargetInventory) { preview.Add(toPos, requestChestRemove.item, requestChestRemove.dragAmount); } } else { if (!(item3 is RequestMove requestMove) || (preview.GetSlot(requestMove.fromPos, out var item2) && requestMove.itemHash != ((item2 != null) ? new int?(StringExtensionMethods.GetStableHashCode(item2.PrefabName())) : ((int?)null)))) { continue; } ItemData itemAt = requestMove.TargetInventory.GetItemAt(requestMove.toPos.x, requestMove.toPos.y); if (itemAt != null && !InventoryHelper.CanStack(requestMove.item, itemAt)) { if (requestMove.dragAmount == requestMove.item.m_stack) { preview.Remove(requestMove.fromPos, requestMove.item, requestMove.dragAmount); preview.Remove(requestMove.toPos, itemAt, itemAt.m_stack); preview.Add(requestMove.fromPos, itemAt, itemAt.m_stack); preview.Add(requestMove.toPos, requestMove.item, requestMove.dragAmount); } } else { int amount = Mathf.Max(0, requestMove.dragAmount); if (itemAt != null) { amount = Mathf.Min(itemAt.m_shared.m_maxStackSize - itemAt.m_stack, requestMove.dragAmount); } preview.Remove(requestMove.fromPos, requestMove.item, amount); preview.Add(requestMove.toPos, requestMove.item, amount); } } } return preview.HasChanges(); } preview = null; return false; } } public static class InventoryIgnore { public static bool IgnoreInventory(this InventoryOwner owner) { if (OdinShip.IsOdinShipInstalled() && owner is ContainerInventoryOwner containerInventoryOwner && containerInventoryOwner.Container.IsOdinShipContainer()) { return true; } if (owner == null || !Object.op_Implicit((Object)(object)owner.ZNetView) || owner.ZNetView.GetZDO() == null) { return false; } return owner.ZNetView.GetZDO().GetBool("MUC_Ignore", false); } public static bool IgnoreInventory(this Container container) { return InventoryOwner.GetOwner(container.GetInventory()).IgnoreInventory(); } } public static class ItemDrawerCompat { private static Type drawerContainerType; private static FieldRef<object, ItemData> drawerField_item; static ItemDrawerCompat() { if (Chainloader.PluginInfos.ContainsKey("mkz.itemdrawers")) { drawerContainerType = AccessTools.TypeByName("DrawerContainer, itemdrawers"); drawerField_item = AccessTools.FieldRefAccess<ItemData>(drawerContainerType, "_item"); } } public static bool IsItemDrawer(Container container) { if (drawerContainerType != null) { return Object.op_Implicit((Object)(object)((Component)container).GetComponent(drawerContainerType)); } return false; } [HarmonyPatch("DrawerContainer, itemdrawers", "OnInventoryChanged")] [HarmonyPrefix] public static void UpdateItemOfDrawer(Container __instance) { if (__instance.m_inventory.m_inventory.Count != 0 && __instance.m_inventory.m_inventory[0] != null) { drawerField_item.Invoke((object)__instance) = __instance.m_inventory.m_inventory[0].Clone(); } } [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })] [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData), typeof(int), typeof(int), typeof(int), typeof(bool) })] [HarmonyPriority(700)] public static bool PreventItemAdd(Inventory __instance, ItemData item) { if (InventoryOwner.GetOwner(__instance) is ContainerInventoryOwner { IsItemDrawer: not false } containerInventoryOwner) { ItemData val = drawerField_item.Invoke((object)containerInventoryOwner.Container); if (val != null && val.PrefabName() != item?.PrefabName()) { Log.LogInfo("PreventItemAdd: " + val.PrefabName() + " != " + item?.PrefabName()); return false; } } return true; } [HarmonyPatch(typeof(Inventory), "CanAddItem", new Type[] { typeof(ItemData), typeof(int) })] [HarmonyPostfix] public static void CanAddItem(Inventory __instance, ref bool __result, ItemData item) { if (__result && InventoryOwner.GetOwner(__instance) is ContainerInventoryOwner { IsItemDrawer: not false } containerInventoryOwner) { ItemData val = drawerField_item.Invoke((object)containerInventoryOwner.Container); __result = val == null || val.PrefabName() == item?.PrefabName(); } } [HarmonyPatch("DrawerContainer, itemdrawers", "AddItem")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> CloneItemBeforeAssignmentTranspiler(IEnumerable<CodeInstruction> instructions) { //IL_0002: 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_0035: Expected O, but got Unknown //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[2] { new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(ItemDrop), "m_itemData"), (string)null), new CodeMatch((OpCode?)OpCodes.Stfld, (object)AccessTools.Field(drawerContainerType, "_item"), (string)null) }).Advance(1).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(InventoryHelper), "CloneDeeper", (Type[])null, (Type[])null)) }) .InstructionEnumeration(); } } public static class OdinShip { public static bool IsOdinShipInstalled() { if (!Chainloader.PluginInfos.ContainsKey("marlthon.OdinShipPlus")) { return Chainloader.PluginInfos.ContainsKey("marlthon.OdinShip"); } return true; } public static bool IsOdinShipContainer(this Container container) { return ((object)container).GetType().FullName == "OdinShip.ShipContainer"; } } public static class QuickStackPatch { [HarmonyPatch("QuickStack.QuickStackPlugin, QuickStack", "StackToMany")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> QuickStackPatchTranspiler(IEnumerable<CodeInstruction> instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[2] { new CodeMatch((OpCode?)OpCodes.Ldloc_S, (object)null, (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.IsVirtCall("ZNetView", "ClaimOwnership")), (string)null) }).RemoveInstructions(9).InstructionEnumeration(); } } [BepInPlugin("com.maxsch.valheim.MultiUserChest", "MultiUserChest", "0.6.2")] [BepInIncompatibility("aedenthorn.QuickStore")] [BepInIncompatibility("aedenthorn.SimpleSort")] [BepInIncompatibility("org.bepinex.plugins.valheim.quick_stack")] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public const string ModName = "MultiUserChest"; public const string ModGuid = "com.maxsch.valheim.MultiUserChest"; public const string ModVersion = "0.6.2"; private static Harmony harmony = new Harmony("com.maxsch.valheim.MultiUserChest"); public static Plugin Instance { get; private set; } private void Awake() { Instance = this; Log.Init(((BaseUnityPlugin)this).Logger); harmony.PatchAll(); } private void Start() { ApplyModPatches(); } internal static void ApplyModPatches() { if (Chainloader.PluginInfos.ContainsKey("mkz.itemdrawers")) { harmony.PatchAll(typeof(ItemDrawerCompat)); } } } public static class PackageHandler { private static readonly Dictionary<int, IPackage> Packages = new Dictionary<int, IPackage>(); private static readonly Random Random = new Random(); private static int total; public static int AddPackage(IPackage package) { int randomId = GetRandomId(); Packages.Add(randomId, package); return randomId; } public static void RemovePackage(int id) { Packages.Remove(id); } private static int GetRandomId() { return Random.Next(int.MinValue, int.MaxValue); } public static bool GetPackage<T>(int id, out T package) where T : IPackage { if (Packages.TryGetValue(id, out var value)) { package = (T)value; return true; } package = default(T); return false; } public static T GetPackage<T>(int id) where T : IPackage { if (Packages.TryGetValue(id, out var value)) { return (T)value; } return default(T); } } } namespace MultiUserChest.Patches { [HarmonyPatch] public static class ContainerPatch { public const string ItemMoveRPC = "MUC_RequestItemMove"; public const string ItemMoveResponseRPC = "MUC_RequestItemMoveResponse"; public const string ItemAddRPC = "MUC_RequestItemAdd"; public const string ItemAddResponseRPC = "MUC_RequestItemAddResponse"; public const string ItemRemoveRPC = "MUC_RequestItemRemove"; public const string ItemRemoveResponseRPC = "MUC_RequestItemRemoveResponse"; public const string ItemConsumeRPC = "MUC_RequestItemConsume"; public const string ItemConsumeResponseRPC = "MUC_RequestItemConsumeResponse"; public const string ItemDropRPC = "MUC_RequestItemDrop"; public const string ItemDropResponseRPC = "MUC_RequestItemDropResponse"; [HarmonyPatch(typeof(Container), "Awake")] [HarmonyPostfix] public static void ContainerAwakePatch(Container __instance) { ((Component)__instance).gameObject.AddComponent<ContainerExtend>(); if (!__instance.IgnoreInventory() && !Object.op_Implicit((Object)(object)__instance.m_nview)) { __instance.m_nview = (Object.op_Implicit((Object)(object)__instance.m_rootObjectOverride) ? ((Component)__instance.m_rootObjectOverride).GetComponent<ZNetView>() : ((Component)__instance).GetComponent<ZNetView>()); } } [HarmonyPatch(typeof(Container), "RPC_RequestOpen")] [HarmonyPrefix] public static bool ContainerRPC_RequestOpenPatch(Container __instance, long uid, long playerID) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) if (__instance.IgnoreInventory() || !__instance.m_nview.IsOwner()) { return true; } if (!__instance.CheckAccess(playerID)) { __instance.m_nview.InvokeRPC(uid, "RPC_OpenResponse", new object[1] { false }); return false; } if (IsContainerInUse(__instance, uid)) { __instance.m_nview.InvokeRPC(uid, "RPC_OpenResponse", new object[1] { true }); return false; } ZDOMan.instance.ForceSendZDO(uid, __instance.m_nview.GetZDO().m_uid); __instance.m_nview.GetZDO().SetOwner(uid); __instance.m_nview.InvokeRPC(uid, "RPC_OpenResponse", new object[1] { true }); return false; } [HarmonyPatch(typeof(Container), "RPC_RequestStack")] [HarmonyPrefix] public static bool ContainerRPC_RequestStackPatch(Container __instance, long uid, long playerID) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) if (__instance.IgnoreInventory() || !__instance.m_nview.IsOwner()) { return true; } if (!__instance.CheckAccess(playerID)) { __instance.m_nview.InvokeRPC(uid, "RPC_StackResponse", new object[1] { false }); return false; } if (IsContainerInUse(__instance, uid)) { __instance.m_nview.InvokeRPC(uid, "RPC_StackResponse", new object[1] { true }); return false; } ZDOMan.instance.ForceSendZDO(uid, __instance.m_nview.GetZDO().m_uid); __instance.m_nview.GetZDO().SetOwner(uid); __instance.m_nview.InvokeRPC(uid, "RPC_StackResponse", new object[1] { true }); return false; } private static bool IsContainerInUse(Container container, long playerId) { bool flag = container.IsInUse(); bool flag2 = Object.op_Implicit((Object)(object)container.m_wagon) && container.m_wagon.InUse(); bool flag3 = playerId == ZNet.GetUID(); if (flag || flag2) { return !flag3; } return false; } } [HarmonyPatch] public static class GamePatches { [HarmonyPatch(typeof(Game), "Start")] [HarmonyPostfix] public static void GameStartPatch() { RegisterRPCs(); } public static void RegisterRPCs() { ZRoutedRpc.instance.Register<ZDOID, ZPackage>("MUC_RequestItemMove", (Action<long, ZDOID, ZPackage>)ContainerRPCHandler.RPC_RequestItemMove); ZRoutedRpc.instance.Register<ZDOID, ZPackage>("MUC_RequestItemAdd", (Action<long, ZDOID, ZPackage>)ContainerRPCHandler.RPC_RequestItemAdd); ZRoutedRpc.instance.Register<ZDOID, ZPackage>("MUC_RequestItemRemove", (Action<long, ZDOID, ZPackage>)ContainerRPCHandler.RPC_RequestItemRemove); ZRoutedRpc.instance.Register<ZDOID, ZPackage>("MUC_RequestItemConsume", (Action<long, ZDOID, ZPackage>)ContainerRPCHandler.RPC_RequestItemConsume); ZRoutedRpc.instance.Register<ZDOID, ZPackage>("MUC_RequestItemDrop", (Action<long, ZDOID, ZPackage>)ContainerRPCHandler.RPC_RequestDrop); ZRoutedRpc.instance.Register<ZDOID, ZPackage>("MUC_RequestItemMoveResponse", (Action<long, ZDOID, ZPackage>)InventoryHandler.RPC_RequestItemMoveResponse); ZRoutedRpc.instance.Register<ZDOID, ZPackage>("MUC_RequestItemAddResponse", (Action<long, ZDOID, ZPackage>)InventoryHandler.RPC_RequestItemAddResponse); ZRoutedRpc.instance.Register<ZDOID, ZPackage>("MUC_RequestItemRemoveResponse", (Action<long, ZDOID, ZPackage>)InventoryHandler.RPC_RequestItemRemoveResponse); ZRoutedRpc.instance.Register<ZDOID, ZPackage>("MUC_RequestItemConsumeResponse", (Action<long, ZDOID, ZPackage>)InventoryHandler.RPC_RequestItemConsumeResponse); ZRoutedRpc.instance.Register<ZDOID, ZPackage>("MUC_RequestItemDropResponse", (Action<long, ZDOID, ZPackage>)InventoryHandler.RPC_RequestDropResponse); } public static void InvokeRPC(ZNetView netView, string rpc, IPackage package) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) ZRoutedRpc.instance.InvokeRoutedRPC(netView.m_zdo.GetOwner(), rpc, new object[2] { netView.m_zdo.m_uid, package.WriteToPackage() }); } } [HarmonyPatch] public static class HumanoidPatch { [HarmonyPatch(typeof(Humanoid), "Awake")] [HarmonyPostfix] public static void HumanoidAwakePatch(Humanoid __instance) { ((Component)__instance).gameObject.AddComponent<HumanoidExtend>(); } } [HarmonyPatch] public static class InventoryGuiPatch { [HarmonyPatch(typeof(InventoryGui), "Update")] [HarmonyPostfix] public static void InventoryGuiUpdatePatch(InventoryGui __instance) { if (Object.op_Implicit((Object)(object)__instance.m_currentContainer) && Object.op_Implicit((Object)(object)__instance.m_currentContainer.m_nview) && __instance.m_currentContainer.m_nview.IsValid()) { __instance.m_currentContainer.CheckForChanges(); } } [HarmonyPatch(typeof(InventoryGui), "OnRightClickItem")] [HarmonyPrefix] public static bool InventoryGuiOnRightClickItemPatch(InventoryGui __instance, InventoryGrid grid, ItemData item) { Player localPlayer = Player.m_localPlayer; if (item == null || !Object.op_Implicit((Object)(object)localPlayer)) { return true; } if (grid.GetInventory() == ((Humanoid)localPlayer).GetInventory()) { return true; } if (!Object.op_Implicit((Object)(object)__instance.m_currentContainer) || __instance.m_currentContainer.IsOwner()) { return true; } if (InventoryBlock.Get(((Humanoid)localPlayer).GetInventory()).BlockConsume) { return false; } if (((Humanoid)localPlayer).CanConsumeItem(item, false)) { InventoryBlock.Get(((Humanoid)localPlayer).GetInventory()).BlockConsume = true; RequestConsume package = new RequestConsume(item); GamePatches.InvokeRPC(__instance.m_currentContainer.m_nview, "MUC_RequestItemConsume", package); } return false; } [HarmonyPatch(typeof(InventoryGui), "UpdateContainer")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> ChangeOwnerCheck(IEnumerable<CodeInstruction> instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Expected O, but got Unknown return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(true, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Ldfld && ((FieldInfo)i.operand).Name == "m_currentContainer"), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Callvirt && ((MethodInfo)i.operand).Name == "IsOwner"), (string)null) }).RemoveInstructions(1).Insert((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(InventoryGuiPatch), "CanOpenContainer", (Type[])null, (Type[])null)) }) .InstructionEnumeration(); } public static bool CanOpenContainer(Container container) { if (container.IgnoreInventory()) { return container.IsOwner(); } return true; } [HarmonyPatch(typeof(InventoryGui), "OnDropOutside")] [HarmonyPrefix] public static void InventoryGuiOnDropOutsidePatch(InventoryGui __instance, ref bool __runOriginal) { //IL_0071: 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) if (!__runOriginal || !Object.op_Implicit((Object)(object)__instance.m_dragGo)) { return; } if (((Humanoid)Player.m_localPlayer).GetInventory().GetInventories().Contains(__instance.m_dragInventory)) { Log.LogDebug("Drop item from own inventory"); return; } bool flag = Object.op_Implicit((Object)(object)__instance.m_currentContainer) && __instance.m_currentContainer.IsOwner(); if (!(!Object.op_Implicit((Object)(object)__instance.m_currentContainer) || flag)) { RequestDrop package = new RequestDrop(__instance.m_dragItem.m_gridPos, __instance.m_dragAmount, ((Character)Player.m_localPlayer).GetZDOID()); GamePatches.InvokeRPC(__instance.m_currentContainer.m_nview, "MUC_RequestItemDrop", package); __instance.SetupDragItem((ItemData)null, (Inventory)null, 1); __runOriginal = false; } } [HarmonyPatch(typeof(Inventory), "Load", new Type[] { typeof(ZPackage) })] [HarmonyPostfix] public static void InventorySelectSameItemAfterLoad(Inventory __instance) { if (Object.op_Implicit((Object)(object)InventoryGui.instance) && InventoryGui.instance.m_dragItem != null && Object.op_Implicit((Object)(object)InventoryGui.instance.m_currentContainer) && InventoryGui.instance.m_currentContainer.GetInventory() == __instance && InventoryGui.instance.m_dragInventory != null && InventoryGui.instance.m_dragInventory == __instance) { ItemData dragItem = InventoryGui.instance.m_dragItem; ItemData itemAt = __instance.GetItemAt(dragItem.m_gridPos.x, dragItem.m_gridPos.y); if (itemAt == null) { InventoryGui.instance.SetupDragItem((ItemData)null, (Inventory)null, 1); return; } int dragAmount = Mathf.Min(itemAt.m_stack, InventoryGui.instance.m_dragAmount); InventoryGui.instance.m_dragAmount = dragAmount; InventoryGui.instance.m_dragItem = itemAt; } } [HarmonyPatch(typeof(InventoryGrid), "UpdateInventory")] [HarmonyPostfix] public static void InventoryGridUpdateInventoryPatch(InventoryGrid __instance) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (!InventoryPreview.GetChanges(__instance.m_inventory, out var preview)) { return; } foreach (InventoryElement element in __instance.m_elements) { if (preview.GetSlot(element.Position, out var item)) { if (item == null) { ShowNoItem(element); } else { ShowItem(__instance, element, item); } } } } private static void ShowItem(InventoryGrid inventoryGrid, InventoryElement element, ItemData item) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Invalid comparison between Unknown and I4 //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) if (item?.m_shared == null) { return; } int stack = item.m_stack; int maxStackSize = item.m_shared.m_maxStackSize; ((Behaviour)element.m_icon).enabled = stack > 0; element.m_icon.sprite = item.GetIcon(); ((Graphic)element.m_icon).color = Color.white; ((Behaviour)element.m_amount).enabled = stack > 0 && maxStackSize > 1; element.m_amount.text = $"{stack}/{maxStackSize}"; bool flag = item.m_shared.m_useDurability && item.m_durability < item.GetMaxDurability(); ((Component)element.m_durability).gameObject.SetActive(flag); if (flag) { if ((double)item.m_durability <= 0.0) { element.m_durability.SetValue(1f); element.m_durability.SetColor((Color)(((double)Mathf.Sin(Time.time * 10f) > 0.0) ? Color.red : new Color(0f, 0f, 0f, 0f))); } else { element.m_durability.SetValue(item.GetDurabilityPercentage()); element.m_durability.ResetColor(); } } ((Behaviour)element.m_equiped).enabled = false; ((Behaviour)element.m_queued).enabled = false; ((Behaviour)element.m_noteleport).enabled = !item.m_shared.m_teleportable && !ZoneSystem.instance.GetGlobalKey((GlobalKeys)35); if ((int)item.m_shared.m_itemType == 2 && ((double)item.m_shared.m_food > 0.0 || (double)item.m_shared.m_foodStamina > 0.0 || (double)item.m_shared.m_foodEitr > 0.0)) { ((Behaviour)element.m_food).enabled = true; if ((double)item.m_shared.m_food < (double)item.m_shared.m_foodEitr / 2.0 && (double)item.m_shared.m_foodStamina < (double)item.m_shared.m_foodEitr / 2.0) { ((Graphic)element.m_food).color = inventoryGrid.m_foodEitrColor; } else if ((double)item.m_shared.m_foodStamina < (double)item.m_shared.m_food / 2.0) { ((Graphic)element.m_food).color = inventoryGrid.m_foodHealthColor; } else if ((double)item.m_shared.m_food < (double)item.m_shared.m_foodStamina / 2.0) { ((Graphic)element.m_food).color = inventoryGrid.m_foodStaminaColor; } else { ((Graphic)element.m_food).color = Color.white; } } else { ((Behaviour)element.m_food).enabled = false; } ((Behaviour)element.m_quality).enabled = item.m_shared.m_maxQuality > 1; if (item.m_shared.m_maxQuality > 1) { element.m_quality.text = item.m_quality.ToString(); } } private static void ShowNoItem(InventoryElement element) { ((Component)element.m_durability).gameObject.SetActive(false); ((Behaviour)element.m_icon).enabled = false; ((Behaviour)element.m_amount).enabled = false; ((Behaviour)element.m_quality).enabled = false; ((Behaviour)element.m_equiped).enabled = false; ((Behaviour)element.m_queued).enabled = false; ((Behaviour)element.m_noteleport).enabled = false; ((Behaviour)element.m_food).enabled = false; element.m_tooltip.m_text = ""; element.m_tooltip.m_topic = ""; } } [HarmonyPatch] public static class InventoryPatch { public static readonly ConditionalWeakTable<ItemData, Inventory> InventoryOfItem = new ConditionalWeakTable<ItemData, Inventory>(); private static readonly WeakReference<ItemData> LastRemovedItem = new WeakReference<ItemData>(null); private static bool allowItemSwap = true; [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData), typeof(int), typeof(int), typeof(int), typeof(bool) })] [HarmonyPrefix] [HarmonyPriority(100)] public static void AddItem1Prefix(Inventory __instance, ref bool __runOriginal, ItemData item, int amount, int x, int y, ref bool __result) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) if (__runOriginal && InterceptAddItem(__instance, item, amount, new Vector2i(x, y), out var successfulAdded)) { __result = successfulAdded; __runOriginal = false; } } [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })] [HarmonyPrefix] [HarmonyPriority(100)] public static void AddItem2Prefix(Inventory __instance, ref bool __runOriginal, ItemData item, ref bool __result) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (__runOriginal && InterceptAddItem(__instance, item, item.m_stack, new Vector2i(-1, -1), out var successfulAdded)) { __result = successfulAdded; __runOriginal = false; } } [HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(ItemData) })] [HarmonyPrefix] [HarmonyPriority(100)] public static void RemoveItemPrefix(Inventory __instance, ref bool __runOriginal, ref bool __result) { if (__runOriginal) { InventoryOwner owner = InventoryOwner.GetOwner(__instance); if (!owner.IgnoreInventory() && owner != null && owner.IsValid() && !owner.ZNetView.IsOwner()) { __result = false; __runOriginal = false; } } } [HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(ItemData) })] [HarmonyPostfix] public static void RemoveItemPostfix(Inventory __instance, ItemData item, ref bool __result) { if (__result) { LastRemovedItem.SetTarget(item); } else { LastRemovedItem.SetTarget(null); } } [HarmonyPatch(typeof(Inventory), "MoveAll")] [HarmonyPrefix] [HarmonyPriority(800)] public static void MoveAllPrefix() { allowItemSwap = false; } [HarmonyPatch(typeof(Inventory), "MoveAll")] [HarmonyPostfix] [HarmonyPriority(0)] public static void MoveAllPostfix() { allowItemSwap = true; } [HarmonyPatch(typeof(Inventory), "Changed")] [HarmonyPostfix] public static void AddItemPostfix(Inventory __instance) { foreach (Inventory inventory in __instance.GetInventories()) { AssignItemsOfInventory(inventory); } if (LastRemovedItem.TryGetTarget(out var target) && InventoryOwner.GetOwner(target)?.Inventory == __instance) { LastRemovedItem.SetTarget(null); } } [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData), typeof(int), typeof(int), typeof(int), typeof(bool) })] [HarmonyWrapSafe] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> RemoveLogging(IEnumerable<CodeInstruction> instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => CodeInstructionExtensions.Calls(i, AccessTools.Method(typeof(ZLog), "Log", (Type[])null, (Type[])null))), (string)null) }).SetInstruction(new CodeInstruction(OpCodes.Pop, (object)null)).Ins
BepInEx/plugins/MegingjordWeightDisplay.dll
Decompiled 2 weeks agousing System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using HarmonyLib; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace MegingjordWeightDisplay; [BepInPlugin("local.megingjordweightdisplay", "Megingjord Weight Display", "1.0.0")] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(Hud), "UpdateStatusEffects")] private static class WeightLabel { private static void Postfix(List<StatusEffect> __0, List<RectTransform> ___m_statusEffects) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)ObjectDB.instance == (Object)null) { return; } GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("BeltStrength"); ItemDrop val = (((Object)(object)itemPrefab == (Object)null) ? null : itemPrefab.GetComponent<ItemDrop>()); if ((Object)(object)val == (Object)null) { return; } StatusEffect equipStatusEffect = val.m_itemData.m_shared.m_equipStatusEffect; if ((Object)(object)equipStatusEffect == (Object)null) { return; } for (int i = 0; i < __0.Count && i < ___m_statusEffects.Count; i++) { StatusEffect val2 = __0[i]; if (!((Object)(object)val2 == (Object)null) && !val2.m_hidden && val2.NameHash() == equipStatusEffect.NameHash()) { RectTransform val3 = ___m_statusEffects[i]; Transform val4 = (((Object)(object)val3 == (Object)null) ? null : ((Transform)val3).Find("TimeText")); TMP_Text val5 = (((Object)(object)val4 == (Object)null) ? null : ((Component)val4).GetComponent<TMP_Text>()); if (!((Object)(object)val5 == (Object)null)) { val5.text = Mathf.CeilToInt(((Humanoid)localPlayer).GetInventory().GetTotalWeight()).ToString(CultureInfo.InvariantCulture) + "/" + Mathf.CeilToInt(localPlayer.GetMaxCarryWeight()).ToString(CultureInfo.InvariantCulture); ((Component)val5).gameObject.SetActive(true); } } } } } public const string PluginId = "local.megingjordweightdisplay"; private Harmony harmony; private void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown harmony = new Harmony("local.megingjordweightdisplay"); harmony.PatchAll(typeof(Plugin).Assembly); } private void OnDestroy() { if (harmony != null) { harmony.UnpatchSelf(); } } }
BepInEx/plugins/PatchedBetterNetworking.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using HarmonyLib; [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyTitle("PatchedBetterNetworking")] [assembly: AssemblyDescription("Conservative dedicated-server Valheim 1.0.15 networking port")] [assembly: AssemblyFileVersion("0.1.2.0")] [assembly: CompilationRelaxations(8)] [assembly: AssemblyVersion("0.1.2.0")] namespace PatchedBetterNetworking; internal static class PatchLogic { internal static List<CodeInstruction> PlayerLimit(IEnumerable<CodeInstruction> source, MethodInfo playerCount, MethodInfo replacement) { List<CodeInstruction> list = source.ToList(); int num = 0; for (int i = 1; i + 1 < list.Count; i++) { if (CodeInstructionExtensions.Calls(list[i - 1], playerCount) && IsInt(list[i], 10) && (list[i + 1].opcode == OpCodes.Blt || list[i + 1].opcode == OpCodes.Blt_S)) { list[i].opcode = OpCodes.Call; list[i].operand = replacement; num++; } } if (num != 1) { throw new InvalidOperationException("Unsupported RPC_PeerInfo: expected exactly one player-count comparison."); } return list; } internal static List<CodeInstruction> QueueBudget(IEnumerable<CodeInstruction> source, MethodInfo queueSize, MethodInfo replacement) { List<CodeInstruction> list = source.ToList(); int num = 0; int num2 = 0; if (list.Count((CodeInstruction i) => CodeInstructionExtensions.Calls(i, queueSize)) != 1) { throw new InvalidOperationException("Unsupported SendZDOs: queue size call changed."); } for (int num3 = 1; num3 + 2 < list.Count; num3++) { if (!IsInt(list[num3], 10240)) { continue; } bool flag = list[num3 - 1].opcode == OpCodes.Ldloc_0 && (list[num3 + 1].opcode == OpCodes.Ble || list[num3 + 1].opcode == OpCodes.Ble_S); bool flag2 = list[num3 + 1].opcode == OpCodes.Ldloc_0 && list[num3 + 2].opcode == OpCodes.Sub; if (flag || flag2) { list[num3].opcode = OpCodes.Call; list[num3].operand = replacement; if (flag) { num++; } if (flag2) { num2++; } } } if (num != 1 || num2 != 1) { throw new InvalidOperationException("Unsupported SendZDOs: expected one queue gate and one remaining-budget expression."); } return list; } internal static bool IsInt(CodeInstruction instruction, int value) { if (instruction.opcode == OpCodes.Ldc_I4 || instruction.opcode == OpCodes.Ldc_I4_S) { return Convert.ToInt32(instruction.operand) == value; } return false; } internal static int Bound(int value, int minimum, int maximum) { return Math.Max(minimum, Math.Min(maximum, value)); } } [BepInIncompatibility("com.github.dalayeth.Networkfix")] [BepInIncompatibility("Steel.ValheimMod")] [BepInPlugin("local.patchedbetternetworking", "Patched Better Networking", "0.1.2")] [BepInIncompatibility("CW_Jesse.BetterNetworking")] [BepInIncompatibility("org.bepinex.plugins.network")] [BepInIncompatibility("be.sebastienvercammen.valheim.netcompression")] public sealed class Plugin : BaseUnityPlugin { public const string Id = "local.patchedbetternetworking"; private Harmony harmony; private static ConfigEntry<int> playerLimit; private static ConfigEntry<int> queueBudget; private void Awake() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Expected O, but got Unknown //IL_0206: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Expected O, but got Unknown //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Expected O, but got Unknown ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Requires restart."); playerLimit = ((BaseUnityPlugin)this).Config.Bind<int>("Dedicated Server", "Player Limit", 10, new ConfigDescription("Maximum accepted players. Vanilla default is 10.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 127), new object[0])); queueBudget = ((BaseUnityPlugin)this).Config.Bind<int>("Networking", "ZDO Queue Budget Bytes", 10240, new ConfigDescription("ZDO admission budget; vanilla default is 10240. Larger values can increase latency on slow connections. Does not change transport compression, rate, queue reporting or reliability.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2048, 81920), new object[0])); if (!val.Value) { return; } try { MethodInfo methodInfo = AccessTools.Method(typeof(ZNet), "IsDedicated", Type.EmptyTypes, (Type[])null); byte[] array = ((methodInfo == null || methodInfo.GetMethodBody() == null) ? null : methodInfo.GetMethodBody().GetILAsByteArray()); if (array == null || array.Length != 2 || array[0] != 23 || array[1] != 42) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Patched Better Networking disabled: this build requires the dedicated server binary."); return; } if (((object)Version.CurrentVersion/*cast due to .constrained prefix*/).ToString() != "1.0.15") { throw new NotSupportedException("This build was reviewed for Valheim 1.0.15 only."); } MethodInfo methodInfo2 = AccessTools.Method(typeof(ZNet), "RPC_PeerInfo", new Type[2] { typeof(ZRpc), typeof(ZPackage) }, (Type[])null); Type nestedType = typeof(ZDOMan).GetNestedType("ZDOPeer", BindingFlags.NonPublic); MethodInfo methodInfo3 = ((nestedType == null) ? null : AccessTools.Method(typeof(ZDOMan), "SendZDOs", new Type[2] { nestedType, typeof(bool) }, (Type[])null)); if (methodInfo2 == null || methodInfo3 == null) { throw new MissingMethodException("Valheim networking patch targets changed."); } harmony = new Harmony("local.patchedbetternetworking"); harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "PatchPlayerLimit", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "PatchQueueBudget", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Patched Better Networking 0.1.2 installed: player limit=" + GetPlayerLimit() + ", ZDO queue budget=" + GetQueueBudget() + ". Vanilla transport, compression and send scheduling retained. Runtime pair testing pending.")); } catch (Exception ex) { if (harmony != null) { harmony.UnpatchSelf(); } ((BaseUnityPlugin)this).Logger.LogError((object)("Patched Better Networking disabled; its patches were removed: " + ex)); } } public static int GetPlayerLimit() { return PatchLogic.Bound(playerLimit.Value, 1, 127); } public static int GetQueueBudget() { return PatchLogic.Bound(queueBudget.Value, 2048, 81920); } private static IEnumerable<CodeInstruction> PatchPlayerLimit(IEnumerable<CodeInstruction> instructions) { return PatchLogic.PlayerLimit(instructions, AccessTools.Method(typeof(ZNet), "GetNrOfPlayers", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(Plugin), "GetPlayerLimit", (Type[])null, (Type[])null)); } private static IEnumerable<CodeInstruction> PatchQueueBudget(IEnumerable<CodeInstruction> instructions) { return PatchLogic.QueueBudget(instructions, AccessTools.Method(typeof(ISocket), "GetSendQueueSize", Type.EmptyTypes, (Type[])null), AccessTools.Method(typeof(Plugin), "GetQueueBudget", (Type[])null, (Type[])null)); } private void OnDestroy() { if (harmony != null) { harmony.UnpatchSelf(); } } }
BepInEx/plugins/PinRecipes.dll
Decompiled 2 weeks agousing System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace PinRecipes; [BepInPlugin("local.pinrecipes", "Pin Recipes", "0.1.2")] public sealed class Plugin : BaseUnityPlugin { [Serializable] public sealed class Pin { public string recipe; public int quality; public int variant; public bool upgrade; public bool upgrader; public string resource; public int resourceAmount; } [Serializable] public sealed class SavedPins { public List<Pin> entries = new List<Pin>(); } private sealed class ResourceSlot { public Requirement requirement; public TMP_Text amount; } private sealed class Card { public Pin pin; public Recipe recipe; public RectTransform rect; public TMP_Text amount; public GameObject remove; public readonly List<ResourceSlot> resources = new List<ResourceSlot>(); } [HarmonyPatch(typeof(InventoryGui), "UpdateRecipeList")] private static class RecipesChanged { private static void Postfix(InventoryGui __instance) { BindRows(__instance); } } [HarmonyPatch(typeof(InventoryGui), "SetupRequirement")] private static class RequirementChanged { private static void Postfix(Transform elementRoot, Requirement req, int quality, int craftMultiplier, bool __result) { InventoryGui instance = InventoryGui.instance; if ((Object)(object)Instance == (Object)null || (Object)(object)instance == (Object)null || Array.IndexOf(instance.m_recipeRequirementList, ((Component)elementRoot).gameObject) < 0) { return; } PinClick pinClick = ((Component)elementRoot).GetComponent<PinClick>(); if ((Object)(object)pinClick == (Object)null) { pinClick = ((Component)elementRoot).gameObject.AddComponent<PinClick>(); } pinClick.OnMiddle = null; if (!__result || req == null || (Object)(object)req.m_resItem == (Object)null) { return; } int amount = req.GetAmount(quality) * craftMultiplier; if (amount <= 0) { return; } Graphic component = ((Component)elementRoot).GetComponent<Graphic>(); if ((Object)(object)component != (Object)null) { component.raycastTarget = true; } pinClick.OnMiddle = delegate { if ((Object)(object)Instance != (Object)null) { Instance.AddResource(req, amount); } }; } } [HarmonyPatch(typeof(InventoryGui), "HideRequirement")] private static class RequirementHidden { private static void Postfix(Transform elementRoot) { PinClick component = ((Component)elementRoot).GetComponent<PinClick>(); if ((Object)(object)component != (Object)null) { component.OnMiddle = null; } } } public const string Id = "local.pinrecipes"; internal static Plugin Instance; private static readonly FieldInfo Available = AccessTools.Field(typeof(InventoryGui), "m_availableRecipes"); private static readonly FieldInfo Selected = AccessTools.Field(typeof(InventoryGui), "m_selectedRecipe"); private static readonly FieldInfo Variant = AccessTools.Field(typeof(InventoryGui), "m_selectedVariant"); private ConfigEntry<int> maxPins; private Harmony harmony; private Player owner; private InventoryGui gui; private RectTransform root; private readonly List<Pin> pins = new List<Pin>(); private readonly List<Card> cards = new List<Card>(); private float nextRefresh; private bool dirty = true; private bool failed; private void Awake() { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown Instance = this; maxPins = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxPins", 3, new ConfigDescription("Maximum number of pinned recipes or individual resources. New pins replace the oldest when full. Zero disables pins.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 30), new object[0])); maxPins.SettingChanged += OnLimitChanged; harmony = new Harmony("local.pinrecipes"); harmony.PatchAll(typeof(Plugin).Assembly); } private void OnLimitChanged(object sender, EventArgs args) { Trim(); Save(); dirty = true; } private void Trim() { while (pins.Count > maxPins.Value) { pins.RemoveAt(0); } } private void Save() { if ((Object)(object)owner != (Object)null) { owner.m_customData["local.pinrecipes"] = JsonUtility.ToJson((object)new SavedPins { entries = new List<Pin>(pins) }); } } private void Load(Player player) { ClearCards(); pins.Clear(); owner = player; if ((Object)(object)player != (Object)null && player.m_customData.TryGetValue("local.pinrecipes", out var value)) { try { SavedPins savedPins = JsonUtility.FromJson<SavedPins>(value); if (savedPins != null && savedPins.entries != null) { foreach (Pin entry in savedPins.entries) { if (entry != null && ((!string.IsNullOrEmpty(entry.resource) && entry.resourceAmount > 0) || (string.IsNullOrEmpty(entry.resource) && !string.IsNullOrEmpty(entry.recipe) && entry.quality > 0 && entry.variant >= 0))) { pins.Add(entry); } } } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not read saved pins: " + ex.Message)); } } Trim(); dirty = true; } private static T Property<T>(object pair, string name) { return (T)pair.GetType().GetProperty(name).GetValue(pair, null); } internal void Add(object pair, InventoryGui source) { if (failed || pair == null || !InventoryGui.IsVisible() || (Object)(object)Player.m_localPlayer == (Object)null || maxPins.Value == 0) { return; } if ((Object)(object)owner != (Object)(object)Player.m_localPlayer) { Load(Player.m_localPlayer); } Recipe val = Property<Recipe>(pair, "Recipe"); ItemData val2 = Property<ItemData>(pair, "ItemData"); if ((Object)(object)val == (Object)null || (Object)(object)val.m_item == (Object)null) { return; } int num = ((val2 == null) ? 1 : (val2.m_quality + 1)); if (num > val.m_item.m_itemData.m_shared.m_maxQuality) { return; } int num2 = val2?.m_variant ?? 0; CraftingStation currentCraftingStation = owner.GetCurrentCraftingStation(); bool flag = (Object)(object)currentCraftingStation != (Object)null && currentCraftingStation.m_upgrader; object value = Selected.GetValue(source); if (val2 == null && (Object)(object)Property<Recipe>(value, "Recipe") == (Object)(object)val) { num2 = (int)Variant.GetValue(source); } foreach (Pin pin in pins) { if (string.IsNullOrEmpty(pin.resource) && pin.recipe == ((Object)val).name && pin.quality == num && pin.variant == num2 && pin.upgrade == (val2 != null) && pin.upgrader == flag) { return; } } pins.Add(new Pin { recipe = ((Object)val).name, quality = num, variant = num2, upgrade = (val2 != null), upgrader = flag }); Trim(); Save(); dirty = true; } private void AddResource(Requirement requirement, int amount) { if (failed || requirement == null || (Object)(object)requirement.m_resItem == (Object)null || amount <= 0 || !InventoryGui.IsVisible() || (Object)(object)Player.m_localPlayer == (Object)null || maxPins.Value == 0) { return; } if ((Object)(object)owner != (Object)(object)Player.m_localPlayer) { Load(Player.m_localPlayer); } string name = ((Object)requirement.m_resItem).name; foreach (Pin pin in pins) { if (pin.resource == name && pin.resourceAmount == amount) { return; } } pins.Add(new Pin { resource = name, resourceAmount = amount, quality = 1 }); Trim(); Save(); dirty = true; } private void Remove(Pin pin) { pins.Remove(pin); Save(); dirty = true; } private void LateUpdate() { //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013e: 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) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0382: Unknown result type (might be due to invalid IL or missing references) //IL_0389: Expected O, but got Unknown //IL_039b: Unknown result type (might be due to invalid IL or missing references) //IL_03a0: Unknown result type (might be due to invalid IL or missing references) //IL_03a5: Unknown result type (might be due to invalid IL or missing references) //IL_03ec: Unknown result type (might be due to invalid IL or missing references) //IL_03f3: Unknown result type (might be due to invalid IL or missing references) //IL_0413: Unknown result type (might be due to invalid IL or missing references) //IL_0424: Unknown result type (might be due to invalid IL or missing references) //IL_0429: Unknown result type (might be due to invalid IL or missing references) //IL_04bf: Unknown result type (might be due to invalid IL or missing references) //IL_04d5: Unknown result type (might be due to invalid IL or missing references) //IL_04e8: Unknown result type (might be due to invalid IL or missing references) //IL_0504: Unknown result type (might be due to invalid IL or missing references) //IL_0484: Unknown result type (might be due to invalid IL or missing references) if (failed) { return; } try { if ((Object)(object)owner != (Object)(object)Player.m_localPlayer) { Load(Player.m_localPlayer); } if ((Object)(object)owner == (Object)null || (Object)(object)InventoryGui.instance == (Object)null || (Object)(object)Hud.instance == (Object)null) { if ((Object)(object)root != (Object)null) { ((Component)root).gameObject.SetActive(false); } return; } if ((Object)(object)gui != (Object)(object)InventoryGui.instance || (Object)(object)root == (Object)null) { ClearCards(); if ((Object)(object)root != (Object)null) { Object.Destroy((Object)(object)((Component)root).gameObject); } gui = InventoryGui.instance; Canvas componentInParent = ((Component)gui.m_playerGrid).GetComponentInParent<Canvas>(); if ((Object)(object)componentInParent == (Object)null) { return; } root = NewRect("PinRecipes", ((Component)componentInParent.rootCanvas).transform); Place(root, -24f, 144f, 0f, 0f); RectTransform obj = root; RectTransform obj2 = root; Vector2 val = (root.pivot = new Vector2(1f, 0f)); Vector2 anchorMin = (obj2.anchorMax = val); obj.anchorMin = anchorMin; AttachSelected(((Component)gui.m_craftButton).gameObject); AttachSelected(((Component)gui.m_recipeIcon).gameObject); BindRows(gui); dirty = true; } ((Component)root).gameObject.SetActive(!((Character)owner).IsDead() && Hud.instance.m_rootObject.activeInHierarchy && !Minimap.IsOpen()); bool active = InventoryGui.IsVisible(); foreach (Card card in cards) { card.remove.SetActive(active); } if (!dirty && Time.unscaledTime < nextRefresh) { return; } nextRefresh = Time.unscaledTime + 0.2f; if (dirty) { ClearCards(); if ((Object)(object)ObjectDB.instance == (Object)null || (Object)(object)Minimap.instance == (Object)null) { return; } foreach (Pin pin in pins) { if (!string.IsNullOrEmpty(pin.resource)) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(pin.resource); ItemDrop val4 = (((Object)(object)itemPrefab == (Object)null) ? null : itemPrefab.GetComponent<ItemDrop>()); if ((Object)(object)val4 != (Object)null) { cards.Add(CreateCard(pin, null, val4)); } } else { Recipe val5 = ObjectDB.instance.m_recipes.Find((Recipe r) => (Object)(object)r != (Object)null && ((Object)r).name == pin.recipe); if ((Object)(object)val5 != (Object)null && (Object)(object)val5.m_item != (Object)null) { cards.Add(CreateCard(pin, val5)); } } } dirty = false; } RectTransform val6 = (RectTransform)((Transform)root).parent; Rect rect = ((RectTransform)gui.m_recipeRequirementList[0].transform).rect; float num = ((Rect)(ref rect)).width; if (num <= 0f) { num = gui.m_playerGrid.m_elementSpace; } float bottom = 150f; float scale = 1f; MatchQuickSlots(val6, num, ref bottom, ref scale); ((Transform)root).localScale = Vector3.one * scale; root.anchoredPosition = new Vector2(-24f, bottom - 6f * scale); Rect rect2 = val6.rect; float num2 = Mathf.Max(1f, (((Rect)(ref rect2)).width - 48f) / scale); float num3 = 0f; float num4 = 0f; float num5 = 0f; foreach (Card card2 in cards) { if (num3 > 0f && num3 + card2.rect.sizeDelta.x > num2) { num3 = 0f; num4 += num5 + 12f; num5 = 0f; } card2.rect.pivot = new Vector2(1f, 0f); card2.rect.anchoredPosition = new Vector2(0f - num3, num4); num3 += card2.rect.sizeDelta.x + 16f; num5 = Mathf.Max(num5, card2.rect.sizeDelta.y); card2.remove.SetActive(active); Refresh(card2); } ((Transform)root).SetAsLastSibling(); } catch (Exception ex) { failed = true; if ((Object)(object)root != (Object)null) { ((Component)root).gameObject.SetActive(false); } ((BaseUnityPlugin)this).Logger.LogError((object)("Pin Recipes disabled after a UI compatibility error: " + ex)); } } private static void MatchQuickSlots(RectTransform parent, float slotSize, ref float bottom, ref float scale) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) Transform val = Hud.instance.m_rootObject.transform.Find("QuickSlotsHotkeyBar"); if ((Object)(object)val == (Object)null) { return; } HotkeyBar component = ((Component)val).GetComponent<HotkeyBar>(); if ((Object)(object)component == (Object)null) { return; } IList list = (IList)AccessTools.Field(typeof(HotkeyBar), "m_elements").GetValue(component); if (list == null || list.Count == 0) { return; } object obj = list[0]; GameObject val2 = (GameObject)AccessTools.Field(obj.GetType(), "m_go").GetValue(obj); if ((Object)(object)val2 == (Object)null) { return; } Transform transform = val2.transform; RectTransform val3 = (RectTransform)(object)((transform is RectTransform) ? transform : null); if (!((Object)(object)val3 == (Object)null)) { Vector3[] array = (Vector3[])(object)new Vector3[4]; val3.GetWorldCorners(array); Vector3 val4 = ((Transform)parent).InverseTransformPoint(array[0]); float num = ((Transform)parent).InverseTransformPoint(array[1]).y - val4.y; if (!(num <= 0f) && !(slotSize <= 0f)) { float y = val4.y; Rect rect = parent.rect; bottom = y - ((Rect)(ref rect)).yMin; scale = num / slotSize; } } } private void AttachSelected(GameObject target) { PinClick pinClick = target.GetComponent<PinClick>(); if ((Object)(object)pinClick == (Object)null) { pinClick = target.AddComponent<PinClick>(); } pinClick.OnMiddle = delegate { Add(Selected.GetValue(gui), gui); }; } private static void BindRows(InventoryGui source) { if ((Object)(object)Instance == (Object)null) { return; } foreach (object item in (IEnumerable)Available.GetValue(source)) { GameObject val = Property<GameObject>(item, "InterfaceElement"); if ((Object)(object)val == (Object)null) { continue; } PinClick pinClick = val.GetComponent<PinClick>(); if ((Object)(object)pinClick == (Object)null) { pinClick = val.AddComponent<PinClick>(); } object captured = item; pinClick.OnMiddle = delegate { if ((Object)(object)Instance != (Object)null) { Instance.Add(captured, source); } }; } } private Card CreateCard(Pin pin, Recipe recipe, ItemDrop resource = null) { //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0426: Unknown result type (might be due to invalid IL or missing references) //IL_042d: Expected O, but got Unknown //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: 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_01f1: 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_0684: Unknown result type (might be due to invalid IL or missing references) //IL_06a4: Unknown result type (might be due to invalid IL or missing references) //IL_06a9: Unknown result type (might be due to invalid IL or missing references) //IL_06aa: Unknown result type (might be due to invalid IL or missing references) //IL_06b1: Unknown result type (might be due to invalid IL or missing references) //IL_06c4: Unknown result type (might be due to invalid IL or missing references) //IL_06d0: Unknown result type (might be due to invalid IL or missing references) //IL_06e6: Unknown result type (might be due to invalid IL or missing references) //IL_0713: Unknown result type (might be due to invalid IL or missing references) //IL_0721: Unknown result type (might be due to invalid IL or missing references) //IL_0737: Unknown result type (might be due to invalid IL or missing references) //IL_0741: Expected O, but got Unknown //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_0394: Unknown result type (might be due to invalid IL or missing references) //IL_039b: Expected O, but got Unknown //IL_039d: Unknown result type (might be due to invalid IL or missing references) //IL_03a2: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_03f3: Unknown result type (might be due to invalid IL or missing references) //IL_04d2: Unknown result type (might be due to invalid IL or missing references) //IL_04e7: Expected O, but got Unknown //IL_0549: Unknown result type (might be due to invalid IL or missing references) //IL_057c: Unknown result type (might be due to invalid IL or missing references) Card card = new Card(); card.pin = pin; card.recipe = recipe; Card card2 = card; card2.rect = NewRect("PinnedRecipe", (Transform)(object)root); GameObject val = gui.m_recipeRequirementList[0]; Image val2 = val.GetComponent<Image>(); if ((Object)(object)val2 == (Object)null) { Image[] componentsInChildren = val.GetComponentsInChildren<Image>(true); foreach (Image val3 in componentsInChildren) { if (((Object)((Component)val3).transform).name != "res_icon" && (Object)(object)val3.sprite != (Object)null) { val2 = val3; break; } } } if ((Object)(object)val2 == (Object)null) { throw new InvalidOperationException("Native requirement slot has no background Image."); } Image val4 = ((Component)card2.rect).gameObject.AddComponent<Image>(); CopyImage(val2, val4); ((Graphic)val4).raycastTarget = false; Rect rect = ((RectTransform)val.transform).rect; float num = ((Rect)(ref rect)).width; if (num <= 0f) { num = gui.m_playerGrid.m_elementSpace; } float num2 = 6f; if ((Object)(object)resource == (Object)null) { GameObject val5 = Object.Instantiate<GameObject>(gui.m_playerGrid.m_elementPrefab, (Transform)(object)card2.rect, false); val5.SetActive(false); InventoryElement component = val5.GetComponent<InventoryElement>(); if ((Object)(object)component == (Object)null) { throw new InvalidOperationException("Native inventory slot has no InventoryElement."); } DisableInteraction(val5); Image[] componentsInChildren2 = val5.GetComponentsInChildren<Image>(true); foreach (Image val6 in componentsInChildren2) { if ((Object)(object)val6 != (Object)(object)component.m_icon) { ((Behaviour)val6).enabled = false; } } RectTransform val7 = NewRect("SlotBackground", val5.transform); val7.anchorMin = Vector2.zero; val7.anchorMax = Vector2.one; Vector2 offsetMin = (val7.offsetMax = Vector2.zero); val7.offsetMin = offsetMin; Image val8 = ((Component)val7).gameObject.AddComponent<Image>(); CopyImage(val2, val8); ((Graphic)val8).raycastTarget = false; ((Transform)val7).SetAsFirstSibling(); Hide((Component)(object)component.m_equiped); Hide((Component)(object)component.m_queued); Hide((Component)(object)component.m_noteleport); Hide((Component)(object)component.m_food); Hide((Component)(object)component.m_durability); Hide((Component)(object)component.m_dropFocus); if ((Object)(object)component.m_selected != (Object)null) { component.m_selected.SetActive(false); } Transform val9 = val5.transform.Find("binding"); if ((Object)(object)val9 != (Object)null) { ((Component)val9).gameObject.SetActive(false); } ItemData val10 = recipe.m_item.m_itemData.Clone(); val10.m_variant = Mathf.Clamp(pin.variant, 0, val10.m_shared.m_icons.Length - 1); component.m_icon.sprite = val10.GetIcon(); ((Graphic)component.m_icon).color = Color.white; ((Component)component.m_icon).gameObject.SetActive(true); component.m_quality.text = pin.quality.ToString(); ((Component)component.m_quality).gameObject.SetActive(pin.upgrade); component.m_amount.text = ""; ((Component)component.m_amount).gameObject.SetActive(true); card2.amount = component.m_amount; RectTransform val11 = (RectTransform)val5.transform; Rect rect2 = val11.rect; float num3 = ((Rect)(ref rect2)).width; if (num3 <= 0f) { num3 = gui.m_playerGrid.m_elementSpace; } Place(val11, 6f, 6f, num3, num3); ((Transform)val11).localScale = Vector3.one * (num / Mathf.Max(1f, num3)); val5.SetActive(true); num2 += num + 12f; } Requirement[] array2; if (!((Object)(object)resource == (Object)null)) { Requirement[] array = (Requirement[])(object)new Requirement[1]; Requirement val12 = new Requirement(); val12.m_resItem = resource; val12.m_amount = pin.resourceAmount; array[0] = val12; array2 = array; } else { array2 = recipe.m_resources; } Requirement[] array3 = array2; Requirement[] array4 = array3; foreach (Requirement val13 in array4) { if (!((Object)(object)val13.m_resItem == (Object)null) && val13.GetAmount(pin.quality) > 0 && val13.m_upgraderResource == pin.upgrader) { GameObject val14 = Object.Instantiate<GameObject>(val, (Transform)(object)card2.rect, false); val14.SetActive(false); DisableInteraction(val14); Place((RectTransform)val14.transform, num2, 6f, num, num); Image component2 = ((Component)val14.transform.Find("res_icon")).GetComponent<Image>(); TMP_Text component3 = ((Component)val14.transform.Find("res_name")).GetComponent<TMP_Text>(); TMP_Text component4 = ((Component)val14.transform.Find("res_amount")).GetComponent<TMP_Text>(); component2.sprite = val13.m_resItem.m_itemData.GetIcon(); ((Graphic)component2).color = Color.white; component3.text = Localization.instance.Localize(val13.m_resItem.m_itemData.m_shared.m_name); ((Graphic)component3).color = Color.white; ((Component)component2).gameObject.SetActive(true); ((Component)component3).gameObject.SetActive(true); ((Component)component4).gameObject.SetActive(true); val14.SetActive(true); card2.resources.Add(new ResourceSlot { requirement = val13, amount = component4 }); num2 += num + 4f; } } Place(card2.rect, 0f, 0f, num2 - 4f + 6f, num + 12f); Transform val15 = Minimap.instance.m_pinPrefab.transform.Find("Checked"); if ((Object)(object)val15 == (Object)null) { throw new InvalidOperationException("Native map pin has no Checked icon."); } RectTransform val16 = NewRect("RemovePin", (Transform)(object)card2.rect); Image val17 = ((Component)val16).gameObject.AddComponent<Image>(); CopyImage(((Component)val15).GetComponent<Image>(), val17); ((Graphic)val17).color = Color.red; ((Graphic)val17).raycastTarget = true; Vector2 anchorMin = (val16.anchorMax = new Vector2(0f, 1f)); val16.anchorMin = anchorMin; val16.pivot = new Vector2(0.5f, 0.5f); val16.anchoredPosition = Vector2.zero; val16.sizeDelta = new Vector2(28f, 28f); Button val19 = ((Component)val16).gameObject.AddComponent<Button>(); ((Selectable)val19).targetGraphic = (Graphic)(object)val17; ((Selectable)val19).transition = (Transition)0; Navigation navigation = default(Navigation); ((Navigation)(ref navigation)).mode = (Mode)0; ((Selectable)val19).navigation = navigation; ((UnityEvent)val19.onClick).AddListener((UnityAction)delegate { Remove(pin); }); card2.remove = ((Component)val16).gameObject; return card2; } private void Refresh(Card card) { //IL_00a0: 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_03d8: Unknown result type (might be due to invalid IL or missing references) Inventory inventory = ((Humanoid)owner).GetInventory(); Dictionary<string, int> dictionary = new Dictionary<string, int>(); foreach (ResourceSlot resource in card.resources) { string name = resource.requirement.m_resItem.m_itemData.m_shared.m_name; int amount = resource.requirement.GetAmount(card.pin.quality); int num = inventory.CountItems(name, -1, true); resource.amount.text = num + "/" + amount; ((Graphic)resource.amount).color = ((num >= amount) ? Color.white : Color.red); dictionary.TryGetValue(name, out var value); dictionary[name] = value + amount; } if (!string.IsNullOrEmpty(card.pin.resource)) { return; } long num2 = ((dictionary.Count != 0) ? int.MaxValue : 0); if (card.recipe.m_requireOnlyOneIngredient) { num2 = 0L; HashSet<string> hashSet = new HashSet<string>(); foreach (ResourceSlot resource2 in card.resources) { string name2 = resource2.requirement.m_resItem.m_itemData.m_shared.m_name; if (!hashSet.Add(name2)) { continue; } int amount2 = resource2.requirement.GetAmount(card.pin.quality); Dictionary<int, int> dictionary2 = new Dictionary<int, int>(); foreach (ItemData allItem in inventory.GetAllItems()) { if (!(allItem.m_shared.m_name != name2) && allItem.m_worldLevel >= Game.m_worldLevel) { dictionary2.TryGetValue(allItem.m_quality, out var value2); dictionary2[allItem.m_quality] = value2 + allItem.m_stack; } } foreach (KeyValuePair<int, int> item in dictionary2) { int num3 = (card.pin.upgrade ? 1 : (card.recipe.m_amount + Mathf.CeilToInt((float)((item.Key - 1) * card.recipe.m_amount) * card.recipe.m_qualityResultAmountMultiplier) + resource2.requirement.m_extraAmountOnlyOneIngredient)); num2 += (long)(item.Value / amount2) * (long)num3; } } } else { foreach (KeyValuePair<string, int> item2 in dictionary) { num2 = Math.Min(num2, inventory.CountItems(item2.Key, -1, true) / item2.Value); } if (!card.pin.upgrade) { num2 *= card.recipe.m_amount; } } if (card.pin.upgrade) { int num4 = 0; foreach (ItemData allItem2 in inventory.GetAllItems()) { if (allItem2.m_shared.m_name == card.recipe.m_item.m_itemData.m_shared.m_name && allItem2.m_quality == card.pin.quality - 1) { num4++; } } num2 = Math.Min(num2, num4); } card.amount.text = ((num2 > 1) ? num2.ToString() : ""); ((Graphic)card.amount).color = Color.white; } private static RectTransform NewRect(string name, Transform parent) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) RectTransform component = new GameObject(name, new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>(); ((Transform)component).SetParent(parent, false); return component; } private static void Hide(Component component) { if ((Object)(object)component != (Object)null) { component.gameObject.SetActive(false); } } private static void Place(RectTransform rect, float x, float y, float width, float height) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0017: 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_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) Vector2 val = (rect.pivot = Vector2.zero); Vector2 anchorMin = (rect.anchorMax = val); rect.anchorMin = anchorMin; rect.anchoredPosition = new Vector2(x, y); rect.sizeDelta = new Vector2(width, height); ((Transform)rect).localScale = Vector3.one; ((Transform)rect).localRotation = Quaternion.identity; } private static void CopyImage(Image source, Image target) { //IL_000e: 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) target.sprite = source.sprite; target.type = source.type; ((Graphic)target).color = ((Graphic)source).color; ((Graphic)target).material = ((Graphic)source).material; target.pixelsPerUnitMultiplier = source.pixelsPerUnitMultiplier; } private static void DisableInteraction(GameObject clone) { MonoBehaviour[] componentsInChildren = clone.GetComponentsInChildren<MonoBehaviour>(true); foreach (MonoBehaviour val in componentsInChildren) { if (!(val is Graphic) && !(val is BaseMeshEffect)) { ((Behaviour)val).enabled = false; } } Graphic[] componentsInChildren2 = clone.GetComponentsInChildren<Graphic>(true); foreach (Graphic val2 in componentsInChildren2) { val2.raycastTarget = false; } } private void ClearCards() { if ((Object)(object)root != (Object)null) { for (int num = ((Transform)root).childCount - 1; num >= 0; num--) { GameObject gameObject = ((Component)((Transform)root).GetChild(num)).gameObject; gameObject.SetActive(false); Object.Destroy((Object)(object)gameObject); } } cards.Clear(); } private void OnDestroy() { maxPins.SettingChanged -= OnLimitChanged; if (harmony != null) { harmony.UnpatchSelf(); } if ((Object)(object)root != (Object)null) { Object.Destroy((Object)(object)((Component)root).gameObject); } Instance = null; } } public sealed class PinClick : MonoBehaviour, IPointerClickHandler, IEventSystemHandler { internal Action OnMiddle; public void OnPointerClick(PointerEventData eventData) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)eventData.button == 2 && (Object)(object)Plugin.Instance != (Object)null && OnMiddle != null) { OnMiddle(); } } }
BepInEx/plugins/QuickRepair.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace QuickRepair; [BepInPlugin("local.quickrepair", "Quick Repair", "1.0.1")] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(InventoryGui), "Show")] private static class StartHold { private static void Postfix(Container __0) { pendingStation = null; holdTime = 0f; repaired = false; Player localPlayer = Player.m_localPlayer; if ((Object)(object)__0 == (Object)null && (Object)(object)localPlayer != (Object)null && UseHeld()) { CraftingStation currentCraftingStation = localPlayer.GetCurrentCraftingStation(); if (!IsExcluded(currentCraftingStation)) { pendingStation = currentCraftingStation; } } } } [HarmonyPatch(typeof(InventoryGui), "WaitForStack")] private static class WaitForRepair { private static void Postfix(ref bool __result) { __result = __result || (Object)(object)pendingStation != (Object)null; } } [HarmonyPatch(typeof(InventoryGui), "Hide")] private static class StopHold { private static void Postfix() { pendingStation = null; } } [HarmonyPatch(typeof(InventoryGui), "UpdateContainer")] private static class UpdateHold { private static void Postfix(InventoryGui __instance, Player __0, Container ___m_currentContainer, Animator ___m_animator, float ___m_containerHoldPlaceStackDelay, float ___m_containerHoldExitDelay) { if ((Object)(object)pendingStation == (Object)null) { return; } if ((Object)(object)__0 == (Object)null || (Object)(object)__0 != (Object)(object)Player.m_localPlayer || (Object)(object)___m_currentContainer != (Object)null || !___m_animator.GetBool("visible") || (Object)(object)__0.GetCurrentCraftingStation() != (Object)(object)pendingStation || IsExcluded(pendingStation) || !pendingStation.InUseDistance((Humanoid)(object)__0) || !UseHeld()) { pendingStation = null; return; } holdTime += Time.deltaTime; if (!repaired && holdTime > ___m_containerHoldPlaceStackDelay) { repaired = true; if (!pendingStation.CheckUsable(__0, true)) { pendingStation = null; } else { RepairAll(__instance, __0); } } else if (repaired && holdTime > ___m_containerHoldPlaceStackDelay + ___m_containerHoldExitDelay) { __instance.Hide(); } } } [HarmonyPatch(typeof(CraftingStation), "GetHoverText")] private static class HoldHint { private static void Postfix(CraftingStation __instance, ref string __result) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && !IsExcluded(__instance) && __instance.InUseDistance((Humanoid)(object)localPlayer)) { __result = __result.TrimEnd() + " (Hold to repair)"; } } } public const string PluginId = "local.quickrepair"; private Harmony harmony; private static ConfigEntry<string> excludedStations; private static string parsedExclusions; private static readonly HashSet<string> exclusionNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private static CraftingStation pendingStation; private static float holdTime; private static bool repaired; private static readonly Func<bool> UseHeld = AccessTools.MethodDelegate<Func<bool>>(AccessTools.Method(typeof(InventoryGui), "UseButtonHeld", (Type[])null, (Type[])null), (object)null, true); private static readonly Func<InventoryGui, ItemData, bool> CanRepair = AccessTools.MethodDelegate<Func<InventoryGui, ItemData, bool>>(AccessTools.Method(typeof(InventoryGui), "CanRepair", (Type[])null, (Type[])null), (object)null, true); private static readonly Action<InventoryGui> RepairOne = AccessTools.MethodDelegate<Action<InventoryGui>>(AccessTools.Method(typeof(InventoryGui), "RepairOneItem", (Type[])null, (Type[])null), (object)null, true); private static bool IsExcluded(CraftingStation station) { if ((Object)(object)station == (Object)null) { return true; } string value = excludedStations.Value; if (parsedExclusions != value) { exclusionNames.Clear(); string[] array = value.Split(','); foreach (string text in array) { string text2 = text.Trim(); if (text2.Length != 0) { exclusionNames.Add(text2); } } parsedExclusions = value; } string text3 = ((Object)((Component)station).gameObject).name; if (text3.EndsWith("(Clone)", StringComparison.Ordinal)) { text3 = text3.Substring(0, text3.Length - "(Clone)".Length).TrimEnd(); } if (!exclusionNames.Contains(text3)) { return exclusionNames.Contains(station.m_name); } return true; } private void Awake() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown excludedStations = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ExcludedStations", "piece_cauldron,piece_preptable,piece_MeadCauldron,piece_cookingstation,piece_cookingstation_iron,piece_oven", "Comma-separated station prefab names or internal localization keys. Case-insensitive; whitespace is ignored. Excluded stations keep normal interaction and show no repair hint. Clear the list to allow all stations. Restart after editing the config file."); harmony = new Harmony("local.quickrepair"); harmony.PatchAll(typeof(Plugin).Assembly); } private void OnDestroy() { pendingStation = null; if (harmony != null) { harmony.UnpatchSelf(); } } private static void RepairAll(InventoryGui gui, Player player) { List<ItemData> list = new List<ItemData>(); ((Humanoid)player).GetInventory().GetWornItems(list); int num = 0; for (int i = 0; i < list.Count; i++) { ItemData val = null; foreach (ItemData item in list) { if (item.m_durability < item.GetMaxDurability() && CanRepair(gui, item)) { val = item; break; } } if (val == null) { break; } float durability = val.m_durability; RepairOne(gui); if (val.m_durability <= durability) { break; } num++; } ((Character)player).Message((MessageType)2, (num == 0) ? "No items to repair at this station" : ("Repaired " + num + ((num == 1) ? " item" : " items")), 0, (Sprite)null, false); } }
BepInEx/plugins/RestConfiguration.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace RestConfiguration; [BepInPlugin("local.restconfiguration", "Rest Configuration", "0.1.0")] public sealed class Plugin : BaseUnityPlugin { private sealed class Peer { internal ZNetPeer Net; internal bool Hello; internal int Ack = -1; internal float Deadline; } [HarmonyPatch(typeof(SE_Cozy), "UpdateStatusEffect")] private static class RestDelayPatch { [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { int count = 0; FieldInfo field = AccessTools.Field(typeof(SE_Cozy), "m_delay"); foreach (CodeInstruction source in instructions) { CodeInstruction instruction = new CodeInstruction(source); if (instruction.opcode == OpCodes.Ldfld && object.Equals(instruction.operand, field)) { instruction.opcode = OpCodes.Call; instruction.operand = AccessTools.Method(typeof(Plugin), "Delay", (Type[])null, (Type[])null); count++; } yield return instruction; } if (count != 1) { throw new InvalidOperationException("Resting delay field read changed."); } } } [HarmonyPatch(typeof(SE_Rested), "GetNearbyComfortPieces")] private static class ComfortRangePatch { [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { int count = 0; foreach (CodeInstruction source in instructions) { CodeInstruction instruction = new CodeInstruction(source); if (instruction.opcode == OpCodes.Ldc_R4 && object.Equals(instruction.operand, 10f)) { instruction.opcode = OpCodes.Call; instruction.operand = AccessTools.Method(typeof(Plugin), "Radius", (Type[])null, (Type[])null); count++; } yield return instruction; } if (count != 1) { throw new InvalidOperationException("Comfort radius constant changed."); } } } [HarmonyPatch(typeof(StatusEffect), "UpdateStatusEffect")] private static class RestedTimerPatch { [HarmonyPrefix] private static void Prefix(StatusEffect __instance, Character ___m_character, float ___m_time, out float __state) { __state = -1f; if ((Object)(object)instance != (Object)null && instance.pauseTimer && __instance is SE_Rested && ___m_character is Player && ___m_character.GetSEMan().HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Resting"))) { __state = ___m_time; } } [HarmonyPostfix] private static void Postfix(ref float ___m_time, float __state) { if (__state >= 0f) { ___m_time = __state; } } } public const string PluginId = "local.restconfiguration"; private const string RpcName = "RestConfiguration_Config_v1"; private const int Protocol = 1; private const float GraceSeconds = 30f; private static Plugin instance; private readonly Dictionary<ZRpc, Peer> peers = new Dictionary<ZRpc, Peer>(); private ConfigEntry<bool> pauseSetting; private ConfigEntry<float> delaySetting; private ConfigEntry<float> rangeSetting; private Harmony harmony; private ZNet session; private ZRpc serverRpc; private bool pauseTimer; private bool received; private bool wasServer; private float restDelay = 20f; private float comfortRange = 1f; private float nextTick; private float nextHello; private float connectedAt; private int revision; private FileSystemWatcher configWatcher; private bool configReloadPending; private float configReloadAfter; private int configReloadRetries; private static bool ValidDelay(float value) { if (value >= 0f) { return value <= 30f; } return false; } private static bool ValidRange(float value) { if (value >= 1f) { return value <= 5f; } return false; } private void Awake() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Expected O, but got Unknown instance = this; delaySetting = ((BaseUnityPlugin)this).Config.Bind<float>("Server", "RestingSeconds", 20f, new ConfigDescription("Continuous seconds Resting before receiving Rested. Server enforced; updates live.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), new object[0])); rangeSetting = ((BaseUnityPlugin)this).Config.Bind<float>("Server", "ComfortRangeMultiplier", 1f, new ConfigDescription("Comfort furniture search radius multiplier (vanilla radius: 10 metres). Server enforced; updates live.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), new object[0])); pauseSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("Server", "PauseRestedWhileResting", false, "Pause the Rested countdown whenever Resting, including at lower comfort. Server enforced; updates live."); ((BaseUnityPlugin)this).Config.Save(); harmony = new Harmony("local.restconfiguration"); try { harmony.PatchAll(typeof(Plugin).Assembly); } catch { harmony.UnpatchSelf(); instance = null; throw; } StartConfigWatcher(); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Rest Configuration loaded. Server config: " + ((BaseUnityPlugin)this).Config.ConfigFilePath)); } private void Update() { if (Time.realtimeSinceStartup < nextTick) { return; } nextTick = Time.realtimeSinceStartup + 0.5f; try { ReloadConfig(); ZNet val = ZNet.instance; bool flag = (Object)(object)val != (Object)null && val.IsServer(); if ((Object)(object)session != (Object)(object)val || wasServer != flag) { ClearNetwork(); session = val; wasServer = flag; SetEffective(pause: false, 20f, 1f); } if ((Object)(object)val != (Object)null) { if (flag) { ServerTick(val); } else { ClientTick(val); } } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Rest Configuration update: " + ex)); } } private void ReloadConfig() { if (!configReloadPending || Time.realtimeSinceStartup < configReloadAfter) { return; } configReloadPending = false; try { if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath)) { throw new IOException("Config temporarily missing."); } ((BaseUnityPlugin)this).Config.Reload(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Config reloaded. Multiplayer clients use server rest settings."); } catch (IOException error) { RetryConfigReload(error); } catch (UnauthorizedAccessException error2) { RetryConfigReload(error2); } } private void StartConfigWatcher() { if (configWatcher != null) { configWatcher.Dispose(); } configWatcher = new FileSystemWatcher(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath)); configWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite; configWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; configWatcher.Changed += ConfigFileChanged; configWatcher.Created += ConfigFileChanged; configWatcher.Renamed += ConfigFileChanged; configWatcher.Error += ConfigWatchFailed; configWatcher.EnableRaisingEvents = true; QueueConfigReload(); } private void ConfigFileChanged(object sender, FileSystemEventArgs args) { if (sender == configWatcher) { QueueConfigReload(); } } private void QueueConfigReload() { configReloadPending = true; configReloadAfter = Time.realtimeSinceStartup + 0.25f; configReloadRetries = 0; } private void ConfigWatchFailed(object sender, ErrorEventArgs args) { if (sender == configWatcher) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Config watcher error; restarting: " + args.GetException().Message)); StartConfigWatcher(); } } private void RetryConfigReload(Exception error) { if (++configReloadRetries <= 5) { configReloadPending = true; configReloadAfter = Time.realtimeSinceStartup + 0.5f; } else { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Config reload failed; save again to retry: " + error.Message)); } } private void SetEffective(bool pause, float delay, float range) { pauseTimer = pause; restDelay = delay; comfortRange = range; } private void ServerTick(ZNet net) { float value = delaySetting.Value; float value2 = rangeSetting.Value; if (ValidDelay(value) && ValidRange(value2) && (pauseTimer != pauseSetting.Value || restDelay != value || comfortRange != value2 || revision == 0)) { SetEffective(pauseSetting.Value, value, value2); revision++; foreach (Peer value3 in peers.Values) { if (value3.Ack == revision - 1) { value3.Deadline = Time.realtimeSinceStartup + 30f; } if (value3.Hello) { SendSettings(value3.Net.m_rpc); } } ((BaseUnityPlugin)this).Logger.LogInfo((object)("Server settings revision " + revision + ": pause=" + pauseTimer + ", delay=" + restDelay + ", range=" + comfortRange)); } ZNetPeer[] array = net.GetPeers().ToArray(); foreach (ZNetPeer val in array) { if (val.IsReady() && !val.m_server && !peers.ContainsKey(val.m_rpc)) { peers.Add(val.m_rpc, new Peer { Net = val, Deadline = Time.realtimeSinceStartup + 30f }); val.m_rpc.Register<ZPackage>("RestConfiguration_Config_v1", (Action<ZRpc, ZPackage>)ReceiveServer); } } foreach (KeyValuePair<ZRpc, Peer> item in new List<KeyValuePair<ZRpc, Peer>>(peers)) { if (!net.GetPeers().Contains(item.Value.Net)) { item.Key.Unregister("RestConfiguration_Config_v1"); peers.Remove(item.Key); } else if (item.Value.Ack != revision && Time.realtimeSinceStartup > item.Value.Deadline) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Disconnecting " + item.Value.Net.m_playerName + ": compatible Rest Configuration config acknowledgement missing.")); net.Disconnect(item.Value.Net); peers.Remove(item.Key); } } } private void ClientTick(ZNet net) { //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Expected O, but got Unknown ZNetPeer serverPeer = net.GetServerPeer(); if (serverPeer == null || !serverPeer.IsReady()) { if (serverRpc != null) { serverRpc.Unregister("RestConfiguration_Config_v1"); serverRpc = null; } received = false; SetEffective(pause: false, 20f, 1f); return; } if (serverRpc != serverPeer.m_rpc) { if (serverRpc != null) { serverRpc.Unregister("RestConfiguration_Config_v1"); } serverRpc = serverPeer.m_rpc; received = false; revision = 0; connectedAt = Time.realtimeSinceStartup; nextHello = 0f; SetEffective(pause: false, 20f, 1f); serverRpc.Register<ZPackage>("RestConfiguration_Config_v1", (Action<ZRpc, ZPackage>)ReceiveClient); } if (!received && Time.realtimeSinceStartup >= nextHello) { nextHello = Time.realtimeSinceStartup + 2f; ZPackage val = new ZPackage(); val.Write(0); val.Write(1); Send(serverRpc, val); } if (!received && Time.realtimeSinceStartup > connectedAt + 30f) { ((BaseUnityPlugin)this).Logger.LogError((object)"Server did not supply compatible Rest Configuration settings; disconnecting."); net.Disconnect(serverPeer); } } private static void Send(ZRpc rpc, ZPackage package) { rpc.Invoke("RestConfiguration_Config_v1", new object[1] { package }); } private void SendSettings(ZRpc rpc) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(1); val.Write(1); val.Write(revision); val.Write(pauseTimer); val.Write(restDelay); val.Write(comfortRange); Send(rpc, val); } private void ReceiveServer(ZRpc rpc, ZPackage package) { if ((Object)(object)session == (Object)null || !session.IsServer() || !peers.TryGetValue(rpc, out var value)) { return; } try { if (package.Size() != 8 && package.Size() != 12) { return; } int num = package.ReadInt(); int num2 = package.ReadInt(); if (num2 != 1) { return; } if (num == 0 && package.Size() == 8) { value.Hello = true; SendSettings(rpc); } else if (num == 2 && package.Size() == 12 && value.Hello) { int num3 = package.ReadInt(); if (num3 == revision) { value.Ack = num3; } } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Invalid config handshake: " + ex.Message)); } } private void ReceiveClient(ZRpc rpc, ZPackage package) { //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown if ((Object)(object)session == (Object)null || session.IsServer() || rpc != serverRpc) { return; } try { if (package.Size() == 21 && package.ReadInt() == 1 && package.ReadInt() == 1) { int num = package.ReadInt(); bool pause = package.ReadBool(); float num2 = package.ReadSingle(); float num3 = package.ReadSingle(); if (ValidDelay(num2) && ValidRange(num3) && num >= 1 && num >= revision) { SetEffective(pause, num2, num3); revision = num; received = true; ZPackage val = new ZPackage(); val.Write(2); val.Write(1); val.Write(revision); Send(rpc, val); } } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Invalid server config: " + ex.Message)); } } private void ClearNetwork() { foreach (ZRpc key in peers.Keys) { key.Unregister("RestConfiguration_Config_v1"); } peers.Clear(); if (serverRpc != null) { serverRpc.Unregister("RestConfiguration_Config_v1"); } serverRpc = null; received = false; revision = 0; } private void OnDestroy() { if (configWatcher != null) { configWatcher.Dispose(); configWatcher = null; } ClearNetwork(); if (harmony != null) { harmony.UnpatchSelf(); } instance = null; } private static float Delay(SE_Cozy effect) { if (!((Object)(object)instance != (Object)null) || !(effect.m_statusEffect == "Rested")) { return effect.m_delay; } return instance.restDelay; } private static float Radius() { return 10f * (((Object)(object)instance != (Object)null) ? instance.comfortRange : 1f); } }
BepInEx/plugins/SyncedWebMap.dll
Decompiled 2 weeks agousing System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Splatform; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace SyncedWebMap; [BepInPlugin("local.syncedwebmap", "Synced Web Map", "0.1.0")] public sealed class Plugin : BaseUnityPlugin { private sealed class Binding { public PinData Local; public MapPin Last; public MapPin Sent; } [HarmonyPatch(typeof(Chat), "SendText")] private static class PublicChat { private static bool Prefix(Type __0, string __1) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_004a: 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_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown if (((int)__0 != 1 && (int)__0 != 2) || (Object)(object)instance == (Object)null || !instance.welcomed || instance.connection == null || (Object)(object)Player.m_localPlayer == (Object)null) { return true; } string text = __1; Type type = __0; Plugin owner = instance; ZRpc rpc = owner.connection; bool reported = false; Chat.CheckPermissionsAndSendChatMessageRPCsAsync((SendChatMessageRPCHandler)delegate(long target, bool privilege) { //IL_0083: 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_009b: Expected I4, but got Unknown if (!((Object)(object)instance != (Object)(object)owner) && owner.welcomed && owner.connection == rpc && !((Object)(object)Player.m_localPlayer == (Object)null) && ZRoutedRpc.instance != null) { UserInfo val = default(UserInfo); string message = default(string); Chat.GetChatMessageData(text, privilege, ref val, ref message); ZRoutedRpc.instance.InvokeRoutedRPC(target, "ChatMessage", new object[4] { ((Character)Player.m_localPlayer).GetHeadPoint(), (int)type, val, message }); if (!reported) { reported = true; Guard(delegate { Send(rpc, Wire.Message(8, delegate(BinaryWriter w) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected I4, but got Unknown w.Write((int)type); w.Write((message.Length > 512) ? message.Substring(0, 512) : message); })); }); } } }); return false; } } [HarmonyPatch(typeof(Chat), "AddInworldText")] private static class NormalWorldText { private static bool Prefix(ref GameObject __0, long __1, Vector3 __2, Type __3) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_0079: 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_007e: 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_0097: Unknown result type (might be due to invalid IL or missing references) if ((int)__3 != 1 || (Object)(object)instance == (Object)null || !instance.welcomed || (Object)(object)Player.m_localPlayer == (Object)null) { return true; } Player val = ((IEnumerable<Player>)Player.GetAllPlayers()).FirstOrDefault((Func<Player, bool>)delegate(Player p) { //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) ZDOID zDOID = ((Character)p).GetZDOID(); return ((ZDOID)(ref zDOID)).UserID == __1; }); Talker component = ((Component)(((Object)(object)val != (Object)null) ? val : Player.m_localPlayer)).GetComponent<Talker>(); Vector3 val2 = (((Object)(object)val != (Object)null) ? ((Component)val).transform.position : __2); if ((Object)(object)component == (Object)null || Vector3.Distance(((Component)Player.m_localPlayer).transform.position, val2) >= component.m_normalDistance) { return false; } if ((Object)(object)val != (Object)null) { __0 = ((Component)val).gameObject; } return true; } } [HarmonyPatch(typeof(Minimap), "LoadMapData")] private static class MapLoaded { private static void Postfix(Minimap __instance) { if ((Object)(object)instance != (Object)null) { instance.ClearClient(); instance.loadedMap = __instance; } } } [HarmonyPatch(typeof(Minimap), "UpdateExplore")] private static class BoatExplore { private static void Prefix(ref float ___m_exploreRadius, out float __state) { __state = ___m_exploreRadius; if (!((Object)(object)instance == (Object)null) && instance.welcomed) { if ((Object)(object)Ship.GetLocalShip() != (Object)null) { ___m_exploreRadius = Mathf.Max(___m_exploreRadius, instance.serverRadius); } else if (instance.serverPlayerRadius > 0f) { ___m_exploreRadius = instance.serverPlayerRadius; } } } private static Exception Finalizer(ref float ___m_exploreRadius, float __state, Exception __exception) { ___m_exploreRadius = __state; return __exception; } } [HarmonyPatch(typeof(Minimap), "GetMapData")] private static class MapSaved { private static void Prefix(out List<PinData> __state) { __state = new List<PinData>(); if ((Object)(object)instance == (Object)null) { return; } foreach (Binding value in instance.bindings.Values) { if (value.Local != null && value.Last != null && value.Last.Revision > 0 && value.Local.m_save) { __state.Add(value.Local); value.Local.m_save = false; } } } private static Exception Finalizer(List<PinData> __state, Exception __exception) { if (__state != null) { foreach (PinData item in __state) { item.m_save = true; } } return __exception; } } [HarmonyPatch(typeof(Chat), "SendPing")] private static class PingSent { private static void Postfix(Vector3 __0) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) Guard(delegate { if (instance.welcomed && instance.connection != null) { Send(instance.connection, Wire.Message(6, delegate(BinaryWriter w) { w.Write(__0.x); w.Write(__0.z); })); } }); } } [HarmonyPatch(typeof(Minimap), "AddSharedMapData")] private static class TableRead { private static bool Prefix(Minimap __instance, byte[] __0, ref bool __result) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_0119: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)instance == (Object)null || !instance.welcomed) { return true; } try { ZPackage val = new ZPackage(__0); int value = val.ReadInt(); List<bool> list = (List<bool>)AccessTools.Method(typeof(Minimap), "ReadExploredArray", (Type[])null, (Type[])null).Invoke(__instance, new object[2] { val, Enum.ToObject(AccessTools.Method(typeof(Minimap), "ReadExploredArray", (Type[])null, (Type[])null).GetParameters()[1].ParameterType, value) }); if (list == null || list.Count != instance.clientState.Size * instance.clientState.Size) { return false; } bool flag = false; for (int i = 0; i < list.Count; i++) { if (list[i]) { flag |= ExplorePixel(__instance, i % instance.clientState.Size, i / instance.clientState.Size); } } if (flag) { ((Texture2D)FogField.GetValue(__instance)).Apply(); } __result = flag; } catch (Exception ex) { ((BaseUnityPlugin)instance).Logger.LogWarning((object)("Could not read table exploration: " + ex.GetType().Name)); } return false; } } [HarmonyPatch(typeof(ZNet), "Shutdown")] private static class Shutdown { private static void Postfix() { Guard(delegate { instance.Stop(); }); } } public const string Id = "local.syncedwebmap"; private const string RpcName = "local.syncedwebmap.v1"; private static Plugin instance; private static readonly FieldInfo ExploredField = AccessTools.Field(typeof(Minimap), "m_explored"); private static readonly FieldInfo OthersField = AccessTools.Field(typeof(Minimap), "m_exploredOthers"); private static readonly FieldInfo PinsField = AccessTools.Field(typeof(Minimap), "m_pins"); private static readonly FieldInfo SizeField = AccessTools.Field(typeof(Minimap), "m_textureSize"); private static readonly FieldInfo PixelField = AccessTools.Field(typeof(Minimap), "m_pixelSize"); private static readonly FieldInfo FogField = AccessTools.Field(typeof(Minimap), "m_fogTexture"); private static readonly Func<Minimap, int, int, bool> ExplorePixel = (Func<Minimap, int, int, bool>)Delegate.CreateDelegate(typeof(Func<Minimap, int, int, bool>), AccessTools.Method(typeof(Minimap), "Explore", new Type[2] { typeof(int), typeof(int) }, (Type[])null)); private Harmony harmony; private float serverPlayerRadius; private ConfigEntry<int> mapUpdatesPerSecond; private int serverUpdatesPerSecond = 4; private float nextConfigCheck; private DateTime configWriteTime; private MapState clientState; private bool welcomed; private bool initialPins; private bool readyReceived; private float serverRadius; private float nextPins; private float nextHello; private float nextUpload; private float nextStats; private int scanPage; private ZRpc connection; private Minimap loadedMap; private ClientPinIds pinIds; private readonly Dictionary<int, byte[]> incomingPages = new Dictionary<int, byte[]>(); private readonly HashSet<int> outgoingPages = new HashSet<int>(); private readonly Dictionary<string, MapPin> incomingPins = new Dictionary<string, MapPin>(); private readonly Dictionary<string, Binding> bindings = new Dictionary<string, Binding>(); private List<PinData> LocalPins => (List<PinData>)PinsField.GetValue(loadedMap); private void Awake() { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown instance = this; mapUpdatesPerSecond = ((BaseUnityPlugin)this).Config.Bind<int>("Web", "MapUpdatesPerSecond", 0, new ConfigDescription("Updates per second: 0 uses 4 on the server or follows the server on clients. Values 1-30 override the rate; client overrides affect their own boat/stats uploads. Server rate controls web snapshots and browser polling. Save config to apply live within one second.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 30), new object[0])); configWriteTime = File.GetLastWriteTimeUtc(((BaseUnityPlugin)this).Config.ConfigFilePath); harmony = new Harmony("local.syncedwebmap"); try { harmony.PatchAll(typeof(Plugin).Assembly); } catch (Exception ex) { harmony.UnpatchSelf(); instance = null; ((Behaviour)this).enabled = false; ((BaseUnityPlugin)this).Logger.LogError((object)("Map hooks incompatible: " + ex.GetType().Name)); } } private void Update() { Guard(Tick); } private void Tick() { ZNet val = ZNet.instance; ReloadConfigIfChanged(); if (!((Object)(object)val == (Object)null) && !val.IsServer()) { ClientTick(val); } } private void ReloadConfigIfChanged() { float realtimeSinceStartup = Time.realtimeSinceStartup; if (realtimeSinceStartup >= nextConfigCheck) { nextConfigCheck = realtimeSinceStartup + 1f; DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(((BaseUnityPlugin)this).Config.ConfigFilePath); if (lastWriteTimeUtc != configWriteTime && File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath)) { ((BaseUnityPlugin)this).Config.Reload(); configWriteTime = lastWriteTimeUtc; nextStats = 0f; } } } private static void Send(ZRpc rpc, byte[] bytes) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown rpc.Invoke("local.syncedwebmap.v1", new object[1] { (object)new ZPackage(bytes) }); } private void ClientTick(ZNet net) { //IL_021d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)loadedMap == (Object)null || (Object)(object)loadedMap != (Object)(object)Minimap.instance || (Object)(object)Player.m_localPlayer == (Object)null) { return; } ZNetPeer serverPeer = net.GetServerPeer(); if (serverPeer == null || !serverPeer.IsReady()) { return; } if (connection != serverPeer.m_rpc) { ClearClient(); connection = serverPeer.m_rpc; connection.Register<ZPackage>("local.syncedwebmap.v1", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg) { Guard(delegate { ReceiveClient(rpc, pkg); }); }); } float realtimeSinceStartup = Time.realtimeSinceStartup; if (!welcomed) { if (realtimeSinceStartup >= nextHello) { nextHello = realtimeSinceStartup + 2f; Send(connection, Wire.Message(1, delegate(BinaryWriter w) { w.Write(1); w.Write((int)SizeField.GetValue(loadedMap)); w.Write((float)PixelField.GetValue(loadedMap)); })); } return; } if (realtimeSinceStartup >= nextStats) { nextStats = realtimeSinceStartup + 1f / (float)((mapUpdatesPerSecond.Value == 0) ? serverUpdatesPerSecond : mapUpdatesPerSecond.Value); Player player = Player.m_localPlayer; Send(connection, Wire.Message(7, delegate(BinaryWriter w) { //IL_0096: 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_00d6: Unknown result type (might be due to invalid IL or missing references) w.Write(((Character)player).GetHealth()); w.Write(((Character)player).GetMaxHealth()); w.Write(((Character)player).GetBodyArmor()); Ship localShip = Ship.GetLocalShip(); ZNetView val = (((Object)(object)localShip != (Object)null) ? ((Component)localShip).GetComponent<ZNetView>() : null); bool flag3 = (Object)(object)val != (Object)null && val.IsValid(); w.Write(flag3 ? ((object)Unsafe.As<ZDOID, ZDOID>(ref val.GetZDO().m_uid)/*cast due to .constrained prefix*/).ToString() : ""); w.Write(flag3 ? ((Component)localShip).transform.position.x : 0f); w.Write(flag3 ? ((Component)localShip).transform.position.z : 0f); w.Write(flag3 ? ((Component)localShip).transform.eulerAngles.y : 0f); })); } bool flag = false; for (int num = 0; num < 2; num++) { if (incomingPages.Count <= 0) { break; } int num2 = incomingPages.Keys.First(); byte[] array = incomingPages[num2]; incomingPages.Remove(num2); clientState.Merge(num2, array); int num3 = num2 * 1024 * 8; for (int num4 = 0; num4 < array.Length * 8; num4++) { if ((array[num4 / 8] & (1 << num4 % 8)) != 0) { int num5 = num3 + num4; flag |= ExplorePixel(loadedMap, num5 % clientState.Size, num5 / clientState.Size); } } } if (flag) { ((Texture2D)FogField.GetValue(loadedMap)).Apply(); } for (int num6 = 0; num6 < 16; num6++) { if (incomingPins.Count <= 0) { break; } string key = incomingPins.Keys.First(); MapPin pin = incomingPins[key]; incomingPins.Remove(key); ApplyPin(pin); } pinIds.Save(); if (!readyReceived || (!initialPins && (incomingPages.Count > 0 || incomingPins.Count > 0))) { return; } BitArray bitArray = (BitArray)ExploredField.GetValue(loadedMap); BitArray bitArray2 = (BitArray)OthersField.GetValue(loadedMap); for (int num7 = 0; num7 < 2; num7++) { int num8 = scanPage++ % clientState.PageCount; byte[] array2 = clientState.Page(num8); bool flag2 = false; int num9 = num8 * 1024 * 8; for (int num10 = 0; num10 < array2.Length * 8; num10++) { if (bitArray[num9 + num10] || bitArray2[num9 + num10]) { byte b = array2[num10 / 8]; array2[num10 / 8] |= (byte)(1 << num10 % 8); flag2 |= b != array2[num10 / 8]; } } if (flag2) { clientState.Merge(num8, array2); outgoingPages.Add(num8); } } if (realtimeSinceStartup >= nextUpload) { nextUpload = realtimeSinceStartup + 0.05f; for (int num11 = 0; num11 < 4; num11++) { if (outgoingPages.Count <= 0) { break; } int num12 = outgoingPages.First(); Send(connection, Wire.PageMessage(clientState, num12)); outgoingPages.Remove(num12); } } if (realtimeSinceStartup >= nextPins) { nextPins = realtimeSinceStartup + 0.5f; ScanPins(); } } private void ReceiveClient(ZRpc rpc, ZPackage pkg) { if (rpc != connection || pkg.Size() > 4096) { return; } using BinaryReader binaryReader = new BinaryReader(new MemoryStream(pkg.GetArray())); byte b = binaryReader.ReadByte(); if (b == 2) { long num = binaryReader.ReadInt64(); int num2 = binaryReader.ReadInt32(); float num3 = binaryReader.ReadSingle(); float num4 = binaryReader.ReadSingle(); if (num == ZNet.instance.GetWorldUID() && num2 == (int)SizeField.GetValue(loadedMap) && num3 == (float)PixelField.GetValue(loadedMap) && MapState.Finite(num4) && !(num4 < 100f) && !(num4 > 1000f)) { pinIds = new ClientPinIds(Path.Combine(Paths.ConfigPath, "SyncedWebMap", "client", num.ToString(), Player.m_localPlayer.GetPlayerID().ToString(), "pins.bin")); clientState = new MapState(num2, num3); serverRadius = num4; serverPlayerRadius = 0f; welcomed = true; } } else { if (!welcomed) { return; } switch (b) { case 9: { int num5 = binaryReader.ReadInt32(); if (num5 >= 1 && num5 <= 30 && binaryReader.BaseStream.Position == binaryReader.BaseStream.Length) { serverUpdatesPerSecond = num5; nextStats = 0f; } break; } case 10: { float num6 = binaryReader.ReadSingle(); float num7 = binaryReader.ReadSingle(); if (MapState.Finite(num6) && !(num6 < 100f) && !(num6 > 1000f) && MapState.Finite(num7) && !(num7 < 0f) && !(num7 > 1000f) && binaryReader.BaseStream.Position == binaryReader.BaseStream.Length) { serverRadius = num6; serverPlayerRadius = num7; } break; } case 5: readyReceived = true; break; case 3: { int num8 = binaryReader.ReadInt32(); int num9 = binaryReader.ReadInt32(); if (num8 < 0 || num8 >= clientState.PageCount || num9 != clientState.Page(num8).Length) { break; } byte[] array = binaryReader.ReadBytes(num9); if (array.Length != num9) { break; } if (incomingPages.TryGetValue(num8, out var value)) { for (int i = 0; i < num9; i++) { array[i] |= value[i]; } } incomingPages[num8] = array; break; } case 4: { MapPin mapPin = Wire.ReadPin(binaryReader); if (incomingPins.Count < 10000 || incomingPins.ContainsKey(mapPin.Id)) { incomingPins[mapPin.Id] = mapPin; } break; } } } } private static MapPin ReadLocal(string id, PinData p, long revision) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected I4, but got Unknown MapPin mapPin = new MapPin(); mapPin.Id = id; mapPin.Name = (((p.m_name ?? "").Length > 100) ? p.m_name.Substring(0, 100) : (p.m_name ?? "")); mapPin.Type = (int)p.m_type; mapPin.X = p.m_pos.x; mapPin.Y = p.m_pos.y; mapPin.Z = p.m_pos.z; mapPin.Checked = p.m_checked; mapPin.Revision = revision; return mapPin; } private string ImportId(PinData p) { byte[] buffer = Wire.Message(0, delegate(BinaryWriter w) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected I4, but got Unknown w.Write(ZNet.instance.GetWorldUID()); w.Write((int)p.m_type); w.Write(p.m_pos.x); w.Write(p.m_pos.z); w.Write(p.m_name ?? ""); }); using SHA256 sHA = SHA256.Create(); byte[] array = new byte[16]; Buffer.BlockCopy(sHA.ComputeHash(buffer), 0, array, 0, 16); return new Guid(array).ToString("N"); } private void ScanPins() { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected I4, but got Unknown List<PinData> localPins = LocalPins; HashSet<PinData> hashSet = new HashSet<PinData>(localPins); HashSet<PinData> hashSet2 = new HashSet<PinData>(bindings.Values.Select((Binding b) => b.Local)); PinData[] array = localPins.ToArray(); foreach (PinData val in array) { if (!val.m_save || !MapState.SharedType((int)val.m_type) || hashSet2.Contains(val)) { continue; } string key = ImportId(val); string text = (initialPins ? Guid.NewGuid().ToString("N") : pinIds.Find(key)); if (bindings.TryGetValue(text, out var _)) { loadedMap.RemovePin(val); continue; } if (bindings.Count >= 10000) { break; } val.m_ownerID = 0L; MapPin last = ReadLocal(text, val, 0L); pinIds.Remember(key, text); bindings[text] = new Binding { Local = val, Last = last }; } initialPins = true; int num2 = 16; KeyValuePair<string, Binding>[] array2 = bindings.ToArray(); for (int num3 = 0; num3 < array2.Length; num3++) { KeyValuePair<string, Binding> keyValuePair = array2[num3]; Binding value2 = keyValuePair.Value; if (value2.Sent != null || value2.Last.Deleted) { continue; } MapPin mapPin = ReadLocal(keyValuePair.Key, value2.Local, value2.Last.Revision); mapPin.Deleted = !hashSet.Contains(value2.Local); if (value2.Last.Revision == 0 && mapPin.Deleted) { bindings.Remove(keyValuePair.Key); } else if (value2.Last.Revision == 0 || !mapPin.Same(value2.Last)) { MapState.Validate(mapPin); pinIds.Remember(ImportId(value2.Local), keyValuePair.Key); pinIds.Save(); Send(connection, Wire.PinMessage(mapPin)); value2.Sent = mapPin; if (--num2 == 0) { break; } } } } private void ApplyPin(MapPin pin) { //IL_0051: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) if (!bindings.TryGetValue(pin.Id, out var value)) { value = new Binding(); bindings.Add(pin.Id, value); if (!pin.Deleted) { value.Local = loadedMap.AddPin(new Vector3(pin.X, pin.Y, pin.Z), (PinType)pin.Type, pin.Name, true, pin.Checked, 0L, default(PlatformUserID)); } } else { if (value.Last != null && pin.Revision < value.Last.Revision) { return; } if (pin.Deleted) { if (value.Local != null) { loadedMap.RemovePin(value.Local); } } else if (value.Sent == null || !pin.Same(value.Sent)) { if (value.Local != null) { loadedMap.RemovePin(value.Local); } value.Local = loadedMap.AddPin(new Vector3(pin.X, pin.Y, pin.Z), (PinType)pin.Type, pin.Name, true, pin.Checked, 0L, default(PlatformUserID)); } } value.Last = pin; value.Sent = null; if (value.Local != null) { pinIds.Remember(ImportId(value.Local), pin.Id); } } private void ClearClient() { if ((Object)(object)loadedMap != (Object)null) { foreach (Binding value in bindings.Values) { if (value.Local != null && value.Last != null && value.Last.Revision > 0) { loadedMap.RemovePin(value.Local); } } } if (connection != null) { connection.Unregister("local.syncedwebmap.v1"); } connection = null; clientState = null; pinIds = null; welcomed = (initialPins = (readyReceived = false)); scanPage = 0; nextHello = (nextStats = 0f); serverUpdatesPerSecond = 4; incomingPages.Clear(); outgoingPages.Clear(); incomingPins.Clear(); bindings.Clear(); } private void Stop() { ClearClient(); loadedMap = null; } private void OnDestroy() { Guard(Stop); if (harmony != null) { harmony.UnpatchSelf(); } instance = null; } private static void Guard(Action action) { if ((Object)(object)instance == (Object)null) { return; } try { action(); } catch (Exception ex) { ((BaseUnityPlugin)instance).Logger.LogError((object)("Map operation failed: " + ex.GetType().Name + " " + ex.Message)); } } } public sealed class MapPin { public string Id; public string Name; public int Type; public float X; public float Y; public float Z; public bool Checked; public bool Deleted; public long Revision; public MapPin Copy() { return (MapPin)MemberwiseClone(); } public bool Same(MapPin b) { if (b != null && Name == b.Name && Type == b.Type && X == b.X && Y == b.Y && Z == b.Z && Checked == b.Checked) { return Deleted == b.Deleted; } return false; } } public sealed class MapState { public const int PageBytes = 1024; public const int MaxPins = 10000; public readonly int Size; public readonly float PixelSize; public readonly byte[] Explored; public long Revision; public int PageCount => (Explored.Length + 1024 - 1) / 1024; public MapState(int size, float pixelSize) { if (size < 128 || size > 4096 || size % 128 != 0 || !Finite(pixelSize) || pixelSize < 1f || pixelSize > 128f) { throw new InvalidDataException("Invalid map dimensions"); } Size = size; PixelSize = pixelSize; Explored = new byte[size * size / 8]; } public static bool Finite(float n) { if (!float.IsNaN(n)) { return !float.IsInfinity(n); } return false; } public byte[] Page(int page) { if (page < 0 || page >= PageCount) { throw new InvalidDataException("Invalid page"); } byte[] array = new byte[Math.Min(1024, Explored.Length - page * 1024)]; Buffer.BlockCopy(Explored, page * 1024, array, 0, array.Length); return array; } public bool Merge(int page, byte[] data) { if (page < 0 || page >= PageCount || data.Length != Math.Min(1024, Explored.Length - page * 1024)) { throw new InvalidDataException("Invalid exploration page"); } bool flag = false; for (int i = 0; i < data.Length; i++) { int num = page * 1024 + i; byte b = (byte)(Explored[num] | data[i]); flag |= b != Explored[num]; Explored[num] = b; } if (flag) { Revision++; } return flag; } public static void Validate(MapPin p) { if (!Guid.TryParseExact(p.Id, "N", out var _) || p.Name == null || p.Name.Length > 100 || p.Revision < 0 || !Finite(p.X) || !Finite(p.Y) || !Finite(p.Z) || Math.Abs(p.X) > 30000f || Math.Abs(p.Z) > 30000f || Math.Abs(p.Y) > 10000f || !SharedType(p.Type)) { throw new InvalidDataException("Invalid pin"); } } public static bool SharedType(int type) { if (type != 0 && type != 1 && type != 2 && type != 3 && type != 4 && type != 6 && type != 9 && type != 14 && type != 15) { return type == 16; } return true; } } public static class Wire { public const byte Hello = 1; public const byte Welcome = 2; public const byte Exploration = 3; public const byte Pin = 4; public const byte Ready = 5; public const byte Ping = 6; public const byte PlayerStats = 7; public const byte ChatMessage = 8; public const byte Settings = 9; public const byte ExplorationSettings = 10; public static byte[] Message(byte kind, Action<BinaryWriter> body) { using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(kind); body(binaryWriter); } return memoryStream.ToArray(); } public static void WritePin(BinaryWriter w, MapPin p) { w.Write(p.Id); w.Write(p.Name); w.Write(p.Type); w.Write(p.X); w.Write(p.Y); w.Write(p.Z); w.Write(p.Checked); w.Write(p.Deleted); w.Write(p.Revision); } public static MapPin ReadPin(BinaryReader r) { MapPin mapPin = new MapPin(); mapPin.Id = ReadText(r, 32); mapPin.Name = ReadText(r, 100); mapPin.Type = r.ReadInt32(); mapPin.X = r.ReadSingle(); mapPin.Y = r.ReadSingle(); mapPin.Z = r.ReadSingle(); mapPin.Checked = r.ReadBoolean(); mapPin.Deleted = r.ReadBoolean(); mapPin.Revision = r.ReadInt64(); MapPin mapPin2 = mapPin; MapState.Validate(mapPin2); return mapPin2; } public static string ReadText(BinaryReader r, int limit) { string text = r.ReadString(); if (text.Length > limit) { throw new InvalidDataException("Text limit"); } return text; } public static byte[] PinMessage(MapPin p) { return Message(4, delegate(BinaryWriter w) { WritePin(w, p); }); } public static byte[] PageMessage(MapState s, int page) { return Message(3, delegate(BinaryWriter w) { byte[] array = s.Page(page); w.Write(page); w.Write(array.Length); w.Write(array); }); } } public sealed class ClientPinIds { private readonly string path; private readonly Dictionary<string, string> aliases = new Dictionary<string, string>(); private bool dirty; public ClientPinIds(string file) { path = file; if (!File.Exists(path)) { return; } using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path)); if (binaryReader.ReadInt32() != 1) { throw new InvalidDataException("Unknown client pin identity format"); } int num = binaryReader.ReadInt32(); if (num < 0 || num > 100000) { throw new InvalidDataException("Client pin identity limit"); } for (int i = 0; i < num; i++) { string text = Wire.ReadText(binaryReader, 32); string text2 = Wire.ReadText(binaryReader, 32); if (!Guid.TryParseExact(text, "N", out var result) || !Guid.TryParseExact(text2, "N", out result)) { throw new InvalidDataException("Invalid client pin identity"); } aliases.Add(text, text2); } if (binaryReader.BaseStream.Position != binaryReader.BaseStream.Length) { throw new InvalidDataException("Trailing client pin data"); } } public string Find(string key) { if (!aliases.TryGetValue(key, out var value)) { return key; } return value; } public void Remember(string key, string id) { if (!aliases.TryGetValue(key, out var value) || !(value == id)) { if (aliases.Count >= 100000 && !aliases.ContainsKey(key)) { throw new InvalidDataException("Client pin identity capacity reached"); } aliases[key] = id; dirty = true; } } public void Save() { if (!dirty) { return; } Directory.CreateDirectory(Path.GetDirectoryName(path)); using (FileStream fileStream = new FileStream(path + ".tmp", FileMode.Create, FileAccess.Write, FileShare.None)) { using BinaryWriter binaryWriter = new BinaryWriter(fileStream); binaryWriter.Write(1); binaryWriter.Write(aliases.Count); foreach (KeyValuePair<string, string> alias in aliases) { binaryWriter.Write(alias.Key); binaryWriter.Write(alias.Value); } binaryWriter.Flush(); fileStream.Flush(flushToDisk: true); } if (File.Exists(path)) { File.Replace(path + ".tmp", path, path + ".bak"); } else { File.Move(path + ".tmp", path); } dirty = false; } }
BepInEx/plugins/WhiskeyStop.dll
Decompiled 2 weeks agousing System; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace WhiskeyStop; [BepInPlugin("local.whiskeystop", "Whiskey Stop", "1.0.1")] public sealed class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(BaseAI), "Awake")] private static class WolfPupIdleTimer { [HarmonyPostfix] private static void Postfix(BaseAI __instance) { if (IsWolfPup(((Component)__instance).gameObject)) { ((MonoBehaviour)__instance).CancelInvoke("DoIdleSound"); } } } [HarmonyPatch(typeof(BaseAI), "DoIdleSound")] private static class WolfPupIdleHowl { [HarmonyPrefix] private static bool Prefix(BaseAI __instance) { return !IsWolfPup(((Component)__instance).gameObject); } } [HarmonyPatch(typeof(AnimationEffect), "Effect")] private static class WolfPupAnimationHowl { [HarmonyPrefix] private static bool Prefix(AnimationEffect __instance, AnimationEvent e) { Object objectReferenceParameter = e.objectReferenceParameter; GameObject val = (GameObject)(object)((objectReferenceParameter is GameObject) ? objectReferenceParameter : null); if ((Object)(object)val == (Object)null || ((Object)val).name != "sfx_wolf_haul") { return true; } Character componentInParent = ((Component)__instance).GetComponentInParent<Character>(); if (!((Object)(object)componentInParent == (Object)null)) { return !IsWolfPup(((Component)componentInParent).gameObject); } return true; } } public const string PluginId = "local.whiskeystop"; private Harmony harmony; private void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown harmony = new Harmony("local.whiskeystop"); try { harmony.PatchAll(typeof(Plugin).Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Whiskey Stop loaded: wolf-pup idle and animation howls suppressed."); } catch (Exception ex) { harmony.UnpatchSelf(); ((BaseUnityPlugin)this).Logger.LogError((object)("Whiskey Stop disabled: " + ex)); } } private void OnDestroy() { if (harmony != null) { harmony.UnpatchSelf(); } } private static bool IsWolfPup(GameObject creature) { string name = ((Object)creature).name; if (!(name == "Wolf_cub")) { return name == "Wolf_cub(Clone)"; } return true; } }