Decompiled source of Physics Castle Builder v1.0.4

BepInEx/plugins/PhysicsCastleBuilder/PhysicsCastleBuilder.dll

Decompiled 3 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Landfall.TABS.GameMode;
using Landfall.TABS.UnitPlacement;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("PhysicsCastleBuilder")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Physics Castle Builder 1.0.4 development build: targeted whole-structure deletion added; direct TABS and Harmony references, Newtonsoft JSON serialization, and source architecture audit.")]
[assembly: AssemblyFileVersion("1.0.4.0")]
[assembly: AssemblyInformationalVersion("1.0.4")]
[assembly: AssemblyProduct("PhysicsCastleBuilder")]
[assembly: AssemblyTitle("PhysicsCastleBuilder")]
[assembly: AssemblyVersion("1.0.4.0")]
namespace PhysicsCastleBuilder;

[BepInPlugin("com.openai.tabs.physicscastlebuilder", "Physics Castle Builder", "1.0.4")]
public sealed class PhysicsCastleBuilderPlugin : BaseUnityPlugin
{
	private enum BuildTool
	{
		Brick,
		Wall,
		Tower,
		Platform,
		Stairs,
		RaisedDeck,
		Flag
	}

	private enum FlagTeamMode
	{
		Red,
		Blue
	}

	private sealed class Vector3JsonConverter : JsonConverter
	{
		public override bool CanConvert(Type objectType)
		{
			return objectType == typeof(Vector3);
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = (Vector3)value;
			writer.WriteStartObject();
			writer.WritePropertyName("x");
			writer.WriteValue(val.x);
			writer.WritePropertyName("y");
			writer.WriteValue(val.y);
			writer.WritePropertyName("z");
			writer.WriteValue(val.z);
			writer.WriteEndObject();
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			JObject val = JObject.Load(reader);
			if (val["x"] == null || val["y"] == null || val["z"] == null)
			{
				throw new JsonSerializationException("A saved Vector3 is missing x, y, or z.");
			}
			return (object)new Vector3(((JToken)val).Value<float>((object)"x"), ((JToken)val).Value<float>((object)"y"), ((JToken)val).Value<float>((object)"z"));
		}
	}

	private sealed class QuaternionJsonConverter : JsonConverter
	{
		public override bool CanConvert(Type objectType)
		{
			return objectType == typeof(Quaternion);
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			Quaternion val = (Quaternion)value;
			writer.WriteStartObject();
			writer.WritePropertyName("x");
			writer.WriteValue(val.x);
			writer.WritePropertyName("y");
			writer.WriteValue(val.y);
			writer.WritePropertyName("z");
			writer.WriteValue(val.z);
			writer.WritePropertyName("w");
			writer.WriteValue(val.w);
			writer.WriteEndObject();
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			JObject val = JObject.Load(reader);
			if (val["x"] == null || val["y"] == null || val["z"] == null || val["w"] == null)
			{
				throw new JsonSerializationException("A saved Quaternion is missing x, y, z, or w.");
			}
			return (object)new Quaternion(((JToken)val).Value<float>((object)"x"), ((JToken)val).Value<float>((object)"y"), ((JToken)val).Value<float>((object)"z"), ((JToken)val).Value<float>((object)"w"));
		}
	}

	public const string PluginGuid = "com.openai.tabs.physicscastlebuilder";

	public const string PluginName = "Physics Castle Builder";

	public const string PluginVersion = "1.0.4";

	private const float BrickHeight = 0.5f;

	private const float DefaultBrickWidth = 1f;

	private const float DefaultBrickDepth = 0.5f;

	private const float RotationStep = 15f;

	private const float UiWidth = 470f;

	private const float UiHeight = 444f;

	private ConfigEntry<KeyCode> toggleKey;

	private ConfigEntry<KeyCode> removeStructureKey;

	private ConfigEntry<int> placeMouseButtonConfig;

	private ConfigEntry<int> maxBricksConfig;

	private ConfigEntry<float> placementDistanceConfig;

	private ConfigEntry<string> placementLayerNameConfig;

	private ConfigEntry<bool> enableNamedUnitLayerCollisionsConfig;

	private ConfigEntry<int> maximumDebrisFragmentsConfig;

	private ConfigEntry<float> debrisLifetimeConfig;

	private ConfigEntry<float> fractureImpactSpeedConfig;

	private ConfigEntry<bool> restoreStructuresAfterBattleResetConfig;

	private readonly List<BuilderBrick> bricks = new List<BuilderBrick>();

	private readonly List<BuilderStructure> structures = new List<BuilderStructure>();

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

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

	private readonly Collider[] explosionColliderBuffer = (Collider[])(object)new Collider[256];

	private readonly HashSet<BuilderBrick> explosionBrickSet = new HashSet<BuilderBrick>();

	private readonly List<BuilderBrick> explosionBrickCandidates = new List<BuilderBrick>();

	private readonly HashSet<BuilderStructure> explosionAffectedStructures = new HashSet<BuilderStructure>();

	private readonly Dictionary<int, float> recentExplosiveDetonations = new Dictionary<int, float>();

	private BuildTool selectedTool;

	private bool builderEnabled;

	private GameObject buildRoot;

	private Material stoneMaterial;

	private PhysicMaterial brickPhysicsMaterial;

	private Mesh curvedTowerSegmentMesh;

	private MaterialPropertyBlock curvedTowerPropertyBlock;

	private BuilderStructure activeStructure;

	private string statusText = "Ready";

	private float statusUntil;

	private int structureCounter;

	private float rotationY;

	private int placementLayer;

	private int layerCycleIndex = -1;

	private float nextPlacementMaskScanTime;

	private float nextCrowdPressureScanTime;

	private float nextAutomaticSupportScanTime;

	private bool automaticSupportScanRunning;

	private Coroutine automaticSupportScanCoroutine;

	private int automaticSupportScanGeneration;

	private const int AutomaticSupportChecksPerFrame = 96;

	private readonly List<BuilderStructure> automaticSupportStructureSnapshot = new List<BuilderStructure>();

	private float lastProjectileImpactTime = -100f;

	private Vector3 lastProjectileImpactPoint = new Vector3(999999f, 999999f, 999999f);

	private float lastUnknownImpactLogTime = -100f;

	private bool placementMaskSummaryLogged;

	private bool layerCycleStarted;

	private FlagTeamMode flagTeamMode;

	private readonly List<Material> flagMaterials = new List<Material>();

	private Rect windowRect = new Rect(12f, 12f, 470f, 444f);

	private static PhysicsCastleBuilderPlugin instance;

	private Harmony battleResetHarmony;

	private bool battleResetBaselineReady;

	private bool battleResetInProgress;

	private int battleLifecycleGeneration;

	private Coroutine battleLifecycleCoroutine;

	private const string BattleResetHarmonyId = "com.openai.tabs.physicscastlebuilder.BattleResetRestore";

	private static readonly JsonSerializerSettings StructureJsonSettings = CreateStructureJsonSettings();

	private string SavePath => Path.Combine(Path.Combine(Paths.ConfigPath, "PhysicsCastleBuilder"), "structures.json");

	private Quaternion CurrentBuildRotation => Quaternion.Euler(0f, rotationY, 0f);

	private void Awake()
	{
		//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
		toggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "ToggleBuilder", (KeyCode)289, "Toggles the construction mode.");
		removeStructureKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "RemoveTargetStructure", (KeyCode)8, "Removes the complete Physics Castle Builder structure currently under the cursor. X still removes only one targeted brick; Delete still clears all construction.");
		placeMouseButtonConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Controls", "PlaceMouseButton", 2, "Mouse button used to place construction. 0=left, 1=right, 2=middle. Default 2 keeps normal left-click unit placement free.");
		maxBricksConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Performance", "MaximumBricksV040", 3000, "Maximum number of individual bricks allowed in one loaded scene (3x the previous default).");
		placementDistanceConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Performance", "PlacementDistance", 250f, "Maximum distance for aiming and placing construction pieces.");
		placementLayerNameConfig = ((BaseUnityPlugin)this).Config.Bind<string>("Placement", "UnitPlacementLayer", "Ground", "Layer assigned to construction colliders. It is included only in TABS PrimaryActionMask and removed from InvalidUnitPlacementMask. Press F9 to cycle available layers.");
		enableNamedUnitLayerCollisionsConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Placement", "EnableNamedUnitLayerCollisions", true, "Enables physics collision between the selected construction layer and common TABS unit/ground layers when those pairs were disabled by the game's layer matrix.");
		maximumDebrisFragmentsConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Destruction", "MaximumDebrisFragments", 800, "Hard cap on temporary dynamic stone fragments to protect performance during large collapses.");
		debrisLifetimeConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Destruction", "DebrisLifetimeSeconds", 14f, "How long small stone fragments remain before cleanup.");
		fractureImpactSpeedConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Destruction", "GroundImpactFractureSpeed", 7.5f, "Minimum impact speed for a released brick to fracture when it hits a static surface.");
		restoreStructuresAfterBattleResetConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "RestoreStructuresAfterBattleReset", true, "Automatically saves the current construction when a battle begins and restores it after the game's Reset Match / Restart Match command.");
		((BaseUnityPlugin)this).Config.SaveOnConfigSet = true;
		placementLayer = ResolvePlacementLayer(placementLayerNameConfig.Value);
		ApplyNamedLayerCollisionCompatibility();
		CreateBrickPhysicsMaterial();
		ApplyTabsPlacementMaskCompatibility();
		instance = this;
		if (restoreStructuresAfterBattleResetConfig.Value)
		{
			InstallBattleResetHooks();
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Physics Castle Builder 1.0.4 loaded (direct TABS integration / Newtonsoft save layer).");
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Construction mode is off by default. Press " + ((object)toggleKey.Value/*cast due to .constrained prefix*/).ToString() + " to enable it."));
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Controls: middle-click places construction; F1-F6 select building tools; F7 selects Flag; F8 toggles builder; Backspace removes the targeted structure; X removes one brick; Delete clears all; F9 cycles construction layers; F10 logs placement diagnostics; Q/E rotate; R resets rotation.");
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Construction colliders use layer '" + LayerMask.LayerToName(placementLayer) + "' (" + placementLayer + ")."));
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Unit placement compatibility targets only PlacementCursor.PrimaryActionMask (include construction layer) and InvalidUnitPlacementMask (exclude construction layer). Other TABS masks are left untouched.");
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Flag colors are manual only: choose Red or Blue in the builder menu; F11 switches between them. No automatic team detection is used.");
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Projectile damage is localized: the directly struck brick fractures; only genuinely unsupported structure sections are released.");
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Available Unity layers: " + GetAvailableLayers()));
	}

	private void InstallBattleResetHooks()
	{
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Expected O, but got Unknown
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c8: Expected O, but got Unknown
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Expected O, but got Unknown
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Expected O, but got Unknown
		try
		{
			MethodBase methodBase = AccessTools.Method(typeof(BaseGameMode), "OnEnterBattleState", (Type[])null, (Type[])null);
			MethodBase methodBase2 = AccessTools.Method(typeof(BaseGameMode), "RestartMatch", (Type[])null, (Type[])null);
			MethodBase methodBase3 = AccessTools.Method(typeof(BaseGameMode), "ResetMatch", (Type[])null, (Type[])null);
			MethodInfo methodInfo = AccessTools.Method(typeof(PhysicsCastleBuilderPlugin), "OnBattleEnteredPostfix", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(PhysicsCastleBuilderPlugin), "OnBattleResetPrefix", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(PhysicsCastleBuilderPlugin), "OnBattleResetPostfix", (Type[])null, (Type[])null);
			if (methodInfo == null || methodInfo2 == null || methodInfo3 == null)
			{
				throw new MissingMethodException("One or more Physics Castle Builder Harmony callbacks could not be resolved.");
			}
			battleResetHarmony = new Harmony("com.openai.tabs.physicscastlebuilder.BattleResetRestore");
			HarmonyMethod val = new HarmonyMethod(methodInfo);
			HarmonyMethod val2 = new HarmonyMethod(methodInfo2);
			HarmonyMethod val3 = new HarmonyMethod(methodInfo3);
			int num = 0;
			int num2 = 0;
			if (methodBase != null)
			{
				battleResetHarmony.Patch(methodBase, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				num++;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Hooked direct TABS lifecycle target: " + methodBase.DeclaringType.FullName + "." + methodBase.Name));
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"TABS BaseGameMode.OnEnterBattleState was not found; automatic battle baseline capture cannot be installed.");
			}
			if (methodBase2 != null)
			{
				battleResetHarmony.Patch(methodBase2, val2, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				num2++;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Hooked direct TABS lifecycle target: " + methodBase2.DeclaringType.FullName + "." + methodBase2.Name));
			}
			if (methodBase3 != null && methodBase3 != methodBase2)
			{
				battleResetHarmony.Patch(methodBase3, val2, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				num2++;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Hooked direct TABS lifecycle target: " + methodBase3.DeclaringType.FullName + "." + methodBase3.Name));
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Battle lifecycle integration installed through direct TABS references: Landfall.TABS.GameMode.BaseGameMode (enter=" + num + ", reset=" + num2 + ")."));
			if (num == 0 || num2 == 0)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Automatic battle-reset restoration is only partially available for this TABS build. Ctrl+S and Ctrl+L remain available.");
			}
		}
		catch (Exception ex)
		{
			if (battleResetHarmony != null)
			{
				try
				{
					battleResetHarmony.UnpatchSelf();
				}
				catch
				{
				}
				battleResetHarmony = null;
			}
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Battle reset hooks could not be installed: " + ex));
		}
	}

	private static void OnBattleEnteredPostfix()
	{
		if ((Object)(object)instance != (Object)null)
		{
			instance.QueueBattleBaselineCapture();
		}
	}

	private static void OnBattleResetPrefix()
	{
		if ((Object)(object)instance != (Object)null)
		{
			((BaseUnityPlugin)instance).Logger.LogInfo((object)"TABS battle-reset prefix received; preserving current construction baseline.");
			instance.battleResetInProgress = true;
			instance.battleLifecycleGeneration++;
			if (instance.battleLifecycleCoroutine != null)
			{
				((MonoBehaviour)instance).StopCoroutine(instance.battleLifecycleCoroutine);
				instance.battleLifecycleCoroutine = null;
			}
		}
	}

	private static void OnBattleResetPostfix()
	{
		if ((Object)(object)instance != (Object)null)
		{
			((BaseUnityPlugin)instance).Logger.LogInfo((object)"TABS battle-reset postfix received; scheduling structure restoration.");
			instance.QueueBattleResetRestore();
		}
	}

	private void QueueBattleBaselineCapture()
	{
		if (restoreStructuresAfterBattleResetConfig.Value && !battleResetInProgress)
		{
			int generation = ++battleLifecycleGeneration;
			if (battleLifecycleCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(battleLifecycleCoroutine);
			}
			battleLifecycleCoroutine = ((MonoBehaviour)this).StartCoroutine(CaptureBattleBaseline(generation));
		}
	}

	private IEnumerator CaptureBattleBaseline(int generation)
	{
		yield return null;
		yield return (object)new WaitForSecondsRealtime(0.25f);
		if (generation != battleLifecycleGeneration || battleResetInProgress)
		{
			yield break;
		}
		if (bricks.Count == 0)
		{
			battleResetBaselineReady = false;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Battle started without Physics Castle Builder bricks; automatic reset restoration is inactive for this battle.");
		}
		else
		{
			SaveStructures(automaticBaselineCapture: true);
			if (battleResetBaselineReady)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Captured the pre-destruction battle structure layout for automatic reset restoration.");
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Battle structure baseline capture failed; automatic reset restoration is unavailable until a valid save succeeds.");
			}
		}
		battleLifecycleCoroutine = null;
	}

	private void QueueBattleResetRestore()
	{
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Queueing battle structure restore: baselineReady=" + battleResetBaselineReady + ", saveExists=" + File.Exists(SavePath) + ", registeredBricks=" + bricks.Count + "."));
		if (!restoreStructuresAfterBattleResetConfig.Value)
		{
			battleResetInProgress = false;
			return;
		}
		int generation = ++battleLifecycleGeneration;
		if (battleLifecycleCoroutine != null)
		{
			((MonoBehaviour)this).StopCoroutine(battleLifecycleCoroutine);
		}
		battleLifecycleCoroutine = ((MonoBehaviour)this).StartCoroutine(RestoreBattleBaselineAfterReset(generation));
	}

	private IEnumerator RestoreBattleBaselineAfterReset(int generation)
	{
		yield return (object)new WaitForSecondsRealtime(1.5f);
		if (generation != battleLifecycleGeneration)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Battle reset restore was superseded by a newer TABS lifecycle event; skipping this stale restore.");
		}
		else if (!battleResetBaselineReady || !File.Exists(SavePath))
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Battle reset detected, but no non-empty structure baseline is available. No construction was changed.");
			battleResetInProgress = false;
			battleLifecycleCoroutine = null;
		}
		else
		{
			LoadStructures(afterBattleReset: true);
			battleResetInProgress = false;
			battleLifecycleCoroutine = null;
		}
	}

	private void RemoveBattleResetHooks()
	{
		if (battleResetHarmony != null)
		{
			try
			{
				battleResetHarmony.UnpatchSelf();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not remove battle reset hooks cleanly: " + ex.Message));
			}
			battleResetHarmony = null;
		}
	}

	private void Update()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		if (Input.GetKeyDown(toggleKey.Value))
		{
			builderEnabled = !builderEnabled;
			if (builderEnabled)
			{
				ApplyTabsPlacementMaskCompatibility();
			}
			SetStatus(builderEnabled ? "Builder enabled" : "Builder disabled");
		}
		if (Time.unscaledTime >= nextPlacementMaskScanTime)
		{
			nextPlacementMaskScanTime = Time.unscaledTime + 0.5f;
			ApplyTabsPlacementMaskCompatibility();
		}
		if (Time.unscaledTime >= nextCrowdPressureScanTime)
		{
			nextCrowdPressureScanTime = Time.unscaledTime + 0.5f;
			for (int num = structures.Count - 1; num >= 0; num--)
			{
				if ((Object)(object)structures[num] == (Object)null)
				{
					structures.RemoveAt(num);
				}
				else
				{
					structures[num].CheckCrowdPressure();
				}
			}
		}
		if (!automaticSupportScanRunning && Time.unscaledTime >= nextAutomaticSupportScanTime)
		{
			nextAutomaticSupportScanTime = Time.unscaledTime + 1f;
			automaticSupportStructureSnapshot.Clear();
			for (int i = 0; i < structures.Count; i++)
			{
				if ((Object)(object)structures[i] != (Object)null)
				{
					automaticSupportStructureSnapshot.Add(structures[i]);
				}
			}
			if (automaticSupportStructureSnapshot.Count > 0)
			{
				automaticSupportScanRunning = true;
				automaticSupportScanCoroutine = ((MonoBehaviour)this).StartCoroutine(RefreshAllStructureSupportIncrementally(automaticSupportScanGeneration));
			}
		}
		if (builderEnabled)
		{
			HandleToolSelection();
			HandleRotation();
			if (Input.GetKeyDown((KeyCode)291))
			{
				LogCursorAndPlacementDiagnostics();
			}
			if (Input.GetKeyDown((KeyCode)292))
			{
				CycleFlagTeamMode();
			}
			if (Input.GetKeyDown((KeyCode)290))
			{
				CyclePlacementLayer();
			}
			HandleBuilderActions();
		}
	}

	private IEnumerator RefreshAllStructureSupportIncrementally(int generation)
	{
		try
		{
			for (int i = 0; i < automaticSupportStructureSnapshot.Count; i++)
			{
				if (generation != automaticSupportScanGeneration)
				{
					break;
				}
				BuilderStructure builderStructure = automaticSupportStructureSnapshot[i];
				if ((Object)(object)builderStructure != (Object)null)
				{
					yield return builderStructure.CheckUnsupportedBricksIncremental(96);
				}
			}
		}
		finally
		{
			PhysicsCastleBuilderPlugin physicsCastleBuilderPlugin = this;
			if (generation == physicsCastleBuilderPlugin.automaticSupportScanGeneration)
			{
				physicsCastleBuilderPlugin.automaticSupportStructureSnapshot.Clear();
				physicsCastleBuilderPlugin.automaticSupportScanRunning = false;
				physicsCastleBuilderPlugin.automaticSupportScanCoroutine = null;
			}
		}
	}

	private void HandleToolSelection()
	{
		if (Input.GetKeyDown((KeyCode)282))
		{
			SelectTool(BuildTool.Brick);
		}
		if (Input.GetKeyDown((KeyCode)283))
		{
			SelectTool(BuildTool.Wall);
		}
		if (Input.GetKeyDown((KeyCode)284))
		{
			SelectTool(BuildTool.Tower);
		}
		if (Input.GetKeyDown((KeyCode)285))
		{
			SelectTool(BuildTool.Platform);
		}
		if (Input.GetKeyDown((KeyCode)286))
		{
			SelectTool(BuildTool.Stairs);
		}
		if (Input.GetKeyDown((KeyCode)287))
		{
			SelectTool(BuildTool.RaisedDeck);
		}
		if (Input.GetKeyDown((KeyCode)288))
		{
			SelectTool(BuildTool.Flag);
		}
	}

	private void HandleRotation()
	{
		if (Input.GetKeyDown((KeyCode)113))
		{
			rotationY -= 15f;
			SetStatus("Rotation: " + rotationY.ToString("0") + " degrees");
		}
		if (Input.GetKeyDown((KeyCode)101))
		{
			rotationY += 15f;
			SetStatus("Rotation: " + rotationY.ToString("0") + " degrees");
		}
		if (Input.GetKeyDown((KeyCode)114))
		{
			rotationY = 0f;
			SetStatus("Rotation reset");
		}
	}

	private void SelectTool(BuildTool tool)
	{
		selectedTool = tool;
		SetStatus("Selected: " + tool);
	}

	private void HandleBuilderActions()
	{
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		if (Input.GetMouseButtonDown(Mathf.Clamp(placeMouseButtonConfig.Value, 0, 6)) && !IsPointerOverBuilderWindow())
		{
			if (TryGetPlacementPosition(out var position))
			{
				BuildSelected(position);
			}
			else
			{
				SetStatus("No placement surface found under the cursor");
			}
		}
		if (Input.GetKeyDown((KeyCode)103))
		{
			ReleaseTargetedBrick();
		}
		if (Input.GetKeyDown((KeyCode)120))
		{
			RemoveTargetedBrick();
		}
		if (removeStructureKey != null && Input.GetKeyDown(removeStructureKey.Value))
		{
			RemoveTargetedStructure();
		}
		int num;
		if (!Input.GetKey((KeyCode)306))
		{
			num = (Input.GetKey((KeyCode)305) ? 1 : 0);
			if (num == 0)
			{
				goto IL_00a9;
			}
		}
		else
		{
			num = 1;
		}
		if (Input.GetKeyDown((KeyCode)115))
		{
			SaveStructures();
		}
		goto IL_00a9;
		IL_00a9:
		if (num != 0 && Input.GetKeyDown((KeyCode)108))
		{
			LoadStructures(afterBattleReset: false);
		}
		if (Input.GetKeyDown((KeyCode)127))
		{
			ClearStructures();
		}
	}

	private bool IsPointerOverBuilderWindow()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		Vector3 mousePosition = Input.mousePosition;
		Vector2 val = default(Vector2);
		((Vector2)(ref val))..ctor(mousePosition.x, (float)Screen.height - mousePosition.y);
		return ((Rect)(ref windowRect)).Contains(val);
	}

	private bool TryGetPlacementPosition(out Vector3 position)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0125: Unknown result type (might be due to invalid IL or missing references)
		position = Vector3.zero;
		Camera val = Camera.main;
		if ((Object)(object)val == (Object)null)
		{
			val = Object.FindObjectOfType<Camera>();
		}
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		RaycastHit[] array = Physics.RaycastAll(val.ScreenPointToRay(Input.mousePosition), placementDistanceConfig.Value, -1, (QueryTriggerInteraction)1);
		Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance));
		for (int num = 0; num < array.Length; num++)
		{
			RaycastHit hit = array[num];
			Collider collider = ((RaycastHit)(ref hit)).collider;
			if ((Object)(object)collider == (Object)null || collider.isTrigger || IsLikelyUnitCollider(collider) || IsPlacementHelperCollider(collider))
			{
				continue;
			}
			BuilderBrick componentInParent = ((Component)collider).GetComponentInParent<BuilderBrick>();
			Rigidbody attachedRigidbody = collider.attachedRigidbody;
			if (!((Object)(object)attachedRigidbody != (Object)null) || attachedRigidbody.isKinematic || !((Object)(object)componentInParent == (Object)null))
			{
				if ((Object)(object)componentInParent != (Object)null)
				{
					position = SnapPlacement(hit, onExistingBrick: true);
					return true;
				}
				if (IsLikelyGroundSurfaceCollider(collider) && ((RaycastHit)(ref hit)).normal.y >= 0.2f)
				{
					position = SnapPlacement(hit, onExistingBrick: false);
					return true;
				}
			}
		}
		return false;
	}

	private bool IsPlacementHelperCollider(Collider collider)
	{
		Transform val = (((Object)(object)collider != (Object)null) ? ((Component)collider).transform : null);
		while ((Object)(object)val != (Object)null)
		{
			string text = (((Object)val).name ?? string.Empty).ToLowerInvariant();
			if (text.Contains("placementcursor") || text.Contains("placement_cursor") || text.Contains("placement square") || text.Contains("placementsquare") || text.Contains("groundcaster") || text.Contains("groundchecker") || text.Contains("placementbrush") || text.Contains("placement_brush") || text.Contains("preview") || text.Contains("ghost"))
			{
				return true;
			}
			val = val.parent;
		}
		Component[] componentsInParent = ((Component)collider).GetComponentsInParent<Component>();
		for (int i = 0; i < componentsInParent.Length; i++)
		{
			if (!((Object)(object)componentsInParent[i] == (Object)null))
			{
				string name = ((object)componentsInParent[i]).GetType().Name;
				if (name.IndexOf("PlacementCursor", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("UnitPlacementBrush", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("GroundCaster", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("GroundChecker", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return true;
				}
			}
		}
		return false;
	}

	private bool IsLikelyGroundSurfaceCollider(Collider collider)
	{
		if ((Object)(object)collider == (Object)null)
		{
			return false;
		}
		if (((Component)collider).gameObject.layer == placementLayer)
		{
			return true;
		}
		string text = (LayerMask.LayerToName(((Component)collider).gameObject.layer) ?? string.Empty).ToLowerInvariant();
		if (text.Contains("ground") || text.Contains("terrain") || text.Contains("environment") || text.Contains("map"))
		{
			return true;
		}
		string text2 = string.Empty;
		try
		{
			text2 = ((Component)collider).tag ?? string.Empty;
		}
		catch
		{
		}
		switch (text2.ToLowerInvariant())
		{
		case "ground":
		case "terrain":
		case "map":
			return true;
		default:
		{
			if (((object)collider).GetType().Name.IndexOf("TerrainCollider", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			Transform val = ((Component)collider).transform;
			while ((Object)(object)val != (Object)null)
			{
				string text3 = (((Object)val).name ?? string.Empty).ToLowerInvariant();
				if (text3.Contains("terrain") || text3.Contains("ground") || text3.Contains("mapground") || text3 == "map" || text3.Contains("floor"))
				{
					return true;
				}
				val = val.parent;
			}
			return false;
		}
		}
	}

	private bool IsLikelyUnitCollider(Collider collider)
	{
		Transform val = (((Object)(object)collider != (Object)null) ? ((Component)collider).transform : null);
		while ((Object)(object)val != (Object)null)
		{
			string text = ((Object)val).name ?? string.Empty;
			if (text.IndexOf("unit", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("character", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("soldier", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("ragdoll", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			val = val.parent;
		}
		Component[] array = (((Object)(object)collider != (Object)null) ? ((Component)collider).GetComponentsInParent<Component>() : null);
		if (array != null)
		{
			for (int i = 0; i < array.Length; i++)
			{
				if (!((Object)(object)array[i] == (Object)null))
				{
					string name = ((object)array[i]).GetType().Name;
					if (name == "Unit" || name.IndexOf("UnitRig", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("Character", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						return true;
					}
				}
			}
		}
		return false;
	}

	private Vector3 SnapPlacement(RaycastHit hit, bool onExistingBrick)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		float num = Mathf.Max(0.004f, Physics.defaultContactOffset * 0.5f);
		Vector3 val = Vector3.up * (0.25f + num);
		if (onExistingBrick && ((RaycastHit)(ref hit)).normal.y < 0.55f)
		{
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(((RaycastHit)(ref hit)).normal.x, 0f, ((RaycastHit)(ref hit)).normal.z);
			if (((Vector3)(ref val2)).sqrMagnitude > 0.0001f)
			{
				((Vector3)(ref val2)).Normalize();
				return ((RaycastHit)(ref hit)).point + val2 * (0.25f + num) + val;
			}
		}
		return ((RaycastHit)(ref hit)).point + val;
	}

	private void BeginStructure(string label)
	{
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Expected O, but got Unknown
		EnsureBuildRoot();
		int num = ++structureCounter;
		GameObject val = new GameObject("PhysicsCastle_" + label + "_" + num);
		val.transform.SetParent(buildRoot.transform, false);
		activeStructure = val.AddComponent<BuilderStructure>();
		activeStructure.Initialize(this, placementLayer);
		structures.Add(activeStructure);
	}

	private void EndStructure()
	{
		activeStructure = null;
	}

	private void BuildSelected(Vector3 origin)
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		BeginStructure(selectedTool.ToString());
		Quaternion currentBuildRotation = CurrentBuildRotation;
		switch (selectedTool)
		{
		case BuildTool.Brick:
			CreateBrick(origin, currentBuildRotation, new Vector3(1f, 0.5f, 0.5f), makeDynamic: false);
			break;
		case BuildTool.Wall:
			BuildWall(origin, currentBuildRotation);
			break;
		case BuildTool.Tower:
			BuildTower(origin, currentBuildRotation);
			break;
		case BuildTool.Platform:
			BuildPlatform(origin, currentBuildRotation);
			break;
		case BuildTool.Stairs:
			BuildStairs(origin, currentBuildRotation);
			break;
		case BuildTool.RaisedDeck:
			BuildRaisedDeck(origin, currentBuildRotation);
			break;
		case BuildTool.Flag:
			BuildFlag(origin, currentBuildRotation);
			break;
		}
		BuilderStructure builderStructure = activeStructure;
		EndStructure();
		Physics.SyncTransforms();
		if ((Object)(object)builderStructure != (Object)null)
		{
			builderStructure.CheckUnsupportedBricks();
			((MonoBehaviour)this).StartCoroutine(RefreshStructureSupport(builderStructure));
		}
		if (restoreStructuresAfterBattleResetConfig != null && restoreStructuresAfterBattleResetConfig.Value && bricks.Count > 0)
		{
			SaveStructures(automaticBaselineCapture: true);
		}
	}

	private IEnumerator RefreshStructureSupport(BuilderStructure structure)
	{
		float[] checkpoints = new float[7] { 0.08f, 0.2f, 0.42f, 0.72f, 1.1f, 1.6f, 2.2f };
		float num = 0f;
		for (int i = 0; i < checkpoints.Length; i++)
		{
			float num2 = checkpoints[i] - num;
			if (num2 > 0f)
			{
				yield return (object)new WaitForSecondsRealtime(num2);
			}
			num = checkpoints[i];
			if ((Object)(object)structure == (Object)null)
			{
				break;
			}
			Physics.SyncTransforms();
			structure.CheckUnsupportedBricks();
		}
	}

	private void BuildWall(Vector3 origin, Quaternion rotation)
	{
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = default(Vector3);
		for (int i = 0; i < 8; i++)
		{
			float num = ((i % 2 == 0) ? 0f : 0.5f);
			for (int j = 0; j < 2; j++)
			{
				float num2 = ((float)j - 0.5f) * 0.5f;
				for (int k = 0; k < 10; k++)
				{
					float num3 = ((float)k - 4.5f) * 1f + num;
					((Vector3)(ref val))..ctor(num3, (float)i * 0.5f, num2);
					Vector3 position = origin + rotation * val;
					if ((Object)(object)CreateBrick(position, rotation, new Vector3(1f, 0.5f, 0.5f), makeDynamic: false) == (Object)null)
					{
						return;
					}
				}
			}
		}
		SetStatus("Wall placed");
	}

	private void BuildTower(Vector3 origin, Quaternion rotation)
	{
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: Unknown result type (might be due to invalid IL or missing references)
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_018f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0190: Unknown result type (might be due to invalid IL or missing references)
		//IL_0192: Unknown result type (might be due to invalid IL or missing references)
		//IL_0197: Unknown result type (might be due to invalid IL or missing references)
		//IL_019c: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		Vector3 size = default(Vector3);
		((Vector3)(ref size))..ctor(0.9f, 0.5f, 0.55f);
		Vector3 val = default(Vector3);
		for (int i = 0; i < 8; i++)
		{
			for (int j = 0; j < 16; j++)
			{
				float num = MathF.PI * 2f * (float)j / 16f;
				((Vector3)(ref val))..ctor(Mathf.Cos(num), 0f, Mathf.Sin(num));
				Vector3 val2 = val * 2.25f + Vector3.up * ((float)i * 0.5f);
				Vector3 position = origin + rotation * val2;
				Quaternion rotation2 = rotation * Quaternion.LookRotation(val, Vector3.up);
				if ((Object)(object)CreateCurvedTowerSegment(position, rotation2, size, makeDynamic: false) == (Object)null)
				{
					return;
				}
			}
		}
		Vector3 val3 = default(Vector3);
		for (int k = 0; k < 8; k++)
		{
			for (int l = 0; l < 4; l++)
			{
				for (int m = 0; m < 4; m++)
				{
					((Vector3)(ref val3))..ctor((float)l - 1.5f, (float)k * 0.5f, (float)m - 1.5f);
					if ((Object)(object)CreateBrick(origin + rotation * val3, rotation, new Vector3(1f, 0.5f, 1f), makeDynamic: false) == (Object)null)
					{
						return;
					}
				}
			}
		}
		float num2 = 4f;
		Vector3 size2 = default(Vector3);
		((Vector3)(ref size2))..ctor(1f, 0.5f, 1f);
		Vector3 val4 = default(Vector3);
		for (int n = 0; n < 5; n++)
		{
			for (int num3 = 0; num3 < 5; num3++)
			{
				((Vector3)(ref val4))..ctor((float)n - 2f, num2, (float)num3 - 2f);
				if ((Object)(object)CreateBrick(origin + rotation * val4, rotation, size2, makeDynamic: false) == (Object)null)
				{
					return;
				}
			}
		}
		BuildCrenellatedPerimeter(origin, rotation, 5, 5, num2 + 0.25f);
		SetStatus("Tower placed with a walkable top platform and crenellated battlements");
	}

	private BuilderBrick CreateCurvedTowerSegment(Vector3 position, Quaternion rotation, Vector3 size, bool makeDynamic)
	{
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Expected O, but got Unknown
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		if (bricks.Count >= Mathf.Max(1, maxBricksConfig.Value))
		{
			SetStatus("Brick limit reached. Clear or remove some bricks first.");
			return null;
		}
		if ((Object)(object)activeStructure == (Object)null)
		{
			BeginStructure("LoosePieces");
		}
		GameObject obj = GameObject.CreatePrimitive((PrimitiveType)3);
		((Object)obj).name = "PhysicsCastle_Brick";
		obj.layer = placementLayer;
		obj.transform.SetParent(((Component)activeStructure).transform, true);
		obj.transform.position = position;
		obj.transform.rotation = rotation;
		obj.transform.localScale = size;
		MeshFilter component = obj.GetComponent<MeshFilter>();
		if ((Object)(object)component != (Object)null)
		{
			if ((Object)(object)curvedTowerSegmentMesh == (Object)null)
			{
				curvedTowerSegmentMesh = CreateCurvedTowerSegmentMesh(size);
			}
			component.sharedMesh = curvedTowerSegmentMesh;
		}
		Renderer component2 = obj.GetComponent<Renderer>();
		if ((Object)(object)component2 != (Object)null)
		{
			EnsureStoneMaterial();
			if ((Object)(object)stoneMaterial != (Object)null)
			{
				component2.sharedMaterial = stoneMaterial;
			}
			if (curvedTowerPropertyBlock == null)
			{
				curvedTowerPropertyBlock = new MaterialPropertyBlock();
				Color val = default(Color);
				((Color)(ref val))..ctor(Random.Range(0.78f, 0.94f), Random.Range(0.78f, 0.94f), Random.Range(0.78f, 0.94f), 1f);
				curvedTowerPropertyBlock.SetColor("_Color", val);
			}
			component2.SetPropertyBlock(curvedTowerPropertyBlock);
		}
		Collider component3 = obj.GetComponent<Collider>();
		if ((Object)(object)component3 != (Object)null)
		{
			component3.isTrigger = false;
			component3.contactOffset = Mathf.Max(0.001f, Physics.defaultContactOffset);
			if ((Object)(object)brickPhysicsMaterial != (Object)null)
			{
				component3.sharedMaterial = brickPhysicsMaterial;
			}
		}
		Rigidbody val2 = obj.AddComponent<Rigidbody>();
		val2.mass = Mathf.Max(0.5f, size.x * size.y * size.z * 12f);
		val2.drag = 0.05f;
		val2.angularDrag = 0.35f;
		val2.useGravity = true;
		val2.interpolation = (RigidbodyInterpolation)1;
		val2.isKinematic = !makeDynamic;
		val2.solverIterations = 12;
		val2.solverVelocityIterations = 12;
		val2.collisionDetectionMode = (CollisionDetectionMode)(makeDynamic ? 2 : 0);
		BuilderBrick builderBrick = obj.AddComponent<BuilderBrick>();
		builderBrick.Initialize(val2, makeDynamic, activeStructure, placementLayer, this, curvedTowerSegment: true);
		activeStructure.Register(builderBrick);
		bricks.Add(builderBrick);
		return builderBrick;
	}

	private Mesh CreateCurvedTowerSegmentMesh(Vector3 size)
	{
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_0145: Unknown result type (might be due to invalid IL or missing references)
		//IL_0157: Unknown result type (might be due to invalid IL or missing references)
		//IL_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_016b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_0176: Unknown result type (might be due to invalid IL or missing references)
		//IL_017a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Unknown result type (might be due to invalid IL or missing references)
		//IL_019c: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01af: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01db: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_020b: Unknown result type (might be due to invalid IL or missing references)
		//IL_020c: Unknown result type (might be due to invalid IL or missing references)
		//IL_021e: Unknown result type (might be due to invalid IL or missing references)
		//IL_021f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0231: Unknown result type (might be due to invalid IL or missing references)
		//IL_0232: Unknown result type (might be due to invalid IL or missing references)
		//IL_0244: Unknown result type (might be due to invalid IL or missing references)
		//IL_0245: Unknown result type (might be due to invalid IL or missing references)
		//IL_024a: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0254: Unknown result type (might be due to invalid IL or missing references)
		//IL_0259: Unknown result type (might be due to invalid IL or missing references)
		//IL_025e: Unknown result type (might be due to invalid IL or missing references)
		//IL_027d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0291: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_02af: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02da: Unknown result type (might be due to invalid IL or missing references)
		//IL_02df: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0306: Unknown result type (might be due to invalid IL or missing references)
		//IL_0307: Unknown result type (might be due to invalid IL or missing references)
		//IL_0319: Unknown result type (might be due to invalid IL or missing references)
		//IL_031a: Unknown result type (might be due to invalid IL or missing references)
		//IL_032c: Unknown result type (might be due to invalid IL or missing references)
		//IL_032d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0332: Unknown result type (might be due to invalid IL or missing references)
		//IL_0334: Unknown result type (might be due to invalid IL or missing references)
		//IL_0336: Unknown result type (might be due to invalid IL or missing references)
		//IL_0338: Unknown result type (might be due to invalid IL or missing references)
		//IL_033a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0353: Unknown result type (might be due to invalid IL or missing references)
		//IL_0354: Unknown result type (might be due to invalid IL or missing references)
		//IL_0366: Unknown result type (might be due to invalid IL or missing references)
		//IL_0367: Unknown result type (might be due to invalid IL or missing references)
		//IL_0379: Unknown result type (might be due to invalid IL or missing references)
		//IL_037a: Unknown result type (might be due to invalid IL or missing references)
		//IL_038c: Unknown result type (might be due to invalid IL or missing references)
		//IL_038d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0392: Unknown result type (might be due to invalid IL or missing references)
		//IL_0394: Unknown result type (might be due to invalid IL or missing references)
		//IL_0396: Unknown result type (might be due to invalid IL or missing references)
		//IL_0398: Unknown result type (might be due to invalid IL or missing references)
		//IL_039a: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d0: Expected O, but got Unknown
		float num = MathF.PI / 16f;
		float radius = 1.975f;
		float radius2 = 2.525f;
		List<Vector3> vertices = new List<Vector3>(256);
		List<Vector3> normals = new List<Vector3>(256);
		List<int> list = new List<int>(384);
		for (int i = 0; i < 6; i++)
		{
			float num2 = 0f - num + 2f * num * (float)i / 6f;
			float num3 = 0f - num + 2f * num * (float)(i + 1) / 6f;
			float angle = (num2 + num3) * 0.5f;
			Vector3 val = CurvedTowerNormal(num2, size, 1f);
			Vector3 val2 = CurvedTowerNormal(num3, size, 1f);
			Vector3 val3 = CurvedTowerNormal(num2, size, -1f);
			Vector3 val4 = CurvedTowerNormal(num3, size, -1f);
			AddCurvedTowerQuad(vertices, normals, list, CurvedTowerPoint(radius2, num2, -0.25f, 2.25f, size), CurvedTowerPoint(radius2, num3, -0.25f, 2.25f, size), CurvedTowerPoint(radius2, num3, 0.25f, 2.25f, size), CurvedTowerPoint(radius2, num2, 0.25f, 2.25f, size), val, val2, val2, val, CurvedTowerNormal(angle, size, 1f));
			AddCurvedTowerQuad(vertices, normals, list, CurvedTowerPoint(radius, num2, -0.25f, 2.25f, size), CurvedTowerPoint(radius, num2, 0.25f, 2.25f, size), CurvedTowerPoint(radius, num3, 0.25f, 2.25f, size), CurvedTowerPoint(radius, num3, -0.25f, 2.25f, size), val3, val3, val4, val4, CurvedTowerNormal(angle, size, -1f));
			AddCurvedTowerQuad(vertices, normals, list, CurvedTowerPoint(radius, num2, 0.25f, 2.25f, size), CurvedTowerPoint(radius2, num2, 0.25f, 2.25f, size), CurvedTowerPoint(radius2, num3, 0.25f, 2.25f, size), CurvedTowerPoint(radius, num3, 0.25f, 2.25f, size), Vector3.up, Vector3.up, Vector3.up, Vector3.up, Vector3.up);
			AddCurvedTowerQuad(vertices, normals, list, CurvedTowerPoint(radius, num2, -0.25f, 2.25f, size), CurvedTowerPoint(radius, num3, -0.25f, 2.25f, size), CurvedTowerPoint(radius2, num3, -0.25f, 2.25f, size), CurvedTowerPoint(radius2, num2, -0.25f, 2.25f, size), Vector3.down, Vector3.down, Vector3.down, Vector3.down, Vector3.down);
		}
		float num4 = 0f - num;
		float num5 = num;
		Vector3 val5 = new Vector3((0f - size.x) * Mathf.Cos(num4), 0f, size.z * Mathf.Sin(num4));
		Vector3 normalized = ((Vector3)(ref val5)).normalized;
		val5 = new Vector3(size.x * Mathf.Cos(num5), 0f, (0f - size.z) * Mathf.Sin(num5));
		Vector3 normalized2 = ((Vector3)(ref val5)).normalized;
		AddCurvedTowerQuad(vertices, normals, list, CurvedTowerPoint(radius, num4, -0.25f, 2.25f, size), CurvedTowerPoint(radius2, num4, -0.25f, 2.25f, size), CurvedTowerPoint(radius2, num4, 0.25f, 2.25f, size), CurvedTowerPoint(radius, num4, 0.25f, 2.25f, size), normalized, normalized, normalized, normalized, normalized);
		AddCurvedTowerQuad(vertices, normals, list, CurvedTowerPoint(radius, num5, -0.25f, 2.25f, size), CurvedTowerPoint(radius2, num5, -0.25f, 2.25f, size), CurvedTowerPoint(radius2, num5, 0.25f, 2.25f, size), CurvedTowerPoint(radius, num5, 0.25f, 2.25f, size), normalized2, normalized2, normalized2, normalized2, normalized2);
		Mesh val6 = new Mesh
		{
			name = "PhysicsCastle_SmoothCurvedTowerSegment"
		};
		val6.SetVertices(vertices);
		val6.SetNormals(normals);
		val6.SetTriangles(list, 0);
		val6.RecalculateBounds();
		return val6;
	}

	private static Vector3 CurvedTowerPoint(float radius, float angle, float y, float centerRadius, Vector3 size)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(radius * Mathf.Sin(angle) / Mathf.Max(0.001f, size.x), y / Mathf.Max(0.001f, size.y), (radius * Mathf.Cos(angle) - centerRadius) / Mathf.Max(0.001f, size.z));
	}

	private static Vector3 CurvedTowerNormal(float angle, Vector3 size, float direction)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = new Vector3(direction * size.x * Mathf.Sin(angle), 0f, direction * size.z * Mathf.Cos(angle));
		return ((Vector3)(ref val)).normalized;
	}

	private static void AddCurvedTowerQuad(List<Vector3> vertices, List<Vector3> normals, List<int> triangles, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 n0, Vector3 n1, Vector3 n2, Vector3 n3, Vector3 outward)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		if (Vector3.Dot(Vector3.Cross(p1 - p0, p2 - p0), outward) < 0f)
		{
			Vector3 val = p1;
			p1 = p3;
			p3 = val;
			Vector3 val2 = n1;
			n1 = n3;
			n3 = val2;
		}
		int count = vertices.Count;
		vertices.Add(p0);
		vertices.Add(p1);
		vertices.Add(p2);
		vertices.Add(p3);
		normals.Add(((Vector3)(ref n0)).normalized);
		normals.Add(((Vector3)(ref n1)).normalized);
		normals.Add(((Vector3)(ref n2)).normalized);
		normals.Add(((Vector3)(ref n3)).normalized);
		triangles.Add(count);
		triangles.Add(count + 1);
		triangles.Add(count + 2);
		triangles.Add(count);
		triangles.Add(count + 2);
		triangles.Add(count + 3);
	}

	private void BuildCrenellatedPerimeter(Vector3 origin, Quaternion rotation, int widthCount, int depthCount, float wallTopSurfaceY)
	{
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		if (widthCount < 2 || depthCount < 2)
		{
			return;
		}
		Vector3 size = default(Vector3);
		((Vector3)(ref size))..ctor(1f, 0.5f, 0.5f);
		float num = wallTopSurfaceY + 0.25f;
		float num2 = (float)(widthCount - 1) * 0.5f;
		float num3 = (float)(depthCount - 1) * 0.5f;
		Vector3 val = default(Vector3);
		Vector3 val2 = default(Vector3);
		for (int i = 0; i < widthCount; i++)
		{
			if ((i & 1) == 0)
			{
				float num4 = (float)i - num2;
				((Vector3)(ref val))..ctor(num4, num, 0f - num3);
				((Vector3)(ref val2))..ctor(num4, num, num3);
				if ((Object)(object)CreateBrick(origin + rotation * val, rotation, size, makeDynamic: false) == (Object)null || (Object)(object)CreateBrick(origin + rotation * val2, rotation, size, makeDynamic: false) == (Object)null)
				{
					return;
				}
			}
		}
		Vector3 size2 = default(Vector3);
		((Vector3)(ref size2))..ctor(0.5f, 0.5f, 1f);
		Vector3 val3 = default(Vector3);
		Vector3 val4 = default(Vector3);
		for (int j = 1; j < depthCount - 1; j++)
		{
			if ((j & 1) == 0)
			{
				float num5 = (float)j - num3;
				((Vector3)(ref val3))..ctor(0f - num2, num, num5);
				((Vector3)(ref val4))..ctor(num2, num, num5);
				if ((Object)(object)CreateBrick(origin + rotation * val3, rotation, size2, makeDynamic: false) == (Object)null || (Object)(object)CreateBrick(origin + rotation * val4, rotation, size2, makeDynamic: false) == (Object)null)
				{
					break;
				}
			}
		}
	}

	private void BuildRaisedDeck(Vector3 origin, Quaternion rotation)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_0114: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0228: Unknown result type (might be due to invalid IL or missing references)
		//IL_0229: Unknown result type (might be due to invalid IL or missing references)
		//IL_022a: Unknown result type (might be due to invalid IL or missing references)
		//IL_022c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0231: Unknown result type (might be due to invalid IL or missing references)
		//IL_0236: Unknown result type (might be due to invalid IL or missing references)
		//IL_0237: Unknown result type (might be due to invalid IL or missing references)
		Vector3 size = default(Vector3);
		((Vector3)(ref size))..ctor(1f, 0.5f, 0.5f);
		Quaternion rotation2 = rotation * Quaternion.Euler(0f, 90f, 0f);
		Vector3 leftWallLine = origin + rotation * new Vector3(-2.5f, 0f, 0f);
		Vector3 rightWallLine = origin + rotation * new Vector3(2.5f, 0f, 0f);
		Vector3 wallForward = rotation * Vector3.forward;
		float num = origin.y + 3.5f;
		if ((Object)(object)activeStructure != (Object)null)
		{
			activeStructure.ConfigureRaisedDeckBridgeSupport(leftWallLine, rightWallLine, wallForward, num);
		}
		float[] array = new float[2] { -2.5f, 2.5f };
		Vector3 val = default(Vector3);
		for (int i = 0; i < array.Length; i++)
		{
			for (int j = 0; j < 7; j++)
			{
				for (int k = 0; k < 8; k++)
				{
					for (int l = 0; l < 2; l++)
					{
						float num2 = array[i] + ((l == 0) ? (-0.25f) : 0.25f);
						float num3 = (float)k - 3.5f;
						((Vector3)(ref val))..ctor(num2, (float)j * 0.5f, num3);
						if ((Object)(object)CreateBrick(origin + rotation * val, rotation2, size, makeDynamic: false) == (Object)null)
						{
							return;
						}
					}
				}
			}
		}
		Vector3 val2 = default(Vector3);
		for (int m = 0; m < 9; m++)
		{
			for (int n = 0; n < 8; n++)
			{
				float num4 = ((float)m - 4f) * 0.5f;
				float num5 = (float)n - 3.5f;
				((Vector3)(ref val2))..ctor(num4, 3.5f, num5);
				if ((Object)(object)CreateBrick(origin + rotation * val2, rotation2, size, makeDynamic: false) == (Object)null)
				{
					return;
				}
			}
		}
		Vector3 val3 = default(Vector3);
		for (int num6 = 0; num6 < array.Length; num6++)
		{
			float num7 = ((num6 == 0) ? (-2f) : 2f);
			for (int num8 = 0; num8 < 4; num8++)
			{
				float num9 = -3.5f + (float)num8 * 2f;
				for (int num10 = 0; num10 < 3; num10++)
				{
					float num11 = num + 0.5f * (float)(num10 + 1);
					((Vector3)(ref val3))..ctor(num7, num11, num9);
					if ((Object)(object)CreateBrick(origin + rotation * val3, rotation2, size, makeDynamic: false) == (Object)null)
					{
						return;
					}
				}
			}
		}
		SetStatus("Archer Stand placed: raised platform with triple-height supported crenellations");
	}

	private void BuildFlag(Vector3 origin, Quaternion rotation)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_021c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0339: Unknown result type (might be due to invalid IL or missing references)
		//IL_033e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0358: Unknown result type (might be due to invalid IL or missing references)
		//IL_035d: Unknown result type (might be due to invalid IL or missing references)
		//IL_036b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0387: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03df: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_03fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0406: Unknown result type (might be due to invalid IL or missing references)
		//IL_040c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0418: Unknown result type (might be due to invalid IL or missing references)
		EnsureBuildRoot();
		GameObject val = new GameObject("PhysicsCastle_TeamFlag");
		val.transform.SetParent(((Component)activeStructure).transform, true);
		val.transform.position = origin - rotation * Vector3.up * 0.25f;
		val.transform.rotation = rotation;
		BuilderBrick builderBrick = FindFlagSupportBrick(val.transform.position);
		Rigidbody val2 = (((Object)(object)builderBrick != (Object)null) ? ((Component)builderBrick).GetComponent<Rigidbody>() : null);
		GameObject val3 = GameObject.CreatePrimitive((PrimitiveType)2);
		((Object)val3).name = "PhysicsCastle_FlagPole_Lower";
		val3.layer = placementLayer;
		val3.transform.SetParent(val.transform, false);
		val3.transform.localPosition = new Vector3(0f, 0.66f, 0f);
		val3.transform.localRotation = Quaternion.identity;
		val3.transform.localScale = new Vector3(0.14f, 0.66f, 0.14f);
		Rigidbody val4 = val3.AddComponent<Rigidbody>();
		val4.mass = 1.8f;
		val4.useGravity = true;
		val4.isKinematic = true;
		val4.interpolation = (RigidbodyInterpolation)1;
		Collider component = val3.GetComponent<Collider>();
		if ((Object)(object)component != (Object)null && (Object)(object)brickPhysicsMaterial != (Object)null)
		{
			component.sharedMaterial = brickPhysicsMaterial;
		}
		SetPoleMaterial(val3);
		FixedJoint val5 = null;
		if ((Object)(object)val2 != (Object)null)
		{
			val5 = val3.AddComponent<FixedJoint>();
			((Joint)val5).connectedBody = val2;
			((Joint)val5).autoConfigureConnectedAnchor = true;
			((Joint)val5).breakForce = 50000f;
			((Joint)val5).breakTorque = 50000f;
			((Joint)val5).enableCollision = false;
		}
		GameObject val6 = GameObject.CreatePrimitive((PrimitiveType)2);
		((Object)val6).name = "PhysicsCastle_FlagPole_Upper";
		val6.layer = placementLayer;
		val6.transform.SetParent(val.transform, false);
		val6.transform.localPosition = new Vector3(0f, 1.72f, 0f);
		val6.transform.localRotation = Quaternion.identity;
		val6.transform.localScale = new Vector3(0.14f, 0.55f, 0.14f);
		Rigidbody val7 = val6.AddComponent<Rigidbody>();
		val7.mass = 1.25f;
		val7.useGravity = true;
		val7.isKinematic = true;
		val7.interpolation = (RigidbodyInterpolation)1;
		val7.collisionDetectionMode = (CollisionDetectionMode)2;
		Collider component2 = val6.GetComponent<Collider>();
		if ((Object)(object)component2 != (Object)null && (Object)(object)brickPhysicsMaterial != (Object)null)
		{
			component2.sharedMaterial = brickPhysicsMaterial;
		}
		SetPoleMaterial(val6);
		FixedJoint val8 = val6.AddComponent<FixedJoint>();
		((Joint)val8).connectedBody = val4;
		((Joint)val8).breakForce = 950f;
		((Joint)val8).breakTorque = 700f;
		val6.AddComponent<BreakableFlagPoleSegment>().Initialize(val7, val8, 5f);
		if ((Object)(object)val2 != (Object)null)
		{
			val.AddComponent<FlagBaseAttachment>().Initialize(builderBrick, val2, val4, val7, val5);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Flag base attached to support brick '" + ((Object)builderBrick).name + "'. The complete pole will follow that brick and release if its support is lost."));
		}
		else
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Flag placed without a builder-brick support; lower pole remains world-anchored.");
		}
		ResolveFlagColor(out var color, out var teamLabel);
		GameObject val9 = new GameObject("PhysicsCastle_BlankWaving" + teamLabel + "Flag");
		val9.transform.SetParent(val6.transform, false);
		Vector3 localScale = val6.transform.localScale;
		Vector3 val10 = default(Vector3);
		((Vector3)(ref val10))..ctor(1f / Mathf.Max(0.001f, Mathf.Abs(localScale.x)), 1f / Mathf.Max(0.001f, Mathf.Abs(localScale.y)), 1f / Mathf.Max(0.001f, Mathf.Abs(localScale.z)));
		val9.layer = val6.layer;
		val9.transform.localPosition = new Vector3(0.055f * val10.x, 0.55f * val10.y, 0f);
		val9.transform.localRotation = Quaternion.identity;
		val9.transform.localScale = val10;
		val9.AddComponent<WavingTeamFlag>().Initialize(color, 1.25f, 0.72f);
		SetStatus(teamLabel + " blank flag placed; upper pole segment can break away");
	}

	private BuilderBrick FindFlagSupportBrick(Vector3 poleFootPosition)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		RaycastHit[] array = Physics.RaycastAll(poleFootPosition + Vector3.up * 0.18f, Vector3.down, 0.68f, -1, (QueryTriggerInteraction)1);
		Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance));
		for (int num = 0; num < array.Length; num++)
		{
			Collider collider = ((RaycastHit)(ref array[num])).collider;
			if (!((Object)(object)collider == (Object)null) && collider.enabled && !collider.isTrigger && !(((RaycastHit)(ref array[num])).normal.y < 0.55f))
			{
				BuilderBrick componentInParent = ((Component)collider).GetComponentInParent<BuilderBrick>();
				if (!((Object)(object)componentInParent == (Object)null) && !((Object)(object)((Component)componentInParent).GetComponent<Rigidbody>() == (Object)null))
				{
					return componentInParent;
				}
			}
		}
		return null;
	}

	private void SetPoleMaterial(GameObject pole)
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Expected O, but got Unknown
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)pole == (Object)null)
		{
			return;
		}
		Renderer component = pole.GetComponent<Renderer>();
		if (!((Object)(object)component == (Object)null))
		{
			Shader val = Shader.Find("Standard");
			if ((Object)(object)val == (Object)null)
			{
				val = Shader.Find("Diffuse");
			}
			if ((Object)(object)val != (Object)null)
			{
				Material val2 = new Material(val);
				val2.color = new Color(0.34f, 0.25f, 0.16f, 1f);
				component.sharedMaterial = val2;
				flagMaterials.Add(val2);
			}
		}
	}

	private void ResolveFlagColor(out Color color, out string teamLabel)
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		if (flagTeamMode == FlagTeamMode.Blue)
		{
			color = new Color(0.08f, 0.28f, 0.88f, 1f);
			teamLabel = "Blue";
		}
		else
		{
			color = new Color(0.86f, 0.08f, 0.08f, 1f);
			teamLabel = "Red";
		}
	}

	private void SetFlagTeamMode(FlagTeamMode mode)
	{
		flagTeamMode = mode;
		SetStatus("Manual flag color set to " + flagTeamMode.ToString() + " (applies to newly placed flags)");
	}

	private void CycleFlagTeamMode()
	{
		SetFlagTeamMode((flagTeamMode == FlagTeamMode.Red) ? FlagTeamMode.Blue : FlagTeamMode.Red);
	}

	private void BuildPlatform(Vector3 origin, Quaternion rotation)
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		Vector3 size = default(Vector3);
		((Vector3)(ref size))..ctor(1f, 0.5f, 1f);
		Vector3 val = default(Vector3);
		for (int i = 0; i < 6; i++)
		{
			for (int j = 0; j < 6; j++)
			{
				((Vector3)(ref val))..ctor((float)i - 2.5f, 0f, (float)j - 2.5f);
				if ((Object)(object)CreateBrick(origin + rotation * val, rotation, size, makeDynamic: false) == (Object)null)
				{
					return;
				}
			}
		}
		SetStatus("Platform placed");
	}

	private void BuildStairs(Vector3 origin, Quaternion rotation)
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		Vector3 size = default(Vector3);
		((Vector3)(ref size))..ctor(1f, 0.5f, 1f);
		Vector3 val = default(Vector3);
		for (int i = 0; i < 8; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				float num = (float)j - 1f;
				for (int k = 0; k <= i; k++)
				{
					((Vector3)(ref val))..ctor(num, (float)k * 0.5f, (float)i);
					if ((Object)(object)CreateBrick(origin + rotation * val, rotation, size, makeDynamic: false) == (Object)null)
					{
						return;
					}
				}
			}
		}
		SetStatus("Supported solid stairs placed");
	}

	private BuilderBrick CreateBrick(Vector3 position, Quaternion rotation, Vector3 size, bool makeDynamic)
	{
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_010c: Expected O, but got Unknown
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		if (bricks.Count >= Mathf.Max(1, maxBricksConfig.Value))
		{
			SetStatus("Brick limit reached. Clear or remove some bricks first.");
			return null;
		}
		if ((Object)(object)activeStructure == (Object)null)
		{
			BeginStructure("LoosePieces");
		}
		GameObject obj = GameObject.CreatePrimitive((PrimitiveType)3);
		((Object)obj).name = "PhysicsCastle_Brick";
		obj.layer = placementLayer;
		obj.transform.SetParent(((Component)activeStructure).transform, true);
		obj.transform.position = position;
		obj.transform.rotation = rotation;
		obj.transform.localScale = size;
		Renderer component = obj.GetComponent<Renderer>();
		if ((Object)(object)component != (Object)null)
		{
			EnsureStoneMaterial();
			if ((Object)(object)stoneMaterial != (Object)null)
			{
				component.sharedMaterial = stoneMaterial;
			}
			Color val = default(Color);
			((Color)(ref val))..ctor(Random.Range(0.78f, 0.94f), Random.Range(0.78f, 0.94f), Random.Range(0.78f, 0.94f), 1f);
			MaterialPropertyBlock val2 = new MaterialPropertyBlock();
			val2.SetColor("_Color", val);
			component.SetPropertyBlock(val2);
		}
		Collider component2 = obj.GetComponent<Collider>();
		if ((Object)(object)component2 != (Object)null)
		{
			component2.isTrigger = false;
			component2.contactOffset = Mathf.Max(0.001f, Physics.defaultContactOffset);
			if ((Object)(object)brickPhysicsMaterial != (Object)null)
			{
				component2.sharedMaterial = brickPhysicsMaterial;
			}
		}
		Rigidbody val3 = obj.AddComponent<Rigidbody>();
		val3.mass = Mathf.Max(0.5f, size.x * size.y * size.z * 12f);
		val3.drag = 0.05f;
		val3.angularDrag = 0.35f;
		val3.useGravity = true;
		val3.interpolation = (RigidbodyInterpolation)1;
		val3.isKinematic = !makeDynamic;
		val3.solverIterations = 12;
		val3.solverVelocityIterations = 12;
		val3.collisionDetectionMode = (CollisionDetectionMode)(makeDynamic ? 2 : 0);
		BuilderBrick builderBrick = obj.AddComponent<BuilderBrick>();
		builderBrick.Initialize(val3, makeDynamic, activeStructure, placementLayer, this);
		activeStructure.Register(builderBrick);
		bricks.Add(builderBrick);
		return builderBrick;
	}

	private void EnsureBuildRoot()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Expected O, but got Unknown
		if ((Object)(object)buildRoot == (Object)null)
		{
			buildRoot = new GameObject("PhysicsCastleBuilder_Structures");
		}
	}

	private void EnsureStoneMaterial()
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Expected O, but got Unknown
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)stoneMaterial != (Object)null))
		{
			Shader val = Shader.Find("Standard");
			if ((Object)(object)val == (Object)null)
			{
				val = Shader.Find("Diffuse");
			}
			if ((Object)(object)val != (Object)null)
			{
				stoneMaterial = new Material(val);
				stoneMaterial.color = new Color(0.72f, 0.72f, 0.68f, 1f);
			}
		}
	}

	private void CreateBrickPhysicsMaterial()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		brickPhysicsMaterial = new PhysicMaterial("PhysicsCastle_Stone")
		{
			staticFriction = 0.9f,
			dynamicFriction = 0.8f,
			bounciness = 0f,
			frictionCombine = (PhysicMaterialCombine)3,
			bounceCombine = (PhysicMaterialCombine)2
		};
	}

	private void CyclePlacementLayer()
	{
		string[] array = new string[5] { "Default", "Ground", "Terrain", "Environment", "GroundCollision" };
		if (!layerCycleStarted)
		{
			int num = Array.IndexOf(array, LayerMask.LayerToName(placementLayer));
			layerCycleIndex = ((num != 0) ? (-1) : 0);
			layerCycleStarted = true;
		}
		for (int i = 0; i < array.Length; i++)
		{
			layerCycleIndex = (layerCycleIndex + 1) % array.Length;
			int num2 = LayerMask.NameToLayer(array[layerCycleIndex]);
			if (num2 < 0)
			{
				continue;
			}
			placementLayer = num2;
			placementLayerNameConfig.Value = array[layerCycleIndex];
			for (int j = 0; j < bricks.Count; j++)
			{
				if ((Object)(object)bricks[j] != (Object)null)
				{
					((Component)bricks[j]).gameObject.layer = placementLayer;
				}
			}
			ApplyNamedLayerCollisionCompatibility();
			ApplyTabsPlacementMaskCompatibility();
			Physics.SyncTransforms();
			SetStatus("Construction layer changed to " + array[layerCycleIndex] + ". Test unit placement on a brick surface.");
			return;
		}
		SetStatus("No supported construction layers were found in this TABS installation");
	}

	private void ApplyNamedLayerCollisionCompatibility()
	{
		if (!enableNamedUnitLayerCollisionsConfig.Value)
		{
			return;
		}
		string[] array = new string[29]
		{
			"Unit", "Units", "UnitCollision", "Character", "Characters", "Soldier", "Ragdoll", "CharacterController", "UnitController", "Ground",
			"GroundCollision", "Terrain", "Environment", "Default", "Projectile", "Projectiles", "Arrow", "Arrows", "Bolt", "Bolts",
			"Ballista", "BallistaProjectile", "BallistaArrow", "Weapon", "Weapons", "WeaponProjectile", "RangedProjectile", "RangedWeapon", "ProjectileCollision"
		};
		for (int i = 0; i < array.Length; i++)
		{
			int num = LayerMask.NameToLayer(array[i]);
			if (num >= 0 && num != placementLayer && Physics.GetIgnoreLayerCollision(placementLayer, num))
			{
				int key = placementLayer * 32 + num;
				if (!originalLayerCollisionStates.ContainsKey(key))
				{
					originalLayerCollisionStates.Add(key, value: true);
				}
				Physics.IgnoreLayerCollision(placementLayer, num, false);
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Enabled physics collision between construction layer '" + LayerMask.LayerToName(placementLayer) + "' and TABS layer '" + array[i] + "'. This may be needed for units to stand on construction."));
			}
		}
	}

	private void ApplyTabsPlacementMaskCompatibility()
	{
		try
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(PlacementCursor), "m_primaryActionMask");
			PropertyInfo propertyInfo = AccessTools.Property(typeof(PlacementCursor), "PrimaryActionMask");
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(PlacementCursor), "m_invalidUnitPlacementMask");
			PropertyInfo propertyInfo2 = AccessTools.Property(typeof(PlacementCursor), "InvalidUnitPlacementMask");
			if (fieldInfo == null && propertyInfo == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"TABS PlacementCursor.PrimaryActionMask backing member was not found. Unit placement compatibility was not changed.");
				return;
			}
			if (fieldInfo2 == null && propertyInfo2 == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"TABS PlacementCursor.InvalidUnitPlacementMask backing member was not found. Unit placement compatibility was not changed.");
				return;
			}
			PlacementCursor[] array = Resources.FindObjectsOfTypeAll<PlacementCursor>();
			if (array == null || array.Length == 0)
			{
				return;
			}
			int layerBit = 1 << placementLayer;
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			int num6 = 0;
			int num7 = 0;
			foreach (PlacementCursor val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				if (TryUpdateExactMask(val, fieldInfo, propertyInfo, layerBit, includeLayer: true, out var before, out var after))
				{
					num5++;
					num6 = after;
					if (before != after)
					{
						num++;
					}
					else
					{
						num3++;
					}
				}
				if (TryUpdateExactMask(val, fieldInfo2, propertyInfo2, layerBit, includeLayer: false, out before, out after))
				{
					num7 = after;
					if (before != after)
					{
						num2++;
					}
					else
					{
						num4++;
					}
				}
			}
			if (num > 0 || num2 > 0 || !placementMaskSummaryLogged)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("TABS PlacementCursor mask compatibility: live cursor instances=" + array.Length + ", inspected=" + num5 + ", construction layer='" + LayerMask.LayerToName(placementLayer) + "' (" + placementLayer + "), PrimaryActionMask changed=" + num + " (already correct=" + num3 + ", last=0x" + num6.ToString("X8") + "), InvalidUnitPlacementMask changed=" + num2 + " (already correct=" + num4 + ", last=0x" + num7.ToString("X8") + ")."));
				placementMaskSummaryLogged = true;
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not apply TABS PlacementCursor unit-placement compatibility: " + ex.Message));
		}
	}

	private bool TryUpdateExactMask(object target, FieldInfo field, PropertyInfo property, int layerBit, bool includeLayer, out int before, out int after)
	{
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		before = 0;
		after = 0;
		if (target == null)
		{
			return false;
		}
		object obj = null;
		Type type = null;
		try
		{
			if (field != null && !field.IsStatic)
			{
				obj = field.GetValue(target);
				type = field.FieldType;
			}
			else if (property != null)
			{
				MethodInfo getMethod = property.GetGetMethod(nonPublic: true);
				if (getMethod == null || getMethod.IsStatic)
				{
					return false;
				}
				obj = property.GetValue(target, null);
				type = property.PropertyType;
			}
			LayerMask val;
			if (type == typeof(LayerMask))
			{
				val = (LayerMask)obj;
				before = ((LayerMask)(ref val)).value;
			}
			else
			{
				if (!(type == typeof(int)))
				{
					return false;
				}
				before = (int)obj;
			}
			after = (includeLayer ? (before | layerBit) : (before & ~layerBit));
			if (after == before)
			{
				return true;
			}
			object value;
			if (type == typeof(LayerMask))
			{
				LayerMask val2 = (LayerMask)obj;
				((LayerMask)(ref val2)).value = after;
				value = val2;
			}
			else
			{
				value = after;
			}
			if (field != null && !field.IsStatic && !field.IsInitOnly && !field.IsLiteral)
			{
				field.SetValue(target, value);
			}
			else
			{
				MethodInfo methodInfo = ((property != null) ? property.GetSetMethod(nonPublic: true) : null);
				if (methodInfo == null || methodInfo.IsStatic)
				{
					return false;
				}
				property.SetValue(target, value, null);
			}
			object obj2 = ((field != null && !field.IsStatic) ? field.GetValue(target) : property.GetValue(target, null));
			if (type == typeof(LayerMask))
			{
				val = (LayerMask)obj2;
				after = ((LayerMask)(ref val)).value;
			}
			else
			{
				after = (int)obj2;
			}
			return includeLayer ? ((after & layerBit) != 0) : ((after & layerBit) == 0);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogDebug((object)("Could not update exact placement mask member " + ((field != null) ? field.Name : ((property != null) ? property.Name : "<missing>")) + ": " + ex.Message));
			return false;
		}
	}

	private void LogPlacementCursorMaskState()
	{
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(PlacementCursor), "m_primaryActionMask");
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(PlacementCursor), "m_invalidUnitPlacementMask");
			PlacementCursor[] array = Resources.FindObjectsOfTypeAll<PlacementCursor>();
			int num = 1 << placementLayer;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("TABS PlacementCursor diagnostics: instances=" + ((array != null) ? array.Length : 0) + ", construction bit=0x" + num.ToString("X8")));
			if (array == null)
			{
				return;
			}
			for (int i = 0; i < array.Length; i++)
			{
				PlacementCursor val = array[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				string text = "unavailable";
				string text2 = "unavailable";
				LayerMask val2;
				if (fieldInfo != null)
				{
					object value = fieldInfo.GetValue(val);
					int num2;
					if (!(fieldInfo.FieldType == typeof(LayerMask)))
					{
						num2 = (int)value;
					}
					else
					{
						val2 = (LayerMask)value;
						num2 = ((LayerMask)(ref val2)).value;
					}
					int num3 = num2;
					text = "0x" + num3.ToString("X8") + ", constructionIncluded=" + ((num3 & num) != 0);
				}
				if (fieldInfo2 != null)
				{
					object value2 = fieldInfo2.GetValue(val);
					int num4;
					if (!(fieldInfo2.FieldType == typeof(LayerMask)))
					{
						num4 = (int)value2;
					}
					else
					{
						val2 = (LayerMask)value2;
						num4 = ((LayerMask)(ref val2)).value;
					}
					int num5 = num4;
					text2 = "0x" + num5.ToString("X8") + ", constructionIncluded=" + ((num5 & num) != 0);
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)("PlacementCursor[" + i + "]: PrimaryActionMask=" + text + " | InvalidUnitPlacementMask=" + text2));
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("PlacementCursor mask diagnostics failed: " + ex.Message));
		}
	}

	private void Lo