Decompiled source of ReturningBough v0.17.2

plugins/ReturningBough.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Splatform;
using TMPro;
using TravsServerNPCs.Npc;
using TravsServerNPCs.Server;
using TravsServerNPCs.Shared;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.UI;
using ValheimNpc;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("ReturningBough")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.17.0.0")]
[assembly: AssemblyInformationalVersion("0.17.0+a2f35a034722da7812b950e985e6acc0439cb25c")]
[assembly: AssemblyProduct("ReturningBough")]
[assembly: AssemblyTitle("ReturningBough")]
[assembly: AssemblyVersion("0.17.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ReturningBough
{
	internal sealed class ArrivalGuide
	{
		private sealed class Speaker
		{
			internal string Name;

			internal Transform Actor;
		}

		private const float Range = 30f;

		private readonly List<Speaker> speakers = new List<Speaker>(2);

		private readonly Text[] labels = (Text[])(object)new Text[2];

		private static readonly int SightMask = LayerMask.GetMask(new string[4] { "terrain", "piece", "static_solid", "Default" });

		internal void Refresh(Player player)
		{
			//IL_00bb: 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_00e6: 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_00f0: Unknown result type (might be due to invalid IL or missing references)
			speakers.Clear();
			StorySnapshot view = StoryNetwork.View;
			if (!Plugin.TestWorld || view?.World != ZNet.instance.GetWorldUID() || view.ArrivalSpeakers == null || view.ArrivalSpeakers.Length == 0 || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			foreach (NpcInfo listedNpc in NpcNetworkSync.ListedNpcs)
			{
				if (listedNpc == null || !view.ArrivalSpeakers.Contains(listedNpc.ProfileId))
				{
					continue;
				}
				GameObject val = ZNetScene.instance.FindInstance(new ZDOID(listedNpc.ZdoUser, listedNpc.ZdoId));
				if (!((Object)(object)val == (Object)null))
				{
					Vector3 val2 = val.transform.position - ((Component)player).transform.position;
					if (!(((Vector3)(ref val2)).sqrMagnitude > 900f))
					{
						string name = ((listedNpc.ProfileId == "rpg_quartermaster") ? "Edda" : ((listedNpc.ProfileId == "rb_sigrid") ? "Sigrid" : "Torvald"));
						speakers.Add(new Speaker
						{
							Name = name,
							Actor = val.transform
						});
					}
				}
			}
		}

		internal string Hint(Vector3 position, float? heading)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			Speaker speaker = speakers.Where((Speaker s) => (Object)(object)s.Actor != (Object)null).OrderBy(delegate(Speaker s)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val2 = s.Actor.position - position;
				return ((Vector3)(ref val2)).sqrMagnitude;
			}).FirstOrDefault();
			if (speaker == null)
			{
				return "";
			}
			Vector3 val = speaker.Actor.position - position;
			return NotebookModel.SpeakerBearing(speaker.Name, val.x, val.z, val.y, heading);
		}

		internal void Draw(Transform canvas, bool visible)
		{
			//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_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: 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_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: 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_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			Camera val = ((visible && speakers.Count > 0) ? Utils.GetMainCamera() : null);
			Vector2 val5 = default(Vector2);
			for (int i = 0; i < labels.Length; i++)
			{
				Speaker speaker = ((i < speakers.Count) ? speakers[i] : null);
				Text val2 = labels[i];
				if ((Object)(object)val == (Object)null || (Object)(object)canvas == (Object)null || (Object)(object)speaker?.Actor == (Object)null)
				{
					if ((Object)(object)val2 != (Object)null)
					{
						((Component)val2).gameObject.SetActive(false);
					}
					continue;
				}
				Vector3 val3 = speaker.Actor.position + Vector3.up * 2.15f;
				Vector3 val4 = val.WorldToViewportPoint(val3);
				if (!(val4.z > 0f) || !(val4.x >= 0f) || !(val4.x <= 1f) || !(val4.y >= 0f) || !(val4.y <= 1f) || Physics.Linecast(((Component)val).transform.position, val3, SightMask, (QueryTriggerInteraction)1))
				{
					if ((Object)(object)val2 != (Object)null)
					{
						((Component)val2).gameObject.SetActive(false);
					}
					continue;
				}
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = SettlementUi.Label(canvas, "", 23, Vector2.zero, 150f, 34f, new Color(1f, 0.91f, 0.58f), (TextAnchor)4);
					((Object)((Component)val2).gameObject).name = "RB arrival speaker";
					Outline obj = ((Component)val2).gameObject.AddComponent<Outline>();
					((Shadow)obj).effectColor = Color.black;
					((Shadow)obj).effectDistance = new Vector2(1.5f, -1.5f);
					labels[i] = val2;
				}
				((Vector2)(ref val5))..ctor(val4.x, val4.y);
				RectTransform rectTransform = ((Graphic)val2).rectTransform;
				Vector2 anchorMin = (((Graphic)val2).rectTransform.anchorMax = val5);
				rectTransform.anchorMin = anchorMin;
				((Graphic)val2).rectTransform.anchoredPosition = Vector2.zero;
				val2.text = speaker.Name;
				((Component)val2).gameObject.SetActive(true);
			}
		}
	}
	internal sealed class AssignmentChest : MonoBehaviour
	{
		[HarmonyPatch(typeof(Container), "Interact")]
		private static class Configure
		{
			private static bool Prefix(Container __instance, Humanoid character, bool hold, bool alt, ref bool __result)
			{
				AssignmentChest assignmentChest = default(AssignmentChest);
				if (!alt || hold || (Object)(object)character != (Object)(object)Player.m_localPlayer || !((Component)__instance).TryGetComponent<AssignmentChest>(ref assignmentChest))
				{
					return true;
				}
				__result = true;
				if (assignmentChest.MayEdit(Player.m_localPlayer))
				{
					assignmentChest.Edit(0);
				}
				else
				{
					((Character)character).Message((MessageType)2, "The chest is busy or access is restricted.", 0, (Sprite)null, false);
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(Container), "GetHoverText")]
		private static class Hint
		{
			private static void Postfix(Container __instance, ref string __result)
			{
				AssignmentChest assignmentChest = default(AssignmentChest);
				if (((Component)__instance).TryGetComponent<AssignmentChest>(ref assignmentChest) && assignmentChest.Record != null && assignmentChest.MayEdit(Player.m_localPlayer))
				{
					string text = ((ZInput.IsGamepadActive() && ZInput.IsNonClassicFunctionality()) ? "$KEY_JoyAltKeys" : "$KEY_AltPlace");
					__result += Localization.instance.Localize("\n[<color=yellow>" + text + " + $KEY_Use</color>] Assign: " + Describe.Invoke(null, new object[1] { assignmentChest.Record }));
				}
			}
		}

		[HarmonyPatch]
		private static class WorkerRules
		{
			private static MethodBase TargetMethod()
			{
				return AccessTools.Method(Rules, "RuleZdo", (Type[])null, (Type[])null);
			}

			private static bool Prefix(Container chest, ref ZDO __result)
			{
				AssignmentChest assignmentChest = default(AssignmentChest);
				if (!Object.op_Implicit((Object)(object)chest) || !((Component)chest).TryGetComponent<AssignmentChest>(ref assignmentChest))
				{
					return true;
				}
				__result = assignmentChest.Record;
				return false;
			}
		}

		internal const string Id = "RB_AssignmentChest";

		private const string Title = "Settlement assignment chest";

		private static readonly Type Rules = AccessTools.TypeByName("ValheimNpc.ChestTags");

		private static readonly MethodInfo OpenRules = AccessTools.Method(Rules, "OpenRules", (Type[])null, (Type[])null);

		private static readonly MethodInfo Describe = AccessTools.Method(Rules, "Describe", (Type[])null, (Type[])null);

		private static readonly MethodInfo RuleIcons = AccessTools.Method(AccessTools.TypeByName("ValheimNpc.ChestSigns"), "RuleIcons", (Type[])null, (Type[])null);

		private static readonly MethodInfo ForgetLabels = AccessTools.Method(typeof(VikingNpc), "ForgetChestLabels", (Type[])null, (Type[])null);

		private static readonly int Mode = StringExtensionMethods.GetStableHashCode("vnpc_tag_mode");

		private static readonly int Jobs = StringExtensionMethods.GetStableHashCode("vnpc_tag_jobs");

		private static readonly Func<Container, long, bool> Access = AccessTools.MethodDelegate<Func<Container, long, bool>>(AccessTools.Method(typeof(Container), "CheckAccess", (Type[])null, (Type[])null), (object)null, true);

		private ZNetView view;

		private Container storage;

		private SpriteRenderer[] emblems;

		private int drawnMode = -1;

		private string drawnJobs;

		private float refreshAt;

		private ZDO Record
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)view) || !view.IsValid())
				{
					return null;
				}
				return view.GetZDO();
			}
		}

		internal static void Register()
		{
			if (Plugin.VersionsValid)
			{
				Register("RB_AssignmentChest", "Settlement assignment chest", "Set the worker assignments on the inset rails. Open normally to store items.");
				Register("RB_CommunalReserveChest", "Communal reserve chest", "Supplies for Boughhaven. Nearby reserve chests count toward the Town notebook's operating stores.");
			}
		}

		private static void Register(string id, string title, string description)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Expected O, but got Unknown
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: 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_0202: 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_0221: Unknown result type (might be due to invalid IL or missing references)
			if (PieceManager.Instance.GetPiece(id) != null)
			{
				return;
			}
			PieceConfig val = new PieceConfig();
			val.Name = title;
			val.Description = description;
			val.PieceTable = "Hammer";
			val.Category = "Furniture";
			val.CraftingStation = "piece_workbench";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
			{
				new RequirementConfig("Wood", 12, 0, true),
				new RequirementConfig("Resin", 1, 0, true)
			};
			CustomPiece val2 = new CustomPiece(id, "piece_chest_wood", val);
			GameObject piecePrefab = val2.PiecePrefab;
			piecePrefab.GetComponent<Container>().m_name = title;
			Material sharedMaterial = ((Renderer)PrefabManager.Instance.GetPrefab("wood_beam").GetComponentsInChildren<MeshRenderer>(true).First((MeshRenderer r) => Object.op_Implicit((Object)(object)((Renderer)r).sharedMaterial) && !((Object)((Renderer)r).sharedMaterial).name.Contains("snow"))).sharedMaterial;
			int[] array = new int[2] { -1, 1 };
			foreach (int num2 in array)
			{
				GameObject val3 = new GameObject("Inlaid assignment rail");
				val3.transform.SetParent(piecePrefab.transform, false);
				val3.transform.localPosition = new Vector3(0f, 0.4f, (float)num2 * 0.378f);
				val3.transform.localRotation = Quaternion.Euler(0f, (float)((num2 < 0) ? 180 : 0), 0f);
				Panel(val3.transform, "Rail", Vector3.zero, new Vector3(1.42f, 0.38f, 0.055f), sharedMaterial);
				for (int num3 = 0; num3 < 3; num3++)
				{
					float num4 = (float)(num3 - 1) * 0.42f;
					Panel(val3.transform, "Recess", new Vector3(num4, 0f, 0.029f), new Vector3(0.34f, 0.3f, 0.016f), sharedMaterial, dark: true);
					GameObject val4 = new GameObject("Assignment emblem");
					val4.transform.SetParent(val3.transform, false);
					val4.transform.localPosition = new Vector3(num4, 0f, 0.044f);
					val4.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
					val4.AddComponent<SpriteRenderer>();
				}
			}
			piecePrefab.AddComponent<AssignmentChest>();
			PieceManager.Instance.AddPiece(val2);
		}

		private static void Panel(Transform parent, string name, Vector3 pos, Vector3 size, Material wood, bool dark = false)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)3);
			((Object)obj).name = name;
			Object.DestroyImmediate((Object)(object)obj.GetComponent<Collider>());
			obj.transform.SetParent(parent, false);
			obj.transform.localPosition = pos;
			obj.transform.localScale = size;
			MeshRenderer component = obj.GetComponent<MeshRenderer>();
			((Renderer)component).sharedMaterial = wood;
			if (dark)
			{
				MaterialPropertyBlock val = new MaterialPropertyBlock();
				val.SetColor("_Color", new Color(0.31f, 0.24f, 0.17f));
				((Renderer)component).SetPropertyBlock(val);
			}
		}

		private void Awake()
		{
			view = ((Component)this).GetComponent<ZNetView>();
			storage = ((Component)this).GetComponent<Container>();
		}

		private void Update()
		{
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: 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_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime < refreshAt || Record == null)
			{
				return;
			}
			refreshAt = Time.unscaledTime + 0.5f;
			ZDO record = Record;
			int num = record.GetInt(Mode, 0);
			string text = record.GetString(Jobs, "");
			if (num == drawnMode && text == drawnJobs)
			{
				return;
			}
			List<Sprite> list = (List<Sprite>)RuleIcons.Invoke(null, new object[2] { record, "piece_chest_wood" });
			if (emblems == null)
			{
				emblems = (from e in ((Component)this).GetComponentsInChildren<SpriteRenderer>(true)
					where ((Object)e).name == "Assignment emblem"
					select e).ToArray();
			}
			for (int num2 = 0; num2 < emblems.Length; num2++)
			{
				SpriteRenderer val = emblems[num2];
				int num3 = num2 % 3;
				Sprite val2 = (val.sprite = ((num3 < list.Count) ? list[num3] : null));
				if (Object.op_Implicit((Object)(object)val2))
				{
					Bounds bounds = val2.bounds;
					float x = ((Bounds)(ref bounds)).size.x;
					bounds = val2.bounds;
					float num4 = Mathf.Max(x, ((Bounds)(ref bounds)).size.y);
					((Component)val).transform.localScale = Vector3.one * (0.26f / Mathf.Max(num4, 0.001f));
				}
			}
			drawnMode = num;
			drawnJobs = text;
		}

		private bool MayEdit(Player player)
		{
			//IL_0023: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			if (Record != null && Object.op_Implicit((Object)(object)player) && (Object)(object)player == (Object)(object)Player.m_localPlayer && Vector3.Distance(((Component)player).transform.position, ((Component)this).transform.position) < 5f && !storage.IsInUse() && Access(storage, player.GetPlayerID()))
			{
				return PrivateArea.CheckAccess(((Component)this).transform.position, 0f, false, false);
			}
			return false;
		}

		private void Edit(int page)
		{
			if (MayEdit(Player.m_localPlayer))
			{
				Type parameterType = OpenRules.GetParameters()[2].ParameterType;
				MethodInfo method = AccessTools.Method(typeof(AssignmentChest), "Choose", (Type[])null, (Type[])null).MakeGenericMethod(parameterType.GetGenericArguments()[0]);
				Delegate obj = Delegate.CreateDelegate(parameterType, this, method);
				OpenRules.Invoke(null, new object[8]
				{
					((Component)this).transform,
					Record,
					obj,
					storage.m_name,
					"",
					null,
					new Action<int>(Edit),
					page
				});
			}
		}

		private void Choose<T>(T mode, string jobs) where T : struct
		{
			if (MayEdit(Player.m_localPlayer))
			{
				view.ClaimOwnership();
				if (view.IsOwner())
				{
					Record.Set(Mode, Convert.ToInt32(mode), false);
					Record.Set(Jobs, jobs ?? "");
					ForgetLabels.Invoke(null, null);
				}
			}
		}
	}
	public static class BodyCoverageRules
	{
		private static readonly HashSet<string> CoveredBones = new HashSet<string> { "Hips", "Spine", "Spine1", "Spine2", "LeftUpLeg", "RightUpLeg", "LeftLeg", "RightLeg" };

		public static bool EddaCovered(float x, float y, float z, IEnumerable<KeyValuePair<string, float>> influences)
		{
			if (float.IsNaN(x) || float.IsNaN(y) || float.IsNaN(z) || Math.Abs(x) > 0.26f || Math.Abs(z) > 0.2f || y < 0.32f || y > 1.4f)
			{
				return false;
			}
			float num = 0f;
			foreach (KeyValuePair<string, float> influence in influences)
			{
				if (!(influence.Value <= 0f))
				{
					if (!CoveredBones.Contains(influence.Key))
					{
						return false;
					}
					num += influence.Value;
				}
			}
			return num > 0.98f;
		}
	}
	[HarmonyPatch(typeof(VikingNpc), "NeedsTravel")]
	internal static class BunkhouseBedRoute
	{
		private static readonly Func<VikingNpc, ZDOID> BedId = AccessTools.MethodDelegate<Func<VikingNpc, ZDOID>>(AccessTools.Method(typeof(VikingNpc), "GetBedId", (Type[])null, (Type[])null), (object)null, true);

		internal static ZDO ClaimedBunk(VikingNpc worker)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = ZDOMan.instance.GetZDO(BedId(worker));
			if (zDO == null || zDO.GetPrefab() != StringExtensionMethods.GetStableHashCode("bed") || !zDO.GetString("rb_b04_construction", "").StartsWith("bed_", StringComparison.Ordinal))
			{
				return null;
			}
			return zDO;
		}

		private static void Postfix(VikingNpc __instance, bool __result, ref Vector3 anchor, ref float arrive)
		{
			//IL_0038: 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_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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: 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_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: 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_00f0: 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_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			if (!__result || arrive > 1.1f || !Plugin.VersionsValid || !Plugin.TestWorld || !__instance.NetView.IsValid())
			{
				return;
			}
			Vector3 val = __instance.NetView.GetZDO().GetVec3("vnpc_home", Vector3.zero) - anchor;
			if (((Vector3)(ref val)).sqrMagnitude > 0.04f)
			{
				return;
			}
			ZDO val2 = ClaimedBunk(__instance);
			if (val2 == null)
			{
				return;
			}
			int num;
			switch (val2.GetString("rb_b04_construction", ""))
			{
			default:
				return;
			case "bed_1":
			case "bed_3":
				num = 1;
				break;
			case "bed_2":
			case "bed_4":
				num = -1;
				break;
			}
			RaycastHit val3 = default(RaycastHit);
			if (Physics.Raycast(val2.GetPosition() + val2.GetRotation() * Vector3.right * (float)num * 1.1f + Vector3.up * 0.3f, Vector3.down, ref val3, 1f, LayerMask.GetMask(new string[1] { "piece" }), (QueryTriggerInteraction)1))
			{
				ZNetView componentInParent = ((Component)((RaycastHit)(ref val3)).collider).GetComponentInParent<ZNetView>();
				if (BunkhouseConstruction.IsBunkroomFloor((componentInParent != null) ? componentInParent.GetZDO() : null))
				{
					anchor = ((RaycastHit)(ref val3)).point;
					arrive = 0.35f;
				}
			}
		}
	}
	[HarmonyPatch(typeof(VikingNpc), "UpdateTavernSchedule")]
	internal static class BunkhouseRestOrder
	{
		private static bool Prefix(VikingNpc __instance, ref float ___m_tavernUntil)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			if (!Plugin.VersionsValid || !Plugin.TestWorld || !Object.op_Implicit((Object)(object)__instance.NetView) || !__instance.NetView.IsOwner() || !__instance.IsResting() || (int)__instance.GetMode() != 3)
			{
				return true;
			}
			long num = __instance.NetView.GetZDO().GetLong("vnpc_join_after_rest", 0L);
			if (num == 0L || num != __instance.GetOwnerId() || BunkhouseBedRoute.ClaimedBunk(__instance) == null)
			{
				return true;
			}
			___m_tavernUntil = 0f;
			return false;
		}
	}
	internal static class BunkhouseConstruction
	{
		internal const string Tag = "rb_b04_construction";

		private static ConstructionPlan plan;

		private static ConstructionState repairRequested;

		private const string ProtectedPlot = "Part of this bunkhouse plot lies in a protected location. Review its paid construction before continuing.";

		private static readonly Dictionary<string, ConstructionPart> IronEntrance = ReadIronEntrance();

		internal const int RegisterFurnishingsAction = 4;

		private const string PreviousMissingPieces = "The completed B04 structure is missing pieces. For a destroyed bed or chest, rebuild it with the hammer and record it from the Town page inside B04. Review other structural damage before claiming construction.";

		private const string PreviousFloorRepairMessage = "B04 is missing pieces. Rebuild damaged bunks, chests, signs or bunkroom floors and record the repairs from the Town page inside B04.";

		private const string LegacyEntranceRepairMessage = "B04 is missing pieces. Restore the bunks, chests, signs, bunkroom floors, entrance or steps with your hammer, then record the repairs from the Town page inside B04.";

		private const string MissingPieces = "The bunkhouse is missing pieces. Restore the bunks, chests, signs, bunkroom floors, entrance or steps with your hammer, then record the repairs from the Town page inside the bunkhouse.";

		private const string StoneFloor = "stone_floor_2x2";

		private const string HouseSign = "<color=white>Boughhaven\nBunkhouse";

		private const string OriginalSign = "<color=white>Boughhaven communal bunkhouse\nBuilt by the returning clans\nFour beds — keep the hearth supplied";

		private static readonly (string Id, string Prefab, Vector3 Local, float Yaw)[] OriginalMounts = new(string, string, Vector3, float)[9]
		{
			("entry_ramp", "wood_roof", new Vector3(0f, -1f, -7f), 180f),
			("part_171", "wood_wall_roof_a", new Vector3(-3f, 3f, -4f), 0f),
			("part_172", "wood_wall_roof_a", new Vector3(-1f, 4f, -4f), 0f),
			("part_173", "wood_wall_roof_a", new Vector3(1f, 4f, -4f), 180f),
			("part_174", "wood_wall_roof_a", new Vector3(3f, 3f, -4f), 180f),
			("part_175", "wood_wall_half", new Vector3(-1f, 3.5f, -4f), 0f),
			("part_176", "wood_wall_half", new Vector3(1f, 3.5f, -4f), 0f),
			("part_180", "wood_pole", new Vector3(-2f, 6.5f, 4f), 0f),
			("part_182", "wood_pole", new Vector3(2f, 6.5f, 4f), 0f)
		};

		internal static ConstructionPlan Plan
		{
			get
			{
				if (plan != null)
				{
					return plan;
				}
				using (Stream stream = typeof(Plugin).Assembly.GetManifestResourceStream("ReturningBough.B04.json"))
				{
					using StreamReader streamReader = new StreamReader(stream);
					plan = JsonConvert.DeserializeObject<ConstructionPlan>(streamReader.ReadToEnd());
				}
				ConstructionPlan constructionPlan = plan;
				if (constructionPlan == null || constructionPlan.pieces?.Count != 200 || plan.pieces.Select((ConstructionPart p) => p.id).Distinct().Count() != 200 || plan.pieces.Count((ConstructionPart p) => p.prefab == "bed") != 4)
				{
					throw new InvalidDataException("bunkhouse blueprint identity/count validation failed.");
				}
				string[] resources = ConstructionRules.Resources;
				foreach (string resource in resources)
				{
					if (plan.pieces.Sum((ConstructionPart p) => p.Cost(resource)) != ChapterRules.Required("bunkhouse", resource))
					{
						throw new InvalidDataException("bunkhouse material schedule disagrees with its blueprint.");
					}
				}
				return plan;
			}
		}

		internal static Vector3 Anchor(ConstructionState state)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(state.X, state.Y, state.Z);
		}

		internal static bool Objective(ChapterState town)
		{
			ConstructionState b = town.B04;
			if (b != null && b.LegacyCompleted)
			{
				return true;
			}
			ConstructionState b2 = town.B04;
			if (b2 == null || !b2.Completed)
			{
				return false;
			}
			return VerifyCompletedPieces(town.B04, Existing());
		}

		private static bool VerifyCompletedPieces(ConstructionState house, Dictionary<string, ZDO> existing)
		{
			bool iron = HasIronDoor(existing);
			int num;
			if (existing.Count == Plan.pieces.Count)
			{
				num = (Plan.pieces.All((ConstructionPart part) => existing.TryGetValue(part.id, out var value) && ((!IronEntrance.TryGetValue(part.id, out var value2)) ? MatchesCompletedPiece(house, part, value) : FitsEntrance(house, iron ? value2 : part, value))) ? 1 : 0);
				if (num != 0)
				{
					if (house.Problem == "The bunkhouse is missing pieces. Restore the bunks, chests, signs, bunkroom floors, entrance or steps with your hammer, then record the repairs from the Town page inside the bunkhouse." || house.Problem == "The completed B04 structure is missing pieces. For a destroyed bed or chest, rebuild it with the hammer and record it from the Town page inside B04. Review other structural damage before claiming construction." || house.Problem == "B04 is missing pieces. Rebuild damaged bunks, chests, signs or bunkroom floors and record the repairs from the Town page inside B04." || house.Problem == "B04 is missing pieces. Restore the bunks, chests, signs, bunkroom floors, entrance or steps with your hammer, then record the repairs from the Town page inside B04." || house.Problem == "The completed B04 structure is missing pieces. Review or restore the matched save before claiming construction.")
					{
						house.Problem = null;
					}
					return (byte)num != 0;
				}
			}
			else
			{
				num = 0;
			}
			RequestFootingReview(house, existing);
			house.Problem = "The bunkhouse is missing pieces. Restore the bunks, chests, signs, bunkroom floors, entrance or steps with your hammer, then record the repairs from the Town page inside the bunkhouse.";
			return (byte)num != 0;
		}

		private static List<ZDO> All(string prefab)
		{
			List<ZDO> list = new List<ZDO>();
			int num = 0;
			while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative(prefab, list, ref num))
			{
			}
			return list;
		}

		internal static Dictionary<string, ZDO> Existing()
		{
			Dictionary<string, ZDO> dictionary = new Dictionary<string, ZDO>();
			foreach (string item in (from p in Plan.pieces.Concat(IronEntrance.Values)
				select p.prefab).Distinct())
			{
				foreach (ZDO item2 in All(item))
				{
					string text = item2.GetString("rb_b04_construction", "");
					if (!(text == ""))
					{
						if (dictionary.ContainsKey(text))
						{
							throw new InvalidDataException("Duplicate bunkhouse construction identity: " + text);
						}
						dictionary.Add(text, item2);
					}
				}
			}
			return dictionary;
		}

		private static string Obstruction(Vector3 at)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: 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_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = ConstructionClearing.Overlap(at + Vector3.up * 2f, new Vector3(5f, 6f, 9f));
			foreach (Collider val in array)
			{
				if (val.isTrigger)
				{
					continue;
				}
				Piece componentInParent = ((Component)val).GetComponentInParent<Piece>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					ZNetView component = ((Component)componentInParent).GetComponent<ZNetView>();
					if ((Object)(object)component == (Object)null || !component.IsValid() || component.GetZDO().GetString("rb_b04_construction", "") == "")
					{
						return "The bunkhouse plot contains another building piece. Nothing was overwritten.";
					}
				}
				if (!((Object)(object)componentInParent != (Object)null) && !((Object)(object)((Component)val).GetComponentInParent<Heightmap>() != (Object)null) && !((Object)(object)((Component)val).GetComponentInParent<Character>() != (Object)null) && !((Object)(object)((Component)val).GetComponentInParent<ItemDrop>() != (Object)null))
				{
					TreeBase componentInParent2 = ((Component)val).GetComponentInParent<TreeBase>();
					TreeLog componentInParent3 = ((Component)val).GetComponentInParent<TreeLog>();
					if ((Object)(object)componentInParent2 != (Object)null || (Object)(object)componentInParent3 != (Object)null)
					{
						Vector3 val2 = (((Object)(object)componentInParent2 != (Object)null) ? ((Component)componentInParent2).transform : ((Component)componentInParent3).transform).position - at;
						return NotebookModel.BunkhouseClearingHint((Object)(object)componentInParent3 != (Object)null, val2.x, val2.z);
					}
					Destructible val3 = ConstructionClearing.WildBeech(val);
					if (Object.op_Implicit((Object)(object)val3))
					{
						Vector3 val4 = ((Component)val3).transform.position - at;
						return NotebookModel.BunkhouseSaplingHint(val4.x, val4.z);
					}
					if ((Object)(object)((Component)val).GetComponentInParent<Destructible>() != (Object)null)
					{
						return "The bunkhouse plot contains a tree or natural obstruction. Clear the obstruction before construction continues.";
					}
					switch (LayerMask.LayerToName(((Component)val).gameObject.layer))
					{
					case "static_solid":
					case "Default":
					case "Default_small":
					case "blocker":
						return "A solid world object obstructs the bunkhouse plot. Construction is paused without overwriting it.";
					}
				}
			}
			return null;
		}

		private static bool Protected(Vector3 at, Location[] locations)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: 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_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			if (!CampaignBuildingSite.Allowed(at, 5f, 9f))
			{
				return true;
			}
			Vector3 val2 = default(Vector3);
			foreach (Location val in locations)
			{
				if (val.m_noBuild)
				{
					Vector3 position = ((Component)val).transform.position;
					((Vector3)(ref val2))..ctor(Mathf.Clamp(position.x, at.x - 5f, at.x + 5f), at.y, Mathf.Clamp(position.z, at.z - 9f, at.z + 9f));
					if (val.IsInside(val2, 0f, true))
					{
						return true;
					}
				}
			}
			return false;
		}

		internal static bool Prepare(ChapterRuntime chapter, Vector3? contributor = null)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: 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_04f9: 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)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0517: Unknown result type (might be due to invalid IL or missing references)
			//IL_051c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0531: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: 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_026b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: 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_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_041f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0430: Unknown result type (might be due to invalid IL or missing references)
			//IL_0435: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0446: Unknown result type (might be due to invalid IL or missing references)
			//IL_037e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0380: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Unknown result type (might be due to invalid IL or missing references)
			//IL_038f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_045e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c2: 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_04c4: 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_0475: Unknown result type (might be due to invalid IL or missing references)
			//IL_047f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0484: Unknown result type (might be due to invalid IL or missing references)
			//IL_0498: Unknown result type (might be due to invalid IL or missing references)
			//IL_0401: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bb: Unknown result type (might be due to invalid IL or missing references)
			ConstructionState state = chapter.State.B04;
			if (state.HasPlot && !SettlementPresence.PlotLoaded(Anchor(state), 5, 9))
			{
				state.Problem = SettlementPresence.LoadingAt(Anchor(state), 5, 9, "bunkhouse");
				return false;
			}
			Location[] locations = Object.FindObjectsByType<Location>((FindObjectsSortMode)0);
			bool replacing = state.HasPlot;
			if (replacing && !Protected(Anchor(state), locations))
			{
				return true;
			}
			if (replacing && !ConstructionRules.CanResurveyBunkhouse(chapter.State))
			{
				state.Problem = "Part of this bunkhouse plot lies in a protected location. Review its paid construction before continuing.";
				return false;
			}
			if (!SettlementPresence.Loaded(chapter.Camp))
			{
				state.Problem = SettlementPresence.LoadingAt(chapter.Camp, 0, 0, "the landing");
				return false;
			}
			if (!SettlementPresence.Near(chapter.Camp, 120f))
			{
				state.Problem = "Visit Boughhaven to survey the bunkhouse plot before contributing.";
				return false;
			}
			SettlementPresence.SurveyScene surveyScene = new SettlementPresence.SurveyScene();
			Vector3? val = null;
			Vector3? val2 = null;
			int num = int.MaxValue;
			float num2 = float.MaxValue;
			float gradeTarget = 0f;
			float num6 = default(float);
			float num8 = default(float);
			float num11 = default(float);
			for (int i = 25; i <= 110; i += 5)
			{
				for (int j = 0; j < 72; j++)
				{
					float num3 = (float)j * (float)Math.PI / 36f;
					Vector3 val3 = chapter.Camp + new Vector3(Mathf.Cos(num3) * (float)i, 0f, Mathf.Sin(num3) * (float)i);
					if (Vector3.Distance(val3, chapter.Yard) < 16f || Vector3.Distance(val3, chapter.Site) < 16f)
					{
						continue;
					}
					ConstructionState b = chapter.State.B03;
					if (b != null && b.HasPlot && Vector3.Distance(val3, TradingPostConstruction.Anchor(chapter.State.B03)) < 22f)
					{
						continue;
					}
					ConstructionState b2 = chapter.State.B05;
					if ((b2 != null && b2.HasPlot && Vector3.Distance(val3, GreenwardConstruction.Anchor(chapter.State.B05)) < 24f) || Protected(val3, locations) || TownSquare.Overlaps(chapter.State.Square, val3, 5f, 9f))
					{
						continue;
					}
					float num4 = float.MaxValue;
					float num5 = float.MinValue;
					bool flag = true;
					for (int k = -5; k <= 5; k += 2)
					{
						foreach (int surveyDepth in TerrainPreparationRules.SurveyDepths)
						{
							if (!ZoneSystem.instance.GetGroundHeight(val3 + new Vector3((float)k, 0f, (float)surveyDepth), ref num6) || num6 < 31f)
							{
								flag = false;
								break;
							}
							num4 = Mathf.Min(num4, num6);
							num5 = Mathf.Max(num5, num6);
						}
					}
					if (!flag || num5 - num4 > 4f)
					{
						continue;
					}
					val3.y = num5 + 0.15f;
					if (num5 - num4 > 1.8f)
					{
						if (!surveyScene.Plot(val3, 5, 9))
						{
							continue;
						}
						int num7 = ConstructionClearing.Trees(val3 + Vector3.up * 2f, new Vector3(5f, 6f, 9f), "rb_b04_construction", includeWildBeech: true);
						if (num7 >= 0 && ZoneSystem.instance.GetGroundHeight(val3, ref num8))
						{
							float num9 = Mathf.Round(num8);
							float num10 = num5 - num4 + (float)num7 * 0.1f;
							if (num9 >= 31f && num10 < num2)
							{
								val2 = val3;
								num2 = num10;
								gradeTarget = num9;
							}
						}
					}
					else if (ZoneSystem.instance.GetGroundHeight(val3 + new Vector3(0f, 0f, -8f), ref num11) && !(val3.y - 1f - num11 > 0.5f) && surveyScene.Plot(val3, 5, 9))
					{
						if (Obstruction(val3) == null)
						{
							return Mark(val3, null);
						}
						int num12 = ConstructionClearing.Trees(val3 + Vector3.up * 2f, new Vector3(5f, 6f, 9f), "rb_b04_construction", includeWildBeech: true);
						if (num12 > 0 && num12 < num)
						{
							num = num12;
							val = val3;
						}
					}
				}
			}
			if (val.HasValue)
			{
				return Mark(val.Value, "Clear the trees and fallen logs from the marked bunkhouse plot.");
			}
			if (val2.HasValue)
			{
				Vector3 value = val2.Value;
				value.y = gradeTarget + 0.15f;
				return Mark(value, "Prepare a 10 × 18 m plot with a hoe and pickaxe at ground level " + gradeTarget.ToString("0") + " m before contributing.", grade: true);
			}
			state.Problem = (replacing ? "The old bunkhouse survey reaches a protected location. Visit the landing to look for a dry unprotected plot. Your materials are still yours." : "No empty, dry bunkhouse plot found near Boughhaven. No materials were spent; survey needs review.");
			return false;
			bool Mark(Vector3 at, string work, bool grade = false)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				state.X = at.x;
				state.Y = at.y;
				state.Z = at.z;
				state.HasPlot = true;
				state.NeedsGrading = grade;
				state.GradeTarget = (grade ? gradeTarget : 0f);
				state.Problem = (replacing ? ("The old bunkhouse survey reached a protected location. Follow the new bunkhouse pin. " + (work ?? "Visit it before contributing.")) : work);
				chapter.Save();
				return !replacing;
			}
		}

		private static float GroundAt(Vector3 position)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			float result = default(float);
			if (!ZoneSystem.instance.GetGroundHeight(position, ref result))
			{
				throw new InvalidOperationException("Wait for the bunkhouse terrain to finish loading.");
			}
			return result;
		}

		private static HearthFooting SurveyFooting(ConstructionState state, ConstructionPart part)
		{
			//IL_0001: 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_0007: Unknown result type (might be due to invalid IL or missing references)
			//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_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: 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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = Anchor(state);
			Vector3 val2 = val + new Vector3(part.x, part.y, part.z);
			float num = float.MaxValue;
			for (int i = -1; i <= 1; i++)
			{
				for (int j = -1; j <= 1; j++)
				{
					num = Mathf.Min(num, GroundAt(val2 + new Vector3((float)i, 0f, (float)j)));
				}
			}
			if (!HearthFooting.IsBuried(val2.y, num))
			{
				return new HearthFooting();
			}
			Vector3 position = val + new Vector3((float)HearthFooting.RearColumns[part.id], 0f, 7f);
			return new HearthFooting
			{
				AtRear = true,
				Top = Mathf.CeilToInt(GroundAt(position) - val.y)
			};
		}

		private static Vector3 Position(ConstructionState state, ConstructionPart part)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			if (state.HearthFootings.TryGetValue(part.id, out var value) && value.AtRear)
			{
				return Anchor(state) + new Vector3((float)HearthFooting.RearColumns[part.id], (float)value.Top - 0.5f, 7f);
			}
			return Anchor(state) + new Vector3(part.x, part.y, part.z);
		}

		private static void RequestFootingReview(ConstructionState state, Dictionary<string, ZDO> existing)
		{
			string[] missing = state.Placed.Where((string id) => !existing.ContainsKey(id)).ToArray();
			if (HearthFooting.MayReview(state, missing))
			{
				repairRequested = state;
			}
			else if (repairRequested == state)
			{
				repairRequested = null;
			}
		}

		private static void Place(ConstructionState state, ConstructionPart part)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(ZNetScene.instance.GetPrefab(part.prefab), Position(state, part), Quaternion.Euler(0f, part.yaw, 0f));
			ZNetView component = val.GetComponent<ZNetView>();
			component.ClaimOwnership();
			component.GetZDO().Set("rb_b04_construction", part.id);
			component.GetZDO().Set("rb_b04_version", Plan.version);
			Piece component2 = val.GetComponent<Piece>();
			if (component2 != null)
			{
				component2.SetCreator(0L, default(PlatformUserID));
			}
			WearNTear component3 = val.GetComponent<WearNTear>();
			if ((Object)(object)component3 != (Object)null)
			{
				component3.OnPlaced();
			}
			if (part.id == "sign")
			{
				SignReadability.WriteAuthored(val.GetComponent<Sign>(), "<color=white>Boughhaven\nBunkhouse");
			}
			if ((Object)(object)val.GetComponent<Fireplace>() != (Object)null)
			{
				component.GetZDO().Set(ZDOVars.s_fuel, 0f);
			}
		}

		private static bool RecoverFootings(ChapterRuntime chapter, Dictionary<string, ZDO> existing, List<ConstructionPart> funded)
		{
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: 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)
			ConstructionState state = chapter.State.B04;
			string[] array = state.Placed.Where((string key) => !existing.ContainsKey(key)).ToArray();
			Dictionary<string, HearthFooting> dictionary = new Dictionary<string, HearthFooting>();
			string[] array2 = array;
			foreach (string id in array2)
			{
				if (!HearthFooting.RearColumns.ContainsKey(id))
				{
					return false;
				}
				ConstructionPart part = funded.SingleOrDefault((ConstructionPart p) => p.id == id && p.prefab == "stone_floor_2x2");
				if (part == null)
				{
					return false;
				}
				if (state.HearthFootings.TryGetValue(id, out var value))
				{
					if (!value.RepairPending)
					{
						return false;
					}
					continue;
				}
				ConstructionPart constructionPart = Plan.pieces.Single((ConstructionPart p) => p.prefab == part.prefab && p.x == part.x && p.z == part.z && p.y == part.y + 1f);
				if (!existing.TryGetValue(constructionPart.id, out var value2) || value2.GetPrefab() != StringExtensionMethods.GetStableHashCode(part.prefab) || Vector3.Distance(value2.GetPosition(), Position(state, constructionPart)) > 0.1f)
				{
					return false;
				}
				HearthFooting hearthFooting = SurveyFooting(state, part);
				if (!hearthFooting.AtRear)
				{
					return false;
				}
				hearthFooting.RepairPending = true;
				dictionary.Add(id, hearthFooting);
			}
			foreach (KeyValuePair<string, HearthFooting> item in dictionary)
			{
				state.HearthFootings.Add(item.Key, item.Value);
			}
			KeyValuePair<string, HearthFooting>[] array3 = state.HearthFootings.Where((KeyValuePair<string, HearthFooting> kv) => kv.Value.RepairPending).ToArray();
			if (array3.Length == 0)
			{
				return array.Length == 0;
			}
			chapter.Save();
			KeyValuePair<string, HearthFooting>[] array4 = array3;
			for (int num = 0; num < array4.Length; num++)
			{
				KeyValuePair<string, HearthFooting> entry = array4[num];
				ConstructionPart constructionPart2 = funded.Single((ConstructionPart p) => p.id == entry.Key && p.prefab == "stone_floor_2x2" && state.Placed.Contains(p.id));
				if (!existing.TryGetValue(constructionPart2.id, out var value3))
				{
					Place(state, constructionPart2);
				}
				else if (value3.GetPrefab() != StringExtensionMethods.GetStableHashCode(constructionPart2.prefab) || Vector3.Distance(value3.GetPosition(), Position(state, constructionPart2)) > 0.1f)
				{
					throw new InvalidDataException("A pending bunkhouse footing moved. Review the plot before continuing.");
				}
			}
			Physics.SyncTransforms();
			if (!Diagnostics.Testing)
			{
				ContributionNetwork.SaveWorld();
			}
			array4 = array3;
			foreach (KeyValuePair<string, HearthFooting> keyValuePair in array4)
			{
				keyValuePair.Value.RepairPending = false;
			}
			state.Problem = null;
			chapter.Save();
			return true;
		}

		internal static bool MayContribute(ChapterRuntime chapter, Vector3? contributor = null)
		{
			//IL_0042: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_0102: Unknown result type (might be due to invalid IL or missing references)
			if (!Prepare(chapter, contributor))
			{
				return false;
			}
			ConstructionState b = chapter.State.B04;
			Vector3? val = contributor;
			Vector3? obj;
			if (!val.HasValue)
			{
				Player localPlayer = Player.m_localPlayer;
				obj = ((localPlayer != null) ? new Vector3?(((Component)localPlayer).transform.position) : ((Vector3?)null));
			}
			else
			{
				obj = val;
			}
			Vector3? val2 = obj;
			if (!val2.HasValue || Vector3.Distance(val2.Value, Anchor(b)) > 60f)
			{
				b.Problem = "Move within 60 m of the bunkhouse plot before contributing.";
				return false;
			}
			if (!SettlementPresence.PlotLoaded(Anchor(b), 5, 9))
			{
				b.Problem = SettlementPresence.LoadingAt(Anchor(b), 5, 9, "bunkhouse");
				return false;
			}
			if (!TerrainPreparation.Bunkhouse(chapter))
			{
				return false;
			}
			Dictionary<string, ZDO> existing = Existing();
			if (b.Placed.Any((string id) => !existing.ContainsKey(id)))
			{
				RequestFootingReview(b, existing);
				b.Problem = ((repairRequested == b) ? "Inspecting the old hearth foundations. Retry when the stones are in place. No materials were spent." : "A committed bunkhouse piece is missing. Construction review is required before spending more materials.");
				return false;
			}
			b.Problem = Obstruction(Anchor(b));
			return b.Problem == null;
		}

		internal static void Tick(ChapterRuntime chapter)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: 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_0418: Unknown result type (might be due to invalid IL or missing references)
			//IL_046c: Unknown result type (might be due to invalid IL or missing references)
			//IL_047e: Unknown result type (might be due to invalid IL or missing references)
			ChapterState state = chapter.State;
			ConstructionState state2 = state.B04;
			bool flag = state2 != null && (repairRequested == state2 || state2.HearthFootings.Values.Any((HearthFooting f) => f.RepairPending));
			if (state2 == null || (state2.Completed && !flag) || !StoryRules.Unlocked(state.Story, "rb_02_roof") || !state2.HasPlot || !SettlementPresence.PlotLoaded(Anchor(state2), 5, 9) || !TerrainPreparation.Bunkhouse(chapter))
			{
				return;
			}
			List<ConstructionPart> funded = ConstructionRules.Funded(state, Plan.pieces);
			if (!flag && state2.Pending.Count == 0 && funded.Count == state2.Placed.Count)
			{
				return;
			}
			if (!SettlementPresence.Near(Anchor(state2), 60f))
			{
				state2.Problem = "Visit the bunkhouse plot to continue building.";
				return;
			}
			if (Protected(Anchor(state2), Object.FindObjectsByType<Location>((FindObjectsSortMode)0)))
			{
				state2.Problem = "Part of this bunkhouse plot lies in a protected location. Review its paid construction before continuing.";
				return;
			}
			try
			{
				Dictionary<string, ZDO> existing = Existing();
				if (flag)
				{
					string text = Obstruction(Anchor(state2));
					if (text != null)
					{
						state2.Problem = text;
						return;
					}
					repairRequested = null;
					if (!RecoverFootings(chapter, existing, funded))
					{
						state2.Problem = "A committed bunkhouse piece is missing. Review the construction before contributing.";
					}
					return;
				}
				if (state2.Placed.Any((string id) => !existing.ContainsKey(id)))
				{
					state2.Problem = "A committed bunkhouse piece is missing. Restore the matched save or request a construction review; it will not be regenerated for free.";
					return;
				}
				if (state2.Pending.Any((string id) => !funded.Any((ConstructionPart p) => p.id == id)))
				{
					throw new InvalidDataException("Placement journal exceeds funded materials.");
				}
				ConstructionPart[] array = funded.Where((ConstructionPart p) => !state2.Placed.Contains(p.id)).ToArray();
				if (array.Length == 0)
				{
					return;
				}
				bool flag2 = array.All((ConstructionPart part) => state2.Pending.Contains(part.id) && existing.ContainsKey(part.id));
				if (!flag2)
				{
					string text2 = Obstruction(Anchor(state2));
					if (text2 != null)
					{
						state2.Problem = text2;
						return;
					}
				}
				ConstructionPart[] array2 = array;
				foreach (ConstructionPart constructionPart in array2)
				{
					if ((Object)(object)ZNetScene.instance.GetPrefab(constructionPart.prefab) == (Object)null)
					{
						throw new InvalidDataException("Missing construction prefab: " + constructionPart.prefab);
					}
				}
				foreach (ConstructionPart item in array.Where((ConstructionPart p) => HearthFooting.RearColumns.ContainsKey(p.id) && !existing.ContainsKey(p.id) && !state2.HearthFootings.ContainsKey(p.id)))
				{
					state2.HearthFootings.Add(item.id, SurveyFooting(state2, item));
				}
				state2.Pending = array.Select((ConstructionPart p) => p.id).ToList();
				chapter.Save();
				if (state2.Placed.Count == 0 && !flag2)
				{
					ConstructionGround.Clear(Anchor(state2), ConstructionGround.HouseCells(Anchor(state2), Plan));
				}
				array2 = array;
				foreach (ConstructionPart constructionPart2 in array2)
				{
					if (existing.TryGetValue(constructionPart2.id, out var value))
					{
						if (value.GetPrefab() != StringExtensionMethods.GetStableHashCode(constructionPart2.prefab) || (Vector3.Distance(value.GetPosition(), Position(state2, constructionPart2)) > 0.1f && !IsOriginalRearBed(state2, constructionPart2, value)))
						{
							throw new InvalidDataException("A pending bunkhouse piece moved; review its placement before resuming.");
						}
					}
					else
					{
						Place(state2, constructionPart2);
					}
				}
				Physics.SyncTransforms();
				if (!Diagnostics.Testing)
				{
					ContributionNetwork.SaveWorld();
				}
				state2.Placed.UnionWith(state2.Pending);
				state2.Pending.Clear();
				state2.Completed = state2.Placed.Count == Plan.pieces.Count;
				state2.Problem = null;
				chapter.Save();
			}
			catch (Exception ex)
			{
				state2.Problem = ex.GetBaseException().Message;
				chapter.Save();
				Plugin.Instance.LogWarning("bunkhouse construction paused: " + state2.Problem);
			}
		}

		internal static string Summary(ChapterState town)
		{
			ConstructionState state = town.B04;
			if (state == null)
			{
				return "bunkhouse construction ledger is loading.";
			}
			string text = (state.Completed ? "Complete — supply firewood and assign beds." : (state.Placed.Count + " / 200 pieces built"));
			int num = (from p in Plan.pieces
				where state.Placed.Contains(p.id)
				select p.stage).DefaultIfEmpty(0).Max();
			return "COMMUNAL BUNKHOUSE · " + text + "\nPhase: " + (new string[5] { "Awaiting materials", "Foundations", "Frame", "Roof", "Furnishings" })[num] + "\n" + string.Join(", ", ConstructionRules.Resources.Select((string r) => ConstructionRules.Paid(town, r) + " / " + ChapterRules.Required("bunkhouse", r) + " " + r)) + "\n" + (state.LegacyCompleted ? "Earlier cabin repair is preserved; the bunkhouse is an optional expansion.\n" : "") + (state.Problem ?? (state.HasPlot ? "Find the bunkhouse map pin." : "The first contribution surveys an empty plot."));
		}

		private static Dictionary<string, ConstructionPart> ReadIronEntrance()
		{
			using Stream stream = typeof(Plugin).Assembly.GetManifestResourceStream("ReturningBough.B04IronEntrance.json");
			using StreamReader streamReader = new StreamReader(stream);
			return JsonConvert.DeserializeObject<ConstructionPlan>(streamReader.ReadToEnd()).pieces.ToDictionary((ConstructionPart p) => p.id);
		}

		private static bool AtEntranceSlot(ConstructionState house, ConstructionPart part, ZDO zdo)
		{
			//IL_0014: 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)
			if (zdo.GetPrefab() == StringExtensionMethods.GetStableHashCode(part.prefab))
			{
				return Vector3.Distance(zdo.GetPosition(), Position(house, part)) <= 0.16f;
			}
			return false;
		}

		private static bool FitsEntrance(ConstructionState house, ConstructionPart part, ZDO zdo)
		{
			//IL_000b: 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)
			if (AtEntranceSlot(house, part, zdo))
			{
				return Quaternion.Angle(zdo.GetRotation(), Quaternion.Euler(0f, part.yaw, 0f)) <= 5f;
			}
			return false;
		}

		private static bool HasIronDoor(Dictionary<string, ZDO> existing)
		{
			if (existing.TryGetValue("door", out var value))
			{
				return value.GetPrefab() == StringExtensionMethods.GetStableHashCode(IronEntrance["door"].prefab);
			}
			return false;
		}

		private static string RecordEntrance(ConstructionState house, Dictionary<string, ZDO> existing, List<ZDO> nearby, long builder, ref int recorded)
		{
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			if (!IronEntrance.Keys.All(house.Placed.Contains))
			{
				return "The saved bunkhouse project is missing entrance records. Review its construction ledger.";
			}
			bool flag = HasIronDoor(existing) || nearby.Any((ZDO z) => AtEntranceSlot(house, IronEntrance["door"], z));
			Dictionary<string, ZDO> dictionary = new Dictionary<string, ZDO>();
			foreach (ConstructionPart item in Plan.pieces.Where((ConstructionPart p) => IronEntrance.ContainsKey(p.id)))
			{
				ConstructionPart constructionPart = IronEntrance[item.id];
				ConstructionPart expected = (flag ? constructionPart : item);
				ConstructionPart other = (flag ? item : constructionPart);
				ZDO[] array = nearby.Where((ZDO z) => AtEntranceSlot(house, expected, z)).ToArray();
				bool flag2 = array.Length == 1 && FitsEntrance(house, expected, array[0]) && !nearby.Any((ZDO z) => AtEntranceSlot(house, other, z));
				if (flag2 && existing.TryGetValue(item.id, out var value))
				{
					flag2 = value.m_uid == array[0].m_uid;
				}
				else if (flag2 && CanRecordRepair(array[0], builder))
				{
					dictionary.Add(item.id, array[0]);
				}
				else
				{
					flag2 = false;
				}
				if (!flag2)
				{
					return flag ? "Finish the iron entrance before recording it. Fit the gate, raised half wall and both short beams. Remove the old frame and use your own hammer pieces." : "Repair the wooden entrance or fit the four-piece iron entrance, then record it here.";
				}
			}
			foreach (KeyValuePair<string, ZDO> item2 in dictionary)
			{
				RecordRepair(item2.Key, item2.Value, existing);
				recorded++;
			}
			return null;
		}

		private static bool ReinforceableFloor(ConstructionPart part)
		{
			if (part.prefab == "wood_floor" && part.y == 0f && Mathf.Abs(part.x) <= 3f && part.z >= -5f)
			{
				return part.z <= 1f;
			}
			return false;
		}

		private static Vector3 StonePosition(ConstructionState house, ConstructionPart part)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			return Position(house, part) + Vector3.down * 0.43f;
		}

		private static bool MatchesCompletedPiece(ConstructionState house, ConstructionPart part, ZDO native)
		{
			//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)
			if (native.GetPrefab() != StringExtensionMethods.GetStableHashCode(part.prefab))
			{
				if (ReinforceableFloor(part) && native.GetPrefab() == StringExtensionMethods.GetStableHashCode("stone_floor_2x2"))
				{
					return Vector3.Distance(native.GetPosition(), StonePosition(house, part)) <= 0.12f;
				}
				return false;
			}
			return true;
		}

		internal static bool IsBunkroomFloor(ZDO support)
		{
			if (support == null)
			{
				return false;
			}
			string id = support.GetString("rb_b04_construction", "");
			if (id.Length == 0)
			{
				return false;
			}
			if (support.GetPrefab() == StringExtensionMethods.GetStableHashCode("wood_floor"))
			{
				return true;
			}
			if (support.GetPrefab() == StringExtensionMethods.GetStableHashCode("stone_floor_2x2"))
			{
				return Plan.pieces.Any((ConstructionPart p) => p.id == id && ReinforceableFloor(p));
			}
			return false;
		}

		private static bool CanRecordRepair(ZDO zdo, long builder)
		{
			if (zdo.GetLong(ZDOVars.s_creator, 0L) == builder && zdo.GetInt(ZDOVars.s_inUse, 0) == 0 && zdo.GetString("rb_b04_construction", "") == "" && zdo.GetString("rb_square_part", "") == "" && zdo.GetString("rb_b03_construction", "") == "")
			{
				return zdo.GetString("rb_b05_construction", "") == "";
			}
			return false;
		}

		private static void RecordRepair(string id, ZDO zdo, Dictionary<string, ZDO> existing)
		{
			zdo.SetOwner(ZDOMan.GetSessionID());
			zdo.Set("rb_b04_construction", id);
			zdo.Set("rb_b04_version", Plan.version);
			existing.Add(id, zdo);
		}

		internal static string RegisterFurnishings(ChapterRuntime chapter, Vector3 inspector, long builder)
		{
			//IL_0059: 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_0062: 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_0076: 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_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			ConstructionState house = chapter.State.B04;
			ConstructionState constructionState = house;
			if (constructionState == null || !constructionState.Completed || !house.HasPlot || house.Pending.Count != 0)
			{
				return "Finish the shared bunkhouse before recording repairs.";
			}
			Vector3 val = Anchor(house);
			if (builder == 0L || Vector3.Distance(inspector, val) > 9f)
			{
				return "Stand inside the bunkhouse to record your repairs.";
			}
			if (!SettlementPresence.PlotLoaded(val, 5, 9))
			{
				return "Wait for the bunkhouse to load, then check the repairs again.";
			}
			Dictionary<string, ZDO> existing = Existing();
			ConstructionPart[] array = Plan.pieces.Where((ConstructionPart p) => p.prefab == "bed" || p.prefab == "piece_chest_wood" || p.prefab == "sign" || p.id == "entry_ramp" || ReinforceableFloor(p)).ToArray();
			if (array.Any((ConstructionPart p) => !house.Placed.Contains(p.id) || (existing.TryGetValue(p.id, out var value) && !MatchesCompletedPiece(house, p, value))))
			{
				return "A piece disagrees with the saved bunkhouse project. Review the matched save before recording repairs.";
			}
			List<ZDO> list = new List<ZDO>();
			ZDOMan.instance.FindSectorObjects(ZoneSystem.GetZone(val), new SimulationDistance(1, 0, true), list, (List<ZDO>)null);
			List<string> list2 = new List<string>();
			int recorded = 0;
			string text = RecordEntrance(house, existing, list, builder, ref recorded);
			ConstructionPart[] array2 = array;
			foreach (ConstructionPart part in array2)
			{
				if (existing.ContainsKey(part.id))
				{
					continue;
				}
				Vector3 position = Position(house, part);
				Quaternion val2 = Quaternion.Euler(0f, part.yaw, 0f);
				ZDO[] array3 = list.Where((ZDO z) => z.GetPrefab() == StringExtensionMethods.GetStableHashCode(part.prefab) && Vector3.Distance(z.GetPosition(), position) <= 0.4f).ToArray();
				if (array3.Length == 0 && ReinforceableFloor(part))
				{
					array3 = list.Where((ZDO z) => z.GetPrefab() == StringExtensionMethods.GetStableHashCode("stone_floor_2x2") && MatchesCompletedPiece(house, part, z)).ToArray();
				}
				if (array3.Length != 1 || Quaternion.Angle(array3[0].GetRotation(), val2) > 10f || !CanRecordRepair(array3[0], builder))
				{
					list2.Add(part.id.Replace("_", " "));
					continue;
				}
				RecordRepair(part.id, array3[0], existing);
				recorded++;
			}
			string problem = house.Problem;
			bool flag = VerifyCompletedPieces(house, existing);
			if (problem != house.Problem)
			{
				chapter.Save();
			}
			string text2 = ((recorded == 0) ? "" : $"Recorded {recorded} of your replacement pieces. ");
			if (text != null)
			{
				text2 = text2 + text + " ";
			}
			if (list2.Count != 0)
			{
				return text2 + "Still missing " + string.Join(", ", list2) + ". Match the original position and facing with your hammer, then check here.";
			}
			if (text != null)
			{
				return text2.TrimEnd(Array.Empty<char>());
			}
			return text2 + (flag ? "All 200 bunkhouse pieces are recorded." : "Other bunkhouse structural pieces still need repair.");
		}

		private static bool IsOriginalRearBed(ConstructionState house, ConstructionPart part, ZDO saved)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: 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)
			if (part.id != "bed_3" && part.id != "bed_4")
			{
				return false;
			}
			int num = saved.GetInt("rb_b04_version", 0);
			if ((num != 1 && num != 2) || saved.GetString("rb_b04_construction", "") != part.id || saved.GetPrefab() != StringExtensionMethods.GetStableHashCode("bed"))
			{
				return false;
			}
			Vector3 val = Anchor(house) + new Vector3((float)((part.id == "bed_3") ? (-3) : 3), part.y, 1.5f);
			if (Vector3.Distance(saved.GetPosition(), val) < 0.05f)
			{
				return Quaternion.Angle(saved.GetRotation(), Quaternion.identity) < 1f;
			}
			return false;
		}

		private static void UpgradeSign(ConstructionState house, IEnumerable<ZDO> taggedSigns)
		{
			//IL_005f: 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_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: 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_012b: Unknown result type (might be due to invalid IL or missing references)
			if (!house.Placed.Contains("sign") && !house.Pending.Contains("sign"))
			{
				return;
			}
			ZDO[] array = taggedSigns.ToArray();
			if (array.Length != 1)
			{
				return;
			}
			ZDO val = array[0];
			int num = val.GetInt("rb_b04_version", 0);
			if (num < 1 || num >= 4 || val.GetPrefab() != StringExtensionMethods.GetStableHashCode("sign") || Quaternion.Angle(val.GetRotation(), Quaternion.Euler(0f, 180f, 0f)) > 1f)
			{
				return;
			}
			Vector3 val2 = Anchor(house);
			Vector3 val3 = val.GetPosition() - val2;
			if (!(Vector3.Distance(val3, new Vector3(-2f, 1.5f, -4.18f)) > 0.05f) || !(Vector3.Distance(val3, new Vector3(-3f, 1.6f, -4.22f)) > 0.05f))
			{
				ConstructionPart constructionPart = Plan.pieces.Single((ConstructionPart p) => p.id == "sign");
				val.SetPosition(val2 + new Vector3(constructionPart.x, constructionPart.y, constructionPart.z));
				if (SignReadability.Default(val.GetString(ZDOVars.s_text, "").Replace("\r\n", "\n")) == "<color=white>Boughhaven communal bunkhouse\nBuilt by the returning clans\nFour beds — keep the hearth supplied")
				{
					val.Set(ZDOVars.s_text, "<color=white>Boughhaven\nBunkhouse");
				}
				val.Set("rb_b04_version", Plan.version);
			}
		}

		internal unsafe static void Upgrade(ConstructionState house, long world)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: 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_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0292: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: 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_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03de: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0400: Unknown result type (might be due to invalid IL or missing references)
			//IL_0405: Unknown result type (might be due to invalid IL or missing references)
			//IL_0370: Unknown result type (might be due to invalid IL or missing references)
			//IL_037d: Unknown result type (might be due to invalid IL or missing references)
			//IL_039b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a0: 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_0446: Unknown result type (might be due to invalid IL or missing references)
			//IL_0448: Unknown result type (might be due to invalid IL or missing references)
			//IL_044a: 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_045c: Unknown result type (might be due to invalid IL or missing references)
			//IL_045e: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = Anchor(house);
			List<ZDO> list = new List<ZDO>();
			ZDOMan.instance.FindSectorObjects(ZoneSystem.GetZone(val), new SimulationDistance(1, 0, true), list, (List<ZDO>)null);
			ILookup<string, ZDO> lookup = list.ToLookup((ZDO z) => z.GetString("rb_b04_construction", ""));
			UpgradeSign(house, lookup["sign"]);
			(string, string, Vector3, float)[] originalMounts = OriginalMounts;
			for (int num = 0; num < originalMounts.Length; num++)
			{
				(string Id, string Prefab, Vector3 Local, float Yaw) old = originalMounts[num];
				if (!house.Placed.Contains(old.Id) && !house.Pending.Contains(old.Id))
				{
					continue;
				}
				ZDO[] array = lookup[old.Id].ToArray();
				if (array.Length == 1)
				{
					ZDO val2 = array[0];
					ConstructionPart constructionPart = Plan.pieces.Single((ConstructionPart p) => p.id == old.Id);
					if (val2.GetInt("rb_b04_version", 0) == 1 && val2.GetPrefab() == StringExtensionMethods.GetStableHashCode(old.Prefab) && !(Vector3.Distance(val2.GetPosition(), val + old.Local) > 0.05f) && !(Quaternion.Angle(val2.GetRotation(), Quaternion.Euler(0f, old.Yaw, 0f)) > 1f))
					{
						val2.SetPrefab(StringExtensionMethods.GetStableHashCode(constructionPart.prefab));
						val2.SetPosition(val + new Vector3(constructionPart.x, constructionPart.y, constructionPart.z));
						val2.SetRotation(Quaternion.Euler(0f, constructionPart.yaw, 0f));
						val2.Set("rb_b04_version", Plan.version);
						Logger.LogInfo((object)("Updated bunkhouse part " + old.Id));
					}
				}
			}
			string[] commandLineArgs = Environment.GetCommandLineArgs();
			int num2 = Array.IndexOf(commandLineArgs, "-rb-align-b04-banner");
			Vector3 target = val + new Vector3(4.26f, 2.95f, 1f);
			Quaternion rotation = Quaternion.Euler(0f, 180f, 0f);
			Vector3 original = val + new Vector3(4.5122f, 1.4861f, 0.3889f);
			Quaternion originalRotation = Quaternion.Euler(0f, 157.5f, 0f);
			ZDO[] source = list.Where((ZDO z) => z.GetPrefab() == StringExtensionMethods.GetStableHashCode("vnpc_settlement_banner")).ToArray();
			long result;
			bool flag = num2 >= 0 && num2 + 1 < commandLineArgs.Length && long.TryParse(commandLineArgs[num2 + 1], out result) && result == world && !ZNet.instance.IsDedicated() && house.Completed;
			ZDO[] array2 = source.Where((ZDO z) => z.GetBool("rb_b04_mounted_banner", false) && Vector3.Distance(z.GetPosition(), target) < 0.06f && Quaternion.Angle(z.GetRotation(), rotation) < 1f).ToArray();
			bool flag2 = array2.Length == 0 && flag;
			if (flag2)
			{
				array2 = source.Where((ZDO z) => z.GetLong(ZDOVars.s_creator, 0L) != 0L && Vector3.Distance(z.GetPosition(), original) < 0.06f && Quaternion.Angle(z.GetRotation(), originalRotation) < 1f).ToArray();
			}
			if (array2.Length != 1)
			{
				return;
			}
			ZDO val3 = array2[0];
			if (flag2)
			{
				val3.SetPosition(target);
				val3.SetRotation(rotation);
				val3.Set("rb_b04_mounted_banner", true);
				ZDOID uid = val3.m_uid;
				Logger.LogInfo((object)("Aligned the existing bunkhouse settlement banner " + ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString()));
			}
			Vector3 val4 = target + rotation * Vector3.forward * 1.5f;
			Vector3 val5 = original + originalRotation * Vector3.forward * 1.5f;
			foreach (ZDO item in All("VNPC_Viking"))
			{
				if (item.GetBool("vnpc_has_base", false))
				{
					Vector3 vec = item.GetVec3("vnpc_base", Vector3.zero);
					if (!(Vector3.Distance(vec, val4) > 0.06f) || (flag2 && !(Vector3.Distance(vec, val5) > 0.06f)))
					{
						item.Set("vnpc_base", val4);
						item.Set("vnpc_base_user", ((ZDOID)(ref val3.m_uid)).UserID);
						item.Set("vnpc_base_id", (long)((ZDOID)(ref val3.m_uid)).ID);
					}
				}
			}
		}
	}
	internal sealed class BunkhouseSurveyOverlay
	{
		private readonly float[] heights = new float[TerrainPreparationRules.SampleCount];

		private readonly Vector3[] points = (Vector3[])(object)new Vector3[TerrainPreparationRules.SampleCount];

		private readonly Text[] marks = (Text[])(object)new Text[TerrainPreparationRules.SampleCount];

		private readonly bool[] obscured = new bool[TerrainPreparationRules.SampleCount];

		private readonly string[] symbols = new string[TerrainPreparationRules.SampleCount];

		private readonly Color[] colors = (Color[])(object)new Color[TerrainPreparationRules.SampleCount];

		private GameObject group;

		private Text readout;

		private ItemData tool;

		private bool measured;

		private string overview;

		private Vector3 anchor;

		private float target;

		private float nextSightCheck;

		private static readonly int PlaceMask = LayerMask.GetMask(new string[7] { "Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "vehicle" });

		internal void Measure(Player player)
		{
			//IL_00e6: 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_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0285: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			measured = false;
			StorySnapshot view = StoryNetwork.View;
			if (!Plugin.TestWorld || view?.World != ZNet.instance.GetWorldUID() || !view.BunkhouseGrade.HasValue || (Object)(object)ZoneSystem.instance == (Object)null)
			{
				return;
			}
			target = view.BunkhouseGrade.Value;
			StorySite storySite = view.Sites?.FirstOrDefault((StorySite s) => s.Id == "b04");
			if (storySite == null || !TerrainPreparationRules.IsPrepared(target, target))
			{
				return;
			}
			anchor = new Vector3(storySite.X, storySite.Y, storySite.Z);
			Vector3 position = ((Component)player).transform.position;
			Vector3 val = anchor - position;
			if (((Vector3)(ref val)).sqrMagnitude > 324f)
			{
				return;
			}
			tool = ((IEnumerable<ItemData>)((Humanoid)player).GetInventory().GetAllItems()).FirstOrDefault((Func<ItemData, bool>)((ItemData item) => ((Humanoid)player).IsItemEquiped(item) && ((int)item.m_shared.m_skillType == 12 || ((Object)(object)item.m_dropPrefab != (Object)null && ((Object)item.m_dropPrefab).name == "Hoe"))));
			float value = default(float);
			if (tool != null && TerrainPreparation.Measure(anchor, heights) && ZoneSystem.instance.GetGroundHeight(position, ref value))
			{
				overview = "Bunkhouse   Target " + Metres(target) + " m   ·   Ground underfoot " + Metres(value) + " m";
				for (int num = 0; num < points.Length; num++)
				{
					Vector3 val2 = TerrainPreparation.SamplePosition(anchor, num);
					val2.y = heights[num] + 0.12f;
					points[num] = val2;
					bool flag = TerrainPreparationRules.IsPrepared(heights[num], target);
					bool flag2 = heights[num] < target;
					symbols[num] = (flag ? "•" : (flag2 ? "+" : "−"));
					colors[num] = (flag ? new Color(0.66f, 0.88f, 0.69f) : (flag2 ? new Color(0.57f, 0.86f, 1f) : new Color(1f, 0.72f, 0.43f)));
				}
				measured = true;
			}
		}

		private static string Metres(float value)
		{
			return value.ToString("0.0", CultureInfo.InvariantCulture);
		}

		internal void Draw(Transform canvas, Player player, bool visible)
		{
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: 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_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: 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_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_0292: 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_02ba: Unknown result type (might be due to invalid IL or missing references)
			StorySnapshot view = StoryNetwork.View;
			Camera val = ((visible && measured && (Object)(object)canvas != (Object)null && view != null && view.BunkhouseGrade.HasValue && view.World == ZNet.instance.GetWorldUID() && ((Humanoid)player).IsItemEquiped(tool)) ? Utils.GetMainCamera() : null);
			if ((Object)(object)val == (Object)null)
			{
				if ((Object)(object)group != (Object)null && group.activeSelf)
				{
					group.SetActive(false);
				}
				return;
			}
			if ((Object)(object)group == (Object)null)
			{
				group = new GameObject("RB B04 grading survey", new Type[1] { typeof(RectTransform) });
				RectTransform val2 = (RectTransform)group.transform;
				((Transform)val2).SetParent(canvas, false);
				val2.anchorMin = Vector2.zero;
				val2.anchorMax = Vector2.one;
				Vector2 offsetMin = (val2.offsetMax = Vector2.zero);
				val2.offsetMin = offsetMin;
				for (int i = 0; i < marks.Length; i++)
				{
					marks[i] = SurveyText((Transform)(object)val2, 28, 38, Vector2.zero);
				}
				readout = SurveyText((Transform)(object)val2, 22, 760, new Vector2(0f, -125f));
			}
			group.SetActive(true);
			bool flag = Time.unscaledTime >= nextSightCheck;
			if (flag)
			{
				nextSightCheck = Time.unscaledTime + 0.2f;
				readout.text = AimHeight(val, player);
			}
			Vector2 val5 = default(Vector2);
			for (int j = 0; j < marks.Length; j++)
			{
				Vector3 val3 = val.WorldToViewportPoint(points[j]);
				bool num = val3.z > 0f && val3.x >= 0f && val3.x <= 1f && val3.y >= 0f && val3.y <= 1f;
				Text val4 = marks[j];
				if (num && flag)
				{
					obscured[j] = Physics.Linecast(((Component)val).transform.position, points[j], PlaceMask, (QueryTriggerInteraction)1);
				}
				bool flag2 = num && !obscured[j];
				if (((Component)val4).gameObject.activeSelf != flag2)
				{
					((Component)val4).gameObject.SetActive(flag2);
				}
				if (flag2)
				{
					((Vector2)(ref val5))..ctor(val3.x, val3.y);
					RectTransform rectTransform = ((Graphic)val4).rectTransform;
					Vector2 offsetMin = (((Graphic)val4).rectTransform.anchorMax = val5);
					rectTransform.anchorMin = offsetMin;
					val4.text = symbols[j];
					((Graphic)val4).color = colors[j];
				}
			}
		}

		private string AimHeight(Camera camera, Player player)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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_004b: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: 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_010f: Unknown result type (might be due to invalid IL or missing references)
			RaycastHit val = default(RaycastHit);
			if (Physics.Raycast(((Component)camera).transform.position, ((Component)camera).transform.forward, ref val, 50f, PlaceMask, (QueryTriggerInteraction)1) && !((Object)(object)((Component)((RaycastHit)(ref val)).collider).GetComponent<Heightmap>() == (Object)null))
			{
				Vector3 val2 = ((RaycastHit)(ref val)).point - ((Character)player).GetEyePoint();
				if (!(((Vector3)(ref val2)).sqrMagnitude >= player.m_maxPlaceDistance * player.m_maxPlaceDistance) && TerrainPreparationRules.Inside(((RaycastHit)(ref val)).point.x - anchor.x, ((RaycastHit)(ref val)).point.z - anchor.z))
				{
					if (TerrainPreparationRules.IsPrepared(((RaycastHit)(ref val)).point.y, target))
					{
						return overview + "   ·   Level";
					}
					string text = ((((RaycastHit)(ref val)).point.y < target) ? "Raise " : "Lower ");
					return overview + "   ·   " + text + Metres(Math.Abs(((RaycastHit)(ref val)).point.y - target)) + " m";
				}
			}
			return overview;
		}

		private static Text SurveyText(Transform parent, int size, int width, Vector2 at)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			Text obj = SettlementUi.Label(parent, "", size, at, width, 42f, Color.white, (TextAnchor)4);
			Outline obj2 = ((Component)obj).gameObject.AddComponent<Outline>();
			((Shadow)obj2).effectColor = Color.black;
			((Shadow)obj2).effectDistance = new Vector2(1.5f, -1.5f);
			return obj;
		}
	}
	internal static class CampaignBuildingSite
	{
		internal const string Reserved = "Campaign buildings need a clear plot at least 100 m from the sacrificial stones. No new materials were spent.";

		private static ZoneSystem mappedWorld;

		private static Vector3 stones;

		internal static bool Allowed(Vector3 at, float halfWidth, float halfDepth)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: 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_002f: Unknown result type (might be due to invalid IL or missing references)
			ZoneSystem instance = ZoneSystem.instance;
			if (!Object.op_Implicit((Object)(object)instance))
			{
				return false;
			}
			if ((Object)(object)mappedWorld != (Object)(object)instance)
			{
				Vector3 val = default(Vector3);
				if (!instance.GetLocationIcon("StartTemple", ref val))
				{
					return false;
				}
				stones = val;
				mappedWorld = instance;
			}
			float num = Mathf.Max(Mathf.Abs(at.x - stones.x) - halfWidth, 0f);
			float num2 = Mathf.Max(Mathf.Abs(at.z - stones.z) - halfDepth, 0f);
			return num * num + num2 * num2 >= 10000f;
		}

		internal static bool CanResurvey(ChapterState town, string project, ConstructionState plot)
		{
			if ((plot == null || (!plot.Completed && plot.Placed.Count == 0 && plot.Pending.Count == 0)) && !town.Contributions.Any((KeyValuePair<string, int> p) => p.Key.StartsWith(project + ":", StringComparison.Ordinal) && p.Value > 0) && town.Pending?.Target != "project:" + project && town.Pending?.Target != project)
			{
				return !town.Deposits.Transfers.Values.Any((ContributionTransfer t) => t.Target == project && ContributionRules.Pending(t));
			}
			return false;
		}
	}
	internal static class CampaignOffers
	{
		[HarmonyPatch]
		private static class AvailableList
		{
			private static MethodBase TargetMethod()
			{
				return AccessTools.Method(AccessTools.TypeByName("TravsServerNPCs.UI.Views"), "QuestsAvailable", (Type[])null, (Type[])null);
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				MethodInfo original = AccessTools.Method(typeof(QuestRules), "Availability", (Type[])null, (Type[])null);
				foreach (CodeInstruction instruction in instructions)
				{
					if (CodeInstructionExtensions.Calls(instruction, original))
					{
						instruction.operand = AccessTools.Method(typeof(AvailableList), "Offer", (Type[])null, (Type[])null);
					}
					yield return instruction;
				}
			}

			priv

plugins/ReturningBough.WorkerDefense.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using ValheimNpc;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("ReturningBough.WorkerDefense")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a2f35a034722da7812b950e985e6acc0439cb25c")]
[assembly: AssemblyProduct("ReturningBough.WorkerDefense")]
[assembly: AssemblyTitle("ReturningBough.WorkerDefense")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ReturningBough.WorkerDefense
{
	[BepInPlugin("cwew.returningbough.workerdefense", "Returning Bough Worker Self-Defense", "0.1.11")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class WorkerDefense : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(VikingNpc), "ApproachReachUp")]
		private static class AssignedGuardStairs
		{
			private sealed class Ascent
			{
				internal Vector3 Post;

				internal Vector3? Origin;

				internal readonly List<Vector3> Waypoints = new List<Vector3>();

				internal readonly List<Piece> Supports = new List<Piece>();

				internal int Next;

				internal float LastUse;

				internal float RetryAt;

				internal object WalkTask;
			}

			[HarmonyPatch(typeof(VikingNpc), "UpdateAssignedPatrol")]
			private static class FinishActiveAscent
			{
				private static bool Prefix(VikingNpc __instance, List<Vector3> points, object ___m_task)
				{
					//IL_0046: 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_0056: Unknown result type (might be due to invalid IL or missing references)
					if (points.Count == 1 && ___m_task != null && Routes.TryGetValue(__instance, out var value) && value.Waypoints.Count != 0 && value.WalkTask == ___m_task && !(Time.time - value.LastUse > 1f))
					{
						Vector3 val = points[0] - value.Post;
						return ((Vector3)(ref val)).sqrMagnitude > 0.01f;
					}
					return true;
				}
			}

			private sealed class WalkTile
			{
				internal Piece Piece;

				internal Vector3 Surface;

				internal WalkTile Uphill;

				internal bool IsStair;
			}

			private sealed class Watch
			{
				internal VikingNpc Guard;

				internal Vector3 Stand;

				internal Piece FloorPiece;
			}

			[HarmonyPatch(typeof(VikingNpc), "UpdateRaid")]
			private static class ArcherOnDuty
			{
				private static void Postfix(VikingNpc __instance, MonsterAI ___m_ai)
				{
					//IL_0073: Unknown result type (might be due to invalid IL or missing references)
					//IL_0079: Invalid comparison between Unknown and I4
					//IL_0094: Unknown result type (might be due to invalid IL or missing references)
					//IL_009a: Invalid comparison between Unknown and I4
					//IL_0109: Unknown result type (might be due to invalid IL or missing references)
					//IL_010e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0115: Unknown result type (might be due to invalid IL or missing references)
					//IL_011a: Unknown result type (might be due to invalid IL or missing references)
					//IL_011c: 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_0136: Unknown result type (might be due to invalid IL or missing references)
					//IL_0138: Unknown result type (might be due to invalid IL or missing references)
					//IL_0199: Unknown result type (might be due to invalid IL or missing references)
					//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
					//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
					//IL_0171: Unknown result type (might be due to invalid IL or missing references)
					//IL_0176: Unknown result type (might be due to invalid IL or missing references)
					//IL_0177: Unknown result type (might be due to invalid IL or missing references)
					//IL_017c: Unknown result type (might be due to invalid IL or missing references)
					//IL_01de: Unknown result type (might be due to invalid IL or missing references)
					//IL_01df: Unknown result type (might be due to invalid IL or missing references)
					Humanoid character = __instance.Character;
					if (!Object.op_Implicit((Object)(object)character))
					{
						return;
					}
					if (!Object.op_Implicit((Object)(object)__instance.NetView) || !__instance.NetView.IsValid() || !__instance.NetView.IsOwner() || !Object.op_Implicit((Object)(object)___m_ai) || (!__instance.IsDefending() && !Object.op_Implicit((Object)(object)((BaseAI)___m_ai).GetTargetCreature())) || __instance.IsAssaulting() || __instance.IsPassive() || (int)__instance.GetMode() != 3 || !__instance.IsHired() || __instance.IsDowned() || __instance.IsSleeping() || (int)__instance.GetCombatRole() != 3 || !OnGuardDuty(__instance) || __instance.NetView.GetZDO().GetInt(Assignment, 0) >= 0 || !(bool)campaignWorld.GetValue(null, null))
					{
						Watches.Remove((Character)(object)character);
						return;
					}
					List<Vector3> list = GuardPoints(__instance);
					if (list == null || list.Count != 1)
					{
						Watches.Remove((Character)(object)character);
						return;
					}
					Vector3 val = list[0];
					Vector3 position = ((Component)character).transform.position;
					if (Mathf.Abs(position.y - val.y) > 0.45f || Utils.DistanceXZ(position, val) > 1.5f)
					{
						Watches.Remove((Character)(object)character);
						return;
					}
					Vector3 surface;
					if (Watches.TryGetValue((Character)(object)character, out var value))
					{
						if (Object.op_Implicit((Object)(object)value.FloorPiece))
						{
							surface = value.Stand - val;
							if (((Vector3)(ref surface)).sqrMagnitude < 0.01f)
							{
								return;
							}
						}
						Watches.Remove((Character)(object)character);
					}
					if (!(val.y - ZoneSystem.instance.GetGroundHeight(val) < 2f))
					{
						Piece val2 = Surface(val, Floor, out surface);
						if (Object.op_Implicit((Object)(object)val2))
						{
							Watches.Add((Character)(object)character, new Watch
							{
								Guard = __instance,
								Stand = val,
								FloorPiece = val2
							});
						}
					}
				}
			}

			[HarmonyPatch(typeof(Character), "SetMoveDir")]
			private static class StayOnGallery
			{
				private static void Prefix(Character __instance, ref Vector3 __0)
				{
					//IL_0076: Unknown result type (might be due to invalid IL or missing references)
					//IL_007c: Invalid comparison between Unknown and I4
					//IL_0091: Unknown result type (might be due to invalid IL or missing references)
					//IL_0097: Unknown result type (might be due to invalid IL or missing references)
					//IL_009c: Unknown result type (might be due to invalid IL or missing references)
					//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
					//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
					//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
					//IL_00d1: 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_00e8: Unknown result type (might be due to invalid IL or missing references)
					if (((Vector3)(ref __0)).sqrMagnitude < 0.001f || !Watches.TryGetValue(__instance, out var value))
					{
						return;
					}
					VikingNpc guard = value.Guard;
					if (!Object.op_Implicit((Object)(object)value.FloorPiece) || !Object.op_Implicit((Object)(object)guard) || !Object.op_Implicit((Object)(object)guard.NetView) || !guard.NetView.IsValid() || !guard.NetView.IsOwner() || !OnGuardDuty(guard) || guard.IsPassive() || (int)guard.GetMode() != 3)
					{
						Watches.Remove(__instance);
						return;
					}
					Vector3 val = ((Component)__instance).transform.position - value.Stand;
					if (!(Mathf.Abs(val.y) > 0.45f))
					{
						val.y = 0f;
						if (((Vector3)(ref val)).sqrMagnitude > 0.42249995f && Vector3.Dot(val, __0) > 0f)
						{
							__0 = Vector3.zero;
						}
					}
				}
			}

			private static readonly ConditionalWeakTable<VikingNpc, Ascent> Routes = new ConditionalWeakTable<VikingNpc, Ascent>();

			private static readonly Func<VikingNpc, List<Vector3>> GuardPoints = AccessTools.MethodDelegate<Func<VikingNpc, List<Vector3>>>(AccessTools.Method(typeof(VikingNpc), "AssignedGuardPoints", (Type[])null, (Type[])null), (object)null, true);

			private static readonly Func<VikingNpc, Vector3, Vector3, float, float, object, float, bool> Approach = AccessTools.MethodDelegate<Func<VikingNpc, Vector3, Vector3, float, float, object, float, bool>>(AccessTools.Method(typeof(VikingNpc), "Approach", (Type[])null, (Type[])null), (object)null, true);

			private static readonly int Assignment = StringExtensionMethods.GetStableHashCode("vnpc_guard_assign");

			private static readonly int Floor = StringExtensionMethods.GetStableHashCode("wood_floor");

			private static readonly int Stair = StringExtensionMethods.GetStableHashCode("wood_stair");

			private static readonly int Pieces = LayerMask.GetMask(new string[1] { "piece" });

			private static readonly ConditionalWeakTable<Character, Watch> Watches = new ConditionalWeakTable<Character, Watch>();

			private static bool Prefix(VikingNpc __instance, object __0, Vector3 point, float dt, ref bool __result)
			{
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Invalid comparison between Unknown and I4
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				//IL_0039: Invalid comparison between Unknown and I4
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0090: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bf: 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)
				//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00da: 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_0100: Unknown result type (might be due to invalid IL or missing references)
				//IL_0101: 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_0132: Unknown result type (might be due to invalid IL or missing references)
				//IL_0161: Unknown result type (might be due to invalid IL or missing references)
				//IL_016c: 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_0225: Unknown result type (might be due to invalid IL or missing references)
				//IL_0227: Unknown result type (might be due to invalid IL or missing references)
				//IL_023c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0242: Unknown result type (might be due to invalid IL or missing references)
				//IL_0183: Unknown result type (might be due to invalid IL or missing references)
				//IL_018c: Unknown result type (might be due to invalid IL or missing references)
				if (!Object.op_Implicit((Object)(object)__instance.NetView) || !__instance.NetView.IsValid() || !__instance.NetView.IsOwner() || (int)__instance.GetMode() != 3 || (int)__instance.GetJob() != 7 || !__instance.IsHired() || __instance.NetView.GetZDO().GetInt(Assignment, 0) >= 0 || !(bool)campaignWorld.GetValue(null, null))
				{
					return true;
				}
				List<Vector3> list = GuardPoints(__instance);
				if (list != null && list.Count == 1)
				{
					Vector3 val = list[0] - point;
					if (!(((Vector3)(ref val)).sqrMagnitude > 0.01f))
					{
						Ascent orCreateValue = Routes.GetOrCreateValue(__instance);
						Vector3 position = ((Component)__instance).transform.position;
						int num;
						if (!(Time.time - orCreateValue.LastUse > 4f))
						{
							val = orCreateValue.Post - point;
							num = ((((Vector3)(ref val)).sqrMagnitude > 0.01f) ? 1 : 0);
						}
						else
						{
							num = 1;
						}
						orCreateValue.LastUse = Time.time;
						if (num != 0)
						{
							orCreateValue.Post = point;
							orCreateValue.Waypoints.Clear();
							orCreateValue.RetryAt = 0f;
						}
						if (orCreateValue.Waypoints.Count == 0)
						{
							if (point.y - position.y < 0.65f || Time.time < orCreateValue.RetryAt)
							{
								return true;
							}
							orCreateValue.RetryAt = Time.time + 5f;
							orCreateValue.Origin = position;
							if (!FindAscent(point, orCreateValue))
							{
								return true;
							}
							orCreateValue.Next = 0;
							for (int i = 1; i < orCreateValue.Waypoints.Count - 1; i++)
							{
								if (Vector3.Distance(position, orCreateValue.Waypoints[i]) < 0.85f)
								{
									orCreateValue.Next = i;
								}
							}
						}
						foreach (Piece support in orCreateValue.Supports)
						{
							if (!Object.op_Implicit((Object)(object)support))
							{
								orCreateValue.Waypoints.Clear();
								return true;
							}
						}
						orCreateValue.WalkTask = __0;
						Vector3 val2 = orCreateValue.Waypoints[orCreateValue.Next];
						if (Approach(__instance, val2, val2, 0.54f, dt, __0, 0.72f) && Mathf.Abs(position.y - val2.y) < 0.85f)
						{
							orCreateValue.Next++;
						}
						__result = orCreateValue.Next == orCreateValue.Waypoints.Count;
						if (__result)
						{
							orCreateValue.Waypoints.Clear();
						}
						return false;
					}
				}
				return true;
			}

			private static bool FindAscent(Vector3 post, Ascent route)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: 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_0044: Unknown result type (might be due to invalid IL or missing references)
				//IL_006a: Unknown result type (might be due to invalid IL or missing references)
				//IL_030b: 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_0143: Unknown result type (might be due to invalid IL or missing references)
				//IL_0148: Unknown result type (might be due to invalid IL or missing references)
				//IL_014c: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b4: 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)
				//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
				//IL_015f: 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_016b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0170: Unknown result type (might be due to invalid IL or missing references)
				//IL_0175: Unknown result type (might be due to invalid IL or missing references)
				//IL_0179: 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_0185: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_0196: Unknown result type (might be due to invalid IL or missing references)
				//IL_0198: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ac: 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_027f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0284: Unknown result type (might be due to invalid IL or missing references)
				//IL_0288: Unknown result type (might be due to invalid IL or missing references)
				//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
				//IL_01da: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0298: Unknown result type (might be due to invalid IL or missing references)
				//IL_029d: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a9: 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)
				//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
				//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_02be: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d7: 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_021a: Unknown result type (might be due to invalid IL or missing references)
				//IL_021c: Unknown result type (might be due to invalid IL or missing references)
				//IL_025a: Unknown result type (might be due to invalid IL or missing references)
				//IL_025c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0233: Unknown result type (might be due to invalid IL or missing references)
				//IL_0238: Unknown result type (might be due to invalid IL or missing references)
				//IL_0245: Unknown result type (might be due to invalid IL or missing references)
				//IL_024a: Unknown result type (might be due to invalid IL or missing references)
				Vector3 surface;
				Piece val = Surface(post, Floor, out surface);
				if (!Object.op_Implicit((Object)(object)val))
				{
					return false;
				}
				WalkTile item = new WalkTile
				{
					Piece = val,
					Surface = ((Component)val).transform.position + Vector3.up * 0.09f
				};
				Queue<WalkTile> queue = new Queue<WalkTile>();
				HashSet<Piece> seen = new HashSet<Piece> { val };
				queue.Enqueue(item);
				WalkTile walkTile = null;
				Vector3 val2 = default(Vector3);
				while (queue.Count > 0)
				{
					WalkTile walkTile2 = queue.Dequeue();
					if (!walkTile2.IsStair && route.Origin.HasValue)
					{
						Vector3 value = route.Origin.Value;
						Vector3 val3 = ((Component)walkTile2.Piece).transform.InverseTransformPoint(value);
						if (Mathf.Abs(val3.x) <= 1.01f && Mathf.Abs(val3.z) <= 1.01f && value.y >= walkTile2.Surface.y - 0.18f && value.y <= walkTile2.Surface.y + 0.75f)
						{
							return BuildRoute(walkTile2, post, route, null);
						}
					}
					if (walkTile2.IsStair)
					{
						Vector3 forward = ((Component)walkTile2.Piece).transform.forward;
						if (!EdgeOpen(walkTile2, forward, -0.5f))
						{
							continue;
						}
						Vector3 val4 = walkTile2.Surface + forward * 2f;
						if (AddTile(walkTile2, val4 + Vector3.down, forward, stair: true, seen, queue) || AddTile(walkTile2, val4 + Vector3.down * 0.5f, forward, stair: false, seen, queue))
						{
							continue;
						}
						Vector3 val5 = walkTile2.Surface + forward * 1.35f;
						float groundHeight = ZoneSystem.instance.GetGroundHeight(val5);
						if (!(Mathf.Abs(groundHeight - (val5.y - 0.55f)) > 0.55f))
						{
							val5.y = groundHeight;
							if (!route.Origin.HasValue)
							{
								return BuildRoute(walkTile2, post, route, val5);
							}
							if (walkTile == null || Vector3.Distance(route.Origin.Value, val5) < Vector3.Distance(route.Origin.Value, val2))
							{
								walkTile = walkTile2;
								val2 = val5;
							}
						}
						continue;
					}
					foreach (Vector3 item2 in Directions(((Component)walkTile2.Piece).transform))
					{
						if (EdgeOpen(walkTile2, item2, 0f))
						{
							Vector3 val6 = walkTile2.Surface + item2 * 2f;
							AddTile(walkTile2, val6 + Vector3.down * 0.5f, item2, stair: true, seen, queue);
							AddTile(walkTile2, val6, item2, stair: false, seen, queue);
						}
					}
				}
				if (walkTile != null)
				{
					return BuildRoute(walkTile, post, route, val2);
				}
				return false;
			}

			private static bool BuildRoute(WalkTile tile, Vector3 post, Ascent route, Vector3? groundFoot)
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				route.Supports.Clear();
				route.Waypoints.Clear();
				if (groundFoot.HasValue)
				{
					route.Waypoints.Add(groundFoot.Value);
				}
				for (WalkTile walkTile = tile; walkTile != null; walkTile = walkTile.Uphill)
				{
					route.Supports.Add(walkTile.Piece);
					route.Waypoints.Add(walkTile.Surface);
				}
				route.Waypoints.Add(post);
				return true;
			}

			private static bool AddTile(WalkTile uphill, Vector3 expected, Vector3 direction, bool stair, HashSet<Piece> seen, Queue<WalkTile> pending)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: 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_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: 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_0047: 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_004d: 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_0064: Unknown result type (might be due to invalid IL or missing references)
				//IL_006a: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a2: 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)
				//IL_0086: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ec: 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)
				Vector3 surface;
				Piece val = Surface(expected, stair ? Stair : Floor, out surface);
				if (!Object.op_Implicit((Object)(object)val))
				{
					return false;
				}
				Vector3 val2 = ((Component)val).transform.position - expected;
				if (Mathf.Abs(Vector3.Dot(val2, direction)) > 0.16f || Mathf.Abs(Vector3.Dot(val2, Vector3.Cross(Vector3.up, direction))) > 0.52f || Mathf.Abs(surface.y - expected.y) > 0.25f || (stair && Vector3.Dot(((Component)val).transform.forward, direction) < 0.98f))
				{
					return false;
				}
				surface.x = ((Component)val).transform.position.x;
				surface.z = ((Component)val).transform.position.z;
				if (seen.Count < 40 && seen.Add(val))
				{
					pending.Enqueue(new WalkTile
					{
						Piece = val,
						Surface = surface,
						Uphill = uphill,
						IsStair = stair
					});
				}
				return true;
			}

			private static bool EdgeOpen(WalkTile tile, Vector3 direction, float edgeRise)
			{
				//IL_0001: 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_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				return !Physics.Raycast(tile.Surface + direction * 0.62f + Vector3.up * (0.64f + edgeRise), direction, 0.76f, Pieces, (QueryTriggerInteraction)1);
			}

			private static IEnumerable<Vector3> Directions(Transform piece)
			{
				yield return piece.forward;
				yield return -piece.forward;
				yield return piece.right;
				yield return -piece.right;
			}

			private static Piece Surface(Vector3 expected, int prefab, out Vector3 surface)
			{
				//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_0008: 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_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0079: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Unknown result type (might be due to invalid IL or missing references)
				surface = default(Vector3);
				RaycastHit val = default(RaycastHit);
				if (!Physics.Raycast(expected + Vector3.up * 0.65f, Vector3.down, ref val, 1.3f, Pieces, (QueryTriggerInteraction)1))
				{
					return null;
				}
				Piece componentInParent = ((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<Piece>();
				ZNetView val2 = (Object.op_Implicit((Object)(object)componentInParent) ? ((Component)componentInParent).GetComponent<ZNetView>() : null);
				if (!Object.op_Implicit((Object)(object)val2) || !val2.IsValid() || val2.GetZDO().GetPrefab() != prefab)
				{
					return null;
				}
				surface = ((RaycastHit)(ref val)).point;
				return componentInParent;
			}
		}

		private sealed class ShelterCheck
		{
			internal float NextCheck;

			internal bool Alarm;

			internal bool BehindCover;
		}

		[HarmonyPatch(typeof(VikingNpc), "IsBedTime")]
		private static class RaidBedTime
		{
			private static void Postfix(VikingNpc __instance, ref bool __result)
			{
				if (!__result)
				{
					__result = NeedsRaidShelter(__instance, requireCover: false);
				}
			}
		}

		[HarmonyPatch(typeof(VikingNpc), "SleepThroughDanger")]
		private static class ShelteredDuringRaid
		{
			private static void Postfix(VikingNpc __instance, ref bool __result)
			{
				if (!__result)
				{
					__result = NeedsRaidShelter(__instance, requireCover: true);
				}
			}
		}

		private static class MedicBanner
		{
			[HarmonyPatch(typeof(GuardMarker), "GetHoverText")]
			private static class Hover
			{
				private static void Postfix(GuardMarker __instance, ref string __result)
				{
					Vector3 point;
					bool stationed;
					VikingNpc val = Medic(__instance, Player.m_localPlayer, out point, out stationed);
					if (Object.op_Implicit((Object)(object)val))
					{
						if (stationed)
						{
							__result = Localization.instance.Localize("<color=#ffd070>" + __instance.GetHoverName() + "</color>") + "\nField medic: " + val.GetDisplayName();
						}
						string text = (stationed ? ("Return " + val.GetDisplayName() + " to settlement duties") : ("Post " + val.GetDisplayName() + " here as field medic"));
						__result = __result + Localization.instance.Localize("\n[<color=yellow><b>$KEY_Use</b></color>] ") + text;
					}
				}
			}

			[HarmonyPatch(typeof(GuardMarker), "Interact")]
			private static class Use
			{
				private static bool Prefix(GuardMarker __instance, Humanoid user, bool hold, bool alt, ref bool __result)
				{
					//IL_003e: Unknown result type (might be due to invalid IL or missing references)
					//IL_005a: Unknown result type (might be due to invalid IL or missing references)
					//IL_005b: Unknown result type (might be due to invalid IL or missing references)
					if (!(hold || alt))
					{
						Player val = (Player)(object)((user is Player) ? user : null);
						if (val != null && !((Object)(object)val != (Object)(object)Player.m_localPlayer))
						{
							Vector3 point;
							bool stationed;
							VikingNpc val2 = Medic(__instance, val, out point, out stationed);
							if (!Object.op_Implicit((Object)(object)val2))
							{
								return true;
							}
							__result = true;
							if (PrivateArea.CheckAccess(((Component)__instance).transform.position, 0f, true, false))
							{
								val2.IssueOrder(val, (VikingOrder)(stationed ? 6 : 3), point, ZDOID.None, false);
							}
							return false;
						}
					}
					return true;
				}
			}

			private static readonly int Banner = StringExtensionMethods.GetStableHashCode("vnpc_guard_post_plain");

			private static readonly Func<GuardMarker, Vector3> StandPoint = AccessTools.MethodDelegate<Func<GuardMarker, Vector3>>(AccessTools.PropertyGetter(typeof(GuardMarker), "StandPoint"), (object)null, true);

			private static readonly Func<Vector3, string> GuardAtPost = AccessTools.MethodDelegate<Func<Vector3, string>>(AccessTools.Method(typeof(VikingNpc), "GuardAtPost", (Type[])null, (Type[])null), (object)null, true);

			private static VikingNpc Medic(GuardMarker marker, Player owner, out Vector3 point, out bool stationed)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
				//IL_0101: Unknown result type (might be due to invalid IL or missing references)
				//IL_0107: Invalid comparison between Unknown and I4
				//IL_0152: Unknown result type (might be due to invalid IL or missing references)
				//IL_0158: Invalid comparison between Unknown and I4
				//IL_011f: 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_012a: Unknown result type (might be due to invalid IL or missing references)
				//IL_012f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0134: Unknown result type (might be due to invalid IL or missing references)
				//IL_016e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0174: Invalid comparison between Unknown and I4
				//IL_017d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0183: Unknown result type (might be due to invalid IL or missing references)
				point = default(Vector3);
				stationed = false;
				ZNetView val = default(ZNetView);
				if (!Object.op_Implicit((Object)(object)owner) || ((Character)owner).IsDead() || !((Component)marker).TryGetComponent<ZNetView>(ref val) || !val.IsValid() || val.GetZDO().GetPrefab() != Banner || !(bool)campaignWorld.GetValue(null, null))
				{
					return null;
				}
				point = StandPoint(marker);
				VikingNpc val2 = null;
				float num = 50f;
				foreach (VikingNpc item in VikingNpc.All)
				{
					if (!Object.op_Implicit((Object)(object)item) || !Object.op_Implicit((Object)(object)item.NetView) || !item.NetView.IsValid() || !item.IsHired() || !item.IsOwnedBy(owner) || !item.HasJob((VikingJob)13) || item.IsDowned() || item.IsHostile())
					{
						continue;
					}
					ZDO zDO = item.NetView.GetZDO();
					if ((int)item.GetMode() == 1 && zDO.GetBool(ZDOVars.s_patrol, false))
					{
						Vector3 val3 = zDO.GetVec3(ZDOVars.s_patrolPoint, Vector3.positiveInfinity) - point;
						if (((Vector3)(ref val3)).sqrMagnitude < 0.25f)
						{
							stationed = true;
							return item;
						}
					}
					if ((int)item.GetMode() == 3 && !item.IsSleeping() && !item.IsAssaulting() && (int)item.GetCombatRole() == 4)
					{
						float num2 = Vector3.Distance(((Component)item).transform.position, point);
						if (num2 < num)
						{
							val2 = item;
							num = num2;
						}
					}
				}
				if (!Object.op_Implicit((Object)(object)val2) || GuardAtPost(((Component)marker).transform.position) != null)
				{
					return null;
				}
				return val2;
			}
		}

		[HarmonyPatch(typeof(BaseAI), "FindEnemy")]
		private static class PostedGuardSenses
		{
			private static void Postfix(BaseAI __instance, ref Character __result)
			{
				VikingNpc guard = default(VikingNpc);
				if (Object.op_Implicit((Object)(object)__result) && ((Component)__instance).TryGetComponent<VikingNpc>(ref guard) && OutsideRaidPost(guard, __result))
				{
					__result = null;
				}
			}
		}

		[HarmonyPatch(typeof(VikingNpc), "AimAiAt")]
		private static class PostedGuardAlarm
		{
			private static bool Prefix(VikingNpc __instance, Character target)
			{
				return !OutsideRaidPost(__instance, target);
			}
		}

		[HarmonyPatch(typeof(VikingNpc), "NearestRaider")]
		private static class PostedRaidSearch
		{
			private static void Postfix(VikingNpc __instance, RandomEvent raid, bool ___m_assault, ref Character __result)
			{
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0090: Unknown result type (might be due to invalid IL or missing references)
				//IL_0095: Unknown result type (might be due to invalid IL or missing references)
				//IL_009d: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b3: 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)
				if (___m_assault || !Object.op_Implicit((Object)(object)__result) || !HasRaidPost(__instance))
				{
					return;
				}
				float num = GuardRadius();
				if (DistanceToLine(__instance, ((Component)__result).transform.position) <= num)
				{
					return;
				}
				__result = null;
				float num2 = 80f;
				foreach (Character allCharacter in Character.GetAllCharacters())
				{
					if (Object.op_Implicit((Object)(object)allCharacter) && !allCharacter.IsDead() && !allCharacter.IsPlayer() && !allCharacter.IsTamed() && BaseAI.IsEnemy((Character)(object)__instance.Character, allCharacter))
					{
						Vector3 position = ((Component)allCharacter).transform.position;
						float num3 = Vector3.Distance(((Component)__instance).transform.position, position);
						if (!(num3 >= num2) && !(Utils.DistanceXZ(position, raid.m_pos) > raid.m_eventRange + 10f) && !(DistanceToLine(__instance, position) > num))
						{
							__result = allCharacter;
							num2 = num3;
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(VikingNpc), "UpdateRaid")]
		private static class PostedRaidPursuit
		{
			private static void Postfix(VikingNpc __instance, MonsterAI ___m_ai, bool ___m_assault)
			{
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				if (!___m_assault && __instance.IsDefending() && Object.op_Implicit((Object)(object)___m_ai))
				{
					Character targetCreature = ((BaseAI)___m_ai).GetTargetCreature();
					if (Object.op_Implicit((Object)(object)targetCreature) && HasRaidPost(__instance) && DistanceToLine(__instance, ((Component)targetCreature).transform.position) > GuardRadius() + 3f)
					{
						DropGuardTarget(__instance);
					}
				}
			}
		}

		private sealed class Response
		{
			internal Character Attacker;

			internal Vector3 Origin;

			internal float Until;
		}

		[HarmonyPatch(typeof(VikingNpc), "FindWorkerThreat")]
		private static class HostileVikingAlarm
		{
			private static void Postfix(VikingNpc __instance, ref Character __result)
			{
				//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b3: 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)
				if (Object.op_Implicit((Object)(object)__result) || !Eligible(__instance) || !__instance.IsHired() || !(bool)campaignWorld.GetValue(null, null))
				{
					return;
				}
				long ownerId = __instance.GetOwnerId();
				if (ownerId == 0L)
				{
					return;
				}
				float num = 196f;
				foreach (VikingNpc item in VikingNpc.All)
				{
					if (!Object.op_Implicit((Object)(object)item) || !Object.op_Implicit((Object)(object)item.NetView) || !item.NetView.IsValid() || item.NetView.GetZDO().GetLong("vnpc_hostile_to", 0L) != ownerId)
					{
						continue;
					}
					Vector3 val = ((Component)item).transform.position - ((Component)__instance).transform.position;
					float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
					if (!(sqrMagnitude >= num) && Object.op_Implicit((Object)(object)item.Character) && !item.IsDowned() && !((Character)item.Character).IsDead() && !item.IsHired())
					{
						MonsterAI component = ((Component)item).GetComponent<MonsterAI>();
						if (!((Object)(object)((component != null) ? ((BaseAI)component).GetTargetCreature() : null) != (Object)(object)__instance.Character) && VikingNpc.AreEnemies((Character)(object)item.Character, (Character)(object)__instance.Character))
						{
							num = sqrMagnitude;
							__result = (Character)(object)item.Character;
						}
					}
				}
				if (Object.op_Implicit((Object)(object)__result) && num > 49f && HasMeleeCover(__instance, __result, ownerId))
				{
					if (Time.time >= NextHelpCall.Invoke(__instance))
					{
						NextHelpCall.Invoke(__instance) = Time.time + 10f;
						CallGuards(__instance, __result);
					}
					__result = null;
				}
			}

			private static bool HasMeleeCover(VikingNpc worker, Character attacker, long employer)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Invalid comparison between Unknown and I4
				//IL_003f: 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_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0054: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
				//IL_0100: Unknown result type (might be due to invalid IL or missing references)
				//IL_0105: Unknown result type (might be due to invalid IL or missing references)
				//IL_0115: Unknown result type (might be due to invalid IL or missing references)
				//IL_0117: Unknown result type (might be due to invalid IL or missing references)
				Character obj = ((attacker is Humanoid) ? attacker : null);
				Attack val = ((obj != null) ? ((Humanoid)obj).GetCurrentWeapon() : null)?.m_shared?.m_attack;
				if (val == null || (int)val.m_attackType == 2)
				{
					return false;
				}
				Vector3 val2 = ((Component)worker).transform.position - ((Component)attacker).transform.position;
				foreach (VikingNpc item in VikingNpc.All)
				{
					if (!Object.op_Implicit((Object)(object)item) || !Object.op_Implicit((Object)(object)item.NetView) || !item.NetView.IsValid() || item.GetOwnerId() != employer || !OnGuardDuty(item) || item.IsPassive() || item.NetView.GetZDO().GetLong("vnpc_passive_until", 0L) > ZNet.instance.GetTime().Ticks)
					{
						continue;
					}
					Vector3 val3 = ((Component)item).transform.position - ((Component)attacker).transform.position;
					if (((Vector3)(ref val3)).sqrMagnitude > 25f || Vector3.Dot(val3, val2) < 0f)
					{
						continue;
					}
					MonsterAI component = ((Component)item).GetComponent<MonsterAI>();
					if (Object.op_Implicit((Object)(object)component))
					{
						Character targetCreature = ((BaseAI)component).GetTargetCreature();
						if (!Object.op_Implicit((Object)(object)targetCreature) || (Object)(object)targetCreature == (Object)(object)attacker)
						{
							return true;
						}
					}
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(VikingNpc), "OnDamagedWhileSleeping")]
		private static class OnHit
		{
			private static void Postfix(VikingNpc __instance, float damage, Character attacker)
			{
				//IL_0044: 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_0077: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				if (!(damage <= 0f) && Eligible(__instance) && (bool)campaignWorld.GetValue(null, null) && HostileMonster(__instance, attacker) && !(((Character)__instance.Character).GetHealthPercentage() <= 0.25f) && !(Vector3.Distance(((Component)__instance).transform.position, ((Component)attacker).transform.position) > 10f))
				{
					Response response = Active(__instance);
					if (response == null)
					{
						response = new Response
						{
							Origin = ((Component)__instance).transform.position
						};
						Responses.Add(__instance, response);
						((BaseUnityPlugin)instance).Logger.LogInfo((object)("Worker " + ((Character)__instance.Character).GetHoverName() + " defending against " + ((Object)attacker).name + "."));
					}
					response.Attacker = attacker;
					response.Until = Time.time + 12f;
					FleeUntil.Invoke(__instance) = Time.time;
					FaceThreat(__instance, response);
				}
			}
		}

		[HarmonyPatch(typeof(VikingNpc), "IsTimidWorker")]
		private static class WorkerAlarm
		{
			private static void Postfix(VikingNpc __instance, ref bool __result)
			{
				if (__result && Active(__instance) != null)
				{
					__result = false;
				}
			}
		}

		[HarmonyPatch(typeof(VikingNpc), "UpdateOrders")]
		private static class Orders
		{
			private static void Prefix(VikingNpc __instance, out Response __state)
			{
				__state = Active(__instance);
				if (__state != null)
				{
					((Character)__instance.Character).m_aiCannotTargetOthers = true;
				}
			}

			private static void Postfix(VikingNpc __instance, Response __state)
			{
				if (__state != null)
				{
					FaceThreat(__instance, __state);
				}
			}
		}

		private static Func<VikingNpc, ZDO> claimedBunk;

		private static readonly ConditionalWeakTable<VikingNpc, ShelterCheck> ShelterChecks = new ConditionalWeakTable<VikingNpc, ShelterCheck>();

		private static readonly int HildirRaidShaman = StringExtensionMethods.GetStableHashCode("GoblinShaman_Hildir_nochest");

		private static readonly int PieceMask = LayerMask.GetMask(new string[1] { "piece" });

		private static readonly int CoverMask = LayerMask.GetMask(new string[4] { "piece", "terrain", "static_solid", "Default" });

		private static readonly Func<VikingNpc, bool> GuardLeashed = AccessTools.MethodDelegate<Func<VikingNpc, bool>>(AccessTools.Method(typeof(VikingNpc), "GuardLeashed", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Func<VikingNpc, Vector3, float> DistanceToLine = AccessTools.MethodDelegate<Func<VikingNpc, Vector3, float>>(AccessTools.Method(typeof(VikingNpc), "DistanceToGuardLine", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Func<float> GuardRadius = AccessTools.MethodDelegate<Func<float>>(AccessTools.PropertyGetter(typeof(VikingNpc), "GuardLeash"), (object)null, true);

		private static readonly Action<VikingNpc> DropGuardTarget = AccessTools.MethodDelegate<Action<VikingNpc>>(AccessTools.Method(typeof(VikingNpc), "DropTarget", (Type[])null, (Type[])null), (object)null, true);

		private const float Leash = 10f;

		private const float Duration = 12f;

		private static readonly ConditionalWeakTable<VikingNpc, Response> Responses = new ConditionalWeakTable<VikingNpc, Response>();

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

		private static readonly FieldRef<VikingNpc, float> FleeUntil = AccessTools.FieldRefAccess<VikingNpc, float>("m_fleeUntil");

		private static readonly FieldRef<VikingNpc, float> NextHelpCall = AccessTools.FieldRefAccess<VikingNpc, float>("m_helpCallAt");

		private static readonly Action<VikingNpc, Character> CallGuards = AccessTools.MethodDelegate<Action<VikingNpc, Character>>(AccessTools.Method(typeof(VikingNpc), "CallGuards", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Func<VikingNpc, bool> OnGuardDuty = AccessTools.MethodDelegate<Func<VikingNpc, bool>>(AccessTools.Method(typeof(VikingNpc), "IsOnGuardDuty", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Action<BaseAI, bool> Alert = AccessTools.MethodDelegate<Action<BaseAI, bool>>(AccessTools.Method(typeof(BaseAI), "SetAlerted", new Type[1] { typeof(bool) }, (Type[])null), (object)null, true);

		private static PropertyInfo campaignWorld;

		private static WorkerDefense instance;

		private Harmony patches;

		private static bool NeedsRaidShelter(VikingNpc worker, bool requireCover)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Invalid comparison between Unknown and I4
			//IL_00e1: 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_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: 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_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_0292: 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_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			if (claimedBunk == null || !Object.op_Implicit((Object)(object)worker.NetView) || !worker.NetView.IsValid() || !worker.NetView.IsOwner() || (int)worker.GetMode() != 3 || !worker.IsHired() || !worker.IsWorker() || worker.IsDowned() || worker.IsTrader() || worker.IsAboard() || worker.IsPortalPending() || worker.HasJob((VikingJob)7) || worker.HasJob((VikingJob)10) || worker.HasJob((VikingJob)13) || !(bool)campaignWorld.GetValue(null, null) || !Object.op_Implicit((Object)(object)RandEventSystem.instance))
			{
				return false;
			}
			ShelterCheck orCreateValue = ShelterChecks.GetOrCreateValue(worker);
			if (Time.time >= orCreateValue.NextCheck)
			{
				orCreateValue.NextCheck = Time.time + 1f;
				ZDO zDO = ZDOMan.instance.GetZDO(worker.GetSettlementId());
				ZDO val = ((zDO != null && zDO.GetInt("vnpc_raid_policy", 0) != 0) ? claimedBunk(worker) : null);
				orCreateValue.Alarm = false;
				orCreateValue.BehindCover = false;
				if (val != null)
				{
					Vector3 position = val.GetPosition();
					RandomEvent currentRandomEvent = RandEventSystem.instance.GetCurrentRandomEvent();
					bool flag = currentRandomEvent != null && Utils.DistanceXZ(currentRandomEvent.m_pos, position) < currentRandomEvent.m_eventRange + 20f;
					Vector3 val2 = ((Component)worker).transform.position - position;
					bool flag2 = ((Vector3)(ref val2)).sqrMagnitude < 4f;
					bool flag3 = false;
					foreach (Character allCharacter in Character.GetAllCharacters())
					{
						if (!Object.op_Implicit((Object)(object)allCharacter) || allCharacter.IsDead() || allCharacter.IsTamed() || allCharacter.IsPlayer())
						{
							continue;
						}
						val2 = ((Component)allCharacter).transform.position - position;
						if (((Vector3)(ref val2)).sqrMagnitude > 1600f)
						{
							continue;
						}
						BaseAI baseAI = allCharacter.GetBaseAI();
						MonsterAI val3 = (MonsterAI)(object)((baseAI is MonsterAI) ? baseAI : null);
						if (val3 == null || !BaseAI.IsEnemy((Character)(object)worker.Character, allCharacter))
						{
							continue;
						}
						if (!flag)
						{
							if (!val3.IsEventCreature())
							{
								ZNetView component = ((Component)val3).GetComponent<ZNetView>();
								int? obj;
								if (component == null)
								{
									obj = null;
								}
								else
								{
									ZDO zDO2 = component.GetZDO();
									obj = ((zDO2 != null) ? new int?(zDO2.GetPrefab()) : ((int?)null));
								}
								if (obj != HildirRaidShaman)
								{
									goto IL_0278;
								}
							}
							flag = true;
						}
						goto IL_0278;
						IL_0278:
						if (flag2)
						{
							Vector3 val4 = position + Vector3.up;
							Vector3 centerPoint = allCharacter.GetCenterPoint();
							val2 = centerPoint - val4;
							if (((Vector3)(ref val2)).sqrMagnitude <= 144f && !Physics.Linecast(val4, centerPoint, CoverMask, (QueryTriggerInteraction)1))
							{
								flag3 = true;
							}
						}
					}
					RaycastHit val5 = default(RaycastHit);
					if (flag && Physics.Raycast(position + Vector3.up, Vector3.up, ref val5, 8f, PieceMask, (QueryTriggerInteraction)1))
					{
						ZNetView componentInParent = ((Component)((RaycastHit)(ref val5)).collider).GetComponentInParent<ZNetView>();
						orCreateValue.Alarm = Object.op_Implicit((Object)(object)componentInParent) && componentInParent.IsValid() && componentInParent.GetZDO().GetString("rb_b04_construction", "") != "";
						orCreateValue.BehindCover = orCreateValue.Alarm && flag2 && !flag3;
					}
				}
			}
			if (!requireCover)
			{
				return orCreateValue.Alarm;
			}
			return orCreateValue.BehindCover;
		}

		private static bool HasRaidPost(VikingNpc guard)
		{
			if (guard.IsDefending() && Object.op_Implicit((Object)(object)guard.NetView) && guard.NetView.IsValid() && guard.NetView.IsOwner() && (bool)campaignWorld.GetValue(null, null))
			{
				return GuardLeashed(guard);
			}
			return false;
		}

		private static bool OutsideRaidPost(VikingNpc guard, Character target)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)target) && !guard.IsAssaulting() && HasRaidPost(guard))
			{
				return DistanceToLine(guard, ((Component)target).transform.position) > GuardRadius();
			}
			return false;
		}

		private void Awake()
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			instance = this;
			Assembly assembly = ((object)Chainloader.PluginInfos["cwew.returningbough"].Instance).GetType().Assembly;
			campaignWorld = AccessTools.Property(assembly.GetType("ReturningBough.Plugin"), "TestWorld");
			MethodInfo methodInfo = assembly.GetType("ReturningBough.BunkhouseBedRoute")?.GetMethod("ClaimedBunk", BindingFlags.Static | BindingFlags.NonPublic);
			if (methodInfo != null)
			{
				claimedBunk = AccessTools.MethodDelegate<Func<VikingNpc, ZDO>>(methodInfo, (object)null, true);
			}
			patches = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
			patches.PatchAll(typeof(WorkerDefense).Assembly);
		}

		private void OnDestroy()
		{
			Harmony obj = patches;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			instance = null;
		}

		private static bool Eligible(VikingNpc worker)
		{
			if (!Object.op_Implicit((Object)(object)worker) || !Object.op_Implicit((Object)(object)worker.NetView) || !worker.NetView.IsValid() || !worker.NetView.IsOwner() || !Object.op_Implicit((Object)(object)ZNet.instance) || worker.IsDowned() || worker.IsTrader() || worker.IsPassive())
			{
				return false;
			}
			ZDO zDO = worker.NetView.GetZDO();
			if (zDO.GetLong("vnpc_passive_until", 0L) > ZNet.instance.GetTime().Ticks)
			{
				return false;
			}
			if (!worker.IsHired())
			{
				return zDO.GetString("rb_specialist_guild", "") == "greenward";
			}
			if (worker.IsWorker() && !worker.HasJob((VikingJob)7))
			{
				return !worker.HasJob((VikingJob)10);
			}
			return false;
		}

		private static bool HostileMonster(VikingNpc worker, Character attacker)
		{
			if (Object.op_Implicit((Object)(object)attacker) && !attacker.IsDead() && !attacker.IsPlayer() && !attacker.IsTamed() && !Object.op_Implicit((Object)(object)((Component)attacker).GetComponent<VikingNpc>()) && Object.op_Implicit((Object)(object)((Component)attacker).GetComponent<MonsterAI>()))
			{
				return BaseAI.IsEnemy((Character)(object)worker.Character, attacker);
			}
			return false;
		}

		private static Response Active(VikingNpc worker)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			if (!Responses.TryGetValue(worker, out var value))
			{
				return null;
			}
			if (Time.time <= value.Until && Eligible(worker) && ((Character)worker.Character).GetHealthPercentage() > 0.25f && HostileMonster(worker, value.Attacker) && Vector3.Distance(((Component)worker).transform.position, value.Origin) <= 10f && Vector3.Distance(((Component)value.Attacker).transform.position, value.Origin) <= 10f)
			{
				return value;
			}
			Responses.Remove(worker);
			if (Object.op_Implicit((Object)(object)worker.NetView) && worker.NetView.IsValid() && worker.NetView.IsOwner())
			{
				MonsterAI component = ((Component)worker).GetComponent<MonsterAI>();
				if (Object.op_Implicit((Object)(object)component) && (Object)(object)Target.Invoke(component) == (Object)(object)value.Attacker)
				{
					Target.Invoke(component) = null;
				}
			}
			return null;
		}

		private static void FaceThreat(VikingNpc worker, Response response)
		{
			MonsterAI component = ((Component)worker).GetComponent<MonsterAI>();
			if (Object.op_Implicit((Object)(object)component))
			{
				((Character)worker.Character).m_aiCannotTargetOthers = false;
				Target.Invoke(component) = response.Attacker;
				Alert((BaseAI)(object)component, arg2: true);
			}
		}
	}
}

plugins/ReturningBough.Wardrobes.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Linq;
using UnityEngine;
using ValheimNpc;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("ReturningBough.Wardrobes")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a2f35a034722da7812b950e985e6acc0439cb25c")]
[assembly: AssemblyProduct("ReturningBough.Wardrobes")]
[assembly: AssemblyTitle("ReturningBough.Wardrobes")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ReturningBough.Wardrobes
{
	internal static class FaceMarkings
	{
		private struct Triangle
		{
			public int A;

			public int B;

			public int C;

			public int Submesh;
		}

		internal static void Paint(Mesh output, Mesh face, FaceShape shape, int skinCount)
		{
			//IL_0001: 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_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: 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)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: 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)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			Matrix4x4 frame = shape.Frame;
			Vector3[] array = ((IEnumerable<Vector3>)face.vertices).Select((Func<Vector3, Vector3>)((Matrix4x4)(object)frame).MultiplyPoint3x4).ToArray();
			Vector3[] normals = face.normals;
			Vector2[] uv = face.uv;
			BoneWeight[] boneWeights = face.boneWeights;
			List<Triangle> list = new List<Triangle>();
			List<int>[] array2 = new List<int>[skinCount];
			for (int i = 0; i < skinCount; i++)
			{
				array2[i] = new List<int>();
				int[] triangles = face.GetTriangles(i);
				for (int j = 0; j < triangles.Length; j += 3)
				{
					int num = triangles[j];
					int num2 = triangles[j + 1];
					int num3 = triangles[j + 2];
					if (ForeheadOrCheek(array[num]) && ForeheadOrCheek(array[num2]) && ForeheadOrCheek(array[num3]))
					{
						list.Add(new Triangle
						{
							A = num,
							B = num2,
							C = num3,
							Submesh = i
						});
					}
				}
			}
			List<Vector3> list2 = new List<Vector3>();
			List<Vector3> list3 = new List<Vector3>();
			List<Vector2> list4 = new List<Vector2>();
			List<BoneWeight> list5 = new List<BoneWeight>();
			Matrix4x4 inverse = ((Matrix4x4)(ref frame)).inverse;
			foreach (JToken item in (IEnumerable<JToken>)shape.Marks)
			{
				int count = list2.Count;
				int num4 = 0;
				foreach (JToken item2 in (IEnumerable<JToken>)item)
				{
					float num5 = (float)item2[(object)0];
					float num6 = (float)item2[(object)1];
					Vector3 barycentric;
					float depth;
					Triangle triangle = Frontmost(list, array, num5, num6, out barycentric, out depth);
					num4 = triangle.Submesh;
					list2.Add(((Matrix4x4)(ref inverse)).MultiplyPoint3x4(new Vector3(num5, num6, depth + 0.00065f)));
					Vector3 val = barycentric.x * normals[triangle.A] + barycentric.y * normals[triangle.B] + barycentric.z * normals[triangle.C];
					list3.Add(((Vector3)(ref val)).normalized);
					list4.Add(barycentric.x * uv[triangle.A] + barycentric.y * uv[triangle.B] + barycentric.z * uv[triangle.C]);
					list5.Add(Blend(boneWeights, triangle, barycentric));
				}
				for (int k = count + 1; k < list2.Count - 1; k++)
				{
					Vector3 val2 = ((Matrix4x4)(ref frame)).MultiplyVector(list2[k] - list2[count]);
					Vector3 val3 = ((Matrix4x4)(ref frame)).MultiplyVector(list2[k + 1] - list2[count]);
					bool flag = Vector3.Cross(val2, val3).z > 0f;
					array2[num4].Add(count);
					array2[num4].Add(flag ? k : (k + 1));
					array2[num4].Add(flag ? (k + 1) : k);
				}
			}
			output.SetVertices(list2);
			output.SetNormals(list3);
			output.SetUVs(0, list4);
			output.boneWeights = list5.ToArray();
			output.bindposes = face.bindposes;
			output.subMeshCount = skinCount;
			for (int l = 0; l < skinCount; l++)
			{
				output.SetTriangles(array2[l], l);
			}
		}

		private static bool ForeheadOrCheek(Vector3 p)
		{
			//IL_0000: 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)
			if (p.y > 1.675f)
			{
				return p.z > 0.048f;
			}
			return false;
		}

		private static Triangle Frontmost(List<Triangle> surface, Vector3[] rest, float x, float y, out Vector3 barycentric, out float depth)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: 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_0068: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: 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_00d2: 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_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			Triangle result = default(Triangle);
			barycentric = Vector3.zero;
			depth = float.NegativeInfinity;
			foreach (Triangle item in surface)
			{
				Vector3 val = rest[item.A];
				Vector3 val2 = rest[item.B];
				Vector3 val3 = rest[item.C];
				float num = (val2.y - val3.y) * (val.x - val3.x) + (val3.x - val2.x) * (val.y - val3.y);
				if (!(Mathf.Abs(num) < 1E-08f))
				{
					float num2 = ((val2.y - val3.y) * (x - val3.x) + (val3.x - val2.x) * (y - val3.y)) / num;
					float num3 = ((val3.y - val.y) * (x - val3.x) + (val.x - val3.x) * (y - val3.y)) / num;
					float num4 = 1f - num2 - num3;
					float num5 = num2 * val.z + num3 * val2.z + num4 * val3.z;
					if (!(Mathf.Min(num2, Mathf.Min(num3, num4)) < -0.0001f) && !(num5 <= depth))
					{
						depth = num5;
						result = item;
						barycentric = new Vector3(num2, num3, num4);
					}
				}
			}
			if (float.IsNegativeInfinity(depth))
			{
				throw new InvalidDataException("Complexion outline outside the fitted face");
			}
			return result;
		}

		private static BoneWeight Blend(BoneWeight[] source, Triangle triangle, Vector3 bary)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<int, float> totals = new Dictionary<int, float>();
			Include(source[triangle.A], bary.x);
			Include(source[triangle.B], bary.y);
			Include(source[triangle.C], bary.z);
			List<KeyValuePair<int, float>> list = totals.OrderByDescending((KeyValuePair<int, float> bone) => bone.Value).Take(4).ToList();
			float num = list.Sum((KeyValuePair<int, float> bone) => bone.Value);
			if (num <= 0f)
			{
				throw new InvalidDataException("Unbound complexion marking");
			}
			while (list.Count < 4)
			{
				list.Add(default(KeyValuePair<int, float>));
			}
			BoneWeight result = default(BoneWeight);
			((BoneWeight)(ref result)).boneIndex0 = list[0].Key;
			((BoneWeight)(ref result)).boneIndex1 = list[1].Key;
			((BoneWeight)(ref result)).boneIndex2 = list[2].Key;
			((BoneWeight)(ref result)).boneIndex3 = list[3].Key;
			((BoneWeight)(ref result)).weight0 = list[0].Value / num;
			((BoneWeight)(ref result)).weight1 = list[1].Value / num;
			((BoneWeight)(ref result)).weight2 = list[2].Value / num;
			((BoneWeight)(ref result)).weight3 = list[3].Value / num;
			return result;
			void Add(int bone, float value)
			{
				if (!(value <= 0f))
				{
					totals.TryGetValue(bone, out var value2);
					totals[bone] = value2 + value;
				}
			}
			void Include(BoneWeight weight, float portion)
			{
				Add(((BoneWeight)(ref weight)).boneIndex0, ((BoneWeight)(ref weight)).weight0 * portion);
				Add(((BoneWeight)(ref weight)).boneIndex1, ((BoneWeight)(ref weight)).weight1 * portion);
				Add(((BoneWeight)(ref weight)).boneIndex2, ((BoneWeight)(ref weight)).weight2 * portion);
				Add(((BoneWeight)(ref weight)).boneIndex3, ((BoneWeight)(ref weight)).weight3 * portion);
			}
		}
	}
	internal sealed class FaceShape
	{
		private sealed class Region
		{
			public Vector3 Centre;

			public Vector3 Radius;

			public Vector3 Displacement;

			public Vector3 Offset(Vector3 point)
			{
				//IL_0000: 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_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
				float num = (Mathf.Abs(point.x) - Centre.x) / Radius.x;
				float num2 = (point.y - Centre.y) / Radius.y;
				float num3 = (point.z - Centre.z) / Radius.z;
				Vector3 displacement = Displacement;
				displacement.x *= Mathf.Clamp(point.x / 0.012f, -1f, 1f);
				return displacement * Mathf.Exp(0f - (num * num + num2 * num2 + num3 * num3));
			}
		}

		private sealed class CoveredBand
		{
			public float Lower;

			public float Upper;

			public float HalfWidth;

			public bool Contains(Vector3 p)
			{
				//IL_0000: 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_001c: Unknown result type (might be due to invalid IL or missing references)
				if (p.y > Lower && p.y < Upper)
				{
					return Mathf.Abs(p.x) < HalfWidth;
				}
				return false;
			}
		}

		private readonly Region[] regions;

		private readonly bool female;

		private readonly CoveredBand[] coveredBody;

		internal readonly Matrix4x4 Frame;

		internal readonly Color Skin;

		internal readonly JToken Marks;

		internal FaceShape(JObject recipe)
		{
			//IL_00cf: 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)
			//IL_00f4: 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_0105: 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_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: 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)
			female = (string)recipe["mesh"] == "bodyfem";
			coveredBody = ((IEnumerable<JToken>)recipe["coveredBody"])?.Select((JToken band) => new CoveredBand
			{
				Lower = (float)band[(object)"lower"],
				Upper = (float)band[(object)"upper"],
				HalfWidth = (float)band[(object)"halfWidth"]
			}).ToArray() ?? Array.Empty<CoveredBand>();
			if (coveredBody.Any((CoveredBand band) => band.Lower < 0.26f || band.Upper > 1.47f || band.Lower >= band.Upper || band.HalfWidth <= 0f || band.HalfWidth > 0.31f))
			{
				throw new InvalidDataException("Invalid dress coverage");
			}
			float[] array = recipe["restFrame"].Values<float>().ToArray();
			if (array.Length != 16)
			{
				throw new InvalidDataException("Invalid fitting frame");
			}
			Matrix4x4 identity = Matrix4x4.identity;
			for (int num = 0; num < array.Length; num++)
			{
				((Matrix4x4)(ref identity))[num / 4, num % 4] = array[num];
			}
			Frame = identity;
			Vector3 val = Vector(recipe["skinTint"]);
			Skin = new Color(val.x, val.y, val.z);
			Marks = recipe["skinAccents"];
			regions = ((IEnumerable<JToken>)recipe["regions"]).Select((JToken region) => new Region
			{
				Centre = Vector(region[(object)"centre"]),
				Radius = Vector(region[(object)"radius"]),
				Displacement = Vector(region[(object)"offsetMM"]) * 0.001f
			}).ToArray();
		}

		private static Vector3 Vector(JToken point)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3((float)point[(object)0], (float)point[(object)1], (float)point[(object)2]);
		}

		private Vector3 Offset(Vector3 point)
		{
			//IL_0000: 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_000d: 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_002a: 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_003c: 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_0042: 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)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			if (point.y <= 1.657f || Mathf.Abs(point.x) > 0.15f)
			{
				return Vector3.zero;
			}
			Vector3 val = Vector3.zero;
			Region[] array = regions;
			foreach (Region region in array)
			{
				val += region.Offset(point);
			}
			return val * Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(1.657f, 1.688f, point.y));
		}

		private Matrix4x4 Gradient(Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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_0012: 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)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//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_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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: 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_0098: Unknown result type (might be due to invalid IL or missing references)
			Matrix4x4 identity = Matrix4x4.identity;
			for (int i = 0; i < 3; i++)
			{
				Vector3 zero = Vector3.zero;
				((Vector3)(ref zero))[i] = 0.0001f;
				Vector3 val = (Offset(point + zero) - Offset(point - zero)) / 0.0002f;
				int num = i;
				((Vector3)(ref val))[num] = ((Vector3)(ref val))[num] + 1f;
				((Matrix4x4)(ref identity)).SetColumn(i, new Vector4(val.x, val.y, val.z, 0f));
			}
			return identity;
		}

		private bool InEye(Vector3 p)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Abs(p.x);
			if (female)
			{
				if (num > 0.0225f && num < 0.05f && p.y > 1.782f && p.y < 1.795f && p.z > 0.122f)
				{
					return p.z < 0.13f;
				}
				return false;
			}
			if (num > 0.025f && num < 0.0505f && p.y > 1.7895f && p.y < 1.798f && p.z > 0.122f)
			{
				return p.z < 0.1325f;
			}
			return false;
		}

		private bool Covered(Vector3 point)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			CoveredBand[] array = coveredBody;
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i].Contains(point))
				{
					return true;
				}
			}
			return false;
		}

		internal void Fit(Mesh mesh, int expectedEyeFaces)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: 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_010e: 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_0117: 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_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0401: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] vertices = mesh.vertices;
			Vector3[] normals = mesh.normals;
			Vector3[] rest = ((IEnumerable<Vector3>)vertices).Select((Func<Vector3, Vector3>)((Matrix4x4)(object)Frame).MultiplyPoint3x4).ToArray();
			Matrix4x4 val = Frame;
			Matrix4x4 inverse = ((Matrix4x4)(ref val)).inverse;
			for (int i = 0; i < vertices.Length; i++)
			{
				Vector3 val2 = Offset(rest[i]);
				if (!(((Vector3)(ref val2)).sqrMagnitude < 1E-14f))
				{
					if (((Vector3)(ref val2)).magnitude > 0.017f)
					{
						throw new InvalidDataException("Face offset exceeds fitted bounds");
					}
					vertices[i] = ((Matrix4x4)(ref inverse)).MultiplyPoint3x4(rest[i] + val2);
					val = ((Matrix4x4)(ref inverse)).transpose;
					Vector3 val3 = ((Matrix4x4)(ref val)).MultiplyVector(normals[i]);
					val = Gradient(rest[i]);
					val = ((Matrix4x4)(ref val)).inverse;
					val = ((Matrix4x4)(ref val)).transpose;
					val3 = ((Matrix4x4)(ref val)).MultiplyVector(val3);
					int num = i;
					val = Frame;
					val = ((Matrix4x4)(ref val)).transpose;
					Vector3 val4 = ((Matrix4x4)(ref val)).MultiplyVector(val3);
					normals[num] = ((Vector3)(ref val4)).normalized;
				}
			}
			List<int> list = new List<int>();
			HashSet<int> hashSet = new HashSet<int>();
			for (int j = 0; j < mesh.subMeshCount; j++)
			{
				int[] triangles = mesh.GetTriangles(j);
				List<int> list2 = new List<int>(triangles.Length);
				for (int k = 0; k < triangles.Length; k += 3)
				{
					int num2 = triangles[k];
					int num3 = triangles[k + 1];
					int num4 = triangles[k + 2];
					if (coveredBody.Length == 0 || !Covered(rest[num2]) || !Covered(rest[num3]) || !Covered(rest[num4]))
					{
						List<int> obj = ((InEye(rest[num2]) && InEye(rest[num3]) && InEye(rest[num4])) ? list : list2);
						obj.Add(num2);
						obj.Add(num3);
						obj.Add(num4);
					}
				}
				hashSet.UnionWith(list2);
				mesh.SetTriangles(list2, j, false);
			}
			if (list.Count != 3 * expectedEyeFaces || list.Any(hashSet.Contains))
			{
				throw new InvalidDataException("Native eye topology does not match the fitted recipe");
			}
			Vector2[] uv = mesh.uv;
			foreach (IGrouping<bool, int> item in from num9 in list.Distinct()
				group num9 by rest[num9].x > 0f)
			{
				if (item.Count() != 4)
				{
					throw new InvalidDataException("Unexpected eye island");
				}
				float num5 = item.Min((int num9) => rest[num9].x);
				float num6 = item.Max((int num9) => rest[num9].x);
				float num7 = item.Min((int num9) => rest[num9].y);
				float num8 = item.Max((int num9) => rest[num9].y);
				foreach (int item2 in item)
				{
					uv[item2] = new Vector2(Mathf.Lerp(0.032f, 0.968f, Mathf.InverseLerp(num5, num6, rest[item2].x)), Mathf.Lerp(0.065f, 0.935f, Mathf.InverseLerp(num7, num8, rest[item2].y)));
				}
			}
			mesh.vertices = vertices;
			mesh.normals = normals;
			mesh.uv = uv;
			int subMeshCount = mesh.subMeshCount;
			mesh.subMeshCount = subMeshCount + 1;
			mesh.SetTriangles(list, subMeshCount, false);
		}
	}
	internal sealed class NativeAppearance : MonoBehaviour
	{
		private static readonly FieldInfo Hair = AccessTools.Field(typeof(VisEquipment), "m_hairItemInstance");

		private static readonly FieldInfo Beard = AccessTools.Field(typeof(VisEquipment), "m_beardItemInstance");

		private static readonly FieldInfo Helmet = AccessTools.Field(typeof(VisEquipment), "m_helmetItemInstance");

		private Renderer workCap;

		private readonly List<Object> resources = new List<Object>();

		private readonly List<GameObject> copies = new List<GameObject>();

		private readonly HashSet<Renderer> hidden = new HashSet<Renderer>();

		private VisEquipment equipment;

		private GameObject previousHair;

		private GameObject previousBeard;

		internal void Fit(string art, JObject recipe, SkinnedMeshRenderer body, VisEquipment nativeEquipment, SkinnedMeshRenderer[] groom, Func<string, Texture2D> albedo)
		{
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Expected O, but got Unknown
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0397: Unknown result type (might be due to invalid IL or missing references)
			//IL_039c: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b2: Expected O, but got Unknown
			if ((int)recipe["schema"] != 1 || (string)recipe["id"] != art || groom.Length == 0)
			{
				throw new InvalidDataException("Incomplete head fitting for " + art);
			}
			string name = (string)recipe["mesh"];
			equipment = nativeEquipment;
			PlayerModel val = equipment?.m_models?.FirstOrDefault((Func<PlayerModel, bool>)((PlayerModel option) => Object.op_Implicit((Object)(object)option.m_mesh) && ((Object)option.m_mesh).name == name));
			Mesh val2 = ((((Object)body.sharedMesh).name == name) ? body.sharedMesh : val?.m_mesh);
			if (!Object.op_Implicit((Object)(object)val2) || val2.vertexCount != (int)recipe["vertices"] || val2.triangles.Length / 3 != (int)recipe["triangles"] || body.bones.Length != 53 || val2.bindposes.Length != body.bones.Length)
			{
				throw new InvalidDataException("Native body does not match " + name);
			}
			FaceShape shape = new FaceShape(recipe);
			Mesh val3 = Own<Mesh>(Object.Instantiate<Mesh>(val2));
			((Object)val3).name = art + " fitted " + name;
			shape.Fit(val3, (int)recipe["eyeFaces"]);
			Material[] array = ((Renderer)body).sharedMaterials.Select((Material material) => Own<Material>(new Material(material))).ToArray();
			if (array.Length != val2.subMeshCount)
			{
				throw new InvalidDataException("Native material layout changed");
			}
			Material[] array2 = array;
			foreach (Material val4 in array2)
			{
				if (val4.HasProperty("_SkinColor"))
				{
					val4.SetColor("_SkinColor", shape.Skin);
				}
			}
			if ((Object)(object)val2 != (Object)(object)body.sharedMesh && Object.op_Implicit((Object)(object)val?.m_baseMaterial))
			{
				string[] array3 = new string[2] { "_MainTex", "_SkinBumpMap" };
				foreach (string text in array3)
				{
					if (array[0].HasProperty(text) && val.m_baseMaterial.HasProperty(text))
					{
						array[0].SetTexture(text, val.m_baseMaterial.GetTexture(text));
					}
				}
			}
			Material val5 = Own<Material>(new Material(((Renderer)groom[0]).sharedMaterial));
			((Object)val5).name = art + " iris";
			val5.mainTexture = (Texture)(object)albedo((string)recipe["eyeTexture"]);
			Matrix4x4 frame = shape.Frame;
			Matrix4x4 inverse = ((Matrix4x4)(ref frame)).inverse;
			Transform[] bones = body.bones;
			Matrix4x4[] bindposes = val2.bindposes;
			foreach (SkinnedMeshRenderer val6 in groom)
			{
				val6.sharedMesh.bindposes = val6.bones.Select((Transform bone) => bindposes[Array.IndexOf(bones, bone)] * inverse).ToArray();
			}
			Attach(body, val3, array.Concat((IEnumerable<Material>)(object)new Material[1] { val5 }).ToArray(), art + " face");
			JToken marks = shape.Marks;
			if (marks != null && ((IEnumerable<JToken>)marks).Any())
			{
				Mesh val7 = Own<Mesh>(new Mesh
				{
					name = art + " complexion"
				});
				FaceMarkings.Paint(val7, val3, shape, array.Length);
				Material[] materials = array.Select(delegate(Material material)
				{
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					//IL_0011: Expected O, but got Unknown
					//IL_0067: Unknown result type (might be due to invalid IL or missing references)
					Material val8 = Own<Material>(new Material(material));
					if (val8.HasProperty("_SkinColor"))
					{
						val8.SetColor("_SkinColor", new Color(shape.Skin.r * 0.84f, shape.Skin.g * 0.8f, shape.Skin.b * 0.79f));
					}
					return val8;
				}).ToArray();
				Attach(body, val7, materials, art + " markings");
			}
			foreach (GameObject copy in copies)
			{
				copy.SetActive(true);
			}
			workCap = (Renderer)(object)((IEnumerable<SkinnedMeshRenderer>)groom).FirstOrDefault((Func<SkinnedMeshRenderer, bool>)((SkinnedMeshRenderer part) => ((Object)part).name == "RB_W02_WorkCap"));
			Hide((Renderer)(object)body);
			RefreshGroom();
		}

		private T Own<T>(T resource) where T : Object
		{
			resources.Add((Object)(object)resource);
			return resource;
		}

		private void Attach(SkinnedMeshRenderer body, Mesh mesh, Material[] materials, string label)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_0076: 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)
			GameObject val = new GameObject("Returning Bough " + label)
			{
				layer = ((Component)body).gameObject.layer
			};
			copies.Add(val);
			val.SetActive(false);
			val.transform.SetParent(((Component)body).transform, false);
			SkinnedMeshRenderer obj = val.AddComponent<SkinnedMeshRenderer>();
			obj.sharedMesh = mesh;
			((Renderer)obj).sharedMaterials = materials;
			obj.bones = body.bones;
			obj.rootBone = body.rootBone;
			obj.quality = body.quality;
			((Renderer)obj).localBounds = ((Renderer)body).localBounds;
			obj.updateWhenOffscreen = body.updateWhenOffscreen;
		}

		internal void RefreshGroom()
		{
			if (Object.op_Implicit((Object)(object)equipment))
			{
				HideAttachment(Hair, ref previousHair);
				HideAttachment(Beard, ref previousBeard);
				if (Object.op_Implicit((Object)(object)workCap))
				{
					object? obj = Helmet?.GetValue(equipment);
					GameObject val = (GameObject)((obj is GameObject) ? obj : null);
					workCap.enabled = !Object.op_Implicit((Object)(object)val) || !val.activeInHierarchy;
				}
			}
		}

		private void HideAttachment(FieldInfo field, ref GameObject previous)
		{
			object? obj = field?.GetValue(equipment);
			GameObject val = (GameObject)((obj is GameObject) ? obj : null);
			if ((Object)(object)val == (Object)(object)previous)
			{
				return;
			}
			previous = val;
			if (Object.op_Implicit((Object)(object)val))
			{
				Renderer[] componentsInChildren = val.GetComponentsInChildren<Renderer>(true);
				foreach (Renderer renderer in componentsInChildren)
				{
					Hide(renderer);
				}
			}
		}

		private void Hide(Renderer renderer)
		{
			if (!renderer.forceRenderingOff)
			{
				hidden.Add(renderer);
				renderer.forceRenderingOff = true;
			}
		}

		private void OnDestroy()
		{
			foreach (Renderer item in hidden)
			{
				if (Object.op_Implicit((Object)(object)item))
				{
					item.forceRenderingOff = false;
				}
			}
			foreach (GameObject copy in copies)
			{
				if (Object.op_Implicit((Object)(object)copy))
				{
					Object.Destroy((Object)(object)copy);
				}
			}
			foreach (Object resource in resources)
			{
				if (Object.op_Implicit(resource))
				{
					Object.Destroy(resource);
				}
			}
		}
	}
	[DefaultExecutionOrder(500)]
	internal sealed class TorvaldFootPlacement : MonoBehaviour
	{
		private sealed class Leg
		{
			private readonly Transform thigh;

			private readonly Transform shin;

			private readonly Transform foot;

			private readonly Transform[] bones;

			private readonly Matrix4x4[] bind;

			private readonly Matrix4x4[] skin;

			private readonly Vector3[] points;

			private readonly BoneWeight[] weights;

			private readonly int[] sole;

			private Quaternion oldThigh;

			private Quaternion oldShin;

			private Quaternion oldFoot;

			private Quaternion setThigh;

			private Quaternion setShin;

			private Quaternion setFoot;

			private bool changed;

			internal Leg(SkinnedMeshRenderer boot, string side)
			{
				Leg leg = this;
				foot = boot.bones.Single((Transform b) => ((Object)b).name == side + "Foot");
				shin = foot.parent;
				thigh = shin.parent;
				bones = boot.bones;
				bind = boot.sharedMesh.bindposes;
				skin = (Matrix4x4[])(object)new Matrix4x4[bones.Length];
				points = boot.sharedMesh.vertices;
				weights = boot.sharedMesh.boneWeights;
				float low = points.Min((Vector3 v) => v.y);
				sole = (from i in Enumerable.Range(0, points.Length)
					where leg.points[i].y <= low + 0.013f
					group i by (leg.points[i], leg.weights[i]) into g
					select g.First()).ToArray();
			}

			internal void Release()
			{
				//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_006c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				//IL_005c: Unknown result type (might be due to invalid IL or missing references)
				//IL_009a: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_008a: 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)
				if (!changed)
				{
					return;
				}
				changed = false;
				if (Object.op_Implicit((Object)(object)thigh) && Object.op_Implicit((Object)(object)shin) && Object.op_Implicit((Object)(object)foot))
				{
					if (Quaternion.Angle(thigh.localRotation, setThigh) < 0.01f)
					{
						thigh.localRotation = oldThigh;
					}
					if (Quaternion.Angle(shin.localRotation, setShin) < 0.01f)
					{
						shin.localRotation = oldShin;
					}
					if (Quaternion.Angle(foot.localRotation, setFoot) < 0.01f)
					{
						foot.localRotation = oldFoot;
					}
				}
			}

			private Vector3 Lowest()
			{
				//IL_0013: 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_0024: 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_006e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_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_0096: Unknown result type (might be due to invalid IL or missing references)
				//IL_0098: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: 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_00ce: 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_00e7: 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_00f8: Unknown result type (might be due to invalid IL or missing references)
				//IL_010f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0111: Unknown result type (might be due to invalid IL or missing references)
				//IL_011d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0122: Unknown result type (might be due to invalid IL or missing references)
				//IL_0127: Unknown result type (might be due to invalid IL or missing references)
				//IL_0129: Unknown result type (might be due to invalid IL or missing references)
				//IL_0130: Unknown result type (might be due to invalid IL or missing references)
				//IL_0148: Unknown result type (might be due to invalid IL or missing references)
				//IL_0138: Unknown result type (might be due to invalid IL or missing references)
				//IL_013a: Unknown result type (might be due to invalid IL or missing references)
				for (int i = 0; i < bones.Length; i++)
				{
					skin[i] = bones[i].localToWorldMatrix * bind[i];
				}
				Vector3 val = default(Vector3);
				((Vector3)(ref val))..ctor(0f, float.PositiveInfinity, 0f);
				int[] array = sole;
				foreach (int num in array)
				{
					Vector3 val2 = points[num];
					BoneWeight val3 = weights[num];
					Vector3 val4 = ((Matrix4x4)(ref skin[((BoneWeight)(ref val3)).boneIndex0])).MultiplyPoint3x4(val2) * ((BoneWeight)(ref val3)).weight0 + ((Matrix4x4)(ref skin[((BoneWeight)(ref val3)).boneIndex1])).MultiplyPoint3x4(val2) * ((BoneWeight)(ref val3)).weight1 + ((Matrix4x4)(ref skin[((BoneWeight)(ref val3)).boneIndex2])).MultiplyPoint3x4(val2) * ((BoneWeight)(ref val3)).weight2 + ((Matrix4x4)(ref skin[((BoneWeight)(ref val3)).boneIndex3])).MultiplyPoint3x4(val2) * ((BoneWeight)(ref val3)).weight3;
					if (val4.y < val.y)
					{
						val = val4;
					}
				}
				return val;
			}

			internal void Place()
			{
				//IL_0001: 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_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: 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_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: 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_0051: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b4: 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)
				//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_00ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00de: 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_00e8: 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_00ec: 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_00f7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
				//IL_0100: 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_010b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0114: Unknown result type (might be due to invalid IL or missing references)
				//IL_0116: Unknown result type (might be due to invalid IL or missing references)
				//IL_013f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0141: Unknown result type (might be due to invalid IL or missing references)
				//IL_0143: Unknown result type (might be due to invalid IL or missing references)
				//IL_0148: Unknown result type (might be due to invalid IL or missing references)
				//IL_014a: 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)
				//IL_017c: Unknown result type (might be due to invalid IL or missing references)
				//IL_017e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0182: Unknown result type (might be due to invalid IL or missing references)
				//IL_0187: Unknown result type (might be due to invalid IL or missing references)
				//IL_018e: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b7: 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_01bb: Unknown result type (might be due to invalid IL or missing references)
				//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d7: 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_01e8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f4: 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)
				//IL_0204: Unknown result type (might be due to invalid IL or missing references)
				//IL_0209: Unknown result type (might be due to invalid IL or missing references)
				//IL_0211: 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_0215: Unknown result type (might be due to invalid IL or missing references)
				//IL_021a: Unknown result type (might be due to invalid IL or missing references)
				//IL_021c: Unknown result type (might be due to invalid IL or missing references)
				//IL_021e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0223: Unknown result type (might be due to invalid IL or missing references)
				//IL_022e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0233: Unknown result type (might be due to invalid IL or missing references)
				//IL_0249: Unknown result type (might be due to invalid IL or missing references)
				//IL_0254: Unknown result type (might be due to invalid IL or missing references)
				//IL_0259: Unknown result type (might be due to invalid IL or missing references)
				//IL_025e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0266: Unknown result type (might be due to invalid IL or missing references)
				//IL_026b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0270: Unknown result type (might be due to invalid IL or missing references)
				//IL_027b: 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_0290: 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_02af: Unknown result type (might be due to invalid IL or missing references)
				//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c0: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val = Lowest();
				RaycastHit val2 = default(RaycastHit);
				if (!Physics.Raycast(val + Vector3.up * 0.1f, Vector3.down, ref val2, 0.14f, Ground, (QueryTriggerInteraction)1) || ((RaycastHit)(ref val2)).normal.y < 0.98f)
				{
					return;
				}
				float num = val.y - ((RaycastHit)(ref val2)).point.y;
				if (num < -0.055f || num >= 0.026f)
				{
					return;
				}
				float num2 = 1f - Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.01f, 0.026f, num));
				float num3 = (0.001f - num) * num2;
				if (!(Mathf.Abs(num3) < 0.0003f))
				{
					Vector3 position = thigh.position;
					Vector3 position2 = shin.position;
					Vector3 position3 = foot.position;
					Vector3 val3 = position3 + Vector3.up * num3;
					Vector3 val4 = val3 - position;
					Vector3 normalized = ((Vector3)(ref val4)).normalized;
					float num4 = Vector3.Distance(position, position2);
					float num5 = Vector3.Distance(position2, position3);
					float num6 = Mathf.Clamp(Vector3.Distance(position, val3), Mathf.Abs(num4 - num5) + 0.0001f, num4 + num5 - 0.0001f);
					Vector3 val5 = Vector3.ProjectOnPlane(position2 - position, normalized);
					if (!(((Vector3)(ref val5)).sqrMagnitude < 1E-09f))
					{
						float num7 = (num4 * num4 + num6 * num6 - num5 * num5) / (2f * num6);
						Vector3 val6 = position + normalized * num7 + ((Vector3)(ref val5)).normalized * Mathf.Sqrt(Mathf.Max(0f, num4 * num4 - num7 * num7));
						Vector3 val7 = position + normalized * num6;
						oldThigh = thigh.localRotation;
						oldShin = shin.localRotation;
						oldFoot = foot.localRotation;
						Quaternion rotation = foot.rotation;
						thigh.rotation = Quaternion.FromToRotation(position2 - position, val6 - position) * thigh.rotation;
						shin.rotation = Quaternion.FromToRotation(foot.position - shin.position, val7 - shin.position) * shin.rotation;
						foot.rotation = rotation;
						setThigh = thigh.localRotation;
						setShin = shin.localRotation;
						setFoot = foot.localRotation;
						changed = true;
					}
				}
			}
		}

		private Leg[] legs = Array.Empty<Leg>();

		private Animator animator;

		private readonly List<AnimatorClipInfo> clips = new List<AnimatorClipInfo>();

		private static readonly int Ground = LayerMask.GetMask(new string[4] { "terrain", "piece", "static_solid", "Default" });

		internal static bool Supports(SkinnedMeshRenderer boot, string side)
		{
			if (!Object.op_Implicit((Object)(object)boot) || !Object.op_Implicit((Object)(object)boot.sharedMesh))
			{
				return false;
			}
			Transform val = ((IEnumerable<Transform>)boot.bones).FirstOrDefault((Func<Transform, bool>)((Transform b) => Object.op_Implicit((Object)(object)b) && ((Object)b).name == side + "Foot"));
			if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val.parent) && ((Object)val.parent).name == side + "Leg" && Object.op_Implicit((Object)(object)val.parent.parent))
			{
				return ((Object)val.parent.parent).name == side + "UpLeg";
			}
			return false;
		}

		internal void Bind(SkinnedMeshRenderer body, SkinnedMeshRenderer leftBoot, SkinnedMeshRenderer rightBoot)
		{
			animator = ((Component)body).GetComponentInParent<Animator>();
			legs = new Leg[2]
			{
				new Leg(leftBoot, "Left"),
				new Leg(rightBoot, "Right")
			};
		}

		private void Update()
		{
			ReleasePose();
		}

		private void OnDisable()
		{
			ReleasePose();
		}

		private void LateUpdate()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)animator) || !((Behaviour)animator).isActiveAndEnabled)
			{
				return;
			}
			animator.GetCurrentAnimatorClipInfo(0, clips);
			foreach (AnimatorClipInfo clip in clips)
			{
				AnimatorClipInfo current = clip;
				if (!(((AnimatorClipInfo)(ref current)).weight < 0.5f))
				{
					switch (((Object)((AnimatorClipInfo)(ref current)).clip).name)
					{
					case "IdleTweaked":
					case "Walk New":
					case "Jog New Fast":
					case "Run New":
						PlaceFeet();
						break;
					}
					break;
				}
			}
		}

		internal void ReleasePose()
		{
			Leg[] array = legs;
			for (int i = 0; i < array.Length; i++)
			{
				array[i].Release();
			}
		}

		internal void PlaceFeet()
		{
			Leg[] array = legs;
			for (int i = 0; i < array.Length; i++)
			{
				array[i].Place();
			}
		}
	}
	[BepInPlugin("cwew.returningbough.wardrobes", "Returning Bough Chapter I Wardrobes", "0.1.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Wardrobes : BaseUnityPlugin
	{
		private static readonly Dictionary<string, string> Cast = new Dictionary<string, string>
		{
			{ "rpg_quartermaster", "N01" },
			{ "rpg_supply", "N02" },
			{ "rb_yrsa", "N03" },
			{ "rb_sigrid", "N04" },
			{ "rb_torvald", "N05" }
		};

		private readonly Dictionary<string, object[]> outfits = new Dictionary<string, object[]>();

		private readonly Dictionary<string, JObject> faces = new Dictionary<string, JObject>();

		private readonly Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>();

		private readonly HashSet<string> errors = new HashSet<string>();

		private Type npcType;

		private Type garmentType;

		private IEnumerable<Component> loadedNpcs;

		private MethodInfo visualRoot;

		private MethodInfo build;

		private PropertyInfo campaignEnabled;

		private string directory;

		private float next;

		private Harmony portraitPatch;

		private void Awake()
		{
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Expected O, but got Unknown
			Assembly assembly = ((object)Chainloader.PluginInfos["cwew.returningbough"].Instance).GetType().Assembly;
			loadedNpcs = assembly.GetType("ReturningBough.LoadedNpcs")?.GetField("All", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue(null) as IEnumerable<Component>;
			npcType = AccessTools.TypeByName("TravsServerNPCs.Npc.NpcComponent");
			garmentType = assembly.GetType("ReturningBough.GarmentData", throwOnError: true);
			visualRoot = AccessTools.Method(assembly.GetType("ReturningBough.NpcVisuals"), "Visual", (Type[])null, (Type[])null);
			build = AccessTools.Method(assembly.GetType("ReturningBough.GarmentMeshFactory"), "Build", (Type[])null, (Type[])null);
			campaignEnabled = AccessTools.Property(assembly.GetType("ReturningBough.Plugin"), "TestWorld");
			directory = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "Outfits");
			portraitPatch = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
			portraitPatch.PatchAll(typeof(WorkerPortrait));
		}

		private void Update()
		{
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Expected O, but got Unknown
			if (Time.unscaledTime < next)
			{
				return;
			}
			next = Time.unscaledTime + 2f;
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer) || !Object.op_Implicit((Object)(object)ZNetScene.instance) || !Object.op_Implicit((Object)(object)ObjectDB.instance) || !(bool)campaignEnabled.GetValue(null, null))
			{
				return;
			}
			foreach (Component item in loadedNpcs ?? Object.FindObjectsByType(npcType, (FindObjectsSortMode)0).OfType<Component>())
			{
				if (!Object.op_Implicit((Object)(object)item) || !item.gameObject.activeInHierarchy)
				{
					continue;
				}
				ZNetView component = item.GetComponent<ZNetView>();
				object obj;
				if (component == null)
				{
					obj = null;
				}
				else
				{
					ZDO zDO = component.GetZDO();
					obj = ((zDO != null) ? zDO.GetString("tsn_profile", "") : null);
				}
				string text = (string)obj;
				if (text != null && Cast.TryGetValue(text, out var value))
				{
					GameObject val = (GameObject)visualRoot.Invoke(null, new object[1] { item });
					if (Object.op_Implicit((Object)(object)val))
					{
						Dress(val.transform, value, worker: false);
					}
				}
			}
			foreach (VikingNpc item2 in VikingNpc.All)
			{
				if (!Object.op_Implicit((Object)(object)item2) || !Object.op_Implicit((Object)(object)item2.NetView) || !item2.NetView.IsValid())
				{
					continue;
				}
				string text2 = WorkerOutfit(item2);
				if (text2 != null)
				{
					Dress(((Component)item2).transform, text2, worker: true);
					continue;
				}
				WardrobeBinding componentInChildren = ((Component)item2).GetComponentInChildren<WardrobeBinding>(true);
				if (Object.op_Implicit((Object)(object)componentInChildren))
				{
					Object.Destroy((Object)(object)((Component)componentInChildren).gameObject);
				}
			}
		}

		private static string WorkerOutfit(VikingNpc worker)
		{
			if (worker.IsHired())
			{
				switch ((worker.GetOwnerId() != 0L) ? worker.NetView.GetZDO().GetLong("vnpc_uid", 0L) : 0)
				{
				case 6975699723225981784L:
					if (worker.HasJob((VikingJob)2))
					{
						return "W02";
					}
					break;
				case 1555986177700387319L:
					if (worker.HasJob((VikingJob)4))
					{
						return "W04";
					}
					break;
				case 8707052282364180231L:
					if (worker.HasJob((VikingJob)5))
					{
						return "W06";
					}
					break;
				}
				if (worker.HasJob((VikingJob)1))
				{
					return "W01";
				}
			}
			if (!(worker.NetView.GetZDO().GetString("rb_specialist_guild", "") == "greenward"))
			{
				return null;
			}
			return "W01";
		}

		private object[] Garments(string art, string filename)
		{
			string text = art + "/" + filename;
			if (outfits.TryGetValue(text, out var value))
			{
				return value;
			}
			JObject val = JObject.Parse(File.ReadAllText(Path.Combine(directory, art, filename)));
			if ((string)val["artID"] != art || (int)val["schema"] != 1)
			{
				throw new InvalidDataException(text);
			}
			object[] array = ((IEnumerable<JToken>)val["garments"]).Select((JToken t) => t.ToObject(garmentType)).ToArray();
			if (array.Length == 0)
			{
				throw new InvalidDataException("Empty outfit " + text);
			}
			outfits.Add(text, array);
			return array;
		}

		private void Dress(Transform actor, string art, bool worker)
		{
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Expected O, but got Unknown
			WardrobeBinding componentInChildren = ((Component)actor).GetComponentInChildren<WardrobeBinding>(true);
			if (Object.op_Implicit((Object)(object)componentInChildren))
			{
				if (componentInChildren.Art == art)
				{
					if (Object.op_Implicit((Object)(object)componentInChildren.Face))
					{
						componentInChildren.Face.RefreshGroom();
					}
				}
				else
				{
					Object.Destroy((Object)(object)((Component)componentInChildren).gameObject);
				}
				return;
			}
			SkinnedMeshRenderer val = ((IEnumerable<SkinnedMeshRenderer>)((Component)actor).GetComponentsInChildren<SkinnedMeshRenderer>(true)).FirstOrDefault((Func<SkinnedMeshRenderer, bool>)((SkinnedMeshRenderer r) => ((Object)r).name.Equals("body", StringComparison.OrdinalIgnoreCase) && ((Component)r).gameObject.activeInHierarchy && Object.op_Implicit((Object)(object)r.sharedMesh) && r.bones.Length != 0 && r.bones.Length == r.sharedMesh.bindposes.Length));
			if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val.rootBone))
			{
				return;
			}
			Transform val2 = (worker ? (actor.Find("Visual") ?? actor.Find("visual") ?? ((Component)val).transform.parent) : actor);
			string item = art + "/" + ((Object)val.sharedMesh).name;
			if (errors.Contains(item))
			{
				return;
			}
			GameObject val3 = null;
			try
			{
				object[] array = Garments(art, "wardrobe.json");
				val3 = new GameObject("Returning Bough outfit " + art);
				val3.transform.SetParent(val2, false);
				Func<string, Texture2D> func = (string name) => Albedo(art, name);
				object[] array2 = array;
				foreach (object obj in array2)
				{
					build.Invoke(null, new object[5] { obj, val3.transform, val2, val, func });
				}
				WardrobeBinding wardrobeBinding = val3.AddComponent<WardrobeBinding>();
				VisEquipment componentInChildren2 = ((Component)actor).GetComponentInChildren<VisEquipment>(true);
				wardrobeBinding.Art = art;
				wardrobeBinding.Fit(val, componentInChildren2);
				if (art != "W01")
				{
					FitFace(wardrobeBinding, art, val2, val, componentInChildren2, func);
				}
				if (art == "N05")
				{
					SkinnedMeshRenderer[] componentsInChildren = val3.GetComponentsInChildren<SkinnedMeshRenderer>();
					SkinnedMeshRenderer val4 = ((IEnumerable<SkinnedMeshRenderer>)componentsInChildren).FirstOrDefault((Func<SkinnedMeshRenderer, bool>)((SkinnedMeshRenderer r) => ((Object)r).name == "RB_BootStyleProof_v03_Left_NativePreview_v01"));
					SkinnedMeshRenderer val5 = ((IEnumerable<SkinnedMeshRenderer>)componentsInChildren).FirstOrDefault((Func<SkinnedMeshRenderer, bool>)((SkinnedMeshRenderer r) => ((Object)r).name == "RB_BootStyleProof_v03_Right_NativePreview_v01"));
					if (TorvaldFootPlacement.Supports(val4, "Left") && TorvaldFootPlacement.Supports(val5, "Right"))
					{
						val3.AddComponent<TorvaldFootPlacement>().Bind(val, val4, val5);
					}
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Fitted {art} to {((Object)actor).name} using {((Object)val.sharedMesh).name}, {array.Length} garments.");
			}
			catch (Exception ex)
			{
				if (Object.op_Implicit((Object)(object)val3))
				{
					Object.Destroy((Object)(object)val3);
				}
				errors.Add(item);
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not fit " + art + " to " + ((Object)val.sharedMesh).name + ": " + ex.GetBaseException().Message));
			}
		}

		private void FitFace(WardrobeBinding wardrobe, string art, Transform visual, SkinnedMeshRenderer body, VisEquipment equipment, Func<string, Texture2D> texture)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			string path = Path.Combine(directory, art, "face.json");
			if (!File.Exists(path))
			{
				return;
			}
			GameObject val = new GameObject(art + " groom");
			val.transform.SetParent(((Component)wardrobe).transform, false);
			try
			{
				if (!faces.TryGetValue(art, out var value))
				{
					value = JObject.Parse(File.ReadAllText(path));
					faces.Add(art, value);
				}
				object[] array = Garments(art, "head.json");
				foreach (object obj in array)
				{
					build.Invoke(null, new object[5] { obj, val.transform, visual, body, texture });
				}
				NativeAppearance nativeAppearance = val.AddComponent<NativeAppearance>();
				nativeAppearance.Fit(art, value, body, equipment, val.GetComponentsInChildren<SkinnedMeshRenderer>(), texture);
				wardrobe.Face = nativeAppearance;
			}
			catch (Exception ex)
			{
				val.SetActive(false);
				Object.Destroy((Object)(object)val);
				if (errors.Add("head/" + art))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not fit the " + art + " head: " + ex.GetBaseException().Message));
				}
			}
		}

		private Texture2D Albedo(string art, string name)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			if (string.IsNullOrEmpty(name) || name != Path.GetFileName(name))
			{
				throw new InvalidDataException("Invalid atlas name");
			}
			string text = Path.Combine(directory, art, name);
			if (textures.TryGetValue(text, out var value))
			{
				return value;
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false, false)
			{
				name = name,
				filterMode = (FilterMode)0
			};
			try
			{
				if (!(bool)AccessTools.Method(typeof(ImageConversion), "LoadImage", new Type[3]
				{
					typeof(Texture2D),
					typeof(byte[]),
					typeof(bool)
				}, (Type[])null).Invoke(null, new object[3]
				{
					val,
					File.ReadAllBytes(text),
					false
				}))
				{
					throw new InvalidDataException("Invalid atlas " + name);
				}
				textures.Add(text, val);
				return val;
			}
			catch
			{
				Object.Destroy((Object)(object)val);
				throw;
			}
		}

		private void OnDisable()
		{
			WardrobeBinding[] array = Object.FindObjectsByType<WardrobeBinding>((FindObjectsSortMode)0);
			for (int i = 0; i < array.Length; i++)
			{
				Object.Destroy((Object)(object)((Component)array[i]).gameObject);
			}
		}

		private void OnDestroy()
		{
			Harmony obj = portraitPatch;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			foreach (Texture2D value in textures.Values)
			{
				Object.Destroy((Object)(object)value);
			}
		}
	}
	internal sealed class WardrobeBinding : MonoBehaviour
	{
		internal string Art;

		internal NativeAppearance Face;

		private readonly List<Renderer> hidden = new List<Renderer>();

		internal void Fit(SkinnedMeshRenderer body, VisEquipment equipment)
		{
			if (!Object.op_Implicit((Object)(object)equipment))
			{
				return;
			}
			string[] array = new string[2] { "m_chestItemInstances", "m_legItemInstances" };
			foreach (string text in array)
			{
				if (!(AccessTools.Field(typeof(VisEquipment), text)?.GetValue(equipment) is IEnumerable<GameObject> source))
				{
					continue;
				}
				foreach (GameObject item in source.Where((GameObject o) => Object.op_Implicit((Object)(object)o)))
				{
					Renderer[] componentsInChildren = item.GetComponentsInChildren<Renderer>(true);
					foreach (Renderer val in componentsInChildren)
					{
						if ((Object)(object)val != (Object)(object)body && !val.forceRenderingOff)
						{
							hidden.Add(val);
							val.forceRenderingOff = true;
						}
					}
				}
			}
		}

		private void OnDestroy()
		{
			foreach (Renderer item in hidden)
			{
				if (Object.op_Implicit((Object)(object)item))
				{
					item.forceRenderingOff = false;
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class WorkerPortrait
	{
		internal sealed class Capture
		{
			private readonly Transform subject;

			private readonly List<Renderer> hidden = new List<Renderer>();

			internal Capture(Transform subject)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Expected O, but got Unknown
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Expected O, but got Unknown
				this.subject = subject;
				Camera.onPreCull = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(BeforePortrait));
			}

			private void BeforePortrait(Camera camera)
			{
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				if (((Object)camera).name != "vnpc_portrait_camera" || !Object.op_Implicit((Object)(object)camera.targetTexture) || ((Object)camera.targetTexture).name != "vnpc_portrait")
				{
					return;
				}
				Plane[] array = GeometryUtility.CalculateFrustumPlanes(camera);
				Renderer[] array2 = Object.FindObjectsByType<Renderer>((FindObjectsSortMode)0);
				foreach (Renderer val in array2)
				{
					if (val.enabled && !val.forceRenderingOff && (camera.cullingMask & (1 << ((Component)val).gameObject.layer)) != 0 && !((Component)val).transform.IsChildOf(subject) && GeometryUtility.TestPlanesAABB(array, val.bounds))
					{
						hidden.Add(val);
						val.forceRenderingOff = true;
					}
				}
			}

			internal void Restore()
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Expected O, but got Unknown
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Expected O, but got Unknown
				Camera.onPreCull = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(BeforePortrait));
				foreach (Renderer item in hidden)
				{
					if (Object.op_Implicit((Object)(object)item))
					{
						item.forceRenderingOff = false;
					}
				}
			}
		}

		private static MethodBase TargetMethod()
		{
			return AccessTools.Method(typeof(VikingNpc).Assembly.GetType("ValheimNpc.VikingPortrait"), "Capture", (Type[])null, (Type[])null);
		}

		private static void Prefix(VikingNpc npc, out Capture __state)
		{
			__state = ((Object.op_Implicit((Object)(object)npc) && Object.op_Implicit((Object)(object)((Component)npc).GetComponentInChildren<WardrobeBinding>())) ? new Capture(((Component)npc).transform) : null);
		}

		private static void Finalizer(Capture __state)
		{
			__state?.Restore();
		}
	}
}

plugins/ReturningBough.PayrollCabinet.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Linq;
using UnityEngine;
using ValheimNpc;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("ReturningBough.PayrollCabinet")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a2f35a034722da7812b950e985e6acc0439cb25c")]
[assembly: AssemblyProduct("ReturningBough.PayrollCabinet")]
[assembly: AssemblyTitle("ReturningBough.PayrollCabinet")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ReturningBough.PayrollCabinet
{
	internal sealed class CabinetArt
	{
		internal readonly Mesh Body;

		internal readonly Mesh Door;

		internal readonly Vector3 Pivot;

		internal readonly Material Surface;

		private readonly byte[] data;

		private readonly JObject doc;

		private readonly int bufferStart;

		internal CabinetArt()
		{
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: 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_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Expected O, but got Unknown
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			using (Stream stream = typeof(CabinetArt).Assembly.GetManifestResourceStream("ReturningBough.PayrollCabinet.glb"))
			{
				using BinaryReader binaryReader = new BinaryReader(stream);
				data = binaryReader.ReadBytes(checked((int)stream.Length));
			}
			int num = BitConverter.ToInt32(data, 12);
			doc = JObject.Parse(Encoding.UTF8.GetString(data, 20, num));
			bufferStart = 28 + num;
			Body = ReadPart("Cabinet_Carcass");
			Door = ReadPart("Cabinet_Door");
			JToken val = Node("Door_Hinge_R")[(object)"translation"];
			Pivot = new Vector3((float)val[(object)0], (float)val[(object)1], 0f - (float)val[(object)2]);
			Texture2D val2 = ReadTexture("cabinet-oak-and-livery", linear: false);
			Texture2D val3 = ReadTexture("cabinet-roughness-metallic", linear: true);
			Color32[] pixels = val3.GetPixels32();
			for (int i = 0; i < pixels.Length; i++)
			{
				Color32 val4 = pixels[i];
				pixels[i] = new Color32(val4.b, (byte)0, (byte)0, (byte)(255 - val4.g));
			}
			val3.SetPixels32(pixels);
			val3.Apply(true, true);
			Material val5 = ZNetScene.instance.GetPrefab("piece_chest_wood").GetComponentsInChildren<MeshRenderer>(true).SelectMany((MeshRenderer r) => ((Renderer)r).sharedMaterials)
				.First((Material m) => Object.op_Implicit((Object)(object)m) && ((Object)m.shader).name == "Custom/Piece" && m.HasProperty("_MainTex") && Object.op_Implicit((Object)(object)m.GetTexture("_MainTex")));
			Surface = new Material(val5)
			{
				name = "Payroll cabinet • oak and indigo"
			};
			string[] array = new string[4] { "_BumpMap", "_DetailAlbedoMap", "_DetailNormalMap", "_EmissionMap" };
			foreach (string text in array)
			{
				if (Surface.HasProperty(text))
				{
					Surface.SetTexture(text, (Texture)null);
				}
			}
			array = new string[4] { "_NORMALMAP", "_DETAIL_MULX2", "_EMISSION", "_PARALLAXMAP" };
			foreach (string text2 in array)
			{
				Surface.DisableKeyword(text2);
			}
			Surface.SetTexture("_MainTex", (Texture)(object)val2);
			Surface.SetTextureOffset("_MainTex", Vector2.zero);
			Surface.SetTextureScale("_MainTex", Vector2.one);
			if (Surface.HasProperty("_Color"))
			{
				Surface.SetColor("_Color", Color.white);
			}
			if (Surface.HasProperty("_MetallicGlossMap"))
			{
				Surface.SetTexture("_MetallicGlossMap", (Texture)(object)val3);
				Surface.EnableKeyword("_METALLICGLOSSMAP");
			}
			if (Surface.HasProperty("_Glossiness"))
			{
				Surface.SetFloat("_Glossiness", 0.19f);
			}
			if (Surface.HasProperty("_GlossMapScale"))
			{
				Surface.SetFloat("_GlossMapScale", 0.8f);
			}
			data = null;
			doc = null;
		}

		private JToken Node(string name)
		{
			return ((IEnumerable<JToken>)doc["nodes"]).Single((JToken n) => (string)n[(object)"name"] == name);
		}

		private int Start(JToken view)
		{
			return bufferStart + ((int?)view[(object)"byteOffset"]).GetValueOrDefault();
		}

		private int Address(JToken accessor)
		{
			JToken val = doc["bufferViews"][(object)(int)accessor[(object)"bufferView"]];
			if (val[(object)"byteStride"] != null)
			{
				throw new InvalidDataException("Unexpected interleaved cabinet mesh");
			}
			return Start(val) + ((int?)accessor[(object)"byteOffset"]).GetValueOrDefault();
		}

		private Vector3[] Vectors(JToken a)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] array = (Vector3[])(object)new Vector3[(int)a[(object)"count"]];
			int num = Address(a);
			for (int i = 0; i < array.Length; i++)
			{
				int num2 = num + i * 12;
				array[i] = new Vector3(BitConverter.ToSingle(data, num2), BitConverter.ToSingle(data, num2 + 4), 0f - BitConverter.ToSingle(data, num2 + 8));
			}
			return array;
		}

		private Mesh ReadPart(string name)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			//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)
			JToken val = ((IEnumerable<JToken>)doc["meshes"][(object)(int)Node(name)[(object)"mesh"]][(object)"primitives"]).Single();
			JToken val2 = val[(object)"attributes"];
			JToken val3 = doc["accessors"];
			Mesh val4 = new Mesh
			{
				name = name
			};
			val4.vertices = Vectors(val3[(object)(int)val2[(object)"POSITION"]]);
			val4.normals = Vectors(val3[(object)(int)val2[(object)"NORMAL"]]);
			JToken val5 = val3[(object)(int)val2[(object)"TEXCOORD_0"]];
			int num = Address(val5);
			Vector2[] array = (Vector2[])(object)new Vector2[(int)val5[(object)"count"]];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new Vector2(BitConverter.ToSingle(data, num + i * 8), 1f - BitConverter.ToSingle(data, num + i * 8 + 4));
			}
			val4.uv = array;
			JToken val6 = val3[(object)(int)val[(object)"indices"]];
			if ((int)val6[(object)"componentType"] != 5123)
			{
				throw new InvalidDataException("Expected 16-bit indices");
			}
			num = Address(val6);
			int[] array2 = new int[(int)val6[(object)"count"]];
			for (int j = 0; j < array2.Length; j += 3)
			{
				array2[j] = BitConverter.ToUInt16(data, num + j * 2);
				array2[j + 1] = BitConverter.ToUInt16(data, num + j * 2 + 4);
				array2[j + 2] = BitConverter.ToUInt16(data, num + j * 2 + 2);
			}
			val4.triangles = array2;
			val4.RecalculateBounds();
			return val4;
		}

		private Texture2D ReadTexture(string name, bool linear)
		{
			//IL_008c: 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_009f: Expected O, but got Unknown
			JToken val = ((IEnumerable<JToken>)doc["images"]).Single((JToken i) => (string)i[(object)"name"] == name);
			JToken val2 = doc["bufferViews"][(object)(int)val[(object)"bufferView"]];
			byte[] array = new byte[(int)val2[(object)"byteLength"]];
			Buffer.BlockCopy(data, Start(val2), array, 0, array.Length);
			Texture2D val3 = new Texture2D(2, 2, (TextureFormat)4, true, linear)
			{
				name = name
			};
			if (!(bool)AccessTools.Method(typeof(ImageConversion), "LoadImage", new Type[3]
			{
				typeof(Texture2D),
				typeof(byte[]),
				typeof(bool)
			}, (Type[])null).Invoke(null, new object[3]
			{
				val3,
				array,
				!linear
			}))
			{
				throw new InvalidDataException(name);
			}
			return val3;
		}

		internal Transform AddMesh(Transform parent, Mesh mesh, Vector3 at)
		{
			//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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_0041: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(((Object)mesh).name);
			val.transform.SetParent(parent, false);
			val.transform.localPosition = at;
			val.layer = ((Component)parent).gameObject.layer;
			val.AddComponent<MeshFilter>().sharedMesh = mesh;
			((Renderer)val.AddComponent<MeshRenderer>()).sharedMaterial = Surface;
			return val.transform;
		}
	}
	[BepInPlugin("cwew.returningbough.payrollcabinet", "Returning Bough • Payroll Cabinet", "1.0.0")]
	[BepInDependency("com.valheimnpc.vikings", "1.6.7")]
	public sealed class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(Container), "Awake")]
		private static class WoodenChest
		{
			private static void Postfix(Container __instance)
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if (Object.op_Implicit((Object)(object)component) && component.IsValid() && __instance.GetInventory() != null)
				{
					int prefab = component.GetZDO().GetPrefab();
					if (prefab == StringExtensionMethods.GetStableHashCode("piece_chest_wood") || prefab == StringExtensionMethods.GetStableHashCode("RB_AssignmentChest") || prefab == StringExtensionMethods.GetStableHashCode("RB_CommunalReserveChest"))
					{
						((Component)__instance).gameObject.AddComponent<TreasuryAppearance>();
					}
				}
			}
		}

		internal static Func<Container, ZDO> Rule;

		internal static int ModeKey;

		internal static int TreasuryMode;

		internal static CabinetArt Art;

		internal static Plugin Instance;

		private Harmony patches;

		private void Awake()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			if ((int)SystemInfo.graphicsDeviceType != 4)
			{
				Type? type = typeof(VikingNpc).Assembly.GetType("ValheimNpc.ChestTags", throwOnError: true);
				Rule = AccessTools.MethodDelegate<Func<Container, ZDO>>(AccessTools.Method(type, "RuleZdo", (Type[])null, (Type[])null), (object)null, true);
				ModeKey = (int)AccessTools.Field(type, "ModeKey").GetValue(null);
				TreasuryMode = Convert.ToInt32(Enum.Parse(type.GetNestedType("Mode", AccessTools.all), "Treasury"));
				Instance = this;
				patches = new Harmony("cwew.returningbough.payrollcabinet");
				patches.PatchAll();
			}
		}

		private void OnDestroy()
		{
			Harmony obj = patches;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		internal static void Error(Exception e)
		{
			((BaseUnityPlugin)Instance).Logger.LogError((object)e);
		}
	}
	internal sealed class TreasuryAppearance : MonoBehaviour
	{
		private static readonly FieldRef<Inventory, string> InventoryName = AccessTools.FieldRefAccess<Inventory, string>("m_name");

		private const string Title = "Payroll Cabinet";

		private Container chest;

		private ZNetView view;

		private GameObject cabinet;

		private Transform door;

		private Renderer[] original;

		private bool[] hidden;

		private string oldName;

		private string oldInventoryName;

		private float angle;

		private bool Open
		{
			get
			{
				if (!view.IsOwner())
				{
					return view.GetZDO().GetInt(ZDOVars.s_inUse, 0) != 0;
				}
				return chest.IsInUse();
			}
		}

		private void Start()
		{
			chest = ((Component)this).GetComponent<Container>();
			view = ((Component)this).GetComponent<ZNetView>();
			((MonoBehaviour)this).InvokeRepeating("CheckTag", Random.Range(0.05f, 0.45f), 2f);
			((Behaviour)this).enabled = false;
		}

		private void CheckTag()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)view) || !view.IsValid() || !Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return;
			}
			Vector3 val = ((Component)Player.m_localPlayer).transform.position - ((Component)this).transform.position;
			if (((Vector3)(ref val)).sqrMagnitude > 10000f)
			{
				return;
			}
			try
			{
				ZDO obj = Plugin.Rule(chest);
				bool flag = ((obj != null) ? new int?(obj.GetInt(Plugin.ModeKey, 0)) : ((int?)null)) == Plugin.TreasuryMode;
				if (flag && !Object.op_Implicit((Object)(object)cabinet))
				{
					Show();
				}
				else if (!flag && Object.op_Implicit((Object)(object)cabinet))
				{
					Restore();
				}
			}
			catch (Exception e)
			{
				Restore();
				((MonoBehaviour)this).CancelInvoke("CheckTag");
				Plugin.Error(e);
			}
		}

		private void Show()
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: 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_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//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_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.Art == null || !Object.op_Implicit((Object)(object)Plugin.Art.Surface) || !Object.op_Implicit((Object)(object)Plugin.Art.Body))
			{
				Plugin.Art = new CabinetArt();
			}
			CabinetArt art = Plugin.Art;
			original = ((Component)this).GetComponentsInChildren<Renderer>(true);
			hidden = Array.ConvertAll(original, (Renderer r) => r.forceRenderingOff);
			oldName = chest.m_name;
			oldInventoryName = chest.GetInventory().GetName();
			cabinet = new GameObject("RB_PayrollCabinet");
			cabinet.transform.SetParent(((Component)this).transform, false);
			BoxCollider componentInChildren = ((Component)this).GetComponentInChildren<BoxCollider>();
			if (Object.op_Implicit((Object)(object)componentInChildren) && !((Collider)componentInChildren).isTrigger)
			{
				cabinet.transform.localPosition = Vector3.up * ((Component)this).transform.InverseTransformPoint(((Component)componentInChildren).transform.TransformPoint(componentInChildren.center - Vector3.up * componentInChildren.size.y * 0.5f)).y;
			}
			art.AddMesh(cabinet.transform, art.Body, Vector3.zero);
			door = art.AddMesh(cabinet.transform, art.Door, art.Pivot);
			BoxCollider obj = cabinet.AddComponent<BoxCollider>();
			obj.center = new Vector3(0f, 0.83f, 0f);
			obj.size = new Vector3(0.84f, 1.66f, 0.55f);
			Renderer[] array = original;
			foreach (Renderer val in array)
			{
				if (val is MeshRenderer || val is SkinnedMeshRenderer || val is SpriteRenderer)
				{
					val.forceRenderingOff = true;
				}
			}
			chest.m_name = "Payroll Cabinet";
			InventoryName.Invoke(chest.GetInventory()) = "Payroll Cabinet";
			((Behaviour)this).enabled = true;
			angle = (Open ? 110 : 0);
			door.localRotation = Quaternion.Euler(0f, 0f - angle, 0f);
		}

		private void Update()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)door) && view.IsValid())
			{
				float num = Mathf.MoveTowards(angle, (float)(Open ? 110 : 0), 137.5f * Time.deltaTime);
				if (num != angle)
				{
					angle = num;
					door.localRotation = Quaternion.Euler(0f, 0f - angle, 0f);
				}
			}
		}

		private void Restore()
		{
			if (Object.op_Implicit((Object)(object)cabinet))
			{
				cabinet.SetActive(false);
				Object.Destroy((Object)(object)cabinet);
				for (int i = 0; i < original.Length; i++)
				{
					if (Object.op_Implicit((Object)(object)original[i]))
					{
						original[i].forceRenderingOff = hidden[i];
					}
				}
				if (Object.op_Implicit((Object)(object)chest) && chest.GetInventory() != null)
				{
					chest.m_name = oldName;
					InventoryName.Invoke(chest.GetInventory()) = oldInventoryName;
				}
			}
			cabinet = null;
			door = null;
			((Behaviour)this).enabled = false;
		}
	}
}