Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of LoadoutBuffs v1.5.1
LoadoutBuffs.dll
Decompiled a month ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.ObjectPool; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.RepresentationModel; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Callbacks; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("LoadoutBuffs")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.5.1.0")] [assembly: AssemblyInformationalVersion("1.5.1+dc7ed39dfbb3cadb54df69e8562d9023f9d7d2f0")] [assembly: AssemblyProduct("LoadoutBuffs")] [assembly: AssemblyTitle("LoadoutBuffs")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LoadoutBuffs { internal static class AllyAssist { private static readonly List<Character> s_nearby = new List<Character>(); private static readonly int s_shieldHash = StringExtensionMethods.GetStableHashCode("Staff_shield"); private static Character s_bubbleSource; private static ShieldRequest s_bubble; private static bool s_bubbleErrorLogged; private static bool s_noShieldWarned; private static bool s_noSkillFactorWarned; public static void Self(Character character, ParryAssist assist) { if (assist.Heal > 0f) { character.Heal(assist.Heal, true); } if (assist.Stamina > 0f) { character.AddStamina(assist.Stamina); } } public static void Others(Character source, ParryAssist assist) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)source == (Object)null || !assist.ReachesOthers || !source.IsPlayer()) { return; } Vector3 position = ((Component)source).transform.position; float num = ((assist.HealAllies > 0f || assist.StaminaAllies > 0f) ? assist.Radius : 0f); float num2 = ((assist.HealTamed > 0f) ? assist.TamedRadius : 0f); s_nearby.Clear(); Character.GetCharactersInRange(position, Mathf.Max(num, num2), s_nearby); foreach (Character item in s_nearby) { if ((Object)(object)item == (Object)null || (Object)(object)item == (Object)(object)source || item.IsDead()) { continue; } Vector3 val = ((Component)item).transform.position - position; float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude; if (item.IsPlayer()) { if (!(sqrMagnitude >= num * num)) { if (assist.HealAllies > 0f) { item.Heal(assist.HealAllies, true); } if (assist.StaminaAllies > 0f) { item.UseStamina(0f - assist.StaminaAllies); } } } else if (item.IsTamed() && assist.HealTamed > 0f && sqrMagnitude < num2 * num2) { item.Heal(assist.HealTamed, true); } } } public static void RequestBubble(Character source, ParryAssist assist) { if (!((Object)(object)source == (Object)null) && assist != null && !(assist.Shield <= 0f) && source.IsPlayer()) { ShieldRequest shieldRequest = new ShieldRequest(assist.Shield, assist.Radius, assist.TamedRadius, assist.ShieldMinutes); s_bubble = ((s_bubbleSource == source) ? ShieldRequest.Merge(s_bubble, shieldRequest) : shieldRequest); s_bubbleSource = source; } } public static void FlushBubble() { //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) if (s_bubbleSource == null) { return; } Character val = s_bubbleSource; ShieldRequest shieldRequest = s_bubble; s_bubbleSource = null; s_bubble = null; try { if ((Object)(object)val == (Object)null || shieldRequest == null || val.IsDead()) { return; } ObjectDB instance = ObjectDB.instance; SE_Shield val2 = (SE_Shield)(((Object)(object)instance == (Object)null) ? null : /*isinst with value type is only supported in some contexts*/); if ((Object)(object)val2 == (Object)null) { WarnOnce(ref s_noShieldWarned, "No bubble sent: the game has no Staff_shield effect."); return; } if (!ShieldMath.TrySkillFor(shieldRequest.Amount, val2.m_absorbDamage, val2.m_absorbDamagePerSkillLevel, val2.m_absorbDamageWorldLevel, Game.m_worldLevel, out var skill)) { WarnOnce(ref s_noSkillFactorWarned, "Staff_shield has no per-skill strength (another mod?): bubbles get the game's base strength."); } int itemLevel = ShieldMath.ItemLevelFor(shieldRequest.Minutes); Give(val, itemLevel, skill); Vector3 position = ((Component)val).transform.position; s_nearby.Clear(); Character.GetCharactersInRange(position, Mathf.Max(shieldRequest.PlayerReach, shieldRequest.TamedReach), s_nearby); foreach (Character item in s_nearby) { if ((Object)(object)item == (Object)null || (Object)(object)item == (Object)(object)val || item.IsDead()) { continue; } Vector3 val3 = ((Component)item).transform.position - position; float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude; bool num; if (!item.IsPlayer()) { if (!item.IsTamed()) { continue; } num = sqrMagnitude < shieldRequest.TamedReach * shieldRequest.TamedReach; } else { num = sqrMagnitude < shieldRequest.PlayerReach * shieldRequest.PlayerReach; } if (num) { Give(item, itemLevel, skill); } } } catch (Exception arg) { if (!s_bubbleErrorLogged) { s_bubbleErrorLogged = true; Plugin.Log.LogError((object)$"Parry bubble failed (logged once): {arg}"); } } } private static void Give(Character character, int itemLevel, float skill) { SEMan sEMan = character.GetSEMan(); if (sEMan != null) { sEMan.AddStatusEffect(s_shieldHash, false, itemLevel, skill, (short)(-1)); } } private static void WarnOnce(ref bool warned, string message) { if (!warned) { warned = true; Plugin.Log.LogWarning((object)message); } } } internal static class BundleEffects { private sealed class Impact { public Projectile Shot; public GameObject Direct; } private struct HitFacts { public bool RapidFire; public bool ShotSpawnsOwn; public bool ShotSparesFriends; public bool ShotExplodes; public bool Summons; public bool OwnBleeding; public bool OwnChain; public bool OwnRoot; } public static bool HookInstalled; public static bool ParryHookInstalled; public static bool BlockHookInstalled; public static bool DamageHookInstalled; public static bool EitrHookInstalled; public static bool HitHookInstalled; public static bool RootHookInstalled; public static bool BuildingHookInstalled; public static bool ClassHookInstalled; public static bool TooltipHookInstalled; private static readonly Dictionary<BundleSlot, StatusEffect> s_effects = new Dictionary<BundleSlot, StatusEffect>(); private static readonly Dictionary<BundleSlot, StatBlock> s_stats = new Dictionary<BundleSlot, StatBlock>(); private static string s_statsName; private static bool s_showHudBuff; private static ParryAssist s_parry; private static bool s_parryErrorLogged; private static bool s_woodcutter; private static bool s_miner; private static bool s_classErrorLogged; private static float s_blockArmor; private static float s_blockForce; private static bool s_blockErrorLogged; private static readonly Dictionary<string, float> s_addDamage = new Dictionary<string, float>(StringComparer.Ordinal); private static bool s_damageErrorLogged; private static float s_eitrCost; private static bool s_eitrErrorLogged; private static float s_parryBonus; private static bool s_tooltipErrorLogged; private static bool s_bleeding; private static bool s_thundering; private static bool s_primal; private static bool s_attackErrorLogged; private static bool s_onHitErrorLogged; private static bool s_chainMissingLogged; private static bool s_rootMissingLogged; private static GameObject s_chainLightning; private static int s_rootHash; private static ObjectDB s_rootHashDb; private static bool s_rootHookErrorLogged; private static bool s_spareBuildings; private static bool s_buildingErrorLogged; private static Impact s_impact; private const string ChainLightningPrefab = "ChainLightning"; private const string RootEffect = "ImmobilizedAshlands"; public const short ClassToolTier = 1000; private static bool s_hookErrorLogged; private static readonly FieldInfo s_nview = AccessTools.Field(typeof(Character), "m_nview"); private static readonly FieldInfo s_helmet = AccessTools.Field(typeof(Humanoid), "m_helmetItem"); private static readonly FieldInfo s_chest = AccessTools.Field(typeof(Humanoid), "m_chestItem"); private static readonly FieldInfo s_legs = AccessTools.Field(typeof(Humanoid), "m_legItem"); private static readonly FieldInfo s_cape = AccessTools.Field(typeof(Humanoid), "m_shoulderItem"); private static readonly FieldInfo s_right = AccessTools.Field(typeof(Humanoid), "m_rightItem"); private static readonly FieldInfo s_left = AccessTools.Field(typeof(Humanoid), "m_leftItem"); private static readonly FieldInfo s_currentAttack = AccessTools.Field(typeof(Humanoid), "m_currentAttack"); private static readonly FieldInfo s_projectileOwner = AccessTools.Field(typeof(Projectile), "m_owner"); private static readonly FieldInfo s_projectileEffect = AccessTools.Field(typeof(Projectile), "m_statusEffectHash"); private static readonly FieldInfo s_projectileHitData = AccessTools.Field(typeof(Projectile), "m_originalHitData"); private static readonly Dictionary<SharedData, HitFacts> s_hitFacts = new Dictionary<SharedData, HitFacts>(); private static readonly Dictionary<SharedData, bool> s_usedOnAllies = new Dictionary<SharedData, bool>(); public static BundleFile File { get; private set; } = new BundleFile(); public static BundleState State { get; private set; } = new BundleState(); public static GameEffectCatalog Catalog { get; private set; } public static bool RootFieldsFound { get { if (s_projectileOwner != null && s_projectileEffect != null) { return s_projectileHitData != null; } return false; } } public static bool AttackFieldFound => s_currentAttack != null; public static BundleState Apply(ObjectDB db) { File = BundleFile.Parse(Read(out var error)); if (error != null) { File.Warnings.Insert(0, error); } Dictionary<string, StatusEffect> dictionary = GameGlue.CollectStatusEffects(db); Catalog = new GameEffectCatalog(db, dictionary); if (File.OnlyMisplaced) { RemoveMisplaced(); } State = BundleRules.Evaluate(File, Catalog); if (State.Enabled && !HookInstalled) { State.Enabled = false; State.OffReason = "this game version isn't supported by the buff hook (see LogOutput.log)."; } s_effects.Clear(); s_stats.Clear(); s_parry = null; s_woodcutter = (s_miner = false); s_bleeding = (s_thundering = (s_primal = false)); s_blockArmor = (s_blockForce = (s_eitrCost = (s_parryBonus = 0f))); s_addDamage.Clear(); s_statsName = State.Active?.Name; s_spareBuildings = State.Enabled && State.Active != null && State.Active.SpareBuildings && BuildingHookInstalled; s_showHudBuff = BundleRules.ShowsHudBuff(State); if (State.Enabled) { State.AddHookWarnings(BundleRules.MissingHookWarnings(State.Stats.Values, ParryHookInstalled, BlockHookInstalled, DamageHookInstalled, EitrHookInstalled, HitHookInstalled, State.Active?.SpareBuildings ?? false, BuildingHookInstalled, ClassHookInstalled, TooltipHookInstalled)); } if (State.Enabled) { foreach (KeyValuePair<BundleSlot, string> effect in State.Effects) { if (dictionary.TryGetValue(effect.Value, out var value) && (Object)(object)value != (Object)null) { s_effects[effect.Key] = value; } } foreach (KeyValuePair<BundleSlot, StatBlock> stat in State.Stats) { s_stats[stat.Key] = stat.Value; } } return State; } private static void RemoveMisplaced() { try { string text = File.Serialize((string code) => Catalog?.DisplayName(code)); System.IO.File.WriteAllText(Plugin.BundlesPath, text); foreach (string item in File.Misplaced) { Plugin.Log.LogInfo((object)("LoadoutBuffs.buffs.yaml: removed " + item + ".")); } File = BundleFile.Parse(text); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not remove the stats on the wrong slots from LoadoutBuffs.buffs.yaml: " + ex.Message)); } } public static BundleState ReloadFile() { ObjectDB instance = ObjectDB.instance; if (!GameGlue.IsReady(instance)) { return State; } Apply(instance); foreach (string warning in State.Warnings) { Plugin.Log.LogWarning((object)warning); } Plugin.Log.LogInfo((object)State.StatusLine()); Refresh(); return State; } public static BundleState Save(BundleFile file) { string contents = file.Serialize((string code) => Catalog?.DisplayName(code)); System.IO.File.WriteAllText(Plugin.BundlesPath, contents); return ReloadFile(); } public static void Refresh() { GameGlue.RefreshEquipmentEffects(Player.m_localPlayer); } public static void AddTo(Humanoid humanoid, HashSet<StatusEffect> set) { try { if ((!s_showHudBuff && s_effects.Count == 0 && s_stats.Count == 0) || set == null || !(humanoid is Player)) { return; } object? obj = s_nview?.GetValue(humanoid); ZNetView val = (ZNetView)((obj is ZNetView) ? obj : null); if ((Object)(object)val == (Object)null || !val.IsValid() || !val.IsOwner()) { return; } foreach (KeyValuePair<BundleSlot, StatusEffect> s_effect in s_effects) { if ((Object)(object)s_effect.Value != (Object)null && Worn(humanoid, s_effect.Key) != null) { set.Add(s_effect.Value); } } StatBlock statBlock = StatBlock.Sum(from p in s_stats where Worn(humanoid, p.Key) != null select p.Value); s_parry = statBlock.ToParryAssist(); s_woodcutter = statBlock.Scalars.ContainsKey("woodcutter"); s_miner = statBlock.Scalars.ContainsKey("miner"); s_bleeding = statBlock.Scalars.ContainsKey("bleeding"); s_thundering = statBlock.Scalars.ContainsKey("thundering"); s_primal = statBlock.Scalars.ContainsKey("primal"); s_blockArmor = statBlock.BlockArmor; s_blockForce = statBlock.BlockForce; s_eitrCost = statBlock.EitrCost; s_parryBonus = statBlock.ParryBonus; s_addDamage.Clear(); foreach (KeyValuePair<string, float> item in statBlock.AddDamage) { s_addDamage[item.Key] = item.Value; } if (s_showHudBuff) { string effectNames = string.Join(", ", from p in s_effects where (Object)(object)p.Value != (Object)null && Worn(humanoid, p.Key) != null orderby p.Key select EffectText.DisplayName(p.Value.m_name)); BundleStatsEffect template = BundleStatsEffect.Template; template.SetTotals(statBlock, s_statsName ?? "Buff", effectNames, s_spareBuildings); if (((Character)humanoid).GetSEMan().GetStatusEffect(((StatusEffect)template).NameHash()) is BundleStatsEffect bundleStatsEffect && (Object)(object)bundleStatsEffect != (Object)(object)template) { bundleStatsEffect.SetTotals(statBlock, s_statsName ?? "Buff", effectNames, s_spareBuildings); } set.Add((StatusEffect)(object)template); } } catch (Exception arg) { if (!s_hookErrorLogged) { s_hookErrorLogged = true; Plugin.Log.LogError((object)$"Buff effects failed (logged once): {arg}"); } } } public static void OnParry(Humanoid humanoid) { try { ParryAssist parryAssist = s_parry; if (parryAssist != null && humanoid is Player) { object? obj = s_nview?.GetValue(humanoid); ZNetView val = (ZNetView)((obj is ZNetView) ? obj : null); if (!((Object)(object)val == (Object)null) && val.IsValid() && val.IsOwner()) { AllyAssist.Self((Character)(object)humanoid, parryAssist); AllyAssist.Others((Character)(object)humanoid, parryAssist); AllyAssist.RequestBubble((Character)(object)humanoid, parryAssist); } } } catch (Exception arg) { if (!s_parryErrorLogged) { s_parryErrorLogged = true; Plugin.Log.LogError((object)$"Buff on-parry stats failed (logged once): {arg}"); } } } public static void OnDestructibleHit(object target, HitData hit) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 try { if ((!s_woodcutter && !s_miner) || hit == null) { return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)hit.GetAttacker() != (Object)(object)localPlayer) { return; } BundleSlot? bundleSlot = HandSlotOf(((Humanoid)localPlayer).GetCurrentWeapon()); if (bundleSlot == BundleSlot.Melee || bundleSlot == BundleSlot.Ranged) { int num; if (!(target is TreeBase) && !(target is TreeLog)) { Destructible val = (Destructible)((target is Destructible) ? target : null); num = ((val != null && (int)val.m_destructibleType == 2) ? 1 : 0); } else { num = 1; } bool tree = (byte)num != 0; if (BundleStatCatalog.WithClass(ref hit.m_damage, tree, s_woodcutter, s_miner) && hit.m_toolTier < 1000) { hit.m_toolTier = 1000; } } } catch (Exception arg) { if (!s_classErrorLogged) { s_classErrorLogged = true; Plugin.Log.LogError((object)$"Buff classes failed (logged once): {arg}"); } } } public static bool OnBuildingHit(WearNTear target, HitData hit) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) try { if (!s_spareBuildings || hit == null || (Object)(object)target == (Object)null) { return false; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return false; } ZDOID zDOID = ((Character)localPlayer).GetZDOID(); if (((ZDOID)(ref zDOID)).IsNone() || hit.m_attacker != zDOID) { return false; } Piece component = ((Component)target).GetComponent<Piece>(); return BundleRules.SparesBuilding(on: true, attackerIsYou: true, ((Object)(object)component != (Object)null) ? component.GetCreator() : 0); } catch (Exception arg) { if (!s_buildingErrorLogged) { s_buildingErrorLogged = true; Plugin.Log.LogError((object)$"Buff Spare buildings failed (logged once): {arg}"); } return false; } } public static void OnAttackStart(Humanoid humanoid) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Invalid comparison between Unknown and I4 //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Invalid comparison between Unknown and I4 try { if (!s_thundering || (Object)(object)humanoid == (Object)null || (object)humanoid != Player.m_localPlayer) { return; } ItemData currentWeapon = humanoid.GetCurrentWeapon(); if (!FillsWeaponSlot(currentWeapon)) { return; } object? obj = s_currentAttack?.GetValue(humanoid); Attack val = (Attack)((obj is Attack) ? obj : null); if (val == null) { return; } bool rapidFire = Facts(currentWeapon.m_shared).RapidFire; if ((Object)(object)val.m_spawnOnHit != (Object)null && val.m_spawnOnHitChance > 0f) { if (!rapidFire) { val.m_spawnOnHitChance = BundleStatCatalog.RaisedOwnChance(on: true, IsChainLightning(val.m_spawnOnHit), val.m_spawnOnHitChance); } return; } bool flag = (int)val.m_attackType == 2 || (int)val.m_attackType == 5; float num = BundleStatCatalog.ChainChance(on: true, attackSpawnsOwn: false, flag && SpawnsOwn(AmmoProjectile(humanoid, currentWeapon) ?? val.m_attackProjectile), rapidFire); if (!(num <= 0f)) { GameObject val2 = ChainLightning(); if (!((Object)(object)val2 == (Object)null)) { val.m_spawnOnHit = val2; val.m_spawnOnHitChance = num; } } } catch (Exception arg) { if (!s_attackErrorLogged) { s_attackErrorLogged = true; Plugin.Log.LogError((object)$"Buff Thundering failed (logged once): {arg}"); } } } public static void OnModifyAttack(Character character, SkillType skill, HitData hit) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 try { if ((!s_bleeding && !s_primal) || hit == null || (int)skill == 6) { return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (object)character != localPlayer) { return; } ItemData currentWeapon = ((Humanoid)localPlayer).GetCurrentWeapon(); if (!FillsWeaponSlot(currentWeapon)) { return; } HitFacts hitFacts = ShotFacts((Humanoid)(object)localPlayer, currentWeapon); float num = BundleStatCatalog.BleedingFactor(s_bleeding, hitFacts.OwnBleeding, ((Character)localPlayer).GetMaxHealth(), ((Character)localPlayer).GetHealth()); if (num != 1f) { ((DamageTypes)(ref hit.m_damage)).Modify(num); } ShotPrimal shotPrimal = BundleStatCatalog.PrimalOnShots(hitFacts.ShotExplodes, hitFacts.ShotSparesFriends, RootHookInstalled); if (s_primal && (hitFacts.OwnRoot ? BundleStatCatalog.ShouldTopUpRoot(on: true, hit.m_statusEffectHash, currentWeapon.m_shared.m_attackStatusEffectChance, hitFacts.RapidFire, Random.value) : BundleStatCatalog.ShouldRoot(on: true, hit.m_statusEffectHash, (Object)(object)currentWeapon.m_shared.m_attackStatusEffect != (Object)null, hitFacts.RapidFire, shotPrimal == ShotPrimal.NoneFriends, shotPrimal == ShotPrimal.NoneBlast, Random.value))) { int num2 = RootHash(); if (num2 != 0) { hit.m_statusEffectHash = num2; } } } catch (Exception arg) { if (!s_onHitErrorLogged) { s_onHitErrorLogged = true; Plugin.Log.LogError((object)$"Buff Bleeding / Primal failed (logged once): {arg}"); } } } public static string OnHitNote(ItemData item, Humanoid humanoid, bool bleeding = true, bool thundering = true, bool primal = true) { try { if (item == null) { return null; } HitFacts hitFacts = ShotFacts(humanoid, item); ShotPrimal primal2 = (primal ? BundleStatCatalog.PrimalOnShots(hitFacts.ShotExplodes, hitFacts.ShotSparesFriends, RootHookInstalled) : ShotPrimal.Rolls); return BundleWindowRules.OnHitException(EffectText.DisplayName(item.m_shared.m_name), hitFacts.RapidFire && (thundering || primal), hitFacts.ShotSpawnsOwn && thundering, primal2, hitFacts.Summons && (bleeding || thundering || primal), hitFacts.OwnChain && thundering, hitFacts.OwnRoot && primal); } catch (Exception) { return null; } } public static object BeginImpact(Projectile shot, Collider collider) { Impact result = s_impact; try { int num = s_rootHash; if (!RootHookInstalled || num == 0 || (Object)(object)shot == (Object)null || !(s_projectileEffect.GetValue(shot) is int num2) || num2 != num || s_projectileOwner.GetValue(shot) != Player.m_localPlayer) { s_impact = null; } else { s_impact = new Impact { Shot = shot, Direct = (((Object)(object)collider != (Object)null) ? Projectile.FindHitObject(collider) : null) }; } } catch (Exception e) { s_impact = null; LogRootHookError(e); } return result; } public static void EndImpact(object previous) { s_impact = previous as Impact; } public static void OnProjectileSetup(Projectile spawned) { try { int num = s_rootHash; if (!RootHookInstalled || num == 0 || (Object)(object)spawned == (Object)null || !(s_projectileEffect.GetValue(spawned) is int num2) || num2 != num) { return; } if (s_impact != null) { s_projectileEffect.SetValue(spawned, 0); } else if ((Object)(object)spawned.m_spawnOnHit != (Object)null && spawned.m_projectilesInheritHitData) { object? value = s_projectileHitData.GetValue(spawned); HitData val = (HitData)((value is HitData) ? value : null); if (val != null) { HitData val2 = val.Clone(); val2.m_statusEffectHash = 0; s_projectileHitData.SetValue(spawned, val2); } } } catch (Exception e) { LogRootHookError(e); } } public static void OnCharacterHit(Character target, HitData hit) { try { int num = s_rootHash; if (!RootHookInstalled || num == 0 || hit == null || hit.m_statusEffectHash != num || (Object)(object)target == (Object)null) { return; } Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && (object)hit.GetAttacker() == localPlayer && (hit.m_ranged || !((Object)(object)((Humanoid)localPlayer).GetCurrentWeapon()?.m_shared.m_attackStatusEffect != (Object)null))) { BaseAI baseAI = target.GetBaseAI(); bool targetIsFriend = !BaseAI.IsEnemy((Character)(object)localPlayer, target) && (!((Object)(object)baseAI != (Object)null) || !baseAI.IsAggravatable()); Impact impact = s_impact; if (!BundleStatCatalog.RootStays(directTarget: impact != null && (Object)(object)impact.Direct != (Object)null && impact.Direct == ((Component)target).gameObject, targetIsFriend: targetIsFriend, ranged: hit.m_ranged, inImpact: impact != null)) { hit.m_statusEffectHash = 0; } else if (hit.m_ranged && (Object)(object)impact?.Shot != (Object)null) { s_projectileEffect.SetValue(impact.Shot, 0); } } } catch (Exception e) { LogRootHookError(e); } } private static void LogRootHookError(Exception e) { if (!s_rootHookErrorLogged) { s_rootHookErrorLogged = true; Plugin.Log.LogError((object)$"Buff Primal direct-hit hooks failed (logged once): {e}"); } } public static string OnHitNoteInUse(Player player, ItemData weapon) { if (!s_bleeding && !s_thundering && !s_primal) { return null; } return OnHitNote(weapon, (Humanoid)(object)player, s_bleeding, s_thundering, s_primal); } private static bool FillsWeaponSlot(ItemData weapon) { BundleSlot? bundleSlot = HandSlotOf(weapon); if (bundleSlot.HasValue) { return BundleStatCatalog.IsWeaponSlot(bundleSlot.Value); } return false; } private static GameObject AmmoProjectile(Humanoid humanoid, ItemData weapon) { string ammoType = weapon.m_shared.m_ammoType; if ((Object)(object)humanoid == (Object)null || string.IsNullOrEmpty(ammoType)) { return null; } ItemData ammoItem = humanoid.GetAmmoItem(); if (ammoItem == null || ammoItem.m_shared.m_ammoType != ammoType || !humanoid.GetInventory().ContainsItem(ammoItem)) { ammoItem = humanoid.GetInventory().GetAmmoItem(ammoType, (string)null); } GameObject val = ammoItem?.m_shared.m_attack?.m_attackProjectile; if (!((Object)(object)val != (Object)null)) { return null; } return val; } private static bool IsChainLightning(GameObject prefab) { if ((Object)(object)prefab != (Object)null) { return ((Object)prefab).name.StartsWith("ChainLightning", StringComparison.Ordinal); } return false; } private static bool SpawnsOwn(GameObject projectile) { Projectile val = (((Object)(object)projectile == (Object)null) ? null : projectile.GetComponent<Projectile>()); if ((Object)(object)val != (Object)null) { return (Object)(object)val.m_spawnOnHit != (Object)null; } return false; } private static bool SparesFriends(GameObject projectile) { Projectile val = (((Object)(object)projectile == (Object)null) ? null : projectile.GetComponent<Projectile>()); if ((Object)(object)val != (Object)null) { return val.m_noDamageFriendly; } return false; } private static bool Explodes(GameObject projectile) { Projectile val = (((Object)(object)projectile == (Object)null) ? null : projectile.GetComponent<Projectile>()); if ((Object)(object)val != (Object)null) { if (!(val.m_aoe > 0f)) { if ((Object)(object)val.m_spawnOnHit != (Object)null) { return val.m_projectilesInheritHitData; } return false; } return true; } return false; } private static bool OnlySummons(GameObject projectile) { if ((Object)(object)projectile != (Object)null && (Object)(object)projectile.GetComponent<Projectile>() == (Object)null) { return (Object)(object)projectile.GetComponent<Aoe>() == (Object)null; } return false; } private static HitFacts ShotFacts(Humanoid humanoid, ItemData weapon) { HitFacts result = Facts(weapon.m_shared); GameObject val = AmmoProjectile(humanoid, weapon); if ((Object)(object)val == (Object)null) { return result; } result.ShotSpawnsOwn |= SpawnsOwn(val); result.ShotSparesFriends |= SparesFriends(val); result.ShotExplodes |= Explodes(val); return result; } private static HitFacts Facts(SharedData shared) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Invalid comparison between Unknown and I4 //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Invalid comparison between Unknown and I4 if (shared == null) { return default(HitFacts); } if (s_hitFacts.TryGetValue(shared, out var value)) { return value; } HitFacts hitFacts = default(HitFacts); try { int num = 0; int num2 = 0; Attack[] array = (Attack[])(object)new Attack[2] { shared.m_attack, shared.m_secondaryAttack }; foreach (Attack val in array) { if (val != null && !string.IsNullOrEmpty(val.m_attackAnimation)) { num++; hitFacts.RapidFire |= BundleStatCatalog.IsRapidFire(val.m_attackType, val.m_projectiles, val.m_projectileBursts, val.m_loopingAttack); bool flag = (int)val.m_attackType == 2 || (int)val.m_attackType == 5; hitFacts.ShotSpawnsOwn |= flag && SpawnsOwn(val.m_attackProjectile); hitFacts.ShotSparesFriends |= flag && SparesFriends(val.m_attackProjectile); hitFacts.ShotExplodes |= flag && Explodes(val.m_attackProjectile); if (flag && OnlySummons(val.m_attackProjectile)) { num2++; } hitFacts.OwnBleeding |= val.m_damageMultiplierPerMissingHP > 0f; hitFacts.OwnChain |= val.m_spawnOnHitChance > 0f && IsChainLightning(val.m_spawnOnHit); } } hitFacts.Summons = num > 0 && num2 == num; hitFacts.OwnRoot = (Object)(object)shared.m_attackStatusEffect != (Object)null && ((Object)shared.m_attackStatusEffect).name == "ImmobilizedAshlands"; } catch (Exception) { } s_hitFacts[shared] = hitFacts; return hitFacts; } private static GameObject ChainLightning() { if ((Object)(object)s_chainLightning != (Object)null) { return s_chainLightning; } s_chainLightning = (((Object)(object)ZNetScene.instance == (Object)null) ? null : ZNetScene.instance.GetPrefab("ChainLightning")); if ((Object)(object)s_chainLightning == (Object)null && !s_chainMissingLogged) { s_chainMissingLogged = true; Plugin.Log.LogWarning((object)"Thundering does nothing: the game has no ChainLightning (game update?)."); } return s_chainLightning; } private static int RootHash() { ObjectDB instance = ObjectDB.instance; if ((Object)(object)instance == (Object)null) { return 0; } if (instance == s_rootHashDb) { return s_rootHash; } StatusEffect statusEffect = instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("ImmobilizedAshlands")); s_rootHash = ((!((Object)(object)statusEffect == (Object)null)) ? statusEffect.NameHash() : 0); s_rootHashDb = instance; if (s_rootHash == 0 && !s_rootMissingLogged) { s_rootMissingLogged = true; Plugin.Log.LogWarning((object)"Primal does nothing: the game has no ImmobilizedAshlands effect (game update?)."); } return s_rootHash; } public static float WithBlockArmor(ItemData item, float value) { try { if (s_blockArmor == 0f || item == null) { return value; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return value; } return ((((Humanoid)localPlayer).LeftItem ?? ((Humanoid)localPlayer).GetCurrentWeapon()) == item) ? BundleStatCatalog.WithBlockArmor(value, s_blockArmor) : value; } catch (Exception arg) { if (!s_blockErrorLogged) { s_blockErrorLogged = true; Plugin.Log.LogError((object)$"Buff block armor failed (logged once): {arg}"); } return value; } } public static void ShowParryBonus(ItemData item, StringBuilder text, int start) { try { if (!(s_parryBonus <= 0f) && item != null && text != null) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && (((Humanoid)localPlayer).LeftItem ?? ((Humanoid)localPlayer).GetCurrentWeapon()) == item) { BundleStatCatalog.ShowParryBonus(text, start, item.m_shared.m_timedBlockBonus, s_parryBonus); } } } catch (Exception arg) { if (!s_tooltipErrorLogged) { s_tooltipErrorLogged = true; Plugin.Log.LogError((object)$"Buff parry bonus tooltip failed (logged once): {arg}"); } } } public static float WithBlockForce(ItemData item, float value) { try { if (s_blockForce == 0f || item == null) { return value; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return value; } return ((((Humanoid)localPlayer).LeftItem ?? ((Humanoid)localPlayer).GetCurrentWeapon()) == item) ? BundleStatCatalog.WithBlockForce(value, s_blockForce) : value; } catch (Exception arg) { if (!s_blockErrorLogged) { s_blockErrorLogged = true; Plugin.Log.LogError((object)$"Buff block force failed (logged once): {arg}"); } return value; } } public static void WithAddedDamage(ItemData item, ref DamageTypes damages) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) try { if (s_addDamage.Count != 0 && item != null) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && ((Humanoid)localPlayer).GetCurrentWeapon() == item) { damages = StatBlock.AddDamageTo(damages, s_addDamage); } } } catch (Exception arg) { if (!s_damageErrorLogged) { s_damageErrorLogged = true; Plugin.Log.LogError((object)$"Buff added damage failed (logged once): {arg}"); } } } public static float WithEitrCost(Player player, float eitr) { try { if (s_eitrCost == 0f || (Object)(object)player == (Object)null || player != Player.m_localPlayer) { return eitr; } return BundleStatCatalog.WithEitrCost(eitr, s_eitrCost); } catch (Exception arg) { if (!s_eitrErrorLogged) { s_eitrErrorLogged = true; Plugin.Log.LogError((object)$"Buff eitr cost failed (logged once): {arg}"); } return eitr; } } public static ItemData CurrentWeapon() { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { return ((Humanoid)localPlayer).GetCurrentWeapon(); } return null; } public static Dictionary<string, float> OwnDamage(ItemData weapon) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, float> dictionary = StatBlock.DamageByType(weapon.GetDamage()); if (CurrentWeapon() != weapon) { return dictionary; } foreach (KeyValuePair<string, float> item in s_addDamage) { if (dictionary.TryGetValue(item.Key, out var value)) { if (value - item.Value > 0.001f) { dictionary[item.Key] = value - item.Value; } else { dictionary.Remove(item.Key); } } } return dictionary; } public static ItemData[] GearSnapshot(Humanoid h) { if ((Object)(object)h == (Object)null) { return (ItemData[])(object)new ItemData[0]; } List<ItemData> list = BundleSlots.All.Select((BundleSlot s) => Worn(h, s)).ToList(); list.Add(h.GetCurrentWeapon()); return list.ToArray(); } public static StatBlock WornTotals(Humanoid h, BundleDef bundle) { if ((Object)(object)h == (Object)null || bundle == null) { return new StatBlock(); } return StatBlock.Sum(from e in bundle.Entries where e.Stats != null && Worn(h, e.Slot) != null select e.Stats); } public static ItemData Worn(Humanoid h, BundleSlot slot) { switch (slot) { case BundleSlot.Helmet: return Get(s_helmet, h); case BundleSlot.Chest: return Get(s_chest, h); case BundleSlot.Legs: return Get(s_legs, h); case BundleSlot.Cape: return Get(s_cape, h); case BundleSlot.Melee: case BundleSlot.Ranged: case BundleSlot.Shield: { ItemData[] array = (ItemData[])(object)new ItemData[2] { Get(s_right, h), Get(s_left, h) }; foreach (ItemData val in array) { if (HandSlotOf(val) == slot) { return val; } } return null; } default: return null; } } private static ItemData Get(FieldInfo field, Humanoid h) { if (!((Object)(object)h == (Object)null)) { object? obj = field?.GetValue(h); return (ItemData)((obj is ItemData) ? obj : null); } return null; } public static BundleSlot? HandSlotOf(ItemData item) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (item != null) { return BundleSlots.HandSlot(item.m_shared.m_itemType, item.m_shared.m_skillType, UsedOnAllies(item.m_shared)); } return null; } private static bool UsedOnAllies(SharedData shared) { if (shared == null) { return false; } if (s_usedOnAllies.TryGetValue(shared, out var value)) { return value; } bool flag = false; try { flag = shared.m_attackStatusEffect is SE_Harpooned; GameObject val = shared.m_attack?.m_attackProjectile; Aoe val2 = (((Object)(object)val == (Object)null) ? null : val.GetComponent<Aoe>()); flag |= (Object)(object)val2 != (Object)null && val2.m_useAttackSettings && !val2.m_hitEnemy; } catch (Exception) { } s_usedOnAllies[shared] = flag; return flag; } private static string Read(out string error) { error = null; try { return System.IO.File.Exists(Plugin.BundlesPath) ? System.IO.File.ReadAllText(Plugin.BundlesPath) : null; } catch (Exception ex) { error = "Could not read " + Plugin.BundlesPath + ": " + ex.Message; return null; } } } internal sealed class GameEffectCatalog : IEffectCatalog { private readonly Dictionary<string, StatusEffect> _all; private readonly List<EffectInfo> _allowed; public IReadOnlyList<EffectInfo> Allowed => _allowed; public GameEffectCatalog(ObjectDB db, Dictionary<string, StatusEffect> all) { _all = all; Dictionary<string, StatusEffect> dictionary = new Dictionary<string, StatusEffect>(StringComparer.Ordinal); foreach (GameObject item in db.m_items) { if ((Object)(object)item == (Object)null) { continue; } ItemDrop component = item.GetComponent<ItemDrop>(); if ((Object)(object)component == (Object)null) { continue; } SharedData shared = component.m_itemData.m_shared; StatusEffect[] array = (StatusEffect[])(object)new StatusEffect[2] { shared.m_equipStatusEffect, shared.m_setStatusEffect }; foreach (StatusEffect val in array) { if ((Object)(object)val != (Object)null && !dictionary.ContainsKey(((Object)val).name)) { dictionary[((Object)val).name] = val; } } } _allowed = dictionary.Values.Select((StatusEffect se) => new EffectInfo { Code = ((Object)se).name, DisplayName = EffectText.DisplayName(se.m_name) }).OrderBy<EffectInfo, string>((EffectInfo e) => e.DisplayName, StringComparer.OrdinalIgnoreCase).ToList(); } public bool Exists(string code) { if (code != null) { return _all.ContainsKey(code); } return false; } public StatusEffect Get(string code) { if (code == null || !_all.TryGetValue(code, out var value)) { return null; } return value; } public string DisplayName(string code) { return _allowed.FirstOrDefault((EffectInfo e) => e.Code == code)?.DisplayName; } } internal sealed class BundleEntry { public BundleSlot Slot; public string Effect; public StatBlock Stats; public long Line; } internal sealed class BundleDef { public string Name; public long Line; public bool SpareBuildings; public readonly List<BundleEntry> Entries = new List<BundleEntry>(); public string Get(BundleSlot slot) { return Entries.FirstOrDefault((BundleEntry e) => e.Slot == slot)?.Effect; } public StatBlock GetStats(BundleSlot slot) { return Entries.FirstOrDefault((BundleEntry e) => e.Slot == slot)?.Stats; } public void Set(BundleSlot slot, string effect) { Update(slot, string.IsNullOrEmpty(effect) ? null : effect, GetStats(slot)); } public void SetStats(BundleSlot slot, StatBlock stats) { Update(slot, Get(slot), stats); } private void Update(BundleSlot slot, string effect, StatBlock stats) { BundleEntry bundleEntry = Entries.FirstOrDefault((BundleEntry e) => e.Slot == slot); if (effect == null && (stats == null || stats.IsEmpty)) { if (bundleEntry != null) { Entries.Remove(bundleEntry); } return; } if (bundleEntry == null) { List<BundleEntry> entries = Entries; BundleEntry obj = new BundleEntry { Slot = slot }; bundleEntry = obj; entries.Add(obj); } bundleEntry.Effect = effect; bundleEntry.Stats = ((stats == null || stats.IsEmpty) ? null : stats); } } internal sealed class BundleFile { public const string FileName = "LoadoutBuffs.buffs.yaml"; public const string SpareBuildingsKey = "spareBuildings"; public string Active; public readonly List<BundleDef> Bundles = new List<BundleDef>(); public readonly List<string> Warnings = new List<string>(); public bool Invalid; public readonly List<string> Misplaced = new List<string>(); public static readonly string[] Header = new string[40] { "# LoadoutBuffs: extra \"while worn\" effects and stats, per equipment slot.", "#", "# Pick and edit buffs in game: inventory -> Buffs (or the console command lb_buffs).", "# Or edit this file and run lb_reload in the F5 console. The Buffs window rewrites this", "# file, so comments you add here are not kept.", "#", "# active: the buff in use for every character in this profile, or none.", "# Slots: helmet, chest, legs, cape, melee (swords, knives, clubs, atgeirs, spears, axes, fists),", "# ranged (bows, crossbows, magic staffs), shield. A slot counts while something is equipped there", "# (weapons: in your hands); your gear keeps its own effects. Pickaxes, the fishing rod, torches and", "# tools fill no slot. Effect: code name or in-game name of an effect gear has in the game (the", "# Buffs window lists them).", "# A slot can also have custom stats (long form):", "# chest:", "# effect: SetEffect_DeepNorthMediumArmor", "# stats: { movementSpeed: 10, armor: 15, resist: { Fire: Resistant }, skills: { Bows: 15 } }", "# Stats: movementSpeed, carryWeight, runStamina, jumpStamina, attackStamina, blockStamina,", "# dodgeStamina, eitrCost (percent stats in percent: 10 = +10 %), skills, fields (raw SE_Stats", "# fields).", "# Helmet, chest, legs or cape slot only: armor, fallDamage, healthRegen, staminaRegen, eitrRegen,", "# resist.", "# Melee, ranged or shield slot only: blockArmor, blockForce (what you block with), parryBonus", "# (added to the parry bonus of what you parry with, up to 20: 2 turns 2.5x into 4.5x).", "# Melee, ranged or shield slot only, on every parry: healOnParry, staminaOnParry (you),", "# healAlliesOnParry, staminaAlliesOnParry (other players), healTamedOnParry, shieldOnParry (a Magic", "# barrier absorbing that much, for all of you), shieldMinutes (its time, default 1), parryRadius", "# (reach in metres, default 10).", "# Melee or ranged slot only: damage (%), addDamage (flat, e.g. { spirit: 30 }), and the classes", "# woodcutter: true (that weapon's hits fell any tree) and miner: true (they break any rock or ore).", "# Melee or ranged slot only, on that weapon's hits (like the Ashlands weapon variants):", "# bleeding: true (+0.2 % damage per missing health), thundering: true (35 % chance of chain", "# lightning) and primal: true (35 % chance to root the target for 10 s). Not on rapid-fire", "# staffs (Dundr, Staff of Frost: no thundering or primal); no chain lightning from staffs whose", "# shot spawns its own effect; a staff's blast roots only the enemy it hits directly, and primal", "# never roots players or tamed animals.", "# The stats of all filled slots add up (reach and bubble time take the largest) and show on your HUD", "# as one buff named after it.", "# spareBuildings: true, next to a buff's slots: while that buff is in use, your hits don't damage", "# anything players built (walls, doors, chests, portals, ships, carts); forts and ruins still break.", "# Spreading fire, falling trees and siege machines still damage them." }; public bool OnlyMisplaced { get { if (!Invalid && Misplaced.Count > 0) { return Warnings.Count == Misplaced.Count; } return false; } } public BundleDef Find(string name) { if (name != null) { return Bundles.FirstOrDefault((BundleDef b) => string.Equals(b.Name, name, StringComparison.OrdinalIgnoreCase)); } return null; } public static BundleFile Parse(string text) { BundleFile bundleFile = new BundleFile(); if (string.IsNullOrWhiteSpace(text)) { return bundleFile; } text = text.Replace('\u00a0', ' ').Replace('\u202f', ' ').Replace('\u2007', ' '); YamlStream yamlStream = new YamlStream(); try { yamlStream.Load(new StringReader(text)); } catch (YamlException ex) { bundleFile.Invalid = true; bundleFile.Warnings.Add(string.Format("{0} is not valid YAML (around line {1}, column {2}), ", "LoadoutBuffs.buffs.yaml", ex.Start.Line, ex.Start.Column) + "so no buff is used: " + ex.Message); return bundleFile; } if (yamlStream.Documents.Count == 0) { return bundleFile; } YamlNode rootNode = yamlStream.Documents[0].RootNode; if (IsNull(rootNode)) { return bundleFile; } if (!(rootNode is YamlMappingNode yamlMappingNode)) { bundleFile.Warnings.Add(string.Format("{0}: expected 'active:' and 'buffs:' (line {1}).", "LoadoutBuffs.buffs.yaml", rootNode.Start.Line)); return bundleFile; } foreach (KeyValuePair<YamlNode, YamlNode> child in yamlMappingNode.Children) { string text2 = Scalar(child.Key); string text3 = text2?.ToLowerInvariant(); if (!(text3 == "active")) { if (text3 == "buffs") { bundleFile.ParseBundles(child.Value); } else { bundleFile.Warnings.Add(string.Format("{0}: unknown key '{1}', skipped (line {2}). Use 'active' and 'buffs'.", "LoadoutBuffs.buffs.yaml", text2, child.Key.Start.Line)); } } else { bundleFile.ParseActive(child.Value); } } if (bundleFile.Active != null && bundleFile.Find(bundleFile.Active) == null) { bundleFile.Warnings.Add("LoadoutBuffs.buffs.yaml: active buff '" + bundleFile.Active + "' doesn't exist, so no buff is used. Buffs: " + ((bundleFile.Bundles.Count == 0) ? "none" : string.Join(", ", bundleFile.Bundles.Select((BundleDef b) => b.Name))) + "."); } return bundleFile; } private void ParseActive(YamlNode node) { if (!IsNull(node) && !IsNone(node)) { if (node is YamlScalarNode yamlScalarNode) { Active = yamlScalarNode.Value.Trim(); } else { Warnings.Add(string.Format("{0}: 'active' must be a buff name or none (line {1}).", "LoadoutBuffs.buffs.yaml", node.Start.Line)); } } } private void ParseBundles(YamlNode node) { if (IsNull(node)) { return; } if (!(node is YamlMappingNode yamlMappingNode)) { Warnings.Add(string.Format("{0}: 'buffs' must be a list of named buffs like 'Warrior: {{ chest: Vanguard }}' (line {1}).", "LoadoutBuffs.buffs.yaml", node.Start.Line)); return; } foreach (KeyValuePair<YamlNode, YamlNode> child in yamlMappingNode.Children) { string text = Scalar(child.Key)?.Trim(); long line = child.Key.Start.Line; if (string.IsNullOrEmpty(text)) { Warnings.Add(string.Format("{0}: expected a buff name (line {1}).", "LoadoutBuffs.buffs.yaml", line)); continue; } if (Find(text) != null) { Warnings.Add(string.Format("{0}: buff '{1}' appears twice (names ignore upper/lower case); the second one is skipped (line {2}).", "LoadoutBuffs.buffs.yaml", text, line)); continue; } BundleDef bundleDef = new BundleDef { Name = text, Line = line }; Bundles.Add(bundleDef); if (IsNull(child.Value)) { continue; } if (!(child.Value is YamlMappingNode yamlMappingNode2)) { Warnings.Add($"{text}: expected slots like 'chest: Vanguard' (line {line})."); continue; } HashSet<BundleSlot> seen = new HashSet<BundleSlot>(); bool seen2 = false; foreach (KeyValuePair<YamlNode, YamlNode> child2 in yamlMappingNode2.Children) { if (string.Equals(Scalar(child2.Key)?.Trim(), "spareBuildings", StringComparison.OrdinalIgnoreCase)) { ParseSpareBuildings(bundleDef, child2.Key, child2.Value, ref seen2); } else { ParseSlot(bundleDef, child2.Key, child2.Value, seen); } } } } private void ParseSpareBuildings(BundleDef bundle, YamlNode keyNode, YamlNode valueNode, ref bool seen) { string arg = bundle.Name + ".spareBuildings"; long line = keyNode.Start.Line; if (seen) { Warnings.Add($"{arg}: appears twice (keys ignore upper/lower case); the second one is skipped (line {line})."); return; } seen = true; if (!IsNull(valueNode)) { object value; string error; if (!(valueNode is YamlScalarNode yamlScalarNode)) { Warnings.Add($"{arg}: expected true or false; skipped (line {line})."); } else if (Values.TryParse(yamlScalarNode.Value, typeof(bool), out value, out error)) { bundle.SpareBuildings = (bool)value; } else { Warnings.Add($"{arg}: {error}; skipped (line {line})."); } } } private void ParseSlot(BundleDef bundle, YamlNode keyNode, YamlNode valueNode, HashSet<BundleSlot> seen) { string text = Scalar(keyNode); long line = keyNode.Start.Line; if (!BundleSlots.TryParse(text, out var slot)) { string text2 = BundleSlots.RemovedSlotHint(text); Warnings.Add(bundle.Name + "." + text + ": " + ((text2 != null) ? (text2 + ", so it's skipped") : "unknown slot, skipped") + string.Format(" (line {0}). Slots: {1}.", line, string.Join(", ", BundleSlots.All.Select(BundleSlots.Key)))); return; } string text3 = bundle.Name + "." + BundleSlots.Key(slot); if (!seen.Add(slot)) { Warnings.Add($"{text3}: the slot appears twice (slots ignore upper/lower case); the second one is skipped (line {line})."); } else { if (IsNull(valueNode) || IsNone(valueNode)) { return; } if (valueNode is YamlScalarNode yamlScalarNode) { bundle.Entries.Add(new BundleEntry { Slot = slot, Effect = yamlScalarNode.Value.Trim(), Line = line }); return; } if (!(valueNode is YamlMappingNode yamlMappingNode)) { Warnings.Add($"{text3}: expected an effect name, or 'effect:' and 'stats:'; skipped (line {line})."); return; } BundleEntry bundleEntry = new BundleEntry { Slot = slot, Line = line }; foreach (KeyValuePair<YamlNode, YamlNode> child in yamlMappingNode.Children) { string text4 = Scalar(child.Key)?.Trim(); string text5 = text4?.ToLowerInvariant(); if (!(text5 == "effect")) { if (text5 == "stats") { if (IsNull(child.Value)) { continue; } if (child.Value is YamlMappingNode map) { List<(string, string)> list = new List<(string, string)>(); bundleEntry.Stats = StatBlock.Parse(map, text3, Warnings, slot, list); foreach (var (text6, text7) in list) { Misplaced.Add(text6 + " from " + bundle.Name + "'s " + BundleSlots.Key(slot) + "; it only goes on the " + text7 + " now"); } } else { Warnings.Add($"{text3}.stats: expected stats like {{ armor: 15 }}; skipped (line {child.Key.Start.Line})."); } } else { Warnings.Add($"{text3}.{text4}: unknown key, skipped (line {child.Key.Start.Line}). Use 'effect' and 'stats'."); } } else if (!IsNull(child.Value) && !IsNone(child.Value)) { if (child.Value is YamlScalarNode yamlScalarNode2) { bundleEntry.Effect = yamlScalarNode2.Value.Trim(); } else { Warnings.Add($"{text3}.effect: expected one effect name; skipped (line {child.Key.Start.Line})."); } } } if (bundleEntry.Stats != null && bundleEntry.Stats.IsEmpty) { bundleEntry.Stats = null; } if (bundleEntry.Effect != null || bundleEntry.Stats != null) { bundle.Entries.Add(bundleEntry); } } } public string Serialize(Func<string, string> displayName) { StringBuilder stringBuilder = new StringBuilder(); string[] header = Header; foreach (string value in header) { stringBuilder.Append(value).Append('\n'); } stringBuilder.Append('\n'); stringBuilder.Append("active: ").Append((Active == null) ? "none" : Values.Quote(Active)).Append('\n'); stringBuilder.Append('\n'); if (Bundles.Count == 0) { stringBuilder.Append("buffs: {}\n"); return stringBuilder.ToString(); } stringBuilder.Append("buffs:\n"); foreach (BundleDef bundle in Bundles) { if (bundle.Entries.Count == 0 && !bundle.SpareBuildings) { stringBuilder.Append(" ").Append(Values.Quote(bundle.Name)).Append(": {}\n"); continue; } stringBuilder.Append(" ").Append(Values.Quote(bundle.Name)).Append(":\n"); if (bundle.SpareBuildings) { stringBuilder.Append(" ").Append("spareBuildings").Append(": true\n"); } BundleSlot[] all = BundleSlots.All; foreach (BundleSlot slot in all) { string text = bundle.Get(slot); StatBlock stats = bundle.GetStats(slot); if (text == null && stats == null) { continue; } string text2 = ((text == null) ? null : displayName?.Invoke(text)); string comment = ((!string.IsNullOrEmpty(text2) && text2 != text) ? text2.Replace('\n', ' ') : null); if (stats == null) { stringBuilder.Append(WithComment(" " + BundleSlots.Key(slot) + ": " + Values.Quote(text), comment)).Append('\n'); continue; } stringBuilder.Append(" " + BundleSlots.Key(slot) + ":\n"); if (text != null) { stringBuilder.Append(WithComment(" effect: " + Values.Quote(text), comment)).Append('\n'); } stringBuilder.Append(" stats: " + stats.Serialize() + "\n"); } } return stringBuilder.ToString(); } private static string WithComment(string line, string comment) { if (comment != null) { return line.PadRight(46) + " # " + comment; } return line; } private static string Scalar(YamlNode node) { return (node as YamlScalarNode)?.Value; } private static bool IsNull(YamlNode node) { if (!(node is YamlScalarNode { Style: ScalarStyle.Plain } yamlScalarNode)) { return false; } string value = yamlScalarNode.Value; if (value != null && value.Length != 0 && !(value == "~")) { return string.Equals(value, "null", StringComparison.OrdinalIgnoreCase); } return true; } private static bool IsNone(YamlNode node) { if (node is YamlScalarNode { Style: ScalarStyle.Plain } yamlScalarNode) { return string.Equals(yamlScalarNode.Value?.Trim(), "none", StringComparison.OrdinalIgnoreCase); } return false; } } [HarmonyPatch] internal static class BundlePatches { [HarmonyPatch(typeof(Humanoid), "UpdateEquipmentStatusEffects")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> UpdateEquipmentStatusEffects(IEnumerable<CodeInstruction> instructions) { //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Expected O, but got Unknown BundleEffects.HookInstalled = false; List<CodeInstruction> list = instructions.ToList(); MethodInfo methodInfo = AccessTools.Method(typeof(BundleEffects), "AddTo", (Type[])null, (Type[])null); for (int i = 0; i < list.Count - 1; i++) { if (!(list[i].opcode != OpCodes.Newobj) && list[i].operand is ConstructorInfo constructorInfo && !(constructorInfo.DeclaringType != typeof(HashSet<StatusEffect>)) && constructorInfo.GetParameters().Length == 0) { CodeInstruction val = LoadFor(list[i + 1]); if (val == null) { break; } list.InsertRange(i + 2, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), val, new CodeInstruction(OpCodes.Call, (object)methodInfo) }); BundleEffects.HookInstalled = true; Plugin.Log.LogInfo((object)"Buff hook installed in Humanoid.UpdateEquipmentStatusEffects"); return list; } } Plugin.Log.LogError((object)"Buffs disabled: Humanoid.UpdateEquipmentStatusEffects doesn't look as expected (game update?)."); return list; } private static CodeInstruction LoadFor(CodeInstruction store) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected O, but got Unknown //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Expected O, but got Unknown if (store.opcode == OpCodes.Stloc_0) { return new CodeInstruction(OpCodes.Ldloc_0, (object)null); } if (store.opcode == OpCodes.Stloc_1) { return new CodeInstruction(OpCodes.Ldloc_1, (object)null); } if (store.opcode == OpCodes.Stloc_2) { return new CodeInstruction(OpCodes.Ldloc_2, (object)null); } if (store.opcode == OpCodes.Stloc_3) { return new CodeInstruction(OpCodes.Ldloc_3, (object)null); } if (store.opcode == OpCodes.Stloc_S) { return new CodeInstruction(OpCodes.Ldloc_S, store.operand); } if (store.opcode == OpCodes.Stloc) { return new CodeInstruction(OpCodes.Ldloc, store.operand); } return null; } } [HarmonyPatch] internal static class BundleParryPatches { [HarmonyPatch(typeof(Humanoid), "BlockAttack")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> BlockAttack(IEnumerable<CodeInstruction> instructions) { //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Expected O, but got Unknown //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown BundleEffects.ParryHookInstalled = false; List<CodeInstruction> list = instructions.ToList(); FieldInfo objB = AccessTools.Field(typeof(Humanoid), "m_perfectBlockEffect"); MethodInfo methodInfo = AccessTools.Method(typeof(BundleEffects), "OnParry", (Type[])null, (Type[])null); for (int i = 0; i < list.Count; i++) { if (list[i].opcode != OpCodes.Ldfld || !object.Equals(list[i].operand, objB)) { continue; } for (int j = i + 1; j < list.Count - 1 && j < i + 20; j++) { if (list[j].operand is MethodInfo methodInfo2 && !(methodInfo2.DeclaringType != typeof(EffectList)) && !(methodInfo2.Name != "Create")) { if (list[j + 1].opcode != OpCodes.Pop) { break; } list.InsertRange(j + 2, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Call, (object)methodInfo) }); BundleEffects.ParryHookInstalled = true; Plugin.Log.LogInfo((object)"Buff parry hook installed in Humanoid.BlockAttack"); return list; } } break; } Plugin.Log.LogError((object)"Buff on-parry stats disabled: Humanoid.BlockAttack doesn't look as expected (game update?). Everything else is not affected."); return list; } } [HarmonyPatch] internal static class BundleBlockPatches { [HarmonyPatch(typeof(ItemData), "GetBaseBlockPower", new Type[] { typeof(int) })] [HarmonyPostfix] private static void BlockArmor(ItemData __instance, ref float __result) { __result = BundleEffects.WithBlockArmor(__instance, __result); } [HarmonyPatch(typeof(ItemData), "GetDeflectionForce", new Type[] { typeof(int) })] [HarmonyPostfix] private static void BlockForce(ItemData __instance, ref float __result) { __result = BundleEffects.WithBlockForce(__instance, __result); } } [HarmonyPatch] internal static class BundleTooltipPatches { [HarmonyPatch(typeof(ItemData), "AddBlockTooltip")] [HarmonyPrefix] private static void Before(StringBuilder text, out int __state) { __state = text?.Length ?? 0; } [HarmonyPatch(typeof(ItemData), "AddBlockTooltip")] [HarmonyPostfix] private static void After(ItemData item, StringBuilder text, int __state) { BundleEffects.ShowParryBonus(item, text, __state); } } [HarmonyPatch] internal static class BundleDamagePatches { [HarmonyPatch(typeof(ItemData), "GetDamage", new Type[] { typeof(int), typeof(float) })] [HarmonyPostfix] private static void AddedDamage(ItemData __instance, ref DamageTypes __result) { BundleEffects.WithAddedDamage(__instance, ref __result); } } [HarmonyPatch] internal static class BundleEitrPatches { [HarmonyPatch(typeof(Player), "UseEitr", new Type[] { typeof(float) })] [HarmonyPrefix] private static void Use(Player __instance, ref float v) { v = BundleEffects.WithEitrCost(__instance, v); } [HarmonyPatch(typeof(Player), "HaveEitr", new Type[] { typeof(float) })] [HarmonyPrefix] private static void Have(Player __instance, ref float amount) { amount = BundleEffects.WithEitrCost(__instance, amount); } } [HarmonyPatch] internal static class BundleHitPatches { [HarmonyPatch(typeof(Humanoid), "StartAttack", new Type[] { typeof(Character), typeof(bool) })] [HarmonyPostfix] private static void AttackStarted(Humanoid __instance, bool __result) { if (__result) { BundleEffects.OnAttackStart(__instance); } } } [HarmonyPatch] internal static class BundleRootPatches { [HarmonyPatch(typeof(Projectile), "OnHit")] [HarmonyPrefix] private static void ImpactStart(Projectile __instance, Collider collider, out object __state) { __state = BundleEffects.BeginImpact(__instance, collider); } [HarmonyPatch(typeof(Projectile), "OnHit")] [HarmonyFinalizer] private static void ImpactEnd(object __state) { BundleEffects.EndImpact(__state); } [HarmonyPatch(typeof(Projectile), "Setup")] [HarmonyPostfix] private static void Spawned(Projectile __instance) { BundleEffects.OnProjectileSetup(__instance); } [HarmonyPatch(typeof(Character), "Damage")] [HarmonyPrefix] private static void Hit(Character __instance, HitData hit) { BundleEffects.OnCharacterHit(__instance, hit); } } [HarmonyPatch] internal static class BundleBuildingPatches { [HarmonyPatch(typeof(WearNTear), "Damage")] [HarmonyPrefix] private static bool Damage(WearNTear __instance, HitData hit) { return !BundleEffects.OnBuildingHit(__instance, hit); } } [HarmonyPatch] internal static class BundleClassPatches { [HarmonyPatch(typeof(TreeBase), "Damage")] [HarmonyPrefix] private static void Tree(TreeBase __instance, HitData hit) { BundleEffects.OnDestructibleHit(__instance, hit); } [HarmonyPatch(typeof(TreeLog), "Damage")] [HarmonyPrefix] private static void Log(TreeLog __instance, HitData hit) { BundleEffects.OnDestructibleHit(__instance, hit); } [HarmonyPatch(typeof(MineRock), "Damage")] [HarmonyPrefix] private static void Rock(MineRock __instance, HitData hit) { BundleEffects.OnDestructibleHit(__instance, hit); } [HarmonyPatch(typeof(MineRock5), "Damage")] [HarmonyPrefix] private static void BigRock(MineRock5 __instance, HitData hit) { BundleEffects.OnDestructibleHit(__instance, hit); } [HarmonyPatch(typeof(Destructible), "Damage")] [HarmonyPrefix] private static void Other(Destructible __instance, HitData hit) { BundleEffects.OnDestructibleHit(__instance, hit); } } internal enum BundleSlot { Helmet, Chest, Legs, Cape, Melee, Ranged, Shield } internal static class BundleSlots { public static readonly BundleSlot[] All = (BundleSlot[])Enum.GetValues(typeof(BundleSlot)); private static readonly HashSet<SkillType> s_ranged = new HashSet<SkillType> { (SkillType)8, (SkillType)14, (SkillType)9, (SkillType)10 }; private static readonly HashSet<SkillType> s_melee = new HashSet<SkillType> { (SkillType)1, (SkillType)2, (SkillType)3, (SkillType)4, (SkillType)5, (SkillType)7, (SkillType)11 }; public static string Key(BundleSlot slot) { return slot.ToString().ToLowerInvariant(); } public static string RemovedSlotHint(string key) { switch (key?.Trim().ToLowerInvariant()) { case "weapon": return "the weapon slot was split: use melee or ranged"; case "utility": case "trinket": return "the " + key.Trim().ToLowerInvariant() + " slot was removed (those items already have their own effects)"; default: return null; } } public static BundleSlot? HandSlot(ItemType type, SkillType skill, bool usedOnAllies) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Invalid comparison between Unknown and I4 //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) if ((int)type <= 5) { if (type - 3 <= 1) { goto IL_0023; } if ((int)type == 5) { return BundleSlot.Shield; } } else if ((int)type == 14 || (int)type == 22) { goto IL_0023; } return null; IL_0023: if (usedOnAllies) { return null; } if (s_ranged.Contains(skill)) { return BundleSlot.Ranged; } if (s_melee.Contains(skill)) { return BundleSlot.Melee; } return null; } public static bool TryParse(string key, out BundleSlot slot) { slot = BundleSlot.Helmet; if (string.IsNullOrEmpty(key)) { return false; } BundleSlot[] all = All; foreach (BundleSlot bundleSlot in all) { if (string.Equals(Key(bundleSlot), key.Trim(), StringComparison.OrdinalIgnoreCase)) { slot = bundleSlot; return true; } } return false; } } internal sealed class EffectInfo { public string Code; public string DisplayName; } internal interface IEffectCatalog { IReadOnlyList<EffectInfo> Allowed { get; } bool Exists(string code); } internal sealed class BundleState { public bool Enabled = true; public string OffReason; public BundleDef Active; public readonly Dictionary<BundleSlot, string> Effects = new Dictionary<BundleSlot, string>(); public readonly Dictionary<BundleSlot, StatBlock> Stats = new Dictionary<BundleSlot, StatBlock>(); public readonly List<string> Warnings = new List<string>(); public int StatCount => StatBlock.Sum(Stats.Values).Count; public int HookWarningCount { get; private set; } public int FileWarnings => Warnings.Count - HookWarningCount; public void AddHookWarnings(IEnumerable<string> warnings) { foreach (string warning in warnings) { Warnings.Add(warning); HookWarningCount++; } } public string StatusLine() { if (!Enabled) { return "Buffs off: " + OffReason; } if (Active == null) { return "No buff active"; } int statCount = StatCount; return string.Format("Buff '{0}' active: {1} effect{2}", Active.Name, Effects.Count, (Effects.Count == 1) ? "" : "s") + ((statCount > 0) ? string.Format(", {0} stat{1}", statCount, (statCount == 1) ? "" : "s") : "") + (Active.SpareBuildings ? ", spares buildings" : ""); } } internal static class BundleRules { public static bool SparesBuilding(bool on, bool attackerIsYou, long creator) { if (on && attackerIsYou) { return creator != 0; } return false; } public static bool ShowsHudBuff(BundleState state) { if (state != null && state.Enabled) { return state.Active != null; } return false; } public static List<string> MissingHookWarnings(IEnumerable<StatBlock> stats, bool parryHook, bool blockHook, bool damageHook, bool eitrHook, bool hitHook, bool spareBuildings = false, bool buildingHook = true, bool classHook = true, bool tooltipHook = true) { List<StatBlock> source = stats.Where((StatBlock b) => b != null).ToList(); List<string> list = new List<string>(); if (!parryHook && source.Any((StatBlock b) => b.ToParryAssist() != null)) { list.Add("The buff's on-parry stats can't work with this game version (the parry hook isn't installed, see LogOutput.log)."); } if (!blockHook && source.Any((StatBlock b) => b.BlockArmor != 0f || b.BlockForce != 0f)) { list.Add("The buff's block armor / force can't work (the block hook isn't installed, see LogOutput.log)."); } if (!damageHook && source.Any((StatBlock b) => b.AddDamage.Count > 0)) { list.Add("The buff's added damage can't work (the added damage hook isn't installed, see LogOutput.log)."); } if (!eitrHook && source.Any((StatBlock b) => b.EitrCost != 0f)) { list.Add("The buff's eitr cost can't work (the eitr hook isn't installed, see LogOutput.log)."); } if (!hitHook && source.Any((StatBlock b) => b.Scalars.ContainsKey("thundering"))) { list.Add("The buff's Thundering can't work (the attack hook isn't installed, see LogOutput.log)."); } if (!buildingHook && spareBuildings) { list.Add("The buff's Spare buildings can't work (the building hook isn't installed, see LogOutput.log)."); } if (!classHook && source.Any((StatBlock b) => b.Scalars.ContainsKey("woodcutter") || b.Scalars.ContainsKey("miner"))) { list.Add("The buff's Woodcutter / Miner may not work (the class hooks aren't all installed, see LogOutput.log)."); } if (!tooltipHook && source.Any((StatBlock b) => b.ParryBonus > 0f)) { list.Add("The item tooltip's Parry bonus doesn't include the buff's (the tooltip hook isn't installed, see LogOutput.log); your parries still get it."); } return list; } public static string Resolve(string text, IEffectCatalog catalog, out string error) { error = null; string t = text?.Trim() ?? ""; EffectInfo effectInfo = catalog.Allowed.FirstOrDefault((EffectInfo e) => string.Equals(e.Code, t, StringComparison.Ordinal)) ?? catalog.Allowed.FirstOrDefault((EffectInfo e) => string.Equals(e.Code, t, StringComparison.OrdinalIgnoreCase)); if (effectInfo != null) { return effectInfo.Code; } List<EffectInfo> list = catalog.Allowed.Where((EffectInfo e) => string.Equals(e.DisplayName, t, StringComparison.OrdinalIgnoreCase)).ToList(); if (list.Count == 1) { return list[0].Code; } if (list.Count > 1) { error = "'" + t + "' is the in-game name of several effects; use one of their code names: " + string.Join(", ", list.Select((EffectInfo e) => e.Code)); return null; } error = (catalog.Exists(t) ? ("'" + t + "' can't be used in a buff: only effects that gear has in the game can (the Buffs window lists them)") : ("unknown effect '" + t + "'; use a code name or in-game name from the Buffs window's list")); return null; } public static BundleState Evaluate(BundleFile file, IEffectCatalog catalog) { BundleState bundleState = new BundleState(); file = file ?? new BundleFile(); bundleState.Warnings.AddRange(file.Warnings); Dictionary<BundleDef, Dictionary<BundleSlot, string>> dictionary = new Dictionary<BundleDef, Dictionary<BundleSlot, string>>(); foreach (BundleDef bundle in file.Bundles) { dictionary[bundle] = ResolveBundle(bundle, catalog, bundleState.Warnings); } if (file.Invalid) { bundleState.Enabled = false; bundleState.OffReason = "LoadoutBuffs.buffs.yaml is not valid YAML (see the warning)."; return bundleState; } bundleState.Active = file.Find(file.Active); if (bundleState.Active == null) { return bundleState; } foreach (KeyValuePair<BundleSlot, string> item in dictionary[bundleState.Active]) { bundleState.Effects[item.Key] = item.Value; } foreach (BundleEntry entry in bundleState.Active.Entries) { if (entry.Stats != null && !entry.Stats.IsEmpty) { bundleState.Stats[entry.Slot] = entry.Stats; } } return bundleState; } public static Dictionary<BundleSlot, string> ResolveBundle(BundleDef bundle, IEffectCatalog catalog, List<string> warnings) { Dictionary<BundleSlot, string> dictionary = new Dictionary<BundleSlot, string>(); Dictionary<string, BundleSlot> dictionary2 = new Dictionary<string, BundleSlot>(StringComparer.Ordinal); foreach (BundleEntry entry in bundle.Entries) { if (entry.Effect != null) { string text = bundle.Name + "." + BundleSlots.Key(entry.Slot); string text2 = ((entry.Line > 0) ? $" (line {entry.Line})" : ""); string error; string text3 = Resolve(entry.Effect, catalog, out error); BundleSlot value; if (text3 == null) { warnings?.Add(text + ": " + error + "; skipped" + text2 + "."); } else if (dictionary2.TryGetValue(text3, out value)) { warnings?.Add(text + ": " + text3 + " is already in the " + BundleSlots.Key(value) + " slot, and an effect only counts once; skipped" + text2 + "."); } else { dictionary2[text3] = entry.Slot; dictionary[entry.Slot] = text3; } } } return dictionary; } } internal static class BundleWindowRules { public const string SpareBuildingsHint = "While this buff is in use, your hits don't damage anything players built."; public const string ShiftHint = "Shift + click on − / + : 10 steps at a time."; public static float ClickStep(float step, bool shift) { if (!shift) { return step; } return step * 10f; } public static string SpareBuildingsButton(bool on) { return "Spare buildings: " + (on ? "<color=orange>On</color>" : "Off"); } public static string ProblemsLine(int count, int fileCount, string first) { string text = string.Format("{0} problem{1}", count, (count == 1) ? "" : "s"); if (fileCount == count) { text += " in the buffs file"; } else if (fileCount > 0) { text += $" ({fileCount} in the buffs file)"; } return text + ": " + first; } public static List<string> DamagePercentRows(IReadOnlyDictionary<string, float> dealt, IReadOnlyDictionary<string, float> set) { if (dealt == null) { return BundleStatCatalog.DamageTypes.ToList(); } return BundleStatCatalog.DamageTypes.Where(delegate(string t) { string key = t.ToLowerInvariant(); float value; return (dealt.TryGetValue(key, out value) && value > 0f) || (set != null && set.ContainsKey(key)); }).ToList(); } public static string OnHitInfo(bool ranged) { return (ranged ? "Your shots" : "Your melee hits") + ": Bleeding +0.2% damage per missing health, Thundering 35% chain lightning, Primal 35% root (10 s)."; } public static string OnHitException(string weaponName, bool rapidFire, bool shotSpawnsOwn, ShotPrimal primal, bool summons, bool ownChainLightning, bool ownRoots) { if (summons) { return weaponName + ": On hit does nothing (it summons instead of hitting)."; } if (rapidFire) { return weaponName + ": no Thundering or Primal (rapid fire)."; } List<string> list = new List<string>(); if (ownChainLightning || ownRoots) { list.Add((ownChainLightning && ownRoots) ? "chain lightning and root effect chances raised to 35%" : (ownChainLightning ? "chain lightning chance raised to 35%" : "root effect chance raised to 35%")); } if (shotSpawnsOwn) { list.Add("no Thundering (its shot spawns its own effect)"); } switch (primal) { case ShotPrimal.DirectHitOnly: list.Add("Primal roots only the enemy it hits directly"); break; case ShotPrimal.NoneBlast: list.Add("no Primal (one roll would root everything it reaches)"); break; case ShotPrimal.NoneFriends: list.Add("no Primal (it would root friends)"); break; } if (list.Count != 0) { return weaponName + ": " + string.Join("; ", list) + "."; } return null; } public static string AddedDamageNote(float own) { if (!(own > 0f)) { return null; } return "has " + own.ToString("0.##", CultureInfo.InvariantCulture); } public static List<string> WornEffectNames(BundleDef bundle, IEffectCatalog catalog, Func<BundleSlot, bool> isWorn) { if (bundle == null || catalog == null) { return new List<string>(); } return (from p in BundleRules.ResolveBundle(bundle, catalog, null) where isWorn(p.Key) orderby p.Key select catalog.Allowed.FirstOrDefault((EffectInfo e) => e.Code == p.Value)?.DisplayName ?? p.Value).ToList(); } } internal enum StatKind { Percent, RegenPercent, Flat, Parry, Toggle, Blocker, EitrCost, ParryBonus } internal enum ShotPrimal { Rolls, DirectHitOnly, NoneBlast, NoneFriends } internal sealed class StatDef { public string Key; public string Label; public string Group; public string Field; public StatKind Kind; public float Step; public float Min; public float Max; public float Default; public bool TakesLargest; public float TotalMax = float.PositiveInfinity; public string Unit = ""; public bool LowerIsBetter; public BundleSlot[] OnlyOn; public string WhereAllowed { get { if (OnlyOn != null) { return BundleStatCatalog.SlotsText(OnlyOn); } return "any slot"; } } public bool IsPercent { get { if (Kind != StatKind.Percent && Kind != StatKind.RegenPercent) { return Kind == StatKind.EitrCost; } return true; } } public bool Allows(BundleSlot slot) { if (OnlyOn != null) { return Array.IndexOf(OnlyOn, slot) >= 0; } return true; } public bool Helps(float value) { if (!LowerIsBetter) { return value > 0f; } return value < 0f; } } internal static class BundleStatCatalog { public const string General = "General"; public const string Regen = "Regen"; public const string Costs = "Costs"; public const string OnParry = "On parry"; public const string Class = "Class"; public const string WoodcutterKey = "woodcutter"; public const string MinerKey = "miner"; public const string OnHit = "On hit"; public const string BleedingKey = "bleeding"; public const string ThunderingKey = "thundering"; public const string PrimalKey = "primal"; public const string Resistances = "Resistances"; public const string Damage = "Damage %"; public const string Skills = "Skills"; public const string ResistKey = "resist"; public const string DamageKey = "damage"; public const string SkillsKey = "skills"; public const string FieldsKey = "fields"; private static readonly BundleSlot[] HandSlots = new BundleSlot[3] { BundleSlot.Melee, BundleSlot.Ranged, BundleSlot.Shield }; private static readonly BundleSlot[] ArmorSlots = new BundleSlot[4] { BundleSlot.Helmet, BundleSlot.Chest, BundleSlot.Legs, BundleSlot.Cape }; public static readonly StatDef[] Scalars = new StatDef[24] { Def("movementSpeed", "Movement speed", "General", "m_speedModifier", StatKind.Percent, 5f, -50f, 100f), Def("carryWeight", "Carry weight", "General", "m_addMaxCarryWeight", StatKind.Flat, 25f, -100f, 500f), OnlyOn(Def("armor", "Armor", "General", "m_addArmor", StatKind.Flat, 5f, -50f, 200f), ArmorSlots), OnlyOn(Def("blockArmor", "Block armor", "General", null, StatKind.Blocker, 5f, -50f, 1000f), HandSlots), OnlyOn(Def("blockForce", "Block force", "General", null, StatKind.Blocker, 5f, -50f, 300f), HandSlots), OnlyOn(Cost("fallDamage", "Fall damage", "General", "m_fallDamageModifier", 10f, -100f, 100f), ArmorSlots), OnlyOn(Def("healthRegen", "Health regen", "Regen", "m_healthRegenMultiplier", StatKind.RegenPercent, 10f, -50f, 300f), ArmorSlots), OnlyOn(Def("staminaRegen", "Stamina regen", "Regen", "m_staminaRegenMultiplier", StatKind.RegenPercent, 10f, -50f, 300f), ArmorSlots), OnlyOn(Def("eitrRegen", "Eitr regen", "Regen", "m_eitrRegenMultiplier", StatKind.RegenPercent, 10f, -50f, 300f), ArmorSlots), Cost("runStamina", "Run stamina cost", "Costs", "m_runStaminaDrainModifier", 5f, -100f, 100f), Cost("jumpStamina", "Jump stamina cost", "Costs", "m_jumpStaminaUseModifier", 5f, -100f, 100f), Cost("attackStamina", "Attack stamina cost", "Costs", "m_attackStaminaUseModifier", 5f, -100f, 100f), Cost("blockStamina", "Block stamina cost", "Costs", "m_blockStaminaUseModifier", 5f, -100f, 100f), Cost("dodgeStamina", "Dodge stamina cost", "Costs", "m_dodgeStaminaUseModifier", 5f, -100f, 100f), new StatDef { Key = "eitrCost", Label = "Eitr cost", Group = "Costs", Kind = StatKind.EitrCost, Step = 5f, Min = -100f, Max = 100f, LowerIsBetter = true }, new StatDef { Key = "parryBonus", Label = "Parry bonus", Group = "On parry", Kind = StatKind.ParryBonus, Step = 0.5f, Min = 0f, Max = 20f, TotalMax = 20f, OnlyOn = HandSlots }, Parry("healOnParry", "Heal you", 10f, 0f, 300f), Parry("staminaOnParry", "Stamina to you", 10f, 0f, 300f), Parry("healAlliesOnParry", "Heal allies", 10f, 0f, 300f), Parry("staminaAlliesOnParry", "Stamina to allies", 10f, 0f, 300f), Parry("healTamedOnParry", "Heal tamed", 10f, 0f, 300f), Parry("shieldOnParry", "Bubble health", 100f, 0f, 3000f), new StatDef { Key = "shieldMinutes", Label = "Bubble time", Group = "On parry", Kind = StatKind.Parry, Step = 1f, Min = 1f, Max = 10f, Default = 1f, TakesLargest = true, Unit = " min", OnlyOn = HandSlots }, new StatDef { Key = "parryRadius", Label = "Reach", Group = "On parry", Kind = StatKind.Parry, Step = 5f, Min = 5f, Max = 50f, Default = 10f, TakesLargest = true, Unit = " m", OnlyOn = HandSlots } }; public const string ParryRadiusKey = "parryRadius"; public const string ParryBonusKey = "parryBonus"; public const float ParryBonusMax = 20f; public const string EitrCostKey = "eitrCost"; private static readonly BundleSlot[] WeaponSlots = new BundleSlot[2] { BundleSlot.Melee, BundleSlot.Ranged }; private static readonly (string Key, string Group, BundleSlot[] Slots)[] s_nestedOnlyOn = new(string, string, BundleSlot[])[3] { ("resist", "Resistances", ArmorSlots), ("damage", "Damage %", WeaponSlots), ("addDamage", "Added damage", WeaponSlots) }; public const string BlockArmorKey = "blockArmor"; public const string BlockForceKey = "blockForce"; public static readonly StatDef[] Toggles = new StatDef[2] { new StatDef { Key = "woodcutter", Label = "Woodcutter", Group = "Class", Kind = StatKind.Toggle, Step = 1f, Min = 0f, Max = 1f, TakesLargest = true, OnlyOn = WeaponSlots }, new StatDef { Key = "miner", Label = "Miner", Group = "Class", Kind = StatKind.Toggle, Step = 1f, Min = 0f, Max = 1f, TakesLargest = true, OnlyOn = WeaponSlots } }; public static readonly StatDef[] OnHitEffects = new StatDef[3] { OnHitToggle("bleeding", "Bleeding"), OnHitToggle("thundering", "Thundering"), OnHitToggle("primal", "Primal") }; public const float BleedingPerMissingHealth = 0.002f; public const float ChainLightningChance = 0.35f; public const float RootChance = 0.35f; public const float DamageStep = 5f; public const float DamageMin = -50f; public const float DamageMax = 200f; public const string AddedDamage = "Added damage"; public const string AddDamageKey = "addDamage"; public const float AddDamageStep = 5f; public const float AddDamageMin = 0f; public const float AddDamageMax = 300f; public static readonly string[] AddDamageTypes = new string[8] { "Blunt", "Slash", "Pierce", "Fire", "Frost", "Lightning", "Poison", "Spirit" }; public const float SkillStep = 5f; public const float SkillMin = -50f; public const float SkillMax = 100f; public static readonly string[] DamageTypes = Catalog.ModifierTypes; public static readonly string[] ModifierCycle = new string[8] { "Normal", "SlightlyResistant", "Resistant", "VeryResistant", "Immune", "SlightlyWeak", "Weak", "VeryWeak" }; private static readonly string[] s_protection = new string[9] { "Immune", "Ignore", "VeryResistant", "Resistant", "SlightlyResistant", "Normal", "SlightlyWeak", "Weak", "VeryWeak" }; public static readonly string[] SkillNames = (from n in Enum.GetNames(typeof(SkillType)) where n != "None" && n != "Step" select n).ToArray(); public static readonly string[] WindowSkills = SkillNames.Where((string n) => n != "All").ToArray(); public static bool IsArmorSlot(BundleSlot slot) { return Array.IndexOf(ArmorSlots, slot) >= 0; } public static float WithParryBonus(float itemBonus, float added) { return itemBonus + Math.Min(20f, Math.Max(0f, added)); } public static bool ShowParryBonus(StringBuilder text, int start, float itemBonus, float bonus) { if (start < 0 || start > text.Length) { return false; } string text2 = ParryTooltipLine(itemBonus); if (text.ToString(start, text.Length - start).IndexOf(text2, StringComparison.Ordinal) < 0) { return false; } text.Replace(text2, ParryTooltipLine(WithParryBonus(itemBonus, bonus)), start, text.Length - start); return true; } private static string ParryTooltipLine(float multiplier) { return $"\n$item_parrybonus: <color=orange>{multiplier}x</color>"; } public static float WithEitrCost(float cost, float percent) { return cost * Math.Max(0f, 1f + percent / 100f); } public static bool IsWeaponSlot(BundleSlot slot) { return Array.IndexOf(WeaponSlots, slot) >= 0; } public static string SlotsText(BundleSlot[] slots) { List<string> list = slots.Select(BundleSlots.Key).ToList(); string text = list[list.Count - 1]; return ((list.Count == 1) ? text : (string.Join(", ", list.Take(list.Count - 1)) + " or " + text)) + " slot"; } public static (string Key, string Group, BundleSlot[] Slots)? NestedOnlyOn(string key) { (string, string, BundleSlot[])[] array = s_nestedOnlyOn; for (int i = 0; i < array.Length; i++) { (string, string, BundleSlot[]) value = array[i]; if (string.Equals(value.Item1, key?.Trim(), StringComparison.OrdinalIgnoreCase)) { return value; } } return null; } public static float WithBlockForce(float baseBlockForce, float bonus) { return Math.Max(0f, baseBlockForce + bonus); } public static float WithBlockArmor(float baseBlockArmor, float bonus) { return Math.Max(Math.Min(baseBlockArmor, 1f), baseBlockArmor + bonus); } public static bool WithClass(ref DamageTypes damage, bool tree, bool woodcutter, bool miner) { float val = ((DamageTypes)(ref damage)).GetTotalDamage() - damage.m_chop - damage.m_pickaxe; if (tree && woodcutter) { damage.m_chop = Math.Max(damage.m_chop, val); } else { if (!(!tree && miner)) { return false; } damage.m_pickaxe = Math.Max(damage.m_pickaxe, val); } return true; } private static StatDef OnHitToggle(string key, string label) { return new StatDef { Key = key, Label = label, Group = "On hit", Kind = StatKind.Toggle, Step = 1f, Min = 0f, Max = 1f, TakesLargest = true, OnlyOn = WeaponSlots }; } public static float BleedingFactor(bool on, bool weaponHasOwn, float maxHealth, float health) { if (!(!on || weaponHasOwn)) { return 1f + Math.Max(0f, maxHealth - health) * 0.002f; } return 1f; } public static float ChainChance(bool on, bool attackSpawnsOwn, bool shotSpawnsOwn, bool rapidFire) { if (!(!on || attackSpawnsOwn || shotSpawnsOwn || rapidFire)) { return 0.35f; } return 0f; } public static float RaisedOwnChance(bool on, bool ownIsChainLightning, float ownChance) { if (!(on && ownIsChainLightning)) { return ownChance; } return Math.Max(ownChance, 0.35f); } public static float TopUpChance(float own, float target) { if (!(own >= target) && !(own >= 1f)) { return (target - Math.Max(0f, own)) / (1f - Math.Max(0f, own)); } return 0f; } public static bool ShouldTopUpRoot(bool on, int hitEffectHash, float ownChance, bool rapidFire, float roll) { if (on && hitEffectHash == 0 && !rapidFire) { return roll < TopUpChance(ownChance, 0.35f); } return false; } public static bool ShouldRoot(bool on, int hitEffectHash, bool weaponHasOwnEffect, bool rapidFire, bool shotSparesFriends, bool shotExplodes, float roll) { if (on && hitEffectHash == 0 && !weaponHasOwnEffect && !rapidFire && !shotSparesFriends && !shotExplodes) { return roll < 0.35f; } return false; } public static ShotPrimal PrimalOnShots(bool shotExplodes, bool shotSparesFriends, bool directHitHooks) { if (directHitHooks) { if (!shotExplodes) { return ShotPrimal.Rolls; } return ShotPrimal.DirectHitOnly; } if (shotSparesFriends) { return ShotPrimal.NoneFriends; } if (!shotExplodes) { return ShotPrimal.Rolls; } return ShotPrimal.NoneBlast; } public static bool RootStays(bool targetIsFriend, bool ranged, bool inImpact, bool directTarget) { if (!targetIsFriend) { if (ranged) { return inImpact && directTarget; } return true; } return false; } public static bool IsRapidFire(AttackType type, int projectiles, int bursts, bool looping) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)type == 2 || (int)type == 5) { return projectiles > 1 || bursts > 1 || looping; } return false; } public static int Protection(string modifier) { int num = Array.IndexOf(s_protection, modifier); if (num >= 0) { return num; } return int.MaxValue; } public static StatDef Find(string key) { return Scalars.Concat(Toggles).Concat(OnHitEffects).FirstOrDefault((StatDef d) => string.Equals(d.Key, key?.Trim(), StringComparison.OrdinalIgnoreCase)); } public static string ModifierLabel(string modifier) { return modifier switch { "SlightlyResistant" => "Slightly resistant", "VeryResistant" => "Very resistant", "SlightlyWeak" => "Slightly weak", "VeryWeak" => "Very weak", _ => modifier, }; } public static FieldInfo RawField(string name, out string error) { error = null; FieldInfo field = typeof(SE_Stats).GetField(name?.Trim() ?? "", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field == null) { error = "'" + name + "' is not a field of SE_Stats"; return null; } if (field.DeclaringType != typeof(SE_Stats)) { error = field.Name + " can't be set from a buff (only SE_Stats' own stat fields can)"; return null; } Type fieldType = field.FieldType; if (fieldType == typeof(float) || fieldType == typeof(int) || fieldType == typeof(bool) || fieldType.IsEnum) { return field; } error = name + " (" + fieldType.Name + ") can't be set from a buff"; return null; } private static StatDef Def(string key, string label, string group, string field, StatKind kind, float step, float min, float max) { return new StatDef { Key = key, Label = label, Group = group, Field = field, Kind = kind, Step = step, Min = min, Max = max }; } private static StatDef Parry(string key, string label, float step, float min, float max) { return OnlyOn(Def(key, label, "On parry", null, StatKind.Parry, step, min, max), HandSlots); } private static StatDef OnlyOn(StatDef def, BundleSlot[] slots) { def.OnlyOn = slots; return def; } private static StatDef Cost(string key, string label, string group, string field, float step, float min, float max) { StatDef statDef = Def(key, label, group, field, StatKind.Percent, step, min, max); statDef.LowerIsBetter = true; return statDef; } } internal sealed class StatBlock { public readonly Dictionary<string, float> Scalars = new Dictionary<string, float>(StringComparer.Ordinal); public readonly Dictionary<string, string> Resist = new Dictionary<string, string>(StringComparer.Ordinal); public readonly Dictionary<string, float> Damage = new Dictionary<string, float>(StringComparer.Ordinal); public readonly Dictionary<string, float> Skills = new Dictionary<string, float>(StringComparer.Ordinal); public readonly Dictionary<string, float> AddDamage = new Dictionary<string, float>(StringComparer.Ordinal); public readonly List<KeyValuePair<string, string>> Fields = new List<KeyValuePair<string, string>>(); public float BlockArmor { get { if (!Scalars.TryGetValue("blockArmor", out var value)) { return 0f; } return value; } } public float BlockForce { get { if (!Scalars.TryGetValue("blockForce", out var value)) { return 0f; } return value; } } public float EitrCost { get { if (!Scalars.TryGetValue("eitrCost", out var value)) { return 0f; } return value; } } public float ParryBonus { get { if (!Scalars.TryGetValue("parryBonus", out var value)) { return 0f; } return value; } } public int Count => Scalars.Count + Resist.Count + Damage.Count + AddDamage.Count + Skills.Count + Fields.Select((KeyValuePair<string, string> f) => f.Key).Distinct().Count(); public bool IsEmpty => Count == 0; public StatBlock Clone() { StatBlock statBlock = new StatBlock(); foreach (KeyValuePair<string, float> scalar in Scalars) { statBlock.Scalars[scalar.Key] = scalar.Value; } foreach (KeyValuePair<string, string> item in Resist) { statBlock.Resist[item.Key] = item.Value; } foreach (KeyValuePair<string, float> item2 in Damage) { statBlock.Damage[item2.Key] = item2.Value; } foreach (KeyValuePair<string, float> skill in Skills) { statBlock.Skills[skill.Key] = skill.Value; } foreach (KeyValuePair<string, float> item3 in AddDamage) { statBlock.AddDamage[item3.Key] = item3.Value; } statBlock.Fields.AddRange(Fields); return statBlock; } public ParryAssist ToParryAssist() { ParryAssist parryAssist = new ParryAssist { Heal = Get("healOnParry"), Stamina = Get("staminaOnParry"), HealAllies = Get("healAlliesOnParry"), StaminaAllies = Get("staminaAlliesOnParry"), HealTamed = Get("healTamedOnParry"), Shield = Get("shieldOnParry") }; if (Scalars.TryGetValue("parryRadius", out var value)) { parryAssist.Radius = value; } if (Scalars.TryGetValue("shieldMinutes", out var value2))