Decompiled source of SiegeNights v0.2.1

BepInEx/plugins/SiegeNights/SiegeNights.dll

Decompiled 18 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Splatform;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: TargetFramework(".NETStandard,Version=v2.1")]
[assembly: AssemblyVersion("0.2.1.0")]
namespace SiegeNights;

internal static class RaiderCombat
{
	private delegate bool MoveToDelegate(BaseAI ai, float dt, Vector3 point, float stoppingDistance, bool run);

	private delegate bool HavePathDelegate(BaseAI ai, Vector3 point);

	private static readonly List<Piece> NearbyPieces = new List<Piece>();

	private static readonly FieldRef<MonsterAI, Character> CreatureTarget = AccessTools.FieldRefAccess<MonsterAI, Character>("m_targetCreature");

	private static readonly FieldRef<MonsterAI, StaticTarget> StructureTarget = AccessTools.FieldRefAccess<MonsterAI, StaticTarget>("m_targetStatic");

	private static readonly FieldRef<Door, ZNetView> DoorView = FindDoorView();

	private static readonly FieldRef<ZoneSystem, HashSet<string>> WorldKeys = AccessTools.FieldRefAccess<ZoneSystem, HashSet<string>>("m_globalKeys");

	private static readonly FieldRef<ZoneSystem, Dictionary<string, string>> WorldKeyValues = AccessTools.FieldRefAccess<ZoneSystem, Dictionary<string, string>>("m_globalKeysValues");

	private static readonly MoveToDelegate MoveTo = AccessTools.MethodDelegate<MoveToDelegate>(AccessTools.Method(typeof(BaseAI), "MoveTo", (Type[])null, (Type[])null), (object)null, true);

	private static readonly HavePathDelegate HavePath = AccessTools.MethodDelegate<HavePathDelegate>(AccessTools.Method(typeof(BaseAI), "HavePath", (Type[])null, (Type[])null), (object)null, true);

	private static readonly FieldRef<SE_Burning, float> FireRemaining = AccessTools.FieldRefAccess<SE_Burning, float>("m_fireDamageLeft");

	private static readonly FieldRef<SE_Burning, float> SpiritRemaining = AccessTools.FieldRefAccess<SE_Burning, float>("m_spiritDamageLeft");

	private static readonly FieldRef<SE_Poison, float> PoisonRemaining = AccessTools.FieldRefAccess<SE_Poison, float>("m_damageLeft");

	[ThreadStatic]
	private static float _statusPlayerShare;

	[ThreadStatic]
	private static Character _statusTarget;

	private const string FireCredit = "siegenights_fire_player";

	private const string PoisonCredit = "siegenights_poison_player";

	private const string SpiritCredit = "siegenights_spirit_player";

	private const string OrphanedAt = "siegenights_orphaned_at";

	[ThreadStatic]
	private static Character _damageTarget;

	[ThreadStatic]
	private static bool _damageFromPlayer;

	internal static void Install(Harmony harmony)
	{
		Hook(harmony, typeof(BaseAI), "IsEnemy", "UseHostility", null, null, new Type[2]
		{
			typeof(Character),
			typeof(Character)
		});
		Hook(harmony, typeof(Character), "RPC_Damage", "FilterHit", null, "RestoreSource");
		Hook(harmony, typeof(Character), "ApplyDamage", "BeforeDamage", "AfterDamage");
		Hook(harmony, typeof(Character), "AddFireDamage", null, "RecordFire");
		Hook(harmony, typeof(Character), "AddSpiritDamage", null, "RecordSpirit");
		Hook(harmony, typeof(Character), "AddPoisonDamage", null, "RecordPoison");
		Hook(harmony, typeof(SE_Burning), "UpdateStatusEffect", "CreditBurn", null, "RestoreTick");
		Hook(harmony, typeof(SE_Poison), "UpdateStatusEffect", "CreditPoison", null, "RestoreTick");
		Hook(harmony, typeof(Character), "OnDeath", "RecordDeath");
		Hook(harmony, typeof(CharacterDrop), "OnDeath", "AllowDrops");
		Hook(harmony, typeof(CharacterDrop), "GenerateDropList", "BuildDropList");
		Hook(harmony, typeof(MonsterAI), "UpdateAI", "RunRaider");
		Hook(harmony, typeof(MonsterAI), "UpdateTarget", null, "PickObjective");
		Hook(harmony, typeof(WearNTear), "RPC_Damage", "AllowStructureDamage");
		Hook(harmony, typeof(SpawnSystem), "IsSpawnPointGood", null, "BlockAmbientPoint");
		Hook(harmony, typeof(CreatureSpawner), "Spawn", "AllowCreatureSpawn");
		Hook(harmony, typeof(SpawnArea), "FindSpawnPoint", "AllowAreaSpawn");
		Hook(harmony, typeof(RandEventSystem), "SetRandomEvent", "AllowRandomRaid");
		Hook(harmony, typeof(EnvMan), "GetEnvironmentOverride", null, "UseSiegeStorm");
		Hook(harmony, typeof(ZoneSystem), "GlobalKeyAdd", "StoreSiegeState");
	}

	private static void Hook(Harmony harmony, Type type, string method, string prefix = null, string postfix = null, string finalizer = null, Type[] parameters = null)
	{
		MethodInfo methodInfo = AccessTools.Method(type, method, parameters, (Type[])null) ?? throw new MissingMethodException(type.FullName, method);
		harmony.Patch((MethodBase)methodInfo, Patch(prefix), Patch(postfix), (HarmonyMethod)null, Patch(finalizer), (HarmonyMethod)null);
		static HarmonyMethod Patch(string name)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			if (name != null)
			{
				return new HarmonyMethod(typeof(RaiderCombat), name, (Type[])null);
			}
			return null;
		}
	}

	internal static ZDO Data(Component component)
	{
		ZNetView val = (((Object)(object)component != (Object)null) ? component.GetComponent<ZNetView>() : null);
		if (!((Object)(object)val != (Object)null) || !val.IsValid())
		{
			return null;
		}
		return val.GetZDO();
	}

	private static FieldRef<Door, ZNetView> FindDoorView()
	{
		if (!(AccessTools.Field(typeof(Door), "m_nview") == null))
		{
			return AccessTools.FieldRefAccess<Door, ZNetView>("m_nview");
		}
		return null;
	}

	private static bool IsRaider(Character character)
	{
		ZDO obj = Data((Component)(object)character);
		if (obj == null)
		{
			return false;
		}
		return obj.GetLong("siegenights_raider", 0L) > 0;
	}

	private static bool ProtectedFrom(Character first, Character second)
	{
		if ((Object)(object)first != (Object)null && (Object)(object)second != (Object)null && (Object)(object)first != (Object)(object)second && !first.IsPlayer() && !second.IsPlayer() && !first.IsTamed() && !second.IsTamed())
		{
			if (!IsRaider(first))
			{
				return IsRaider(second);
			}
			return true;
		}
		return false;
	}

	private static bool UseHostility(Character __0, Character __1, ref bool __result)
	{
		if (!ProtectedFrom(__0, __1))
		{
			return true;
		}
		__result = false;
		return false;
	}

	private static bool FilterHit(Character __instance, HitData __1, out (Character target, bool player) __state)
	{
		__state = (target: _damageTarget, player: _damageFromPlayer);
		Character attacker = __1.GetAttacker();
		if (ProtectedFrom(__instance, attacker))
		{
			return false;
		}
		_damageTarget = __instance;
		_damageFromPlayer = (Object)(object)attacker != (Object)null && attacker.IsPlayer();
		return true;
	}

	private static void RestoreSource((Character target, bool player) __state)
	{
		(_damageTarget, _damageFromPlayer) = __state;
	}

	private static bool BeforeDamage(Character __instance, HitData __0, out (ZDO data, float health, float share) __state)
	{
		__state = default((ZDO, float, float));
		Character attacker = __0.GetAttacker();
		if (ProtectedFrom(__instance, attacker))
		{
			return false;
		}
		ZDO val = Data((Component)(object)__instance);
		if (val != null && val.GetLong("siegenights_raider", 0L) > 0 && __instance.IsOwner())
		{
			__state = (data: val, health: __instance.GetHealth(), share: ((Object)(object)attacker != (Object)null && attacker.IsPlayer()) ? 1f : (((Object)(object)_statusTarget == (Object)(object)__instance) ? _statusPlayerShare : 0f));
		}
		return true;
	}

	private static void AfterDamage(Character __instance, (ZDO data, float health, float share) __state)
	{
		if (__state.data == null)
		{
			return;
		}
		float num = Mathf.Max(0f, __state.health - Mathf.Max(0f, __instance.GetHealth()));
		if (!(num <= 0f))
		{
			var (val, _, _) = __state;
			val.Set("siegenights_damage_all", val.GetFloat("siegenights_damage_all", 0f) + num);
			if (__state.share > 0f)
			{
				val.Set("siegenights_damage_player", val.GetFloat("siegenights_damage_player", 0f) + num * __state.share);
			}
		}
	}

	private static void RecordFire(Character __instance, float __0)
	{
		if (!(__0 <= 0f) && IsRaider(__instance))
		{
			StatusEffect statusEffect = __instance.GetSEMan().GetStatusEffect(StringExtensionMethods.GetStableHashCode("Burning"));
			SE_Burning val = (SE_Burning)(object)((statusEffect is SE_Burning) ? statusEffect : null);
			if ((Object)(object)val != (Object)null)
			{
				RecordStatus(__instance, __0, FireRemaining.Invoke(val), "siegenights_fire_player", additive: true);
			}
		}
	}

	private static void RecordSpirit(Character __instance, float __0)
	{
		if (!(__0 <= 0f) && IsRaider(__instance))
		{
			StatusEffect statusEffect = __instance.GetSEMan().GetStatusEffect(StringExtensionMethods.GetStableHashCode("Spirit"));
			SE_Burning val = (SE_Burning)(object)((statusEffect is SE_Burning) ? statusEffect : null);
			if ((Object)(object)val != (Object)null)
			{
				RecordStatus(__instance, __0, SpiritRemaining.Invoke(val), "siegenights_spirit_player", additive: true);
			}
		}
	}

	private static void RecordPoison(Character __instance, float __0)
	{
		if (!(__0 <= 0f) && IsRaider(__instance))
		{
			StatusEffect statusEffect = __instance.GetSEMan().GetStatusEffect(StringExtensionMethods.GetStableHashCode("Poison"));
			SE_Poison val = (SE_Poison)(object)((statusEffect is SE_Poison) ? statusEffect : null);
			if ((Object)(object)val != (Object)null && __0 >= PoisonRemaining.Invoke(val))
			{
				RecordStatus(__instance, __0, PoisonRemaining.Invoke(val), "siegenights_poison_player", additive: false);
			}
		}
	}

	private static void RecordStatus(Character character, float damage, float remaining, string key, bool additive)
	{
		if (!(damage <= 0f) && character.IsOwner())
		{
			ZDO val = Data((Component)(object)character);
			if (val != null && val.GetLong("siegenights_raider", 0L) > 0)
			{
				bool flag = (Object)(object)_damageTarget == (Object)(object)character && _damageFromPlayer;
				float num = (additive ? SiegeRules.CombineDamageShare(remaining, damage, val.GetFloat(key, val.GetBool(key, false) ? 1f : 0f), flag) : (flag ? 1f : 0f));
				val.Set(key, num);
			}
		}
	}

	private static void CreditBurn(SE_Burning __instance, out (Character target, float share) __state)
	{
		__state = (target: _statusTarget, share: _statusPlayerShare);
		_statusTarget = ((StatusEffect)__instance).m_character;
		ZDO val = Data((Component)(object)((StatusEffect)__instance).m_character);
		string text = (((Object)__instance).name.StartsWith("Spirit", StringComparison.Ordinal) ? "siegenights_spirit_player" : "siegenights_fire_player");
		_statusPlayerShare = ((val != null) ? val.GetFloat(text, val.GetBool(text, false) ? 1f : 0f) : 0f);
	}

	private static void CreditPoison(SE_Poison __instance, out (Character target, float share) __state)
	{
		__state = (target: _statusTarget, share: _statusPlayerShare);
		_statusTarget = ((StatusEffect)__instance).m_character;
		ZDO val = Data((Component)(object)((StatusEffect)__instance).m_character);
		_statusPlayerShare = ((val != null) ? val.GetFloat("siegenights_poison_player", val.GetBool("siegenights_poison_player", false) ? 1f : 0f) : 0f);
	}

	private static void RestoreTick((Character target, float share) __state)
	{
		(_statusTarget, _statusPlayerShare) = __state;
	}

	private static void RecordDeath(Character __instance)
	{
		ZDO val = Data((Component)(object)__instance);
		if (val != null && val.GetLong("siegenights_raider", 0L) > 0 && __instance.IsOwner())
		{
			SiegePlugin.Director?.ReportDeath(val);
		}
	}

	private static bool AllowDrops(CharacterDrop __instance)
	{
		ZDO obj = Data((Component)(object)__instance);
		return obj == null || obj.GetLong("siegenights_raider", 0L) <= 0;
	}

	private static bool BuildDropList(CharacterDrop __instance, ref List<KeyValuePair<GameObject, int>> __result)
	{
		if (AllowDrops(__instance))
		{
			return true;
		}
		__result = new List<KeyValuePair<GameObject, int>>();
		return false;
	}

	private static bool RunRaider(MonsterAI __instance, float __0, ref bool __result)
	{
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0121: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_021e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
		ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
		if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner())
		{
			return true;
		}
		ZDO zDO = component.GetZDO();
		long num = zDO.GetLong("siegenights_raider", 0L);
		if (num == 0L)
		{
			return true;
		}
		SiegeState current = SiegePlugin.Current;
		if (current == null || current.Id != num || current.Phase == Phase.Aftermath)
		{
			SiegeDirector director = SiegePlugin.Director;
			if (director != null && director.Ready)
			{
				float num2 = (float)ZNet.instance.GetTimeSeconds();
				float num3 = zDO.GetFloat("siegenights_orphaned_at", 0f);
				if (num3 == 0f)
				{
					zDO.Set("siegenights_orphaned_at", num2);
				}
				else if (num2 - num3 >= 30f)
				{
					ZNetScene.instance.Destroy(((Component)__instance).gameObject);
					__result = false;
					return false;
				}
				goto IL_00ee;
			}
		}
		if (zDO.GetFloat("siegenights_orphaned_at", 0f) != 0f)
		{
			zDO.Set("siegenights_orphaned_at", 0f);
		}
		goto IL_00ee;
		IL_00ee:
		if (current == null || current.Id != num || current.Phase != Phase.Assault || current.Paused)
		{
			((BaseAI)__instance).StopMoving();
			__result = false;
			return false;
		}
		Vector3 position = ((Component)__instance).transform.position;
		float num4 = SiegeRules.HorizontalDistance(position, current.Center);
		if (num4 > 140f)
		{
			CreatureTarget.Invoke(__instance) = null;
			StructureTarget.Invoke(__instance) = null;
			MoveTo((BaseAI)(object)__instance, __0, current.Center, 3f, run: true);
			__result = true;
			return false;
		}
		if (num4 > 16f && (Object)(object)((BaseAI)__instance).GetTargetCreature() == (Object)null && (Object)(object)__instance.GetStaticTarget() == (Object)null && Player.GetPlayersInRangeXZ(position, 22f) == 0)
		{
			Objectives objectives = SiegeRules.Objective(current.Difficulty, current.Target, current.Wave);
			if (num4 <= 58f && objectives != Objectives.Defenders && ((Time.frameCount + ((Object)__instance).GetInstanceID()) & 0xF) == 0)
			{
				StructureTarget.Invoke(__instance) = FindStructure(__instance, position, current.Center, objectives);
				if ((Object)(object)__instance.GetStaticTarget() != (Object)null)
				{
					return true;
				}
			}
			MoveTo((BaseAI)(object)__instance, __0, current.Center, 3f, run: true);
			__result = true;
			return false;
		}
		return true;
	}

	private static void PickObjective(MonsterAI __instance, ref bool __2, ref bool __3)
	{
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		SiegeState current = SiegePlugin.Current;
		if (current == null || current.Phase != Phase.Assault || current.Paused)
		{
			return;
		}
		ZDO obj = Data((Component)(object)__instance);
		if (((obj != null) ? new long?(obj.GetLong("siegenights_raider", 0L)) : ((long?)null)) != current.Id)
		{
			return;
		}
		Character val = CreatureTarget.Invoke(__instance);
		if ((Object)(object)val != (Object)null && !val.IsPlayer() && !val.IsTamed())
		{
			CreatureTarget.Invoke(__instance) = null;
		}
		Objectives objectives = SiegeRules.Objective(current.Difficulty, current.Target, current.Wave);
		if (objectives == Objectives.Defenders)
		{
			StructureTarget.Invoke(__instance) = null;
			return;
		}
		Vector3 position = ((Component)__instance).transform.position;
		StaticTarget val2 = StructureTarget.Invoke(__instance);
		if ((Object)(object)val2 != (Object)null && IsObjectivePiece(((Component)val2).GetComponentInParent<Piece>(), objectives, current.Center))
		{
			CreatureTarget.Invoke(__instance) = null;
			__2 = (__3 = false);
			return;
		}
		if ((Object)(object)val2 != (Object)null)
		{
			StructureTarget.Invoke(__instance) = null;
		}
		if (!(SiegeRules.HorizontalDistance(position, current.Center) > 58f) && ((Time.frameCount + ((Object)__instance).GetInstanceID()) & 0xF) == 0)
		{
			StaticTarget val3 = FindStructure(__instance, position, current.Center, objectives);
			if (!((Object)(object)val3 == (Object)null))
			{
				StructureTarget.Invoke(__instance) = val3;
				CreatureTarget.Invoke(__instance) = null;
				__2 = (__3 = false);
			}
		}
	}

	private static bool IsObjectivePiece(Piece piece, Objectives objective, Vector3 center)
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)piece == (Object)null || !piece.IsPlacedByPlayer() || Vector3.Distance(((Component)piece).transform.position, center) > 38f)
		{
			return false;
		}
		if (objective == Objectives.Structures)
		{
			return Settlement.IsStructural(piece);
		}
		Door componentInChildren = ((Component)piece).GetComponentInChildren<Door>();
		if ((Object)(object)componentInChildren != (Object)null)
		{
			if (DoorView != null)
			{
				ZNetView obj = DoorView.Invoke(componentInChildren);
				if (obj == null)
				{
					return false;
				}
				ZDO zDO = obj.GetZDO();
				return ((zDO != null) ? new int?(zDO.GetInt(ZDOVars.s_state, 0)) : ((int?)null)) == 0;
			}
			return true;
		}
		return false;
	}

	private static StaticTarget FindStructure(MonsterAI raider, Vector3 position, Vector3 center, Objectives objective)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//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_005d: 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)
		//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_0084: Unknown result type (might be due to invalid IL or missing references)
		NearbyPieces.Clear();
		Piece.GetAllPiecesInRadius(position, 24f, NearbyPieces);
		StaticTarget result = null;
		float num = float.MaxValue;
		foreach (Piece nearbyPiece in NearbyPieces)
		{
			if (!IsObjectivePiece(nearbyPiece, objective, center))
			{
				continue;
			}
			StaticTarget componentInChildren = ((Component)nearbyPiece).GetComponentInChildren<StaticTarget>();
			if (!((Object)(object)componentInChildren == (Object)null))
			{
				Vector3 val = componentInChildren.FindClosestPoint(position);
				Vector3 val2 = val - position;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				if (!(sqrMagnitude >= num) && (!(sqrMagnitude > 25f) || HavePath((BaseAI)(object)raider, val)))
				{
					num = sqrMagnitude;
					result = componentInChildren;
				}
			}
		}
		return result;
	}

	private static bool NearSiege(Vector3 point)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		SiegeState current = SiegePlugin.Current;
		if (current != null && current.Phase != Phase.Aftermath && Math.Abs(point.y - current.Center.y) < 55f)
		{
			return SiegeRules.HorizontalDistance(point, current.Center) < 150f;
		}
		return false;
	}

	private static void BlockAmbientPoint(SpawnData __0, ref Vector3 __1, ref bool __result)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		if (__result && NearSiege(__1) && IsAmbientMonster(__0.m_prefab))
		{
			__result = false;
		}
	}

	private static bool AllowCreatureSpawn(CreatureSpawner __instance)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		if (NearSiege(((Component)__instance).transform.position))
		{
			return !IsAmbientMonster(__instance.m_creaturePrefab);
		}
		return true;
	}

	private static bool AllowAreaSpawn(SpawnArea __instance, GameObject __0, ref bool __result)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		if (!NearSiege(((Component)__instance).transform.position) || !IsAmbientMonster(__0))
		{
			return true;
		}
		__result = false;
		return false;
	}

	private static bool IsAmbientMonster(GameObject prefab)
	{
		MonsterAI val = default(MonsterAI);
		Character val2 = default(Character);
		if ((Object)(object)prefab != (Object)null && prefab.TryGetComponent<MonsterAI>(ref val) && prefab.TryGetComponent<Character>(ref val2))
		{
			return !val2.IsBoss();
		}
		return false;
	}

	private static bool AllowRandomRaid(RandomEvent __0)
	{
		SiegeState current = SiegePlugin.Current;
		if (__0 != null && current != null)
		{
			return current.Phase == Phase.Aftermath;
		}
		return true;
	}

	private static void UseSiegeStorm(EnvMan __instance, ref string __result)
	{
		if (SiegePresentation.StormActive && __instance.m_environments.Exists((EnvSetup env) => env.m_name == "ThunderStorm"))
		{
			__result = "ThunderStorm";
		}
	}

	private static bool StoreSiegeState(ZoneSystem __instance, string __0)
	{
		int num = __0.IndexOf(' ');
		string text = ((num < 0) ? __0 : __0.Substring(0, num)).ToLowerInvariant();
		if (text != "siegenights_event" && text != "siegenights_last_roll" && text != "siegenights_next_day")
		{
			return true;
		}
		HashSet<string> hashSet = WorldKeys.Invoke(__instance);
		Dictionary<string, string> obj = WorldKeyValues.Invoke(__instance);
		if (obj.TryGetValue(text, out var value))
		{
			hashSet.Remove((text + " " + value).TrimEnd());
		}
		string text2 = ((num < 0) ? "" : __0.Substring(num + 1).ToLowerInvariant());
		hashSet.Add((text + " " + text2).TrimEnd());
		obj[text] = text2;
		return false;
	}

	private static bool AllowStructureDamage(HitData __1)
	{
		SiegeState current = SiegePlugin.Current;
		if (current != null && SiegeRules.Objective(current.Difficulty, current.Target, current.Wave) == Objectives.Defenders)
		{
			return !IsRaider(__1.GetAttacker());
		}
		return true;
	}
}
internal sealed class Settlement
{
	internal const float BuildRadius = 38f;

	internal const float OccupiedRadius = 76f;

	internal const float IsolationRadius = 150f;

	private static readonly int Workbench = StringExtensionMethods.GetStableHashCode("piece_workbench");

	private static readonly SimulationDistance Nearby = new SimulationDistance(2, 2, false);

	private readonly List<ZDO> _near = new List<ZDO>();

	private readonly List<ZDO> _far = new List<ZDO>();

	private readonly Dictionary<int, bool> _structures = new Dictionary<int, bool>();

	private readonly Dictionary<int, bool> _baseObjects = new Dictionary<int, bool>();

	internal bool TryFind(Vector3 playerPosition, int minimum, out Vector3 center)
	{
		//IL_0001: 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_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: 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_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: 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_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		center = default(Vector3);
		if (Character.InInterior(playerPosition))
		{
			return false;
		}
		ReadNearby(playerPosition);
		float num = 45f;
		bool result = false;
		foreach (ZDO item in _near)
		{
			if (item.GetPrefab() == Workbench && IsPlayerBuilt(item))
			{
				Vector3 position = item.GetPosition();
				float num2 = Vector3.Distance(position, playerPosition);
				if (!(num2 >= num) && Qualifies(position, minimum))
				{
					center = position;
					num = num2;
					result = true;
				}
			}
		}
		return result;
	}

	internal bool IsOccupied(Vector3 center)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		foreach (ZDO allCharacterZDO in ZNet.instance.GetAllCharacterZDOS())
		{
			Vector3 position = allCharacterZDO.GetPosition();
			if (!allCharacterZDO.GetBool(ZDOVars.s_dead, false) && Math.Abs(position.y - center.y) < 40f && SiegeRules.HorizontalDistance(position, center) <= 76f)
			{
				return true;
			}
		}
		return false;
	}

	internal bool HasNearbyStructure(Vector3 position, float radius)
	{
		//IL_001f: 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)
		foreach (ZDO item in _near)
		{
			if (IsPlayerBuilt(item) && SiegeRules.HorizontalDistance(item.GetPosition(), position) < radius)
			{
				return true;
			}
		}
		return false;
	}

	internal void ReadNearby(Vector3 position)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		_near.Clear();
		_far.Clear();
		ZDOMan.instance.FindSectorObjects(ZoneSystem.GetZone(position), Nearby, _near, _far);
	}

	private bool Qualifies(Vector3 center, int minimum)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: 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)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		int num = 0;
		int num2 = 0;
		foreach (ZDO item in _near)
		{
			if (!IsPlayerBuilt(item) || Vector3.Distance(item.GetPosition(), center) > 38f)
			{
				continue;
			}
			int prefab = item.GetPrefab();
			if (!_structures.TryGetValue(prefab, out var value))
			{
				GameObject prefab2 = ZNetScene.instance.GetPrefab(prefab);
				value = (Object)(object)prefab2 != (Object)null && IsStructural(prefab2.GetComponent<Piece>());
				_structures.Add(prefab, value);
				bool value2 = false;
				if ((Object)(object)prefab2 != (Object)null)
				{
					EffectArea[] componentsInChildren = prefab2.GetComponentsInChildren<EffectArea>(true);
					for (int i = 0; i < componentsInChildren.Length; i++)
					{
						if ((componentsInChildren[i].m_type & 4) != 0)
						{
							value2 = true;
						}
					}
				}
				_baseObjects.Add(prefab, value2);
			}
			if (value)
			{
				num++;
			}
			if (_baseObjects[prefab])
			{
				num2++;
			}
			if (num >= minimum && num2 >= 3)
			{
				return true;
			}
		}
		return false;
	}

	internal static bool IsPlayerBuilt(ZDO piece)
	{
		return piece.GetLong(ZDOVars.s_creator, 0L) != 0;
	}

	internal static bool IsGate(Piece piece)
	{
		if ((Object)(object)piece != (Object)null)
		{
			if (!((Object)(object)((Component)piece).GetComponent<Door>() != (Object)null))
			{
				return (Object)(object)((Component)piece).GetComponentInChildren<Door>() != (Object)null;
			}
			return true;
		}
		return false;
	}

	internal static bool IsStructural(Piece piece)
	{
		if ((Object)(object)piece == (Object)null || (Object)(object)((Component)piece).GetComponent<WearNTear>() == (Object)null)
		{
			return false;
		}
		string name = ((Object)((Component)piece).gameObject).name;
		if (!IsGate(piece) && !Has(name, "wall") && !Has(name, "floor") && !Has(name, "roof") && !Has(name, "beam") && !Has(name, "pole") && !Has(name, "pillar"))
		{
			return Has(name, "fence");
		}
		return true;
	}

	private static bool Has(string name, string part)
	{
		return name.IndexOf(part, StringComparison.OrdinalIgnoreCase) >= 0;
	}
}
internal sealed class SiegeDirector
{
	private const string StateKey = "siegenights_event";

	private const string RollKey = "siegenights_last_roll";

	private const string CooldownKey = "siegenights_next_day";

	internal const string RaiderKey = "siegenights_raider";

	internal const string WaveKey = "siegenights_wave";

	internal const string SlotKey = "siegenights_slot";

	internal const string DamageAllKey = "siegenights_damage_all";

	internal const string DamagePlayerKey = "siegenights_damage_player";

	internal const string ReportRpc = "SiegeNights.RaiderDeath";

	internal const string AckRpc = "SiegeNights.DeathAck";

	private readonly ManualLogSource _log;

	private readonly List<ZDO> _near = new List<ZDO>();

	private readonly List<ZDO> _far = new List<ZDO>();

	private readonly List<Vector3> _sites = new List<Vector3>();

	private readonly Dictionary<int, ZDOID> _waveRaiders = new Dictionary<int, ZDOID>();

	private readonly Dictionary<ZDOID, (ZPackage payload, float expires)> _pendingDeaths = new Dictionary<ZDOID, (ZPackage, float)>();

	private readonly List<ZDOID> _pendingIds = new List<ZDOID>();

	private Settlement _settlement = new Settlement();

	private ZoneSystem _world;

	private ZRoutedRpc _rpc;

	private string _encoded;

	private float _lastTick;

	private float _spawnBlockedFor;

	private int _lastRoll = -1;

	private int _nextDay;

	private bool _paused;

	private float _nextPublish;

	private float _nextSearch;

	internal readonly SiegeRules Rules;

	internal SiegeState Current { get; private set; }

	internal bool Ready
	{
		get
		{
			if ((Object)(object)ZoneSystem.instance != (Object)null && (Object)(object)ZNet.instance != (Object)null && ZRoutedRpc.instance != null && ZDOMan.instance != null && (Object)(object)ZNetScene.instance != (Object)null)
			{
				return (Object)(object)EnvMan.instance != (Object)null;
			}
			return false;
		}
	}

	internal SiegeDirector(SiegeRules rules, ManualLogSource log)
	{
		Rules = rules;
		_log = log;
	}

	internal void Tick(float now)
	{
		//IL_019a: Unknown result type (might be due to invalid IL or missing references)
		if (!Ready)
		{
			_world = null;
			Current = null;
			return;
		}
		if (_rpc != ZRoutedRpc.instance)
		{
			_rpc = ZRoutedRpc.instance;
			_rpc.Register<ZPackage>("SiegeNights.RaiderDeath", (Action<long, ZPackage>)ReceiveDeath);
			_rpc.Register<ZDOID>("SiegeNights.DeathAck", (Action<long, ZDOID>)ReceiveAcknowledgement);
			_pendingDeaths.Clear();
		}
		if ((Object)(object)_world != (Object)(object)ZoneSystem.instance)
		{
			_world = ZoneSystem.instance;
			_encoded = null;
			Current = null;
			_lastRoll = ReadDay("siegenights_last_roll", -1);
			_nextDay = ReadDay("siegenights_next_day", 0);
			_lastTick = now;
			_spawnBlockedFor = 0f;
			_nextPublish = now;
			_nextSearch = now;
			_paused = false;
			_settlement = new Settlement();
			_waveRaiders.Clear();
		}
		if (Current == null || !ZNet.instance.IsServer())
		{
			ReadState();
		}
		float num = Mathf.Clamp(now - _lastTick, 0f, 3f);
		_lastTick = now;
		if (!ZNet.instance.IsServer())
		{
			RetryDeathReports(now);
		}
		else
		{
			if (Time.timeScale <= 0f)
			{
				return;
			}
			SiegeState current = Current;
			if (current == null)
			{
				Schedule(now);
				return;
			}
			if (current.Phase == Phase.Aftermath)
			{
				current.Seconds -= num;
				if (current.Seconds <= 0f)
				{
					Clear();
				}
				return;
			}
			bool flag = _settlement.IsOccupied(current.Center);
			if (_paused != !flag)
			{
				_paused = !flag;
				Publish();
			}
			if (!flag)
			{
				return;
			}
			if ((current.Phase == Phase.Assault || current.Phase == Phase.Breather) && current.NightOnly && !EnvMan.IsNight())
			{
				Finish(victory: false, "Daybreak. The warband withdrew before the settlement defeated every wave.");
				return;
			}
			current.Seconds = Mathf.Max(0f, current.Seconds - num);
			switch (current.Phase)
			{
			case Phase.Warning:
				if (current.Seconds <= 0f && (!current.NightOnly || EnvMan.IsNight()) && VanillaRaidClear())
				{
					OpenWave();
				}
				else if (now >= _nextPublish)
				{
					Publish();
				}
				break;
			case Phase.Breather:
				if (current.Seconds <= 0f)
				{
					OpenWave();
				}
				else if (now >= _nextPublish)
				{
					Publish();
				}
				break;
			case Phase.Assault:
				AdvanceWave(num);
				break;
			}
		}
	}

	private void Schedule(float now)
	{
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: Unknown result type (might be due to invalid IL or missing references)
		//IL_017f: Unknown result type (might be due to invalid IL or missing references)
		float dayFraction = EnvMan.instance.GetDayFraction();
		float num = default(float);
		if (!Rules.Automatic.Value || !VanillaRaidClear() || dayFraction < 0.31f || dayFraction >= 0.73f || (ZoneSystem.instance.GetGlobalKey((GlobalKeys)3, ref num) && num <= 0f))
		{
			return;
		}
		int day = EnvMan.instance.GetDay();
		if (day == _lastRoll || day < _nextDay || now < _nextSearch)
		{
			return;
		}
		_nextSearch = now + 8f;
		_sites.Clear();
		foreach (ZDO allCharacterZDO in ZNet.instance.GetAllCharacterZDOS())
		{
			if (!allCharacterZDO.GetBool(ZDOVars.s_dead, false) && _settlement.TryFind(allCharacterZDO.GetPosition(), Rules.MinimumStructures.Value, out var center) && !_sites.Exists((Vector3 site) => SiegeRules.HorizontalDistance(site, center) < 38f))
			{
				_sites.Add(center);
			}
		}
		if (_sites.Count != 0)
		{
			_lastRoll = day;
			SetDay("siegenights_last_roll", day);
			if (Random.Range(0, 100) < Rules.Chance.Value)
			{
				Begin(_sites[Random.Range(0, _sites.Count)], Rules.Difficulty.Value, test: false);
			}
		}
	}

	internal string Check(Vector3 position)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		if (!_settlement.TryFind(position, Rules.MinimumStructures.Value, out var _))
		{
			return $"Build a workbench, two other base objects (such as a bed and campfire), and {Rules.MinimumStructures.Value} walls, floors or roof pieces close together.";
		}
		return "This settlement qualifies for a siege.";
	}

	internal string Start(Vector3 position, Difficulty difficulty, bool test)
	{
		//IL_0021: 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_003c: Unknown result type (might be due to invalid IL or missing references)
		if (Current != null)
		{
			return "A siege is already active. Use siege stop to end it.";
		}
		if (!VanillaRaidClear())
		{
			return "Wait for the current Valheim raid to end.";
		}
		if (!_settlement.TryFind(position, Rules.MinimumStructures.Value, out var center))
		{
			return Check(position);
		}
		Begin(center, difficulty, test);
		if (!test)
		{
			return $"{difficulty} siege scheduled here. At least {Rules.WarningSeconds.Value} seconds to prepare before the nighttime assault.";
		}
		return $"{difficulty} test scheduled here. At least 20 seconds to prepare, then the first wave waits for nightfall.";
	}

	private void Begin(Vector3 center, Difficulty difficulty, bool test)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0173: Unknown result type (might be due to invalid IL or missing references)
		Current = new SiegeState
		{
			Id = DateTime.UtcNow.Ticks,
			Center = center,
			Difficulty = difficulty,
			Wave = 1,
			Waves = SiegeRules.WaveCount(difficulty, Rules.MaxWaves.Value),
			Phase = Phase.Warning,
			Target = Rules.Target.Value,
			Seconds = (test ? 20f : ((float)Rules.WarningSeconds.Value)),
			Test = test,
			NightOnly = true,
			AliveLimit = Rules.MaxAlive.Value,
			HealthMultiplier = Rules.HealthScale.Value,
			RewardCoins = ((!test || Rules.TestPayout.Value) ? Rules.Coins.Value : 0),
			WaveSeconds = Rules.WaveSeconds.Value,
			RepairSeconds = Rules.RepairSeconds.Value
		};
		if (!test)
		{
			_nextDay = EnvMan.instance.GetDay() + Rules.CooldownDays.Value;
			SetDay("siegenights_next_day", _nextDay);
		}
		_paused = false;
		Publish();
		_log.LogInfo((object)$"{difficulty} siege warning at {center}, {Current.Waves} waves.");
	}

	private void OpenWave()
	{
		Current.Phase = Phase.Assault;
		Current.Seconds = Current.WaveSeconds;
		Current.Released = 0;
		Current.Fallen = 0;
		Current.DefeatedSlots = 0;
		_spawnBlockedFor = 0f;
		_waveRaiders.Clear();
		Publish();
		_log.LogInfo((object)$"Wave {Current.Wave}/{Current.Waves} started. Objective {SiegeRules.Objective(Current.Difficulty, Current.Target, Current.Wave)}.");
	}

	private void AdvanceWave(float elapsed)
	{
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_0229: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		SiegeState current = Current;
		int num = 0;
		bool flag = false;
		ReadRaiders();
		foreach (ZDO item in _near)
		{
			if (item.GetLong("siegenights_raider", 0L) != current.Id || item.GetInt("siegenights_wave", 0) != current.Wave)
			{
				continue;
			}
			int num2 = item.GetInt("siegenights_slot", 0);
			if (num2 < 1 || num2 > SiegeRules.WaveSize(current.Difficulty, current.Wave))
			{
				continue;
			}
			_waveRaiders[num2] = item.m_uid;
			current.Released = Math.Max(current.Released, num2);
			if ((current.DefeatedSlots & (1 << num2 - 1)) != 0)
			{
				continue;
			}
			if (item.GetFloat(ZDOVars.s_health, 1f) > 0f)
			{
				if (SiegeRules.HorizontalDistance(item.GetPosition(), current.Center) > 150f)
				{
					Finish(victory: false, "The attackers scattered. The siege is over.");
					return;
				}
				num++;
			}
			else
			{
				flag |= Deposit(num2, item.GetFloat("siegenights_damage_player", 0f), item.GetFloat("siegenights_damage_all", 0f));
			}
		}
		int num3 = SiegeRules.WaveSize(current.Difficulty, current.Wave);
		if (current.Fallen >= num3)
		{
			if (current.Wave >= current.Waves)
			{
				Finish(victory: true, null);
				return;
			}
			_log.LogInfo((object)$"Wave {current.Wave} defeated. Repair break.");
			current.Wave++;
			current.Phase = Phase.Breather;
			current.Seconds = current.RepairSeconds;
			current.Fallen = 0;
			current.Released = 0;
			current.DefeatedSlots = 0;
			Publish();
			return;
		}
		if (current.Seconds <= 0f)
		{
			Finish(victory: false, "The warband withdrew before the wave was defeated.");
			return;
		}
		int num4 = Math.Min(5, Math.Min(current.AliveLimit - num, num3 - current.Released));
		if (num4 > 0)
		{
			_settlement.ReadNearby(current.Center);
		}
		for (int i = 0; i < num4; i++)
		{
			if (!SpawnRaider(current.Released + 1))
			{
				break;
			}
			current.Released++;
			flag = true;
		}
		if (num4 > 0 && !flag && num == 0)
		{
			_spawnBlockedFor += elapsed;
			if (_spawnBlockedFor >= 15f)
			{
				Finish(victory: false, "The warband found no dry approach and withdrew.");
				return;
			}
		}
		else
		{
			_spawnBlockedFor = 0f;
		}
		if (flag || _lastTick >= _nextPublish)
		{
			Publish();
		}
	}

	private void ReadRaiders()
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		_near.Clear();
		_far.Clear();
		ZDOMan.instance.FindSectorObjects(ZoneSystem.GetZone(Current.Center), new SimulationDistance(4, 4, false), _near, _far);
	}

	private bool Deposit(int slot, float playerDamage, float allDamage)
	{
		if (slot < 1 || slot > Current.Released || slot > SiegeRules.WaveSize(Current.Difficulty, Current.Wave) || float.IsNaN(allDamage) || float.IsInfinity(allDamage) || allDamage < 0f || allDamage > 100000f || float.IsNaN(playerDamage) || playerDamage < 0f || playerDamage > allDamage)
		{
			return false;
		}
		int num = 1 << slot - 1;
		if ((Current.DefeatedSlots & num) != 0)
		{
			return false;
		}
		Current.DefeatedSlots |= num;
		Current.Fallen++;
		Current.PlayerDamage += playerDamage;
		Current.TotalDamage += allDamage;
		return true;
	}

	internal void ReportDeath(ZDO raider)
	{
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Expected O, but got Unknown
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		if (Ready && raider.GetLong("siegenights_raider", 0L) != 0L)
		{
			float num = raider.GetFloat("siegenights_damage_player", 0f);
			float num2 = raider.GetFloat("siegenights_damage_all", 0f);
			if (ZNet.instance.IsServer())
			{
				TallyDeath(raider, num, num2);
				return;
			}
			ZPackage val = new ZPackage();
			val.Write(raider.GetLong("siegenights_raider", 0L));
			val.Write(raider.GetInt("siegenights_wave", 0));
			val.Write(raider.GetInt("siegenights_slot", 0));
			val.Write(raider.m_uid);
			val.Write(num);
			val.Write(num2);
			_pendingDeaths[raider.m_uid] = (val, Time.unscaledTime + 20f);
			ZRoutedRpc.instance.InvokeRoutedRPC("SiegeNights.RaiderDeath", new object[1] { val });
		}
	}

	private void ReceiveDeath(long sender, ZPackage payload)
	{
		//IL_0045: 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)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		if (!Ready || !ZNet.instance.IsServer() || payload == null || payload.Size() != 36 || ZNet.instance.GetPeer(sender) == null)
		{
			return;
		}
		long num = payload.ReadLong();
		int num2 = payload.ReadInt();
		int num3 = payload.ReadInt();
		ZDOID val = payload.ReadZDOID();
		if (Current == null || Current.Id != num || Current.Wave != num2 || Current.Phase != Phase.Assault)
		{
			return;
		}
		ZDO zDO = ZDOMan.instance.GetZDO(val);
		if (!_waveRaiders.TryGetValue(num3, out var value))
		{
			if (zDO == null || zDO.GetLong("siegenights_raider", 0L) != num || zDO.GetInt("siegenights_wave", 0) != num2 || zDO.GetInt("siegenights_slot", 0) != num3)
			{
				return;
			}
			value = val;
			_waveRaiders[num3] = val;
		}
		if (!(value != val) && (zDO == null || zDO.GetOwner() == sender))
		{
			if (Deposit(num3, payload.ReadSingle(), payload.ReadSingle()))
			{
				Publish();
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(sender, "SiegeNights.DeathAck", new object[1] { val });
		}
	}

	private void ReceiveAcknowledgement(long sender, ZDOID id)
	{
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		if (!ZNet.instance.IsServer() && sender == ZNet.instance.GetServerPeer()?.m_uid)
		{
			_pendingDeaths.Remove(id);
		}
	}

	private void RetryDeathReports(float now)
	{
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		_pendingIds.Clear();
		_pendingIds.AddRange(_pendingDeaths.Keys);
		foreach (ZDOID pendingId in _pendingIds)
		{
			(ZPackage, float) tuple = _pendingDeaths[pendingId];
			if (now >= tuple.Item2)
			{
				_pendingDeaths.Remove(pendingId);
				continue;
			}
			ZRoutedRpc.instance.InvokeRoutedRPC("SiegeNights.RaiderDeath", new object[1] { tuple.Item1 });
		}
	}

	private void TallyDeath(ZDO raider, float player, float total)
	{
		if (Current != null && Current.Phase == Phase.Assault && raider.GetLong("siegenights_raider", 0L) == Current.Id && raider.GetInt("siegenights_wave", 0) == Current.Wave && Deposit(raider.GetInt("siegenights_slot", 0), player, total))
		{
			Publish();
		}
	}

	private bool SpawnRaider(int slot)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_014b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0164: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Unknown result type (might be due to invalid IL or missing references)
		//IL_018a: Unknown result type (might be due to invalid IL or missing references)
		//IL_018f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0206: Unknown result type (might be due to invalid IL or missing references)
		//IL_020c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0213: Unknown result type (might be due to invalid IL or missing references)
		//IL_0218: Unknown result type (might be due to invalid IL or missing references)
		//IL_021d: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
		SiegeState current = Current;
		ZoneSystem instance = ZoneSystem.instance;
		WorldGenerator instance2 = WorldGenerator.instance;
		if (instance2 == null)
		{
			return false;
		}
		GameObject val = RaiderPrefab(instance2.GetBiome(current.Center), current.Wave, slot);
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		int num = (current.Wave - 1) % 4;
		float num2 = (float)(int)(current.Id % 360) + 90f * (float)num;
		List<ZDO> allCharacterZDOS = ZNet.instance.GetAllCharacterZDOS();
		float height = default(float);
		float num5 = default(float);
		float num6 = default(float);
		Character val3 = default(Character);
		ZNetView val4 = default(ZNetView);
		MonsterAI val5 = default(MonsterAI);
		for (int i = 0; i < 24; i++)
		{
			float num3 = (num2 + (float)(i / 6) * 90f + Random.Range(-29f, 29f)) * (MathF.PI / 180f);
			float num4 = Random.Range(44f, 65f);
			Vector3 point = current.Center + new Vector3(Mathf.Sin(num3) * num4, 0f, Mathf.Cos(num3) * num4);
			if (!instance.GetGroundHeight(point, ref height))
			{
				height = instance2.GetHeight(point);
			}
			if (height < instance.m_waterLevel + 0.4f || Math.Abs(height - current.Center.y) > 13f)
			{
				continue;
			}
			point.y = height + 0.35f;
			if (ZoneSystem.IsLavaPreHeightmap(point, height) || _settlement.HasNearbyStructure(point, 4.5f) || (instance.GetGroundHeight(point + Vector3.forward * 2f, ref num5) && Math.Abs(num5 - height) > 2.5f) || (instance.GetGroundHeight(point + Vector3.right * 2f, ref num6) && Math.Abs(num6 - height) > 2.5f) || allCharacterZDOS.Exists((ZDO player) => SiegeRules.HorizontalDistance(player.GetPosition(), point) < 14f))
			{
				continue;
			}
			GameObject val2 = Object.Instantiate<GameObject>(val, point, Quaternion.LookRotation(current.Center - point));
			if (!val2.TryGetComponent<Character>(ref val3) || !val2.TryGetComponent<ZNetView>(ref val4) || !val4.IsValid() || !val2.TryGetComponent<MonsterAI>(ref val5))
			{
				if ((Object)(object)val2 != (Object)null)
				{
					ZNetScene.instance.Destroy(val2);
				}
				return false;
			}
			ZDO zDO = val4.GetZDO();
			zDO.Set("siegenights_raider", current.Id);
			zDO.Set("siegenights_wave", current.Wave);
			zDO.Set("siegenights_slot", slot);
			_waveRaiders[slot] = zDO.m_uid;
			zDO.Persistent = true;
			val3.SetLevel(1);
			val3.SetMaxHealth(Mathf.Max(10f, val3.GetMaxHealth() * current.HealthMultiplier));
			CharacterDrop component = val2.GetComponent<CharacterDrop>();
			if (component != null)
			{
				component.SetDropsEnabled(false);
			}
			val5.SetDespawnInDay(false);
			((BaseAI)val5).SetHuntPlayer(false);
			((BaseAI)val5).Alert();
			return true;
		}
		return false;
	}

	private static GameObject RaiderPrefab(Biome biome, int wave, int slot)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Invalid comparison between Unknown and I4
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Invalid comparison between Unknown and I4
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Invalid comparison between Unknown and I4
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Invalid comparison between Unknown and I4
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Invalid comparison between Unknown and I4
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Invalid comparison between Unknown and I4
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Invalid comparison between Unknown and I4
		bool flag = wave > 1 && slot % 5 == 0;
		string text;
		if ((int)biome <= 16)
		{
			if ((int)biome != 2)
			{
				if ((int)biome != 4)
				{
					if ((int)biome != 16)
					{
						goto IL_007a;
					}
					text = "Goblin";
				}
				else
				{
					text = "Ulv";
				}
			}
			else
			{
				text = (flag ? "Draugr_Ranged" : "Draugr");
			}
		}
		else if ((int)biome != 32)
		{
			if ((int)biome != 64)
			{
				if ((int)biome != 512)
				{
					goto IL_007a;
				}
				text = "Seeker";
			}
			else
			{
				text = "Skeleton_NoArcher";
			}
		}
		else
		{
			text = (flag ? "Charred_Archer" : "Charred_Twitcher");
		}
		goto IL_0090;
		IL_0090:
		return ZNetScene.instance.GetPrefab(text) ?? ZNetScene.instance.GetPrefab("Greydwarf");
		IL_007a:
		text = ((wave > 1 && slot % 4 == 0) ? "Skeleton_NoArcher" : "Greydwarf");
		goto IL_0090;
	}

	private void Finish(bool victory, string reason)
	{
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		SiegeState current = Current;
		current.Phase = Phase.Aftermath;
		current.Seconds = 40f;
		current.FinalCoins = ((victory && SiegeRules.EarnsCoins(current.PlayerDamage, current.TotalDamage)) ? current.RewardCoins : 0);
		if (!victory)
		{
			current.FinalCoins = -1;
		}
		Publish();
		if (current.FinalCoins > 0)
		{
			GameObject prefab = ZNetScene.instance.GetPrefab("Coins");
			ItemDrop val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val == (Object)null)
			{
				current.FinalCoins = 0;
			}
			else
			{
				int num = Math.Max(1, val.m_itemData.m_shared.m_maxStackSize);
				for (int num2 = current.FinalCoins; num2 > 0; num2 -= num)
				{
					Object.Instantiate<GameObject>(prefab, current.Center + Vector3.up * 1.3f, Quaternion.identity).GetComponent<ItemDrop>().SetStack(Math.Min(num, num2));
				}
			}
		}
		Publish();
		RemoveRaiders();
		_log.LogInfo((object)(reason ?? $"Siege held. Player damage {current.PlayerDamage:F0}/{current.TotalDamage:F0}. Coins: {current.FinalCoins}."));
	}

	private void RemoveRaiders()
	{
		ReadRaiders();
		foreach (ZDO item in _near)
		{
			if (item.GetLong("siegenights_raider", 0L) == Current.Id)
			{
				item.SetOwner(ZDOMan.GetSessionID());
				ZNetView val = ZNetScene.instance.FindInstance(item);
				if ((Object)(object)val != (Object)null)
				{
					ZNetScene.instance.Destroy(((Component)val).gameObject);
				}
				else
				{
					ZDOMan.instance.DestroyZDO(item);
				}
			}
		}
	}

	private void Clear()
	{
		Current = null;
		_waveRaiders.Clear();
		_encoded = "-";
		ZoneSystem.instance.SetGlobalKey("siegenights_event -");
	}

	internal string Stop()
	{
		if (Current == null)
		{
			return "No siege is active.";
		}
		if (Current.Phase != Phase.Aftermath)
		{
			Finish(victory: false, "Siege stopped by the host.");
		}
		else
		{
			RemoveRaiders();
		}
		Clear();
		return "Siege ended.";
	}

	internal string Status()
	{
		SiegeState current = Current;
		if (current == null)
		{
			return "No siege is active.";
		}
		Objectives objectives = SiegeRules.Objective(current.Difficulty, current.Target, current.Wave);
		return $"{current.Difficulty} siege: {current.Phase}, wave {current.Wave}/{current.Waves}, target {objectives}. " + $"{current.Fallen}/{SiegeRules.WaveSize(current.Difficulty, current.Wave)} defeated. {Mathf.CeilToInt(current.Seconds)} seconds. " + (EnvMan.IsNight() ? "Night" : "Day") + ", weather " + EnvMan.instance.GetCurrentEnvironment()?.m_name + ".";
	}

	private void ReadState()
	{
		string text = default(string);
		if (!ZoneSystem.instance.GetGlobalKey("siegenights_event", ref text))
		{
			text = "-";
		}
		if (!(_encoded == text))
		{
			_encoded = text;
			Current = SiegeState.Decode(text);
			if (Current != null)
			{
				Current.NightOnly = true;
			}
			else if (text != "-" && ZNet.instance.IsServer())
			{
				_log.LogWarning((object)"Discarded invalid saved siege state. Orphaned raiders will be removed when loaded.");
				_encoded = "-";
				ZoneSystem.instance.SetGlobalKey("siegenights_event -");
			}
		}
	}

	private void Publish()
	{
		Current.ClockAtWrite = ZNet.instance.GetTimeSeconds();
		Current.Paused = _paused;
		_nextPublish = _lastTick + 5f;
		_encoded = Current.Encode();
		ZoneSystem.instance.SetGlobalKey("siegenights_event " + _encoded);
	}

	private static bool VanillaRaidClear()
	{
		if (!((Object)(object)RandEventSystem.instance == (Object)null))
		{
			return RandEventSystem.instance.GetCurrentRandomEvent() == null;
		}
		return true;
	}

	private static int ReadDay(string key, int fallback)
	{
		string s = default(string);
		if (!ZoneSystem.instance.GetGlobalKey(key, ref s) || !int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
		{
			return fallback;
		}
		return result;
	}

	private static void SetDay(string key, int day)
	{
		ZoneSystem.instance.SetGlobalKey(key + " " + day.ToString(CultureInfo.InvariantCulture));
	}
}
[BepInPlugin("serge.valheim.siegenights", "Siege Nights", "0.2.1")]
public sealed class SiegePlugin : BaseUnityPlugin
{
	public const string Version = "0.2.1";

	internal static SiegeDirector Director;

	private SiegePresentation _presentation;

	private Harmony _harmony;

	private float _nextTick;

	internal static SiegeState Current => Director?.Current;

	private void Awake()
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Expected O, but got Unknown
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Expected O, but got Unknown
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		Director = new SiegeDirector(new SiegeRules(((BaseUnityPlugin)this).Config), ((BaseUnityPlugin)this).Logger);
		_harmony = new Harmony("serge.valheim.siegenights");
		try
		{
			RaiderCombat.Install(_harmony);
		}
		catch
		{
			_harmony.UnpatchSelf();
			Director = null;
			((Behaviour)this).enabled = false;
			throw;
		}
		new ConsoleCommand("siege", "Siege Nights: status, check, outpost, omen, start, test [easy|normal|hard], reload, stop", (ConsoleEvent)delegate(ConsoleEventArgs args)
		{
			args.Context.AddString(RunCommand(args));
		}, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Siege Nights 0.2.1 loaded");
	}

	private string RunCommand(ConsoleEventArgs args)
	{
		//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_026f: Unknown result type (might be due to invalid IL or missing references)
		if (!Director.Ready)
		{
			return "Enter a world first.";
		}
		string text = ((args.Length > 1) ? args[1].ToLowerInvariant() : "status");
		if (text == "status")
		{
			return Director.Status();
		}
		if (text == "omen")
		{
			Player localPlayer = Player.m_localPlayer;
			if (_presentation == null || (Object)(object)localPlayer == (Object)null || ((Character)localPlayer).InInterior())
			{
				return "Stand outdoors to preview the siege warning.";
			}
			if (Current != null)
			{
				return "A siege is already active.";
			}
			GameCamera instance = GameCamera.instance;
			Vector3 forward = (((Object)(object)instance != (Object)null) ? ((Component)instance).transform.forward : ((Component)localPlayer).transform.forward);
			_presentation.Preview(((Component)localPlayer).transform.position, forward);
			return "20-second warning preview. Close the console and look toward the storm.";
		}
		if (!ZNet.instance.IsServer())
		{
			return "The world host can run this command.";
		}
		if (text == "stop")
		{
			return Director.Stop();
		}
		if (text == "reload")
		{
			((BaseUnityPlugin)this).Config.Reload();
			return $"Settings reloaded. Next siege: {Director.Rules.Difficulty.Value}, {Director.Rules.Target.Value}, " + $"{SiegeRules.WaveCount(Director.Rules.Difficulty.Value, Director.Rules.MaxWaves.Value)} waves.";
		}
		Player localPlayer2 = Player.m_localPlayer;
		if ((Object)(object)localPlayer2 == (Object)null)
		{
			return "Stand at the settlement in a locally hosted world.";
		}
		switch (text)
		{
		case "check":
			return Director.Check(((Component)localPlayer2).transform.position);
		case "outpost":
			if (!args.Context.IsCheatsEnabled())
			{
				return "Enable devcommands in your test world to build a free outpost.";
			}
			if (Current != null)
			{
				return "End the current siege before building a test outpost.";
			}
			return TestOutpost.Build(localPlayer2);
		case "test":
		case "start":
		{
			Difficulty result = Director.Rules.Difficulty.Value;
			if (args.Length > 2 && (!Enum.TryParse<Difficulty>(args[2], ignoreCase: true, out result) || !Enum.IsDefined(typeof(Difficulty), result)))
			{
				return "Usage: siege start|test [easy|normal|hard]";
			}
			return Director.Start(((Component)localPlayer2).transform.position, result, text == "test");
		}
		default:
			return "Usage: siege status | check | outpost | omen | start/test [easy|normal|hard] | reload | stop";
		}
	}

	private void Update()
	{
		if (Director != null)
		{
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime >= _nextTick)
			{
				_nextTick = unscaledTime + 1f;
				Director.Tick(unscaledTime);
			}
		}
	}

	private void LateUpdate()
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Invalid comparison between Unknown and I4
		if (Director != null && (int)SystemInfo.graphicsDeviceType != 4)
		{
			if (_presentation == null)
			{
				_presentation = new SiegePresentation(((BaseUnityPlugin)this).Logger);
			}
			_presentation.Update(Current);
		}
	}

	private void OnGUI()
	{
		_presentation?.DrawWarning();
	}

	private void OnDestroy()
	{
		_presentation?.Dispose();
		Harmony harmony = _harmony;
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		Director = null;
	}
}
internal sealed class SiegePresentation : IDisposable
{
	private const float PreviewSeconds = 20f;

	private readonly ManualLogSource _log;

	private readonly SpriteRenderer[] _clouds = (SpriteRenderer[])(object)new SpriteRenderer[18];

	private readonly Vector3[] _boltPoints = (Vector3[])(object)new Vector3[9];

	private long _lastId;

	private Phase _lastPhase;

	private int _lastWave;

	private float _nextStrike;

	private float _strikeTime;

	private bool _finalStrike;

	private SiegeState _preview;

	private ZNetScene _previewWorld;

	private Vector3 _previewDirection;

	private float _previewUntil;

	private string _warningTitle;

	private string _warningDetail;

	private GUIStyle _titleStyle;

	private GUIStyle _detailStyle;

	private GameObject _storm;

	private Sprite _sprite;

	private Texture2D _texture;

	private LineRenderer _bolt;

	private Light _flashLight;

	private Material _boltMaterial;

	private AudioClip _fallbackThunder;

	private int _openingStrikes;

	internal static bool StormActive { get; private set; }

	internal SiegePresentation(ManualLogSource log)
	{
		_log = log;
	}

	internal void Preview(Vector3 center, Vector3 forward)
	{
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: 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)
		_preview = new SiegeState
		{
			Id = DateTime.UtcNow.Ticks,
			Phase = Phase.Warning,
			Wave = 1,
			Center = center
		};
		_previewUntil = Time.unscaledTime + 20f;
		_previewWorld = ZNetScene.instance;
		forward.y = 0f;
		_previewDirection = ((Vector3)(ref forward)).normalized;
	}

	internal void Update(SiegeState state)
	{
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_044c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0444: Unknown result type (might be due to invalid IL or missing references)
		//IL_0451: Unknown result type (might be due to invalid IL or missing references)
		//IL_0454: Unknown result type (might be due to invalid IL or missing references)
		//IL_0459: Unknown result type (might be due to invalid IL or missing references)
		//IL_0460: Unknown result type (might be due to invalid IL or missing references)
		//IL_0465: Unknown result type (might be due to invalid IL or missing references)
		//IL_046a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0510: Unknown result type (might be due to invalid IL or missing references)
		//IL_0503: Unknown result type (might be due to invalid IL or missing references)
		//IL_0505: Unknown result type (might be due to invalid IL or missing references)
		float unscaledTime = Time.unscaledTime;
		if (_preview != null)
		{
			if ((Object)(object)_previewWorld != (Object)(object)ZNetScene.instance || unscaledTime >= _previewUntil || state != null)
			{
				_preview = null;
			}
			else
			{
				_preview.Seconds = _previewUntil - unscaledTime;
				state = _preview;
			}
		}
		_warningTitle = null;
		StormActive = false;
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null || state == null || ((Character)localPlayer).InInterior() || SiegeRules.HorizontalDistance(((Component)localPlayer).transform.position, state.Center) > 260f)
		{
			if ((Object)(object)_storm != (Object)null)
			{
				_storm.SetActive(false);
			}
			_lastId = 0L;
			return;
		}
		if (_lastId != state.Id || _lastPhase != state.Phase || _lastWave != state.Wave)
		{
			_lastId = state.Id;
			_lastPhase = state.Phase;
			_lastWave = state.Wave;
			_nextStrike = unscaledTime + ((state.Phase == Phase.Warning) ? 2.5f : 0.3f);
			_strikeTime = float.NegativeInfinity;
			_finalStrike = false;
			_openingStrikes = ((state.Phase == Phase.Warning) ? 3 : 0);
			if (_openingStrikes > 0)
			{
				_nextStrike = unscaledTime + 0.5f;
			}
			Announce(state);
		}
		float num = state.Seconds;
		if (_preview == null && !state.Paused && (Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer())
		{
			num -= Mathf.Clamp((float)(ZNet.instance.GetTimeSeconds() - state.ClockAtWrite), 0f, 6f);
		}
		int num2 = Mathf.Max(0, Mathf.CeilToInt(num));
		string text = $"{num2 / 60}:{num2 % 60:00}";
		if (state.Phase == Phase.Warning)
		{
			_warningTitle = ((_preview != null) ? "SIEGE WARNING PREVIEW" : "A WARBAND APPROACHES");
			_warningDetail = (state.Paused ? "The warband waits for defenders to return" : ((num2 == 0 && state.NightOnly) ? "The warband waits for nightfall" : ("First wave in " + text + "  ·  Prepare the defenses")));
		}
		else if (state.Phase == Phase.Assault)
		{
			_warningTitle = $"DEFEND THE SETTLEMENT  ·  WAVE {state.Wave}/{state.Waves}";
			int num3 = SiegeRules.WaveSize(state.Difficulty, state.Wave);
			_warningDetail = (state.Paused ? "The siege waits for defenders to return" : $"{state.Fallen}/{num3} defeated  ·  {SiegeRules.Objective(state.Difficulty, state.Target, state.Wave)}  ·  {text}");
		}
		else if (state.Phase == Phase.Breather)
		{
			_warningTitle = "REPAIR AND REGROUP";
			_warningDetail = (state.Paused ? "The siege waits for defenders to return" : $"Wave {state.Wave}/{state.Waves} approaches in {text}");
		}
		else if (state.Phase == Phase.Aftermath)
		{
			_warningTitle = ((state.FinalCoins < 0) ? "THE WARBAND WITHDREW" : "THE SETTLEMENT HELD");
			_warningDetail = ((state.FinalCoins > 0) ? $"{state.FinalCoins} shared coins await at the workbench" : ((state.FinalCoins < 0) ? "The remaining attackers have left" : ((state.Test && state.RewardCoins == 0) ? "Test complete  ·  Repair the defenses" : ((state.RewardCoins > 0) ? "The defenders needed to deal most of the damage to earn coins" : "Repair the defenses"))));
		}
		Camera val = (((Object)(object)GameCamera.instance != (Object)null) ? ((Component)GameCamera.instance).GetComponent<Camera>() : Camera.main);
		if ((Object)(object)val == (Object)null || state.Phase == Phase.Aftermath)
		{
			if ((Object)(object)_storm != (Object)null)
			{
				_storm.SetActive(false);
			}
			return;
		}
		if ((Object)(object)_storm == (Object)null)
		{
			CreateStorm();
		}
		StormActive = true;
		_storm.SetActive(true);
		Vector3 val2 = ((_preview != null) ? _previewDirection : ApproachDirection(state));
		Vector3 center = state.Center + val2 * 30f;
		bool flag = !_finalStrike && state.Phase == Phase.Warning && num > 0f && num <= 5f;
		if (!state.Paused && (unscaledTime >= _nextStrike || flag))
		{
			_finalStrike |= flag;
			if (_openingStrikes > 0)
			{
				_openingStrikes--;
			}
			_nextStrike = unscaledTime + ((_openingStrikes > 0) ? 1.15f : ((state.Phase == Phase.Warning) ? 24f : 35f));
			Strike(state, center, val2, unscaledTime);
		}
		DrawStorm(val, center, unscaledTime);
	}

	private static Vector3 ApproachDirection(SiegeState state)
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		float num = ((float)(int)(state.Id % 360) + 90f * (float)((state.Wave - 1) % 4)) * (MathF.PI / 180f);
		return new Vector3(Mathf.Sin(num), 0f, Mathf.Cos(num));
	}

	private void Announce(SiegeState state)
	{
		if (state.Phase == Phase.Warning)
		{
			_log.LogInfo((object)((_preview == null) ? "Showing siege warning effects." : "Showing local siege warning preview."));
		}
		else if (!((Object)(object)MessageHud.instance == (Object)null))
		{
			string text;
			switch (state.Phase)
			{
			default:
				return;
			case Phase.Assault:
			{
				Objectives objectives = SiegeRules.Objective(state.Difficulty, state.Target, state.Wave);
				text = string.Format("Wave {0} of {1}. {2}", state.Wave, state.Waves, objectives switch
				{
					Objectives.Structures => "They are attacking the defenses.", 
					Objectives.Gates => "They are coming for the gates.", 
					_ => "Stand your ground.", 
				});
				break;
			}
			case Phase.Breather:
				text = "The assault breaks. You have a moment to repair and regroup.";
				break;
			case Phase.Aftermath:
				text = ((state.FinalCoins > 0) ? $"The settlement held. Collect {state.FinalCoins} coins at the workbench." : ((state.FinalCoins < 0) ? "The warband has withdrawn." : ((state.Test && state.RewardCoins == 0) ? "The settlement held. Test siege complete." : ((state.RewardCoins == 0) ? "The settlement held." : "The settlement held. Defenders must deal most of the damage to earn the reward."))));
				break;
			}
			MessageHud.instance.ShowMessage((MessageType)2, text, 0, (Sprite)null, false, true);
		}
	}

	internal void DrawWarning()
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Invalid comparison between Unknown and I4
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: 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_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Expected O, but got Unknown
		if (_warningTitle != null && (int)Event.current.type == 7)
		{
			if (_titleStyle == null)
			{
				GUIStyle val = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)4,
					fontStyle = (FontStyle)1
				};
				val.normal.textColor = new Color(1f, 0.75f, 0.37f);
				_titleStyle = val;
				GUIStyle val2 = new GUIStyle(_titleStyle)
				{
					fontStyle = (FontStyle)0
				};
				val2.normal.textColor = new Color(0.96f, 0.89f, 0.78f);
				_detailStyle = val2;
			}
			float num = Mathf.Clamp((float)Screen.height / 1080f, 0.72f, 2.2f);
			float num2 = Mathf.Min((float)Screen.width - 16f, 520f * num);
			Rect val3 = default(Rect);
			((Rect)(ref val3))..ctor(((float)Screen.width - num2) * 0.5f, 84f * num, num2, 58f * num);
			Color color = GUI.color;
			GUI.color = new Color(0.065f, 0.05f, 0.045f, 0.9f);
			GUI.DrawTexture(val3, (Texture)(object)Texture2D.whiteTexture);
			GUI.color = color;
			_titleStyle.fontSize = Mathf.RoundToInt(21f * num);
			_detailStyle.fontSize = Mathf.RoundToInt(15f * num);
			GUI.Label(new Rect(((Rect)(ref val3)).x, ((Rect)(ref val3)).y + 4f * num, num2, 25f * num), _warningTitle, _titleStyle);
			GUI.Label(new Rect(((Rect)(ref val3)).x, ((Rect)(ref val3)).y + 30f * num, num2, 23f * num), _warningDetail, _detailStyle);
		}
	}

	private void DrawStorm(Camera camera, Vector3 center, float now)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: 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_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0205: Unknown result type (might be due to invalid IL or missing references)
		//IL_0212: Unknown result type (might be due to invalid IL or missing references)
		Quaternion rotation = ((Component)camera).transform.rotation;
		float num = now - _strikeTime;
		float num2 = Mathf.Max(0f, 1f - num / 0.55f);
		((Component)_flashLight).transform.position = center + Vector3.up * 22f;
		((Behaviour)_flashLight).enabled = num2 > 0f;
		_flashLight.intensity = num2 * 5f;
		Vector3 val = default(Vector3);
		for (int i = 0; i < _clouds.Length; i++)
		{
			float num3 = (float)i * 2.399963f + now * (0.023f + (float)(i % 3) * 0.004f);
			float num4 = 5f + (float)(i * 13 % 38);
			float num5 = 14f + (float)(i * 7 % 36);
			((Vector3)(ref val))..ctor(Mathf.Cos(num3) * num4, num5, Mathf.Sin(num3) * num4);
			SpriteRenderer obj = _clouds[i];
			((Component)obj).transform.SetPositionAndRotation(center + val, rotation);
			((Component)obj).transform.localScale = new Vector3(29f + (float)(i * 13 % 22), 16f + (float)(i * 5 % 15), 1f);
			float num6 = num2 * (0.13f + (float)(i % 4) * 0.04f);
			obj.color = new Color(0.045f + num6, 0.051f + num6, 0.075f + num6, 0.77f);
		}
		if (!((Object)(object)_bolt == (Object)null))
		{
			((Renderer)_bolt).enabled = num < 0.26f && (num < 0.13f || num > 0.18f);
			if (((Renderer)_bolt).enabled)
			{
				Color val2 = default(Color);
				((Color)(ref val2))..ctor(0.78f, 0.86f, 1f, Mathf.Clamp01(1f - num * 2f));
				_bolt.startColor = val2;
				_bolt.endColor = new Color(val2.r, val2.g, val2.b, val2.a * 0.65f);
			}
		}
	}

	private void Strike(SiegeState state, Vector3 center, Vector3 approach, float now)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0133: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: 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_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		_strikeTime = now;
		Vector3 val = Vector3.Cross(Vector3.up, approach);
		Vector3 val2 = center + approach * 31f + val * Random.Range(-12f, 12f);
		val2.y = state.Center.y + 2f;
		float num = default(float);
		if (ZoneSystem.instance.GetGroundHeight(val2, ref num))
		{
			val2.y = num + 2f;
		}
		if ((Object)(object)_bolt != (Object)null)
		{
			Vector3 val3 = center + Vector3.up * 42f;
			for (int i = 0; i < _boltPoints.Length; i++)
			{
				float num2 = (float)i / (float)(_boltPoints.Length - 1);
				Vector3 val4 = ((i == 0 || i == _boltPoints.Length - 1) ? Vector3.zero : (val * Random.Range(-7f, 7f)));
				_boltPoints[i] = Vector3.Lerp(val3, val2, num2) + val4;
			}
			_bolt.SetPositions(_boltPoints);
		}
		PlayThunder(center + Vector3.up * 14f);
	}

	private void PlayThunder(Vector3 position)
	{
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0134: Expected O, but got Unknown
		ZNetScene instance = ZNetScene.instance;
		GameObject val = ((instance != null) ? instance.GetPrefab("sfx_thunder") : null);
		AudioSource val2 = (((Object)(object)val != (Object)null) ? val.GetComponentInChildren<AudioSource>(true) : null);
		AudioClip[] array = ((!((Object)(object)val != (Object)null)) ? null : val.GetComponentInChildren<ZSFX>(true)?.m_audioClips);
		AudioClip val3 = ((array != null && array.Length != 0) ? array[Random.Range(0, array.Length)] : ((val2 != null) ? val2.clip : null));
		if ((Object)(object)val3 == (Object)null)
		{
			if ((Object)(object)_fallbackThunder == (Object)null)
			{
				_fallbackThunder = CreateRumble();
			}
			val3 = _fallbackThunder;
		}
		GameObject val4 = new GameObject("Siege warning thunder");
		val4.transform.SetParent(_storm.transform);
		val4.transform.position = position;
		AudioSource obj = val4.AddComponent<AudioSource>();
		obj.outputAudioMixerGroup = ((val2 != null) ? val2.outputAudioMixerGroup : null);
		obj.clip = val3;
		obj.spatialBlend = 0.8f;
		obj.minDistance = 75f;
		obj.maxDistance = 260f;
		obj.rolloffMode = (AudioRolloffMode)1;
		obj.dopplerLevel = 0f;
		obj.volume = 0.72f;
		obj.Play();
		Object.Destroy((Object)val4, val3.length + 1f);
	}

	private static AudioClip CreateRumble()
	{
		float[] array = new float[88200];
		Random random = new Random(173);
		float num = 0f;
		float num2 = 0f;
		for (int i = 0; i < array.Length; i++)
		{
			float num3 = (float)i / 22050f;
			float num4 = (float)(random.NextDouble() * 2.0 - 1.0);
			num += (num4 - num) * 0.019f;
			num2 += (num4 - num2) * 0.2f;
			float num5 = Mathf.Min(1f, num3 * 75f);
			float num6 = Mathf.Max(0f, num3 - 0.55f);
			float num7 = (3.6f * num + 0.13f * Mathf.Sin(num3 * 283f + Mathf.Sin(num3 * 21f))) * (Mathf.Exp((0f - num3) * 1.55f) + 0.45f * Mathf.Sin(num6 * 3f) * Mathf.Exp((0f - num6) * 1.7f));
			float num8 = 0.52f * num2 * Mathf.Exp((0f - num3) * 13f);
			array[i] = Mathf.Clamp((num7 + num8) * num5 * Mathf.Clamp01((4f - num3) * 2f), -1f, 1f);
		}
		AudioClip obj = AudioClip.Create("Siege thunder rumble", array.Length, 1, 22050, false);
		obj.SetData(array, 0);
		return obj;
	}

	private void CreateStorm()
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: 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_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Expected O, but got Unknown
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c3: Expected O, but got Unknown
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d9: Expected O, but got Unknown
		//IL_022c: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_0258: Unknown result type (might be due to invalid IL or missing references)
		//IL_025d: Unknown result type (might be due to invalid IL or missing references)
		//IL_02de: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e4: Expected O, but got Unknown
		//IL_0308: Unknown result type (might be due to invalid IL or missing references)
		//IL_030d: Unknown result type (might be due to invalid IL or missing references)
		//IL_031d: Expected O, but got Unknown
		//IL_032e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0335: Expected O, but got Unknown
		//IL_034d: Unknown result type (might be due to invalid IL or missing references)
		//IL_035e: Unknown result type (might be due to invalid IL or missing references)
		_texture = new Texture2D(128, 128, (TextureFormat)4, true)
		{
			name = "Siege storm cloud",
			wrapMode = (TextureWrapMode)1,
			filterMode = (FilterMode)2
		};
		Color[] array = (Color[])(object)new Color[16384];
		for (int i = 0; i < 128; i++)
		{
			for (int j = 0; j < 128; j++)
			{
				float num = (float)j / 127f;
				float num2 = (float)i / 127f;
				Vector2 val = new Vector2(2f * num - 1f, 2f * num2 - 1f);
				float magnitude = ((Vector2)(ref val)).magnitude;
				float num3 = Mathf.PerlinNoise(4f * num + 21.3f, 4f * num2 + 17.8f);
				float num4 = Mathf.PerlinNoise(10f * num + 2f, 10f * num2 + 9f);
				float num5 = Mathf.Clamp01((1f - magnitude) * 3.4f);
				float num6 = Mathf.Clamp01((0.78f * num3 + 0.22f * num4 - 0.19f) * 2.6f);
				array[i * 128 + j] = new Color(1f, 1f, 1f, num5 * num6);
			}
		}
		_texture.SetPixels(array);
		_texture.Apply(true, true);
		_sprite = Sprite.Create(_texture, new Rect(0f, 0f, 128f, 128f), new Vector2(0.5f, 0.5f), 128f, 0u, (SpriteMeshType)0);
		_storm = new GameObject("Siege storm");
		Object.DontDestroyOnLoad((Object)(object)_storm);
		GameObject val2 = new GameObject("Siege lightning flash");
		val2.transform.SetParent(_storm.transform);
		_flashLight = val2.AddComponent<Light>();
		_flashLight.type = (LightType)2;
		_flashLight.range = 110f;
		_flashLight.color = new Color(0.78f, 0.85f, 1f);
		_flashLight.shadows = (LightShadows)0;
		((Behaviour)_flashLight).enabled = false;
		for (int k = 0; k < _clouds.Length; k++)
		{
			GameObject val3 = new GameObject("Siege storm cloud");
			val3.transform.SetParent(_storm.transform);
			SpriteRenderer val4 = val3.AddComponent<SpriteRenderer>();
			val4.sprite = _sprite;
			((Renderer)val4).allowOcclusionWhenDynamic = false;
			((Renderer)val4).shadowCastingMode = (ShadowCastingMode)0;
			_clouds[k] = val4;
		}
		Shader val5 = Shader.Find("Sprites/Default");
		if ((Object)(object)val5 == (Object)null)
		{
			_log.LogWarning((object)"Storm lightning shader unavailable. Clouds and thunder are still active.");
			return;
		}
		GameObject val6 = new GameObject("Siege storm lightning");
		val6.transform.SetParent(_storm.transform);
		_bolt = val6.AddComponent<LineRenderer>();
		_boltMaterial = new Material(val5)
		{
			renderQueue = 3020
		};
		((Renderer)_bolt).sharedMaterial = _boltMaterial;
		MaterialPropertyBlock val7 = new MaterialPropertyBlock();
		val7.SetTexture("_MainTex", (Texture)(object)Texture2D.whiteTexture);
		val7.SetColor("_RendererColor", Color.white);
		val7.SetVector("_Flip", Vector4.one);
		((Renderer)_bolt).SetPropertyBlock(val7);
		_bolt.positionCount = _boltPoints.Length;
		_bolt.startWidth = 0.36f;
		_bolt.endWidth = 0.09f;
		((Renderer)_bolt).shadowCastingMode = (ShadowCastingMode)0;
		((Renderer)_bolt).allowOcclusionWhenDynamic = false;
		((Renderer)_bolt).enabled = false;
	}

	public void Dispose()
	{
		StormActive = false;
		Object.Destroy((Object)(object)_storm);
		Object.Destroy((Object)(object)_boltMaterial);
		Object.Destroy((Object)(object)_sprite);
		Object.Destroy((Object)(object)_texture);
		Object.Destroy((Object)(object)_fallbackThunder);
	}
}
internal enum Difficulty
{
	Easy,
	Normal,
	Hard
}
internal enum Objectives
{
	Preset,
	Defenders,
	Gates,
	Structures
}
internal enum Phase
{
	None,
	Warning,
	Assault,
	Breather,
	Aftermath
}
internal sealed class SiegeRules
{
	internal readonly ConfigEntry<bool> Automatic;

	internal readonly ConfigEntry<bool> TestPayout;

	internal readonly ConfigEntry<Difficulty> Difficulty;

	internal readonly ConfigEntry<Objectives> Target;

	internal readonly ConfigEntry<int> MaxWaves;

	internal readonly ConfigEntry<int> MaxAlive;

	internal readonly ConfigEntry<int> Chance;

	internal readonly ConfigEntry<int> CooldownDays;

	internal readonly ConfigEntry<int> WarningSeconds;

	internal readonly ConfigEntry<int> WaveSeconds;

	internal readonly ConfigEntry<int> RepairSeconds;

	internal readonly ConfigEntry<int> MinimumStructures;

	internal readonly ConfigEntry<float> HealthScale;

	internal readonly ConfigEntry<int> Coins;

	internal SiegeRules(ConfigFile config)
	{
		//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c4: Expected O, but got Unknown
		Automatic = config.Bind<bool>("Sieges", "Automatic", false, "Enable random sieges on occupied settlements. Manual playtests remain available to the host.");
		Difficulty = config.Bind<Difficulty>("Sieges", "Difficulty", SiegeNights.Difficulty.Normal, "Choose Easy, Normal or Hard.");
		Target = config.Bind<Objectives>("Sieges", "Objectives", Objectives.Preset, "Preset, Defenders, Gates or Structures. The preset can change the objective between waves.");
		MaxWaves = config.Bind<int>("Sieges", "MaxWaves", 0, Range("Maximum waves per siege. 0 uses the preset.", 0, 5));
		MaxAlive = config.Bind<int>("Sieges", "MaxAlive", 14, Range("Maximum number of living siege raiders at once.", 3, 30));
		Chance = config.Bind<int>("Sieges", "DailyChancePercent", 25, Range("Chance of a siege on each eligible day.", 0, 100));
		CooldownDays = config.Bind<int>("Sieges", "CooldownDays", 3, Range("Minimum in-game days between sieges.", 1, 30));
		WarningSeconds = config.Bind<int>("Sieges", "WarningSeconds", 600, Range("Minimum real seconds of warning before the nighttime assault.", 20, 1200));
		WaveSeconds = config.Bind<int>("Sieges", "WaveSeconds", 240, Range("Time allowed to defeat each wave.", 60, 900));
		RepairSeconds = config.Bind<int>("Sieges", "RepairSeconds", 35, Range("Time between waves to repair and regroup.", 10, 180));
		MinimumStructures = config.Bind<int>("Settlement", "MinimumStructures", 6, Range("Minimum nearby player-built structural pieces.", 3, 80));
		HealthScale = config.Bind<float>("Combat", "RaiderHealthMultiplier", 0.6f, new ConfigDescription("Fraction of a raider's normal health.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.15f, 1f), Array.Empty<object>()));
		Coins = config.Bind<int>("Rewards", "VictoryCoins", 120, Range("One shared coin reward after a qualifying victory.", 0, 999));
		TestPayout = config.Bind<bool>("Rewards", "RewardManualTests", false, "Allow the manual test command to award coins.");
	}

	private static ConfigDescription Range(string description, int min, int max)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Expected O, but got Unknown
		return new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<int>(min, max), Array.Empty<object>());
	}

	internal static int WaveCount(Difficulty difficulty, int limit)
	{
		int num = difficulty switch
		{
			SiegeNights.Difficulty.Hard => 5, 
			SiegeNights.Difficulty.Easy => 3, 
			_ => 4, 
		};
		if (limit != 0)
		{
			return Math.Min(num, limit);
		}
		return num;
	}

	internal static int WaveSize(Difficulty difficulty, int wave)
	{
		return difficulty switch
		{
			SiegeNights.Difficulty.Easy => 3 + 2 * wave, 
			SiegeNights.Difficulty.Hard => 4 + 4 * wave, 
			_ => 3 + 3 * wave, 
		};
	}

	internal static Objectives Objective(Difficulty difficulty, Objectives configured, int wave)
	{
		if (configured != Objectives.Preset)
		{
			return configured;
		}
		if (difficulty == SiegeNights.Difficulty.Easy || wave == 1)
		{
			return Objectives.Defenders;
		}
		if (difficulty != SiegeNights.Difficulty.Hard || wave < 3)
		{
			return Objectives.Gates;
		}
		return Objectives.Structures;
	}

	internal static bool EarnsCoins(float playerDamage, float totalDamage)
	{
		if (totalDamage > 0f)
		{
			return playerDamage > totalDamage * 0.5f;
		}
		return false;
	}

	internal static float CombineDamageShare(float remaining, float added, float previousShare, bool fromPlayer)
	{
		if (remaining <= 0f)
		{
			return 0f;
		}
		float num = Math.Max(0f, remaining - added);
		return Math.Min(1f, Math.Max(0f, (num * previousShare + (fromPlayer ? added : 0f)) / remaining));
	}

	internal static float HorizontalDistance(Vector3 a, Vector3 b)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		float num = a.x - b.x;
		float num2 = a.z - b.z;
		return Mathf.Sqrt(num * num + num2 * num2);
	}
}
internal sealed class SiegeState
{
	internal long Id;

	internal Phase Phase;

	internal Vector3 Center;

	internal int Wave;

	internal int Waves;

	internal int Released;

	internal int Fallen;

	internal int DefeatedSlots;

	internal Objectives Target;

	internal Difficulty Difficulty;

	internal bool Test;

	internal bool NightOnly;

	internal float Seconds;

	internal float PlayerDamage;

	internal float TotalDamage;

	internal int FinalCoins;

	internal int RewardCoins;

	internal int AliveLimit;

	internal float HealthMultiplier;

	internal double ClockAtWrite;

	internal bool Paused;

	internal int WaveSeconds = 165;

	internal int RepairSeconds = 22;

	internal string Encode()
	{
		return FormattableString.Invariant($"2,{Id},{(int)Phase},{Center.x:R},{Center.y:R},{Center.z:R},{Wave},{Waves},{Released},{Fallen},{(int)Target},{(int)Difficulty},{(Test ? 1 : 0)},{(NightOnly ? 1 : 0)},{Seconds:R},{PlayerDamage:R},{TotalDamage:R},{FinalCoins},{RewardCoins},{AliveLimit},{HealthMultiplier:R},{ClockAtWrite:R},{(Paused ? 1 : 0)},{DefeatedSlots},{WaveSeconds},{RepairSeconds}");
	}

	internal static SiegeState Decode(string raw)
	{
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		if (string.IsNullOrEmpty(raw) || raw.Length > 512)
		{
			return null;
		}
		string[] array = raw.Split(',');
		bool flag = array.Length == 24 && array[0] == "1";
		if (!flag && (array.Length != 26 || array[0] != "2"))
		{
			return null;
		}
		int[] array2 = new int[3] { 12, 13, 22 };
		foreach (int num in array2)
		{
			if (array[num] != "0" && array[num] != "1")
			{
				return null;
			}
		}
		CultureInfo invariantCulture = CultureInfo.InvariantCulture;
		try
		{
			SiegeState siegeState = new SiegeState
			{
				Id = long.Parse(array[1], invariantCulture),
				Phase = (Phase)int.Parse(array[2], invariantCulture),
				Center = new Vector3(float.Parse(array[3], invariantCulture), float.Parse(array[4], invariantCulture), float.Parse(array[5], invariantCulture)),
				Wave = int.Parse(array[6], invariantCulture),
				Waves = int.Parse(array[7], invariantCulture),
				Released = int.Parse(array[8], invariantCulture),
				Fallen = int.Parse(array[9], invariantCulture),
				Target = (Objectives)int.Parse(array[10], invariantCulture),
				Difficulty = (Difficulty)int.Parse(array[11], invariantCulture),
				Test = (array[12] == "1"),
				NightOnly = (array[13] == "1"),
				Seconds = float.Parse(array[14], invariantCulture),
				PlayerDamage = float.Parse(array[15], invariantCulture),
				TotalDamage = float.Parse(array[16], invariantCulture),
				FinalCoins = int.Parse(array[17], invariantCulture),
				RewardCoins = int.Parse(array[18], invariantCulture),
				AliveLimit = int.Parse(array[19], invariantCulture),
				HealthMultiplier = float.Parse(array[20], invariantCulture),
				ClockAtWrite = double.Parse(array[21], invariantCulture),
				Paused = (array[22] == "1"),
				DefeatedSlots = int.Parse(array[23], invariantCulture),
				WaveSeconds = (flag ? 165 : int.Parse(array[24], invariantCulture)),
				RepairSeconds = (flag ? 22 : int.Parse(array[25], invariantCulture))
			};
			if (siegeState.Id <= 0 || siegeState.Phase < Phase.Warning || siegeState.Phase > Phase.Aftermath || siegeState.Wave < 1 || siegeState.Wave > siegeState.Waves || siegeState.Waves > 5 || siegeState.Difficulty < Difficulty.Easy || siegeState.Difficulty > Difficulty.Hard || siegeState.Target < Objectives.Preset || siegeState.Target > Objectives.Structures || siegeState.Released < 0 || siegeState.Released > SiegeRules.WaveSize(siegeState.Difficulty, siegeState.Wave) || siegeState.Fallen < 0 || siegeState.Fallen > siegeState.Released || siegeState.PlayerDamage < 0f || siegeState.TotalDamage < siegeState.PlayerDamage || siegeState.Seconds < 0f || siegeState.WaveSeconds < 60 || siegeState.WaveSeconds > 900 || siegeState.RepairSeconds < 10 || siegeState.RepairSeconds > 180 || siegeState.AliveLimit < 3 || siegeState.AliveLimit > 30 || !Finite(siegeState.HealthMultiplier) || siegeState.HealthMultiplier < 0.15f || siegeState.HealthMultiplier > 1f || siegeState.RewardCoins < 0 || siegeState.RewardCoins > 999 || siegeState.FinalCoins < -1 || siegeState.FinalCoins > 999 || siegeState.DefeatedSlots < 0 || double.IsNaN(siegeState.ClockAtWrite) || double.IsInfinity(siegeState.ClockAtWrite) || !Finite(siegeState.Seconds) || !Finite(siegeState.PlayerDamage) || !Finite(siegeState.TotalDamage) || !Finite(siegeState.Center.x) || !Finite(siegeState.Center.y) || !Finite(siegeState.Center.z))
			{
				return null;
			}
			int num2 = siegeState.DefeatedSlots;
			int num3 = 0;
			while (num2 != 0)
			{
				num2 &= num2 - 1;
				num3++;
			}
			int num4 = (1 << SiegeRules.WaveSize(siegeState.Difficulty, siegeState.Wave)) - 1;
			if (num3 != siegeState.Fallen || (siegeState.DefeatedSlots & ~num4) != 0)
			{
				return null;
			}
			return siegeState;
		}
		catch (FormatException)
		{
			return null;
		}
		catch (OverflowException)
		{
			return null;
		}
	}

	private static bool Finite(float x)
	{
		if (!float.IsNaN(x))
		{
			return !float.IsInfinity(x);
		}
		return false;
	}
}
internal static class TestOutpost
{
	internal static string Build(Player player)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_027f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0280: Unknown result type (might be due to invalid IL or missing references)
		//IL_0294: Unknown result type (might be due to invalid IL or missing references)
		//IL_0299: Unknown result type (might be due to invalid IL or missing references)
		//IL_029e: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_0403: Unknown result type (might be due to invalid IL or missing references)
		//IL_0408: Unknown result type (might be due to invalid IL or missing references)
		//IL_031e: Unknown result type (might be due to invalid IL or missing references)
		//IL_041d: Unknown result type (might be due to invalid IL or missing references)
		//IL_041e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0432: Unknown result type (might be due to invalid IL or missing references)
		//IL_0437: Unknown result type (might be due to invalid IL or missing references)
		//IL_043c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0441: Unknown result type (might be due to invalid IL or missing references)
		//IL_0339: Unknown result type (might be due to invalid IL or missing references)
		//IL_0345: Unknown result type (might be due to invalid IL or missing references)
		//IL_0471: Unknown result type (might be due to invalid IL or missing references)
		//IL_0473: Unknown result type (might be due to invalid IL or missing references)
		//IL_0485: Unknown result type (might be due to invalid IL or missing references)
		//IL_048a: Unknown result type (might be due to invalid IL or missing references)
		//IL_049c: Unknown result type (might be due to invalid IL or missing references)
		//IL_034e: Unknown result type (might be due to invalid IL or missing references)
		//IL_035d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0364: Unkn