Decompiled source of Equipment v1.0.1

meadworks.equipment.dll

Decompiled 29 minutes ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using MeadWorks.Core;
using MeadWorks.UI;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("MeadWorks.Equipment.Tests")]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("expDARE")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2026 expDARE")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("meadworks.equipment")]
[assembly: AssemblyTitle("meadworks.equipment")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[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 MeadWorks.Equipment
{
	public sealed class AppliedAttackTable<TShared, TAttack> where TShared : class where TAttack : class
	{
		private sealed class Entry
		{
			public TAttack Original;

			public TAttack Copy;

			public TAttack Foreign;
		}

		private readonly ConditionalWeakTable<TShared, Entry> _entries = new ConditionalWeakTable<TShared, Entry>();

		private readonly List<WeakReference<TShared>> _keys = new List<WeakReference<TShared>>();

		public int Count { get; private set; }

		public TAttack Original(TShared shared, TAttack live)
		{
			if (live == null || !_entries.TryGetValue(shared, out var value) || live != value.Copy)
			{
				return live;
			}
			return value.Original;
		}

		public TAttack Donor(TShared target, TShared donor, TAttack live)
		{
			if (target != donor)
			{
				return Original(donor, live);
			}
			return live;
		}

		public bool Owns(TShared shared, TAttack live)
		{
			if (live != null && _entries.TryGetValue(shared, out var value))
			{
				return live == value.Copy;
			}
			return false;
		}

		public TAttack Apply(TShared shared, TAttack live, Func<TAttack, TAttack> clone)
		{
			return Apply(shared, live, clone, live);
		}

		public TAttack Apply(TShared shared, TAttack live, Func<TAttack, TAttack> clone, TAttack baseline)
		{
			return Apply(shared, live, (TAttack attack, Func<TAttack, TAttack> transform) => transform(attack), clone, baseline);
		}

		public TAttack Apply<TState>(TShared shared, TAttack live, Func<TAttack, TState, TAttack> clone, TState state, TAttack baseline)
		{
			if (live == null)
			{
				return null;
			}
			if (!_entries.TryGetValue(shared, out var value))
			{
				value = new Entry();
				_entries.Add(shared, value);
				_keys.Add(new WeakReference<TShared>(shared));
			}
			if (live == value.Copy)
			{
				return live;
			}
			if (value.Copy != null)
			{
				value.Foreign = live;
				value.Copy = null;
				Count--;
			}
			if (live == value.Foreign)
			{
				return live;
			}
			value.Foreign = null;
			value.Original = baseline;
			value.Copy = clone(value.Original, state);
			Count++;
			return value.Copy;
		}

		public void Revert(Func<TShared, TAttack> read, Action<TShared, TAttack> write)
		{
			for (int num = _keys.Count - 1; num >= 0; num--)
			{
				Entry value;
				if (!_keys[num].TryGetTarget(out var target))
				{
					_keys.RemoveAt(num);
				}
				else if (_entries.TryGetValue(target, out value) && value.Copy != null)
				{
					TAttack val = read(target);
					if (val == value.Copy)
					{
						write(target, value.Original);
					}
					else
					{
						value.Foreign = val;
					}
					value.Copy = null;
				}
			}
			Count = 0;
		}
	}
	public static class ArrowImpacts
	{
		private static class Patches
		{
			[HarmonyPatch(typeof(ObjectDB), "Awake")]
			[HarmonyPostfix]
			private static void Awake()
			{
				SafeRegister.Run("ArrowImpacts.Awake", (Action)delegate
				{
					Register();
				});
			}

			[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
			[HarmonyPostfix]
			private static void CopyOtherDB()
			{
				SafeRegister.Run("ArrowImpacts.CopyOtherDB", (Action)delegate
				{
					Register();
				});
			}

			[HarmonyPatch(typeof(ZNet), "Awake")]
			[HarmonyPostfix]
			private static void NetworkReady()
			{
				EmberGround.Register();
			}

			[HarmonyPatch(typeof(Projectile), "Setup")]
			[HarmonyPostfix]
			private static void SetupEmber(Projectile __instance)
			{
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0056: Expected O, but got Unknown
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: Expected O, but got Unknown
				if (!EmberArrow.Enabled || !LocalOwner(__instance) || AmmoPrefab(__instance) != "MW_ArrowEmber")
				{
					return;
				}
				Projectile obj = __instance;
				obj.m_onHit = (OnProjectileHit)Delegate.Combine((Delegate?)(object)obj.m_onHit, (Delegate?)(OnProjectileHit)delegate(Collider collider, Vector3 point, bool water)
				{
					//IL_0031: Unknown result type (might be due to invalid IL or missing references)
					if (water || !EmberArrow.Enabled || !LocalOwner(__instance) || TranspileGuard.Off(typeof(ArrowImpacts)))
					{
						return;
					}
					try
					{
						Ember(__instance, collider, point);
					}
					catch (Exception ex)
					{
						MwLog.WarnOnce("ember impact", (object)("Ember arrow impact: " + ex.Message));
					}
				});
			}

			[HarmonyPatch(typeof(Projectile), "OnHit")]
			[HarmonyPrefix]
			private static void Prepare(Projectile __instance)
			{
				_stagger = 0f;
				if (EmberArrow.Enabled && LocalOwner(__instance) && AmmoPrefab(__instance) == "MW_ArrowWhistling")
				{
					_stagger = 8f;
				}
			}

			[HarmonyPatch(typeof(Projectile), "OnHit")]
			[HarmonyPostfix]
			internal static void After(Projectile __instance, Collider collider, Vector3 hitPoint)
			{
				//IL_0054: Unknown result type (might be due to invalid IL or missing references)
				//IL_0069: Unknown result type (might be due to invalid IL or missing references)
				_stagger = 0f;
				if (EmberArrow.Enabled && LocalOwner(__instance))
				{
					string text = AmmoPrefab(__instance);
					Character hit = Struck(collider);
					Character owner = __instance.m_owner;
					switch (text)
					{
					case "MW_ArrowThunder":
						Thunder(owner, __instance, hit);
						break;
					case "MW_ArrowBramble":
						Bramble(owner, hit, hitPoint);
						break;
					case "MW_ArrowWhistling":
						Whistle(owner, hitPoint);
						break;
					}
				}
			}

			[HarmonyPatch(typeof(Character), "Damage")]
			[HarmonyPrefix]
			private static void Stamp(HitData hit)
			{
				if (!(_stagger <= 0f) && hit != null)
				{
					hit.m_staggerMultiplier = _stagger;
					_stagger = 0f;
				}
			}
		}

		private static readonly HashSet<ObjectDB> Databases = new HashSet<ObjectDB>();

		private static readonly HashSet<Character> Skip = new HashSet<Character>();

		private static BrambleRoot _root;

		private static SE_Stats _slow;

		private static float _stagger;

		public static void Init()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			Ledger.Add("arrow impacts", (Action)Teardown);
			EnsureEffects();
			if (TranspileGuard.PatchAll(new Harmony("expdare.meadworks.equipment.arrowimpacts"), typeof(Patches), "arrow impacts"))
			{
				EmberGround.Register();
				Register();
			}
		}

		public static string Describe()
		{
			ObjectDB instance = ObjectDB.instance;
			bool flag = (Object)(object)instance != (Object)null && (Object)(object)_root != (Object)null && instance.m_StatusEffects != null && instance.m_StatusEffects.Contains((StatusEffect)(object)_root);
			bool flag2 = (Object)(object)instance != (Object)null && (Object)(object)_slow != (Object)null && instance.m_StatusEffects != null && instance.m_StatusEffects.Contains((StatusEffect)(object)_slow);
			return "root=" + flag + " slow=" + flag2;
		}

		private static void Register()
		{
			if (TranspileGuard.Off(typeof(ArrowImpacts)))
			{
				return;
			}
			ObjectDB instance = ObjectDB.instance;
			if (!((Object)(object)instance == (Object)null) && instance.m_StatusEffects != null)
			{
				EnsureEffects();
				if (!instance.m_StatusEffects.Contains((StatusEffect)(object)_root))
				{
					SafeRegister.Add<StatusEffect>(instance.m_StatusEffects, (StatusEffect)(object)_root);
				}
				if (!instance.m_StatusEffects.Contains((StatusEffect)(object)_slow))
				{
					SafeRegister.Add<StatusEffect>(instance.m_StatusEffects, (StatusEffect)(object)_slow);
				}
				Databases.Add(instance);
			}
		}

		private static void EnsureEffects()
		{
			if ((Object)(object)_root == (Object)null)
			{
				_root = ScriptableObject.CreateInstance<BrambleRoot>();
				((Object)_root).name = "SE_MW_BrambleRoot";
				((StatusEffect)_root).m_name = Lang.T("equipment.rooted", "Rooted");
				((StatusEffect)_root).m_ttl = 2f;
				((StatusEffect)_root).m_tooltip = Lang.T("equipment.rooted_text", "Cannot move.");
			}
			if ((Object)(object)_slow == (Object)null)
			{
				_slow = ScriptableObject.CreateInstance<SE_Stats>();
				((Object)_slow).name = "SE_MW_BrambleSlow";
				((StatusEffect)_slow).m_name = Lang.T("equipment.slowed", "Slowed");
				((StatusEffect)_slow).m_ttl = 3f;
				_slow.m_speedModifier = -0.39999998f;
				((StatusEffect)_slow).m_tooltip = "";
			}
		}

		private static void Teardown()
		{
			EmberGround.Clear();
			foreach (ObjectDB database in Databases)
			{
				if (!((Object)(object)database == (Object)null) && database.m_StatusEffects != null)
				{
					database.m_StatusEffects.Remove((StatusEffect)(object)_root);
					database.m_StatusEffects.Remove((StatusEffect)(object)_slow);
				}
			}
			Databases.Clear();
			if ((Object)(object)_root != (Object)null)
			{
				Object.Destroy((Object)(object)_root);
			}
			if ((Object)(object)_slow != (Object)null)
			{
				Object.Destroy((Object)(object)_slow);
			}
			_root = null;
			_slow = null;
			_stagger = 0f;
		}

		private static bool LocalOwner(Projectile projectile)
		{
			if ((Object)(object)projectile != (Object)null && (Object)(object)projectile.m_owner != (Object)null)
			{
				return (Object)(object)projectile.m_owner == (Object)(object)Player.m_localPlayer;
			}
			return false;
		}

		private static string AmmoPrefab(Projectile projectile)
		{
			ItemData ammo = projectile.m_ammo;
			if (ammo == null || (Object)(object)ammo.m_dropPrefab == (Object)null)
			{
				return "";
			}
			string text = ((Object)ammo.m_dropPrefab).name;
			if (text.EndsWith("(Clone)", StringComparison.Ordinal))
			{
				text = text.Substring(0, text.Length - "(Clone)".Length);
			}
			return text;
		}

		private static Character Struck(Collider collider)
		{
			if (!((Object)(object)collider == (Object)null))
			{
				return ((Component)collider).GetComponentInParent<Character>();
			}
			return null;
		}

		private static void Ember(Projectile projectile, Collider collider, Vector3 point)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			EmberGround.Ignite(projectile, point);
			Character val = Struck(collider);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Character owner = projectile.m_owner;
			float fire = projectile.m_damage.m_fire;
			Skip.Clear();
			Skip.Add(val);
			Character val2 = val;
			for (int i = 0; i < 1; i++)
			{
				Character val3 = Nearest(owner, val2.GetCenterPoint(), 3f);
				if ((Object)(object)val3 == (Object)null)
				{
					break;
				}
				if (fire > 0f)
				{
					Hurt(owner, val3, fire, lightning: false);
				}
				SEMan sEMan = val3.GetSEMan();
				if (sEMan != null)
				{
					sEMan.AddStatusEffect(SEMan.s_statusEffectBurning, true, 0, 0f, (short)(-1));
				}
				Skip.Add(val3);
				val2 = val3;
			}
			Skip.Clear();
		}

		private static void Thunder(Character owner, Projectile projectile, Character hit)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)hit == (Object)null)
			{
				return;
			}
			float lightning = projectile.m_damage.m_lightning;
			if (lightning <= 0f)
			{
				return;
			}
			Skip.Clear();
			Skip.Add(hit);
			Vector3 centerPoint = hit.GetCenterPoint();
			for (int i = 1; i <= 2; i++)
			{
				Character val = Nearest(owner, centerPoint, 6f);
				if ((Object)(object)val == (Object)null)
				{
					break;
				}
				float amount = ArrowRules.JumpDamage(lightning, i);
				Hurt(owner, val, amount, lightning: true);
				Arc(centerPoint, val.GetCenterPoint());
				Skip.Add(val);
				centerPoint = val.GetCenterPoint();
			}
			Skip.Clear();
		}

		private static void Bramble(Character owner, Character hit, Vector3 point)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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_0076: Unknown result type (might be due to invalid IL or missing references)
			EnsureEffects();
			if ((Object)(object)hit != (Object)null && !hit.IsDead())
			{
				SEMan sEMan = hit.GetSEMan();
				if (sEMan != null)
				{
					sEMan.AddStatusEffect(((StatusEffect)_root).NameHash(), true, 0, 0f, (short)(-1));
				}
			}
			Vector3 val = (((Object)(object)hit != (Object)null) ? hit.GetCenterPoint() : point);
			List<Character> allCharacters = Character.GetAllCharacters();
			for (int i = 0; i < allCharacters.Count; i++)
			{
				Character val2 = allCharacters[i];
				if (!((Object)(object)val2 == (Object)(object)hit) && Hostile(owner, val2) && !(Vector3.Distance(val, val2.GetCenterPoint()) > 3f))
				{
					SEMan sEMan2 = val2.GetSEMan();
					if (sEMan2 != null)
					{
						sEMan2.AddStatusEffect(((StatusEffect)_slow).NameHash(), true, 0, 0f, (short)(-1));
					}
				}
			}
		}

		private static void Whistle(Character owner, Vector3 point)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			List<Character> allCharacters = Character.GetAllCharacters();
			for (int i = 0; i < allCharacters.Count; i++)
			{
				Character val = allCharacters[i];
				if ((Object)(object)val == (Object)null || val.IsDead() || val.IsPlayer() || (Object)(object)val == (Object)(object)owner)
				{
					continue;
				}
				BaseAI baseAI = val.GetBaseAI();
				if (!((Object)(object)baseAI == (Object)null) && !(Vector3.Distance(((Component)val).transform.position, point) > 15f) && !val.IsTamed() && (!((Object)(object)owner != (Object)null) || BaseAI.IsEnemy(owner, val) || baseAI.IsAggravatable()))
				{
					baseAI.Alert();
					baseAI.m_randomMoveTarget = point;
					baseAI.m_reachedRandomMoveTarget = false;
					MonsterAI val2 = (MonsterAI)(object)((baseAI is MonsterAI) ? baseAI : null);
					if ((Object)(object)val2 != (Object)null)
					{
						val2.m_lastKnownTargetPos = point;
					}
				}
			}
		}

		private static Character Nearest(Character owner, Vector3 from, float range)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			Character result = null;
			float num = range;
			List<Character> allCharacters = Character.GetAllCharacters();
			for (int i = 0; i < allCharacters.Count; i++)
			{
				Character val = allCharacters[i];
				if (Hostile(owner, val) && !Skip.Contains(val))
				{
					float num2 = Vector3.Distance(from, val.GetCenterPoint());
					if (!(num2 > num))
					{
						num = num2;
						result = val;
					}
				}
			}
			return result;
		}

		private static bool Hostile(Character owner, Character target)
		{
			if ((Object)(object)target == (Object)null || (Object)(object)target == (Object)(object)owner || target.IsDead())
			{
				return false;
			}
			if (!((Object)(object)owner == (Object)null))
			{
				return BaseAI.IsEnemy(owner, target);
			}
			return true;
		}

		internal static void Hurt(Character attacker, Character target, float amount, bool lightning)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)target == (Object)null) && !(amount <= 0f) && !target.IsDead())
			{
				HitData val = new HitData();
				if (lightning)
				{
					val.m_damage.m_lightning = amount;
				}
				else
				{
					val.m_damage.m_fire = amount;
				}
				val.m_point = target.GetCenterPoint();
				Vector3 val2 = (((Object)(object)attacker != (Object)null) ? (target.GetCenterPoint() - attacker.GetCenterPoint()) : Vector3.forward);
				if (((Vector3)(ref val2)).sqrMagnitude < 0.001f)
				{
					val2 = Vector3.forward;
				}
				val.m_dir = ((Vector3)(ref val2)).normalized;
				val.m_ranged = true;
				val.SetAttacker(attacker);
				val.m_hitType = (HitType)2;
				val.m_skill = (SkillType)8;
				target.Damage(val);
			}
		}

		private static void Arc(Vector3 from, Vector3 to)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = to - from;
			Quaternion rot = ((((Vector3)(ref val)).sqrMagnitude > 0.001f) ? Quaternion.LookRotation(val) : Quaternion.identity);
			Effect(from, rot, "fx_chainlightning_spread", "fx_lightningstaffprojectile_hit");
			Effect(to, rot, "fx_chainlightning_hit", "fx_lightningweapon_hit");
			Effect(to, rot, "sfx_StaffLightning_fire");
		}

		private static void Effect(Vector3 point, Quaternion rot, params string[] names)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			ZNetScene instance = ZNetScene.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			foreach (string text in names)
			{
				GameObject prefab = instance.GetPrefab(text);
				if (!((Object)(object)prefab == (Object)null))
				{
					Object.Destroy((Object)(object)Object.Instantiate<GameObject>(prefab, point, rot), 6f);
					break;
				}
			}
		}
	}
	public class BrambleRoot : SE_Stats
	{
		public override void ModifySpeed(float baseSpeed, ref float speed, Character character, Vector3 dir)
		{
			speed = 0f;
		}
	}
	public static class ArrowRules
	{
		public const int StackSize = 100;

		public const int ThunderJumps = 2;

		public const float ChainFalloff = 0.6f;

		public const float ChainRange = 6f;

		public const float EmberSpreadRange = 3f;

		public const int EmberSpreads = 1;

		public const float EmberPatchRadius = 2f;

		public const double EmberPatchSeconds = 4.0;

		public const double EmberPatchInterval = 1.0;

		public const float EmberPatchFireFraction = 0.25f;

		public const float RootSeconds = 2f;

		public const float SlowSeconds = 3f;

		public const float SlowRange = 3f;

		public const float SlowMultiplier = 0.6f;

		public const float AlertRange = 15f;

		public static bool InEmberPatch(float distanceSquared)
		{
			if (distanceSquared >= 0f)
			{
				return distanceSquared <= 4f;
			}
			return false;
		}

		public static bool EmberPatchDue(double now, double next, double until)
		{
			if (now >= next)
			{
				return now < until;
			}
			return false;
		}

		public static float EmberPatchFire(float impactFire)
		{
			if (!(impactFire > 0f) || !(impactFire < float.PositiveInfinity))
			{
				return 0f;
			}
			return impactFire * 0.25f;
		}

		internal static bool EmberPatchCanHit(bool enemy, bool aggravatable, bool pvp, bool hitFriendly, bool noDamageFriendly)
		{
			if (!(enemy || aggravatable))
			{
				if (!noDamageFriendly)
				{
					return pvp || hitFriendly;
				}
				return false;
			}
			return true;
		}

		public static float JumpDamage(float initialDamage, int jump)
		{
			if (jump < 0 || jump > 2)
			{
				throw new ArgumentOutOfRangeException("jump");
			}
			if (float.IsNaN(initialDamage) || float.IsInfinity(initialDamage) || initialDamage < 0f)
			{
				throw new ArgumentOutOfRangeException("initialDamage");
			}
			return initialDamage * (float)Math.Pow(0.6000000238418579, jump);
		}
	}
	public enum AttackMember
	{
		AttackStamina,
		AttackEitr,
		AttackHealth,
		ForceMultiplier,
		StaggerMultiplier,
		AttackRange,
		ProjectileVel,
		ProjectileVelMin,
		ProjectileAccuracy,
		ProjectileAccuracyMin,
		DrawDurationMin,
		DrawStaminaDrain,
		ReloadTime
	}
	public static class AttackFieldMap
	{
		private static readonly AttackMember[][] Members_ = new AttackMember[11][]
		{
			new AttackMember[1],
			new AttackMember[1] { AttackMember.AttackEitr },
			new AttackMember[1] { AttackMember.AttackHealth },
			new AttackMember[1] { AttackMember.ForceMultiplier },
			new AttackMember[1] { AttackMember.StaggerMultiplier },
			new AttackMember[1] { AttackMember.AttackRange },
			new AttackMember[2]
			{
				AttackMember.ProjectileVel,
				AttackMember.ProjectileVelMin
			},
			new AttackMember[2]
			{
				AttackMember.ProjectileAccuracy,
				AttackMember.ProjectileAccuracyMin
			},
			new AttackMember[1] { AttackMember.DrawDurationMin },
			new AttackMember[1] { AttackMember.DrawStaminaDrain },
			new AttackMember[1] { AttackMember.ReloadTime }
		};

		public static IReadOnlyList<AttackMember> Members(AttackField field)
		{
			return Members_[(int)field];
		}

		public static float Scale(AttackMember member, float live, float factor)
		{
			if (member != AttackMember.AttackEitr || live > 0f)
			{
				return AttackOverrideRules.Scale(live, factor);
			}
			return live;
		}
	}
	[Flags]
	public enum LiveAttackPlan
	{
		None = 0,
		Primary = 1,
		CopySecondary = 2,
		OverrideSecondary = 4
	}
	public sealed class LiveAttackChecks<T> where T : class
	{
		private sealed class Entry
		{
			public int Version = -1;

			public bool Applied;
		}

		private readonly ConditionalWeakTable<T, Entry> entries = new ConditionalWeakTable<T, Entry>();

		private int version;

		public void Refresh()
		{
			version++;
		}

		public bool Begin(T item)
		{
			Entry orCreateValue = entries.GetOrCreateValue(item);
			if (orCreateValue.Version == version)
			{
				return false;
			}
			orCreateValue.Version = version;
			return true;
		}

		public bool TrackApplied(T item)
		{
			Entry orCreateValue = entries.GetOrCreateValue(item);
			if (orCreateValue.Applied)
			{
				return false;
			}
			orCreateValue.Applied = true;
			return true;
		}
	}
	public static class AttackLiveRules
	{
		public static LiveAttackPlan Plan(bool work, bool sharedSame, bool ammo, bool weapon, bool primaryRule, Func<bool> presetFields, bool givenSecondary, bool secondaryRule, bool skipSecondary)
		{
			if (!work || sharedSame || ammo || !weapon)
			{
				return LiveAttackPlan.None;
			}
			LiveAttackPlan liveAttackPlan = ((primaryRule || presetFields()) ? LiveAttackPlan.Primary : LiveAttackPlan.None);
			if (givenSecondary)
			{
				liveAttackPlan |= LiveAttackPlan.CopySecondary;
			}
			else if (secondaryRule && !skipSecondary)
			{
				liveAttackPlan |= LiveAttackPlan.OverrideSecondary;
			}
			return liveAttackPlan;
		}
	}
	public enum AttackField
	{
		Stamina,
		Eitr,
		Health,
		Force,
		Stagger,
		Range,
		Velocity,
		Accuracy,
		DrawMin,
		DrawStamina,
		Reload
	}
	public sealed class AttackBlock
	{
		private readonly float?[] _values = new float?[AttackOverrideRules.Fields.Length];

		public bool IsEmpty
		{
			get
			{
				float?[] values = _values;
				foreach (float? num in values)
				{
					if (num.HasValue)
					{
						return false;
					}
				}
				return true;
			}
		}

		public float? Get(AttackField field)
		{
			return _values[(int)field];
		}

		public void Set(AttackField field, float? value)
		{
			_values[(int)field] = value;
		}
	}
	public sealed class AttackRule
	{
		public float? Damage;

		public readonly AttackBlock Primary = new AttackBlock();

		public readonly AttackBlock Secondary = new AttackBlock();

		public bool IsEmpty
		{
			get
			{
				if (!Damage.HasValue && Primary.IsEmpty)
				{
					return Secondary.IsEmpty;
				}
				return false;
			}
		}
	}
	public sealed class AttackFile
	{
		public readonly Dictionary<string, AttackRule> Rules = new Dictionary<string, AttackRule>(StringComparer.OrdinalIgnoreCase);

		public int Ignored;

		public string FirstIgnored;

		public string Error;

		internal void Ignore(string what)
		{
			Ignored++;
			if (FirstIgnored == null)
			{
				FirstIgnored = what;
			}
		}
	}
	public static class AttackOverrideRules
	{
		private sealed class Reader
		{
			private readonly string _s;

			private int _i;

			private int _depth;

			public Reader(string s)
			{
				_s = s;
			}

			public object Document()
			{
				object result = Value();
				Space();
				if (_i < _s.Length)
				{
					throw new FormatException("trailing text at " + _i);
				}
				return result;
			}

			private void Space()
			{
				while (_i < _s.Length && (_s[_i] == ' ' || _s[_i] == '\t' || _s[_i] == '\n' || _s[_i] == '\r'))
				{
					_i++;
				}
			}

			private char Take()
			{
				if (_i >= _s.Length)
				{
					throw new FormatException("unexpected end");
				}
				return _s[_i++];
			}

			private object Value()
			{
				Space();
				if (_i >= _s.Length)
				{
					throw new FormatException("unexpected end");
				}
				char c = _s[_i];
				switch (c)
				{
				case '[':
				case '{':
				{
					if (++_depth > 6)
					{
						throw new FormatException("nested deeper than " + 6);
					}
					ICollection result = ((c == '{') ? ((ICollection)Map()) : ((ICollection)List()));
					_depth--;
					return result;
				}
				case '"':
					return Text();
				default:
					if (Word("true"))
					{
						return true;
					}
					if (Word("false"))
					{
						return false;
					}
					if (Word("null"))
					{
						return null;
					}
					return Number();
				}
			}

			private bool Word(string w)
			{
				if (string.CompareOrdinal(_s, _i, w, 0, w.Length) != 0)
				{
					return false;
				}
				_i += w.Length;
				return true;
			}

			private Dictionary<string, object> Map()
			{
				_i++;
				Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.Ordinal);
				Space();
				if (_i < _s.Length && _s[_i] == '}')
				{
					_i++;
					return dictionary;
				}
				while (true)
				{
					Space();
					if (_i >= _s.Length || _s[_i] != '"')
					{
						throw new FormatException("expected a key at " + _i);
					}
					string key = Text();
					if (dictionary.ContainsKey(key))
					{
						throw new FormatException("repeated key at " + _i);
					}
					Space();
					if (Take() != ':')
					{
						break;
					}
					dictionary[key] = Value();
					Space();
					switch (Take())
					{
					case ',':
						break;
					case '}':
						return dictionary;
					default:
						throw new FormatException("expected ',' or '}' at " + _i);
					}
				}
				throw new FormatException("expected ':' at " + _i);
			}

			private List<object> List()
			{
				_i++;
				List<object> list = new List<object>();
				Space();
				if (_i < _s.Length && _s[_i] == ']')
				{
					_i++;
					return list;
				}
				while (true)
				{
					list.Add(Value());
					Space();
					switch (Take())
					{
					case ',':
						break;
					case ']':
						return list;
					default:
						throw new FormatException("expected ',' or ']' at " + _i);
					}
				}
			}

			private string Text()
			{
				_i++;
				StringBuilder stringBuilder = new StringBuilder();
				while (true)
				{
					char c = Take();
					if (c == '"')
					{
						return stringBuilder.ToString();
					}
					if (c < ' ')
					{
						break;
					}
					if (c != '\\')
					{
						stringBuilder.Append(c);
						continue;
					}
					char c2 = Take();
					switch (c2)
					{
					case 'u':
					{
						int num = 0;
						for (int i = 0; i < 4; i++)
						{
							int num2 = ((_i < _s.Length) ? Hex(_s[_i]) : (-1));
							if (num2 < 0)
							{
								throw new FormatException("bad escape at " + _i);
							}
							num = num * 16 + num2;
							_i++;
						}
						stringBuilder.Append((char)num);
						break;
					}
					case '"':
					case '/':
					case '\\':
						stringBuilder.Append(c2);
						break;
					case 'n':
						stringBuilder.Append('\n');
						break;
					case 't':
						stringBuilder.Append('\t');
						break;
					case 'r':
						stringBuilder.Append('\r');
						break;
					case 'b':
						stringBuilder.Append('\b');
						break;
					case 'f':
						stringBuilder.Append('\f');
						break;
					default:
						throw new FormatException("bad escape at " + (_i - 1));
					}
				}
				throw new FormatException("control character in text at " + (_i - 1));
			}

			private static int Hex(char c)
			{
				if (c < '0' || c > '9')
				{
					if (c < 'a' || c > 'f')
					{
						if (c < 'A' || c > 'F')
						{
							return -1;
						}
						return c - 65 + 10;
					}
					return c - 97 + 10;
				}
				return c - 48;
			}

			private bool Digit()
			{
				if (_i < _s.Length && _s[_i] >= '0')
				{
					return _s[_i] <= '9';
				}
				return false;
			}

			private int Digits()
			{
				int i = _i;
				while (Digit())
				{
					_i++;
				}
				return _i - i;
			}

			private double Number()
			{
				int i = _i;
				if (_i < _s.Length && _s[_i] == '-')
				{
					_i++;
				}
				if (_i < _s.Length && _s[_i] == '0')
				{
					_i++;
					if (Digit())
					{
						throw new FormatException("bad value at " + i);
					}
				}
				else if (Digits() == 0)
				{
					throw new FormatException("bad value at " + i);
				}
				if (_i < _s.Length && _s[_i] == '.')
				{
					_i++;
					if (Digits() == 0)
					{
						throw new FormatException("bad value at " + i);
					}
				}
				if (_i < _s.Length && (_s[_i] == 'e' || _s[_i] == 'E'))
				{
					_i++;
					if (_i < _s.Length && (_s[_i] == '+' || _s[_i] == '-'))
					{
						_i++;
					}
					if (Digits() == 0)
					{
						throw new FormatException("bad value at " + i);
					}
				}
				if (!double.TryParse(_s.Substring(i, _i - i), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					return double.NaN;
				}
				return result;
			}
		}

		public const int MaxItems = 128;

		public const int MaxName = 64;

		public const int MaxDepth = 6;

		public const int MaxPacked = 16384;

		public const int MaxInput = 262144;

		public const int Version = 1;

		public const float DamageMin = 0.1f;

		public const float DamageMax = 5f;

		public const string FileName = "attacks.json";

		public static readonly AttackField[] Fields = new AttackField[11]
		{
			AttackField.Stamina,
			AttackField.Eitr,
			AttackField.Health,
			AttackField.Force,
			AttackField.Stagger,
			AttackField.Range,
			AttackField.Velocity,
			AttackField.Accuracy,
			AttackField.DrawMin,
			AttackField.DrawStamina,
			AttackField.Reload
		};

		public static string Key(AttackField field)
		{
			return field switch
			{
				AttackField.Stamina => "stamina", 
				AttackField.Eitr => "eitr", 
				AttackField.Health => "health", 
				AttackField.Force => "force", 
				AttackField.Stagger => "stagger", 
				AttackField.Range => "range", 
				AttackField.Velocity => "velocity", 
				AttackField.Accuracy => "accuracy", 
				AttackField.DrawMin => "drawMin", 
				AttackField.DrawStamina => "drawStamina", 
				_ => "reload", 
			};
		}

		public static float Min(AttackField field)
		{
			switch (field)
			{
			case AttackField.Range:
				return 0.5f;
			case AttackField.Velocity:
			case AttackField.DrawMin:
			case AttackField.Reload:
				return 0.25f;
			default:
				return 0f;
			}
		}

		public static float Max(AttackField field)
		{
			switch (field)
			{
			case AttackField.Force:
			case AttackField.Stagger:
				return 5f;
			case AttackField.Range:
				return 2f;
			case AttackField.Velocity:
			case AttackField.Accuracy:
			case AttackField.DrawMin:
			case AttackField.Reload:
				return 3f;
			default:
				return 4f;
			}
		}

		public static float Clamp(AttackField field, float factor)
		{
			if (!float.IsNaN(factor) && !float.IsInfinity(factor))
			{
				return Math.Max(Min(field), Math.Min(Max(field), factor));
			}
			return 1f;
		}

		public static float ClampDamage(float factor)
		{
			if (!float.IsNaN(factor) && !float.IsInfinity(factor))
			{
				return Math.Max(0.1f, Math.Min(5f, factor));
			}
			return 1f;
		}

		public static float DamageFactor(float? file, float preset)
		{
			return ClampDamage(file ?? preset);
		}

		public static float FieldFactor(AttackField field, AttackBlock block, float preset)
		{
			return Clamp(field, block?.Get(field) ?? preset);
		}

		public static float Scale(float live, float factor)
		{
			if (!float.IsNaN(live) && !float.IsInfinity(live))
			{
				if (live != 0f)
				{
					return live * factor;
				}
				return 0f;
			}
			return live;
		}

		public static bool ChangesDamage(float factor)
		{
			if (!float.IsNaN(factor))
			{
				return Math.Abs(factor - 1f) > 1E-06f;
			}
			return false;
		}

		public static bool Applies(bool ammo, bool fileRule, bool presetFamily, bool craftable)
		{
			if (!ammo)
			{
				if (!fileRule)
				{
					return presetFamily && craftable;
				}
				return true;
			}
			return false;
		}

		public static bool ApplySecondary(bool native, bool supplied, bool charge, bool chargeFamily)
		{
			if (native && !supplied && !charge)
			{
				return !chargeFamily;
			}
			return false;
		}

		public static int UnknownCount(IEnumerable<string> names, ISet<string> seen)
		{
			int num = 0;
			foreach (string name in names)
			{
				if (!seen.Contains(name))
				{
					num++;
				}
			}
			return num;
		}

		public static string CleanName(string name)
		{
			if (string.IsNullOrEmpty(name) || name.Length > 64)
			{
				return null;
			}
			foreach (char c in name)
			{
				if (!char.IsLetterOrDigit(c) && c != '_' && c != '-')
				{
					return null;
				}
			}
			return name;
		}

		public static bool FileTooLarge(long bytes)
		{
			return bytes > 262144;
		}

		public static bool PackedFits(int length)
		{
			return length <= 16384;
		}

		public static string Summary(AttackFile file)
		{
			if (file != null && file.Ignored != 0)
			{
				return file.Ignored + ((file.Ignored == 1) ? " entry was" : " entries were") + " ignored (first: " + file.FirstIgnored + ")";
			}
			return null;
		}

		public static string Packed(long fileBytes, Func<string> read, out string error)
		{
			string note;
			return Packed(fileBytes, read, out error, out note);
		}

		public static string Packed(long fileBytes, Func<string> read, out string error, out string note)
		{
			error = null;
			note = null;
			if (FileTooLarge(fileBytes))
			{
				error = "larger than " + 262144 + " bytes";
				return "";
			}
			if (!TryParse(read(), out var file))
			{
				error = file.Error;
				return "";
			}
			note = Summary(file);
			if (file.Rules.Count == 0)
			{
				return "";
			}
			string text = Serialize(file.Rules, pretty: false);
			if (PackedFits(text.Length))
			{
				return text;
			}
			error = "too large to sync";
			note = null;
			return "";
		}

		public static bool TryParse(string json, out AttackFile file)
		{
			file = new AttackFile();
			if (string.IsNullOrEmpty(json))
			{
				return true;
			}
			if (json.Length > 262144)
			{
				file.Error = "attack overrides are larger than " + 262144 + " characters";
				return false;
			}
			object obj;
			try
			{
				obj = new Reader(json).Document();
			}
			catch (FormatException ex)
			{
				file.Error = ex.Message;
				return false;
			}
			if (!(obj is Dictionary<string, object> dictionary))
			{
				file.Error = "attack overrides are not a JSON object";
				return false;
			}
			foreach (KeyValuePair<string, object> item in dictionary)
			{
				if (item.Key == "version")
				{
					if (!(item.Value is double num) || num != 1.0)
					{
						file.Error = "unsupported version";
						return false;
					}
				}
				else if (item.Key == "items")
				{
					Items(item.Value, file);
				}
				else
				{
					file.Ignore(item.Key);
				}
			}
			return true;
		}

		private static void Items(object value, AttackFile file)
		{
			if (!(value is Dictionary<string, object> dictionary))
			{
				file.Ignore("items");
				return;
			}
			foreach (KeyValuePair<string, object> item in dictionary)
			{
				string text = CleanName(item.Key);
				if (text == null || !(item.Value is Dictionary<string, object> dictionary2))
				{
					file.Ignore(item.Key);
					continue;
				}
				if (file.Rules.ContainsKey(text) || file.Rules.Count >= 128)
				{
					file.Ignore(text);
					continue;
				}
				AttackRule attackRule = new AttackRule();
				foreach (KeyValuePair<string, object> item2 in dictionary2)
				{
					if (item2.Key == "damage")
					{
						if (Number(item2.Value, out var number))
						{
							attackRule.Damage = (float)Math.Max(0.10000000149011612, Math.Min(5.0, number));
						}
						else
						{
							file.Ignore(text + ".damage");
						}
					}
					else if (item2.Key == "primary")
					{
						Block(item2.Value, attackRule.Primary, text + ".primary", file);
					}
					else if (item2.Key == "secondary")
					{
						Block(item2.Value, attackRule.Secondary, text + ".secondary", file);
					}
					else
					{
						file.Ignore(text + "." + item2.Key);
					}
				}
				if (!attackRule.IsEmpty)
				{
					file.Rules[text] = attackRule;
				}
			}
		}

		private static void Block(object value, AttackBlock block, string where, AttackFile file)
		{
			if (!(value is Dictionary<string, object> dictionary))
			{
				file.Ignore(where);
				return;
			}
			foreach (KeyValuePair<string, object> item in dictionary)
			{
				bool flag = false;
				AttackField[] fields = Fields;
				foreach (AttackField field in fields)
				{
					if (!(Key(field) != item.Key))
					{
						flag = true;
						if (Number(item.Value, out var number))
						{
							block.Set(field, (float)Math.Max(Min(field), Math.Min(Max(field), number)));
						}
						else
						{
							file.Ignore(where + "." + item.Key);
						}
					}
				}
				if (!flag)
				{
					file.Ignore(where + "." + item.Key);
				}
			}
		}

		private static bool Number(object value, out double number)
		{
			number = 0.0;
			if (!(value is double num) || double.IsNaN(num) || double.IsInfinity(num))
			{
				return false;
			}
			number = num;
			return true;
		}

		public static string Serialize(Dictionary<string, AttackRule> rules, bool pretty)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string text = (pretty ? "\n" : "");
			string text2 = (pretty ? "  " : "");
			stringBuilder.Append('{').Append(text).Append(text2)
				.Append("\"version\":")
				.Append(1.ToString(CultureInfo.InvariantCulture));
			stringBuilder.Append(',').Append(text).Append(text2)
				.Append("\"items\":{");
			bool flag = true;
			foreach (KeyValuePair<string, AttackRule> rule in rules)
			{
				if (rule.Value != null && !rule.Value.IsEmpty)
				{
					stringBuilder.Append(flag ? "" : ",").Append(text).Append(text2)
						.Append(text2)
						.Append(Quote(rule.Key))
						.Append(':')
						.Append('{');
					flag = false;
					AttackRule value = rule.Value;
					bool any = false;
					if (value.Damage.HasValue)
					{
						stringBuilder.Append("\"damage\":").Append(Num(value.Damage.Value));
						any = true;
					}
					any = Append(stringBuilder, "primary", value.Primary, any);
					Append(stringBuilder, "secondary", value.Secondary, any);
					stringBuilder.Append('}');
				}
			}
			stringBuilder.Append(flag ? "" : (text + text2)).Append('}').Append(text)
				.Append('}');
			return stringBuilder.ToString();
		}

		private static bool Append(StringBuilder b, string name, AttackBlock block, bool any)
		{
			if (block.IsEmpty)
			{
				return any;
			}
			b.Append(any ? "," : "").Append('"').Append(name)
				.Append("\":{");
			bool flag = true;
			AttackField[] fields = Fields;
			foreach (AttackField field in fields)
			{
				float? num = block.Get(field);
				if (num.HasValue)
				{
					b.Append(flag ? "" : ",").Append('"').Append(Key(field))
						.Append("\":")
						.Append(Num(num.Value));
					flag = false;
				}
			}
			b.Append('}');
			return true;
		}

		private static string Num(float v)
		{
			return v.ToString("R", CultureInfo.InvariantCulture);
		}

		public static string Example()
		{
			Dictionary<string, AttackRule> dictionary = new Dictionary<string, AttackRule>(StringComparer.OrdinalIgnoreCase);
			AttackRule attackRule = new AttackRule
			{
				Damage = 1f
			};
			AttackField[] array = new AttackField[3]
			{
				AttackField.Stamina,
				AttackField.Force,
				AttackField.Stagger
			};
			foreach (AttackField field in array)
			{
				attackRule.Primary.Set(field, 1f);
			}
			attackRule.Secondary.Set(AttackField.Stamina, 1f);
			dictionary["MaceIron"] = attackRule;
			return Serialize(dictionary, pretty: true);
		}

		private static string Quote(string s)
		{
			StringBuilder stringBuilder = new StringBuilder("\"");
			foreach (char c in s)
			{
				if (c == '"' || c == '\\')
				{
					stringBuilder.Append('\\').Append(c);
				}
				else if (c < ' ')
				{
					StringBuilder stringBuilder2 = stringBuilder.Append("\\u");
					int num = c;
					stringBuilder2.Append(num.ToString("x4", CultureInfo.InvariantCulture));
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.Append('"').ToString();
		}
	}
	internal static class AttackOverrides
	{
		private struct LiveBlock
		{
			public AttackBlock Block;

			public AttackPreset Preset;
		}

		internal sealed class Runner : MonoBehaviour
		{
			private float _timer;

			private void Update()
			{
				_timer += Time.unscaledDeltaTime;
				if (!(_timer < 1f))
				{
					_timer = 0f;
					SafeRegister.Run("AttackOverrides.Tick", (Action)Tick);
				}
			}
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(ItemDrop), "Awake")]
			[HarmonyPostfix]
			private static void ItemAwake(ItemDrop __instance)
			{
				if (_liveWork)
				{
					ObserveSafely("AttackOverrides.ItemAwake", __instance.m_itemData);
				}
			}

			[HarmonyPatch(typeof(Inventory), "Changed")]
			[HarmonyPostfix]
			private static void InventoryChanged(Inventory __instance)
			{
				if (!_liveWork)
				{
					return;
				}
				try
				{
					foreach (ItemData allItem in __instance.GetAllItems())
					{
						Observe(allItem);
					}
				}
				catch (Exception ex)
				{
					MwLog.WarnOnce("AttackOverrides.InventoryChanged", (object)ex.ToString());
				}
			}

			[HarmonyPatch(typeof(Humanoid), "EquipItem")]
			[HarmonyPrefix]
			private static void Equip(ItemData item)
			{
				if (_liveWork)
				{
					ObserveSafely("AttackOverrides.Equip", item);
				}
			}

			[HarmonyPatch(typeof(ZNet), "Awake")]
			[HarmonyPostfix]
			private static void WorldStart(ZNet __instance)
			{
				if ((Object)(object)__instance != (Object)null && __instance.IsServer())
				{
					ReloadLocal();
				}
			}

			[HarmonyPatch(typeof(Projectile), "Setup")]
			[HarmonyPostfix]
			private static void ProjectileSetup(Projectile __instance, ItemData item)
			{
				__instance.m_aoe = BlastRadius(__instance, __instance.m_aoe, item);
			}

			[HarmonyPatch(typeof(Aoe), "Setup")]
			[HarmonyPostfix]
			private static void AoeSetup(Aoe __instance, ItemData item)
			{
				__instance.m_radius = BlastRadius(__instance, __instance.m_radius, item);
			}

			[HarmonyPatch(typeof(ItemData), "GetDamage", new Type[]
			{
				typeof(int),
				typeof(float)
			})]
			[HarmonyPostfix]
			[HarmonyPriority(400)]
			private static void GetDamage(ItemData __instance, ref DamageTypes __result)
			{
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0025: Invalid comparison between Unknown and I4
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Invalid comparison between Unknown and I4
				if (DamageFactors.Count != 0 && __instance != null && __instance.m_shared != null && (int)__instance.m_shared.m_itemType != 9 && (int)__instance.m_shared.m_itemType != 23 && DamageFactors.TryGet(__instance.m_shared, __instance.m_dropPrefab, out var factor))
				{
					((DamageTypes)(ref __result)).Modify(factor);
				}
			}
		}

		private static Setting<bool> _on;

		private static Setting<string> _bow;

		private static Setting<string> _crossbow;

		private static Setting<string> _bomb;

		private static string _signaturePresets;

		private static AttackRadiusTable<object> Radii = new AttackRadiusTable<object>();

		private static Setting<string> _data;

		private static readonly AttackOverridePayload Payload = new AttackOverridePayload();

		private static string _signatureText;

		private static bool _signatureOn;

		private static int _signatureItems = -1;

		private static int _signatureRecipes = -1;

		private static ObjectDB _signatureDb;

		private static Dictionary<string, AttackRule> _active = new Dictionary<string, AttackRule>(StringComparer.OrdinalIgnoreCase);

		private static readonly AttackDamageTable<SharedData, GameObject> DamageFactors = new AttackDamageTable<SharedData, GameObject>();

		private static readonly AppliedAttackTable<SharedData, Attack> Primary = new AppliedAttackTable<SharedData, Attack>();

		private static readonly AppliedAttackTable<SharedData, Attack> Secondary = new AppliedAttackTable<SharedData, Attack>();

		private static readonly HashSet<GameObject> CraftablePrefabs = new HashSet<GameObject>();

		private static readonly HashSet<SharedData> CraftableShared = new HashSet<SharedData>();

		private static ConditionalWeakTable<SharedData, AttackPreset> Presets = new ConditionalWeakTable<SharedData, AttackPreset>();

		private static bool _refreshing;

		private static bool _liveWork;

		private static int _pruneAt = 64;

		private static int _unknown;

		private static readonly List<WeakReference<ItemData>> Live = new List<WeakReference<ItemData>>();

		private static LiveAttackChecks<ItemData> Tracked = new LiveAttackChecks<ItemData>();

		private static readonly Func<bool> NoPresetFields = () => false;

		private static readonly Func<bool> HasPresetFields = () => true;

		private static string PresetSignature => (_bow?.Value ?? "Vanilla") + "/" + (_crossbow?.Value ?? "Vanilla") + "/" + (_bomb?.Value ?? "Vanilla");

		public static bool Enabled
		{
			get
			{
				if (!TranspileGuard.Off(typeof(AttackOverrides)) && _on != null)
				{
					return _on.Value;
				}
				return false;
			}
		}

		public static int DamageRuleCount => DamageFactors.Count;

		public static string Folder => Path.Combine(Paths.ConfigPath, "MeadWorks", "equipment");

		private static bool IsClient
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return !ZNet.instance.IsServer();
				}
				return false;
			}
		}

		internal static IEnumerable<KeyValuePair<string, AttackRule>> ActiveRules => _active;

		internal static bool FileServerInEffect
		{
			get
			{
				if (_data != null)
				{
					return ((Setting)_data).ServerInEffect;
				}
				return false;
			}
		}

		public static void Init(SettingsPage page)
		{
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Expected O, but got Unknown
			_bow = page.Choice("bow_preset", "Bow preset", "Vanilla", AttackPresetRules.Names, (SettingPolicy)1, true);
			_crossbow = page.Choice("crossbow_preset", "Crossbow preset", "Vanilla", AttackPresetRules.Names, (SettingPolicy)1, true);
			_bomb = page.Choice("bomb_preset", "Bomb preset", "Vanilla", AttackPresetRules.Names, (SettingPolicy)1, true);
			((Setting)_bow).Changed += Rebuild;
			((Setting)_crossbow).Changed += Rebuild;
			((Setting)_bomb).Changed += Rebuild;
			_on = page.Toggle("attack_overrides", "Attack overrides", true, (SettingPolicy)1, true);
			_data = page.Text("attack_overrides_data", "Attack overrides data (synced)", "", (SettingPolicy)1, true);
			page.Hide((Setting)(object)_data);
			((Setting)_on).Changed += Rebuild;
			((Setting)_data).Changed += DataChanged;
			TranspileGuard.PatchAll(new Harmony("expdare.meadworks.equipment.attackoverrides"), typeof(Patches), "equipment attack overrides");
			Ledger.Add("equipment attack overrides state", (Action)delegate
			{
				if (_on != null)
				{
					((Setting)_on).Changed -= Rebuild;
				}
				if (_data != null)
				{
					((Setting)_data).Changed -= DataChanged;
				}
				((Setting)_bow).Changed -= Rebuild;
				((Setting)_crossbow).Changed -= Rebuild;
				((Setting)_bomb).Changed -= Rebuild;
				_bow = (_crossbow = (_bomb = null));
				Radii = new AttackRadiusTable<object>();
				_signaturePresets = null;
				RevertAll();
				_liveWork = false;
				Live.Clear();
				Tracked = new LiveAttackChecks<ItemData>();
				SecondaryAttacks.RefreshAttacks();
				_on = null;
				_data = null;
				Payload.Load("");
				_signatureText = null;
				_signatureItems = -1;
				_signatureDb = null;
				_active = new Dictionary<string, AttackRule>(StringComparer.OrdinalIgnoreCase);
				DamageFactors.Clear();
				CraftablePrefabs.Clear();
				CraftableShared.Clear();
				Presets = new ConditionalWeakTable<SharedData, AttackPreset>();
			});
		}

		private static void ReloadLocal()
		{
			Payload.Load("");
			string file = Path.Combine(Folder, "attacks.json");
			try
			{
				Directory.CreateDirectory(Folder);
				if (!File.Exists(file))
				{
					File.WriteAllText(file, AttackOverrideRules.Example());
				}
				Payload.Load(AttackOverrideRules.Packed(new FileInfo(file).Length, () => File.ReadAllText(file), out var error, out var note));
				if (error != null)
				{
					MwLog.WarnOnce("equipment attack overrides", (object)("attack overrides " + file + " are not usable (" + error + "); using family presets without file rules"));
				}
				else if (note != null)
				{
					MwLog.WarnOnce("equipment attack overrides", (object)("attack overrides " + file + ": " + note));
				}
			}
			catch (Exception ex)
			{
				MwLog.WarnOnce("equipment attack overrides", (object)("attack overrides could not be read: " + ex.Message + "; using family presets without file rules"));
			}
			DataChanged();
		}

		private static void DataChanged()
		{
			AttackOverridePayload payload = Payload;
			bool client = IsClient || _data == null;
			Setting<string> data = _data;
			payload.Handle(client, (data != null) ? ((Setting)data).LocalText : null, delegate(string value)
			{
				string text = default(string);
				_data.TrySetLocal(value, ref text);
			}, Rebuild);
		}

		internal static Attack DonorPrimary(SharedData target, SharedData donor)
		{
			return Primary.Donor(target, donor, donor.m_attack);
		}

		internal static Attack OriginalPrimary(SharedData shared)
		{
			return Primary.Original(shared, shared.m_attack);
		}

		internal static Setting<string> PresetSetting(PresetFamily family)
		{
			return (Setting<string>)(family switch
			{
				PresetFamily.Crossbow => _crossbow, 
				PresetFamily.Bow => _bow, 
				_ => _bomb, 
			});
		}

		internal static PresetFamily Family(ItemData item)
		{
			return Preset(item).Family;
		}

		internal static bool HasLiveSecondary(ItemData item)
		{
			return Secondary.Owns(item.m_shared, item.m_shared.m_secondaryAttack);
		}

		private static string CurrentText()
		{
			return Payload.Effective(IsClient, (_data != null && ((Setting)_data).ServerHasValue) ? _data.Value : null);
		}

		internal static void Tick()
		{
			ObjectDB instance = ObjectDB.instance;
			int num = (((Object)(object)instance != (Object)null && instance.m_items != null) ? instance.m_items.Count : 0);
			if (!(PresetSignature == _signaturePresets) || Enabled != _signatureOn || instance != _signatureDb || num != _signatureItems || (instance?.m_recipes?.Count).GetValueOrDefault() != _signatureRecipes || !string.Equals(CurrentText(), _signatureText, StringComparison.Ordinal))
			{
				Rebuild();
			}
		}

		private static void Rebuild()
		{
			Refresh();
		}

		internal static void Refresh()
		{
			if (TranspileGuard.Off(typeof(AttackOverrides)) || _refreshing)
			{
				return;
			}
			try
			{
				_refreshing = true;
				RevertAll();
				RebuildRules();
				ApplyAttacks(secondary: false);
				SecondaryAttacks.RefreshAttacks();
				ApplyAttacks(secondary: true);
				_liveWork = Primary.Count > 0 || Secondary.Count > 0 || SecondaryAttacks.HasSecondaryChanges;
				RefreshLive();
				CompendiumHost.Invalidate();
			}
			finally
			{
				_refreshing = false;
			}
		}

		private static void RevertAll()
		{
			Primary.Revert((SharedData shared) => shared.m_attack, delegate(SharedData shared, Attack attack)
			{
				shared.m_attack = attack;
			});
			Secondary.Revert((SharedData shared) => shared.m_secondaryAttack, delegate(SharedData shared, Attack attack)
			{
				shared.m_secondaryAttack = attack;
			});
		}

		private static void RebuildRules()
		{
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Invalid comparison between Unknown and I4
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Invalid comparison between Unknown and I4
			ObjectDB instance = ObjectDB.instance;
			string text = CurrentText();
			_signatureOn = Enabled;
			_signaturePresets = PresetSignature;
			_signatureRecipes = (instance?.m_recipes?.Count).GetValueOrDefault();
			_signatureText = text;
			_signatureDb = instance;
			_signatureItems = (((Object)(object)instance != (Object)null && instance.m_items != null) ? instance.m_items.Count : 0);
			Presets = new ConditionalWeakTable<SharedData, AttackPreset>();
			CraftablePrefabs.Clear();
			CraftableShared.Clear();
			if (instance?.m_recipes != null)
			{
				foreach (Recipe recipe in instance.m_recipes)
				{
					if ((Object)(object)recipe != (Object)null && (Object)(object)recipe.m_item != (Object)null && recipe.m_item.m_itemData?.m_shared != null)
					{
						CraftablePrefabs.Add(((Component)recipe.m_item).gameObject);
						CraftableShared.Add(recipe.m_item.m_itemData.m_shared);
					}
				}
			}
			DamageFactors.Clear();
			_unknown = 0;
			_active = new Dictionary<string, AttackRule>(StringComparer.OrdinalIgnoreCase);
			if ((Object)(object)instance == (Object)null || _signatureItems == 0)
			{
				return;
			}
			if (_signatureOn && !string.IsNullOrEmpty(text) && AttackOverrideRules.PackedFits(text.Length) && AttackOverrideRules.TryParse(text, out var file))
			{
				_active = file.Rules;
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (GameObject item in instance.m_items)
			{
				ItemDrop val = (((Object)(object)item == (Object)null) ? null : item.GetComponent<ItemDrop>());
				SharedData val2 = (((Object)(object)val != (Object)null && val.m_itemData != null) ? val.m_itemData.m_shared : null);
				if (val2 == null)
				{
					continue;
				}
				_active.TryGetValue(((Object)item).name, out var value);
				AttackPreset attackPreset = Preset(val.m_itemData);
				if (value != null)
				{
					hashSet.Add(((Object)item).name);
				}
				if (AttackOverrideRules.Applies((int)val2.m_itemType == 9 || (int)val2.m_itemType == 23, fileRule: true, presetFamily: false, craftable: false))
				{
					float factor = AttackOverrideRules.DamageFactor(value?.Damage, attackPreset.Damage);
					if (AttackOverrideRules.ChangesDamage(factor))
					{
						DamageFactors.Set(val2, item, factor);
					}
				}
			}
			_unknown = AttackOverrideRules.UnknownCount(_active.Keys, hashSet);
			if (_unknown > 0)
			{
				MwLog.WarnOnce("equipment attack overrides unknown", (object)("attack overrides: " + _unknown + " unknown prefab names ignored"));
			}
		}

		private static AttackPreset Preset(ItemData item)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected I4, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Invalid comparison between Unknown and I4
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Invalid comparison between Unknown and I4
			SharedData val = item?.m_shared;
			ObjectDB instance = ObjectDB.instance;
			if (val == null || (Object)(object)instance == (Object)null)
			{
				return AttackPresetRules.Get(PresetFamily.None, "Vanilla");
			}
			if (Presets.TryGetValue(val, out var value))
			{
				return value;
			}
			GameObject val2 = val.m_attack?.m_attackProjectile;
			Projectile val3 = (((Object)(object)val2 != (Object)null) ? val2.GetComponent<Projectile>() : null);
			WeaponFamily family = SecondaryAttacks.GetFamily(item);
			bool flag = (Object)(object)val3 != (Object)null && AttackPresetRules.BombProjectile((int)val3.m_type);
			GameObject dropPrefab = item.m_dropPrefab;
			bool craftable = (family == WeaponFamily.Bow || family == WeaponFamily.Crossbow || flag) && (((Object)(object)dropPrefab != (Object)null) ? CraftablePrefabs.Contains(dropPrefab) : CraftableShared.Contains(val));
			PresetFamily presetFamily = AttackPresetRules.Category(family, craftable, (int)val.m_itemType == 9 || (int)val.m_itemType == 23, flag, ((object)Unsafe.As<SkillType, SkillType>(ref val.m_skillType)/*cast due to .constrained prefix*/).ToString(), ((Object)(object)dropPrefab != (Object)null) ? ((Object)dropPrefab).name : null);
			string name = presetFamily switch
			{
				PresetFamily.Crossbow => _crossbow?.Value, 
				PresetFamily.Bow => _bow?.Value, 
				_ => _bomb?.Value, 
			};
			AttackPreset attackPreset = AttackPresetRules.Effective(Enabled, presetFamily, name);
			Presets.Add(val, attackPreset);
			return attackPreset;
		}

		private static float BlastRadius(object instance, float radius, ItemData item)
		{
			AttackPreset attackPreset = Preset(item);
			return Radii.Apply(instance, radius, (attackPreset.Family == PresetFamily.Bomb) ? attackPreset.Blast : 1f);
		}

		private static bool SkipSecondary(ItemData item)
		{
			Attack secondaryAttack = item.m_shared.m_secondaryAttack;
			return !AttackOverrideRules.ApplySecondary(secondaryAttack != null && !string.IsNullOrEmpty(secondaryAttack.m_attackAnimation), SecondaryAttacks.HasApplied(item.m_shared), SecondaryAttacks.HasCharge(item), MoveRules.Charges(SecondaryAttacks.GetFamily(item)));
		}

		private static void ApplyAttacks(bool secondary)
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Invalid comparison between Unknown and I4
			ObjectDB instance = ObjectDB.instance;
			if ((Object)(object)instance == (Object)null || instance.m_items == null)
			{
				return;
			}
			foreach (GameObject item in instance.m_items)
			{
				ItemDrop val = (((Object)(object)item == (Object)null) ? null : item.GetComponent<ItemDrop>());
				ItemData val2 = (((Object)(object)val == (Object)null) ? null : val.m_itemData);
				SharedData val3 = val2?.m_shared;
				if (val3 == null)
				{
					continue;
				}
				_active.TryGetValue(((Object)item).name, out var value);
				AttackPreset preset = (secondary ? AttackPresetRules.Get(PresetFamily.None, "Vanilla") : Preset(val2));
				if (!AttackOverrideRules.Applies((int)val3.m_itemType == 9 || (int)val3.m_itemType == 23, fileRule: true, presetFamily: false, craftable: false))
				{
					continue;
				}
				AttackBlock block = ((!secondary) ? value?.Primary : value?.Secondary);
				if (((block == null || block.IsEmpty) && (secondary || preset.Fields.IsEmpty)) || (secondary && SkipSecondary(val2)))
				{
					continue;
				}
				if (secondary)
				{
					val3.m_secondaryAttack = Secondary.Apply(val3, val3.m_secondaryAttack, (Attack attack) => ApplyBlock(attack, block, AttackPresetRules.Get(PresetFamily.None, "Vanilla")));
				}
				else
				{
					val3.m_attack = Primary.Apply(val3, val3.m_attack, (Attack attack) => ApplyBlock(attack, block, preset));
				}
			}
		}

		private static void ObserveSafely(string context, ItemData item)
		{
			SafeRegister.Run(context, (Action)delegate
			{
				Observe(item);
			});
		}

		private static void Observe(ItemData item)
		{
			if (_liveWork && item?.m_shared != null && !((Object)(object)item.m_dropPrefab == (Object)null) && Tracked.Begin(item) && ApplyLive(item) && Tracked.TrackApplied(item))
			{
				Live.Add(new WeakReference<ItemData>(item));
				if (Live.Count >= _pruneAt)
				{
					PruneLive();
				}
			}
		}

		private static void PruneLive()
		{
			Live.RemoveAll((WeakReference<ItemData> reference) => !reference.TryGetTarget(out var _));
			_pruneAt = Math.Max(64, Live.Count * 2);
		}

		private static void RefreshLive()
		{
			PruneLive();
			Tracked.Refresh();
			if (!_liveWork)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				foreach (ItemData allItem in ((Humanoid)localPlayer).GetInventory().GetAllItems())
				{
					Observe(allItem);
				}
				Observe(((Humanoid)localPlayer).GetCurrentWeapon());
			}
			foreach (WeakReference<ItemData> item in Live)
			{
				if (item.TryGetTarget(out var target))
				{
					Observe(target);
				}
			}
		}

		private static Attack ApplyLiveBlock(Attack attack, LiveBlock state)
		{
			return ApplyBlock(attack, state.Block, state.Preset);
		}

		private static Attack CloneLiveSecondary(Attack original, Attack source)
		{
			return source.Clone();
		}

		private static bool ApplyLive(ItemData item)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Invalid comparison between Unknown and I4
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Invalid comparison between Unknown and I4
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Invalid comparison between Unknown and I4
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Invalid comparison between Unknown and I4
			if (!_liveWork)
			{
				return false;
			}
			SharedData shared = item.m_shared;
			if (shared.m_attack == null || string.IsNullOrEmpty(shared.m_attack.m_attackAnimation))
			{
				return false;
			}
			ItemData val = ((!((Object)(object)item.m_dropPrefab != (Object)null)) ? null : item.m_dropPrefab.GetComponent<ItemDrop>()?.m_itemData);
			if (val?.m_shared == null)
			{
				return false;
			}
			if (shared == val.m_shared || (int)shared.m_itemType == 9 || (int)shared.m_itemType == 23)
			{
				return false;
			}
			_active.TryGetValue(((Object)item.m_dropPrefab).name, out var value);
			AttackPreset attackPreset = Preset(val);
			LiveAttackPlan liveAttackPlan = AttackLiveRules.Plan(_liveWork, shared == val.m_shared, (int)shared.m_itemType == 9 || (int)shared.m_itemType == 23, weapon: true, value?.Primary != null && !value.Primary.IsEmpty, attackPreset.Fields.IsEmpty ? NoPresetFields : HasPresetFields, SecondaryAttacks.HasScaledSecondary(val.m_shared) && val.m_shared.m_secondaryAttack != null, value?.Secondary != null && !value.Secondary.IsEmpty, SkipSecondary(val));
			if ((liveAttackPlan & LiveAttackPlan.Primary) != LiveAttackPlan.None)
			{
				shared.m_attack = Primary.Apply(shared, shared.m_attack, ApplyLiveBlock, new LiveBlock
				{
					Block = value?.Primary,
					Preset = attackPreset
				}, OriginalPrimary(val.m_shared));
			}
			if ((liveAttackPlan & LiveAttackPlan.CopySecondary) != LiveAttackPlan.None)
			{
				shared.m_secondaryAttack = Secondary.Apply<Attack>(shared, shared.m_secondaryAttack ?? val.m_shared.m_secondaryAttack, CloneLiveSecondary, val.m_shared.m_secondaryAttack, SecondaryAttacks.Original(val.m_shared));
			}
			else if ((liveAttackPlan & LiveAttackPlan.OverrideSecondary) != LiveAttackPlan.None)
			{
				shared.m_secondaryAttack = Secondary.Apply(shared, shared.m_secondaryAttack, ApplyLiveBlock, new LiveBlock
				{
					Block = value.Secondary,
					Preset = AttackPresetRules.Get(PresetFamily.None, "Vanilla")
				}, Secondary.Original(val.m_shared, val.m_shared.m_secondaryAttack));
			}
			return liveAttackPlan != LiveAttackPlan.None;
		}

		private static Attack ApplyBlock(Attack original, AttackBlock block, AttackPreset preset)
		{
			Attack copy = original.Clone();
			AttackPresetRules.Apply(preset, block, delegate(AttackField field, float factor)
			{
				foreach (AttackMember item in AttackFieldMap.Members(field))
				{
					switch (item)
					{
					case AttackMember.AttackStamina:
						copy.m_attackStamina = AttackFieldMap.Scale(item, copy.m_attackStamina, factor);
						break;
					case AttackMember.AttackEitr:
						copy.m_attackEitr = AttackFieldMap.Scale(item, copy.m_attackEitr, factor);
						break;
					case AttackMember.AttackHealth:
						copy.m_attackHealth = AttackFieldMap.Scale(item, copy.m_attackHealth, factor);
						break;
					case AttackMember.ForceMultiplier:
						copy.m_forceMultiplier = AttackFieldMap.Scale(item, copy.m_forceMultiplier, factor);
						break;
					case AttackMember.StaggerMultiplier:
						copy.m_staggerMultiplier = AttackFieldMap.Scale(item, copy.m_staggerMultiplier, factor);
						break;
					case AttackMember.AttackRange:
						copy.m_attackRange = AttackFieldMap.Scale(item, copy.m_attackRange, factor);
						break;
					case AttackMember.ProjectileVel:
						copy.m_projectileVel = AttackFieldMap.Scale(item, copy.m_projectileVel, factor);
						break;
					case AttackMember.ProjectileVelMin:
						copy.m_projectileVelMin = AttackFieldMap.Scale(item, copy.m_projectileVelMin, factor);
						break;
					case AttackMember.ProjectileAccuracy:
						copy.m_projectileAccuracy = AttackFieldMap.Scale(item, copy.m_projectileAccuracy, factor);
						break;
					case AttackMember.ProjectileAccuracyMin:
						copy.m_projectileAccuracyMin = AttackFieldMap.Scale(item, copy.m_projectileAccuracyMin, factor);
						break;
					case AttackMember.DrawDurationMin:
						copy.m_drawDurationMin = AttackFieldMap.Scale(item, copy.m_drawDurationMin, factor);
						break;
					case AttackMember.DrawStaminaDrain:
						copy.m_drawStaminaDrain = AttackFieldMap.Scale(item, copy.m_drawStaminaDrain, factor);
						break;
					case AttackMember.ReloadTime:
						copy.m_reloadTime = AttackFieldMap.Scale(item, copy.m_reloadTime, factor);
						break;
					}
				}
			});
			return copy;
		}
	}
	public sealed class AttackDamageTable<TShared, TPrefab> where TShared : class where TPrefab : class
	{
		private readonly Dictionary<TShared, float> _shared = new Dictionary<TShared, float>();

		private readonly Dictionary<TPrefab, float> _prefabs = new Dictionary<TPrefab, float>();

		public int Count => _prefabs.Count;

		public void Clear()
		{
			_shared.Clear();
			_prefabs.Clear();
		}

		public void Set(TShared shared, TPrefab prefab, float factor)
		{
			_shared[shared] = factor;
			_prefabs[prefab] = factor;
		}

		public bool TryGet(TShared shared, TPrefab prefab, out float factor)
		{
			factor = 1f;
			if (shared == null || !_shared.TryGetValue(shared, out factor))
			{
				if (prefab != null)
				{
					return _prefabs.TryGetValue(prefab, out factor);
				}
				return false;
			}
			return true;
		}
	}
	public sealed class AttackOverridePayload
	{
		private string _file = "";

		private bool _repairing;

		public void Load(string packed)
		{
			_file = packed ?? "";
		}

		public string Effective(bool client, string received)
		{
			if (!client)
			{
				return _file;
			}
			return received ?? "";
		}

		public void Handle(bool client, string published, Action<string> write, Action rebuild)
		{
			if (!client)
			{
				Repair(published, write);
			}
			rebuild();
		}

		public void Repair(string published, Action<string> write)
		{
			if (_repairing || string.Equals(published, _file, StringComparison.Ordinal))
			{
				return;
			}
			try
			{
				_repairing = true;
				write(_file);
			}
			finally
			{
				_repairing = false;
			}
		}
	}
	public enum PresetFamily
	{
		None,
		Bow,
		Crossbow,
		Bomb
	}
	public sealed class AttackPreset
	{
		public readonly PresetFamily Family;

		public readonly string Name;

		public readonly float Damage;

		public readonly float Blast;

		public readonly AttackBlock Fields = new AttackBlock();

		public AttackPreset(PresetFamily family, string name, float damage = 1f, float blast = 1f)
		{
			Family = family;
			Name = name;
			Damage = damage;
			Blast = blast;
		}

		public float Factor(AttackField field)
		{
			return Fields.Get(field) ?? 1f;
		}
	}
	public static class AttackPresetRules
	{
		public static readonly string[] Names = new string[3] { "Vanilla", "Balanced", "Hardcore" };

		public static readonly IReadOnlyList<AttackPreset> Rows = Build();

		private static readonly AttackPreset Vanilla = new AttackPreset(PresetFamily.None, "Vanilla");

		private static IReadOnlyList<AttackPreset> Build()
		{
			return new List<AttackPreset>
			{
				new AttackPreset(PresetFamily.Bow, "Vanilla"),
				Row(PresetFamily.Bow, "Balanced", 1f, 0.85f, 0.9f, 1.15f, 0.85f, 1f),
				Row(PresetFamily.Bow, "Hardcore", 0.9f, 1.25f, 1.15f, 0.9f, 1.25f, 1f),
				new AttackPreset(PresetFamily.Crossbow, "Vanilla"),
				Row(PresetFamily.Crossbow, "Balanced", 1f, 0.85f, 0.85f, 1.1f, 0.85f, 1f),
				Row(PresetFamily.Crossbow, "Hardcore", 0.9f, 1.2f, 1.25f, 0.9f, 1.25f, 1f),
				new AttackPreset(PresetFamily.Bomb, "Vanilla"),
				Row(PresetFamily.Bomb, "Balanced", 1f, 0.85f, 1f, 1.1f, 0.85f, 1.15f),
				Row(PresetFamily.Bomb, "Hardcore", 1f, 1.25f, 1f, 0.9f, 1.25f, 0.85f)
			}.AsReadOnly();
		}

		private static AttackPreset Row(PresetFamily family, string name, float damage, float stamina, float time, float velocity, float spread, float blast)
		{
			AttackPreset attackPreset = new AttackPreset(family, name, damage, blast);
			attackPreset.Fields.Set((family == PresetFamily.Bow) ? AttackField.DrawStamina : AttackField.Stamina, stamina);
			if (family != PresetFamily.Bomb)
			{
				attackPreset.Fields.Set((family == PresetFamily.Bow) ? AttackField.DrawMin : AttackField.Reload, time);
			}
			attackPreset.Fields.Set(AttackField.Velocity, velocity);
			attackPreset.Fields.Set(AttackField.Accuracy, spread);
			return attackPreset;
		}

		public static AttackPreset Get(PresetFamily family, string name)
		{
			foreach (AttackPreset row in Rows)
			{
				if (row.Family == family && row.Name == name)
				{
					return row;
				}
			}
			foreach (AttackPreset row2 in Rows)
			{
				if (row2.Family == family && row2.Name == "Vanilla")
				{
					return row2;
				}
			}
			return Vanilla;
		}

		public static AttackPreset Effective(bool enabled, PresetFamily family, string name)
		{
			return Get(family, enabled ? name : "Vanilla");
		}

		public static void Apply(AttackPreset preset, AttackBlock block, Action<AttackField, float> set)
		{
			AttackField[] fields = AttackOverrideRules.Fields;
			foreach (AttackField attackField in fields)
			{
				if ((block != null && block.Get(attackField).HasValue) || preset.Fields.Get(attackField).HasValue)
				{
					set(attackField, AttackOverrideRules.FieldFactor(attackField, block, preset.Factor(attackField)));
				}
			}
		}

		public static bool BombProjectile(int flags)
		{
			return (flags & 4) != 0;
		}

		public static PresetFamily Category(WeaponFamily family, bool craftable, bool ammo, bool bomb, string skill = null, string prefab = null)
		{
			if (prefab == "GrapplingHook")
			{
				return PresetFamily.None;
			}
			if (!(!craftable || ammo))
			{
				switch (skill)
				{
				case "ElementalMagic":
				case "BloodMagic":
				case "Fishing":
					break;
				default:
					if (bomb)
					{
						return PresetFamily.Bomb;
					}
					return family switch
					{
						WeaponFamily.Bow => PresetFamily.Bow, 
						WeaponFamily.Crossbow => PresetFamily.Crossbow, 
						_ => PresetFamily.None, 
					};
				}
			}
			return PresetFamily.None;
		}
	}
	public sealed class AttackRadiusTable<T> where T : class
	{
		private sealed class Entry
		{
			public float Original;
		}

		private readonly ConditionalWeakTable<T, Entry> _entries = new ConditionalWeakTable<T, Entry>();

		public float Apply(T instance, float liveRadius, float factor)
		{
			if (!_entries.TryGetValue(instance, out var value))
			{
				if (factor == 1f)
				{
					return liveRadius;
				}
				value = new Entry
				{
					Original = liveRadius
				};
				_entries.Add(instance, value);
			}
			return AttackOverrideRules.Scale(value.Original, factor);
		}
	}
	public sealed class AttackSourceRules
	{
		private sealed class Source
		{
			public ItemData Weapon;
		}

		private readonly ConditionalWeakTable<HitData, Source> _hits = new ConditionalWeakTable<HitData, Source>();

		public void Record(HitData hit, ItemData weapon)
		{
			if (hit != null && weapon != null)
			{
				_hits.GetOrCreateValue(hit).Weapon = weapon;
			}
		}

		public ItemData Find(HitData hit)
		{
			if (hit == null || !_hits.TryGetValue(hit, out var value))
			{
				return null;
			}
			return value.Weapon;
		}
	}
	public static class AugurItems
	{
		private static readonly Dictionary<string, SE_Stats> Sets = new Dictionary<string, SE_Stats>();

		public static void Init()
		{
			Ledger.Add("Augur set effects", (Action)Sets.Clear);
			AugurTextures.Init();
		}

		public static void Configure(ItemDef row, SharedData shared)
		{
			if (!(row.Family != "robe"))
			{
				if (!Sets.TryGetValue(row.CasterSet, out var value))
				{
					value = LedgerTrack.Object<SE_Stats>(ScriptableObject.CreateInstance<SE_Stats>(), "Augur set effect");
					((Object)value).name = row.CasterSet;
					FocusItems.ConfigureEffect(row, value);
					((StatusEffect)value).m_name = row.Title.Substring(0, row.Title.LastIndexOf(' '));
					Sets.Add(row.CasterSet, value);
				}
				ConfigureSet(row, shared, value);
			}
		}

		public static void ConfigureSet(ItemDef row, SharedData shared, SE_Stats effect)
		{
			shared.m_setName = row.CasterSet;
			shared.m_setSize = 3;
			shared.m_setStatusEffect = (StatusEffect)(object)effect;
		}
	}
	public static class AugurRules
	{
		public static readonly IReadOnlyList<ItemDef> Definitions = Array.AsReadOnly(Set("Meadow", "Meadow Augur", "ShieldWood", 8.8f, 0.55f, 3, 3131467519u, "LeatherScraps", "DeerHide", "Feathers", "Resin").Concat(Set("Bark", "Barkweaver", "ShieldBronzeBuckler", 10.4f, 0.65f, 5, 1367819007u, "FineWood", "Bronze", "Thistle", "LeatherScraps")).Concat(Set("Hoar", "Hoarfrost Augur", "ShieldSilver", 14.4f, 0.8f, 8, 2446458623u, "WolfPelt", "Silver", "FreezeGland", "Crystal")).Concat(Set("Dusk", "Duskfield Augur", "ShieldBlackmetal", 16f, 0.9f, 10, 2439362559u, "LoxPelt", "BlackMetal", "LinenThread", "Tar"))
			.ToArray());

		private static IEnumerable<ItemDef> Set(string id, string title, string station, float armor, float regenRatio, int magic, uint tint, params string[] materials)
		{
			string[] donors = new string[3] { "HelmetMage", "ArmorMageChest", "ArmorMageLegs" };
			string[] names = new string[3]
			{
				"MW_HelmetAugur" + id,
				"MW_ArmorAugur" + id + "Chest",
				"MW_ArmorAugur" + id + "Legs"
			};
			string[] parts = new string[3] { " Hood", " Robe", " Trousers" };
			int[][] amounts = new int[3][]
			{
				new int[3] { 16, 15, 2 },
				new int[4] { 20, 20, 10, 5 },
				new int[3] { 20, 20, 10 }
			};
			for (int i = 0; i < donors.Length; i++)
			{
				EquipmentRecipeRules.Recipe recipe = new EquipmentRecipeRules.Recipe(1, amounts[i].Select((int n, int slot) => new EquipmentRecipeRules.Material(materials[slot], n)).ToArray());
				yield return new ItemDef(names[i], donors[i], "robe", title + parts[i], tint, 1f, recipe, station, 0, PeerRatio.Fixed(ItemStat.armor, armor), new PeerRatio(ItemStat.armorPerLevel, donors[i], 1f), new PeerRatio(ItemStat.eitrRegenModifier, donors[i], regenRatio))
				{
					NativeUpgrades = true,
					DonorMainMaterial = "LinenThread",
					PrimaryMaterials = Array.AsReadOnly(recipe.Materials.Select((EquipmentRecipeRules.Material m) => m.Prefab).ToArray()),
					CasterSet = "MW_Augur" + id,
					EitrRegen = 1f,
					ElementalMagic = magic
				};
			}
		}
	}
	public static class AugurTextureRules
	{
		public static readonly IReadOnlyList<string> ColorMaps = Array.AsReadOnly(new string[4] { "_MainTex", "_BaseMap", "_ChestTex", "_LegsTex" });

		public static int Luminance(uint pixel)
		{
			return (int)((((pixel >> 24) & 0xFF) * 54 + ((pixel >> 16) & 0xFF) * 183 + ((pixel >> 8) & 0xFF) * 19 + 128) / 256);
		}

		public static float SetGain(IEnumerable<int[]> histograms)
		{
			return SetGain(histograms, uint.MaxValue);
		}

		public static float SetGain(IEnumerable<int[]> histograms, uint tint)
		{
			List<int> list = new List<int>();
			foreach (int[] histogram in histograms)
			{
				if (histogram == null || histogram.Length != 256 || histogram.Any((int n) => n < 0))
				{
					throw new ArgumentException("Invalid luminance histogram");
				}
				long num = ((IEnumerable<int>)histogram).Sum((Func<int, long>)((int n) => n));
				if (num == 0L)
				{
					continue;
				}
				long num2 = (long)Math.Ceiling((double)num * 0.95);
				long num3 = 0L;
				for (int num4 = 0; num4 < histogram.Length; num4++)
				{
					num3 += histogram[num4];
					if (num3 >= num2)
					{
						if (num4 > 0)
						{
							list.Add(num4);
						}
						break;
					}
				}
			}
			if (list.Count == 0)
			{
				return 1f;
			}
			list.Sort();
			float num5 = (float)(list[(list.Count - 1) / 2] + list[list.Count / 2]) / 2f;
			num5 *= (float)Luminance(tint) / 255f;
			return Math.Min(4f, 255f / Math.Max(1f, num5));
		}

		public static bool CanApply(bool bodyReady, bool helmet, int rendererCopies)
		{
			if (bodyReady)
			{
				if (helmet)
				{
					return rendererCopies > 0;
				}
				return true;
			}
			return false;
		}

		public static uint Recolor(uint pixel, uint tint, float gain = 1f)
		{
			uint light = (uint)Math.Min(255.0, Math.Round((float)Luminance(pixel) * gain));
			return (Channel(24) << 24) | (Channel(16) << 16) | (Channel(8) << 8) | (pixel & 0xFF);
			uint Channel(int shift)
			{
				return (((tint >> shift) & 0xFF) * light + 127) / 255;
			}
		}
	}
	public sealed class AugurTextureCache<T> where T : class
	{
		private readonly Dictionary<(int, uint), T> copies = new Dictionary<(int, uint), T>();

		private readonly Dictionary<(int, uint), Exception> errors = new Dictionary<(int, uint), Exception>();

		public Exception Failure(int source, uint tint)
		{
			if (!errors.TryGetValue((source, tint), out var value))
			{
				return null;
			}
			return value;
		}

		public T Get(int source, uint tint, Func<T> build)
		{
			(int, uint) key = (source, tint);
			if (copies.TryGetValue(key, out var value))
			{
				return value;
			}
			try
			{
				value = build();
			}
			catch (Exception value2)
			{
				errors[key] = value2;
				value = null;
			}
			copies.Add(key, value);
			return value;
		}

		public void Clear(Action<T> release)
		{
			try
			{
				foreach (T value in copies.Values)
				{
					if (value != null)
					{
						release(value);
					}
				}
			}
			finally
			{
				copies.Clear();
				errors.Clear();
			}
		}
	}
	public static class AugurTextures
	{
		private sealed class DonorPixels
		{
			internal Color32[] Pixels;

			internal int[] Histogram;
		}

		private static readonly AugurTextureCache<Texture2D> Copies = new AugurTextureCache<Texture2D>();

		private static readonly Dictionary<int, DonorPixels> Donors = new Dictionary<int, DonorPixels>();

		private static readonly HashSet<string> Prepared = new HashSet<string>();

		private static readonly Dictionary<string, Exception> Errors = new Dictionary<string, Exception>();

		public static void Init()
		{
			Ledger.Add("Augur texture copies", (Action)delegate
			{
				Copies.Clear(delegate(Texture2D copy)
				{
					Object.Destroy((Object)(object)copy);
				});
				Prepared.Clear();
				Errors.Clear();
				Donors.Clear();
			});
		}

		public static void Configure(ItemDef row, GameObject item, SharedData shared)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Invalid comparison between Unknown and I4
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Expected O, but got Unknown
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Expected O, but got Unknown
			if (row.Family != "robe" || ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated()) || (int)SystemInfo.graphicsDeviceType == 4)
			{
				return;
			}
			List<Material> list = new List<Material>();
			List<Action> list2 = new List<Action>();
			bool bodyReady = row.Donor == "HelmetMage";
			try
			{
				PrepareSet(row);
				if (row.Donor != "HelmetMage")
				{
					Material armorMaterial = shared.m_armorMaterial;
					string text = ((row.Donor == "ArmorMageChest") ? "_ChestTex" : "_LegsTex");
					if ((Object)(object)armorMaterial == (Object)null || !armorMaterial.HasProperty(text))
					{
						throw new InvalidOperationException("missing " + text);
					}
					Material copy = new Material(armorMaterial);
					list.Add(copy);
					copy.SetTexture(text, (Texture)(object)Copy(armorMaterial.GetTexture(text), row.Tint));
					list2.Add(delegate
					{
						shared.m_armorMaterial = copy;
					});
					bodyReady = true;
				}
				int num = 0;
				Renderer[] componentsInChildren = item.GetComponentsInChildren<Renderer>(true);
				foreach (Renderer renderer in componentsInChildren)
				{
					Material[] copies = renderer.sharedMaterials;
					bool flag = false;
					for (int num3 = 0; num3 < copies.Length; num3++)
					{
						Material val = copies[num3];
						if ((Object)(object)val == (Object)null)
						{
							continue;
						}
						Material val2 = null;
						foreach (string colorMap in AugurTextureRules.ColorMaps)
						{
							if (val.HasProperty(colorMap) && !((Object)(object)val.GetTexture(colorMap) == (Object)null))
							{
								if ((Object)(object)val2 == (Object)null)
								{
									val2 = new Material(val);
									list.Add(val2);
								}
								val2.SetTexture(colorMap, (Texture)(object)Copy(val.GetTexture(colorMap), row.Tint));
							}
						}
						if (!((Object)(object)val2 == (Object)null))
						{
							copies[num3] = val2;
							flag = true;
							num++;
						}
					}
					if (flag)
					{
						list2.Add(delegate
						{
							renderer.sharedMaterials = copies;
						});
					}
				}
				if (!AugurTextureRules.CanApply(bodyReady, row.Donor == "HelmetMage", num))
				{
					throw new InvalidOperationException("missing color texture");
				}
				foreach (Material item2 in list)
				{
					LedgerTrack.Object<Material>(item2, "Augur material");
				}
				foreach (Action item3 in list2)
				{
					item3();
				}
			}
			catch (Exception ex)
			{
				foreach (Material item4 in list)
				{
					Object.Destroy((Object)(object)item4);
				}
				MwLog.WarnOnce("Equipment.augur.texture." + row.CasterSet, (object)("Augur " + row.CasterSet + " texture recolor unavailable; using donor appearance: " + ex.GetBaseException().Message));
			}
		}

		internal static Texture2D Recolored(Texture source, uint tint)
		{
			if ((Object)(object)source == (Object)null)
			{
				throw new InvalidOperationException("missing color texture");
			}
			int id = ((Object)source).GetInstanceID();
			Texture2D obj = Copies.Get(id, tint, delegate
			{
				if (Donors.TryGetValue(id, out var value) && value.Pixels == null)
				{
					Donors.Remove(id);
				}
				DonorPixels donorPixels = ReadDonor(source);
				return Bake(source, donorPixels.Pixels, tint, AugurTextureRules.SetGain(new int[1][] { donorPixels.Histogram }, tint));
			});
			if ((Object)(object)obj == (Object)null)
			{
				throw new InvalidOperationException("could not recolor " + ((Object)source).name, Copies.Failure(id, tint));
			}
			return obj;
		}

		private static Texture2D Copy(Texture source, uint tint)
		{
			if ((Object)(object)source == (Object)null)
			{
				throw new InvalidOperationException("missing color texture");
			}
			Texture2D obj = Copies.Get(((Object)source).GetInstanceID(), tint, delegate
			{
				throw new InvalidOperationException("unprepared color texture " + ((Object)source).name);
			});
			if ((Object)(object)obj == (Object)null)
			{
				throw new InvalidOperationException("could not copy " + ((Object)source).name, Copies.Failure(((Object)source).GetInstanceID(), tint));
			}
			return obj;
		}

		private static void PrepareSet(ItemDef row)
		{
			if (Errors.TryGetValue(row.CasterSet, out var value))
			{
				throw new InvalidOperationException("set bake failed", value);
			}
			if (Prepared.Contains(row.CasterSet))
			{
				return;
			}
			try
			{
				HashSet<Texture> hashSet = new HashSet<Texture>();
				foreach (ItemDef item in AugurRules.Definitions.Where((ItemDef p) => p.CasterSet == row.CasterSet))
				{
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(item.Donor);
					if ((Object)(object)itemPrefab == (Object)null)
					{
						throw new InvalidOperationException("missing donor " + item.Donor);
					}
					SharedData shared = itemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared;
					if (item.Donor != "HelmetMage")
					{
						string text = ((item.Donor == "ArmorMageChest") ? "_ChestTex" : "_LegsTex");
						if ((Object)(object)shared.m_armorMaterial == (Object)null || !shared.m_armorMaterial.HasProperty(text) || (Object)(object)shared.m_armorMaterial.GetTexture(text) == (Object)null)
						{
							throw new InvalidOperationException("missing " + text);
						}
						hashSet.Add(shared.m_armorMaterial.GetTexture(text));
					}
					foreach (Material item2 in from m in itemPrefab.GetComponentsInChildren<Renderer>(true).SelectMany((Renderer r) => r.sharedMaterials)
						where (Object)(object)m != (Object)null
						select m)
					{
						foreach (string colorMap in AugurTextureRules.ColorMaps)
						{
							if (item2.HasProperty(colorMap) && (Object)(object)item2.GetTexture(colorMap) != (Object)null)
							{
								hashSet.Add(item2.GetTexture(colorMap));
							}
						}
					}
				}
				float gain = AugurTextureRules.SetGain(hashSet.Select((Texture source2) => ReadDonor(source2).Histogram), row.Tint);
				MwLog.Info((object)("Augur " + row.CasterSet + " exposure gain " + gain.ToString("0.###", CultureInfo.InvariantCulture) + "x across " + hashSet.Count + " textures" + ((gain >= 4f) ? " (4x cap)" : "")));
				foreach (Texture source in hashSet)
				{
					if ((Object)(object)Copies.Get(((Object)source).GetInstanceID(), row.Tint, () => Bake(source, ReadDonor(source).Pixels, row.Tint, gain)) == (Object)null)
					{
						throw new InvalidOperationException("could not bake " + ((Object)source).name, Copies.Failure(((Object)source).GetInstanceID(), row.Tint));
					}
				}
				Prepared.Add(row.CasterSet);
			}
			catch (Exception value2)
			{
				Errors[row.CasterSet] = value2;
				throw;
			}
			finally
			{
				ReleasePixels();
			}
		}

		private static void ReleasePixels()
		{
			if (!AugurRules.Definitions.All((ItemDef row) => Prepared.Contains(row.CasterSet) || Errors.ContainsKey(row.CasterSet)))
			{
				return;
			}
			foreach (DonorPixels value in Donors.Values)
			{
				value.Pixels = null;
			}
		}

		private static DonorPixels ReadDonor(Texture source)
		{
			//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)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)source).GetInstanceID();
			if (Donors.TryGetValue(instanceID, out var value))
			{
				return value;
			}
			Texture2D val = Readback(source);
			try
			{
				Color32[] pixels = val.GetPixels32();
				int[] array = new int[256];
				Color32[] array2 = pixels;
				foreach (Color32 val2 in array2)
				{
					if (val2.a > 0)
					{
						array[AugurTextureRules.Luminance((uint)((val2.r << 24) | (val2.g << 16) | (val2.b << 8)))]++;
					}
				}
				value = new DonorPixels
				{
					Pixels = pixels,
					Histogram = array
				};
				Donors.Add(instanceID, value);
				return value;
			}
			finally
			{
				Object.Destroy((Object)(object)val);
			}
		}

		private static Texture2D Readback(Texture source)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Invalid comparison between Unknown and I4
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			if ((int)SystemInfo.graphicsDeviceType == 4)
			{
				throw new InvalidOperationException("no graphics device");
			}
			RenderTexture active = RenderTexture.active;
			bool sRGBWrite = GL.sRGBWrite;
			RenderTexture val = null;
			Texture2D val2 = null;
			try
			{
				val = RenderTexture.GetTemporary(source.width, source.height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
				GL.sRGBWrite = (int)QualitySettings.activeColorSpace == 1;
				Graphics.Blit(source, val);
				RenderTexture.active = val;
				val2 = new Texture2D(source.width, source.height, (TextureFormat)4, true, false);
				((Object)val2).name = ((Object)source).name + "_Augur";
				val2.ReadPixels(new Rect(0f, 0f, (float)source.width, (float)source.height), 0, 0, false);
				return val2;
			}
			catch
			{
				if ((Object)(object)val2 != (Object)null)
				{
					Object.Destroy((Object)(object)val2);
				}
				throw;
			}
			finally
			{
				RenderTexture.active = active;
				GL.sRGBWrite = sRGBWrite;
				if ((Object)(object)val != (Object)null)
				{
					RenderTexture.ReleaseTemporary(val);
				}
			}
		}

		private static Texture2D Bake(Texture source, Color32[] donorPixels, uint tint, float gain)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = null;
			try
			{
				val = new Texture2D(source.width, source.height, (TextureFormat)4, true, false);
				((Object)val).name = ((Object)source).name + "_Augur";
				Color32[] array = (Color32[])donorPixels.Clone();
				for (int i = 0; i < array.Length; i++)
				{
					Color32 val2 = array[i];
					uint num = AugurTextureRules.Recolor((uint)((val2.r << 24) | (val2.g << 16) | (val2.b << 8) | val2.a), tint, gain);
					array[i] = new Color32((byte)(num >> 24), (byte)(num >> 16), (byte)(num >> 8), (byte)num);
				}
				val.SetPixels32(array);
				((Texture)val).wrapMode = source.wrapMode;
				((Texture)val).filterMode = source.filterMode;
				((Texture)val).anisoLevel = source.anisoLevel;
				val.Apply(true, true);
				return val;
			}
			catch
			{
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
				throw;
			}
		}
	}
	public sealed class VolleySkillBudget
	{
		private bool _used;

		public bool TryUse()
		{
			if (_used)
			{
				return false;
			}
			_used = true;
			return true;
		}
	}
	internal static class BowVolley
	{
		private sealed class Burst
		{
			public Attack Attack;

			public Player Owner;

			public ItemData Weapon;

			public ItemData Ammo;

			public int Index;

			public float Stamina;

			public bool Paid;

			public readonly VolleySkillBudget Skill = new VolleySkillBudget();
		}

		public sealed class Arrow : MonoBehaviour
		{
			public VolleySkillBudget Skill;
		}

		internal static class Patches
		{
			[HarmonyPatch(typeof(Attack), "UseAmmo")]
			[HarmonyPostfix]
			private static void Ammo(Attack __instance, ItemData ammoItem, bool __result)
			{
				Burst firing = _firing;
				if (firing != null && firing.Attack == __instance && __result && ammoItem == firing.Ammo)
				{
					if (__instance.m_projectiles > 1)
					{
						((Humanoid)firing.Owner).GetInventory().RemoveItem(ammoItem, __instance.m_projectiles - 1);
					}
					((Character)firing.Owner).UseStamina(firing.Stamina);
					SecondaryAttacks.TriggerCooldown(firing.Owner, WeaponFamily.Bow);
					firing.Paid = true;
				}
			}

			[HarmonyPatch(typeof(Projectile), "Setup")]
			[HarmonyPrefix]
			private static void Fan(Projectile __instance, Character owner, ref Vector3 velocity, ItemData item, ItemData ammo)
			{
				//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)
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_006e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0081: Unknown result type (might be due to invalid IL or missing references)
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				Burst firing = _firing;
				if (firing != null && !((Object)(object)owner != (Object)(object)firing.Owner) && item == firing.Weapon && ammo == firing.Ammo)
				{
					Vector3 aimDir = ((Humanoid)firing.Owner).GetAimDir(((Component)__instance).transform.position);
					Vector3 val = Quaternion.AngleAxis(MoveRules.VolleyAngle(firing.Index++, firing.Attack.m_projectiles), Vector3.up) * aimDir;
					velocity = val * ((Vector3)(ref velocity)).magnitude;
					((Component)__instance).transform.rotation = Quaternion.LookRotation(val);
					((Component)__instance).gameObject.AddComponent<Arrow>().Skill = firing.Skill;
				}
			}

			[HarmonyPatch(typeof(Projectile), "OnHit")]
			[HarmonyPrefix]
			private static void Hit(Projectile __instance, out Arrow __state)
			{
				__state = _hitting;
				_hitting = (((Object)(object)__instance.m_owner == (Object)(object)Player.m_localPlayer) ? ((Component)__instance).GetComponent<Arrow>() : null);
			}

			[HarmonyPatch(typeof(Projectile), "OnHit")]
			[HarmonyFinalizer]
			private static void EndHit(Arrow __state)
			{
				_hitting = __state;
			}

			[HarmonyPatch(typeof(Player), "RaiseSkill")]
			[HarmonyPrefix]
			private static bool Skill(Player __instance, SkillType skill, float value, bool __runOriginal = true)
			{
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Invalid comparison between Unknown and I4
				if (!__runOriginal)
				{
					return false;
				}
				if (!((Object)(object)_hitting == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && (int)skill == 8 && !(value <= 0f))
				{
					return _hitting.Skill.TryUse();
				}
				return true;
			}
		}

		private static Burst _firing;

		private static Arrow _hitting;

		internal static float StaminaCost(Player p, ItemData weapon)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			Attack attack = weapon.m_shared.m_attack;
			float num = weapon.GetDrawStaminaDrain() * (1f + ((Character)p).GetEquipmentAttackStaminaModifier());
			((Character)p).GetSEMan().ModifyAttackStaminaUsage(num, ref num, true);
			float skillFactor = ((Character)p).GetSkillFactor(weapon.m_shared.m_skillType);
			float num2 = MoveRules.VolleyDrawStamina(num, attack.m_drawDurationMin, skillFactor);
			if (attack.m_attackStamina <= 0f)
			{
				return num2 * SecondaryAttacks.StaminaMultiplier;
			}
			float num3 = attack.m_attackStamina * (1f + (attack.m_isHomeItem ? ((Character)p).GetEquipmentHomeItemModifier() : ((Character)p).GetEquipmentAttackStaminaModifier()));
			((Character)p).GetSEMan().ModifyAttackStaminaUsage(num3, ref num3, true);
			return Mathf.Max(0f, num2 + MoveRules.StartStamina(num3, skillFactor, ((Character)p).GetMaxHealth() - ((Character)p).GetHealth(), attack.m_staminaReturnPerMissingHP)) * SecondaryAttacks.StaminaMultiplier;
		}

		internal static void Configure(Attack attack, int arrows)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			attack.m_attackType = (AttackType)2;
			attack.m_projectiles = MoveRules.VolleyCount(arrows);
			attack.m_projectileBursts = 1;
			attack.m_perBurstResourceUsage = false;
			attack.m_loopingAttack = false;
			attack.m_cons