Decompiled source of SimpleTeamLives v1.5.1

SimpleTeamLives.dll

Decompiled 5 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CSync.Extensions;
using CSync.Lib;
using GameNetcodeStuff;
using HarmonyLib;
using LethalModDataLib.Enums;
using LethalModDataLib.Events;
using LethalModDataLib.Features;
using LethalNetworkAPI;
using LethalNetworkAPI.Utils;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;

[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("SimpleTeamLives")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.5.1.0")]
[assembly: AssemblyInformationalVersion("1.5.1")]
[assembly: AssemblyProduct("SimpleTeamLives")]
[assembly: AssemblyTitle("SimpleTeamLives")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Anthropic Claude (Claude Opus 5.5 and other Claude models, via Claude Code); designed and tested by the author")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")]
[assembly: AssemblyVersion("1.5.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SimpleTeamLives
{
	internal static class Hud
	{
		private struct Pending
		{
			public string Header;

			public string Body;

			public bool Warning;
		}

		private const string TipPrefsKey = "SimpleTeamLives_Tip";

		private const int MaxQueued = 6;

		private const int FlushFailuresBeforeOff = 3;

		internal const string OutOfLivesText = "Out of team lives";

		private static readonly Queue<Pending> Queue = new Queue<Pending>();

		private static FieldRef<HUDManager, bool> _hudHidden;

		private static FieldRef<HUDManager, Coroutine> _tipsCoroutine;

		private static int _flushFailures;

		private static bool _flushOff;

		private static HUDManager _lastHud;

		internal static bool FiringIsOutOfLives;

		private static readonly Dictionary<TMP_Text, string> OriginalFiredTexts = new Dictionary<TMP_Text, string>();

		internal static void Init()
		{
			_hudHidden = Safe.Optional("Hud.Init.hudHidden", () => AccessTools.FieldRefAccess<HUDManager, bool>("hudHidden"), null);
			_tipsCoroutine = Safe.Optional("Hud.Init.tipsPanelCoroutine", () => AccessTools.FieldRefAccess<HUDManager, Coroutine>("tipsPanelCoroutine"), null);
		}

		internal static void ShowLocal(string header, string body, bool warning)
		{
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogInfo((object)("Notice: " + header + " | " + body));
			}
			if (!_flushOff)
			{
				Queue.Enqueue(new Pending
				{
					Header = (header ?? ""),
					Body = (body ?? ""),
					Warning = warning
				});
				while (Queue.Count > 6)
				{
					Queue.Dequeue();
				}
			}
		}

		internal static void TryFlush()
		{
			if (_flushOff || Queue.Count == 0)
			{
				return;
			}
			try
			{
				HUDManager instance = HUDManager.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					return;
				}
				if ((Object)(object)_lastHud != (Object)(object)instance)
				{
					if ((Object)(object)_lastHud != (Object)null)
					{
						Queue.Clear();
					}
					_lastHud = instance;
					if (Queue.Count == 0)
					{
						return;
					}
				}
				if ((_hudHidden == null || !_hudHidden.Invoke(instance)) && (_tipsCoroutine == null || _tipsCoroutine.Invoke(instance) == null))
				{
					StartOfRound instance2 = StartOfRound.Instance;
					if (!((Object)(object)instance2 != (Object)null) || !instance2.firingPlayersCutsceneRunning)
					{
						Pending pending = Queue.Dequeue();
						instance.DisplayTip(pending.Header, pending.Body, pending.Warning, false, "SimpleTeamLives_Tip");
					}
				}
			}
			catch (Exception e)
			{
				Safe.Fail("Hud.TryFlush", e);
				Queue.Clear();
				if (++_flushFailures >= 3)
				{
					_flushOff = true;
					ManualLogSource log = Plugin.Log;
					if (log != null)
					{
						log.LogWarning((object)"HUD messages switched off after repeated errors; lives are still tracked (see log lines starting 'Notice:')");
					}
				}
			}
		}

		internal static void OnOutOfLives()
		{
			FiringIsOutOfLives = true;
			Queue.Clear();
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"Host reports the team is out of lives; firing sequence follows");
			}
		}

		internal static void OnFiredScreenShown(HUDManager hud)
		{
			if ((Object)(object)hud == (Object)null || (Object)(object)hud.playersFiredAnimator == (Object)null)
			{
				return;
			}
			OriginalFiredTexts.Clear();
			TMP_Text[] componentsInChildren = ((Component)hud.playersFiredAnimator).GetComponentsInChildren<TMP_Text>(true);
			TMP_Text[] array = componentsInChildren;
			foreach (TMP_Text val in array)
			{
				if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)hud.EndOfRunStatsText)
				{
					OriginalFiredTexts[val] = val.text;
				}
			}
			if (!FiringIsOutOfLives)
			{
				return;
			}
			int num = 0;
			array = componentsInChildren;
			foreach (TMP_Text val2 in array)
			{
				if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2 == (Object)(object)hud.EndOfRunStatsText) && !string.IsNullOrEmpty(val2.text) && val2.text.IndexOf("quota", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					val2.text = "Out of team lives.";
					num++;
				}
			}
			if (num == 0 && (Object)(object)hud.EndOfRunStatsText != (Object)null)
			{
				string text = ((TMP_Text)hud.EndOfRunStatsText).text ?? "";
				if (!text.StartsWith("Out of team lives"))
				{
					((TMP_Text)hud.EndOfRunStatsText).text = "Out of team lives\n" + text;
				}
				Safe.WarnOnce("Hud.NoQuotaLine", "Firing screen has no quota line to replace; put the reason above the run stats instead");
			}
		}

		internal static void OnFiredScreenHidden()
		{
			foreach (KeyValuePair<TMP_Text, string> originalFiredText in OriginalFiredTexts)
			{
				if ((Object)(object)originalFiredText.Key != (Object)null)
				{
					originalFiredText.Key.text = originalFiredText.Value;
				}
			}
			OriginalFiredTexts.Clear();
			FiringIsOutOfLives = false;
		}
	}
	internal static class Net
	{
		private const char Sep = '\u001f';

		internal static LNetworkVariable<int> Lives;

		internal static LNetworkMessage<string> Notice;

		internal static LNetworkEvent OutOfLives;

		internal static bool IsHost
		{
			get
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton != (Object)null && singleton.IsListening)
				{
					return singleton.IsServer;
				}
				return false;
			}
		}

		internal static void Init()
		{
			Safe.Optional("Net.Init.Lives", delegate
			{
				Lives = LNetworkVariable<int>.Connect("Lives", -2, (LNetworkVariableWritePerms)0, (Action<int, int>)null);
			});
			Safe.Optional("Net.Init.Notice", delegate
			{
				Notice = LNetworkMessage<string>.Connect("Notice", (Action<string, ulong>)null, (Action<string>)OnNotice, (Action<string, ulong>)null);
			});
			Safe.Optional("Net.Init.OutOfLives", delegate
			{
				OutOfLives = LNetworkEvent.Connect("OutOfLives", (Action<ulong>)null, (Action)OnOutOfLives, (Action<ulong>)null);
			});
			if (Lives == null || Notice == null || OutOfLives == null)
			{
				Plugin.Log.LogWarning((object)"Some networking failed to set up; other players may not see lives messages");
			}
		}

		internal static void PublishLives(int value)
		{
			if (Lives != null && IsHost)
			{
				Safe.Optional("Net.PublishLives", delegate
				{
					Lives.Value = value;
				});
			}
		}

		internal static void SendNotice(string header, string body, bool warning = false)
		{
			if (!IsHost)
			{
				return;
			}
			if (Notice == null)
			{
				Hud.ShowLocal(header, body, warning);
				return;
			}
			Safe.Optional("Net.SendNotice", delegate
			{
				Notice.SendClients(header + "\u001f" + body + "\u001f" + (warning ? "1" : "0"));
			});
		}

		internal static void SendOutOfLives()
		{
			if (!IsHost)
			{
				return;
			}
			if (OutOfLives == null)
			{
				Hud.OnOutOfLives();
				return;
			}
			Safe.Optional("Net.SendOutOfLives", delegate
			{
				OutOfLives.InvokeClients();
			});
		}

		private static void OnNotice(string packed)
		{
			Safe.Optional("Net.OnNotice", delegate
			{
				string[] array = (packed ?? "").Split('\u001f');
				string header = ((array.Length != 0) ? array[0] : "");
				string body = ((array.Length > 1) ? array[1] : "");
				bool warning = array.Length > 2 && array[2] == "1";
				Hud.ShowLocal(header, body, warning);
			});
		}

		private static void OnOutOfLives()
		{
			Safe.Optional("Net.OnOutOfLives", Hud.OnOutOfLives);
		}
	}
	internal static class Patches
	{
		private static Harmony _harmony;

		private static bool _dncTried;

		internal const string DncLivesOffText = "Team lives are off (TeamLives = false in the host's jacob.SimpleTeamLives.cfg).";

		internal static bool TakeoffHooked { get; private set; }

		internal static bool CanFire { get; private set; }

		internal static void Apply(Harmony harmony)
		{
			_harmony = harmony;
			TakeoffHooked = Patch(harmony, "takeoff", typeof(StartOfRound), "EndOfGameClientRpc", "EndOfGameClientRpc_Prefix");
			CanFire = Patch(harmony, "game over", typeof(StartOfRound), "AllPlayersHaveRevivedClientRpc", "AllPlayersHaveRevivedClientRpc_Prefix") && typeof(StartOfRound).GetMethod("FirePlayersAfterDeadlineClientRpc") != null;
			PatchKeepScrap(harmony);
			Patch(harmony, "quota refill", typeof(TimeOfDay), "SetNewProfitQuota", null, "SetNewProfitQuota_Postfix");
			Patch(harmony, "round start", typeof(StartOfRound), "StartGame", null, "StartGame_Postfix");
			Patch(harmony, "HUD messages", typeof(HUDManager), "Update", null, "HudUpdate_Postfix");
			Patch(harmony, "lives terminal command", typeof(Terminal), "ParsePlayerSentence", null, "ParsePlayerSentence_Postfix", 0);
			Patch(harmony, "terminal help entry", typeof(Terminal), "Start", null, "TerminalStart_Postfix");
			Patch(harmony, "firing screen text", typeof(HUDManager), "ShowPlayersFiredScreen", "ShowPlayersFiredScreen_Prefix", "ShowPlayersFiredScreen_Postfix");
			if (!TakeoffHooked)
			{
				Safe.Disable("the takeoff hook couldn't be applied (game update?)");
			}
			else if (!CanFire)
			{
				Plugin.Log.LogWarning((object)"Firing hook unavailable: a full wipe at 0 lives will only show a warning");
			}
		}

		private static void PatchKeepScrap(Harmony harmony)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0065: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(RoundManager), "DespawnPropsAtEndOfRound", (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					Plugin.Log.LogWarning((object)"Couldn't find RoundManager.DespawnPropsAtEndOfRound; keeping ship scrap on a wipe is off");
				}
				else
				{
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Patches), "DespawnPropsAtEndOfRound_Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Patches), "DespawnPropsAtEndOfRound_Finalizer", (Type[])null), (HarmonyMethod)null);
				}
			}
			catch (Exception e)
			{
				Safe.Fail("Patch.keep ship scrap", e);
				Plugin.Log.LogWarning((object)"Couldn't patch RoundManager.DespawnPropsAtEndOfRound; keeping ship scrap on a wipe is off");
			}
		}

		private static bool Patch(Harmony harmony, string feature, Type type, string method, string prefix = null, string postfix = null, int postfixPriority = 400)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				MethodInfo methodInfo = AccessTools.Method(type, method, (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					Plugin.Log.LogWarning((object)("Couldn't find " + type.Name + "." + method + "; " + feature + " is off"));
					return false;
				}
				harmony.Patch((MethodBase)methodInfo, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Patches), prefix, (Type[])null), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(AccessTools.Method(typeof(Patches), postfix, (Type[])null, (Type[])null))
				{
					priority = postfixPriority
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				return true;
			}
			catch (Exception e)
			{
				Safe.Fail("Patch." + feature, e);
				Plugin.Log.LogWarning((object)("Couldn't patch " + type.Name + "." + method + "; " + feature + " is off"));
				return false;
			}
		}

		private static void EndOfGameClientRpc_Prefix(StartOfRound __instance)
		{
			Safe.Core("Takeoff", delegate
			{
				TeamLives.OnTakeoff(__instance);
			});
		}

		private static bool AllPlayersHaveRevivedClientRpc_Prefix(StartOfRound __instance)
		{
			try
			{
				return TeamLives.ContinueOrFire(__instance);
			}
			catch (Exception e)
			{
				Safe.Fail("ContinueOrFire", e);
				return true;
			}
		}

		private static void DespawnPropsAtEndOfRound_Prefix(out bool __state)
		{
			__state = false;
			try
			{
				StartOfRound instance = StartOfRound.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.allPlayersDead && Net.IsHost && TeamLives.ConsumeShipScrapProtection())
				{
					instance.allPlayersDead = false;
					__state = true;
					Plugin.Log.LogInfo((object)(Settings.TeamLivesOn ? "Keeping the ship's scrap (full wipe paid for with a life)" : "Keeping the ship's scrap (full wipe, team lives off)"));
				}
			}
			catch (Exception e)
			{
				Safe.Fail("KeepShipScrap", e);
			}
		}

		private static Exception DespawnPropsAtEndOfRound_Finalizer(Exception __exception, bool __state)
		{
			if (__state)
			{
				try
				{
					StartOfRound.Instance.allPlayersDead = true;
				}
				catch (Exception e)
				{
					Safe.Fail("KeepShipScrap.Restore", e);
				}
				Safe.Optional("KeepShipScrap.Notice", TeamLives.OnShipScrapKept);
			}
			return __exception;
		}

		private static void SetNewProfitQuota_Postfix()
		{
			Safe.Core("QuotaMet", TeamLives.OnQuotaMet);
		}

		private static void StartGame_Postfix()
		{
			Safe.Core("RoundStart", TeamLives.OnRoundStart);
		}

		private static void HudUpdate_Postfix()
		{
			Hud.TryFlush();
		}

		private static void ParsePlayerSentence_Postfix(Terminal __instance, ref TerminalNode __result)
		{
			try
			{
				TerminalNode val = TerminalPage.TryHandle(__instance);
				if ((Object)(object)val != (Object)null)
				{
					__result = val;
				}
			}
			catch (Exception e)
			{
				Safe.Fail("TerminalCommand", e);
			}
		}

		private static void TerminalStart_Postfix(Terminal __instance)
		{
			Safe.Optional("TerminalHelp", delegate
			{
				TerminalPage.AddToHelp(__instance);
			});
			Safe.Optional("DncAddLives", PatchDncAddLives);
		}

		private static void PatchDncAddLives()
		{
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			if (_dncTried || _harmony == null)
			{
				return;
			}
			_dncTried = true;
			Type type = null;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (!(assembly.GetName().Name != "DefinitelyNotCheats"))
				{
					type = assembly.GetType("DefinitelyNotCheats.Compat", throwOnError: false);
					if (type != null)
					{
						break;
					}
				}
			}
			if (!(type == null))
			{
				MethodInfo method = type.GetMethod("AddLives", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(int) }, null);
				if (!(method == null) && !(method.ReturnType != typeof(string)))
				{
					_harmony.Patch((MethodBase)method, new HarmonyMethod(typeof(Patches), "DncAddLives_Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Plugin.Log.LogInfo((object)"DefinitelyNotCheats found: its Add team lives action says when team lives are off");
				}
			}
		}

		private static bool DncAddLives_Prefix(ref string __result)
		{
			try
			{
				if (Settings.TeamLivesOn)
				{
					return true;
				}
				__result = "Team lives are off (TeamLives = false in the host's jacob.SimpleTeamLives.cfg).";
				return false;
			}
			catch (Exception e)
			{
				Safe.Fail("DncAddLives", e);
				return true;
			}
		}

		private static void ShowPlayersFiredScreen_Prefix(HUDManager __instance, bool show)
		{
			if (show)
			{
				Safe.Optional("FiredScreen.Show", delegate
				{
					Hud.OnFiredScreenShown(__instance);
				});
			}
		}

		private static void ShowPlayersFiredScreen_Postfix(bool show)
		{
			if (!show)
			{
				Safe.Optional("FiredScreen.Hide", Hud.OnFiredScreenHidden);
			}
		}
	}
	[BepInPlugin("jacob.SimpleTeamLives", "SimpleTeamLives", "1.5.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency("com.sigurd.csync", "5.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "jacob.SimpleTeamLives";

		public const string Name = "SimpleTeamLives";

		public const string Version = "1.5.1";

		internal static ManualLogSource Log;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			Step("config", delegate
			{
				Settings.Init(((BaseUnityPlugin)this).Config);
			});
			Step("networking", Net.Init);
			Step("HUD", Hud.Init);
			Step("save hooks", TeamLives.Init);
			Step("game hooks", delegate
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Expected O, but got Unknown
				Patches.Apply(new Harmony("jacob.SimpleTeamLives"));
			});
			if (Safe.Disabled)
			{
				Log.LogWarning((object)("SimpleTeamLives 1.5.1 loaded but is OFF: " + Safe.DisabledReason));
				return;
			}
			Log.LogInfo((object)("SimpleTeamLives 1.5.1 loaded (config " + (Settings.IsSynced ? "synced from host" : "local only") + ", team lives " + (Settings.TeamLivesOn ? "on" : "off") + " in this file (the host's value applies), keep ship scrap on wipe " + (Settings.KeepShipScrapOnWipe ? "on" : "off") + ", game over " + (Patches.CanFire ? "fires the crew" : "warns only") + ")"));
		}

		private static void Step(string name, Action action)
		{
			try
			{
				action();
			}
			catch (Exception e)
			{
				Safe.Fail("Startup." + name, e);
				if (name == "game hooks" || name == "save hooks")
				{
					Safe.Disable("startup failed at " + name);
				}
			}
		}
	}
	public enum GameOverMode
	{
		Fire,
		Warn
	}
	public enum LifeLossMode
	{
		WipeOnly,
		PerDeath
	}
	public enum TakeoffResult
	{
		NoChange,
		Deducted,
		GameOver,
		GameOverWarnOnly
	}
	public struct TakeoffOutcome
	{
		public TakeoffResult Result;

		public int Before;

		public int After;

		public int Dead;
	}
	public static class Rules
	{
		public const int MaxStoredLives = 999;

		public const int ValueOffByError = -1;

		public const int ValueUnknown = -2;

		public const int ValueOffByConfig = -3;

		public static TakeoffOutcome Takeoff(int before, int dead, int alive, bool onCompanyMoon, bool countCompanyMoonDeaths, GameOverMode mode, bool canFire)
		{
			return Takeoff(before, dead, alive, onCompanyMoon, countCompanyMoonDeaths, mode, canFire, LifeLossMode.PerDeath);
		}

		public static TakeoffOutcome Takeoff(int before, int dead, int alive, bool onCompanyMoon, bool countCompanyMoonDeaths, GameOverMode mode, bool canFire, LifeLossMode lossMode)
		{
			before = Clamp(before);
			dead = Math.Max(0, dead);
			alive = Math.Max(0, alive);
			TakeoffOutcome result = new TakeoffOutcome
			{
				Before = before,
				After = before,
				Dead = dead,
				Result = TakeoffResult.NoChange
			};
			if (dead == 0)
			{
				return result;
			}
			if (onCompanyMoon && !countCompanyMoonDeaths)
			{
				return result;
			}
			bool flag = alive == 0;
			if (flag && before == 0)
			{
				result.Result = ((mode == GameOverMode.Fire && canFire) ? TakeoffResult.GameOver : TakeoffResult.GameOverWarnOnly);
				return result;
			}
			if (lossMode == LifeLossMode.WipeOnly)
			{
				if (!flag)
				{
					return result;
				}
				result.After = Math.Max(0, before - 1);
				result.Result = TakeoffResult.Deducted;
				return result;
			}
			result.After = Math.Max(0, before - dead);
			result.Result = TakeoffResult.Deducted;
			return result;
		}

		public static int QuotaRefill(int before, int perQuota, int maxLives)
		{
			before = Clamp(before);
			int num = Clamp(before + Math.Max(0, perQuota));
			if (maxLives > 0)
			{
				num = Math.Max(before, Math.Min(num, maxLives));
			}
			return num;
		}

		public static int Clamp(int lives)
		{
			return Math.Max(0, Math.Min(999, lives));
		}

		public static TakeoffDecision Decide(bool teamLivesOn, bool keepShipScrapOnWipe, int before, int dead, int alive, bool onCompanyMoon, bool countCompanyMoonDeaths, GameOverMode mode, bool canFire, LifeLossMode lossMode)
		{
			TakeoffDecision result = new TakeoffDecision
			{
				TeamLivesOn = teamLivesOn
			};
			if (teamLivesOn)
			{
				result.Outcome = Takeoff(before, dead, alive, onCompanyMoon, countCompanyMoonDeaths, mode, canFire, lossMode);
			}
			else
			{
				result.Outcome = new TakeoffOutcome
				{
					Result = TakeoffResult.NoChange,
					Before = 0,
					After = 0,
					Dead = Math.Max(0, dead)
				};
			}
			result.KeepShipScrap = KeepShipScrap(teamLivesOn, keepShipScrapOnWipe, dead, alive, result.Outcome.Result);
			return result;
		}

		public static bool KeepShipScrap(bool teamLivesOn, bool keepShipScrapOnWipe, int dead, int alive, TakeoffResult result)
		{
			if (!keepShipScrapOnWipe)
			{
				return false;
			}
			if (!IsFullWipe(dead, alive))
			{
				return false;
			}
			if (teamLivesOn)
			{
				return result == TakeoffResult.Deducted;
			}
			return true;
		}

		public static bool IsFullWipe(int dead, int alive)
		{
			if (dead > 0)
			{
				return alive <= 0;
			}
			return false;
		}

		public static bool ShouldLoadLives(bool teamLivesOn, bool hosting)
		{
			return teamLivesOn && hosting;
		}

		public static bool ShouldWriteLives(bool teamLivesOn, bool hosting, bool livesReady, bool saveBlocked, bool sameSaveFile)
		{
			return teamLivesOn && hosting && livesReady && !saveBlocked && sameSaveFile;
		}

		public static LivesView View(int value, bool teamLivesOnSetting)
		{
			if (value == -1)
			{
				return LivesView.OffByError;
			}
			if (value == -3)
			{
				return LivesView.OffByConfig;
			}
			if (value >= 0)
			{
				return LivesView.Count;
			}
			if (!teamLivesOnSetting)
			{
				return LivesView.OffByConfig;
			}
			return LivesView.NotLoaded;
		}
	}
	public struct TakeoffDecision
	{
		public bool TeamLivesOn;

		public TakeoffOutcome Outcome;

		public bool KeepShipScrap;
	}
	public enum LivesView
	{
		Count,
		OffByConfig,
		OffByError,
		NotLoaded
	}
	public static class SaveKeys
	{
		public const string Lives = "SimpleTeamLives.TeamLives";

		public static readonly string[] Legacy = new string[2] { "jacob.SimpleTeamLives.TeamLives", "Unknown.TeamLives" };

		public static int Load(Func<string, int> load, int noValue, out string fromKey)
		{
			fromKey = null;
			int num = load("SimpleTeamLives.TeamLives");
			if (num >= 0)
			{
				fromKey = "SimpleTeamLives.TeamLives";
				return num;
			}
			string[] legacy = Legacy;
			foreach (string text in legacy)
			{
				num = load(text);
				if (num >= 0)
				{
					fromKey = text;
					return num;
				}
			}
			return noValue;
		}

		public static bool NeedsMigration(string fromKey)
		{
			if (fromKey != null)
			{
				return fromKey != "SimpleTeamLives.TeamLives";
			}
			return false;
		}
	}
	internal static class Safe
	{
		private const int CoreFailuresBeforeDisable = 3;

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

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

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

		private static int _coreFailures;

		internal static bool Disabled { get; private set; }

		internal static string DisabledReason { get; private set; }

		internal static void Core(string site, Action action)
		{
			if (Disabled)
			{
				return;
			}
			try
			{
				action();
			}
			catch (Exception e)
			{
				Fail(site, e);
				if (++_coreFailures >= 3)
				{
					Disable($"{_coreFailures} errors in the lives logic (last in {site})");
				}
			}
		}

		internal static void Optional(string site, Action action)
		{
			try
			{
				action();
			}
			catch (Exception e)
			{
				Fail(site, e);
			}
		}

		internal static T Optional<T>(string site, Func<T> func, T fallback)
		{
			try
			{
				return func();
			}
			catch (Exception e)
			{
				Fail(site, e);
				return fallback;
			}
		}

		internal static int Fail(string site, Exception e)
		{
			FailureCounts.TryGetValue(site, out var value);
			value = (FailureCounts[site] = value + 1);
			switch (value)
			{
			case 1:
			{
				Exception ex = e;
				while (ex.InnerException != null)
				{
					ex = ex.InnerException;
				}
				string item = ex.GetType().FullName + ": " + ex.Message;
				if (LoggedErrors.Add(item))
				{
					ManualLogSource log2 = Plugin.Log;
					if (log2 != null)
					{
						log2.LogError((object)("[" + site + "] " + e.GetType().Name + ": " + e.Message + ((ex != e) ? ("\n  caused by " + ex.GetType().Name + ": " + ex.Message) : "") + "\n" + ex.StackTrace));
					}
				}
				else
				{
					ManualLogSource log3 = Plugin.Log;
					if (log3 != null)
					{
						log3.LogDebug((object)("[" + site + "] same error as above (" + ex.GetType().Name + ")"));
					}
				}
				break;
			}
			case 2:
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[" + site + "] failed again; further errors from here are not logged"));
				}
				break;
			}
			}
			return value;
		}

		internal static void WarnOnce(string key, string message)
		{
			if (WarnedOnce.Add(key))
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)message);
				}
			}
		}

		internal static void Disable(string reason)
		{
			if (!Disabled)
			{
				Disabled = true;
				DisabledReason = reason;
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("SimpleTeamLives is OFF for this session: " + reason + ". The game continues with vanilla rules and no lives are tracked."));
				}
				Optional("Safe.DisablePublish", delegate
				{
					Net.PublishLives(-1);
				});
				Optional("Safe.DisableNotice", delegate
				{
					Hud.ShowLocal("SimpleTeamLives off", "An error switched team lives off for this session. See the BepInEx log.", warning: true);
				});
			}
		}
	}
	public class StlConfig : SyncedConfig2<StlConfig>
	{
		[SyncedEntryField]
		public SyncedEntry<bool> TeamLives;

		[SyncedEntryField]
		public SyncedEntry<int> StartingLives;

		[SyncedEntryField]
		public SyncedEntry<int> LivesPerQuota;

		[SyncedEntryField]
		public SyncedEntry<int> MaxLives;

		[SyncedEntryField]
		public SyncedEntry<bool> CountCompanyMoonDeaths;

		[SyncedEntryField]
		public SyncedEntry<GameOverMode> GameOverMode;

		[SyncedEntryField]
		public SyncedEntry<bool> ShowLivesOnTakeoff;

		[SyncedEntryField]
		public SyncedEntry<bool> KeepShipScrapOnWipe;

		[SyncedEntryField]
		public SyncedEntry<LifeLossMode> LifeLossMode;

		public StlConfig(ConfigFile cfg)
			: base("jacob.SimpleTeamLives")
		{
			TeamLives = SyncedBindingExtensions.BindSyncedEntry<bool>(cfg, "General", "TeamLives", false, Settings.Descriptions.TeamLives);
			StartingLives = SyncedBindingExtensions.BindSyncedEntry<int>(cfg, "Lives", "StartingLives", 3, Settings.Descriptions.StartingLives);
			LivesPerQuota = SyncedBindingExtensions.BindSyncedEntry<int>(cfg, "Lives", "LivesPerQuota", 1, Settings.Descriptions.LivesPerQuota);
			MaxLives = SyncedBindingExtensions.BindSyncedEntry<int>(cfg, "Lives", "MaxLives", 5, Settings.Descriptions.MaxLives);
			CountCompanyMoonDeaths = SyncedBindingExtensions.BindSyncedEntry<bool>(cfg, "Lives", "CountCompanyMoonDeaths", true, Settings.Descriptions.CountCompanyMoonDeaths);
			GameOverMode = SyncedBindingExtensions.BindSyncedEntry<GameOverMode>(cfg, "Game over", "GameOverMode", SimpleTeamLives.GameOverMode.Fire, Settings.Descriptions.GameOverMode);
			ShowLivesOnTakeoff = SyncedBindingExtensions.BindSyncedEntry<bool>(cfg, "Display", "ShowLivesOnTakeoff", true, Settings.Descriptions.ShowLivesOnTakeoff);
			LifeLossMode = SyncedBindingExtensions.BindSyncedEntry<LifeLossMode>(cfg, "Lives", "LifeLossMode", SimpleTeamLives.LifeLossMode.WipeOnly, Settings.Descriptions.LifeLossMode);
			KeepShipScrapOnWipe = SyncedBindingExtensions.BindSyncedEntry<bool>(cfg, "Lives", "KeepShipScrapOnWipe", true, Settings.Descriptions.KeepShipScrapOnWipe);
			ConfigManager.Register<StlConfig>((SyncedConfig2<StlConfig>)this);
		}
	}
	internal static class Settings
	{
		internal static class Section
		{
			public const string General = "General";

			public const string Lives = "Lives";

			public const string GameOver = "Game over";

			public const string Display = "Display";
		}

		internal static class Defaults
		{
			public const bool TeamLives = false;

			public const int StartingLives = 3;

			public const int LivesPerQuota = 1;

			public const int MaxLives = 5;

			public const bool CountCompanyMoonDeaths = true;

			public const GameOverMode GameOverMode = GameOverMode.Fire;

			public const bool ShowLivesOnTakeoff = true;

			public const bool KeepShipScrapOnWipe = true;

			public const LifeLossMode LifeLossMode = LifeLossMode.WipeOnly;
		}

		internal static class Descriptions
		{
			public static readonly ConfigDescription TeamLives = new ConfigDescription("Team lives on or off. The host's setting applies to everyone. true = the crew shares a pool of lives: a full wipe costs one (see LifeLossMode), and a wipe with none left ends the run (fired, save reset). false = vanilla rules for deaths and game over: no lives are counted, shown or saved. Lives already saved on a file are left alone and carry on if you switch this back on. KeepShipScrapOnWipe works either way.", (AcceptableValueBase)null, Array.Empty<object>());

			public static readonly ConfigDescription StartingLives = new ConfigDescription("Team lives at the start of a new run. Changing this applies to the next new run, not the current one.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 99), Array.Empty<object>());

			public static readonly ConfigDescription LivesPerQuota = new ConfigDescription("Lives added each time a quota is met.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 99), Array.Empty<object>());

			public static readonly ConfigDescription MaxLives = new ConfigDescription("Cap on the team pool. 0 means no cap.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 99), Array.Empty<object>());

			public static readonly ConfigDescription CountCompanyMoonDeaths = new ConfigDescription("Whether deaths on the Company moon cost lives.", (AcceptableValueBase)null, Array.Empty<object>());

			public static readonly ConfigDescription GameOverMode = new ConfigDescription("Fire = vanilla firing sequence and save reset when the crew wipes with 0 lives left. Warn = message only, for testing.", (AcceptableValueBase)null, Array.Empty<object>());

			public static readonly ConfigDescription LifeLossMode = new ConfigDescription("WipeOnly = a life is only used when the whole crew is dead at takeoff (1 life per wipe); single deaths are free. PerDeath = every player still dead at takeoff costs a life, even if someone survived. Either way, a full wipe with 0 lives left ends the run.", (AcceptableValueBase)null, Array.Empty<object>());

			public static readonly ConfigDescription KeepShipScrapOnWipe = new ConfigDescription("When the whole crew dies, keep the scrap already in the ship (vanilla deletes it on any full wipe). Works with team lives on or off. With team lives on it applies when a life pays for the wipe; a wipe that ends the run is unchanged. Items left on the moon or held by the dead are still lost, as normal.", (AcceptableValueBase)null, Array.Empty<object>());

			public static readonly ConfigDescription ShowLivesOnTakeoff = new ConfigDescription("Show the before and after lives count when the ship leaves a moon and someone died.", (AcceptableValueBase)null, Array.Empty<object>());
		}

		private static StlConfig _synced;

		private static ConfigEntry<int> _startingLives;

		private static ConfigEntry<int> _livesPerQuota;

		private static ConfigEntry<int> _maxLives;

		private static ConfigEntry<bool> _teamLives;

		private static ConfigEntry<bool> _countCompany;

		private static ConfigEntry<bool> _showOnTakeoff;

		private static ConfigEntry<bool> _keepScrap;

		private static ConfigEntry<GameOverMode> _gameOverMode;

		private static ConfigEntry<LifeLossMode> _lifeLossMode;

		internal static bool IsSynced => _synced != null;

		internal static bool TeamLivesOn => Read(() => _synced.TeamLives.Value, () => _teamLives.Value, fallback: false);

		internal static int StartingLives => Rules.Clamp(Read(() => _synced.StartingLives.Value, () => _startingLives.Value, 3));

		internal static int LivesPerQuota => Rules.Clamp(Read(() => _synced.LivesPerQuota.Value, () => _livesPerQuota.Value, 1));

		internal static int MaxLives => Rules.Clamp(Read(() => _synced.MaxLives.Value, () => _maxLives.Value, 5));

		internal static bool CountCompanyMoonDeaths => Read(() => _synced.CountCompanyMoonDeaths.Value, () => _countCompany.Value, fallback: true);

		internal static bool KeepShipScrapOnWipe => Read(() => _synced.KeepShipScrapOnWipe.Value, () => _keepScrap.Value, fallback: true);

		internal static bool ShowLivesOnTakeoff => Read(() => _synced.ShowLivesOnTakeoff.Value, () => _showOnTakeoff.Value, fallback: true);

		internal static LifeLossMode LifeLossMode
		{
			get
			{
				LifeLossMode lifeLossMode = Read(() => _synced.LifeLossMode.Value, () => _lifeLossMode.Value, LifeLossMode.WipeOnly);
				if (!Enum.IsDefined(typeof(LifeLossMode), lifeLossMode))
				{
					return LifeLossMode.WipeOnly;
				}
				return lifeLossMode;
			}
		}

		internal static GameOverMode GameOverMode
		{
			get
			{
				GameOverMode gameOverMode = Read(() => _synced.GameOverMode.Value, () => _gameOverMode.Value, GameOverMode.Fire);
				if (!Enum.IsDefined(typeof(GameOverMode), gameOverMode))
				{
					return GameOverMode.Fire;
				}
				return gameOverMode;
			}
		}

		internal static void Init(ConfigFile cfg)
		{
			try
			{
				_synced = new StlConfig(cfg);
				return;
			}
			catch (Exception e)
			{
				_synced = null;
				Safe.Fail("Settings.CSync", e);
				Plugin.Log.LogWarning((object)"CSync setup failed; using local config values only (not synced from host)");
			}
			try
			{
				_teamLives = cfg.Bind<bool>("General", "TeamLives", false, Descriptions.TeamLives);
				_startingLives = cfg.Bind<int>("Lives", "StartingLives", 3, Descriptions.StartingLives);
				_livesPerQuota = cfg.Bind<int>("Lives", "LivesPerQuota", 1, Descriptions.LivesPerQuota);
				_maxLives = cfg.Bind<int>("Lives", "MaxLives", 5, Descriptions.MaxLives);
				_countCompany = cfg.Bind<bool>("Lives", "CountCompanyMoonDeaths", true, Descriptions.CountCompanyMoonDeaths);
				_gameOverMode = cfg.Bind<GameOverMode>("Game over", "GameOverMode", GameOverMode.Fire, Descriptions.GameOverMode);
				_showOnTakeoff = cfg.Bind<bool>("Display", "ShowLivesOnTakeoff", true, Descriptions.ShowLivesOnTakeoff);
				_lifeLossMode = cfg.Bind<LifeLossMode>("Lives", "LifeLossMode", LifeLossMode.WipeOnly, Descriptions.LifeLossMode);
				_keepScrap = cfg.Bind<bool>("Lives", "KeepShipScrapOnWipe", true, Descriptions.KeepShipScrapOnWipe);
			}
			catch (Exception e2)
			{
				Safe.Fail("Settings.Local", e2);
				Plugin.Log.LogWarning((object)"Config could not be read; using built-in defaults");
			}
		}

		private static T Read<T>(Func<T> synced, Func<T> local, T fallback)
		{
			try
			{
				if (_synced != null)
				{
					return synced();
				}
				if (_teamLives != null)
				{
					return local();
				}
			}
			catch (Exception e)
			{
				Safe.Fail("Settings.Read", e);
			}
			return fallback;
		}
	}
	internal static class TeamLives
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static PostLoadGameEventHandler <>9__19_3;

			public static PostSaveGameEventHandler <>9__19_4;

			public static PostAutoSaveEventHandler <>9__19_5;

			public static PostResetSavedGameValuesEventHandler <>9__19_6;

			public static Action <>9__19_0;

			public static Action<bool> <>9__19_8;

			public static Action <>9__19_1;

			public static Func<Func<StartOfRound, int[]>> <>9__19_2;

			public static Func<string, int> <>9__24_0;

			internal void <Init>b__19_0()
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Expected O, but got Unknown
				//IL_0038: 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: Expected O, but got Unknown
				//IL_005c: 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: Expected O, but got Unknown
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_0085: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: Expected O, but got Unknown
				object obj = <>9__19_3;
				if (obj == null)
				{
					PostLoadGameEventHandler val = delegate(bool challenge, string file)
					{
						Safe.Core("OnLoadGame", new <>c__DisplayClass19_0
						{
							file = file
						}.<Init>b__7);
					};
					<>9__19_3 = val;
					obj = (object)val;
				}
				SaveLoadEvents.PostLoadGameEvent += (PostLoadGameEventHandler)obj;
				object obj2 = <>9__19_4;
				if (obj2 == null)
				{
					PostSaveGameEventHandler val2 = delegate
					{
						Safe.Core("OnSaveGame", Save);
					};
					<>9__19_4 = val2;
					obj2 = (object)val2;
				}
				SaveLoadEvents.PostSaveGameEvent += (PostSaveGameEventHandler)obj2;
				object obj3 = <>9__19_5;
				if (obj3 == null)
				{
					PostAutoSaveEventHandler val3 = delegate
					{
						Safe.Core("OnAutoSave", Save);
					};
					<>9__19_5 = val3;
					obj3 = (object)val3;
				}
				SaveLoadEvents.PostAutoSaveEvent += (PostAutoSaveEventHandler)obj3;
				object obj4 = <>9__19_6;
				if (obj4 == null)
				{
					PostResetSavedGameValuesEventHandler val4 = delegate
					{
						Safe.Core("OnSaveReset", OnSaveReset);
					};
					<>9__19_6 = val4;
					obj4 = (object)val4;
				}
				SaveLoadEvents.PostResetSavedGameValuesEvent += (PostResetSavedGameValuesEventHandler)obj4;
			}

			internal void <Init>b__19_3(bool challenge, string file)
			{
				Safe.Core("OnLoadGame", new <>c__DisplayClass19_0
				{
					file = file
				}.<Init>b__7);
			}

			internal void <Init>b__19_4(bool challenge, string file)
			{
				Safe.Core("OnSaveGame", Save);
			}

			internal void <Init>b__19_5(bool challenge, string file)
			{
				Safe.Core("OnAutoSave", Save);
			}

			internal void <Init>b__19_6()
			{
				Safe.Core("OnSaveReset", OnSaveReset);
			}

			internal void <Init>b__19_1()
			{
				LNetworkUtils.OnNetworkStart += delegate(bool isServer)
				{
					if (isServer)
					{
						if (!Settings.TeamLivesOn)
						{
							Net.PublishLives(-3);
						}
						else if (_livesReady)
						{
							Net.PublishLives(Lives);
						}
					}
				};
			}

			internal void <Init>b__19_8(bool isServer)
			{
				if (isServer)
				{
					if (!Settings.TeamLivesOn)
					{
						Net.PublishLives(-3);
					}
					else if (_livesReady)
					{
						Net.PublishLives(Lives);
					}
				}
			}

			internal Func<StartOfRound, int[]> <Init>b__19_2()
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(StartOfRound), "GetEndgameStatsInOrder", (Type[])null, (Type[])null);
				if (!(methodInfo == null))
				{
					return AccessTools.MethodDelegate<Func<StartOfRound, int[]>>(methodInfo, (object)null, true);
				}
				return null;
			}

			internal int <LoadOrInitialise>b__24_0(string k)
			{
				return SaveLoadHandler.LoadData<int>(k, (SaveLocation)0, -1, false);
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass19_0
		{
			public string file;

			internal void <Init>b__7()
			{
				OnLoadGame(file);
			}
		}

		private const int NoSavedValue = -1;

		private const string CompanySceneName = "CompanyBuilding";

		private const float SameRoundSeconds = 60f;

		private const float GameOverPendingMaxSeconds = 600f;

		internal static int Lives;

		private static bool _livesReady;

		private static string _livesFile;

		private static bool _saveBlocked;

		private static float _lastTakeoffTime = -1000f;

		private static bool _takeoffProcessedThisRound;

		private static bool _gameOverPending;

		private static float _gameOverPendingSince;

		private static bool _announceNewRun;

		private static bool _protectShipScrap;

		private static Func<StartOfRound, int[]> _getEndgameStatsInOrder;

		internal static int LivesForDisplay
		{
			get
			{
				if (Settings.TeamLivesOn)
				{
					if (!_livesReady || !(_livesFile == CurrentSaveFile))
					{
						return -2;
					}
					return Lives;
				}
				return -3;
			}
		}

		internal static bool TeamLivesOn => Settings.TeamLivesOn;

		private static bool IsHosting
		{
			get
			{
				if ((Object)(object)GameNetworkManager.Instance != (Object)null)
				{
					return GameNetworkManager.Instance.isHostingGame;
				}
				return false;
			}
		}

		private static string CurrentSaveFile
		{
			get
			{
				if (!((Object)(object)GameNetworkManager.Instance != (Object)null))
				{
					return null;
				}
				return GameNetworkManager.Instance.currentSaveFileName;
			}
		}

		internal static void Init()
		{
			Safe.Optional("TeamLives.Init.SaveEvents", delegate
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Expected O, but got Unknown
				//IL_0038: 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: Expected O, but got Unknown
				//IL_005c: 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: Expected O, but got Unknown
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_0085: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: Expected O, but got Unknown
				object obj = <>c.<>9__19_3;
				if (obj == null)
				{
					PostLoadGameEventHandler val = delegate(bool challenge, string file)
					{
						Safe.Core("OnLoadGame", delegate
						{
							OnLoadGame(file);
						});
					};
					<>c.<>9__19_3 = val;
					obj = (object)val;
				}
				SaveLoadEvents.PostLoadGameEvent += (PostLoadGameEventHandler)obj;
				object obj2 = <>c.<>9__19_4;
				if (obj2 == null)
				{
					PostSaveGameEventHandler val2 = delegate
					{
						Safe.Core("OnSaveGame", Save);
					};
					<>c.<>9__19_4 = val2;
					obj2 = (object)val2;
				}
				SaveLoadEvents.PostSaveGameEvent += (PostSaveGameEventHandler)obj2;
				object obj3 = <>c.<>9__19_5;
				if (obj3 == null)
				{
					PostAutoSaveEventHandler val3 = delegate
					{
						Safe.Core("OnAutoSave", Save);
					};
					<>c.<>9__19_5 = val3;
					obj3 = (object)val3;
				}
				SaveLoadEvents.PostAutoSaveEvent += (PostAutoSaveEventHandler)obj3;
				object obj4 = <>c.<>9__19_6;
				if (obj4 == null)
				{
					PostResetSavedGameValuesEventHandler val4 = delegate
					{
						Safe.Core("OnSaveReset", OnSaveReset);
					};
					<>c.<>9__19_6 = val4;
					obj4 = (object)val4;
				}
				SaveLoadEvents.PostResetSavedGameValuesEvent += (PostResetSavedGameValuesEventHandler)obj4;
			});
			Safe.Optional("TeamLives.Init.NetworkStart", delegate
			{
				LNetworkUtils.OnNetworkStart += delegate(bool isServer)
				{
					if (isServer)
					{
						if (!Settings.TeamLivesOn)
						{
							Net.PublishLives(-3);
						}
						else if (_livesReady)
						{
							Net.PublishLives(Lives);
						}
					}
				};
			});
			_getEndgameStatsInOrder = Safe.Optional("TeamLives.Init.EndgameStats", delegate
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(StartOfRound), "GetEndgameStatsInOrder", (Type[])null, (Type[])null);
				return (!(methodInfo == null)) ? AccessTools.MethodDelegate<Func<StartOfRound, int[]>>(methodInfo, (object)null, true) : null;
			}, null);
		}

		private static void OnLoadGame(string saveFileName)
		{
			ResetRoundState();
			if (IsHosting)
			{
				if (!Rules.ShouldLoadLives(Settings.TeamLivesOn, IsHosting))
				{
					SetLivesOff();
					Plugin.Log.LogInfo((object)("Team lives are off (TeamLives = false): vanilla rules on " + saveFileName + "; nothing is read or written for lives" + (Settings.KeepShipScrapOnWipe ? ". The ship's scrap is kept on a full wipe" : "")));
				}
				else
				{
					LoadOrInitialise(saveFileName);
				}
			}
		}

		private static void SetLivesOff()
		{
			_livesReady = false;
			_livesFile = null;
			_announceNewRun = false;
			Net.PublishLives(-3);
		}

		private static void LoadOrInitialise(string saveFileName)
		{
			int num = -1;
			bool flag = false;
			string fromKey = null;
			try
			{
				num = SaveKeys.Load((string k) => SaveLoadHandler.LoadData<int>(k, (SaveLocation)0, -1, false), -1, out fromKey);
			}
			catch (Exception e)
			{
				Safe.Fail("LoadLives", e);
				flag = true;
			}
			_saveBlocked = flag;
			if (num < 0)
			{
				Lives = Settings.StartingLives;
				_announceNewRun = true;
				_livesReady = true;
				_livesFile = CurrentSaveFile;
				if (!flag)
				{
					Save();
				}
				Plugin.Log.LogInfo((object)(flag ? $"Couldn't read saved lives on {saveFileName}; using StartingLives {Lives} for now" : $"New run on {saveFileName}: team lives {Lives}"));
			}
			else
			{
				Lives = Rules.Clamp(num);
				Plugin.Log.LogInfo((object)$"Loaded team lives {Lives} from {saveFileName}");
			}
			_livesReady = true;
			_livesFile = CurrentSaveFile;
			if (!flag && num >= 0 && SaveKeys.NeedsMigration(fromKey))
			{
				Save();
				Plugin.Log.LogInfo((object)("Moved team lives on " + saveFileName + " from the 1.4.0 save key (" + fromKey + ") to SimpleTeamLives.TeamLives"));
			}
			if (flag)
			{
				Plugin.Log.LogWarning((object)"Team lives won't be written to this save this session, to protect the stored value");
			}
			Net.PublishLives(Lives);
		}

		private static void Save()
		{
			if (Rules.ShouldWriteLives(Settings.TeamLivesOn, IsHosting, _livesReady, _saveBlocked, _livesFile == CurrentSaveFile) && !SaveLoadHandler.SaveData<int>(Lives, "SimpleTeamLives.TeamLives", (SaveLocation)0, false))
			{
				Safe.WarnOnce("SaveLives", "LethalModDataLib reported it couldn't save team lives (further save failures not logged)");
			}
		}

		private static void OnSaveReset()
		{
			ResetRoundState();
			if (IsHosting)
			{
				if (!Settings.TeamLivesOn)
				{
					SetLivesOff();
					return;
				}
				Lives = Settings.StartingLives;
				_livesReady = true;
				_livesFile = CurrentSaveFile;
				_saveBlocked = false;
				_announceNewRun = true;
				Save();
				Net.PublishLives(Lives);
				Plugin.Log.LogInfo((object)$"Save reset after firing: team lives back to {Lives}");
			}
		}

		private static void ResetRoundState()
		{
			_takeoffProcessedThisRound = false;
			_gameOverPending = false;
			_lastTakeoffTime = -1000f;
			_protectShipScrap = false;
		}

		private static bool EnsureLivesReady()
		{
			if (!Settings.TeamLivesOn)
			{
				return false;
			}
			if (_livesReady && _livesFile == CurrentSaveFile)
			{
				return true;
			}
			Safe.WarnOnce("LateLoad", "Team lives weren't loaded with this save; loading them now");
			LoadOrInitialise(CurrentSaveFile ?? "current save");
			return _livesReady;
		}

		internal static void OnRoundStart()
		{
			if (Net.IsHost)
			{
				_takeoffProcessedThisRound = false;
				_gameOverPending = false;
				_protectShipScrap = false;
				if (_announceNewRun && _livesReady && Settings.TeamLivesOn)
				{
					_announceNewRun = false;
					Net.SendNotice($"Team lives: {Lives}", "Shared by the whole crew for this run.");
				}
			}
		}

		internal static void OnTakeoff(StartOfRound sor)
		{
			if (!Net.IsHost || (Object)(object)sor == (Object)null)
			{
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (_takeoffProcessedThisRound && realtimeSinceStartup - _lastTakeoffTime < 60f)
			{
				return;
			}
			_takeoffProcessedThisRound = true;
			_lastTakeoffTime = realtimeSinceStartup;
			_gameOverPending = false;
			_protectShipScrap = false;
			if (sor.isChallengeFile)
			{
				return;
			}
			CountPlayers(sor, out var dead, out var alive);
			bool flag = (Object)(object)sor.currentLevel != (Object)null && sor.currentLevel.sceneName == "CompanyBuilding";
			if (!Settings.TeamLivesOn)
			{
				TakeoffDecision takeoffDecision = Rules.Decide(teamLivesOn: false, Settings.KeepShipScrapOnWipe, 0, dead, alive, flag, Settings.CountCompanyMoonDeaths, Settings.GameOverMode, Patches.CanFire, Settings.LifeLossMode);
				_protectShipScrap = takeoffDecision.KeepShipScrap;
				if (dead > 0)
				{
					Plugin.Log.LogInfo((object)($"Takeoff (team lives off): {dead} dead, {alive} alive (vanilla living={sor.livingPlayers})" + (takeoffDecision.KeepShipScrap ? ": full wipe, keeping the scrap in the ship" : (Rules.IsFullWipe(dead, alive) ? ": full wipe, KeepShipScrapOnWipe is off so vanilla clears the ship" : ""))));
				}
			}
			else
			{
				if (!EnsureLivesReady())
				{
					return;
				}
				TakeoffDecision takeoffDecision2 = Rules.Decide(teamLivesOn: true, Settings.KeepShipScrapOnWipe, Lives, dead, alive, flag, Settings.CountCompanyMoonDeaths, Settings.GameOverMode, Patches.CanFire, Settings.LifeLossMode);
				TakeoffOutcome outcome = takeoffDecision2.Outcome;
				Plugin.Log.LogInfo((object)($"Takeoff ({Settings.LifeLossMode}): {dead} dead, {alive} alive (vanilla living={sor.livingPlayers}), " + $"lives {outcome.Before} -> {outcome.After}, {outcome.Result}" + (flag ? " (Company moon)" : "")));
				switch (outcome.Result)
				{
				case TakeoffResult.NoChange:
					break;
				case TakeoffResult.GameOver:
					_gameOverPending = true;
					_gameOverPendingSince = realtimeSinceStartup;
					break;
				case TakeoffResult.GameOverWarnOnly:
				{
					string body = (Patches.CanFire ? "Warn mode: the run would have ended here." : "The run should have ended here, but firing isn't available in this game version.");
					Net.SendNotice("Out of team lives", body, warning: true);
					break;
				}
				case TakeoffResult.Deducted:
					if (takeoffDecision2.KeepShipScrap)
					{
						_protectShipScrap = true;
						Plugin.Log.LogInfo((object)"Full wipe paid for with a life: keeping the scrap in the ship");
					}
					Lives = outcome.After;
					Net.PublishLives(Lives);
					SendTakeoffNotice(outcome);
					break;
				}
			}
		}

		internal static bool ConsumeShipScrapProtection()
		{
			if (!_protectShipScrap)
			{
				return false;
			}
			_protectShipScrap = false;
			return true;
		}

		internal static void OnShipScrapKept()
		{
			if (!Settings.TeamLivesOn)
			{
				Net.SendNotice("Ship's scrap kept", "The whole crew died, but the scrap already in the ship is safe.");
			}
		}

		private static void SendTakeoffNotice(TakeoffOutcome o)
		{
			string text = ((o.After == 0) ? "No lives left. The next full wipe ends the run." : null);
			if (Settings.ShowLivesOnTakeoff)
			{
				string header = ((o.Before == o.After) ? $"Team lives: {o.After}" : $"Team lives: {o.Before} -> {o.After}");
				string body = text ?? ((o.Dead == 1) ? "1 crew member didn't make it back." : $"{o.Dead} crew members didn't make it back.");
				Net.SendNotice(header, body, o.After == 0);
			}
			else if (text != null)
			{
				Net.SendNotice("Team lives: 0", text, warning: true);
			}
		}

		internal static void OnQuotaMet()
		{
			if (Net.IsHost && Settings.TeamLivesOn && (!((Object)(object)StartOfRound.Instance != (Object)null) || !StartOfRound.Instance.isChallengeFile) && !_gameOverPending && EnsureLivesReady())
			{
				int lives = Lives;
				int num = (Lives = Rules.QuotaRefill(lives, Settings.LivesPerQuota, Settings.MaxLives));
				Net.PublishLives(Lives);
				Plugin.Log.LogInfo((object)$"Quota met: team lives {lives} -> {num}");
				string body = ((num == lives) ? $"Team lives: {num} (max)" : $"Team lives: {lives} -> {num}");
				Net.SendNotice("Quota met", body);
			}
		}

		internal static bool ContinueOrFire(StartOfRound sor)
		{
			if (!_gameOverPending)
			{
				return true;
			}
			_gameOverPending = false;
			if (Safe.Disabled || !Net.IsHost || (Object)(object)sor == (Object)null)
			{
				return true;
			}
			if (!Settings.TeamLivesOn)
			{
				Plugin.Log.LogWarning((object)"Team lives were switched off before the run could end; the run continues");
				return true;
			}
			if (Time.realtimeSinceStartup - _gameOverPendingSince > 600f)
			{
				Plugin.Log.LogWarning((object)"Dropped a stale game over (older than 10 minutes); the run continues");
				return true;
			}
			int[] array;
			try
			{
				array = ((_getEndgameStatsInOrder != null) ? _getEndgameStatsInOrder(sor) : null);
			}
			catch (Exception e)
			{
				Safe.Fail("GetEndgameStatsInOrder", e);
				array = null;
			}
			if (array == null || array.Length < 4)
			{
				array = new int[4];
			}
			Plugin.Log.LogInfo((object)"Out of team lives: starting the vanilla firing sequence");
			Net.SendOutOfLives();
			try
			{
				sor.FirePlayersAfterDeadlineClientRpc(array, false);
				return false;
			}
			catch (Exception e2)
			{
				Safe.Fail("FirePlayers", e2);
				Plugin.Log.LogError((object)"Couldn't fire the crew; the run continues instead");
				Net.SendNotice("Out of team lives", "Firing failed, so the run continues. See the BepInEx log.", warning: true);
				return true;
			}
		}

		internal static void CountPlayers(StartOfRound sor, out int dead, out int alive)
		{
			dead = 0;
			alive = 0;
			if (sor.allPlayerScripts == null)
			{
				return;
			}
			PlayerControllerB[] allPlayerScripts = sor.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if (!((Object)(object)val == (Object)null) && !val.disconnectedMidGame)
				{
					if (val.isPlayerDead)
					{
						dead++;
					}
					else if (val.isPlayerControlled)
					{
						alive++;
					}
				}
			}
		}
	}
	internal static class TerminalPage
	{
		private const string HelpMarker = ">LIVES";

		private static TerminalNode _node;

		private const string Rule = "____________________________\n\n";

		internal const int LivesOff = -1;

		internal const int LivesUnknown = -2;

		internal const int LivesDisabled = -3;

		internal static TerminalNode TryHandle(Terminal terminal)
		{
			if ((Object)(object)terminal == (Object)null || (Object)(object)terminal.screenText == (Object)null)
			{
				return null;
			}
			string text = terminal.screenText.text ?? "";
			int textAdded = terminal.textAdded;
			if (textAdded <= 0 || textAdded > text.Length)
			{
				return null;
			}
			if (!IsLivesCommand(text.Substring(text.Length - textAdded)))
			{
				return null;
			}
			TerminalNode node = GetNode();
			node.displayText = BuildText();
			return node;
		}

		internal static bool IsLivesCommand(string input)
		{
			if (string.IsNullOrEmpty(input) || input.Length > 40)
			{
				return false;
			}
			StringBuilder stringBuilder = new StringBuilder(input.Length);
			foreach (char c in input)
			{
				if (char.IsLetter(c))
				{
					stringBuilder.Append(char.ToLowerInvariant(c));
				}
			}
			string text = stringBuilder.ToString();
			if (!(text == "lives"))
			{
				return text == "teamlives";
			}
			return true;
		}

		private static TerminalNode GetNode()
		{
			if ((Object)(object)_node != (Object)null)
			{
				return _node;
			}
			TerminalNode obj = ScriptableObject.CreateInstance<TerminalNode>();
			((Object)obj).name = "SimpleTeamLives_LivesPage";
			obj.clearPreviousText = true;
			obj.maxCharactersToType = 25;
			obj.terminalEvent = "";
			obj.creatureName = "";
			obj.buyItemIndex = -1;
			obj.buyVehicleIndex = -1;
			obj.buyRerouteToMoon = -1;
			obj.displayPlanetInfo = -1;
			obj.shipUnlockableID = -1;
			obj.creatureFileID = -1;
			obj.storyLogFileID = -1;
			obj.playSyncedClip = -1;
			obj.itemCost = 0;
			obj.buyUnlockable = false;
			obj.returnFromStorage = false;
			obj.isConfirmationNode = false;
			obj.overrideOptions = false;
			obj.acceptAnything = false;
			obj.loadImageSlowly = false;
			obj.persistentImage = false;
			((Object)obj).hideFlags = (HideFlags)32;
			_node = obj;
			return obj;
		}

		private static string BuildText()
		{
			StringBuilder stringBuilder = new StringBuilder();
			if ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.isChallengeFile)
			{
				stringBuilder.Append("Team lives:\n").Append("____________________________\n\n");
				stringBuilder.Append("Team lives aren't used on challenge moons.\n\n");
				return stringBuilder.ToString();
			}
			int num = CurrentLives();
			switch (Rules.View(num, Settings.TeamLivesOn))
			{
			case LivesView.OffByError:
				stringBuilder.Append("Team lives:\n").Append("____________________________\n\n");
				stringBuilder.Append("Team lives are OFF this session. An error switched them off, so the game is running with vanilla rules. The host's BepInEx log has the details.\n\n");
				return stringBuilder.ToString();
			case LivesView.OffByConfig:
				stringBuilder.Append("Team lives:\n").Append("____________________________\n\n");
				stringBuilder.Append("Team lives are off. Deaths and game over follow the normal rules.\n\n");
				stringBuilder.Append("To turn them on, the host closes the game and sets TeamLives = true under [General] in BepInEx/config/jacob.SimpleTeamLives.cfg.\n\n");
				if (Settings.KeepShipScrapOnWipe)
				{
					stringBuilder.Append("If the whole crew dies, the scrap already in the ship is kept.\n\n");
				}
				return stringBuilder.ToString();
			case LivesView.NotLoaded:
				stringBuilder.Append("Team lives:\n").Append("____________________________\n\n");
				stringBuilder.Append("Lives haven't loaded yet. Try again once the ship is in orbit.\n\n");
				return stringBuilder.ToString();
			default:
			{
				int maxLives = Settings.MaxLives;
				int livesPerQuota = Settings.LivesPerQuota;
				stringBuilder.Append("Team lives: ").Append(num).Append("\n")
					.Append("____________________________\n\n");
				if (num == 0)
				{
					stringBuilder.Append((Settings.GameOverMode == GameOverMode.Fire) ? "WARNING: no lives left. If the whole crew dies on a moon, you're fired. One death is still survivable.\n\n" : "No lives left. A full crew wipe would end the run, but game over is set to warn only.\n\n");
				}
				stringBuilder.Append((Settings.LifeLossMode == LifeLossMode.WipeOnly) ? "A life is only used if the whole crew is dead when the ship leaves. One person dying costs nothing.\n\n" : "Anyone still dead when the ship leaves costs 1 life. Revived before takeoff costs nothing.\n\n");
				if (livesPerQuota > 0)
				{
					stringBuilder.Append("Meeting a quota adds ").Append(livesPerQuota).Append((livesPerQuota == 1) ? " life" : " lives");
					if (maxLives > 0)
					{
						stringBuilder.Append((num >= maxLives) ? (", but you're already at the max of " + maxLives) : (", up to a max of " + maxLives));
					}
					stringBuilder.Append(".\n\n");
				}
				else
				{
					stringBuilder.Append("Meeting a quota doesn't add lives.\n\n");
				}
				if (!Settings.CountCompanyMoonDeaths)
				{
					stringBuilder.Append("Deaths on the Company moon don't cost lives.\n\n");
				}
				if (Settings.KeepShipScrapOnWipe)
				{
					stringBuilder.Append("If a life pays for a full wipe, the scrap already in the ship is kept.\n\n");
				}
				return stringBuilder.ToString();
			}
			}
		}

		private static int CurrentLives()
		{
			if (Safe.Disabled)
			{
				return -1;
			}
			if (Net.IsHost)
			{
				return TeamLives.LivesForDisplay;
			}
			if (Net.Lives == null)
			{
				return -2;
			}
			return Net.Lives.Value;
		}

		internal static void AddToHelp(Terminal terminal)
		{
			TerminalKeyword[] array = terminal?.terminalNodes?.allKeywords;
			if (array == null)
			{
				return;
			}
			TerminalKeyword[] array2 = array;
			foreach (TerminalKeyword val in array2)
			{
				if (!((Object)(object)val == (Object)null) && string.Equals(val.word, "other", StringComparison.OrdinalIgnoreCase))
				{
					TerminalNode specialKeywordResult = val.specialKeywordResult;
					if (!((Object)(object)specialKeywordResult == (Object)null) && specialKeywordResult.displayText != null && !specialKeywordResult.displayText.Contains(">LIVES"))
					{
						string text = specialKeywordResult.displayText.TrimEnd('\n', ' ');
						specialKeywordResult.displayText = text + "\n\n>LIVES\nTo see the crew's shared team lives.\n\n\n";
					}
					break;
				}
			}
		}
	}
}