Decompiled source of BaconClips v1.0.0

BepInEx/plugins/BaconClips.dll

Decompiled 19 minutes ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Experimental.Rendering;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BaconClips
{
	[HarmonyPatch]
	internal static class ClipMoments
	{
		private const float GlobalCooldown = 4f;

		private const float KillWindow = 6f;

		private const float WitnessRange = 24f;

		private const float WitnessClose = 9f;

		private const float MineRange = 16f;

		private static readonly Dictionary<string, float> Cooldowns = new Dictionary<string, float>();

		private static readonly Dictionary<EnemyAI, float> LocalHits = new Dictionary<EnemyAI, float>();

		private static readonly HashSet<EnemyAI> ClippedKills = new HashSet<EnemyAI>();

		private static float _lastAny = -100f;

		private static float _nextTick;

		private static StartOfRound _round;

		private static bool ActiveMoon(out PlayerControllerB local)
		{
			local = Store.LocalPlayer;
			StartOfRound instance = StartOfRound.Instance;
			if (Settings.Enabled.Value && (Object)(object)instance != (Object)null && !instance.inShipPhase && instance.shipHasLanded && (Object)(object)local != (Object)null && local.isPlayerControlled)
			{
				return !local.isPlayerDead;
			}
			return false;
		}

		private static bool CanTrigger(string category, float cooldown)
		{
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime - _lastAny < 4f)
			{
				return false;
			}
			if (Cooldowns.TryGetValue(category, out var value) && unscaledTime < value)
			{
				return false;
			}
			Cooldowns[category] = unscaledTime + cooldown;
			_lastAny = unscaledTime;
			return true;
		}

		internal static void Tick()
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance != (Object)(object)_round || ((Object)(object)instance != (Object)null && instance.inShipPhase))
			{
				_round = instance;
				if ((Object)(object)instance == (Object)null || instance.inShipPhase)
				{
					LocalHits.Clear();
					ClippedKills.Clear();
					Cooldowns.Clear();
				}
			}
			else
			{
				if (Time.unscaledTime < _nextTick)
				{
					return;
				}
				_nextTick = Time.unscaledTime + 0.25f;
				if (!ActiveMoon(out var local) || LocalHits.Count == 0)
				{
					return;
				}
				float time = Time.time;
				List<EnemyAI> list = new List<EnemyAI>();
				foreach (KeyValuePair<EnemyAI, float> localHit in LocalHits)
				{
					EnemyAI key = localHit.Key;
					if ((Object)(object)key == (Object)null || time - localHit.Value > 6f)
					{
						list.Add(key);
					}
					else if (key.isEnemyDead && ClippedKills.Add(key))
					{
						list.Add(key);
						if (Settings.ClipKills.Value && CanTrigger("kill", 12f))
						{
							string text = CleanMonster(((Object)(object)key.enemyType != (Object)null) ? key.enemyType.enemyName : "MONSTER");
							Photo.Take(local, "KILLED " + text, 0.8f);
							Plugin.Log.LogInfo((object)("ClipMoments: captured monster kill (" + text + ")"));
						}
					}
				}
				foreach (EnemyAI item in list)
				{
					LocalHits.Remove(item);
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayerClientRpc")]
		private static void AfterCrewmateDeath(int playerId)
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			if (!Settings.ClipWitness.Value || !ActiveMoon(out var local))
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || playerId < 0 || playerId >= instance.allPlayerScripts.Length)
			{
				return;
			}
			PlayerControllerB val = instance.allPlayerScripts[playerId];
			if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)local) && !((Object)(object)local.gameplayCamera == (Object)null))
			{
				Transform transform = ((Component)local.gameplayCamera).transform;
				Vector3 val2 = (((Object)(object)val.deadBody != (Object)null) ? ((Component)val.deadBody).transform.position : (((Component)val).transform.position + Vector3.up * 1.2f));
				Vector3 val3 = val2 - transform.position;
				float magnitude = ((Vector3)(ref val3)).magnitude;
				if (!(magnitude > 24f) && (!(magnitude > 9f) || (!(Vector3.Dot(transform.forward, val3 / Mathf.Max(0.01f, magnitude)) < 0.28f) && !Physics.Linecast(transform.position, val2, instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))) && CanTrigger("witness", 8f))
				{
					string text = CleanName(val.playerUsername);
					Photo.Take(local, "SAW " + text + " DIE", 1f);
					Plugin.Log.LogInfo((object)$"ClipMoments: witnessed {text}'s death from {magnitude:0.0} m");
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "HitEnemyClientRpc")]
		private static void AfterEnemyHit(EnemyAI __instance, int playerWhoHit)
		{
			if (!((Object)(object)__instance == (Object)null) && ActiveMoon(out var local) && playerWhoHit == (int)local.playerClientId)
			{
				LocalHits[__instance] = Time.time;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlayerControllerB), "DamagePlayer")]
		private static void BeforeDamage(PlayerControllerB __instance, out int __state)
		{
			__state = (((Object)(object)__instance != (Object)null && (Object)(object)__instance == (Object)(object)Store.LocalPlayer && !__instance.isPlayerDead) ? __instance.health : (-1));
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "DamagePlayer")]
		private static void AfterDamage(PlayerControllerB __instance, int damageNumber, bool fallDamage, int __state)
		{
			if (!Settings.ClipCloseCalls.Value || __state <= 0 || (Object)(object)__instance == (Object)null || (Object)(object)__instance != (Object)(object)Store.LocalPlayer || __instance.isPlayerDead || !ActiveMoon(out var local))
			{
				return;
			}
			int num = __state - __instance.health;
			if (num >= 25)
			{
				if (__instance.health <= 20 && CanTrigger("closecall", 30f))
				{
					Photo.Take(local, $"CLOSE CALL ({__instance.health} HP)", 0.8f);
					Plugin.Log.LogInfo((object)$"ClipMoments: close call at {__instance.health} HP");
				}
				else if (fallDamage && num >= 35 && CanTrigger("fall", 25f))
				{
					Photo.Take(local, "BAD LANDING", 0.8f);
					Plugin.Log.LogInfo((object)$"ClipMoments: bad landing (-{num} HP)");
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Landmine), "SpawnExplosion")]
		private static void AfterExplosion(Vector3 explosionPosition)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if (Settings.ClipMines.Value && ActiveMoon(out var local))
			{
				float num = Vector3.Distance(((Component)local).transform.position, explosionPosition);
				if (!(num > 16f) && CanTrigger("mine", 20f))
				{
					Photo.Take(local, "MINE BLAST", 0.9f);
					Plugin.Log.LogInfo((object)$"ClipMoments: survived explosion {num:0.0} m away");
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(LungProp), "EquipItem")]
		private static void BeforeApparatus(LungProp __instance, out bool __state)
		{
			__state = (Object)(object)__instance != (Object)null && __instance.isLungDocked;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LungProp), "EquipItem")]
		private static void AfterApparatus(LungProp __instance, bool __state)
		{
			if (Settings.ClipSpecial.Value && __state && !((Object)(object)__instance == (Object)null) && ActiveMoon(out var local) && !((Object)(object)((GrabbableObject)__instance).playerHeldBy != (Object)(object)local) && CanTrigger("apparatus", 30f))
			{
				Photo.Take(local, "PULLED APPARATUS", 1f);
				Plugin.Log.LogInfo((object)"ClipMoments: pulled apparatus");
			}
		}

		internal static int Priority(string why)
		{
			if (string.IsNullOrEmpty(why))
			{
				return 50;
			}
			if (why.StartsWith("SAW ", StringComparison.OrdinalIgnoreCase))
			{
				return 95;
			}
			if (why == "SOLE SURVIVOR")
			{
				return 88;
			}
			if (why.StartsWith("KILLED ", StringComparison.OrdinalIgnoreCase))
			{
				return 85;
			}
			if (why == "MINE BLAST")
			{
				return 82;
			}
			if (why == "PULLED APPARATUS")
			{
				return 76;
			}
			if (why.StartsWith("CLOSE CALL", StringComparison.OrdinalIgnoreCase))
			{
				return 72;
			}
			if (why == "BAD LANDING")
			{
				return 68;
			}
			return 100;
		}

		private static string CleanName(string name)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				return "CREWMATE";
			}
			name = name.Trim().ToUpperInvariant().Replace("<", "")
				.Replace(">", "")
				.Replace(",", "")
				.Replace(";", "");
			if (name.Length <= 14)
			{
				return name;
			}
			return name.Substring(0, 14);
		}

		private static string CleanMonster(string name)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				return "MONSTER";
			}
			name = name.Trim().ToUpperInvariant().Replace("<", "")
				.Replace(">", "")
				.Replace(",", "")
				.Replace(";", "");
			if (name.Length <= 18)
			{
				return name;
			}
			return name.Substring(0, 18);
		}
	}
	internal static class ClipReel
	{
		private const float GatherAfterOrbitSolo = 1.2f;

		private const float GatherAfterOrbit = 2.2f;

		private const float GatherAfterLast = 0.8f;

		private const float GatherMax = 4.5f;

		private const float ReelEndPause = 1f;

		private const float DefaultClipSeconds = 5.1f;

		private const float TheaterWidth = 1520f;

		private const float TheaterHeight = 940f;

		private const float FrameWidth = 1280f;

		private const float FrameHeight = 768f;

		private static StartOfRound _hostRound;

		private static int _hostDay = -1;

		private static float _hostOrbitAt = -1f;

		private static float _hostLastClipAt = -1f;

		private static bool _hostStartedToday;

		private static bool _hostActive;

		private static bool _hostPaused;

		private static int _hostIndex;

		private static float _hostStepAt;

		private static float _hostPauseLeft;

		private static readonly HashSet<ulong> HostSkipVoters = new HashSet<ulong>();

		private static Canvas _canvas;

		private static RectTransform _frame;

		private static RectTransform _progressFill;

		private static RectTransform _pillsRow;

		private static RectTransform _controlsRow;

		private static RawImage _video;

		private static RawImage _scanlines;

		private static TextMeshProUGUI _header;

		private static TextMeshProUGUI _counter;

		private static TextMeshProUGUI _syncTag;

		private static TextMeshProUGUI _camName;

		private static TextMeshProUGUI _why;

		private static TextMeshProUGUI _meta;

		private static TextMeshProUGUI _loading;

		private static bool _active;

		private static bool _hidden;

		private static bool _waitingTerminal;

		private static bool _paused;

		private static bool _synced;

		private static bool _votedSkip;

		private static int _index;

		private static int _day;

		private static int _loadedIndex = -1;

		private static int _skipVotes;

		private static int _skipNeeded;

		private static float _clipStartedAt;

		private static float _clipDuration = 5.1f;

		private static bool _loadedSheet;

		private static StartOfRound _localRound;

		internal static bool IsOpen
		{
			get
			{
				if (_active && !_hidden && (Object)(object)_canvas != (Object)null)
				{
					return ((Component)_canvas).gameObject.activeSelf;
				}
				return false;
			}
		}

		internal static void HostClipAdded()
		{
			_hostLastClipAt = Time.unscaledTime;
		}

		internal static void HostReset(StartOfRound round)
		{
			int num = (((Object)(object)round != (Object)null && round.gameStats != null) ? round.gameStats.daysSpent : (-1));
			if (!((Object)(object)round == (Object)(object)_hostRound) || num != _hostDay)
			{
				_hostRound = round;
				_hostDay = num;
				_hostOrbitAt = -1f;
				_hostLastClipAt = -1f;
				_hostStartedToday = false;
				HostSkipVoters.Clear();
				if (_hostActive)
				{
					HostEnd();
				}
			}
		}

		internal static void HostTick(StartOfRound round)
		{
			if (!Store.IsHost || (Object)(object)round == (Object)null)
			{
				return;
			}
			if (!round.inShipPhase)
			{
				if (_hostActive)
				{
					HostEnd();
				}
				_hostOrbitAt = -1f;
				return;
			}
			HostReset(round);
			if (((round.gameStats != null && round.gameStats.daysSpent != 0) ? 1 : 0) <= (false ? 1 : 0))
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (_hostOrbitAt < 0f)
			{
				_hostOrbitAt = unscaledTime;
			}
			if (_hostActive)
			{
				if (DayClips.HostedCount == 0)
				{
					HostEnd();
				}
				else if (!_hostPaused && unscaledTime >= _hostStepAt)
				{
					if (_hostIndex + 1 < DayClips.HostedCount)
					{
						HostShow(_hostIndex + 1);
					}
					else
					{
						HostEnd();
					}
				}
			}
			else
			{
				if (!Settings.ClipReel.Value || _hostStartedToday || DayClips.HostedCount == 0 || round.firingPlayersCutsceneRunning || ((Object)(object)HUDManager.Instance != (Object)null && HUDManager.Instance.displayingNewQuota))
				{
					return;
				}
				TimeOfDay instance = TimeOfDay.Instance;
				if ((!((Object)(object)instance != (Object)null) || round.isChallengeFile || instance.profitQuota <= 0 || instance.quotaFulfilled < instance.profitQuota) && (!((Object)(object)instance != (Object)null) || !(instance.timeUntilDeadline <= 0f) || instance.quotaFulfilled >= instance.profitQuota))
				{
					float num = Mathf.Clamp(Settings.ReelDelay.Value, 1, 8);
					float num2 = (Share.CrewHere ? num : Mathf.Max(0.8f, num * 0.55f));
					float num3 = Mathf.Max(4.5f, num + 2.5f);
					bool num4 = unscaledTime - _hostOrbitAt >= num2 && (_hostLastClipAt < 0f || unscaledTime - _hostLastClipAt >= 0.8f);
					bool flag = unscaledTime - _hostOrbitAt >= num3;
					if (num4 || flag)
					{
						HostStart();
					}
				}
			}
		}

		internal static void HostStart(int startIndex = 0)
		{
			if (Store.IsHost && DayClips.HostedCount != 0)
			{
				StartOfRound instance = StartOfRound.Instance;
				int num = (((Object)(object)instance != (Object)null && instance.gameStats != null) ? instance.gameStats.daysSpent : 0);
				_hostStartedToday = true;
				_hostActive = true;
				_hostPaused = false;
				_hostIndex = Mathf.Clamp(startIndex, 0, DayClips.HostedCount - 1);
				HostSkipVoters.Clear();
				float num2 = EstimateDuration(_hostIndex);
				_hostStepAt = Time.unscaledTime + num2;
				Net.BroadcastReel(new ReelPacket
				{
					Action = "play",
					Index = _hostIndex,
					Day = num,
					Duration = num2
				});
				Plugin.Log.LogInfo((object)$"ClipReel: host started Day {num} reel ({DayClips.HostedCount} clip(s))");
			}
		}

		internal static void HostShow(int index)
		{
			if (Store.IsHost && _hostActive && DayClips.HostedCount != 0)
			{
				_hostIndex = Mathf.Clamp(index, 0, DayClips.HostedCount - 1);
				_hostPaused = false;
				HostSkipVoters.Clear();
				float num = EstimateDuration(_hostIndex);
				_hostStepAt = Time.unscaledTime + num;
				Net.BroadcastReel(new ReelPacket
				{
					Action = "step",
					Index = _hostIndex,
					Duration = num
				});
			}
		}

		internal static void HostTogglePause()
		{
			if (Store.IsHost && _hostActive)
			{
				_hostPaused = !_hostPaused;
				if (_hostPaused)
				{
					_hostPauseLeft = Mathf.Max(1.5f, _hostStepAt - Time.unscaledTime);
				}
				else
				{
					_hostStepAt = Time.unscaledTime + Mathf.Max(1.5f, _hostPauseLeft);
				}
				Net.BroadcastReel(new ReelPacket
				{
					Action = (_hostPaused ? "pause" : "resume"),
					Index = _hostIndex
				});
			}
		}

		internal static void HostSkipVote(ulong sender, int clipIndex)
		{
			if (!Store.IsHost || !_hostActive || clipIndex != _hostIndex)
			{
				return;
			}
			if (sender == 0L)
			{
				if (_hostIndex + 1 < DayClips.HostedCount)
				{
					HostShow(_hostIndex + 1);
				}
				else
				{
					HostEnd();
				}
			}
			else
			{
				if (!HostSkipVoters.Add(sender))
				{
					return;
				}
				NetworkManager singleton = NetworkManager.Singleton;
				int num = ((!((Object)(object)singleton != (Object)null)) ? 1 : Mathf.Max(1, singleton.ConnectedClientsIds.Count));
				int num2 = Mathf.Max(1, (num + 1) / 2);
				if (HostSkipVoters.Count >= num2)
				{
					if (_hostIndex + 1 < DayClips.HostedCount)
					{
						HostShow(_hostIndex + 1);
					}
					else
					{
						HostEnd();
					}
				}
				else
				{
					Net.BroadcastReel(new ReelPacket
					{
						Action = "votes",
						Index = _hostIndex,
						Votes = HostSkipVoters.Count,
						Needed = num2
					});
				}
			}
		}

		internal static void HostEnd()
		{
			if (Store.IsHost)
			{
				_hostActive = false;
				_hostPaused = false;
				HostSkipVoters.Clear();
				Net.BroadcastReel(new ReelPacket
				{
					Action = "end"
				});
				Plugin.Log.LogInfo((object)"ClipReel: host ended reel");
			}
		}

		private static float EstimateDuration(int index)
		{
			float num = Mathf.Clamp(Settings.ReelPause.Value, 0, 4);
			if (index >= 0 && index < DayClips.Clips.Count)
			{
				DayClips.Entry entry = DayClips.Clips[index];
				ClipRecord clipRecord = (entry.Mine ? DayClips.OwnFile(entry) : null);
				if (clipRecord != null && clipRecord.Frames > 1 && clipRecord.Fps > 0)
				{
					return (float)clipRecord.Frames / (float)clipRecord.Fps + num;
				}
				CrewClip crewClip = DayClips.Crew(entry);
				if (crewClip != null && crewClip.Frames > 1 && crewClip.Fps > 0)
				{
					return (float)crewClip.Frames / (float)crewClip.Fps + num;
				}
			}
			return 4.1f + num;
		}

		private static bool InTerminal()
		{
			PlayerControllerB localPlayer = Store.LocalPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				return localPlayer.inTerminalMenu;
			}
			return false;
		}

		private static void LeaveTerminalAndMenus()
		{
			PlayerControllerB localPlayer = Store.LocalPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			if (localPlayer.inTerminalMenu)
			{
				Terminal val = Object.FindObjectOfType<Terminal>();
				if ((Object)(object)val != (Object)null)
				{
					try
					{
						val.QuitTerminal(true);
					}
					catch (Exception ex)
					{
						Plugin.Log.LogInfo((object)("ClipReel: QuitTerminal: " + ex.Message));
					}
				}
			}
			if (!((Object)(object)localPlayer.quickMenuManager != (Object)null) || !((Object)(object)localPlayer.quickMenuManager.menuContainer != (Object)null) || !localPlayer.quickMenuManager.menuContainer.activeSelf)
			{
				return;
			}
			try
			{
				localPlayer.quickMenuManager.CloseQuickMenu();
			}
			catch (Exception)
			{
			}
		}

		internal static void OnPacket(ReelPacket pkt)
		{
			if (pkt == null)
			{
				return;
			}
			switch (pkt.Action)
			{
			case "play":
				_day = ((pkt.Day > 0) ? pkt.Day : (StartOfRound.Instance?.gameStats?.daysSpent).GetValueOrDefault());
				_synced = true;
				_hidden = false;
				_waitingTerminal = false;
				_paused = false;
				_active = true;
				_index = pkt.Index;
				_skipVotes = (_skipNeeded = 0);
				_votedSkip = false;
				_clipDuration = ((pkt.Duration > 1f) ? pkt.Duration : 5.1f);
				_clipStartedAt = Time.unscaledTime;
				_loadedIndex = -1;
				_loadedSheet = false;
				if (!Settings.ClipReel.Value)
				{
					_hidden = true;
				}
				else if (!Settings.ReelKickTerminal.Value && InTerminal())
				{
					_hidden = true;
					_waitingTerminal = true;
				}
				else
				{
					ShowUI();
				}
				break;
			case "step":
				if (_active)
				{
					_index = pkt.Index;
					_paused = false;
					_skipVotes = (_skipNeeded = 0);
					_votedSkip = false;
					_clipDuration = ((pkt.Duration > 1f) ? pkt.Duration : 5.1f);
					_clipStartedAt = Time.unscaledTime;
					_loadedIndex = -1;
					_loadedSheet = false;
					if (IsOpen)
					{
						RefreshClip();
					}
				}
				break;
			case "votes":
				if (_active && pkt.Index == _index)
				{
					_skipVotes = pkt.Votes;
					_skipNeeded = pkt.Needed;
					if (IsOpen)
					{
						RebuildControls();
					}
				}
				break;
			case "pause":
				_paused = true;
				ApplyPause();
				if (IsOpen)
				{
					RebuildControls();
				}
				break;
			case "resume":
				_paused = false;
				ApplyPause();
				if (IsOpen)
				{
					RebuildControls();
				}
				break;
			case "end":
				CloseUI(endAll: true);
				break;
			}
		}

		internal static void OpenLocal(int startIndex = 0)
		{
			if (DayClips.Clips.Count != 0)
			{
				if (Store.IsHost && Share.CrewHere)
				{
					HostStart(startIndex);
					return;
				}
				StartOfRound instance = StartOfRound.Instance;
				_day = (((Object)(object)instance != (Object)null && instance.gameStats != null) ? instance.gameStats.daysSpent : 0);
				_synced = false;
				_hidden = false;
				_paused = false;
				_active = true;
				_skipVotes = (_skipNeeded = 0);
				_votedSkip = false;
				_index = Mathf.Clamp(startIndex, 0, DayClips.Clips.Count - 1);
				_clipDuration = EstimateDuration(_index);
				_clipStartedAt = Time.unscaledTime;
				_loadedIndex = -1;
				_loadedSheet = false;
				ShowUI();
			}
		}

		internal static void OnClipReceived()
		{
			if (IsOpen && !_loadedSheet)
			{
				RefreshClip();
			}
		}

		internal static void Tick()
		{
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance != (Object)(object)_localRound || (Object)(object)instance == (Object)null || !instance.inShipPhase)
			{
				_localRound = instance;
				_hidden = false;
				_waitingTerminal = false;
				if (_active)
				{
					CloseUI(endAll: true);
				}
			}
			else if (_active && _waitingTerminal)
			{
				if (!InTerminal())
				{
					_waitingTerminal = false;
					_hidden = false;
					ShowUI();
				}
			}
			else
			{
				if (!IsOpen)
				{
					return;
				}
				PlayerControllerB localPlayer = Store.LocalPlayer;
				if ((Object)(object)localPlayer != (Object)null && localPlayer.inTerminalMenu)
				{
					if (!Settings.ReelKickTerminal.Value)
					{
						_hidden = true;
						_waitingTerminal = true;
						if ((Object)(object)_canvas != (Object)null)
						{
							((Component)_canvas).gameObject.SetActive(false);
						}
						return;
					}
					LeaveTerminalAndMenus();
				}
				if ((int)Cursor.lockState != 0 || !Cursor.visible)
				{
					Cursor.lockState = (CursorLockMode)0;
					Cursor.visible = true;
				}
				Keyboard current = Keyboard.current;
				if (current != null && ((ButtonControl)current.escapeKey).wasPressedThisFrame)
				{
					HideLocal();
					return;
				}
				if (current != null)
				{
					if (Store.IsHost || !_synced)
					{
						if (((ButtonControl)current.rightArrowKey).wasPressedThisFrame || ((ButtonControl)current.dKey).wasPressedThisFrame)
						{
							Next();
						}
						else if (((ButtonControl)current.leftArrowKey).wasPressedThisFrame || ((ButtonControl)current.aKey).wasPressedThisFrame)
						{
							Prev();
						}
						else if (((ButtonControl)current.spaceKey).wasPressedThisFrame)
						{
							TogglePause();
						}
					}
					else if (((ButtonControl)current.spaceKey).wasPressedThisFrame || ((ButtonControl)current.rightArrowKey).wasPressedThisFrame)
					{
						VoteSkip();
					}
				}
				if (!_synced && !_paused && Time.unscaledTime - _clipStartedAt >= _clipDuration)
				{
					if (_index + 1 < DayClips.Clips.Count)
					{
						_index++;
						_clipDuration = EstimateDuration(_index);
						_clipStartedAt = Time.unscaledTime;
						_loadedIndex = -1;
						_loadedSheet = false;
						RefreshClip();
					}
					else
					{
						CloseUI(endAll: true);
					}
				}
				if ((Object)(object)_progressFill != (Object)null)
				{
					ClipPlayer clipPlayer = (((Object)(object)_video != (Object)null) ? ((Component)_video).GetComponent<ClipPlayer>() : null);
					float num = (((Object)(object)clipPlayer != (Object)null && _loadedSheet) ? clipPlayer.Progress : Mathf.Clamp01((Time.unscaledTime - _clipStartedAt) / Mathf.Max(0.1f, _clipDuration)));
					_progressFill.anchorMax = new Vector2(num, 1f);
				}
				if ((Object)(object)_header != (Object)null)
				{
					string text = ((Mathf.Repeat(Time.unscaledTime * 1.4f, 1f) < 0.65f) ? "<color=#FF4444>●</color> " : "<color=#551111>●</color> ");
					string text2 = ((_day > 0) ? $"DAY {_day}" : "TODAY");
					((TMP_Text)_header).text = text + "CREW CLIP REEL  ·  " + text2;
				}
				if (_loadedIndex != _index || !_loadedSheet)
				{
					RefreshClip();
				}
			}
		}

		private static void Next()
		{
			if (DayClips.Clips.Count == 0)
			{
				return;
			}
			if (_synced && Store.IsHost)
			{
				if (_index + 1 < DayClips.Clips.Count)
				{
					HostShow(_index + 1);
				}
				else
				{
					HostEnd();
				}
			}
			else if (!_synced)
			{
				if (_index + 1 < DayClips.Clips.Count)
				{
					_index++;
					_clipDuration = EstimateDuration(_index);
					_clipStartedAt = Time.unscaledTime;
					_loadedIndex = -1;
					_loadedSheet = false;
					RefreshClip();
				}
				else
				{
					CloseUI(endAll: true);
				}
			}
		}

		private static void Prev()
		{
			if (DayClips.Clips.Count != 0)
			{
				int index = Mathf.Max(0, _index - 1);
				if (_synced && Store.IsHost)
				{
					HostShow(index);
				}
				else if (!_synced)
				{
					_index = index;
					_clipDuration = EstimateDuration(_index);
					_clipStartedAt = Time.unscaledTime;
					_loadedIndex = -1;
					_loadedSheet = false;
					RefreshClip();
				}
			}
		}

		private static void VoteSkip()
		{
			if (!_votedSkip)
			{
				_votedSkip = true;
				Net.SendSkipVote(_index);
				RebuildControls();
			}
		}

		private static void TogglePause()
		{
			if (_synced && Store.IsHost)
			{
				HostTogglePause();
			}
			else if (!_synced)
			{
				_paused = !_paused;
				ApplyPause();
				RebuildControls();
			}
		}

		private static void SaveCurrentClip()
		{
			List<DayClips.Entry> clips = DayClips.Clips;
			if (_index < 0 || _index >= clips.Count)
			{
				return;
			}
			DayClips.Entry entry = clips[_index];
			if (!entry.Mine)
			{
				CrewClip crewClip = DayClips.Crew(entry);
				if (crewClip != null && !crewClip.Saved && Photo.SaveFromCrew(crewClip))
				{
					RebuildControls();
				}
			}
		}

		private static void ApplyPause()
		{
			ClipPlayer clipPlayer = (((Object)(object)_video != (Object)null) ? ((Component)_video).GetComponent<ClipPlayer>() : null);
			if ((Object)(object)clipPlayer != (Object)null)
			{
				clipPlayer.SetPaused(_paused);
			}
		}

		internal static void HideLocal()
		{
			_hidden = true;
			if ((Object)(object)_canvas != (Object)null)
			{
				((Component)_canvas).gameObject.SetActive(false);
			}
			RestoreCursor();
		}

		private static void CloseUI(bool endAll)
		{
			bool num = (Object)(object)_canvas != (Object)null && ((Component)_canvas).gameObject.activeSelf;
			if (endAll)
			{
				_active = false;
			}
			_hidden = true;
			if ((Object)(object)_canvas != (Object)null)
			{
				((Component)_canvas).gameObject.SetActive(false);
			}
			if (num)
			{
				RestoreCursor();
			}
		}

		internal static void SceneGone()
		{
			_active = false;
			_hostActive = false;
			_hidden = true;
			if ((Object)(object)_canvas != (Object)null)
			{
				((Component)_canvas).gameObject.SetActive(false);
			}
		}

		private static void RestoreCursor()
		{
			if (!Gallery.IsOpen && (Settings.ReelKickTerminal.Value || !InTerminal()))
			{
				PlayerControllerB localPlayer = Store.LocalPlayer;
				if ((Object)(object)localPlayer != (Object)null && (Object)(object)localPlayer.quickMenuManager != (Object)null)
				{
					localPlayer.quickMenuManager.isMenuOpen = false;
				}
				Cursor.lockState = (CursorLockMode)1;
				Cursor.visible = false;
			}
		}

		private static void ShowUI()
		{
			if (Gallery.IsOpen)
			{
				Gallery.CloseImmediate();
			}
			LeaveTerminalAndMenus();
			EnsureBuilt();
			((Component)_canvas).gameObject.SetActive(true);
			PlayerControllerB localPlayer = Store.LocalPlayer;
			if ((Object)(object)localPlayer != (Object)null && (Object)(object)localPlayer.quickMenuManager != (Object)null)
			{
				localPlayer.quickMenuManager.isMenuOpen = true;
			}
			Cursor.lockState = (CursorLockMode)0;
			Cursor.visible = true;
			RefreshClip();
		}

		private static void EnsureBuilt()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0313: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03be: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_041a: Unknown result type (might be due to invalid IL or missing references)
			//IL_045a: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a0: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_canvas != (Object)null))
			{
				Ui.Prepare();
				_canvas = Ui.Canvas("BaconClips Reel", 95);
				Object.DontDestroyOnLoad((Object)(object)((Component)_canvas).gameObject);
				Image obj = Ui.Panel(((Component)_canvas).transform, "Shade", new Color(0f, 0f, 0f, 0.93f));
				((Graphic)obj).raycastTarget = true;
				Ui.Stretch(((Graphic)obj).rectTransform);
				_frame = Ui.Empty((Transform)(object)Ui.Root(((Component)_canvas).transform, "Root"), "Theater");
				RectTransform frame = _frame;
				RectTransform frame2 = _frame;
				RectTransform frame3 = _frame;
				Vector2 val = default(Vector2);
				((Vector2)(ref val))..ctor(0.5f, 0.5f);
				frame3.pivot = val;
				Vector2 anchorMin = (frame2.anchorMax = val);
				frame.anchorMin = anchorMin;
				_frame.sizeDelta = new Vector2(1520f, 940f);
				_frame.anchoredPosition = Vector2.zero;
				Ui.Stretch(((Graphic)Ui.Panel((Transform)(object)_frame, "Bg", Ui.Window)).rectTransform);
				Ui.Frame((Transform)(object)_frame, Ui.Main, 2f);
				float num = 120f;
				_header = Ui.Place<TextMeshProUGUI>(Ui.Label((Transform)(object)_frame, "CREW CLIP REEL", 24f, Ui.Main, (TextAlignmentOptions)257), num, 16f, 760f, 32f);
				((TMP_Text)_header).characterSpacing = 3f;
				_counter = Ui.Place<TextMeshProUGUI>(Ui.Label((Transform)(object)_frame, "CLIP 1 / 1", 20f, Ui.Ink, (TextAlignmentOptions)260), 1520f - num - 420f, 16f, 420f, 26f);
				((TMP_Text)_counter).characterSpacing = 2f;
				_syncTag = Ui.Place<TextMeshProUGUI>(Ui.Label((Transform)(object)_frame, "", 13f, Ui.InkSoft, (TextAlignmentOptions)260), 1520f - num - 520f, 42f, 520f, 18f);
				((TMP_Text)_syncTag).characterSpacing = 2f;
				float num2 = 66f;
				Image obj2 = Ui.Place<Image>(Ui.Panel((Transform)(object)_frame, "VideoFrame", new Color(0.02f, 0.02f, 0.02f, 1f)), num, num2, 1280f, 768f);
				Ui.Frame(((Component)obj2).transform, Ui.Line, 2f);
				_video = ((Component)Ui.Empty(((Component)obj2).transform, "Video")).gameObject.AddComponent<RawImage>();
				((Graphic)_video).raycastTarget = false;
				Ui.Stretch(((Graphic)_video).rectTransform);
				_scanlines = ((Component)Ui.Empty(((Component)obj2).transform, "Scanlines")).gameObject.AddComponent<RawImage>();
				_scanlines.texture = (Texture)(object)Ui.Scanline();
				((Graphic)_scanlines).color = new Color(0f, 0f, 0f, 0.18f);
				_scanlines.uvRect = new Rect(0f, 0f, 1f, 192f);
				((Graphic)_scanlines).raycastTarget = false;
				Ui.Stretch(((Graphic)_scanlines).rectTransform);
				_loading = Ui.Label(((Component)obj2).transform, "LOADING CLIP...", 24f, Ui.InkSoft, (TextAlignmentOptions)514);
				Ui.Stretch(((TMP_Text)_loading).rectTransform);
				_progressFill = ((Graphic)Ui.Panel(((Component)Ui.Place<Image>(Ui.Panel((Transform)(object)_frame, "ProgressTrack", Ui.Track), num, num2 + 768f + 6f, 1280f, 7f)).transform, "ProgressFill", Ui.Main)).rectTransform;
				_progressFill.anchorMin = Vector2.zero;
				_progressFill.anchorMax = new Vector2(0f, 1f);
				RectTransform progressFill = _progressFill;
				anchorMin = (_progressFill.offsetMax = Vector2.zero);
				progressFill.offsetMin = anchorMin;
				float num3 = num2 + 768f + 20f;
				_camName = Ui.Place<TextMeshProUGUI>(Ui.Label((Transform)(object)_frame, "", 22f, Ui.Ink, (TextAlignmentOptions)257), num, num3, 520f, 28f);
				((TMP_Text)_camName).overflowMode = (TextOverflowModes)1;
				_why = Ui.Place<TextMeshProUGUI>(Ui.Label((Transform)(object)_frame, "", 19f, Ui.Warn, (TextAlignmentOptions)257), num, num3 + 28f, 520f, 24f);
				((TMP_Text)_why).overflowMode = (TextOverflowModes)1;
				_meta = Ui.Place<TextMeshProUGUI>(Ui.Label((Transform)(object)_frame, "", 15f, Ui.InkSoft, (TextAlignmentOptions)260), num + 540f, num3 + 2f, 740f, 22f);
				((TMP_Text)_meta).overflowMode = (TextOverflowModes)1;
				_pillsRow = Ui.Place(Ui.Empty((Transform)(object)_frame, "Pills"), num, 904f, 420f, 20f);
				_controlsRow = Ui.Place(Ui.Empty((Transform)(object)_frame, "Controls"), num + 440f, 886f, 840f, 40f);
			}
		}

		private static void RefreshClip()
		{
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_canvas == (Object)null)
			{
				return;
			}
			List<DayClips.Entry> clips = DayClips.Clips;
			if (clips.Count == 0)
			{
				CloseUI(endAll: true);
				return;
			}
			_index = Mathf.Clamp(_index, 0, clips.Count - 1);
			DayClips.Entry entry = clips[_index];
			_loadedIndex = _index;
			((TMP_Text)_counter).text = $"CLIP {_index + 1} / {clips.Count}";
			bool canControl = Store.IsHost || !_synced;
			((TMP_Text)_syncTag).text = ((!_synced) ? "REPLAY MODE" : (Store.IsHost ? "SYNCED WITH CREW  ·  HOST CONTROLS" : "WATCHING TOGETHER  ·  SYNCED WITH HOST"));
			string text = entry.Name.ToUpperInvariant();
			((TMP_Text)_camName).text = (entry.Mine ? (text + "'S CAM  (YOU)") : (text + "'S CAM"));
			((TMP_Text)_why).text = entry.Why;
			string dot = Ui.Dot;
			ClipRecord clipRecord = (entry.Mine ? DayClips.OwnFile(entry) : null);
			CrewClip crewClip = (entry.Mine ? null : DayClips.Crew(entry));
			if (clipRecord != null)
			{
				((TMP_Text)_meta).text = string.Format("D{0}{1}{2}", clipRecord.Day, (clipRecord.Clock != "") ? (" " + dot + " " + clipRecord.Clock) : "", (clipRecord.Moon != "") ? (" " + dot + " " + clipRecord.Moon) : "");
			}
			else if (crewClip != null)
			{
				((TMP_Text)_meta).text = crewClip.Caption;
			}
			else
			{
				((TMP_Text)_meta).text = ((!string.IsNullOrEmpty(entry.Moon)) ? (entry.Clock + " " + dot + " " + entry.Moon) : "");
			}
			bool flag = false;
			if (clipRecord != null)
			{
				flag = Clips.Play(_video, clipRecord, loop: false);
			}
			else if (crewClip != null && (Object)(object)crewClip.Sheet != (Object)null)
			{
				flag = Clips.Play(_video, crewClip.Sheet, crewClip.Frames, crewClip.Columns, crewClip.Fps, loop: false);
			}
			else if (crewClip != null && (Object)(object)crewClip.Picture != (Object)null)
			{
				_video.texture = (Texture)(object)crewClip.Picture;
				_video.uvRect = new Rect(0f, 0f, 1f, 1f);
				((Behaviour)_video).enabled = true;
				flag = true;
			}
			_loadedSheet = flag;
			((Behaviour)_video).enabled = flag;
			((Component)_loading).gameObject.SetActive(!flag);
			if (flag)
			{
				ApplyPause();
			}
			RebuildPips(canControl);
			RebuildControls();
		}

		private static void RebuildPips(bool canControl)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Expected O, but got Unknown
			for (int num = ((Transform)_pillsRow).childCount - 1; num >= 0; num--)
			{
				Object.Destroy((Object)(object)((Component)((Transform)_pillsRow).GetChild(num)).gameObject);
			}
			List<DayClips.Entry> clips = DayClips.Clips;
			float num2 = Mathf.Min(42f, (400f - (float)(clips.Count - 1) * 6f) / (float)Mathf.Max(1, clips.Count));
			for (int i = 0; i < clips.Count; i++)
			{
				int target = i;
				Image val = Ui.Place<Image>(Ui.Panel((Transform)(object)_pillsRow, "Pip", (i == _index) ? Ui.Main : ((i < _index) ? Ui.Accent(0.45f) : Ui.Track)), (float)i * (num2 + 6f), 4f, num2, 10f);
				if (!canControl)
				{
					continue;
				}
				((Graphic)val).raycastTarget = true;
				Button obj = ((Component)val).gameObject.AddComponent<Button>();
				((Selectable)obj).transition = (Transition)0;
				((UnityEvent)obj.onClick).AddListener((UnityAction)delegate
				{
					if (_synced && Store.IsHost)
					{
						HostShow(target);
					}
					else if (!_synced)
					{
						_index = target;
						_clipDuration = EstimateDuration(_index);
						_clipStartedAt = Time.unscaledTime;
						_loadedIndex = -1;
						_loadedSheet = false;
						RefreshClip();
					}
				});
			}
		}

		private static void RebuildControls()
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_controlsRow == (Object)null)
			{
				return;
			}
			for (int num = ((Transform)_controlsRow).childCount - 1; num >= 0; num--)
			{
				Object.Destroy((Object)(object)((Component)((Transform)_controlsRow).GetChild(num)).gameObject);
			}
			List<DayClips.Entry> clips = DayClips.Clips;
			DayClips.Entry entry = ((_index >= 0 && _index < clips.Count) ? clips[_index] : null);
			CrewClip crewClip = ((entry != null && !entry.Mine) ? DayClips.Crew(entry) : null);
			bool num2 = Store.IsHost || !_synced;
			float rx = _controlsRow.sizeDelta.x;
			AddBtn("HIDE", 96f, HideLocal);
			if (num2)
			{
				AddBtn("END REEL", 116f, delegate
				{
					if (_synced && Store.IsHost)
					{
						HostEnd();
					}
					else
					{
						CloseUI(endAll: true);
					}
				});
				AddBtn("SKIP >", 104f, Next);
				AddBtn(_paused ? "PLAY" : "PAUSE", 96f, TogglePause);
				AddBtn("< PREV", 104f, Prev);
			}
			else
			{
				AddBtn((_skipNeeded > 0) ? $"SKIP ({_skipVotes}/{_skipNeeded})" : "SKIP", 134f, VoteSkip, filled: false, !_votedSkip);
			}
			if (entry != null)
			{
				if (entry.Mine)
				{
					AddBtn("SAVED (YOURS)", 162f, delegate
					{
					}, filled: false, enabled: false);
				}
				else if (crewClip != null && crewClip.Saved)
				{
					AddBtn("SAVED", 120f, delegate
					{
					}, filled: false, enabled: false);
				}
				else if (crewClip != null)
				{
					AddBtn("SAVE CLIP", 136f, SaveCurrentClip, filled: true);
				}
			}
			void AddBtn(string label, float w, Action onClick, bool filled = false, bool enabled = true)
			{
				rx -= w;
				Ui.Place<Image>(Ui.MenuButton((Transform)(object)_controlsRow, label, 14f, onClick, filled, enabled).Fill, rx, 0f, w, 38f);
				rx -= 8f;
			}
		}
	}
	internal static class Clips
	{
		private sealed class PendingClip
		{
			internal ClipRecord Info;

			internal List<byte[]> Frames;

			internal int Remaining;

			internal float NextAt;

			internal bool DeathTail;
		}

		internal const int Width = 240;

		internal const int Height = 144;

		internal const int Fps = 10;

		internal const int Columns = 8;

		private const int Ring = 30;

		private const int MaxFrames = 44;

		private const int Quality = 68;

		private const int Kept = 6;

		private const int HoldCentiseconds = 120;

		internal const float Hold = 1.2f;

		private static readonly byte[][] Frames = new byte[30][];

		private static readonly float[] Times = new float[30];

		private static int _head;

		private static int _filled;

		private static RenderTexture _half;

		private static RenderTexture _small;

		private static float _nextAt;

		private static bool _reading;

		private static readonly List<PendingClip> Pending = new List<PendingClip>();

		private static readonly ConcurrentQueue<Action> Done = new ConcurrentQueue<Action>();

		private static readonly Dictionary<string, Texture2D> Loaded = new Dictionary<string, Texture2D>();

		internal static string Folder => Path.Combine(Store.Root, "clips");

		internal static bool HasPending => Pending.Count > 0;

		internal static bool HasDeathTail => Pending.Exists((PendingClip p) => p.DeathTail);

		private static RenderTexture CaptureSource(PlayerControllerB local, bool allowSpectate)
		{
			StartOfRound instance = StartOfRound.Instance;
			if (allowSpectate && (Object)(object)instance != (Object)null)
			{
				if ((Object)(object)instance.activeCamera != (Object)null && (Object)(object)instance.activeCamera.targetTexture != (Object)null)
				{
					return instance.activeCamera.targetTexture;
				}
				if ((Object)(object)instance.spectateCamera != (Object)null && (Object)(object)instance.spectateCamera.targetTexture != (Object)null)
				{
					return instance.spectateCamera.targetTexture;
				}
			}
			if (!((Object)(object)local != (Object)null) || !((Object)(object)local.gameplayCamera != (Object)null))
			{
				return null;
			}
			return local.gameplayCamera.targetTexture;
		}

		internal static void Tick()
		{
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			Action result;
			while (Done.TryDequeue(out result))
			{
				try
				{
					result();
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Clips: " + ex.Message));
				}
			}
			PlayerControllerB localPlayer = Store.LocalPlayer;
			StartOfRound instance = StartOfRound.Instance;
			if (!Settings.Enabled.Value || (Object)(object)localPlayer == (Object)null || (Object)(object)instance == (Object)null)
			{
				if (Pending.Count > 0)
				{
					FlushPending();
				}
				if ((Object)(object)localPlayer == (Object)null && _filled > 0)
				{
					_filled = 0;
				}
				return;
			}
			Store.TrackRound(instance);
			float now = Time.unscaledTime;
			bool flag = !localPlayer.isPlayerDead && localPlayer.isPlayerControlled;
			bool flag2 = flag && now >= _nextAt;
			bool flag3 = false;
			bool flag4 = false;
			for (int num = Pending.Count - 1; num >= 0; num--)
			{
				PendingClip pendingClip = Pending[num];
				if (pendingClip.Remaining <= 0)
				{
					Pending.RemoveAt(num);
					Save(pendingClip.Info, pendingClip.Frames);
				}
				else if (now >= pendingClip.NextAt)
				{
					flag3 = true;
					if (pendingClip.DeathTail || localPlayer.isPlayerDead)
					{
						flag4 = true;
					}
				}
			}
			if ((!flag2 && !flag3) || _reading || !SystemInfo.supportsAsyncGPUReadback)
			{
				return;
			}
			if (flag4)
			{
				DeathCam.SyncNow();
			}
			RenderTexture val = CaptureSource(localPlayer, flag4 || !flag);
			if ((Object)(object)val == (Object)null)
			{
				if (flag3 && !flag)
				{
					FlushPending();
				}
				return;
			}
			if (flag2)
			{
				_nextAt = now + 0.1f;
			}
			Shrink(val);
			_reading = true;
			bool captureRing = flag2;
			bool captureTail = flag3;
			AsyncGPUReadback.Request((Texture)(object)_small, 0, (TextureFormat)4, (Action<AsyncGPUReadbackRequest>)delegate(AsyncGPUReadbackRequest request)
			{
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_004a: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
				_reading = false;
				if (!((AsyncGPUReadbackRequest)(ref request)).hasError)
				{
					byte[] array = null;
					if (captureRing)
					{
						byte[] array2 = Frames[_head] ?? (Frames[_head] = new byte[138240]);
						((AsyncGPUReadbackRequest)(ref request)).GetData<byte>(0).CopyTo(array2);
						Times[_head] = now;
						_head = (_head + 1) % 30;
						if (_filled < 30)
						{
							_filled++;
						}
						array = array2;
					}
					if (captureTail)
					{
						for (int num2 = Pending.Count - 1; num2 >= 0; num2--)
						{
							PendingClip pendingClip2 = Pending[num2];
							if (!(now < pendingClip2.NextAt))
							{
								byte[] item = ((array != null) ? ((byte[])array.Clone()) : ((AsyncGPUReadbackRequest)(ref request)).GetData<byte>(0).ToArray());
								pendingClip2.Frames.Add(item);
								pendingClip2.Remaining--;
								pendingClip2.NextAt = now + 0.1f;
								if (pendingClip2.Remaining <= 0)
								{
									Pending.RemoveAt(num2);
									Save(pendingClip2.Info, pendingClip2.Frames);
								}
							}
						}
					}
				}
			});
		}

		private static void FlushPending()
		{
			List<PendingClip> list = Pending.ToList();
			Pending.Clear();
			foreach (PendingClip item in list)
			{
				Save(item.Info, item.Frames);
			}
		}

		private static void Shrink(RenderTexture source)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			if ((Object)(object)_half == (Object)null)
			{
				_half = new RenderTexture(480, 288, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2)
				{
					name = "BaconClips half"
				};
				_half.Create();
				_small = new RenderTexture(240, 144, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2)
				{
					name = "BaconClips small"
				};
				_small.Create();
			}
			Graphics.Blit((Texture)(object)source, _half);
			Graphics.Blit((Texture)(object)_half, _small);
		}

		internal static void Keep(ClipRecord info, float tailSeconds = 0f, bool deathTail = false)
		{
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			if (!Settings.Enabled.Value || info == null)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			List<byte[]> frames = new List<byte[]>();
			for (int i = 0; i < _filled; i++)
			{
				int num = (_head - _filled + i + 30) % 30;
				if (Frames[num] != null && unscaledTime - Times[num] <= 3.3f)
				{
					frames.Add((byte[])Frames[num].Clone());
				}
			}
			if (tailSeconds > 0.05f && SystemInfo.supportsAsyncGPUReadback)
			{
				int remaining = Mathf.Clamp(Mathf.RoundToInt(tailSeconds * 10f) + 1, 2, 14);
				Pending.Add(new PendingClip
				{
					Info = info,
					Frames = frames,
					Remaining = remaining,
					NextAt = unscaledTime + (deathTail ? 0.09f : 0f),
					DeathTail = deathTail
				});
				return;
			}
			RenderTexture val = CaptureSource(Store.LocalPlayer, deathTail);
			if ((Object)(object)val == (Object)null || !SystemInfo.supportsAsyncGPUReadback)
			{
				Save(info, frames);
				return;
			}
			Shrink(val);
			AsyncGPUReadback.Request((Texture)(object)_small, 0, (TextureFormat)4, (Action<AsyncGPUReadbackRequest>)delegate(AsyncGPUReadbackRequest request)
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				if (!((AsyncGPUReadbackRequest)(ref request)).hasError)
				{
					frames.Add(((AsyncGPUReadbackRequest)(ref request)).GetData<byte>(0).ToArray());
				}
				Save(info, frames);
			});
		}

		private static void Save(ClipRecord info, List<byte[]> frames)
		{
			if (frames.Count < 2)
			{
				return;
			}
			if (frames.Count > 44)
			{
				frames = frames.GetRange(frames.Count - 44, 44);
			}
			string name = $"{DateTime.Now:yyyyMMdd-HHmmss-fff}";
			string folder = Folder;
			bool saveGif = Settings.SaveGif.Value;
			bool bigGif = Settings.BigGif.Value;
			ThreadPool.QueueUserWorkItem(delegate
			{
				try
				{
					int count = frames.Count;
					int num = (count + 8 - 1) / 8;
					int num2 = 1920;
					int num3 = num * 144;
					int num4 = 960;
					byte[] array = new byte[num2 * num3 * 4];
					for (int i = 0; i < count; i++)
					{
						int num5 = i % 8;
						int num6 = (num - 1 - i / 8) * 144;
						for (int j = 0; j < 144; j++)
						{
							Buffer.BlockCopy(frames[i], j * num4, array, ((num6 + j) * num2 + num5 * 240) * 4, num4);
						}
					}
					byte[] jpg = ImageConversion.EncodeArrayToJPG((Array)array, (GraphicsFormat)4, (uint)num2, (uint)num3, 0u, 68);
					if (jpg.Length > 215040)
					{
						jpg = ImageConversion.EncodeArrayToJPG((Array)array, (GraphicsFormat)4, (uint)num2, (uint)num3, 0u, 54);
					}
					if (jpg.Length > 215040)
					{
						jpg = ImageConversion.EncodeArrayToJPG((Array)array, (GraphicsFormat)4, (uint)num2, (uint)num3, 0u, 44);
					}
					byte[] gif = (saveGif ? GifWriter.Encode(frames, 240, 144, 10, 120, bigGif) : null);
					Directory.CreateDirectory(folder);
					File.WriteAllBytes(Path.Combine(folder, name + ".jpg"), jpg);
					if (gif != null && gif.Length != 0)
					{
						File.WriteAllBytes(Path.Combine(folder, name + ".gif"), gif);
					}
					Done.Enqueue(delegate
					{
						Saved(info, name, count, jpg.Length, (gif != null) ? gif.Length : 0);
					});
				}
				catch (Exception ex)
				{
					Exception ex2 = ex;
					Exception e = ex2;
					Done.Enqueue(delegate
					{
						Plugin.Log.LogWarning((object)("Clips: couldn't save clip: " + e.Message));
					});
				}
			});
		}

		private static void Saved(ClipRecord info, string name, int frames, int jpg, int gif)
		{
			info.Clip = name + ".jpg";
			info.Gif = ((gif > 0) ? (name + ".gif") : "");
			info.Frames = frames;
			info.Columns = 8;
			info.Fps = 10;
			Plugin.Log.LogInfo((object)string.Format("Clips: saved {0}, {1} frames, sheet {2} KB{3} ({4})", name, frames, jpg / 1024, (gif > 0) ? $", GIF {gif / 1024} KB" : "", info.Why));
			if (Store.Data.Clips.Contains(info))
			{
				Store.Save();
			}
			Gallery.Refresh();
		}

		internal static void SaveCrewSheet(ClipRecord info, Texture2D sheet, int frames, int columns, int fps)
		{
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			if (info == null || (Object)(object)sheet == (Object)null || frames < 2 || columns < 1)
			{
				return;
			}
			try
			{
				byte[] bytes = ImageConversion.EncodeToJPG(sheet, 68);
				string name = $"{DateTime.Now:yyyyMMdd-HHmmss-fff}";
				string folder = Folder;
				Directory.CreateDirectory(folder);
				File.WriteAllBytes(Path.Combine(folder, name + ".jpg"), bytes);
				info.Clip = name + ".jpg";
				info.Frames = frames;
				info.Columns = columns;
				info.Fps = Mathf.Clamp(fps, 1, 30);
				int num = Mathf.Max(1, (frames + columns - 1) / columns);
				int width = ((Texture)sheet).width;
				int height = ((Texture)sheet).height;
				int fw = width / columns;
				int fh = height / num;
				if (fw <= 0 || fh <= 0)
				{
					return;
				}
				Color32[] pixels = sheet.GetPixels32();
				List<byte[]> list = new List<byte[]>(frames);
				for (int i = 0; i < frames; i++)
				{
					int num2 = i % columns;
					int num3 = (num - 1 - i / columns) * fh;
					byte[] array = new byte[fw * fh * 4];
					for (int j = 0; j < fh; j++)
					{
						int num4 = (num3 + j) * width + num2 * fw;
						int num5 = j * fw * 4;
						for (int k = 0; k < fw; k++)
						{
							Color32 val = pixels[num4 + k];
							int num6 = num5 + k * 4;
							array[num6] = val.r;
							array[num6 + 1] = val.g;
							array[num6 + 2] = val.b;
							array[num6 + 3] = byte.MaxValue;
						}
					}
					list.Add(array);
				}
				int delayCs = Mathf.Max(4, 100 / info.Fps);
				bool value = Settings.SaveGif.Value;
				bool bigGif = Settings.BigGif.Value;
				if (!value)
				{
					return;
				}
				ThreadPool.QueueUserWorkItem(delegate
				{
					try
					{
						byte[] bytes2 = GifWriter.Encode(list, fw, fh, delayCs, 120, bigGif);
						File.WriteAllBytes(Path.Combine(folder, name + ".gif"), bytes2);
						Done.Enqueue(delegate
						{
							info.Gif = name + ".gif";
							if (Store.Data.Clips.Contains(info))
							{
								Store.Save();
							}
							Gallery.Refresh();
						});
					}
					catch (Exception ex2)
					{
						Exception ex3 = ex2;
						Exception e = ex3;
						Done.Enqueue(delegate
						{
							Plugin.Log.LogInfo((object)("Clips: couldn't write saved crew GIF: " + e.Message));
						});
					}
				});
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Clips: couldn't save crew sheet: " + ex.Message));
			}
		}

		internal static bool Has(ClipRecord clip)
		{
			if (clip != null && !string.IsNullOrEmpty(clip.Clip))
			{
				return clip.Frames > 1;
			}
			return false;
		}

		internal static string GifPath(ClipRecord clip)
		{
			if (!Has(clip) || string.IsNullOrEmpty(clip.Gif))
			{
				return null;
			}
			return Path.Combine(Folder, clip.Gif);
		}

		internal static string GifShown(ClipRecord clip)
		{
			string text = GifPath(clip);
			if (text == null)
			{
				return null;
			}
			int num = text.IndexOf("LocalLow", StringComparison.OrdinalIgnoreCase);
			if (num < 0)
			{
				return Path.Combine("BaconClips", "clips", clip.Gif);
			}
			return text.Substring(num);
		}

		internal static byte[] Bytes(ClipRecord clip)
		{
			if (!Has(clip))
			{
				return null;
			}
			string path = Path.Combine(Folder, clip.Clip);
			try
			{
				return File.Exists(path) ? File.ReadAllBytes(path) : null;
			}
			catch (Exception)
			{
				return null;
			}
		}

		internal static void Delete(ClipRecord clip)
		{
			if (clip != null)
			{
				DeleteFile(clip.Clip);
				DeleteFile(clip.Gif);
			}
		}

		private static void DeleteFile(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return;
			}
			Forget(name);
			try
			{
				File.Delete(Path.Combine(Folder, name));
			}
			catch (Exception)
			{
			}
		}

		internal static void Tidy(IEnumerable<ClipRecord> clips)
		{
			try
			{
				if (!Directory.Exists(Folder))
				{
					return;
				}
				HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
				foreach (ClipRecord clip in clips)
				{
					if (!string.IsNullOrEmpty(clip.Clip))
					{
						hashSet.Add(clip.Clip);
					}
					if (!string.IsNullOrEmpty(clip.Gif))
					{
						hashSet.Add(clip.Gif);
					}
				}
				FileInfo[] files = new DirectoryInfo(Folder).GetFiles();
				foreach (FileInfo fileInfo in files)
				{
					if (!hashSet.Contains(fileInfo.Name) && (DateTime.Now - fileInfo.LastWriteTime).TotalMinutes > 1.0)
					{
						DeleteFile(fileInfo.Name);
					}
				}
			}
			catch (Exception)
			{
			}
		}

		internal static Texture2D Sheet(ClipRecord clip)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			if (!Has(clip))
			{
				return null;
			}
			if (Loaded.TryGetValue(clip.Clip, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			string path = Path.Combine(Folder, clip.Clip);
			if (!File.Exists(path))
			{
				return null;
			}
			try
			{
				value = new Texture2D(2, 2, (TextureFormat)4, false)
				{
					name = clip.Clip,
					hideFlags = (HideFlags)61
				};
				if (!ImageConversion.LoadImage(value, File.ReadAllBytes(path)))
				{
					Object.Destroy((Object)(object)value);
					return null;
				}
				Forget(clip.Clip);
				while (Loaded.Count >= 6)
				{
					Forget(Loaded.Keys.First());
				}
				Loaded[clip.Clip] = value;
				return value;
			}
			catch (Exception)
			{
				return null;
			}
		}

		private static void Forget(string name)
		{
			if (name != null && Loaded.TryGetValue(name, out var value))
			{
				Loaded.Remove(name);
				if ((Object)(object)value != (Object)null)
				{
					Object.Destroy((Object)(object)value);
				}
			}
		}

		internal static bool Play(RawImage picture, ClipRecord clip, bool loop = true)
		{
			if (Has(clip))
			{
				return Play(picture, Sheet(clip), clip.Frames, clip.Columns, clip.Fps, loop);
			}
			return false;
		}

		internal static bool Play(RawImage picture, Texture2D sheet, int frames, int columns, int fps, bool loop = true)
		{
			if ((Object)(object)picture == (Object)null || (Object)(object)sheet == (Object)null || frames < 2 || columns < 1)
			{
				return false;
			}
			picture.texture = (Texture)(object)sheet;
			((Behaviour)picture).enabled = true;
			(((Component)picture).GetComponent<ClipPlayer>() ?? ((Component)picture).gameObject.AddComponent<ClipPlayer>()).Set(picture, frames, columns, Mathf.Max(1, (frames + columns - 1) / columns), Mathf.Clamp(fps, 1, 30), loop);
			return true;
		}
	}
	internal sealed class ClipPlayer : MonoBehaviour
	{
		private RawImage _picture;

		private int _frames;

		private int _columns;

		private int _rows;

		private int _shown = -1;

		private float _fps;

		private float _start;

		private float _elapsed;

		private bool _loop = true;

		internal bool Paused;

		internal float PlaySeconds
		{
			get
			{
				if (_frames <= 1 || !(_fps > 0f))
				{
					return 0f;
				}
				return (float)_frames / _fps;
			}
		}

		internal float Duration
		{
			get
			{
				if (_frames <= 1 || !(_fps > 0f))
				{
					return 0f;
				}
				return (float)_frames / _fps + 1.2f;
			}
		}

		internal float Progress
		{
			get
			{
				float num = (Paused ? _elapsed : (Time.unscaledTime - _start));
				if (!_loop)
				{
					float playSeconds = PlaySeconds;
					if (!(playSeconds <= 0.01f))
					{
						return Mathf.Clamp01(num / playSeconds);
					}
					return 1f;
				}
				float duration = Duration;
				if (duration <= 0.01f)
				{
					return 0f;
				}
				return Mathf.Repeat(num, duration) / duration;
			}
		}

		internal void Set(RawImage picture, int frames, int columns, int rows, int fps, bool loop = true)
		{
			_picture = picture;
			_frames = frames;
			_columns = columns;
			_rows = rows;
			_fps = fps;
			_loop = loop;
			Paused = false;
			_elapsed = 0f;
			_start = Time.unscaledTime;
			_shown = -1;
			Update();
		}

		internal void SetPaused(bool paused)
		{
			if (Paused != paused)
			{
				if (paused)
				{
					_elapsed = Time.unscaledTime - _start;
				}
				else
				{
					_start = Time.unscaledTime - _elapsed;
				}
				Paused = paused;
			}
		}

		private void OnEnable()
		{
			_start = Time.unscaledTime - _elapsed;
			_shown = -1;
		}

		private void Update()
		{
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_picture == (Object)null) && _frames >= 2)
			{
				float num = (Paused ? _elapsed : (Time.unscaledTime - _start));
				int num3;
				if (_loop)
				{
					int num2 = _frames + Mathf.RoundToInt(_fps * 1.2f);
					num3 = Mathf.Min((int)(Mathf.Max(0f, num) * _fps) % num2, _frames - 1);
				}
				else
				{
					num3 = Mathf.Clamp((int)(Mathf.Max(0f, num) * _fps), 0, _frames - 1);
				}
				if (num3 != _shown)
				{
					_shown = num3;
					float num4 = 1f / (float)_columns;
					float num5 = 1f / (float)_rows;
					_picture.uvRect = new Rect((float)(num3 % _columns) * num4, 1f - (float)(num3 / _columns + 1) * num5, num4, num5);
				}
			}
		}
	}
	internal static class DayClips
	{
		private sealed class Kept
		{
			internal int Slot;

			internal int ClipId;

			internal string Name;

			internal string Why;

			internal string Moon;

			internal string Clock;
		}

		internal sealed class Entry
		{
			internal int Slot;

			internal int ClipId;

			internal string Name;

			internal string Why;

			internal string Moon;

			internal string Clock;

			internal bool Mine;
		}

		private const float ShareWait = 12f;

		private const float ShareStagger = 0.35f;

		private const int MaxTotal = 12;

		private static readonly List<Kept> Hosted = new List<Kept>();

		private static StartOfRound _hostRound;

		private static int _hostDay = -1;

		internal static readonly List<Entry> Clips = new List<Entry>();

		private static readonly Dictionary<int, ClipRecord> LocalByClipId = new Dictionary<int, ClipRecord>();

		private static StartOfRound _round;

		private static int _sharedCount;

		private static float _orbitSince = -1f;

		private static float _nextShareAt = -1f;

		private static bool _shareDone;

		private static bool _returnedFromMoon;

		private static int MaxPerPlayer => Mathf.Clamp(Settings.DayClipsPerPlayer.Value, 1, 4);

		internal static int HostedCount => Hosted.Count;

		internal static bool HostAdd(PlayerControllerB by, SharedClip shared)
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || !instance.inShipPhase || (Object)(object)by == (Object)null)
			{
				return false;
			}
			HostFresh(instance);
			int slot = (int)by.playerClientId;
			if (Hosted.Count >= 12)
			{
				return false;
			}
			if (Hosted.Count((Kept k) => k.Slot == slot) >= MaxPerPlayer)
			{
				return false;
			}
			if (Hosted.Exists((Kept k) => k.Slot == slot && k.ClipId == shared.ClipId))
			{
				return false;
			}
			string text = (string.IsNullOrWhiteSpace(by.playerUsername) ? "EMPLOYEE" : by.playerUsername);
			Hosted.Add(new Kept
			{
				Slot = slot,
				ClipId = shared.ClipId,
				Name = Clean(text),
				Why = Clean(shared.Why),
				Moon = Clean(shared.Moon),
				Clock = Clean(shared.Clock)
			});
			Plugin.Log.LogInfo((object)$"DayClips: {text}'s clip #{shared.ClipId} ({shared.Why}) added ({Hosted.Count} today)");
			ClipReel.HostClipAdded();
			HostSend();
			return true;
		}

		private static void HostFresh(StartOfRound round)
		{
			int num = ((round.gameStats != null) ? round.gameStats.daysSpent : (-1));
			if (!((Object)(object)round == (Object)(object)_hostRound) || num != _hostDay)
			{
				_hostRound = round;
				_hostDay = num;
				Hosted.Clear();
				ClipReel.HostReset(round);
			}
		}

		private static void HostSend()
		{
			Net.BroadcastDayList(string.Join(";", Hosted.Select((Kept k) => $"{k.Slot},{k.ClipId},{k.Name},{k.Why},{k.Moon},{k.Clock}")));
		}

		private static string Clean(string text)
		{
			return (text ?? "").Replace(",", " ").Replace(";", " ").Replace("<", "")
				.Replace(">", "");
		}

		internal static void OnList(string text)
		{
			PlayerControllerB localPlayer = Store.LocalPlayer;
			int num = (((Object)(object)localPlayer != (Object)null) ? ((int)localPlayer.playerClientId) : (-1));
			Clips.Clear();
			string[] array = (text ?? "").Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split(',');
				if (array2.Length >= 4 && int.TryParse(array2[0], out var result) && int.TryParse(array2[1], out var result2))
				{
					Clips.Add(new Entry
					{
						Slot = result,
						ClipId = result2,
						Name = array2[2],
						Why = array2[3],
						Moon = ((array2.Length > 4) ? array2[4] : ""),
						Clock = ((array2.Length > 5) ? array2[5] : ""),
						Mine = (result == num)
					});
				}
			}
			Gallery.Refresh();
		}

		internal static void Tick()
		{
			StartOfRound instance = StartOfRound.Instance;
			PlayerControllerB localPlayer = Store.LocalPlayer;
			if ((Object)(object)instance == (Object)null || (Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			if (Store.IsHost)
			{
				if (Hosted.Count > 0 && !instance.inShipPhase)
				{
					Hosted.Clear();
					HostSend();
				}
				ClipReel.HostTick(instance);
			}
			if ((Object)(object)instance != (Object)(object)_round)
			{
				_round = instance;
				_returnedFromMoon = false;
				_sharedCount = 0;
				_shareDone = false;
				_orbitSince = -1f;
				_nextShareAt = -1f;
				LocalByClipId.Clear();
				Clips.Clear();
			}
			if (!instance.inShipPhase)
			{
				if (instance.shipHasLanded)
				{
					_returnedFromMoon = true;
				}
				_sharedCount = 0;
				_shareDone = false;
				_orbitSince = -1f;
				_nextShareAt = -1f;
				LocalByClipId.Clear();
				Clips.Clear();
			}
			else
			{
				if (((instance.gameStats != null && instance.gameStats.daysSpent != 0) ? 1 : 0) <= (false ? 1 : 0) || !_returnedFromMoon)
				{
					return;
				}
				float unscaledTime = Time.unscaledTime;
				if (_orbitSince < 0f)
				{
					_orbitSince = unscaledTime;
				}
				if (_shareDone || !Settings.ShareDayClips.Value || !Settings.Enabled.Value)
				{
					return;
				}
				if (unscaledTime - _orbitSince > 12f)
				{
					_shareDone = true;
				}
				else
				{
					if (BaconClips.Clips.HasPending || unscaledTime < _nextShareAt)
					{
						return;
					}
					List<ClipRecord> list = TodayAll(instance);
					if (_sharedCount >= list.Count)
					{
						if (_sharedCount > 0 && unscaledTime - _orbitSince >= 3.5f)
						{
							_shareDone = true;
						}
						return;
					}
					ClipRecord clipRecord = list[_sharedCount];
					int sharedCount = _sharedCount;
					LocalByClipId[sharedCount] = clipRecord;
					_sharedCount++;
					_nextShareAt = unscaledTime + 0.35f;
					if (_sharedCount >= MaxPerPlayer)
					{
						_shareDone = true;
					}
					string text = Share.SendDaily(clipRecord, sharedCount);
					Plugin.Log.LogInfo((object)((text == null) ? $"DayClips: shared clip #{sharedCount} ({clipRecord.Why})" : $"DayClips: clip #{sharedCount} skipped ({text})"));
				}
			}
		}

		internal static List<ClipRecord> TodayAll(StartOfRound round)
		{
			List<ClipRecord> list = new List<ClipRecord>();
			if ((Object)(object)round == (Object)null || round.gameStats == null)
			{
				return list;
			}
			int daysSpent = round.gameStats.daysSpent;
			if (daysSpent <= 0)
			{
				return list;
			}
			List<ClipRecord> clips = Store.Data.Clips;
			for (int num = clips.Count - 1; num >= 0; num--)
			{
				ClipRecord clipRecord = clips[num];
				if (clipRecord.Run == Store.Data.RunsPlayed && clipRecord.Day == daysSpent && BaconClips.Clips.Has(clipRecord))
				{
					string path = Path.Combine(BaconClips.Clips.Folder, clipRecord.Clip);
					if (File.Exists(path) && (DateTime.Now - File.GetLastWriteTime(path)).TotalMinutes < 30.0)
					{
						list.Add(clipRecord);
					}
				}
			}
			return list.OrderByDescending((ClipRecord c) => ClipMoments.Priority(c.Why)).Take(MaxPerPlayer).ToList();
		}

		internal static ClipRecord OwnFile(Entry entry)
		{
			if (entry == null || !entry.Mine)
			{
				return null;
			}
			if (LocalByClipId.TryGetValue(entry.ClipId, out var value) && value != null)
			{
				return value;
			}
			List<ClipRecord> list = TodayAll(StartOfRound.Instance);
			if (entry.ClipId < 0 || entry.ClipId >= list.Count)
			{
				return list.FirstOrDefault();
			}
			return list[entry.ClipId];
		}

		internal static CrewClip Crew(Entry entry)
		{
			if (entry == null || entry.Mine)
			{
				return null;
			}
			return Share.Crew.FirstOrDefault((CrewClip c) => c.Daily && c.Slot == entry.Slot && c.ClipId == entry.ClipId && (Object)(object)c.Sheet != (Object)null && c.At >= _orbitSince - 2f) ?? Share.Crew.FirstOrDefault((CrewClip c) => c.Daily && c.Slot == entry.Slot && (Object)(object)c.Sheet != (Object)null && c.At >= _orbitSince - 2f);
		}
	}
	[HarmonyPatch]
	internal static class DeathCam
	{
		private struct PreState
		{
			internal bool Watch;

			internal Vector3 Pos;

			internal Quaternion Rot;

			internal float Fov;
		}

		internal const float BodyHoldSeconds = 1.8f;

		internal const float MaxDuration = 2.4f;

		private const float PosSmooth = 16f;

		private const float RotSmooth = 6.5f;

		private const float MaxRollDeg = 55f;

		private const float HeadRadius = 0.14f;

		private const float Gravity = 14.5f;

		private static bool _fpActive;

		private static bool _holdingBody;

		private static bool _deferredGameOver;

		private static bool _replayingGameOver;

		private static bool _useFallback;

		private static bool _gibPhysicsInit;

		private static float _startedAt;

		private static float _until;

		private static float _fov = 66f;

		private static float _gibShake;

		private static float _lastSimAt;

		private static CauseOfDeath _cause;

		private static DeadBodyInfo _body;

		private static Transform _head;

		private static Transform _gibHead;

		private static Vector3 _localPos;

		private static Vector3 _curPos;

		private static Vector3 _fallbackOrigin;

		private static Vector3 _deathVelocity;

		private static Vector3 _gibPos;

		private static Vector3 _gibVel;

		private static Vector3 _gibAngVel;

		private static Quaternion _localRot = Quaternion.identity;

		private static Quaternion _curRot = Quaternion.identity;

		private static Quaternion _gibRot = Quaternion.identity;

		private static bool _gibGrounded;

		private static readonly List<(Renderer Renderer, ShadowCastingMode Mode)> Hidden = new List<(Renderer, ShadowCastingMode)>();

		private static bool StillHolding(PlayerControllerB local)
		{
			if (!_holdingBody || (Object)(object)local == (Object)null)
			{
				return false;
			}
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime - _startedAt >= 2.4f)
			{
				return false;
			}
			if (unscaledTime < _until)
			{
				return true;
			}
			if (Clips.HasDeathTail)
			{
				return true;
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
		private static void BeforeDeath(PlayerControllerB __instance, out PreState __state)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			__state = default(PreState);
			if (Settings.DeathCamera.Value != DeathCamMode.Vanilla && !((Object)(object)__instance == (Object)null) && ((NetworkBehaviour)__instance).IsOwner && !__instance.isPlayerDead && !((Object)(object)__instance != (Object)(object)Store.LocalPlayer))
			{
				Camera gameplayCamera = __instance.gameplayCamera;
				if (!((Object)(object)gameplayCamera == (Object)null))
				{
					__state = new PreState
					{
						Watch = true,
						Pos = ((Component)gameplayCamera).transform.position,
						Rot = ((Component)gameplayCamera).transform.rotation,
						Fov = gameplayCamera.fieldOfView
					};
					_startedAt = Time.unscaledTime;
					_until = _startedAt + 1.8f;
					_holdingBody = true;
					_deferredGameOver = false;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
		private static void AfterDeath(PlayerControllerB __instance, Vector3 bodyVelocity, CauseOfDeath causeOfDeath, PreState __state)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			if (!__state.Watch)
			{
				return;
			}
			if ((Object)(object)__instance == (Object)null || !__instance.isPlayerDead)
			{
				End();
				return;
			}
			DeadBodyInfo deadBody = __instance.deadBody;
			bool flag = IsBodyUsable(deadBody);
			StartOfRound instance = StartOfRound.Instance;
			bool deferredGameOver = _deferredGameOver;
			if ((Object)(object)instance != (Object)null && instance.overrideSpectateCamera)
			{
				deferredGameOver = true;
				_replayingGameOver = true;
				try
				{
					instance.SetSpectateCameraToGameOverMode(false, __instance);
				}
				finally
				{
					_replayingGameOver = false;
				}
			}
			End();
			_body = (flag ? deadBody : null);
			_cause = causeOfDeath;
			_deathVelocity = bodyVelocity;
			_startedAt = Time.unscaledTime;
			_lastSimAt = _startedAt;
			_until = _startedAt + 1.8f;
			_holdingBody = true;
			_deferredGameOver = deferredGameOver;
			_fov = ((__state.Fov > 10f) ? __state.Fov : 66f);
			_curPos = __state.Pos;
			_curRot = __state.Rot;
			_fallbackOrigin = __state.Pos;
			if (__instance.isInGameOverAnimation < 1.8f)
			{
				__instance.isInGameOverAnimation = 1.8f;
			}
			bool flag2 = Settings.DeathCamera.Value == DeathCamMode.FirstPerson;
			Plugin.Log.LogInfo((object)$"DeathCam: holding {Settings.DeathCamera.Value} for {1.8f:0.0}s (body={flag}, cause={causeOfDeath}, deferredGameOver={_deferredGameOver})");
			if (!flag2)
			{
				if (!flag && (Object)(object)__instance.spectateCameraPivot != (Object)null)
				{
					__instance.spectateCameraPivot.position = __state.Pos;
				}
				return;
			}
			Transform val = (_head = (flag ? FindHead(deadBody, __state.Pos) : null));
			_useFallback = (Object)(object)val == (Object)null;
			if ((Object)(object)val != (Object)null)
			{
				Vector3 localPos = val.InverseTransformPoint(__state.Pos);
				if (((Vector3)(ref localPos)).magnitude > 0.3f)
				{
					localPos = ((Vector3)(ref localPos)).normalized * 0.3f;
				}
				_localPos = localPos;
				_localRot = Quaternion.Inverse(val.rotation) * __state.Rot;
				Renderer[] componentsInChildren = ((Component)deadBody).GetComponentsInChildren<Renderer>(true);
				foreach (Renderer val2 in componentsInChildren)
				{
					if (!((Object)(object)val2 == (Object)null) && !(val2 is ParticleSystemRenderer))
					{
						Hidden.Add((val2, val2.shadowCastingMode));
						val2.shadowCastingMode = (ShadowCastingMode)3;
					}
				}
			}
			_fpActive = true;
			ApplyCamera(instant: true);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(StartOfRound), "SetSpectateCameraToGameOverMode")]
		private static bool BeforeGameOverCam(bool enableGameOver)
		{
			if (_replayingGameOver || !enableGameOver)
			{
				return true;
			}
			if (!StillHolding(Store.LocalPlayer))
			{
				return true;
			}
			_deferredGameOver = true;
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPriority(0)]
		[HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")]
		private static void AfterLateUpdate(PlayerControllerB __instance)
		{
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			if (!_holdingBody || (Object)(object)__instance != (Object)(object)Store.LocalPlayer)
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || !__instance.isPlayerDead || !StillHolding(__instance))
			{
				bool num = _deferredGameOver && (Object)(object)instance != (Object)null && instance.allPlayersDead && (Object)(object)__instance != (Object)null && __instance.isPlayerDead;
				End();
				if (!num)
				{
					return;
				}
				_replayingGameOver = true;
				try
				{
					instance.SetSpectateCameraToGameOverMode(true, (PlayerControllerB)null);
					return;
				}
				finally
				{
					_replayingGameOver = false;
				}
			}
			if (__instance.isInGameOverAnimation < 0.25f)
			{
				__instance.isInGameOverAnimation = 0.25f;
			}
			if (instance.overrideSpectateCamera)
			{
				_deferredGameOver = true;
				_replayingGameOver = true;
				try
				{
					instance.SetSpectateCameraToGameOverMode(false, __instance);
				}
				finally
				{
					_replayingGameOver = false;
				}
			}
			if (_fpActive)
			{
				ApplyCamera(instant: false);
			}
			else if (!IsBodyUsable(_body) && (Object)(object)instance.spectateCamera != (Object)null)
			{
				((Component)instance.spectateCamera).transform.position = _fallbackOrigin - _curRot * Vector3.forward * 1.6f + Vector3.up * 0.5f;
				((Component)instance.spectateCamera).transform.LookAt(_fallbackOrigin - Vector3.up * 0.35f);
			}
		}

		internal static void SyncNow()
		{
			if (_fpActive && _holdingBody)
			{
				ApplyCamera(instant: false);
			}
		}

		private static bool IsBodyUsable(DeadBodyInfo body)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)body != (Object)null && ((Component)body).gameObject.activeInHierarchy)
			{
				Vector3 localScale = ((Component)body).transform.localScale;
				return ((Vector3)(ref localScale)).sqrMagnitude > 0.01f;
			}
			return false;
		}

		private static void ApplyCamera(bool instant)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			//IL_03aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_035e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0398: Unknown result type (might be due to invalid IL or missing references)
			//IL_039d: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			Camera val = (((Object)(object)instance != (Object)null) ? instance.spectateCamera : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			float num = (instant ? 0f : Mathf.Clamp(unscaledTime - _lastSimAt, 0f, 0.08f));
			_lastSimAt = unscaledTime;
			Quaternion val6;
			if (!_useFallback && IsBodyUsable(_body) && (Object)(object)_head != (Object)null && ((Component)_head).gameObject.activeInHierarchy)
			{
				Vector3 val2 = _head.TransformPoint(_localPos) + Vector3.up * 0.06f;
				Quaternion val3 = _head.rotation * _localRot;
				Vector3 val4 = val3 * Vector3.forward;
				Vector3 val5 = Vector3.Slerp(val3 * Vector3.up, Vector3.up, 0.45f);
				Vector3 normalized = ((Vector3)(ref val5)).normalized;
				val6 = ((((Vector3)(ref val4)).sqrMagnitude > 0.001f) ? Quaternion.LookRotation(val4, (((Vector3)(ref normalized)).sqrMagnitude > 0.001f) ? normalized : Vector3.up) : val3);
				Vector3 eulerAngles = ((Quaternion)(ref val6)).eulerAngles;
				float num2 = ((eulerAngles.z > 180f) ? (eulerAngles.z - 360f) : eulerAngles.z);
				if (Mathf.Abs(num2) > 55f)
				{
					val6 = Quaternion.Euler(eulerAngles.x, eulerAngles.y, Mathf.Clamp(num2, -55f, 55f));
				}
				if (instant)
				{
					_curPos = val2;
					_curRot = val6;
				}
				else
				{
					_curPos = Vector3.Lerp(_curPos, val2, 1f - Mathf.Exp(-16f * num));
					_curRot = Quaternion.Slerp(_curRot, val6, 1f - Mathf.Exp(-6.5f * num));
				}
			}
			else
			{
				if (!_gibPhysicsInit)
				{
					InitGibHead();
				}
				if ((Object)(object)_gibHead == (Object)null && unscaledTime - _startedAt < 0.28f)
				{
					_gibHead = FindSpawnedHeadGib(_fallbackOrigin);
					if ((Object)(object)_gibHead != (Object)null)
					{
						HideGibMesh(_gibHead);
					}
				}
				if ((Object)(object)_gibHead != (Object)null && ((Component)_gibHead).gameObject.activeInHierarchy)
				{
					Vector3 val2 = _gibHead.position + Vector3.up * 0.05f;
					val6 = _gibHead.rotation;
					_curPos = Vector3.Lerp(_curPos, val2, 1f - Mathf.Exp(-22f * Mathf.Max(num, 0.016f)));
					_curRot = Quaternion.Slerp(_curRot, val6, 1f - Mathf.Exp(-12f * Mathf.Max(num, 0.016f)));
				}
				else
				{
					StepGibHead(num);
					_curPos = _gibPos;
					_curRot = _gibRot;
				}
			}
			Vector3 val7 = _curPos;
			Quaternion val8 = _curRot;
			if (_gibShake > 0.005f)
			{
				_gibShake = Mathf.Max(0f, _gibShake - num * 3.4f);
				float num3 = _gibShake * _gibShake;
				val7 += Random.insideUnitSphere * (0.07f * num3);
				val8 *= Quaternion.Euler(Random.Range(-10f, 10f) * num3, Random.Range(-10f, 10f) * num3, Random.Range(-14f, 14f) * num3);
			}
			((Component)val).transform.position = val7;
			((Component)val).transform.rotation = val8;
			val.fieldOfView = _fov;
		}

		private static void InitGibHead()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Invalid comparison between Unknown and I4
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Invalid comparison between Unknown and I4
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Invalid comparison between Unknown and I4
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			_gibPhysicsInit = true;
			_gibGrounded = false;
			_gibPos = _curPos;
			_gibRot = _curRot;
			_gibShake = 1f;
			_gibHead = FindSpawnedHeadGib(_curPos);
			if ((Object)(object)_gibHead != (Object)null)
			{
				HideGibMesh(_gibHead);
				return;
			}
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(_deathVelocity.x, 0f, _deathVelocity.z);
			if (((Vector3)(ref val)).sqrMagnitude < 1.5f)
			{
				float num = Random.Range(0f, 360f) * (MathF.PI / 180f);
				val = new Vector3(Mathf.Cos(num), 0f, Mathf.Sin(num)) * Random.Range(3.6f, 6f);
			}
			else
			{
				val = Vector3.ClampMagnitude(val * 0.85f, 8.5f);
				val += new Vector3(Random.Range(-1.4f, 1.4f), 0f, Random.Range(-1.4f, 1.4f));
			}
			float num2 = (((int)_cause == 3 || (int)_cause == 15 || (int)_cause == 8 || ((Vector3)(ref _deathVelocity)).magnitude > 4f) ? Random.Range(3.4f, 5.4f) : Random.Range(2.2f, 3.8f));
			_gibVel = val + Vector3.up * Mathf.Clamp(_deathVelocity.y * 0.45f + num2, 2f, 6.2f);
			float num3 = ((Random.value < 0.5f) ? (-1f) : 1f);
			float num4 = ((Random.value < 0.5f) ? (-1f) : 1f);
			float num5 = ((Random.value < 0.5f) ? (-1f) : 1f);
			_gibAngVel = new Vector3(num4 * Random.Range(125f, 230f), num3 * Random.Range(160f, 310f), num5 * Random.Range(140f, 260f));
		}

		private static void StepGibHead(float dt)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: 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_0084: 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_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			//IL_031d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0326: Unknown result type (might be due to invalid IL or missing references)
			//IL_033d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0342: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or mi