Decompiled source of LethalCCTV v1.3.8

LethalCCTV.dll

Decompiled 15 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using CSync.Extensions;
using CSync.Lib;
using Dawn;
using DunGen;
using DunGen.Graph;
using DunGen.Tags;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCCTV;
using LethalCCTV.Api;
using LethalCCTV.NetcodePatcher;
using LethalCompanyInputUtils.Api;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Audio;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Networking;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;
using UnityEngine.TextCore;
using UnityEngine.UI;
using UnityEngine.Video;
using Y4NGZCompany.Bootstrap;
using Y4NGZCompany.Core;
using Y4NGZCompany.Core.Compat;
using Y4NGZCompany.Core.Pilot;
using Y4NGZCompany.Experience.Fonts;
using Y4NGZCompany.Experience.Scan;
using Y4NGZCompany.Experience.UITheme;
using Y4NGZCompany.Facility.Cameras;
using Y4NGZCompany.Facility.Cameras.Placement;
using Y4NGZCompany.Facility.Interior;
using Y4NGZCompany.Facility.Interior.Placement;
using Y4NGZCompany.Facility.Interior.Placement.Authored;
using Y4NGZCompany.Facility.Lockdown;
using Y4NGZCompany.Facility.Mainframe;
using Y4NGZCompany.Facility.Security;
using Y4NGZCompany.Facility.Security.Drone;
using Y4NGZCompany.Facility.Shared;
using Y4NGZCompany.Facility.Stash;
using Y4NGZCompany.RoundSetup;
using Y4NGZCompany.ShipSystems.Rendering;
using Y4NGZCompany.ShipSystems.Rendering.Outlines;
using Y4NGZCompany.ShipSystems.Surveillance;
using Y4NGZCore.Bindings;
using Y4NGZCore.Diagnostics;
using Y4NGZCore.Interop;
using Y4NGZCore.Lifecycle;
using Y4NGZCore.Modules;
using Y4NGZCore.Modules.Hud;
using Y4NGZCore.Modules.Net;
using Y4NGZCore.Modules.Objectives;
using Y4NGZCore.Modules.Security;
using Y4NGZCore.Modules.ShipSystems;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("com.olegknyazev.softmask")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("DunGen")]
[assembly: IgnoresAccessChecksTo("DunGen.Integration.ASPP")]
[assembly: IgnoresAccessChecksTo("DunGen.Integration.UnityNav")]
[assembly: IgnoresAccessChecksTo("EasyTextEffects")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.XR.CoreUtils")]
[assembly: IgnoresAccessChecksTo("Unity.XR.Management")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.ConformanceAutomation")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.MetaQuestSupport")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.MockRuntime")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.OculusQuestSupport")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.RuntimeDebugger")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SpatialTracking")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: IgnoresAccessChecksTo("UnityEngine.XR.LegacyInputHelpers")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalCCTV")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Y4NGZ surveillance and CCTV systems")]
[assembly: AssemblyFileVersion("1.3.8.0")]
[assembly: AssemblyInformationalVersion("1.3.8+e6a125e550da6a3e0bc1c6bfc8b4276a564432c0")]
[assembly: AssemblyProduct("LethalCCTV")]
[assembly: AssemblyTitle("LethalCCTV")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.3.8.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Y4NGZCompany.RoundSetup
{
	internal sealed class RoundSetupForce<T>
	{
		internal bool IsSet { get; private set; }

		internal T Value { get; private set; }

		internal bool Sticky { get; private set; }

		internal bool BoundToLanding { get; private set; }

		internal void Set(T value, bool sticky)
		{
			IsSet = true;
			Value = value;
			Sticky = sticky;
			BoundToLanding = false;
		}

		internal void NoteLandingStarted()
		{
			if (IsSet)
			{
				BoundToLanding = true;
			}
		}

		internal bool TryUse(out T value)
		{
			value = default(T);
			if (!IsSet || !BoundToLanding)
			{
				return false;
			}
			value = Value;
			if (!Sticky)
			{
				Clear();
			}
			return true;
		}

		internal void NoteShipLeft()
		{
			if (IsSet && BoundToLanding)
			{
				if (Sticky)
				{
					BoundToLanding = false;
				}
				else
				{
					Clear();
				}
			}
		}

		internal void Clear()
		{
			IsSet = false;
			Value = default(T);
			Sticky = false;
			BoundToLanding = false;
		}
	}
}
namespace Y4NGZCompany.ShipSystems.Surveillance
{
	[HarmonyPatch(typeof(HUDManager), "PingScan_performed")]
	internal static class CameraOperatorPingScanPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(ref CallbackContext context)
		{
			if (!MonitorFocus.IsFocused)
			{
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "UpdateScanNodes")]
	internal static class CameraOperatorScanNodesPatch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return !MonitorFocus.IsFocused;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_performed")]
	internal static class CameraOperatorActivateItemPatch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return !MonitorFocus.IsFocused;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_canceled")]
	internal static class CameraOperatorActivateItemCancelPatch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return !MonitorFocus.IsFocused;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "Jump_performed")]
	internal static class CameraOperatorJumpPerformedPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(PlayerControllerB __instance)
		{
			return !MonitorFocus.ShouldSuppressPlayerInput(__instance);
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "Update")]
	internal static class CameraOperatorPlayerUpdatePatch
	{
		[HarmonyPrefix]
		private static void Prefix(PlayerControllerB __instance)
		{
			if (MonitorFocus.ShouldSuppressPlayerInput(__instance))
			{
				MonitorFocus.ApplyFocusInputLock(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "PlayerLookInput")]
	internal static class CameraOperatorPlayerLookInputPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(PlayerControllerB __instance)
		{
			return !MonitorFocus.ShouldSuppressPlayerInput(__instance);
		}
	}
	internal static class CCTVAccessButton
	{
		private const string RootName = "LethalCCTV_AccessButton";

		private const string TemplateChildName = "ButtonContainer/ButtonAnimContainer";

		private const string RedButtonChildName = "RedButton";

		private const string GlassChildName = "ButtonGlass";

		private static readonly Vector3 GlassOpenEuler = new Vector3(-180f, 291.843f, -180f);

		private const float CapPressedDepthZ = 0.0106743f;

		private const float CapPressDownSeconds = 0.05f;

		private const float CapPressTotalSeconds = 0.4f;

		private const float StateRefreshIntervalSeconds = 0.2f;

		private const float PressSfxVolume = 0.9f;

		private const string ScanNodeName = "LethalCCTV_AccessButtonScanNode";

		private const string ScanNodeHeader = "CCTV Station";

		private const string ScanNodeSubText = "View cameras";

		private static GameObject _root;

		private static Transform _glass;

		private static Transform _cap;

		private static Vector3 _capRestScale;

		private static float _pressStartedAt = -1f;

		private static InteractTrigger _trigger;

		private static AudioSource _audio;

		private static AudioClip _pressSfx;

		private static UnityAction<PlayerControllerB> _listener;

		private static float _nextStateRefreshAt;

		private static bool _templateMissingLogged;

		private static bool _spawnLogged;

		internal static bool IsAvailable
		{
			get
			{
				if ((Object)(object)_root != (Object)null)
				{
					return (Object)(object)_trigger != (Object)null;
				}
				return false;
			}
		}

		internal static Transform Root
		{
			get
			{
				if (!((Object)(object)_root != (Object)null))
				{
					return null;
				}
				return _root.transform;
			}
		}

		internal static Transform PressContactTransform
		{
			get
			{
				if (!((Object)(object)_trigger != (Object)null))
				{
					return null;
				}
				return ((Component)_trigger).transform;
			}
		}

		internal static bool TryGetPressSurface(out Vector3 point, out Vector3 normal)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: 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_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: 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_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: 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_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: 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_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			point = Vector3.zero;
			normal = Vector3.up;
			Transform pressContactTransform = PressContactTransform;
			if ((Object)(object)pressContactTransform == (Object)null)
			{
				return false;
			}
			Vector3 bestAxis = pressContactTransform.up;
			float bestScore = Mathf.Abs(Vector3.Dot(bestAxis, Vector3.up));
			ConsiderAxis(pressContactTransform.right);
			ConsiderAxis(pressContactTransform.forward);
			if (Vector3.Dot(bestAxis, Vector3.up) < 0f)
			{
				bestAxis = -bestAxis;
			}
			normal = ((((Vector3)(ref bestAxis)).sqrMagnitude > 0.0001f) ? ((Vector3)(ref bestAxis)).normalized : Vector3.up);
			Renderer val = ((Component)pressContactTransform).GetComponent<Renderer>();
			if ((Object)(object)val == (Object)null)
			{
				val = ((Component)pressContactTransform).GetComponentInChildren<Renderer>(true);
			}
			if ((Object)(object)val == (Object)null)
			{
				point = pressContactTransform.position + normal * 0.015f;
				return true;
			}
			Bounds bounds = val.bounds;
			Vector3 extents = ((Bounds)(ref bounds)).extents;
			float num = Mathf.Abs(normal.x) * extents.x + Mathf.Abs(normal.y) * extents.y + Mathf.Abs(normal.z) * extents.z;
			point = ((Bounds)(ref bounds)).center + normal * num;
			return true;
			void ConsiderAxis(Vector3 candidate)
			{
				//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_001c: 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)
				float num2 = Mathf.Abs(Vector3.Dot(candidate, Vector3.up));
				if (!(num2 <= bestScore))
				{
					bestAxis = candidate;
					bestScore = num2;
				}
			}
		}

		internal static void Ensure(Transform stationRoot)
		{
			//IL_0157: 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_01df: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)stationRoot == (Object)null || (Object)(object)_root != (Object)null)
			{
				return;
			}
			long timestamp = Stopwatch.GetTimestamp();
			AudioClip pressSfx;
			Transform val = ResolveTemplateButtonContainer(out pressSfx);
			RecordSetupStep("CCTVAccessButton.Ensure.TemplateLookup", timestamp);
			if ((Object)(object)val == (Object)null)
			{
				if (!_templateMissingLogged)
				{
					_templateMissingLogged = true;
					ManualLogSource log = SurveillanceBootstrap.Log;
					if (log != null)
					{
						log.LogWarning((object)"[LethalCCTV] Access button template unavailable (teleporter unlockable prefab or ButtonContainer not found); red bezel button remains the CCTV entry.");
					}
				}
				return;
			}
			timestamp = Stopwatch.GetTimestamp();
			GameObject val2;
			try
			{
				val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, stationRoot, false);
			}
			catch (Exception ex)
			{
				if (!_templateMissingLogged)
				{
					_templateMissingLogged = true;
					ManualLogSource log2 = SurveillanceBootstrap.Log;
					if (log2 != null)
					{
						log2.LogWarning((object)("[LethalCCTV] Access button clone failed: " + ex.Message));
					}
				}
				return;
			}
			finally
			{
				RecordSetupStep("CCTVAccessButton.Ensure.Instantiate", timestamp);
			}
			timestamp = Stopwatch.GetTimestamp();
			((Object)val2).name = "LethalCCTV_AccessButton";
			_root = val2;
			_pressSfx = pressSfx;
			_glass = FindChildRecursive(val2.transform, "ButtonGlass");
			StripClonedBehaviours(val2);
			_audio = val2.AddComponent<AudioSource>();
			_audio.playOnAwake = false;
			_audio.spatialBlend = 1f;
			_audio.minDistance = 0.8f;
			_audio.maxDistance = 12f;
			WireInteractTrigger(val2);
			CCTVOperatorStation.ApplyAccessButtonPlacement(val2.transform);
			BuildScanNode(val2);
			if ((Object)(object)_glass != (Object)null)
			{
				_glass.localEulerAngles = GlassOpenEuler;
			}
			_cap = (((Object)(object)_trigger != (Object)null) ? ((Component)_trigger).transform : null);
			if ((Object)(object)_cap != (Object)null)
			{
				_capRestScale = _cap.localScale;
			}
			_pressStartedAt = -1f;
			RecordSetupStep("CCTVAccessButton.Ensure.Configure", timestamp);
			if (!_spawnLogged)
			{
				_spawnLogged = true;
				ManualLogSource log3 = SurveillanceBootstrap.Log;
				if (log3 != null)
				{
					log3.LogInfo((object)($"[LethalCCTV] Access button spawned from teleporter template: local={val2.transform.localPosition} " + "trigger=" + (((Object)(object)_trigger != (Object)null) ? "wired" : "MISSING") + " cap=" + (((Object)(object)_cap != (Object)null) ? "found" : "MISSING") + " glass=" + (((Object)(object)_glass != (Object)null) ? "found" : "MISSING") + " pressSfx=" + (((Object)(object)_pressSfx != (Object)null) ? ((Object)_pressSfx).name : "<none>") + "."));
				}
			}
		}

		private static void RecordSetupStep(string name, long startedAt)
		{
			SurveillanceBootstrap.RecordLateUpdateNestedStep(name, Stopwatch.GetTimestamp() - startedAt);
		}

		internal static void Shutdown()
		{
			if ((Object)(object)_trigger != (Object)null && _listener != null && _trigger.onInteract != null)
			{
				((UnityEvent<PlayerControllerB>)(object)_trigger.onInteract).RemoveListener(_listener);
			}
			if ((Object)(object)_root != (Object)null)
			{
				Object.Destroy((Object)(object)_root);
			}
			_root = null;
			_glass = null;
			_cap = null;
			_pressStartedAt = -1f;
			_trigger = null;
			_audio = null;
			_pressSfx = null;
			_listener = null;
			_nextStateRefreshAt = 0f;
			_spawnLogged = false;
		}

		private static void AdvanceCapPress()
		{
			//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_0099: Unknown result type (might be due to invalid IL or missing references)
			if (!(_pressStartedAt < 0f) && !((Object)(object)_cap == (Object)null))
			{
				float num = Time.time - _pressStartedAt;
				Vector3 capRestScale = _capRestScale;
				if (num >= 0.4f)
				{
					_pressStartedAt = -1f;
				}
				else if (num < 0.05f)
				{
					capRestScale.z = Mathf.SmoothStep(_capRestScale.z, 0.0106743f, num / 0.05f);
				}
				else
				{
					capRestScale.z = Mathf.SmoothStep(0.0106743f, _capRestScale.z, (num - 0.05f) / 0.35f);
				}
				_cap.localScale = capRestScale;
			}
		}

		internal static void Tick()
		{
			if ((Object)(object)_trigger == (Object)null)
			{
				return;
			}
			AdvanceCapPress();
			if (!(Time.unscaledTime < _nextStateRefreshAt))
			{
				_nextStateRefreshAt = Time.unscaledTime + 0.2f;
				if (CCTVMonitorFeedSync.IsEntryAvailable(out var unavailableReason))
				{
					_trigger.interactable = true;
					_trigger.hoverTip = CCTVVanillaMonitorButtons.EntryHoverTip;
				}
				else
				{
					_trigger.interactable = false;
					_trigger.disabledHoverTip = unavailableReason ?? string.Empty;
				}
			}
		}

		internal static void PlayPressAnimation()
		{
			_pressStartedAt = Time.time;
			if ((Object)(object)_audio != (Object)null && (Object)(object)_pressSfx != (Object)null)
			{
				_audio.PlayOneShot(_pressSfx, 0.9f);
			}
		}

		private static void BuildScanNode(GameObject clone)
		{
			//IL_005c: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			Transform val = (((Object)(object)_trigger != (Object)null) ? ((Component)_trigger).transform : clone.transform);
			GameObject val2 = new GameObject("LethalCCTV_AccessButtonScanNode");
			val2.transform.SetParent(clone.transform, false);
			val2.transform.position = val.position;
			try
			{
				val2.tag = "DoNotSet";
			}
			catch (UnityException ex)
			{
				UnityException ex2 = ex;
				if (LogGate.Once("LethalCCTV.AccessButton.scanNodeTag", (LogScope)0))
				{
					ManualLogSource log = SurveillanceBootstrap.Log;
					if (log != null)
					{
						log.LogWarning((object)("[LethalCCTV] Access button scan node tag 'DoNotSet' could not be set; the node keeps its default tag: " + ((Exception)(object)ex2).Message));
					}
				}
			}
			SphereCollider obj = val2.AddComponent<SphereCollider>();
			((Collider)obj).isTrigger = true;
			obj.radius = 0.3f;
			ScanNodeProperties obj2 = val2.AddComponent<ScanNodeProperties>();
			obj2.scrapValue = 0;
			ScanNodePolicy.Apply(obj2, (ScanNodeRole)2, 0, "CCTV Station", "View cameras", -1);
		}

		private static void OnPressed(PlayerControllerB player)
		{
			if (CCTVOperatorStation.IsReady)
			{
				CCTVVanillaMonitorButtons.RequestEntry(player);
			}
		}

		private static Transform ResolveTemplateButtonContainer(out AudioClip pressSfx)
		{
			pressSfx = null;
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.unlockablesList == (Object)null || instance.unlockablesList.unlockables == null)
			{
				return null;
			}
			for (int i = 0; i < instance.unlockablesList.unlockables.Count; i++)
			{
				GameObject val = instance.unlockablesList.unlockables[i]?.prefabObject;
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				ShipTeleporter component = val.GetComponent<ShipTeleporter>();
				if (!((Object)(object)component == (Object)null) && !component.isInverseTeleporter)
				{
					Transform val2 = val.transform.Find("ButtonContainer/ButtonAnimContainer");
					if (!((Object)(object)val2 == (Object)null))
					{
						pressSfx = component.buttonPressSFX;
						return val2;
					}
				}
			}
			return null;
		}

		private static void StripClonedBehaviours(GameObject clone)
		{
			MonoBehaviour[] componentsInChildren = clone.GetComponentsInChildren<MonoBehaviour>(true);
			foreach (MonoBehaviour val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null) && (!(val is InteractTrigger) || !string.Equals(((Object)((Component)val).gameObject).name, "RedButton", StringComparison.Ordinal)))
				{
					Object.Destroy((Object)(object)val);
				}
			}
			Animator componentInChildren = clone.GetComponentInChildren<Animator>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				((Behaviour)componentInChildren).enabled = false;
				Object.Destroy((Object)(object)componentInChildren);
			}
			if ((Object)(object)_glass != (Object)null)
			{
				Collider[] components = ((Component)_glass).GetComponents<Collider>();
				for (int j = 0; j < components.Length; j++)
				{
					Object.Destroy((Object)(object)components[j]);
				}
			}
		}

		private static void WireInteractTrigger(GameObject clone)
		{
			Transform val = FindChildRecursive(clone.transform, "RedButton");
			_trigger = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<InteractTrigger>() : null);
			if ((Object)(object)_trigger == (Object)null)
			{
				ManualLogSource log = SurveillanceBootstrap.Log;
				if (log != null)
				{
					log.LogWarning((object)"[LethalCCTV] Access button clone has no RedButton InteractTrigger; entry stays on the bezel button.");
				}
				return;
			}
			if (_trigger.onInteract != null)
			{
				int persistentEventCount = ((UnityEventBase)_trigger.onInteract).GetPersistentEventCount();
				for (int i = 0; i < persistentEventCount; i++)
				{
					((UnityEventBase)_trigger.onInteract).SetPersistentListenerState(i, (UnityEventCallState)0);
				}
			}
			_listener = OnPressed;
			((UnityEvent<PlayerControllerB>)(object)_trigger.onInteract).AddListener(_listener);
			_trigger.hoverTip = CCTVVanillaMonitorButtons.EntryHoverTip;
			_trigger.interactable = true;
		}

		private static Transform FindChildRecursive(Transform root, string childName)
		{
			if ((Object)(object)root == (Object)null)
			{
				return null;
			}
			if (string.Equals(((Object)root).name, childName, StringComparison.Ordinal))
			{
				return root;
			}
			for (int i = 0; i < root.childCount; i++)
			{
				Transform val = FindChildRecursive(root.GetChild(i), childName);
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			return null;
		}
	}
	internal enum BezelButtonAction
	{
		None,
		CycleRadar,
		ToggleFeed,
		EnterCctv,
		GiPower
	}
	internal readonly struct BezelButtonState
	{
		internal readonly bool Purchased;

		internal readonly bool OperatorSeated;

		internal readonly bool ClaimInFlight;

		internal readonly bool FeedIsCctv;

		internal readonly bool Landed;

		internal readonly bool AccessButtonLive;

		internal readonly bool GiOwnsForeignScreen;

		internal BezelButtonState(bool purchased, bool operatorSeated, bool claimInFlight, bool feedIsCctv, bool landed, bool accessButtonLive, bool giOwnsForeignScreen)
		{
			Purchased = purchased;
			OperatorSeated = operatorSeated;
			ClaimInFlight = claimInFlight;
			FeedIsCctv = feedIsCctv;
			Landed = landed;
			AccessButtonLive = accessButtonLive;
			GiOwnsForeignScreen = giOwnsForeignScreen;
		}
	}
	internal readonly struct BezelButtonActions
	{
		internal readonly BezelButtonAction Grey;

		internal readonly BezelButtonAction Red;

		internal BezelButtonActions(BezelButtonAction grey, BezelButtonAction red)
		{
			Grey = grey;
			Red = red;
		}
	}
	internal static class CctvBezelButtonPolicy
	{
		internal static BezelButtonActions Resolve(in BezelButtonState state)
		{
			if (!state.Purchased)
			{
				return new BezelButtonActions(BezelButtonAction.CycleRadar, BezelButtonAction.GiPower);
			}
			if (state.OperatorSeated || state.ClaimInFlight)
			{
				return new BezelButtonActions(BezelButtonAction.None, BezelButtonAction.None);
			}
			bool grey = !state.FeedIsCctv;
			BezelButtonAction red = ((!state.AccessButtonLive) ? (state.Landed ? BezelButtonAction.EnterCctv : BezelButtonAction.None) : ((!state.GiOwnsForeignScreen) ? (state.Landed ? BezelButtonAction.ToggleFeed : BezelButtonAction.None) : BezelButtonAction.GiPower));
			return new BezelButtonActions(grey ? BezelButtonAction.CycleRadar : BezelButtonAction.None, red);
		}
	}
	internal static class CctvCameraStabilizerMath
	{
		internal static Vector3 ComputeContainerWorldDelta(Vector3 currentContainerWorldPosition, Vector3 targetContainerWorldPosition)
		{
			//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_0002: Unknown result type (might be due to invalid IL or missing references)
			return targetContainerWorldPosition - currentContainerWorldPosition;
		}

		internal static Vector3 ApplyContainerHold(Vector3 currentContainerWorldPosition, Vector3 targetContainerWorldPosition, Vector3 childLocalPosition, out Vector3 resultingChildLocalPosition)
		{
			//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_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: 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_000f: 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_0011: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ComputeContainerWorldDelta(currentContainerWorldPosition, targetContainerWorldPosition);
			resultingChildLocalPosition = childLocalPosition;
			return currentContainerWorldPosition + val;
		}
	}
	internal static class CctvCameraTrace
	{
		private const int FlushBatchRows = 256;

		private const float FlushIntervalSeconds = 2f;

		private const float DeltaThresholdMetersSq = 2.5E-05f;

		private const float SlowFrameThresholdMs = 25f;

		private const float NeckCapRetrySeconds = 2f;

		private const int PostTransitionTailFrames = 15;

		internal const string CsvHeader = "frame,time,dt_ms,isCrouching,inSpecialAnim,fpvBodyShown,camLocalX,camLocalY,camLocalZ,containerLocalY,containerLocalZ,armsMetarigLocalY,armsMetarigLocalZ,bodyMeshName,neckCapEnabled,cameraUp,camLocalEulerX";

		private const string FpvControllerTypeName = "FirstPersonView.LocalBodyViewController";

		private const string FpvBodyShownMemberName = "LocalBodyShown";

		private const string NeckCapObjectName = "FPVNeckCap";

		private static readonly StringBuilder RowBuilder = new StringBuilder(256);

		private static CctvCameraTraceWriter _writer;

		private static bool _capLoggedThisRound;

		private static bool _ioErrorLogged;

		private static float _lastFlushTime;

		private static PlayerControllerB _cachedPlayer;

		private static Transform _cachedArmsMetarig;

		private static Renderer _cachedNeckCapRenderer;

		private static float _nextNeckCapProbeAt;

		private static Component _cachedFpvControllerComponent;

		private static bool _hasPreviousSample;

		private static Vector3 _prevPlayerPos;

		private static Vector3 _prevCamLocalPos;

		private static bool _prevCrouching;

		private static bool _prevInSpecialAnim;

		private static bool _prevSeatActive;

		private static int _prevFpvBodyShown = -1;

		private static int _prevNeckCapEnabled = -1;

		private static int _tailFramesRemaining;

		private static bool _fpvProbeAttempted;

		private static Type _fpvControllerType;

		private static PropertyInfo _fpvBodyShownProp;

		private static FieldInfo _fpvBodyShownField;

		private static bool _fpvBodyShownIsStatic;

		private static PropertyInfo _fpvInstanceProp;

		private static FieldInfo _fpvInstanceField;

		internal static void Tick()
		{
			//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_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: 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_019f: 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_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: 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)
			CctvCameraTraceWriter cctvCameraTraceWriter = EnsureWriter();
			if (cctvCameraTraceWriter.RoundCapReached)
			{
				FlushSafe(cctvCameraTraceWriter);
				if (!_capLoggedThisRound)
				{
					_capLoggedThisRound = true;
					ManualLogSource log = SurveillanceBootstrap.Log;
					if (log != null)
					{
						log.LogInfo((object)$"[LethalCCTV][CameraTrace] Round row cap ({5000}) reached; pausing trace until next round.");
					}
				}
				return;
			}
			PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val.gameplayCamera == (Object)null)
			{
				return;
			}
			EnsurePlayerCache(val);
			Transform transform = ((Component)val.gameplayCamera).transform;
			Transform val2 = (((Object)(object)val.cameraContainerTransform != (Object)null) ? val.cameraContainerTransform : transform.parent);
			Vector3 position = ((Component)val).transform.position;
			Vector3 localPosition = transform.localPosition;
			bool isCrouching = val.isCrouching;
			bool flag = val.inSpecialInteractAnimation || val.enteringSpecialAnimation;
			bool flag2 = MonitorFocus.IsFocused || MonitorFocus.IsEntryPoseSettleActive || MainframeInteractionSession.IsAnyLocalSessionActive || MainframeInteractionSession.WasActiveThisFrame;
			int num = ReadFpvBodyShown(val);
			int num2 = ReadNeckCapEnabled(val);
			float num3 = Time.unscaledDeltaTime * 1000f;
			int num4;
			if (_hasPreviousSample && isCrouching == _prevCrouching && flag == _prevInSpecialAnim && flag2 == _prevSeatActive && num == _prevFpvBodyShown)
			{
				num4 = ((num2 != _prevNeckCapEnabled) ? 1 : 0);
				if (num4 == 0)
				{
					goto IL_0157;
				}
			}
			else
			{
				num4 = 1;
			}
			_tailFramesRemaining = 15;
			goto IL_0157;
			IL_0157:
			Vector3 val3;
			int num5;
			if (_hasPreviousSample)
			{
				val3 = position - _prevPlayerPos;
				num5 = ((((Vector3)(ref val3)).sqrMagnitude > 2.5E-05f) ? 1 : 0);
			}
			else
			{
				num5 = 0;
			}
			bool flag3 = (byte)num5 != 0;
			if (!flag3 && ((Vector2)(ref val.moveInputVector)).sqrMagnitude > 0.0001f)
			{
				flag3 = true;
			}
			int num6;
			if (_hasPreviousSample)
			{
				val3 = localPosition - _prevCamLocalPos;
				num6 = ((((Vector3)(ref val3)).sqrMagnitude > 2.5E-05f) ? 1 : 0);
			}
			else
			{
				num6 = 0;
			}
			bool flag4 = (byte)num6 != 0;
			bool num7 = ((uint)num4 | (flag3 ? 1u : 0u) | (isCrouching ? 1u : 0u) | (flag ? 1u : 0u) | (flag2 ? 1u : 0u) | (flag4 ? 1u : 0u)) != 0 || num3 > 25f || _tailFramesRemaining > 0;
			if (_tailFramesRemaining > 0)
			{
				_tailFramesRemaining--;
			}
			_hasPreviousSample = true;
			_prevPlayerPos = position;
			_prevCamLocalPos = localPosition;
			_prevCrouching = isCrouching;
			_prevInSpecialAnim = flag;
			_prevSeatActive = flag2;
			_prevFpvBodyShown = num;
			_prevNeckCapEnabled = num2;
			if (!num7)
			{
				if (cctvCameraTraceWriter.BufferedRows > 0 && Time.unscaledTime - _lastFlushTime >= 2f)
				{
					FlushSafe(cctvCameraTraceWriter);
				}
				return;
			}
			float containerLocalY = (((Object)(object)val2 != (Object)null) ? val2.localPosition.y : 0f);
			float containerLocalZ = (((Object)(object)val2 != (Object)null) ? val2.localPosition.z : 0f);
			float armsMetarigLocalY = (((Object)(object)_cachedArmsMetarig != (Object)null) ? _cachedArmsMetarig.localPosition.y : 0f);
			float armsMetarigLocalZ = (((Object)(object)_cachedArmsMetarig != (Object)null) ? _cachedArmsMetarig.localPosition.z : 0f);
			string bodyMeshName = ResolveBodyMeshName(val);
			float cameraUp = val.cameraUp;
			float x = transform.localEulerAngles.x;
			string row = FormatRow(Time.frameCount, Time.unscaledTime, num3, isCrouching, flag, num, localPosition, containerLocalY, containerLocalZ, armsMetarigLocalY, armsMetarigLocalZ, bodyMeshName, num2, cameraUp, x);
			if (cctvCameraTraceWriter.TryBufferRow(row) && (cctvCameraTraceWriter.BufferedRows >= 256 || cctvCameraTraceWriter.RoundCapReached || Time.unscaledTime - _lastFlushTime >= 2f))
			{
				FlushSafe(cctvCameraTraceWriter);
			}
		}

		internal static void FlushAndResetRound()
		{
			if (_writer != null)
			{
				try
				{
					_writer.EndRound();
				}
				catch (Exception ex)
				{
					LogIoErrorOnce(ex);
				}
				_lastFlushTime = Time.unscaledTime;
			}
			_capLoggedThisRound = false;
			_tailFramesRemaining = 0;
		}

		internal static void FlushAndEndSession()
		{
			if (_writer != null)
			{
				try
				{
					_writer.EndSession();
				}
				catch (Exception ex)
				{
					LogIoErrorOnce(ex);
				}
				_lastFlushTime = Time.unscaledTime;
			}
			_capLoggedThisRound = false;
			_hasPreviousSample = false;
			_tailFramesRemaining = 0;
			ClearPlayerCache();
		}

		internal static void Shutdown()
		{
			FlushAndEndSession();
			_writer = null;
			_fpvProbeAttempted = false;
			_fpvControllerType = null;
			_fpvBodyShownProp = null;
			_fpvBodyShownField = null;
			_fpvBodyShownIsStatic = false;
			_fpvInstanceProp = null;
			_fpvInstanceField = null;
			_ioErrorLogged = false;
		}

		private static CctvCameraTraceWriter EnsureWriter()
		{
			if (_writer == null)
			{
				_writer = new CctvCameraTraceWriter(Path.Combine(Paths.ConfigPath, "Y4NGZCompany", "cctv-camera-trace.csv"), "frame,time,dt_ms,isCrouching,inSpecialAnim,fpvBodyShown,camLocalX,camLocalY,camLocalZ,containerLocalY,containerLocalZ,armsMetarigLocalY,armsMetarigLocalZ,bodyMeshName,neckCapEnabled,cameraUp,camLocalEulerX");
			}
			return _writer;
		}

		private static void FlushSafe(CctvCameraTraceWriter writer)
		{
			if (writer == null || writer.BufferedRows <= 0)
			{
				return;
			}
			try
			{
				if (writer.Flush(out var startedNewFile) && startedNewFile)
				{
					ManualLogSource log = SurveillanceBootstrap.Log;
					if (log != null)
					{
						log.LogInfo((object)("[LethalCCTV][CameraTrace] Writing bounded per-frame camera trace to '" + writer.FilePath + "'."));
					}
				}
			}
			catch (Exception ex)
			{
				LogIoErrorOnce(ex);
			}
			finally
			{
				_lastFlushTime = Time.unscaledTime;
			}
		}

		private static void LogIoErrorOnce(Exception ex)
		{
			if (!_ioErrorLogged)
			{
				_ioErrorLogged = true;
				ManualLogSource log = SurveillanceBootstrap.Log;
				if (log != null)
				{
					log.LogWarning((object)("[LethalCCTV][CameraTrace] Failed to write camera trace CSV: " + ex.Message));
				}
			}
		}

		private static void EnsurePlayerCache(PlayerControllerB player)
		{
			if (_cachedPlayer == player)
			{
				return;
			}
			ClearPlayerCache();
			_cachedPlayer = player;
			_hasPreviousSample = false;
			if ((Object)(object)player.localArmsTransform != (Object)null)
			{
				for (int i = 0; i < player.localArmsTransform.childCount; i++)
				{
					Transform child = player.localArmsTransform.GetChild(i);
					if ((Object)(object)child != (Object)null && string.Equals(((Object)child).name, "metarig", StringComparison.Ordinal))
					{
						_cachedArmsMetarig = child;
						break;
					}
				}
			}
			ProbeNeckCap(player);
			EnsureFpvReflection();
			if (_fpvControllerType != null && !_fpvBodyShownIsStatic && typeof(Component).IsAssignableFrom(_fpvControllerType))
			{
				_cachedFpvControllerComponent = ((Component)player).GetComponent(_fpvControllerType);
			}
		}

		private static void ClearPlayerCache()
		{
			_cachedPlayer = null;
			_cachedArmsMetarig = null;
			_cachedNeckCapRenderer = null;
			_nextNeckCapProbeAt = 0f;
			_cachedFpvControllerComponent = null;
		}

		private static int ReadNeckCapEnabled(PlayerControllerB player)
		{
			if ((Object)(object)_cachedNeckCapRenderer == (Object)null && Time.unscaledTime >= _nextNeckCapProbeAt)
			{
				ProbeNeckCap(player);
			}
			if ((Object)(object)_cachedNeckCapRenderer == (Object)null)
			{
				return -1;
			}
			if (!_cachedNeckCapRenderer.enabled || !((Component)_cachedNeckCapRenderer).gameObject.activeInHierarchy)
			{
				return 0;
			}
			return 1;
		}

		private static void ProbeNeckCap(PlayerControllerB player)
		{
			_nextNeckCapProbeAt = Time.unscaledTime + 2f;
			if ((Object)(object)player == (Object)null)
			{
				return;
			}
			Renderer[] componentsInChildren = ((Component)((Component)player).transform).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && string.Equals(((Object)((Component)val).gameObject).name, "FPVNeckCap", StringComparison.Ordinal))
				{
					_cachedNeckCapRenderer = val;
					break;
				}
			}
		}

		private static void EnsureFpvReflection()
		{
			if (_fpvProbeAttempted)
			{
				return;
			}
			_fpvProbeAttempted = true;
			if (!Chainloader.PluginInfos.TryGetValue("com.seeya.firstpersonview", out var value) || value == null || (Object)(object)value.Instance == (Object)null)
			{
				return;
			}
			try
			{
				_fpvControllerType = ((object)value.Instance).GetType().Assembly.GetType("FirstPersonView.LocalBodyViewController", throwOnError: false);
				if (_fpvControllerType == null)
				{
					return;
				}
				_fpvBodyShownProp = _fpvControllerType.GetProperty("LocalBodyShown", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (_fpvBodyShownProp != null && _fpvBodyShownProp.PropertyType == typeof(bool))
				{
					MethodInfo getMethod = _fpvBodyShownProp.GetGetMethod(nonPublic: true);
					_fpvBodyShownIsStatic = getMethod != null && getMethod.IsStatic;
				}
				else
				{
					_fpvBodyShownProp = null;
					_fpvBodyShownField = _fpvControllerType.GetField("LocalBodyShown", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					if (_fpvBodyShownField != null && _fpvBodyShownField.FieldType == typeof(bool))
					{
						_fpvBodyShownIsStatic = _fpvBodyShownField.IsStatic;
					}
					else
					{
						_fpvBodyShownField = null;
					}
				}
				if (!_fpvBodyShownIsStatic)
				{
					_fpvInstanceProp = _fpvControllerType.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					_fpvInstanceField = _fpvControllerType.GetField("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? _fpvControllerType.GetField("_instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = SurveillanceBootstrap.Log;
				if (log != null)
				{
					log.LogWarning((object)("[LethalCCTV][CameraTrace] FPV reflection probe failed: " + ex.Message));
				}
			}
		}

		private static int ReadFpvBodyShown(PlayerControllerB player)
		{
			if (_fpvBodyShownProp == null && _fpvBodyShownField == null)
			{
				return -1;
			}
			try
			{
				object obj = null;
				if (!_fpvBodyShownIsStatic)
				{
					if ((Object)(object)_cachedFpvControllerComponent != (Object)null)
					{
						obj = _cachedFpvControllerComponent;
					}
					else if (_fpvInstanceProp != null)
					{
						obj = _fpvInstanceProp.GetValue(null, null);
					}
					else if (_fpvInstanceField != null)
					{
						obj = _fpvInstanceField.GetValue(null);
					}
					else if (_fpvControllerType != null && typeof(Component).IsAssignableFrom(_fpvControllerType) && (Object)(object)player != (Object)null)
					{
						_cachedFpvControllerComponent = ((Component)player).GetComponent(_fpvControllerType);
						obj = _cachedFpvControllerComponent;
					}
					if (obj == null)
					{
						return -1;
					}
				}
				return (((_fpvBodyShownProp != null) ? _fpvBodyShownProp.GetValue(obj, null) : _fpvBodyShownField.GetValue(obj)) is bool flag) ? (flag ? 1 : 0) : (-1);
			}
			catch
			{
				return -1;
			}
		}

		private static string ResolveBodyMeshName(PlayerControllerB player)
		{
			if ((Object)(object)player.thisPlayerModel == (Object)null || (Object)(object)player.thisPlayerModel.sharedMesh == (Object)null)
			{
				return string.Empty;
			}
			string name = ((Object)player.thisPlayerModel.sharedMesh).name;
			if (string.IsNullOrEmpty(name))
			{
				return string.Empty;
			}
			if (name.IndexOf(',') < 0 && name.IndexOf('\n') < 0 && name.IndexOf('\r') < 0)
			{
				return name;
			}
			return name.Replace(',', '_').Replace('\r', ' ').Replace('\n', ' ');
		}

		private static string FormatRow(int frame, float time, float dtMs, bool isCrouching, bool inSpecialAnim, int fpvBodyShown, Vector3 camLocal, float containerLocalY, float containerLocalZ, float armsMetarigLocalY, float armsMetarigLocalZ, string bodyMeshName, int neckCapEnabled, float cameraUp, float camLocalEulerX)
		{
			CultureInfo invariantCulture = CultureInfo.InvariantCulture;
			RowBuilder.Clear();
			RowBuilder.Append(frame.ToString(invariantCulture)).Append(',');
			RowBuilder.Append(time.ToString("F4", invariantCulture)).Append(',');
			RowBuilder.Append(dtMs.ToString("F3", invariantCulture)).Append(',');
			RowBuilder.Append(isCrouching ? '1' : '0').Append(',');
			RowBuilder.Append(inSpecialAnim ? '1' : '0').Append(',');
			RowBuilder.Append(fpvBodyShown.ToString(invariantCulture)).Append(',');
			RowBuilder.Append(camLocal.x.ToString("F5", invariantCulture)).Append(',');
			RowBuilder.Append(camLocal.y.ToString("F5", invariantCulture)).Append(',');
			RowBuilder.Append(camLocal.z.ToString("F5", invariantCulture)).Append(',');
			RowBuilder.Append(containerLocalY.ToString("F5", invariantCulture)).Append(',');
			RowBuilder.Append(containerLocalZ.ToString("F5", invariantCulture)).Append(',');
			RowBuilder.Append(armsMetarigLocalY.ToString("F5", invariantCulture)).Append(',');
			RowBuilder.Append(armsMetarigLocalZ.ToString("F5", invariantCulture)).Append(',');
			RowBuilder.Append(bodyMeshName).Append(',');
			RowBuilder.Append(neckCapEnabled.ToString(invariantCulture)).Append(',');
			RowBuilder.Append(cameraUp.ToString("F3", invariantCulture)).Append(',');
			RowBuilder.Append(camLocalEulerX.ToString("F3", invariantCulture));
			return RowBuilder.ToString();
		}
	}
	internal sealed class CctvCameraTraceWriter
	{
		internal const int DefaultMaxRowsPerRound = 5000;

		internal const int DefaultMaxRowsPerFile = 20000;

		private readonly string _filePath;

		private readonly string _prevFilePath;

		private readonly string _header;

		private readonly int _maxRowsPerRound;

		private readonly int _maxRowsPerFile;

		private readonly StringBuilder _buffer = new StringBuilder(16384);

		private int _rowsWrittenThisRound;

		private int _rowsWrittenInCurrentFile;

		private int _bufferedRows;

		private bool _sessionFileInitialized;

		private bool _rotateBeforeNextWrite;

		internal string FilePath => _filePath;

		internal string PrevFilePath => _prevFilePath;

		internal int RowsWrittenThisRound => _rowsWrittenThisRound;

		internal int RowsWrittenInCurrentFile => _rowsWrittenInCurrentFile;

		internal int BufferedRows => _bufferedRows;

		internal bool RoundCapReached => _rowsWrittenThisRound >= _maxRowsPerRound;

		internal CctvCameraTraceWriter(string filePath, string header, int maxRowsPerRound = 5000, int maxRowsPerFile = 20000)
		{
			_filePath = filePath;
			_prevFilePath = BuildPrevPath(filePath);
			_header = header;
			_maxRowsPerRound = Math.Max(1, maxRowsPerRound);
			_maxRowsPerFile = Math.Max(_maxRowsPerRound, maxRowsPerFile);
		}

		internal bool TryBufferRow(string row)
		{
			if (RoundCapReached || string.IsNullOrEmpty(row))
			{
				return false;
			}
			_buffer.Append(row).AppendLine();
			_rowsWrittenThisRound++;
			_bufferedRows++;
			return true;
		}

		internal bool Flush(out bool startedNewFile)
		{
			startedNewFile = false;
			if (_bufferedRows <= 0 || _buffer.Length == 0)
			{
				return false;
			}
			try
			{
				bool num = !_sessionFileInitialized || _rotateBeforeNextWrite || _rowsWrittenInCurrentFile >= _maxRowsPerFile;
				string directoryName = Path.GetDirectoryName(_filePath);
				if (!string.IsNullOrEmpty(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				if (num)
				{
					RotateExistingFileIfNonEmpty();
					using (StreamWriter streamWriter = new StreamWriter(_filePath, append: false, Encoding.UTF8))
					{
						streamWriter.WriteLine(_header);
						streamWriter.Write(_buffer.ToString());
					}
					_sessionFileInitialized = true;
					_rotateBeforeNextWrite = false;
					_rowsWrittenInCurrentFile = _bufferedRows;
					startedNewFile = true;
				}
				else
				{
					using (StreamWriter streamWriter2 = new StreamWriter(_filePath, append: true, Encoding.UTF8))
					{
						streamWriter2.Write(_buffer.ToString());
					}
					_rowsWrittenInCurrentFile += _bufferedRows;
				}
				return true;
			}
			finally
			{
				_buffer.Clear();
				_bufferedRows = 0;
			}
		}

		internal void EndRound()
		{
			Flush(out var _);
			_rowsWrittenThisRound = 0;
		}

		internal void EndSession()
		{
			Flush(out var _);
			_rowsWrittenThisRound = 0;
			if (_sessionFileInitialized)
			{
				_rotateBeforeNextWrite = true;
			}
		}

		private void RotateExistingFileIfNonEmpty()
		{
			if (File.Exists(_filePath) && new FileInfo(_filePath).Length > 0)
			{
				if (File.Exists(_prevFilePath))
				{
					File.Delete(_prevFilePath);
				}
				File.Move(_filePath, _prevFilePath);
			}
		}

		private static string BuildPrevPath(string filePath)
		{
			string? path = Path.GetDirectoryName(filePath) ?? string.Empty;
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
			string extension = Path.GetExtension(filePath);
			return Path.Combine(path, fileNameWithoutExtension + ".prev" + extension);
		}
	}
	internal static class CctvChairEventTimer
	{
		private const int MaxSpans = 32;

		private const double MinReportedMilliseconds = 0.05;

		private static readonly string[] _names = new string[32];

		private static readonly long[] _ticks = new long[32];

		private static readonly StringBuilder _builder = new StringBuilder(512);

		private static int _count;

		private static int _dropped;

		private static bool _armed;

		private static long _beganAt;

		private static long _endedAt;

		internal static void Begin()
		{
			_count = 0;
			_dropped = 0;
			_endedAt = 0L;
			_armed = true;
			_beganAt = Stopwatch.GetTimestamp();
		}

		internal static long Start()
		{
			if (!_armed)
			{
				return 0L;
			}
			return Stopwatch.GetTimestamp();
		}

		internal static void Stop(string name, long startedAt)
		{
			if (_armed)
			{
				long num = Stopwatch.GetTimestamp() - startedAt;
				if (_count >= 32)
				{
					_dropped++;
					return;
				}
				_names[_count] = name;
				_ticks[_count] = num;
				_count++;
			}
		}

		internal static void End()
		{
			if (_armed)
			{
				_endedAt = Stopwatch.GetTimestamp();
				_armed = false;
			}
		}

		internal static void Report()
		{
			if (_endedAt == 0L)
			{
				return;
			}
			long endedAt = _endedAt;
			_endedAt = 0L;
			double num = 1000.0 / (double)Stopwatch.Frequency;
			double elapsedMilliseconds = (double)(endedAt - _beganAt) * num;
			CctvLogTier cctvLogTier = CctvDiagnosticLogPolicy.FocusProbe(elapsedMilliseconds, SurveillanceBootstrap.PerformanceTimingEnabled);
			if (cctvLogTier == CctvLogTier.None)
			{
				return;
			}
			_builder.Length = 0;
			_builder.Append("[LethalCCTV][EntryPerf] phase=chair-event frame=").Append(Time.frameCount).Append(" Enter.chair-event=")
				.Append(elapsedMilliseconds.ToString("F2"))
				.Append("ms (nested, not additive:");
			double num2 = 0.0;
			for (int i = 0; i < _count; i++)
			{
				double num3 = (double)_ticks[i] * num;
				if (num3 < 0.05)
				{
					num2 += num3;
				}
				else
				{
					_builder.Append(' ').Append(_names[i]).Append('=')
						.Append(num3.ToString("F2"));
				}
			}
			if (_dropped > 0)
			{
				_builder.Append(" dropped=").Append(_dropped);
			}
			if (num2 >= 0.05)
			{
				_builder.Append(" sub-floor=").Append(num2.ToString("F2"));
			}
			_builder.Append(')');
			SurveillanceBootstrap.LogAt(SurveillanceBootstrap.Log, cctvLogTier, _builder.ToString());
		}
	}
	internal static class CctvChildTiming
	{
		internal static long Start()
		{
			if (!SurveillanceBootstrap.PerformanceTimingEnabled)
			{
				return 0L;
			}
			return Stopwatch.GetTimestamp();
		}

		internal static long Record(string name, long startedAt, int count = -1)
		{
			if (!SurveillanceBootstrap.PerformanceTimingEnabled || startedAt == 0L)
			{
				return 0L;
			}
			long timestamp = Stopwatch.GetTimestamp();
			long num = timestamp - startedAt;
			SurveillanceBootstrap.RecordLateUpdateNestedStep(name, num);
			double num2 = (double)num * 1000.0 / (double)Stopwatch.Frequency;
			bool flag = num2 > 20.0;
			if (flag || num2 >= 0.5)
			{
				SurveillanceBootstrap.LogAt(SurveillanceBootstrap.Log, flag ? CctvLogTier.Warning : CctvLogTier.Info, $"[LethalCCTV.Timing] {name} took {num2:0.00}ms; items={count}");
			}
			return timestamp;
		}

		internal static long RecordReceipt(string name, long startedAt, int count, string detail)
		{
			if (!SurveillanceBootstrap.PerformanceTimingEnabled || startedAt == 0L)
			{
				return 0L;
			}
			long timestamp = Stopwatch.GetTimestamp();
			long num = timestamp - startedAt;
			SurveillanceBootstrap.RecordLateUpdateNestedStep(name, num);
			double num2 = (double)num * 1000.0 / (double)Stopwatch.Frequency;
			SurveillanceBootstrap.LogAt(SurveillanceBootstrap.Log, (num2 > 20.0) ? CctvLogTier.Warning : CctvLogTier.Info, $"[LethalCCTV.Timing] {name} took {num2:0.00}ms; items={count}; {detail}");
			return timestamp;
		}
	}
	internal static class CctvControlGeometry
	{
		internal static readonly Vector3 RedButton = new Vector3(0.27866f, 4.76938f, 3.2164f);

		internal static readonly Vector3 ButtonNormal;

		internal static Quaternion PalmDown(Vector3 normal, Vector3 fingersForward)
		{
			//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_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_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)
			Vector3 val = Vector3.ProjectOnPlane(fingersForward, normal);
			return Quaternion.LookRotation(normal, ((Vector3)(ref val)).normalized);
		}

		internal static bool TryLeverHandleTop(Transform transform, Mesh mesh, out Vector3 top)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: 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)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: 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_01a2: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			top = default(Vector3);
			if ((Object)(object)mesh == (Object)null || mesh.subMeshCount < 2)
			{
				return false;
			}
			SubMeshDescriptor subMesh = mesh.GetSubMesh(1);
			Bounds bounds = ((SubMeshDescriptor)(ref subMesh)).bounds;
			Vector3 size = ((Bounds)(ref bounds)).size;
			if (((Vector3)(ref size)).sqrMagnitude < 1E-06f)
			{
				return false;
			}
			if (mesh.isReadable)
			{
				Vector3[] vertices = mesh.vertices;
				int[] indices = mesh.GetIndices(1);
				if (indices.Length == 0)
				{
					return false;
				}
				Bounds val = default(Bounds);
				((Bounds)(ref val))..ctor(transform.TransformPoint(vertices[indices[0]]), Vector3.zero);
				int[] array = indices;
				foreach (int num in array)
				{
					((Bounds)(ref val)).Encapsulate(transform.TransformPoint(vertices[num]));
				}
				top = new Vector3(((Bounds)(ref val)).center.x, ((Bounds)(ref val)).max.y, ((Bounds)(ref val)).center.z);
			}
			else
			{
				Vector3 val2 = transform.TransformVector(Vector3.right * ((Bounds)(ref bounds)).extents.x);
				Vector3 val3 = transform.TransformVector(Vector3.up * ((Bounds)(ref bounds)).extents.y);
				Vector3 val4 = transform.TransformVector(Vector3.forward * ((Bounds)(ref bounds)).extents.z);
				float num2 = Mathf.Sqrt(val2.y * val2.y + val3.y * val3.y + val4.y * val4.y);
				if (num2 < 0.0001f)
				{
					return false;
				}
				top = transform.TransformPoint(((Bounds)(ref bounds)).center) + Vector3.up * num2;
			}
			return true;
		}

		internal static Vector3 FitMonitorEye(Vector3 eye, Quaternion rotation, Vector3 center, Vector3 right, Vector3 up, float halfWidth, float halfHeight, float fov, float aspect)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: 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_0077: 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_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Tan(fov * 0.5f * (MathF.PI / 180f));
			float num2 = num * Mathf.Max(0.25f, aspect);
			float num3 = 0f;
			Quaternion val = Quaternion.Inverse(rotation);
			for (int i = -1; i <= 1; i += 2)
			{
				for (int j = -1; j <= 1; j += 2)
				{
					Vector3 val2 = center + right * (halfWidth * (float)i) + up * (halfHeight * (float)j);
					Vector3 val3 = val * (val2 - eye);
					num3 = Mathf.Max(num3, Mathf.Abs(val3.x) / (num2 * 0.84f) - val3.z);
					num3 = Mathf.Max(num3, Mathf.Abs(val3.y) / (num * 0.84f) - val3.z);
				}
			}
			return eye - rotation * Vector3.forward * CctvMonitorFitPolicy.ClampPullback(num3);
		}

		internal static bool TryKeepElbowBehindWrist(Vector3 center, Vector3 aim, float radius, Vector3 proposed, Vector3 wrist, Vector3 forward, out Vector3 elbow)
		{
			//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_0009: 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_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: 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_0069: 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_0070: 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_007b: 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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: 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)
			elbow = proposed;
			if (Vector3.Dot(proposed - wrist, forward) <= 0f)
			{
				return true;
			}
			Vector3 val = Vector3.ProjectOnPlane(forward, aim);
			float magnitude = ((Vector3)(ref val)).magnitude;
			if (radius < 1E-06f || magnitude < 1E-06f)
			{
				return false;
			}
			float num = Vector3.Dot(wrist - center, forward) / (radius * magnitude);
			if (num < -1f)
			{
				return false;
			}
			Vector3 val2 = val / magnitude;
			Vector3 val3 = Vector3.Cross(aim, val2);
			Vector3 val4 = ((Vector3)(ref val3)).normalized;
			if (Vector3.Dot(proposed - center, val4) < 0f)
			{
				val4 = -val4;
			}
			float num2 = Mathf.Clamp(num, -1f, 1f);
			elbow = center + radius * (val2 * num2 + val4 * Mathf.Sqrt(1f - num2 * num2));
			return true;
		}

		internal static Vector3 PressPosition(float seconds, Vector3 start, Vector3 rest, Vector3 contact, Vector3 normal)
		{
			//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_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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_0091: 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_0064: 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)
			Vector3 val = contact + normal * 0.07f;
			if (seconds < 0.3f)
			{
				return Vector3.Lerp(start, val, Ease(seconds / 0.3f));
			}
			if (seconds < 0.44f)
			{
				return Vector3.Lerp(val, contact, Ease((seconds - 0.3f) / 0.14f));
			}
			if (seconds < 0.51f)
			{
				return contact;
			}
			if (seconds < 0.66f)
			{
				return Vector3.Lerp(contact, val, Ease((seconds - 0.51f) / 0.15f));
			}
			return Vector3.Lerp(val, rest, Ease((seconds - 0.66f) / 0.34f));
		}

		internal static Vector3 EntryHandPosition(float seconds, Vector3 rest, Vector3 contact, Vector3 grip, Vector3 normal)
		{
			//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_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: 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_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_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = contact + normal * 0.055f;
			if (seconds < 0.27f)
			{
				return Vector3.Lerp(rest, val, Ease(seconds / 0.27f));
			}
			if (seconds < 0.38f)
			{
				return Vector3.Lerp(val, contact, Ease((seconds - 0.27f) / 0.109999985f));
			}
			if (seconds < 0.47f)
			{
				return contact;
			}
			if (seconds < 0.59f)
			{
				return Vector3.Lerp(contact, val, Ease((seconds - 0.47f) / 0.12f));
			}
			float num = Ease((seconds - 0.47f - 0.12f) / 0.54999995f);
			return Vector3.Lerp(val, grip, num) + normal * (0.025f * Mathf.Sin(num * MathF.PI));
		}

		internal static float Ease(float t)
		{
			return CctvIntroTiming.Ease(Mathf.Clamp01(t));
		}

		static CctvControlGeometry()
		{
			//IL_000f: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			Vector3 val = new Vector3(0.5209f, 0.005f, 0.8536f);
			ButtonNormal = ((Vector3)(ref val)).normalized;
		}
	}
	internal static class CctvDeviceCommandLine
	{
		private static TerminalAccessibleObject _target;

		private static CCTVCamera _camera;

		private static CCTVCamera _pendingCamera;

		private static string _code;

		private static string _label;

		private static string _text = "";

		private static string _pending;

		private static Keyboard _keyboard;

		private static RectTransform _root;

		private static TextMeshProUGUI _readout;

		private static float _statusUntil;

		private static float _nextHoverAt;

		private static int _closedFrame = -1;

		private static string _commandKeyLabel;

		private static string _commandHint;

		internal static bool IsOpen => _keyboard != null;

		internal static bool ConsumesInput
		{
			get
			{
				if (!IsOpen)
				{
					return _closedFrame == Time.frameCount;
				}
				return true;
			}
		}

		internal static bool TryOpen(CCTVCamera camera)
		{
			if (IsOpen)
			{
				return true;
			}
			if ((Object)(object)camera?.Cam == (Object)null || camera.IsSecurityBroken || !MonitorFocus.IsStationCameraControlActive)
			{
				return false;
			}
			TerminalAccessibleObject val = CctvDeviceCommands.Hover(camera.Cam);
			if (!CctvDeviceCommands.TryDescribe(val, out var label))
			{
				return false;
			}
			if (Keyboard.current == null)
			{
				ShowStatus("KEYBOARD UNAVAILABLE");
				return true;
			}
			EnsureUi();
			if ((Object)(object)_root == (Object)null)
			{
				return true;
			}
			_target = val;
			_camera = camera;
			_code = val.objectCode;
			_label = label;
			_text = "";
			_pending = null;
			_keyboard = Keyboard.current;
			_keyboard.onTextInput += OnText;
			CCTVWalkieTalkieBridge.SetLocalSpeaking(speaking: false);
			UpdateReadout();
			CCTVStationEvents.RaiseActionButtonPressed("device-command-open");
			return true;
		}

		private static void OnText(char character)
		{
			if (IsOpen && !char.IsControl(character) && _text.Length < 24)
			{
				_text += character;
				UpdateReadout();
			}
		}

		internal static void Tick()
		{
			PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
			if (!MonitorFocus.IsFocused || (Object)(object)val == (Object)null || val.isPlayerDead || !MonitorFocus.IsFacilityFeedActive || !CCTVShipSystemsBridge.IsShipPowerOnline())
			{
				Close(clearStatus: true);
				return;
			}
			CCTVCamera boundCamera = QuadCameraAssignment.GetBoundCamera(MonitorFocus.ActiveSlot);
			if ((Object)(object)boundCamera?.Cam == (Object)null || boundCamera.IsSecurityBroken)
			{
				Close(clearStatus: true);
				return;
			}
			if (_pending != null && (Object)(object)boundCamera != (Object)(object)_pendingCamera)
			{
				Close(clearStatus: true);
				return;
			}
			if (IsOpen)
			{
				bool flag = (Object)(object)_root == (Object)null;
				EnsureUi();
				if ((Object)(object)_target == (Object)null || (Object)(object)boundCamera != (Object)(object)_camera || _target.objectCode != _code)
				{
					Close(clearStatus: true);
					return;
				}
				if (flag)
				{
					UpdateReadout();
				}
				if (((ButtonControl)_keyboard.escapeKey).wasPressedThisFrame)
				{
					Close();
				}
				else if (((ButtonControl)_keyboard.enterKey).wasPressedThisFrame || ((ButtonControl)_keyboard.numpadEnterKey).wasPressedThisFrame)
				{
					Submit();
				}
				else if (((ButtonControl)_keyboard.backspaceKey).wasPressedThisFrame && _text.Length > 0)
				{
					_text = _text.Substring(0, _text.Length - 1);
					UpdateReadout();
				}
				return;
			}
			if (_pending != null && Time.unscaledTime >= _statusUntil)
			{
				_pending = null;
				ShowStatus("NO RESPONSE FROM HOST");
			}
			if (!(Time.unscaledTime < _statusUntil) && !(Time.unscaledTime < _nextHoverAt))
			{
				_nextHoverAt = Time.unscaledTime + 0.1f;
				if (CctvDeviceCommands.TryDescribe(CctvDeviceCommands.Hover(boundCamera.Cam), out var label))
				{
					EnsureUi();
					SetText(label + CommandHint());
				}
				else if ((Object)(object)_root != (Object)null)
				{
					((Component)_root).gameObject.SetActive(false);
				}
			}
		}

		private static string CommandHint()
		{
			string text = BindingLabel.Of(MonitorFocus.GetFocusAction(MonitorFocus.FocusAction.Ping));
			if ((object)text != _commandKeyLabel)
			{
				_commandKeyLabel = text;
				_commandHint = "   /   " + text.ToUpperInvariant() + " COMMAND";
			}
			return _commandHint;
		}

		private static void Submit()
		{
			TerminalAccessibleObject target = _target;
			CCTVCamera camera = _camera;
			string text = _text;
			bool num = (Object)(object)target != (Object)null && target.objectCode == _code && (Object)(object)camera?.Cam != (Object)null && (Object)(object)camera == (Object)(object)QuadCameraAssignment.GetBoundCamera(MonitorFocus.ActiveSlot) && !camera.IsSecurityBroken && (Object)(object)CctvDeviceCommands.Hover(camera.Cam) == (Object)(object)target;
			Close();
			if (!num)
			{
				ShowStatus("TARGET LOST");
				return;
			}
			string text2 = text.Trim().ToLowerInvariant();
			bool num2;
			if (!target.isBigDoor)
			{
				num2 = text2 != "disable";
			}
			else
			{
				if (!(text2 != "unlock"))
				{
					goto IL_00e5;
				}
				num2 = text2 != "open";
			}
			if (num2)
			{
				ShowStatus(target.isBigDoor ? "USE UNLOCK" : "USE DISABLE");
				return;
			}
			goto IL_00e5;
			IL_00e5:
			try
			{
				if (CctvDeviceCommands.Submit(target, camera, text2) == null)
				{
					ShowStatus("HOST COMMAND CHANNEL UNAVAILABLE");
				}
			}
			catch
			{
				_pending = null;
				ShowStatus("COMMAND COULD NOT BE SENT");
			}
		}

		internal static void SetPending(string requestId, CCTVCamera camera)
		{
			_pending = requestId;
			_pendingCamera = camera;
			ShowStatus("COMMAND PENDING", 4f);
		}

		internal static void ReceiveResult(string requestId, string status)
		{
			if (!(_pending != requestId) && MonitorFocus.IsFocused)
			{
				_pending = null;
				ShowStatus(status);
			}
		}

		internal static void Close(bool clearStatus = false)
		{
			if (_keyboard != null)
			{
				_keyboard.onTextInput -= OnText;
				_keyboard = null;
				_closedFrame = Time.frameCount;
			}
			_target = null;
			_camera = null;
			_text = "";
			if (clearStatus)
			{
				_pending = null;
				_pendingCamera = null;
				_statusUntil = 0f;
			}
			if ((Object)(object)_root != (Object)null && ((Component)_root).gameObject.activeSelf)
			{
				((Component)_root).gameObject.SetActive(false);
				CCTVVanillaMonitorDisplay.InvalidateMachineVisionUi();
			}
		}

		internal static void Shutdown()
		{
			Close(clearStatus: true);
			if ((Object)(object)_root != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_root).gameObject);
			}
			_root = null;
			_readout = null;
		}

		private static void ShowStatus(string status, float seconds = 2f)
		{
			_statusUntil = Time.unscaledTime + seconds;
			EnsureUi();
			SetText(status);
		}

		private static void UpdateReadout()
		{
			string text = (((Object)(object)_target != (Object)null && _target.isBigDoor) ? "unlock" : "disable");
			SetText(_label + "  >  " + _text + "_\n" + text + "   /   ENTER SEND   /   ESC CANCEL");
		}

		private static void SetText(string text)
		{
			if (!((Object)(object)_root == (Object)null) && !((Object)(object)_readout == (Object)null))
			{
				((Component)_root).gameObject.SetActive(true);
				((TMP_Text)_readout).text = text ?? "";
				CCTVVanillaMonitorDisplay.InvalidateMachineVisionUi();
			}
		}

		private static void EnsureUi()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: 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_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: 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_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_root != (Object)null))
			{
				_root = new GameObject("CCTV_DeviceCommand", new Type[2]
				{
					typeof(RectTransform),
					typeof(Image)
				}).GetComponent<RectTransform>();
				if (!CCTVVanillaMonitorDisplay.TryAttachToLowerLeftOverlay(((Component)_root).gameObject))
				{
					Object.Destroy((Object)(object)((Component)_root).gameObject);
					_root = null;
					return;
				}
				RectTransform root = _root;
				RectTransform root2 = _root;
				Vector2 val = default(Vector2);
				((Vector2)(ref val))..ctor(0.5f, 0f);
				root2.anchorMax = val;
				root.anchorMin = val;
				_root.pivot = new Vector2(0.5f, 0f);
				_root.anchoredPosition = new Vector2(0f, 48f);
				_root.sizeDelta = new Vector2(510f, 48f);
				Image component = ((Component)_root).GetComponent<Image>();
				((Graphic)component).color = new Color(0.015f, 0.035f, 0.045f, 0.9f);
				((Graphic)component).raycastTarget = false;
				_readout = new GameObject("Text", new Type[2]
				{
					typeof(RectTransform),
					typeof(TextMeshProUGUI)
				}).GetComponent<TextMeshProUGUI>();
				((TMP_Text)_readout).transform.SetParent((Transform)(object)_root, false);
				((Component)_readout).gameObject.layer = ((Component)_root).gameObject.layer;
				((TMP_Text)_readout).rectTransform.anchorMin = Vector2.zero;
				((TMP_Text)_readout).rectTransform.anchorMax = Vector2.one;
				((TMP_Text)_readout).rectTransform.offsetMin = new Vector2(12f, 4f);
				((TMP_Text)_readout).rectTransform.offsetMax = new Vector2(-12f, -4f);
				((TMP_Text)_readout).fontSize = 13f;
				((TMP_Text)_readout).richText = false;
				((Graphic)_readout).color = new Color(0.7f, 0.94f, 0.96f);
				((TMP_Text)_readout).alignment = (TextAlignmentOptions)4097;
				((Graphic)_readout).raycastTarget = false;
			}
		}
	}
	internal enum CctvDeviceAction
	{
		Invalid,
		OpenDoor,
		AlreadyOpen,
		Unpowered,
		DisableTurret,
		Cooldown
	}
	internal static class CctvDeviceCommandPolicy
	{
		internal static CctvDeviceAction Decide(string input, bool door, bool open, bool powered, bool cooling, bool turretActive)
		{
			string text = (input ?? string.Empty).Trim();
			if (door)
			{
				if (!text.Equals("unlock", StringComparison.OrdinalIgnoreCase) && !text.Equals("open", StringComparison.OrdinalIgnoreCase))
				{
					return CctvDeviceAction.Invalid;
				}
				if (!powered)
				{
					return CctvDeviceAction.Unpowered;
				}
				if (!open)
				{
					return CctvDeviceAction.OpenDoor;
				}
				return CctvDeviceAction.AlreadyOpen;
			}
			if (!text.Equals("disable", StringComparison.OrdinalIgnoreCase))
			{
				return CctvDeviceAction.Invalid;
			}
			if (!cooling && turretActive)
			{
				return CctvDeviceAction.DisableTurret;
			}
			return CctvDeviceAction.Cooldown;
		}
	}
	public sealed class CctvDeviceCommandMessage
	{
		public bool IsResult;

		public string RequestId;

		public string Code;

		public string Command;

		public string Status;

		public ulong TargetId;

		public ulong ClientId;

		public int CameraIndex;

		public int MapSeed;

		public Vector3 CameraPosition;

		public Vector3 Direction;

		internal static void Write(FastBufferWriter writer, CctvDeviceCommandMessage message)
		{
			//IL_000a: 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_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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: 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)
			//IL_0082: 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_0098: Unknown result type (might be due to invalid IL or missing references)
			((FastBufferWriter)(ref writer)).WriteValueSafe<bool>(ref message.IsResult, default(ForPrimitives));
			CctvMessageChannel.WriteString(writer, message.RequestId);
			CctvMessageChannel.WriteString(writer, message.Code);
			CctvMessageChannel.WriteString(writer, message.Command);
			CctvMessageChannel.WriteString(writer, message.Status);
			((FastBufferWriter)(ref writer)).WriteValueSafe<ulong>(ref message.TargetId, default(ForPrimitives));
			((FastBufferWriter)(ref writer)).WriteValueSafe<ulong>(ref message.ClientId, default(ForPrimitives));
			((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref message.CameraIndex, default(ForPrimitives));
			((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref message.MapSeed, default(ForPrimitives));
			((FastBufferWriter)(ref writer)).WriteValueSafe(ref message.CameraPosition);
			((FastBufferWriter)(ref writer)).WriteValueSafe(ref message.Direction);
		}

		internal static CctvDeviceCommandMessage Read(FastBufferReader reader)
		{
			//IL_0010: 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_001d: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: 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_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)
			CctvDeviceCommandMessage cctvDeviceCommandMessage = new CctvDeviceCommandMessage();
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref cctvDeviceCommandMessage.IsResult, default(ForPrimitives));
			cctvDeviceCommandMessage.RequestId = CctvMessageChannel.ReadString(reader);
			cctvDeviceCommandMessage.Code = CctvMessageChannel.ReadString(reader);
			cctvDeviceCommandMessage.Command = CctvMessageChannel.ReadString(reader);
			cctvDeviceCommandMessage.Status = CctvMessageChannel.ReadString(reader);
			((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref cctvDeviceCommandMessage.TargetId, default(ForPrimitives));
			((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref cctvDeviceCommandMessage.ClientId, default(ForPrimitives));
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref cctvDeviceCommandMessage.CameraIndex, default(ForPrimitives));
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref cctvDeviceCommandMessage.MapSeed, default(ForPrimitives));
			((FastBufferReader)(ref reader)).ReadValueSafe(ref cctvDeviceCommandMessage.CameraPosition);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref cctvDeviceCommandMessage.Direction);
			return cctvDeviceCommandMessage;
		}
	}
	internal static class CctvDeviceCommands
	{
		private static CctvMessageChannel<CctvDeviceCommandMessage> _channel;

		private static readonly Dictionary<ulong, float> NextRequest = new Dictionary<ulong, float>();

		private static readonly Dictionary<ulong, string> LastRequest = new Dictionary<ulong, string>();

		internal static void Initialize()
		{
			if (_channel != null)
			{
				return;
			}
			try
			{
				_channel = new CctvMessageChannel<CctvDeviceCommandMessage>("y4ngz_cctv_device_v1", CctvDeviceCommandMessage.Write, CctvDeviceCommandMessage.Read, ReceiveRequest, ReceiveResult);
			}
			catch (Exception ex)
			{
				ManualLogSource log = SurveillanceBootstrap.Log;
				if (log != null)
				{
					log.LogWarning((object)("[LethalCCTV] Coded device channel unavailable: " + ex.Message));
				}
			}
		}

		internal static void Reset()
		{
			NextRequest.Clear();
			LastRequest.Clear();
			CctvDeviceCommandLine.Close(clearStatus: true);
		}

		internal static void Shutdown()
		{
			Reset();
			_channel?.Shutdown();
			_channel = null;
			CctvDeviceCommandLine.Shutdown();
		}

		internal static Turret TurretFor(TerminalAccessibleObject device)
		{
			if ((Object)(object)device == (Object)null || device.isBigDoor)
			{
				return null;
			}
			return ((Component)device).GetComponent<Turret>() ?? ((Component)device).GetComponentInParent<Turret>() ?? ((Component)device).GetComponentInChildren<Turret>();
		}

		internal static bool TryDescribe(TerminalAccessibleObject device, out string label)
		{
			label = null;
			if ((Object)(object)device == (Object)null || !((Component)device).gameObject.activeInHierarchy || string.IsNullOrWhiteSpace(device.objectCode))
			{
				return false;
			}
			bool flag = false;
			if (device.codeMaterials != null)
			{
				MeshRenderer[] codeMaterials = device.codeMaterials;
				foreach (MeshRenderer val in codeMaterials)
				{
					if ((Object)(object)val != (Object)null && ((Component)val).gameObject.activeInHierarchy)
					{
						flag = true;
						break;
					}
				}
			}
			if (!flag)
			{
				return false;
			}
			if (!device.isBigDoor && (Object)(object)TurretFor(device) == (Object)null)
			{
				return false;
			}
			label = (device.isBigDoor ? "DOOR " : "TURRET ") + device.objectCode.ToUpperInvariant();
			return true;
		}

		internal static TerminalAccessibleObject Hover(Camera camera)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)camera == (Object)null))
			{
				return RayTarget(((Component)camera).transform.position, ((Component)camera).transform.forward);
			}
			return null;
		}

		private static TerminalAccessibleObject RayTarget(Vector3 origin, Vector3 direction)
		{
			//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)
			if (!CctvSquadPing.TryRayHit(origin, direction, out var hit) || ((RaycastHit)(ref hit)).distance > 60f)
			{
				return null;
			}
			TerminalAccessibleObject val = ((Component)((RaycastHit)(ref hit)).collider).GetComponentInParent<TerminalAccessibleObject>();
			if ((Object)(object)val == (Object)null)
			{
				Turret componentInParent = ((Component)((RaycastHit)(ref hit)).collider).GetComponentInParent<Turret>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					val = ((Component)componentInParent).GetComponent<TerminalAccessibleObject>() ?? ((Component)componentInParent).GetComponentInChildren<TerminalAccessibleObject>();
				}
			}
			if (!TryDescribe(val, out var _))
			{
				return null;
			}
			return val;
		}

		internal static string Submit(TerminalAccessibleObject target, CCTVCamera camera, string command)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			if (_channel == null || (Object)(object)target == (Object)null || (Object)(object)((NetworkBehaviour)target).NetworkObject == (Object)null || !((NetworkBehaviour)target).NetworkObject.IsSpawned || (Object)(object)camera?.Cam == (Object)null)
			{
				return null;
			}
			CctvDeviceCommandMessage cctvDeviceCommandMessage = new CctvDeviceCommandMessage
			{
				RequestId = Guid.NewGuid().ToString("N"),
				TargetId = ((NetworkBehaviour)target).NetworkObjectId,
				Code = target.objectCode,
				Command = command,
				CameraIndex = camera.CameraIndex,
				CameraPosition = ((Component)camera.Cam).transform.position,
				Direction = ((Component)camera.Cam).transform.forward,
				MapSeed = (((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.randomMapSeed : 0)
			};
			CctvDeviceCommandLine.SetPending(cctvDeviceCommandMessage.RequestId, camera);
			_channel.SendServer(cctvDeviceCommandMessage);
			return cctvDeviceCommandMessage.RequestId;
		}

		private static void ReceiveRequest(CctvDeviceCommandMessage request, ulong sender)
		{
			if ((Object)(object)NetworkManager.Singleton == (Object)null || !NetworkManager.Singleton.IsServer || request == null || request.IsResult || string.IsNullOrEmpty(request.RequestId) || request.RequestId.Length > 40 || (LastRequest.TryGetValue(sender, out var value) && value == request.RequestId))
			{
				return;
			}
			string status;
			if (NextRequest.TryGetValue(sender, out var value2) && Time.unscaledTime < value2)
			{
				status = "PLEASE WAIT";
			}
			else
			{
				NextRequest[sender] = Time.unscaledTime + 0.4f;
				LastRequest[sender] = request.RequestId;
				try
				{
					status = Execute(request, sender);
				}
				catch (Exception ex)
				{
					ManualLogSource log = SurveillanceBootstrap.Log;
					if (log != null)
					{
						log.LogWarning((object)("[LethalCCTV] Coded device command failed: " + ex.Message));
					}
					status = "COMMAND FAILED";
				}
			}
			_channel?.SendClients(new CctvDeviceCommandMessage
			{
				IsResult = true,
				ClientId = sender,
				RequestId = request.RequestId,
				Status = status
			});
		}

		private static string Execute(CctvDeviceCommandMessage request, ulong sender)
		{
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: 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_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: 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_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Unknown result type (might be due to invalid IL or missing references)
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || instance.inShipPhase || instance.shipIsLeaving || request.MapSeed