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 Kratyr Unified Skills v0.2.4
BepInEx/plugins/KratyrUnifiedSkills.dll
Decompiled 2 days agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("KratyrUnifiedSkills")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("KratyrUnifiedSkills")] [assembly: AssemblyTitle("KratyrUnifiedSkills")] [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 Kratyr.UnifiedSkills { internal static class KratyrSkillAdmin { private struct Pending { public long Target; public long Requester; public string Action; public float SentAt; } [HarmonyPatch(typeof(ZNet), "Awake")] private static class ZNetRegisterPatch { [HarmonyPostfix] private static void Postfix() { Register(ZRoutedRpc.instance); } } [HarmonyPatch(typeof(ZNetScene), "Awake")] private static class SceneRegisterPatch { [HarmonyPostfix] private static void Postfix() { Register(ZRoutedRpc.instance); } } private const int Protocol = 2; private const long LocalHostRequester = long.MinValue; private const string AdminRequest = "KratyrUS_AdminRequest_v2"; private const string ClientOperation = "KratyrUS_ClientOperation_v2"; private const string ClientReport = "KratyrUS_ClientReport_v2"; private const string AdminResult = "KratyrUS_AdminResult_v2"; private static ZRoutedRpc _registered; private static int _nextTicket; private static readonly Dictionary<int, Pending> PendingOperations = new Dictionary<int, Pending>(); private static void Register(ZRoutedRpc rpc) { if (rpc == null || _registered == rpc) { return; } try { rpc.Register<ZPackage>("KratyrUS_AdminRequest_v2", (Action<long, ZPackage>)OnAdminRequest); rpc.Register<ZPackage>("KratyrUS_ClientOperation_v2", (Action<long, ZPackage>)OnClientOperation); rpc.Register<ZPackage>("KratyrUS_ClientReport_v2", (Action<long, ZPackage>)OnClientReport); rpc.Register<ZPackage>("KratyrUS_AdminResult_v2", (Action<long, ZPackage>)OnAdminResult); _registered = rpc; PendingOperations.Clear(); KratyrUnifiedSkills.Instance.AdminLog("Host-authorized skill administration RPC endpoints registered."); } catch (Exception ex) { KratyrUnifiedSkills.Instance.AdminWarn("Cannot register skill admin RPCs (remote management unavailable): " + ex); } } internal static void ExecuteConsole(Terminal terminal, string action, string target, string skillName, string rawLevel) { //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Expected O, but got Unknown if (!KratyrUnifiedSkills.Instance.ActiveForAdmin) { terminal.AddString("Skill administration disabled: plugin initialization failed."); return; } if ((Object)(object)ZNet.instance == (Object)null || ZRoutedRpc.instance == null || (Object)(object)Player.m_localPlayer == (Object)null) { terminal.AddString("Enter a hosted or joined world before using skill admin commands."); return; } Register(ZRoutedRpc.instance); if (_registered != ZRoutedRpc.instance) { terminal.AddString("Admin RPC registration failed; see LogOutput.log. No changes made."); return; } if (action != "players" && string.IsNullOrWhiteSpace(target)) { terminal.AddString("Specify a player: kskills " + action + " <player name or peer UID>. Use 'kskills players' to see connected players."); return; } if (action == "set" && (string.IsNullOrWhiteSpace(skillName) || string.IsNullOrWhiteSpace(rawLevel))) { terminal.AddString("Usage: kskills set <player> <existing skill ID/name> <level>."); return; } if (ZNet.instance.IsServer()) { string text = Dispatch(long.MinValue, action, target, skillName, rawLevel); terminal.AddString(text); return; } ZPackage val = new ZPackage(); val.Write(2); val.Write(action); val.Write(target ?? ""); val.Write(skillName ?? ""); val.Write(rawLevel ?? ""); ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); if (serverPeer == null) { terminal.AddString("Cannot identify the host connection; no request sent."); return; } Send(serverPeer.m_uid, "KratyrUS_AdminRequest_v2", val); terminal.AddString("Requested '" + action + "' from host. Only server-approved admins can use these commands. Await response."); } private static void OnAdminRequest(long sender, ZPackage package) { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } if (!IsAuthorizedOnServer(sender)) { KratyrUnifiedSkills.Instance.AdminWarn("Rejected unauthorized remote kskills request from peer " + sender); Reply(sender, "Denied: only the host or players authorized in Valheim's server admin list can manage skills."); return; } try { if (package.ReadInt() != 2) { Reply(sender, "Skill admin protocol mismatch. Install the same Kratyr mod version on all clients."); return; } string action = package.ReadString(); string target = package.ReadString(); string skill = package.ReadString(); string value = package.ReadString(); Reply(sender, Dispatch(sender, action, target, skill, value)); } catch (Exception ex) { KratyrUnifiedSkills.Instance.AdminWarn("Malformed skill admin request from " + sender + ": " + ex); Reply(sender, "Malformed administration request rejected."); } } private static bool IsAuthorizedOnServer(long sender) { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZRoutedRpc.instance == null) { return false; } ZNetPeer val = ((IEnumerable<ZNetPeer>)ZNet.instance.GetPeers()).FirstOrDefault((Func<ZNetPeer, bool>)((ZNetPeer p) => p.m_uid == sender)); if (val == null) { return false; } try { MethodInfo methodInfo = AccessTools.Method(typeof(ZNet), "PlayerIsAdmin", new Type[1] { typeof(long) }, (Type[])null); if (methodInfo != null && methodInfo.ReturnType == typeof(bool)) { return (bool)methodInfo.Invoke(ZNet.instance, new object[1] { sender }); } MethodInfo methodInfo2 = AccessTools.Method(typeof(ZNet), "IsAdmin", new Type[1] { typeof(string) }, (Type[])null); if (methodInfo2 == null || methodInfo2.ReturnType != typeof(bool)) { return false; } ZRpc rpc = val.m_rpc; object obj; if (rpc == null) { obj = null; } else { ISocket socket = rpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; return !string.IsNullOrWhiteSpace(text) && (bool)methodInfo2.Invoke(ZNet.instance, new object[1] { text }); } catch (Exception ex) { KratyrUnifiedSkills.Instance.AdminWarn("Admin authorization check unavailable (DENIED): " + ex.Message); return false; } } private static string Dispatch(long requester, string action, string target, string skill, string value) { //IL_03fa: Unknown result type (might be due to invalid IL or missing references) //IL_0401: Expected O, but got Unknown if (action != "players" && action != "inspect" && action != "preview" && action != "half" && action != "reset" && action != "set") { return "Unknown admin command. Use players, inspect, preview, half, reset or set."; } if (action == "players") { List<string> list = new List<string>(); Player localPlayer = Player.m_localPlayer; string text = (((Object)(object)localPlayer == (Object)null) ? "Host" : SafeName(localPlayer)); list.Add("Host: " + text + " [me]"); foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { list.Add((peer.m_playerName ?? "(connecting)") + " [" + peer.m_uid.ToString(CultureInfo.InvariantCulture) + "]"); } return "Connected characters: " + string.Join("; ", list.ToArray()); } if (string.IsNullOrWhiteSpace(target) || target.Length > 128) { return "Specify one connected player name or peer UID; use kskills players."; } if ((action == "reset" || action == "preview") && !string.IsNullOrWhiteSpace(skill) && skill.Length > 80) { return "Skill ID/name is too long. Use the exact skill name or numeric ID."; } if (action == "set") { if (!KratyrUnifiedSkills.AllowHostTestSet.Value) { return "kskills set is disabled on the host. Enable 'Allow Host Test Set Command' for testing."; } if (string.IsNullOrWhiteSpace(skill) || skill.Length > 80 || !float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || float.IsNaN(result) || float.IsInfinity(result)) { return "Usage: kskills set <player> <existing skill ID/name> <finite raw level>."; } } bool flag = target.Equals("me", StringComparison.OrdinalIgnoreCase); Player localPlayer2 = Player.m_localPlayer; if (!flag && (Object)(object)localPlayer2 != (Object)null && target.Equals(SafeName(localPlayer2), StringComparison.OrdinalIgnoreCase)) { flag = true; } List<ZNetPeer> list2 = (from peer in ZNet.instance.GetPeers() where peer.m_uid.ToString(CultureInfo.InvariantCulture) == target || string.Equals(peer.m_playerName, target, StringComparison.OrdinalIgnoreCase) select peer).ToList(); if ((flag && list2.Count > 0) || list2.Count > 1) { return "Ambiguous player name. Use kskills players and target a numeric peer UID."; } if (!flag && list2.Count == 0) { return "Player not connected: " + target + ". Use kskills players. Offline characters cannot be edited."; } if (flag) { if ((Object)(object)localPlayer2 == (Object)null || (Object)(object)((Character)localPlayer2).GetSkills() == (Object)null) { return "Host character is not available."; } string text2 = ApplyToLocal(action, skill, value); KratyrUnifiedSkills.Instance.AdminLog("Host kskills " + action + " on " + SafeName(localPlayer2) + ": " + text2); return text2; } ZNetPeer val = list2[0]; int num = ++_nextTicket; if (num == 0) { num = ++_nextTicket; } float now = Time.realtimeSinceStartup; int[] array = (from entry in PendingOperations where now - entry.Value.SentAt > 30f select entry.Key).ToArray(); foreach (int key in array) { PendingOperations.Remove(key); } if (PendingOperations.Count >= 64) { return "Too many outstanding skill operations; check if target clients have this mod installed."; } PendingOperations[num] = new Pending { Requester = requester, Target = val.m_uid, Action = action, SentAt = now }; ZPackage val2 = new ZPackage(); val2.Write(2); val2.Write(num); val2.Write(action); val2.Write(skill ?? ""); val2.Write(value ?? ""); Send(val.m_uid, "KratyrUS_ClientOperation_v2", val2); KratyrUnifiedSkills.Instance.AdminLog("Host authorized kskills " + action + " on " + val.m_playerName + " (UID " + val.m_uid + ") request=" + num); return "Sent '" + action + "' to " + val.m_playerName + " (" + val.m_uid + "), request #" + num + ". Await result; player must have v0.2.4 installed."; } private static void OnClientOperation(long sender, ZPackage package) { //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Expected O, but got Unknown if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || ZRoutedRpc.instance == null) { return; } ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); if (serverPeer == null || sender != serverPeer.m_uid) { KratyrUnifiedSkills.Instance.AdminWarn("Rejected skill modification RPC from NON-SERVER peer " + sender); return; } int num = 0; string text2; try { if (package.ReadInt() != 2) { return; } num = package.ReadInt(); string text = package.ReadString(); string skillName = package.ReadString(); string rawLevel = package.ReadString(); object obj; switch (text) { default: obj = "Rejected unknown operation"; break; case "inspect": case "preview": case "half": case "reset": case "set": obj = ApplyToLocal(text, skillName, rawLevel); break; } text2 = (string)obj; } catch (Exception ex) { KratyrUnifiedSkills.Instance.AdminWarn("Failed host-requested skill operation: " + ex); text2 = "Target error: " + ex.Message; } ZPackage val = new ZPackage(); val.Write(2); val.Write(num); val.Write((text2.Length > 3500) ? text2.Substring(0, 3500) : text2); Send(sender, "KratyrUS_ClientReport_v2", val); } private static bool TryResolveExistingSkill(List<KeyValuePair<SkillType, Skill>> entries, string requested, out KeyValuePair<SkillType, Skill> resolved, out string error) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Invalid comparison between Unknown and I4 //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) resolved = default(KeyValuePair<SkillType, Skill>); error = ""; if (string.IsNullOrWhiteSpace(requested)) { error = "Specify an exact skill name or numeric ID."; return false; } string text = requested.Trim(); if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { foreach (KeyValuePair<SkillType, Skill> entry in entries) { if (entry.Value != null && (int)entry.Key == result) { resolved = entry; return true; } } error = "Skill ID " + result + " is not recorded on the target character. No change made."; return false; } string text2 = NormalizeSkillName(text); if (text2.Length == 0) { error = "Invalid skill name; no change made."; return false; } List<KeyValuePair<SkillType, Skill>> list = new List<KeyValuePair<SkillType, Skill>>(); foreach (KeyValuePair<SkillType, Skill> entry2 in entries) { if (entry2.Value != null) { string b = NormalizeSkillName(((object)entry2.Key/*cast due to .constrained prefix*/).ToString()); string b2 = NormalizeSkillName(KratyrSkillSorting.GetSkillDisplayName(entry2.Value)); if (string.Equals(text2, b, StringComparison.OrdinalIgnoreCase) || string.Equals(text2, b2, StringComparison.OrdinalIgnoreCase)) { list.Add(entry2); } } } if (list.Count != 1) { error = ((list.Count == 0) ? ("Skill not found on target: " + text + ". Use its numeric ID from kskills inspect <player>.") : ("Ambiguous skill name: " + text + ". Use its numeric skill ID from kskills inspect <player>.")); return false; } resolved = list[0]; return true; } private static string NormalizeSkillName(string value) { return new string((value ?? "").Where(char.IsLetterOrDigit).ToArray()); } private static string ApplyToLocal(string action, string skillName, string rawLevel) { //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Expected I4, but got Unknown //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Expected I4, but got Unknown //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_03bc: Unknown result type (might be due to invalid IL or missing references) //IL_045d: Unknown result type (might be due to invalid IL or missing references) //IL_0462: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Unknown result type (might be due to invalid IL or missing references) //IL_0485: Expected I4, but got Unknown //IL_03de: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03ff: Unknown result type (might be due to invalid IL or missing references) //IL_0406: Expected I4, but got Unknown Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)((Character)localPlayer).GetSkills() == (Object)null) { return "Target character is not loaded; no change made."; } Skills skills = ((Character)localPlayer).GetSkills(); List<KeyValuePair<SkillType, Skill>> skillEntries = KratyrUnifiedSkills.GetSkillEntries(skills); if (skillEntries == null) { return "Skill records unavailable; no change made."; } if (action == "set") { if (string.IsNullOrEmpty(skillName) || !float.TryParse(rawLevel, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || float.IsNaN(result) || float.IsInfinity(result)) { return "Invalid set value; no change made."; } if (!TryResolveExistingSkill(skillEntries, skillName, out var resolved, out var error)) { return error; } float level = resolved.Value.m_level; if (!KratyrUnifiedSkills.Instance.TrySetSkillLevel(skills, resolved.Key, result, out var actual)) { return "Balrond rejected set; no change made."; } return "Set " + KratyrSkillSorting.GetSkillDisplayName(resolved.Value) + " (" + (int)resolved.Key + ") " + F(level) + " -> " + F(actual) + " for " + SafeName(localPlayer); } if ((action == "reset" || action == "preview") && !string.IsNullOrWhiteSpace(skillName)) { if (!TryResolveExistingSkill(skillEntries, skillName, out var resolved2, out var error2)) { return error2; } float level2 = resolved2.Value.m_level; if (float.IsNaN(level2) || float.IsInfinity(level2)) { return "Invalid stored skill level; no change made."; } string text = KratyrSkillSorting.GetSkillDisplayName(resolved2.Value) + " (ID " + (int)resolved2.Key + ")"; if (action == "preview") { return "Preview: reset " + text + " on " + SafeName(localPlayer) + ": " + F(level2) + " -> 0 (NO change made)."; } if (level2 == 0f) { return "Skill " + text + " on " + SafeName(localPlayer) + " is already at 0; no change made."; } if (!KratyrUnifiedSkills.Instance.TrySetSkillLevel(skills, resolved2.Key, 0f, out var actual2)) { return "Balrond rejected reset of " + text + "; no change made."; } string text2 = "Reset ONLY " + text + " on " + SafeName(localPlayer) + ": " + F(level2) + " -> " + F(actual2) + ". Other skills unchanged."; KratyrUnifiedSkills.Instance.AdminLog(text2); return text2; } List<KeyValuePair<SkillType, Skill>> list = (from entry in skillEntries where entry.Value != null && !float.IsNaN(entry.Value.m_level) && !float.IsInfinity(entry.Value.m_level) && (action == "inspect" || entry.Value.m_level < 0f) orderby (int)entry.Key select entry).ToList(); int num = 0; int num2 = 0; List<string> list2 = new List<string>(); foreach (KeyValuePair<SkillType, Skill> item in list) { float level3 = item.Value.m_level; if (action == "half" || action == "reset") { float proposed = ((action == "reset") ? 0f : (level3 * 0.5f)); if (KratyrUnifiedSkills.Instance.TrySetSkillLevel(skills, item.Key, proposed, out var actual3)) { num++; list2.Add(((object)item.Key/*cast due to .constrained prefix*/).ToString() + "[" + (int)item.Key + "]:" + F(level3) + "->" + F(actual3)); } else { num2++; } } else if (list2.Count < 24) { list2.Add(((object)item.Key/*cast due to .constrained prefix*/).ToString() + "[" + (int)item.Key + "]=" + F(level3)); } } string text3 = "kskills " + action + " on " + SafeName(localPlayer) + ": " + list.Count + " records; changed " + num + ", failed " + num2 + ". " + string.Join(", ", list2.Take(24).ToArray()); KratyrUnifiedSkills.Instance.AdminLog(text3); return text3; } private static void OnClientReport(long sender, ZPackage package) { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } try { if (package.ReadInt() == 2) { int key = package.ReadInt(); string text = package.ReadString(); if (PendingOperations.TryGetValue(key, out var value) && value.Target == sender) { PendingOperations.Remove(key); Reply(value.Requester, "Remote " + value.Action + " completed [#" + key + "]: " + text); } } } catch (Exception ex) { KratyrUnifiedSkills.Instance.AdminWarn("Malformed target result: " + ex); } } private static void OnAdminResult(long sender, ZPackage package) { if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || ZRoutedRpc.instance == null) { return; } ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); if (serverPeer == null || sender != serverPeer.m_uid) { return; } try { if (package.ReadInt() == 2) { ShowResult(package.ReadString()); } } catch (Exception ex) { KratyrUnifiedSkills.Instance.AdminWarn("Malformed admin response: " + ex); } } private static void Reply(long requester, string message) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown if (requester == long.MinValue) { ShowResult(message); return; } ZPackage val = new ZPackage(); val.Write(2); val.Write((message.Length > 3700) ? message.Substring(0, 3700) : message); Send(requester, "KratyrUS_AdminResult_v2", val); } private static void Send(long target, string method, ZPackage package) { if (ZRoutedRpc.instance != null) { ZRoutedRpc.instance.InvokeRoutedRPC(target, method, new object[1] { package }); } } private static void ShowResult(string message) { KratyrUnifiedSkills.Instance.AdminLog(message); try { Type type = AccessTools.TypeByName("Console"); FieldInfo fieldInfo = ((type == null) ? null : AccessTools.Field(type, "instance")); object obj = ((fieldInfo == null) ? null : fieldInfo.GetValue(null)); if (obj == null && type != null) { PropertyInfo propertyInfo = AccessTools.Property(type, "instance"); if (propertyInfo != null) { obj = propertyInfo.GetValue(null, null); } } Terminal val = (Terminal)((obj is Terminal) ? obj : null); if (val != null) { val.AddString(message); } } catch { } } private static string SafeName(Player player) { try { MethodInfo methodInfo = AccessTools.Method(typeof(Player), "GetPlayerName", Type.EmptyTypes, (Type[])null); if (methodInfo != null) { return (methodInfo.Invoke(player, null) as string) ?? "Host"; } } catch { } return "Host"; } private static string F(float value) { return value.ToString("0.###", CultureInfo.InvariantCulture); } } public enum SkillSortMode { Default, Name, Type } internal static class KratyrSkillSorting { [HarmonyPatch(typeof(SkillsDialog), "Setup", new Type[] { typeof(Player) })] private static class DialogSetupPatch { [HarmonyPrefix] private static void Prefix() { if (_skillsDialogDepth == 0) { _dialogTimer = Stopwatch.StartNew(); } _skillsDialogDepth++; } [HarmonyPostfix] private static void Postfix(SkillsDialog __instance) { if (!KratyrUnifiedSkills.ShowSkillSortButton.Value) { return; } try { EnsureButton(__instance); } catch (Exception ex) { WarnOnce("Cannot display the sort button", ex); } } [HarmonyFinalizer] private static Exception Finalizer(Exception __exception) { _skillsDialogDepth = Math.Max(0, _skillsDialogDepth - 1); if (_skillsDialogDepth == 0 && _dialogTimer != null) { _dialogTimer.Stop(); if (_dialogTimer.ElapsedMilliseconds >= 500 && (Object)(object)KratyrUnifiedSkills.Instance != (Object)null) { KratyrUnifiedSkills.Instance.LogWarningForSort("SkillsDialog.Setup took " + _dialogTimer.ElapsedMilliseconds + " ms (sort mode " + KratyrUnifiedSkills.SkillSortOrder.Value.ToString() + "). Other mods and UI construction are included in this timing."); } _dialogTimer = null; } return __exception; } } [HarmonyPatch(typeof(Skills), "GetSkillList")] private static class GetSkillListPatch { [HarmonyPostfix] [HarmonyPriority(0)] private static void Postfix(ref List<Skill> __result) { if (_skillsDialogDepth <= 0 || __result == null || __result.Count <= 1) { return; } SkillSortMode value = KratyrUnifiedSkills.SkillSortOrder.Value; if (value == SkillSortMode.Default) { return; } Stopwatch stopwatch = Stopwatch.StartNew(); try { var source = __result.Select((Skill skill, int index) => new { Skill = skill, Index = index }); switch (value) { case SkillSortMode.Name: __result = (from item in source.OrderBy(item => GetName(item.Skill), StringComparer.CurrentCultureIgnoreCase).ThenBy(item => item.Index) select item.Skill).ToList(); break; case SkillSortMode.Type: __result = (from item in source.OrderBy(item => GetGroupIndex(item.Skill)).ThenBy(item => GetName(item.Skill), StringComparer.CurrentCultureIgnoreCase).ThenBy(item => item.Index) select item.Skill).ToList(); break; } } catch (Exception ex) { WarnOnce("Skills window sort failed; leaving original order", ex); } finally { stopwatch.Stop(); if (stopwatch.ElapsedMilliseconds >= 100 && (Object)(object)KratyrUnifiedSkills.Instance != (Object)null) { KratyrUnifiedSkills.Instance.LogWarningForSort("GetSkillList sort spent " + stopwatch.ElapsedMilliseconds + " ms sorting " + __result.Count + " skill entries."); } } } } [ThreadStatic] private static int _skillsDialogDepth; [ThreadStatic] private static Stopwatch _dialogTimer; private static bool _warned; private const string ButtonName = "KratyrUnifiedSkillsSortButton"; private static readonly Dictionary<int, string> KnownCustomNames = new Dictionary<int, string> { { 15001, "Vitality" }, { 15002, "Arcana" }, { 15003, "Endurance" }, { 15004, "Exploration" }, { 15005, "Fortitude" }, { 15006, "Hauling" }, { 15007, "Sailing" }, { 15008, "Taming" }, { 16050, "Runeforging" } }; private static readonly Dictionary<int, string> CachedNames = new Dictionary<int, string>(); private static readonly Dictionary<int, int> CachedGroups = new Dictionary<int, int>(); private static string CachedOverrides = ""; private static bool LocalizerInitialized; private static object LocalizerObject; private static MethodInfo LocalizeMethod; private static readonly Dictionary<string, string> DefaultGroups = BuildDefaultGroups(); private static readonly string[] GroupOrder = new string[7] { "Movement", "Combat", "Magic", "Survival", "Gathering", "Crafting", "Other" }; private static Dictionary<string, string> BuildDefaultGroups() { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); AddGroup(dictionary, "Movement", "Run", "Jump", "Swim", "Sneak", "Dodge", "Riding", "Sailing", "Exploration"); AddGroup(dictionary, "Combat", "Swords", "Knives", "Clubs", "Polearms", "Spears", "Axes", "Bows", "Crossbows", "Unarmed", "Fists", "Blocking", "Slingshots", "Throwing", "Dual Mastery", "DualMastery"); AddGroup(dictionary, "Magic", "ElementalMagic", "Elemental Magic", "BloodMagic", "Blood Magic", "Arcana", "Runeforging", "MagicSupremacy", "Magic Supremacy", "Wizardry"); AddGroup(dictionary, "Survival", "Vitality", "Endurance", "Fortitude", "Taming"); AddGroup(dictionary, "Gathering", "WoodCutting", "Wood Cutting", "Pickaxes", "Fishing", "Farming", "Hauling", "Mining"); AddGroup(dictionary, "Crafting", "Crafting", "Cooking", "Fermenting", "Blacksmithing", "Smelting"); return dictionary; } private static void AddGroup(Dictionary<string, string> groups, string group, params string[] names) { foreach (string value in names) { groups[Normalize(value)] = group; } } private static string Normalize(string value) { return new string((value ?? string.Empty).Where(char.IsLetterOrDigit).ToArray()); } internal static string GetSkillDisplayName(Skill skill) { return GetName(skill); } private unsafe static string GetName(Skill skill) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected I4, but got Unknown if (skill == null || skill.m_info == null) { return string.Empty; } SkillType skill2 = skill.m_info.m_skill; int key = (int)skill2; if (KnownCustomNames.TryGetValue(key, out var value)) { return value; } if (CachedNames.TryGetValue(key, out var value2)) { return value2; } string text = ((object)(*(SkillType*)(&skill2))/*cast due to .constrained prefix*/).ToString(); if (string.IsNullOrEmpty(text)) { text = key.ToString(CultureInfo.InvariantCulture); } if (!LocalizerInitialized) { LocalizerInitialized = true; try { Type type = AccessTools.TypeByName("Localization"); if (type != null) { FieldInfo fieldInfo = AccessTools.Field(type, "instance"); LocalizerObject = ((fieldInfo != null) ? fieldInfo.GetValue(null) : null); if (LocalizerObject == null) { PropertyInfo propertyInfo = AccessTools.Property(type, "instance"); if (propertyInfo != null) { LocalizerObject = propertyInfo.GetValue(null, null); } } if (LocalizerObject != null) { LocalizeMethod = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo method) => method.Name == "Localize" && method.GetParameters().Length >= 1 && method.GetParameters()[0].ParameterType == typeof(string)); } } } catch { LocalizeMethod = null; } } string text2 = text; if (LocalizeMethod != null && LocalizerObject != null) { try { ParameterInfo[] parameters = LocalizeMethod.GetParameters(); object[] array = new object[parameters.Length]; array[0] = "$skill_" + text.ToLowerInvariant(); for (int num = 1; num < array.Length; num++) { array[num] = ((parameters[num].ParameterType == typeof(string[])) ? new string[0] : (parameters[num].IsOptional ? parameters[num].DefaultValue : null)); } string text3 = LocalizeMethod.Invoke(LocalizerObject, array) as string; if (!string.IsNullOrEmpty(text3) && (!text3.StartsWith("[") || !text3.EndsWith("]"))) { text2 = text3; } } catch { } } CachedNames[key] = text2; return text2; } private static string GroupOverride(int id, string enumName, string displayName) { string value = KratyrUnifiedSkills.SkillSortCategoryOverrides.Value; if (string.IsNullOrWhiteSpace(value)) { return null; } string[] array = value.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string text in array) { int num = text.IndexOf(':'); if (num <= 0) { continue; } string text2 = text.Substring(0, num).Trim(); string proposed = text.Substring(num + 1).Trim(); if (text2.Equals(id.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase) || Normalize(text2).Equals(Normalize(enumName), StringComparison.OrdinalIgnoreCase) || Normalize(text2).Equals(Normalize(displayName), StringComparison.OrdinalIgnoreCase)) { return GroupOrder.FirstOrDefault((string group) => group.Equals(proposed, StringComparison.OrdinalIgnoreCase)); } } return null; } private static int GetGroupIndex(Skill skill) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected I4, but got Unknown if (skill == null || skill.m_info == null) { return GroupOrder.Length - 1; } string text = KratyrUnifiedSkills.SkillSortCategoryOverrides.Value ?? ""; if (!string.Equals(CachedOverrides, text, StringComparison.Ordinal)) { CachedOverrides = text; CachedGroups.Clear(); } int num = (int)skill.m_info.m_skill; if (CachedGroups.TryGetValue(num, out var value)) { return value; } string text2 = ((object)Unsafe.As<SkillType, SkillType>(ref skill.m_info.m_skill)/*cast due to .constrained prefix*/).ToString(); string name = GetName(skill); string value2 = GroupOverride(num, text2, name); if (value2 == null && !DefaultGroups.TryGetValue(Normalize(name), out value2)) { DefaultGroups.TryGetValue(Normalize(text2), out value2); } int num2 = GroupOrder.Length - 1; if (value2 != null) { for (int i = 0; i < GroupOrder.Length; i++) { if (GroupOrder[i].Equals(value2, StringComparison.OrdinalIgnoreCase)) { num2 = i; break; } } } CachedGroups[num] = num2; return num2; } private static void EnsureButton(SkillsDialog dialog) { //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0242: 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_0264: Expected O, but got Unknown if ((Object)(object)dialog == (Object)null) { return; } Transform transform = ((Component)dialog).transform; RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null); if ((Object)(object)val == (Object)null) { val = ((Component)dialog).GetComponentInParent<RectTransform>(); } if ((Object)(object)val == (Object)null || (Object)(object)((Component)val).GetComponentInParent<Canvas>() == (Object)null) { WarnOnce("Sort button has no compatible RectTransform / Canvas parent", new InvalidOperationException("SkillsDialog UI hierarchy is incompatible")); return; } Transform val2 = ((Transform)val).Find("KratyrUnifiedSkillsSortButton"); GameObject val3; TMP_Text val4; if ((Object)(object)val2 != (Object)null) { val3 = ((Component)val2).gameObject; Button component = val3.GetComponent<Button>(); val4 = val3.GetComponentInChildren<TMP_Text>(true); } else { val3 = new GameObject("KratyrUnifiedSkillsSortButton", new Type[3] { typeof(RectTransform), typeof(Image), typeof(Button) }); val3.transform.SetParent((Transform)(object)val, false); Image component2 = val3.GetComponent<Image>(); ((Graphic)component2).color = new Color(0.21f, 0.13f, 0.075f, 0.94f); Button component = val3.GetComponent<Button>(); ((Selectable)component).targetGraphic = (Graphic)(object)component2; GameObject val5 = new GameObject("Label", new Type[2] { typeof(RectTransform), typeof(TextMeshProUGUI) }); val5.transform.SetParent(val3.transform, false); val4 = (TMP_Text)(object)val5.GetComponent<TextMeshProUGUI>(); val4.alignment = (TextAlignmentOptions)514; ((Graphic)val4).color = new Color(1f, 0.78f, 0.34f, 1f); val4.fontSize = 16f; ((Graphic)val4).raycastTarget = false; val4.textWrappingMode = (TextWrappingModes)0; TMP_Text val6 = ((IEnumerable<TMP_Text>)((Component)dialog).GetComponentsInChildren<TMP_Text>(true)).FirstOrDefault((Func<TMP_Text, bool>)((TMP_Text text) => ((Object)text).name.Equals("name", StringComparison.OrdinalIgnoreCase))); if ((Object)(object)val6 != (Object)null) { val4.font = val6.font; val4.fontSize = Mathf.Clamp(val6.fontSize * 0.9f, 13f, 19f); } RectTransform val7 = (RectTransform)val5.transform; val7.anchorMin = Vector2.zero; val7.anchorMax = Vector2.one; val7.offsetMin = Vector2.zero; val7.offsetMax = Vector2.zero; ((UnityEvent)component.onClick).AddListener((UnityAction)delegate { CycleMode(dialog); }); } RectTransform val8 = (RectTransform)val3.transform; val8.anchorMin = Vector2.one; val8.anchorMax = Vector2.one; val8.pivot = new Vector2(0.5f, 0.5f); val8.sizeDelta = new Vector2(166f, 32f); val8.anchoredPosition = new Vector2(KratyrUnifiedSkills.SkillSortButtonX.Value, KratyrUnifiedSkills.SkillSortButtonY.Value); val3.transform.SetAsLastSibling(); if ((Object)(object)val4 != (Object)null) { val4.text = "Sort: " + ((KratyrUnifiedSkills.SkillSortOrder.Value == SkillSortMode.Default) ? "Default" : KratyrUnifiedSkills.SkillSortOrder.Value.ToString()); } } private static void CycleMode(SkillsDialog dialog) { SkillSortMode value = KratyrUnifiedSkills.SkillSortOrder.Value; KratyrUnifiedSkills.SkillSortOrder.Value = value switch { SkillSortMode.Name => SkillSortMode.Type, SkillSortMode.Default => SkillSortMode.Name, _ => SkillSortMode.Default, }; try { Player localPlayer = Player.m_localPlayer; if ((Object)(object)dialog != (Object)null && (Object)(object)localPlayer != (Object)null) { MethodInfo methodInfo = AccessTools.Method(typeof(SkillsDialog), "Setup", new Type[1] { typeof(Player) }, (Type[])null); if (methodInfo != null) { methodInfo.Invoke(dialog, new object[1] { localPlayer }); } } } catch (Exception ex) { WarnOnce("Cannot refresh skills menu; reopen it after sorting", ex); } } private static void WarnOnce(string message, Exception ex) { if (!_warned) { _warned = true; if ((Object)(object)KratyrUnifiedSkills.Instance != (Object)null) { KratyrUnifiedSkills.Instance.LogWarningForSort(message + ": " + ex); } } } } [BepInPlugin("kratyr.valheim.unifiedskills.playtest", "Kratyr Unified Skills - Compatibility Playtest", "0.2.4")] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class KratyrUnifiedSkills : BaseUnityPlugin { [HarmonyPatch(typeof(Skill), "Raise", new Type[] { typeof(float) })] private static class SkillRaise { [HarmonyPrefix] [HarmonyPriority(900)] private static bool Prefix(Skill __instance, ref float factor, ref bool __result) { if (__instance == null) { return true; } float level = __instance.m_level; if (level < 0f) { if (factor > 0f && !float.IsNaN(factor) && !float.IsInfinity(factor)) { factor *= NegativeRecoverySpeed.Value; } return true; } if (level < 100f) { factor *= PositiveXPSpeed.Value; return true; } if (level >= PositiveCap.Value || __instance.m_info == null || factor <= 0f) { __result = false; return false; } float num = __instance.m_info.m_increseStep * factor * ExtendedXPSpeed.Value * Game.m_skillGainRate; if (float.IsNaN(num) || float.IsInfinity(num) || num <= 0f) { __result = false; return false; } __instance.m_accumulator += num; if (__instance.m_accumulator >= Requirement(level + 1f)) { __instance.m_level = Mathf.Min(PositiveCap.Value, level + 1f); __instance.m_accumulator = 0f; __result = true; if (Diagnostics.Value) { ((BaseUnityPlugin)Instance).Logger.LogInfo((object)("Raised extended skill to " + __instance.m_level)); } } else { __result = false; } return false; } } [HarmonyPatch(typeof(Skill), "GetLevelPercentage")] private static class ExtendedSkillProgress { [HarmonyPrefix] [HarmonyPriority(900)] private static bool Prefix(Skill __instance, ref float __result) { if (__instance == null || __instance.m_level < 100f) { return true; } if (__instance.m_level >= PositiveCap.Value) { __result = 1f; return false; } __result = Mathf.Clamp01(__instance.m_accumulator / Requirement(__instance.m_level + 1f)); return false; } } [HarmonyPatch(typeof(Skills), "GetSkillFactor", new Type[] { typeof(SkillType) })] private static class ExtendedPositiveFactor { [HarmonyPostfix] private static void Postfix(Skills __instance, SkillType skillType, ref float __result) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (ExtendPositiveFactors.Value && (int)skillType != 0) { float skillLevel = __instance.GetSkillLevel(skillType); if (!(skillLevel <= 100f)) { __result = Mathf.Min(skillLevel / 100f, ExtendedFactorCap.Value); } } } } private struct SkillSnapshot { public Skill Skill; public float Level; public float Accumulator; } [HarmonyPatch(typeof(Skills), "LowerAllSkills", new Type[] { typeof(float) })] private static class ProtectZeroSkills { [HarmonyPrefix] [HarmonyPriority(900)] private static void Prefix(Skills __instance, float factor, out List<SkillSnapshot> __state) { __state = null; if (!ProtectZeroOnDeath.Value || factor <= 0f) { return; } List<KeyValuePair<SkillType, Skill>> skillEntries = GetSkillEntries(__instance); if (skillEntries == null) { return; } __state = new List<SkillSnapshot>(); foreach (KeyValuePair<SkillType, Skill> item in skillEntries) { if (item.Value != null) { float level = item.Value.m_level; if (level >= 0f && level < 1f) { __state.Add(new SkillSnapshot { Skill = item.Value, Level = level, Accumulator = item.Value.m_accumulator }); } } } } [HarmonyPostfix] [HarmonyPriority(0)] private static void Postfix(List<SkillSnapshot> __state) { if (__state == null) { return; } int num = 0; foreach (SkillSnapshot item in __state) { if (item.Skill != null) { bool num2 = item.Skill.m_level < item.Level; bool flag = item.Skill.m_level == item.Level && item.Skill.m_accumulator < item.Accumulator; if (num2 || flag) { item.Skill.m_level = item.Level; item.Skill.m_accumulator = item.Accumulator; num++; } } } if (num > 0 && Diagnostics.Value) { ((BaseUnityPlugin)Instance).Logger.LogInfo((object)("Protected " + num + " raw 0.0 to <1.0 skill records from death loss.")); } } } [HarmonyPatch(typeof(Terminal), "InitTerminal")] private static class Commands { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleEvent <>9__1_0; internal void <Postfix>b__1_0(ConsoleEventArgs args) { Instance.Execute(args.Context, (args.Length > 1) ? args[1] : "status", (args.Length > 2) ? args[2] : null, (args.Length > 3) ? args[3] : null, (args.Length > 4) ? args[4] : null); } } private static bool _registered; [HarmonyPostfix] private static void Postfix() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown if (_registered) { return; } object obj = <>c.<>9__1_0; if (obj == null) { ConsoleEvent val = delegate(ConsoleEventArgs args) { Instance.Execute(args.Context, (args.Length > 1) ? args[1] : "status", (args.Length > 2) ? args[2] : null, (args.Length > 3) ? args[3] : null, (args.Length > 4) ? args[4] : null); }; <>c.<>9__1_0 = val; obj = (object)val; } new ConsoleCommand("kskills", "Kratyr Skills: status | sort | players | inspect <player> | preview <player> [skill] | half <player> | reset <player> [skill] | set <player> <skill> <level> (admin).", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); _registered = true; } } public const string GUID = "kratyr.valheim.unifiedskills.playtest"; public const string Version = "0.2.4"; public const string BalrondGUID = "balrond.astafaraios.BalrondNegativeSkills"; private const string UncappedGUID = "com.koalaking.uncappedskills"; private const string BalrondMathName = "BalrondNegativeSkills.Core.NegativeSkillMath"; internal static KratyrUnifiedSkills Instance; internal static ConfigEntry<float> PositiveCap; internal static ConfigEntry<float> NegativeRecoverySpeed; internal static ConfigEntry<float> PositiveXPSpeed; internal static ConfigEntry<float> ExtendedXPSpeed; internal static ConfigEntry<bool> ProtectZeroOnDeath; internal static ConfigEntry<bool> ExtendPositiveFactors; internal static ConfigEntry<float> ExtendedFactorCap; internal static ConfigEntry<bool> Diagnostics; internal static ConfigEntry<bool> AllowHostTestSet; internal static ConfigEntry<bool> LockConfig; internal static ConfigEntry<SkillSortMode> SkillSortOrder; internal static ConfigEntry<bool> ShowSkillSortButton; internal static ConfigEntry<float> SkillSortButtonX; internal static ConfigEntry<float> SkillSortButtonY; internal static ConfigEntry<string> SkillSortCategoryOverrides; private Harmony _harmony; private bool _active; private object _sync; private MethodInfo _balrondSetLevel; private static readonly FieldInfo SkillDataField = FindSkillDataField(); internal bool ActiveForAdmin => _active; private void Awake() { //IL_03c1: Unknown result type (might be due to invalid IL or missing references) //IL_03cb: Expected O, but got Unknown //IL_03e2: Unknown result type (might be due to invalid IL or missing references) //IL_03e7: Unknown result type (might be due to invalid IL or missing references) //IL_03fb: Expected O, but got Unknown Instance = this; PositiveCap = Bind("1 - Skill Caps", "Maximum Positive Skill Level", 200f, 100f, 500f, "Maximum skill level stored and trainable. Negative minimum remains Balrond's -100."); NegativeRecoverySpeed = Bind("2 - Experience", "Negative Skill Speed Multiplier", 2f, 0.1f, 20f, "Multiplier for POSITIVE skill XP earned while skill level is below 0. 2.0 gives 2x recovery XP toward zero; it does NOT multiply death penalties, negative XP, or other skill losses."); PositiveXPSpeed = Bind("2 - Experience", "Positive XP Multiplier (0 to 100)", 1f, 0.1f, 20f, "Normal positive XP multiplier before the vanilla cap."); ExtendedXPSpeed = Bind("2 - Experience", "Extended XP Multiplier (100+)", 1f, 0.1f, 20f, "XP multiplier applied above level 100, independently of ordinary positive XP."); ProtectZeroOnDeath = ((BaseUnityPlugin)this).Config.Bind<bool>("3 - Death", "Protect Zero Skills On Death", false, "Protect existing skill records with raw level 0.0 up to (but not including) 1.0 from death skill loss, including fractional levels displayed as 0. Negative and level-1+ skills still lose levels according to Balrond's rules."); ExtendPositiveFactors = ((BaseUnityPlugin)this).Config.Bind<bool>("4 - Effects", "Extend Positive Skill Factor", false, "UNSAFE EXPERIMENTAL: allow GetSkillFactor to exceed 1 for level >100. Disabled by default; most effects remain level-100 capped."); ExtendedFactorCap = Bind("4 - Effects", "Extended Skill Factor Ceiling", 1.5f, 1f, 3f, "Maximum GetSkillFactor when extended positive skill factors are enabled."); Diagnostics = ((BaseUnityPlugin)this).Config.Bind<bool>("5 - Diagnostics", "Detailed Logging", false, "Log individual changes for diagnosis (local setting)."); AllowHostTestSet = ((BaseUnityPlugin)this).Config.Bind<bool>("5 - Diagnostics", "Allow Host Test Set Command", false, "OFF by default. Enables kskills set <existing ID/name> <value> on local hosted world ONLY, for disposable-character testing."); LockConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("6 - Multiplayer", "Lock Host Configuration", true, "Use the host's Kratyr settings when connected, through Balrond's bundled ServerSync (experimental)."); SkillSortOrder = ((BaseUnityPlugin)this).Config.Bind<SkillSortMode>("7 - Skills Window", "Sort Order", SkillSortMode.Default, "Default keeps the game's original order. Name sorts alphabetically. Type groups related skills, sorting each group by name."); ShowSkillSortButton = ((BaseUnityPlugin)this).Config.Bind<bool>("7 - Skills Window", "Show Sort Button", true, "Show a small Sort control on the game's normal skills panel. Config and 'kskills sort' still work when disabled."); SkillSortButtonX = Bind("7 - Skills Window", "Sort Button Offset X", -110f, -800f, 200f, "Horizontal position relative to the Skills dialog top-right; negative values move left."); SkillSortButtonY = Bind("7 - Skills Window", "Sort Button Offset Y", -53f, -400f, 50f, "Vertical position relative to the Skills dialog top-right; negative values move down."); SkillSortCategoryOverrides = ((BaseUnityPlugin)this).Config.Bind<string>("7 - Skills Window", "Skill Category Overrides", "", "Optional mappings, separated by semicolons. Example: 16050:Magic;Throwing:Combat;Hauling:Gathering. Available categories: Movement, Combat, Magic, Survival, Gathering, Crafting, Other."); if (!Chainloader.PluginInfos.TryGetValue("balrond.astafaraios.BalrondNegativeSkills", out var value) || value.Metadata.Version.ToString() != "0.1.2") { ((BaseUnityPlugin)this).Logger.LogError((object)"Requires exactly Balrond Negative Skills 0.1.2. Disabled without patching."); return; } if (Chainloader.PluginInfos.ContainsKey("com.koalaking.uncappedskills") || AppDomain.CurrentDomain.GetAssemblies().Any((Assembly a) => a.GetName().Name == "UncappedSkills")) { ((BaseUnityPlugin)this).Logger.LogError((object)"Remove the separate UncappedSkills DLL first. Two positive cap mods must not patch Skills.Raise simultaneously."); return; } Assembly assembly = ((object)value.Instance).GetType().Assembly; Type type = assembly.GetType("BalrondNegativeSkills.Core.NegativeSkillMath", throwOnError: false); MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "ClampRawLevel", new Type[1] { typeof(float) }, (Type[])null)); Type type2 = assembly.GetType("BalrondNegativeSkills.API.NegativeSkillsApi", throwOnError: false); _balrondSetLevel = ((type2 == null) ? null : type2.GetMethod("TrySetLevel", BindingFlags.Static | BindingFlags.Public, null, new Type[5] { typeof(Skills), typeof(SkillType), typeof(float), typeof(bool), typeof(float).MakeByRefType() }, null)); if (methodInfo == null || methodInfo.ReturnType != typeof(float) || _balrondSetLevel == null) { ((BaseUnityPlugin)this).Logger.LogError((object)"Required Balrond 0.1.2 internals not found; no game patches applied."); return; } try { _harmony = new Harmony("kratyr.valheim.unifiedskills.playtest"); _harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(KratyrUnifiedSkills), "ClampRawLevel", (Type[])null) { priority = 900 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _harmony.PatchAll(typeof(KratyrUnifiedSkills).Assembly); if (SkillDataField == null) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"Could not locate Valheim Skills dictionary; inspect/cleanup/zero-death protection will not operate. Other patches will still load."); } else { ((BaseUnityPlugin)this).Logger.LogInfo((object)("Skill dictionary field resolved as " + SkillDataField.Name + ".")); } _active = true; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Skill cap/recovery/zero-death protection/cleanup patches registered. Original Balrond negative gameplay behavior preserved."); if (!TryInitializeConfigSync(assembly)) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"Kratyr ServerSync unavailable: for multiplayer, EVERY PLAYER must manually match Kratyr config values. Original Balrond settings continue to use its own ServerSync."); } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Patch registration failed; reverting Kratyr patches: " + ex)); _harmony.UnpatchSelf(); _active = false; } } private static ConfigEntry<float> Bind(string section, string key, float value, float minimum, float maximum, string description) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown return ((BaseUnityPlugin)Instance).Config.Bind<float>(section, key, value, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<float>(minimum, maximum), Array.Empty<object>())); } private bool TryInitializeConfigSync(Assembly assembly) { try { Type type = assembly.GetType("ServerSync.ConfigSync", throwOnError: false); if (type == null) { return false; } _sync = Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new object[1] { "kratyr.valheim.unifiedskills.playtest" }, CultureInfo.InvariantCulture); if (_sync == null) { return false; } SetSyncField(type, "DisplayName", "Kratyr Unified Skills Playtest"); SetSyncField(type, "CurrentVersion", "0.2.4"); SetSyncField(type, "MinimumRequiredVersion", "0.2.4"); RegisterSync<bool>(type, "AddLockingConfigEntry", LockConfig); RegisterSync<float>(type, "AddConfigEntry", PositiveCap); RegisterSync<float>(type, "AddConfigEntry", NegativeRecoverySpeed); RegisterSync<float>(type, "AddConfigEntry", PositiveXPSpeed); RegisterSync<float>(type, "AddConfigEntry", ExtendedXPSpeed); RegisterSync<bool>(type, "AddConfigEntry", ProtectZeroOnDeath); RegisterSync<bool>(type, "AddConfigEntry", ExtendPositiveFactors); RegisterSync<float>(type, "AddConfigEntry", ExtendedFactorCap); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Kratyr config entries registered with Balrond-bundled ServerSync; verify host sync in a multiplayer test."); return true; } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Cannot initialize bundled ServerSync: " + ex)); return false; } } private void SetSyncField(Type syncType, string field, object value) { FieldInfo field2 = syncType.GetField(field, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field2 != null) { field2.SetValue(_sync, value); } } private void RegisterSync<T>(Type syncType, string method, ConfigEntry<T> entry) { syncType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).First((MethodInfo m) => m.Name == method && m.IsGenericMethodDefinition && m.GetParameters().Length == 1).MakeGenericMethod(typeof(T)) .Invoke(_sync, new object[1] { entry }); } internal void LogWarningForSort(string message) { ((BaseUnityPlugin)this).Logger.LogWarning((object)message); } private void OnDestroy() { if (_harmony != null) { _harmony.UnpatchSelf(); } } private static bool ClampRawLevel(float level, ref float __result) { if (float.IsNaN(level) || float.IsInfinity(level)) { level = 0f; } __result = Mathf.Clamp(level, -100f, PositiveCap.Value); return false; } private static float Requirement(float targetLevel) { float num = Mathf.Max(1f, Mathf.Ceil(targetLevel)); return 0.5f * Mathf.Pow(num, 1.5f) + 0.5f; } private static FieldInfo FindSkillDataField() { string[] array = new string[2] { "m_skillData", "m_skills" }; foreach (string name in array) { FieldInfo field = typeof(Skills).GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && typeof(IDictionary).IsAssignableFrom(field.FieldType)) { return field; } } FieldInfo[] fields = typeof(Skills).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { Type fieldType = fieldInfo.FieldType; if (fieldType.IsGenericType && !(fieldType.GetGenericTypeDefinition() != typeof(Dictionary<, >))) { Type[] genericArguments = fieldType.GetGenericArguments(); if (genericArguments[0] == typeof(SkillType) && genericArguments[1] == typeof(Skill)) { return fieldInfo; } } } return null; } internal static List<KeyValuePair<SkillType, Skill>> GetSkillEntries(Skills skills) { //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)skills == (Object)null || SkillDataField == null) { return null; } if (!(SkillDataField.GetValue(skills) is IDictionary dictionary)) { return null; } List<KeyValuePair<SkillType, Skill>> list = new List<KeyValuePair<SkillType, Skill>>(dictionary.Count); foreach (DictionaryEntry item in dictionary) { object? value = item.Value; Skill val = (Skill)((value is Skill) ? value : null); if (val != null) { if (item.Key is SkillType key) { list.Add(new KeyValuePair<SkillType, Skill>(key, val)); } else if (item.Key is int num) { list.Add(new KeyValuePair<SkillType, Skill>((SkillType)num, val)); } } } return list; } internal bool TrySetSkillLevel(Skills skills, SkillType type, float proposed, out float actual) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) actual = 0f; if (!_active || _balrondSetLevel == null || (Object)(object)skills == (Object)null || float.IsNaN(proposed) || float.IsInfinity(proposed)) { return false; } object[] array = new object[5] { skills, type, Mathf.Clamp(proposed, -100f, PositiveCap.Value), true, 0f }; try { if (!(bool)_balrondSetLevel.Invoke(null, array)) { return false; } actual = (float)array[4]; return true; } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Balrond TrySetLevel failed: " + ex)); return false; } } internal void AdminLog(string message) { ((BaseUnityPlugin)this).Logger.LogInfo((object)message); } internal void AdminWarn(string message) { ((BaseUnityPlugin)this).Logger.LogWarning((object)message); } private void Execute(Terminal terminal, string action, string first, string second, string third) { try { string text = (action ?? "status").Trim().ToLowerInvariant(); if (text == "sort") { if (string.IsNullOrEmpty(first)) { terminal.AddString("Skills window sort: " + SkillSortOrder.Value.ToString() + ". Usage: kskills sort default | name | type"); return; } if (!Enum.TryParse<SkillSortMode>(first, ignoreCase: true, out var result) || !Enum.IsDefined(typeof(SkillSortMode), result)) { terminal.AddString("Usage: kskills sort default | name | type"); return; } SkillSortOrder.Value = result; terminal.AddString("Skills window sort changed to " + result.ToString() + ". Reopen Skills to see the result."); } else if (text == "status") { terminal.AddString("Kratyr Unified Skills 0.2.4 active=" + _active + " range=-100.." + PositiveCap.Value.ToString(CultureInfo.InvariantCulture) + " negative recovery=" + NegativeRecoverySpeed.Value + "x gain-only"); terminal.AddString("Only the host and server-authorized admins may inspect or modify character skill data via kskills."); terminal.AddString("kskills players | inspect <player> | preview <player> [skill] | half <player> | reset <player> [skill] | set <player> <skill> <level>"); } else if (text != "players" && text != "inspect" && text != "preview" && text != "half" && text != "reset" && text != "set") { terminal.AddString("Usage: kskills status | sort default/name/type | players | inspect/half <player> | preview/reset <player> [skill] | set <player> <skill> <level>"); } else { KratyrSkillAdmin.ExecuteConsole(terminal, text, first, second, third); } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("kskills command failed: " + ex)); terminal.AddString("kskills failed. See LogOutput.log."); } } } }