Decompiled source of MimicMod v1.0.0

BepInEx/plugins/MimicMod/MimicMod.dll

Decompiled 43 minutes ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using Photon.Voice;
using Photon.Voice.Unity;
using RepoMimicMod.Mimic;
using RepoMimicMod.Network;
using RepoMimicMod.Prefab;
using RepoMimicMod.Reflection;
using RepoMimicMod.Voice;
using TMPro;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;
using UnityEngine.Rendering;
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("borsboomT")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("BepInEx 5 Mimic mod for R.E.P.O. that disguises monsters as players and selectively captures & replays voice chat snippets.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+3a341cf25c1456e42d5efc3759876dd8348970d1")]
[assembly: AssemblyProduct("MimicMod")]
[assembly: AssemblyTitle("MimicMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[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 RepoMimicMod
{
	public static class MimicConfig
	{
		public static ConfigEntry<bool> Enabled { get; private set; }

		public static ConfigEntry<int> DifficultyTier { get; private set; }

		public static ConfigEntry<bool> AlsoSpawnInAdjacentTiers { get; private set; }

		public static ConfigEntry<float> SpawnRarityChance { get; private set; }

		public static ConfigEntry<int> MinLevelsCompleted { get; private set; }

		public static ConfigEntry<bool> EnableDebugHotkeys { get; private set; }

		public static ConfigEntry<int> MimicHealth { get; private set; }

		public static ConfigEntry<float> WalkSpeed { get; private set; }

		public static ConfigEntry<float> SprintSpeed { get; private set; }

		public static ConfigEntry<float> CrouchSpeed { get; private set; }

		public static ConfigEntry<float> FollowDistanceMin { get; private set; }

		public static ConfigEntry<float> FollowDistanceMax { get; private set; }

		public static ConfigEntry<float> CrouchChance { get; private set; }

		public static ConfigEntry<bool> ShowFakeNameplate { get; private set; }

		public static ConfigEntry<float> UncannyGlitchIntensity { get; private set; }

		public static ConfigEntry<bool> EnableValuableSabotage { get; private set; }

		public static ConfigEntry<int> ValuableSabotageStrength { get; private set; }

		public static ConfigEntry<float> ValuableSabotageCooldownSeconds { get; private set; }

		public static ConfigEntry<float> UnobservedMinPlayerDistance { get; private set; }

		public static ConfigEntry<float> ValuableSearchRadius { get; private set; }

		public static ConfigEntry<bool> EnableHazardPush { get; private set; }

		public static ConfigEntry<float> HazardPushForce { get; private set; }

		public static ConfigEntry<float> HazardPushCooldownSeconds { get; private set; }

		public static ConfigEntry<bool> RequireBackTurnedForPush { get; private set; }

		public static ConfigEntry<bool> EnableVoiceCapture { get; private set; }

		public static ConfigEntry<bool> CaptureLocalVoice { get; private set; }

		public static ConfigEntry<bool> CaptureRemoteVoice { get; private set; }

		public static ConfigEntry<bool> CaptureTtsVoice { get; private set; }

		public static ConfigEntry<int> MaxSnippetsPerPlayer { get; private set; }

		public static ConfigEntry<float> MinSnippetSeconds { get; private set; }

		public static ConfigEntry<float> MaxSnippetSeconds { get; private set; }

		public static ConfigEntry<float> SpeechThresholdRms { get; private set; }

		public static ConfigEntry<float> MinVoiceIntervalSeconds { get; private set; }

		public static ConfigEntry<float> MaxVoiceIntervalSeconds { get; private set; }

		public static ConfigEntry<float> SubtleVoiceGlitchChance { get; private set; }

		public static ConfigEntry<bool> SyncVoiceOverNetwork { get; private set; }

		public static void Bind(ConfigFile config)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Expected O, but got Unknown
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Expected O, but got Unknown
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Expected O, but got Unknown
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Expected O, but got Unknown
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Expected O, but got Unknown
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Expected O, but got Unknown
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Expected O, but got Unknown
			//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Expected O, but got Unknown
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Expected O, but got Unknown
			//IL_0362: Unknown result type (might be due to invalid IL or missing references)
			//IL_036c: Expected O, but got Unknown
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a4: Expected O, but got Unknown
			//IL_03ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f7: Expected O, but got Unknown
			//IL_0425: Unknown result type (might be due to invalid IL or missing references)
			//IL_042f: Expected O, but got Unknown
			//IL_04da: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e4: Expected O, but got Unknown
			//IL_0512: Unknown result type (might be due to invalid IL or missing references)
			//IL_051c: Expected O, but got Unknown
			//IL_054a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0554: Expected O, but got Unknown
			//IL_0582: Unknown result type (might be due to invalid IL or missing references)
			//IL_058c: Expected O, but got Unknown
			//IL_05ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c4: Expected O, but got Unknown
			//IL_05f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fc: Expected O, but got Unknown
			//IL_062a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0634: Expected O, but got Unknown
			Enabled = config.Bind<bool>("Spawning", "Enabled", true, "Enable or disable Mimic enemies spawning in levels.");
			DifficultyTier = config.Bind<int>("Spawning", "DifficultyTier", 2, new ConfigDescription("Primary EnemyDirector difficulty pool (1 = Easy, 2 = Medium, 3 = Hard).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 3), Array.Empty<object>()));
			AlsoSpawnInAdjacentTiers = config.Bind<bool>("Spawning", "AlsoSpawnInAdjacentTiers", true, "Also register the Mimic in adjacent difficulty tiers so it can appear on early and late moons.");
			SpawnRarityChance = config.Bind<float>("Spawning", "SpawnRarityChance", 0.55f, new ConfigDescription("Rarity weight passed to R.E.P.O.'s EnemyDirector when picking enemies.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1f), Array.Empty<object>()));
			MinLevelsCompleted = config.Bind<int>("Spawning", "MinLevelsCompleted", 0, new ConfigDescription("Minimum levels completed before Mimics can spawn.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			EnableDebugHotkeys = config.Bind<bool>("Spawning", "EnableDebugHotkeys", false, "Enable F8 (spawn nearby Mimic), F9 (force nearby Mimic voice snippet), and F10 (log voice bank stats).");
			MimicHealth = config.Bind<int>("Behavior", "MimicHealth", 150, new ConfigDescription("Maximum health of a Mimic.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(50, 1000), Array.Empty<object>()));
			WalkSpeed = config.Bind<float>("Behavior", "WalkSpeed", 2.6f, new ConfigDescription("Fallback walk speed when PlayerController is unavailable; dynamically matches player MoveSpeed in-game.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1.2f, 6f), Array.Empty<object>()));
			SprintSpeed = config.Bind<float>("Behavior", "SprintSpeed", 5.4f, new ConfigDescription("Fallback sprint speed when PlayerController is unavailable; dynamically matches player SprintSpeed in-game.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2.5f, 10f), Array.Empty<object>()));
			CrouchSpeed = config.Bind<float>("Behavior", "CrouchSpeed", 1.35f, new ConfigDescription("Fallback crouch speed when PlayerController is unavailable; dynamically matches player CrouchSpeed in-game.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.6f, 4f), Array.Empty<object>()));
			FollowDistanceMin = config.Bind<float>("Behavior", "FollowDistanceMin", 3.2f, new ConfigDescription("Minimum comfortable distance the Mimic keeps from teammates while blending in.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1.5f, 10f), Array.Empty<object>()));
			FollowDistanceMax = config.Bind<float>("Behavior", "FollowDistanceMax", 8.5f, new ConfigDescription("Distance beyond which the Mimic jogs/sprints to rejoin nearby teammates.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 20f), Array.Empty<object>()));
			CrouchChance = config.Bind<float>("Behavior", "CrouchChance", 0f, new ConfigDescription("Legacy setting (superseded by automatic overhead-clearance crouching under low spaces).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			ShowFakeNameplate = config.Bind<bool>("Behavior", "ShowFakeNameplate", true, "Show a floating player nameplate above the Mimic when nearby.");
			UncannyGlitchIntensity = config.Bind<float>("Behavior", "UncannyGlitchIntensity", 0.08f, new ConfigDescription("Subtlety of uncanny micro-twitches in head tracking (kept very low so Mimics blend in).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			EnableValuableSabotage = config.Bind<bool>("Sabotage", "EnableValuableSabotage", true, "Allow Mimics to secretly break/damage valuables when no players can see them.");
			ValuableSabotageStrength = config.Bind<int>("Sabotage", "ValuableSabotageStrength", 2, new ConfigDescription("Severity of valuable sabotage hit (1 = Light, 2 = Medium, 3 = Heavy).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 3), Array.Empty<object>()));
			ValuableSabotageCooldownSeconds = config.Bind<float>("Sabotage", "ValuableSabotageCooldownSeconds", 14f, new ConfigDescription("Minimum seconds between valuable sabotage attempts.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(3f, 60f), Array.Empty<object>()));
			UnobservedMinPlayerDistance = config.Bind<float>("Sabotage", "UnobservedMinPlayerDistance", 4.5f, new ConfigDescription("Minimum distance from all living players before a Mimic dares to damage a valuable.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 15f), Array.Empty<object>()));
			ValuableSearchRadius = config.Bind<float>("Sabotage", "ValuableSearchRadius", 15f, new ConfigDescription("Search radius for nearby valuables to sabotage when unobserved.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 35f), Array.Empty<object>()));
			EnableHazardPush = config.Bind<bool>("Sabotage", "EnableHazardPush", true, "Allow Mimics to opportunistically shove a player toward nearby pits or traps (without direct HP damage).");
			HazardPushForce = config.Bind<float>("Sabotage", "HazardPushForce", 15f, new ConfigDescription("Impulse force applied to tumble-shove a player toward an environmental hazard.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 35f), Array.Empty<object>()));
			HazardPushCooldownSeconds = config.Bind<float>("Sabotage", "HazardPushCooldownSeconds", 18f, new ConfigDescription("Minimum seconds between environmental hazard shove attempts.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 60f), Array.Empty<object>()));
			RequireBackTurnedForPush = config.Bind<bool>("Sabotage", "RequireBackTurnedForPush", true, "Only shove a player into a hazard when their back is turned and no third-party witness is watching.");
			EnableVoiceCapture = config.Bind<bool>("VoiceMimicry", "EnableVoiceCapture", true, "Enable selective capture and playback of player voice chat snippets.");
			CaptureLocalVoice = config.Bind<bool>("VoiceMimicry", "CaptureLocalVoice", true, "Capture snippets from the local player's microphone via Photon Voice.");
			CaptureRemoteVoice = config.Bind<bool>("VoiceMimicry", "CaptureRemoteVoice", true, "Capture snippets from remote teammates' voice playback AudioSources.");
			CaptureTtsVoice = config.Bind<bool>("VoiceMimicry", "CaptureTtsVoice", true, "Capture snippets from in-game TTS chat audio.");
			MaxSnippetsPerPlayer = config.Bind<int>("VoiceMimicry", "MaxSnippetsPerPlayer", 10, new ConfigDescription("Maximum curated voice snippets retained per player.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 30), Array.Empty<object>()));
			MinSnippetSeconds = config.Bind<float>("VoiceMimicry", "MinSnippetSeconds", 0.65f, new ConfigDescription("Minimum duration in seconds for a captured speech snippet to be kept.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.3f, 2.5f), Array.Empty<object>()));
			MaxSnippetSeconds = config.Bind<float>("VoiceMimicry", "MaxSnippetSeconds", 3.8f, new ConfigDescription("Maximum duration in seconds for a single captured voice snippet.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1.5f, 8f), Array.Empty<object>()));
			SpeechThresholdRms = config.Bind<float>("VoiceMimicry", "SpeechThresholdRms", 0.018f, new ConfigDescription("Minimum RMS energy threshold for selective voice activity detection.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.004f, 0.1f), Array.Empty<object>()));
			MinVoiceIntervalSeconds = config.Bind<float>("VoiceMimicry", "MinVoiceIntervalSeconds", 6f, new ConfigDescription("Minimum seconds between Mimic voice lines.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 30f), Array.Empty<object>()));
			MaxVoiceIntervalSeconds = config.Bind<float>("VoiceMimicry", "MaxVoiceIntervalSeconds", 15f, new ConfigDescription("Maximum seconds between Mimic voice lines while active near players.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 60f), Array.Empty<object>()));
			SubtleVoiceGlitchChance = config.Bind<float>("VoiceMimicry", "SubtleVoiceGlitchChance", 0.1f, new ConfigDescription("Chance a played voice snippet has a subtle uncanny pitch wobble/glitch.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			SyncVoiceOverNetwork = config.Bind<bool>("VoiceMimicry", "SyncVoiceOverNetwork", true, "Stream IMA-ADPCM voice snippets over Photon events so all clients hear the same stolen clips.");
		}
	}
	[BepInPlugin("com.borsboomt.repo.mimic", "R.E.P.O. Mimic Mod", "1.0.0")]
	public sealed class MimicPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.borsboomt.repo.mimic";

		public const string PluginName = "R.E.P.O. Mimic Mod";

		public const string PluginVersion = "1.0.0";

		private Harmony _harmony;

		public static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			MimicConfig.Bind(((BaseUnityPlugin)this).Config);
			if (RepoReflection.ValidateAll(delegate(string msg)
			{
				Log.LogWarning((object)msg);
			}) == 0)
			{
				Log.LogInfo((object)"All R.E.P.O. reflection bindings validated.");
			}
			_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "com.borsboomt.repo.mimic");
			GameObject val = new GameObject("RepoMimicRuntime");
			Object.DontDestroyOnLoad((Object)val);
			val.AddComponent<MimicRuntimeHost>();
			Log.LogInfo((object)"R.E.P.O. Mimic Mod v1.0.0 loaded.");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			MimicNetworkSync.Instance.Unregister();
		}
	}
	public sealed class MimicRuntimeHost : MonoBehaviour
	{
		private float _nextAudioTapScanTime;

		private bool _wasInMenu;

		private void Start()
		{
			MimicNetworkSync.Instance.Register();
		}

		private void Update()
		{
			VoiceSnippetManager.Instance.TickMainThread();
			bool flag = SemiFunc.MenuLevel();
			if (flag && !_wasInMenu)
			{
				VoiceSnippetManager.Instance.ClearAll();
				MimicNetworkSync.Instance.ClearSessionCaches();
			}
			_wasInMenu = flag;
			if (Time.time >= _nextAudioTapScanTime)
			{
				_nextAudioTapScanTime = Time.time + 2f;
				ScanLateAudioTaps();
			}
			if (MimicConfig.EnableDebugHotkeys.Value)
			{
				HandleDebugHotkeys();
			}
		}

		private static void ScanLateAudioTaps()
		{
			if (!MimicConfig.EnableVoiceCapture.Value)
			{
				return;
			}
			List<PlayerAvatar> list = SemiFunc.PlayerGetAll();
			if (list == null)
			{
				return;
			}
			foreach (PlayerAvatar item in list)
			{
				if (!((Object)(object)item == (Object)null))
				{
					PlayerVoiceChat val = RepoReflection.Get<PlayerVoiceChat>(RepoReflection.PlayerAvatarVoiceChat, item);
					if ((Object)(object)val != (Object)null)
					{
						VoiceCaptureHooks.EnsureAudioTaps(val);
					}
				}
			}
		}

		private static void HandleDebugHotkeys()
		{
			if (Input.GetKeyDown((KeyCode)289))
			{
				TryDebugSpawnMimic();
			}
			else if (Input.GetKeyDown((KeyCode)290))
			{
				TryDebugTriggerVoice();
			}
			else if (Input.GetKeyDown((KeyCode)291))
			{
				ManualLogSource log = MimicPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)("[MimicDebug] Voice bank: " + VoiceSnippetManager.Instance.BuildStatsSummary()));
				}
			}
		}

		private static void TryDebugSpawnMimic()
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: 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_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			if (!SemiFunc.IsMasterClientOrSingleplayer())
			{
				ManualLogSource log = MimicPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"[MimicDebug] Only host/singleplayer can spawn a Mimic.");
				}
				return;
			}
			if (!MimicPrefabFactory.EnsureRegistered() || (Object)(object)MimicPrefabFactory.MimicSetup == (Object)null || (Object)(object)LevelGenerator.Instance == (Object)null)
			{
				ManualLogSource log2 = MimicPlugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)"[MimicDebug] Cannot spawn Mimic outside an active level.");
				}
				return;
			}
			PlayerAvatar val = SemiFunc.PlayerAvatarLocal();
			Vector3 val2 = (((Object)(object)val != (Object)null) ? (((Component)val).transform.position + ((Component)val).transform.forward * 6.5f) : Vector3.zero);
			NavMeshHit val4 = default(NavMeshHit);
			Vector3 val3 = (NavMesh.SamplePosition(val2, ref val4, 4f, -1) ? ((NavMeshHit)(ref val4)).position : val2);
			LevelGenerator.Instance.EnemySpawn(MimicPrefabFactory.MimicSetup, val3);
			ManualLogSource log3 = MimicPlugin.Log;
			if (log3 != null)
			{
				log3.LogInfo((object)$"[MimicDebug] Spawned Mimic near {val3}.");
			}
		}

		private static void TryDebugTriggerVoice()
		{
			EnemyMimic[] array = Object.FindObjectsByType<EnemyMimic>((FindObjectsSortMode)0);
			if (array == null || array.Length == 0)
			{
				ManualLogSource log = MimicPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"[MimicDebug] No active Mimic in scene.");
				}
				return;
			}
			array[0].ForcePlayVoiceSnippet(distorted: false);
			ManualLogSource log2 = MimicPlugin.Log;
			if (log2 != null)
			{
				log2.LogInfo((object)"[MimicDebug] Triggered Mimic voice playback.");
			}
		}
	}
}
namespace RepoMimicMod.Voice
{
	public static class ImaAdpcmCodec
	{
		public const int DefaultNetworkSampleRate = 12000;

		private const int HeaderSize = 10;

		private static readonly int[] IndexTable = new int[16]
		{
			-1, -1, -1, -1, 2, 4, 6, 8, -1, -1,
			-1, -1, 2, 4, 6, 8
		};

		private static readonly int[] StepTable = new int[89]
		{
			7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
			19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
			50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
			130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
			337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
			876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
			2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
			5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
			15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
		};

		public static float[] ResampleMono(float[] input, int srcRate, int dstRate)
		{
			if (input == null || input.Length == 0)
			{
				return Array.Empty<float>();
			}
			if (srcRate <= 0 || dstRate <= 0 || srcRate == dstRate)
			{
				float[] array = new float[input.Length];
				Array.Copy(input, array, input.Length);
				return array;
			}
			double num = (double)dstRate / (double)srcRate;
			int num2 = Math.Max(1, (int)Math.Round((double)input.Length * num));
			float[] array2 = new float[num2];
			double num3 = (double)srcRate / (double)dstRate;
			for (int i = 0; i < num2; i++)
			{
				double num4 = (double)i * num3;
				int num5 = (int)num4;
				float num6 = (float)(num4 - (double)num5);
				float num7 = input[Math.Min(num5, input.Length - 1)];
				float num8 = input[Math.Min(num5 + 1, input.Length - 1)];
				array2[i] = num7 + (num8 - num7) * num6;
			}
			return array2;
		}

		public static byte[] Encode(float[] monoSamples, int srcRate, int dstRate = 12000)
		{
			if (monoSamples == null || monoSamples.Length == 0)
			{
				return Array.Empty<byte>();
			}
			float[] array = ((srcRate == dstRate) ? monoSamples : ResampleMono(monoSamples, srcRate, dstRate));
			int num = array.Length;
			int num2 = (num + 1) / 2;
			byte[] array2 = new byte[10 + num2];
			int num3 = Math.Max(4000, Math.Min(48000, dstRate));
			array2[0] = (byte)(num3 & 0xFF);
			array2[1] = (byte)((num3 >> 8) & 0xFF);
			array2[2] = (byte)(num & 0xFF);
			array2[3] = (byte)((num >> 8) & 0xFF);
			array2[4] = (byte)((num >> 16) & 0xFF);
			array2[5] = (byte)((num >> 24) & 0xFF);
			int predictor = FloatToPcm16(array[0]);
			int stepIndex = 0;
			array2[6] = (byte)(predictor & 0xFF);
			array2[7] = (byte)((predictor >> 8) & 0xFF);
			array2[8] = (byte)stepIndex;
			array2[9] = 0;
			for (int i = 0; i < num; i++)
			{
				int num4 = EncodeSample(FloatToPcm16(array[i]), ref predictor, ref stepIndex);
				int num5 = 10 + (i >> 1);
				if ((i & 1) == 0)
				{
					array2[num5] = (byte)(num4 & 0xF);
				}
				else
				{
					array2[num5] |= (byte)((num4 & 0xF) << 4);
				}
			}
			return array2;
		}

		public static float[] Decode(byte[] adpcm, out int sampleRate)
		{
			sampleRate = 12000;
			if (adpcm == null || adpcm.Length < 10)
			{
				return Array.Empty<float>();
			}
			sampleRate = adpcm[0] | (adpcm[1] << 8);
			int num = adpcm[2] | (adpcm[3] << 8) | (adpcm[4] << 16) | (adpcm[5] << 24);
			if (num <= 0 || sampleRate <= 0)
			{
				return Array.Empty<float>();
			}
			int num2 = (adpcm.Length - 10) * 2;
			if (num > num2)
			{
				num = num2;
			}
			int predictor = (short)(adpcm[6] | (adpcm[7] << 8));
			int stepIndex = Math.Max(0, Math.Min(88, (int)adpcm[8]));
			float[] array = new float[num];
			for (int i = 0; i < num; i++)
			{
				int num3 = adpcm[10 + (i >> 1)];
				int num4 = DecodeSample(((i & 1) == 0) ? (num3 & 0xF) : ((num3 >> 4) & 0xF), ref predictor, ref stepIndex);
				array[i] = (float)num4 / 32768f;
			}
			return array;
		}

		private static int FloatToPcm16(float sample)
		{
			int val = (int)Math.Round(Math.Max(-1f, Math.Min(1f, sample)) * 32767f);
			return Math.Max(-32768, Math.Min(32767, val));
		}

		private static int EncodeSample(int sample, ref int predictor, ref int stepIndex)
		{
			int num = StepTable[stepIndex];
			int num2 = sample - predictor;
			int num3 = 0;
			if (num2 < 0)
			{
				num3 = 8;
				num2 = -num2;
			}
			int num4 = num >> 3;
			if (num2 >= num)
			{
				num3 |= 4;
				num2 -= num;
				num4 += num;
			}
			num >>= 1;
			if (num2 >= num)
			{
				num3 |= 2;
				num2 -= num;
				num4 += num;
			}
			num >>= 1;
			if (num2 >= num)
			{
				num3 |= 1;
				num4 += num;
			}
			if ((num3 & 8) != 0)
			{
				predictor -= num4;
			}
			else
			{
				predictor += num4;
			}
			if (predictor > 32767)
			{
				predictor = 32767;
			}
			else if (predictor < -32768)
			{
				predictor = -32768;
			}
			stepIndex += IndexTable[num3];
			if (stepIndex < 0)
			{
				stepIndex = 0;
			}
			else if (stepIndex > 88)
			{
				stepIndex = 88;
			}
			return num3;
		}

		private static int DecodeSample(int nibble, ref int predictor, ref int stepIndex)
		{
			int num = StepTable[stepIndex];
			int num2 = num >> 3;
			if ((nibble & 4) != 0)
			{
				num2 += num;
			}
			if ((nibble & 2) != 0)
			{
				num2 += num >> 1;
			}
			if ((nibble & 1) != 0)
			{
				num2 += num >> 2;
			}
			if ((nibble & 8) != 0)
			{
				predictor -= num2;
			}
			else
			{
				predictor += num2;
			}
			if (predictor > 32767)
			{
				predictor = 32767;
			}
			else if (predictor < -32768)
			{
				predictor = -32768;
			}
			stepIndex += IndexTable[nibble];
			if (stepIndex < 0)
			{
				stepIndex = 0;
			}
			else if (stepIndex > 88)
			{
				stepIndex = 88;
			}
			return predictor;
		}
	}
	public sealed class CompletedSnippetData
	{
		public float[] Samples { get; }

		public int SampleRate { get; }

		public float QualityScore { get; }

		public CompletedSnippetData(float[] samples, int sampleRate, float qualityScore)
		{
			Samples = samples;
			SampleRate = sampleRate;
			QualityScore = qualityScore;
		}
	}
	public sealed class PlayerVoiceCaptureBuffer
	{
		public const int TargetSampleRate = 16000;

		private const int FrameSize = 320;

		private const int PreRollSamplesCount = 4000;

		private const float HangoverSeconds = 0.45f;

		private const float OnsetConfirmSeconds = 0.08f;

		private readonly object _sync = new object();

		private readonly float[] _preRoll = new float[4000];

		private int _preRollWriteIndex;

		private int _preRollCount;

		private readonly float[] _frameAccum = new float[320];

		private int _frameAccumCount;

		private readonly List<float> _activeSamples = new List<float>(64000);

		private readonly Queue<CompletedSnippetData> _completed = new Queue<CompletedSnippetData>();

		private float _noiseFloorRms = 0.004f;

		private bool _inUtterance;

		private float _onsetAccumSeconds;

		private float _silenceAccumSeconds;

		private int _activeFrameCount;

		private int _totalFrameCount;

		private float _lastActiveTimeOffset;

		private float _minSnippetSeconds = 0.65f;

		private float _maxSnippetSeconds = 3.8f;

		private float _speechThresholdRms = 0.018f;

		public string SpeakerSteamId { get; }

		public string SpeakerName { get; private set; }

		public PlayerVoiceCaptureBuffer(string steamId, string speakerName)
		{
			SpeakerSteamId = steamId ?? string.Empty;
			SpeakerName = (string.IsNullOrEmpty(speakerName) ? "Teammate" : speakerName);
		}

		public void UpdateSpeakerName(string speakerName)
		{
			if (!string.IsNullOrEmpty(speakerName))
			{
				lock (_sync)
				{
					SpeakerName = speakerName;
				}
			}
		}

		public void Configure(float minSnippetSeconds, float maxSnippetSeconds, float speechThresholdRms)
		{
			lock (_sync)
			{
				_minSnippetSeconds = Math.Max(0.25f, minSnippetSeconds);
				_maxSnippetSeconds = Math.Max(_minSnippetSeconds + 0.3f, maxSnippetSeconds);
				_speechThresholdRms = Math.Max(0.002f, speechThresholdRms);
			}
		}

		public void PushInterleavedFloat(float[] interleaved, int channels, int sampleRate)
		{
			if (interleaved == null || interleaved.Length == 0 || channels <= 0 || sampleRate <= 0)
			{
				return;
			}
			int num = interleaved.Length / channels;
			if (num <= 0)
			{
				return;
			}
			float[] array = new float[num];
			if (channels == 1)
			{
				Array.Copy(interleaved, array, num);
			}
			else
			{
				float num2 = 1f / (float)channels;
				for (int i = 0; i < num; i++)
				{
					float num3 = 0f;
					int num4 = i * channels;
					for (int j = 0; j < channels; j++)
					{
						num3 += interleaved[num4 + j];
					}
					array[i] = num3 * num2;
				}
			}
			PushMonoFloat(array, sampleRate);
		}

		public void PushMonoShort(short[] samples, int channels, int sampleRate)
		{
			if (samples == null || samples.Length == 0 || channels <= 0 || sampleRate <= 0)
			{
				return;
			}
			int num = samples.Length / channels;
			if (num <= 0)
			{
				return;
			}
			float[] array = new float[num];
			float num2 = 1f / (32768f * (float)channels);
			for (int i = 0; i < num; i++)
			{
				float num3 = 0f;
				int num4 = i * channels;
				for (int j = 0; j < channels; j++)
				{
					num3 += (float)samples[num4 + j];
				}
				array[i] = num3 * num2;
			}
			PushMonoFloat(array, sampleRate);
		}

		public void PushMonoFloat(float[] monoSamples, int sampleRate)
		{
			if (monoSamples == null || monoSamples.Length == 0 || sampleRate <= 0)
			{
				return;
			}
			float[] array = ((sampleRate == 16000) ? monoSamples : ImaAdpcmCodec.ResampleMono(monoSamples, sampleRate, 16000));
			lock (_sync)
			{
				int num = 0;
				while (num < array.Length)
				{
					int num2 = Math.Min(320 - _frameAccumCount, array.Length - num);
					Array.Copy(array, num, _frameAccum, _frameAccumCount, num2);
					_frameAccumCount += num2;
					num += num2;
					if (_frameAccumCount == 320)
					{
						Process20MsFrame(_frameAccum);
						_frameAccumCount = 0;
					}
				}
			}
		}

		public List<CompletedSnippetData> DrainCompleted()
		{
			lock (_sync)
			{
				if (_completed.Count == 0)
				{
					return null;
				}
				List<CompletedSnippetData> list = new List<CompletedSnippetData>(_completed.Count);
				while (_completed.Count > 0)
				{
					list.Add(_completed.Dequeue());
				}
				return list;
			}
		}

		private void Process20MsFrame(float[] frame)
		{
			double num = 0.0;
			for (int i = 0; i < 320; i++)
			{
				float num2 = frame[i];
				num += (double)(num2 * num2);
			}
			float num3 = (float)Math.Sqrt(num / 320.0);
			float num4 = Math.Max(_speechThresholdRms, _noiseFloorRms * 2.5f);
			bool flag = num3 >= num4;
			if (!flag && !_inUtterance)
			{
				_noiseFloorRms = _noiseFloorRms * 0.96f + Math.Min(num3, _speechThresholdRms) * 0.04f;
			}
			if (!_inUtterance)
			{
				WritePreRoll(frame);
				if (flag)
				{
					_onsetAccumSeconds += 0.02f;
					if (_onsetAccumSeconds >= 0.08f)
					{
						BeginUtterance();
					}
				}
				else
				{
					_onsetAccumSeconds = Math.Max(0f, _onsetAccumSeconds - 0.01f);
				}
				return;
			}
			_activeSamples.AddRange(frame);
			_totalFrameCount++;
			if (flag)
			{
				_activeFrameCount++;
				_silenceAccumSeconds = 0f;
				_lastActiveTimeOffset = (float)_activeSamples.Count / 16000f;
			}
			else
			{
				_silenceAccumSeconds += 0.02f;
			}
			float num5 = (float)_activeSamples.Count / 16000f;
			if (_silenceAccumSeconds >= 0.45f || num5 >= _maxSnippetSeconds)
			{
				FinalizeUtterance();
			}
		}

		private void WritePreRoll(float[] frame)
		{
			for (int i = 0; i < frame.Length; i++)
			{
				_preRoll[_preRollWriteIndex] = frame[i];
				_preRollWriteIndex = (_preRollWriteIndex + 1) % 4000;
				if (_preRollCount < 4000)
				{
					_preRollCount++;
				}
			}
		}

		private void BeginUtterance()
		{
			_inUtterance = true;
			_activeSamples.Clear();
			_silenceAccumSeconds = 0f;
			_activeFrameCount = 1;
			_totalFrameCount = 1;
			int preRollCount = _preRollCount;
			int num = (_preRollWriteIndex - preRollCount + 4000) % 4000;
			for (int i = 0; i < preRollCount; i++)
			{
				_activeSamples.Add(_preRoll[(num + i) % 4000]);
			}
			_lastActiveTimeOffset = (float)_activeSamples.Count / 16000f;
			_preRollCount = 0;
			_preRollWriteIndex = 0;
		}

		private void FinalizeUtterance()
		{
			_inUtterance = false;
			_onsetAccumSeconds = 0f;
			int num = Math.Min(_activeSamples.Count, (int)Math.Round((_lastActiveTimeOffset + 0.06f) * 16000f));
			if (num > 0)
			{
				float num2 = (float)num / 16000f;
				float num3 = ((_totalFrameCount > 0) ? ((float)_activeFrameCount / (float)_totalFrameCount) : 0f);
				if (num2 >= _minSnippetSeconds && num3 >= 0.3f)
				{
					float[] array = new float[num];
					_activeSamples.CopyTo(0, array, 0, num);
					if (TryEvaluateAndNormalize(array, out var qualityScore))
					{
						if (_completed.Count >= 8)
						{
							_completed.Dequeue();
						}
						_completed.Enqueue(new CompletedSnippetData(array, 16000, qualityScore));
					}
				}
			}
			_activeSamples.Clear();
			_silenceAccumSeconds = 0f;
			_activeFrameCount = 0;
			_totalFrameCount = 0;
		}

		private static bool TryEvaluateAndNormalize(float[] samples, out float qualityScore)
		{
			qualityScore = 0f;
			int num = samples.Length;
			if (num < 160)
			{
				return false;
			}
			double num2 = 0.0;
			for (int i = 0; i < num; i++)
			{
				num2 += (double)samples[i];
			}
			float num3 = (float)(num2 / (double)num);
			double num4 = 0.0;
			float num5 = 0f;
			int num6 = 0;
			int num7 = 0;
			float num8 = samples[0] - num3;
			for (int j = 0; j < num; j++)
			{
				float num9 = (samples[j] -= num3);
				float num10 = Math.Abs(num9);
				if (num10 > num5)
				{
					num5 = num10;
				}
				if (num10 >= 0.97f)
				{
					num7++;
				}
				num4 += (double)(num9 * num9);
				if ((num9 >= 0f && num8 < 0f) || (num9 < 0f && num8 >= 0f))
				{
					num6++;
				}
				num8 = num9;
			}
			if (num5 < 0.02f)
			{
				return false;
			}
			float num11 = (float)Math.Sqrt(num4 / (double)num);
			if (num11 < 0.005f)
			{
				return false;
			}
			float num12 = (float)num6 / (float)num;
			if (num12 > 0.38f || num12 < 0.008f)
			{
				return false;
			}
			float num13 = (float)num / 16000f;
			float num14 = ((num13 >= 1f && num13 <= 3.2f) ? 1f : Math.Max(0.35f, 1f - Math.Abs(num13 - 2f) * 0.25f));
			float num15 = Math.Min(1.25f, num11 / 0.06f);
			float num16 = num5 / Math.Max(0.001f, num11);
			float num17 = Math.Min(1.2f, Math.Max(0.4f, num16 / 5.5f));
			float num18 = Math.Max(0.3f, 1f - (float)num7 / (float)num * 20f);
			qualityScore = num14 * num15 * num17 * num18;
			float num19 = Math.Min(8f, 0.18f / num11);
			if (num5 * num19 > 0.92f)
			{
				num19 = 0.92f / num5;
			}
			int num20 = Math.Min(num / 4, 400);
			for (int k = 0; k < num; k++)
			{
				float num21 = samples[k] * num19;
				if (k < num20)
				{
					float num22 = 0.5f * (1f - (float)Math.Cos(Math.PI * (double)k / (double)num20));
					num21 *= num22;
				}
				else if (k >= num - num20)
				{
					int num23 = num - 1 - k;
					float num24 = 0.5f * (1f - (float)Math.Cos(Math.PI * (double)num23 / (double)num20));
					num21 *= num24;
				}
				samples[k] = Math.Max(-0.95f, Math.Min(0.95f, num21));
			}
			return true;
		}
	}
	public sealed class MimicFloatVoiceProcessor : IProcessor<float>, IDisposable
	{
		private readonly string _steamId;

		private readonly string _speakerName;

		private readonly int _channels;

		private readonly int _sampleRate;

		public MimicFloatVoiceProcessor(string steamId, string speakerName, int channels, int sampleRate)
		{
			_steamId = steamId;
			_speakerName = speakerName;
			_channels = Math.Max(1, channels);
			_sampleRate = Math.Max(8000, sampleRate);
		}

		public float[] Process(float[] buf)
		{
			if (MimicConfig.EnableVoiceCapture.Value && MimicConfig.CaptureLocalVoice.Value && buf != null && buf.Length != 0)
			{
				VoiceSnippetManager.Instance.GetOrCreateBuffer(_steamId, _speakerName).PushInterleavedFloat(buf, _channels, _sampleRate);
			}
			return buf;
		}

		public void Dispose()
		{
		}
	}
	public sealed class MimicShortVoiceProcessor : IProcessor<short>, IDisposable
	{
		private readonly string _steamId;

		private readonly string _speakerName;

		private readonly int _channels;

		private readonly int _sampleRate;

		public MimicShortVoiceProcessor(string steamId, string speakerName, int channels, int sampleRate)
		{
			_steamId = steamId;
			_speakerName = speakerName;
			_channels = Math.Max(1, channels);
			_sampleRate = Math.Max(8000, sampleRate);
		}

		public short[] Process(short[] buf)
		{
			if (MimicConfig.EnableVoiceCapture.Value && MimicConfig.CaptureLocalVoice.Value && buf != null && buf.Length != 0)
			{
				VoiceSnippetManager.Instance.GetOrCreateBuffer(_steamId, _speakerName).PushMonoShort(buf, _channels, _sampleRate);
			}
			return buf;
		}

		public void Dispose()
		{
		}
	}
	public sealed class MimicAudioTap : MonoBehaviour
	{
		private PlayerVoiceChat _voiceChat;

		private bool _isTts;

		private int _outputSampleRate;

		public void Initialize(PlayerVoiceChat voiceChat, bool isTts)
		{
			_voiceChat = voiceChat;
			_isTts = isTts;
			_outputSampleRate = ((AudioSettings.outputSampleRate > 0) ? AudioSettings.outputSampleRate : 48000);
		}

		private void OnAudioFilterRead(float[] data, int channels)
		{
			if (MimicConfig.EnableVoiceCapture.Value && (!_isTts || MimicConfig.CaptureTtsVoice.Value) && (_isTts || MimicConfig.CaptureRemoteVoice.Value) && data != null && data.Length != 0 && !((Object)(object)_voiceChat == (Object)null))
			{
				PlayerAvatar val = RepoReflection.Get<PlayerAvatar>(RepoReflection.PlayerVoiceChatAvatar, _voiceChat);
				if (!((Object)(object)val == (Object)null) && (_isTts || !RepoReflection.IsPlayerLocal(val)))
				{
					string playerSteamId = RepoReflection.GetPlayerSteamId(val);
					string playerName = RepoReflection.GetPlayerName(val);
					int sampleRate = ((_outputSampleRate > 0) ? _outputSampleRate : 48000);
					VoiceSnippetManager.Instance.GetOrCreateBuffer(playerSteamId, playerName).PushInterleavedFloat(data, Math.Max(1, channels), sampleRate);
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayerVoiceChat))]
	public static class VoiceCaptureHooks
	{
		[HarmonyPatch("PhotonVoiceCreated")]
		[HarmonyPostfix]
		private static void PhotonVoiceCreatedPostfix(PlayerVoiceChat __instance, PhotonVoiceCreatedParams _params)
		{
			//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_007b: Unknown result type (might be due to invalid IL or missing references)
			if (MimicConfig.EnableVoiceCapture.Value && MimicConfig.CaptureLocalVoice.Value && !((Object)(object)__instance == (Object)null) && _params.Voice != null)
			{
				PlayerAvatar player = RepoReflection.Get<PlayerAvatar>(RepoReflection.PlayerVoiceChatAvatar, __instance) ?? SemiFunc.PlayerAvatarLocal();
				string text = RepoReflection.GetPlayerSteamId(player);
				string playerName = RepoReflection.GetPlayerName(player);
				if (string.IsNullOrEmpty(text))
				{
					text = "local";
				}
				VoiceInfo info = _params.Voice.Info;
				int channels = ((VoiceInfo)(ref info)).Channels;
				info = _params.Voice.Info;
				int samplingRate = ((VoiceInfo)(ref info)).SamplingRate;
				if (_params.Voice is LocalVoiceFramed<float> val)
				{
					val.AddPostProcessor(new IProcessor<float>[1]
					{
						new MimicFloatVoiceProcessor(text, playerName, channels, samplingRate)
					});
				}
				else if (_params.Voice is LocalVoiceFramed<short> val2)
				{
					val2.AddPostProcessor(new IProcessor<short>[1]
					{
						new MimicShortVoiceProcessor(text, playerName, channels, samplingRate)
					});
				}
			}
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPostfix(PlayerVoiceChat __instance)
		{
			EnsureAudioTaps(__instance);
		}

		public static void EnsureAudioTaps(PlayerVoiceChat voiceChat)
		{
			if (!((Object)(object)voiceChat == (Object)null))
			{
				AudioSource val = RepoReflection.Get<AudioSource>(RepoReflection.PlayerVoiceChatAudioSource, voiceChat);
				if ((Object)(object)val != (Object)null)
				{
					AttachTapIfMissing(((Component)val).gameObject, voiceChat, isTts: false);
				}
				if ((Object)(object)voiceChat.ttsAudioSource != (Object)null)
				{
					AttachTapIfMissing(((Component)voiceChat.ttsAudioSource).gameObject, voiceChat, isTts: true);
				}
			}
		}

		private static void AttachTapIfMissing(GameObject target, PlayerVoiceChat voiceChat, bool isTts)
		{
			if ((Object)(object)target == (Object)null)
			{
				return;
			}
			MimicAudioTap[] components = target.GetComponents<MimicAudioTap>();
			for (int i = 0; i < components.Length; i++)
			{
				if ((Object)(object)components[i] != (Object)null)
				{
					return;
				}
			}
			target.AddComponent<MimicAudioTap>().Initialize(voiceChat, isTts);
		}
	}
	public sealed class VoiceSnippet
	{
		public int ClipId { get; }

		public string SpeakerSteamId { get; }

		public string SpeakerName { get; }

		public int SampleRate { get; }

		public float[] Samples { get; }

		public float DurationSeconds { get; }

		public float QualityScore { get; }

		public float CapturedRealtime { get; }

		public float LastPlayedRealtime { get; set; }

		public VoiceSnippet(int clipId, string speakerSteamId, string speakerName, int sampleRate, float[] samples, float qualityScore, float capturedRealtime)
		{
			ClipId = clipId;
			SpeakerSteamId = speakerSteamId ?? string.Empty;
			SpeakerName = (string.IsNullOrEmpty(speakerName) ? "Teammate" : speakerName);
			SampleRate = sampleRate;
			Samples = samples;
			DurationSeconds = ((samples != null && sampleRate > 0) ? ((float)samples.Length / (float)sampleRate) : 0f);
			QualityScore = qualityScore;
			CapturedRealtime = capturedRealtime;
			LastPlayedRealtime = -9999f;
		}
	}
	public sealed class VoiceSnippetManager
	{
		private readonly object _buffersLock = new object();

		private readonly Dictionary<string, PlayerVoiceCaptureBuffer> _captureBuffers = new Dictionary<string, PlayerVoiceCaptureBuffer>();

		private readonly Dictionary<string, List<VoiceSnippet>> _snippetsBySteamId = new Dictionary<string, List<VoiceSnippet>>();

		private readonly Dictionary<int, VoiceSnippet> _snippetsById = new Dictionary<int, VoiceSnippet>();

		private readonly List<VoiceSnippet> _allSnippets = new List<VoiceSnippet>();

		private int _nextClipId = 1;

		private readonly Random _rng = new Random();

		public static VoiceSnippetManager Instance { get; } = new VoiceSnippetManager();

		public int TotalSnippetCount => _allSnippets.Count;

		private VoiceSnippetManager()
		{
		}

		public PlayerVoiceCaptureBuffer GetOrCreateBuffer(string steamId, string speakerName)
		{
			string text = (string.IsNullOrEmpty(steamId) ? ("name:" + speakerName) : steamId);
			lock (_buffersLock)
			{
				if (!_captureBuffers.TryGetValue(text, out var value))
				{
					value = new PlayerVoiceCaptureBuffer(text, speakerName);
					_captureBuffers[text] = value;
				}
				else
				{
					value.UpdateSpeakerName(speakerName);
				}
				value.Configure(MimicConfig.MinSnippetSeconds.Value, MimicConfig.MaxSnippetSeconds.Value, MimicConfig.SpeechThresholdRms.Value);
				return value;
			}
		}

		public void TickMainThread()
		{
			List<PlayerVoiceCaptureBuffer> list;
			lock (_buffersLock)
			{
				if (_captureBuffers.Count == 0)
				{
					return;
				}
				list = new List<PlayerVoiceCaptureBuffer>(_captureBuffers.Values);
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			int maxPerPlayer = Math.Max(1, MimicConfig.MaxSnippetsPerPlayer.Value);
			foreach (PlayerVoiceCaptureBuffer item in list)
			{
				item.Configure(MimicConfig.MinSnippetSeconds.Value, MimicConfig.MaxSnippetSeconds.Value, MimicConfig.SpeechThresholdRms.Value);
				List<CompletedSnippetData> list2 = item.DrainCompleted();
				if (list2 == null)
				{
					continue;
				}
				foreach (CompletedSnippetData item2 in list2)
				{
					VoiceSnippet snippet = new VoiceSnippet(GenerateUniqueClipId(), item.SpeakerSteamId, item.SpeakerName, item2.SampleRate, item2.Samples, item2.QualityScore, realtimeSinceStartup);
					StoreSnippet(snippet, maxPerPlayer);
				}
			}
		}

		public void RegisterRemoteSnippet(int clipId, string speakerSteamId, string speakerName, int sampleRate, float[] samples)
		{
			if (samples != null && samples.Length != 0 && sampleRate > 0 && !_snippetsById.ContainsKey(clipId))
			{
				VoiceSnippet snippet = new VoiceSnippet(clipId, speakerSteamId, speakerName, sampleRate, samples, 1f, Time.realtimeSinceStartup);
				StoreSnippet(snippet, Math.Max(1, MimicConfig.MaxSnippetsPerPlayer.Value));
			}
		}

		public VoiceSnippet GetSnippetById(int clipId)
		{
			_snippetsById.TryGetValue(clipId, out var value);
			return value;
		}

		public VoiceSnippet SelectBestSnippet(string preferredSteamId, bool allowFallback = true)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (!string.IsNullOrEmpty(preferredSteamId) && _snippetsBySteamId.TryGetValue(preferredSteamId, out var value) && value.Count > 0)
			{
				return PickWeightedSnippet(value, realtimeSinceStartup);
			}
			if (allowFallback && _allSnippets.Count > 0)
			{
				return PickWeightedSnippet(_allSnippets, realtimeSinceStartup);
			}
			return null;
		}

		public string BuildStatsSummary()
		{
			return $"Speakers={_snippetsBySteamId.Count}, TotalSnippets={_allSnippets.Count}";
		}

		public void ClearAll()
		{
			lock (_buffersLock)
			{
				_captureBuffers.Clear();
			}
			_snippetsBySteamId.Clear();
			_snippetsById.Clear();
			_allSnippets.Clear();
		}

		private void StoreSnippet(VoiceSnippet snippet, int maxPerPlayer)
		{
			if (!_snippetsBySteamId.TryGetValue(snippet.SpeakerSteamId, out var value))
			{
				value = new List<VoiceSnippet>();
				_snippetsBySteamId[snippet.SpeakerSteamId] = value;
			}
			if (value.Count >= maxPerPlayer)
			{
				int index = 0;
				float num = float.MaxValue;
				for (int i = 0; i < value.Count; i++)
				{
					float num2 = Math.Min(0.4f, (Time.realtimeSinceStartup - value[i].CapturedRealtime) * 0.001f);
					float num3 = value[i].QualityScore - num2;
					if (num3 < num)
					{
						num = num3;
						index = i;
					}
				}
				VoiceSnippet voiceSnippet = value[index];
				value.RemoveAt(index);
				_snippetsById.Remove(voiceSnippet.ClipId);
				_allSnippets.Remove(voiceSnippet);
			}
			value.Add(snippet);
			_snippetsById[snippet.ClipId] = snippet;
			_allSnippets.Add(snippet);
		}

		private VoiceSnippet PickWeightedSnippet(List<VoiceSnippet> candidates, float now)
		{
			if (candidates.Count == 0)
			{
				return null;
			}
			if (candidates.Count == 1)
			{
				candidates[0].LastPlayedRealtime = now;
				return candidates[0];
			}
			float num = 0f;
			float[] array = new float[candidates.Count];
			for (int i = 0; i < candidates.Count; i++)
			{
				VoiceSnippet voiceSnippet = candidates[i];
				float num2 = now - voiceSnippet.LastPlayedRealtime;
				float num3 = ((num2 < 12f) ? 0.12f : Math.Min(1.5f, num2 / 30f));
				num += (array[i] = Math.Max(0.05f, voiceSnippet.QualityScore * num3));
			}
			double num4 = _rng.NextDouble() * (double)num;
			float num5 = 0f;
			for (int j = 0; j < candidates.Count; j++)
			{
				num5 += array[j];
				if (num4 <= (double)num5)
				{
					candidates[j].LastPlayedRealtime = now;
					return candidates[j];
				}
			}
			VoiceSnippet voiceSnippet2 = candidates[candidates.Count - 1];
			voiceSnippet2.LastPlayedRealtime = now;
			return voiceSnippet2;
		}

		private int GenerateUniqueClipId()
		{
			int num = ((((PhotonNetwork.LocalPlayer != null) ? PhotonNetwork.LocalPlayer.ActorNumber : 0) & 0xFF) << 22) | (_nextClipId++ & 0x3FFFFF);
			if (num == 0)
			{
				num = _nextClipId++;
			}
			return num;
		}
	}
}
namespace RepoMimicMod.Reflection
{
	public static class RepoReflection
	{
		public static readonly FieldInfo RunManagerSingleplayerPool = AccessTools.Field(typeof(RunManager), "singleplayerPool");

		public static readonly FieldInfo RunManagerMultiplayerPool = AccessTools.Field(typeof(RunManager), "multiplayerPool");

		public static readonly FieldInfo EnemyParentEnemy = AccessTools.Field(typeof(EnemyParent), "Enemy");

		public static readonly FieldInfo EnemyParentSetupDone = AccessTools.Field(typeof(EnemyParent), "SetupDone");

		public static readonly FieldInfo EnemyParentSpawned = AccessTools.Field(typeof(EnemyParent), "Spawned");

		public static readonly FieldInfo EnemyEnemyParent = AccessTools.Field(typeof(Enemy), "EnemyParent");

		public static readonly FieldInfo EnemyPhotonView = AccessTools.Field(typeof(Enemy), "PhotonView");

		public static readonly FieldInfo EnemyMasterClient = AccessTools.Field(typeof(Enemy), "MasterClient");

		public static readonly FieldInfo EnemyNavMeshAgentField = AccessTools.Field(typeof(Enemy), "NavMeshAgent");

		public static readonly FieldInfo EnemyVisionField = AccessTools.Field(typeof(Enemy), "Vision");

		public static readonly FieldInfo EnemyRigidbodyField = AccessTools.Field(typeof(Enemy), "Rigidbody");

		public static readonly FieldInfo EnemyHealthField = AccessTools.Field(typeof(Enemy), "Health");

		public static readonly FieldInfo EnemyOnScreenField = AccessTools.Field(typeof(Enemy), "OnScreen");

		public static readonly FieldInfo EnemyPlayerDistanceField = AccessTools.Field(typeof(Enemy), "PlayerDistance");

		public static readonly FieldInfo EnemyPlayerRoomField = AccessTools.Field(typeof(Enemy), "PlayerRoom");

		public static readonly FieldInfo EnemyGroundedField = AccessTools.Field(typeof(Enemy), "Grounded");

		public static readonly FieldInfo EnemyJumpField = AccessTools.Field(typeof(Enemy), "Jump");

		public static readonly FieldInfo EnemyStateSpawnField = AccessTools.Field(typeof(Enemy), "StateSpawn");

		public static readonly FieldInfo EnemyStateInvestigateField = AccessTools.Field(typeof(Enemy), "StateInvestigate");

		public static readonly FieldInfo EnemyStateStunnedField = AccessTools.Field(typeof(Enemy), "StateStunned");

		public static readonly FieldInfo EnemyStateDespawnField = AccessTools.Field(typeof(Enemy), "StateDespawn");

		public static readonly FieldInfo EnemyTargetPlayerAvatar = AccessTools.Field(typeof(Enemy), "TargetPlayerAvatar");

		public static readonly FieldInfo EnemyVisionTriggeredPlayer = AccessTools.Field(typeof(EnemyVision), "onVisionTriggeredPlayer");

		public static readonly FieldInfo EnemyVisionTriggeredDistance = AccessTools.Field(typeof(EnemyVision), "onVisionTriggeredDistance");

		public static readonly FieldInfo EnemyVisionTriggeredCulled = AccessTools.Field(typeof(EnemyVision), "onVisionTriggeredCulled");

		public static readonly FieldInfo EnemyInvestigateTriggeredPosition = AccessTools.Field(typeof(EnemyStateInvestigate), "onInvestigateTriggeredPosition");

		public static readonly FieldInfo EnemyHealthCurrent = AccessTools.Field(typeof(EnemyHealth), "healthCurrent");

		public static readonly FieldInfo EnemyHealthDead = AccessTools.Field(typeof(EnemyHealth), "dead");

		public static readonly FieldInfo EnemyHealthRenderers = AccessTools.Field(typeof(EnemyHealth), "renderers");

		public static readonly FieldInfo EnemyHealthSharedMaterials = AccessTools.Field(typeof(EnemyHealth), "sharedMaterials");

		public static readonly FieldInfo EnemyHealthInstancedMaterials = AccessTools.Field(typeof(EnemyHealth), "instancedMaterials");

		public static readonly FieldInfo EnemyHealthMaterialHurtColor = AccessTools.Field(typeof(EnemyHealth), "materialHurtColor");

		public static readonly FieldInfo EnemyHealthMaterialHurtAmount = AccessTools.Field(typeof(EnemyHealth), "materialHurtAmount");

		public static readonly FieldInfo EnemyHealthHurtColor = AccessTools.Field(typeof(EnemyHealth), "hurtColor");

		public static readonly FieldInfo EnemyNavMeshAgentComponent = AccessTools.Field(typeof(EnemyNavMeshAgent), "Agent");

		public static readonly FieldInfo EnemyRigidbodyRb = AccessTools.Field(typeof(EnemyRigidbody), "rb");

		public static readonly FieldInfo EnemyRigidbodyGrabbed = AccessTools.Field(typeof(EnemyRigidbody), "grabbed");

		public static readonly FieldInfo EnemyRigidbodyOnGrabbedPlayer = AccessTools.Field(typeof(EnemyRigidbody), "onGrabbedPlayerAvatar");

		public static readonly FieldInfo EnemyRigidbodyOnTouchPlayer = AccessTools.Field(typeof(EnemyRigidbody), "onTouchPlayerAvatar");

		public static readonly FieldInfo PlayerAvatarName = AccessTools.Field(typeof(PlayerAvatar), "playerName");

		public static readonly FieldInfo PlayerAvatarSteamId = AccessTools.Field(typeof(PlayerAvatar), "steamID");

		public static readonly FieldInfo PlayerAvatarIsLocal = AccessTools.Field(typeof(PlayerAvatar), "isLocal");

		public static readonly FieldInfo PlayerAvatarDeadSet = AccessTools.Field(typeof(PlayerAvatar), "deadSet");

		public static readonly FieldInfo PlayerAvatarIsDisabled = AccessTools.Field(typeof(PlayerAvatar), "isDisabled");

		public static readonly FieldInfo PlayerAvatarIsCrouching = AccessTools.Field(typeof(PlayerAvatar), "isCrouching");

		public static readonly FieldInfo PlayerAvatarIsSprinting = AccessTools.Field(typeof(PlayerAvatar), "isSprinting");

		public static readonly FieldInfo PlayerAvatarVoiceChat = AccessTools.Field(typeof(PlayerAvatar), "voiceChat");

		public static readonly FieldInfo PlayerAvatarTumble = AccessTools.Field(typeof(PlayerAvatar), "tumble");

		public static readonly FieldInfo PlayerAvatarClientPosition = AccessTools.Field(typeof(PlayerAvatar), "clientPosition");

		public static readonly FieldInfo PlayerAvatarClientPositionCurrent = AccessTools.Field(typeof(PlayerAvatar), "clientPositionCurrent");

		public static readonly FieldInfo ValuableObjectImpactDetector = AccessTools.Field(typeof(ValuableObject), "impactDetector");

		public static readonly FieldInfo ValuableObjectDollarValueCurrent = AccessTools.Field(typeof(ValuableObject), "dollarValueCurrent");

		public static readonly FieldInfo ValuableObjectRb = AccessTools.Field(typeof(ValuableObject), "rb");

		public static readonly FieldInfo ValuableObjectPhysGrabObject = AccessTools.Field(typeof(ValuableObject), "physGrabObject");

		public static readonly FieldInfo ValuableObjectCommittedToExtraction = AccessTools.Field(typeof(ValuableObject), "committedToExtraction");

		public static readonly FieldInfo PlayerVoiceChatAvatar = AccessTools.Field(typeof(PlayerVoiceChat), "playerAvatar");

		public static readonly FieldInfo PlayerVoiceChatAudioSource = AccessTools.Field(typeof(PlayerVoiceChat), "audioSource");

		public static readonly FieldInfo PlayerVoiceChatIsTalking = AccessTools.Field(typeof(PlayerVoiceChat), "isTalking");

		public static readonly FieldInfo PlayerVoiceChatClipLoudness = AccessTools.Field(typeof(PlayerVoiceChat), "clipLoudness");

		public static readonly FieldInfo PlayerAvatarVisualsAnimator = AccessTools.Field(typeof(PlayerAvatarVisuals), "animator");

		public static readonly FieldInfo PlayerAvatarVisualsTalkAnim = AccessTools.Field(typeof(PlayerAvatarVisuals), "playerAvatarTalkAnimation");

		public static readonly FieldInfo PlayerCosmeticsColorsEquipped = AccessTools.Field(typeof(PlayerCosmetics), "colorsEquipped");

		public static readonly FieldInfo PhysGrabberCurrentlyLookingAtPhysGrabObject = AccessTools.Field(typeof(PhysGrabber), "currentlyLookingAtPhysGrabObject");

		public static readonly FieldInfo PhysGrabberGrabbedPhysGrabObject = AccessTools.Field(typeof(PhysGrabber), "grabbedPhysGrabObject");

		public static readonly FieldInfo PhysGrabHingeClosed = AccessTools.Field(typeof(PhysGrabHinge), "closed");

		public static readonly FieldInfo PhysGrabHingeCloseDisableTimer = AccessTools.Field(typeof(PhysGrabHinge), "closeDisableTimer");

		public static readonly FieldInfo PhysGrabHingeBroken = AccessTools.Field(typeof(PhysGrabHinge), "broken");

		public static readonly FieldInfo PhysGrabHingeDead = AccessTools.Field(typeof(PhysGrabHinge), "dead");

		public static readonly FieldInfo PhysGrabHingeJoint = AccessTools.Field(typeof(PhysGrabHinge), "joint");

		public static readonly FieldInfo PhysGrabHingePhysGrabObject = AccessTools.Field(typeof(PhysGrabHinge), "physGrabObject");

		public static readonly MethodInfo PhysGrabHingeOpenImpulse = AccessTools.Method(typeof(PhysGrabHinge), "OpenImpulse", (Type[])null, (Type[])null);

		private static readonly (string Name, FieldInfo Field)[] AllFields = new(string, FieldInfo)[70]
		{
			("RunManager.singleplayerPool", RunManagerSingleplayerPool),
			("RunManager.multiplayerPool", RunManagerMultiplayerPool),
			("EnemyParent.Enemy", EnemyParentEnemy),
			("EnemyParent.SetupDone", EnemyParentSetupDone),
			("EnemyParent.Spawned", EnemyParentSpawned),
			("Enemy.EnemyParent", EnemyEnemyParent),
			("Enemy.PhotonView", EnemyPhotonView),
			("Enemy.MasterClient", EnemyMasterClient),
			("Enemy.NavMeshAgent", EnemyNavMeshAgentField),
			("Enemy.Vision", EnemyVisionField),
			("Enemy.Rigidbody", EnemyRigidbodyField),
			("Enemy.Health", EnemyHealthField),
			("Enemy.OnScreen", EnemyOnScreenField),
			("Enemy.PlayerDistance", EnemyPlayerDistanceField),
			("Enemy.PlayerRoom", EnemyPlayerRoomField),
			("Enemy.Grounded", EnemyGroundedField),
			("Enemy.Jump", EnemyJumpField),
			("Enemy.StateSpawn", EnemyStateSpawnField),
			("Enemy.StateInvestigate", EnemyStateInvestigateField),
			("Enemy.StateStunned", EnemyStateStunnedField),
			("Enemy.StateDespawn", EnemyStateDespawnField),
			("Enemy.TargetPlayerAvatar", EnemyTargetPlayerAvatar),
			("EnemyVision.onVisionTriggeredPlayer", EnemyVisionTriggeredPlayer),
			("EnemyVision.onVisionTriggeredDistance", EnemyVisionTriggeredDistance),
			("EnemyVision.onVisionTriggeredCulled", EnemyVisionTriggeredCulled),
			("EnemyStateInvestigate.onInvestigateTriggeredPosition", EnemyInvestigateTriggeredPosition),
			("EnemyHealth.healthCurrent", EnemyHealthCurrent),
			("EnemyHealth.dead", EnemyHealthDead),
			("EnemyHealth.renderers", EnemyHealthRenderers),
			("EnemyHealth.sharedMaterials", EnemyHealthSharedMaterials),
			("EnemyHealth.instancedMaterials", EnemyHealthInstancedMaterials),
			("EnemyHealth.materialHurtColor", EnemyHealthMaterialHurtColor),
			("EnemyHealth.materialHurtAmount", EnemyHealthMaterialHurtAmount),
			("EnemyHealth.hurtColor", EnemyHealthHurtColor),
			("EnemyNavMeshAgent.Agent", EnemyNavMeshAgentComponent),
			("EnemyRigidbody.rb", EnemyRigidbodyRb),
			("EnemyRigidbody.grabbed", EnemyRigidbodyGrabbed),
			("EnemyRigidbody.onGrabbedPlayerAvatar", EnemyRigidbodyOnGrabbedPlayer),
			("EnemyRigidbody.onTouchPlayerAvatar", EnemyRigidbodyOnTouchPlayer),
			("PlayerAvatar.playerName", PlayerAvatarName),
			("PlayerAvatar.steamID", PlayerAvatarSteamId),
			("PlayerAvatar.isLocal", PlayerAvatarIsLocal),
			("PlayerAvatar.deadSet", PlayerAvatarDeadSet),
			("PlayerAvatar.isDisabled", PlayerAvatarIsDisabled),
			("PlayerAvatar.isCrouching", PlayerAvatarIsCrouching),
			("PlayerAvatar.isSprinting", PlayerAvatarIsSprinting),
			("PlayerAvatar.voiceChat", PlayerAvatarVoiceChat),
			("PlayerAvatar.tumble", PlayerAvatarTumble),
			("PlayerAvatar.clientPosition", PlayerAvatarClientPosition),
			("PlayerAvatar.clientPositionCurrent", PlayerAvatarClientPositionCurrent),
			("ValuableObject.impactDetector", ValuableObjectImpactDetector),
			("ValuableObject.dollarValueCurrent", ValuableObjectDollarValueCurrent),
			("ValuableObject.rb", ValuableObjectRb),
			("ValuableObject.physGrabObject", ValuableObjectPhysGrabObject),
			("ValuableObject.committedToExtraction", ValuableObjectCommittedToExtraction),
			("PlayerVoiceChat.playerAvatar", PlayerVoiceChatAvatar),
			("PlayerVoiceChat.audioSource", PlayerVoiceChatAudioSource),
			("PlayerVoiceChat.isTalking", PlayerVoiceChatIsTalking),
			("PlayerVoiceChat.clipLoudness", PlayerVoiceChatClipLoudness),
			("PlayerAvatarVisuals.animator", PlayerAvatarVisualsAnimator),
			("PlayerAvatarVisuals.playerAvatarTalkAnimation", PlayerAvatarVisualsTalkAnim),
			("PlayerCosmetics.colorsEquipped", PlayerCosmeticsColorsEquipped),
			("PhysGrabber.currentlyLookingAtPhysGrabObject", PhysGrabberCurrentlyLookingAtPhysGrabObject),
			("PhysGrabber.grabbedPhysGrabObject", PhysGrabberGrabbedPhysGrabObject),
			("PhysGrabHinge.closed", PhysGrabHingeClosed),
			("PhysGrabHinge.closeDisableTimer", PhysGrabHingeCloseDisableTimer),
			("PhysGrabHinge.broken", PhysGrabHingeBroken),
			("PhysGrabHinge.dead", PhysGrabHingeDead),
			("PhysGrabHinge.joint", PhysGrabHingeJoint),
			("PhysGrabHinge.physGrabObject", PhysGrabHingePhysGrabObject)
		};

		public static int ValidateAll(Action<string> logWarning = null)
		{
			int num = 0;
			(string, FieldInfo)[] allFields = AllFields;
			for (int i = 0; i < allFields.Length; i++)
			{
				(string, FieldInfo) tuple = allFields[i];
				if (tuple.Item2 == null)
				{
					num++;
					logWarning?.Invoke("[RepoReflection] Missing expected field: " + tuple.Item1);
				}
			}
			if (PhysGrabHingeOpenImpulse == null)
			{
				num++;
				logWarning?.Invoke("[RepoReflection] Missing expected method: PhysGrabHinge.OpenImpulse");
			}
			return num;
		}

		public static T Get<T>(FieldInfo field, object instance, T fallback = default(T))
		{
			if (field == null || instance == null)
			{
				return fallback;
			}
			object value = field.GetValue(instance);
			if (value is T)
			{
				return (T)value;
			}
			return fallback;
		}

		public static void Set(FieldInfo field, object instance, object value)
		{
			if (field != null && instance != null)
			{
				field.SetValue(instance, value);
			}
		}

		public static string GetPlayerName(PlayerAvatar player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return "Unknown";
			}
			string text = Get<string>(PlayerAvatarName, player);
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
			return SemiFunc.PlayerGetName(player) ?? "Teammate";
		}

		public static string GetPlayerSteamId(PlayerAvatar player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return string.Empty;
			}
			string text = Get<string>(PlayerAvatarSteamId, player);
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
			return SemiFunc.PlayerGetSteamID(player) ?? string.Empty;
		}

		public static bool IsPlayerDeadOrDisabled(PlayerAvatar player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return true;
			}
			if (!Get(PlayerAvatarDeadSet, player, fallback: false))
			{
				return Get(PlayerAvatarIsDisabled, player, fallback: false);
			}
			return true;
		}

		public static bool IsPlayerLocal(PlayerAvatar player)
		{
			if ((Object)(object)player != (Object)null)
			{
				return Get(PlayerAvatarIsLocal, player, fallback: false);
			}
			return false;
		}

		public static bool IsPlayerCrouching(PlayerAvatar player)
		{
			if ((Object)(object)player != (Object)null)
			{
				return Get(PlayerAvatarIsCrouching, player, fallback: false);
			}
			return false;
		}

		public static bool IsPlayerSprinting(PlayerAvatar player)
		{
			if ((Object)(object)player != (Object)null)
			{
				return Get(PlayerAvatarIsSprinting, player, fallback: false);
			}
			return false;
		}

		public static NavMeshAgent GetNavAgent(EnemyNavMeshAgent wrapper)
		{
			return Get<NavMeshAgent>(EnemyNavMeshAgentComponent, wrapper);
		}

		public static PhotonView GetPhotonView(Enemy enemy)
		{
			return Get<PhotonView>(EnemyPhotonView, enemy);
		}

		public static EnemyParent GetEnemyParent(Enemy enemy)
		{
			return Get<EnemyParent>(EnemyEnemyParent, enemy);
		}

		public static bool IsMasterClient(Enemy enemy)
		{
			return Get(EnemyMasterClient, enemy, fallback: false);
		}

		public static PlayerTumble GetPlayerTumble(PlayerAvatar player)
		{
			return Get<PlayerTumble>(PlayerAvatarTumble, player);
		}

		public static PhysGrabObjectImpactDetector GetValuableImpactDetector(ValuableObject vo)
		{
			return Get<PhysGrabObjectImpactDetector>(ValuableObjectImpactDetector, vo);
		}

		public static float GetValuableDollarValue(ValuableObject vo)
		{
			return Get(ValuableObjectDollarValueCurrent, vo, 0f);
		}

		public static Rigidbody GetValuableRigidbody(ValuableObject vo)
		{
			return Get<Rigidbody>(ValuableObjectRb, vo);
		}

		public static PhysGrabObject GetValuablePhysGrabObject(ValuableObject vo)
		{
			return Get<PhysGrabObject>(ValuableObjectPhysGrabObject, vo);
		}

		public static bool IsValuableCommittedToExtraction(ValuableObject vo)
		{
			return Get(ValuableObjectCommittedToExtraction, vo, fallback: false);
		}
	}
}
namespace RepoMimicMod.Prefab
{
	public static class MimicPrefabFactory
	{
		public const string MimicResourcePath = "Enemies/Enemy - Mimic";

		private static readonly string[] PreferredSourceEnemyNames = new string[5] { "EnemyRunner", "EnemyHidden", "EnemySlowWalker", "EnemyValuableThrower", "EnemyHunter" };

		private static readonly HashSet<string> CoreEnemyComponentWhitelist = new HashSet<string>(StringComparer.Ordinal)
		{
			"EnemyParent", "Enemy", "EnemyNavMeshAgent", "EnemyRigidbody", "EnemyHealth", "EnemyVision", "EnemyOnScreen", "EnemyPlayerDistance", "EnemyPlayerRoom", "EnemyGrounded",
			"EnemyJump", "EnemyStateSpawn", "EnemyStateRoaming", "EnemyStateInvestigate", "EnemyStateChaseBegin", "EnemyStateChase", "EnemyStateChaseSlow", "EnemyStateChaseEnd", "EnemyStateLookUnder", "EnemyStateStunned",
			"EnemyStateDespawn", "EnemyAttackStuckPhysObject", "EnemyPitCheck"
		};

		private static GameObject _templateHolder;

		private static GameObject _mimicTemplate;

		private static EnemySetup _mimicSetup;

		public static GameObject MimicTemplate => _mimicTemplate;

		public static EnemySetup MimicSetup => _mimicSetup;

		public static bool EnsureRegistered()
		{
			if (!MimicConfig.Enabled.Value)
			{
				return false;
			}
			if ((Object)(object)_mimicTemplate == (Object)null && !BuildTemplate())
			{
				return false;
			}
			RegisterInPools();
			RegisterInEnemyDirector();
			return (Object)(object)_mimicTemplate != (Object)null;
		}

		private static bool BuildTemplate()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			GameObject val = FindBestSourcePrefab();
			if ((Object)(object)val == (Object)null)
			{
				ManualLogSource log = MimicPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"[MimicPrefabFactory] Could not find a suitable base enemy prefab yet.");
				}
				return false;
			}
			if ((Object)(object)_templateHolder == (Object)null)
			{
				_templateHolder = new GameObject("RepoMimicTemplateHolder");
				_templateHolder.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)_templateHolder);
			}
			GameObject obj = Object.Instantiate<GameObject>(val, _templateHolder.transform);
			((Object)obj).name = "Enemy - Mimic";
			obj.SetActive(true);
			StripSourceEnemyControllers(obj);
			PrunePhotonObservedComponents(obj);
			ResetCoreUnityEvents(obj);
			DisableTemplateVisuals(obj);
			ConfigureCoreComponents(obj);
			_mimicTemplate = obj;
			ManualLogSource log2 = MimicPlugin.Log;
			if (log2 != null)
			{
				log2.LogInfo((object)("[MimicPrefabFactory] Built Mimic template from '" + ((Object)val).name + "'."));
			}
			return true;
		}

		private static GameObject FindBestSourcePrefab()
		{
			EnemyDirector instance = EnemyDirector.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return null;
			}
			List<EnemySetup>[] array = new List<EnemySetup>[3] { instance.enemiesDifficulty2, instance.enemiesDifficulty1, instance.enemiesDifficulty3 };
			string[] preferredSourceEnemyNames = PreferredSourceEnemyNames;
			List<EnemySetup>[] array2;
			foreach (string typeName in preferredSourceEnemyNames)
			{
				array2 = array;
				foreach (List<EnemySetup> list in array2)
				{
					if (list == null)
					{
						continue;
					}
					foreach (EnemySetup item in list)
					{
						GameObject val = ExtractPrefabFromSetup(item);
						if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)_mimicTemplate) && HasComponentNamed(val, typeName) && HasRequiredChassis(val))
						{
							return val;
						}
					}
				}
			}
			array2 = array;
			foreach (List<EnemySetup> list2 in array2)
			{
				if (list2 == null)
				{
					continue;
				}
				foreach (EnemySetup item2 in list2)
				{
					GameObject val2 = ExtractPrefabFromSetup(item2);
					if ((Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)_mimicTemplate && HasRequiredChassis(val2))
					{
						return val2;
					}
				}
			}
			return null;
		}

		private static GameObject ExtractPrefabFromSetup(EnemySetup setup)
		{
			if ((Object)(object)setup == (Object)null || setup.spawnObjects == null)
			{
				return null;
			}
			foreach (PrefabRef spawnObject in setup.spawnObjects)
			{
				if (spawnObject != null)
				{
					GameObject prefab = ((PrefabRef<GameObject>)(object)spawnObject).Prefab;
					if ((Object)(object)prefab != (Object)null && (Object)(object)prefab.GetComponent<EnemyParent>() != (Object)null)
					{
						return prefab;
					}
				}
			}
			return null;
		}

		private static bool HasComponentNamed(GameObject root, string typeName)
		{
			MonoBehaviour[] componentsInChildren = root.GetComponentsInChildren<MonoBehaviour>(true);
			foreach (MonoBehaviour val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && string.Equals(((object)val).GetType().Name, typeName, StringComparison.Ordinal))
				{
					return true;
				}
			}
			return false;
		}

		private static bool HasRequiredChassis(GameObject root)
		{
			if ((Object)(object)root.GetComponent<EnemyParent>() != (Object)null && (Object)(object)root.GetComponentInChildren<Enemy>(true) != (Object)null && (Object)(object)root.GetComponentInChildren<EnemyNavMeshAgent>(true) != (Object)null && (Object)(object)root.GetComponentInChildren<EnemyRigidbody>(true) != (Object)null && (Object)(object)root.GetComponentInChildren<EnemyVision>(true) != (Object)null)
			{
				return (Object)(object)root.GetComponentInChildren<EnemyHealth>(true) != (Object)null;
			}
			return false;
		}

		private static void StripSourceEnemyControllers(GameObject root)
		{
			MonoBehaviour[] componentsInChildren = root.GetComponentsInChildren<MonoBehaviour>(true);
			foreach (MonoBehaviour val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null))
				{
					string name = ((object)val).GetType().Name;
					if (name.StartsWith("Enemy", StringComparison.Ordinal) && !CoreEnemyComponentWhitelist.Contains(name))
					{
						Object.DestroyImmediate((Object)(object)val);
					}
				}
			}
			HurtCollider[] componentsInChildren2 = root.GetComponentsInChildren<HurtCollider>(true);
			foreach (HurtCollider val2 in componentsInChildren2)
			{
				if ((Object)(object)val2 != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)val2);
				}
			}
		}

		private static void PrunePhotonObservedComponents(GameObject root)
		{
			PhotonView[] componentsInChildren = root.GetComponentsInChildren<PhotonView>(true);
			foreach (PhotonView val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null) && val.ObservedComponents != null)
				{
					val.ObservedComponents.RemoveAll((Component c) => (Object)(object)c == (Object)null);
				}
			}
		}

		private static void ResetCoreUnityEvents(GameObject root)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Expected O, but got Unknown
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected O, but got Unknown
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			EnemyVision componentInChildren = root.GetComponentInChildren<EnemyVision>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.onVisionTriggered = new UnityEvent();
			}
			EnemyStateInvestigate componentInChildren2 = root.GetComponentInChildren<EnemyStateInvestigate>(true);
			if ((Object)(object)componentInChildren2 != (Object)null)
			{
				componentInChildren2.onInvestigateTriggered = new UnityEvent();
			}
			EnemyStateSpawn componentInChildren3 = root.GetComponentInChildren<EnemyStateSpawn>(true);
			if ((Object)(object)componentInChildren3 != (Object)null)
			{
				componentInChildren3.OnSpawn = new UnityEvent();
			}
			EnemyStateDespawn componentInChildren4 = root.GetComponentInChildren<EnemyStateDespawn>(true);
			if ((Object)(object)componentInChildren4 != (Object)null)
			{
				componentInChildren4.OnDespawn = new UnityEvent();
			}
			EnemyStateStunned componentInChildren5 = root.GetComponentInChildren<EnemyStateStunned>(true);
			if ((Object)(object)componentInChildren5 != (Object)null)
			{
				componentInChildren5.onStunnedStart = new UnityEvent();
				componentInChildren5.onStunnedEnd = new UnityEvent();
			}
			EnemyHealth componentInChildren6 = root.GetComponentInChildren<EnemyHealth>(true);
			if ((Object)(object)componentInChildren6 != (Object)null)
			{
				componentInChildren6.onHurt = new UnityEvent();
				componentInChildren6.onDeathStart = new UnityEvent();
				componentInChildren6.onDeath = new UnityEvent();
				componentInChildren6.onObjectHurt = new UnityEvent();
			}
			EnemyRigidbody componentInChildren7 = root.GetComponentInChildren<EnemyRigidbody>(true);
			if ((Object)(object)componentInChildren7 != (Object)null)
			{
				componentInChildren7.onGrabbed = new UnityEvent();
				componentInChildren7.onTouchPlayer = new UnityEvent();
				componentInChildren7.onTouchPlayerGrabbedObject = new UnityEvent();
				componentInChildren7.onTouchPhysObject = new UnityEvent();
				componentInChildren7.onImpactLight = new UnityEvent();
				componentInChildren7.onImpactMedium = new UnityEvent();
				componentInChildren7.onImpactHeavy = new UnityEvent();
			}
		}

		private static void DisableTemplateVisuals(GameObject root)
		{
			Renderer[] componentsInChildren = root.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null)
				{
					val.enabled = false;
				}
			}
			ParticleSystem[] componentsInChildren2 = root.GetComponentsInChildren<ParticleSystem>(true);
			foreach (ParticleSystem val2 in componentsInChildren2)
			{
				if ((Object)(object)val2 != (Object)null)
				{
					val2.Stop(true, (ParticleSystemStopBehavior)0);
					GameObject gameObject = ((Component)val2).gameObject;
					if ((Object)(object)gameObject != (Object)(object)root)
					{
						gameObject.SetActive(false);
					}
				}
			}
			Animator[] componentsInChildren3 = root.GetComponentsInChildren<Animator>(true);
			foreach (Animator val3 in componentsInChildren3)
			{
				if ((Object)(object)val3 != (Object)null)
				{
					((Behaviour)val3).enabled = false;
				}
			}
		}

		private static void ConfigureCoreComponents(GameObject root)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			EnemyParent component = root.GetComponent<EnemyParent>();
			if ((Object)(object)component != (Object)null)
			{
				component.enemyName = string.Empty;
				component.enemyNameLocalized = null;
				component.difficulty = DifficultyFromTier(MimicConfig.DifficultyTier.Value);
				component.SpawnedTimeMin = 55f;
				component.SpawnedTimeMax = 105f;
				component.DespawnedTimeMin = 35f;
				component.DespawnedTimeMax = 75f;
			}
			Enemy componentInChildren = root.GetComponentInChildren<Enemy>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.Type = (EnemyType)2;
				componentInChildren.SightingStinger = false;
				componentInChildren.EnemyNearMusic = false;
				NavMeshAgent val = ((Component)componentInChildren).GetComponent<NavMeshAgent>() ?? ((Component)componentInChildren).GetComponentInChildren<NavMeshAgent>(true);
				if ((Object)(object)val != (Object)null)
				{
					val.radius = 0.32f;
					val.height = 1.25f;
					val.baseOffset = 0f;
					val.speed = MimicConfig.WalkSpeed.Value;
					val.acceleration = 32f;
					val.stoppingDistance = 0.2f;
					val.autoBraking = true;
					val.updateRotation = false;
				}
				EnemyNavMeshAgent val2 = ((Component)componentInChildren).GetComponent<EnemyNavMeshAgent>() ?? ((Component)componentInChildren).GetComponentInChildren<EnemyNavMeshAgent>(true);
				if ((Object)(object)val2 != (Object)null)
				{
					val2.updateRotation = false;
				}
				EnemyRigidbody val3 = ((Component)componentInChildren).GetComponent<EnemyRigidbody>() ?? ((Component)componentInChildren).GetComponentInChildren<EnemyRigidbody>(true);
				if ((Object)(object)val3 != (Object)null)
				{
					val3.positionSpeedIdle = 12f;
					val3.positionSpeedChase = 16f;
					val3.rotationSpeedIdle = 12f;
					val3.rotationSpeedChase = 16f;
				}
				EnemyHealth val4 = ((Component)componentInChildren).GetComponent<EnemyHealth>() ?? ((Component)componentInChildren).GetComponentInChildren<EnemyHealth>(true);
				if ((Object)(object)val4 != (Object)null)
				{
					val4.health = MimicConfig.MimicHealth.Value;
					val4.spawnValuable = true;
					val4.spawnValuableMax = 1;
					val4.meshParent = ((Component)componentInChildren).transform;
				}
				EnemyVision val5 = ((Component)componentInChildren).GetComponent<EnemyVision>() ?? ((Component)componentInChildren).GetComponentInChildren<EnemyVision>(true);
				if ((Object)(object)val5 != (Object)null)
				{
					val5.VisionDistance = 20f;
					val5.VisionDistanceClose = 6f;
					val5.VisionDistanceCloseCrouch = 3.5f;
					val5.VisionsToTrigger = 4;
					val5.VisionsToTriggerCrouch = 6;
					val5.VisionsToTriggerCrawl = 8;
				}
				((Component)componentInChildren).gameObject.AddComponent<MimicVisualController>();
				((Component)componentInChildren).gameObject.AddComponent<MimicVoiceEmitter>();
				((Component)componentInChildren).gameObject.AddComponent<EnemyMimic>();
			}
		}

		private static Difficulty DifficultyFromTier(int tier)
		{
			//IL_000b: 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_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			return (Difficulty)(tier switch
			{
				1 => 0, 
				3 => 2, 
				_ => 1, 
			});
		}

		private static void RegisterInPools()
		{
			if (!((Object)(object)_mimicTemplate == (Object)null) && !((Object)(object)RunManager.instance == (Object)null))
			{
				Dictionary<string, Object> dictionary = RepoReflection.Get<Dictionary<string, Object>>(RepoReflection.RunManagerSingleplayerPool, RunManager.instance);
				if (dictionary != null)
				{
					dictionary["Enemies/Enemy - Mimic"] = (Object)(object)_mimicTemplate;
				}
				MultiplayerPool val = RepoReflection.Get<MultiplayerPool>(RepoReflection.RunManagerMultiplayerPool, RunManager.instance);
				if (val != null && val.ResourceCache != null)
				{
					val.ResourceCache["Enemies/Enemy - Mimic"] = _mimicTemplate;
				}
			}
		}

		private static void RegisterInEnemyDirector()
		{
			//IL_0047: 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_007e: Expected O, but got Unknown
			if (!((Object)(object)_mimicTemplate == (Object)null) && !((Object)(object)EnemyDirector.instance == (Object)null))
			{
				if ((Object)(object)_mimicSetup == (Object)null)
				{
					_mimicSetup = ScriptableObject.CreateInstance<EnemySetup>();
					((Object)_mimicSetup).name = "EnemySetup - Mimic";
					_mimicSetup.status = (Status)1;
					RarityPreset val = ScriptableObject.CreateInstance<RarityPreset>();
					((Object)val).name = "Rarity - Mimic";
					val.chance = MimicConfig.SpawnRarityChance.Value;
					_mimicSetup.rarityPreset = val;
					PrefabRef val2 = new PrefabRef();
					((PrefabRef<GameObject>)(object)val2).SetPrefab(_mimicTemplate, "Enemies/Enemy - Mimic");
					_mimicSetup.spawnObjects = new List<PrefabRef> { val2 };
				}
				if ((Object)(object)_mimicSetup.rarityPreset != (Object)null)
				{
					_mimicSetup.rarityPreset.chance = MimicConfig.SpawnRarityChance.Value;
				}
				_mimicSetup.levelsCompletedCondition = MimicConfig.MinLevelsCompleted.Value > 0;
				_mimicSetup.levelsCompletedMin = MimicConfig.MinLevelsCompleted.Value;
				_mimicSetup.levelsCompletedMax = 999;
				int value = MimicConfig.DifficultyTier.Value;
				bool value2 = MimicConfig.AlsoSpawnInAdjacentTiers.Value;
				SyncSetupInList(EnemyDirector.instance.enemiesDifficulty1, value == 1 || (value2 && value == 2));
				SyncSetupInList(EnemyDirector.instance.enemiesDifficulty2, value == 2 || value2);
				SyncSetupInList(EnemyDirector.instance.enemiesDifficulty3, value == 3 || (value2 && value == 2));
			}
		}

		private static void SyncSetupInList(List<EnemySetup> list, bool shouldInclude)
		{
			if (list != null && !((Object)(object)_mimicSetup == (Object)null))
			{
				bool flag = list.Contains(_mimicSetup);
				if (shouldInclude && !flag)
				{
					list.Add(_mimicSetup);
				}
				else if (!shouldInclude && flag)
				{
					list.Remove(_mimicSetup);
				}
			}
		}
	}
}
namespace RepoMimicMod.Patches
{
	[HarmonyPatch(typeof(EnemyDirector))]
	public static class EnemyDirectorRegistrationPatch
	{
		[HarmonyPatch("AmountSetup")]
		[HarmonyPrefix]
		private static void AmountSetupPrefix()
		{
			if (MimicConfig.Enabled.Value)
			{
				MimicPrefabFactory.EnsureRegistered();
			}
		}
	}
	[HarmonyPatch(typeof(MultiplayerPool))]
	public static class MultiplayerPoolRegistrationPatch
	{
		[HarmonyPatch("InstantiateNew")]
		[HarmonyPrefix]
		private static void InstantiateNewPrefix(string prefabId)
		{
			if (prefabId == "Enemies/Enemy - Mimic")
			{
				MimicPrefabFactory.EnsureRegistered();
			}
		}
	}
	public static class MimicInteractionHelper
	{
		public static bool IsMimicObject(Component comp, out EnemyMimic mimic)
		{
			mimic = null;
			if ((Object)(object)comp == (Object)null)
			{
				return false;
			}
			mimic = comp.GetComponent<EnemyMimic>() ?? comp.GetComponentInParent<EnemyMimic>();
			if ((Object)(object)mimic != (Object)null)
			{
				return true;
			}
			EnemyParent componentInParent = comp.GetComponentInParent<EnemyParent>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				mimic = ((Component)componentInParent).GetComponentInChildren<EnemyMimic>(true);
			}
			return (Object)(object)mimic != (Object)null;
		}
	}
	[HarmonyPatch(typeof(PhysGrabber))]
	public static class PhysGrabberMimicPatches
	{
		[HarmonyPatch("StartGrabbingPhysObject")]
		[HarmonyPrefix]
		private static bool StartGrabbingPhysObjectPrefix(PhysGrabObject _physGrabObject)
		{
			if (MimicInteractionHelper.IsMimicObject((Component)(object)_physGrabObject, out var mimic) && !mimic.IsGrabbableLikePlayer)
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch("RayCheck")]
		[HarmonyPostfix]
		private static void RayCheckPostfix(PhysGrabber __instance)
		{
			if (!((Object)(object)__instance == (Object)null) && MimicInteractionHelper.IsMimicObject((Component)(object)RepoReflection.Get<PhysGrabObject>(RepoReflection.PhysGrabberCurrentlyLookingAtPhysGrabObject, __instance), out var mimic) && !mimic.IsGrabbableLikePlayer)
			{
				RepoReflection.Set(RepoReflection.PhysGrabberCurrentlyLookingAtPhysGrabObject, __instance, null);
			}
		}
	}
	[HarmonyPatch(typeof(Aim))]
	public static class AimMimicPatch
	{
		[HarmonyPatch("SetState")]
		[HarmonyPrefix]
		private static bool SetStatePrefix(State _state)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)_state == 1 && (Object)(object)PhysGrabber.instance != (Object)null && MimicInteractionHelper.IsMimicObject((Component)(object)RepoReflection.Get<PhysGrabObject>(RepoReflection.PhysGrabberCurrentlyLookingAtPhysGrabObject, PhysGrabber.instance), out var mimic) && !mimic.IsGrabbableLikePlayer)
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(EnemyRigidbody))]
	public static class EnemyRigidbodyMimicPatch
	{
		[HarmonyPatch("PhysGrabOverCharge")]
		[HarmonyPrefix]
		private static bool PhysGrabOverChargePrefix(EnemyRigidbody __instance)
		{
			if (MimicInteractionHelper.IsMimicObject((Component)(object)__instance, out var _))
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(ItemInfoUI))]
	public static class ItemInfoUiMimicPatch
	{
		[HarmonyPatch("ItemInfoText")]
		[HarmonyPrefix]
		private static bool ItemInfoTextPrefix(string message, bool enemy)
		{
			if (!enemy)
			{
				return true;
			}
			if (string.IsNullOrEmpty(message))
			{
				return false;
			}
			if ((Object)(object)PhysGrabber.instance != (Object)null)
			{
				if (MimicInteractionHelper.IsMimicObject((Component)(object)RepoReflection.Get<PhysGrabObject>(RepoReflection.PhysGrabberGrabbedPhysGrabObject, PhysGrabber.instance), out var mimic))
				{
					return false;
				}
				if (MimicInteractionHelper.IsMimicObject((Component)(object)RepoReflection.Get<PhysGrabObject>(RepoReflection.PhysGrabberCurrentlyLookingAtPhysGrabObject, PhysGrabber.instance), out mimic))
				{
					return false;
				}
			}
			return true;
		}
	}
}
namespace RepoMimicMod.Network
{
	public sealed class MimicNetworkSync : IOnEventCallback
	{
		private sealed class PendingClipAssembly
		{
			public int TotalChunks;

			public int ReceivedCount;

			public byte[][] Chunks;

			public string SpeakerSteamId;

			public string SpeakerName;
		}

		public const byte EventMimicState = 174;

		public const byte EventVoiceChunk = 175;

		public const byte EventVoicePlay = 176;

		private const int MaxChunkBytes = 6000;

		private readonly Dictionary<int, PendingClipAssembly> _incomingClips = new Dictionary<int, PendingClipAssembly>();

		private readonly HashSet<int> _broadcastedClipIds = new HashSet<int>();

		private readonly Dictionary<int, List<object[]>> _deferredVoicePlays = new Dictionary<int, List<object[]>>();

		private bool _registered;

		public static MimicNetworkSync Instance { get; } = new MimicNetworkSync();

		private MimicNetworkSync()
		{
		}

		public void Register()
		{
			if (!_registered)
			{
				PhotonNetwork.AddCallbackTarget((object)this);
				_registered = true;
			}
		}

		public void Unregister()
		{
			if (_registered)
			{
				PhotonNetwork.RemoveCallbackTarget((object)this);
				_registered = false;
			}
		}

		public void ClearSessionCaches()
		{
			_incomingClips.Clear();
			_broadcastedClipIds.Clear();
			_deferredVoicePlays.Clear();
		}

		public void BroadcastState(int mimicViewId, byte aiState, string disguiseSteamId, int disguisePlayerViewId, byte postureFlags, Vector3 lookTarget)
		{
			//IL_0047: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			if (SemiFunc.IsMultiplayer() && mimicViewId > 0)
			{
				object[] array = new object[8]
				{
					mimicViewId,
					aiState,
					disguiseSteamId ?? string.Empty,
					disguisePlayerViewId,
					postureFlags,
					lookTarget.x,
					lookTarget.y,
					lookTarget.z
				};
				RaiseEventOptions val = new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)0
				};
				PhotonNetwork.RaiseEvent((byte)174, (object)array, val, SendOptions.SendUnreliable);
			}
		}

		public void BroadcastVoicePlay(int mimicViewId, VoiceSnippet snippet, float pitch, bool distorted)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			if (!SemiFunc.IsMultiplayer() || !MimicConfig.SyncVoiceOverNetwork.Value || snippet == null || mimicViewId <= 0)
			{
				return;
			}
			RaiseEventOptions val = new RaiseEventOptions
			{
				Receivers = (ReceiverGroup)0
			};
			if (!_broadcastedClipIds.Contains(snippet.ClipId))
			{
				byte[] array = ImaAdpcmCodec.Encode(snippet.Samples, snippet.SampleRate);
				if (array.Length != 0)
				{
					int num = (array.Length + 6000 - 1) / 6000;
					for (int i = 0; i < num; i++)
					{
						int num2 = i * 6000;
						int num3 = Math.Min(6000, array.Length - num2);
						byte[] array2 = new byte[num3];
						Buffer.BlockCopy(array, num2, array2, 0, num3);
						object[] array3 = new object[6]
						{
							snippet.ClipId,
							num,
							i,
							snippet.SpeakerSteamId ?? string.Empty,
							snippet.SpeakerName ?? "Teammate",
							array2
						};
						PhotonNetwork.RaiseEvent((byte)175, (object)array3, val, SendOptions.SendReliable);
					}
					_broadcastedClipIds.Add(snippet.ClipId);
				}
			}
			object[] array4 = new object[5]
			{
				mimicViewId,
				snippet.ClipId,
				snippet.SpeakerSteamId ?? string.Empty,
				pitch,
				distorted
			};
			PhotonNetwork.RaiseEvent((byte)176, (object)array4, val, SendOptions.SendReliable);
		}

		public void OnEvent(EventData photonEvent)
		{
			if (photonEvent != null)
			{
				switch (photonEvent.Code)
				{
				case 174:
					HandleMimicStateEvent(photonEvent.CustomData as object[]);
					break;
				case 175:
					HandleVoiceChunkEvent(photonEvent.CustomData as object[]);
					break;
				case 176:
					HandleVoicePlayEvent(photonEvent.CustomData as object[]);
					break;
				}
			}
		}

		private void HandleMimicStateEvent(object[] data)
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			if (data == null || data.Length < 8)
			{
				return;
			}
			try
			{
				int num = Convert.ToInt32(data[0]);
				byte aiStateByte = Convert.ToByte(data[1]);
				string disguiseSteamId = (data[2] as string) ?? string.Empty;
				int disguisePlayerViewId = Convert.ToInt32(data[3]);
				byte postureFlags = Convert.ToByte(data[4]);
				float num2 = Convert.ToSingle(data[5]);
				float num3 = Convert.ToSingle(data[6]);
				float num4 = Convert.ToSingle(data[7]);
				PhotonView val = PhotonView.Find(num);
				if (!((Object)(object)val == (Object)null))
				{
					EnemyMimic componentInChildren = ((Component)val).GetComponentInChildren<EnemyMimic>(true);
					if (!((Object)(object)componentInChildren == (Object)null))
					{
						componentInChildren.ApplyNetworkState(aiStateByte, disguiseSteamId, disguisePlayerViewId, postureFlags, new Vector3(num2, num3, num4));
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = MimicPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[MimicNetworkSync] Failed to handle state event: " + ex.Message));
				}
			}
		}

		private void HandleVoiceChunkEvent(object[] data)
		{
			if (data == null || data.Length < 6)
			{
				return;
			}
			try
			{
				int num = Convert.ToInt32(data[0]);
				int num2 = Convert.ToInt32(data[1]);
				int num3 = Convert.ToInt32(data[2]);
				string speakerSteamId = (data[3] as string) ?? string.Empty;
				string speakerName = (data[4] as string) ?? "Teammate";
				byte[] array = data[5] as byte[];
				if (num2 <= 0 || num3 < 0 || num3 >= num2 || array == null)
				{
					return;
				}
				if (!_incomingClips.TryGetValue(num, out var value))
				{
					value = new PendingClipAssembly
					{
						TotalChunks = num2,
						Chunks = new byte[num2][],
						SpeakerSteamId = speakerSteamId,
						SpeakerName = speakerName
					};
					_incomingClips[num] = value;
				}
				if (value.Chunks[num3] == null)
				{
					value.Chunks[num3] = array;
					value.ReceivedCount++;
				}
				if (value.ReceivedCount < value.TotalChunks)
				{
					return;
				}
				_incomingClips.Remove(num);
				int num4 = 0;
				for (int i = 0; i < value.Chunks.Length; i++)
				{
					if (value.Chunks[i] == null)
					{
						return;
					}
					num4 += value.Chunks[i].Length;
				}
				byte[] array2 = new byte[num4];
				int num5 = 0;
				for (int j = 0; j < value.Chunks.Length; j++)
				{
					Buffer.BlockCopy(value.Chunks[j], 0, array2, num5, value.Chunks[j].Length);
					num5 += value.Chunks[j].Length;
				}
				int sampleRate;
				float[] samples = ImaAdpcmCodec.Decode(array2, out sampleRate);
				VoiceSnippetManager.Instance.RegisterRemoteSnippet(num, value.SpeakerSteamId, value.SpeakerName, sampleRate, samples);
				if (!_deferredVoicePlays.TryGetValue(num, out var value2))
				{
					return;
				}
				_deferredVoicePlays.Remove(num);
				foreach (object[] item in value2)
				{
					HandleVoicePlayEvent(item);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = MimicPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[MimicNetworkSync] Failed to handle voice chunk: " + ex.Message));
				}
			}
		}

		private void HandleVoicePlayEvent(object[] data)
		{
			if (data == null || data.Length < 5)
			{
				return;
			}
			try
			{
				int num = Convert.ToInt32(data[0]);
				int num2 = Convert.ToInt32(data[1]);
				float pitch = Convert.ToSingle(data[3]);
				bool distorted = Convert.ToBoolean(data[4]);
				VoiceSnippet snippetById = VoiceSnippetManager.Instance.GetSnippetById(num2);
				if (snippetById == null)
				{
					if (!_deferredVoicePlays.TryGetValue(num2, out var value))
					{
						value = new List<object[]>();
						_deferredVoicePlays[num2] = value;
					}
					if (value.Count < 4)
					{
						value.Add(data);
					}
					return;
				}
				PhotonView val = PhotonView.Find(num);
				if (!((Object)(object)val == (Object)null))
				{
					MimicVoiceEmitter componentInChildren = ((Component)val).GetComponentInChildren<MimicVoiceEmitter>(true);
					if (!((Object)(object)componentInChildren == (Object)null))
					{
						componentInChildren.PlaySnippet(snippetById, pitch, distorted);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = MimicPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[MimicNetworkSync] Failed to handle voice play: " + ex.Message));
				}
			}
		}
	}
}
namespace RepoMimicMod.Mimic
{
	public enum MimicAiState : byte
	{
		Spawn,
		BlendWithPlayers,
		WanderNearby,
		Investigate,
		SabotageValuable,
		HazardPush,
		Evade,
		Stunned,
		Retreat,
		Despawn,
		OpenDoor
	}
	internal enum BlendActivity : byte
	{
		SearchRoom,
		InspectValuable,
		CheckCart,
		HangWithTeammate,
		ScoutNearby,
		OpenContainer
	}
	public sealed class EnemyMimic : MonoBehaviour
	{
		private Enemy _enemy;

		private EnemyParent _enemyParent;

		private EnemyNavMeshAgent _navWrapper;

		private NavMeshAgent _unityNavAgent;

		private EnemyVision _vision;

		private EnemyHealth _health;

		private EnemyRigidbody _enemyRb;

		private PhysGrabObject _physGrabObject;

		private EnemyOnScreen _onScreen;

		private EnemyStateInvestigate _stateInvestigate;

		private EnemyStateSpawn _stateSpawn;

		private EnemyStateDespawn _stateDespawn;

		private PhotonView _photonView;

		private MimicVisualController _visuals;

		private MimicVoiceEmitter _voiceEmitter;

		private MimicAiState _state;

		private float _stateTimer;

		private float _voiceCooldownTimer = 4f;

		private float _sabotageCooldownTimer = 8f;

		private float _hazardPushCooldownTimer = 10f;

		private float _nextSabotageScanTime;

		private float _nextHazardScanTime;

		private float _blendPauseTimer;

		private float _nextPostureFlipTime;

		private float _nextNetworkSyncTime;

		private float _sabotageWindupTimer;

		private bool _sabotageExecuted;

		private float _stamina = 1f;

		private float _sprintBurstTimer;

		private float _sprintCooldownTimer;

		private BlendActivity _blendActivity;

		private float _activityTimer;

		private float _activityDuration = 8f;

		private int _activityStepsRemaining;

		private ValuableObject _inspectValuable;

		private PhysGrabCart _inspectCart;

		private PhysGrabHinge _inspectContainer;

		private Vector3 _containerTangentDir;

		private float _containerInitialAngle;

		private bool _containerUnlatched;

		private bool _containerFlippedDir;

		private bool _containerOpened;

		private float _containerOpenElapsed;

		private readonly RaycastHit[] _overheadHits = (RaycastHit[])(object)new RaycastHit[12];

		private float _clearanceCrouchHoldTimer;

		private LayerMask _overheadMask;

		private LayerMask _doorLayerMask;

		private Transform _selfRoot;

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

		private PhysGrabHinge _activeDoor;

		private MimicAiState _doorStateBefore = MimicAiState.BlendWithPlayers;

		private Vector3 _doorPushDir;

		private float _doorInitialAngle;

		private bool _doorUnlatched;

		private bool _doorFlippedDir;

		private Vector3 _desiredLookTarget;

		private float _nextGazeSweepTime;

		private float _gazeOffsetYaw;

		private float _gazeOffsetPitch;

		private bool _isCrouching;

		private bool _isSprinting;

		private bool _isFakeGrabbing;

		private Vector3 _grabTarget;

		private bool _hasDestination;

		private Vector3 _destination;

		private Vector3 _lookTarget;

		private PlayerAvatar _disguisePlayer;

		private string _disguiseSteamId = string.Empty;

		private int _disguisePlayerViewId;

		private PlayerAvatar _anchorPlayer;

		private Play