Decompiled source of StaminaExtended v1.0.5
StaminaExtended.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("StaminaExtended")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StaminaExtended")] [assembly: AssemblyCopyright("Copyright © 2024")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("566e4d45-1d36-47c7-8a5e-ab19706121bd")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace StaminaExtended { internal static class ExtraStamina { [HarmonyPatch(typeof(Player), "GetTotalFoodValue")] public static class Player_GetTotalFoodValue_BaseStaminaIncrease { [HarmonyPriority(100)] public static void Prefix(Player __instance, ref float __state) { if (StaminaExtended.modEnabled.Value && StaminaExtended.baseStamina.Value && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { __state = __instance.m_baseStamina; __instance.m_baseStamina += GetAdditionalBaseStamina(__instance); } } [HarmonyPriority(700)] public static void Postfix(Player __instance, float __state) { if (StaminaExtended.modEnabled.Value && __state != 0f) { __instance.m_baseStamina = __state; } } } [HarmonyPatch(typeof(ItemData), "GetTooltip", new Type[] { typeof(ItemData), typeof(int), typeof(bool), typeof(float), typeof(int) })] public static class ItemDrop_ItemData_GetTooltip_StaminaRegenTooltipForFoodRegen { private static string[] tooltipTokens = new string[4] { "$item_food_regen", "$item_food_duration", "$item_food_eitr", "$item_food_stamina" }; [HarmonyPriority(800)] [HarmonyBefore(new string[] { "shudnal.MyLittleUI" })] private static void Postfix(ItemData item, ref string __result) { if (!StaminaExtended.modEnabled.Value || !IsFoodItemForExtraStaminaRegeneration(item, out var foodStamina)) { return; } int num = -1; string[] array = tooltipTokens; foreach (string value in array) { num = __result.IndexOf(value, StringComparison.InvariantCulture); if (num != -1) { break; } } if (num != -1) { string text = $"\n$se_staminaregen: <color=#ffff80ff>{GetStaminaRegenerationValueFromStaminaPoints(foodStamina):P1}</color> ($item_current:<color=yellow>{GetMultiplier(Player.m_localPlayer):P1}</color>)"; int num2 = __result.IndexOf("\n", num, StringComparison.InvariantCulture); if (num2 != -1) { __result.Insert(num2, text); } else { __result += text; } } } } [HarmonyPatch(typeof(TextsDialog), "AddActiveEffects")] public static class TextsDialog_AddActiveEffects_SeasonTooltipWhenBuffDisabled { private static void Postfix(TextsDialog __instance) { if (StaminaExtended.modEnabled.Value && !((Object)(object)Player.m_localPlayer == (Object)null)) { float multiplier = GetMultiplier(Player.m_localPlayer); if (!(multiplier < 0.01f)) { TextInfo obj = __instance.m_texts[0]; obj.m_text += Localization.instance.Localize(string.Format("\n$se_staminaregen ({0}): <color=orange>{1:P1}</color>", StaminaExtended.extraStaminaRegenerationOnlyFood.Value ? "$item_food" : "$hud_misc", multiplier)); } } } } public static float GetMultiplier(Player player) { float maxStamina = ((Character)player).GetMaxStamina(); if (StaminaExtended.extraStaminaRegenerationOnlyFood.Value) { float num = default(float); float num2 = default(float); player.GetTotalFoodValue(ref num, ref maxStamina, ref num2); } return GetStaminaRegenerationValueFromStaminaPoints(maxStamina - player.m_baseStamina - GetAdditionalBaseStamina(player)); } private static float GetStaminaRegenerationValueFromStaminaPoints(float points) { return StaminaExtended.extraStaminaRegenerationPercent.Value / 100f * points / (float)StaminaExtended.extraStaminaRegenerationPoints.Value; } private static bool IsFoodItemForExtraStaminaRegeneration(ItemData item, out float foodStamina) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 foodStamina = 0f; if (!StaminaExtended.extraStaminaRegeneration.Value || (Object)(object)Player.m_localPlayer == (Object)null) { return false; } if ((int)item.m_shared.m_itemType == 2) { foodStamina = item.m_shared.m_foodStamina; } return foodStamina > 0f || ((Object)(object)item.m_shared.m_appendToolTip != (Object)null && IsFoodItemForExtraStaminaRegeneration(item.m_shared.m_appendToolTip.m_itemData, out foodStamina)); } private static float GetAdditionalBaseStamina(Player player) { if (!StaminaExtended.baseStamina.Value) { return 0f; } return ((Character)player).GetSkillFactor((SkillType)102) * StaminaExtended.runBaseStaminaIncrease.Value + ((Character)player).GetSkillFactor((SkillType)103) * StaminaExtended.swimBaseStaminaIncrease.Value + ((Character)player).GetSkillFactor((SkillType)104) * StaminaExtended.fishingBaseStaminaIncrease.Value + ((Character)player).GetSkillFactor((SkillType)101) * StaminaExtended.sneakBaseStaminaIncrease.Value + ((Character)player).GetSkillFactor((SkillType)100) * StaminaExtended.jumpBaseStaminaIncrease.Value + ((Character)player).GetSkillFactor((SkillType)11) * StaminaExtended.handsBaseStaminaIncrease.Value; } } public class SE_Surface : SE_Stats { public static Sprite statusEffectIcon; private SurfaceStaminaSpeed.SurfaceMaterial surfaceMaterial = SurfaceStaminaSpeed.SurfaceMaterial.None; public override void UpdateStatusEffect(float dt) { if (surfaceMaterial != SurfaceStaminaSpeed.currentSurface) { ((StatusEffect)this).Setup(((StatusEffect)this).m_character); } else { ((SE_Stats)this).UpdateStatusEffect(dt); } } public override void Setup(Character character) { surfaceMaterial = SurfaceStaminaSpeed.currentSurface; UpdateSurfaceStatusEffect(); ((SE_Stats)this).Setup(character); } public void UpdateSurfaceStatusEffect() { //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) ((StatusEffect)this).m_name = GetSurfaceMaterialName(surfaceMaterial); ((StatusEffect)this).m_icon = (StaminaExtended.groundsShowStatusEffect.Value ? statusEffectIcon : null); base.m_runStaminaDrainModifier = GetSurfaceMaterialStaminaDrain(surfaceMaterial) - 1f; base.m_jumpStaminaUseModifier = GetSurfaceMaterialStaminaDrain(surfaceMaterial) - 1f; base.m_staminaRegenMultiplier = GetSurfaceMaterialStaminaRegen(surfaceMaterial); base.m_speedModifier = GetSurfaceMaterialSpeed(surfaceMaterial) - 1f; base.m_jumpModifier = new Vector3(0f, GetSurfaceMaterialJump(surfaceMaterial) - 1f, 0f); } public static void UpdateSurfaceStatusEffectStats() { if (!((Object)(object)ObjectDB.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null)) { SE_Surface obj = ((Character)Player.m_localPlayer).GetSEMan().GetStatusEffect(StaminaExtended.statusEffectSurfaceHash) as SE_Surface; if (obj != null) { ((StatusEffect)obj).Setup((Character)(object)Player.m_localPlayer); } } } public static float GetSurfaceMaterialSpeed(SurfaceStaminaSpeed.SurfaceMaterial surfaceMaterial) { if (surfaceMaterial == SurfaceStaminaSpeed.SurfaceMaterial.None) { return 1f; } return StaminaExtended.instance.GetFloatConfig($"groundsSpeed{surfaceMaterial}"); } public static float GetSurfaceMaterialJump(SurfaceStaminaSpeed.SurfaceMaterial surfaceMaterial) { if (surfaceMaterial == SurfaceStaminaSpeed.SurfaceMaterial.None) { return 1f; } return StaminaExtended.instance.GetFloatConfig($"groundsJump{surfaceMaterial}"); } public static float GetSurfaceMaterialStaminaDrain(SurfaceStaminaSpeed.SurfaceMaterial surfaceMaterial) { if (surfaceMaterial == SurfaceStaminaSpeed.SurfaceMaterial.None) { return 1f; } return StaminaExtended.instance.GetFloatConfig($"groundsStaminaDrain{surfaceMaterial}"); } public static float GetSurfaceMaterialStaminaRegen(SurfaceStaminaSpeed.SurfaceMaterial surfaceMaterial) { if (surfaceMaterial == SurfaceStaminaSpeed.SurfaceMaterial.None) { return 1f; } return StaminaExtended.instance.GetFloatConfig($"groundsStaminaRegen{surfaceMaterial}"); } public static string GetSurfaceMaterialName(SurfaceStaminaSpeed.SurfaceMaterial surfaceMaterial) { return StaminaExtended.instance.GetStringConfig("groundsName" + ((surfaceMaterial == SurfaceStaminaSpeed.SurfaceMaterial.None) ? "Default" : surfaceMaterial.ToString())); } } public class SurfaceStaminaSpeed { public enum SurfaceMaterial { None, Grass, Mud, Snow, Wood, HardWood, Stone, Marble, Metal, Cultivated, Cleared, Paved, Ash, Lava } [HarmonyPatch(typeof(FootStep), "GetGroundMaterial")] private static class FootStep_GetGroundMaterial_GroundDetection { private static void Postfix(Character character, Vector3 point, GroundMaterial __result) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Invalid comparison between Unknown and I4 //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Invalid comparison between Unknown and I4 //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Invalid comparison between Unknown and I4 //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Invalid comparison between Unknown and I4 //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Invalid comparison between Unknown and I4 //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Invalid comparison between Unknown and I4 //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Expected I4, but got Unknown //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Invalid comparison between Unknown and I4 //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Invalid comparison between Unknown and I4 //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Invalid comparison between Unknown and I4 //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Invalid comparison between Unknown and I4 //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Invalid comparison between Unknown and I4 if (!StaminaExtended.modEnabled.Value || (Object)(object)character != (Object)(object)Player.m_localPlayer) { return; } Collider collider = character.GetLastGroundCollider(); if ((Object)(object)collider == (Object)null) { currentSurface = SurfaceMaterial.None; return; } if ((int)__result <= 64) { if ((int)__result <= 16) { switch ((int)__result) { default: if ((int)__result != 16) { goto IL_024e; } currentSurface = SurfaceMaterial.Snow; return; case 0: case 2: break; case 8: currentSurface = (IsUpgradedMaterial(collider) ? SurfaceMaterial.HardWood : SurfaceMaterial.Wood); return; case 4: currentSurface = (IsUpgradedMaterial(collider) ? SurfaceMaterial.Marble : SurfaceMaterial.Stone); return; case 1: { WearNTear piece = GetPiece(collider); if ((Object)(object)piece != (Object)null) { currentSurface = GetSurfaceMaterial(piece.m_materialType); } return; } case 3: case 5: case 6: case 7: goto IL_024e; } goto IL_0121; } if ((int)__result == 32) { currentSurface = GetModifiedGround(collider, point); if (currentSurface == SurfaceMaterial.None) { currentSurface = SurfaceMaterial.Mud; } return; } if ((int)__result == 64) { currentSurface = GetModifiedGround(collider, point); if (currentSurface == SurfaceMaterial.None) { currentSurface = SurfaceMaterial.Grass; } return; } } else if ((int)__result <= 256) { if ((int)__result == 128) { currentSurface = GetModifiedGround(collider, point); if (currentSurface == SurfaceMaterial.None && IsPlainsGrass()) { currentSurface = SurfaceMaterial.Grass; } return; } if ((int)__result == 256) { currentSurface = SurfaceMaterial.Metal; return; } } else { if ((int)__result == 512) { goto IL_0121; } if ((int)__result == 1024) { currentSurface = SurfaceMaterial.Ash; return; } if ((int)__result == 2048) { currentSurface = SurfaceMaterial.Lava; return; } } goto IL_024e; IL_0121: currentSurface = SurfaceMaterial.None; return; IL_024e: currentSurface = SurfaceMaterial.None; bool IsPlainsGrass() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between Unknown and I4 //IL_0043: Unknown result type (might be due to invalid IL or missing references) Heightmap heightmap = GetHeightmap(collider); if ((Object)(object)heightmap == (Object)null) { return false; } if ((int)heightmap.GetBiome(point, 0.02f, false) != 16) { return false; } return Mathf.Acos(Mathf.Clamp01(character.GetLastGroundNormal().y)) * 57.29578f < 40f; } } } [HarmonyPatch(typeof(ObjectDB), "Awake")] public static class ObjectDB_Awake_AddStatusEffects { public static void AddCustomStatusEffects(ObjectDB odb) { if (odb.m_StatusEffects.Count > 0 && !odb.m_StatusEffects.Any((StatusEffect se) => ((Object)se).name == "Surface")) { SE_Surface sE_Surface = ScriptableObject.CreateInstance<SE_Surface>(); ((Object)sE_Surface).name = "Surface"; ((StatusEffect)sE_Surface).m_nameHash = StaminaExtended.statusEffectSurfaceHash; ((StatusEffect)sE_Surface).m_icon = SE_Surface.statusEffectIcon; odb.m_StatusEffects.Add((StatusEffect)(object)sE_Surface); } } private static void Postfix(ObjectDB __instance) { AddCustomStatusEffects(__instance); } } [HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")] public static class ObjectDB_CopyOtherDB_SE_Season { private static void Postfix(ObjectDB __instance) { ObjectDB_Awake_AddStatusEffects.AddCustomStatusEffects(__instance); } } [HarmonyPatch(typeof(Skills), "Awake")] public static class Skills_Awake_SE_Season { private static void Postfix(Skills __instance) { if ((Object)(object)SE_Surface.statusEffectIcon == (Object)null) { CollectionExtensions.DoIf<SkillDef>((IEnumerable<SkillDef>)__instance.m_skills, (Func<SkillDef, bool>)((SkillDef skill) => (int)skill.m_skill == 102), (Action<SkillDef>)delegate(SkillDef skill) { SE_Surface.statusEffectIcon = skill.m_icon; }); } } } [HarmonyPatch(typeof(TextsDialog), "AddActiveEffects")] public static class TextsDialog_AddActiveEffects_StatusTooltipWhenBuffDisabled { public static bool isActiveEffectsListCall; private static void Prefix() { isActiveEffectsListCall = StaminaExtended.groundsEnabled.Value && !StaminaExtended.groundsShowStatusEffect.Value; } private static void Postfix() { isActiveEffectsListCall = false; } } [HarmonyPatch(typeof(SEMan), "GetHUDStatusEffects")] public static class SEMan_GetHUDStatusEffects_SeasonTooltipWhenBuffDisabled { private static void Postfix(Character ___m_character, List<StatusEffect> ___m_statusEffects, List<StatusEffect> effects) { if (TextsDialog_AddActiveEffects_StatusTooltipWhenBuffDisabled.isActiveEffectsListCall && (Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)___m_character == (Object)(object)Player.m_localPlayer && !effects.Any((StatusEffect effect) => effect is SE_Surface)) { StatusEffect val = ___m_statusEffects.Find((StatusEffect se) => se is SE_Surface); if ((Object)(object)val != (Object)null) { effects.Add(val); } } } } [HarmonyPatch(typeof(Character), "UpdateGroundContact")] public static class Character_UpdateGroundContact_GroundDetectionOnContact { private static void Prefix(Character __instance, float ___m_maxAirAltitude, ref float __state) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (StaminaExtended.groundsEnabled.Value && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { __state = Mathf.Max(0f, ___m_maxAirAltitude - ((Component)__instance).transform.position.y); } } private static void Postfix(Character __instance, float ___m_maxAirAltitude, float __state) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (__state != 0f && __state >= 0.2f && ___m_maxAirAltitude == ((Component)__instance).transform.position.y && __instance.IsOnGround() && currentSurface == SurfaceMaterial.None) { CheckCurrentGround(__instance); } } } public static SurfaceMaterial currentSurface = SurfaceMaterial.None; public static Dictionary<Collider, WearNTear> colliderPieces = new Dictionary<Collider, WearNTear>(); public static Dictionary<Collider, Heightmap> colliderHeightmaps = new Dictionary<Collider, Heightmap>(); public static int colliderCacheCleared = 0; public static int pieceLayer; private static bool IsUpgradedMaterial(Collider collider) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Invalid comparison between Unknown and I4 //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 WearNTear piece = GetPiece(collider); return (Object)(object)piece != (Object)null && ((int)piece.m_materialType == 3 || (int)piece.m_materialType == 4 || (int)piece.m_materialType == 5 || (int)piece.m_materialType == 6); } private static WearNTear GetPiece(Collider collider) { if ((int)(ZNet.instance.GetTimeSeconds() / 300.0) != colliderCacheCleared) { colliderCacheCleared = (int)(ZNet.instance.GetTimeSeconds() / 300.0); colliderPieces.Clear(); colliderHeightmaps.Clear(); } if ((Object)(object)collider == (Object)null) { return null; } if (pieceLayer == 0) { pieceLayer = LayerMask.NameToLayer("piece"); } if (((Component)collider).gameObject.layer != pieceLayer) { return null; } if (!colliderPieces.ContainsKey(collider)) { colliderPieces.Add(collider, ((Component)collider).GetComponentInParent<WearNTear>()); } return colliderPieces[collider]; } private static Heightmap GetHeightmap(Collider collider) { if ((int)(ZNet.instance.GetTimeSeconds() / 300.0) != colliderCacheCleared) { colliderCacheCleared = (int)(ZNet.instance.GetTimeSeconds() / 300.0); colliderPieces.Clear(); colliderHeightmaps.Clear(); } if ((Object)(object)collider == (Object)null) { return null; } if (!colliderHeightmaps.ContainsKey(collider)) { colliderHeightmaps.Add(collider, ((Component)collider).GetComponent<Heightmap>()); } return colliderHeightmaps[collider]; } private static SurfaceMaterial GetModifiedGround(Collider collider, Vector3 worldPos) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) Heightmap heightmap = GetHeightmap(collider); if ((Object)(object)heightmap == (Object)null) { return SurfaceMaterial.None; } int num = default(int); int num2 = default(int); heightmap.WorldToVertex(worldPos, ref num, ref num2); if (heightmap.m_paintMask.GetPixel(num, num2).g > 0.5f) { return SurfaceMaterial.Cultivated; } worldPos.x = (float)((double)worldPos.x - 0.5); worldPos.z = (float)((double)worldPos.z - 0.5); heightmap.WorldToVertex(worldPos, ref num, ref num2); Color pixel = heightmap.m_paintMask.GetPixel(num, num2); if (pixel.r > 0.5f) { return SurfaceMaterial.Cleared; } if (pixel.b > 0.5f) { return SurfaceMaterial.Paved; } if (pixel.g > 0.5f) { return SurfaceMaterial.Cultivated; } return SurfaceMaterial.None; } private static void CheckCurrentGround(Character character) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) Collider lastGroundCollider = character.GetLastGroundCollider(); if ((Object)(object)lastGroundCollider == (Object)null) { return; } currentSurface = GetModifiedGround(lastGroundCollider, ((Component)character).transform.position); if (currentSurface == SurfaceMaterial.None && ((Component)lastGroundCollider).gameObject.layer == pieceLayer) { WearNTear piece = GetPiece(lastGroundCollider); if ((Object)(object)piece != (Object)null) { currentSurface = GetSurfaceMaterial(piece.m_materialType); } } } public static SurfaceMaterial GetSurfaceMaterial(MaterialType materialType) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected I4, but got Unknown if (1 == 0) { } SurfaceMaterial result = (int)materialType switch { 0 => SurfaceMaterial.Wood, 1 => SurfaceMaterial.Stone, 4 => SurfaceMaterial.Marble, 3 => SurfaceMaterial.HardWood, 2 => SurfaceMaterial.Metal, 5 => SurfaceMaterial.Marble, 6 => SurfaceMaterial.Marble, _ => SurfaceMaterial.None, }; if (1 == 0) { } return result; } } [BepInPlugin("shudnal.StaminaExtended", "Stamina Extended", "1.0.5")] public class StaminaExtended : BaseUnityPlugin { [HarmonyPatch(typeof(Player), "UpdateStats", new Type[] { typeof(float) })] public static class Player_UpdateStats_StaminaRegenMultiplier { private static float _m_encumberedStaminaDrain; private static float _m_staminaRegenTimeMultiplier; [HarmonyPriority(100)] public static void Prefix(Player __instance, float dt) { if (!modEnabled.Value || ((Character)__instance).InIntro() || ((Character)__instance).IsTeleporting()) { return; } _m_staminaRegenTimeMultiplier = __instance.m_staminaRegenTimeMultiplier; if (extraStaminaRegeneration.Value && extraStaminaRegenerationPercent.Value > 0f && extraStaminaRegenerationPoints.Value > 0) { __instance.m_staminaRegenTimeMultiplier += ExtraStamina.GetMultiplier(__instance); } if (sneakingStamina.Value && ((Character)__instance).IsSneaking()) { __instance.m_staminaRegenTimeMultiplier += sneakingStaminaRegenerationMultiplier.Value * __instance.m_skills.GetSkillFactor((SkillType)101); } if (linearRegeneration.Value && 0f < linearRegenerationThreshold.Value && linearRegenerationThreshold.Value < 1f && linearRegenerationMultiplier.Value > 0f && ((Character)__instance).GetMaxStamina() != 0f) { if (((Character)__instance).GetStaminaPercentage() < linearRegenerationThreshold.Value) { float num = Mathf.Clamp01(__instance.GetStamina() / (((Character)__instance).GetMaxStamina() * linearRegenerationThreshold.Value)); __instance.m_staminaRegenTimeMultiplier = Mathf.Lerp(linearRegenerationMultiplier.Value, __instance.m_staminaRegenTimeMultiplier, num); } else if (((Character)__instance).GetStaminaPercentage() > linearRegenerationThreshold.Value) { float num2 = Mathf.Clamp01((((Character)__instance).GetMaxStamina() - __instance.GetStamina()) / (((Character)__instance).GetMaxStamina() * (1f - linearRegenerationThreshold.Value))); __instance.m_staminaRegenTimeMultiplier = Mathf.Lerp(1f / linearRegenerationMultiplier.Value, __instance.m_staminaRegenTimeMultiplier, num2); } } if (encumberedStamina.Value && ((Character)__instance).IsEncumbered()) { _m_encumberedStaminaDrain = __instance.m_encumberedStaminaDrain; __instance.m_encumberedStaminaDrain *= encumberedStaminaDrainMultiplier.Value; if (encumberedStaminaRegeneration.Value && ((Vector3)(ref ((Character)__instance).m_moveDir)).magnitude <= 0.1f && __instance.GetStamina() < ((Character)__instance).GetMaxStamina() && __instance.m_staminaRegenTimer <= 0f) { __instance.m_stamina = Mathf.Min(((Character)__instance).GetMaxStamina(), __instance.m_stamina + encumberedStaminaRegenerationMultiplier.Value * __instance.m_staminaRegen * dt * Game.m_staminaRegenRate); } } } [HarmonyPriority(700)] public static void Postfix(Player __instance) { if (modEnabled.Value) { if (__instance.m_staminaRegenTimeMultiplier != _m_staminaRegenTimeMultiplier && _m_staminaRegenTimeMultiplier != 0f) { __instance.m_staminaRegenTimeMultiplier = _m_staminaRegenTimeMultiplier; } if (__instance.m_encumberedStaminaDrain != _m_encumberedStaminaDrain && _m_encumberedStaminaDrain != 0f) { __instance.m_encumberedStaminaDrain = _m_encumberedStaminaDrain; } } } } [HarmonyPatch(typeof(Player), "OnSwimming")] public static class Player_OnSwimming_SwimmingStamina { public static void Prefix(Player __instance, Vector3 targetVel, float dt) { if (modEnabled.Value && swimmingStaminaRegeneration.Value && ((Vector3)(ref targetVel)).magnitude <= 0.1f) { __instance.m_staminaRegenTimer -= dt; if (__instance.GetStamina() < ((Character)__instance).GetMaxStamina() && __instance.m_staminaRegenTimer <= 0f - swimmingStaminaRegenerationDelay.Value) { float skillFactor = __instance.m_skills.GetSkillFactor((SkillType)103); __instance.m_stamina = Mathf.Min(((Character)__instance).GetMaxStamina(), __instance.m_stamina + (1f + skillFactor) * swimmingStaminaRegenerationMultiplier.Value * __instance.m_staminaRegen * dt * Game.m_staminaRegenRate); } } } } [HarmonyPatch(typeof(Character), "UpdateSwimming")] public static class Character_UpdateSwimming_SwimmingStamina { private static float _m_swimStaminaDrainMinSkill; private static float _m_swimStaminaDrainMaxSkill; private static float _m_swimSpeed; internal static float shiftSwimDownTime; internal static bool shiftSwimStaminaDepleted; [HarmonyPriority(100)] public static void Prefix(Character __instance, float dt) { if (!modEnabled.Value || !swimmingStamina.Value || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || __instance.IsOnGround()) { return; } _m_swimStaminaDrainMinSkill = Player.m_localPlayer.m_swimStaminaDrainMinSkill; _m_swimStaminaDrainMaxSkill = Player.m_localPlayer.m_swimStaminaDrainMaxSkill; _m_swimSpeed = __instance.m_swimSpeed; Player localPlayer = Player.m_localPlayer; localPlayer.m_swimStaminaDrainMinSkill *= swimmingStaminaDrainMultiplier.Value; Player localPlayer2 = Player.m_localPlayer; localPlayer2.m_swimStaminaDrainMaxSkill *= swimmingStaminaDrainMultiplier.Value; if (!swimmingRun.Value) { return; } shiftSwimStaminaDepleted = shiftSwimStaminaDepleted || !((Character)Player.m_localPlayer).HaveStamina(0f); if (ZInput.GetButton("Run") || ZInput.GetButton("JoyRun")) { shiftSwimDownTime += dt; if (!shiftSwimStaminaDepleted) { float num = Math.Abs(Mathf.Min(swimmingRunMaximumSpeed.Value - 1f, shiftSwimDownTime / 10f)); __instance.m_swimSpeed *= 1f + num; Player localPlayer3 = Player.m_localPlayer; localPlayer3.m_swimStaminaDrainMinSkill *= 1f + num; Player localPlayer4 = Player.m_localPlayer; localPlayer4.m_swimStaminaDrainMaxSkill *= 1f + num; } } else { shiftSwimDownTime = 0f; shiftSwimStaminaDepleted = false; } } [HarmonyPriority(700)] public static void Postfix(Character __instance) { if (modEnabled.Value && swimmingStamina.Value && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && !__instance.IsOnGround()) { if (((Character)Player.m_localPlayer).m_swimSpeed != _m_swimSpeed && _m_swimSpeed != 0f) { ((Character)Player.m_localPlayer).m_swimSpeed = _m_swimSpeed; } if (Player.m_localPlayer.m_swimStaminaDrainMinSkill != _m_swimStaminaDrainMinSkill && _m_swimStaminaDrainMinSkill != 0f) { Player.m_localPlayer.m_swimStaminaDrainMinSkill = _m_swimStaminaDrainMinSkill; } if (Player.m_localPlayer.m_swimStaminaDrainMaxSkill != _m_swimStaminaDrainMaxSkill && _m_swimStaminaDrainMaxSkill != 0f) { Player.m_localPlayer.m_swimStaminaDrainMaxSkill = _m_swimStaminaDrainMaxSkill; } } } } [HarmonyPatch(typeof(Player), "OnSneaking")] public static class Player_OnSneaking_SneakingStamina { private static float _m_sneakStaminaDrain; public static bool IsEnemyInRange(Character me) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) foreach (BaseAI baseAIInstance in BaseAI.BaseAIInstances) { if (!BaseAI.IsEnemy(me, baseAIInstance.m_character) || !(Vector3.Distance(((Component)me).transform.position, ((Component)baseAIInstance).transform.position) < Math.Max(baseAIInstance.m_viewRange, (baseAIInstance.IsAlerted() ? 1.5f : 1f) * sneakingStaminaNoEnemiesRange.Value))) { continue; } return true; } return false; } [HarmonyPriority(100)] public static void Prefix(Player __instance) { if (modEnabled.Value && sneakingStamina.Value && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { _m_sneakStaminaDrain = __instance.m_sneakStaminaDrain; __instance.m_sneakStaminaDrain *= ((sneakingStaminaNoEnemies.Value && !IsEnemyInRange((Character)(object)__instance)) ? 0f : sneakingStaminaDrainMultiplier.Value); if (__instance.m_sneakStaminaDrain == 0f) { __instance.m_staminaRegenTimer = __instance.m_staminaRegenDelay; } } } [HarmonyPriority(700)] public static void Postfix(Player __instance) { if (modEnabled.Value && swimmingStamina.Value && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && __instance.m_sneakStaminaDrain != _m_sneakStaminaDrain && _m_sneakStaminaDrain != 0f) { __instance.m_sneakStaminaDrain = _m_sneakStaminaDrain; } } } [HarmonyPatch(typeof(Hud), "UpdateStamina")] public class Hud_UpdateStamina_HideStaminaValue { public static void Prefix(Hud __instance) { if (!((Object)(object)__instance.m_staminaText == (Object)null)) { ((Component)__instance.m_staminaText).gameObject.SetActive(modEnabled.Value && !hideStaminaValue.Value); } } } [HarmonyPatch(typeof(FishingFloat), "Awake")] public static class FishingFloat_Awake_FishingStaminaDrainMultipliers { private static void Postfix(FishingFloat __instance) { if (modEnabled.Value) { __instance.m_pullStaminaUse *= pullStaminaUse.Value; __instance.m_hookedStaminaPerSec *= hookedStaminaPerSec.Value; } } } [HarmonyPatch(typeof(SE_Harpooned), "Setup")] public static class SE_Harpooned_Setup_HarpoonedStaminaDrainMultiplier { private static void Postfix(SE_Harpooned __instance) { if (modEnabled.Value) { __instance.m_staminaDrain *= harpoonedStaminaDrain.Value; } } } [HarmonyPatch(typeof(Player), "UpdatePlacement")] public static class Player_UpdatePlacement_ToolsStaminaDrainMultiplier { [HarmonyPriority(100)] public static void Prefix(Player __instance, bool takeInput, ref float __state) { if (modEnabled.Value) { ItemData rightItem = ((Humanoid)__instance).GetRightItem(); if (((Character)__instance).InPlaceMode() && !((Character)__instance).IsDead() && takeInput && rightItem != null) { __state = rightItem.m_shared.m_attack.m_attackStamina; Attack attack = rightItem.m_shared.m_attack; attack.m_attackStamina *= toolStaminaDrain.Value; } } } [HarmonyPriority(700)] private static void Postfix(Player __instance, float __state) { if (modEnabled.Value && __state != 0f && ((Humanoid)__instance).GetRightItem() != null) { ((Humanoid)__instance).GetRightItem().m_shared.m_attack.m_attackStamina = __state; } } } [HarmonyPatch(typeof(Humanoid), "BlockAttack")] public static class Humanoid_BlockAttack_BlockStaminaDrainMultiplier { [HarmonyPriority(100)] public static void Prefix(Humanoid __instance, ref float __state) { if (modEnabled.Value) { __state = __instance.m_blockStaminaDrain; __instance.m_blockStaminaDrain *= blockStaminaDrain.Value; if (blockStaminaSkill.Value) { __instance.m_blockStaminaDrain *= 1f - 0.33f * ((Character)__instance).GetSkillFactor((SkillType)6); } } } [HarmonyPriority(700)] private static void Postfix(Humanoid __instance, float __state) { if (modEnabled.Value && __state != 0f) { __instance.m_blockStaminaDrain = __state; } } } [HarmonyPatch(typeof(Player), "CheckRun")] public static class Player_CheckRun_RunStaminaDrainMultiplier { [HarmonyPriority(100)] public static void Prefix(Player __instance, ref float __state) { if (modEnabled.Value) { __state = __instance.m_runStaminaDrain; __instance.m_runStaminaDrain *= runStaminaDrain.Value; } } [HarmonyPriority(700)] private static void Postfix(Player __instance, float __state) { if (modEnabled.Value && __state != 0f) { __instance.m_runStaminaDrain = __state; } } } [HarmonyPatch(typeof(Player), "UpdateDodge")] public static class Player_UpdateDodge_DodgeStaminaDrainMultiplier { [HarmonyPriority(100)] public static void Prefix(Player __instance, ref float __state) { if (modEnabled.Value) { __state = __instance.m_dodgeStaminaUsage; __instance.m_dodgeStaminaUsage *= dodgeStaminaUsage.Value; if (dodgeStaminaSkill.Value) { __instance.m_dodgeStaminaUsage *= 1f - 0.33f * ((Character)__instance).GetSkillFactor((SkillType)100); } if (groundsEnabled.Value) { __instance.m_dodgeStaminaUsage *= SE_Surface.GetSurfaceMaterialStaminaDrain(SurfaceStaminaSpeed.currentSurface); } } } [HarmonyPriority(700)] private static void Postfix(Player __instance, float __state) { if (modEnabled.Value && __state != 0f) { __instance.m_dodgeStaminaUsage = __state; } } } [HarmonyPatch(typeof(Player), "OnJump")] public static class Player_OnJump_JumpStaminaDrainMultiplier { [HarmonyPriority(100)] public static void Prefix(Player __instance, ref float __state) { if (modEnabled.Value) { __state = ((Character)__instance).m_jumpStaminaUsage; ((Character)__instance).m_jumpStaminaUsage = ((Character)__instance).m_jumpStaminaUsage * jumpStaminaUsage.Value; if (jumpStaminaSkill.Value) { ((Character)__instance).m_jumpStaminaUsage = ((Character)__instance).m_jumpStaminaUsage * (1f - 0.33f * ((Character)__instance).GetSkillFactor((SkillType)100)); } } } [HarmonyPriority(700)] private static void Postfix(Player __instance, float __state) { if (modEnabled.Value && __state != 0f) { ((Character)__instance).m_jumpStaminaUsage = __state; } } } private const string pluginID = "shudnal.StaminaExtended"; private const string pluginName = "Stamina Extended"; private const string pluginVersion = "1.0.5"; private readonly Harmony harmony = new Harmony("shudnal.StaminaExtended"); internal static readonly ConfigSync configSync = new ConfigSync("shudnal.StaminaExtended") { DisplayName = "Stamina Extended", CurrentVersion = "1.0.5", MinimumRequiredVersion = "1.0.5" }; public static ConfigEntry<bool> modEnabled; public static ConfigEntry<bool> configLocked; public static ConfigEntry<bool> loggingEnabled; public static ConfigEntry<bool> linearRegeneration; public static ConfigEntry<float> linearRegenerationMultiplier; public static ConfigEntry<float> linearRegenerationThreshold; public static ConfigEntry<bool> extraStaminaRegeneration; public static ConfigEntry<float> extraStaminaRegenerationPercent; public static ConfigEntry<int> extraStaminaRegenerationPoints; public static ConfigEntry<bool> extraStaminaRegenerationOnlyFood; public static ConfigEntry<bool> encumberedStamina; public static ConfigEntry<float> encumberedStaminaDrainMultiplier; public static ConfigEntry<bool> encumberedStaminaRegeneration; public static ConfigEntry<float> encumberedStaminaRegenerationMultiplier; public static ConfigEntry<bool> swimmingStamina; public static ConfigEntry<float> swimmingStaminaDrainMultiplier; public static ConfigEntry<bool> swimmingStaminaRegeneration; public static ConfigEntry<float> swimmingStaminaRegenerationMultiplier; public static ConfigEntry<float> swimmingStaminaRegenerationDelay; public static ConfigEntry<bool> swimmingRun; public static ConfigEntry<float> swimmingRunMaximumSpeed; public static ConfigEntry<bool> sneakingStamina; public static ConfigEntry<float> sneakingStaminaDrainMultiplier; public static ConfigEntry<float> sneakingStaminaRegenerationMultiplier; public static ConfigEntry<bool> sneakingStaminaNoEnemies; public static ConfigEntry<float> sneakingStaminaNoEnemiesRange; public static ConfigEntry<bool> baseStamina; public static ConfigEntry<float> runBaseStaminaIncrease; public static ConfigEntry<float> swimBaseStaminaIncrease; public static ConfigEntry<float> fishingBaseStaminaIncrease; public static ConfigEntry<float> sneakBaseStaminaIncrease; public static ConfigEntry<float> jumpBaseStaminaIncrease; public static ConfigEntry<float> handsBaseStaminaIncrease; public static ConfigEntry<float> pullStaminaUse; public static ConfigEntry<float> hookedStaminaPerSec; public static ConfigEntry<float> harpoonedStaminaDrain; public static ConfigEntry<float> toolStaminaDrain; public static ConfigEntry<float> blockStaminaDrain; public static ConfigEntry<float> runStaminaDrain; public static ConfigEntry<float> dodgeStaminaUsage; public static ConfigEntry<float> jumpStaminaUsage; public static ConfigEntry<bool> hideStaminaValue; public static ConfigEntry<bool> blockStaminaSkill; public static ConfigEntry<bool> dodgeStaminaSkill; public static ConfigEntry<bool> jumpStaminaSkill; public static ConfigEntry<bool> groundsEnabled; public static ConfigEntry<bool> groundsShowStatusEffect; public static ConfigEntry<string> groundsNameDefault; public static ConfigEntry<float> groundsSpeedSnow; public static ConfigEntry<float> groundsJumpSnow; public static ConfigEntry<float> groundsStaminaDrainSnow; public static ConfigEntry<float> groundsStaminaRegenSnow; public static ConfigEntry<string> groundsNameSnow; public static ConfigEntry<float> groundsSpeedMud; public static ConfigEntry<float> groundsJumpMud; public static ConfigEntry<float> groundsStaminaDrainMud; public static ConfigEntry<float> groundsStaminaRegenMud; public static ConfigEntry<string> groundsNameMud; public static ConfigEntry<float> groundsSpeedGrass; public static ConfigEntry<float> groundsJumpGrass; public static ConfigEntry<float> groundsStaminaDrainGrass; public static ConfigEntry<float> groundsStaminaRegenGrass; public static ConfigEntry<string> groundsNameGrass; public static ConfigEntry<float> groundsSpeedWood; public static ConfigEntry<float> groundsJumpWood; public static ConfigEntry<float> groundsStaminaDrainWood; public static ConfigEntry<float> groundsStaminaRegenWood; public static ConfigEntry<string> groundsNameWood; public static ConfigEntry<float> groundsSpeedHardWood; public static ConfigEntry<float> groundsJumpHardWood; public static ConfigEntry<float> groundsStaminaDrainHardWood; public static ConfigEntry<float> groundsStaminaRegenHardWood; public static ConfigEntry<string> groundsNameHardWood; public static ConfigEntry<float> groundsSpeedStone; public static ConfigEntry<float> groundsJumpStone; public static ConfigEntry<float> groundsStaminaDrainStone; public static ConfigEntry<float> groundsStaminaRegenStone; public static ConfigEntry<string> groundsNameStone; public static ConfigEntry<float> groundsSpeedMarble; public static ConfigEntry<float> groundsJumpMarble; public static ConfigEntry<float> groundsStaminaDrainMarble; public static ConfigEntry<float> groundsStaminaRegenMarble; public static ConfigEntry<string> groundsNameMarble; public static ConfigEntry<float> groundsSpeedMetal; public static ConfigEntry<float> groundsJumpMetal; public static ConfigEntry<float> groundsStaminaDrainMetal; public static ConfigEntry<float> groundsStaminaRegenMetal; public static ConfigEntry<string> groundsNameMetal; public static ConfigEntry<float> groundsSpeedCultivated; public static ConfigEntry<float> groundsJumpCultivated; public static ConfigEntry<float> groundsStaminaDrainCultivated; public static ConfigEntry<float> groundsStaminaRegenCultivated; public static ConfigEntry<string> groundsNameCultivated; public static ConfigEntry<float> groundsSpeedCleared; public static ConfigEntry<float> groundsJumpCleared; public static ConfigEntry<float> groundsStaminaDrainCleared; public static ConfigEntry<float> groundsStaminaRegenCleared; public static ConfigEntry<string> groundsNameCleared; public static ConfigEntry<float> groundsSpeedPaved; public static ConfigEntry<float> groundsJumpPaved; public static ConfigEntry<float> groundsStaminaDrainPaved; public static ConfigEntry<float> groundsStaminaRegenPaved; public static ConfigEntry<string> groundsNamePaved; public static ConfigEntry<float> groundsSpeedAsh; public static ConfigEntry<float> groundsJumpAsh; public static ConfigEntry<float> groundsStaminaDrainAsh; public static ConfigEntry<float> groundsStaminaRegenAsh; public static ConfigEntry<string> groundsNameAsh; public static ConfigEntry<float> groundsSpeedLava; public static ConfigEntry<float> groundsJumpLava; public static ConfigEntry<float> groundsStaminaDrainLava; public static ConfigEntry<float> groundsStaminaRegenLava; public static ConfigEntry<string> groundsNameLava; public static StaminaExtended instance; public const string statusEffectSurfaceName = "Surface"; public static int statusEffectSurfaceHash = StringExtensionMethods.GetStableHashCode("Surface"); private void Awake() { harmony.PatchAll(); instance = this; ConfigInit(); configSync.AddLockingConfigEntry<bool>(configLocked); Game.isModded = true; } private void FixedUpdate() { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { if (groundsEnabled.Value && !((Character)localPlayer).GetSEMan().HaveStatusEffect(statusEffectSurfaceHash)) { ((Character)localPlayer).GetSEMan().AddStatusEffect(statusEffectSurfaceHash, false, 0, 0f); } else if (!groundsEnabled.Value && ((Character)localPlayer).GetSEMan().HaveStatusEffect(statusEffectSurfaceHash)) { ((Character)localPlayer).GetSEMan().RemoveStatusEffect(statusEffectSurfaceHash, true); } } } private void OnDestroy() { Harmony obj = harmony; if (obj != null) { obj.UnpatchSelf(); } instance = null; } private void ConfigInit() { config("1 - General", "NexusID", 2719, "Nexus mod ID for updates", synchronizedSetting: false); modEnabled = config("1 - General", "Enabled", defaultValue: true, "Mod alters stamina behavior"); configLocked = config("1 - General", "Lock Configuration", defaultValue: true, "Configuration is locked and can be changed by server admins only."); loggingEnabled = config("1 - General", "Logging enabled", defaultValue: false, "Enable logging. [Not Synced with Server]", synchronizedSetting: false); linearRegeneration = config("2 - Linear regeneration change", "Enabled", defaultValue: true, "Enable linear change of stamina regeneration rate. Overall time to regenerate stamina to 100% is still almost the same."); linearRegenerationMultiplier = config("2 - Linear regeneration change", "Multiplier", 3f, "Multiplier of regeneration rate when stamina is 0.\nIf value is above 1. Stamina will regenerate faster at lower values and proportionally slower at higher values.\nIf value is below 1. Stamina will regenerate slower at lower values and proportionally higher at higher values."); linearRegenerationThreshold = config("2 - Linear regeneration change", "Regeneration threshold", 0.5f, "Inflection point of stamina regeneration rate. Stamina regeneration rate is normal only in that point.\nIn that point regeneration rate changes its sign.\nIf set value is outside of 0-1 range stamina will regenerate normally"); extraStaminaRegeneration = config("3 - Extra stamina regeneration", "Enabled", defaultValue: true, "Enable increased stamina regeneration by X% per every Y point of additional stamina"); extraStaminaRegenerationPercent = config("3 - Extra stamina regeneration", "Percent", 1f, "Stamina regeneration increased by X%"); extraStaminaRegenerationPoints = config("3 - Extra stamina regeneration", "Points", 10, "Stamina regeneration increased per every Y points of additional stamina"); extraStaminaRegenerationOnlyFood = config("3 - Extra stamina regeneration", "Stamina from food only", defaultValue: true, "Only stamina gain from food is counted for increased regeneration"); encumberedStamina = config("4 - Encumbered stamina", "Enabled", defaultValue: true, "Enable encumbered stamina control"); encumberedStaminaDrainMultiplier = config("4 - Encumbered stamina", "Stamina drain multiplier", 2f, "Encumbered stamina drain multiplier. Set 0 to disable stamina usage while encumbered"); encumberedStaminaRegeneration = config("4 - Encumbered stamina", "Stamina regeneration while encumbered", defaultValue: true, "Stamina will regenerate while encumbered"); encumberedStaminaRegenerationMultiplier = config("4 - Encumbered stamina", "Stamina regeneration multiplier", 0.2f, "Stamina regeneration multiplier of normal stamina regeneration rate"); swimmingStamina = config("5 - Swimming stamina", "Enabled", defaultValue: true, "Enable swimming stamina control"); swimmingStaminaDrainMultiplier = config("5 - Swimming stamina", "Stamina drain multiplier", 1f, "Swimming stamina drain multiplier. Set 0 to disable stamina usage while swimming"); swimmingStaminaRegeneration = config("5 - Swimming stamina", "Stamina regeneration while swimming", defaultValue: true, "Stamina will regenerate while encumbered"); swimmingStaminaRegenerationMultiplier = config("5 - Swimming stamina", "Stamina regeneration multiplier", 0.2f, "Stamina regeneration multiplier of normal stamina regeneration rate"); swimmingStaminaRegenerationDelay = config("5 - Swimming stamina", "Stamina regeneration delay", 2f, "Additional delay in seconds before stamina begins to regenerate while not moving"); swimmingRun = config("5 - Swimming stamina", "Swimming acceleration", defaultValue: true, "Press Run hotkey to swim faster depleting proportionally more stamina. Swimming speed will gradually increase until maximum speed is reached."); swimmingRunMaximumSpeed = config("5 - Swimming stamina", "Swimming acceleration maximum speed", 2f, "Maximum speed of swimming acceleration in proportion to normal swim speed."); sneakingStamina = config("6 - Sneaking stamina", "Enabled", defaultValue: true, "Enable sneaking stamina regeneration control"); sneakingStaminaDrainMultiplier = config("6 - Sneaking stamina", "Stamina drain multiplier", 1f, "Sneaking stamina drain multiplier"); sneakingStaminaRegenerationMultiplier = config("6 - Sneaking stamina", "Stamina regeneration while sneaking", 0.5f, "Set additional stamina regen rate. Stamina will regenerate faster while sneaking depending on the Sneak skill\n0.5 with 40 sneak skill means stamina will regenerate 20% faster while sneaking and not moving"); sneakingStaminaNoEnemies = config("6 - Sneaking stamina", "Stamina is not spent if no enemy in range", defaultValue: true, "Stamina regeneration multiplier of normal stamina regeneration rate"); sneakingStaminaNoEnemiesRange = config("6 - Sneaking stamina", "Stamina is not spent range", 20f, "Distance to nearby enemy to activate stamina usage while sneaking"); baseStamina = config("7 - Base stamina", "Enabled", defaultValue: true, "Base stamina will be increased proportionally to skills where set value reached at skill level 100."); runBaseStaminaIncrease = config("7 - Base stamina", "Run", 20f, "Base stamina will be increased by set value when Run skill is level 100"); swimBaseStaminaIncrease = config("7 - Base stamina", "Swim", 20f, "Base stamina will be increased by set value when Swim skill is level 100"); fishingBaseStaminaIncrease = config("7 - Base stamina", "Fishing", 20f, "Base stamina will be increased by set value when Fishing skill is level 100"); sneakBaseStaminaIncrease = config("7 - Base stamina", "Sneak", 20f, "Base stamina will be increased by set value when Sneak skill is level 100"); jumpBaseStaminaIncrease = config("7 - Base stamina", "Jump", 20f, "Base stamina will be increased by set value when Jump skill is level 100"); handsBaseStaminaIncrease = config("7 - Base stamina", "Unarmed", 0f, "Base stamina will be increased by set value when Unarmed skill is level 100"); pullStaminaUse = config("8 - Various multipliers", "Fishing pull stamina", 1f, "Stamina required to reel"); hookedStaminaPerSec = config("8 - Various multipliers", "Fishing hooked stamina", 1f, "Stamina required to keep a fish on the line"); harpoonedStaminaDrain = config("8 - Various multipliers", "Harpooned pull stamina", 1f, "Stamina required to pull harpooned target"); toolStaminaDrain = config("8 - Various multipliers", "Tools stamina drain", 1f, "Stamina required to use tools such as hammer, hoe, cultivator"); blockStaminaDrain = config("8 - Various multipliers", "Block stamina drain", 1f, "Stamina required to block"); runStaminaDrain = config("8 - Various multipliers", "Run stamina drain", 1f, "Stamina required to run"); dodgeStaminaUsage = config("8 - Various multipliers", "Dodge stamina usage", 1f, "Stamina required to dodge"); jumpStaminaUsage = config("8 - Various multipliers", "Jump stamina usage", 1f, "Stamina required to jump"); hideStaminaValue = config("9 - Misc", "Hide stamina text", defaultValue: false, "Hide stamina text value on stamina bar"); blockStaminaSkill = config("9 - Misc", "Block stamina usage depends on skill", defaultValue: true, "Amount of stamina needed to block is reduced by 33% when Block skill is 100"); dodgeStaminaSkill = config("9 - Misc", "Dodge stamina usage depends on Jump skill", defaultValue: true, "Amount of stamina needed to block is reduced by 33% when Jump skill is 100"); jumpStaminaSkill = config("9 - Misc", "Jump stamina usage depends on Jump skill", defaultValue: true, "Amount of stamina needed to block is reduced by 33% when Jump skill is 100"); groundsEnabled = config("Grounds", "Enabled", defaultValue: true, "Enable change of movement speed, run, jump and dodge stamina consumption on different surfaces"); groundsShowStatusEffect = config("Grounds", "Show status effect", defaultValue: false, "Show status effect of current surface. Status effect will still be shown in Raven menu if disabled."); groundsNameDefault = config("Grounds", "Status name by default", "Default", "Localized default name for status effect"); groundsEnabled.SettingChanged += delegate { SE_Surface.UpdateSurfaceStatusEffectStats(); }; groundsShowStatusEffect.SettingChanged += delegate { SE_Surface.UpdateSurfaceStatusEffectStats(); }; groundsSpeedSnow = config("Grounds - Snow", "Speed multiplier", 1f, "Movement speed multiplier"); groundsJumpSnow = config("Grounds - Snow", "Jump multiplier", 1f, "Jump height multiplier"); groundsStaminaDrainSnow = config("Grounds - Snow", "Stamina drain multiplier", 1f, "Stamina drain multiplier"); groundsStaminaRegenSnow = config("Grounds - Snow", "Stamina regen multiplier", 1f, "Stamina regen multiplier"); groundsNameSnow = config("Grounds - Snow", "Status effect name", "Snow", "Localized name for status effect"); groundsSpeedMud = config("Grounds - Mud", "Speed multiplier", 1f, "Movement speed multiplier (swamps ground)"); groundsJumpMud = config("Grounds - Mud", "Jump multiplier", 1f, "Jump height multiplier (swamps ground)"); groundsStaminaDrainMud = config("Grounds - Mud", "Stamina drain multiplier", 1f, "Stamina drain multiplier (swamps ground)"); groundsStaminaRegenMud = config("Grounds - Mud", "Stamina regen multiplier", 1f, "Stamina regen multiplier (swamps ground)"); groundsNameMud = config("Grounds - Mud", "Status effect name", "Mud", "Localized name for status effect (swamps ground)"); groundsSpeedGrass = config("Grounds - Grass", "Speed multiplier", 1f, "Movement speed multiplier (meadows and black forest)"); groundsJumpGrass = config("Grounds - Grass", "Jump multiplier", 1f, "Jump height multiplier"); groundsStaminaDrainGrass = config("Grounds - Grass", "Stamina drain multiplier", 1f, "Stamina drain multiplier (meadows and black forest)"); groundsStaminaRegenGrass = config("Grounds - Grass", "Stamina regen multiplier", 1f, "Stamina regen multiplier"); groundsNameGrass = config("Grounds - Grass", "Status effect name", "Grass", "Localized name for status effect (meadows and black forest)"); groundsSpeedWood = config("Grounds - Wood", "Speed multiplier", 1.15f, "Movement speed multiplier"); groundsJumpWood = config("Grounds - Wood", "Jump multiplier", 1.05f, "Jump height multiplier"); groundsStaminaDrainWood = config("Grounds - Wood", "Stamina drain multiplier", 0.85f, "Stamina drain multiplier"); groundsStaminaRegenWood = config("Grounds - Wood", "Stamina regen multiplier", 1f, "Stamina regen multiplier"); groundsNameWood = config("Grounds - Wood", "Status effect name", "Wood", "Localized name for status effect"); groundsSpeedHardWood = config("Grounds - HardWood", "Speed multiplier", 1.2f, "Movement speed multiplier"); groundsJumpHardWood = config("Grounds - HardWood", "Jump multiplier", 1.05f, "Jump height multiplier"); groundsStaminaDrainHardWood = config("Grounds - HardWood", "Stamina drain multiplier", 0.85f, "Stamina drain multiplier"); groundsStaminaRegenHardWood = config("Grounds - HardWood", "Stamina regen multiplier", 1f, "Stamina regen multiplier"); groundsNameHardWood = config("Grounds - HardWood", "Status effect name", "Hardwood", "Localized name for status effect"); groundsSpeedStone = config("Grounds - Stone", "Speed multiplier", 1.25f, "Movement speed multiplier"); groundsJumpStone = config("Grounds - Stone", "Jump multiplier", 1.1f, "Jump height multiplier"); groundsStaminaDrainStone = config("Grounds - Stone", "Stamina drain multiplier", 0.8f, "Stamina drain multiplier"); groundsStaminaRegenStone = config("Grounds - Stone", "Stamina regen multiplier", 1f, "Stamina regen multiplier"); groundsNameStone = config("Grounds - Stone", "Status effect name", "Stone", "Localized name for status effect"); groundsSpeedMarble = config("Grounds - Marble", "Speed multiplier", 1.3f, "Movement speed multiplier (dverger marble, ashstone and ancient)"); groundsJumpMarble = config("Grounds - Marble", "Jump multiplier", 1.1f, "Jump height multiplier (dverger marble, ashstone and ancient)"); groundsStaminaDrainMarble = config("Grounds - Marble", "Stamina drain multiplier", 0.75f, "Stamina drain multiplier (dverger marble, ashstone and ancient)"); groundsStaminaRegenMarble = config("Grounds - Marble", "Stamina regen multiplier", 1f, "Stamina regen multiplier (dverger marble, ashstone and ancient)"); groundsNameMarble = config("Grounds - Marble", "Status effect name", "Marble", "Localized name for status effect (dverger marble, ashstone and ancient)"); groundsSpeedMetal = config("Grounds - Metal", "Speed multiplier", 1.25f, "Movement speed multiplier"); groundsJumpMetal = config("Grounds - Metal", "Jump multiplier", 1.05f, "Jump height multiplier"); groundsStaminaDrainMetal = config("Grounds - Metal", "Stamina drain multiplier", 0.8f, "Stamina drain multiplier"); groundsStaminaRegenMetal = config("Grounds - Metal", "Stamina regen multiplier", 1f, "Stamina regen multiplier"); groundsNameMetal = config("Grounds - Metal", "Status effect name", "Metal", "Localized name for status effect"); groundsSpeedCultivated = config("Grounds - Cultivated", "Speed multiplier", 0.9f, "Movement speed multiplier"); groundsJumpCultivated = config("Grounds - Cultivated", "Jump multiplier", 0.9f, "Jump height multiplier"); groundsStaminaDrainCultivated = config("Grounds - Cultivated", "Stamina drain multiplier", 1.1f, "Stamina drain multiplier"); groundsStaminaRegenCultivated = config("Grounds - Cultivated", "Stamina regen multiplier", 1.1f, "Stamina regen multiplier"); groundsNameCultivated = config("Grounds - Cultivated", "Status effect name", "Cultivated", "Localized name for status effect"); groundsSpeedCleared = config("Grounds - Cleared", "Speed multiplier", 1.1f, "Movement speed multiplier"); groundsJumpCleared = config("Grounds - Cleared", "Jump multiplier", 1f, "Jump height multiplier"); groundsStaminaDrainCleared = config("Grounds - Cleared", "Stamina drain multiplier", 0.9f, "Stamina drain multiplier"); groundsStaminaRegenCleared = config("Grounds - Cleared", "Stamina regen multiplier", 1f, "Stamina regen multiplier"); groundsNameCleared = config("Grounds - Cleared", "Status effect name", "Cleared", "Localized name for status effect"); groundsSpeedPaved = config("Grounds - Paved", "Speed multiplier", 1.2f, "Movement speed multiplier"); groundsJumpPaved = config("Grounds - Paved", "Jump multiplier", 1.05f, "Jump height multiplier"); groundsStaminaDrainPaved = config("Grounds - Paved", "Stamina drain multiplier", 0.85f, "Stamina drain multiplier"); groundsStaminaRegenPaved = config("Grounds - Paved", "Stamina regen multiplier", 1f, "Stamina regen multiplier"); groundsNamePaved = config("Grounds - Paved", "Status effect name", "Paved", "Localized name for status effect"); groundsSpeedAsh = config("Grounds - Ash", "Speed multiplier", 1f, "Movement speed multiplier (Ashlands ground)"); groundsJumpAsh = config("Grounds - Ash", "Jump multiplier", 1f, "Jump height multiplier (Ashlands ground)"); groundsStaminaDrainAsh = config("Grounds - Ash", "Stamina drain multiplier", 1f, "Stamina drain multiplier (Ashlands ground)"); groundsStaminaRegenAsh = config("Grounds - Ash", "Stamina regen multiplier", 1f, "Stamina regen multiplier (Ashlands ground)"); groundsNameAsh = config("Grounds - Ash", "Status effect name", "Ash", "Localized name for status effect (Ashlands ground)"); groundsSpeedLava = config("Grounds - Lava", "Speed multiplier", 1f, "Movement speed multiplier (lava in Ashlands)"); groundsJumpLava = config("Grounds - Lava", "Jump multiplier", 1f, "Jump height multiplier (lava in Ashlands)"); groundsStaminaDrainLava = config("Grounds - Lava", "Stamina drain multiplier", 1f, "Stamina drain multiplier (lava in Ashlands)"); groundsStaminaRegenLava = config("Grounds - Lava", "Stamina regen multiplier", 1f, "Stamina regen multiplier (lava in Ashlands)"); groundsNameLava = config("Grounds - Lava", "Status effect name", "Lava", "Localized name for status effect (lava in Ashlands)"); } private ConfigEntry<T> config<T>(string group, string name, T defaultValue, ConfigDescription description, bool synchronizedSetting = true) { ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, defaultValue, description); SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry<T>(val); syncedConfigEntry.SynchronizedConfig = synchronizedSetting; return val; } private ConfigEntry<T> config<T>(string group, string name, T defaultValue, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } public static void LogInfo(object message) { if (loggingEnabled.Value) { ((BaseUnityPlugin)instance).Logger.LogInfo(message); } } public static void LogWarning(object data) { if (loggingEnabled.Value) { ((BaseUnityPlugin)instance).Logger.LogWarning(data); } } public string GetStringConfig(string fieldName) { return (((object)this).GetType().GetField(fieldName).GetValue(this) as ConfigEntry<string>).Value; } public float GetFloatConfig(string fieldName) { return (((object)this).GetType().GetField(fieldName).GetValue(this) as ConfigEntry<float>).Value; } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.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 ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry<T> : OwnConfigEntryBase { public readonly ConfigEntry<T> SourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public SyncedConfigEntry(ConfigEntry<T> sourceConfig) { SourceConfig = sourceConfig; } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } internal abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] internal class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List<ZNetPeer> peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket : ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (__instance.IsServer()) { BufferingSocket value = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value); } if (__state == null) { __state = new Dictionary<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = value; } } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc) { ZRpc rpc2 = rpc; ZNet __instance2 = __instance; Dictionary<Assembly, BufferingSocket> __state2 = __state; ZNetPeer peer; if (__instance2.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance2).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc2.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc2.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag.GetValueOrDefault(); } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0053: return (byte)result != 0; IL_0052: result = 0; goto IL_0053; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { ConfigEntry<T> configEntry2 = configEntry; OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry2); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry2.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { CustomSyncedValueBase customValue2 = customValue; if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue2); allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue2.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue2); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2u) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4u) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; } foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int i = 0; i < num; i++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { OwnConfigEntryBase config2 = config; ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZNetPeer peer2 = peer; ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer2.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer2.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg }); } } IEnumerable<bool> waitForQueue() { float timeout = Time.time + 30f; while (peer2.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout"); peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer2); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package) { ZPackage package2 = package; if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package2.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package2 = compressedPackage; } List<IEnumerator<bool>> writers = (from peer in peers where peer.IsReady() select peer into p select distributeConfigToPeers(p, package2)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault(); } public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config) { return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault(); } private static T configAttribute<T>(ConfigEntryBase config) { return config.Description.Tags.OfType<T>().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>(); List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); {