Decompiled source of TrucTweaks v1.5.1

TrucTweaks.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("TrucTweaks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.5.1.0")]
[assembly: AssemblyInformationalVersion("1.5.1")]
[assembly: AssemblyProduct("TrucTweaks")]
[assembly: AssemblyTitle("TrucTweaks")]
[assembly: AssemblyVersion("1.5.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TrucTweaks
{
	internal static class HelmetCamMirror
	{
		private static MethodInfo _getMonitor;

		private static Material _material;

		private static RenderTexture _sharp;

		private static RenderTexture _materialRt;

		internal static void Patch(Harmony h)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			if (Plugin.HelmetCamMonitor.Value <= 0 || !SoftDeps.GeneralImprovements)
			{
				return;
			}
			if (SoftDeps.Has("OpenBodyCams"))
			{
				Plugin.Log.LogInfo((object)"Caméra casque : OpenBodyCams est installé, il s'en charge déjà. Miroir désactivé.");
				return;
			}
			try
			{
				Type type = AccessTools.TypeByName("GeneralImprovements.API.MonitorsAPI");
				Type type2 = AccessTools.TypeByName("GeneralImprovements.Utilities.MonitorsHelper");
				_getMonitor = ((type == null) ? null : AccessTools.Method(type, "GetMonitorAtIndex", new Type[1] { typeof(int) }, (Type[])null));
				MethodInfo methodInfo = ((type2 == null) ? null : AccessTools.Method(type2, "InitializeMonitors", (Type[])null, (Type[])null));
				if (_getMonitor == null || methodInfo == null)
				{
					Plugin.Log.LogWarning((object)"Caméra casque : API de GeneralImprovements introuvable, miroir désactivé.");
					return;
				}
				h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(HelmetCamMirror), "AfterMonitorsCreated", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Plugin.Log.LogInfo((object)$"Caméra casque : sera affichée sur l'écran {Plugin.HelmetCamMonitor.Value}.");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Caméra casque : patch impossible : " + ex.Message));
			}
		}

		private static void AfterMonitorsCreated()
		{
			if ((Object)(object)Plugin.Runner != (Object)null)
			{
				Plugin.Runner.StartCoroutine(Apply());
			}
		}

		private static IEnumerator Apply()
		{
			for (int attempt = 0; attempt < 10; attempt++)
			{
				yield return (object)new WaitForSecondsRealtime((attempt == 0) ? 0.1f : 0.5f);
				if (TryApply(out var why))
				{
					SessionLog.Write($"CAM  {DateTime.Now:HH:mm:ss}  caméra casque affichée sur l'écran {Plugin.HelmetCamMonitor.Value}");
					break;
				}
				if (attempt == 9)
				{
					Plugin.Log.LogWarning((object)("Caméra casque : non affichée (" + why + ")."));
				}
			}
		}

		private static bool TryApply(out string why)
		{
			why = "";
			try
			{
				ManualCameraRenderer val = StartOfRound.Instance?.mapScreen;
				if ((Object)(object)val == (Object)null)
				{
					why = "radar absent";
					return false;
				}
				RenderTexture val2 = (((Object)(object)val.headMountedCam != (Object)null) ? val.headMountedCam.targetTexture : null);
				if ((Object)(object)val2 == (Object)null && (Object)(object)val.headMountedCamUI != (Object)null)
				{
					Texture texture = val.headMountedCamUI.texture;
					val2 = (RenderTexture)(object)((texture is RenderTexture) ? texture : null);
				}
				if ((Object)(object)val2 == (Object)null)
				{
					why = "caméra casque du jeu introuvable";
					return false;
				}
				object obj = Monitor(Plugin.HelmetCamMonitor.Value - 1);
				MeshRenderer val3 = ((obj == null) ? null : Get<MeshRenderer>(obj, "MeshRenderer"));
				if ((Object)(object)val3 == (Object)null)
				{
					why = "écran " + Plugin.HelmetCamMonitor.Value + " introuvable (AddMoreBetterMonitors/UseBetterMonitors actifs ?)";
					return false;
				}
				int num = Get<int>(obj, "ScreenMaterialIndex");
				val2 = Sharpen(val, val2);
				if ((Object)(object)_material != (Object)null && (Object)(object)_materialRt != (Object)(object)val2)
				{
					Object.Destroy((Object)(object)_material);
					_material = null;
				}
				if ((Object)(object)_material == (Object)null)
				{
					_material = BuildMaterial(val2);
					_materialRt = val2;
				}
				if ((Object)(object)_material == (Object)null)
				{
					why = "matériau impossible à créer";
					return false;
				}
				HideRadarThumbnail(val);
				Set(obj, "OverwrittenMaterial", _material);
				Material[] sharedMaterials = ((Renderer)val3).sharedMaterials;
				if (num >= 0 && num < sharedMaterials.Length)
				{
					sharedMaterials[num] = _material;
					((Renderer)val3).sharedMaterials = sharedMaterials;
				}
				return true;
			}
			catch (Exception ex)
			{
				why = ex.InnerException?.Message ?? ex.Message;
				return false;
			}
		}

		private static RenderTexture Sharpen(ManualCameraRenderer map, RenderTexture original)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			int value = Plugin.HelmetCamHeight.Value;
			Camera headMountedCam = map.headMountedCam;
			if (value <= 0 || (Object)(object)headMountedCam == (Object)null || (Object)(object)original == (Object)null)
			{
				return original;
			}
			if ((Object)(object)original == (Object)(object)_sharp)
			{
				return _sharp;
			}
			if (((Texture)original).height >= value)
			{
				return original;
			}
			if ((Object)(object)_sharp == (Object)null)
			{
				int num = Mathf.Max(16, Mathf.RoundToInt((float)value * (float)((Texture)original).width / (float)Mathf.Max(1, ((Texture)original).height)));
				RenderTextureDescriptor descriptor = original.descriptor;
				((RenderTextureDescriptor)(ref descriptor)).width = num;
				((RenderTextureDescriptor)(ref descriptor)).height = value;
				_sharp = new RenderTexture(descriptor)
				{
					name = "TrucTweaks HelmetCam",
					filterMode = (FilterMode)1
				};
				_sharp.Create();
				Plugin.Log.LogInfo((object)$"Caméra casque : image {((Texture)original).width}x{((Texture)original).height} -> {num}x{value}.");
			}
			headMountedCam.targetTexture = _sharp;
			if ((Object)(object)map.headMountedCamUI != (Object)null)
			{
				map.headMountedCamUI.texture = (Texture)(object)_sharp;
			}
			return _sharp;
		}

		private static void HideRadarThumbnail(ManualCameraRenderer map)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.HideRadarHelmetCam.Value && !((Object)(object)map.headMountedCamUI == (Object)null))
			{
				((Transform)((Graphic)map.headMountedCamUI).rectTransform).localScale = Vector3.zero;
			}
		}

		private static Material BuildMaterial(RenderTexture headRt)
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			for (int i = 0; i < 14; i++)
			{
				object obj = Monitor(i);
				if (obj == null)
				{
					continue;
				}
				Camera val = Get<Camera>(obj, "Camera");
				Material val2 = Get<Material>(obj, "AssignedMaterial");
				if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)val.targetTexture == (Object)null)
				{
					continue;
				}
				Material val3 = new Material(val2)
				{
					name = "TrucTweaks HelmetCam"
				};
				int num = 0;
				string[] texturePropertyNames = val3.GetTexturePropertyNames();
				foreach (string text in texturePropertyNames)
				{
					if ((Object)(object)val3.GetTexture(text) == (Object)(object)val.targetTexture)
					{
						val3.SetTexture(text, (Texture)(object)headRt);
						num++;
					}
				}
				if (num > 0)
				{
					return val3;
				}
				Object.Destroy((Object)(object)val3);
			}
			Shader val4 = Shader.Find("HDRP/Unlit");
			if ((Object)(object)val4 == (Object)null)
			{
				return null;
			}
			Material val5 = new Material(val4)
			{
				name = "TrucTweaks HelmetCam"
			};
			val5.SetTexture("_UnlitColorMap", (Texture)(object)headRt);
			return val5;
		}

		private static object Monitor(int i)
		{
			try
			{
				return _getMonitor.Invoke(null, new object[1] { i });
			}
			catch
			{
				return null;
			}
		}

		private static T Get<T>(object o, string prop)
		{
			PropertyInfo propertyInfo = AccessTools.Property(o.GetType(), prop);
			if (propertyInfo != null)
			{
				object value = propertyInfo.GetValue(o);
				if (value is T)
				{
					return (T)value;
				}
			}
			return default(T);
		}

		private static void Set(object o, string prop, object value)
		{
			PropertyInfo propertyInfo = AccessTools.Property(o.GetType(), prop);
			if (propertyInfo != null && propertyInfo.CanWrite)
			{
				propertyInfo.SetValue(o, value);
			}
		}
	}
	internal class ItemWatch : MonoBehaviour
	{
		private static ItemWatch _instance;

		private static PlayerControllerB Local
		{
			get
			{
				try
				{
					return ((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null;
				}
				catch
				{
					return null;
				}
			}
		}

		private void Awake()
		{
			_instance = this;
		}

		internal static void Patch(Harmony h)
		{
			TryPatch(h, typeof(PlayerControllerB), "DespawnHeldObject", "DespawnPrefix", "ConsumedPostfix");
			TryPatch(h, typeof(PlayerControllerB), "DespawnHeldObjectClientRpc", "DespawnClientRpcPrefix", null);
			TryPatch(h, typeof(PlayerControllerB), "DestroyItemInSlot", "DestroySlotPrefix", "ConsumedPostfix");
		}

		private static void TryPatch(Harmony h, Type type, string method, string prefix, string postfix)
		{
			//IL_0043: 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_0069: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(type, method, (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					Plugin.Log.LogWarning((object)("Objets fantômes : méthode introuvable " + type.Name + "." + method));
				}
				else
				{
					h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ItemWatch), prefix, (Type[])null), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(ItemWatch), postfix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Objets fantômes : patch " + type.Name + "." + method + " impossible : " + ex.Message));
			}
		}

		private static void DespawnPrefix(PlayerControllerB __instance, out GrabbableObject __state)
		{
			__state = null;
			if (!((Object)(object)_instance == (Object)null) && !((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Local))
			{
				__state = __instance.currentlyHeldObjectServer;
				if ((Object)(object)__state != (Object)null)
				{
					Log("objet consommé : " + N(__state) + " | " + State(__instance, __state));
				}
			}
		}

		private static void DestroySlotPrefix(PlayerControllerB __instance, int __0, out GrabbableObject __state)
		{
			__state = null;
			if (!((Object)(object)_instance == (Object)null) && !((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Local))
			{
				GrabbableObject[] itemSlots = __instance.ItemSlots;
				__state = ((itemSlots != null && __0 >= 0 && __0 < itemSlots.Length) ? itemSlots[__0] : __instance.ItemOnlySlot);
				if ((Object)(object)__state != (Object)null)
				{
					Log("objet retiré de l'inventaire : " + N(__state) + " | " + State(__instance, __state));
				}
			}
		}

		private static void ConsumedPostfix(PlayerControllerB __instance, GrabbableObject __state)
		{
			if ((Object)(object)__state == (Object)null || (Object)(object)__instance == (Object)null)
			{
				return;
			}
			try
			{
				if (Plugin.GhostFix.Value && !InSlots(__instance, __state))
				{
					__state.EnableItemMeshes(false);
					if ((Object)(object)__instance.currentlyHeldObject == (Object)(object)__state && !__instance.isHoldingObject)
					{
						__instance.currentlyHeldObject = null;
					}
				}
			}
			catch (Exception ex)
			{
				Log("masquage immédiat impossible : " + ex.Message);
			}
			((MonoBehaviour)_instance).StartCoroutine(CheckLater(__instance, __state, N(__state)));
		}

		private static void DespawnClientRpcPrefix(PlayerControllerB __instance)
		{
			if ((Object)(object)__instance != (Object)null && (Object)(object)__instance == (Object)(object)Local)
			{
				Log("confirmation de l'hôte reçue");
			}
		}

		private static IEnumerator CheckLater(PlayerControllerB p, GrabbableObject obj, string name)
		{
			yield return (object)new WaitForSecondsRealtime(Plugin.GhostDelaySeconds.Value);
			if ((Object)(object)obj == (Object)null)
			{
				Log(name + " détruit normalement");
			}
			else
			{
				if ((Object)(object)p == (Object)null || InSlots(p, obj))
				{
					yield break;
				}
				Log($"FANTÔME : {name} existe encore {Plugin.GhostDelaySeconds.Value:0.#} s après, hors inventaire | {State(p, obj)}");
				if (Plugin.GhostFix.Value)
				{
					try
					{
						obj.EnableItemMeshes(false);
					}
					catch (Exception ex)
					{
						Log("masquage impossible : " + ex.Message);
						yield break;
					}
					if ((Object)(object)p.currentlyHeldObject == (Object)(object)obj && !p.isHoldingObject)
					{
						p.currentlyHeldObject = null;
					}
					Log("→ " + name + " masqué chez toi (pas détruit). S'il est rééquipé un jour, le jeu le réaffichera de lui-même.");
				}
			}
		}

		private static bool InSlots(PlayerControllerB p, GrabbableObject o)
		{
			if ((Object)(object)p.ItemOnlySlot == (Object)(object)o)
			{
				return true;
			}
			GrabbableObject[] itemSlots = p.ItemSlots;
			if (itemSlots == null)
			{
				return false;
			}
			for (int i = 0; i < itemSlots.Length; i++)
			{
				if ((Object)(object)itemSlots[i] == (Object)(object)o)
				{
					return true;
				}
			}
			return false;
		}

		private static string N(GrabbableObject o)
		{
			if ((Object)(object)o == (Object)null)
			{
				return "rien";
			}
			try
			{
				return $"{o.itemProperties?.itemName ?? ((Object)o).name}#{((Object)o).GetInstanceID()}";
			}
			catch
			{
				return "?";
			}
		}

		private static string State(PlayerControllerB p, GrabbableObject o)
		{
			try
			{
				bool flag = (Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsHost;
				bool flag2 = (Object)(object)o != (Object)null && (Object)(object)((NetworkBehaviour)o).NetworkObject != (Object)null && ((NetworkBehaviour)o).NetworkObject.IsSpawned;
				return $"emplacement={p.currentItemSlot} tenu(client)={N(p.currentlyHeldObject)} tenu(serveur)={N(p.currentlyHeldObjectServer)} " + $"utilitaire={N(p.ItemOnlySlot)} enMain={p.isHoldingObject} hôte={flag}" + (((Object)(object)o == (Object)null) ? "" : (" | objet: tenuPar=" + (((Object)(object)o.playerHeldBy == (Object)null) ? "personne" : o.playerHeldBy.playerUsername) + " " + string.Format("isHeld={0} réseau={1} parent={2}", o.isHeld, flag2 ? "actif" : "inactif", Object.op_Implicit((Object)(object)((Component)o).transform.parent) ? ((Object)((Component)o).transform.parent).name : "aucun")));
			}
			catch (Exception ex)
			{
				return "(état illisible : " + ex.Message + ")";
			}
		}

		private static void Log(string msg)
		{
			SessionLog.Write($"OBJ  {DateTime.Now:HH:mm:ss.fff}  {msg}");
		}
	}
	internal static class MirageQuiet
	{
		private static PropertyInfo _audioSource;

		private static Type _voiceType;

		private static readonly Dictionary<int, AudioSource> _silenced = new Dictionary<int, AudioSource>();

		internal static void Patch(Harmony h)
		{
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Expected O, but got Unknown
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			if (!SoftDeps.Has("qwbarch.Mirage"))
			{
				return;
			}
			try
			{
				Type type = AccessTools.TypeByName("Mirage.Unity.AudioStream+AudioStream");
				_voiceType = AccessTools.TypeByName("Mirage.Unity.MimicVoice+MimicVoice");
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "InitializeAudioReceiver", (Type[])null, (Type[])null));
				MethodInfo methodInfo2 = ((_voiceType == null) ? null : AccessTools.Method(_voiceType, "FixedUpdate", (Type[])null, (Type[])null));
				_audioSource = ((type == null) ? null : AccessTools.Property(type, "AudioSource"));
				if (methodInfo == null || methodInfo2 == null || _audioSource == null || AccessTools.Field(_voiceType, "audioStream") == null)
				{
					Plugin.Log.LogWarning((object)"Mirage : version non reconnue, voix laissées telles quelles.");
					return;
				}
				h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(MirageQuiet), "OnPhraseStart", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				h.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(MirageQuiet), "AfterMirageTick", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Plugin.Log.LogInfo((object)$"Mirage : mobs repérés silencieux (rayon {Plugin.MirageQuietDistance.Value} m, groupe {Plugin.MirageQuietCrowd.Value}).");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Mirage : patch impossible : " + ex.Message));
			}
		}

		private static void OnPhraseStart(Component __instance)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null)
				{
					return;
				}
				int instanceID = ((Object)__instance).GetInstanceID();
				object? value = _audioSource.GetValue(__instance);
				AudioSource val = (AudioSource)((value is AudioSource) ? value : null);
				EnemyAI componentInParent = __instance.GetComponentInParent<EnemyAI>();
				if ((Object)(object)val == (Object)null || (Object)(object)componentInParent == (Object)null)
				{
					_silenced.Remove(instanceID);
					return;
				}
				string text = Reason(componentInParent);
				if (text == null)
				{
					if (_silenced.Remove(instanceID))
					{
						val.mute = false;
					}
				}
				else
				{
					_silenced[instanceID] = val;
					val.mute = true;
					SessionLog.Write($"VOX  {DateTime.Now:HH:mm:ss}  {componentInParent.enemyType?.enemyName ?? ((Object)componentInParent).name} muet ({text})");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Mirage : " + ex.Message));
			}
		}

		private static void AfterMirageTick(object ___audioStream)
		{
			if (_silenced.Count == 0)
			{
				return;
			}
			Component val = (Component)((___audioStream is Component) ? ___audioStream : null);
			if (val != null && (Object)(object)val != (Object)null && _silenced.TryGetValue(((Object)val).GetInstanceID(), out var value))
			{
				if ((Object)(object)value != (Object)null)
				{
					value.mute = true;
				}
				else
				{
					_silenced.Remove(((Object)val).GetInstanceID());
				}
			}
		}

		private static string Reason(EnemyAI enemy)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)val == (Object)null || (Object)(object)instance == (Object)null || enemy.isEnemyDead)
			{
				return null;
			}
			Transform val2 = (((Object)(object)instance.activeCamera != (Object)null) ? ((Component)instance.activeCamera).transform : (((Object)(object)val.gameplayCamera != (Object)null) ? ((Component)val.gameplayCamera).transform : null));
			if ((Object)(object)val2 == (Object)null)
			{
				return null;
			}
			Vector3 position = val2.position;
			float value = Plugin.MirageQuietDistance.Value;
			float num = Vector3.Distance(position, ((Component)enemy).transform.position);
			if (!val.isPlayerDead && (Object)(object)enemy.targetPlayer == (Object)(object)val && enemy.movingTowardsTargetPlayer && num <= value * 2f)
			{
				return $"te poursuit, {num:0} m";
			}
			if (num <= value && InPlainSight(position, enemy, instance))
			{
				return $"à découvert, {num:0} m";
			}
			int value2 = Plugin.MirageQuietCrowd.Value;
			if (value2 > 1 && num <= value)
			{
				int num2 = 0;
				List<EnemyAI> list = (((Object)(object)RoundManager.Instance != (Object)null) ? RoundManager.Instance.SpawnedEnemies : null);
				if (list != null)
				{
					foreach (EnemyAI item in list)
					{
						if ((Object)(object)item != (Object)null && !item.isEnemyDead && Vector3.Distance(position, ((Component)item).transform.position) <= value && (Object)(object)((Component)item).GetComponent(_voiceType) != (Object)null)
						{
							num2++;
						}
					}
				}
				if (num2 >= value2)
				{
					return $"{num2} mobs autour";
				}
			}
			return null;
		}

		private static bool InPlainSight(Vector3 eye, EnemyAI enemy, StartOfRound sor)
		{
			//IL_002b: 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_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = (((Object)(object)enemy.eye != (Object)null) ? enemy.eye.position : (((Component)enemy).transform.position + Vector3.up));
			return !Physics.Linecast(eye, val, sor.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1);
		}
	}
	[BepInPlugin("truc.tweaks", "TrucTweaks", "1.5.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "truc.tweaks";

		public const string Name = "TrucTweaks";

		public const string Version = "1.5.1";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> MuteSpam;

		internal static ConfigEntry<string> MutedPrefixes;

		internal static ConfigEntry<bool> HitchEnabled;

		internal static ConfigEntry<float> HitchThresholdMs;

		internal static ConfigEntry<bool> MinuteSummary;

		internal static ConfigEntry<bool> ItemLogs;

		internal static ConfigEntry<bool> GhostFix;

		internal static ConfigEntry<float> GhostDelaySeconds;

		internal static ConfigEntry<bool> PanelEnabled;

		internal static ConfigEntry<string> PanelSide;

		internal static ConfigEntry<float> PanelScale;

		internal static ConfigEntry<float> PanelOffsetX;

		internal static ConfigEntry<float> PanelOffsetY;

		internal static ConfigEntry<float> PanelOffsetZ;

		internal static ConfigEntry<float> PanelYaw;

		internal static ConfigEntry<bool> PanelShowHiddenMoons;

		internal static ConfigEntry<string> PanelMessages;

		internal static MonoBehaviour Runner;

		internal static ConfigEntry<bool> ShipScrapWithInventory;

		internal static ConfigEntry<int> HelmetCamMonitor;

		internal static ConfigEntry<int> HelmetCamHeight;

		internal static ConfigEntry<bool> HideRadarHelmetCam;

		internal static ConfigEntry<bool> SpectatorClearView;

		internal static ConfigEntry<bool> SpectatorMobsOnLeftTrigger;

		internal static ConfigEntry<bool> MirageQuietEnabled;

		internal static ConfigEntry<float> MirageQuietDistance;

		internal static ConfigEntry<int> MirageQuietCrowd;

		internal static ConfigEntry<bool> AimAssist;

		internal static ConfigEntry<bool> HandRayOnTarget;

		internal static ConfigEntry<float> AimAssistRadius;

		internal static ConfigEntry<float> HandRayGuideAngle;

		private const string DefaultPrefixes = "Targetable A;Set puma ;Stalking frozen;Puma;puma:;PUMA AI;Get end target tree;Getting end target tree;Got target tree;Got tree;tree #;i:;Adding tree ';Num of trees;Checking Tree #;player knowledge;Received tree climb;Send Stalking charge;Confirm leap to tree;Distance from startingPos;Set GetTargetTree;Flashlight click;Flashlight being disabled or enabled;Desk: ;enemy rush index;Time since hitting;Whining audio playing;Reviving players;Skipping player #;Path to exit could not be calculated;Is being used set to;secondary use ;Add to anger meter;Setting animation on client;Item slot #;Got target player?;Interact trigger destroying;Picked up scrap ";

		private void Awake()
		{
			//IL_040e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0414: Expected O, but got Unknown
			//IL_043a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0440: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			MuteSpam = ((BaseUnityPlugin)this).Config.Bind<bool>("Logs", "MuteVanillaSpam", true, "Coupe les messages de debug du jeu de base listés dans MutedPrefixes (ils ne sont plus écrits dans Player.log).");
			MutedPrefixes = ((BaseUnityPlugin)this).Config.Bind<string>("Logs", "MutedPrefixes", "Targetable A;Set puma ;Stalking frozen;Puma;puma:;PUMA AI;Get end target tree;Getting end target tree;Got target tree;Got tree;tree #;i:;Adding tree ';Num of trees;Checking Tree #;player knowledge;Received tree climb;Send Stalking charge;Confirm leap to tree;Distance from startingPos;Set GetTargetTree;Flashlight click;Flashlight being disabled or enabled;Desk: ;enemy rush index;Time since hitting;Whining audio playing;Reviving players;Skipping player #;Path to exit could not be calculated;Is being used set to;secondary use ;Add to anger meter;Setting animation on client;Item slot #;Got target player?;Interact trigger destroying;Picked up scrap ", "Débuts de messages à couper, séparés par des points-virgules. Seuls les messages d'info sont filtrés, jamais les avertissements ni les erreurs.");
			HitchEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Hitches", "Enabled", true, "Note chaque gel du jeu (image trop longue) avec l'heure et ce qui se passait, dans BepInEx/TrucTweaks/.");
			HitchThresholdMs = ((BaseUnityPlugin)this).Config.Bind<float>("Hitches", "ThresholdMs", 100f, "Durée d'image à partir de laquelle on note un gel, en millisecondes (72 Hz = 14 ms par image).");
			MinuteSummary = ((BaseUnityPlugin)this).Config.Bind<bool>("Hitches", "MinuteSummary", true, "Écrit aussi un résumé par minute (images par seconde, pire image, ramasse-miettes, mémoire).");
			ItemLogs = ((BaseUnityPlugin)this).Config.Bind<bool>("Items", "WatchItems", true, "Surveille les objets consommés (clés…) et note dans le log de session ce qui leur arrive (pour la clé fantôme).");
			GhostFix = ((BaseUnityPlugin)this).Config.Bind<bool>("Items", "HideGhostItems", true, "Masque chez toi un objet resté affiché en main alors qu'il n'est plus dans ton inventaire (clé fantôme). Ne détruit rien.");
			GhostDelaySeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Items", "GhostDelaySeconds", 2f, "Temps d'attente avant de considérer un objet comme fantôme, en secondes.");
			PanelEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Panel", "Enabled", true, "Affiche un panneau de boutons à côté du terminal en VR (lunes, magasin, codes, radar, messages, infos, vente).");
			PanelSide = ((BaseUnityPlugin)this).Config.Bind<string>("Panel", "Side", "Right", "Côté du clavier où placer le panneau : Right ou Left.");
			PanelScale = ((BaseUnityPlugin)this).Config.Bind<float>("Panel", "Scale", 0.0009f, "Taille du panneau (le clavier LCVR est à 0.0009). Plus grand = boutons plus gros.");
			PanelOffsetX = ((BaseUnityPlugin)this).Config.Bind<float>("Panel", "OffsetX", 0f, "Décalage vers la droite, en mètres (négatif = vers la gauche).");
			PanelOffsetY = ((BaseUnityPlugin)this).Config.Bind<float>("Panel", "OffsetY", 0f, "Décalage vers le haut, en mètres.");
			PanelOffsetZ = ((BaseUnityPlugin)this).Config.Bind<float>("Panel", "OffsetZ", 0f, "Décalage vers l'avant/l'arrière, en mètres.");
			PanelYaw = ((BaseUnityPlugin)this).Config.Bind<float>("Panel", "TurnTowardYou", 0f, "Tourne le panneau vers toi, en degrés (ex. 20).");
			PanelShowHiddenMoons = ((BaseUnityPlugin)this).Config.Bind<bool>("Panel", "ShowHiddenMoons", true, "Affiche aussi les lunes cachées (marquées *), pour y aller sans taper leur nom.");
			PanelMessages = ((BaseUnityPlugin)this).Config.Bind<string>("Panel", "SignalMessages", "HELP,RUN,COME BACK,SHIP NOW,LEAVE NOW,WAIT,FOLLOW ME,GO LEFT,GO RIGHT,TURN BACK,FIRE EXIT,MAIN DOOR,DANGER,TURRET,MINES,DOG,GIANT,TRAP,BRING KEY,OK,NO,YES,NICE,LOL", "Messages prêts pour le signal translator, séparés par des virgules (10 caractères max chacun, en anglais de préférence).");
			ShipScrapWithInventory = ((BaseUnityPlugin)this).Config.Bind<bool>("Monitors", "ShipScrapIncludesInventory", true, "Écran SHIP SCRAP de GeneralImprovements : ajoute la valeur des objets rangés dans la trappe (ShipInventory). Sans effet si l'un des deux mods manque.");
			HelmetCamMonitor = ((BaseUnityPlugin)this).Config.Bind<int>("Monitors", "HelmetCamMonitor", 13, "Numéro de l'écran GeneralImprovements (1-14, même numérotation que ShipMonitorN) où afficher la caméra casque du jeu (vue du joueur suivi). 0 = désactivé.");
			HelmetCamHeight = ((BaseUnityPlugin)this).Config.Bind<int>("Monitors", "HelmetCamHeight", 480, "Hauteur en pixels de l'image de la caméra casque (le jeu la calcule en tout petit). Plus grand = plus net mais un peu plus coûteux. 0 = taille du jeu.");
			HideRadarHelmetCam = ((BaseUnityPlugin)this).Config.Bind<bool>("Monitors", "HideRadarHelmetCam", true, "Cache le petit médaillon 'vue joueur' sur le radar quand la caméra casque est affichée en grand (même image, inutile en double).");
			SpectatorClearView = ((BaseUnityPlugin)this).Config.Bind<bool>("Spectator", "ClearView", true, "VR (LCVR) : à la mort, coupe le brouillard et allume la lampe de spectateur d'office. Les boutons du poignet marchent toujours.");
			SpectatorMobsOnLeftTrigger = ((BaseUnityPlugin)this).Config.Bind<bool>("Spectator", "MobsOnLeftTrigger", true, "VR (LCVR) + mod SpectateEnemies : mort, la gâchette gauche passe de mob en mob (la droite reste pour les joueurs).");
			MirageQuietEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Mirage", "QuietWhenSpotted", true, "Mirage : un mob ne t'imite plus la voix (chez toi seulement) s'il te poursuit, s'il est proche et à découvert, ou s'ils sont plusieurs autour de toi.");
			MirageQuietDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Mirage", "QuietDistance", 20f, "Distance (mètres) en dessous de laquelle un mob à découvert se tait.");
			MirageQuietCrowd = ((BaseUnityPlugin)this).Config.Bind<int>("Mirage", "QuietCrowd", 3, "Nombre de mobs imitateurs dans ce rayon à partir duquel ils se taisent tous. 0 = règle désactivée.");
			AimAssist = ((BaseUnityPlugin)this).Config.Bind<bool>("VR", "AimAssist", true, "VR (LCVR) : la visée des objets ignore l'objet tenu en main et accepte un objet tout proche du rayon (fusibles, portes, objets au sol).");
			AimAssistRadius = ((BaseUnityPlugin)this).Config.Bind<float>("VR", "AimAssistRadius", 0.08f, "Tolérance de visée autour du rayon, en mètres (0 = rayon exact de LCVR).");
			HandRayOnTarget = ((BaseUnityPlugin)this).Config.Bind<bool>("VR", "HandRayOnTarget", true, "VR (LCVR) : affiche un fin rayon de la main jusqu'à l'objet, la porte ou l'interrupteur visé, et seulement à ce moment-là (rien quand on ne vise rien).");
			HandRayGuideAngle = ((BaseUnityPlugin)this).Config.Bind<float>("VR", "HandRayGuideAngle", 15f, "VR (LCVR) : angle (degrés) du cône de guidage. Quand un objet, une porte ou un interrupteur est dans ce cône sans être visé, un rayon orange montre où pointe ta main pour corriger ; il devient blanc sur la cible. 0 = rayon seulement sur la cible.");
			SessionLog.Open();
			Harmony h = new Harmony("truc.tweaks");
			if (MuteSpam.Value)
			{
				LogFilter.Load(MutedPrefixes.Value);
				LogFilter.Patch(h);
			}
			GameObject val = new GameObject("TrucTweaks.Monitor");
			Object.DontDestroyOnLoad((Object)(object)val);
			((Object)val).hideFlags = (HideFlags)61;
			if (HitchEnabled.Value)
			{
				val.AddComponent<HitchMonitor>();
				RoundEvents.Patch(h);
			}
			if (ItemLogs.Value)
			{
				val.AddComponent<ItemWatch>();
				ItemWatch.Patch(h);
			}
			Runner = (MonoBehaviour)(object)val.AddComponent<CoroutineRunner>();
			if (PanelEnabled.Value)
			{
				TerminalPanel.Patch(h);
			}
			if (ShipScrapWithInventory.Value)
			{
				ShipScrapBridge.Patch(h);
			}
			HelmetCamMirror.Patch(h);
			SpectatorTweaks.Patch(h);
			if (MirageQuietEnabled.Value)
			{
				MirageQuiet.Patch(h);
			}
			if (AimAssist.Value || HandRayOnTarget.Value)
			{
				VrAimAssist.Patch(h);
			}
			Debug.Log((object)"Targetable A");
			Debug.Log((object)$"[TrucTweaks] filtre actif : {LogFilter.Count} préfixes, auto-test OK si 'Targetable A' n'est pas juste au-dessus");
			Log.LogInfo((object)string.Format("{0} {1} chargé (filtre={2}, gels={3}, objets={4}, fantômes={5}, panneau={6})", "TrucTweaks", "1.5.1", MuteSpam.Value, HitchEnabled.Value, ItemLogs.Value, GhostFix.Value, PanelEnabled.Value));
		}
	}
	internal class CoroutineRunner : MonoBehaviour
	{
	}
	internal static class LogFilter
	{
		private static string[] _prefixes = Array.Empty<string>();

		internal static long Muted;

		internal static int Count => _prefixes.Length;

		internal static void Load(string raw)
		{
			_prefixes = (from p in (raw ?? "").Split(';')
				where p.Length > 0
				select p).Distinct().ToArray();
		}

		internal static void Patch(Harmony h)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			HarmonyMethod val = new HarmonyMethod(typeof(LogFilter), "Prefix", (Type[])null);
			HarmonyMethod val2 = new HarmonyMethod(typeof(LogFilter), "PrefixCtx", (Type[])null);
			MethodInfo methodInfo = AccessTools.Method(typeof(Logger), "Log", new Type[2]
			{
				typeof(LogType),
				typeof(object)
			}, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(Logger), "Log", new Type[3]
			{
				typeof(LogType),
				typeof(object),
				typeof(Object)
			}, (Type[])null);
			if (methodInfo != null)
			{
				h.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo2 != null)
			{
				h.Patch((MethodBase)methodInfo2, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool Prefix(LogType logType, object message)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return !ShouldMute(logType, message);
		}

		private static bool PrefixCtx(LogType logType, object message)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return !ShouldMute(logType, message);
		}

		private static bool ShouldMute(LogType type, object message)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)type != 3 || message == null)
			{
				return false;
			}
			string text = (message as string) ?? message.ToString();
			if (text == null)
			{
				return false;
			}
			string[] prefixes = _prefixes;
			for (int i = 0; i < prefixes.Length; i++)
			{
				if (text.StartsWith(prefixes[i], StringComparison.Ordinal))
				{
					Muted++;
					return true;
				}
			}
			return false;
		}
	}
	internal class HitchMonitor : MonoBehaviour
	{
		private static string _lastEvent = "démarrage";

		private static double _lastEventAt;

		private double _prev;

		private int _gc0;

		private int _minute = -1;

		private int _frames;

		private int _hitches;

		private int _gcInMinute;

		private double _worst;

		private long _mutedAtMinuteStart;

		private readonly int[] _buckets = new int[4];

		private void Awake()
		{
			_prev = Time.realtimeSinceStartupAsDouble;
			_gc0 = GC.CollectionCount(0);
			SceneManager.sceneLoaded += delegate(Scene s, LoadSceneMode mode)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				Event($"scène chargée : {((Scene)(ref s)).name} ({mode})");
			};
			SceneManager.sceneUnloaded += delegate(Scene s)
			{
				Event("scène déchargée : " + ((Scene)(ref s)).name);
			};
		}

		internal static void Event(string label)
		{
			_lastEvent = label;
			_lastEventAt = Time.realtimeSinceStartupAsDouble;
			Write($"EVT  {DateTime.Now:HH:mm:ss.fff}  {label}");
		}

		private static void Write(string line)
		{
			SessionLog.Write(line);
		}

		internal static void Raw(string line)
		{
			SessionLog.Write(line);
		}

		private void Update()
		{
			double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
			double num = realtimeSinceStartupAsDouble - _prev;
			_prev = realtimeSinceStartupAsDouble;
			int num2 = GC.CollectionCount(0);
			int num3 = num2 - _gc0;
			_gc0 = num2;
			_frames++;
			_gcInMinute += num3;
			if (num > _worst)
			{
				_worst = num;
			}
			double num4 = num * 1000.0;
			if (num4 >= (double)Plugin.HitchThresholdMs.Value)
			{
				_hitches++;
				_buckets[(!(num4 < 250.0)) ? ((num4 < 500.0) ? 1 : ((num4 < 1000.0) ? 2 : 3)) : 0]++;
				Write(string.Format("GEL  {0:HH:mm:ss.fff}  {1,6:0} ms | GC:{2} | {3} Mo | ", DateTime.Now, num4, (num3 > 0) ? "OUI" : "non", GC.GetTotalMemory(forceFullCollection: false) / 1048576) + $"{_lastEvent} (il y a {realtimeSinceStartupAsDouble - _lastEventAt:0.0} s) | {SceneManager.sceneCount} scènes");
				if (num4 >= 1000.0)
				{
					Plugin.Log.LogWarning((object)$"Gel de {num4:0} ms (dernier événement : {_lastEvent})");
				}
			}
			if (Plugin.MinuteSummary.Value)
			{
				int minute = DateTime.Now.Minute;
				if (_minute == -1)
				{
					_minute = minute;
					_mutedAtMinuteStart = LogFilter.Muted;
				}
				else if (minute != _minute)
				{
					long num5 = LogFilter.Muted - _mutedAtMinuteStart;
					Write($"MIN  {DateTime.Now.AddMinutes(-1.0):HH:mm}  {(double)_frames / 60.0,5:0.0} img/s | pire {_worst * 1000.0,5:0} ms | gels {_hitches} | GC {_gcInMinute} | " + $"{GC.GetTotalMemory(forceFullCollection: false) / 1048576} Mo | messages coupés {num5}");
					_minute = minute;
					_frames = 0;
					_hitches = 0;
					_gcInMinute = 0;
					_worst = 0.0;
					_mutedAtMinuteStart = LogFilter.Muted;
				}
			}
		}

		private void OnApplicationQuit()
		{
			Write($"FIN  {DateTime.Now:HH:mm:ss}  gels 100-250 ms: {_buckets[0]}, 250-500 ms: {_buckets[1]}, 0,5-1 s: {_buckets[2]}, >1 s: {_buckets[3]} | messages coupés au total : {LogFilter.Muted}");
			SessionLog.Close();
		}
	}
	internal static class SessionLog
	{
		private static StreamWriter _w;

		internal static void Open()
		{
			try
			{
				string text = Path.Combine(Paths.BepInExRootPath, "TrucTweaks");
				Directory.CreateDirectory(text);
				foreach (FileInfo item in (from f in new DirectoryInfo(text).GetFiles("session_*.log")
					orderby f.Name descending
					select f).Skip(15))
				{
					item.Delete();
				}
				_w = new StreamWriter(Path.Combine(text, $"session_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.log"), append: false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true))
				{
					AutoFlush = true
				};
				_w.WriteLine("# TrucTweaks 1.5.1 — heures locales du PC.");
				_w.WriteLine($"# GEL = image de plus de {Plugin.HitchThresholdMs.Value:0} ms : heure, durée | ramasse-miettes pendant l'image | mémoire C# | dernier événement (il y a X s) | scènes chargées");
				_w.WriteLine("# EVT = moment de la partie, MIN = résumé par minute, OBJ = objets consommés (clé, trappe), PAN = panneau terminal, CAM = caméra casque, SPC = spectateur, VOX = voix Mirage coupées");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Impossible d'ouvrir le log de session : " + ex.Message));
			}
		}

		internal static void Write(string line)
		{
			try
			{
				_w?.WriteLine(line);
			}
			catch
			{
			}
		}

		internal static void Close()
		{
			try
			{
				_w?.Flush();
				_w?.Dispose();
				_w = null;
			}
			catch
			{
			}
		}
	}
	internal static class RoundEvents
	{
		private static readonly Dictionary<string, string> Labels = new Dictionary<string, string>();

		internal static void Patch(Harmony h)
		{
			Add(h, typeof(StartOfRound), "StartGame", "levier tiré (départ vers la lune)");
			Add(h, typeof(RoundManager), "FinishGeneratingLevel", "intérieur généré");
			Add(h, typeof(StartOfRound), "openingDoorsSequence", "atterrissage terminé, portes ouvertes");
			Add(h, typeof(StartOfRound), "ShipLeave", "décollage demandé");
			Add(h, typeof(StartOfRound), "ShipHasLeft", "vaisseau parti (fin du round)");
			Add(h, typeof(RoundManager), "DespawnPropsAtEndOfRound", "nettoyage des objets de fin de round");
			Add(h, typeof(StartOfRound), "EndOfGame", "écran de fin de journée");
			Add(h, typeof(StartOfRound), "PassTimeToNextDay", "jour suivant");
			Add(h, typeof(StartOfRound), "ResetShip", "vaisseau réinitialisé (virés)");
		}

		private static void Add(Harmony h, Type type, string method, string label)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(type, method, (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					Plugin.Log.LogWarning((object)("Repère ignoré, méthode introuvable : " + type.Name + "." + method));
					return;
				}
				Labels[type.Name + "." + method] = label;
				h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(RoundEvents), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Repère " + type.Name + "." + method + " non posé : " + ex.Message));
			}
		}

		private static void Postfix(MethodBase __originalMethod)
		{
			string text = __originalMethod.DeclaringType?.Name + "." + __originalMethod.Name;
			if (!Labels.TryGetValue(text, out var value))
			{
				return;
			}
			if (text == "StartOfRound.StartGame")
			{
				try
				{
					value = value + " : " + StartOfRound.Instance?.currentLevel?.PlanetName;
				}
				catch
				{
				}
			}
			HitchMonitor.Event(value);
		}
	}
	internal static class ShipScrapBridge
	{
		private static FieldInfo _shipTexts;

		private static MethodInfo _giUpdate;

		private static FieldInfo _invInstance;

		private static FieldInfo _storedItems;

		private static MethodInfo _getItems;

		private static FieldInfo _scrapValue;

		private static object _subscribedList;

		private static bool _updating;

		private static readonly Regex Money = new Regex("\\$(\\d+)");

		private static readonly Regex Items = new Regex("\\((\\d+) ITEMS\\)");

		internal static void Patch(Harmony h)
		{
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Expected O, but got Unknown
			if (!SoftDeps.GeneralImprovements || !SoftDeps.ShipInventory)
			{
				return;
			}
			try
			{
				Type type = AccessTools.TypeByName("GeneralImprovements.Utilities.MonitorsHelper");
				Type type2 = AccessTools.TypeByName("ShipInventoryUpdated.Scripts.Inventory");
				Type type3 = AccessTools.TypeByName("ShipInventoryUpdated.Objects.ItemData");
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "UpdateGenericTextList", (Type[])null, (Type[])null));
				_shipTexts = ((type == null) ? null : AccessTools.Field(type, "_shipScrapMonitorTexts"));
				_giUpdate = ((type == null) ? null : AccessTools.Method(type, "UpdateCalculatedScrapMonitors", new Type[1] { typeof(bool) }, (Type[])null));
				_invInstance = ((type2 == null) ? null : AccessTools.Field(type2, "_instance"));
				_storedItems = ((type2 == null) ? null : AccessTools.Field(type2, "_storedItems"));
				_getItems = ((type2 == null) ? null : AccessTools.PropertyGetter(type2, "Items"));
				_scrapValue = ((type3 == null) ? null : AccessTools.Field(type3, "SCRAP_VALUE"));
				if (methodInfo == null || _shipTexts == null || _getItems == null || _scrapValue == null)
				{
					Plugin.Log.LogWarning((object)"Écran SHIP SCRAP : version de GeneralImprovements ou ShipInventory inattendue, ajout de la trappe désactivé.");
					return;
				}
				h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ShipScrapBridge), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Plugin.Log.LogInfo((object)"Écran SHIP SCRAP : la valeur de la trappe sera ajoutée.");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Écran SHIP SCRAP : patch impossible : " + ex.Message));
			}
		}

		private static void Prefix(object __0, ref string __1)
		{
			try
			{
				if (__0 == null || __1 == null || __0 != _shipTexts.GetValue(null))
				{
					return;
				}
				Subscribe();
				Totals(out var value, out var count);
				if (count != 0)
				{
					Match match = Money.Match(__1);
					if (match.Success && int.TryParse(match.Groups[1].Value, out var result))
					{
						__1 = __1.Substring(0, match.Index) + "$" + (result + value) + __1.Substring(match.Index + match.Length);
					}
					Match match2 = Items.Match(__1);
					if (match2.Success && int.TryParse(match2.Groups[1].Value, out var result2))
					{
						__1 = __1.Substring(0, match2.Index) + $"({result2 + count} ITEMS)" + __1.Substring(match2.Index + match2.Length);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Écran SHIP SCRAP : " + ex.Message));
			}
		}

		private static void Totals(out int value, out int count)
		{
			value = 0;
			count = 0;
			if (!(_getItems.Invoke(null, null) is Array array))
			{
				return;
			}
			foreach (object item in array)
			{
				int num = (int)_scrapValue.GetValue(item);
				if (num > 0)
				{
					value += num;
					count++;
				}
			}
		}

		private static void Subscribe()
		{
			if (_invInstance == null || _storedItems == null)
			{
				return;
			}
			object? value = _invInstance.GetValue(null);
			Object val = (Object)((value is Object) ? value : null);
			if (val == (Object)null)
			{
				return;
			}
			object value2 = _storedItems.GetValue(val);
			if (value2 == null || value2 == _subscribedList)
			{
				return;
			}
			EventInfo eventInfo = value2.GetType().GetEvent("OnListChanged");
			if (!(eventInfo == null))
			{
				ParameterExpression[] parameters = Array.ConvertAll(eventInfo.EventHandlerType.GetMethod("Invoke").GetParameters(), (ParameterInfo p) => Expression.Parameter(p.ParameterType, p.Name));
				MethodCallExpression body = Expression.Call(typeof(ShipScrapBridge).GetMethod("OnInventoryChanged", BindingFlags.Static | BindingFlags.NonPublic));
				Delegate handler = Expression.Lambda(eventInfo.EventHandlerType, body, parameters).Compile();
				eventInfo.AddEventHandler(value2, handler);
				_subscribedList = value2;
			}
		}

		private static void OnInventoryChanged()
		{
			if (_updating || _giUpdate == null)
			{
				return;
			}
			_updating = true;
			try
			{
				_giUpdate.Invoke(null, new object[1] { false });
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Écran SHIP SCRAP : mise à jour impossible : " + (ex.InnerException?.Message ?? ex.Message)));
			}
			finally
			{
				_updating = false;
			}
		}
	}
	internal static class SpectatorTweaks
	{
		private static Type _mgrType;

		private static MethodInfo _toggleFog;

		private static MethodInfo _toggleLights;

		private static MethodInfo _stopSpectating;

		private static MethodInfo _teleport;

		private static PropertyInfo _spectatedPlayer;

		private static bool _appliedThisDeath;

		private static int _mobIndex = -1;

		private static bool _showingMobText;

		private static PlayerControllerB Local
		{
			get
			{
				try
				{
					return ((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null;
				}
				catch
				{
					return null;
				}
			}
		}

		internal static void Patch(Harmony h)
		{
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Expected O, but got Unknown
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Expected O, but got Unknown
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Expected O, but got Unknown
			if (!SoftDeps.Has("io.daxcess.lcvr"))
			{
				return;
			}
			try
			{
				_mgrType = AccessTools.TypeByName("LCVR.Managers.SpectatingManager");
				if (_mgrType == null)
				{
					Plugin.Log.LogWarning((object)"Spectateur : SpectatingManager de LCVR introuvable.");
					return;
				}
				_toggleFog = AccessTools.Method(_mgrType, "ToggleFog", (Type[])null, (Type[])null);
				_toggleLights = AccessTools.Method(_mgrType, "ToggleLights", (Type[])null, (Type[])null);
				_stopSpectating = AccessTools.Method(_mgrType, "StopSpectatingPlayer", (Type[])null, (Type[])null);
				_teleport = AccessTools.Method(_mgrType, "TeleportLocalPlayer", (Type[])null, (Type[])null);
				_spectatedPlayer = AccessTools.Property(_mgrType, "SpectatedPlayer");
				MethodInfo methodInfo = AccessTools.Method(_mgrType, "PlayerDeath", (Type[])null, (Type[])null);
				MethodInfo methodInfo2 = AccessTools.Method(_mgrType, "PlayerRevive", (Type[])null, (Type[])null);
				if (Plugin.SpectatorClearView.Value && methodInfo != null && methodInfo2 != null && _toggleFog != null && _toggleLights != null)
				{
					h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(SpectatorTweaks), "AfterDeath", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					h.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(SpectatorTweaks), "AfterRevive", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				if (!Plugin.SpectatorMobsOnLeftTrigger.Value || !SoftDeps.Has("SpectateEnemy"))
				{
					return;
				}
				MethodInfo methodInfo3 = AccessTools.Method(_mgrType, "OnSpectatePrevious", (Type[])null, (Type[])null);
				MethodInfo methodInfo4 = AccessTools.Method(_mgrType, "OnSpectateNext", (Type[])null, (Type[])null);
				if (methodInfo3 != null && _teleport != null)
				{
					h.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(SpectatorTweaks), "LeftTrigger", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					if (methodInfo4 != null)
					{
						h.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(SpectatorTweaks), "RightTrigger", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
					Plugin.Log.LogInfo((object)"Spectateur : gâchette gauche = mobs (SpectateEnemies présent).");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Spectateur : patch impossible : " + ex.Message));
			}
		}

		private static void AfterDeath(object __instance)
		{
			PlayerControllerB local = Local;
			if (_appliedThisDeath || (Object)(object)local == (Object)null || !local.isPlayerDead)
			{
				return;
			}
			_appliedThisDeath = true;
			try
			{
				_toggleFog.Invoke(__instance, new object[1] { false });
				_toggleLights.Invoke(__instance, new object[1] { true });
				SessionLog.Write($"SPC  {DateTime.Now:HH:mm:ss}  mort : brouillard coupé, lampe allumée");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Spectateur : réglage brouillard/lampe impossible : " + (ex.InnerException?.Message ?? ex.Message)));
			}
		}

		private static void AfterRevive()
		{
			_appliedThisDeath = false;
			_mobIndex = -1;
			ClearMobText();
		}

		private static bool LeftTrigger(object __instance)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PlayerControllerB local = Local;
				if ((Object)(object)local == (Object)null || !local.isPlayerDead || SpectateMenuOpen())
				{
					return true;
				}
				List<EnemyAI> list = SpectatableMobs();
				if (list.Count == 0)
				{
					SetMobText("Aucun mob à regarder");
					return false;
				}
				_mobIndex = (_mobIndex + 1) % list.Count;
				EnemyAI val = list[_mobIndex];
				object? obj = _spectatedPlayer?.GetValue(__instance);
				PlayerControllerB val2 = (PlayerControllerB)((obj is PlayerControllerB) ? obj : null);
				if (val2 != null && (Object)(object)val2 != (Object)null)
				{
					_stopSpectating?.Invoke(__instance, null);
				}
				Vector3 val3 = ViewpointNear(val);
				_teleport.Invoke(__instance, new object[4]
				{
					val3,
					!val.isOutside,
					false,
					false
				});
				SetMobText($"Mob : {MobName(val)}  ({_mobIndex + 1}/{list.Count})");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Spectateur : mob suivant impossible : " + (ex.InnerException?.Message ?? ex.Message)));
			}
			return false;
		}

		private static void RightTrigger()
		{
			ClearMobText();
		}

		private static List<EnemyAI> SpectatableMobs()
		{
			List<EnemyAI> list = new List<EnemyAI>();
			RoundManager instance = RoundManager.Instance;
			if ((Object)(object)instance == (Object)null || instance.SpawnedEnemies == null)
			{
				return list;
			}
			Dictionary<string, bool> dictionary = SpectateEnemyConfig();
			foreach (EnemyAI spawnedEnemy in instance.SpawnedEnemies)
			{
				if (!((Object)(object)spawnedEnemy == (Object)null) && !spawnedEnemy.isEnemyDead && !((Object)(object)spawnedEnemy.enemyType == (Object)null) && (dictionary == null || !dictionary.TryGetValue(spawnedEnemy.enemyType.enemyName ?? "", out var value) || value))
				{
					list.Add(spawnedEnemy);
				}
			}
			return list;
		}

		private static Dictionary<string, bool> SpectateEnemyConfig()
		{
			try
			{
				PluginInfo? obj = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo i) => i.Metadata.GUID == "SpectateEnemy"));
				object obj2;
				if (obj == null)
				{
					obj2 = null;
				}
				else
				{
					BaseUnityPlugin instance = obj.Instance;
					obj2 = ((instance != null) ? instance.Config : null);
				}
				ConfigFile val = (ConfigFile)obj2;
				if (val == null)
				{
					return null;
				}
				Dictionary<string, bool> dictionary = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
				foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in val)
				{
					if (item.Key.Section == "Enemies" && item.Value.BoxedValue is bool value)
					{
						dictionary[item.Key.Key] = value;
					}
				}
				return dictionary;
			}
			catch
			{
				return null;
			}
		}

		private static Vector3 ViewpointNear(EnemyAI mob)
		{
			//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_000e: 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_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = ((Component)mob).transform;
			Vector3 position = transform.position;
			Vector3 val = position - transform.forward * 2.5f + Vector3.up * 0.3f;
			int num = (((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.collidersAndRoomMaskAndDefault : (-5));
			if (!Physics.Linecast(position + Vector3.up, val + Vector3.up, num, (QueryTriggerInteraction)1))
			{
				return val;
			}
			return position + Vector3.up * 0.2f;
		}

		private static string MobName(EnemyAI mob)
		{
			try
			{
				string text = mob.enemyType?.enemyName;
				ScanNodeProperties componentInChildren = ((Component)mob).GetComponentInChildren<ScanNodeProperties>();
				if ((Object)(object)componentInChildren != (Object)null && !string.IsNullOrEmpty(componentInChildren.headerText))
				{
					return componentInChildren.headerText;
				}
				return string.IsNullOrEmpty(text) ? ((Object)mob).name : text;
			}
			catch
			{
				return "?";
			}
		}

		private static bool SpectateMenuOpen()
		{
			try
			{
				Type type = AccessTools.TypeByName("LCVR.Managers.VRSession");
				object obj = ((type == null) ? null : AccessTools.Property(type, "Instance")?.GetValue(null));
				object obj2 = ((obj == null) ? null : AccessTools.Property(obj.GetType(), "HUD")?.GetValue(obj));
				object obj3 = ((obj2 == null) ? null : AccessTools.Property(obj2.GetType(), "SpectatingMenu")?.GetValue(obj2));
				bool flag = default(bool);
				int num;
				if (obj3 != null)
				{
					object obj4 = AccessTools.Property(obj3.GetType(), "IsOpen")?.GetValue(obj3);
					if (obj4 is bool)
					{
						flag = (bool)obj4;
						num = 1;
					}
					else
					{
						num = 0;
					}
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
			catch
			{
				return false;
			}
		}

		private static void SetMobText(string s)
		{
			HUDManager instance = HUDManager.Instance;
			if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance.spectatingPlayerText == (Object)null))
			{
				((TMP_Text)instance.spectatingPlayerText).text = s;
				_showingMobText = true;
			}
		}

		private static void ClearMobText()
		{
			if (_showingMobText)
			{
				_showingMobText = false;
				HUDManager instance = HUDManager.Instance;
				if ((Object)(object)instance != (Object)null && (Object)(object)instance.spectatingPlayerText != (Object)null)
				{
					((TMP_Text)instance.spectatingPlayerText).text = "";
				}
			}
		}
	}
	internal class TerminalPanel : MonoBehaviour
	{
		private enum Tab
		{
			Lunes,
			Magasin,
			Codes,
			Radar,
			Messages,
			Infos,
			Vente
		}

		private class RayBackup
		{
			public Component Ray;

			public Component Visual;

			public PropertyInfo Mask;

			public PropertyInfo Grad;

			public object OldMask;

			public object OldGrad;
		}

		private class Entry
		{
			public string Label;

			public Action Click;

			public Color Color = BtnCol;
		}

		private class PooledButton
		{
			public RectTransform Rt;

			public Button B;

			public TextMeshProUGUI Lbl;

			public PanelClick Click;
		}

		private const float W = 760f;

		private const float H = 1000f;

		private const float Pad = 10f;

		private const float HeaderY = 8f;

		private const float TabsY = 64f;

		private const float ToolY = 128f;

		private const float GridY = 192f;

		private const float FootY1 = 826f;

		private const float FootY2 = 890f;

		private const float StatusY = 952f;

		private const float RowH = 56f;

		private const float Gap = 6f;

		private const int Cols = 2;

		private const int Rows = 10;

		private const int PerPage = 20;

		private static readonly Color BgCol = new Color(0.01f, 0.06f, 0.02f, 0.94f);

		private static readonly Color BtnCol = new Color(0.04f, 0.22f, 0.07f, 1f);

		private static readonly Color BtnOnCol = new Color(0.1f, 0.5f, 0.16f, 1f);

		private static readonly Color BtnWarnCol = new Color(0.55f, 0.32f, 0.02f, 1f);

		private static readonly Color BtnDimCol = new Color(0.05f, 0.1f, 0.06f, 1f);

		private static readonly Color BtnRedCol = new Color(0.45f, 0.06f, 0.05f, 1f);

		private static readonly Color TextCol = new Color(0.62f, 1f, 0.62f, 1f);

		internal static TerminalPanel Instance;

		private Terminal _terminal;

		private Canvas _canvas;

		private RectTransform _root;

		private RectTransform _dynamic;

		private TMP_FontAsset _font;

		private TextMeshProUGUI _header;

		private TextMeshProUGUI _status;

		private bool _visible;

		private bool _refreshQueued;

		private Tab _tab;

		private readonly Dictionary<string, int> _pages = new Dictionary<string, int>();

		private int _shopSub;

		private int _infoSub;

		private int _qty = 1;

		private string _lastSent = "";

		private static readonly List<RayBackup> _rays = new List<RayBackup>();

		private RectTransform _kb;

		private float _lastClickTime;

		private static readonly HashSet<string> SeenPointers = new HashSet<string>();

		private string _pendingBuyWord;

		private bool _batching;

		private readonly List<TextMeshProUGUI> _lblPool = new List<TextMeshProUGUI>();

		private int _lblUsed;

		private readonly List<PooledButton> _btnPool = new List<PooledButton>();

		private int _btnUsed;

		private static PlayerControllerB Local
		{
			get
			{
				try
				{
					return ((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null;
				}
				catch
				{
					return null;
				}
			}
		}

		internal static void OnTerminalOpened(Terminal t)
		{
			if (Plugin.PanelEnabled.Value && !((Object)(object)t == (Object)null))
			{
				Plugin.Runner.StartCoroutine(OpenNextFrame(t));
			}
		}

		private static IEnumerator OpenNextFrame(Terminal t)
		{
			yield return null;
			if ((Object)(object)t == (Object)null || (Object)(object)Local == (Object)null)
			{
				yield break;
			}
			if ((Object)(object)Instance == (Object)null || (Object)(object)Instance._terminal != (Object)(object)t)
			{
				if ((Object)(object)Instance != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)Instance).gameObject);
				}
				Instance = Create(t);
				if ((Object)(object)Instance == (Object)null)
				{
					yield break;
				}
			}
			Instance.Show();
		}

		internal static void CloseAll()
		{
			if ((Object)(object)Instance != (Object)null)
			{
				Instance.Hide();
			}
		}

		private void Show()
		{
			DisableSpectatorRay();
			Place();
			_visible = true;
			((Component)this).gameObject.SetActive(true);
			TuneUiRays(on: true, ((Component)this).gameObject.layer, ((Object)(object)_kb != (Object)null) ? ((Component)_kb).gameObject.layer : ((Component)this).gameObject.layer);
			Refresh();
		}

		private void Hide()
		{
			_visible = false;
			_refreshQueued = false;
			_batching = false;
			((MonoBehaviour)this).StopAllCoroutines();
			TuneUiRays(on: false, 0, 0);
			if ((Object)(object)this != (Object)null && (Object)(object)((Component)this).gameObject != (Object)null)
			{
				((Component)this).gameObject.SetActive(false);
			}
		}

		private static void TuneUiRays(bool on, int panelLayer, int kbLayer)
		{
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!on)
				{
					foreach (RayBackup ray in _rays)
					{
						if ((Object)(object)ray.Ray != (Object)null && ray.Mask != null)
						{
							ray.Mask.SetValue(ray.Ray, ray.OldMask);
						}
						if ((Object)(object)ray.Visual != (Object)null && ray.Grad != null)
						{
							ray.Grad.SetValue(ray.Visual, ray.OldGrad);
						}
					}
					_rays.Clear();
				}
				else
				{
					if (_rays.Count > 0)
					{
						return;
					}
					LayerMask val = LayerMask.op_Implicit((1 << panelLayer) | (1 << kbLayer));
					string[] array = new string[2] { "Left Ray Interactor", "Right Ray Interactor" };
					for (int i = 0; i < array.Length; i++)
					{
						GameObject val2 = GameObject.Find(array[i]);
						if ((Object)(object)val2 == (Object)null)
						{
							continue;
						}
						RayBackup rayBackup = new RayBackup();
						Component[] components = val2.GetComponents<Component>();
						foreach (Component val3 in components)
						{
							string name = ((object)val3).GetType().Name;
							if (name == "XRRayInteractor")
							{
								rayBackup.Ray = val3;
								rayBackup.Mask = AccessTools.Property(((object)val3).GetType(), "raycastMask");
							}
							else if (name == "XRInteractorLineVisual")
							{
								rayBackup.Visual = val3;
								rayBackup.Grad = AccessTools.Property(((object)val3).GetType(), "invalidColorGradient");
							}
						}
						if ((Object)(object)rayBackup.Ray != (Object)null && rayBackup.Mask != null && rayBackup.Mask.PropertyType == typeof(LayerMask))
						{
							rayBackup.OldMask = rayBackup.Mask.GetValue(rayBackup.Ray);
							rayBackup.Mask.SetValue(rayBackup.Ray, val);
						}
						else
						{
							rayBackup.Mask = null;
						}
						if ((Object)(object)rayBackup.Visual != (Object)null && rayBackup.Grad != null && rayBackup.Grad.PropertyType == typeof(Gradient))
						{
							rayBackup.OldGrad = rayBackup.Grad.GetValue(rayBackup.Visual);
							rayBackup.Grad.SetValue(rayBackup.Visual, VisibleRay());
						}
						else
						{
							rayBackup.Grad = null;
						}
						_rays.Add(rayBackup);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Panneau : réglage des rayons de visée : " + ex.Message));
			}
		}

		private static Gradient VisibleRay()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_0020: 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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			Gradient val = new Gradient();
			val.mode = (GradientMode)0;
			val.alphaKeys = (GradientAlphaKey[])(object)new GradientAlphaKey[2]
			{
				new GradientAlphaKey(0.6f, 0f),
				new GradientAlphaKey(0.25f, 1f)
			};
			val.colorKeys = (GradientColorKey[])(object)new GradientColorKey[2]
			{
				new GradientColorKey(Color.white, 0f),
				new GradientColorKey(Color.white, 1f)
			};
			return val;
		}

		private void OnDestroy()
		{
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private static TerminalPanel Create(Terminal t)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Expected O, but got Unknown
			try
			{
				Type type = AccessTools.TypeByName("UnityEngine.XR.Interaction.Toolkit.UI.TrackedDeviceGraphicRaycaster");
				Component val = FindLcvrKeyboard(t);
				if (type == null || (Object)(object)val == (Object)null)
				{
					Plugin.Log.LogInfo((object)"Panneau terminal : pas de VR active (clavier LCVR introuvable), panneau désactivé pour cette partie.");
					return null;
				}
				GameObject val2 = new GameObject("TrucTweaks.TerminalPanel", new Type[1] { typeof(RectTransform) });
				val2.transform.SetParent(val.transform.parent, false);
				val2.layer = val.gameObject.layer;
				TerminalPanel terminalPanel = val2.AddComponent<TerminalPanel>();
				terminalPanel._terminal = t;
				terminalPanel._root = (RectTransform)val2.transform;
				terminalPanel._root.sizeDelta = new Vector2(760f, 1000f);
				terminalPanel._root.pivot = new Vector2(0.5f, 0.5f);
				terminalPanel._canvas = val2.AddComponent<Canvas>();
				terminalPanel._canvas.renderMode = (RenderMode)2;
				Canvas componentInParent = val.GetComponentInParent<Canvas>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					terminalPanel._canvas.worldCamera = componentInParent.worldCamera;
					terminalPanel._canvas.sortingOrder = componentInParent.sortingOrder + 1;
				}
				val2.AddComponent(type);
				TMP_FontAsset val3 = (((Object)(object)t.inputFieldText != (Object)null) ? ((TMP_Text)t.inputFieldText).font : null);
				terminalPanel._font = (((Object)(object)val3 != (Object)null && val3.HasCharacters("éèàçê$")) ? val3 : (TMP_Settings.defaultFontAsset ?? val3));
				terminalPanel.BuildStatic();
				terminalPanel._kb = (RectTransform)val.transform;
				val2.SetActive(false);
				return terminalPanel;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Panneau terminal : création impossible : " + ex));
				return null;
			}
		}

		private static Component FindLcvrKeyboard(Terminal t)
		{
			Component[] componentsInChildren = ((Component)(((Object)(object)((Component)t).transform.parent != (Object)null && (Object)(object)((Component)t).transform.parent.parent != (Object)null) ? ((Component)t).transform.parent.parent : ((Component)t).transform.root)).GetComponentsInChildren<Component>(true);
			foreach (Component val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && ((object)val).GetType().Name == "NonNativeKeyboard" && val.transform is RectTransform)
				{
					return val;
				}
			}
			return null;
		}

		private void Place()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: 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_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: 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_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_kb == (Object)null))
			{
				((Component)this).transform.localScale = Vector3.one * Plugin.PanelScale.Value;
				Vector3[] array = (Vector3[])(object)new Vector3[4];
				_kb.GetWorldCorners(array);
				Vector3 val = array[3] - array[0];
				if (((Vector3)(ref val)).sqrMagnitude < 1E-06f)
				{
					val = ((Transform)_kb).right;
				}
				((Vector3)(ref val)).Normalize();
				Vector3 val2 = array[1] - array[0];
				if (((Vector3)(ref val2)).sqrMagnitude < 1E-06f)
				{
					val2 = ((Transform)_kb).up;
				}
				((Vector3)(ref val2)).Normalize();
				Vector3 val3 = Vector3.Cross(val, val2);
				Vector3 normalized = ((Vector3)(ref val3)).normalized;
				float x = ((Component)this).transform.lossyScale.x;
				float num = 760f * x;
				float num2 = 1000f * x;
				bool flag = !string.Equals(Plugin.PanelSide.Value, "Left", StringComparison.OrdinalIgnoreCase);
				float num3 = 0.03f;
				Vector3 val4 = (flag ? array[3] : array[0]) + (flag ? 1f : (-1f)) * val * (num3 + num / 2f) + val2 * (num2 / 2f);
				val4 += val * Plugin.PanelOffsetX.Value + val2 * Plugin.PanelOffsetY.Value + normalized * Plugin.PanelOffsetZ.Value;
				((Component)this).transform.position = val4;
				((Component)this).transform.rotation = ((Transform)_kb).rotation;
				if (Mathf.Abs(Plugin.PanelYaw.Value) > 0.01f)
				{
					((Component)this).transform.RotateAround(flag ? (val4 - val * num / 2f) : (val4 + val * num / 2f), val2, flag ? Plugin.PanelYaw.Value : (0f - Plugin.PanelYaw.Value));
				}
			}
		}

		private void BuildStatic()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			Image obj = ((Component)Rect("Fond", (Transform)(object)_root, 0f, 0f, 760f, 1000f)).gameObject.AddComponent<Image>();
			((Graphic)obj).color = BgCol;
			((Graphic)obj).raycastTarget = true;
			_header = Label((Transform)(object)_root, 10f, 8f, 740f, 48f, "", 26f, (TextAlignmentOptions)513);
			_status = Label((Transform)(object)_root, 10f, 952f, 740f, 40f, "", 20f, (TextAlignmentOptions)513);
			_dynamic = Rect("Contenu", (Transform)(object)_root, 0f, 0f, 760f, 1000f);
		}

		internal static void NotifyTerminalChanged()
		{
			if ((Object)(object)Instance != (Object)null && Instance._visible && !Instance._batching)
			{
				Instance.Refresh();
			}
		}

		private void RefreshSoon(float delay = 0.4f)
		{
			if (_visible && !_refreshQueued)
			{
				_refreshQueued = true;
				((MonoBehaviour)this).StartCoroutine(RefreshLater(delay));
			}
		}

		private IEnumerator RefreshLater(float delay)
		{
			yield return (object)new WaitForSecondsRealtime(delay);
			_refreshQueued = false;
			if (_visible)
			{
				Refresh();
			}
		}

		private void Refresh()
		{
			if (!_visible || (Object)(object)_terminal == (Object)null)
			{
				return;
			}
			try
			{
				_btnUsed = 0;
				_lblUsed = 0;
				((TMP_Text)_header).text = HeaderText();
				((TMP_Text)_status).text = ((_lastSent.Length > 0) ? ("> " + _lastSent) : "Vise un bouton et appuie sur la gâchette.");
				if (Itapi.IsActive)
				{
					BuildItapiPad();
					BuildFooter(paging: false);
				}
				else
				{
					BuildTabs();
					switch (_tab)
					{
					case Tab.Lunes:
						BuildMoons();
						break;
					case Tab.Magasin:
						BuildShop();
						break;
					case Tab.Codes:
						BuildCodes();
						break;
					case Tab.Radar:
						BuildRadar();
						break;
					case Tab.Messages:
						BuildMessages();
						break;
					case Tab.Infos:
						BuildInfos();
						break;
					case Tab.Vente:
						BuildSell();
						break;
					}
				}
				for (int i = _btnUsed; i < _btnPool.Count; i++)
				{
					if (((Component)_btnPool[i].Rt).gameObject.activeSelf)
					{
						((Component)_btnPool[i].Rt).gameObject.SetActive(false);
					}
				}
				for (int j = _lblUsed; j < _lblPool.Count; j++)
				{
					if (((Component)_lblPool[j]).gameObject.activeSelf)
					{
						((Component)_lblPool[j]).gameObject.SetActive(false);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Panneau terminal : erreur d'affichage : " + ex));
			}
		}

		internal bool AcceptClick(PointerEventData e)
		{
			string text = PointerName(e);
			if (SeenPointers.Add(text))
			{
				SessionLog.Write($"PAN  {DateTime.Now:HH:mm:ss}  clic reçu de : {text}");
			}
			if (text.IndexOf("Spectator", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return false;
			}
			if (Time.unscaledTime - _lastClickTime < 0.25f)
			{
				return false;
			}
			_lastClickTime = Time.unscaledTime;
			return true;
		}

		private static string PointerName(PointerEventData e)
		{
			try
			{
				object? obj = (((object)e)?.GetType().GetProperty("interactor"))?.GetValue(e);
				Component val = (Component)((obj is Component) ? obj : null);
				if (val != null)
				{
					return ((object)val).GetType().Name + " / " + ((Object)val.gameObject).name;
				}
				return ((object)e)?.GetType().Name ?? "?";
			}
			catch
			{
				return "?";
			}
		}

		private static void DisableSpectatorRay()
		{
			try
			{
				PlayerControllerB local = Local;
				if ((Object)(object)local == (Object)null || local.isPlayerDead)
				{
					return;
				}
				GameObject val = GameObject.Find("Spectator Ray Interactor");
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				Behaviour[] components = val.GetComponents<Behaviour>();
				foreach (Behaviour val2 in components)
				{
					string name = ((object)val2).GetType().Name;
					if (val2.enabled && (name == "XRRayInteractor" || name == "XRInteractorLineVisual"))
					{
						val2.enabled = false;
						SessionLog.Write($"PAN  {DateTime.Now:HH:mm:ss}  rayon spectateur LCVR actif alors qu'on est vivant : coupé ({name})");
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Panneau : rayon spectateur : " + ex.Message));
			}
		}

		private string HeaderText()
		{
			StartOfRound instance = StartOfRound.Instance;
			string arg = (((Object)(object)instance == (Object)null) ? "" : (instance.inShipPhase ? "En orbite" : (((Object)(object)instance.currentLevel != (Object)null) ? (instance.currentLevel.PlanetName + (instance.shipHasLanded ? " (posé)" : "")) : "")));
			string arg2 = "";
			TimeOfDay instance2 = TimeOfDay.Instance;
			if ((Object)(object)instance2 != (Object)null)
			{
				arg2 = $"  ·  Quota {instance2.quotaFulfilled}/{instance2.profitQuota}  ·  J-{Mathf.Max(0, instance2.daysUntilDeadline)}";
			}
			return $"<b>{_terminal.groupCredits} $</b>  ·  {arg}{arg2}";
		}

		private void BuildTabs()
		{
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			List<(Tab, string)> list = new List<(Tab, string)>
			{
				(Tab.Lunes, "LUNES"),
				(Tab.Magasin, "SHOP"),
				(Tab.Codes, "CODES"),
				(Tab.Radar, "RADAR"),
				(Tab.Messages, "MSG"),
				(Tab.Infos, "INFOS"),
				(Tab.Vente, "VENTE")
			};
			float num = (740f - (float)(list.Count - 1) * 6f) / (float)list.Count;
			for (int i = 0; i < list.Count; i++)
			{
				var (tab, text) = list[i];
				Button((Transform)(object)_dynamic, 10f + (float)i * (num + 6f), 64f, num, 56f, text, 22f, (tab == _tab) ? BtnOnCol : BtnCol, delegate
				{
					_tab = tab;
					Refresh();
				}, (TextAlignmentOptions)514);
			}
		}

		private void BuildGrid(string key, List<Entry> entries, string emptyText, int rows = 10)
		{
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			int num = 2 * rows;
			if (entries.Count == 0)
			{
				Label((Transform)(object)_dynamic, 10f, 202f, 740f, 200f, emptyText, 24f, (TextAlignmentOptions)257);
				BuildFooter(paging: false);
				return;
			}
			int num2 = Mathf.Max(1, Mathf.CeilToInt((float)entries.Count / (float)num));
			_pages.TryGetValue(key, out var value);
			value = Mathf.Clamp(value, 0, num2 - 1);
			_pages[key] = value;
			float num3 = 367f;
			for (int i = 0; i < num; i++)
			{
				int num4 = value * num + i;
				if (num4 >= entries.Count)
				{
					break;
				}
				Entry entry = entries[num4];
				int num5 = i / rows;
				int num6 = i % rows;
				Button((Transform)(object)_dynamic, 10f + (float)num5 * (num3 + 6f), 192f + (float)num6 * 62f, num3, 56f, entry.Label, 21f, entry.Color, entry.Click, (TextAlignmentOptions)513);
			}
			BuildFooter(num2 > 1, key, value, num2);
		}

		private void BuildFooter(bool paging, string key = null, int page = 0, int pages = 1)
		{
			//IL_015f: 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_0060: 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_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			float num = 242.66667f;
			if (paging)
			{
				Button((Transform)(object)_dynamic, 10f, 826f, num, 56f, "<< page", 22f, (page > 0) ? BtnCol : BtnDimCol, delegate
				{
					if (page > 0)
					{
						_pages[key] = page - 1;
						Refresh();
					}
				}, (TextAlignmentOptions)514);
				Label((Transform)(object)_dynamic, 10f + num + 6f, 826f, num, 56f, $"{page + 1} / {pages}", 24f, (TextAlignmentOptions)514);
				Button((Transform)(object)_dynamic, 10f + 2f * (num + 6f), 826f, num, 56f, "page >>", 22f, (page < pages - 1) ? BtnCol : BtnDimCol, delegate
				{
					if (page < pages - 1)
					{
						_pages[key] = page + 1;
						Refresh();
					}
				}, (TextAlignmentOptions)514);
			}
			bool flag = TerminalWaitsForConfirm();
			Button((Transform)(object)_dynamic, 10f, 890f, num, 56f, "CONFIRMER", 24f, flag ? BtnWarnCol : BtnCol, delegate
			{
				Send("confirm");
			}, (TextAlignmentOptions)514);
			Button((Transform)(object)_dynamic, 10f + num + 6f, 890f, num, 56f, "ANNULER", 24f, BtnCol, delegate
			{
				Send("deny");
			}, (TextAlignmentOptions)514);
			Button((Transform)(object)_dynamic, 10f + 2f * (num + 6f), 890f, num, 56f, "FERMER X", 24f, BtnRedCol, CloseTerminal, (TextAlignmentOptions)514);
		}

		private void Toolbar(params (string label, Color color, Action click)[] items)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			if (items.Length == 0)
			{
				return;
			}
			float num = (740f - (float)(items.Length - 1) * 6f) / (float)items.Length;
			for (int i = 0; i < items.Length; i++)
			{
				(string, Color, Action) tuple = items[i];
				if (tuple.Item3 == null)
				{
					Label((Transform)(object)_dynamic, 10f + (float)i * (num + 6f), 128f, num, 56f, tuple.Item1, 22f, (TextAlignmentOptions)514);
				}
				else
				{
					Button((Transform)(object)_dynamic, 10f + (float)i * (num + 6f), 128f, num, 56f, tuple.Item1, 21f, tuple.Item2, tuple.Item3, (TextAlignmentOptions)514);
				}
			}
		}

		private bool TerminalWaitsForConfirm()
		{
			TerminalNode currentNode = _terminal.currentNode;
			if ((Object)(object)currentNode == (Object)null)
			{
				return false;
			}
			if (currentNode.isConfirmationNode)
			{
				return true;
			}
			if (currentNode.terminalOptions != null)
			{
				return currentNode.terminalOptions.Any((CompatibleNoun o) => (Object)(object)o?.noun != (Object)null && o.noun.word == "confirm");
			}
			return false;
		}

		private void BuildMoons()
		{
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: 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_0138: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			List<Catalog.Moon> list = Catalog.Moons(_terminal);
			List<Entry> list2 = new List<Entry>();
			foreach (Catalog.Moon item in list)
			{
				if (!item.Hidden || Plugin.PanelShowHiddenMoons.Value)
				{
					bool flag = (Object)(object)instance != (Object)null && (Object)(object)instance.currentLevel == (Object)(object)item.Level;
					string text = Weather(item.Level);
					string label = string.Format("{0}{1}{2}  <color=#ffd35a>{3}$</color>{4}", flag ? "> " : "", item.Hidden ? "* " : "", item.Level.PlanetName, item.Cost, (text.Length > 0) ? ("  <color=#ff9a6a>" + text + "</color>") : "");
					string word = item.Word;
					list2.Add(new Entry
					{
						Label = label,
						Click = delegate
						{
							Send("route " + word);
						},
						Color = (flag ? BtnOnCol : BtnCol)
					});
				}
			}
			Toolbar((((Object)(object)instance != (Object)null && instance.inShipPhase) ? "Choisis la lune puis CONFIRMER" : "Route possible seulement en orbite", BtnCol, null));
			BuildGrid("moons", list2, "Aucune lune trouvée dans le terminal.");
		}

		private static string Weather(SelectableLevel l)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected I4, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			switch ((int)l.currentWeather)
			{
			case 0:
				return "Poussière";
			case 1:
				return "Pluie";
			case 2:
				return "Orage";
			case 3:
				return "Brouillard";
			case 4:
				return "Inondé";
			case 5:
				return "Éclipse";
			default:
				if ((int)l.currentWeather >= 0)
				{
					return ((object)Unsafe.As<LevelWeatherType, LevelWeatherType>(ref l.currentWeather)/*cast due to .constrained prefix*/).ToString();
				}
				return "";
			}
		}

		private void BuildShop()
		{
			//IL_0072: 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)
			string[] array = new string[4] { "Objets", "Amélio.", "Déco", "Véhicules" };
			List<(string, Color, Action)> list = new List<(string, Color, Action)>();
			for (int i = 0; i < array.Length; i++)
			{
				int k = i;
				list.Add((array[i], (k == _shopSub) ? BtnOnCol : BtnCol, delegate
				{
					_shopSub = k;
					Refresh();
				}));
			}
			Toolbar(list.ToArray());
			List<Entry> list2 = new List<Entry>();
			List<Catalog.ShopEntry> source = Catalog.Shop(_terminal);
			if (_shopSub == 0)
			{
				foreach (Catalog.ShopEntry item in source.Where((Catalog.ShopEntry s) => s.Kind == ShopKind.Item))
				{
					string word = item.Word;
					string arg = ((item.SalePercent > 0) ? $"  <color=#7fd7ff>-{item.SalePercent}%</color>" : "");
					list2.Add(new Entry
					{
						Label = $"{item.Name}  <color=#ffd35a>{item.Price}$</color>{arg}",
						Click = delegate
						{
							Send($"buy {word} {_qty}");
							_pendingBuyWord = word;
						}
					});
				}
				BuildGrid("shop0", list2, "Aucun objet en vente.", 9);
				QuantityRow();
				return;
			}
			ShopKind kind = ((_shopSub == 1) ? ShopKind.Upgrade : ((_shopSub == 2) ? ShopKind.Decor : ShopKind.Vehicle));
			foreach (Catalog.ShopEntry item2 in source.Where((Catalog.ShopEntry s) => s.Kind == kind))
			{
				string word2 = item2.Word;
				list2.Add(new Entry
				{
					Label = $"{item2.Name}  <color=#ffd35a>{item2.Price}$</color>",
					Click = delegate
					{
						Send("buy " + word2);
					}
				});
			}
			BuildGrid("shop" + _shopSub, list2, (kind == ShopKind.Decor) ? "Rien en déco cette semaine (ou tout est déjà acheté)." : "Rien à acheter ici (déjà tout acheté ?).");
		}

		private void QuantityRow()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			float y = 750f;
			float num = 143.2f;
			Label((Transform)(object)_dynamic, 10f, y, num * 2f + 6f, 56f, "Quantité :", 24f, (TextAlignmentOptions)516);
			Button((Transform)(object)_dynamic, 10f + 2f * (num + 6f), y, num, 56f, "-", 30f, BtnCol, delegate
			{
				SetQuantity(_qty - 1);
			}, (TextAlignmentOptions)514);
			Label((Transform)(object)_dynamic, 10f + 3f * (num + 6f), y, num, 56f, _qty.ToString(), 30f, (TextAlignmentOptions)514);
			Button((Transform)(object)_dynamic, 10f + 4f * (num + 6f), y, num, 56f, "+", 30f, BtnCol, delegate
			{
				SetQuantity(_qty + 1);
			}, (TextAlignmentOptions)514);
		}

		private void SetQuantity(int q)
		{
			_qty = Mathf.Clamp(q, 1, 24);
			string pendingBuyWord = _pendingBuyWord;
			if (pendingBuyWord != null && TerminalWaitsForConfirm())
			{
				Send("deny", refresh: false);
				Send($"buy {pendingBuyWord} {_qty}");
				_pendingBuyWord = pendingBuyWord;
				Click($"buy {pendingBuyWord} {_qty} : CONFIRMER pour valider");
			}
			else
			{
				Refresh();
			}
		}

		private void BuildCodes()
		{
			//IL_00d8: 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_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			Transform val = null;
			string text = "toi";
			try
			{
				ManualCameraRenderer val2 = instance?.mapScreen;
				if ((Object)(object)val2 != (Object)null && val2.radarTargets != null && val2.targetTransformIndex >= 0 && val2.targetTransformIndex < val2.radarTargets.Count)
				{
					val = val2.radarTargets[val2.targetTransformIndex].transform;
					text = val2.radarTargets[val2.targetTransformIndex].name;
				}
			}
			catch
			{
			}
			if ((Object)(object)val == (Object)null && (Object)(object)Local != (Object)null)
			{
				val = ((Component)Local).transform;
			}
			List<Catalog.CodeEntry> codes = Catalog.Codes(val);
			Toolbar(("Près de " + text + "  >>", BtnOnCol, delegate
			{
				ManualCameraRenderer val3 = StartOfRound.Instance?.mapScreen;
				if (!((Object)(object)val3 == (Object)null))
				{
					val3.SwitchRadarTargetForward(true);
					Click("cible radar suivante");
					RefreshSoon(0.3f);
				}
			}), ("Actualiser", BtnCol, delegate
			{
				Refresh();
			}), ("Tourelles OFF", BtnWarnCol, delegate
			{
				SendMany(from c in codes
					where c.Type == "Tourelle"
					select c.Code);
			}), ("Mines OFF", BtnWarnCol, delegate
			{
				SendMany(from c in codes
					where c.Type == "Mine"
					select c.Code);
			}));
			List<Entry> entries = codes.Select((Catalog.CodeEntry c) => new Entry
			{
				Label = $"<b>{c.Code.ToUpperInvariant()}</b>  {c.Type}  <color=#ffd35a>{c.Distance:0} m</color>  {c.State}",
				Color = ((c.Type == "Porte") ? BtnCol : (BtnWarnCol * 0.8f + BtnCol * 0.2f)),
				Click = delegate
				{
					Send(c.Code);
					RefreshSoon(0.6f);
				}
			}).ToList();
			BuildGrid("codes", entries, "Aucun code : il faut être posé sur une lune avec des portes ou des pièges.");
		}

		private void BuildRadar()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			ManualCameraRenderer map = StartOfRound.Instance?.mapScreen;
			Toolbar(("Carte sur l'écran", BtnCol, delegate
			{
				Send("view monitor");
			}), ("Cible suivante", BtnCol, delegate
			{
				Send("switch");
			}));
			List<Entry> list = new List<Entry>();
			if ((Object)(object)map != (Object)null && map.radarTargets != null)
			{
				for (int num = 0; num < map.radarTargets.Count; num++)
				{
					TransformAndName rt = map.radarTargets[num];
					if (rt == null || (Object)(object)rt.transform == (Object)null)
					{
						continue;
					}
					int idx = num;
					bool flag = idx == map.targetTransformIndex;
					if (!rt.isNonPlayer)
					{
						PlayerControllerB component = ((Component)rt.transform).GetComponent<PlayerControllerB>();
						if (!((Object)(object)component != (Object)null) || component.isPlayerControlled || component.isPlayerDead)
						{
							string text = (((Object)(object)component != (Object)null && component.isPlayerDead) ? "  <color=#ff6a6a>(mort)</color>" : "");
							list.Add(new Entry
							{
								Label = (flag ? "> " : "") + "Suivre " + rt.name + text,
								Color = (flag ? BtnOnCol : BtnCol),
								Click = delegate
								{
									map.SwitchRadarTargetAndSync(idx);
									Click("suivre " + rt.name);
									RefreshSoon();
								}
							});
						}
						continue;
					}
					list.Add(new Entry
					{
						Label = (flag ? "> " : "") + "Booster " + rt.name,
						Color = (flag ? BtnOnCol : BtnCol),
						Click = delegate
						{
							map.SwitchRadarTargetAndSync(idx);
							Click("suivre booster " + rt.name);
							RefreshSoon();
						}
					});
					list.Add(new Entry
					{
						Label = "   PING " + rt.name,
						Click = delegate
						{
							map.PingRadarBooster(idx);
							Click("ping " + rt.name);
						}
					});
					list.Add(new Entry
					{
						Label = "   FLASH " + rt.name,
						Color = BtnWarnCol,
						Click = delegate
						{
							map.FlashRadarBooster(idx);
							Click("flash " + rt.name);
						}
					});
				}
			}
			BuildGrid("radar", list, "Aucune cible radar.");
		}

		private void BuildMessages()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Object.FindObjectOfType<SignalTranslator>() != (Object)null))
			{
				Toolbar(("Signal translator pas acheté (SHOP > Amélio.)", BtnCol, null));
				BuildGrid("msg", new List<Entry>(), "Sans signal translator, les messages ne partent pas.");
				return;
			}
			Toolbar(("Message affiché à tous (10 lettres max)", BtnCol, null));
			List<Entry> entries = (from m in Plugin.PanelMessages.Value.Split(',')
				select m.Trim() into m
				where m.Length > 0
				select (m.Length <= 10) ? m : m.Substring(0, 10) into m
				select new Entry
				{
					Label = m,
					Click = delegate
					{
						Send("transmit " + m);
					}
				}).ToList();
			BuildGrid("msg", entries, "Aucun message prêt (config [Pane