Decompiled source of QuotaRevive v1.0.0

QuotaRevive.dll

Decompiled 34 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using Microsoft.CodeAnalysis;
using QuotaRevive.Logic;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
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("Gamingregory")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Host-configurable revive rules for Lethal Company.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("QuotaRevive")]
[assembly: AssemblyTitle("QuotaRevive")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace QuotaRevive
{
	internal sealed class DeathRecord
	{
		public int Id;

		public float RealTime;

		public double LandedSecondsAtDeath;

		public double LandedHoursAtDeath;
	}
	internal static class DeathTracker
	{
		private static readonly List<DeathRecord> records = new List<DeathRecord>();

		internal static double LandedSeconds;

		internal static double LandedHours;

		internal static readonly HashSet<int> DiedThisRound = new HashSet<int>();

		internal static IReadOnlyList<DeathRecord> All => records;

		internal static DeathRecord Get(int id)
		{
			foreach (DeathRecord record in records)
			{
				if (record.Id == id)
				{
					return record;
				}
			}
			return null;
		}

		internal static void Record(PlayerControllerB p, string source)
		{
			if (!((Object)(object)p == (Object)null))
			{
				int num = (int)p.playerClientId;
				if (Get(num) == null)
				{
					records.Add(new DeathRecord
					{
						Id = num,
						RealTime = Time.realtimeSinceStartup,
						LandedSecondsAtDeath = LandedSeconds,
						LandedHoursAtDeath = LandedHours
					});
					Plugin.DebugLog($"Death recorded ({source}): {p.playerUsername} id={num}");
				}
			}
		}

		internal static void Remove(int id)
		{
			records.RemoveAll((DeathRecord r) => r.Id == id);
			DiedThisRound.Remove(id);
		}

		internal static void Clear()
		{
			records.Clear();
			DiedThisRound.Clear();
		}

		internal static void Scan(StartOfRound sor)
		{
			PlayerControllerB[] allPlayerScripts = sor.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if ((Object)(object)val != (Object)null && val.isPlayerDead)
				{
					Record(val, "scan");
				}
			}
			records.RemoveAll((DeathRecord r) => r.Id >= sor.allPlayerScripts.Length || !sor.allPlayerScripts[r.Id].isPlayerDead);
		}
	}
	internal sealed class HostController : MonoBehaviour
	{
		private sealed class Pending
		{
			public List<int> Ids;

			public double At;

			public string Reason;
		}

		internal static HostController Instance;

		private readonly VoteCoordinator votes = new VoteCoordinator();

		private readonly ReviveLimits limits = new ReviveLimits();

		private readonly QuotaWatcher quotaWatcher = new QuotaWatcher();

		private readonly QuotaPlanner quotaPlanner = new QuotaPlanner();

		private TimeTrigger timeTrigger;

		private bool lastInShipPhase = true;

		private bool lastLanded;

		private bool wasActive;

		private float landedReal;

		private float landedDayTime;

		private int deadlineFiredForQuotaIndex = -1;

		private readonly ScrapQuotaWatcher scrapWatcher = new ScrapQuotaWatcher();

		private float scrapTimer;

		private bool deferredQuota;

		private float prevDayTime;

		private bool lastSkipSent;

		private bool lastAllSent;

		private bool policySentOnce;

		private float policyTimer;

		private readonly List<Pending> pending = new List<Pending>();

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

		private readonly Dictionary<int, double> retryAt = new Dictionary<int, double>();

		private readonly Dictionary<string, double> throttle = new Dictionary<string, double>();

		private static double Now => Time.realtimeSinceStartup;

		private static bool HostActive
		{
			get
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton != (Object)null && singleton.IsListening && singleton.IsServer && (Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.allPlayerScripts != null)
				{
					return (Object)(object)GameNetworkManager.Instance != (Object)null;
				}
				return false;
			}
		}

		private void Awake()
		{
			Instance = this;
		}

		private void Update()
		{
			ReviveNet.EnsureRegistered();
			if (!HostActive)
			{
				if (wasActive)
				{
					ResetSession();
				}
				wasActive = false;
				return;
			}
			wasActive = true;
			try
			{
				Tick();
			}
			catch (Exception ex)
			{
				if (Throttle("tickerr", 10.0))
				{
					Plugin.Log.LogError((object)("QuotaRevive tick error: " + ex));
				}
			}
		}

		private void ResetSession()
		{
			votes.ResetAll();
			limits.ResetAll();
			quotaPlanner.Reset();
			pending.Clear();
			pendingIds.Clear();
			retryAt.Clear();
			DeathTracker.Clear();
			timeTrigger = null;
			lastInShipPhase = true;
			lastLanded = false;
			deadlineFiredForQuotaIndex = -1;
			deferredQuota = false;
			policySentOnce = false;
			DeathTracker.LandedSeconds = 0.0;
			DeathTracker.LandedHours = 0.0;
			Plugin.DebugLog("Session state reset (not hosting).");
		}

		private void Tick()
		{
			StartOfRound instance = StartOfRound.Instance;
			bool flag = instance.shipHasLanded && !instance.inShipPhase;
			if (lastInShipPhase && !instance.inShipPhase)
			{
				OnRoundStart();
			}
			if (!lastInShipPhase && instance.inShipPhase)
			{
				OnRoundEnd();
			}
			if (flag && !lastLanded)
			{
				OnLanded();
			}
			lastInShipPhase = instance.inShipPhase;
			lastLanded = flag;
			AccumulateLandedTime(flag);
			UpdatePolicy();
			DeathTracker.Scan(instance);
			TimeOfDay instance2 = TimeOfDay.Instance;
			if ((Object)(object)instance2 != (Object)null && quotaWatcher.Update(instance2.profitQuota, instance2.quotaFulfilled) && Settings.Mode.Value == ReviveMode.AfterQuota)
			{
				Plugin.DebugLog("Quota fulfilled.");
				TriggerQuota(QuotaTrigger.QuotaFulfilled);
			}
			TickScrapTrigger(flag);
			ProcessPending();
			switch (Settings.Mode.Value)
			{
			case ReviveMode.AfterTimeOnPlanet:
				TickTime(flag);
				break;
			case ReviveMode.Vote:
				TickVote();
				break;
			}
		}

		private void OnRoundStart()
		{
			Plugin.DebugLog("Round started.");
			limits.ResetRound();
			votes.NewRound();
			retryAt.Clear();
		}

		private void OnRoundEnd()
		{
			Plugin.DebugLog("Round ended (ship in orbit).");
			pending.Clear();
			pendingIds.Clear();
			timeTrigger = null;
			if (votes.Active && Settings.VoteCancelOnRoundEnd.Value)
			{
				CancelVote(announce: true);
			}
		}

		private void OnLanded()
		{
			landedReal = Time.realtimeSinceStartup;
			landedDayTime = (((Object)(object)TimeOfDay.Instance != (Object)null) ? TimeOfDay.Instance.currentDayTime : 0f);
			prevDayTime = landedDayTime;
			RebuildTimeTrigger();
			Plugin.DebugLog($"Ship landed. dayTime={landedDayTime}");
			if (deferredQuota)
			{
				deferredQuota = false;
				Plugin.DebugLog("Applying deferred quota revive.");
				DoQuotaRevive("deferred");
			}
			TimeOfDay instance = TimeOfDay.Instance;
			if (Settings.Mode.Value == ReviveMode.AfterQuota && (Object)(object)instance != (Object)null && instance.totalTime > 0f && Mathf.Floor(instance.timeUntilDeadline / instance.totalTime) <= 0f && deadlineFiredForQuotaIndex != instance.timesFulfilledQuota)
			{
				deadlineFiredForQuotaIndex = instance.timesFulfilledQuota;
				TriggerQuota(QuotaTrigger.DeadlineDay);
			}
		}

		internal void OnNewQuota()
		{
			limits.ResetQuota();
			deadlineFiredForQuotaIndex = -1;
			Plugin.DebugLog("New quota started.");
			if (Settings.Mode.Value == ReviveMode.AfterQuota)
			{
				TriggerQuota(QuotaTrigger.NewQuotaStarted);
			}
		}

		internal void OnSettingChanged(ConfigEntryBase e)
		{
			string section = e.Definition.Section;
			if ((object)e == Settings.Mode)
			{
				if (votes.Active && Settings.Mode.Value != ReviveMode.Vote)
				{
					CancelVote(announce: true);
				}
				RebuildTimeTrigger();
			}
			else if (section.StartsWith("2."))
			{
				RebuildTimeTrigger();
			}
		}

		private static bool CanReviveNow(out string why)
		{
			StartOfRound instance = StartOfRound.Instance;
			why = null;
			bool flag = instance.shipHasLanded && !instance.inShipPhase;
			if (instance.allPlayersDead || instance.firingPlayersCutsceneRunning)
			{
				why = "game over sequence";
			}
			else if (!flag && (Settings.OnlyWhileLanded.Value || (!instance.shipIsLeaving && !instance.inShipPhase)))
			{
				why = (instance.inShipPhase ? "ship is in orbit (OnlyWhileLanded)" : "ship is not landed");
			}
			return why == null;
		}

		private static bool IsPresent(PlayerControllerB p)
		{
			if ((Object)(object)p != (Object)null)
			{
				if (!p.isPlayerControlled)
				{
					return p.isPlayerDead;
				}
				return true;
			}
			return false;
		}

		private static string NameOf(int id)
		{
			return StartOfRound.Instance.allPlayerScripts[id].playerUsername;
		}

		private static bool IsHostPlayer(PlayerControllerB p)
		{
			if (!p.isHostPlayerObject)
			{
				return p.playerClientId == 0;
			}
			return true;
		}

		private static List<int> DeadInOrder()
		{
			StartOfRound sor = StartOfRound.Instance;
			return (from r in DeathTracker.All
				orderby r.RealTime
				select r.Id into id
				where sor.allPlayerScripts[id].isPlayerDead
				select id).ToList();
		}

		private static int AliveCount()
		{
			return StartOfRound.Instance.allPlayerScripts.Count((PlayerControllerB p) => (Object)(object)p != (Object)null && p.isPlayerControlled && !p.isPlayerDead);
		}

		private bool Throttle(string key, double seconds)
		{
			if (throttle.TryGetValue(key, out var value) && Now < value)
			{
				return false;
			}
			throttle[key] = Now + seconds;
			return true;
		}

		private void Chat(string text)
		{
			if (!string.IsNullOrEmpty(text) && !((Object)(object)HUDManager.Instance == (Object)null))
			{
				Plugin.DebugLog("chat: " + text);
				HUDManager.Instance.AddTextToChatOnServer(text, -1);
			}
		}

		private static string Fmt(ConfigEntry<string> template, params string[] kv)
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			for (int i = 0; i + 1 < kv.Length; i += 2)
			{
				dictionary[kv[i]] = kv[i + 1];
			}
			dictionary["command"] = Settings.CommandName;
			return TemplateFormatter.Format(template.Value, dictionary);
		}

		private void RebuildTimeTrigger()
		{
			if (Settings.Mode.Value != ReviveMode.AfterTimeOnPlanet || Settings.TimeBasisEntry.Value != TimeBasis.SinceLanding || !lastLanded)
			{
				timeTrigger = null;
			}
			else
			{
				timeTrigger = new TimeTrigger(Settings.TimeDelay.Value, Settings.TimeRepeatEvery.Value);
			}
		}

		private double ElapsedSince(float realStart, float dayStart)
		{
			if (Settings.TimeUnitEntry.Value == TimeUnit.RealSeconds)
			{
				return Time.realtimeSinceStartup - realStart;
			}
			TimeOfDay instance = TimeOfDay.Instance;
			return ((Object)(object)instance == (Object)null || instance.lengthOfHours <= 0f) ? 0f : ((instance.currentDayTime - dayStart) / instance.lengthOfHours);
		}

		private void TickTime(bool landed)
		{
			if (!landed)
			{
				return;
			}
			if (Settings.TimeBasisEntry.Value == TimeBasis.SinceLanding)
			{
				if (timeTrigger == null)
				{
					RebuildTimeTrigger();
				}
				if (timeTrigger != null && timeTrigger.Poll(ElapsedSince(landedReal, landedDayTime)))
				{
					List<int> list = DeadInOrder();
					Plugin.DebugLog($"Time trigger fired; dead={list.Count}");
					if (list.Count != 0 && (!Settings.TimeOnlyIfAtLeastOneAlive.Value || AliveCount() != 0))
					{
						int count = ((Settings.TimeSelection.Value == ReviveSelection.OneAtATime) ? 1 : 0);
						RequestRevive(TargetPicker.Pick(list, count), "time");
					}
				}
				return;
			}
			List<int> list2 = new List<int>();
			foreach (DeathRecord item in DeathTracker.All.OrderBy((DeathRecord x) => x.RealTime))
			{
				if (!pendingIds.Contains(item.Id) && (!retryAt.TryGetValue(item.Id, out var value) || !(Now < value)) && ((Settings.TimeUnitEntry.Value == TimeUnit.RealSeconds) ? (DeathTracker.LandedSeconds - item.LandedSecondsAtDeath) : (DeathTracker.LandedHours - item.LandedHoursAtDeath)) >= (double)Settings.TimeDelay.Value)
				{
					list2.Add(item.Id);
				}
			}
			if (list2.Count == 0 || (Settings.TimeOnlyIfAtLeastOneAlive.Value && AliveCount() == 0))
			{
				return;
			}
			if (Settings.TimeSelection.Value == ReviveSelection.OneAtATime)
			{
				list2 = list2.Take(1).ToList();
			}
			if (RequestRevive(list2, "time-since-death"))
			{
				return;
			}
			foreach (int item2 in list2)
			{
				retryAt[item2] = Now + 10.0;
			}
		}

		private void TriggerQuota(QuotaTrigger occurred)
		{
			if (quotaPlanner.Fire(occurred, Settings.QuotaTriggerEntry.Value, Settings.QuotaEveryN.Value))
			{
				if (!CanReviveNow(out var why))
				{
					deferredQuota = true;
					Plugin.DebugLog($"Quota trigger {occurred} fired while revives are not possible ({why}); deferred to the next landing.");
				}
				else
				{
					DoQuotaRevive(occurred.ToString());
				}
			}
		}

		private void DoQuotaRevive(string what)
		{
			List<int> list = DeadInOrder();
			Plugin.DebugLog($"Quota revive ({what}); dead={list.Count}");
			if (list.Count != 0)
			{
				RequestRevive(TargetPicker.Pick(list, Settings.QuotaReviveCount.Value), "quota:" + what);
			}
		}

		private void TickScrapTrigger(bool landed)
		{
			if (!landed || Settings.Mode.Value != ReviveMode.AfterQuota || Settings.QuotaTriggerEntry.Value != QuotaTrigger.ScrapCollectedReachesQuota)
			{
				return;
			}
			scrapTimer -= Time.deltaTime;
			if (scrapTimer > 0f)
			{
				return;
			}
			scrapTimer = 2f;
			TimeOfDay instance = TimeOfDay.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				int valueOfAllScrap = StartOfRound.Instance.GetValueOfAllScrap(true, false);
				if (scrapWatcher.Update(instance.timesFulfilledQuota, instance.profitQuota, instance.quotaFulfilled, valueOfAllScrap))
				{
					Plugin.Log.LogInfo((object)$"Scrap on ship ({valueOfAllScrap}) + sold ({instance.quotaFulfilled}) reached the quota ({instance.profitQuota}).");
					TriggerQuota(QuotaTrigger.ScrapCollectedReachesQuota);
				}
			}
		}

		private void AccumulateLandedTime(bool landed)
		{
			TimeOfDay instance = TimeOfDay.Instance;
			if (landed && !((Object)(object)instance == (Object)null))
			{
				DeathTracker.LandedSeconds += Time.deltaTime;
				float num = instance.currentDayTime - prevDayTime;
				if (num > 0f && instance.lengthOfHours > 0f && num < 500f)
				{
					DeathTracker.LandedHours += num / instance.lengthOfHours;
				}
				prevDayTime = instance.currentDayTime;
			}
		}

		private void UpdatePolicy()
		{
			bool flag = EndOfDayPolicy.DisableVanillaEffective(Settings.Mode.Value, Settings.DisableVanillaRevive.Value);
			bool value = Settings.ReviveAllIfEveryoneDead.Value;
			HostPolicy.SkipDead = flag;
			HostPolicy.ReviveAllIfEveryoneDead = value;
			policyTimer -= Time.deltaTime;
			if (!policySentOnce || flag != lastSkipSent || value != lastAllSent || policyTimer <= 0f)
			{
				policySentOnce = true;
				lastSkipSent = flag;
				lastAllSent = value;
				policyTimer = 5f;
				ReviveNet.SendPolicy(flag, value);
			}
		}

		internal void SendPolicyTo(ulong clientId)
		{
			ReviveNet.SendPolicy(HostPolicy.SkipDead, HostPolicy.ReviveAllIfEveryoneDead, clientId);
		}

		internal bool RequestRevive(List<int> ids, string reason)
		{
			StartOfRound sor = StartOfRound.Instance;
			bool allowAlive = reason == "vote-alive";
			ids = ids.Where((int id) => id >= 0 && id < sor.allPlayerScripts.Length && !pendingIds.Contains(id) && (sor.allPlayerScripts[id].isPlayerDead || (allowAlive && IsPresent(sor.allPlayerScripts[id])))).ToList();
			if (ids.Count == 0)
			{
				return false;
			}
			if (!CanReviveNow(out var why))
			{
				Plugin.Log.LogInfo((object)("Revive (" + reason + ") skipped: " + why + "."));
				return false;
			}
			if (Settings.RequireModOnAllPlayers.Value && !ReviveNet.AllClientsModded(out var missing))
			{
				Plugin.Log.LogWarning((object)("Revive (" + reason + ") blocked: clients without QuotaRevive: " + string.Join(",", missing) + " (RequireModOnAllPlayers=true)."));
				if (Throttle("nomod", 20.0))
				{
					Chat(Fmt(Settings.MsgNoMod));
				}
				return false;
			}
			int num = limits.Allow(ids.Count, Settings.MaxRevivesPerRound.Value, Settings.MaxRevivesPerQuota.Value, Settings.MaxRevivesTotal.Value);
			if (num <= 0)
			{
				Plugin.Log.LogInfo((object)$"Revive ({reason}) blocked by limits (round {limits.Round}, quota {limits.Quota}, total {limits.Total}).");
				if (Throttle("limit", 20.0))
				{
					Chat(Fmt(Settings.MsgLimit));
				}
				return false;
			}
			ids = ids.Take(num).ToList();
			int value = Settings.ReviveDelaySeconds.Value;
			if (value > 0)
			{
				pending.Add(new Pending
				{
					Ids = ids,
					At = Now + (double)value,
					Reason = reason
				});
				foreach (int id in ids)
				{
					pendingIds.Add(id);
				}
				Chat(Fmt(Settings.MsgCountdown, "target", Names(ids), "seconds", value.ToString()));
				return true;
			}
			return Execute(ids, reason);
		}

		private void ProcessPending()
		{
			if (pending.Count == 0)
			{
				return;
			}
			foreach (Pending p in pending.Where((Pending x) => Now >= x.At).ToList())
			{
				pending.Remove(p);
				foreach (int id in p.Ids)
				{
					pendingIds.Remove(id);
				}
				List<int> list = p.Ids.Where((int id) => StartOfRound.Instance.allPlayerScripts[id].isPlayerDead || p.Reason == "vote-alive").ToList();
				string why = "no longer dead";
				if (list.Count > 0 && CanReviveNow(out why))
				{
					Execute(list, p.Reason);
					continue;
				}
				Plugin.Log.LogInfo((object)("Delayed revive (" + p.Reason + ") dropped: " + why + "."));
			}
		}

		private bool Execute(List<int> ids, string reason)
		{
			List<ReviveInfo> list = ids.Select(BuildInfo).ToList();
			foreach (ReviveInfo item in list)
			{
				Plugin.Log.LogInfo((object)$"Reviving {NameOf(item.PlayerId)} (id {item.PlayerId}) reason={reason} -> ship, empty hands");
			}
			ReviveNet.SendRevive(list);
			limits.Record(ids.Count);
			if (Settings.AnnounceRevives.Value)
			{
				Chat(Fmt(Settings.MsgRevived, "target", Names(ids), "seconds", "0"));
			}
			return true;
		}

		private static string Names(IEnumerable<int> ids)
		{
			return string.Join(", ", ids.Select(NameOf));
		}

		private ReviveInfo BuildInfo(int id)
		{
			return new ReviveInfo
			{
				PlayerId = id,
				Health = Settings.ReviveHealth.Value,
				Stamina = Settings.RestoreStamina.Value,
				Insanity = Settings.ClearInsanity.Value
			};
		}

		internal void DespawnLater(RagdollGrabbableObject rag)
		{
			((MonoBehaviour)this).StartCoroutine(DespawnRoutine(rag));
		}

		private IEnumerator DespawnRoutine(RagdollGrabbableObject rag)
		{
			yield return (object)new WaitForSeconds(0.75f);
			if ((Object)(object)rag == (Object)null)
			{
				yield break;
			}
			try
			{
				if (((GrabbableObject)rag).isHeld && (Object)(object)((GrabbableObject)rag).playerHeldBy != (Object)null)
				{
					((GrabbableObject)rag).playerHeldBy.DropAllHeldItems(true, false, false, false, default(Vector3), default(Vector3), default(Vector3), default(Vector3), default(Vector3));
				}
				if ((Object)(object)((NetworkBehaviour)rag).NetworkObject != (Object)null && ((NetworkBehaviour)rag).NetworkObject.IsSpawned)
				{
					((NetworkBehaviour)rag).NetworkObject.Despawn(true);
				}
				else
				{
					Object.Destroy((Object)(object)((Component)rag).gameObject);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not despawn ragdoll object: " + ex.Message));
			}
		}

		internal void OnChat(int playerId, string message)
		{
			if (!HostActive)
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if (playerId < 0 || playerId >= instance.allPlayerScripts.Length)
			{
				return;
			}
			PlayerControllerB val = instance.allPlayerScripts[playerId];
			if (ChatParser.TryParseCommand(message, Settings.CommandName, out var args))
			{
				Plugin.DebugLog("Command from " + val.playerUsername + ": '" + message + "'");
				HandleCommand(val, args);
			}
			else
			{
				int num = ChatParser.ParseVote(message);
				if (num != 0 && votes.Active && Settings.Mode.Value == ReviveMode.Vote && Settings.VoteAllowChat.Value)
				{
					HandleVote(val, num == 1);
				}
			}
		}

		private void HandleCommand(PlayerControllerB sender, string args)
		{
			StartOfRound instance = StartOfRound.Instance;
			int num = (int)sender.playerClientId;
			string playerUsername = sender.playerUsername;
			if (Settings.Mode.Value != ReviveMode.Vote)
			{
				Chat(Fmt(Settings.MsgDisabled, "requester", playerUsername));
				return;
			}
			if (!CanReviveNow(out var why))
			{
				Plugin.DebugLog("Command rejected: " + why);
				Chat(Fmt(Settings.MsgNotLanded, "requester", playerUsername));
				return;
			}
			List<PlayerControllerB> list = instance.allPlayerScripts.Where(IsPresent).ToList();
			List<PlayerControllerB> list2 = list.Where((PlayerControllerB p) => p.isPlayerDead).ToList();
			if (string.IsNullOrWhiteSpace(args))
			{
				Chat(Fmt(Settings.MsgUsage, "requester", playerUsername, "list", (list2.Count == 0) ? "none" : string.Join(", ", list2.Select((PlayerControllerB p) => p.playerUsername))));
				return;
			}
			NameMatchResult nameMatchResult = NameMatcher.Match(args, list2.Select((PlayerControllerB p) => new NameEntry((int)p.playerClientId, p.playerUsername)));
			if (nameMatchResult.Kind == MatchKind.Ambiguous)
			{
				ReportAmbiguous(playerUsername, args, nameMatchResult);
				return;
			}
			int id;
			if (nameMatchResult.Kind == MatchKind.Single)
			{
				id = nameMatchResult.Id;
			}
			else
			{
				NameMatchResult nameMatchResult2 = NameMatcher.Match(args, list.Select((PlayerControllerB p) => new NameEntry((int)p.playerClientId, p.playerUsername)));
				if (nameMatchResult2.Kind == MatchKind.Ambiguous)
				{
					ReportAmbiguous(playerUsername, args, nameMatchResult2);
					return;
				}
				if (nameMatchResult2.Kind == MatchKind.None)
				{
					Chat(Fmt(Settings.MsgNotFound, "requester", playerUsername, "target", args));
					return;
				}
				id = nameMatchResult2.Id;
				if (Settings.VoteRequireTargetDead.Value)
				{
					Chat(Fmt(Settings.MsgNotDead, "requester", playerUsername, "target", NameOf(id)));
					return;
				}
			}
			string text = NameOf(id);
			string reason = (instance.allPlayerScripts[id].isPlayerDead ? "vote" : "vote-alive");
			if (Settings.VoteHostForce.Value && IsHostPlayer(sender))
			{
				Plugin.DebugLog("Host force revive of " + text);
				RequestRevive(new List<int> { id }, reason);
				return;
			}
			if (sender.isPlayerDead && Settings.VoteWho.Value == WhoCanVote.AliveOnly)
			{
				Chat(Fmt(Settings.MsgRequesterDead, "requester", playerUsername));
				return;
			}
			double remaining;
			switch (votes.CanStart(num, Now, Settings.VoteCooldown.Value, Settings.VotePerPlayerCooldown.Value, Settings.VoteMaxPerRound.Value, out remaining))
			{
			case StartCheck.AlreadyRunning:
				Chat(Fmt(Settings.MsgAlreadyRunning, "requester", playerUsername));
				return;
			case StartCheck.GlobalCooldown:
			case StartCheck.PlayerCooldown:
				Chat(Fmt(Settings.MsgCooldown, "requester", playerUsername, "seconds", Mathf.CeilToInt((float)remaining).ToString()));
				return;
			case StartCheck.RoundLimit:
				Chat(Fmt(Settings.MsgLimit, "requester", playerUsername));
				return;
			}
			if (limits.Allow(1, Settings.MaxRevivesPerRound.Value, Settings.MaxRevivesPerQuota.Value, Settings.MaxRevivesTotal.Value) <= 0)
			{
				Chat(Fmt(Settings.MsgLimit, "requester", playerUsername));
				return;
			}
			List<int> list3 = new List<int>();
			foreach (PlayerControllerB item in list)
			{
				int num2 = (int)item.playerClientId;
				bool flag = (item.isPlayerDead ? (Settings.VoteWho.Value == WhoCanVote.EveryoneIncludingDead) : item.isPlayerControlled);
				if (num2 == id && !Settings.VoteTargetCanVote.Value)
				{
					flag = false;
				}
				if (flag)
				{
					list3.Add(num2);
				}
			}
			if (list3.Count == 0)
			{
				Chat(Fmt(Settings.MsgNoVoters, "requester", playerUsername));
				return;
			}
			VoteSession voteSession = new VoteSession(Settings.ToVoteSettings(), num, id, list3, Now);
			votes.Begin(voteSession, Now);
			Plugin.Log.LogInfo((object)$"Vote started: {playerUsername} -> revive {text}; eligible={list3.Count} needed={voteSession.Needed}");
			VoteChat(Fmt(Settings.MsgVoteStarted, "requester", playerUsername, "target", text, "seconds", Settings.VoteDuration.Value.ToString(), "needed", voteSession.Needed.ToString()));
			if (Settings.VoteRequesterAutoYes.Value && voteSession.IsEligible(num))
			{
				voteSession.Cast(num, yes: true);
			}
			BroadcastVoteState();
		}

		private void ReportAmbiguous(string requester, string typed, NameMatchResult m)
		{
			Chat(Fmt(Settings.MsgAmbiguous, "requester", requester, "target", typed, "list", string.Join(", ", m.Candidates.Select((NameEntry c) => c.Name))));
		}

		private void HandleVote(PlayerControllerB sender, bool yes)
		{
			VoteSession current = votes.Current;
			CastResult castResult = current.Cast((int)sender.playerClientId, yes);
			Plugin.DebugLog(string.Format("Vote from {0}: {1} -> {2} (yes {3}, no {4}, eligible {5}, needed {6})", sender.playerUsername, yes ? "yes" : "no", castResult, current.Yes, current.No, current.Eligible, current.Needed));
			if (castResult == CastResult.Counted || castResult == CastResult.Changed)
			{
				BroadcastVoteState();
				if (Settings.VoteAnnounceProgress.Value)
				{
					VoteChat(Fmt(Settings.MsgVoteProgress, "target", NameOf(current.TargetId), "yes", current.Yes.ToString(), "no", current.No.ToString(), "needed", current.Needed.ToString()));
				}
			}
		}

		internal void OnPopupVote(ulong senderClientId, bool yes)
		{
			if (HostActive && votes.Active && Settings.Mode.Value == ReviveMode.Vote)
			{
				PlayerControllerB val = ((IEnumerable<PlayerControllerB>)StartOfRound.Instance.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB x) => IsPresent(x) && ((NetworkBehaviour)x).OwnerClientId == senderClientId));
				if ((Object)(object)val == (Object)null)
				{
					Plugin.DebugLog($"Popup vote from unknown client {senderClientId}.");
				}
				else
				{
					HandleVote(val, yes);
				}
			}
		}

		private void VoteChat(string text)
		{
			if (Settings.VoteAnnounceInChat.Value)
			{
				Chat(text);
			}
		}

		private string[] VoteFmtArgs(VoteSession s)
		{
			return new string[12]
			{
				"requester",
				NameOf(s.RequesterId),
				"target",
				NameOf(s.TargetId),
				"yes",
				s.Yes.ToString(),
				"no",
				s.No.ToString(),
				"needed",
				s.Needed.ToString(),
				"seconds",
				Mathf.CeilToInt((float)s.SecondsLeft(Now)).ToString()
			};
		}

		private void BroadcastVoteState()
		{
			VoteSession current = votes.Current;
			if (current == null)
			{
				return;
			}
			NetworkManager singleton = NetworkManager.Singleton;
			StartOfRound instance = StartOfRound.Instance;
			string header = Fmt(Settings.MsgPopupHeader, VoteFmtArgs(current));
			for (int i = 0; i < instance.allPlayerScripts.Length; i++)
			{
				PlayerControllerB val = instance.allPlayerScripts[i];
				if (IsPresent(val) && singleton.ConnectedClientsIds.Contains(((NetworkBehaviour)val).OwnerClientId))
				{
					PopupStateData d = new PopupStateData
					{
						Header = header,
						YesLabel = Settings.MsgPopupAccept.Value,
						NoLabel = Settings.MsgPopupDeny.Value,
						Duration = Settings.VoteDuration.Value,
						SecondsLeft = (float)current.SecondsLeft(Now),
						Yes = current.Yes,
						No = current.No,
						Needed = current.Needed,
						Eligible = current.Eligible,
						MyVote = current.VoteOf(i),
						CanVote = current.IsEligible(i)
					};
					ReviveNet.SendVoteState(((NetworkBehaviour)val).OwnerClientId, 1, d, null, passed: false);
				}
			}
		}

		private void BroadcastVoteResult(string text, bool passed)
		{
			foreach (ulong item in NetworkManager.Singleton.ConnectedClientsIds.ToList())
			{
				ReviveNet.SendVoteState(item, 2, null, text, passed);
			}
		}

		private void TickVote()
		{
			VoteSession current = votes.Current;
			if (current == null)
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			bool flag = false;
			for (int i = 0; i < instance.allPlayerScripts.Length; i++)
			{
				if (current.IsEligible(i) && !IsPresent(instance.allPlayerScripts[i]))
				{
					current.RemoveVoter(i);
					flag = true;
					Plugin.DebugLog($"Voter {i} left; removed from vote.");
				}
			}
			PlayerControllerB val = instance.allPlayerScripts[current.TargetId];
			if (!IsPresent(val))
			{
				CancelVote(announce: true);
				return;
			}
			if (Settings.VoteRequireTargetDead.Value && !val.isPlayerDead)
			{
				Plugin.DebugLog("Vote target is no longer dead.");
				CancelVote(announce: true);
				return;
			}
			VoteOutcome voteOutcome = current.Evaluate(Now);
			if (voteOutcome == VoteOutcome.Pending)
			{
				if (flag)
				{
					BroadcastVoteState();
				}
				return;
			}
			votes.End(Now);
			string text = NameOf(current.TargetId);
			Plugin.Log.LogInfo((object)$"Vote for {text} ended: {voteOutcome} (yes {current.Yes}, no {current.No}, eligible {current.Eligible}, needed {current.Needed})");
			if (voteOutcome == VoteOutcome.Passed)
			{
				VoteChat(Fmt(Settings.MsgVotePassed, VoteFmtArgs(current)));
				BroadcastVoteResult(Fmt(Settings.MsgPopupPassed, VoteFmtArgs(current)), passed: true);
				RequestRevive(new List<int> { current.TargetId }, val.isPlayerDead ? "vote" : "vote-alive");
			}
			else
			{
				VoteChat(Fmt(Settings.MsgVoteFailed, VoteFmtArgs(current)));
				BroadcastVoteResult(Fmt(Settings.MsgPopupFailed, VoteFmtArgs(current)), passed: false);
			}
		}

		private void CancelVote(bool announce)
		{
			VoteSession current = votes.Current;
			if (current != null)
			{
				string[] kv = VoteFmtArgs(current);
				votes.Cancel();
				Plugin.Log.LogInfo((object)"Vote cancelled.");
				if (announce)
				{
					VoteChat(Fmt(Settings.MsgVoteCancelled, kv));
					BroadcastVoteResult(Fmt(Settings.MsgPopupCancelled, kv), passed: false);
				}
				else
				{
					BroadcastVoteResult("", passed: false);
				}
			}
		}
	}
	internal static class LethalConfigBridge
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static CanModifyDelegate <0>__CanModify;
		}

		private static Sprite iconSprite;

		internal static CanModifyResult CanModify()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
			{
				return CanModifyResult.True();
			}
			if (!singleton.IsHost)
			{
				return CanModifyResult.False("Only the host can change this");
			}
			return CanModifyResult.True();
		}

		private static bool IsHostOnly(ConfigEntryBase e)
		{
			if (!e.Definition.Section.StartsWith("6."))
			{
				return !e.Definition.Section.StartsWith("7.");
			}
			return false;
		}

		private static BaseOptions Prep(BaseOptions o, ConfigEntryBase e)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			o.RequiresRestart = false;
			if (IsHostOnly(e))
			{
				object obj = <>O.<0>__CanModify;
				if (obj == null)
				{
					CanModifyDelegate val = CanModify;
					<>O.<0>__CanModify = val;
					obj = (object)val;
				}
				o.CanModifyCallback = (CanModifyDelegate)obj;
			}
			return o;
		}

		private static void SetIcon()
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_00c1: 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)
			try
			{
				if ((Object)(object)iconSprite == (Object)null)
				{
					using Stream stream = typeof(LethalConfigBridge).Assembly.GetManifestResourceStream("QuotaRevive.icon.png");
					if (stream == null)
					{
						Plugin.Log.LogWarning((object)"LethalConfig icon: embedded icon.png not found.");
						return;
					}
					byte[] array = new byte[stream.Length];
					int num;
					for (int i = 0; i < array.Length; i += num)
					{
						num = stream.Read(array, i, array.Length - i);
						if (num <= 0)
						{
							break;
						}
					}
					Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
					if (!ImageConversion.LoadImage(val, array, true))
					{
						Plugin.Log.LogWarning((object)"LethalConfig icon: could not decode icon.png.");
						return;
					}
					((Texture)val).filterMode = (FilterMode)1;
					((Object)val).hideFlags = (HideFlags)61;
					iconSprite = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
					((Object)iconSprite).hideFlags = (HideFlags)61;
				}
				LethalConfigManager.SetModIcon(iconSprite);
				Plugin.Log.LogInfo((object)$"LethalConfig icon set ({((Texture)iconSprite.texture).width}x{((Texture)iconSprite.texture).height}).");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("LethalConfig icon failed: " + ex.Message));
			}
		}

		internal static void Register()
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//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_0146: Expected O, but got Unknown
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Expected O, but got Unknown
			//IL_015a: Expected O, but got Unknown
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Expected O, but got Unknown
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Expected O, but got Unknown
			//IL_0121: Expected O, but got Unknown
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Expected O, but got Unknown
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected O, but got Unknown
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Expected O, but got Unknown
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Expected O, but got Unknown
			//IL_01a6: Expected O, but got Unknown
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Expected O, but got Unknown
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Expected O, but got Unknown
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Expected O, but got Unknown
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Expected O, but got Unknown
			LethalConfigManager.SetModDescription("This mod allows the host to config the game to change revive time, whether that being each planet, after time frames, after reaching a quota, or through a vote system.");
			SetIcon();
			List<ConfigEntryBase> list = new List<ConfigEntryBase>();
			foreach (ConfigDefinition key in ((BaseUnityPlugin)Plugin.Instance).Config.Keys)
			{
				list.Add(((BaseUnityPlugin)Plugin.Instance).Config[key]);
			}
			foreach (ConfigEntryBase item in list)
			{
				BaseConfigItem val = null;
				if (!(item is ConfigEntry<bool> val2))
				{
					if (!(item is ConfigEntry<int> val3))
					{
						if (!(item is ConfigEntry<float> val4))
						{
							val = (BaseConfigItem)((!(item is ConfigEntry<string> val5)) ? ((object)RegisterEnum(item)) : ((object)new TextInputFieldConfigItem(val5, (TextInputFieldOptions)Prep((BaseOptions)new TextInputFieldOptions
							{
								CharacterLimit = 160,
								TrimText = true
							}, item))));
						}
						else
						{
							AcceptableValueRange<float> val6 = (AcceptableValueRange<float>)(object)((ConfigEntryBase)val4).Description.AcceptableValues;
							FloatInputFieldOptions val7 = new FloatInputFieldOptions();
							((BaseRangeOptions<float>)val7).Min = val6.MinValue;
							((BaseRangeOptions<float>)val7).Max = val6.MaxValue;
							val = (BaseConfigItem)new FloatInputFieldConfigItem(val4, (FloatInputFieldOptions)Prep((BaseOptions)val7, item));
						}
					}
					else
					{
						AcceptableValueRange<int> val8 = (AcceptableValueRange<int>)(object)((ConfigEntryBase)val3).Description.AcceptableValues;
						if (val8.MaxValue - val8.MinValue <= 100)
						{
							IntSliderOptions val9 = new IntSliderOptions();
							((BaseRangeOptions<int>)val9).Min = val8.MinValue;
							((BaseRangeOptions<int>)val9).Max = val8.MaxValue;
							val = (BaseConfigItem)new IntSliderConfigItem(val3, (IntSliderOptions)Prep((BaseOptions)val9, item));
						}
						else
						{
							IntInputFieldOptions val10 = new IntInputFieldOptions();
							((BaseRangeOptions<int>)val10).Min = val8.MinValue;
							((BaseRangeOptions<int>)val10).Max = val8.MaxValue;
							val = (BaseConfigItem)new IntInputFieldConfigItem(val3, (IntInputFieldOptions)Prep((BaseOptions)val10, item));
						}
					}
				}
				else
				{
					val = (BaseConfigItem)new BoolCheckBoxConfigItem(val2, (BoolCheckBoxOptions)Prep((BaseOptions)new BoolCheckBoxOptions(), item));
				}
				if (val != null)
				{
					LethalConfigManager.AddConfigItem(val);
				}
				else
				{
					Plugin.Log.LogWarning((object)$"LethalConfig: unsupported entry type for {item.Definition}");
				}
			}
			Plugin.Log.LogInfo((object)$"Registered {list.Count} settings with LethalConfig.");
		}

		private static BaseConfigItem RegisterEnum(ConfigEntryBase e)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			EnumDropDownOptions val = (EnumDropDownOptions)Prep((BaseOptions)new EnumDropDownOptions(), e);
			if (e is ConfigEntry<ReviveMode> val2)
			{
				return (BaseConfigItem)(object)new EnumDropDownConfigItem<ReviveMode>(val2, val);
			}
			if (e is ConfigEntry<Key> val3)
			{
				return (BaseConfigItem)(object)new EnumDropDownConfigItem<Key>(val3, val);
			}
			if (e is ConfigEntry<TimeUnit> val4)
			{
				return (BaseConfigItem)(object)new EnumDropDownConfigItem<TimeUnit>(val4, val);
			}
			if (e is ConfigEntry<TimeBasis> val5)
			{
				return (BaseConfigItem)(object)new EnumDropDownConfigItem<TimeBasis>(val5, val);
			}
			if (e is ConfigEntry<ReviveSelection> val6)
			{
				return (BaseConfigItem)(object)new EnumDropDownConfigItem<ReviveSelection>(val6, val);
			}
			if (e is ConfigEntry<QuotaTrigger> val7)
			{
				return (BaseConfigItem)(object)new EnumDropDownConfigItem<QuotaTrigger>(val7, val);
			}
			if (e is ConfigEntry<WhoCanVote> val8)
			{
				return (BaseConfigItem)(object)new EnumDropDownConfigItem<WhoCanVote>(val8, val);
			}
			if (e is ConfigEntry<AbstainRule> val9)
			{
				return (BaseConfigItem)(object)new EnumDropDownConfigItem<AbstainRule>(val9, val);
			}
			return null;
		}
	}
	internal static class LocalRevive
	{
		private static readonly MethodInfo GetSpawnPos = AccessTools.Method(typeof(StartOfRound), "GetPlayerSpawnPosition", (Type[])null, (Type[])null);

		internal static void Apply(ReviveInfo r)
		{
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: 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_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: 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_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || r.PlayerId < 0 || r.PlayerId >= instance.allPlayerScripts.Length)
			{
				return;
			}
			PlayerControllerB val = instance.allPlayerScripts[r.PlayerId];
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			bool isPlayerDead = val.isPlayerDead;
			if (!isPlayerDead && !val.isPlayerControlled)
			{
				return;
			}
			Plugin.DebugLog($"LocalRevive: {val.playerUsername} (id {r.PlayerId}) wasDead={isPlayerDead} owner={((NetworkBehaviour)val).IsOwner}");
			val.ResetPlayerBloodObjects(isPlayerDead);
			val.isClimbingLadder = false;
			if (!val.inSpecialInteractAnimation || (Object)(object)val.currentTriggerInAnimationWith == (Object)null || !Object.op_Implicit((Object)(object)((Component)val.currentTriggerInAnimationWith).GetComponentInChildren<MoveToExitSpecialAnimation>()))
			{
				val.clampLooking = false;
				Vector3 localEulerAngles = ((Component)val.gameplayCamera).transform.localEulerAngles;
				((Component)val.gameplayCamera).transform.localEulerAngles = new Vector3(localEulerAngles.x, 0f, localEulerAngles.z);
				val.inVehicleAnimation = false;
			}
			val.overridePoisonValue = false;
			val.disableMoveInput = false;
			val.ResetZAndXRotation();
			((Collider)val.thisController).enabled = true;
			val.health = r.Health;
			val.hasBeenCriticallyInjured = false;
			val.disableLookInput = false;
			val.disableInteract = false;
			((Behaviour)val.nightVisionRadar).enabled = false;
			Vector3 val2 = (Vector3)GetSpawnPos.Invoke(instance, new object[2] { r.PlayerId, false });
			if (isPlayerDead)
			{
				val.isPlayerDead = false;
				val.enemyWaitingForBodyRagdoll = null;
				val.isPlayerControlled = true;
				val.isInElevator = true;
				val.isInHangarShipRoom = true;
				val.isInsideFactory = false;
				val.parentedToElevatorLastFrame = false;
				val.overrideGameOverSpectatePivot = null;
				instance.SetPlayerObjectExtrapolate(false);
				val.TeleportPlayer(val2, false, 0f, false, true);
				val.setPositionOfDeadPlayer = false;
				val.DisablePlayerModel(instance.allPlayerObjects[r.PlayerId], true, true);
				((Behaviour)val.helmetLight).enabled = false;
				val.Crouch(false);
				val.criticallyInjured = false;
				if ((Object)(object)val.playerBodyAnimator != (Object)null)
				{
					val.playerBodyAnimator.SetBool("Limp", false);
				}
				val.bleedingHeavily = false;
				val.activatingItem = false;
				val.twoHanded = false;
				val.inShockingMinigame = false;
				val.inSpecialInteractAnimation = false;
				val.freeRotationInInteractAnimation = false;
				val.disableSyncInAnimation = false;
				val.inAnimationWithEnemy = null;
				val.holdingWalkieTalkie = false;
				val.speakingToWalkieTalkie = false;
				val.isSinking = false;
				val.isUnderwater = false;
				val.sinkingValue = 0f;
				val.statusEffectAudio.Stop();
				val.DisableJetpackControlsLocally();
				val.health = r.Health;
				val.mapRadarDotAnimator.SetBool("dead", false);
				val.externalForceAutoFade = Vector3.zero;
				val.carryWeight = 1f;
				ClearHandsLocally(val);
				if (((NetworkBehaviour)val).IsOwner)
				{
					HUDManager.Instance.SetCracksOnVisor(100f);
					HUDManager.Instance.gasHelmetAnimator.SetBool("gasEmitting", false);
					val.hasBegunSpectating = false;
					HUDManager.Instance.RemoveSpectateUI();
					HUDManager.Instance.gameOverAnimator.SetTrigger("revive");
					val.hinderedMultiplier = 1f;
					val.isMovementHindered = 0;
					val.sourcesCausingSinking = 0;
					instance.SendChangedWeightEvent();
					val.reverbPreset = instance.shipReverb;
					HUDManager.Instance.HideHUD(false);
				}
			}
			else
			{
				val.TeleportPlayer(val2, false, 0f, false, true);
				val.isInElevator = true;
				val.isInHangarShipRoom = true;
				val.isInsideFactory = false;
			}
			if (((NetworkBehaviour)val).IsOwner)
			{
				if (r.Stamina)
				{
					val.sprintMeter = 1f;
				}
				if (r.Insanity)
				{
					val.insanityLevel = 0f;
				}
				val.bleedingHeavily = false;
				val.criticallyInjured = false;
				if ((Object)(object)val.playerBodyAnimator != (Object)null)
				{
					val.playerBodyAnimator.SetBool("Limp", false);
				}
				HUDManager.Instance.UpdateHealthUI(val.health, false);
			}
			SoundManager.Instance.playerVoicePitchTargets[r.PlayerId] = 1f;
			SoundManager.Instance.SetPlayerPitch(1f, r.PlayerId);
			val.voiceMuffledByEnemy = false;
			if ((Object)(object)val.currentVoiceChatIngameSettings == (Object)null)
			{
				instance.RefreshPlayerVoicePlaybackObjects();
			}
			if ((Object)(object)val.currentVoiceChatIngameSettings != (Object)null)
			{
				if ((Object)(object)val.currentVoiceChatIngameSettings.voiceAudio == (Object)null)
				{
					val.currentVoiceChatIngameSettings.InitializeComponents();
				}
				if ((Object)(object)val.currentVoiceChatIngameSettings.voiceAudio != (Object)null)
				{
					OccludeAudio component = ((Component)val.currentVoiceChatIngameSettings.voiceAudio).GetComponent<OccludeAudio>();
					if ((Object)(object)component != (Object)null)
					{
						component.overridingLowPass = false;
					}
				}
			}
			if (isPlayerDead)
			{
				if ((Object)(object)localPlayerController == (Object)(object)val)
				{
					localPlayerController.spectatedPlayerScript = null;
					((Behaviour)HUDManager.Instance.audioListenerLowPass).enabled = false;
					HUDManager.Instance.cadaverFilter = 0f;
					HUDManager.Instance.spitOnCameraAlpha = 1f;
					SoundManager.Instance.earsRingingTimer = 0f;
					SoundManager.Instance.alternateEarsRinging = false;
					instance.SetSpectateCameraToGameOverMode(false, localPlayerController);
				}
				CleanupBody(instance, r.PlayerId);
				instance.livingPlayers = Mathf.Min(instance.livingPlayers + 1, instance.connectedPlayersAmount + 1);
				instance.allPlayersDead = false;
				DeathTracker.Remove(r.PlayerId);
				instance.UpdatePlayerVoiceEffects();
				if ((Object)(object)localPlayerController != (Object)null && localPlayerController.isPlayerDead)
				{
					HUDManager.Instance.UpdateBoxesSpectateUI();
				}
			}
		}

		private static void ClearHandsLocally(PlayerControllerB p)
		{
			int num = 0;
			for (int i = 0; i < p.ItemSlots.Length; i++)
			{
				if ((Object)(object)p.ItemSlots[i] != (Object)null)
				{
					num++;
				}
			}
			if ((Object)(object)p.ItemOnlySlot != (Object)null)
			{
				num++;
			}
			if (num > 0)
			{
				Plugin.Log.LogWarning((object)$"{p.playerUsername} still had {num} item reference(s) after death; clearing the references only (the objects are left alone).");
			}
			for (int j = 0; j < p.ItemSlots.Length; j++)
			{
				p.ItemSlots[j] = null;
			}
			p.ItemOnlySlot = null;
			p.currentlyHeldObjectServer = null;
			p.currentlyHeldObject = null;
			p.isHoldingObject = false;
			p.twoHanded = false;
			p.currentItemSlot = 0;
			p.carryWeight = 1f;
			if (!((NetworkBehaviour)p).IsOwner)
			{
				return;
			}
			try
			{
				for (int k = 0; k < HUDManager.Instance.itemSlotIcons.Length; k++)
				{
					((Behaviour)HUDManager.Instance.itemSlotIcons[k]).enabled = false;
				}
			}
			catch (Exception ex)
			{
				Plugin.DebugLog("Could not reset hotbar icons: " + ex.Message);
			}
		}

		private static void CleanupBody(StartOfRound sor, int id)
		{
			//IL_0048: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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)
			PlayerControllerB val = sor.allPlayerScripts[id];
			RagdollGrabbableObject[] array = Object.FindObjectsOfType<RagdollGrabbableObject>();
			foreach (RagdollGrabbableObject val2 in array)
			{
				if (val2.bodyID == id)
				{
					if (((GrabbableObject)val2).isHeld && (Object)(object)((GrabbableObject)val2).playerHeldBy != (Object)null)
					{
						((GrabbableObject)val2).playerHeldBy.DropAllHeldItems(true, false, false, false, default(Vector3), default(Vector3), default(Vector3), default(Vector3), default(Vector3));
					}
					if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsServer)
					{
						HostController.Instance?.DespawnLater(val2);
					}
				}
			}
			DeadBodyInfo[] array2 = Object.FindObjectsOfType<DeadBodyInfo>(true);
			foreach (DeadBodyInfo val3 in array2)
			{
				if (val3.playerObjectId == id)
				{
					Object.Destroy((Object)(object)((Component)val3).gameObject);
				}
			}
			val.deadBody = null;
		}
	}
	internal static class RpcStage
	{
		private static readonly FieldInfo Field = AccessTools.Field(typeof(NetworkBehaviour), "__rpc_exec_stage");

		internal static bool IsExecuting(NetworkBehaviour nb)
		{
			if (Field != null)
			{
				return Field.GetValue(nb)?.ToString() == "Execute";
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageServerRpc")]
	internal static class ChatInterceptPatch
	{
		[HarmonyPrefix]
		private static void Prefix(HUDManager __instance, string chatMessage, int playerId)
		{
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if (!((Object)(object)singleton == (Object)null) && singleton.IsServer && chatMessage != null && chatMessage.Length <= 50 && RpcStage.IsExecuting((NetworkBehaviour)(object)__instance))
				{
					HostController.Instance?.OnChat(playerId, chatMessage);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Chat intercept error: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
	internal static class KillLocalPatch
	{
		[HarmonyPrefix]
		private static void Prefix(PlayerControllerB __instance)
		{
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton != (Object)null && singleton.IsServer && ((NetworkBehaviour)__instance).IsOwner && !__instance.isPlayerDead)
				{
					DeathTracker.Record(__instance, "KillPlayer");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)ex);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "KillPlayerClientRpc")]
	internal static class KillRpcPatch
	{
		[HarmonyPrefix]
		private static void Prefix(PlayerControllerB __instance)
		{
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				DeathTracker.DiedThisRound.Add((int)__instance.playerClientId);
				if ((Object)(object)singleton != (Object)null && singleton.IsServer && !((NetworkBehaviour)__instance).IsOwner)
				{
					DeathTracker.Record(__instance, "KillPlayerClientRpc");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)ex);
			}
		}
	}
	[HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")]
	internal static class NewQuotaPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			try
			{
				if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsServer)
				{
					HostController.Instance?.OnNewQuota();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)ex);
			}
		}
	}
	internal sealed class GateState
	{
		public readonly List<PlayerControllerB> Kept = new List<PlayerControllerB>();

		public readonly Dictionary<PlayerControllerB, int> Health = new Dictionary<PlayerControllerB, int>();

		public PlayerControllerB LocalSpectated;
	}
	[HarmonyPatch(typeof(StartOfRound), "ReviveDeadPlayers")]
	internal static class VanillaReviveGatePatch
	{
		internal static bool ForceFull;

		internal static bool LastWasPartial;

		[HarmonyPrefix]
		private static void Prefix(StartOfRound __instance, out GateState __state)
		{
			__state = null;
			try
			{
				bool flag = __instance.allPlayersDead || __instance.livingPlayers <= 0;
				if (!(LastWasPartial = EndOfDayPolicy.ShouldSkipDead(HostPolicy.SkipDead, HostPolicy.ReviveAllIfEveryoneDead, ForceFull, flag)))
				{
					if (HostPolicy.SkipDead)
					{
						Plugin.Log.LogInfo((object)$"Vanilla revive runs for everyone (forced={ForceFull}, everyoneDead={flag}).");
					}
					DeathTracker.DiedThisRound.Clear();
					return;
				}
				GateState gateState = new GateState();
				PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
				PlayerControllerB[] allPlayerScripts = __instance.allPlayerScripts;
				foreach (PlayerControllerB val2 in allPlayerScripts)
				{
					if (!((Object)(object)val2 == (Object)null) && val2.isPlayerDead)
					{
						gateState.Kept.Add(val2);
						gateState.Health[val2] = val2.health;
						val2.isPlayerDead = false;
					}
				}
				if ((Object)(object)val != (Object)null && !val.isPlayerDead && gateState.Kept.Contains(val))
				{
					gateState.LocalSpectated = val.spectatedPlayerScript;
				}
				__state = gateState;
				Plugin.Log.LogInfo((object)$"Vanilla end-of-day revive: keeping {gateState.Kept.Count} dead player(s) dead (DisableVanillaRevive).");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Revive gate prefix: " + ex));
			}
		}

		[HarmonyFinalizer]
		private static Exception Finalizer(StartOfRound __instance, Exception __exception, GateState __state)
		{
			try
			{
				if (__state != null)
				{
					foreach (PlayerControllerB item in __state.Kept)
					{
						item.isPlayerDead = true;
						item.isPlayerControlled = false;
						if (__state.Health.TryGetValue(item, out var value))
						{
							item.health = value;
						}
					}
					__instance.livingPlayers = Math.Max(0, __instance.connectedPlayersAmount + 1 - __state.Kept.Count);
					__instance.allPlayersDead = __instance.livingPlayers <= 0;
					PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
					if ((Object)(object)val != (Object)null && val.isPlayerDead)
					{
						val.spectatedPlayerScript = __state.LocalSpectated;
						HUDManager.Instance.UpdateBoxesSpectateUI();
					}
					__instance.UpdatePlayerVoiceEffects();
					Plugin.DebugLog($"Revive gate done: livingPlayers={__instance.livingPlayers}");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Revive gate finalizer: " + ex));
			}
			return __exception;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "EndPlayersFiredSequenceClientRpc")]
	internal static class FiredForceFullPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			VanillaReviveGatePatch.ForceFull = true;
		}

		[HarmonyFinalizer]
		private static Exception Finalizer(Exception __exception)
		{
			VanillaReviveGatePatch.ForceFull = false;
			return __exception;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "Debug_ReviveAllPlayersClientRpc")]
	internal static class DebugReviveClientForceFullPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			VanillaReviveGatePatch.ForceFull = true;
		}

		[HarmonyFinalizer]
		private static Exception Finalizer(Exception __exception)
		{
			VanillaReviveGatePatch.ForceFull = false;
			return __exception;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "Debug_RevivePlayers")]
	internal static class DebugReviveMenuForceFullPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			VanillaReviveGatePatch.ForceFull = true;
		}

		[HarmonyFinalizer]
		private static Exception Finalizer(Exception __exception)
		{
			VanillaReviveGatePatch.ForceFull = false;
			return __exception;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "ApplyPenalty")]
	internal static class PenaltyPatch
	{
		[HarmonyPrefix]
		private static void Prefix(ref int playersDead, ref int bodiesInsured)
		{
			try
			{
				int num = EndOfDayPolicy.PenaltyCasualties(VanillaReviveGatePatch.LastWasPartial, playersDead, DeathTracker.DiedThisRound.Count);
				if (num != playersDead)
				{
					Plugin.Log.LogInfo((object)$"Casualty penalty: {playersDead} dead, {num} died today.");
					playersDead = num;
					bodiesInsured = Math.Min(bodiesInsured, num);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Penalty patch: " + ex));
			}
		}

		[HarmonyPostfix]
		private static void Postfix()
		{
			DeathTracker.DiedThisRound.Clear();
		}
	}
	[HarmonyPatch]
	internal static class EmoteSwallowPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(PlayerControllerB), "Emote1_performed", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(PlayerControllerB), "Emote2_performed", (Type[])null, (Type[])null);
		}

		[HarmonyPrefix]
		private static bool Prefix(CallbackContext context)
		{
			try
			{
				if (VotePopupUI.CapturesVoteKeys && VotePopupUI.IsVoteKey(((CallbackContext)(ref context)).control))
				{
					return false;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Emote swallow: " + ex));
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class DeadChatPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(HUDManager), "EnableChat_performed", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(HUDManager), "SubmitChat_performed", (Type[])null, (Type[])null);
		}

		internal static bool IsDeadForChat(PlayerControllerB p)
		{
			if (p.isPlayerDead)
			{
				return !Settings.AllowDeadChat.Value;
			}
			return false;
		}

		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase original)
		{
			FieldInfo dead = AccessTools.Field(typeof(PlayerControllerB), "isPlayerDead");
			MethodInfo repl = AccessTools.Method(typeof(DeadChatPatch), "IsDeadForChat", (Type[])null, (Type[])null);
			int n = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (instruction.opcode == OpCodes.Ldfld && instruction.operand is FieldInfo fieldInfo && fieldInfo == dead)
				{
					n++;
					yield return new CodeInstruction(OpCodes.Call, (object)repl)
					{
						labels = instruction.labels,
						blocks = instruction.blocks
					};
				}
				else
				{
					yield return instruction;
				}
			}
			Plugin.Log.LogInfo((object)$"DeadChatPatch: {original.Name}: replaced {n} isPlayerDead check(s).");
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
	internal static class ConnectPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			ReviveNet.EnsureRegistered();
		}
	}
	public static class ModInfo
	{
		public const string GUID = "Gamingregory.QuotaRevive";

		public const string NAME = "QuotaRevive";

		public const string VERSION = "1.0.0";
	}
	[BepInPlugin("Gamingregory.QuotaRevive", "QuotaRevive", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		internal const string LethalConfigGuid = "ainavt.lc.lethalconfig";

		internal static ManualLogSource Log;

		internal static Plugin Instance;

		private readonly Harmony harmony = new Harmony("Gamingregory.QuotaRevive");

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			Settings.Bind(((BaseUnityPlugin)this).Config);
			((BaseUnityPlugin)this).Config.SettingChanged += delegate(object s, SettingChangedEventArgs e)
			{
				DebugLog($"Setting changed: [{e.ChangedSetting.Definition.Section}] {e.ChangedSetting.Definition.Key} = {e.ChangedSetting.BoxedValue}");
				HostController.Instance?.OnSettingChanged(e.ChangedSetting);
			};
			harmony.PatchAll(typeof(Plugin).Assembly);
			((Component)this).gameObject.AddComponent<HostController>();
			VotePopupUI.Create();
			if (Chainloader.PluginInfos.ContainsKey("ainavt.lc.lethalconfig"))
			{
				try
				{
					RegisterLethalConfig();
				}
				catch (Exception ex)
				{
					Log.LogWarning((object)("LethalConfig integration failed (settings are still editable in the config file): " + ex));
				}
			}
			else
			{
				Log.LogInfo((object)"LethalConfig not found: in-game settings menu unavailable, use the config file / mod manager editor.");
			}
			Log.LogInfo((object)string.Format("{0} {1} loaded (mode: {2})", "QuotaRevive", "1.0.0", Settings.Mode.Value));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void RegisterLethalConfig()
		{
			LethalConfigBridge.Register();
		}

		internal static void DebugLog(string msg)
		{
			if (Settings.LogDebug != null && Settings.LogDebug.Value)
			{
				Log.LogInfo((object)("[debug] " + msg));
			}
		}
	}
	internal struct ReviveInfo
	{
		public int PlayerId;

		public int Health;

		public bool Stamina;

		public bool Insanity;
	}
	internal static class HostPolicy
	{
		internal static bool SkipDead;

		internal static bool ReviveAllIfEveryoneDead = true;

		internal static void Reset()
		{
			SkipDead = false;
			ReviveAllIfEveryoneDead = true;
		}
	}
	internal static class ReviveNet
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnReviveMessage;

			public static HandleNamedMessageDelegate <1>__OnHelloMessage;

			public static HandleNamedMessageDelegate <2>__OnPolicyMessage;

			public static HandleNamedMessageDelegate <3>__OnVoteMessage;

			public static HandleNamedMessageDelegate <4>__OnVoteStateMessage;
		}

		private const string ReviveMsg = "QuotaRevive.Revive";

		private const string HelloMsg = "QuotaRevive.Hello";

		private const string PolicyMsg = "QuotaRevive.Policy";

		private const string VoteMsg = "QuotaRevive.Vote";

		private const string VoteStateMsg = "QuotaRevive.VoteState";

		private const byte Protocol = 2;

		private static CustomMessagingManager registeredOn;

		internal static readonly Dictionary<ulong, string> ModdedClients = new Dictionary<ulong, string>();

		internal const byte StateUpdate = 1;

		internal const byte StateResult = 2;

		internal const byte StateClose = 3;

		internal static void EnsureRegistered()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//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_0099: Expected O, but got Unknown
			//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_00bf: Expected O, but got Unknown
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
			{
				if (registeredOn != null)
				{
					registeredOn = null;
					HostPolicy.Reset();
				}
				return;
			}
			CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
			if (customMessagingManager != null && customMessagingManager != registeredOn)
			{
				registeredOn = customMessagingManager;
				ModdedClients.Clear();
				HostPolicy.Reset();
				object obj = <>O.<0>__OnReviveMessage;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnReviveMessage;
					<>O.<0>__OnReviveMessage = val;
					obj = (object)val;
				}
				customMessagingManager.RegisterNamedMessageHandler("QuotaRevive.Revive", (HandleNamedMessageDelegate)obj);
				object obj2 = <>O.<1>__OnHelloMessage;
				if (obj2 == null)
				{
					HandleNamedMessageDelegate val2 = OnHelloMessage;
					<>O.<1>__OnHelloMessage = val2;
					obj2 = (object)val2;
				}
				customMessagingManager.RegisterNamedMessageHandler("QuotaRevive.Hello", (HandleNamedMessageDelegate)obj2);
				object obj3 = <>O.<2>__OnPolicyMessage;
				if (obj3 == null)
				{
					HandleNamedMessageDelegate val3 = OnPolicyMessage;
					<>O.<2>__OnPolicyMessage = val3;
					obj3 = (object)val3;
				}
				customMessagingManager.RegisterNamedMessageHandler("QuotaRevive.Policy", (HandleNamedMessageDelegate)obj3);
				object obj4 = <>O.<3>__OnVoteMessage;
				if (obj4 == null)
				{
					HandleNamedMessageDelegate val4 = OnVoteMessage;
					<>O.<3>__OnVoteMessage = val4;
					obj4 = (object)val4;
				}
				customMessagingManager.RegisterNamedMessageHandler("QuotaRevive.Vote", (HandleNamedMessageDelegate)obj4);
				object obj5 = <>O.<4>__OnVoteStateMessage;
				if (obj5 == null)
				{
					HandleNamedMessageDelegate val5 = OnVoteStateMessage;
					<>O.<4>__OnVoteStateMessage = val5;
					obj5 = (object)val5;
				}
				customMessagingManager.RegisterNamedMessageHandler("QuotaRevive.VoteState", (HandleNamedMessageDelegate)obj5);
				Plugin.DebugLog($"Network handlers registered (host={singleton.IsHost}, localId={singleton.LocalClientId})");
				if (!singleton.IsServer)
				{
					SendHello();
				}
			}
		}

		private unsafe static void SendHello()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(128, (Allocator)2, -1);
				try
				{
					byte b = 2;
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe("1.0.0", false);
					singleton.CustomMessagingManager.SendNamedMessage("QuotaRevive.Hello", 0uL, val, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
				Plugin.DebugLog("Sent hello to host.");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Hello failed: " + ex));
			}
		}

		private static void OnHelloMessage(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				byte b = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
				string text = default(string);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
				ModdedClients[sender] = text;
				Plugin.Log.LogInfo((object)string.Format("Client {0} has {1} {2} (protocol {3}).", sender, "QuotaRevive", text, b));
				if (b != 2)
				{
					Plugin.Log.LogWarning((object)$"Client {sender} runs a different protocol ({b} vs {(byte)2}); update the mod everywhere.");
				}
				HostController.Instance?.SendPolicyTo(sender);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Bad hello: " + ex));
			}
		}

		internal static bool AllClientsModded(out List<ulong> missing)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			missing = singleton.ConnectedClientsIds.Where((ulong id) => id != 0L && !ModdedClients.ContainsKey(id)).ToList();
			return missing.Count == 0;
		}

		internal unsafe static void SendPolicy(bool skipDead, bool reviveAllIfDead, ulong? only = null)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: 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)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(32, (Allocator)2, -1);
			try
			{
				byte b = 2;
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref skipDead, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref reviveAllIfDead, default(ForPrimitives));
				if (only.HasValue)
				{
					singleton.CustomMessagingManager.SendNamedMessage("QuotaRevive.Policy", only.Value, val, (NetworkDelivery)3);
				}
				else
				{
					singleton.CustomMessagingManager.SendNamedMessageToAll("QuotaRevive.Policy", val, (NetworkDelivery)3);
				}
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static void OnPolicyMessage(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				byte b = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (HostPolicy.SkipDead != flag || HostPolicy.ReviveAllIfEveryoneDead != flag2)
				{
					Plugin.Log.LogInfo((object)string.Format("Host policy: vanilla end-of-day revive of dead players {0}; revive-all-if-everyone-dead={1}", flag ? "DISABLED" : "enabled", flag2));
				}
				HostPolicy.SkipDead = flag;
				HostPolicy.ReviveAllIfEveryoneDead = flag2;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Bad policy message: " + ex));
			}
		}

		internal unsafe static void SendRevive(IList<ReviveInfo> infos)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: 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_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: 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_00b2: 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)
			NetworkManager singleton = NetworkManager.Singleton;
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(64 + infos.Count * 32, (Allocator)2, -1);
			try
			{
				byte b = 2;
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
				int count = infos.Count;
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref count, default(ForPrimitives));
				foreach (ReviveInfo info in infos)
				{
					ReviveInfo current = info;
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref current.PlayerId, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref current.Health, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref current.Stamina, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref current.Insanity, default(ForPrimitives));
				}
				singleton.CustomMessagingManager.SendNamedMessageToAll("QuotaRevive.Revive", val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static void OnReviveMessage(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: 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)
			try
			{
				byte b = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
				if (b != 2)
				{
					Plugin.Log.LogWarning((object)$"Revive message with unknown protocol {b}; ignored.");
					return;
				}
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
				for (int i = 0; i < num; i++)
				{
					ReviveInfo r = default(ReviveInfo);
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref r.PlayerId, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref r.Health, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref r.Stamina, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref r.Insanity, default(ForPrimitives));
					try
					{
						LocalRevive.Apply(r);
					}
					catch (Exception arg)
					{
						Plugin.Log.LogError((object)$"Local revive of player {r.PlayerId} failed: {arg}");
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Bad revive message: " + ex));
			}
		}

		internal unsafe static void SendVote(bool yes)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
				{
					return;
				}
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(16, (Allocator)2, -1);
				try
				{
					byte b = 2;
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref yes, default(ForPrimitives));
					singleton.CustomMessagingManager.SendNamedMessage("QuotaRevive.Vote", 0uL, val, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("SendVote failed: " + ex));
			}
		}

		private static void OnVoteMessage(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				byte b = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
				bool yes = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref yes, default(ForPrimitives));
				HostController.Instance?.OnPopupVote(sender, yes);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Bad vote message: " + ex));
			}
		}

		internal unsafe static void SendVoteState(ulong clientId, byte type, PopupStateData d, string resultText, bool passed)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: 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_00e2: 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_00f8: 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_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: 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_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(4096, (Allocator)2, -1);
			try
			{
				byte b = 2;
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref type, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref passed, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe(resultText ?? "", false);
				if (type == 1)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(d.Header ?? "", false);
					((FastBufferWriter)(ref val)).WriteValueSafe(d.YesLabel ?? "", false);
					((FastBufferWriter)(ref val)).WriteValueSafe(d.NoLabel ?? "", false);
					((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref d.Duration, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref d.SecondsLeft, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref d.Yes, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref d.No, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref d.Needed, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref d.Eligible, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref d.MyVote, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref d.CanVote, default(ForPrimitives));
				}
				singleton.CustomMessagingManager.SendNamedMessage("QuotaRevive.VoteState", clientId, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static void OnVoteStateMessage(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: 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_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: 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_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				byte b = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
				byte b2 = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b2, default(ForPrimitives));
				bool passed = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref passed, default(ForPrimitives));
				string text = default(string);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
				VotePopupUI instance = VotePopupUI.Instance;
				switch (b2)
				{
				case 1:
				{
					PopupStateData popupStateData = new PopupStateData();
					((FastBufferReader)(ref reader)).ReadValueSafe(ref popupStateData.Header, false);
					((FastBufferReader)(ref reader)).ReadValueSafe(ref popupStateData.YesLabel, false);
					((FastBufferReader)(ref reader)).ReadValueSafe(ref popupStateData.NoLabel, false);
					((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref popupStateData.Duration, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref popupStateData.SecondsLeft, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref popupStateData.Yes, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref popupStateData.No, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref popupStateData.Needed, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref popupStateData.Eligible, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref popupStateData.MyVote, default(ForPrimitives));
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref popupStateData.CanVote, default(ForPrimitives));
					instance?.OnState(popupStateData);
					break;
				}
				case 2:
					instance?.OnResult(text, passed);
					break;
				default:
					instance?.OnClose();
					break;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Bad vote state message: " + ex));
			}
		}
	}
	internal static class Settings
	{
		internal const string Host = "Host only. ";

		internal static ConfigEntry<ReviveMode> Mode;

		internal static ConfigEntry<int> ReviveHealth;

		internal static ConfigEntry<bool> DisableVanillaRevive;

		internal static ConfigEntry<bool> ReviveAllIfEveryoneDead;

		internal static ConfigEntry<bool> RestoreStamina;

		internal static ConfigEntry<bool> ClearInsanity;

		internal static ConfigEntry<int> MaxRevivesPerRound;

		internal static ConfigEntry<int> MaxRevivesPerQuota;

		internal static ConfigEntry<int> MaxRevivesTotal;

		internal static ConfigEntry<bool> OnlyWhileLanded;

		internal static ConfigEntry<bool> AnnounceRevives;

		internal static ConfigEntry<int> ReviveDelaySeconds;

		internal static ConfigEntry<bool> RequireModOnAllPlayers;

		internal static ConfigEntry<TimeBasis> TimeBasisEntry;

		internal static ConfigEntry<TimeUnit> TimeUnitEntry;

		internal static ConfigEntry<float> TimeDelay;

		internal static ConfigEntry<float> TimeRepeatEvery;

		internal static ConfigEntry<ReviveSelection> TimeSelection;

		internal static ConfigEntry<bool> TimeOnlyIfAtLeastOneAlive;

		internal static ConfigEntry<QuotaTrigger> QuotaTriggerEntry;

		internal static ConfigEntry<int> QuotaEveryN;

		internal static ConfigEntry<int> QuotaReviveCount;

		internal static ConfigEntry<string> VoteCommand;

		internal static ConfigEntry<int> VoteDuration;

		internal static ConfigEntry<int> VoteCooldown;

		internal static ConfigEntry<int> VotePerPlayerCooldown;

		internal static ConfigEntry<int> VoteRequiredYesPercent;

		internal static ConfigEntry<int> VoteMinimumYes;

		internal static ConfigEntry<WhoCanVote> VoteWho;

		internal static ConfigEntry<bool> VoteRequesterAutoYes;

		internal static ConfigEntry<bool> VoteTargetCanVote;

		internal static ConfigEntry<AbstainRule> VoteAbstain;

		internal static ConfigEntry<int> VoteMaxPerRound;

		internal static ConfigEntry<bool> VoteHostForce;

		internal static ConfigEntry<bool> VoteRequireTargetDead;

		internal static ConfigEntry<bool> VoteEndEarly;

		internal static ConfigEntry<bool> VoteAllowChange;

		internal static ConfigEntry<bool> VoteCancelOnRoundEnd;

		internal static ConfigEntry<bool> VoteAnnounceProgress;

		internal static ConfigEntry<bool> VoteAllowChat;

		internal static ConfigEntry<bool> VoteAnnounceInChat;

		internal static ConfigEntry<string> MsgVoteStarted;

		internal static ConfigEntry<string> MsgVoteProgress;

		internal static ConfigEntry<string> MsgVotePassed;

		internal static ConfigEntry<string> MsgVoteFailed;

		internal static ConfigEntry<string> MsgVoteCancelled;

		internal static ConfigEntry<string> MsgRevived;

		internal static ConfigEntry<string> MsgCountdown;

		internal static ConfigEntry<string> MsgDisabled;

		internal static ConfigEntry<string> MsgAlreadyRunning;

		internal static ConfigEntry<string> MsgCooldown;

		internal static ConfigEntry<string> MsgNotFound;

		internal static ConfigEntry<string> MsgAmbiguous;

		internal static ConfigEntry<string> MsgNotDead;

		internal static ConfigEntry<string> MsgNotLanded;

		internal static ConfigEntry<string> MsgLimit;

		internal static ConfigEntry<string> MsgUsage;

		internal static ConfigEntry<string> MsgRequesterDead;

		internal static ConfigEntry<string> MsgNoVoters;

		internal static ConfigEntry<string> MsgNoMod;

		internal static ConfigEntry<string> MsgPopupHeader;

		internal static ConfigEntry<string> MsgPopupAccept;

		internal static ConfigEntry<string> MsgPopupDeny;

		internal static ConfigEntry<string> MsgPopupPassed;

		internal static ConfigEntry<string> MsgPopupFailed;

		internal static ConfigEntry<string> MsgPopupCancelled;

		internal static ConfigEntry<bool> ShowVotePopup;

		internal static ConfigEntry<Key> VoteKeyYes;

		internal static ConfigEntry<Key> VoteKeyNo;

		internal static ConfigEntry<Key> PopupMouseKey;

		internal static ConfigEntry<bool> PopupGamepad;

		internal static ConfigEntry<int> PopupOffsetX;

		internal static ConfigEntry<int> PopupOffsetY;

		internal static ConfigEntry<bool> AllowDeadChat;

		internal static ConfigEntry<bool> LogDebug;

		internal static string CommandName
		{
			get
			{
				string text = (VoteCommand.Value ?? "").Trim().TrimStart('/');
				if (!string.IsNullOrEmpty(text) && !text.Contains(" "))
				{
					return text;
				}
				return "revive";
			}
		}

		internal static void Bind(ConfigFile c)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Expected O, but got Unknown
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Expected O, but got Unknown
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Expected O, but got Unknown
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Expected O, but got Unknown
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Expected O, but got Unknown
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Expected O, but got Unknown
			//IL_035d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0367: Expected O, but got Unknown
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0398: Expected O, but got Unknown
			//IL_03be: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c8: Expected O, but got Unknown
			//IL_03ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f6: Expected O, but got Unknown
			//IL_0419: Unknown result type (might be due to invalid IL or missing references)
			//IL_0423: Expected O, but got Unknown
			//IL_04b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bc: Expected O, but got Unknown
			//IL_094c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0956: Expected O, but got Unknown
			//IL_0980: Unknown result type (might be due to invalid IL or missing references)
			//IL_098a: Expected O, but got Unknown
			Mode = c.Bind<ReviveMode>("1. General", "Mode", ReviveMode.Normal, new ConfigDescription("Host only. How dead players are revived. Normal = vanilla (mod does nothing; the game revives everyone at the end of each day). In every other mode the vanilla between-moons revive is disabled while DisableVanillaRevive is on. AfterTimeOnPlanet = revive after a time on the moon. AfterQuota = revive when the quota event in [3. Quota] happens. Vote = players type /revive <name> in chat and vote with 1 / 2. Every player needs this mod installed.", (AcceptableValueBase)null, Array.Empty<object>()));
			ReviveHealth = c.Bind<int>("1. General", "ReviveHealth", 100, new ConfigDescription("Host only. Health a revived player gets (1-100).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>()));
			DisableVanillaRevive = c.Bind<bool>("1. General", "DisableVanillaRevive", true, "Host only. Only applies when Mode is not Normal. true = the game's own revive of dead players when the ship leaves a moon / at the end of the day is DISABLED: dead players stay dead (and spectate) through takeoff, orbit and later days until the selected mode revives them. Alive players are unaffected. false = vanilla still revives everyone between moons. Players who stay dead are not charged the casualty penalty again on later days.");
			ReviveAllIfEveryoneDead = c.Bind<bool>("1. General", "ReviveAllIfEveryoneDead", true, "Host only. Safety valve for DisableVanillaRevive: if every player is dead at the end of the day (game over), the vanilla revive runs for everyone so the run cannot softlock. Being fired after a missed deadline always revives everyone (a new run starts).");
			RestoreStamina = c.Bind<bool>("1. General", "RestoreStamina", true, "Host only. Refill the sprint meter of revived players.");
			ClearInsanity = c.Bind<bool>("1. General", "ClearInsanity", true, "Host only. Reset the insanity level of revived players.");
			MaxRevivesPerRound = c.Bind<int>("1. General", "MaxRevivesPerRound", 0, new ConfigDescription("Host only. Maximum number of players this mod may revive per round (landing to takeoff). 0 = unlimited.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			MaxRevivesPerQuota = c.Bind<int>("1. General", "MaxRevivesPerQuota", 0, new ConfigDescription("Host only. Maximum revives per quota period (resets when a new quota starts). 0 = unlimited.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000), Array.Empty<object>()));
			MaxRevivesTotal = c.Bind<int>("1. General", "MaxRevivesTotal", 0, new ConfigDescription("Host only. Maximum revives for the whole play session (resets when the game is restarted). 0 = unlimited.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10000), Array.Empty<object>()));
			OnlyWhileLanded = c.Bind<bool>("1. General", "OnlyWhileLanded", true, "Host only. true = revive only while the ship is landed on a moon. false = also while the ship is taking off or in orbit (relevant when DisableVanillaRevive keeps players dead in orbit, e.g. for votes). Revived players always appear in the ship with empty hands; their items stay where they died.");
			AnnounceRevives = c.Bind<bool>("1. General", "AnnounceRevives", true, "Host only. Post a chat message when someone is revived.");
			ReviveDelaySeconds = c.Bind<int>("1. General", "ReviveDelaySeconds", 0, new ConfigDescription("Host only. Countdown (seconds) between the decision to revive and the actual revive. A chat countdown message is shown when above 0.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 60), Array.Empty<object>()));
			RequireModOnAllPlayers = c.Bind<bool>("1. General", "RequireModOnAllPlayers", true, "Host only. Only revive when every connected player has announced that they run this mod. Players without it would not see the revive and would end up desynced. Turn off only if you accept that risk.");
			TimeBasisEntry = c.Bind<TimeBasis>("2. TimeOnPlanet", "Basis", TimeBasis.SinceLanding, "Host only. SinceLanding = one timer starts when the ship lands; every time it fires, dead players are revived. SincePlayerDeath = every dead player is revived Delay after their own death (RepeatEvery is ignored).");
			TimeUnitEntry = c.Bind<TimeUnit>("2. TimeOnPlanet", "Unit", TimeUnit.RealSeconds, "Host only. RealSeconds or GameHours (in-game hours; one in-game hour is 100 time units; does not advance on the company moon).");
			TimeDelay = c.Bind<float>("2. TimeOnPlanet", "Delay", 120f, new ConfigDescription("Host only. How long until the revive, in the unit chosen above.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 3600f), Array.Empty<object>()));
			TimeRepeatEvery = c.Bind<float>("2. TimeOnPlanet", "RepeatEvery", 0f, new ConfigDescription("Host only. SinceLanding only: repeat the revive every this many units after the first one. 0 = only once per round.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3600f), Array.Empty<object>()));
			TimeSelection = c.Bind<ReviveSelection>("2. TimeOnPlanet", "ReviveSelection", ReviveSelection.All, "Host only. All = revive every dead player when the timer fires. OneAtATime = only the player who died first.");
			TimeOnlyIfAtLeastOneAlive = c.Bind<bool>("2. TimeOnPlanet", "OnlyIfAtLeastOneAlive", true, "Host only. Do not revive when everyone is dead (that is a game over).");
			QuotaTriggerEntry = c.Bind<QuotaTrigger>("3. Quota", "Trigger", QuotaTrigger.QuotaFulfilled, "Host only. QuotaFulfilled = when the quota is met by selling scrap at the company (the game only updates the quota there). ScrapCollectedReachesQuota = as soon as (scrap already sold + value of scrap currently in the ship) reaches the quota, on any moon; checked every 2 s, once per quota. NewQuotaStarted = when a new quota begins. DeadlineDay = when the ship lands on the last day before the deadline. If a trigger happens while revives are not possible (e.g. in orbit), it is applied at the next landing.");
			QuotaEveryN = c.Bind<int>("3. Quota", "EveryNQuotas", 1, new ConfigDescription("Host only. Revive only on every N-th occurrence of the trigger (1 = every time).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50), Array.Empty<object>()));
			QuotaReviveCount = c.Bind<int>("3. Quota", "ReviveCount",