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 ArtifactOfEgo v1.0.0
ArtifactOfEgo.dll
Decompiled 3 days agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Cil; using MonoMod.RuntimeDetour; using MonoMod.Utils; using R2API; using R2API.Utils; using RoR2; using UnityEngine; using UnityEngine.Networking; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("ArtifactOfEgo")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("ArtifactOfEgo")] [assembly: AssemblyTitle("ArtifactOfEgo")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ArtifactOfEgo { internal static class EgoArtifact { private delegate void OrigOnInventoryChanged(CharacterBody self); private static ArtifactDef _def; private static Hook _inventoryHook; private static bool _granting; internal static void Init() { //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Expected O, but got Unknown Sprite val = LoadSprite("ArtifactOfEgo_On.png"); Sprite val2 = LoadSprite("ArtifactOfEgo_Off.png"); if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null) { EgoPlugin.Log.LogError((object)"Artifact icons failed to load; the Artifact of Ego was not registered."); return; } _def = ScriptableObject.CreateInstance<ArtifactDef>(); _def.cachedName = "ArtifactOfEgo"; _def.nameToken = "ARTIFACT_ARTIFACTOFEGO_NAME"; _def.descriptionToken = "ARTIFACT_ARTIFACTOFEGO_DESCRIPTION"; _def.smallIconSelectedSprite = val; _def.smallIconDeselectedSprite = val2; LanguageAPI.Add(_def.nameToken, "Artifact of Ego"); LanguageAPI.Add(_def.descriptionToken, "Every player starts with an Egocentrism and cannot drop below one."); if (!ContentAddition.AddArtifactDef(_def)) { EgoPlugin.Log.LogError((object)"R2API rejected the Artifact of Ego; see the earlier R2API log line for the reason."); return; } EgoPlugin.Log.LogInfo((object)"Artifact of Ego registered."); MethodInfo method = typeof(CharacterBody).GetMethod("OnInventoryChanged", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method == null) { EgoPlugin.Log.LogError((object)"CharacterBody.OnInventoryChanged not found; the Artifact of Ego will not do anything."); } else { _inventoryHook = new Hook((MethodBase)method, (Delegate)new Action<OrigOnInventoryChanged, CharacterBody>(OnInventoryChanged)); } } private static void OnInventoryChanged(OrigOnInventoryChanged orig, CharacterBody self) { orig(self); if (!NetworkServer.active || _granting) { return; } RunArtifactManager instance = RunArtifactManager.instance; if (!Object.op_Implicit((Object)(object)instance) || !instance.IsArtifactEnabled(_def) || !Object.op_Implicit((Object)(object)self) || !self.isPlayerControlled || !Object.op_Implicit((Object)(object)self.inventory)) { return; } ItemDef lunarSun = Items.LunarSun; if (self.inventory.GetItemCountEffective(lunarSun) >= 1) { return; } _granting = true; try { self.inventory.GiveItemPermanent(lunarSun, 1); } finally { _granting = false; } } private static Sprite LoadSprite(string fileName) { //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) Assembly assembly = typeof(EgoPlugin).Assembly; string text = assembly.GetManifestResourceNames().FirstOrDefault((string n) => n.EndsWith(fileName, StringComparison.OrdinalIgnoreCase)); if (text == null) { EgoPlugin.Log.LogError((object)("Embedded icon " + fileName + " not found.")); return null; } byte[] array; using (Stream stream = assembly.GetManifestResourceStream(text)) { using MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); array = memoryStream.ToArray(); } Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false); if (!ImageConversion.LoadImage(val, array)) { EgoPlugin.Log.LogError((object)("Icon " + fileName + " could not be decoded.")); return null; } ((Object)val).name = fileName; return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f)); } } internal static class EgocentrismBlacklist { private static readonly string[][] Entries = new string[22][] { new string[2] { "Rusted Key", "TreasureCache" }, new string[2] { "Encrusted Key", "TreasureCacheVoid" }, new string[1] { "Collector's Compulsion" }, new string[3] { "Regenerating Scrap", "RegeneratingScrap", "RegeneratingScrapConsumed" }, new string[3] { "Sale Star", "LowerPricedChests", "LowerPricedChestsConsumed" }, new string[2] { "Shipping Request Form", "FreeChest" }, new string[2] { "57 Leaf Clover", "Clover" }, new string[2] { "Sonorous Whispers", "ItemDropChanceOnKill" }, new string[2] { "Substandard Duplicator", "Duplicator" }, new string[2] { "Artifact Key", "ArtifactKey" }, new string[1] { "Encrypted Cerebellum" }, new string[1] { "Exposed Cerebellum" }, new string[1] { "Functional Coupler" }, new string[2] { "Irradiant Pearl", "ShinyPearl" }, new string[1] { "Sentry Key" }, new string[2] { "Eulogy Zero", "RandomlyLunar" }, new string[2] { "Longstanding Solitude", "OnLevelUpFreeUnlock" }, new string[2] { "Benthic Bloom", "CloverVoid" }, new string[1] { "Peace Flower" }, new string[1] { "Dream Crucible" }, new string[2] { "Gesture of the Drowned", "AutoCastEquipment" }, new string[2] { "Beads of Fealty", "LunarTrinket" } }; private static HashSet<ItemIndex> _blocked = new HashSet<ItemIndex>(); private static bool _active; internal static void Init() { RoR2Application.onLoad = (Action)Delegate.Combine(RoR2Application.onLoad, new Action(Build)); } internal static void SetHolder(MonoBehaviour behaviour) { _active = false; if (EgoPlugin.BeadsBlacklist.Value && _blocked.Count != 0 && Object.op_Implicit((Object)(object)behaviour)) { CharacterBody component = ((Component)behaviour).GetComponent<CharacterBody>(); if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.inventory)) { _active = component.inventory.GetItemCountEffective(Items.LunarTrinket) > 0; } } } internal static bool IsBlacklisted(ItemIndex index) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) if (_active) { return _blocked.Contains(index); } return false; } private static string Normalize(string text) { return new string((text ?? string.Empty).Where(char.IsLetterOrDigit).ToArray()).ToLowerInvariant(); } private static void Build() { //IL_0152: 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_0227: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) try { HashSet<ItemIndex> hashSet = new HashSet<ItemIndex>(); List<string> list = new List<string>(); List<string> list2 = new List<string>(); Dictionary<string, ItemDef> dictionary = new Dictionary<string, ItemDef>(StringComparer.OrdinalIgnoreCase); Dictionary<string, List<ItemDef>> dictionary2 = new Dictionary<string, List<ItemDef>>(); List<ItemDef> list3 = new List<ItemDef>(); for (int i = 0; i < ItemCatalog.itemCount; i++) { ItemDef itemDef = ItemCatalog.GetItemDef((ItemIndex)i); if (!Object.op_Implicit((Object)(object)itemDef)) { continue; } list3.Add(itemDef); dictionary[((Object)itemDef).name] = itemDef; if (!string.IsNullOrEmpty(itemDef.nameToken)) { string key = Normalize(Language.GetString(itemDef.nameToken)); if (!dictionary2.TryGetValue(key, out var value)) { value = (dictionary2[key] = new List<ItemDef>()); } value.Add(itemDef); } } string[][] entries = Entries; foreach (string[] array in entries) { bool flag = false; if (dictionary2.TryGetValue(Normalize(array[0]), out var value2)) { foreach (ItemDef item in value2) { hashSet.Add(item.itemIndex); list.Add(array[0] + " -> " + ((Object)item).name); flag = true; } } for (int k = 1; k < array.Length; k++) { if (dictionary.TryGetValue(array[k], out var value3)) { if (hashSet.Add(value3.itemIndex)) { list.Add(array[0] + " -> " + ((Object)value3).name + " (by internal name)"); } flag = true; } } if (!flag) { list2.Add(array[0]); } } int num = 0; int num2 = 0; foreach (ItemDef item2 in list3) { string text = TierStacks.TierId(item2); bool flag2 = TierStacks.Classify(text) == TierStacks.Category.Hex; bool flag3 = text.ToLowerInvariant().Contains("page") || (((Object)item2).name.StartsWith("Page", StringComparison.Ordinal) && ((Object)item2).name.EndsWith("Consumed", StringComparison.Ordinal)); if ((flag2 || flag3) && hashSet.Add(item2.itemIndex)) { if (flag2) { num++; } if (flag3) { num2++; } } } List<string> list5 = new List<string>(); string[] array2 = (EgoPlugin.ExtraBlacklist.Value ?? string.Empty).Split(','); for (int j = 0; j < array2.Length; j++) { string text2 = array2[j].Trim(); if (text2.Length != 0) { if (dictionary.TryGetValue(text2, out var value4)) { hashSet.Add(value4.itemIndex); list.Add("(config) " + text2); } else { list5.Add(text2); } } } _blocked = hashSet; EgoPlugin.Log.LogInfo((object)$"Beads of Fealty blacklist built: {hashSet.Count} items ({num} hexes, {num2} pages, {list.Count} named matches)."); if (list2.Count > 0) { EgoPlugin.Log.LogWarning((object)("Blacklist entries not found in this game (check the spelling/language, or add their internal names to the config): " + string.Join(", ", list2.ToArray()))); } if (list5.Count > 0) { EgoPlugin.Log.LogWarning((object)("Extra blacklist names in the config that match no item: " + string.Join(", ", list5.ToArray()))); } EgocentrismDump.Append(Environment.NewLine + "== Beads of Fealty blacklist" + Environment.NewLine + " total items: " + hashSet.Count + " (hexes " + num + ", pages " + num2 + ")" + Environment.NewLine + " resolved:" + Environment.NewLine + string.Join(Environment.NewLine, list.Select((string r) => " " + r).ToArray()) + Environment.NewLine + " NOT FOUND: " + ((list2.Count == 0) ? "(none)" : string.Join(", ", list2.ToArray())) + Environment.NewLine); } catch (Exception ex) { EgoPlugin.Log.LogError((object)("Could not build the Beads of Fealty blacklist: " + ex)); } } } internal static class EgocentrismConversion { [CompilerGenerated] private static class <>O { public static Manipulator <0>__ManipulateTransform; public static Manipulator <1>__ManipulateFilter; public static Action<MonoBehaviour> <2>__SetHolder; public static Action<CharacterMaster, ItemIndex, ItemIndex, TransformationType, int> <3>__OnTransformed; public static Func<ItemIndex, bool> <4>__IsBlacklisted; public static Func<ItemDef, int> <5>__GetRejectedTier; } private const string BehaviourTypeName = "LunarSunBehavior"; private static ILHook _transformHook; private static ILHook _filterHook; private static int _transformPatched; private static int _filterPatched; private static int _blacklistPatched; internal static void Init() { //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown //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_0096: Expected O, but got Unknown //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Expected O, but got Unknown //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Expected O, but got Unknown Type type = typeof(CharacterBody).Assembly.GetTypes().FirstOrDefault((Type t) => t.Name == "LunarSunBehavior"); if (type == null) { EgoPlugin.Log.LogError((object)"Conversion rules: could not find LunarSunBehavior. They are disabled."); return; } MethodInfo method = type.GetMethod("TransformItem", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (method == null) { EgoPlugin.Log.LogError((object)"Conversion rules: TransformItem not found. Keep-original chance and bonus stacks are disabled."); } else { object obj = <>O.<0>__ManipulateTransform; if (obj == null) { Manipulator val = ManipulateTransform; <>O.<0>__ManipulateTransform = val; obj = (object)val; } _transformHook = new ILHook((MethodBase)method, (Manipulator)obj); if (_transformPatched == 0) { _transformHook.Dispose(); _transformHook = null; EgoPlugin.Log.LogError((object)"Conversion rules: TransformItem no longer sends a transform notification. Keep-original chance and bonus stacks are disabled."); } else { EgoPlugin.Log.LogInfo((object)"Conversion rules active: keep-original chance and bonus stacks."); } } MethodInfo method2 = type.GetMethod("TransformationFilter", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (method2 == null) { EgoPlugin.Log.LogError((object)"Conversion rules: TransformationFilter not found. Used/broken items and the blacklist are disabled."); return; } object obj2 = <>O.<1>__ManipulateFilter; if (obj2 == null) { Manipulator val2 = ManipulateFilter; <>O.<1>__ManipulateFilter = val2; obj2 = (object)val2; } _filterHook = new ILHook((MethodBase)method2, (Manipulator)obj2); if (_filterPatched == 0 && _blacklistPatched == 0) { _filterHook.Dispose(); _filterHook = null; EgoPlugin.Log.LogError((object)"Conversion rules: TransformationFilter doesn't look as expected. Used/broken items and the blacklist are disabled."); return; } EgoPlugin.Log.LogInfo((object)("Conversion rules active: " + ((_filterPatched > 0) ? "used/broken items can be selected" : "used/broken patch NOT applied") + "; " + ((_blacklistPatched > 0) ? "Beads of Fealty blacklist hooked in" : "blacklist patch NOT applied") + ".")); } private static void ManipulateTransform(ILContext il) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_000f: 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_00d2: 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) ILCursor val = new ILCursor(il); val.Index = 0; val.Emit(OpCodes.Ldarg_0); val.EmitDelegate<Action<MonoBehaviour>>((Action<MonoBehaviour>)EgocentrismBlacklist.SetHolder); Type nestedType = typeof(Inventory).GetNestedType("TryTransformRandomItemsResult", BindingFlags.Public | BindingFlags.NonPublic); FieldInfo fieldInfo = ((nestedType == null) ? null : nestedType.GetField("originalItemStorageType", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); bool flag = il.Body.Variables.Count > 0 && ((MemberReference)((VariableReference)il.Body.Variables[0]).VariableType).Name == "TryTransformRandomItemsResult"; if (fieldInfo == null || !flag) { EgoPlugin.Log.LogError((object)"Conversion rules: could not find the converted item's storage type; temporary items will be treated as permanent."); } MethodReference val2 = default(MethodReference); while (val.TryGotoNext((MoveType)0, new Func<Instruction, bool>[1] { (Instruction x) => ILPatternMatchingExt.MatchCall(x, ref val2) && ((MemberReference)val2).Name == "SendTransformNotification" })) { if (fieldInfo != null && flag) { val.Emit(OpCodes.Ldloc_0); val.Emit(OpCodes.Ldfld, il.Import(fieldInfo)); } else { val.Emit(OpCodes.Ldc_I4_1); } val.Remove(); val.EmitDelegate<Action<CharacterMaster, ItemIndex, ItemIndex, TransformationType, int>>((Action<CharacterMaster, ItemIndex, ItemIndex, TransformationType, int>)OnTransformed); _transformPatched++; } } private static void OnTransformed(CharacterMaster master, ItemIndex original, ItemIndex replacement, TransformationType type, int storage) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) CharacterMasterNotificationQueue.SendTransformNotification(master, original, replacement, type); try { ApplyRules(master, original, storage); } catch (Exception ex) { EgoPlugin.Log.LogError((object)("Conversion rules failed for one conversion: " + ex)); } } private unsafe static void ApplyRules(CharacterMaster master, ItemIndex original, int storage) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)master) || !Object.op_Implicit((Object)(object)master.inventory) || !NetworkServer.active) { return; } Inventory inventory = master.inventory; ItemDef itemDef = ItemCatalog.GetItemDef(original); TierStacks.Category category; string tierId; int num = TierStacks.Stacks(itemDef, out category, out tierId); bool flag = false; float value = EgoPlugin.KeepOriginalChance.Value; if (value > 0f && Object.op_Implicit((Object)(object)itemDef)) { flag = Util.CheckRoll(value, master); if (flag) { GiveBack(inventory, original, 1, storage); } } int num2 = num - 1; if (num2 > 0) { GiveBack(inventory, Items.LunarSun.itemIndex, num2, storage); } string text = (Object.op_Implicit((Object)(object)itemDef) ? ((Object)itemDef).name : ((object)(*(ItemIndex*)(&original))/*cast due to .constrained prefix*/).ToString()); EgoPlugin.Log.LogInfo((object)string.Format("Egocentrism converted {0} {1} [{2}] -> counted as {3}: +{4} stack(s){5}.", StorageName(storage), text, tierId, category, num, flag ? ", original item kept" : string.Empty)); } private static void GiveBack(Inventory inventory, ItemIndex index, int count, int storage) { //IL_000b: 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_001e: Unknown result type (might be due to invalid IL or missing references) switch (storage) { case 2: inventory.GiveItemTemp(index, (float)count); break; case 3: inventory.GiveItemRented(index, count); break; default: inventory.GiveItemPermanent(index, count); break; } } private static string StorageName(int storage) { return storage switch { 3 => "rental", 2 => "temporary", _ => "permanent", }; } private static void ManipulateFilter(ILContext il) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_000f: 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_002a: 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_0083: 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_00be: 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_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) ILCursor val = new ILCursor(il); FieldReference val2 = null; Enumerator<Instruction> enumerator = il.Instrs.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; object operand = current.Operand; FieldReference val3 = (FieldReference)((operand is FieldReference) ? operand : null); if (current.OpCode == OpCodes.Ldfld && val3 != null && ((MemberReference)val3).Name == "itemIndex") { val2 = val3; break; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } if (val2 != null) { ILLabel val4 = val.DefineLabel(); val.Index = 0; val.Emit(OpCodes.Ldarg_0); val.Emit(OpCodes.Ldfld, val2); val.EmitDelegate<Func<ItemIndex, bool>>((Func<ItemIndex, bool>)EgocentrismBlacklist.IsBlacklisted); val.Emit(OpCodes.Brfalse, (object)val4); val.Emit(OpCodes.Ldc_I4_M1); val.Emit(OpCodes.Ret); val.MarkLabel(val4); _blacklistPatched++; } MethodReference val5 = default(MethodReference); if (val.TryGotoNext((MoveType)0, new Func<Instruction, bool>[2] { (Instruction x) => ILPatternMatchingExt.MatchCallvirt(x, ref val5) && ((MemberReference)val5).Name == "get_tier", (Instruction x) => ILPatternMatchingExt.MatchLdcI4(x, 5) })) { int index = val.Index; val.Index = index + 1; val.Remove(); val.Emit(OpCodes.Ldloc_0); val.EmitDelegate<Func<ItemDef, int>>((Func<ItemDef, int>)GetRejectedTier); _filterPatched++; } } private static int GetRejectedTier(ItemDef def) { if (EgoPlugin.AllowUsedBroken.Value && (Object)(object)def != (Object)null && ((Object)def).name != null && ((Object)def).name.EndsWith("Consumed", StringComparison.Ordinal)) { return -1; } return 5; } } internal static class EgocentrismDump { private static bool _poolDumped; private static readonly Dictionary<CharacterMaster, int[]> _pearlCounts = new Dictionary<CharacterMaster, int[]>(); private static string FilePath => Path.Combine(Paths.BepInExRootPath, "ArtifactOfEgo_dump.txt"); internal static void Init() { File.WriteAllText(FilePath, "ArtifactOfEgo diagnostic dump " + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + Environment.NewLine); RoR2Application.onLoad = (Action)Delegate.Combine(RoR2Application.onLoad, new Action(DumpItems)); RoR2Application.onLoad = (Action)Delegate.Combine(RoR2Application.onLoad, new Action(DumpInventoryApi)); } internal static void Append(string text) { try { File.AppendAllText(FilePath, text); } catch (Exception) { } } private static void DumpInventoryApi() { //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_0322: Expected O, but got Unknown //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) try { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(); stringBuilder.AppendLine("== Inventory: methods about temporary items, transforms, giving, removing, counting"); foreach (MethodInfo item in from m in typeof(Inventory).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) orderby m.Name select m) { string name = item.Name; if (name.IndexOf("temp", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("transform", StringComparison.OrdinalIgnoreCase) >= 0 || name.StartsWith("GiveItem", StringComparison.Ordinal) || name.StartsWith("RemoveItem", StringComparison.Ordinal) || name.StartsWith("GetItemCount", StringComparison.Ordinal)) { string text = string.Join(", ", (from p in item.GetParameters() select p.ParameterType.Name + " " + p.Name).ToArray()); bool flag = item.GetCustomAttributes(typeof(ObsoleteAttribute), inherit: false).Length != 0; stringBuilder.AppendLine(" " + (item.IsStatic ? "static " : "") + item.ReturnType.Name + " " + name + "(" + text + ")" + (flag ? " [obsolete]" : "")); } } stringBuilder.AppendLine(); stringBuilder.AppendLine("== Inventory: fields with 'temp' in the name"); FieldInfo[] fields = typeof(Inventory).GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.Name.IndexOf("temp", StringComparison.OrdinalIgnoreCase) >= 0) { stringBuilder.AppendLine(" " + fieldInfo.FieldType.Name + " " + fieldInfo.Name); } } Type[] nestedTypes = typeof(Inventory).GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic); foreach (Type type in nestedTypes) { stringBuilder.AppendLine(); stringBuilder.AppendLine("== Inventory nested type " + type.Name); fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo2 in fields) { stringBuilder.AppendLine(" " + fieldInfo2.FieldType.Name + " " + fieldInfo2.Name); } } foreach (MethodInfo item2 in from m in typeof(Inventory).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where m.Name == "TryTransformRandomItem" select m) { stringBuilder.AppendLine(); stringBuilder.AppendLine("-- Inventory::" + item2.Name + " (code)"); try { DynamicMethodDefinition val = new DynamicMethodDefinition((MethodBase)item2); try { Enumerator<Instruction> enumerator2 = val.Definition.Body.Instructions.GetEnumerator(); try { while (enumerator2.MoveNext()) { stringBuilder.AppendLine(" " + (object)enumerator2.Current); } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)val)?.Dispose(); } } catch (Exception ex) { stringBuilder.AppendLine(" (could not read this method's code: " + ex.Message + ")"); } } Append(stringBuilder.ToString()); } catch (Exception ex2) { EgoPlugin.Log.LogError((object)("Could not write the inventory part of the dump: " + ex2.Message)); } } private static void DumpItems() { //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_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected I4, but got Unknown try { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(); stringBuilder.AppendLine("== ItemTier enum"); foreach (ItemTier value3 in Enum.GetValues(typeof(ItemTier))) { stringBuilder.AppendLine(" " + (int)value3 + " " + ((object)value3/*cast due to .constrained prefix*/).ToString()); } stringBuilder.AppendLine(); stringBuilder.AppendLine("== Items grouped by tier (tier enum / tier def name) [category this mod counts it as]"); SortedDictionary<string, List<string>> sortedDictionary = new SortedDictionary<string, List<string>>(); for (int i = 0; i < ItemCatalog.itemCount; i++) { ItemDef itemDef = ItemCatalog.GetItemDef((ItemIndex)i); if (Object.op_Implicit((Object)(object)itemDef)) { string key = TierStacks.TierId(itemDef); if (!sortedDictionary.TryGetValue(key, out var value)) { value = (sortedDictionary[key] = new List<string>()); } value.Add(((Object)itemDef).name); } } foreach (KeyValuePair<string, List<string>> item in sortedDictionary) { stringBuilder.AppendLine(" " + item.Key + " [" + TierStacks.Classify(item.Key).ToString() + "] count=" + item.Value.Count); bool flag = item.Key.ToLowerInvariant().Contains("notier") || item.Value.Count <= 20; IEnumerable<string> enumerable; if (!flag) { enumerable = item.Value.Take(6); } else { IEnumerable<string> value2 = item.Value; enumerable = value2; } IEnumerable<string> source = enumerable; stringBuilder.AppendLine(" " + string.Join(", ", source.ToArray()) + (flag ? "" : ", ...")); } File.AppendAllText(FilePath, stringBuilder.ToString()); EgoPlugin.Log.LogInfo((object)("Wrote item tiers to " + FilePath)); } catch (Exception ex) { EgoPlugin.Log.LogError((object)("Could not write the item part of the dump: " + ex.Message)); } } internal static void ProbeCleansingPool() { if (_poolDumped) { return; } try { List<Component> list = new List<Component>(); Type type = typeof(CharacterBody).Assembly.GetType("RoR2.ShrineCleanseBehavior"); if (type != null) { Object[] array = Object.FindObjectsOfType(type); foreach (Object obj in array) { Component val = (Component)(object)((obj is Component) ? obj : null); if ((Object)(object)val != (Object)null) { list.Add(val); } } } PurchaseInteraction[] array2 = Object.FindObjectsOfType<PurchaseInteraction>(); foreach (PurchaseInteraction val2 in array2) { if (((Object)((Component)val2).gameObject).name.IndexOf("cleans", StringComparison.OrdinalIgnoreCase) >= 0) { list.Add((Component)(object)val2); } } ShopTerminalBehavior[] array3 = Object.FindObjectsOfType<ShopTerminalBehavior>(); foreach (ShopTerminalBehavior val3 in array3) { if (((Object)((Component)val3).gameObject).name.IndexOf("cleans", StringComparison.OrdinalIgnoreCase) >= 0) { list.Add((Component)(object)val3); } } if (list.Count == 0) { return; } Object[] array4 = list.Cast<Object>().ToArray(); _poolDumped = true; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(); stringBuilder.AppendLine("== Cleansing Pool found in the current scene (" + array4.Length + " of them)"); Object obj2 = array4[0]; Component val4 = (Component)(object)((obj2 is Component) ? obj2 : null); if ((Object)(object)val4 != (Object)null) { stringBuilder.AppendLine("GameObject: " + ((Object)val4.gameObject).name); int budget = 600; Component[] components = val4.gameObject.GetComponents<Component>(); foreach (Component val5 in components) { if (!((Object)(object)val5 == (Object)null)) { stringBuilder.AppendLine("-- component " + ((object)val5).GetType().FullName); DumpMembers(stringBuilder, val5, 1, ref budget); } } } File.AppendAllText(FilePath, stringBuilder.ToString()); EgoPlugin.Log.LogInfo((object)("Wrote the Cleansing Pool's components to " + FilePath)); } catch (Exception ex) { _poolDumped = true; EgoPlugin.Log.LogError((object)("Could not inspect the Cleansing Pool: " + ex.Message)); } } internal static void WatchPearls() { try { if (ItemCatalog.itemCount == 0) { return; } foreach (PlayerCharacterMasterController instance in PlayerCharacterMasterController.instances) { CharacterMaster val = (Object.op_Implicit((Object)(object)instance) ? instance.master : null); if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val.inventory)) { continue; } int itemCountPermanent = val.inventory.GetItemCountPermanent(Items.Pearl); int itemCountPermanent2 = val.inventory.GetItemCountPermanent(Items.ShinyPearl); if (_pearlCounts.TryGetValue(val, out var value)) { if (itemCountPermanent > value[0]) { EgoPlugin.Log.LogInfo((object)("Pearl gained (" + value[0] + " -> " + itemCountPermanent + "). Luck now: " + val.luck)); } if (itemCountPermanent2 > value[1]) { EgoPlugin.Log.LogInfo((object)("IRRADIANT Pearl gained (" + value[1] + " -> " + itemCountPermanent2 + "). Luck now: " + val.luck)); } } _pearlCounts[val] = new int[2] { itemCountPermanent, itemCountPermanent2 }; } } catch (Exception) { } } private static void DumpMembers(StringBuilder sb, object target, int depth, ref int budget) { string text = new string(' ', depth * 2); FieldInfo[] fields = target.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (budget <= 0) { break; } object value; try { value = fieldInfo.GetValue(target); } catch (Exception) { continue; } budget--; sb.AppendLine(text + fieldInfo.FieldType.Name + " " + fieldInfo.Name + " = " + Describe(value)); DumpChildren(sb, value, depth, ref budget); } } private static void DumpChildren(StringBuilder sb, object value, int depth, ref int budget) { if (value == null || depth >= 3 || budget <= 0) { return; } Type type = value.GetType(); if (type.IsPrimitive || type.IsEnum || value is string) { return; } if ((Object)((value is Object) ? value : null) != (Object)null) { if (value is ScriptableObject && type.Namespace != null && type.Namespace.StartsWith("RoR2")) { DumpMembers(sb, value, depth + 1, ref budget); } return; } if (value is IEnumerable enumerable) { int num = 0; { foreach (object item in enumerable) { if (num >= 12 || budget <= 0) { break; } budget--; sb.AppendLine(new string(' ', (depth + 1) * 2) + "[" + num + "] " + Describe(item)); num++; DumpChildren(sb, item, depth + 1, ref budget); } return; } } DumpMembers(sb, value, depth + 1, ref budget); } private static string Describe(object value) { if (value == null) { return "null"; } Object val = (Object)((value is Object) ? value : null); if (val != (Object)null) { return value.GetType().Name + " '" + val.name + "'"; } Type type = value.GetType(); if (type.IsPrimitive || type.IsEnum || value is string) { return value.ToString(); } if (value is ICollection collection) { return type.Name + " (" + collection.Count + " items)"; } string text = value.ToString(); if (!(text == type.FullName)) { return type.Name + " " + text; } return type.Name; } } internal static class EgocentrismScaling { [CompilerGenerated] private static class <>O { public static Manipulator <0>__Manipulate; public static Func<MonoBehaviour, float> <1>__GetInterval; } private const string BehaviourTypeName = "LunarSunBehavior"; private const string IntervalFieldName = "secondsPerTransform"; private const float FallbackInterval = 60f; private static ILHook _hook; private static FieldInfo _intervalField; private static int _patchedCount; internal static void Init() { //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Expected O, but got Unknown //IL_00af: 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_00ba: Expected O, but got Unknown Type type = typeof(CharacterBody).Assembly.GetTypes().FirstOrDefault((Type t) => t.Name == "LunarSunBehavior"); if (type == null) { EgoPlugin.Log.LogError((object)"Could not find LunarSunBehavior. Egocentrism scaling is disabled (vanilla behaviour)."); return; } _intervalField = type.GetField("secondsPerTransform", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo method = type.GetMethod("FixedUpdate", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (_intervalField == null || method == null) { EgoPlugin.Log.LogError((object)"LunarSunBehavior no longer has secondsPerTransform or FixedUpdate. Egocentrism scaling is disabled (vanilla behaviour)."); return; } _patchedCount = 0; object obj = <>O.<0>__Manipulate; if (obj == null) { Manipulator val = Manipulate; <>O.<0>__Manipulate = val; obj = (object)val; } _hook = new ILHook((MethodBase)method, (Manipulator)obj); if (_patchedCount == 0) { _hook.Dispose(); _hook = null; EgoPlugin.Log.LogError((object)"FixedUpdate no longer reads secondsPerTransform. Egocentrism scaling is disabled (vanilla behaviour)."); } else { EgoPlugin.Log.LogInfo((object)string.Format("Egocentrism scaling active: patched {0} read(s) of {1}.", _patchedCount, "secondsPerTransform")); } } private static void Manipulate(ILContext il) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_000f: Unknown result type (might be due to invalid IL or missing references) ILCursor val = new ILCursor(il); FieldReference val2 = default(FieldReference); while (val.TryGotoNext((MoveType)0, new Func<Instruction, bool>[1] { (Instruction x) => ILPatternMatchingExt.MatchLdsfld(x, ref val2) && ((MemberReference)val2).Name == "secondsPerTransform" })) { val.Next.OpCode = OpCodes.Ldarg_0; val.Next.Operand = null; int index = val.Index; val.Index = index + 1; val.EmitDelegate<Func<MonoBehaviour, float>>((Func<MonoBehaviour, float>)GetInterval); _patchedCount++; } } private static float GetInterval(MonoBehaviour behaviour) { float num = ReadBaseInterval(); float value = EgoPlugin.ScalingExponent.Value; if (value <= 0f) { return num; } CharacterBody component = ((Component)behaviour).GetComponent<CharacterBody>(); if (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)component.inventory)) { return num; } int itemCountEffective = component.inventory.GetItemCountEffective(Items.LunarSun); if (itemCountEffective <= 1) { return num; } return num / Mathf.Pow((float)itemCountEffective, value); } private static float ReadBaseInterval() { try { return (float)_intervalField.GetValue(null); } catch (Exception) { return 60f; } } } internal static class EgocentrismTooltip { private const string EgocentrismToken = "ITEM_LUNARSUN_DESC"; internal static void Init() { Language.onCurrentLanguageChanged += Apply; RoR2Application.onLoad = (Action)Delegate.Combine(RoR2Application.onLoad, new Action(Apply)); } private static string BuildEgocentrismAddition() { string text = string.Empty; if (EgoPlugin.ScalingExponent.Value > 0f) { text += " Conversion speed <style=cIsUtility>scales with stack count</style>."; } float value = EgoPlugin.KeepOriginalChance.Value; if (value > 0f) { string text2 = value.ToString("0.##", CultureInfo.InvariantCulture); text = text + " Each conversion has a <style=cIsUtility>" + text2 + "%</style> chance to <style=cIsUtility>keep the original item</style>."; } if (TierStacks.AnyBonus) { text += " Rarer items give <style=cIsUtility>more stacks</style>."; } if (EgoPlugin.AllowUsedBroken.Value) { text += " Used and broken items can be converted too."; } return text; } private static string BuildBeadsAddition() { if (!EgoPlugin.BeadsBlacklist.Value) { return string.Empty; } return " <style=cIsUtility>Tempers</style> the ego."; } private static void Apply() { Language currentLanguage = Language.currentLanguage; if (currentLanguage != null) { AppendTo(currentLanguage, "ITEM_LUNARSUN_DESC", BuildEgocentrismAddition()); ItemDef lunarTrinket = Items.LunarTrinket; if (Object.op_Implicit((Object)(object)lunarTrinket)) { AppendTo(currentLanguage, lunarTrinket.descriptionToken, BuildBeadsAddition()); } } } private static void AppendTo(Language language, string token, string addition) { if (addition.Length != 0 && !string.IsNullOrEmpty(token) && language.TokenIsRegistered(token)) { string localizedStringByToken = language.GetLocalizedStringByToken(token); if (!localizedStringByToken.Contains(addition)) { language.SetStringByToken(token, localizedStringByToken + addition); } } } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] [BepInPlugin("com.taran.artifactofego", "ArtifactOfEgo", "1.0.0")] public class EgoPlugin : BaseUnityPlugin { public const string PluginGUID = "com.taran.artifactofego"; public const string PluginName = "ArtifactOfEgo"; public const string PluginVersion = "1.0.0"; internal static ManualLogSource Log; internal static ConfigEntry<bool> ArtifactAvailable; internal static ConfigEntry<float> ScalingExponent; internal static ConfigEntry<float> KeepOriginalChance; internal static ConfigEntry<bool> AllowUsedBroken; internal static ConfigEntry<bool> BeadsBlacklist; internal static ConfigEntry<string> ExtraBlacklist; internal static ConfigEntry<bool> LuckyPearls; internal static ConfigEntry<float> ShinyPearlChance; private float _probeTimer; private void Awake() { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: 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_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; ArtifactAvailable = ((BaseUnityPlugin)this).Config.Bind<bool>("Artifact", "Artifact Of Ego Available", true, "Whether the Artifact of Ego shows up in the lobby's artifact list.\nWhen enabled and selected: every player starts the run with one Egocentrism and cannot drop below one.\nTakes effect on game restart. Everyone in a multiplayer lobby must use the same value."); ScalingExponent = ((BaseUnityPlugin)this).Config.Bind<float>("Egocentrism", "Conversion Scaling Exponent (P)", 0.3f, new ConfigDescription("How much faster Egocentrism converts items as you stack it.\nConversion speed is multiplied by (stacks ^ P).\n P = 0 -> vanilla: one item every 60 seconds no matter how many stacks you have.\n P = 1 -> fully linear: 2 stacks convert twice as fast, 10 stacks ten times as fast.\n In between -> speeds up as you stack, with diminishing returns.\n\nExamples. Time for ONE Egocentrism, with unlimited other items to convert (each conversion\nadds a stack), to reach one conversion every 3 seconds:\n P = 0.3 -> about 26 hours (21,700 stacks) [default] - effectively never reaches it\n P = 0.35 -> about 6.6 hours (5,200 stacks)\n P = 0.4 -> about 2.5 hours (1,800 stacks)\n P = 0.5 -> about 38 minutes (400 stacks)\n P = 0.6 -> about 16 minutes (150 stacks)\n P = 0.7 -> about 9 minutes (72 stacks)\n P = 0.8 -> about 6 minutes (42 stacks)\n P = 1.0 -> about 3 minutes (20 stacks)\nIn a real run you are capped by how many items you own, so the lower values never reach 3 seconds.\nOnly the host's value matters for conversion speed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); KeepOriginalChance = ((BaseUnityPlugin)this).Config.Bind<float>("Egocentrism", "Keep Original Item Chance (%)", 1f, new ConfigDescription("Chance, in percent, that an Egocentrism conversion does NOT destroy the item it picked.\nWhen that happens you keep the item AND still gain the Egocentrism stack.\n0 turns the feature off. Only the host's value matters.\n\nThis roll is affected by luck, like the game's own chances: positive luck (Clover etc.) gives\nextra attempts, negative luck (Purity) makes it worse. At the default 1%, as far as I know:\n luck 0 -> 1.0% luck 1 -> 2.0% luck 2 -> 3.0% luck 3 -> 3.9% luck 5 -> 5.9% luck 10 -> 10.5%", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); AllowUsedBroken = ((BaseUnityPlugin)this).Config.Bind<bool>("Egocentrism", "Convert Used And Broken Items", true, "Whether Egocentrism can pick used/broken items (Dio's Best Friend once used, Delicate Watch once broken,\nPower Elixir once used, and so on) as well as normal ones. Vanilla never picks them.\nOnly items whose internal name ends in 'Consumed' are included. Hidden gameplay items with no tier\n(difficulty helpers, survivor passives) stay excluded, since converting those would break the game.\nOnly the host's value matters."); BeadsBlacklist = ((BaseUnityPlugin)this).Config.Bind<bool>("Beads Of Fealty", "Enable Egocentrism Blacklist", true, "While you hold Beads of Fealty, Egocentrism will not pick the items on a built-in list:\nkeys, Irradiant Pearls, items that give items (Regenerating Scrap, Sale Star, Shipping Request Form, 57 Leaf Clover,\nSubstandard Duplicator, Sonorous Whispers...), cerebellums, Functional Coupler, Eulogy Zero, Longstanding Solitude,\nBenthic Bloom, Peace Flower, Dream Crucible, Gesture of the Drowned, Beads of Fealty, every Hex and every N'tormat page.\nEgocentrism itself is always excluded. Without Beads of Fealty, nothing is blacklisted.\nOnly the host's value matters."); ExtraBlacklist = ((BaseUnityPlugin)this).Config.Bind<string>("Beads Of Fealty", "Extra Blacklisted Items", string.Empty, "Extra items to add to the blacklist, as internal item names separated by commas, for example: Clover, TreasureCache\nInternal names are in ArtifactOfEgo_dump.txt (untiered items) or can be listed with DebugToolkit's list_item command.\nTakes effect on game restart."); LuckyPearls = ((BaseUnityPlugin)this).Config.Bind<bool>("Cleansing Pool", "Luck Affects Irradiant Pearl", true, "When you buy from a Cleansing Pool, the Pearl / Irradiant Pearl roll is redone using your luck, like the game's\nother chances: Clover etc. help, Purity hurts. Off = vanilla (the pool decides when it is created, luck ignored).\nTakes effect on game restart. Only the host's value matters."); ShinyPearlChance = ((BaseUnityPlugin)this).Config.Bind<float>("Cleansing Pool", "Irradiant Pearl Chance (%)", 20f, new ConfigDescription("Base chance that a Cleansing Pool gives an Irradiant Pearl instead of a Pearl. The game's pool uses 20%.\nLuck example at 20%: luck 0 -> 20%, 1 -> 36%, 2 -> 48.8%, 3 -> 59%, 5 -> 73.8%, 10 -> 91.4%.\nOnly used when 'Luck Affects Irradiant Pearl' is on.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); TierStacks.Bind(((BaseUnityPlugin)this).Config); Start("Artifact of Ego", delegate { if (ArtifactAvailable.Value) { EgoArtifact.Init(); } else { Log.LogInfo((object)"Artifact of Ego is switched off in the config, so it was not registered."); } }); Start("Diagnostic dump", EgocentrismDump.Init); Start("Egocentrism scaling", EgocentrismScaling.Init); Start("Beads of Fealty blacklist", EgocentrismBlacklist.Init); Start("Egocentrism conversion rules", EgocentrismConversion.Init); Start("Egocentrism tooltip", EgocentrismTooltip.Init); Start("Cleansing Pool luck", EgoPool.Init); } private void Update() { _probeTimer += Time.unscaledDeltaTime; if (!(_probeTimer < 1f)) { _probeTimer = 0f; EgocentrismDump.ProbeCleansingPool(); EgocentrismDump.WatchPearls(); } } private static void Start(string feature, Action init) { try { init(); } catch (Exception arg) { Log.LogError((object)$"{feature} failed to start and was skipped: {arg}"); } } } internal static class EgoPool { private delegate void OrigInteract(PurchaseInteraction self, Interactor activator); private static Hook _hook; private static FieldInfo _pickupField; private static FieldInfo _pickupIndexField; private static FieldInfo _dropTableField; private static MethodInfo _setPickup; private static bool _setPickupTakesUnique; internal static void Init() { //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Expected O, but got Unknown if (!EgoPlugin.LuckyPearls.Value) { EgoPlugin.Log.LogInfo((object)"Cleansing Pool luck is switched off in the config."); return; } MethodInfo method = typeof(PurchaseInteraction).GetMethod("OnInteractionBegin", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); Type? typeFromHandle = typeof(ShopTerminalBehavior); _pickupField = typeFromHandle.GetField("pickup", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _dropTableField = typeFromHandle.GetField("dropTable", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _pickupIndexField = ((_pickupField == null) ? null : _pickupField.FieldType.GetField("pickupIndex", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); MethodInfo[] methods = typeFromHandle.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (!(methodInfo.Name != "SetPickup") && methodInfo.GetParameters().Length == 1) { Type parameterType = methodInfo.GetParameters()[0].ParameterType; if (_pickupField != null && parameterType == _pickupField.FieldType) { _setPickup = methodInfo; _setPickupTakesUnique = true; break; } if (_pickupIndexField != null && parameterType == _pickupIndexField.FieldType && _setPickup == null) { _setPickup = methodInfo; _setPickupTakesUnique = false; } } } if (method == null || _pickupField == null || _pickupIndexField == null || _dropTableField == null) { EgoPlugin.Log.LogError((object)"Cleansing Pool luck: the pool's code isn't what the mod expected, so it is disabled (vanilla pool)."); return; } _hook = new Hook((MethodBase)method, (Delegate)new Action<OrigInteract, PurchaseInteraction, Interactor>(OnInteract)); EgoPlugin.Log.LogInfo((object)("Cleansing Pool luck active: Irradiant Pearl chance " + EgoPlugin.ShinyPearlChance.Value + "% (luck applies)" + ((_setPickup == null) ? " [no SetPickup found, writing the pickup directly]" : "."))); } private static void OnInteract(OrigInteract orig, PurchaseInteraction self, Interactor activator) { try { Reroll(self, activator); } catch (Exception ex) { EgoPlugin.Log.LogError((object)("Cleansing Pool luck failed for one purchase (vanilla result used): " + ex)); } orig(self, activator); } private static void Reroll(PurchaseInteraction self, Interactor activator) { //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) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: 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_00a6: 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_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: 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_00fd: 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) //IL_0168: 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_017b: 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) if (!NetworkServer.active || !Object.op_Implicit((Object)(object)self) || !self.available || !Object.op_Implicit((Object)(object)activator) || !self.CanBeAffordedByInteractor(activator)) { return; } ShopTerminalBehavior component = ((Component)self).GetComponent<ShopTerminalBehavior>(); if (!Object.op_Implicit((Object)(object)component)) { return; } object? value = _dropTableField.GetValue(component); Object val = (Object)((value is Object) ? value : null); if (val == (Object)null || val.name != "dtPearls") { return; } PickupIndex val2 = PickupCatalog.FindPickupIndex(Items.Pearl.itemIndex); PickupIndex val3 = PickupCatalog.FindPickupIndex(Items.ShinyPearl.itemIndex); object value2 = _pickupField.GetValue(component); PickupIndex val4 = (PickupIndex)_pickupIndexField.GetValue(value2); if (val4 != val2 && val4 != val3) { return; } CharacterBody component2 = ((Component)activator).GetComponent<CharacterBody>(); CharacterMaster val5 = (Object.op_Implicit((Object)(object)component2) ? component2.master : null); if (!Object.op_Implicit((Object)(object)val5)) { return; } float value3 = EgoPlugin.ShinyPearlChance.Value; bool flag = Util.CheckRoll(value3, val5); PickupIndex val6 = (flag ? val3 : val2); EgoPlugin.Log.LogInfo((object)("Cleansing Pool roll: " + (flag ? "IRRADIANT Pearl" : "Pearl") + " (base chance " + value3 + "%, luck " + val5.luck + ").")); if (!(val6 == val4)) { _pickupIndexField.SetValue(value2, val6); if (_setPickup == null) { _pickupField.SetValue(component, value2); return; } _setPickup.Invoke(component, new object[1] { _setPickupTakesUnique ? value2 : ((object)val6) }); } } } internal static class TierStacks { internal enum Category { Common, Uncommon, Legendary, Boss, Hallowed, VoidCommon, VoidUncommon, VoidLegendary, VoidBoss, Hex, Lunar, UsedBroken, Other } private static readonly Dictionary<Category, ConfigEntry<int>> Entries = new Dictionary<Category, ConfigEntry<int>>(); private static ConfigEntry<int> _pearlStacks; internal static bool AnyBonus => Entries.Values.Any((ConfigEntry<int> e) => e.Value > 1); internal static void Bind(ConfigFile config) { //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Expected O, but got Unknown Add(config, Category.Common, "Common (white)", 1, null); Add(config, Category.Uncommon, "Uncommon (green)", 2, null); Add(config, Category.Legendary, "Legendary (red)", 3, null); Add(config, Category.Boss, "Boss (yellow)", 3, null); Add(config, Category.Hallowed, "Hallowed", 3, "In the game's code this tier is called 'Cursed' (Sanguine Chalice, Vile Censer, Golden Goose and so on)."); Add(config, Category.VoidCommon, "Void common", 2, null); Add(config, Category.VoidUncommon, "Void uncommon", 3, null); Add(config, Category.VoidLegendary, "Void legendary", 4, null); Add(config, Category.VoidBoss, "Void boss", 3, "You didn't specify this one, so it follows normal boss items."); Add(config, Category.Hex, "Hex", 2, "Matched by the game's tier name containing 'hex'."); Add(config, Category.Lunar, "Lunar", 2, null); Add(config, Category.UsedBroken, "Used / broken", 1, "Only matters if used/broken items can be picked for conversion."); Add(config, Category.Other, "Anything else (unrecognised tiers)", 1, "Items from other mods' custom tiers land here."); _pearlStacks = config.Bind<int>("Stacks Per Conversion", "Pearl (normal)", 1, new ConfigDescription("Stacks gained when a normal Pearl is converted. The Pearl is a boss-tier item, but it uses this setting instead of the Boss one.\nThe Irradiant Pearl is not affected (it is on the Beads of Fealty blacklist).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50), Array.Empty<object>())); } private static void Add(ConfigFile config, Category category, string label, int defaultValue, string extra) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown string text = "How many Egocentrism stacks you gain when an item of this rarity is converted (or spared by the keep-original chance).\nVanilla Egocentrism always gives 1. Values below 1 are not allowed." + ((extra == null) ? string.Empty : ("\n" + extra)); Entries[category] = config.Bind<int>("Stacks Per Conversion", label, defaultValue, new ConfigDescription(text, (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50), Array.Empty<object>())); } internal static int Stacks(ItemDef def, out Category category, out string tierId) { tierId = (Object.op_Implicit((Object)(object)def) ? TierId(def) : "?/-"); category = Classify(tierId); if (Object.op_Implicit((Object)(object)def) && ((Object)def).name == "Pearl") { return Math.Max(1, _pearlStacks.Value); } return Math.Max(1, Entries[category].Value); } internal static string TierId(ItemDef def) { try { Type typeFromHandle = typeof(ItemDef); object obj = null; PropertyInfo property = typeFromHandle.GetProperty("tier", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null) { obj = property.GetValue(def, null); } if (obj == null) { FieldInfo fieldInfo = typeFromHandle.GetField("tier", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? typeFromHandle.GetField("deprecatedTier", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (fieldInfo != null) { obj = fieldInfo.GetValue(def); } } object obj2 = null; PropertyInfo property2 = typeFromHandle.GetProperty("itemTierDef", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property2 != null) { obj2 = property2.GetValue(def, null); } if (obj2 == null) { FieldInfo field = typeFromHandle.GetField("_itemTierDef", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { obj2 = field.GetValue(def); } } Object val = (Object)((obj2 is Object) ? obj2 : null); string obj3 = ((obj != null) ? obj.ToString() : "?"); string text = ((val != (Object)null) ? val.name : "-"); return obj3 + "/" + text; } catch (Exception) { return "?/-"; } } internal static Category Classify(string tierId) { string text = (tierId ?? string.Empty).ToLowerInvariant(); if (text.Contains("notier") || text.Contains("no tier") || text.Contains("untiered")) { return Category.UsedBroken; } if (text.Contains("hallow") || text.Contains("cursed")) { return Category.Hallowed; } if (text.Contains("hex")) { return Category.Hex; } if (text.Contains("void")) { if (text.Contains("boss")) { return Category.VoidBoss; } if (text.Contains("tier3") || text.Contains("legend")) { return Category.VoidLegendary; } if (text.Contains("tier2") || text.Contains("uncommon")) { return Category.VoidUncommon; } return Category.VoidCommon; } if (text.Contains("lunar")) { return Category.Lunar; } if (text.Contains("boss")) { return Category.Boss; } if (text.Contains("tier3") || text.Contains("legend")) { return Category.Legendary; } if (text.Contains("tier2") || text.Contains("uncommon")) { return Category.Uncommon; } if (text.Contains("tier1") || text.Contains("common")) { return Category.Common; } return Category.Other; } } }