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 SkillLoss v1.2.0
plugins/TXC.SkillLoss.dll
Decompiled 2 months 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 System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: AssemblyCompany("TXC.SkillLoss")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.2.0.0")] [assembly: AssemblyInformationalVersion("1.2.0")] [assembly: AssemblyProduct("TXC.SkillLoss")] [assembly: AssemblyTitle("TXC.SkillLoss")] [assembly: AssemblyVersion("1.2.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 TXC.SkillLoss { [BepInPlugin("txc.skillloss", "TXC Skill Loss", "1.2.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] [SynchronizationMode(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public const string PluginGuid = "txc.skillloss"; public const string PluginName = "TXC Skill Loss"; public const string PluginVersion = "1.2.0"; internal static ManualLogSource Log; private Harmony _harmony; private void Awake() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; PluginConfig.Init(((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Logger); _harmony = new Harmony("txc.skillloss"); _harmony.PatchAll(typeof(Patches)); _harmony.PatchAll(typeof(XpPatches)); CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new ClearDeathCommand()); CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new SkillsCommand()); Log.LogInfo((object)"TXC Skill Loss 1.2.0 loaded."); } private void OnDestroy() { Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } internal unsafe static string SkillDisplayName(SkillType skill) { Localization instance = Localization.instance; string text = ((instance != null) ? instance.Localize("$skill_" + ((object)(*(SkillType*)(&skill))/*cast due to .constrained prefix*/).ToString().ToLowerInvariant()) : null) ?? string.Empty; if (string.IsNullOrWhiteSpace(text) || text.StartsWith("[")) { text = "Skill"; } text = Regex.Replace(text, "[=\\n\\t\\\\\"'\\[\\]()]", string.Empty).Trim(); if (text.Length != 0) { return text; } return "Skill"; } } internal static class CatchUp { private const string DataKey = "txc.skillloss.peaks"; private static readonly Dictionary<SkillType, float> Peaks = new Dictionary<SkillType, float>(); private static Player _owner; internal static bool Ensure(Player player, Skills skills) { //IL_00c5: 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) if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer) { return false; } if ((Object)(object)_owner != (Object)(object)player) { _owner = player; Peaks.Clear(); int num = Load(player); TrackAll(skills); Plugin.Log.LogInfo((object)$"Catch-up XP: tracking peak levels for {Peaks.Count} skills ({num} loaded from the character)."); if (PluginConfig.DebugLogging.Value) { Dictionary<SkillType, Skill> dictionary = Patches.SkillData.Invoke(skills); foreach (KeyValuePair<SkillType, float> item in Peaks.OrderBy((KeyValuePair<SkillType, float> p) => ((object)p.Key/*cast due to .constrained prefix*/).ToString())) { Skill value; float num2 = (dictionary.TryGetValue(item.Key, out value) ? Patches.EffectiveLevel(value) : 0f); Plugin.Log.LogInfo((object)$" [debug] peak {item.Key}: {item.Value:0.00} (now {num2:0.00})"); } } } return true; } internal static float GetPeak(SkillType type) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (!Peaks.TryGetValue(type, out var value)) { return -1f; } return value; } internal static void TrackAll(Skills skills) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) foreach (KeyValuePair<SkillType, Skill> item in Patches.SkillData.Invoke(skills)) { Track(item.Key, item.Value); } } internal static void Track(SkillType type, Skill skill) { //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) float num = Patches.EffectiveLevel(skill); if (!Peaks.TryGetValue(type, out var value) || num > value) { Peaks[type] = num; } } internal static float XpMultiplier(SkillType type, Skill skill) { //IL_0000: 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) PluginConfig.GetCatchUp(type, out var perLevel, out var max); if (perLevel <= 0f || max <= 0f || !Peaks.TryGetValue(type, out var value)) { return 1f; } float num = value - Patches.EffectiveLevel(skill); if (!(num <= 0f)) { return 1f + Math.Min(max, perLevel * num); } return 1f; } internal static void Save(Player player) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected I4, but got Unknown if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)_owner || Peaks.Count == 0) { return; } StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair<SkillType, float> peak in Peaks) { if (stringBuilder.Length > 0) { stringBuilder.Append(';'); } stringBuilder.Append(((int)peak.Key).ToString(CultureInfo.InvariantCulture)).Append(':').Append(peak.Value.ToString("0.####", CultureInfo.InvariantCulture)); } player.m_customData["txc.skillloss.peaks"] = stringBuilder.ToString(); } private static int Load(Player player) { if (!player.m_customData.TryGetValue("txc.skillloss.peaks", out var value) || string.IsNullOrEmpty(value)) { return 0; } 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 && int.TryParse(array2[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && float.TryParse(array2[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { Peaks[(SkillType)result] = Math.Max(0f, Math.Min(100f, result2)); } } return Peaks.Count; } } internal static class Patches { internal static readonly FieldRef<Skills, Dictionary<SkillType, Skill>> SkillData = AccessTools.FieldRefAccess<Skills, Dictionary<SkillType, Skill>>("m_skillData"); private static readonly FieldRef<Skills, Player> SkillsPlayer = AccessTools.FieldRefAccess<Skills, Player>("m_player"); private static readonly FieldRef<Player, Skills> PlayerSkills = AccessTools.FieldRefAccess<Player, Skills>("m_skills"); private static readonly FieldRef<Character, HitData> LastHit = AccessTools.FieldRefAccess<Character, HitData>("m_lastHit"); private static bool _loggedWorldMultiplier; internal const int MaxLevel = 100; [HarmonyPatch(typeof(Skills), "OnDeath")] [HarmonyPrefix] [HarmonyPriority(800)] private static bool SkillsOnDeath(Skills __instance, ref Dictionary<SkillType, Skill> __state) { //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_025a: 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_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_0343: Unknown result type (might be due to invalid IL or missing references) //IL_0425: Unknown result type (might be due to invalid IL or missing references) //IL_042a: Unknown result type (might be due to invalid IL or missing references) //IL_042e: Unknown result type (might be due to invalid IL or missing references) __state = null; try { float num = __instance.m_DeathLowerFactor * Game.m_skillReductionRate * 100f; float num2 = 1f; if (PluginConfig.ApplyWorldDeathPenalty.Value) { num2 = num / 5f; } if (!_loggedWorldMultiplier) { _loggedWorldMultiplier = true; Plugin.Log.LogInfo((object)($"World death penalty: vanilla loss {num:0.##}%" + (PluginConfig.ApplyWorldDeathPenalty.Value ? $" -> configured losses x{num2:0.##}." : "."))); } Player val = SkillsPlayer.Invoke(__instance); HitData val2 = (((Object)(object)val != (Object)null) ? LastHit.Invoke((Character)(object)val) : null); DeathCause deathCause = PluginConfig.GetDeathCause(val2); float causeMultiplier = PluginConfig.GetCauseMultiplier(deathCause); bool value = PluginConfig.DebugLogging.Value; Plugin.Log.LogInfo((object)(string.Format("Death by {0} ({1}): loss x{2:0.##}.", ((object)Unsafe.As<HitType, HitType>(ref val2?.m_hitType)/*cast due to .constrained prefix*/).ToString() ?? "unknown", deathCause, causeMultiplier) + (value ? $" [{PluginConfig.TogglesSummary()}; world vanilla loss {num:0.##}%]" : ""))); if (CatchUp.Ensure(val, __instance)) { CatchUp.TrackAll(__instance); } bool flag = false; foreach (KeyValuePair<SkillType, Skill> item in SkillData.Invoke(__instance)) { float? lossPercent = PluginConfig.GetLossPercent(item.Key); float num3 = (lossPercent.HasValue ? (lossPercent.Value * num2) : num); float num4 = Math.Min(1f, Math.Max(0f, num3 / 100f * causeMultiplier)); Skill value2 = item.Value; float num5 = EffectiveLevel(value2); if (num4 <= 0f) { if (value && num5 > 0f) { Plugin.Log.LogInfo((object)$" [debug] {item.Key}: {num5:0.00} kept (loss {num3:0.##}% x{causeMultiplier:0.##} = 0)"); } continue; } if (PluginConfig.Mode.Value == LossMode.TotalXp) { LowerTotalXp(value2, num4); } else { value2.m_level -= value2.m_level * num4; value2.m_accumulator = 0f; } float levelCap = PluginConfig.GetLevelCap(item.Key); float num6 = EffectiveLevel(value2); ApplyCap(value2, num5, levelCap); flag = true; if (value) { float num7 = EffectiveLevel(value2); Plugin.Log.LogInfo((object)($" [debug] {item.Key}: {num5:0.00} -> {num7:0.00} (-{num5 - num7:0.00}; loss " + $"{num3:0.##}% x{causeMultiplier:0.##} = {num4 * 100f:0.##}%" + ((levelCap > 0f) ? string.Format(", cap {0:0.##}{1}", levelCap, (num7 > num6 + 0.001f) ? $" applied (uncapped {num6:0.00})" : "") : "") + $"; peak {CatchUp.GetPeak(item.Key):0.00})")); } } if (flag) { Player localPlayer = Player.m_localPlayer; if (localPlayer != null) { ((Character)localPlayer).Message((MessageType)1, "$msg_skills_lowered", 0, (Sprite)null, false); } } Dictionary<SkillType, Skill> dictionary = SkillData.Invoke(__instance); __state = dictionary.Where((KeyValuePair<SkillType, Skill> x) => !PluginConfig.IsVanilla(x.Key)).ToDictionary((KeyValuePair<SkillType, Skill> x) => x.Key, (KeyValuePair<SkillType, Skill> x) => x.Value); foreach (SkillType key in __state.Keys) { dictionary.Remove(key); } return false; } catch (Exception arg) { Plugin.Log.LogError((object)$"Skill loss failed, falling back to vanilla: {arg}"); return true; } } internal static double Requirement(int level) { return Math.Pow(level + 1, 1.5) * 0.5 + 0.5; } private static double TotalXpForLevel(int level) { double num = 0.0; for (int i = 0; i < level; i++) { num += Requirement(i); } return num; } internal static float EffectiveLevel(Skill skill) { int num = Math.Max(0, Math.Min(100, (int)Math.Floor(skill.m_level))); if (num >= 100) { return 100f; } double val = (double)(skill.m_level - (float)num) + (double)skill.m_accumulator / Requirement(num); return (float)num + (float)Math.Min(0.9999, Math.Max(0.0, val)); } private static void LowerTotalXp(Skill skill, float factor) { int num = Math.Max(0, Math.Min(100, (int)Math.Floor(skill.m_level))); double num2 = TotalXpForLevel(num); if (num < 100) { double num3 = Requirement(num); num2 += Math.Min(num3, (double)(skill.m_level - (float)num) * num3 + (double)skill.m_accumulator); } double num4 = num2 * (1.0 - (double)factor); int i; for (i = 0; i < 100 && num4 >= Requirement(i); i++) { num4 -= Requirement(i); } skill.m_level = i; skill.m_accumulator = ((i >= 100) ? 0f : ((float)num4)); } private static void ApplyCap(Skill skill, float before, float cap) { if (!(cap <= 0f) && !(before - EffectiveLevel(skill) <= cap)) { float num = Math.Max(0f, before - cap); int num2 = Math.Min(100, (int)Math.Floor(num)); skill.m_level = num2; skill.m_accumulator = ((num2 >= 100) ? 0f : ((float)((double)(num - (float)num2) * Requirement(num2)))); } } [HarmonyPatch(typeof(Skills), "OnDeath")] [HarmonyFinalizer] private static void SkillsOnDeathFinalizer(Skills __instance, Dictionary<SkillType, Skill> __state) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (__state == null) { return; } Dictionary<SkillType, Skill> dictionary = SkillData.Invoke(__instance); foreach (KeyValuePair<SkillType, Skill> item in __state) { dictionary[item.Key] = item.Value; } } internal static Player GetPlayer(Skills skills) { return SkillsPlayer.Invoke(skills); } [HarmonyPatch(typeof(Player), "Save")] [HarmonyPrefix] private static void PlayerSave(Player __instance) { try { CatchUp.Save(__instance); } catch (Exception arg) { Plugin.Log.LogWarning((object)$"Saving peak levels failed: {arg}"); } } [HarmonyPatch(typeof(Player), "OnSpawned")] [HarmonyPostfix] private static void PlayerOnSpawned(Player __instance) { //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer) { return; } try { Skills val = PlayerSkills.Invoke(__instance); if ((Object)(object)val == (Object)null) { return; } CatchUp.Ensure(__instance, val); Plugin.Log.LogInfo((object)("Active settings: " + PluginConfig.TogglesSummary() + (PluginConfig.DebugLogging.Value ? " (debug logging on)" : ""))); HashSet<SkillType> hashSet = new HashSet<SkillType>(SkillData.Invoke(val).Keys); foreach (SkillDef skill in val.m_skills) { hashSet.Add(skill.m_skill); } foreach (SkillType item in hashSet.Where((SkillType t) => !PluginConfig.IsVanilla(t))) { PluginConfig.DiscoverModdedSkill(item, Plugin.SkillDisplayName(item)); } } catch (Exception arg) { Plugin.Log.LogWarning((object)$"Modded skill discovery failed: {arg}"); } } } internal sealed class ClearDeathCommand : ConsoleCommand { public override string Name => "skillloss_cleardeath"; public override string Help => "Ends the 'No skill drain' period after a death, so the next death loses skills again (testing)"; public override bool IsCheat => true; public override void Run(string[] args, Terminal context) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { if (context != null) { context.AddString("No character loaded."); } return; } localPlayer.ClearHardDeath(); bool flag = ((Character)localPlayer).GetSEMan().RemoveStatusEffect(SEMan.s_statusEffectSoftDeath, false); string text = "No skill drain cleared" + (flag ? " (buff removed)." : ".") + " The next death applies the skill loss."; if (context != null) { context.AddString(text); } Plugin.Log.LogInfo((object)text); } } internal sealed class SkillsCommand : ConsoleCommand { public override string Name => "skillloss_skills"; public override string Help => "Lists your skills with level, peak, catch-up and XP multipliers (also written to the log)"; public override void Run(string[] args, Terminal context) { //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_0108: 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_00e9: 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_00ff: Expected I4, but got Unknown //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; Skills val = (((Object)(object)localPlayer != (Object)null) ? ((Character)localPlayer).GetSkills() : null); if ((Object)(object)val == (Object)null || !CatchUp.Ensure(localPlayer, val)) { if (context != null) { context.AddString("No character loaded."); } return; } Plugin.Log.LogInfo((object)("skillloss_skills: " + PluginConfig.TogglesSummary())); foreach (KeyValuePair<SkillType, Skill> item in from p in Patches.SkillData.Invoke(val) orderby ((object)p.Key/*cast due to .constrained prefix*/).ToString() select p) { float num = Patches.EffectiveLevel(item.Value); float num2 = CatchUp.XpMultiplier(item.Key, item.Value); float xpGainMultiplier = PluginConfig.GetXpGainMultiplier(item.Key); float? lossPercent = PluginConfig.GetLossPercent(item.Key); string text = (PluginConfig.IsVanilla(item.Key) ? ((object)item.Key/*cast due to .constrained prefix*/).ToString() : $"{Plugin.SkillDisplayName(item.Key)} ({(int)item.Key})"); string text2 = $"{text}: {num:0.00} (peak {CatchUp.GetPeak(item.Key):0.00}) | XP x{xpGainMultiplier * num2:0.###} " + string.Format("(XpGain {0:0.00} x catch-up {1:0.###}) | loss {2}", xpGainMultiplier, num2, lossPercent.HasValue ? (lossPercent.Value.ToString("0.##") + "%") : "world default") + $", cap {PluginConfig.GetLevelCap(item.Key):0.##}"; if (context != null) { context.AddString(text2); } Plugin.Log.LogInfo((object)(" " + text2)); } } } internal static class XpPatches { internal struct RaiseState { public bool Active; public bool Carry; public int Level; public float Accumulator; public float Gain; public float BaseGain; public float XpGain; public float CatchUp; } private sealed class XpTally { public float Since; public int Count; public float Base; public float Gained; public float XpGain; public float CatchUp; } private const float TallySeconds = 10f; private static readonly Dictionary<SkillType, XpTally> Tallies = new Dictionary<SkillType, XpTally>(); [HarmonyPatch(typeof(Skills), "RaiseSkill")] [HarmonyPrefix] private static void SkillsRaiseSkill(Skills __instance, SkillType skillType, ref float factor, out RaiseState __state) { //IL_0007: 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_0030: 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) __state = default(RaiseState); try { if ((int)skillType != 0 && CatchUp.Ensure(Patches.GetPlayer(__instance), __instance)) { float xpGainMultiplier = PluginConfig.GetXpGainMultiplier(skillType); Patches.SkillData.Invoke(__instance).TryGetValue(skillType, out var value); float num = ((value != null) ? CatchUp.XpMultiplier(skillType, value) : 1f); float num2 = xpGainMultiplier * num; float num3 = factor; factor *= num2; if (value?.m_info != null && value.m_level < 100f) { float num4 = value.m_info.m_increseStep * Game.m_skillGainRate; __state = new RaiseState { Active = true, Carry = (num2 > 1f), Level = (int)Math.Floor(value.m_level), Accumulator = value.m_accumulator, Gain = num4 * factor, BaseGain = num4 * num3, XpGain = xpGainMultiplier, CatchUp = num }; } } } catch (Exception arg) { Plugin.Log.LogWarning((object)$"XP multiplier failed: {arg}"); } } [HarmonyPatch(typeof(Skills), "RaiseSkill")] [HarmonyPostfix] private static void SkillsRaiseSkillPostfix(Skills __instance, SkillType skillType, RaiseState __state) { //IL_0000: 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_00e3: 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) try { if ((int)skillType == 0 || !CatchUp.Ensure(Patches.GetPlayer(__instance), __instance) || !Patches.SkillData.Invoke(__instance).TryGetValue(skillType, out var value)) { return; } bool flag = __state.Active && (int)Math.Floor(value.m_level) > __state.Level; float carried = 0f; if (__state.Carry && flag && value.m_level < 100f) { double num = (double)(__state.Accumulator + __state.Gain) - Patches.Requirement(__state.Level); float num2 = __state.Gain - __state.BaseGain; if (num > 0.0 && num2 > 0f) { double num3 = Patches.Requirement((int)Math.Floor(value.m_level)); carried = (value.m_accumulator = (float)Math.Min(Math.Min(num, num2), num3 * 0.99)); } } CatchUp.Track(skillType, value); if (__state.Active && PluginConfig.DebugLogging.Value) { LogXp(skillType, value, __state, flag, carried); } } catch (Exception arg) { Plugin.Log.LogWarning((object)$"XP tracking failed: {arg}"); } } private static void LogXp(SkillType type, Skill skill, RaiseState state, bool leveledUp, float carried) { //IL_000b: 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_0027: 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_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Unknown result type (might be due to invalid IL or missing references) float time = Time.time; if (!Tallies.TryGetValue(type, out var value)) { value = new XpTally { Since = time }; Tallies[type] = value; } value.Count++; value.Base += state.BaseGain; value.Gained += state.Gain; value.XpGain = state.XpGain; value.CatchUp = state.CatchUp; float num = Patches.EffectiveLevel(skill); float peak = CatchUp.GetPeak(type); if (leveledUp) { Plugin.Log.LogInfo((object)($" [debug] LEVEL UP {type} {state.Level} -> {(int)Math.Floor(skill.m_level)} " + $"(x{state.XpGain * state.CatchUp:0.###} = XpGain {state.XpGain:0.00} x catch-up {state.CatchUp:0.###}" + ((carried > 0f) ? $"; carried {carried:0.###} XP into the new level" : "") + $"; peak {peak:0.00})")); } if (!(time - value.Since < 10f) || leveledUp) { Plugin.Log.LogInfo((object)($" [debug] XP {type}: +{value.Gained:0.###} from {value.Count} gain(s) in {time - value.Since:0}s " + $"(vanilla would be +{value.Base:0.###}; x{value.XpGain * value.CatchUp:0.###} = XpGain {value.XpGain:0.00} " + $"x catch-up {value.CatchUp:0.###}); now {num:0.00}, peak {peak:0.00}" + ((peak > num) ? $", {peak - num:0.00} below" : ""))); Tallies.Remove(type); } } } public enum LossMode { Level, TotalXp } public enum Scope { Off, Category, Skill } public enum Toggle { Off, On } public enum DeathCause { Enemy, PvP, Fall, Drowning, Environment, Accident, Other } public readonly struct Scale : IComparable, IComparable<Scale>, IEquatable<Scale> { public readonly float Value; public Scale(float value) { Value = (float)Math.Round(value, 2); } public int CompareTo(Scale other) { float value = Value; return value.CompareTo(other.Value); } public int CompareTo(object obj) { if (!(obj is Scale other)) { return 1; } return CompareTo(other); } public bool Equals(Scale other) { float value = Value; return value.Equals(other.Value); } public override bool Equals(object obj) { if (obj is Scale other) { return Equals(other); } return false; } public override int GetHashCode() { float value = Value; return value.GetHashCode(); } public override string ToString() { float value = Value; return value.ToString("0.00", CultureInfo.InvariantCulture); } internal static void RegisterConverter() { //IL_001c: 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_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown if (!TomlTypeConverter.CanConvert(typeof(Scale))) { TomlTypeConverter.AddConverter(typeof(Scale), new TypeConverter { ConvertToString = (object obj, Type type) => ((Scale)obj/*cast due to .constrained prefix*/).ToString(), ConvertToObject = (string str, Type type) => new Scale(float.Parse(str.Trim().Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture)) }); } } } internal sealed class GroupSettings { public ConfigEntry<float> Loss; public ConfigEntry<float> MaxLevelsLost; public ConfigEntry<Scale> CatchUpPerLevel; public ConfigEntry<Scale> CatchUpMax; public ConfigEntry<Scale> XpGain; } internal static class PluginConfig { internal const float VanillaNormalLoss = 5f; private const string TogglesSection = "0 - Toggles"; private const string GeneralSection = "1 - General"; private const string CausesSection = "2 - Death Causes"; private const string CategoriesPrefix = "3 - Categories - "; private const string SkillsPrefix = "4 - Skills - "; internal const string ModdedCategory = "Modded"; private static readonly Regex ModdedSectionPattern = new Regex("^4 - Skills - Modded - (.*)\\((-?\\d+)\\)\\s*$"); private static readonly Regex DevModdedSectionPattern = new Regex("^Modded - (.*)\\((-?\\d+)\\)\\s*$"); private static readonly Regex LegacyModdedKeyPattern = new Regex("^(.*)\\((-?\\d+)\\)\\s*$"); private static readonly AcceptableValueRange<float> Percent = new AcceptableValueRange<float>(0f, 100f); private static readonly AcceptableValueRange<float> Levels = new AcceptableValueRange<float>(0f, 100f); internal static readonly (SkillType Skill, string Category, string Key)[] VanillaSkills = new(SkillType, string, string)[24] { ((SkillType)1, "Combat", "Swords"), ((SkillType)2, "Combat", "Knives"), ((SkillType)3, "Combat", "Clubs"), ((SkillType)4, "Combat", "Polearms"), ((SkillType)5, "Combat", "Spears"), ((SkillType)6, "Combat", "Blocking"), ((SkillType)7, "Combat", "Axes"), ((SkillType)8, "Combat", "Bows"), ((SkillType)14, "Combat", "Crossbows"), ((SkillType)9, "Combat", "Elemental Magic"), ((SkillType)10, "Combat", "Blood Magic"), ((SkillType)11, "Combat", "Unarmed"), ((SkillType)12, "Utility", "Pickaxes"), ((SkillType)13, "Utility", "Woodcutting"), ((SkillType)104, "Utility", "Fishing"), ((SkillType)110, "Utility", "Ride"), ((SkillType)105, "Crafting", "Cooking"), ((SkillType)107, "Crafting", "Crafting"), ((SkillType)106, "Crafting", "Farming"), ((SkillType)100, "Movement", "Jump"), ((SkillType)102, "Movement", "Run"), ((SkillType)101, "Movement", "Sneak"), ((SkillType)103, "Movement", "Swim"), ((SkillType)108, "Movement", "Dodge") }; private static readonly (DeathCause Cause, string Description)[] DeathCauses = new(DeathCause, string)[7] { (DeathCause.Enemy, "killed by a creature"), (DeathCause.PvP, "killed by another player's direct hit"), (DeathCause.Fall, "fall damage"), (DeathCause.Drowning, "drowning"), (DeathCause.Environment, "burning, freezing, poison, smoke, water, Ashlands lava/ocean, cinder fire (damage over time counts here even when a creature or player caused it)"), (DeathCause.Accident, "trees, carts, boats, collapsing structures, traps/turrets, stalactites, catapults, obliterators, drawbridges, impacts"), (DeathCause.Other, "self-inflicted, edge of the world, unknown") }; internal static ManualLogSource Log; internal static ConfigEntry<Scope> LossScope; internal static ConfigEntry<Scope> LossCapScope; internal static ConfigEntry<Scope> CatchUpScope; internal static ConfigEntry<Scope> XpGainScope; internal static ConfigEntry<Toggle> DeathCausesToggle; internal static ConfigEntry<LossMode> Mode; internal static ConfigEntry<bool> ApplyWorldDeathPenalty; internal static ConfigEntry<bool> DebugLogging; private static ConfigFile _config; private static readonly Dictionary<string, GroupSettings> CategorySettings = new Dictionary<string, GroupSettings>(); private static readonly Dictionary<int, GroupSettings> SkillSettings = new Dictionary<int, GroupSettings>(); private static readonly Dictionary<int, string> VanillaCategory = new Dictionary<int, string>(); private static readonly Dictionary<DeathCause, ConfigEntry<Scale>> CauseMultiplier = new Dictionary<DeathCause, ConfigEntry<Scale>>(); internal static void Init(ConfigFile config, ManualLogSource log) { _config = config; Log = log; CategorySettings.Clear(); SkillSettings.Clear(); VanillaCategory.Clear(); CauseMultiplier.Clear(); Scale.RegisterConverter(); Dictionary<string, Dictionary<string, string>> dictionary = ReadRaw(config.ConfigFilePath); bool flag = dictionary.ContainsKey("General") && dictionary["General"].ContainsKey("UseCategories") && !dictionary.ContainsKey("0 - Toggles"); bool flag2 = dictionary.ContainsKey("0 - Toggles") && dictionary.ContainsKey("Combat"); bool saveOnConfigSet = config.SaveOnConfigSet; config.SaveOnConfigSet = false; try { BindAll(config); foreach (string key in dictionary.Keys) { Match match = ModdedSectionPattern.Match(key); if (match.Success && int.TryParse(match.Groups[2].Value, out var result)) { BindModdedSkill(result, match.Groups[1].Value.Trim()); } } if (flag) { MigrateLegacy(dictionary); } else if (flag2) { MigrateDevLayout(dictionary); } else { MigrateMovedSkills(dictionary); } if (typeof(ConfigFile).GetProperty("OrphanedEntries", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(config) is IDictionary { Count: >0 } dictionary2) { ManualLogSource log2 = Log; if (log2 != null) { log2.LogInfo((object)$"Removing {dictionary2.Count} obsolete config entries."); } dictionary2.Clear(); } config.Save(); } finally { config.SaveOnConfigSet = saveOnConfigSet; } } private static void BindAll(ConfigFile config) { //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Expected O, but got Unknown //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0252: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Expected I4, but got Unknown //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Expected I4, but got Unknown LossScope = config.Bind<Scope>("0 - Toggles", "Loss", Scope.Skill, AdminOnly("Where the death loss % comes from. Off = vanilla: the world's Death penalty setting decides (Normal 5%, Hard 7.5%, Easy 2.5%, ...); Category = 'Loss' in each [3 - Categories - ...] section; Skill = 'Loss' in each [4 - Skills - ...] section.")); LossCapScope = config.Bind<Scope>("0 - Toggles", "MaxLevelsLostCap", Scope.Off, AdminOnly("Where the most levels a skill can lose per death comes from ('MaxLevelsLost'). Off = no cap; Category = [3 - Categories - ...] sections; Skill = [4 - Skills - ...] sections.")); CatchUpScope = config.Bind<Scope>("0 - Toggles", "CatchUpXp", Scope.Off, AdminOnly("Where the catch-up XP values come from ('CatchUpPerLevel', 'CatchUpMax'): extra XP while a skill is below the highest level the character ever had in it. Off = no bonus; Category = [3 - Categories - ...] sections; Skill = [4 - Skills - ...] sections.")); XpGainScope = config.Bind<Scope>("0 - Toggles", "XpGain", Scope.Off, AdminOnly("Where the XP multiplier comes from ('XpGain'). Off = normal XP; Category = [3 - Categories - ...] sections; Skill = [4 - Skills - ...] sections.")); DeathCausesToggle = config.Bind<Toggle>("0 - Toggles", "DeathCauses", Toggle.Off, AdminOnly("Off = every death loses the same; On = multiply the loss by the [2 - Death Causes] value for how you died.")); Mode = config.Bind<LossMode>("1 - General", "LossMode", LossMode.Level, AdminOnly("Level = lose % of the skill level and all progress towards the next level (vanilla). TotalXp = lose % of all XP ever earned in the skill; the level and progress bar are recalculated from what's left, so progress is kept. Levels cost more XP the higher they are, so the same % costs fewer levels in TotalXp mode (5% XP is roughly 2% of the level).")); ApplyWorldDeathPenalty = config.Bind<bool>("1 - General", "ApplyWorldDeathPenalty", false, AdminOnly("true = multiply the configured Loss by the world's 'Death penalty' modifier relative to Normal (Normal x1, Easy x0.5, Hard x1.5, ...); false = the values here are final. Not used when [0 - Toggles] Loss = Off (that already is the world's setting).")); DebugLogging = config.Bind<bool>("1 - General", "DebugLogging", false, new ConfigDescription("true = write details to the BepInEx log: every skill's level before/after each death, XP gained per skill with the multipliers used (summed every 10 s), level-ups, and the stored peak levels on login. For testing; leave false on a live server.", (AcceptableValueBase)null, Array.Empty<object>())); (DeathCause, string)[] deathCauses = DeathCauses; for (int i = 0; i < deathCauses.Length; i++) { var (key, text) = deathCauses[i]; CauseMultiplier[key] = BindScale(config, "2 - Death Causes", key.ToString(), new Scale(1f), 10f, "Loss multiplier when the death was: " + text + ". 1.00 = normal loss, 0.00 = no loss, 0.50 = half, 2.00 = double. Used when DeathCauses = On."); } foreach (string item in VanillaSkills.Select(((SkillType Skill, string Category, string Key) x) => x.Category).Distinct().Concat(new string[1] { "Modded" })) { string text2 = ((item == "Modded") ? "skill added by another mod (without a section of its own)" : (item.ToLowerInvariant() + " skill")); CategorySettings[item] = BindGroup(config, "3 - Categories - " + item, "each " + text2, "Category", null); } (SkillType, string, string)[] vanillaSkills = VanillaSkills; for (int i = 0; i < vanillaSkills.Length; i++) { var (val, text3, text4) = vanillaSkills[i]; VanillaCategory[(int)val] = text3; SkillSettings[(int)val] = BindGroup(config, "4 - Skills - " + text3 + " - " + text4, text4, "Skill", null); } } private static GroupSettings BindGroup(ConfigFile config, string section, string label, string scope, GroupSettings defaults) { string format = "Used when [0 - Toggles] {0} = " + scope + "."; return new GroupSettings { Loss = config.Bind<float>(section, "Loss", defaults?.Loss.Value ?? 5f, AdminOnly("% of " + label + " lost on death (0-100). " + string.Format(format, "Loss"), (AcceptableValueBase)(object)Percent)), MaxLevelsLost = config.Bind<float>(section, "MaxLevelsLost", defaults?.MaxLevelsLost.Value ?? 0f, AdminOnly("Most levels " + label + " can lose in one death, progress bar included (fractions allowed, e.g. 1.5). 0 = no cap. " + string.Format(format, "MaxLevelsLostCap"), (AcceptableValueBase)(object)Levels)), CatchUpPerLevel = BindScale(config, section, "CatchUpPerLevel", defaults?.CatchUpPerLevel.Value ?? new Scale(0f), 10f, "Extra XP for every level below the highest level the character ever had in the skill (0.10 = +10% per missing level). 0.00 = none. " + string.Format(format, "CatchUpXp")), CatchUpMax = BindScale(config, section, "CatchUpMax", defaults?.CatchUpMax.Value ?? new Scale(1f), 100f, "Upper limit of the catch-up bonus (1.00 = at most double XP). " + string.Format(format, "CatchUpXp")), XpGain = BindScale(config, section, "XpGain", defaults?.XpGain.Value ?? new Scale(1f), 10f, "XP multiplier (1.00 = normal, 1.50 = +50%, 2.00 = double, 0.50 = half). " + string.Format(format, "XpGain")) }; } private static ConfigEntry<Scale> BindScale(ConfigFile config, string section, string key, Scale defaultValue, float max, string description) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown ConfigurationManagerAttributes val = new ConfigurationManagerAttributes { IsAdminOnly = true, ObjToStr = (object obj) => obj.ToString() }; ConfigEntry<Scale> entry = config.Bind<Scale>(section, key, defaultValue, new ConfigDescription($"{description} Range 0.00-{max:0.00}.", (AcceptableValueBase)null, new object[1] { val })); val.StrToObj = (string str) => float.TryParse(str.Trim().Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) ? new Scale(Math.Max(0f, Math.Min(max, result))) : entry.Value; entry.SettingChanged += delegate { Clamp(); }; Clamp(); return entry; void Clamp() { float value = entry.Value.Value; if (value < 0f || value > max) { entry.Value = new Scale(Math.Max(0f, Math.Min(max, value))); } } } private static ConfigDescription AdminOnly(string description, AcceptableValueBase range = null) { //IL_000a: 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_0017: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown return new ConfigDescription(description, range, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } }); } internal static string TogglesSummary() { return $"Loss={LossScope.Value}, MaxLevelsLostCap={LossCapScope.Value}, CatchUpXp={CatchUpScope.Value}, " + $"XpGain={XpGainScope.Value}, DeathCauses={DeathCausesToggle.Value}, LossMode={Mode.Value}, " + $"ApplyWorldDeathPenalty={ApplyWorldDeathPenalty.Value}"; } internal static bool IsVanilla(SkillType skill) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected I4, but got Unknown return VanillaCategory.ContainsKey((int)skill); } private static string CategoryOf(SkillType skill) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected I4, but got Unknown if (!VanillaCategory.TryGetValue((int)skill, out var value)) { return "Modded"; } return value; } private static GroupSettings Resolve(SkillType skill, Scope scope) { //IL_0020: 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_0017: Expected I4, but got Unknown if (scope != Scope.Category) { if (scope != Scope.Skill) { return null; } if (SkillSettings.TryGetValue((int)skill, out var value)) { return value; } } return CategorySettings[CategoryOf(skill)]; } internal static float? GetLossPercent(SkillType skill) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return Resolve(skill, LossScope.Value)?.Loss.Value; } internal static float GetLevelCap(SkillType skill) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return Resolve(skill, LossCapScope.Value)?.MaxLevelsLost.Value ?? 0f; } internal static void GetCatchUp(SkillType skill, out float perLevel, out float max) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) GroupSettings groupSettings = Resolve(skill, CatchUpScope.Value); perLevel = groupSettings?.CatchUpPerLevel.Value.Value ?? 0f; max = groupSettings?.CatchUpMax.Value.Value ?? 0f; } internal static float GetXpGainMultiplier(SkillType skill) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return Resolve(skill, XpGainScope.Value)?.XpGain.Value.Value ?? 1f; } internal static float GetCauseMultiplier(DeathCause cause) { if (DeathCausesToggle.Value != Toggle.On) { return 1f; } return CauseMultiplier[cause].Value.Value; } internal static DeathCause GetDeathCause(HitData hit) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: 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_0093: Expected I4, but got Unknown switch (hit?.m_hitType) { case (HitType)0L: return DeathCause.Enemy; case (HitType)1L: return DeathCause.PvP; case (HitType)2L: return DeathCause.Fall; case (HitType)3L: return DeathCause.Drowning; case (HitType)4L: case (HitType)5L: case (HitType)6L: case (HitType)7L: case (HitType)8L: case (HitType)19L: case (HitType)20L: case (HitType)21L: return DeathCause.Environment; case (HitType)10L: case (HitType)11L: case (HitType)12L: case (HitType)14L: case (HitType)15L: case (HitType)16L: case (HitType)17L: case (HitType)18L: case (HitType)22L: case (HitType)23L: return DeathCause.Accident; default: return DeathCause.Other; } } internal static void DiscoverModdedSkill(SkillType skill, string displayName) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Expected I4, but got Unknown //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) int num = (int)skill; if ((int)skill != 0 && (int)skill != 999 && !IsVanilla(skill) && !SkillSettings.ContainsKey(num)) { GroupSettings groupSettings = BindModdedSkill(num, displayName); ManualLogSource log = Log; if (log != null) { log.LogInfo((object)$"Added config section for modded skill '{ModdedSection(displayName, num)}' (Loss {groupSettings.Loss.Value}%)."); } } } private static GroupSettings BindModdedSkill(int id, string displayName) { if (SkillSettings.TryGetValue(id, out var value)) { return value; } GroupSettings groupSettings = BindGroup(_config, ModdedSection(displayName, id), $"this modded skill (id {id})", "Skill", CategorySettings["Modded"]); SkillSettings[id] = groupSettings; return groupSettings; } private static string ModdedSection(string displayName, int id) { return string.Format("{0}{1} - {2} ({3})", "4 - Skills - ", "Modded", displayName, id); } private static void MigrateDevLayout(Dictionary<string, Dictionary<string, string>> raw) { //IL_0087: 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_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected I4, but got Unknown if (raw["0 - Toggles"].TryGetValue("LossCap", out var value) && Enum.TryParse<Scope>(value, ignoreCase: true, out var result)) { LossCapScope.Value = result; } foreach (KeyValuePair<string, GroupSettings> categorySetting in CategorySettings) { CopyGroup(raw, categorySetting.Key, categorySetting.Value); } (SkillType, string, string)[] vanillaSkills = VanillaSkills; for (int i = 0; i < vanillaSkills.Length; i++) { var (val, text, text2) = vanillaSkills[i]; CopyGroup(raw, text + " - " + text2, SkillSettings[(int)val]); } foreach (string key in raw.Keys) { Match match = DevModdedSectionPattern.Match(key); if (match.Success && int.TryParse(match.Groups[2].Value, out var result2)) { CopyGroup(raw, key, BindModdedSkill(result2, match.Groups[1].Value.Trim())); } } ManualLogSource log = Log; if (log != null) { log.LogInfo((object)"Moved the categories and skills to the numbered [3 - Categories - ...] / [4 - Skills - ...] sections."); } } private static void MigrateMovedSkills(Dictionary<string, Dictionary<string, string>> raw) { //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_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected I4, but got Unknown (SkillType, string, string)[] vanillaSkills = VanillaSkills; for (int i = 0; i < vanillaSkills.Length; i++) { (SkillType, string, string) tuple = vanillaSkills[i]; SkillType item = tuple.Item1; string item2 = tuple.Item2; string key = tuple.Item3; string text = "4 - Skills - " + item2 + " - " + key; if (raw.ContainsKey(text)) { continue; } string text2 = raw.Keys.FirstOrDefault((string s) => s.StartsWith("4 - Skills - ") && s.EndsWith(" - " + key) && !s.StartsWith("4 - Skills - Modded - ")); if (text2 != null) { CopyGroup(raw, text2, SkillSettings[(int)item]); ManualLogSource log = Log; if (log != null) { log.LogInfo((object)("Moved [" + text2 + "] to [" + text + "].")); } } } } private static void CopyGroup(Dictionary<string, Dictionary<string, string>> raw, string section, GroupSettings target) { if (!raw.TryGetValue(section, out var value)) { return; } ConfigEntryBase[] array = (ConfigEntryBase[])(object)new ConfigEntryBase[5] { (ConfigEntryBase)target.Loss, (ConfigEntryBase)target.MaxLevelsLost, (ConfigEntryBase)target.CatchUpPerLevel, (ConfigEntryBase)target.CatchUpMax, (ConfigEntryBase)target.XpGain }; foreach (ConfigEntryBase val in array) { if (!value.TryGetValue(val.Definition.Key, out var value2)) { continue; } try { val.SetSerializedValue(value2); } catch (Exception ex) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)("Couldn't read [" + section + "] " + val.Definition.Key + " = " + value2 + ": " + ex.Message)); } } } } private static void MigrateLegacy(Dictionary<string, Dictionary<string, string>> raw) { //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_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected I4, but got Unknown LossScope.Value = (string.Equals(Get("General", "UseCategories"), "true", StringComparison.OrdinalIgnoreCase) ? Scope.Category : Scope.Skill); if (Enum.TryParse<LossMode>(Get("General", "LossMode") ?? string.Empty, ignoreCase: true, out var result)) { Mode.Value = result; } if (bool.TryParse(Get("General", "ApplyWorldDeathPenalty") ?? string.Empty, out var result2)) { ApplyWorldDeathPenalty.Value = result2; } foreach (string item in CategorySettings.Keys.Where((string c) => c != "Modded")) { SetFloat(CategorySettings[item].Loss, Get("Categories", item)); } (SkillType, string, string)[] vanillaSkills = VanillaSkills; for (int num = 0; num < vanillaSkills.Length; num++) { var (val, text, key) = vanillaSkills[num]; SetFloat(SkillSettings[(int)val].Loss, Get(text + " Skills", key)); } SetFloat(CategorySettings["Modded"].Loss, Get("Modded Skills", "Default")); if (raw.TryGetValue("Modded Skills", out var value)) { foreach (KeyValuePair<string, string> item2 in value) { Match match = LegacyModdedKeyPattern.Match(item2.Key); if (match.Success && int.TryParse(match.Groups[2].Value, out var result3)) { SetFloat(BindModdedSkill(result3, match.Groups[1].Value.Trim()).Loss, item2.Value); } } } ManualLogSource log = Log; if (log != null) { log.LogInfo((object)$"Migrated the 1.1 config to the new layout (Loss = {LossScope.Value})."); } string Get(string section, string key2) { if (!raw.TryGetValue(section, out var value2) || !value2.TryGetValue(key2, out var value3)) { return null; } return value3; } static void SetFloat(ConfigEntry<float> entry, string text2) { if (text2 != null && float.TryParse(text2.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var result4)) { entry.Value = result4; } } } private static Dictionary<string, Dictionary<string, string>> ReadRaw(string path) { Dictionary<string, Dictionary<string, string>> dictionary = new Dictionary<string, Dictionary<string, string>>(); if (!File.Exists(path)) { return dictionary; } Dictionary<string, string> value = null; string[] array = File.ReadAllLines(path); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.StartsWith("[") && text.EndsWith("]")) { string key = text.Substring(1, text.Length - 2).Trim(); if (!dictionary.TryGetValue(key, out value)) { value = (dictionary[key] = new Dictionary<string, string>()); } } else if (value != null && text.Length != 0 && !text.StartsWith("#")) { int num = text.IndexOf('='); if (num > 0) { value[text.Substring(0, num).Trim()] = text.Substring(num + 1).Trim(); } } } return dictionary; } } }