Decompiled source of ValheimCapsules v0.1.0

plugins/ValheimCapsules/ValheimCapsules.dll

Decompiled 13 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Splatform;
using UnityEngine;
using ValheimCapsules.Commands;
using ValheimCapsules.Core;
using ValheimCapsules.Game;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("ValheimCapsules")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+e5372c3d7857a266f1c4195915efcb085cd563cd")]
[assembly: AssemblyProduct("ValheimCapsules")]
[assembly: AssemblyTitle("ValheimCapsules")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[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 ValheimCapsules
{
	internal sealed class CapsuleController : MonoBehaviour
	{
		private sealed class PlantSession
		{
			public Inventory Inventory;

			public ItemData Item;

			public Blueprint Blueprint;

			public List<Placement.GroundPoint> Contacts;

			public Aabb LocalBounds;

			public float Yaw;

			public bool HasTarget;

			public Vector3 LastAnchor = new Vector3(float.NaN, 0f, 0f);

			public float LastYaw = float.NaN;

			public float NextReplan;

			public Vec3 Origin;

			public PlantPlanner.Plan Plan;

			public string Problem;

			public readonly List<StiltPlacement> Stilts = new List<StiltPlacement>();
		}

		private const float ConfirmWindow = 8f;

		private const float RotateStep = 22.5f;

		private const float MaxPlantDistance = 60f;

		private StructureScanner.Scan _pending;

		private float _pendingUntil;

		private float _nextHighlight;

		private PlantSession _plant;

		internal float ScrollAccum;

		private MaterialPropertyBlock _invalidTint;

		private static int _terrainMask;

		private float _lastAttackCall = -10f;

		private ItemData _hinted;

		private ItemData _unreadable;

		public static CapsuleController Instance { get; private set; }

		public bool IsPlanting => _plant != null;

		private void Awake()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			_invalidTint = new MaterialPropertyBlock();
			_invalidTint.SetColor("_Color", new Color(1f, 0.25f, 0.25f, 1f));
		}

		public bool OnWandAttack(Player player, ItemData item)
		{
			bool num = Time.time - _lastAttackCall > 0.25f;
			_lastAttackCall = Time.time;
			if (!num)
			{
				return false;
			}
			if (InventoryGui.IsVisible() || TextInput.IsVisible() || Menu.IsVisible())
			{
				return false;
			}
			if (_plant != null && _plant.Item == item)
			{
				return TryPlant(player);
			}
			if (!CapsuleSeedItem.IsFull(item))
			{
				return OnCaptureUse(player, ((Humanoid)player).GetInventory(), item);
			}
			return false;
		}

		private void SyncWithEquipment(Player player)
		{
			ItemData rightItem = ((Humanoid)player).GetRightItem();
			if (!CapsuleSeedItem.IsSeed(rightItem))
			{
				_plant = null;
				_pending = null;
				_hinted = null;
				return;
			}
			if (CapsuleSeedItem.IsFull(rightItem))
			{
				if ((_plant == null || _plant.Item != rightItem) && rightItem != _unreadable)
				{
					BeginPlanting(player, ((Humanoid)player).GetInventory(), rightItem);
				}
				return;
			}
			_plant = null;
			if (_hinted != rightItem)
			{
				_hinted = rightItem;
				Msg(player, "Strike a building you made to seal it in the wand.");
			}
		}

		private bool OnCaptureUse(Player player, Inventory inventory, ItemData item)
		{
			Piece val = StructureScanner.PieceUnderCrosshair();
			if ((Object)(object)val == (Object)null)
			{
				Msg(player, "Aim the wand at a building you made.");
				return false;
			}
			if (_pending != null && Time.time < _pendingUntil && _pending.Pieces.Contains(val))
			{
				DoCapture(player, inventory, item, _pending);
				_pending = null;
				return true;
			}
			StructureScanner.Scan scan = StructureScanner.FindStructure(val);
			string text = Capture.Validate(scan);
			if (text != null)
			{
				Msg(player, text);
				return false;
			}
			_pending = scan;
			_pendingUntil = Time.time + 8f;
			Vec3 vec = scan.Bounds.Max - scan.Bounds.Min;
			Msg(player, $"Seal {scan.Pieces.Count} pieces ({vec.X:0}×{vec.Z:0}×{vec.Y:0} m) into the wand?\nStrike it again to confirm.");
			return true;
		}

		private void DoCapture(Player player, Inventory inventory, ItemData item, StructureScanner.Scan scan)
		{
			string text = Capture.Validate(scan);
			if (text != null)
			{
				Msg(player, text);
				return;
			}
			if (!inventory.ContainsItem(item) || CapsuleSeedItem.IsFull(item))
			{
				Msg(player, "The seed is gone or already full.");
				return;
			}
			Blueprint blueprint;
			string text2;
			try
			{
				blueprint = Capture.BuildBlueprint(scan, player);
				text2 = BlueprintCodec.Encode(blueprint);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Capture failed, nothing was changed: {arg}");
				Msg(player, "Capture failed — nothing was changed. See the log.");
				return;
			}
			string text3 = (from p in scan.Pieces
				select (!((Object)(object)p != (Object)null)) ? null : ((Component)p).GetComponentInChildren<Sign>() into sg
				where (Object)(object)sg != (Object)null
				select sg.GetText()).FirstOrDefault((string t) => !string.IsNullOrWhiteSpace(t)) ?? $"{blueprint.Pieces.Count}-piece building";
			CapsuleSeedItem.Write(item, text2, blueprint.Pieces.Count);
			CapsuleSeedItem.SetName(item, (text3.Length > 40) ? text3.Substring(0, 40) : text3);
			inventory.Changed(false, false);
			Capture.DestroyAll(scan);
			Plugin.Log.LogInfo((object)$"Captured {blueprint.Pieces.Count} pieces ({(float)text2.Length / 1024f:0.0} KB) into a seed");
			Msg(player, $"Sealed {blueprint.Pieces.Count} pieces into the Capsule Seed.");
			TextInput instance = TextInput.instance;
			if (instance != null)
			{
				instance.RequestText((TextReceiver)(object)new SeedNamer(item, inventory), "Name this capsule", 40);
			}
		}

		private void BeginPlanting(Player player, Inventory inventory, ItemData item)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			Blueprint blueprint;
			try
			{
				blueprint = CapsuleSeedItem.Read(item);
			}
			catch (Exception ex)
			{
				_unreadable = item;
				Plugin.Log.LogError((object)$"Couldn't read seed: {ex}");
				Msg(player, (ex is NotSupportedException) ? ex.Message : "This wand's contents are unreadable. See the log.");
				return;
			}
			_pending = null;
			Quaternion rotation = ((Component)player).transform.rotation;
			float yaw = Mathf.Round(((Quaternion)(ref rotation)).eulerAngles.y / 22.5f) * 22.5f;
			_plant = new PlantSession
			{
				Inventory = inventory,
				Item = item,
				Blueprint = blueprint,
				Contacts = Placement.GroundPoints(blueprint),
				LocalBounds = Placement.Bounds(blueprint),
				Yaw = yaw
			};
			ScrollAccum = 0f;
			Msg(player, string.Format("“{0}” ({1} pieces): scroll to rotate, strike the ground to plant, put the wand away to cancel.", CapsuleSeedItem.GetName(item) ?? "Building", blueprint.Pieces.Count));
		}

		private void CancelPlanting(string why)
		{
			_plant = null;
			if (why != null && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				Msg(Player.m_localPlayer, why);
			}
		}

		private bool TryPlant(Player player)
		{
			PlantSession plant = _plant;
			if (!plant.HasTarget || plant.Plan == null)
			{
				Msg(player, "Aim at the ground where you want it.");
				return false;
			}
			string arg = CapsuleSeedItem.GetName(plant.Item) ?? "building";
			string text;
			Spawner.Result result;
			try
			{
				text = Planting.Execute(player, plant.Inventory, plant.Item, plant.Blueprint, plant.Plan, plant.Yaw, out result);
			}
			catch (Exception arg2)
			{
				Plugin.Log.LogError((object)$"Planting failed part-way: {arg2}");
				CancelPlanting("Planting failed part-way. The wand kept the building. See the log.");
				return false;
			}
			if (text != null)
			{
				Msg(player, text);
				return false;
			}
			int count = plant.Plan.Stilts.Count;
			string text2 = $"Planted “{arg}”: {result.Spawned} pieces" + ((count > 0) ? string.Format(" on {0} stilt pole{1}", count, (count == 1) ? "" : "s") : "") + "." + (ModConfig.ConsumeSeedOnPlant.Value ? "" : " The wand is empty again.");
			if (result.MissingPrefabs.Count > 0)
			{
				text2 += string.Format("\n{0} piece types are missing (removed mod?): {1}", result.MissingPrefabs.Count, string.Join(", ", result.MissingPrefabs.Take(3)));
				Plugin.Log.LogWarning((object)("Missing prefabs on plant: " + string.Join(", ", result.MissingPrefabs)));
			}
			Plugin.Log.LogInfo((object)text2.Replace('\n', ' '));
			CancelPlanting(text2);
			return true;
		}

		private void Update()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead())
			{
				_plant = null;
				_pending = null;
			}
			else
			{
				if (InventoryGui.IsVisible() || Menu.IsVisible() || Console.IsVisible() || TextInput.IsVisible())
				{
					return;
				}
				SyncWithEquipment(localPlayer);
				if (_pending != null)
				{
					UpdateCaptureHighlight();
				}
				if (_plant != null)
				{
					if (ScrollAccum != 0f)
					{
						_plant.Yaw = Mathf.Repeat(_plant.Yaw + Mathf.Sign(ScrollAccum) * 22.5f, 360f);
						ScrollAccum = 0f;
					}
					UpdatePlantTarget();
					DrawGhost();
				}
			}
		}

		private void UpdateCaptureHighlight()
		{
			if (Time.time > _pendingUntil)
			{
				_pending = null;
			}
			else if (!(Time.time < _nextHighlight))
			{
				_nextHighlight = Time.time + 0.15f;
				StructureScanner.Highlight(_pending.Pieces);
			}
		}

		private void UpdatePlantTarget()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0067: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: 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_00c4: Unknown result type (might be due to invalid IL or missing references)
			PlantSession plant = _plant;
			if (_terrainMask == 0)
			{
				_terrainMask = LayerMask.GetMask(new string[1] { "terrain" });
			}
			Transform transform = ((Component)GameCamera.instance).transform;
			RaycastHit val = default(RaycastHit);
			if (!Physics.Raycast(transform.position, transform.forward, ref val, 80f, _terrainMask))
			{
				plant.HasTarget = false;
				return;
			}
			plant.HasTarget = true;
			Vector3 point = ((RaycastHit)(ref val)).point;
			Vector3 val2 = point - plant.LastAnchor;
			if (!(((Vector3)(ref val2)).sqrMagnitude < 0.0025f) || plant.Yaw != plant.LastYaw || !(Time.time < plant.NextReplan))
			{
				plant.NextReplan = Time.time + 0.5f;
				plant.LastAnchor = point;
				plant.LastYaw = plant.Yaw;
				Replan(plant, point, Player.m_localPlayer);
			}
		}

		private static void Replan(PlantSession s, Vector3 anchor, Player player)
		{
			//IL_000c: 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)
			PlantPlanner.Plan plan = (s.Plan = PlantPlanner.Compute(s.Contacts, s.LocalBounds, anchor, s.Yaw, player));
			s.Origin = plan.Origin;
			s.Problem = plan.Problem;
			s.Stilts.Clear();
			s.Stilts.AddRange(plan.Stilts);
			if (s.Problem == null && Vector3.Distance(((Component)player).transform.position, anchor) > 60f)
			{
				s.Problem = "Too far away.";
			}
		}

		private void DrawGhost()
		{
			//IL_0065: 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_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_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: 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_00df: 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)
			PlantSession plant = _plant;
			if (!plant.HasTarget)
			{
				return;
			}
			MaterialPropertyBlock props = ((plant.Problem == null) ? null : _invalidTint);
			foreach (PieceRecord piece in plant.Blueprint.Pieces)
			{
				PrefabVisuals prefabVisuals = PrefabVisuals.Get(piece.Prefab);
				if (prefabVisuals != null)
				{
					Vector3 val = Placement.ToWorld(piece.Position, plant.Origin, plant.Yaw).ToUnity();
					Quaternion val2 = Placement.ToWorld(piece.Rotation, plant.Yaw).ToUnity();
					prefabVisuals.Draw(Matrix4x4.TRS(val, val2, Vector3.one), props);
				}
			}
			foreach (StiltPlacement stilt in plant.Stilts)
			{
				PrefabVisuals.Get(stilt.Prefab)?.Draw(Matrix4x4.TRS(stilt.Position, stilt.Rotation, Vector3.one), props);
			}
		}

		private static void Msg(Player player, string text)
		{
			((Character)player).Message((MessageType)2, text, 0, (Sprite)null, false);
		}
	}
	internal static class CapsuleSeedItem
	{
		public const string PrefabName = "VC_CapsuleSeed";

		public const string TokenName = "$vc_capsule_seed";

		public const string DataKey = "vc.blueprint";

		public const string CountKey = "vc.count";

		public const string NameKey = "vc.name";

		public static void Register()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			PrefabManager.OnVanillaPrefabsAvailable -= Register;
			ItemConfig val = new ItemConfig();
			val.Name = "$vc_capsule_seed";
			val.Description = "$vc_capsule_seed_desc";
			val.CraftingStation = CraftingStations.Workbench;
			val.StackSize = 1;
			Sprite val2 = LoadIcon();
			val.Icons = (Sprite[])(object)((val2 == null) ? null : new Sprite[1] { val2 });
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
			{
				new RequirementConfig("AncientSeed", 1, 0, true),
				new RequirementConfig("Resin", 10, 0, true),
				new RequirementConfig("GreydwarfEye", 4, 0, true)
			};
			ItemConfig val3 = val;
			CustomItem val4 = new CustomItem("VC_CapsuleSeed", "Hammer", val3);
			SharedData shared = val4.ItemDrop.m_itemData.m_shared;
			shared.m_buildPieces = null;
			shared.m_useDurability = false;
			shared.m_canBeReparied = false;
			shared.m_weight = 1f;
			WandModel.Apply(val4.ItemPrefab);
			ItemManager.Instance.AddItem(val4);
			LocalizationManager.Instance.AddToken("$vc_capsule_seed", "Capsule Seed", false);
			LocalizationManager.Instance.AddToken("$vc_capsule_seed_desc", "A seed wand that holds a whole building. Equip it and strike a building you made to seal it inside; strike the ground with a full wand to plant the building somewhere new.", false);
			Plugin.Log.LogInfo((object)"Registered VC_CapsuleSeed");
		}

		private static Sprite LoadIcon()
		{
			//IL_0076: 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)
			using Stream stream = typeof(CapsuleSeedItem).Assembly.GetManifestResourceStream("ValheimCapsules.seed-icon.png");
			if (stream == null)
			{
				Plugin.Log.LogWarning((object)"seed-icon.png not embedded");
				return null;
			}
			byte[] array = new byte[stream.Length];
			stream.Read(array, 0, array.Length);
			Texture2D val = AssetUtils.LoadImage(array);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
		}

		public static bool IsSeed(ItemData item)
		{
			return item?.m_shared?.m_name == "$vc_capsule_seed";
		}

		public static bool IsFull(ItemData item)
		{
			return item.m_customData.ContainsKey("vc.blueprint");
		}

		public static int PieceCount(ItemData item)
		{
			if (!item.m_customData.TryGetValue("vc.count", out var value) || !int.TryParse(value, out var result))
			{
				return 0;
			}
			return result;
		}

		public static string GetName(ItemData item)
		{
			if (!item.m_customData.TryGetValue("vc.name", out var value) || string.IsNullOrWhiteSpace(value))
			{
				return null;
			}
			return value;
		}

		public static void SetName(ItemData item, string name)
		{
			item.m_customData["vc.name"] = name.Trim();
		}

		public static Blueprint Read(ItemData item)
		{
			return BlueprintCodec.Decode(item.m_customData["vc.blueprint"]);
		}

		public static void Write(ItemData item, string encoded, int pieces)
		{
			item.m_customData["vc.blueprint"] = encoded;
			item.m_customData["vc.count"] = pieces.ToString();
		}

		public static void Clear(ItemData item)
		{
			item.m_customData.Remove("vc.blueprint");
			item.m_customData.Remove("vc.count");
			item.m_customData.Remove("vc.name");
		}
	}
	internal static class ModConfig
	{
		public static ConfigEntry<int> MaxPieces;

		public static ConfigEntry<float> ConnectTolerance;

		public static ConfigEntry<float> MaxStiltHeight;

		public static ConfigEntry<float> StiltSpacing;

		public static ConfigEntry<float> SinkTolerance;

		public static ConfigEntry<float> StiltMinGap;

		public static ConfigEntry<bool> ConsumeSeedOnPlant;

		public static ConfigEntry<bool> StiltsCostWood;

		public static ConfigEntry<bool> RequireWardAccess;

		public static void Bind(ConfigFile cfg)
		{
			//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: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Expected O, but got Unknown
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Expected O, but got Unknown
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			ConfigurationManagerAttributes val = new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			};
			MaxPieces = cfg.Bind<int>("Capture", "MaxPieces", 1500, new ConfigDescription("Largest building a capsule can hold.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 10000), new object[1] { val }));
			ConnectTolerance = cfg.Bind<float>("Capture", "ConnectTolerance", 0.15f, new ConfigDescription("Pieces closer than this (metres) count as connected.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), new object[1] { val }));
			RequireWardAccess = cfg.Bind<bool>("Capture", "RequireWardAccess", true, new ConfigDescription("Only capture/plant where you have ward access.", (AcceptableValueBase)null, new object[1] { val }));
			ConsumeSeedOnPlant = cfg.Bind<bool>("Planting", "ConsumeSeedOnPlant", false, new ConfigDescription("Planting uses up the seed. Off: the seed comes back empty, ready to capture again.", (AcceptableValueBase)null, new object[1] { val }));
			StiltsCostWood = cfg.Bind<bool>("Planting", "StiltsCostWood", true, new ConfigDescription("Stilts cost what the poles cost to build (wood), taken from your inventory when planting. Ignored with the no-cost cheat.", (AcceptableValueBase)null, new object[1] { val }));
			SinkTolerance = cfg.Bind<float>("Planting", "SinkTolerance", 0.4f, new ConfigDescription("On uneven ground, how far (metres) a building may settle into the terrain instead of getting stilts. Poles and pillars can always sink.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), new object[1] { val }));
			StiltMinGap = cfg.Bind<float>("Planting", "StiltMinGap", 1f, new ConfigDescription("Gaps under the building smaller than this (metres) are left open: it's held up by the rest of the structure, like hand-built Valheim floors. Lower = more stilts.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.3f, 5f), new object[1] { val }));
			StiltSpacing = cfg.Bind<float>("Planting", "StiltSpacing", 4f, new ConfigDescription("Stilts go under the footprint's corners, then roughly this far apart (metres). Higher = fewer stilts.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 20f), new object[1] { val }));
			MaxStiltHeight = cfg.Bind<float>("Planting", "MaxStiltHeight", 10f, new ConfigDescription("Refuse to plant if any stilt would be taller than this.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 50f), new object[1] { val }));
		}
	}
	internal static class Patches
	{
		[HarmonyPatch(typeof(ZInput), "Internal_GetMouseScrollWheel")]
		private static class ScrollPatch
		{
			private static int _frame = -1;

			private static void Postfix(ref float __result)
			{
				CapsuleController instance = CapsuleController.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsPlanting && __result != 0f)
				{
					if (_frame != Time.frameCount)
					{
						_frame = Time.frameCount;
						instance.ScrollAccum += __result;
					}
					__result = 0f;
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "StartAttack")]
		private static class StartAttackPatch
		{
			private static bool Prefix(Humanoid __instance, bool secondaryAttack, ref bool __result)
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Expected O, but got Unknown
				if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					return true;
				}
				ItemData rightItem = __instance.GetRightItem();
				if (!CapsuleSeedItem.IsSeed(rightItem))
				{
					return true;
				}
				__result = false;
				if (secondaryAttack)
				{
					return false;
				}
				Player val = (Player)__instance;
				CapsuleController instance = CapsuleController.Instance;
				if (instance != null && instance.OnWandAttack(val, rightItem) && !string.IsNullOrEmpty(rightItem.m_shared.m_attack.m_attackAnimation))
				{
					((Character)val).m_zanim.SetTrigger(rightItem.m_shared.m_attack.m_attackAnimation);
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(ItemData), "GetIcon")]
		private static class IconPatch
		{
			private static void Postfix(ItemData __instance, ref Sprite __result)
			{
				if (CapsuleSeedItem.IsSeed(__instance) && CapsuleSeedItem.IsFull(__instance))
				{
					Sprite val = CapsuleIcons.Get(__instance);
					if ((Object)(object)val != (Object)null)
					{
						__result = val;
					}
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGrid), "CreateItemTooltip")]
		private static class TooltipTitlePatch
		{
			private static bool Prefix(InventoryGrid __instance, ItemData item, UITooltip tooltip)
			{
				//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)
				string text = (CapsuleSeedItem.IsSeed(item) ? CapsuleSeedItem.GetName(item) : null);
				if (text == null)
				{
					return true;
				}
				tooltip.Set("“" + text.Replace("$", "") + "”", item.GetTooltip(-1), __instance.m_tooltipAnchor, default(Vector2));
				return false;
			}
		}

		[HarmonyPatch(typeof(ItemData), "GetTooltip", new Type[]
		{
			typeof(ItemData),
			typeof(int),
			typeof(bool),
			typeof(float),
			typeof(int),
			typeof(bool)
		})]
		private static class TooltipPatch
		{
			private static void Postfix(ItemData item, ref string __result)
			{
				if (CapsuleSeedItem.IsSeed(item))
				{
					__result += (CapsuleSeedItem.IsFull(item) ? string.Format("\n\n<color=orange>Holds “{0}”: {1} pieces.</color>\nUse it to plant. The seed comes back empty.", CapsuleSeedItem.GetName(item) ?? "a building", CapsuleSeedItem.PieceCount(item)) : "\n\n<color=#a0a0a0>Empty. Use it while looking at a building to seal it inside.</color>");
				}
			}
		}
	}
	[BepInPlugin("com.valheimcapsules.mod", "Valheim Capsules", "0.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ModConfig.Bind(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("com.valheimcapsules.mod");
			_harmony.PatchAll(typeof(Plugin).Assembly);
			PrefabManager.OnVanillaPrefabsAvailable += CapsuleSeedItem.Register;
			((Component)this).gameObject.AddComponent<CapsuleController>();
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new ScanCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new CleanStiltsCommand());
			Log.LogInfo((object)"Valheim Capsules 0.1.0 loaded");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class PluginInfo
	{
		public const string Guid = "com.valheimcapsules.mod";

		public const string Name = "Valheim Capsules";

		public const string Version = "0.1.0";
	}
}
namespace ValheimCapsules.Core
{
	public sealed class Blueprint
	{
		public string Name = "";

		public long CapturedBy;

		public long CapturedAt;

		public string GameVersion = "";

		public List<PieceRecord> Pieces = new List<PieceRecord>();
	}
	public sealed class PieceRecord
	{
		public string Prefab = "";

		public Vec3 Position;

		public Quat Rotation = Quat.Identity;

		public Vec3 BoundsMin;

		public Vec3 BoundsMax;

		public bool Grounded;

		public ZdoData Data = new ZdoData();
	}
	public sealed class ZdoData
	{
		public Dictionary<int, float> Floats = new Dictionary<int, float>();

		public Dictionary<int, Vec3> Vec3s = new Dictionary<int, Vec3>();

		public Dictionary<int, Quat> Quats = new Dictionary<int, Quat>();

		public Dictionary<int, int> Ints = new Dictionary<int, int>();

		public Dictionary<int, long> Longs = new Dictionary<int, long>();

		public Dictionary<int, string> Strings = new Dictionary<int, string>();

		public Dictionary<int, byte[]> ByteArrays = new Dictionary<int, byte[]>();

		public int Count => Floats.Count + Vec3s.Count + Quats.Count + Ints.Count + Longs.Count + Strings.Count + ByteArrays.Count;
	}
	public static class BlueprintCodec
	{
		public const int CurrentVersion = 1;

		private const string Prefix = "VC";

		public static string Encode(Blueprint bp)
		{
			using MemoryStream memoryStream = new MemoryStream();
			using (GZipStream output = new GZipStream(memoryStream, CompressionLevel.Optimal, leaveOpen: true))
			{
				using BinaryWriter w = new BinaryWriter(output, Encoding.UTF8);
				WriteV1(w, bp);
			}
			return "VC" + 1 + ":" + Convert.ToBase64String(memoryStream.ToArray());
		}

		public static Blueprint Decode(string encoded)
		{
			if (encoded == null)
			{
				throw new ArgumentNullException("encoded");
			}
			int num = encoded.IndexOf(':');
			if (num < 3 || !encoded.StartsWith("VC", StringComparison.Ordinal) || !int.TryParse(encoded.Substring(2, num - 2), out var result))
			{
				throw new FormatException("Not a capsule blueprint.");
			}
			using GZipStream input = new GZipStream(new MemoryStream(Convert.FromBase64String(encoded.Substring(num + 1))), CompressionMode.Decompress);
			using BinaryReader r = new BinaryReader(input, Encoding.UTF8);
			if (result == 1)
			{
				return ReadV1(r);
			}
			throw new NotSupportedException($"Capsule format v{result} is newer than this mod (v{1}). Update the mod.");
		}

		private static void WriteV1(BinaryWriter w, Blueprint bp)
		{
			w.Write(bp.Name ?? "");
			w.Write(bp.CapturedBy);
			w.Write(bp.CapturedAt);
			w.Write(bp.GameVersion ?? "");
			List<string> list = new List<string>();
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			foreach (PieceRecord piece in bp.Pieces)
			{
				if (!dictionary.ContainsKey(piece.Prefab))
				{
					dictionary[piece.Prefab] = list.Count;
					list.Add(piece.Prefab);
				}
			}
			w.Write(list.Count);
			foreach (string item in list)
			{
				w.Write(item);
			}
			w.Write(bp.Pieces.Count);
			foreach (PieceRecord piece2 in bp.Pieces)
			{
				w.Write(dictionary[piece2.Prefab]);
				Write(w, piece2.Position);
				Write(w, piece2.Rotation);
				Write(w, piece2.BoundsMin);
				Write(w, piece2.BoundsMax);
				w.Write(piece2.Grounded);
				WriteZdo(w, piece2.Data);
			}
		}

		private static Blueprint ReadV1(BinaryReader r)
		{
			Blueprint blueprint = new Blueprint
			{
				Name = r.ReadString(),
				CapturedBy = r.ReadInt64(),
				CapturedAt = r.ReadInt64(),
				GameVersion = r.ReadString()
			};
			string[] array = new string[r.ReadInt32()];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = r.ReadString();
			}
			int num = r.ReadInt32();
			blueprint.Pieces = new List<PieceRecord>(num);
			for (int j = 0; j < num; j++)
			{
				blueprint.Pieces.Add(new PieceRecord
				{
					Prefab = array[r.ReadInt32()],
					Position = ReadVec3(r),
					Rotation = ReadQuat(r),
					BoundsMin = ReadVec3(r),
					BoundsMax = ReadVec3(r),
					Grounded = r.ReadBoolean(),
					Data = ReadZdo(r)
				});
			}
			return blueprint;
		}

		private static void WriteZdo(BinaryWriter w, ZdoData d)
		{
			WriteMap(w, d.Floats, delegate(BinaryWriter x, float v)
			{
				x.Write(v);
			});
			WriteMap(w, d.Vec3s, Write);
			WriteMap(w, d.Quats, Write);
			WriteMap(w, d.Ints, delegate(BinaryWriter x, int v)
			{
				x.Write(v);
			});
			WriteMap(w, d.Longs, delegate(BinaryWriter x, long v)
			{
				x.Write(v);
			});
			WriteMap(w, d.Strings, delegate(BinaryWriter x, string v)
			{
				x.Write(v ?? "");
			});
			WriteMap(w, d.ByteArrays, delegate(BinaryWriter x, byte[] v)
			{
				x.Write(v.Length);
				x.Write(v);
			});
		}

		private static ZdoData ReadZdo(BinaryReader r)
		{
			return new ZdoData
			{
				Floats = ReadMap(r, (BinaryReader x) => x.ReadSingle()),
				Vec3s = ReadMap(r, ReadVec3),
				Quats = ReadMap(r, ReadQuat),
				Ints = ReadMap(r, (BinaryReader x) => x.ReadInt32()),
				Longs = ReadMap(r, (BinaryReader x) => x.ReadInt64()),
				Strings = ReadMap(r, (BinaryReader x) => x.ReadString()),
				ByteArrays = ReadMap(r, (BinaryReader x) => x.ReadBytes(x.ReadInt32()))
			};
		}

		private static void WriteMap<T>(BinaryWriter w, Dictionary<int, T> map, Action<BinaryWriter, T> write)
		{
			w.Write(map.Count);
			foreach (KeyValuePair<int, T> item in map)
			{
				w.Write(item.Key);
				write(w, item.Value);
			}
		}

		private static Dictionary<int, T> ReadMap<T>(BinaryReader r, Func<BinaryReader, T> read)
		{
			int num = r.ReadInt32();
			Dictionary<int, T> dictionary = new Dictionary<int, T>(num);
			for (int i = 0; i < num; i++)
			{
				int key = r.ReadInt32();
				dictionary[key] = read(r);
			}
			return dictionary;
		}

		private static void Write(BinaryWriter w, Vec3 v)
		{
			w.Write(v.X);
			w.Write(v.Y);
			w.Write(v.Z);
		}

		private static void Write(BinaryWriter w, Quat q)
		{
			w.Write(q.X);
			w.Write(q.Y);
			w.Write(q.Z);
			w.Write(q.W);
		}

		private static Vec3 ReadVec3(BinaryReader r)
		{
			return new Vec3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
		}

		private static Quat ReadQuat(BinaryReader r)
		{
			return new Quat(r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
		}
	}
	public readonly struct Vec3 : IEquatable<Vec3>
	{
		public readonly float X;

		public readonly float Y;

		public readonly float Z;

		public static readonly Vec3 Zero = new Vec3(0f, 0f, 0f);

		public Vec3(float x, float y, float z)
		{
			X = x;
			Y = y;
			Z = z;
		}

		public static Vec3 operator +(Vec3 a, Vec3 b)
		{
			return new Vec3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
		}

		public static Vec3 operator -(Vec3 a, Vec3 b)
		{
			return new Vec3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
		}

		public static Vec3 operator *(Vec3 a, float s)
		{
			return new Vec3(a.X * s, a.Y * s, a.Z * s);
		}

		public static Vec3 Min(Vec3 a, Vec3 b)
		{
			return new Vec3(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Min(a.Z, b.Z));
		}

		public static Vec3 Max(Vec3 a, Vec3 b)
		{
			return new Vec3(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y), Math.Max(a.Z, b.Z));
		}

		public bool Equals(Vec3 o)
		{
			if (X == o.X && Y == o.Y)
			{
				return Z == o.Z;
			}
			return false;
		}

		public override bool Equals(object obj)
		{
			if (obj is Vec3 o)
			{
				return Equals(o);
			}
			return false;
		}

		public override int GetHashCode()
		{
			float x = X;
			int num = x.GetHashCode() * 397;
			x = Y;
			int num2 = (num ^ x.GetHashCode()) * 397;
			x = Z;
			return num2 ^ x.GetHashCode();
		}

		public override string ToString()
		{
			return $"({X:0.##}, {Y:0.##}, {Z:0.##})";
		}
	}
	public readonly struct Quat : IEquatable<Quat>
	{
		public readonly float X;

		public readonly float Y;

		public readonly float Z;

		public readonly float W;

		public static readonly Quat Identity = new Quat(0f, 0f, 0f, 1f);

		public Quat(float x, float y, float z, float w)
		{
			X = x;
			Y = y;
			Z = z;
			W = w;
		}

		public bool Equals(Quat o)
		{
			if (X == o.X && Y == o.Y && Z == o.Z)
			{
				return W == o.W;
			}
			return false;
		}

		public override bool Equals(object obj)
		{
			if (obj is Quat o)
			{
				return Equals(o);
			}
			return false;
		}

		public override int GetHashCode()
		{
			float x = X;
			int num = x.GetHashCode() * 397;
			x = Y;
			int num2 = (num ^ x.GetHashCode()) * 397;
			x = Z;
			int num3 = (num2 ^ x.GetHashCode()) * 397;
			x = W;
			return num3 ^ x.GetHashCode();
		}
	}
	public readonly struct Aabb
	{
		public readonly Vec3 Min;

		public readonly Vec3 Max;

		public Aabb(Vec3 min, Vec3 max)
		{
			Min = min;
			Max = max;
		}

		public Aabb Expand(float by)
		{
			return new Aabb(Min - new Vec3(by, by, by), Max + new Vec3(by, by, by));
		}

		public bool Intersects(Aabb o)
		{
			if (Min.X <= o.Max.X && Max.X >= o.Min.X && Min.Y <= o.Max.Y && Max.Y >= o.Min.Y && Min.Z <= o.Max.Z)
			{
				return Max.Z >= o.Min.Z;
			}
			return false;
		}

		public Aabb Union(Aabb o)
		{
			return new Aabb(Vec3.Min(Min, o.Min), Vec3.Max(Max, o.Max));
		}
	}
	public static class Placement
	{
		public readonly struct GroundPoint
		{
			public readonly Vec3 Point;

			public readonly bool Column;

			public GroundPoint(Vec3 point, bool column)
			{
				Point = point;
				Column = column;
			}
		}

		public static Quat Yaw(float degrees)
		{
			double num = (double)degrees * Math.PI / 360.0;
			return new Quat(0f, (float)Math.Sin(num), 0f, (float)Math.Cos(num));
		}

		public static Quat Mul(Quat a, Quat b)
		{
			return new Quat(a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y, a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z, a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X, a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z);
		}

		public static Vec3 Rotate(Quat q, Vec3 v)
		{
			Vec3 a = new Vec3(q.X, q.Y, q.Z);
			Vec3 vec = Cross(a, v) * 2f;
			return v + vec * q.W + Cross(a, vec);
		}

		public static float YawOf(Quat q)
		{
			Vec3 vec = Rotate(q, new Vec3(0f, 0f, 1f));
			return (float)((Math.Atan2(vec.X, vec.Z) * 180.0 / Math.PI % 360.0 + 360.0) % 360.0);
		}

		public static Vec3 ToLocal(Vec3 world, Vec3 origin, float yaw)
		{
			return Rotate(Yaw(0f - yaw), world - origin);
		}

		public static Vec3 ToWorld(Vec3 local, Vec3 origin, float yaw)
		{
			return origin + Rotate(Yaw(yaw), local);
		}

		public static Quat ToLocal(Quat world, float yaw)
		{
			return Mul(Yaw(0f - yaw), world);
		}

		public static Quat ToWorld(Quat local, float yaw)
		{
			return Mul(Yaw(yaw), local);
		}

		public static Aabb ToLocal(Aabb world, Vec3 origin, float yaw)
		{
			Vec3 vec = new Vec3(float.MaxValue, float.MaxValue, float.MaxValue);
			Vec3 vec2 = new Vec3(float.MinValue, float.MinValue, float.MinValue);
			for (int i = 0; i < 8; i++)
			{
				Vec3 b = ToLocal(new Vec3(((i & 1) == 0) ? world.Min.X : world.Max.X, ((i & 2) == 0) ? world.Min.Y : world.Max.Y, ((i & 4) == 0) ? world.Min.Z : world.Max.Z), origin, yaw);
				vec = Vec3.Min(vec, b);
				vec2 = Vec3.Max(vec2, b);
			}
			return new Aabb(vec, vec2);
		}

		public static Aabb Bounds(Blueprint bp)
		{
			if (bp.Pieces.Count == 0)
			{
				return new Aabb(Vec3.Zero, Vec3.Zero);
			}
			Aabb result = new Aabb(bp.Pieces[0].BoundsMin, bp.Pieces[0].BoundsMax);
			foreach (PieceRecord piece in bp.Pieces)
			{
				result = result.Union(new Aabb(piece.BoundsMin, piece.BoundsMax));
			}
			return result;
		}

		public static List<Vec3> GroundContacts(Blueprint bp, float inset = 0.15f, float merge = 0.4f)
		{
			return GroundPoints(bp, inset, merge).ConvertAll((GroundPoint g) => g.Point);
		}

		public static List<GroundPoint> GroundPoints(Blueprint bp, float inset = 0.15f, float merge = 0.4f)
		{
			List<GroundPoint> list = new List<GroundPoint>();
			foreach (PieceRecord piece in bp.Pieces)
			{
				if (piece.Grounded)
				{
					bool num = IsColumn(piece);
					float num2 = Math.Min(piece.BoundsMin.X + inset, (piece.BoundsMin.X + piece.BoundsMax.X) / 2f);
					float num3 = Math.Max(piece.BoundsMax.X - inset, (piece.BoundsMin.X + piece.BoundsMax.X) / 2f);
					float num4 = Math.Min(piece.BoundsMin.Z + inset, (piece.BoundsMin.Z + piece.BoundsMax.Z) / 2f);
					float num5 = Math.Max(piece.BoundsMax.Z - inset, (piece.BoundsMin.Z + piece.BoundsMax.Z) / 2f);
					float y = piece.BoundsMin.Y;
					if (num)
					{
						Add(list, new Vec3((num2 + num3) / 2f, y, (num4 + num5) / 2f), column: true, merge);
						continue;
					}
					Add(list, new Vec3(num2, y, num4), column: false, merge);
					Add(list, new Vec3(num3, y, num4), column: false, merge);
					Add(list, new Vec3(num2, y, num5), column: false, merge);
					Add(list, new Vec3(num3, y, num5), column: false, merge);
					Add(list, new Vec3((num2 + num3) / 2f, y, (num4 + num5) / 2f), column: false, merge);
				}
			}
			return list;
		}

		public static bool IsColumn(PieceRecord p)
		{
			float val = p.BoundsMax.X - p.BoundsMin.X;
			float val2 = p.BoundsMax.Z - p.BoundsMin.Z;
			float num = p.BoundsMax.Y - p.BoundsMin.Y;
			float num2 = Math.Max(val, val2);
			if (num >= 0.9f && num2 <= 0.8f)
			{
				return num >= 2.5f * num2;
			}
			return false;
		}

		private static void Add(List<GroundPoint> list, Vec3 c, bool column, float merge)
		{
			float num = merge * merge;
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].Column != column)
				{
					continue;
				}
				float num2 = list[i].Point.X - c.X;
				float num3 = list[i].Point.Z - c.Z;
				if (num2 * num2 + num3 * num3 < num)
				{
					if (c.Y < list[i].Point.Y)
					{
						list[i] = new GroundPoint(new Vec3(list[i].Point.X, c.Y, list[i].Point.Z), column);
					}
					return;
				}
			}
			list.Add(new GroundPoint(c, column));
		}

		private static Vec3 Cross(Vec3 a, Vec3 b)
		{
			return new Vec3(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X);
		}
	}
	public static class StiltPlanner
	{
		public readonly struct Contact
		{
			public readonly Vec3 LocalBottom;

			public readonly float GroundY;

			public readonly float MaxSink;

			public Contact(Vec3 localBottom, float groundY, float maxSink = 0f)
			{
				LocalBottom = localBottom;
				GroundY = groundY;
				MaxSink = maxSink;
			}
		}

		public readonly struct Segment
		{
			public readonly float BottomY;

			public readonly float Length;

			public readonly int ContactIndex;

			public Segment(int contact, float bottomY, float length)
			{
				ContactIndex = contact;
				BottomY = bottomY;
				Length = length;
			}
		}

		public sealed class Plan
		{
			public float OriginY;

			public readonly List<Segment> Segments = new List<Segment>();

			public float MaxGap;

			public int Columns;
		}

		public static Plan Compute(IReadOnlyList<Contact> contacts, IReadOnlyList<float> segmentLengths, IReadOnlyCollection<int> stiltAt = null, float minGap = 0.3f)
		{
			if (contacts == null || contacts.Count == 0)
			{
				throw new ArgumentException("Need at least one ground contact.", "contacts");
			}
			if (segmentLengths == null || segmentLengths.Count == 0)
			{
				throw new ArgumentException("Need at least one segment length.", "segmentLengths");
			}
			List<float> list = segmentLengths.OrderBy((float l) => l).ToList();
			float num = list[list.Count - 1];
			IReadOnlyCollection<int> readOnlyCollection = stiltAt ?? Enumerable.Range(0, contacts.Count).ToList();
			float num2 = ChooseOrigin(contacts, readOnlyCollection, minGap);
			Plan plan = new Plan
			{
				OriginY = num2
			};
			for (int num3 = 0; num3 < contacts.Count; num3++)
			{
				plan.MaxGap = Math.Max(plan.MaxGap, num2 + contacts[num3].LocalBottom.Y - contacts[num3].GroundY);
			}
			foreach (int item in readOnlyCollection)
			{
				Contact contact = contacts[item];
				float num4 = num2 + contact.LocalBottom.Y;
				float num5 = num4 - contact.GroundY;
				if (num5 < minGap)
				{
					continue;
				}
				plan.Columns++;
				float num6 = num5;
				while (num6 > 0.001f)
				{
					float num7 = num;
					foreach (float item2 in list)
					{
						if (item2 >= num6 - 0.001f)
						{
							num7 = item2;
							break;
						}
					}
					plan.Segments.Add(new Segment(item, num4 - num7, num7));
					num4 -= num7;
					num6 -= num7;
				}
			}
			return plan;
		}

		private static float ChooseOrigin(IReadOnlyList<Contact> contacts, IReadOnlyCollection<int> stiltAt, float minGap)
		{
			float num = float.NegativeInfinity;
			foreach (Contact contact in contacts)
			{
				if (!float.IsPositiveInfinity(contact.MaxSink))
				{
					num = Math.Max(num, contact.GroundY - contact.LocalBottom.Y - contact.MaxSink);
				}
			}
			List<float> list = new List<float>();
			if (!float.IsNegativeInfinity(num))
			{
				list.Add(num);
			}
			foreach (Contact contact2 in contacts)
			{
				float num2 = contact2.GroundY - contact2.LocalBottom.Y;
				if (num2 >= num - 0.0001f)
				{
					list.Add(num2);
				}
			}
			float result = list[0];
			int[] array = null;
			foreach (float item in list)
			{
				int num3 = 0;
				foreach (int item2 in stiltAt)
				{
					if (item + contacts[item2].LocalBottom.Y - contacts[item2].GroundY >= minGap)
					{
						num3++;
					}
				}
				float num4 = 0f;
				float num5 = 0f;
				float num6 = 0f;
				foreach (Contact contact3 in contacts)
				{
					float num7 = item + contact3.LocalBottom.Y - contact3.GroundY;
					num6 = Math.Max(num6, num7);
					if (num7 < 0f)
					{
						if (float.IsPositiveInfinity(contact3.MaxSink))
						{
							num5 -= num7;
						}
						else
						{
							num4 -= num7;
						}
					}
				}
				int[] array2 = new int[4]
				{
					num3,
					(int)Math.Round(num4 * 100f),
					(int)Math.Round(num6 * 100f),
					(int)Math.Round(num5 * 100f)
				};
				if (array == null || Less(array2, array))
				{
					array = array2;
					result = item;
				}
			}
			return result;
		}

		private static bool Less(int[] a, int[] b)
		{
			for (int i = 0; i < a.Length; i++)
			{
				if (a[i] != b[i])
				{
					return a[i] < b[i];
				}
			}
			return false;
		}

		public static List<int> SelectStiltPoints(IReadOnlyList<Vec3> contacts, float spacing)
		{
			List<int> list = new List<int>();
			if (contacts.Count == 0)
			{
				return list;
			}
			list.AddRange(ConvexHull(contacts));
			float[] array = new float[contacts.Count];
			int i;
			for (i = 0; i < contacts.Count; i++)
			{
				array[i] = ((list.Count == 0) ? float.MaxValue : list.Min((int j) => Dist2D(contacts[i], contacts[j])));
			}
			while (true)
			{
				int num = -1;
				for (int num2 = 0; num2 < contacts.Count; num2++)
				{
					if (num < 0 || array[num2] > array[num])
					{
						num = num2;
					}
				}
				if (num < 0 || array[num] < spacing)
				{
					break;
				}
				list.Add(num);
				for (int num3 = 0; num3 < contacts.Count; num3++)
				{
					array[num3] = Math.Min(array[num3], Dist2D(contacts[num3], contacts[num]));
				}
			}
			return list;
		}

		private static List<int> ConvexHull(IReadOnlyList<Vec3> pts)
		{
			List<int> list = (from i in Enumerable.Range(0, pts.Count)
				orderby pts[i].X, pts[i].Z
				select i).ToList();
			if (list.Count < 3)
			{
				return list;
			}
			List<int> list2 = new List<int>();
			for (int num = 0; num < 2; num++)
			{
				int count = list2.Count;
				foreach (int item in list)
				{
					while (list2.Count >= count + 2 && Cross(pts[list2[list2.Count - 2]], pts[list2[list2.Count - 1]], pts[item]) <= 1E-06f)
					{
						list2.RemoveAt(list2.Count - 1);
					}
					list2.Add(item);
				}
				list2.RemoveAt(list2.Count - 1);
				list.Reverse();
			}
			return list2.Distinct().ToList();
		}

		private static float Cross(Vec3 o, Vec3 a, Vec3 b)
		{
			return (a.X - o.X) * (b.Z - o.Z) - (a.Z - o.Z) * (b.X - o.X);
		}

		private static float Dist2D(Vec3 a, Vec3 b)
		{
			float num = a.X - b.X;
			float num2 = a.Z - b.Z;
			return (float)Math.Sqrt(num * num + num2 * num2);
		}
	}
	public static class Foundations
	{
		public static bool[] Find(IReadOnlyList<Aabb> bounds, IReadOnlyList<bool> nearGround)
		{
			bool[] array = new bool[bounds.Count];
			for (int i = 0; i < bounds.Count; i++)
			{
				if (nearGround[i])
				{
					array[i] = !RestsOnAnother(bounds, i) && !PokesThroughAnother(bounds, i);
				}
			}
			return array;
		}

		private static bool PokesThroughAnother(IReadOnlyList<Aabb> bounds, int i)
		{
			Aabb aabb = bounds[i];
			float num = (aabb.Min.X + aabb.Max.X) / 2f;
			float num2 = (aabb.Min.Z + aabb.Max.Z) / 2f;
			for (int j = 0; j < bounds.Count; j++)
			{
				if (j != i)
				{
					Aabb aabb2 = bounds[j];
					if (!(aabb2.Min.Y <= aabb.Min.Y + 0.1f) && !(aabb2.Min.Y >= aabb.Max.Y - 0.05f) && !(num < aabb2.Min.X) && !(num > aabb2.Max.X) && !(num2 < aabb2.Min.Z) && !(num2 > aabb2.Max.Z))
					{
						return true;
					}
				}
			}
			return false;
		}

		private static bool RestsOnAnother(IReadOnlyList<Aabb> bounds, int i)
		{
			Aabb aabb = bounds[i];
			float num = (aabb.Min.X + aabb.Max.X) / 2f;
			float num2 = (aabb.Min.Z + aabb.Max.Z) / 2f;
			for (int j = 0; j < bounds.Count; j++)
			{
				if (j != i)
				{
					Aabb aabb2 = bounds[j];
					if (!(aabb2.Max.Y > aabb.Min.Y + 0.05f) && !(aabb2.Max.Y < aabb.Min.Y - 0.3f) && !(num < aabb2.Min.X - 0.15f) && !(num > aabb2.Max.X + 0.15f) && !(num2 < aabb2.Min.Z - 0.15f) && !(num2 > aabb2.Max.Z + 0.15f))
					{
						return true;
					}
				}
			}
			return false;
		}
	}
	public static class StructureDetector
	{
		public sealed class Result
		{
			public readonly List<int> Indices = new List<int>();

			public bool Truncated;

			public Aabb Bounds;
		}

		public static Result FindConnected(IReadOnlyList<Aabb> pieces, int start, float tolerance = 0.1f, int maxPieces = 2000)
		{
			if (pieces == null)
			{
				throw new ArgumentNullException("pieces");
			}
			if (start < 0 || start >= pieces.Count)
			{
				throw new ArgumentOutOfRangeException("start");
			}
			Dictionary<long, List<int>> grid = new Dictionary<long, List<int>>();
			int i;
			for (i = 0; i < pieces.Count; i++)
			{
				ForEachCell(pieces[i].Expand(tolerance), 4f, delegate(long key)
				{
					if (!grid.TryGetValue(key, out var value))
					{
						value = (grid[key] = new List<int>());
					}
					value.Add(i);
				});
			}
			Result result = new Result
			{
				Bounds = pieces[start]
			};
			HashSet<int> seen = new HashSet<int> { start };
			Queue<int> queue = new Queue<int>();
			queue.Enqueue(start);
			while (queue.Count > 0)
			{
				int num = queue.Dequeue();
				result.Indices.Add(num);
				result.Bounds = result.Bounds.Union(pieces[num]);
				Aabb b = pieces[num].Expand(tolerance);
				ForEachCell(b, 4f, delegate(long key)
				{
					if (!grid.TryGetValue(key, out var value))
					{
						return;
					}
					foreach (int item in value)
					{
						if (!seen.Contains(item) && b.Intersects(pieces[item]))
						{
							seen.Add(item);
							queue.Enqueue(item);
						}
					}
				});
				if (result.Indices.Count >= maxPieces)
				{
					result.Truncated = queue.Count > 0;
					break;
				}
			}
			return result;
		}

		private static void ForEachCell(Aabb b, float cell, Action<long> f)
		{
			int num = Floor(b.Min.X / cell);
			int num2 = Floor(b.Max.X / cell);
			int num3 = Floor(b.Min.Y / cell);
			int num4 = Floor(b.Max.Y / cell);
			int num5 = Floor(b.Min.Z / cell);
			int num6 = Floor(b.Max.Z / cell);
			for (int i = num; i <= num2; i++)
			{
				for (int j = num3; j <= num4; j++)
				{
					for (int k = num5; k <= num6; k++)
					{
						f(Key(i, j, k));
					}
				}
			}
		}

		private static int Floor(float v)
		{
			return (int)Math.Floor(v);
		}

		private static long Key(int x, int y, int z)
		{
			return ((long)(x & 0x1FFFFF) << 42) | ((long)(y & 0x1FFFFF) << 21) | (z & 0x1FFFFF);
		}
	}
}
namespace ValheimCapsules.Game
{
	internal static class CapsuleIcons
	{
		private sealed class Entry
		{
			public string Encoded;

			public Sprite Sprite;
		}

		private static readonly ConditionalWeakTable<ItemData, Entry> Cache = new ConditionalWeakTable<ItemData, Entry>();

		public static Sprite Get(ItemData item)
		{
			if (!item.m_customData.TryGetValue("vc.blueprint", out var value))
			{
				return null;
			}
			Entry orCreateValue = Cache.GetOrCreateValue(item);
			if ((object)orCreateValue.Encoded == value)
			{
				return orCreateValue.Sprite;
			}
			orCreateValue.Encoded = value;
			orCreateValue.Sprite = null;
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				return null;
			}
			try
			{
				orCreateValue.Sprite = Render(BlueprintCodec.Decode(value));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't render seed icon: " + ex.Message));
			}
			return orCreateValue.Sprite;
		}

		private static Sprite Render(Blueprint bp)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0020: 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_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_0078: 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_0176: 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_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Expected O, but got Unknown
			//IL_009b: 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_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_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: 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_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: 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_0103: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("VC_CapsuleIcon");
			val.transform.position = new Vector3(0f, -5000f, 0f);
			try
			{
				int num = 0;
				foreach (PieceRecord piece in bp.Pieces)
				{
					PrefabVisuals prefabVisuals = PrefabVisuals.Get(piece.Prefab);
					if (prefabVisuals == null)
					{
						continue;
					}
					Matrix4x4 val2 = Matrix4x4.TRS(piece.Position.ToUnity(), piece.Rotation.ToUnity(), Vector3.one);
					foreach (PrefabVisuals.Part part in prefabVisuals.Parts)
					{
						Matrix4x4 val3 = val2 * part.LocalToRoot;
						GameObject val4 = new GameObject("part");
						val4.transform.SetParent(val.transform, false);
						val4.transform.localPosition = Vector4.op_Implicit(((Matrix4x4)(ref val3)).GetColumn(3));
						val4.transform.localRotation = ((Matrix4x4)(ref val3)).rotation;
						val4.transform.localScale = ((Matrix4x4)(ref val3)).lossyScale;
						val4.AddComponent<MeshFilter>().sharedMesh = part.Mesh;
						((Renderer)val4.AddComponent<MeshRenderer>()).sharedMaterials = part.Materials;
						num++;
					}
				}
				if (num == 0)
				{
					return null;
				}
				Stopwatch stopwatch = Stopwatch.StartNew();
				Sprite result = RenderManager.Instance.Render(new RenderRequest(val)
				{
					Rotation = RenderManager.IsometricRotation,
					Width = 128,
					Height = 128
				});
				Plugin.Log.LogInfo((object)$"Rendered seed icon: {bp.Pieces.Count} pieces, {num} meshes, {stopwatch.ElapsedMilliseconds} ms");
				return result;
			}
			finally
			{
				Object.DestroyImmediate((Object)(object)val);
			}
		}
	}
	internal sealed class SeedNamer : TextReceiver
	{
		private readonly ItemData _item;

		private readonly Inventory _inventory;

		public SeedNamer(ItemData item, Inventory inventory)
		{
			_item = item;
			_inventory = inventory;
		}

		public string GetText()
		{
			return CapsuleSeedItem.GetName(_item) ?? "";
		}

		public void SetText(string text)
		{
			if (!string.IsNullOrWhiteSpace(text) && CapsuleSeedItem.IsFull(_item))
			{
				CapsuleSeedItem.SetName(_item, text);
				_inventory.Changed(false, false);
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, "Capsule named “" + CapsuleSeedItem.GetName(_item) + "”.", 0, (Sprite)null, false);
				}
			}
		}
	}
	internal static class Capture
	{
		private const float GroundedThreshold = 0.4f;

		public static string Validate(StructureScanner.Scan scan)
		{
			if (scan == null || scan.Pieces.Count == 0)
			{
				return "Nothing to capture.";
			}
			if (scan.Truncated)
			{
				return $"Too big: over {ModConfig.MaxPieces.Value} pieces.";
			}
			if (scan.Pieces.Any((Piece p) => (Object)(object)p == (Object)null))
			{
				return "Part of the building disappeared — try again.";
			}
			if (ModConfig.RequireWardAccess.Value && scan.Pieces.Any((Piece p) => !PrivateArea.CheckAccess(((Component)p).transform.position, 0f, false, false)))
			{
				return "Part of this building is protected by a ward you don't have access to.";
			}
			if (scan.Pieces.Any(delegate(Piece p)
			{
				Container componentInChildren = ((Component)p).GetComponentInChildren<Container>();
				return componentInChildren != null && componentInChildren.IsInUse();
			}))
			{
				return "Someone is using a chest in this building.";
			}
			return null;
		}

		public static Blueprint BuildBlueprint(StructureScanner.Scan scan, Player player)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_041e: Unknown result type (might be due to invalid IL or missing references)
			float yaw = Placement.YawOf(((Component)scan.Target).transform.rotation.ToCore());
			List<Piece> list = scan.Pieces.Where((Piece p) => !Spawner.IsStilt(p)).ToList();
			List<Piece> source = scan.Pieces.Where(Spawner.IsStilt).ToList();
			Vec3 flat = new Vec3((scan.Bounds.Min.X + scan.Bounds.Max.X) / 2f, 0f, (scan.Bounds.Min.Z + scan.Bounds.Max.Z) / 2f);
			Aabb[] array = list.Select((Piece p) => StructureScanner.LocalBounds(p, flat, yaw)).ToArray();
			List<Aabb> source2 = source.Select((Piece p) => StructureScanner.LocalBounds(p, flat, yaw)).ToList();
			bool[] array2 = new bool[list.Count];
			bool[] array3 = new bool[list.Count];
			float[] array4 = new float[list.Count];
			for (int num = 0; num < list.Count; num++)
			{
				Aabb b = array[num];
				GroundUnder(b, flat, yaw, out array4[num], out var max);
				array3[num] = source2.Any((Aabb sb) => SitsOn(b, sb));
				array2[num] = array3[num] || b.Min.Y - max < 0.4f;
			}
			bool[] grounded = Foundations.Find(array, array2);
			float[] baseY = new float[list.Count];
			for (int num2 = 0; num2 < list.Count; num2++)
			{
				baseY[num2] = ((grounded[num2] && !array3[num2]) ? Math.Max(array[num2].Min.Y, array4[num2]) : array[num2].Min.Y);
			}
			float num3 = (grounded.Any((bool g) => g) ? (from i in Enumerable.Range(0, grounded.Length)
				where grounded[i]
				select i).Min((int i) => baseY[i]) : array.Min((Aabb aabb) => aabb.Min.Y));
			Vec3 origin = new Vec3(flat.X, num3, flat.Z);
			Blueprint blueprint = new Blueprint
			{
				Name = scan.Target.m_name,
				CapturedBy = player.GetPlayerID(),
				CapturedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
				GameVersion = ((object)Version.CurrentVersion/*cast due to .constrained prefix*/).ToString()
			};
			for (int num4 = 0; num4 < list.Count; num4++)
			{
				Piece val = list[num4];
				Vec3 boundsMin = array[num4].Min - new Vec3(0f, num3, 0f);
				Vec3 boundsMax = array[num4].Max - new Vec3(0f, num3, 0f);
				if (grounded[num4])
				{
					boundsMin = new Vec3(boundsMin.X, Math.Max(boundsMin.Y, baseY[num4] - num3), boundsMin.Z);
				}
				blueprint.Pieces.Add(new PieceRecord
				{
					Prefab = Utils.GetPrefabName(((Component)val).gameObject),
					Position = Placement.ToLocal(((Component)val).transform.position.ToCore(), origin, yaw),
					Rotation = Placement.ToLocal(((Component)val).transform.rotation.ToCore(), yaw),
					BoundsMin = boundsMin,
					BoundsMax = boundsMax,
					Grounded = grounded[num4],
					Data = ZdoBridge.Capture(((Component)val).GetComponent<ZNetView>().GetZDO())
				});
			}
			return blueprint;
		}

		private static bool SitsOn(Aabb piece, Aabb stilt)
		{
			float num = (stilt.Min.X + stilt.Max.X) / 2f;
			float num2 = (stilt.Min.Z + stilt.Max.Z) / 2f;
			if (stilt.Max.Y <= piece.Min.Y + 0.1f && stilt.Max.Y >= piece.Min.Y - 0.3f && num >= piece.Min.X - 0.2f && num <= piece.Max.X + 0.2f && num2 >= piece.Min.Z - 0.2f)
			{
				return num2 <= piece.Max.Z + 0.2f;
			}
			return false;
		}

		private static void GroundUnder(Aabb b, Vec3 flat, float yaw, out float min, out float max)
		{
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			float num = Math.Min(b.Min.X + 0.1f, (b.Min.X + b.Max.X) / 2f);
			float num2 = Math.Max(b.Max.X - 0.1f, (b.Min.X + b.Max.X) / 2f);
			float num3 = Math.Min(b.Min.Z + 0.1f, (b.Min.Z + b.Max.Z) / 2f);
			float num4 = Math.Max(b.Max.Z - 0.1f, (b.Min.Z + b.Max.Z) / 2f);
			min = float.MaxValue;
			max = float.MinValue;
			Vec3[] array = new Vec3[5]
			{
				new Vec3(num, 0f, num3),
				new Vec3(num2, 0f, num3),
				new Vec3(num, 0f, num4),
				new Vec3(num2, 0f, num4),
				new Vec3((num + num2) / 2f, 0f, (num3 + num4) / 2f)
			};
			foreach (Vec3 local in array)
			{
				float groundHeight = ZoneSystem.instance.GetGroundHeight(Placement.ToWorld(local, flat, yaw).ToUnity());
				min = Math.Min(min, groundHeight);
				max = Math.Max(max, groundHeight);
			}
		}

		public static void DestroyAll(StructureScanner.Scan scan)
		{
			foreach (Piece piece in scan.Pieces)
			{
				if (!((Object)(object)piece == (Object)null))
				{
					ZNetView component = ((Component)piece).GetComponent<ZNetView>();
					if (!((Object)(object)component == (Object)null) && component.IsValid())
					{
						component.ClaimOwnership();
						ZNetScene.instance.Destroy(((Component)piece).gameObject);
					}
				}
			}
		}
	}
	internal static class PlantPlanner
	{
		public sealed class Plan
		{
			public Vec3 Origin;

			public string Problem;

			public float MaxGap;

			public readonly List<StiltPlacement> Stilts = new List<StiltPlacement>();

			public readonly Dictionary<string, int> StiltCost = new Dictionary<string, int>();
		}

		public static Plan Compute(List<Placement.GroundPoint> contacts, Aabb localBounds, Vector3 anchor, float yaw, Player player)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a4: 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_0237: 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_025c: 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_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			Plan plan = new Plan();
			Vec3 origin = new Vec3(anchor.x, 0f, anchor.z);
			List<Stilts.Pole> list = Stilts.Available();
			float y = anchor.y;
			if (contacts.Count > 0)
			{
				List<StiltPlanner.Contact> list2 = new List<StiltPlanner.Contact>(contacts.Count);
				foreach (Placement.GroundPoint contact in contacts)
				{
					Vec3 point = contact.Point;
					Vector3 val = Placement.ToWorld(new Vec3(point.X, 0f, point.Z), origin, yaw).ToUnity();
					float maxSink = (contact.Column ? float.PositiveInfinity : ModConfig.SinkTolerance.Value);
					list2.Add(new StiltPlanner.Contact(point, ZoneSystem.instance.GetGroundHeight(val), maxSink));
				}
				List<int> stiltAt = StiltPlanner.SelectStiltPoints(contacts.ConvertAll((Placement.GroundPoint g) => g.Point), ModConfig.StiltSpacing.Value);
				StiltPlanner.Plan plan2 = StiltPlanner.Compute(list2, (list.Count > 0) ? list.Select((Stilts.Pole x) => x.Length).ToList() : new List<float> { 1f }, stiltAt, ModConfig.StiltMinGap.Value);
				y = plan2.OriginY;
				plan.MaxGap = plan2.MaxGap;
				if (plan2.MaxGap > ModConfig.MaxStiltHeight.Value)
				{
					plan.Problem = $"Too uneven here: it would need {plan2.MaxGap:0.0} m stilts (max {ModConfig.MaxStiltHeight.Value:0}).";
				}
				foreach (StiltPlanner.Segment seg in plan2.Segments)
				{
					Stilts.Pole pole = list.FirstOrDefault((Stilts.Pole x) => x.Length == seg.Length);
					if (pole.Prefab != null)
					{
						Vec3 localBottom = list2[seg.ContactIndex].LocalBottom;
						Vector3 val2 = Placement.ToWorld(new Vec3(localBottom.X, 0f, localBottom.Z), origin, yaw).ToUnity();
						plan.Stilts.Add(new StiltPlacement
						{
							Prefab = pole.Prefab,
							Position = new Vector3(val2.x, seg.BottomY + pole.PivotAboveBottom, val2.z),
							Rotation = Quaternion.Euler(0f, yaw, 0f)
						});
					}
				}
			}
			plan.Origin = new Vec3(anchor.x, y, anchor.z);
			if (ModConfig.StiltsCostWood.Value && !player.NoCostCheat())
			{
				foreach (StiltPlacement stilt in plan.Stilts)
				{
					Requirement[] resources = ZNetScene.instance.GetPrefab(stilt.Prefab).GetComponent<Piece>().m_resources;
					foreach (Requirement val3 in resources)
					{
						if (!((Object)(object)val3.m_resItem == (Object)null))
						{
							string name = val3.m_resItem.m_itemData.m_shared.m_name;
							plan.StiltCost.TryGetValue(name, out var value);
							plan.StiltCost[name] = value + val3.m_amount;
						}
					}
				}
				if (plan.Problem == null)
				{
					plan.Problem = MissingMaterials(plan.StiltCost, ((Humanoid)player).GetInventory());
				}
			}
			if (plan.Problem == null && ModConfig.RequireWardAccess.Value)
			{
				Aabb aabb = localBounds;
				Vec3[] array = new Vec3[5]
				{
					aabb.Min,
					aabb.Max,
					new Vec3(aabb.Min.X, 0f, aabb.Max.Z),
					new Vec3(aabb.Max.X, 0f, aabb.Min.Z),
					Vec3.Zero
				};
				for (int num = 0; num < array.Length; num++)
				{
					Vec3 vec = array[num];
					if (!PrivateArea.CheckAccess(Placement.ToWorld(new Vec3(vec.X, 0f, vec.Z), plan.Origin, yaw).ToUnity(), 0f, false, false))
					{
						plan.Problem = "Someone else's ward protects this area.";
						break;
					}
				}
			}
			return plan;
		}

		public static string MissingMaterials(Dictionary<string, int> cost, Inventory inv)
		{
			List<string> list = new List<string>();
			foreach (KeyValuePair<string, int> item in cost)
			{
				int num = item.Value - inv.CountItems(item.Key, -1, true);
				if (num > 0)
				{
					list.Add($"{num} {Localization.instance.Localize(item.Key).ToLowerInvariant()}");
				}
			}
			if (list.Count != 0)
			{
				return "Missing " + string.Join(", ", list) + " for stilts.";
			}
			return null;
		}
	}
	internal static class Planting
	{
		public static string Execute(Player player, Inventory inventory, ItemData seed, Blueprint bp, PlantPlanner.Plan plan, float yaw, out Spawner.Result result)
		{
			result = null;
			if (plan.Problem != null)
			{
				return plan.Problem;
			}
			if (!inventory.ContainsItem(seed))
			{
				return "The seed is no longer in your inventory.";
			}
			string text = PlantPlanner.MissingMaterials(plan.StiltCost, ((Humanoid)player).GetInventory());
			if (text != null)
			{
				return text;
			}
			result = Spawner.Spawn(bp, plan.Origin, yaw, plan.Stilts);
			foreach (KeyValuePair<string, int> item in plan.StiltCost)
			{
				((Humanoid)player).GetInventory().RemoveItem(item.Key, item.Value, -1, true);
			}
			if (ModConfig.ConsumeSeedOnPlant.Value)
			{
				inventory.RemoveItem(seed);
			}
			else
			{
				CapsuleSeedItem.Clear(seed);
				inventory.Changed(false, false);
			}
			return null;
		}
	}
	internal static class Stilts
	{
		public struct Pole
		{
			public string Prefab;

			public float Length;

			public float PivotAboveBottom;
		}

		private static readonly string[] Candidates = new string[2] { "wood_pole2", "wood_pole" };

		private static List<Pole> _cache;

		public static List<Pole> Available()
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			if (_cache != null)
			{
				return _cache;
			}
			_cache = new List<Pole>();
			string[] candidates = Candidates;
			foreach (string text in candidates)
			{
				PrefabVisuals prefabVisuals = PrefabVisuals.Get(text);
				if (prefabVisuals == null || prefabVisuals.Parts.Count == 0)
				{
					Plugin.Log.LogWarning((object)("Stilt prefab '" + text + "' not found"));
					continue;
				}
				float num = (float)Math.Round(((Bounds)(ref prefabVisuals.LocalBounds)).size.y, 2);
				_cache.Add(new Pole
				{
					Prefab = text,
					Length = num,
					PivotAboveBottom = 0f - ((Bounds)(ref prefabVisuals.LocalBounds)).min.y
				});
				Plugin.Log.LogInfo((object)$"Stilt '{text}': {num} m, pivot {0f - ((Bounds)(ref prefabVisuals.LocalBounds)).min.y:0.00} m above base");
			}
			return _cache;
		}
	}
	internal sealed class PrefabVisuals
	{
		public struct Part
		{
			public Mesh Mesh;

			public Material[] Materials;

			public Matrix4x4 LocalToRoot;
		}

		public readonly List<Part> Parts = new List<Part>();

		public Bounds LocalBounds;

		private static readonly Dictionary<string, PrefabVisuals> Cache = new Dictionary<string, PrefabVisuals>();

		public static PrefabVisuals Get(string prefabName)
		{
			if (Cache.TryGetValue(prefabName, out var value))
			{
				return value;
			}
			ZNetScene instance = ZNetScene.instance;
			GameObject val = ((instance != null) ? instance.GetPrefab(prefabName) : null);
			value = (((Object)(object)val == (Object)null) ? null : Build(val));
			Cache[prefabName] = value;
			return value;
		}

		private static PrefabVisuals Build(GameObject prefab)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: 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_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: 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_017e: 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_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: 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_01f3: 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_01da: 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)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			PrefabVisuals prefabVisuals = new PrefabVisuals();
			Transform transform = prefab.transform;
			Matrix4x4 worldToLocalMatrix = transform.worldToLocalMatrix;
			bool flag = true;
			HashSet<Renderer> hashSet = new HashSet<Renderer>();
			LODGroup[] componentsInChildren = prefab.GetComponentsInChildren<LODGroup>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				LOD[] lODs = componentsInChildren[i].GetLODs();
				for (int j = 1; j < lODs.Length; j++)
				{
					Renderer[] renderers = lODs[j].renderers;
					foreach (Renderer val in renderers)
					{
						if ((Object)(object)val != (Object)null)
						{
							hashSet.Add(val);
						}
					}
				}
			}
			MeshFilter[] componentsInChildren2 = prefab.GetComponentsInChildren<MeshFilter>(true);
			foreach (MeshFilter val2 in componentsInChildren2)
			{
				MeshRenderer component = ((Component)val2).GetComponent<MeshRenderer>();
				if ((Object)(object)val2.sharedMesh == (Object)null || (Object)(object)component == (Object)null || !((Renderer)component).enabled || hashSet.Contains((Renderer)(object)component) || !ActiveUnder(((Component)val2).transform, transform))
				{
					continue;
				}
				Matrix4x4 localToRoot = worldToLocalMatrix * ((Component)val2).transform.localToWorldMatrix;
				prefabVisuals.Parts.Add(new Part
				{
					Mesh = val2.sharedMesh,
					Materials = ((Renderer)component).sharedMaterials,
					LocalToRoot = localToRoot
				});
				Bounds bounds = val2.sharedMesh.bounds;
				for (int l = 0; l < 8; l++)
				{
					Vector3 val3 = ((Matrix4x4)(ref localToRoot)).MultiplyPoint3x4(new Vector3(((l & 1) == 0) ? ((Bounds)(ref bounds)).min.x : ((Bounds)(ref bounds)).max.x, ((l & 2) == 0) ? ((Bounds)(ref bounds)).min.y : ((Bounds)(ref bounds)).max.y, ((l & 4) == 0) ? ((Bounds)(ref bounds)).min.z : ((Bounds)(ref bounds)).max.z));
					if (flag)
					{
						prefabVisuals.LocalBounds = new Bounds(val3, Vector3.zero);
						flag = false;
					}
					else
					{
						((Bounds)(ref prefabVisuals.LocalBounds)).Encapsulate(val3);
					}
				}
			}
			return prefabVisuals;
		}

		private static bool ActiveUnder(Transform t, Transform root)
		{
			while ((Object)(object)t != (Object)null && (Object)(object)t != (Object)(object)root)
			{
				if (!((Component)t).gameObject.activeSelf)
				{
					return false;
				}
				t = t.parent;
			}
			return true;
		}

		public void Draw(Matrix4x4 world, MaterialPropertyBlock props)
		{
			//IL_0016: 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_001d: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			foreach (Part part in Parts)
			{
				Matrix4x4 val = world * part.LocalToRoot;
				for (int i = 0; i < part.Mesh.subMeshCount && i < part.Materials.Length; i++)
				{
					if ((Object)(object)part.Materials[i] != (Object)null)
					{
						Graphics.DrawMesh(part.Mesh, val, part.Materials[i], 0, (Camera)null, i, props, false, false);
					}
				}
			}
		}
	}
	internal static class Spawner
	{
		public sealed class Result
		{
			public int Spawned;

			public int Stilts;

			public readonly List<string> MissingPrefabs = new List<string>();
		}

		public static readonly int StiltKey = StringExtensionMethods.GetStableHashCode("vc_stilt");

		public static bool IsStilt(Piece p)
		{
			ZNetView component = ((Component)p).GetComponent<ZNetView>();
			if (component == null)
			{
				return false;
			}
			ZDO zDO = component.GetZDO();
			return ((zDO != null) ? new int?(zDO.GetInt(StiltKey, 0)) : ((int?)null)) == 1;
		}

		public static Result Spawn(Blueprint bp, Vec3 origin, float yaw, IReadOnlyList<StiltPlacement> stilts)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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_00a9: 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_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: 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_0184: Unknown result type (might be due to invalid IL or missing references)
			Result result = new Result();
			Player localPlayer = Player.m_localPlayer;
			PlatformUserID platformUserID = ((IUser)PlatformManager.DistributionPlatform.LocalUser).PlatformUserID;
			foreach (PieceRecord piece in bp.Pieces)
			{
				GameObject prefab = ZNetScene.instance.GetPrefab(piece.Prefab);
				if ((Object)(object)prefab == (Object)null)
				{
					if (!result.MissingPrefabs.Contains(piece.Prefab))
					{
						result.MissingPrefabs.Add(piece.Prefab);
					}
					continue;
				}
				Vector3 pos = Placement.ToWorld(piece.Position, origin, yaw).ToUnity();
				Quaternion rot = Placement.ToWorld(piece.Rotation, yaw).ToUnity();
				GameObject obj = SpawnWithData(prefab, pos, rot, piece.Data);
				if (obj != null)
				{
					Piece component = obj.GetComponent<Piece>();
					if (component != null)
					{
						component.SetCreator(localPlayer.GetPlayerID(), platformUserID);
					}
				}
				if ((Object)(object)obj != (Object)null)
				{
					result.Spawned++;
				}
			}
			foreach (StiltPlacement stilt in stilts)
			{
				GameObject prefab2 = ZNetScene.instance.GetPrefab(stilt.Prefab);
				if ((Object)(object)prefab2 == (Object)null)
				{
					continue;
				}
				ZdoData zdoData = new ZdoData();
				zdoData.Ints[StiltKey] = 1;
				GameObject obj2 = SpawnWithData(prefab2, stilt.Position, stilt.Rotation, zdoData);
				if (obj2 != null)
				{
					Piece component2 = obj2.GetComponent<Piece>();
					if (component2 != null)
					{
						component2.SetCreator(localPlayer.GetPlayerID(), platformUserID);
					}
				}
				if ((Object)(object)obj2 != (Object)null)
				{
					result.Stilts++;
				}
			}
			return result;
		}

		public static GameObject SpawnWithData(GameObject prefab, Vector3 pos, Quaternion rot, ZdoData data)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			ZNetView component = prefab.GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null)
			{
				return null;
			}
			int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)prefab).name);
			ZDO val = ZDOMan.instance.CreateNewZDO(pos, stableHashCode);
			val.Persistent = component.m_persistent;
			val.Type = component.m_type;
			val.Distant = component.m_distant;
			val.SetPrefab(stableHashCode);
			val.SetRotation(rot);
			if (data != null)
			{
				ZdoBridge.Apply(val, data);
			}
			return ZNetScene.instance.CreateObject(val);
		}
	}
	internal struct StiltPlacement
	{
		public string Prefab;

		public Vector3 Position;

		public Quaternion Rotation;
	}
	internal static class StructureScanner
	{
		public sealed class Scan
		{
			public Piece Target;

			public List<Piece> Pieces;

			public Aabb Bounds;

			public bool Truncated;
		}

		private static int _pieceMask;

		public static Piece PieceUnderCrosshair(float maxDistance = 50f)
		{
			//IL_0055: 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 (_pieceMask == 0)
			{
				_pieceMask = LayerMask.GetMask(new string[4] { "piece", "piece_nonsolid", "Default_small", "Default" });
			}
			GameCamera instance = GameCamera.instance;
			Transform val = ((instance != null) ? ((Component)instance).transform : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			RaycastHit val2 = default(RaycastHit);
			if (!Physics.Raycast(val.position, val.forward, ref val2, maxDistance, _pieceMask))
			{
				return null;
			}
			Piece componentInParent = ((Component)((RaycastHit)(ref val2)).collider).GetComponentInParent<Piece>();
			if (!((Object)(object)componentInParent != (Object)null) || !Eligible(componentInParent))
			{
				return null;
			}
			return componentInParent;
		}

		public static Scan FindStructure(Piece target)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			List<Piece> nearby = new List<Piece>();
			Piece.GetAllPiecesInRadius(((Component)target).transform.position, 160f, nearby);
			nearby.RemoveAll((Piece p) => (Object)(object)p == (Object)null || !Eligible(p));
			int num = nearby.IndexOf(target);
			if (num < 0)
			{
				return null;
			}
			List<Aabb> list = nearby.Select(WorldBounds).ToList();
			StructureDetector.Result result = StructureDetector.FindConnected(list, num, ModConfig.ConnectTolerance.Value, ModConfig.MaxPieces.Value);
			List<Piece> list2 = result.Indices.Select((int i) => nearby[i]).ToList();
			Aabb bounds = result.Bounds;
			HashSet<Piece> hashSet = new HashSet<Piece>(list2);
			for (int num2 = 0; num2 < nearby.Count; num2++)
			{
				Piece val = nearby[num2];
				if (!hashSet.Contains(val) && Spawner.IsStilt(val))
				{
					Aabb aabb = list[num2];
					float num3 = (aabb.Min.X + aabb.Max.X) / 2f;
					float num4 = (aabb.Min.Z + aabb.Max.Z) / 2f;
					if (num3 >= bounds.Min.X - 0.5f && num3 <= bounds.Max.X + 0.5f && num4 >= bounds.Min.Z - 0.5f && num4 <= bounds.Max.Z + 0.5f && aabb.Max.Y <= bounds.Max.Y)
					{
						list2.Add(val);
						hashSet.Add(val);
					}
				}
			}
			return new Scan
			{
				Target = target,
				Pieces = list2,
				Bounds = result.Bounds,
				Truncated = result.Truncated
			};
		}

		public static bool Eligible(Piece p)
		{
			if (p.IsPlacedByPlayer())
			{
				ZNetView component = ((Component)p).GetComponent<ZNetView>();
				if (((component != null) ? component.GetZDO() : null) != null && (Object)(object)((Component)p).GetComponent<Ship>() == (Object)null)
				{
					return (Object)(object)((Component)p).GetComponent<Vagon>() == (Object)null;
				}
			}
			return false;
		}

		public static Aabb WorldBounds(Piece p)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: 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_0071: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = (from c in ((Component)p).GetComponentsInChildren<Collider>()
				where c.enabled && !c.isTrigger
				select c).ToArray();
			if (array.Length == 0)
			{
				Vec3 vec = ((Component)p).transform.position.ToCore();
				return new Aabb(vec, vec);
			}
			Bounds bounds = array[0].bounds;
			for (int num = 1; num < array.Length; num++)
			{
				((Bounds)(ref bounds)).Encapsulate(array[num].bounds);
			}
			return bounds.ToCore();
		}

		public static Aabb LocalBounds(Piece p, Vec3 origin, float yaw)
		{
			//IL_0290: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: 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_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: 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_00d9: 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_00ea: 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_0103: 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_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_014b: 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_020f: 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_017f: 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_022f: 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_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: 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_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: 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)
			bool any = false;
			Vec3 min = default(Vec3);
			Vec3 max = default(Vec3);
			Collider[] componentsInChildren = ((Component)p).GetComponentsInChildren<Collider>();
			Bounds bounds = default(Bounds);
			foreach (Collider val in componentsInChildren)
			{
				if (!val.enabled || val.isTrigger)
				{
					continue;
				}
				Collider val2 = val;
				BoxCollider val3 = (BoxCollider)(object)((val2 is BoxCollider) ? val2 : null);
				if (val3 == null)
				{
					MeshCollider val4 = (MeshCollider)(object)((val2 is MeshCollider) ? val2 : null);
					if (val4 == null)
					{
						SphereCollider val5 = (SphereCollider)(object)((val2 is SphereCollider) ? val2 : null);
						if (val5 == null)
						{
							CapsuleCollider val6 = (CapsuleCollider)(object)((val2 is CapsuleCollider) ? val2 : null);
							if (val6 == null)
							{
								goto IL_015c;
							}
							Vector3 val7 = Vector3.one * val6.radius * 2f;
							((Vector3)(ref val7))[val6.direction] = Mathf.Max(val6.height, val6.radius * 2f);
							((Bounds)(ref bounds))..ctor(val6.center, val7);
						}
						else
						{
							((Bounds)(ref bounds))..ctor(val5.center, Vector3.one * val5.radius * 2f);
						}
					}
					else
					{
						if (!((Object)(object)val4.sharedMesh != (Object)null))
						{
							goto IL_015c;
						}
						bounds = val4.sharedMesh.bounds;
					}
				}
				else
				{
					((Bounds)(ref bounds))..ctor(val3.center, val3.size);
				}
				Matrix4x4 localToWorldMatrix = ((Component)val).transform.localToWorldMatrix;
				for (int j = 0; j < 8; j++)
				{
					Add(((Matrix4x4)(ref localToWorldMatrix)).MultiplyPoint3x4(new Vector3(((j & 1) == 0) ? ((Bounds)(ref bounds)).min.x : ((Bounds)(ref bounds)).max.x, ((j & 2) == 0) ? ((Bounds)(ref bounds)).min.y : ((Bounds)(ref bounds)).max.y, ((j & 4) == 0) ? ((Bounds)(ref bounds)).min.z : ((Bounds)(ref bounds)).max.z)));
				}
				continue;
				IL_015c:
				Bounds bounds2 = val.bounds;
				for (int k = 0; k < 8; k++)
				{
					Add(new Vector3(((k & 1) == 0) ? ((Bounds)(ref bounds2)).min.x : ((Bounds)(ref bounds2)).max.x, ((k & 2) == 0) ? ((Bounds)(ref bounds2)).min.y : ((Bounds)(ref bounds2)).max.y, ((k & 4) == 0) ? ((Bounds)(ref bounds2)).min.z : ((Bounds)(ref bounds2)).max.z));
				}
			}
			if (!any)
			{
				Vec3 vec = Placement.ToLocal(((Component)p).transform.position.ToCore(), origin, yaw);
				return new Aabb(vec, vec);
			}
			return new Aabb(min, max);
			void Add(Vector3 world)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				Vec3 vec2 = Placement.ToLocal(world.ToCore(), origin, yaw);
				if (!any)
				{
					min = (max = vec2);
					any = true;
				}
				else
				{
					min = Vec3.Min(min, vec2);
					max = Vec3.Max(max, vec2);
				}
			}
		}

		public static void Highlight(IEnumerable<Piece> pieces)
		{
			foreach (Piece piece in pieces)
			{
				if ((Object)(object)piece != (Object)null)
				{
					WearNTear component = ((Component)piece).GetComponent<WearNTear>();
					if (component != null)
					{
						component.Highlight();
					}
				}
			}
		}
	}
	internal static class WandModel
	{
		public const string HeadName = "VC_WandHead";

		private static readonly Color Gold = new Color(1f, 0.7f, 0.22f);

		public static void Apply(GameObject itemPrefab)
		{
			//IL_00f5: 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_011d: 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_018d: 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_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: 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_0292: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			GameObject prefab = Cache.GetPrefab<GameObject>("Torch");
			GameObject prefab2 = Cache.GetPrefab<GameObject>("AncientSeed");
			Transform val = itemPrefab.transform.Find("attach");
			if ((Object)(object)prefab == (Object)null || (Object)(object)prefab2 == (Object)null || (Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)$"Wand model: vanilla parts missing (torch={(Object)(object)prefab != (Object)null}, seed={(Object)(object)prefab2 != (Object)null}, attach={(Object)(object)val != (Object)null}); keeping the base model");
				return;
			}
			foreach (Transform item in ((IEnumerable)val).Cast<Transform>().ToList())
			{
				Object.DestroyImmediate((Object)(object)((Component)item).gameObject);
			}
			Transform val2 = prefab.transform.Find("attach/model");
			Part(val, "shaft", ((Component)val2).GetComponent<MeshFilter>().sharedMesh, ((Renderer)((Component)val2).GetComponent<MeshRenderer>()).sharedMaterials, new Vector3(0f, 0f, 0.28f), Quaternion.Euler(90f, 0f, 0f), new Vector3(0.85f, 0.78f, 0.85f));
			Transform val3 = prefab2.transform.Find("attach/model");
			Material val4 = Gild(((Renderer)((Component)val3).GetComponent<MeshRenderer>()).sharedMaterial);
			Part(val, "VC_WandHead", ((Component)val3).GetComponent<MeshFilter>().sharedMesh, (Material[])(object)new Material[1] { val4 }, new Vector3(0f, 0f, 0.74f), Quaternion.Euler(-90f, 0f, 0f), Vector3.one * 0.075f);
			Mesh mesh = PrimitiveMesh((PrimitiveType)2);
			Material val5 = GoldMaterial(val4);
			float[] array = new float[3] { 0.06f, 0.11f, 0.62f };
			float[] array2 = new float[3] { 0.05f, 0.05f, 0.046f };
			for (int i = 0; i < array.Length; i++)
			{
				Part(val, "band", mesh, (Material[])(object)new Material[1] { val5 }, new Vector3(0f, 0f, array[i]), Quaternion.Euler(90f, 0f, 0f), new Vector3(array2[i], 0.012f, array2[i]));
			}
			GameObject obj = Object.Instantiate<GameObject>(((Component)prefab2.transform.Find("attach/Point light")).gameObject, val, false);
			((Object)obj).name = "light";
			obj.transform.localPosition = new Vector3(0f, 0f, 0.76f);
			Light component = obj.GetComponent<Light>();
			component.color = Gold;
			component.intensity = 1.2f;
			component.range = 1.2f;
			Transform val6 = itemPrefab.transform.Find("collider");
			if ((Object)(object)val6 != (Object)null)
			{
				BoxCollider component2 = ((Component)val6).GetComponent<BoxCollider>();
				if (component2 != null)
				{
					val6.localScale = Vector3.one;
					component2.center = new Vector3(0f, 0f, 0.18f);
					component2.size = new Vector3(0.14f, 0.14f, 0.95f);
				}
			}
			Plugin.Log.LogInfo((object)"Wand model built");
		}

		private static GameObject Part(Transform parent, string name, Mesh mesh, Material[] mats, Vector3 pos, Quaternion rot, Vector3 scale)
		{
			//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_0017: 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_002a: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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_0064: Expected O, but got Unknown
			GameObject val = new GameObject(name)
			{
				layer = ((Component)parent).gameObject.layer
			};
			val.transform.SetParent(parent, false);
			val.transform.localPosition = pos;
			val.transform.localRotation = rot;
			val.transform.localScale = scale;
			val.AddComponent<MeshFilter>().sharedMesh = mesh;
			((Renderer)val.AddComponent<MeshRenderer>()).sharedMaterials = mats;
			return val;
		}

		private static Mesh PrimitiveMesh(PrimitiveType type)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GameObject.CreatePrimitive(type);
			Mesh sharedMesh = obj.GetComponent<MeshFilter>().sharedMesh;
			Object.DestroyImmediate((Object)(object)obj);
			return sharedMesh;
		}

		private static Material Gild(Material src)
		{
			//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_0012: Expected O, but got Unknown
			//IL_007c: 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)
			Material val = new Material(src)
			{
				name = "VC_ancientseed_gold"
			};
			Texture texture = src.GetTexture("_MainTex");
			if (texture != null)
			{
				val.SetTexture("_MainTex", (Texture)(object)Recolor(texture, 1.15f));
			}
			if (src.HasProperty("_EmissionMap"))
			{
				Texture texture2 = src.GetTexture("_EmissionMap");
				if (texture2 != null)
				{
					val.SetTexture("_EmissionMap", (Texture)(object)Recolor(texture2, 1f));
				}
			}
			if (src.HasProperty("_EmissionColor"))
			{
				val.SetColor("_EmissionColor", Gold * 0.7f);
			}
			return val;
		}

		private static Material GoldMaterial(Material template)
		{
			//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_0017: Expected O, but got Unknown
			//IL_001d: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			Material val = new Material(template.shader)
			{
				name = "VC_gold"
			};
			val.SetColor("_Color", Gold);
			if (val.HasProperty("_Metallic"))
			{
				val.SetFloat("_Metallic", 0.85f);
			}
			if (val.HasProperty("_Glossiness"))
			{
				val.SetFloat("_Glossiness", 0.55f);
			}
			if (val.HasProperty("_EmissionColor"))
			{
				val.EnableKeyword("_EMISSION");
				val.SetColor("_EmissionColor", Gold * 0.15f);
			}
			return val;
		}

		private static Texture2D Recolor(Texture src, float valueScale)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_006b: 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_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: 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_0100: 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_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)
			RenderTexture temporary = RenderTexture.GetTemporary(src.width, src.height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
			RenderTexture active = RenderTexture.active;
			Graphics.Blit(src, temporary);
			RenderTexture.acti