Decompiled source of ScoutBuilding v1.1.0

BepInEx/plugins/PeakFortnite.Building/PeakFortnite.Building.dll

Decompiled a week ago
using System;
using System.Buffers.Binary;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Peak;
using Peak.Afflictions;
using Peak.Network;
using PeakFortnite.Core;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using Unity.Collections;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.Animations.Rigging;
using UnityEngine.Audio;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Experimental.Rendering;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.LowLevelPhysics;
using UnityEngine.Pool;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using UnityEngine.Scripting;
using UnityEngine.UI;
using Zorro.ControllerSupport;
using Zorro.Core;
using Zorro.Settings;
using Zorro.UI;
using Zorro.UI.Modal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("PeakFortnite.Building")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+52bee84a6466bd05db4c9c27a95ab742dad3e598")]
[assembly: AssemblyProduct("PeakFortnite.Building")]
[assembly: AssemblyTitle("PeakFortnite.Building")]
[assembly: AssemblyVersion("1.1.0.0")]
namespace PeakFortnite.Core
{
	public static class BuildAimGeometry
	{
		private const float EdgeTolerance = 0.001f;

		public const float RoofApexFraction = 0.5f;

		public static bool Intersect(PieceSpec spec, Vector3 gridOrigin, float width, float height, Vector3 origin, Vector3 direction, out Vector3 hit, out float distance)
		{
			hit = default(Vector3);
			distance = 0f;
			if (spec == null || spec.Kind < PieceKind.Wall || spec.Kind > PieceKind.Roof || !Finite(width) || !Finite(height) || width <= 0f || height <= 0f || !Finite(gridOrigin) || !Finite(origin) || !TryNormalize(direction, out direction))
			{
				return false;
			}
			Vector3 vector = gridOrigin + new Vector3((float)spec.Cell.X * width, (float)spec.Cell.Y * height, (float)spec.Cell.Z * width);
			Vector3 vector2 = new Vector3(width * 0.5f, 0f, width * 0.5f);
			if (!Finite(vector))
			{
				return false;
			}
			int num = (spec.Rotation % 4 + 4) % 4;
			Vector3 vector3 = Rotate(origin - vector - vector2, -num) + vector2;
			Vector3 vector4 = Rotate(direction, -num);
			if (!Finite(vector3))
			{
				return false;
			}
			float nearest = float.PositiveInfinity;
			if (spec.Kind == PieceKind.Wall)
			{
				if (!Plane(vector3, vector4, Vector3.UnitZ, out nearest))
				{
					return false;
				}
				Vector3 vector5 = vector3 + vector4 * nearest;
				if (!Inside(vector5.X, width) || !Inside(vector5.Y, height))
				{
					return false;
				}
			}
			else if (spec.Kind == PieceKind.Floor)
			{
				if (!Plane(vector3, vector4, Vector3.UnitY, out nearest))
				{
					return false;
				}
				Vector3 vector6 = vector3 + vector4 * nearest;
				if (!Inside(vector6.X, width) || !Inside(vector6.Z, width))
				{
					return false;
				}
			}
			else if (spec.Kind == PieceKind.Ramp)
			{
				TryNormalize(new Vector3(0f, width, 0f - height), out var normal);
				if (!Plane(vector3, vector4, normal, out nearest))
				{
					return false;
				}
				Vector3 vector7 = vector3 + vector4 * nearest;
				if (!Inside(vector7.X, width) || !Inside(vector7.Z, width))
				{
					return false;
				}
			}
			else
			{
				Vector3 zero = Vector3.Zero;
				Vector3 vector8 = new Vector3(width, 0f, 0f);
				Vector3 vector9 = new Vector3(width, 0f, width);
				Vector3 vector10 = new Vector3(0f, 0f, width);
				Vector3 c = new Vector3(width * 0.5f, height * 0.5f, width * 0.5f);
				TakeTriangle(vector3, vector4, zero, vector8, c, ref nearest);
				TakeTriangle(vector3, vector4, vector8, vector9, c, ref nearest);
				TakeTriangle(vector3, vector4, vector9, vector10, c, ref nearest);
				TakeTriangle(vector3, vector4, vector10, zero, c, ref nearest);
				if (!Finite(nearest))
				{
					return false;
				}
			}
			Vector3 vector11 = origin + direction * nearest;
			if (!Finite(vector11) || !Finite(nearest))
			{
				return false;
			}
			distance = nearest;
			hit = vector11;
			return true;
		}

		public static bool ContainsSurface(PieceSpec spec, Vector3 gridOrigin, float width, float height, Vector3 point, float tolerance = 0.06f)
		{
			if (Finite(tolerance) && tolerance >= 0f)
			{
				return DistanceToSurface(spec, gridOrigin, width, height, point) <= tolerance;
			}
			return false;
		}

		public static float DistanceToSurface(PieceSpec spec, Vector3 gridOrigin, float width, float height, Vector3 point)
		{
			if (spec == null || spec.Kind < PieceKind.Wall || spec.Kind > PieceKind.Roof || !Finite(gridOrigin) || !Finite(point) || !Finite(width) || !Finite(height) || width <= 0f || height <= 0f)
			{
				return float.PositiveInfinity;
			}
			Vector3 vector = gridOrigin + new Vector3((float)spec.Cell.X * width, (float)spec.Cell.Y * height, (float)spec.Cell.Z * width);
			Vector3 vector2 = new Vector3(width * 0.5f, 0f, width * 0.5f);
			if (!Finite(vector))
			{
				return float.PositiveInfinity;
			}
			Vector3 vector3 = Rotate(point - vector - vector2, -((spec.Rotation % 4 + 4) % 4)) + vector2;
			if (!Finite(vector3))
			{
				return float.PositiveInfinity;
			}
			Vector3 zero = Vector3.Zero;
			Vector3 vector4 = new Vector3(width, 0f, 0f);
			Vector3 vector5;
			Vector3 c;
			if (spec.Kind == PieceKind.Wall)
			{
				vector5 = new Vector3(width, height, 0f);
				c = new Vector3(0f, height, 0f);
			}
			else if (spec.Kind == PieceKind.Floor)
			{
				vector5 = new Vector3(width, 0f, width);
				c = new Vector3(0f, 0f, width);
			}
			else
			{
				if (spec.Kind != PieceKind.Ramp)
				{
					vector5 = new Vector3(width, 0f, width);
					c = new Vector3(0f, 0f, width);
					Vector3 c2 = new Vector3(width * 0.5f, height * 0.5f, width * 0.5f);
					return Math.Min(Math.Min(TriangleDistance(vector3, zero, vector4, c2), TriangleDistance(vector3, vector4, vector5, c2)), Math.Min(TriangleDistance(vector3, vector5, c, c2), TriangleDistance(vector3, c, zero, c2)));
				}
				vector5 = new Vector3(width, height, width);
				c = new Vector3(0f, height, width);
			}
			return Math.Min(TriangleDistance(vector3, zero, vector4, vector5), TriangleDistance(vector3, zero, vector5, c));
		}

		public static float TriangleDistance(Vector3 p, Vector3 a, Vector3 b, Vector3 c)
		{
			if (!Finite(p) || !Finite(a) || !Finite(b) || !Finite(c))
			{
				return float.PositiveInfinity;
			}
			Vector3 vector = b - a;
			Vector3 vector2 = c - a;
			Vector3 vector3 = p - a;
			if (!Finite(vector) || !Finite(vector2) || !Finite(vector3))
			{
				return float.PositiveInfinity;
			}
			double num = (double)vector.Y * (double)vector2.Z - (double)vector.Z * (double)vector2.Y;
			double num2 = (double)vector.Z * (double)vector2.X - (double)vector.X * (double)vector2.Z;
			double num3 = (double)vector.X * (double)vector2.Y - (double)vector.Y * (double)vector2.X;
			if (num * num + num2 * num2 + num3 * num3 <= 1E-24 * Math.Max(Dot(vector, vector) * Dot(vector2, vector2), 1E-40))
			{
				return Math.Min(SegmentDistance(p, a, b), Math.Min(SegmentDistance(p, b, c), SegmentDistance(p, c, a)));
			}
			double num4 = Dot(vector, vector3);
			double num5 = Dot(vector2, vector3);
			if (num4 <= 0.0 && num5 <= 0.0)
			{
				return Length(vector3);
			}
			Vector3 vector4 = p - b;
			double num6 = Dot(vector, vector4);
			double num7 = Dot(vector2, vector4);
			if (num6 >= 0.0 && num7 <= num6)
			{
				return Length(vector4);
			}
			double num8 = num4 * num7 - num6 * num5;
			if (num8 <= 0.0 && num4 >= 0.0 && num6 <= 0.0)
			{
				return Length(p - (a + vector * (float)(num4 / (num4 - num6))));
			}
			Vector3 vector5 = p - c;
			double num9 = Dot(vector, vector5);
			double num10 = Dot(vector2, vector5);
			if (num10 >= 0.0 && num9 <= num10)
			{
				return Length(vector5);
			}
			double num11 = num9 * num5 - num4 * num10;
			if (num11 <= 0.0 && num5 >= 0.0 && num10 <= 0.0)
			{
				return Length(p - (a + vector2 * (float)(num5 / (num5 - num10))));
			}
			double num12 = num6 * num10 - num9 * num7;
			if (num12 <= 0.0 && num7 - num6 >= 0.0 && num9 - num10 >= 0.0)
			{
				return Length(p - (b + (c - b) * (float)((num7 - num6) / (num7 - num6 + (num9 - num10)))));
			}
			double num13 = num12 + num11 + num8;
			if (num13 <= 0.0 || double.IsNaN(num13))
			{
				return float.PositiveInfinity;
			}
			return Length(p - (a + vector * (float)(num11 / num13) + vector2 * (float)(num8 / num13)));
		}

		private static float SegmentDistance(Vector3 p, Vector3 a, Vector3 b)
		{
			Vector3 vector = b - a;
			double num = Dot(vector, vector);
			if (num <= 0.0)
			{
				return Length(p - a);
			}
			float num2 = (float)Math.Max(0.0, Math.Min(1.0, Dot(p - a, vector) / num));
			return Length(p - (a + vector * num2));
		}

		private static float Length(Vector3 v)
		{
			if (!Finite(v))
			{
				return float.PositiveInfinity;
			}
			return (float)Math.Sqrt(Dot(v, v));
		}

		private static bool Plane(Vector3 origin, Vector3 direction, Vector3 normal, out float distance)
		{
			distance = 0f;
			double num = Dot(direction, normal);
			if (Math.Abs(num) < 1E-07)
			{
				return false;
			}
			double num2 = (0.0 - Dot(origin, normal)) / num;
			if (num2 < 0.0 || double.IsNaN(num2) || num2 > 3.4028234663852886E+38)
			{
				return false;
			}
			distance = (float)num2;
			return true;
		}

		private static void TakeTriangle(Vector3 origin, Vector3 direction, Vector3 a, Vector3 b, Vector3 c, ref float nearest)
		{
			double num = b.X - a.X;
			double num2 = b.Y - a.Y;
			double num3 = b.Z - a.Z;
			double num4 = c.X - a.X;
			double num5 = c.Y - a.Y;
			double num6 = c.Z - a.Z;
			double num7 = (double)direction.Y * num6 - (double)direction.Z * num5;
			double num8 = (double)direction.Z * num4 - (double)direction.X * num6;
			double num9 = (double)direction.X * num5 - (double)direction.Y * num4;
			double num10 = num * num7 + num2 * num8 + num3 * num9;
			double num11 = Math.Sqrt((num * num + num2 * num2 + num3 * num3) * (num4 * num4 + num5 * num5 + num6 * num6));
			if (num11 == 0.0 || Math.Abs(num10) < 1E-07 * num11)
			{
				return;
			}
			double num12 = origin.X - a.X;
			double num13 = origin.Y - a.Y;
			double num14 = origin.Z - a.Z;
			double num15 = (num12 * num7 + num13 * num8 + num14 * num9) / num10;
			if (num15 < -1E-06 || num15 > 1.000001)
			{
				return;
			}
			double num16 = num13 * num3 - num14 * num2;
			double num17 = num14 * num - num12 * num3;
			double num18 = num12 * num2 - num13 * num;
			double num19 = ((double)direction.X * num16 + (double)direction.Y * num17 + (double)direction.Z * num18) / num10;
			if (!(num19 < -1E-06) && !(num15 + num19 > 1.000001))
			{
				double num20 = (num4 * num16 + num5 * num17 + num6 * num18) / num10;
				if (num20 >= 0.0 && num20 < (double)nearest && num20 <= 3.4028234663852886E+38)
				{
					nearest = (float)num20;
				}
			}
		}

		private static bool Inside(float value, float extent)
		{
			if (Finite(value) && value >= -0.001f)
			{
				return value <= extent + 0.001f;
			}
			return false;
		}

		private static double Dot(Vector3 a, Vector3 b)
		{
			return (double)a.X * (double)b.X + (double)a.Y * (double)b.Y + (double)a.Z * (double)b.Z;
		}

		private static Vector3 Rotate(Vector3 value, int turns)
		{
			return ((turns % 4 + 4) % 4) switch
			{
				1 => new Vector3(value.Z, value.Y, 0f - value.X), 
				2 => new Vector3(0f - value.X, value.Y, 0f - value.Z), 
				3 => new Vector3(0f - value.Z, value.Y, value.X), 
				_ => value, 
			};
		}

		private static bool TryNormalize(Vector3 value, out Vector3 normal)
		{
			normal = default(Vector3);
			if (!Finite(value))
			{
				return false;
			}
			float num = Math.Max(Math.Abs(value.X), Math.Max(Math.Abs(value.Y), Math.Abs(value.Z)));
			if (num < 1E-10f)
			{
				return false;
			}
			value /= num;
			normal = value / value.Length();
			return Finite(normal);
		}

		private static bool Finite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}

		private static bool Finite(Vector3 value)
		{
			if (Finite(value.X) && Finite(value.Y))
			{
				return Finite(value.Z);
			}
			return false;
		}
	}
	public sealed class BuildBindingDefinition
	{
		public readonly string ActionName;

		public readonly string DisplayName;

		public readonly string DefaultPath;

		public readonly int ContextMask;

		public BuildBindingDefinition(string name, string label, string path, int context)
		{
			ActionName = name;
			DisplayName = label;
			DefaultPath = path;
			ContextMask = context;
		}
	}
	public static class BuildBindingCatalog
	{
		public const string MapName = "FortniteBuilding";

		public const string ToggleBuilder = "Fortnite_ToggleBuild";

		public const string Pickaxe = "Fortnite_Pickaxe";

		public const string PickaxeAlt = "Fortnite_PickaxeAlternate";

		public const string Camera = "Fortnite_Camera";

		public const string Wall = "Fortnite_Wall";

		public const string WallAlt = "Fortnite_WallAlternate";

		public const string Floor = "Fortnite_Floor";

		public const string FloorAlt = "Fortnite_FloorAlternate";

		public const string Ramp = "Fortnite_Ramp";

		public const string RampAlt = "Fortnite_RampAlternate";

		public const string Roof = "Fortnite_Roof";

		public const string RoofAlt = "Fortnite_RoofAlternate";

		public const string Place = "Fortnite_Place";

		public const string Swing = "Fortnite_Swing";

		public const string Edit = "Fortnite_Edit";

		public const string ConfirmEdit = "Fortnite_ConfirmEdit";

		public const string EditSelect = "Fortnite_EditSelect";

		public const string ResetEdit = "Fortnite_ResetEdit";

		public const string CancelEdit = "Fortnite_CancelEdit";

		public const string Rotate = "Fortnite_Rotate";

		public const string Material = "Fortnite_Material";

		public const string Repair = "Fortnite_Repair";

		public const string Remove = "Fortnite_Remove";

		public const string SimpleTraversal = "Fortnite_SimpleTraversal";

		public const string SimpleWall = "Fortnite_SimpleWall";

		public const string SimpleMaterial = "Fortnite_SimpleMaterial";

		public const int Outside = 1;

		public const int Build = 2;

		public const int Editing = 4;

		public const int PickaxeMode = 8;

		public const int SimpleBuild = 16;

		public const int BuildingModes = 18;

		public const int All = 31;

		private static readonly BuildBindingDefinition[] Items = new BuildBindingDefinition[26]
		{
			new BuildBindingDefinition("Fortnite_ToggleBuild", "Toggle build mode", "<Keyboard>/b", 31),
			new BuildBindingDefinition("Fortnite_Pickaxe", "Equip pickaxe", "<Keyboard>/5", 31),
			new BuildBindingDefinition("Fortnite_PickaxeAlternate", "Equip pickaxe (alternate)", "<Keyboard>/p", 31),
			new BuildBindingDefinition("Fortnite_Camera", "Toggle tool camera", "<Keyboard>/f5", 30),
			new BuildBindingDefinition("Fortnite_Wall", "Wall", "<Keyboard>/z", 2),
			new BuildBindingDefinition("Fortnite_WallAlternate", "Wall (alternate)", "<Keyboard>/1", 2),
			new BuildBindingDefinition("Fortnite_Floor", "Floor", "<Keyboard>/x", 2),
			new BuildBindingDefinition("Fortnite_FloorAlternate", "Floor (alternate)", "<Keyboard>/2", 2),
			new BuildBindingDefinition("Fortnite_Ramp", "Ramp", "<Keyboard>/c", 2),
			new BuildBindingDefinition("Fortnite_RampAlternate", "Ramp (alternate)", "<Keyboard>/3", 2),
			new BuildBindingDefinition("Fortnite_Roof", "Cone", "<Keyboard>/v", 2),
			new BuildBindingDefinition("Fortnite_RoofAlternate", "Cone (alternate)", "<Keyboard>/4", 2),
			new BuildBindingDefinition("Fortnite_Place", "Place structure", "<Mouse>/leftButton", 2),
			new BuildBindingDefinition("Fortnite_SimpleTraversal", "Place ramp or floor", "<Mouse>/leftButton", 16),
			new BuildBindingDefinition("Fortnite_SimpleWall", "Place wall", "<Mouse>/rightButton", 16),
			new BuildBindingDefinition("Fortnite_Swing", "Swing pickaxe", "<Mouse>/leftButton", 8),
			new BuildBindingDefinition("Fortnite_Edit", "Edit / confirm edit", "<Keyboard>/f", 31),
			new BuildBindingDefinition("Fortnite_ConfirmEdit", "Confirm edit (alternate)", "<Keyboard>/enter", 4),
			new BuildBindingDefinition("Fortnite_EditSelect", "Select edit cells", "<Mouse>/leftButton", 4),
			new BuildBindingDefinition("Fortnite_ResetEdit", "Reset edit", "<Keyboard>/r", 4),
			new BuildBindingDefinition("Fortnite_CancelEdit", "Cancel edit", "<Mouse>/rightButton", 4),
			new BuildBindingDefinition("Fortnite_Rotate", "Rotate structure", "<Keyboard>/r", 18),
			new BuildBindingDefinition("Fortnite_Material", "Change material", "<Keyboard>/m", 2),
			new BuildBindingDefinition("Fortnite_SimpleMaterial", "Change material", "<Keyboard>/v", 16),
			new BuildBindingDefinition("Fortnite_Repair", "Repair structure", "<Keyboard>/h", 18),
			new BuildBindingDefinition("Fortnite_Remove", "Remove structure (creative)", "<Keyboard>/delete", 18)
		};

		public static IReadOnlyList<BuildBindingDefinition> Definitions { get; } = Array.AsReadOnly(Items);

		public static Guid StableId(string kind, string name)
		{
			using SHA256 sHA = SHA256.Create();
			byte[] sourceArray = sHA.ComputeHash(Encoding.UTF8.GetBytes("ewan.peak.fortnitebuilding.bind.v1/" + kind + "/" + name));
			byte[] array = new byte[16];
			Array.Copy(sourceArray, array, 16);
			return new Guid(array);
		}

		public static BuildBindingDefinition Find(string name)
		{
			BuildBindingDefinition[] items = Items;
			foreach (BuildBindingDefinition buildBindingDefinition in items)
			{
				if (buildBindingDefinition.ActionName == name)
				{
					return buildBindingDefinition;
				}
			}
			return null;
		}

		public static bool IsVisible(BuildBindingDefinition action, bool simpleBuild)
		{
			int num = action.ContextMask & 0x12;
			if (num != 0)
			{
				return (num & (simpleBuild ? 16 : 2)) != 0;
			}
			return true;
		}

		public static bool Overlaps(string a, string b)
		{
			BuildBindingDefinition buildBindingDefinition = Find(a);
			BuildBindingDefinition buildBindingDefinition2 = Find(b);
			if (buildBindingDefinition != null && buildBindingDefinition2 != null)
			{
				return (buildBindingDefinition.ContextMask & buildBindingDefinition2.ContextMask) != 0;
			}
			return false;
		}
	}
	public sealed class BuildCommandAdmission
	{
		private sealed class Bucket
		{
			internal double Tokens = 16.0;

			internal double Time;
		}

		public const int PlacementBurstCapacity = 16;

		public const double PlacementTokensPerSecond = 200.0;

		public const double ActionIntervalSeconds = 0.07;

		private readonly Dictionary<int, Bucket> _placements = new Dictionary<int, Bucket>();

		private readonly Dictionary<int, double> _lastAction = new Dictionary<int, double>();

		public bool TryAdmitAtIngress(int actor, string operation, double receivedAt)
		{
			if (actor <= 0 || !Finite(receivedAt))
			{
				return false;
			}
			if (operation != "place")
			{
				return true;
			}
			if (!_placements.TryGetValue(actor, out var value))
			{
				value = new Bucket
				{
					Time = receivedAt
				};
				_placements.Add(actor, value);
			}
			if (receivedAt > value.Time)
			{
				value.Tokens = Math.Min(16.0, value.Tokens + (receivedAt - value.Time) * 200.0);
				value.Time = receivedAt;
			}
			if (value.Tokens + 1E-09 < 1.0)
			{
				return false;
			}
			value.Tokens = Math.Max(0.0, value.Tokens - 1.0);
			return true;
		}

		public bool TryAdmitAtExecution(int actor, string operation, double executionAt)
		{
			if (actor <= 0 || !Finite(executionAt))
			{
				return false;
			}
			if (operation == "place")
			{
				return true;
			}
			if (_lastAction.TryGetValue(actor, out var value) && executionAt - value + 1E-09 < 0.07)
			{
				return false;
			}
			_lastAction[actor] = executionAt;
			return true;
		}

		public void Clear()
		{
			_placements.Clear();
			_lastAction.Clear();
		}

		private static bool Finite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}
	}
	public enum PieceKind
	{
		Wall,
		Floor,
		Ramp,
		Roof
	}
	public enum BuildMaterial
	{
		Wood,
		Brick,
		Metal
	}
	[Serializable]
	public struct GridCell : IEquatable<GridCell>
	{
		public int X;

		public int Y;

		public int Z;

		public GridCell(int x, int y, int z)
		{
			X = x;
			Y = y;
			Z = z;
		}

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

		public override bool Equals(object value)
		{
			if (value is GridCell)
			{
				return Equals((GridCell)value);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return (((X * 397) ^ Y) * 397) ^ Z;
		}

		public override string ToString()
		{
			return X + "," + Y + "," + Z;
		}

		public static bool operator ==(GridCell a, GridCell b)
		{
			return a.Equals(b);
		}

		public static bool operator !=(GridCell a, GridCell b)
		{
			return !a.Equals(b);
		}
	}
	[Serializable]
	public sealed class PieceSpec
	{
		public GridCell Cell;

		public PieceKind Kind;

		public int Rotation;

		public BuildMaterial Material;

		public int EditMask;

		public bool Grounded;

		public bool TerrainFaceContact;

		public int EditCode;

		public PieceSpec()
		{
			EditMask = 511;
		}

		public PieceSpec(GridCell cell, PieceKind kind, int rotation, BuildMaterial material, int editMask = -1, bool grounded = false)
		{
			Cell = cell;
			Kind = kind;
			Rotation = rotation;
			Material = material;
			EditMask = ((editMask == -1) ? BuildRules.FullMask(kind) : editMask);
			Grounded = grounded;
		}

		public PieceSpec Copy()
		{
			return new PieceSpec(Cell, Kind, Rotation, Material, EditMask, Grounded)
			{
				EditCode = EditCode,
				TerrainFaceContact = TerrainFaceContact
			};
		}
	}
	[Serializable]
	public sealed class BuildPiece
	{
		public int Id;

		public int OwnerId;

		public int GeometryVersion;

		public PieceSpec Spec;

		public float Health;

		public float MaxHealth;

		public bool DoorOpen;

		public double ConstructionStartedAt;

		public float ConstructionDuration;

		public float ConstructionHealthBudget;

		public float ConstructionHealthGranted;

		public double ConstructionHealthRemainder;

		public float ConstructionProgress = 1f;

		public int ConstructionMask = -1;

		public int ConstructionCode;

		public double RepairStartedAt;

		public double RepairDuration;

		public double RepairHealthBudget;

		public double RepairBaseHealth;

		public double CollapseDueTime = -1.0;

		public int CollapseOrder = -1;

		public int DoorDirection = 1;

		public bool IsConstructing
		{
			get
			{
				if (ConstructionDuration > 0f)
				{
					return ConstructionProgress < 1f;
				}
				return false;
			}
		}

		public bool IsRepairing => RepairDuration > 0.0;

		public bool IsCollapsePending => CollapseDueTime >= 0.0;

		public double RepairProgress(double now)
		{
			if (!IsRepairing)
			{
				return 0.0;
			}
			return Math.Min(1.0, Math.Max(0.0, (now - RepairStartedAt) / RepairDuration));
		}

		public BuildPiece Copy()
		{
			return new BuildPiece
			{
				Id = Id,
				OwnerId = OwnerId,
				GeometryVersion = GeometryVersion,
				Spec = Spec.Copy(),
				Health = Health,
				MaxHealth = MaxHealth,
				DoorOpen = DoorOpen,
				DoorDirection = DoorDirection,
				ConstructionStartedAt = ConstructionStartedAt,
				ConstructionDuration = ConstructionDuration,
				ConstructionHealthBudget = ConstructionHealthBudget,
				ConstructionHealthGranted = ConstructionHealthGranted,
				ConstructionHealthRemainder = ConstructionHealthRemainder,
				ConstructionProgress = ConstructionProgress,
				ConstructionMask = ConstructionMask,
				ConstructionCode = ConstructionCode,
				RepairStartedAt = RepairStartedAt,
				RepairDuration = RepairDuration,
				RepairHealthBudget = RepairHealthBudget,
				RepairBaseHealth = RepairBaseHealth,
				CollapseDueTime = CollapseDueTime,
				CollapseOrder = CollapseOrder
			};
		}
	}
	[Serializable]
	public sealed class ResourceInventory
	{
		public int OwnerId;

		public int Wood;

		public int Brick;

		public int Metal;

		public int Get(BuildMaterial material)
		{
			return material switch
			{
				BuildMaterial.Brick => Brick, 
				BuildMaterial.Wood => Wood, 
				_ => Metal, 
			};
		}

		internal void Set(BuildMaterial material, int value)
		{
			switch (material)
			{
			case BuildMaterial.Wood:
				Wood = value;
				break;
			case BuildMaterial.Brick:
				Brick = value;
				break;
			default:
				Metal = value;
				break;
			}
		}

		public ResourceInventory Copy()
		{
			return new ResourceInventory
			{
				OwnerId = OwnerId,
				Wood = Wood,
				Brick = Brick,
				Metal = Metal
			};
		}
	}
	[Serializable]
	public sealed class WorldOptions
	{
		public int PlacementCost = 10;

		public int ResourceCap = 999;

		public int InitialResources = 999;

		public int MaxPieces = 1500;

		public int MaxPiecesPerPlayer = 750;

		public bool RequireSupport = true;

		public bool AllowTeamEditing = true;

		public bool AllowTeamDamage = true;

		public int RepairHealthPerResource = 10;

		public bool ProportionalRepairCost;

		public bool RefundOnRemove;

		public int MaxSupportDistance = 128;

		public bool TimedConstruction;

		public bool TimedRepair;

		public bool DeferredSupportCollapse;

		public float CollapseStepInterval = 0.4f;
	}
	[Serializable]
	public sealed class HarvestPatch
	{
		public string Key;

		public BuildMaterial Material;

		public int Used;

		public string TreeLocator;

		public int TreeDamage;

		public HarvestPatch Copy()
		{
			return new HarvestPatch
			{
				Key = Key,
				Material = Material,
				Used = Used,
				TreeLocator = TreeLocator,
				TreeDamage = TreeDamage
			};
		}
	}
	[Serializable]
	public sealed class WorldSnapshot
	{
		public int Version = 1;

		public int Revision;

		public int NextId = 1;

		public double Now;

		public BuildPiece[] Pieces = Array.Empty<BuildPiece>();

		public ResourceInventory[] Inventories = Array.Empty<ResourceInventory>();

		public HarvestPatch[] HarvestPatches = Array.Empty<HarvestPatch>();
	}
	public static class BuildRules
	{
		public static int FullMask(PieceKind kind)
		{
			if (kind != PieceKind.Wall)
			{
				return 15;
			}
			return 511;
		}

		public static float MaxHealth(PieceSpec spec)
		{
			if (!SourceLifecycleProfiles.TryGet(spec, out var profile))
			{
				return MaxHealth(spec.Material);
			}
			return profile.MaxHealth;
		}

		public static float MaxHealth(BuildMaterial material)
		{
			return material switch
			{
				BuildMaterial.Brick => 300f, 
				BuildMaterial.Wood => 150f, 
				_ => 500f, 
			};
		}

		public static bool ValidMask(PieceKind kind, int mask)
		{
			if (kind < PieceKind.Wall || kind > PieceKind.Roof)
			{
				return false;
			}
			if (mask > 0)
			{
				return (mask & ~FullMask(kind)) == 0;
			}
			return false;
		}

		public static bool ValidMaterial(BuildMaterial material)
		{
			if (material >= BuildMaterial.Wood)
			{
				return material <= BuildMaterial.Metal;
			}
			return false;
		}

		public static bool HasGroundContact(PieceSpec spec)
		{
			if (SourceSupportProfiles.TryHasGroundContact(spec, out var contact))
			{
				return contact;
			}
			if (spec.Kind == PieceKind.Wall)
			{
				return (spec.EditMask & 7) != 0;
			}
			if (spec.Kind == PieceKind.Ramp)
			{
				return (spec.EditMask & 3) != 0;
			}
			return spec.EditMask != 0;
		}
	}
	public sealed class BuildWorld
	{
		private readonly Dictionary<int, BuildPiece> _pieces = new Dictionary<int, BuildPiece>();

		private readonly Dictionary<int, ResourceInventory> _inventories = new Dictionary<int, ResourceInventory>();

		private readonly Dictionary<(PieceKind Kind, GridCell Cell, int WallAxis), int> _slots = new Dictionary<(PieceKind, GridCell, int), int>();

		private readonly Dictionary<GridCell, List<int>> _buckets = new Dictionary<GridCell, List<int>>();

		private readonly Dictionary<int, List<SupportGeometry.Segment>> _edges = new Dictionary<int, List<SupportGeometry.Segment>>();

		private Dictionary<int, int> _distances = new Dictionary<int, int>();

		private Dictionary<int, int> _previousDistances = new Dictionary<int, int>();

		private readonly Queue<int> _supportQueue = new Queue<int>();

		private bool _supportCacheValid;

		private int _supportDistanceLimit;

		private long _supportTopologyGeneration;

		private long _supportProfileGeneration;

		private readonly List<int> _removed = new List<int>();

		private int _nextId = 1;

		public const int HarvestPerHit = 10;

		public const int HarvestPatchCapacity = 100;

		public const int MaximumHarvestPatches = 2048;

		public const int TreeHealth = 300;

		public const int TreeHitDamage = 50;

		public const int TreeWoodPerHit = 6;

		public const int MaximumTreeLocatorLength = 2048;

		private readonly Dictionary<string, HarvestPatch> _harvestPatches = new Dictionary<string, HarvestPatch>(StringComparer.Ordinal);

		public double Now { get; private set; }

		public IReadOnlyDictionary<int, BuildPiece> Pieces => _pieces;

		public IReadOnlyDictionary<int, ResourceInventory> Inventories => _inventories;

		public WorldOptions Options { get; private set; }

		public int Revision { get; private set; }

		private int InitialResourceBalance => Math.Min(Options.InitialResources, Options.ResourceCap);

		public BuildWorld(WorldOptions options = null)
		{
			Options = options ?? new WorldOptions();
			if (Options.ResourceCap < 0 || Options.InitialResources < 0 || Options.PlacementCost < 0 || Options.MaxPieces < 1 || Options.MaxPiecesPerPlayer < 1 || Options.RepairHealthPerResource < 1 || Options.MaxSupportDistance < 1 || !Finite(Options.CollapseStepInterval) || Options.CollapseStepInterval <= 0f || Options.CollapseStepInterval > 300f)
			{
				throw new ArgumentException("Invalid building world options.", "options");
			}
		}

		public ResourceInventory EnsurePlayer(int ownerId)
		{
			if (ownerId <= 0)
			{
				throw new ArgumentOutOfRangeException("ownerId");
			}
			if (!_inventories.TryGetValue(ownerId, out var value))
			{
				int initialResourceBalance = InitialResourceBalance;
				value = new ResourceInventory
				{
					OwnerId = ownerId,
					Wood = initialResourceBalance,
					Brick = initialResourceBalance,
					Metal = initialResourceBalance
				};
				_inventories.Add(ownerId, value);
			}
			return value;
		}

		public int GrantResources(int ownerId, BuildMaterial material, int amount)
		{
			if (!BuildRules.ValidMaterial(material) || amount <= 0 || ownerId <= 0)
			{
				return 0;
			}
			ResourceInventory resourceInventory = EnsurePlayer(ownerId);
			int num = (int)Math.Min(amount, (long)Options.ResourceCap - (long)resourceInventory.Get(material));
			if (num > 0)
			{
				resourceInventory.Set(material, resourceInventory.Get(material) + num);
				Revision++;
			}
			return num;
		}

		public bool CanPlace(int ownerId, PieceSpec spec, out string reason)
		{
			if (ownerId <= 0)
			{
				return Fail("Invalid player.", out reason);
			}
			if (!ValidSpec(spec, out reason))
			{
				return false;
			}
			if (_pieces.Count >= Options.MaxPieces)
			{
				return Fail("World building limit reached.", out reason);
			}
			int maxPiecesPerPlayer = Options.MaxPiecesPerPlayer;
			if (_pieces.Count >= maxPiecesPerPlayer)
			{
				int num = 0;
				using (Dictionary<int, BuildPiece>.ValueCollection.Enumerator enumerator = _pieces.Values.GetEnumerator())
				{
					while (enumerator.MoveNext() && (enumerator.Current.OwnerId != ownerId || ++num < maxPiecesPerPlayer))
					{
					}
				}
				if (num >= maxPiecesPerPlayer)
				{
					return Fail("Your building limit is reached.", out reason);
				}
			}
			if (IsPlacementSlotOccupied(spec))
			{
				return Fail("A piece already occupies this slot.", out reason);
			}
			if (EnsurePlayer(ownerId).Get(spec.Material) < Options.PlacementCost)
			{
				return Fail("Not enough " + spec.Material.ToString().ToLowerInvariant() + ".", out reason);
			}
			if (Options.RequireSupport && !HasSupport(spec))
			{
				return Fail("Piece needs terrain or a connected supported structure.", out reason);
			}
			reason = null;
			return true;
		}

		public bool TryPlace(int ownerId, PieceSpec spec, out BuildPiece piece, out string reason)
		{
			piece = null;
			if (!CanPlace(ownerId, spec, out reason))
			{
				return false;
			}
			if (_nextId == int.MaxValue)
			{
				return Fail("Building identifier limit reached.", out reason);
			}
			piece = new BuildPiece
			{
				Id = _nextId++,
				OwnerId = ownerId,
				Spec = spec.Copy(),
				MaxHealth = BuildRules.MaxHealth(spec),
				Health = BuildRules.MaxHealth(spec)
			};
			if (Options.TimedConstruction && SourceLifecycleProfiles.TryGet(spec, out var profile) && profile.InitialHealthFraction.HasValue)
			{
				piece.ConstructionStartedAt = Now;
				piece.ConstructionDuration = profile.BuildTime;
				piece.ConstructionProgress = 0f;
				piece.ConstructionMask = spec.EditMask;
				piece.ConstructionCode = spec.EditCode;
				piece.Health = profile.MaxHealth * profile.InitialHealthFraction.Value;
				piece.ConstructionHealthBudget = profile.MaxHealth - piece.Health;
			}
			_pieces.Add(piece.Id, piece);
			Index(piece);
			ResourceInventory resourceInventory = EnsurePlayer(ownerId);
			resourceInventory.Set(spec.Material, resourceInventory.Get(spec.Material) - Options.PlacementCost);
			if (!TryAppendSupportDistance(piece))
			{
				RecomputeSupport();
			}
			Revision++;
			return true;
		}

		public bool TryEdit(int actorId, int pieceId, int editMask, out string reason)
		{
			return EditInternal(actorId, pieceId, editMask, null, null, null, out reason);
		}

		public bool TryEdit(int actorId, int pieceId, int editMask, bool grounded, out string reason, int editCode = 0, bool terrainFaceContact = false)
		{
			return EditInternal(actorId, pieceId, editMask, grounded, editCode, terrainFaceContact, out reason);
		}

		private bool EditInternal(int actorId, int pieceId, int editMask, bool? grounded, int? editCode, bool? terrainFaceContact, out string reason)
		{
			if (!Editable(actorId, pieceId, out var piece, out reason))
			{
				return false;
			}
			if (!BuildRules.ValidMask(piece.Spec.Kind, editMask))
			{
				return Fail("Keep at least one valid edit cell.", out reason);
			}
			bool flag = grounded ?? piece.Spec.Grounded;
			int num = editCode ?? piece.Spec.EditCode;
			if (num < 0 || num > 4095 || (piece.Spec.Kind != PieceKind.Ramp && num != 0))
			{
				return Fail("Invalid edit path.", out reason);
			}
			bool flag2 = piece.Spec.EditMask != editMask || piece.Spec.EditCode != num;
			bool flag3 = terrainFaceContact ?? (!flag2 && piece.Spec.TerrainFaceContact);
			if (!flag2 && piece.Spec.Grounded == flag && piece.Spec.TerrainFaceContact == flag3)
			{
				reason = null;
				return true;
			}
			if (flag2 && piece.GeometryVersion == int.MaxValue)
			{
				return Fail("Structure shape revision limit reached.", out reason);
			}
			if (flag2)
			{
				piece.GeometryVersion++;
				piece.DoorOpen = false;
			}
			piece.Spec.EditMask = editMask;
			piece.Spec.Grounded = flag;
			piece.Spec.TerrainFaceContact = flag3;
			piece.Spec.EditCode = num;
			piece.MaxHealth = BuildRules.MaxHealth(piece.Spec);
			if ((double)piece.Health + piece.ConstructionHealthRemainder > (double)piece.MaxHealth)
			{
				piece.Health = piece.MaxHealth;
				piece.ConstructionHealthRemainder = 0.0;
			}
			if (piece.IsRepairing && piece.Health == piece.MaxHealth)
			{
				ClearRepair(piece);
			}
			_edges[piece.Id] = SupportGeometry.Edges(piece.Spec);
			RecomputeSupport();
			Revision++;
			reason = null;
			return true;
		}

		public bool TrySetDoor(int actorId, int pieceId, bool open, int direction, out string reason)
		{
			if (!Editable(actorId, pieceId, out var piece, out reason))
			{
				return false;
			}
			if (piece.Spec.Kind != PieceKind.Wall || (direction != -1 && direction != 1))
			{
				return Fail("Invalid door state.", out reason);
			}
			if (piece.DoorOpen == open && piece.DoorDirection == direction)
			{
				reason = null;
				return true;
			}
			piece.DoorOpen = open;
			piece.DoorDirection = direction;
			Revision++;
			reason = null;
			return true;
		}

		public int RepairQuote(int actorId, int pieceId)
		{
			if (!Editable(actorId, pieceId, out var piece, out var _) || piece.IsRepairing)
			{
				return 0;
			}
			double num = (double)piece.MaxHealth - (double)piece.Health;
			if (!(num > 0.0))
			{
				return 0;
			}
			return (int)Math.Min(2147483647.0, RepairPrice(piece, num));
		}

		public (int FullCost, int Spend) RepairOffer(int actorId, int pieceId)
		{
			if (!Editable(actorId, pieceId, out var piece, out var _) || piece.IsRepairing)
			{
				return default((int, int));
			}
			double num = (double)piece.MaxHealth - (double)piece.Health;
			if (!(num > 0.0) || !TryGetRepairCeiling(piece, out var _))
			{
				return default((int, int));
			}
			int payer = ((actorId == 0) ? piece.OwnerId : actorId);
			var (val, item) = AffordableRepair(piece, num, ResourceBalance(payer, piece.Spec.Material));
			return (FullCost: (int)Math.Min(2147483647.0, val), Spend: item);
		}

		private int ResourceBalance(int payer, BuildMaterial material)
		{
			if (!_inventories.TryGetValue(payer, out var value))
			{
				return InitialResourceBalance;
			}
			return value.Get(material);
		}

		private (double FullCost, int Spend) AffordableRepair(BuildPiece piece, double missing, int balance)
		{
			double num = RepairPrice(piece, missing);
			return (FullCost: num, Spend: (int)Math.Min(num, balance));
		}

		private double RepairPrice(BuildPiece piece, double missing)
		{
			if (!Options.ProportionalRepairCost)
			{
				return Math.Ceiling(missing / (double)Options.RepairHealthPerResource);
			}
			return Math.Max(1.0, Math.Floor(missing / (double)piece.MaxHealth * (double)Options.PlacementCost * 0.75));
		}

		public bool TryRepair(int actorId, int pieceId, out string reason)
		{
			if (!Editable(actorId, pieceId, out var piece, out reason))
			{
				return false;
			}
			if (piece.IsRepairing)
			{
				return Fail("Piece is already being repaired.", out reason);
			}
			if (!TryGetRepairCeiling(piece, out var builtCeiling))
			{
				return Fail("Construction source profile unavailable.", out reason);
			}
			double num = (double)piece.MaxHealth - (double)piece.Health;
			if (num <= 0.0)
			{
				return Fail("Piece is already fully repaired.", out reason);
			}
			int num2 = ((actorId == 0) ? piece.OwnerId : actorId);
			int num3 = ResourceBalance(num2, piece.Spec.Material);
			var (num4, num5) = AffordableRepair(piece, num, num3);
			if (num5 == 0)
			{
				return Fail("Not enough material to repair.", out reason);
			}
			EnsurePlayer(num2).Set(piece.Spec.Material, num3 - num5);
			double num6 = (Options.ProportionalRepairCost ? (num * ((double)num5 / num4)) : Math.Min(num, (double)num5 * (double)Options.RepairHealthPerResource));
			if (Options.TimedRepair && !piece.IsConstructing && SourceLifecycleProfiles.TryGet(piece.Spec, out var profile))
			{
				piece.RepairStartedAt = Now;
				piece.RepairDuration = (double)profile.RepairTime * num6 / (double)piece.MaxHealth;
				piece.RepairHealthBudget = num6;
				piece.RepairBaseHealth = piece.Health;
				piece.ConstructionHealthRemainder = 0.0;
				Revision++;
				reason = null;
				return true;
			}
			float num7 = (float)num6;
			float num8 = Math.Max(0f, num7 - Math.Max(0f, builtCeiling - piece.Health));
			piece.ConstructionHealthGranted = Math.Min(piece.ConstructionHealthBudget, piece.ConstructionHealthGranted + num8);
			piece.Health = Math.Min(piece.MaxHealth, piece.Health + num7);
			piece.ConstructionHealthRemainder = 0.0;
			Revision++;
			reason = null;
			return true;
		}

		private static bool TryGetRepairCeiling(BuildPiece piece, out float builtCeiling)
		{
			builtCeiling = piece.MaxHealth;
			if (piece.ConstructionDuration <= 0f)
			{
				return true;
			}
			PieceSpec pieceSpec = piece.Spec;
			if (pieceSpec.EditMask != piece.ConstructionMask || pieceSpec.EditCode != piece.ConstructionCode)
			{
				pieceSpec = pieceSpec.Copy();
				pieceSpec.EditMask = piece.ConstructionMask;
				pieceSpec.EditCode = piece.ConstructionCode;
			}
			if (!SourceLifecycleProfiles.TryGet(pieceSpec, out var profile))
			{
				return false;
			}
			builtCeiling = Math.Min(piece.MaxHealth, profile.MaxHealth - piece.ConstructionHealthBudget + piece.ConstructionHealthGranted);
			return true;
		}

		public bool TryDamage(int actorId, int pieceId, float damage, out string reason)
		{
			if (!_pieces.TryGetValue(pieceId, out var value))
			{
				return Fail("Piece no longer exists.", out reason);
			}
			if (actorId < 0 || (actorId != 0 && actorId != value.OwnerId && !Options.AllowTeamDamage))
			{
				return Fail("You cannot damage this player's structure.", out reason);
			}
			if (float.IsNaN(damage) || float.IsInfinity(damage) || damage <= 0f)
			{
				return Fail("Invalid damage.", out reason);
			}
			value.Health = Math.Max(0f, value.Health - damage);
			value.ConstructionHealthRemainder = 0.0;
			if (value.Health == 0f)
			{
				RemoveInternal(pieceId);
				RecomputeSupport();
			}
			else if (value.IsRepairing)
			{
				value.RepairBaseHealth = (double)value.Health - value.RepairHealthBudget * value.RepairProgress(Now);
			}
			Revision++;
			reason = null;
			return true;
		}

		public bool TryRemove(int actorId, int pieceId, out string reason)
		{
			if (!Editable(actorId, pieceId, out var piece, out reason))
			{
				return false;
			}
			if (Options.RefundOnRemove)
			{
				GrantResources(piece.OwnerId, piece.Spec.Material, Options.PlacementCost);
			}
			RemoveInternal(pieceId);
			RecomputeSupport();
			Revision++;
			reason = null;
			return true;
		}

		public int[] DrainRemovedIds()
		{
			int[] result = _removed.ToArray();
			_removed.Clear();
			return result;
		}

		public void Clear()
		{
			foreach (int item in _pieces.Keys.OrderBy((int id) => id))
			{
				_removed.Add(item);
			}
			_pieces.Clear();
			_inventories.Clear();
			_slots.Clear();
			_buckets.Clear();
			_edges.Clear();
			_distances.Clear();
			_supportCacheValid = false;
			_harvestPatches.Clear();
			_nextId = 1;
			Revision++;
		}

		public WorldSnapshot Snapshot()
		{
			return new WorldSnapshot
			{
				Revision = Revision,
				NextId = _nextId,
				Now = Now,
				Pieces = (from p in _pieces.Values
					orderby p.Id
					select p.Copy()).ToArray(),
				Inventories = (from p in _inventories.Values
					orderby p.OwnerId
					select p.Copy()).ToArray(),
				HarvestPatches = HarvestSnapshot()
			};
		}

		public bool ApplySnapshot(WorldSnapshot snapshot, out string reason)
		{
			if (snapshot == null || snapshot.Version != 1 || snapshot.Revision < 0 || snapshot.NextId < 1 || snapshot.Pieces == null || snapshot.Inventories == null || !ValidTime(snapshot.Now) || snapshot.Now < Now)
			{
				return Fail("Invalid building snapshot header.", out reason);
			}
			if (snapshot.Pieces.Length > Options.MaxPieces || snapshot.Inventories.Length > 256)
			{
				return Fail("Snapshot exceeds limits.", out reason);
			}
			Dictionary<int, BuildPiece> dictionary = new Dictionary<int, BuildPiece>();
			HashSet<(PieceKind, GridCell, int)> hashSet = new HashSet<(PieceKind, GridCell, int)>();
			Dictionary<int, ResourceInventory> inventories = new Dictionary<int, ResourceInventory>();
			if (!ValidateHarvestSnapshot(snapshot.HarvestPatches, out var patches, out reason))
			{
				return false;
			}
			BuildPiece[] pieces = snapshot.Pieces;
			foreach (BuildPiece buildPiece in pieces)
			{
				if (buildPiece == null || buildPiece.Id < 1 || buildPiece.Id >= snapshot.NextId || buildPiece.OwnerId < 1 || buildPiece.GeometryVersion < 0 || !ValidSpec(buildPiece.Spec, out reason) || !Finite(buildPiece.Health) || !Finite(buildPiece.MaxHealth) || buildPiece.Health <= 0f || buildPiece.MaxHealth != BuildRules.MaxHealth(buildPiece.Spec) || buildPiece.Health > buildPiece.MaxHealth)
				{
					return Fail("Invalid piece in snapshot.", out reason);
				}
				if (!ValidLifecycle(buildPiece, snapshot.Now, out reason))
				{
					return false;
				}
				if ((buildPiece.DoorDirection != -1 && buildPiece.DoorDirection != 1) || (buildPiece.DoorOpen && buildPiece.Spec.Kind != PieceKind.Wall))
				{
					return Fail("Invalid snapshot door state.", out reason);
				}
				if (dictionary.ContainsKey(buildPiece.Id) || !hashSet.Add(SupportGeometry.SlotKey(buildPiece.Spec)))
				{
					return Fail("Duplicate piece in snapshot.", out reason);
				}
				dictionary.Add(buildPiece.Id, buildPiece.Copy());
			}
			ResourceInventory[] inventories2 = snapshot.Inventories;
			foreach (ResourceInventory resourceInventory in inventories2)
			{
				if (resourceInventory == null || resourceInventory.OwnerId < 1 || inventories.ContainsKey(resourceInventory.OwnerId) || !ValidResource(resourceInventory.Wood) || !ValidResource(resourceInventory.Brick) || !ValidResource(resourceInventory.Metal))
				{
					return Fail("Invalid inventory in snapshot.", out reason);
				}
				inventories.Add(resourceInventory.OwnerId, resourceInventory.Copy());
			}
			if (dictionary.Values.Any((BuildPiece p) => !inventories.ContainsKey(p.OwnerId)))
			{
				return Fail("Piece owner inventory missing from snapshot.", out reason);
			}
			BuildWorld candidate = new BuildWorld(Options);
			foreach (KeyValuePair<int, BuildPiece> item in dictionary)
			{
				candidate._pieces.Add(item.Key, item.Value);
				candidate.Index(item.Value);
			}
			candidate.ComputeDistances();
			BuildPiece[] array = (from p in dictionary.Values
				where p.IsCollapsePending
				orderby p.CollapseOrder
				select p).ToArray();
			if (array.Length != 0 && (!Options.RequireSupport || !Options.DeferredSupportCollapse))
			{
				return Fail("Support collapse is disabled for this snapshot.", out reason);
			}
			double num = -1.0;
			for (int num2 = 0; num2 < array.Length; num2++)
			{
				if (array[num2].CollapseOrder != num2 || array[num2].CollapseDueTime < num || candidate._distances.ContainsKey(array[num2].Id))
				{
					return Fail("Invalid collapse queue in snapshot.", out reason);
				}
				num = array[num2].CollapseDueTime;
			}
			if (Options.RequireSupport && dictionary.Values.Any((BuildPiece p) => !candidate._distances.ContainsKey(p.Id) && !p.IsCollapsePending))
			{
				return Fail(Options.DeferredSupportCollapse ? "Unsupported snapshot piece has no collapse deadline." : "Unsupported snapshot piece.", out reason);
			}
			_pieces.Clear();
			_inventories.Clear();
			_slots.Clear();
			_buckets.Clear();
			_edges.Clear();
			_distances.Clear();
			_removed.Clear();
			foreach (KeyValuePair<int, BuildPiece> item2 in dictionary)
			{
				_pieces.Add(item2.Key, item2.Value);
				Index(item2.Value);
			}
			foreach (KeyValuePair<int, ResourceInventory> item3 in inventories)
			{
				_inventories.Add(item3.Key, item3.Value);
			}
			_harvestPatches.Clear();
			foreach (KeyValuePair<string, HarvestPatch> item4 in patches)
			{
				_harvestPatches.Add(item4.Key, item4.Value);
			}
			_nextId = snapshot.NextId;
			Revision = snapshot.Revision;
			Now = snapshot.Now;
			ComputeDistances();
			reason = null;
			return true;
		}

		public bool AdvanceTime(double now)
		{
			string reason;
			return AdvanceTime(now, out reason);
		}

		public bool AdvanceTime(double now, out string reason)
		{
			if (!ValidTime(now) || now < Now)
			{
				return Fail("Building time must be finite and monotonic.", out reason);
			}
			Now = now;
			bool flag = false;
			List<BuildPiece> list = null;
			foreach (BuildPiece value in _pieces.Values)
			{
				if (value.IsCollapsePending && value.CollapseDueTime <= Now)
				{
					(list ?? (list = new List<BuildPiece>())).Add(value);
				}
				if (value.IsRepairing)
				{
					flag |= AdvanceRepair(value);
				}
				if (value.IsConstructing)
				{
					float num = (float)Math.Min(1.0, Math.Max(value.ConstructionProgress, (Now - value.ConstructionStartedAt) / (double)value.ConstructionDuration));
					if (!(num <= value.ConstructionProgress))
					{
						float num2 = value.ConstructionHealthBudget * num;
						double addition = Math.Max(0.0, (double)num2 - (double)value.ConstructionHealthGranted);
						value.ConstructionHealthGranted = Math.Max(value.ConstructionHealthGranted, num2);
						value.ConstructionProgress = num;
						CreditConstructionHealth(value, addition);
						flag = true;
					}
				}
			}
			if (list != null)
			{
				list.Sort((BuildPiece a, BuildPiece b) => (a.CollapseDueTime, a.CollapseOrder, a.Id).CompareTo((b.CollapseDueTime, b.CollapseOrder, b.Id)));
				foreach (BuildPiece item in list)
				{
					RemoveInternal(item.Id);
				}
				RecomputeSupport();
				flag = true;
			}
			if (flag)
			{
				Revision++;
			}
			reason = null;
			return true;
		}

		private bool AdvanceRepair(BuildPiece piece)
		{
			float health = piece.Health;
			double num = piece.RepairProgress(Now);
			piece.Health = (float)Math.Min(piece.MaxHealth, piece.RepairBaseHealth + num * piece.RepairHealthBudget);
			if (num == 1.0 || piece.Health == piece.MaxHealth)
			{
				ClearRepair(piece);
				return true;
			}
			return piece.Health != health;
		}

		private static void ClearRepair(BuildPiece piece)
		{
			piece.RepairStartedAt = 0.0;
			piece.RepairDuration = 0.0;
			piece.RepairHealthBudget = 0.0;
			piece.RepairBaseHealth = 0.0;
		}

		private static bool ValidRepair(BuildPiece piece, double now)
		{
			if (piece.RepairDuration == 0.0)
			{
				if (piece.RepairStartedAt == 0.0 && piece.RepairHealthBudget == 0.0)
				{
					return piece.RepairBaseHealth == 0.0;
				}
				return false;
			}
			if (!ValidTime(piece.RepairStartedAt) || piece.RepairStartedAt > now || !Finite(piece.RepairDuration) || piece.RepairDuration < 0.0 || !Finite(piece.RepairHealthBudget) || piece.RepairHealthBudget <= 0.0 || piece.RepairHealthBudget > 3.4028234663852886E+38 || !Finite(piece.RepairBaseHealth) || piece.IsConstructing || piece.ConstructionHealthRemainder != 0.0)
			{
				return false;
			}
			double num = piece.RepairProgress(now);
			if (num < 1.0 && piece.Health < piece.MaxHealth)
			{
				return (float)(piece.RepairBaseHealth + num * piece.RepairHealthBudget) == piece.Health;
			}
			return false;
		}

		private static void CreditConstructionHealth(BuildPiece piece, double addition)
		{
			double num = (double)piece.Health + piece.ConstructionHealthRemainder + addition;
			if (num >= (double)piece.MaxHealth)
			{
				piece.Health = piece.MaxHealth;
				piece.ConstructionHealthRemainder = 0.0;
			}
			else
			{
				piece.Health = (float)num;
				piece.ConstructionHealthRemainder = num - (double)piece.Health;
			}
		}

		private static bool ValidConstructionRemainder(BuildPiece piece)
		{
			double constructionHealthRemainder = piece.ConstructionHealthRemainder;
			if (!Finite(constructionHealthRemainder))
			{
				return false;
			}
			if (constructionHealthRemainder == 0.0)
			{
				return true;
			}
			double num = (double)piece.Health + constructionHealthRemainder;
			if (num <= 0.0 || num > (double)piece.MaxHealth)
			{
				return false;
			}
			float num2 = BitConverter.Int32BitsToSingle(BitConverter.SingleToInt32Bits(piece.Health) + ((constructionHealthRemainder > 0.0) ? 1 : (-1)));
			if (Finite(num2))
			{
				return Math.Abs(constructionHealthRemainder) <= Math.Abs((double)num2 - (double)piece.Health) * 0.5;
			}
			return false;
		}

		private bool ValidLifecycle(BuildPiece piece, double now, out string reason)
		{
			if (!ValidRepair(piece, now))
			{
				return Fail("Invalid repair state in snapshot.", out reason);
			}
			if (!Finite(piece.ConstructionProgress) || piece.ConstructionProgress < 0f || piece.ConstructionProgress > 1f || !Finite(piece.ConstructionDuration) || piece.ConstructionDuration < 0f || !Finite(piece.ConstructionHealthBudget) || piece.ConstructionHealthBudget < 0f || !Finite(piece.ConstructionHealthGranted) || piece.ConstructionHealthGranted < 0f || piece.ConstructionHealthGranted > piece.ConstructionHealthBudget + 0.0001f || !ValidConstructionRemainder(piece) || !ValidTime(piece.ConstructionStartedAt) || piece.ConstructionStartedAt > now)
			{
				return Fail("Invalid construction state in snapshot.", out reason);
			}
			if (piece.ConstructionDuration == 0f)
			{
				if (piece.ConstructionStartedAt != 0.0 || piece.ConstructionProgress != 1f || piece.ConstructionHealthBudget != 0f || piece.ConstructionHealthGranted != 0f || piece.ConstructionHealthRemainder != 0.0 || piece.ConstructionMask != -1 || piece.ConstructionCode != 0)
				{
					return Fail("Invalid legacy construction state.", out reason);
				}
			}
			else
			{
				PieceSpec pieceSpec = piece.Spec.Copy();
				pieceSpec.EditMask = piece.ConstructionMask;
				pieceSpec.EditCode = piece.ConstructionCode;
				if (!ValidSpec(pieceSpec, out var _) || !SourceLifecycleProfiles.TryGet(pieceSpec, out var profile) || !profile.InitialHealthFraction.HasValue || piece.ConstructionDuration != profile.BuildTime || Math.Abs(piece.ConstructionHealthBudget - profile.MaxHealth * (1f - profile.InitialHealthFraction.Value)) > 0.0001f)
				{
					return Fail("Construction source profile or frozen budget mismatch.", out reason);
				}
				float num = (float)Math.Min(1.0, Math.Max(0.0, (now - piece.ConstructionStartedAt) / (double)piece.ConstructionDuration));
				if (Math.Abs(piece.ConstructionProgress - num) > 0.0001f || piece.ConstructionHealthGranted + 0.0001f < piece.ConstructionHealthBudget * piece.ConstructionProgress)
				{
					return Fail("Construction progress or consumed health pool disagrees with snapshot time.", out reason);
				}
			}
			if (piece.CollapseDueTime == -1.0)
			{
				if (piece.CollapseOrder != -1)
				{
					return Fail("Invalid inactive collapse order.", out reason);
				}
			}
			else if (!ValidTime(piece.CollapseDueTime) || piece.CollapseOrder < 0 || piece.CollapseOrder >= Options.MaxPieces)
			{
				return Fail("Invalid pending collapse state.", out reason);
			}
			reason = null;
			return true;
		}

		private static bool ValidTime(double value)
		{
			if (Finite(value) && value >= 0.0)
			{
				return value <= 1000000000000.0;
			}
			return false;
		}

		private bool ValidResource(int value)
		{
			if (value >= 0)
			{
				return value <= Options.ResourceCap;
			}
			return false;
		}

		private static bool Finite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}

		private static bool Finite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}

		private static bool Fail(string message, out string reason)
		{
			reason = message;
			return false;
		}

		private static bool ValidSpec(PieceSpec spec, out string reason)
		{
			if (spec == null || !BuildRules.ValidMask(spec.Kind, spec.EditMask) || !BuildRules.ValidMaterial(spec.Material) || spec.Rotation < 0 || spec.Rotation > 3)
			{
				return Fail("Invalid building piece.", out reason);
			}
			if (spec.EditCode < 0 || spec.EditCode > 4095 || (spec.Kind != PieceKind.Ramp && spec.EditCode != 0))
			{
				return Fail("Invalid edit path.", out reason);
			}
			if (Math.Abs((long)spec.Cell.X) > 100000 || Math.Abs((long)spec.Cell.Y) > 100000 || Math.Abs((long)spec.Cell.Z) > 100000)
			{
				return Fail("Building position is outside world limits.", out reason);
			}
			reason = null;
			return true;
		}

		public bool CanEdit(int actorId, int pieceId, out string reason)
		{
			BuildPiece piece;
			return Editable(actorId, pieceId, out piece, out reason);
		}

		private bool Editable(int actorId, int pieceId, out BuildPiece piece, out string reason)
		{
			if (!_pieces.TryGetValue(pieceId, out piece))
			{
				return Fail("Piece no longer exists.", out reason);
			}
			if (actorId < 0 || (actorId != 0 && piece.OwnerId != actorId && !Options.AllowTeamEditing))
			{
				return Fail("You cannot edit this player's structure.", out reason);
			}
			reason = null;
			return true;
		}

		internal bool IsPlacementSlotOccupied(PieceSpec spec)
		{
			return _slots.ContainsKey(SupportGeometry.SlotKey(spec));
		}

		internal bool TryGetPieceInSlot(PieceSpec spec, out BuildPiece piece)
		{
			piece = null;
			if (_slots.TryGetValue(SupportGeometry.SlotKey(spec), out var value))
			{
				return _pieces.TryGetValue(value, out piece);
			}
			return false;
		}

		private void Index(BuildPiece piece)
		{
			_slots.Add(SupportGeometry.SlotKey(piece.Spec), piece.Id);
			if (!_buckets.TryGetValue(piece.Spec.Cell, out var value))
			{
				value = new List<int>();
				_buckets.Add(piece.Spec.Cell, value);
			}
			value.Add(piece.Id);
			_edges.Add(piece.Id, SupportGeometry.Edges(piece.Spec));
		}

		private IEnumerable<int> Neighbors(GridCell cell)
		{
			for (int y = -1; y <= 1; y++)
			{
				for (int x = -1; x <= 1; x++)
				{
					for (int z = -1; z <= 1; z++)
					{
						if (_buckets.TryGetValue(new GridCell(cell.X + x, cell.Y + y, cell.Z + z), out var bucket))
						{
							for (int i = 0; i < bucket.Count; i++)
							{
								yield return bucket[i];
							}
						}
						bucket = null;
					}
				}
			}
		}

		private bool HasSupport(PieceSpec spec)
		{
			if (IsTerrainRoot(spec))
			{
				return true;
			}
			List<SupportGeometry.Segment> a = SupportGeometry.Edges(spec);
			foreach (int item in Neighbors(spec.Cell))
			{
				if (!_pieces[item].IsCollapsePending && _distances.TryGetValue(item, out var value) && value < Options.MaxSupportDistance && (SupportGeometry.Connected(a, _edges[item]) || SourceTopologyCentres.Connected(spec, _pieces[item].Spec)))
				{
					return true;
				}
			}
			return false;
		}

		private bool Connected(int a, int b)
		{
			if (!SupportGeometry.Connected(_edges[a], _edges[b]))
			{
				return SourceTopologyCentres.Connected(_pieces[a].Spec, _pieces[b].Spec);
			}
			return true;
		}

		private static bool IsTerrainRoot(PieceSpec spec)
		{
			if (!spec.TerrainFaceContact)
			{
				if (spec.Grounded)
				{
					return BuildRules.HasGroundContact(spec);
				}
				return false;
			}
			return true;
		}

		private bool TryAppendSupportDistance(BuildPiece piece)
		{
			if (!_supportCacheValid || _supportDistanceLimit != Options.MaxSupportDistance || _supportTopologyGeneration != SourceTopologyCentres.Generation || _supportProfileGeneration != SourceSupportProfiles.Generation || _distances.Count != _pieces.Count - 1)
			{
				return false;
			}
			int num = ((!IsTerrainRoot(piece.Spec)) ? int.MaxValue : 0);
			int num2 = -1;
			foreach (int item in Neighbors(piece.Spec.Cell))
			{
				if (item != piece.Id && Connected(piece.Id, item))
				{
					if (!_distances.TryGetValue(item, out var value))
					{
						return false;
					}
					num2 = Math.Max(num2, value);
					if (value < Options.MaxSupportDistance)
					{
						num = Math.Min(num, value + 1);
					}
				}
			}
			if (num == int.MaxValue || num2 > (long)num + 1L)
			{
				return false;
			}
			_distances.Add(piece.Id, num);
			return true;
		}

		private void ComputeDistances()
		{
			_supportCacheValid = false;
			_distances.Clear();
			foreach (BuildPiece value in _pieces.Values)
			{
				if (IsTerrainRoot(value.Spec))
				{
					_distances.Add(value.Id, 0);
				}
			}
			if (_distances.Count != _pieces.Count && _distances.Count != 0)
			{
				_supportQueue.Clear();
				foreach (int key in _distances.Keys)
				{
					_supportQueue.Enqueue(key);
				}
				while (_supportQueue.Count > 0 && _distances.Count < _pieces.Count)
				{
					int num = _supportQueue.Dequeue();
					int num2 = _distances[num];
					if (num2 >= Options.MaxSupportDistance)
					{
						continue;
					}
					foreach (int item in Neighbors(_pieces[num].Spec.Cell))
					{
						if (!_distances.ContainsKey(item) && Connected(num, item))
						{
							_distances.Add(item, num2 + 1);
							_supportQueue.Enqueue(item);
						}
					}
				}
			}
			_supportDistanceLimit = Options.MaxSupportDistance;
			_supportTopologyGeneration = SourceTopologyCentres.Generation;
			_supportProfileGeneration = SourceSupportProfiles.Generation;
			_supportCacheValid = true;
		}

		private void RecomputeSupport()
		{
			Dictionary<int, int> prior = _distances;
			_distances = _previousDistances;
			_previousDistances = prior;
			ComputeDistances();
			foreach (BuildPiece value2 in _pieces.Values)
			{
				if (!Options.RequireSupport || _distances.ContainsKey(value2.Id))
				{
					value2.CollapseDueTime = -1.0;
					value2.CollapseOrder = -1;
				}
			}
			if (!Options.RequireSupport || _distances.Count == _pieces.Count)
			{
				return;
			}
			BuildPiece[] array = _pieces.Values.Where((BuildPiece piece) => !piece.IsCollapsePending && !_distances.ContainsKey(piece.Id)).ToArray();
			if (!Options.DeferredSupportCollapse)
			{
				foreach (BuildPiece item in array.OrderBy((BuildPiece piece) => piece.Id))
				{
					RemoveInternal(item.Id);
				}
				return;
			}
			if (array.Length != 0)
			{
				int num = ((IEnumerable<BuildPiece>)array).Min((Func<BuildPiece, int>)PriorDepth);
				BuildPiece[] array2 = array;
				foreach (BuildPiece buildPiece in array2)
				{
					buildPiece.CollapseDueTime = Now + (double)(PriorDepth(buildPiece) - num + 1) * (double)Options.CollapseStepInterval;
				}
			}
			int num3 = 0;
			foreach (BuildPiece item2 in from piece in _pieces.Values
				where piece.IsCollapsePending
				orderby piece.CollapseDueTime, piece.Id
				select piece)
			{
				item2.CollapseOrder = num3++;
			}
			int PriorDepth(BuildPiece piece)
			{
				if (!prior.TryGetValue(piece.Id, out var value))
				{
					return 0;
				}
				return value;
			}
		}

		private void RemoveInternal(int id)
		{
			if (_pieces.TryGetValue(id, out var value))
			{
				_pieces.Remove(id);
				_slots.Remove(SupportGeometry.SlotKey(value.Spec));
				_edges.Remove(id);
				_distances.Remove(id);
				List<int> list = _buckets[value.Spec.Cell];
				list.Remove(id);
				if (list.Count == 0)
				{
					_buckets.Remove(value.Spec.Cell);
				}
				_removed.Add(id);
			}
		}

		public HarvestPatch[] HarvestSnapshot()
		{
			return (from p in _harvestPatches.Values.OrderBy<HarvestPatch, string>((HarvestPatch p) => p.Key, StringComparer.Ordinal)
				select p.Copy()).ToArray();
		}

		public bool TryHarvestTree(int actor, string key, string locator, bool critical, out int granted, out int remaining, out string reason)
		{
			granted = 0;
			remaining = 0;
			if (actor <= 0 || !ValidHarvestKey(key) || !ValidTreeLocator(locator))
			{
				return Fail("Invalid tree.", out reason);
			}
			_harvestPatches.TryGetValue(key, out var value);
			if (value != null && value.TreeLocator != locator)
			{
				return Fail("Harvesting target changed.", out reason);
			}
			if (value == null && _harvestPatches.Count >= 2048)
			{
				return Fail("Harvesting target limit reached.", out reason);
			}
			remaining = 300 - (value?.TreeDamage ?? 0);
			if (remaining <= 0)
			{
				return Fail("This tree is already broken.", out reason);
			}
			int num = Math.Min(remaining, 50 * ((!critical) ? 1 : 2));
			granted = GrantResources(actor, BuildMaterial.Wood, num / 50 * 6);
			if (value == null)
			{
				value = new HarvestPatch
				{
					Key = key,
					Material = BuildMaterial.Wood,
					TreeLocator = locator
				};
				_harvestPatches.Add(key, value);
			}
			value.TreeDamage += num;
			remaining -= num;
			if (granted == 0)
			{
				Revision++;
			}
			reason = null;
			return true;
		}

		public int RemainingTreeHealth(string key)
		{
			if (!_harvestPatches.TryGetValue(key, out var value) || value.TreeLocator == null)
			{
				return 300;
			}
			return 300 - value.TreeDamage;
		}

		public IEnumerable<HarvestPatch> DestroyedTrees()
		{
			return from patch in _harvestPatches.Values.Where(IsDestroyedTree)
				select patch.Copy();
		}

		private static bool IsDestroyedTree(HarvestPatch patch)
		{
			if (patch.TreeLocator != null)
			{
				return patch.TreeDamage == 300;
			}
			return false;
		}

		internal void CollectDestroyedTreeLocators(List<(string Key, string Locator)> destination)
		{
			foreach (HarvestPatch value in _harvestPatches.Values)
			{
				if (IsDestroyedTree(value))
				{
					destination.Add((value.Key, value.TreeLocator));
				}
			}
		}

		public bool TryHarvest(int actor, string key, BuildMaterial material, out int granted, out string reason)
		{
			granted = 0;
			if (actor <= 0 || !ValidHarvestKey(key) || !BuildRules.ValidMaterial(material))
			{
				return Fail("Invalid harvesting target.", out reason);
			}
			_harvestPatches.TryGetValue(key, out var value);
			if (value != null && (value.Material != material || value.TreeLocator != null))
			{
				return Fail("Harvesting target changed material.", out reason);
			}
			if (value == null && _harvestPatches.Count >= 2048)
			{
				return Fail("Harvesting target limit reached.", out reason);
			}
			int num = 100 - (value?.Used ?? 0);
			if (num <= 0)
			{
				return Fail("This patch is depleted", out reason);
			}
			granted = GrantResources(actor, material, Math.Min(10, num));
			if (granted == 0)
			{
				return Fail("Material inventory is full", out reason);
			}
			if (value == null)
			{
				value = new HarvestPatch
				{
					Key = key,
					Material = material
				};
				_harvestPatches.Add(key, value);
			}
			value.Used += granted;
			reason = null;
			return true;
		}

		private static bool ValidHarvestKey(string key)
		{
			if (key != null && key.Length == 64)
			{
				return key.All(delegate(char c)
				{
					switch (c)
					{
					case '0':
					case '1':
					case '2':
					case '3':
					case '4':
					case '5':
					case '6':
					case '7':
					case '8':
					case '9':
					case 'a':
					case 'b':
					case 'c':
					case 'd':
					case 'e':
					case 'f':
						return true;
					default:
						return false;
					}
				});
			}
			return false;
		}

		private static bool ValidTreeLocator(string locator)
		{
			if (!string.IsNullOrWhiteSpace(locator))
			{
				return locator.Length <= 2048;
			}
			return false;
		}

		private static bool ValidateHarvestSnapshot(HarvestPatch[] input, out Dictionary<string, HarvestPatch> patches, out string reason)
		{
			patches = new Dictionary<string, HarvestPatch>(StringComparer.Ordinal);
			if (input == null || input.Length > 2048)
			{
				return Fail("Invalid harvest snapshot size.", out reason);
			}
			int num = 0;
			while (num < input.Length)
			{
				HarvestPatch harvestPatch = input[num];
				if (harvestPatch == null || !ValidHarvestKey(harvestPatch.Key) || !BuildRules.ValidMaterial(harvestPatch.Material) || patches.ContainsKey(harvestPatch.Key))
				{
					return Fail("Invalid harvest depletion in snapshot.", out reason);
				}
				bool num2;
				if (harvestPatch.TreeLocator != null)
				{
					if (ValidTreeLocator(harvestPatch.TreeLocator) && harvestPatch.Material == BuildMaterial.Wood && harvestPatch.Used == 0 && harvestPatch.TreeDamage > 0 && harvestPatch.TreeDamage <= 300)
					{
						num2 = harvestPatch.TreeDamage % 50 == 0;
						goto IL_00d7;
					}
				}
				else if (harvestPatch.TreeDamage == 0 && harvestPatch.Used > 0)
				{
					num2 = harvestPatch.Used <= 100;
					goto IL_00d7;
				}
				goto IL_00d9;
				IL_00d7:
				if (num2)
				{
					patches.Add(harvestPatch.Key, harvestPatch.Copy());
					num++;
					continue;
				}
				goto IL_00d9;
				IL_00d9:
				return Fail("Invalid harvest depletion in snapshot.", out reason);
			}
			reason = null;
			return true;
		}
	}
	public static class PieceGeometry
	{
		public static bool Same(PieceSpec a, PieceSpec b)
		{
			if (a != null && b != null && a.Cell == b.Cell && a.Kind == b.Kind && a.Rotation == b.Rotation && a.Material == b.Material && a.EditMask == b.EditMask)
			{
				return a.EditCode == b.EditCode;
			}
			return false;
		}

		public static bool Matches(BuildPiece current, PieceSpec expected, int version)
		{
			if (current != null && version >= 0 && current.GeometryVersion == version)
			{
				return Same(current.Spec, expected);
			}
			return false;
		}

		public static string Key(PieceSpec spec)
		{
			if (spec != null)
			{
				string[] obj = new string[8]
				{
					spec.Cell.X.ToString(CultureInfo.InvariantCulture),
					spec.Cell.Y.ToString(CultureInfo.InvariantCulture),
					spec.Cell.Z.ToString(CultureInfo.InvariantCulture),
					null,
					null,
					null,
					null,
					null
				};
				int kind = (int)spec.Kind;
				obj[3] = kind.ToString(CultureInfo.InvariantCulture);
				obj[4] = spec.Rotation.ToString(CultureInfo.InvariantCulture);
				kind = (int)spec.Material;
				obj[5] = kind.ToString(CultureInfo.InvariantCulture);
				obj[6] = spec.EditMask.ToString(CultureInfo.InvariantCulture);
				obj[7] = spec.EditCode.ToString(CultureInfo.InvariantCulture);
				return string.Join(":", obj);
			}
			return "missing";
		}
	}
	public enum EditViewState
	{
		Unchanged,
		AwaitingOwnCommit,
		Changed,
		Missing
	}
	public sealed class EditCommitState
	{
		private PieceSpec _baseline;

		private PieceSpec _proposed;

		public int PieceId { get; private set; }

		public int GeometryVersion { get; private set; }

		public int RequestId { get; private set; }

		public double SentAt { get; private set; }

		public bool Pending => RequestId > 0;

		public PieceSpec Baseline => _baseline?.Copy();

		public void Begin(BuildPiece piece)
		{
			if (piece?.Spec == null || piece.Id <= 0 || piece.GeometryVersion < 0)
			{
				throw new ArgumentException("Invalid edit target");
			}
			Clear();
			PieceId = piece.Id;
			GeometryVersion = piece.GeometryVersion;
			_baseline = piece.Spec.Copy();
		}

		public bool Submit(int requestId, int mask, int code, double now)
		{
			if (PieceId <= 0 || Pending || requestId <= 0 || double.IsNaN(now) || double.IsInfinity(now) || now < 0.0)
			{
				return false;
			}
			_proposed = _baseline.Copy();
			_proposed.EditMask = mask;
			_proposed.EditCode = code;
			RequestId = requestId;
			SentAt = now;
			return true;
		}

		public EditViewState Inspect(BuildPiece current)
		{
			if (current == null || current.Id != PieceId)
			{
				return EditViewState.Missing;
			}
			if (PieceGeometry.Matches(current, _baseline, GeometryVersion))
			{
				return EditViewState.Unchanged;
			}
			int num = ((GeometryVersion == int.MaxValue) ? int.MaxValue : (GeometryVersion + ((!PieceGeometry.Same(_baseline, _proposed)) ? 1 : 0)));
			if (Pending && current.GeometryVersion == num && PieceGeometry.Same(current.Spec, _proposed))
			{
				return EditViewState.AwaitingOwnCommit;
			}
			return EditViewState.Changed;
		}

		public bool MatchesReply(int requestId, int pieceId)
		{
			if (Pending && RequestId == requestId)
			{
				return PieceId == pieceId;
			}
			return false;
		}

		public bool TimedOut(double now, double timeout = 8.0)
		{
			if (Pending && !double.IsNaN(now) && !double.IsInfinity(now))
			{
				return now - SentAt >= timeout;
			}
			return false;
		}

		public void Finish()
		{
			RequestId = 0;
			SentAt = 0.0;
			_proposed = null;
		}

		public void Clear()
		{
			Finish();
			PieceId = 0;
			GeometryVersion = 0;
			_baseline = null;
		}
	}
	public enum EditReplayLookup
	{
		Missing,
		Replay,
		ReusedId
	}
	public sealed class EditReplyCache
	{
		private sealed class Entry
		{
			public string Epoch;

			public string Signature;

			public string Reply;

			public int Id;

			public double Time;
		}

		private const int ActorLimit = 64;

		private const int RepliesPerActor = 32;

		private const double Lifetime = 30.0;

		private readonly Dictionary<int, List<Entry>> _actors = new Dictionary<int, List<Entry>>();

		public EditReplayLookup Find(int actor, string epoch, int id, string signature, double now, out string reply)
		{
			reply = null;
			Prune(now);
			if (!_actors.TryGetValue(actor, out var value))
			{
				return EditReplayLookup.Missing;
			}
			foreach (Entry item in value)
			{
				if (item.Id == id && item.Epoch == epoch)
				{
					if (item.Signature != signature)
					{
						return EditReplayLookup.ReusedId;
					}
					reply = item.Reply;
					return EditReplayLookup.Replay;
				}
			}
			return EditReplayLookup.Missing;
		}

		public void Store(int actor, string epoch, int id, string signature, string reply, double now)
		{
			Prune(now);
			if (actor <= 0 || id <= 0 || string.IsNullOrEmpty(epoch) || string.IsNullOrEmpty(reply))
			{
				return;
			}
			if (!_actors.TryGetValue(actor, out var value))
			{
				if (_actors.Count >= 64)
				{
					_actors.Remove(OldestActor());
				}
				_actors.Add(actor, value = new List<Entry>());
			}
			value.RemoveAll((Entry e) => e.Epoch == epoch && e.Id == id);
			if (value.Count >= 32)
			{
				value.RemoveAt(0);
			}
			value.Add(new Entry
			{
				Epoch = epoch,
				Id = id,
				Signature = signature,
				Reply = reply,
				Time = now
			});
		}

		private int OldestActor()
		{
			int result = 0;
			double num = double.PositiveInfinity;
			foreach (KeyValuePair<int, List<Entry>> actor in _actors)
			{
				if (actor.Value[0].Time < num)
				{
					num = actor.Value[0].Time;
					result = actor.Key;
				}
			}
			return result;
		}

		private void Prune(double now)
		{
			List<int> list = new List<int>();
			foreach (KeyValuePair<int, List<Entry>> actor in _actors)
			{
				actor.Value.RemoveAll((Entry e) => now - e.Time > 30.0);
				if (actor.Value.Count == 0)
				{
					list.Add(actor.Key);
				}
			}
			foreach (int item in list)
			{
				_actors.Remove(item);
			}
		}

		public void Clear()
		{
			_actors.Clear();
		}
	}
	public static class EditGridProjection
	{
		public const float AboveDeck = 0.26f;

		public const float BelowDeck = -0.2f;

		public const float WallSeparation = 0.15f;

		public static Vector3 SurfaceOffset(PieceKind kind, bool positiveSide)
		{
			if (kind != PieceKind.Wall)
			{
				return new Vector3(0f, positiveSide ? 0.26f : (-0.2f), 0f);
			}
			return new Vector3(0f, 0f, positiveSide ? 0.15f : (-0.15f));
		}

		public static bool Intersect(PieceKind kind, float width, float height, Vector3 origin, Vector3 direction, out Vector3 point, out float distance, out int cell)
		{
			return Intersect(kind, width, height, origin, direction, Vector3.Zero, out point, out distance, out cell);
		}

		public static bool Intersect(PieceKind kind, float width, float height, Vector3 origin, Vector3 direction, Vector3 surfaceOffset, out Vector3 point, out float distance, out int cell)
		{
			point = default(Vector3);
			distance = 0f;
			cell = -1;
			if (kind < PieceKind.Wall || kind > PieceKind.Roof || !Finite(origin) || !Finite(direction) || !Finite(surfaceOffset) || !Finite(width) || !Finite(height) || width <= 0f || height <= 0f || direction.LengthSquared() < 1E-10f)
			{
				return false;
			}
			origin -= surfaceOffset;
			direction = Vector3.Normalize(direction);
			float num = ((kind == PieceKind.Wall) ? direction.Z : direction.Y);
			if (Math.Abs(num) < 1E-06f)
			{
				return false;
			}
			distance = (0f - ((kind == PieceKind.Wall) ? origin.Z : origin.Y)) / num;
			if (distance < 0f || !Finite(distance))
			{
				return false;
			}
			point = origin + direction * distance;
			float num2 = ((kind == PieceKind.Wall) ? point.Y : point.Z);
			float num3 = ((kind == PieceKind.Wall) ? height : width);
			if (point.X < -0.001f || point.X > width + 0.001f || num2 < -0.001f || num2 > num3 + 0.001f)
			{
				return false;
			}
			int num4 = ((kind == PieceKind.Wall) ? 3 : 2);
			int num5 = Math.Max(0, Math.Min(num4 - 1, (int)Math.Floor(point.X / width * (float)num4)));
			int num6 = Math.Max(0, Math.Min(num4 - 1, (int)Math.Floor(num2 / num3 * (float)num4)));
			cell = num5 + num6 * num4;
			point += surfaceOffset;
			return true;
		}

		private static bool Finite(float x)
		{
			if (!float.IsNaN(x))
			{
				return !float.IsInfinity(x);
			}
			return false;
		}

		private static bool Finite(Vector3 v)
		{
			if (Finite(v.X) && Finite(v.Y))
			{
				return Finite(v.Z);
			}
			return false;
		}
	}
	public sealed class FixedCommandQueue
	{
		private readonly struct Entry
		{
			internal readonly int Actor;

			internal readonly string Json;

			internal Entry(int actor, string json)
			{
				Actor = actor;
				Json = json;
			}
		}

		public const int MaximumPayloadCharacters = 65536;

		private readonly int _capacity;

		private readonly Queue<Entry> _queue = new Queue<Entry>();

		private uint _generation;

		private bool _processing;

		public int Count => _queue.Count;

		public FixedCommandQueue(int capacity = 256)
		{
			if (capacity < 1 || capacity > 4096)
			{
				throw new ArgumentOutOfRangeException("capacity");
			}
			_capacity = capacity;
		}

		public bool TryEnqueue(int actor, string json)
		{
			if (actor <= 0 || string.IsNullOrEmpty(json) || json.Length > 65536 || _queue.Count >= _capacity)
			{
				return false;
			}
			_queue.Enqueue(new Entry(actor, json));
			return true;
		}

		public int ProcessBatch(Action<int, string> execute)
		{
			if (execute == null)
			{
				throw new ArgumentNullException("execute");
			}
			if (_processing)
			{
				return 0;
			}
			_processing = true;
			int count = _queue.Count;
			int num = 0;
			uint generation = _generation;
			try
			{
				for (int i = 0; i < count; i++)
				{
					if (generation != _generation)
					{
						break;
					}
					if (_queue.Count <= 0)
					{
						break;
					}
					Entry entry = _queue.Dequeue();
					num++;
					execute(entry.Actor, entry.Json);
				}
				return num;
			}
			finally
			{
				_processing = false;
			}
		}

		public void Clear()
		{
			_queue.Clear();
			_generation++;
		}
	}
	public enum MeleePhase
	{
		Unequipped,
		Equip,
		Idle,
		Swing,
		Recovery
	}
	public struct MeleeEvents
	{
		public bool Started;

		public bool Contact;

		public bool Sound;
	}
	public sealed class MeleeComboClock
	{
		private bool _hit;

		private bool _sound;

		public MeleePhase Phase { get; private set; }

		public int Variant { get; private set; } = 1;

		public int Sequence { get; private set; }

		public double PhaseStarted { get; private set; }

		public bool Swinging => Phase == MeleePhase.Swing;

		public bool Recovering => Phase == MeleePhase.Recovery;

		public void Equip(double now)
		{
			Phase = MeleePhase.Equip;
			PhaseStarted = now;
			Variant = 1;
			Sequence = 0;
			_hit = (_sound = false);
		}

		public void Stop()
		{
			Phase = MeleePhase.Unequipped;
			_hit = (_sound = false);
		}

		public float Age(double now)
		{
			return (float)Math.Max(0.0, now - PhaseStarted);
		}

		public float Progress(double now)
		{
			if (!Swinging)
			{
				return 0f;
			}
			return Math.Min(1f, Age(now) / SourceMeleeTiming.SwingDuration(Variant));
		}

		private void Start(int variant, double now, ref MeleeEvents events)
		{
			Variant = variant;
			Sequence++;
			Phase = MeleePhase.Swing;
			PhaseStarted = now;
			_hit = (_sound = false);
			events.Started = true;
		}

		public MeleeEvents Tick(double now, bool held, bool pressed)
		{
			MeleeEvents events = default(MeleeEvents);
			if (double.IsNaN(now) || double.IsInfinity(now) || Phase == MeleePhase.Unequipped)
			{
				return events;
			}
			if (Phase == MeleePhase.Equip && Age(now) >= 0.331f)
			{
				Phase = MeleePhase.Idle;
			}
			if (Phase == MeleePhase.Swing)
			{
				float num = Age(now);
				if (!_sound && num >= SourceMeleeTiming.SoundTime(Variant))
				{
					_sound = true;
					events.Sound = true;
				}
				if (!_hit && num >= SourceMeleeTiming.HitTime(Variant))
				{
					_hit = true;
					events.Contact = true;
				}
				if (num >= SourceMeleeTiming.SwingDuration(Variant))
				{
					if (held)
					{
						Start(3 - Variant, now, ref events);
					}
					else
					{
						Phase = MeleePhase.Recovery;
						PhaseStarted = now;
					}
				}
			}
			if (Phase == MeleePhase.Recovery)
			{
				if (Age(now) >= SourceMeleeTiming.RecoveryDuration(Variant))
				{
					Phase = MeleePhase.Idle;
				}
				else if (pressed)
				{
					Start(3 - Variant, now, ref events);
				}
			}
			if (Phase == MeleePhase.Idle && (held || pressed))
			{
				Start(1, now, ref events);
			}
			return events;
		}
	}
	public static class SourcePlacementTiming
	{
		public const double FirstIntervalSeconds = 0.005;

		public const double RepeatIntervalSeconds = 0.005;

		public const string TablePackage = "/Game/Athena/Balance/DataTables/AthenaGameData";

		public const string TableSha256 = "817243EA2ED27EF8A06DCA4CF960F5E0179DE4A0435613DBEBDCB9F2DA19A7FD";
	}
	public enum PlacementInputDecision
	{
		None,
		Submit,
		Invalid
	}
	public enum PlacementRequestOutcome
	{
		SendFailed,
		Rejected,
		AwaitingVisibility,
		Visible
	}
	public sealed class PlacementInputState
	{
		public const double UnacknowledgedRetrySeconds = 0.5;

		public const int MaximumPendingSlots = 128;

		private readonly Dictionary<string, (double RetryAt, int RequestId, PieceSpec Submitted, bool Accepted)> _pending = new Dictionary<string, (double, int, PieceSpec, bool)>();

		private bool _wasHeld;

		private bool _pendingPress;

		private bool _requireRelease;

		private double _eligibleAt;

		private string _invalidKey;

		public int PendingSlots => _pending.Count;

		public bool RequiresRelease => _requireRelease;

		internal bool HasPendingPress => _pendingPress;

		public static string CanonicalSlot(PieceSpec candidate)
		{
			if (candidate != null)
			{
				return SupportGeometry.Slot(candidate);
			}
			return null;
		}

		public void TrackRequest(PieceSpec submitted, int requestId)
		{
			string text = CanonicalSlot(submitted);
			if (requestId <= 0 || text == null || !_pending.TryGetValue(text, out (double, int, PieceSpec, bool) value))
			{
				throw new ArgumentException("The placement request has no reserved slot");
			}
			_pending[text] = (value.Item1, requestId, submitted.Copy(), false);
		}

		public bool CompleteRequest(string slot, int requestId, bool sent = true)
		{
			PieceSpec submitted;
			return CompleteRequest(slot, requestId, out submitted, sent);
		}

		public bool CompleteRequest(string slot, int requestId, out PieceSpec submitted, bool sent = true)
		{
			return CompleteRequest(slot, requestId, out submitted, sent ? PlacementRequestOutcome.AwaitingVisibility : PlacementRequestOutcome.SendFailed);
		}

		public bool CompleteRequest(string slot, int requestId, out PieceSpec submitted, PlacementRequestOutcome outcome)
		{
			submitted = null;
			if (requestId <= 0 || slot == null || !_pending.TryGetValue(slot, out (double, int, PieceSpec, bool) value) || value.Item2 != requestId)
			{
				return false;
			}
			submitted = value.Item3;
			if (outcome == PlacementRequestOutcome.Rejected || outcome == PlacementRequestOutcome.AwaitingVisibility)
			{
				_pending[slot] = (value.Item1, 0, null, outcome == PlacementRequestOutcome.AwaitingVisibility);
			}
			else
			{
				_pending.Remove(slot);
			}
			return true;
		}

		public void Reset()
		{
			_pending.Clear();
			_wasHeld = false;
			_pendingPress = false;
			_requireRelease = false;
			_eligibleAt = 0.0;
			_invalidKey = null;
		}

		public void SuppressUntilRelease(bool held)
		{
			Reset();
			_requireRelease = held;
			_wasHeld = held;
		}

		public PlacementInputDecision Step(double now, bool held, bool pressed, PieceSpec candidate, bool valid, string rejection = null, bool allowRepeat = true)
		{
			if (double.IsNaN(now) || double.IsInfinity(now))
			{
				throw new ArgumentOutOfRangeException("now");
			}
			if (_requireRelease)
			{
				if (held)
				{
					return PlacementInputDecision.None;
				}
				_requireRelease = false;
				_wasHeld = false;
				if (!pressed)
				{
					return PlacementInputDecision.None;
				}
			}
			bool num = pressed || (held && !_wasHeld);
			_wasHeld = held;
			if (num)
			{
				_invalidKey = null;
				_pendingPress = true;
				_eligibleAt = now + 0.005;
			}
			if ((!held && !_pendingPress) || now + 1E-09 < _eligibleAt)
			{
				return PlacementInputDecision.None;
			}
			if (!allowRepeat && !_pendingPress)
			{
				return PlacementInputDecision.None;
			}
			if (candidate == null)
			{
				if (!held)
				{
					_pendingPress = false;
				}
				return PlacementInputDecision.None;
			}
			if (!valid)
			{
				_pendingPress = false;
				string text = PieceGeometry.Key(candidate) + ":" + rejection;
				if (text == _invalidKey)
				{
					return PlacementInputDecision.None;
				}
				_invalidKey = text;
				return PlacementInputDecision.Invalid;
			}
			_invalidKey = null;
			string key = CanonicalSlot(candidate);
			if (_pending.TryGetValue(key, out (double, int, PieceSpec, bool) value) && now + 1E-09 < value.Item1 && (!_pendingPress || value.Item2 != 0 || value.Item4))
			{
				_pendingPress = false;
				return PlacementInputDecision.None;
			}
			if (_pending.Count >= 128 && !_pending.ContainsKey(key))
			{
				string text2 = null;
				double num2 = double.MaxValue;
				foreach (KeyValuePair<string, (double, int, PieceSpec, bool)> item in _pending)
				{
					if (item.Value.Item1 < num2)
					{
						text2 = item.Key;
						num2 = item.Value.Item1;
					}
				}
				if (text2 != null)
				{
					_pending.Remove(text2);
				}
			}
			_pending[key] = (now + 0.5, 0, null, false);
			_pendingPress = false;
			_eligibleAt = now + 0.005;
			return PlacementInputDecision.Submit;
		}
	}
	public static class PlacementMath
	{
		public static bool TryForwardRayOrigin(Vector3 camera, Vector3 direction, Vector3 player, out Vector3 origin)
		{
			origin = default(Vector3);
			if (!Finite(camera) || !Finite(direction) || !Finite(player))
			{
				return false;
			}
			float num = direction.LengthSquared();
			if (!Finite(num) || num < 1E-10f)
			{
				return false;
			}
			Vector3 vector = new Vector3(direction.X, 0f, direction.Z);
			float num2 = num * 0.0669873f;
			float num3 = vector.LengthSquared();
			if (num3 < num2)
			{
				float num4 = 1f - MathF.Sqrt(num3 / num2);
				vector.Y = direction.Y * (num4 * num4 * (3f - 2f * num4));
			}
			double num5 = Vector3.Dot(direction, vector);
			double num6 = Math.Max(0.0, (double)Vector3.Dot(player - camera, vector) / num5);
			origin = camera + direction * (float)num6;
			return Finite(origin);
		}

		public static bool TryForwardWallCell(GridCell snapped, Vector3 player, Vector3 gridOrigin, float width, float height, int rotation, out GridCell cell)
		{
			cell = snapped;
			if (!TryWallCell(player, gridOrigin, width, height, rotation, out var cell2, player))
			{
				return false;
			}
			Vector3 vector = (player - gridOrigin) / new Vector3(width, height, width);
			int num = (rotation % 4 + 4) % 4;
			if (num == 0 && (float)snapped.Z < vector.Z)
			{
				cell = new GridCell(snapped.X, snapped.Y, cell2.Z);
			}
			else if (num == 1 && (float)snapped.X < vector.X)
			{
				cell = new GridCell(cell2.X, snapped.Y, snapped.Z);
			}
			else if (num == 2 && (double)snapped.Z + 1.0 > (double)vector.Z)
			{
				cell = new GridCell(snapped.X, snapped.Y, cell2.Z);
			}
			else if (num == 3 && (double)snapped.X + 1.0 > (double)vector.X)
			{
				cell = new GridCell(cell2.X, snapped.Y, snapped.Z);
			}
			return true;
		}

		public static bool TryFreeAimPoint(Vector3 camera, Vector3 direction, Vector3 head, float preferredDistance, float reach, out Vector3 point)
		{
			point = default(Vector3);
			if (!Finite(camera) || !Finite(direction) || !Finite(head) || !Finite(preferredDistance) || !Finite(reach) || preferredDistance <= 0f || reach <= 0f)
			{
				return false;
			}
			double num = Math.Sqrt((double)direction.X * (double)direction.X + (double)direction.Y * (double)direction.Y + (double)direction.Z * (double)direction.Z);
			if (num < 1E-10)
			{
				return false;
			}
			double num2 = (double)direction.X / num;
			double num3 = (double)direction.Y / num;
			double num4 = (double)direction.Z / num;
			double num5 = (double)camera.X - (double)head.X;
			double num6 = (double)camera.Y - (double)head.Y;
			double num7 = (double)camera.Z - (double)head.Z;
			double num8 = Math.Min(preferredDistance, reach);
			double num9 = num5 * num2 + num6 * num3 + num7 * num4;
			double num10 = (num5 - num9 * num2) * (num5 - num9 * num2) + (num6 - num9 * num3) * (num6 - num9 * num3) + (num7 - num9 * num4) * (num7 - num9 * num4);
			double num11 = num8 * num8 - num10;
			if (num11 < 0.0)
			{
				return false;
			}
			double num12 = 0.0 - num9 + Math.Sqrt(num11);
			if (num12 < 0.0)
			{
				return false;
			}
			point = new Vector3((float)((double)camera.X + num2 * num12), (float)((double)camera.Y + num3 * num12), (float)((double)camera.Z + num4 * num12));
			return Finite(point);
		}

		public static bool TryWallCell(Vector3 point, Vector3 gridOrigin, float width, float height, int rotation, out GridCell cell, Vector3? groundedPlayer = null)
		{
			cell = default(GridCell);
			if (!Finite(point) || !Finite(gridOrigin) || !Finite(width) || !Finite(height) || width <= 0f || height <= 0f)
			{
				return false;
			}
			Vector3 value = (point - gridOrigin) / new Vector3(width, height, width);
			if (!Finite(value))
			{
				return false;
			}
			int num = (rotation % 4 + 4) % 4;
			double num2 = Math.Floor(value.X);
			double num3 = Math.Floor(value.Y + 0.04f);
			double num4 = Math.Floor(value.Z);
			Vector3 value2 = (groundedPlayer.HasValue ? ((groundedPlayer.Value - gridOrigin) / new Vector3(width, height, width)) : new Vector3(float.NaN));
			if (Finite(value2) && Math.Floor(value2.X) == num2 && Math.Floor(value2.Z) == num4 && Math.Floor(value2.Y + 0.04f) == num3)
			{
				switch (num)
				{
				case 0:
					num4 += 1.0;
					break;
				case 1:
					num2 += 1.0;
					break;
				case 2:
					num4 -= 1.0;
					break;
				default:
					num2 -= 1.0;
					break;
				}
			}
			else if (num == 0 || num == 2)
			{
				num4 = Math.Round(value.Z, MidpointRounding.ToEven) - (double)((num == 2) ? 1 : 0);
			}
			else
			{
				num2 = Math.Round(value.X, MidpointRounding.ToEven) - (double)((num == 3) ? 1 : 0);
			}
			if (num2 < -2147483648.0 || num2 > 2147483647.0 || num3 < -2147483648.0 || num3 > 2147483647.0 || num4 < -2147483648.0 || num4 > 2147483647.0)
			{
				return false;
			}
			cell = new GridCell((int)num2, (int)num3, (int)num4);
			return true;
		}

		public static bool TryNearWallCell(Vector3 camera, Vector3 aimPoint, Vector3 player, Vector3 gridOrigin, float width, float height, int rotation, GridCell snapped, out GridCell cell, bool allowAdjacentRow = false)
		{
			cell = default(GridCell);
			if (!Finite(camera) || !Finite(aimPoint) || !TryWallCell(player, gridOrigin, width, height, rotation, out var cell2, player))
			{
				return false;
			}
			int num = (rotation % 4 + 4) % 4;
			cell2 = new GridCell(cell2.X, snapped.Y, cell2.Z);
			Vector3 direction = aimPoint - camera;
			int num2 = (allowAdjacentRow ? 1 : 0);
			if (num switch
			{
				0 => (Math.Abs((long)cell2.X - (long)snapped.X) <= num2 && cell2.Z < snapped.Z && direction.Z > 0f) ? 1 : 0, 
				1 => (Math.Abs((long)cell2.Z - (long)snapped.Z) <= num2 && cell2.X < snapped.X && direction.X > 0f) ? 1 : 0, 
				2 => (Math.Abs((long)cell2.X - (long)snapped.X) <= num2 && cell2.Z > snapped.Z && direction.Z < 0f) ? 1 : 0, 
				_ => (Math.Abs((long)cell2.Z - (long)snapped.Z) <= num2 && cell2.X > snapped.X && direction.X < 0f) ? 1 : 0, 
			} == 0)
			{
				return false;
			}
			if (!BuildAimGeometry.Intersect(new PieceSpec(cell2, PieceKind.Wall, num, BuildMaterial.Wood), gridOrigin, width, height, camera, direction, out var _, out var distance) || distance > direction.Length())
			{
				return false;
			}
			cell = cell2;
			return true;
		}

		public static bool TryContactLayer(PieceKind requested, PieceSpec blocking, Vector3 contact, Vector3 gridOrigin, float height, out int layer)
		{
			layer = 0;
			if ((requested != PieceKind.Floor && requested != PieceKind.Roof) || blocking == null || !Finite(contact) || !Finite(gridOrigin) || !Finite(height) || height <= 0f)
			{
				return false;
			}
			bool num = blocking.Kind == PieceKind.Wall && blocking.EditMask == 511 && blocking.EditCode == 0;
			bool flag = blocking.Kind == PieceKind.Ramp && blocking.EditMask == 15 && blocking.EditCode == 0;
			if (!num && !flag)
			{
				return false;
			}
			double num2 = ((double)contact.Y - (double)gridOrigin.Y) / (double)height - (double)blocking.Cell.Y;
			if (Math.Abs(num2 - 0.5) < 1E-05 || num2 < 0.0 || num2 > 1.0)
			{
				return false;
			}
			long num3 = (long)blocking.Cell.Y + (long)((num2 > 0.5) ? 1 : 0);
			if (num3 < int.MinValue || num3 > int.MaxValue)
			{
				return false;
			}
			layer = (int)num3;
			return true;
		}

		private static bool Finite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}

		private static bool Finite(Vector3 value)
		{
			if (Finite(value.X) && Finite(value.Y))
			{
				return Finite(value.Z);
			}
			return false;
		}

		public static int ViewRotation(float yawDegrees, int manualTurns)
		{
			if (float.IsNaN(yawDegrees) || float.IsInfinity(yawDegrees))
			{
				return (manualTurns % 4 + 4) % 4;
			}
			return (((int)Math.Floor((((double)yawDegrees % 360.0 + 360.0) % 360.0 + 45.0) / 90.0) % 4 + manualTurns) % 4 + 4) % 4;
		}
	}
	public static class SceneryMaterialRules
	{
		private static readonly string[] WoodPrefixes = new string[25]
		{
			" tree", " palm", " bush", " wood", " bark", " branch", " trunk", " stump", " shrub", " fern",
			" foliage", " leaf", " leaves", " timber", " bamboo", " hedge", " plank", " vegetation", " oak", " pine",
			" birch", " spruce", " cedar", " cactus", " vine"
		};

		private static readonly string[] MetalPrefixes = new string[19]
		{
			" metal", " plane", " aircraft", " airplane", " aeroplane", " fuselage", " cockpit", " wreck", " steel", " iron",
			" copper", " aluminium", " aluminum", " machine", " engine", " pipe", " antenna", " crane", " rail"
		};

		public static bool TryClassifyName(string name, out BuildMaterial material)
		{
			string text = NormalizeName(name);
			if (Matches(text, WoodPrefixes) || text.Contains(" log "))
			{
				material = BuildMaterial.Wood;
				return true;
			}
			if (Matches(text, MetalPrefixes))
			{
				material = BuildMaterial.Metal;
				return true;
			}
			material = BuildMaterial.Brick;
			return false;
		}

		public static string NormalizeName(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				return " ";
			}
			StringBuilder stringBuilder = new StringBuilder(" ");
			for (int i = 0; i < value.Length; i++)
			{
				char c = value[i];
				if (!char.IsLetterOrDigit(c))
				{
					stringBuilder.Append(' ');
					continue;
				}
				if (i > 0 && ((char.IsUpper(c) && char.IsLower(value[i - 1])) || (char.IsDigit(c) && char.IsLetter(value[i - 1]))))
				{
					stringBuilder.Append(' ');
				}
				stringBuilder.Append(char.ToLowerInvariant(c));
			}
			stringBuilder.Append(' ');
			return stringBuilder.ToString();
		}

		private static bool Matches(string text, string[] prefixes)
		{
			foreach (string value in prefixes)
			{
				if (text.IndexOf(value, StringComparison.Ordinal) >= 0)
				{
					return true;
				}
			}
			return false;
		}
	}
	public readonly struct SimpleBuildSelection
	{
		public PieceKind Primary { get; }

		public int PrimaryRotationOffset { get; }

		public bool TriesCone { get; }

		internal SimpleBuildSelection(PieceKind primary, int primaryRotationOffset, bool triesCone)
		{
			Primary = primary;
			PrimaryRotationOffset = primaryRotationOffset;
			TriesCone = triesCone;
		}
	}
	public static class SimpleBuildProfile
	{
		private static readonly (float MinPitch, SimpleBuildSelection Selection)[] TraversalSections = new(float, SimpleBuildSelection)[6]
		{
			(52.5f, new SimpleBuildSelection(PieceKind.Floor, 0, triesCone: true)),
			(3f, new SimpleBuildSelection(PieceKind.Ramp, 0, triesCone: false)),
			(-15f, new SimpleBuildSelection(PieceKind.Floor, 0, triesCone: false)),
			(-30f, new SimpleBuildSelection(PieceKind.Floor, 0, triesCone: true)),
			(-70f, new SimpleBuildSelection(PieceKind.Ramp, 2, triesCone: true)),
			(-180f, new SimpleBuildSelection(PieceKind.Floor, 0, triesCone: true))
		};

		public static bool TrySelect(float pitchDegrees, out SimpleBuildSelection selection)
		{
			selection = default(SimpleBuildSelection);
			if (float.IsNaN(pitchDegrees) || float.IsInfinity(pitchDegrees))
			{
				return false;
			}
			(float, SimpleBuildSelection)[] traversalSections = TraversalSections;
			for (int i = 0; i < traversalSections.Length; i++)
			{
				(float, SimpleBuildSelection) tuple = traversalSections[i];
				if (pitchDegrees >= tuple.Item1)
				{
					selection = tuple.Item2;
					return true;
				}
			}
			return false;
		}
	}
	public static class SimpleEditSelection
	{
		private const float LowerThird = 1f / 3f;

		private const float UpperThird = 2f / 3f;

		public static bool TrySelect(PieceSpec spec, float across, float height, float depth, out int mask, out int code)
		{
			mask = (code = 0);
			bool flag = spec == null;
			if (!flag)
			{
				PieceKind kind = spec.Kind;
				bool flag2 = (uint)kind <= 1u;
				flag = !flag2;
			}
			if (flag || spec.EditCode != 0 || !BuildRules.ValidMask(spec.Kind, spec.EditMask) || !InUnit(across) || !Finite(height) || !Finite(depth) || (spec.Kind == PieceKind.Wall && !InUnit(height)))
			{
				return false;
			}
			int num = BuildRules.FullMask(spec.Kind);
			if (spec.EditMask != num)
			{
				mask = num;
				return true;
			}
			if (spec.Kind == PieceKind.Floor)
			{
				int num2 = ((!(across < 0.5f)) ? 1 : 0);
				int num3 = ((!(depth < 0.5f)) ? 1 : 0);
				mask = num & ~(1 << num2 + 2 * num3);
				return true;
			}
			if (across < 1f / 3f || across >= 2f / 3f || height >= 2f / 3f)
			{
				return false;
			}
			mask = ((height < 1f / 3f) ? 493 : 495);
			return true;
		}

		private static bool InUnit(float value)
		{
			if (value >= 0f)
			{
				return value <= 1f;
			}
			return false;
		}

		private static bool Finite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}
	}
	public sealed class SourceLifecycleProfile
	{
		public float MaxHealth { get; }

		public float BuildTime { get; }

		public float RepairTime { get; }

		public int FrameSections { get; }

		public int Sections { get; }

		public float? InitialHealthFraction { get; }

		public float? DamagePause { get; }

		public float PlaceDuration { get; }

		public float BreakDuration { get; }

		public float DestroyDuration { get; }

		public float? CollapseDelay { get; }

		public SourceLifecycleProfile(float maxHealth, float buildTime, float repairTime, int frameSections, int sections, float? initialHealthFraction = null, float? damagePause = null, float placeDuration = 0f, float breakDuration = 0f, float destroyDuration = 0f, float? collapseDelay = null)
		{
			if (!Finite(maxHealth) || maxHealth <= 0f || !Finite(buildTime) || buildTime <= 0f || !Finite(repairTime) || repairTime <= 0f || frameSections < 0 || sections < 1 || frameSections > sections || sections > 10000 || (initialHealthFraction.HasValue && (!Finite(initialHealthFraction.Value) || initialHealthFraction <= 0f || initialHealthFraction > 1f)) || !Duration(damagePause) || !Duration(collapseDelay) || !Duration(placeDuration) || !Duration(breakDuration) || !Duration(destroyDuration))
			{
				throw new ArgumentException("Invalid original building lifecycle profile");
			}
			MaxHealth = maxHealth;
			BuildTime = buildTime;
			RepairTime = repairTime;
			FrameSections = frameSections;
			Sections = sections;
			InitialHealthFraction = initialHealthFraction;
			DamagePause = damagePause;
			PlaceDuration = placeDuration;
			BreakDuration = breakDuration;
			DestroyDuration = destroyDuration;
			CollapseDelay = collapseDelay;
		}

		private static bool Finite(float v)
		{
			if (!float.IsNaN(v))
			{
				return !float.IsInfinity(v);
			}
			return false;
		}

		private static bool Duration(float? v)
		{
			if (v.HasValue)
			{
				if (Finite(v.Value) && v.Value >= 0f)
				{
					return v.Value <= 300f;
				}
				return false;
			}
			return true;
		}
	}
	public static class SourceLifecycleProfiles
	{
		private static readonly Dictionary<string, SourceLifecycleProfile> Profiles = new Dictionary<string, SourceLifecycleProfile>();

		public static int Count => Profiles.Count;

		private static string Key(PieceSpec spec)
		{
			string[] array = new string[7];
			int kind = (int)spec.Kind;
			array[0] = kind.ToString();
			array[1] = ":";
			kind = (int)spec.Material;
			array[2] = kind.ToString();
			array[3] = ":";
			array[4] = spec.EditMask.ToString();
			array[5] = ":";
			array[6] = spec.EditCode.ToString();
			return string.Concat(array);
		}

		public static void Register(PieceKind kind, BuildMaterial material, int mask, int code, SourceLifecycleProfile profile)
		{
			if (!BuildRules.ValidMask(kind, mask) || !BuildRules.ValidMaterial(material) || code < 0 || code > 4095 || (kind != PieceKind.Ramp && code != 0) || profile == null)
			{
				throw new ArgumentException("Invalid source lifecycle definition");
			}
			Profiles[Key(new PieceSpec(default(GridCell), kind, 0, material, mask)
			{
				EditCode = code
			})] = profile;
		}

		public static bool TryGet(PieceSpec spec, out SourceLifecycleProfile profile)
		{
			profile = null;
			if (spec != null)
			{
				return Profiles.TryGetValue(Key(spec), out profile);
			}
			return false;
		}

		public static void Clear()
		{
			Profiles.Clear();
		}
	}
	public static class SourceMeleeTiming
	{
		public const float Swing1Duration = 0.5333f;

		public const float Swing2Duration = 19f / 30f;

		public const float Recovery1Duration = 8f / 15f;

		public const float Reco