Decompiled source of KeepCheckpoint v1.1.1

KeepCheckpoint.dll

Decompiled 5 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Peak;
using Peak.Network;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.SceneManagement;
using Zorro.Core;

[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("KeepCheckpoint")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1+5cf153d318f4f64f1cd91f34a1f7a25416aa59a9")]
[assembly: AssemblyProduct("KeepCheckpoint")]
[assembly: AssemblyTitle("KeepCheckpoint")]
[assembly: AssemblyVersion("1.1.1.0")]
namespace KeepCheckpoint;

internal class Cover : MonoBehaviour
{
	internal const string RoomKey = "t0y9n.kc.reload";

	private const float MaxSeconds = 15f;

	private const float IslandSettleSeconds = 1f;

	private float shownAt = float.NaN;

	private bool atAirport;

	private float islandReadySince = float.NaN;

	private float savedVolume = 1f;

	private static Cover instance;

	private GUIStyle labelStyle;

	internal static bool Showing { get; private set; }

	internal static void MarkRoom(string runId)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Expected O, but got Unknown
		//IL_0025: Expected O, but got Unknown
		if (InOnlineRoom())
		{
			Room currentRoom = PhotonNetwork.CurrentRoom;
			Hashtable val = new Hashtable();
			((Dictionary<object, object>)val).Add((object)"t0y9n.kc.reload", (object)runId);
			currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
		}
	}

	internal static void ClearRoom()
	{
		//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_0025: Expected O, but got Unknown
		//IL_002c: Expected O, but got Unknown
		if (InOnlineRoom() && RoomMarked())
		{
			Room currentRoom = PhotonNetwork.CurrentRoom;
			Hashtable val = new Hashtable();
			((Dictionary<object, object>)val).Add((object)"t0y9n.kc.reload", (object)null);
			currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
		}
	}

	private static bool InOnlineRoom()
	{
		if (PhotonNetwork.InRoom && !PhotonNetwork.OfflineMode)
		{
			return PhotonNetwork.CurrentRoom != null;
		}
		return false;
	}

	private static bool RoomMarked()
	{
		if (PhotonNetwork.CurrentRoom == null)
		{
			return false;
		}
		if (((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)"t0y9n.kc.reload", out object value))
		{
			return value != null;
		}
		return false;
	}

	private void OnEnable()
	{
		SceneManager.sceneLoaded += OnSceneLoaded;
	}

	private void OnDisable()
	{
		SceneManager.sceneLoaded -= OnSceneLoaded;
	}

	private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
	{
		try
		{
			atAirport = ((Scene)(ref scene)).name == "Airport";
			islandReadySince = float.NaN;
			if (atAirport && !Showing && Plugin.Enabled.Value && (PhotonNetwork.IsMasterClient ? ReloadWatcher.ReloadPending : RoomMarked()))
			{
				Show();
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)ex.ToString());
		}
	}

	private void Show()
	{
		Showing = true;
		shownAt = Time.realtimeSinceStartup;
		savedVolume = AudioListener.volume;
		Plugin.Log.LogInfo((object)"Hiding the airport while the checkpoint loads again.");
	}

	internal static void HideNow(string reason)
	{
		if ((Object)(object)instance != (Object)null)
		{
			instance.Hide(reason);
		}
	}

	private void Awake()
	{
		instance = this;
	}

	private void Hide(string reason)
	{
		if (Showing)
		{
			Showing = false;
			shownAt = float.NaN;
			AudioListener.volume = savedVolume;
			Plugin.Log.LogInfo((object)("Showing the game again: " + reason + "."));
		}
	}

	private void LateUpdate()
	{
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		if (!Showing)
		{
			return;
		}
		AudioListener.volume = 0f;
		try
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup - shownAt >= 15f)
			{
				string[] obj = new string[13]
				{
					"the checkpoint did not load within ",
					15f.ToString(),
					" seconds (scene ",
					null,
					null,
					null,
					null,
					null,
					null,
					null,
					null,
					null,
					null
				};
				Scene activeScene = SceneManager.GetActiveScene();
				obj[3] = ((Scene)(ref activeScene)).name;
				obj[4] = ", loading ";
				obj[5] = LoadingScreenHandler.loading.ToString();
				obj[6] = ", own character ";
				obj[7] = ((Object)(object)Character.localCharacter != (Object)null).ToString();
				obj[8] = ", host ";
				obj[9] = PhotonNetwork.IsMasterClient.ToString();
				obj[10] = ", room marked ";
				obj[11] = RoomMarked().ToString();
				obj[12] = ")";
				Hide(string.Concat(obj));
			}
			else if (atAirport)
			{
				if (!PhotonNetwork.IsMasterClient && !RoomMarked())
				{
					Hide("the host stayed at the airport");
				}
			}
			else if (!PhotonNetwork.IsMasterClient && !RoomMarked())
			{
				Hide("the host is back at the campfire");
			}
			else if (LoadingScreenHandler.loading || (Object)(object)Character.localCharacter == (Object)null)
			{
				islandReadySince = float.NaN;
			}
			else
			{
				if (float.IsNaN(islandReadySince))
				{
					islandReadySince = realtimeSinceStartup;
				}
				if (realtimeSinceStartup - islandReadySince >= 1f)
				{
					Hide("back at the campfire");
				}
			}
		}
		catch (Exception ex)
		{
			Hide(ex.ToString());
		}
	}

	private void OnGUI()
	{
		//IL_0012: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		if (Showing)
		{
			GUI.depth = -10000;
			GUI.color = Color.black;
			GUI.DrawTexture(new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), (Texture)(object)Texture2D.whiteTexture);
			if (labelStyle == null)
			{
				labelStyle = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)4
				};
				labelStyle.normal.textColor = Color.white;
			}
			labelStyle.fontSize = Mathf.Max(18, Screen.height / 30);
			int count = (int)(Time.realtimeSinceStartup * 2f) % 4;
			GUI.color = Color.white;
			GUI.Label(new Rect(0f, (float)Screen.height * 0.45f, (float)Screen.width, (float)Screen.height * 0.1f), "Returning to the campfire" + new string('.', count), labelStyle);
		}
	}
}
[BepInPlugin("t0y9n.peak.keepcheckpoint", "KeepCheckpoint", "1.1.1")]
public class Plugin : BaseUnityPlugin
{
	internal const string Guid = "t0y9n.peak.keepcheckpoint";

	internal static ConfigEntry<bool> Enabled;

	internal static ConfigEntry<bool> KeepAfterWin;

	internal static ConfigEntry<bool> ReloadOnWipe;

	internal static ManualLogSource Log;

	private void Awake()
	{
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Expected O, but got Unknown
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Keep the checkpoint after a loss. When false, the game behaves as unmodded.");
		KeepAfterWin = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "KeepAfterWin", false, "Also keep the checkpoint after a win. Ignored when Enabled is false.");
		ReloadOnWipe = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ReloadOnWipe", true, "When the whole team dies, load the checkpoint again right away instead of ending the run, so no one has to pick Continue. Only the host's setting matters. Ignored when Enabled is false.");
		try
		{
			new Harmony("t0y9n.peak.keepcheckpoint").PatchAll(typeof(Plugin).Assembly);
		}
		catch (Exception arg)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)$"Patching failed, the checkpoint is deleted as usual: {arg}");
			return;
		}
		GameObject val = new GameObject("KeepCheckpoint");
		Object.DontDestroyOnLoad((Object)val);
		val.AddComponent<ReloadWatcher>();
		val.AddComponent<Cover>();
	}
}
[HarmonyPatch(typeof(Character), "RPCEndGame")]
internal static class EndGamePatch
{
	[ThreadStatic]
	internal static bool KeepFile;

	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		return CallSwap.ReplaceOne(instructions, AccessTools.Method(typeof(Quicksave), "DestroySaveData", (Type[])null, (Type[])null), AccessTools.Method(typeof(EndGamePatch), "DestroySaveDataOnGameOver", (Type[])null, (Type[])null), "Character.RPCEndGame");
	}

	internal static void DestroySaveDataOnGameOver()
	{
		bool keepFile;
		try
		{
			keepFile = ShouldKeep();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Keep check failed, the checkpoint is deleted as usual: " + ex.GetType().Name + ": " + ex.Message));
			keepFile = false;
		}
		bool keepFile2 = KeepFile;
		KeepFile = keepFile;
		try
		{
			Quicksave.DestroySaveData();
		}
		finally
		{
			KeepFile = keepFile2;
		}
	}

	private static bool ShouldKeep()
	{
		if (!Plugin.Enabled.Value)
		{
			return false;
		}
		if (Plugin.KeepAfterWin.Value)
		{
			return true;
		}
		if (SomeoneWon())
		{
			Plugin.Log.LogInfo((object)"Checkpoint not kept: the run was won.");
			return false;
		}
		return true;
	}

	private static bool SomeoneWon()
	{
		try
		{
			foreach (Character allCharacter in Character.AllCharacters)
			{
				if (Character.CheckWinCondition(allCharacter))
				{
					return true;
				}
			}
			return false;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Win check failed, keeping the checkpoint: " + ex.GetType().Name + ": " + ex.Message));
			return false;
		}
	}
}
[HarmonyPatch(typeof(Quicksave), "DestroySaveData")]
internal static class DestroySaveDataPatch
{
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		return CallSwap.ReplaceOne(instructions, AccessTools.Method(typeof(File), "Delete", new Type[1] { typeof(string) }, (Type[])null), AccessTools.Method(typeof(DestroySaveDataPatch), "Delete", (Type[])null, (Type[])null), "Quicksave.DestroySaveData");
	}

	internal static void Delete(string path)
	{
		if (EndGamePatch.KeepFile)
		{
			Plugin.Log.LogInfo((object)"Checkpoint kept.");
		}
		else
		{
			File.Delete(path);
		}
	}
}
internal static class CallSwap
{
	internal static IEnumerable<CodeInstruction> ReplaceOne(IEnumerable<CodeInstruction> instructions, MethodInfo from, MethodInfo to, string where)
	{
		List<CodeInstruction> list = instructions.ToList();
		List<CodeInstruction> list2 = ((from == null) ? new List<CodeInstruction>() : list.Where((CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, from)).ToList());
		if (to == null || list2.Count != 1)
		{
			Plugin.Log.LogWarning((object)string.Format("{0}: expected one call to {1}, found {2}. Not patched; the checkpoint is deleted as usual.", where, from?.Name ?? "?", list2.Count));
			return list;
		}
		list2[0].opcode = OpCodes.Call;
		list2[0].operand = to;
		return list;
	}
}
internal static class Wipe
{
	internal const string AirportScene = "Airport";

	internal static bool TeamIsDead()
	{
		if (!Plugin.Enabled.Value || !Plugin.ReloadOnWipe.Value)
		{
			return false;
		}
		if (!PhotonNetwork.IsMasterClient || !GameHandler.IsOnIsland || RunSettings.isMiniRun)
		{
			return false;
		}
		Character localCharacter = Character.localCharacter;
		if ((Object)(object)localCharacter == (Object)null || localCharacter.gameOver)
		{
			return false;
		}
		List<Character> allCharacters = Character.AllCharacters;
		if (allCharacters.Count == 0)
		{
			return false;
		}
		for (int i = 0; i < allCharacters.Count; i++)
		{
			if ((Object)(object)allCharacters[i] == (Object)null || !allCharacters[i].data.dead)
			{
				return false;
			}
		}
		return true;
	}

	internal unsafe static bool TryReadSave(string runId, out string reason)
	{
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		if (!Quicksave.Exists)
		{
			reason = "there is no checkpoint";
			return false;
		}
		bool answered = false;
		bool loaded = false;
		Quicksave.TryLoadSave((Action<bool>)delegate(bool success)
		{
			if (!answered)
			{
				answered = true;
				loaded = success;
			}
		});
		if (!loaded)
		{
			reason = "the checkpoint could not be read";
			return false;
		}
		if (runId == null || !string.Equals(Quicksave.SavedRunId, runId, StringComparison.OrdinalIgnoreCase))
		{
			reason = "the checkpoint is from another run";
			return false;
		}
		RunProgress savedRun = Quicksave.SavedRun;
		LobbyMode lobbyType = ((RunProgress)(ref savedRun)).LobbyType;
		LobbyMode val = (LobbyMode)(NetCode.Session.IsOffline ? 1 : 2);
		if (lobbyType != val)
		{
			reason = "the checkpoint is a " + ((object)(*(LobbyMode*)(&lobbyType))/*cast due to .constrained prefix*/).ToString() + " run and this is a " + ((object)(*(LobbyMode*)(&val))/*cast due to .constrained prefix*/).ToString() + " run";
			return false;
		}
		reason = null;
		return true;
	}
}
[HarmonyPatch(typeof(Character), "CheckEndGame")]
internal static class CheckEndGamePatch
{
	private static bool Prefix()
	{
		if (ReloadWatcher.EndRequested || !Wipe.TeamIsDead())
		{
			return true;
		}
		if (!Quicksave.Exists)
		{
			return true;
		}
		if (!ReloadWatcher.IsRunning)
		{
			Plugin.Log.LogWarning((object)"The whole team died but the reload watcher is not running; the run ends as usual.");
			return true;
		}
		return false;
	}
}
internal class ReloadWatcher : MonoBehaviour
{
	private const float CheckSeconds = 0.25f;

	private const float SettleSeconds = 1f;

	private const float GiveUpSeconds = 5f;

	private const float AirportSettleSeconds = 1f;

	private const float AirportGiveUpSeconds = 30f;

	private const float AliveSeconds = 2f;

	internal static bool EndRequested;

	private static float lastFrame = float.NegativeInfinity;

	private static string pendingRunId;

	private const float ClearRoomSeconds = 10f;

	private bool clearRoomAfterIsland;

	private float islandSince = float.NaN;

	private float nextCheck;

	private float deadSince = float.NaN;

	private float airportAskedAt = float.NaN;

	private bool loadingSeen;

	private float airportLoadedAt = float.NaN;

	private float airportReadySince = float.NaN;

	internal static bool IsRunning => Time.realtimeSinceStartup - lastFrame <= 2f;

	internal static bool ReloadPending => pendingRunId != null;

	private void OnEnable()
	{
		SceneManager.sceneLoaded += OnSceneLoaded;
	}

	private void OnDisable()
	{
		SceneManager.sceneLoaded -= OnSceneLoaded;
	}

	private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
	{
		ResetWipe();
		airportReadySince = float.NaN;
		if (pendingRunId != null && ((Scene)(ref scene)).name == "Airport")
		{
			airportLoadedAt = Time.realtimeSinceStartup;
			return;
		}
		if (pendingRunId != null)
		{
			Plugin.Log.LogWarning((object)("Not reloading the checkpoint: " + ((Scene)(ref scene)).name + " was loaded instead of the airport."));
		}
		pendingRunId = null;
		airportLoadedAt = float.NaN;
	}

	private void Update()
	{
		float num = (lastFrame = Time.realtimeSinceStartup);
		if (num < nextCheck)
		{
			return;
		}
		nextCheck = num + 0.25f;
		try
		{
			ClearRoomWhenBack(num);
			Check(num);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)ex.ToString());
		}
	}

	private void Check(float now)
	{
		if (!float.IsNaN(airportLoadedAt))
		{
			AtAirport(now);
		}
		else if (!float.IsNaN(airportAskedAt))
		{
			if (LoadingScreenHandler.loading)
			{
				loadingSeen = true;
			}
			else if (!loadingSeen && now - airportAskedAt >= 5f)
			{
				pendingRunId = null;
				Cover.ClearRoom();
				EndRun("the airport did not start loading " + 5f + " seconds after it was asked for");
			}
		}
		else if (!Wipe.TeamIsDead())
		{
			ResetWipe();
		}
		else
		{
			if (EndRequested)
			{
				return;
			}
			if (float.IsNaN(deadSince))
			{
				deadSince = now;
			}
			if (now - deadSince < 1f)
			{
				return;
			}
			string text = null;
			bool flag;
			string reason;
			try
			{
				if (LoadingScreenHandler.loading)
				{
					flag = false;
					reason = "a scene is already loading";
				}
				else
				{
					text = (((Object)(object)RunManager.Instance == (Object)null) ? null : RunManager.Instance.RunId.ToString());
					flag = Wipe.TryReadSave(text, out reason);
				}
			}
			catch (Exception ex)
			{
				flag = false;
				reason = ex.ToString();
			}
			if (!flag)
			{
				EndRun(reason);
				return;
			}
			GameOverHandler instance = Singleton<GameOverHandler>.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				EndRun("the game over handler was not found");
				return;
			}
			Plugin.Log.LogInfo((object)("The whole team died; going to the airport to load the checkpoint again (run " + text + ")."));
			pendingRunId = text;
			airportAskedAt = now;
			loadingSeen = false;
			Cover.MarkRoom(text);
			instance.LoadAirportMaster();
		}
	}

	private void AtAirport(float now)
	{
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		if (now - airportLoadedAt >= 30f)
		{
			StayAtAirport("the airport was not ready " + 30f + " seconds after it loaded");
			return;
		}
		if (!PhotonNetwork.IsMasterClient)
		{
			StayAtAirport("this player is no longer the host");
			return;
		}
		if (LoadingScreenHandler.loading || (Object)(object)Character.localCharacter == (Object)null)
		{
			airportReadySince = float.NaN;
			return;
		}
		if (float.IsNaN(airportReadySince))
		{
			airportReadySince = now;
		}
		if (now - airportReadySince < 1f)
		{
			return;
		}
		string text = pendingRunId;
		try
		{
			if (!Wipe.TryReadSave(text, out var reason))
			{
				StayAtAirport(reason);
				return;
			}
			ManualLogSource log = Plugin.Log;
			RunProgress savedRun = Quicksave.SavedRun;
			log.LogInfo((object)$"Loading the checkpoint again (run {text}, {((RunProgress)(ref savedRun)).LobbyType}).");
			pendingRunId = null;
			airportLoadedAt = float.NaN;
			Quicksave.ShouldUseSaveData = true;
			Quicksave.LoadSavedGameScene();
			clearRoomAfterIsland = true;
			islandSince = float.NaN;
		}
		catch (Exception ex)
		{
			StayAtAirport(ex.ToString());
		}
	}

	private void StayAtAirport(string reason)
	{
		Plugin.Log.LogInfo((object)("Not reloading the checkpoint, staying at the airport: " + reason + "."));
		Quicksave.ShouldUseSaveData = false;
		pendingRunId = null;
		airportLoadedAt = float.NaN;
		Cover.ClearRoom();
		Cover.HideNow("staying at the airport");
	}

	private void ClearRoomWhenBack(float now)
	{
		if (!clearRoomAfterIsland)
		{
			return;
		}
		if (!GameHandler.IsOnIsland || LoadingScreenHandler.loading || (Object)(object)Character.localCharacter == (Object)null)
		{
			islandSince = float.NaN;
			return;
		}
		if (float.IsNaN(islandSince))
		{
			islandSince = now;
		}
		if (!(now - islandSince < 10f))
		{
			clearRoomAfterIsland = false;
			Cover.ClearRoom();
		}
	}

	private void ResetWipe()
	{
		deadSince = float.NaN;
		airportAskedAt = float.NaN;
		loadingSeen = false;
		EndRequested = false;
	}

	private static void EndRun(string reason)
	{
		Plugin.Log.LogInfo((object)("The run ends as usual: " + reason + "."));
		EndRequested = true;
		if ((Object)(object)Character.localCharacter != (Object)null)
		{
			Character.localCharacter.CheckEndGame();
		}
	}
}