Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of SaveGuardianPatched v1.0.0
SaveGuardianPatched.dll
Decompiled an hour agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Photon.Pun; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("SaveGuardianPatched")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("SaveGuardianPatched")] [assembly: AssemblyTitle("SaveGuardianPatched")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace SaveGuardianPatched { [HarmonyPatch(typeof(DataDirector), "SaveDeleteCheck")] internal static class BlockSaveDeleteCheckPatch { private static bool Prefix(bool _leaveGame) { if (!SaveGuardianPatched.BlockSaveDeletion.Value) { return true; } SaveGuardianPatched.Logger.LogDebug((object)$"Skipped automatic save deletion check (leaveGame={_leaveGame})."); return false; } } [HarmonyPatch(typeof(SemiFunc), "OnSceneSwitch")] internal static class CaptureLevelStartPatch { private static void Postfix(bool _gameOver, bool _leaveGame) { if (_leaveGame) { LevelSnapshot.Clear(); } else if (!_gameOver && SaveGuardianPatched.IsRestartableScene() && !SaveGuardianPatched.IsRestarting) { LevelSnapshot.Capture(); } } } [HarmonyPatch(typeof(RunManager), "ResetProgress")] internal static class KeepProgressOnGameOverPatch { private static bool Prefix() { if (!SaveGuardianPatched.BlockSaveDeletion.Value || !SemiFunc.RunIsArena()) { return true; } SaveGuardianPatched.Logger.LogInfo((object)"Game over: run progress kept."); return false; } } internal static class LeaveGameRestore { private static float _lastSave = -100f; internal static void Apply(string where) { if (!SaveGuardianPatched.IsRestartableScene()) { return; } SaveGuardianPatched.Logger.LogInfo((object)("Leaving the game (" + where + "): restoring level-start stats.")); LevelSnapshot.Restore(); if (Time.realtimeSinceStartup - _lastSave < 2f) { return; } _lastSave = Time.realtimeSinceStartup; try { StatsManager.instance.SaveFileSave(); SaveGuardianPatched.Logger.LogInfo((object)"Rewrote the save with level-start stats."); } catch (Exception ex) { SaveGuardianPatched.Logger.LogWarning((object)("Could not rewrite the save: " + ex.Message)); } } } [HarmonyPatch(typeof(RunManager), "LeavePhotonRoom")] internal static class LeavePhotonRoomPatch { private static void Prefix() { LeaveGameRestore.Apply("LeavePhotonRoom"); } } [HarmonyPatch(typeof(RunManager), "LeaveToMainMenu")] internal static class LeaveToMainMenuPatch { private static void Prefix() { LeaveGameRestore.Apply("LeaveToMainMenu"); } } [HarmonyPatch(typeof(SemiFunc), "OnSceneSwitch")] internal static class LeaveSceneSwitchPatch { private static void Prefix(bool _leaveGame) { if (_leaveGame) { LeaveGameRestore.Apply("OnSceneSwitch"); } } } internal static class LevelSnapshot { private static Dictionary<string, Dictionary<string, int>> _stats; private static string Describe(string label, StatsManager stats) { return "[" + label + "] crystalsPurchased=" + stats.itemsPurchased.GetValueOrDefault("Item Power Crystal") + " crystalCount=" + stats.runStats.GetValueOrDefault("chargingStationCharge") + " truckEnergy=" + stats.runStats.GetValueOrDefault("chargingStationChargeTotal") + " batteries=" + string.Join(",", stats.itemStatBattery.Select((KeyValuePair<string, int> kv) => kv.Key + ":" + kv.Value)); } internal static void Capture() { StatsManager instance = StatsManager.instance; if (Object.op_Implicit((Object)(object)instance)) { _stats = instance.dictionaryOfDictionaries.ToDictionary((KeyValuePair<string, Dictionary<string, int>> kv) => kv.Key, (KeyValuePair<string, Dictionary<string, int>> kv) => new Dictionary<string, int>(kv.Value)); SaveGuardianPatched.Logger.LogInfo((object)Describe("Capture", instance)); } } internal static void Clear() { _stats = null; } internal static void RestoreHealth() { StatsManager instance = StatsManager.instance; if (!Object.op_Implicit((Object)(object)instance) || _stats == null || !_stats.TryGetValue("playerHealth", out var value)) { return; } instance.playerHealth.Clear(); foreach (KeyValuePair<string, int> item in value) { instance.playerHealth[item.Key] = item.Value; } } internal static void RestoreItems() { StatsManager instance = StatsManager.instance; if (!Object.op_Implicit((Object)(object)instance) || _stats == null) { return; } string[] array = new string[5] { "itemStatBattery", "item", "itemsPurchased", "itemsPurchasedTotal", "runStats" }; foreach (string key in array) { if (!_stats.TryGetValue(key, out var value) || !instance.dictionaryOfDictionaries.TryGetValue(key, out var value2)) { continue; } value2.Clear(); foreach (KeyValuePair<string, int> item in value) { value2[item.Key] = item.Value; } } } internal static int GetStartHealth(string steamID) { if (_stats != null && _stats.TryGetValue("playerHealth", out var value) && value.TryGetValue(steamID, out var value2)) { return value2; } return 100; } internal static bool TryGetRunStat(string key, out int value) { value = 0; if (_stats != null && _stats.TryGetValue("runStats", out var value2)) { return value2.TryGetValue(key, out value); } return false; } internal static void RestoreChargingStation() { ChargingStation instance = ChargingStation.instance; if (Object.op_Implicit((Object)(object)instance) && TryGetRunStat("chargingStationChargeTotal", out var value) && instance.chargeTotal != value) { SaveGuardianPatched.Logger.LogInfo((object)("Charging station energy: " + instance.chargeTotal + " -> " + value)); instance.chargeTotal = value; } } internal static void Restore() { StatsManager instance = StatsManager.instance; if (!Object.op_Implicit((Object)(object)instance) || _stats == null) { SaveGuardianPatched.Logger.LogWarning((object)"No level-start snapshot: restarting with the current stats."); return; } SaveGuardianPatched.Logger.LogInfo((object)Describe("Before restore", instance)); foreach (KeyValuePair<string, Dictionary<string, int>> stat in _stats) { if (!instance.dictionaryOfDictionaries.TryGetValue(stat.Key, out var value)) { continue; } value.Clear(); foreach (KeyValuePair<string, int> item in stat.Value) { value[item.Key] = item.Value; } } RestoreChargingStation(); SaveGuardianPatched.Logger.LogInfo((object)Describe("After restore", instance)); } } [HarmonyPatch(typeof(RunManager), "ChangeLevel")] internal static class RestartLevelOnDeathPatch { private static bool Prefix(RunManager __instance, bool _levelFailed) { if (!_levelFailed || !SaveGuardianPatched.RestartLevelOnDeath.Value || __instance.restarting || !SemiFunc.IsMasterClientOrSingleplayer() || !SaveGuardianPatched.IsRestartableScene()) { return true; } SaveGuardianPatched.RestartCurrentLevel(); return false; } } [BepInPlugin("somebodyst.SaveGuardianPatched", "SaveGuardianPatched", "1.0.0")] public class SaveGuardianPatched : BaseUnityPlugin { internal static ConfigEntry<bool> BlockSaveDeletion = null; internal static ConfigEntry<bool> RestartLevelOnDeath = null; internal static ConfigEntry<KeyboardShortcut> RestartLevelKey = null; internal static bool IsRestarting; private static bool _pendingHealthRestore; private static readonly HashSet<PlayerHealth> _healthRestored = new HashSet<PlayerHealth>(); private static float _healthDeadline; private const float HealthTimeoutSeconds = 20f; internal static SaveGuardianPatched Instance { get; private set; } = null; internal static ManualLogSource Logger => Instance._logger; private ManualLogSource _logger => ((BaseUnityPlugin)this).Logger; internal Harmony Harmony { get; set; } private void Awake() { //IL_007e: Unknown result type (might be due to invalid IL or missing references) Instance = this; ((Component)this).gameObject.transform.parent = null; ((Object)((Component)this).gameObject).hideFlags = (HideFlags)61; BlockSaveDeletion = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "BlockSaveDeletion", true, "Empêche la suppression automatique de la sauvegarde (mort, game over, quitter avant la fin du premier niveau) et conserve la progression après un game over. La suppression manuelle depuis le menu reste possible."); RestartLevelOnDeath = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "RestartLevelOnDeath", true, "Quand toute l'équipe est morte (solo ou multijoueur), le niveau ou la boutique est relancé depuis son début sur une nouvelle map : chaque joueur retrouve ses PV d'entrée de niveau, et les objets (batteries comprises) reviennent à leur état d'entrée de niveau."); RestartLevelKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "RestartLevelKey", new KeyboardShortcut((KeyCode)290, Array.Empty<KeyCode>()), "Relance manuellement le niveau ou la boutique depuis son début sur une nouvelle map, comme après une mort (hôte uniquement)."); Patch(); Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} has loaded!"); } internal void Patch() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown if (Harmony == null) { Harmony = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID); } Harmony.PatchAll(); } internal void Unpatch() { Harmony harmony = Harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private void Update() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (_pendingHealthRestore) { TickHealthRestore(); } KeyboardShortcut value = RestartLevelKey.Value; if (((KeyboardShortcut)(ref value)).IsDown() && CanRestartManually()) { Logger.LogInfo((object)"Manual restart requested."); RestartCurrentLevel(); } } private static bool CanRestartManually() { RunManager instance = RunManager.instance; if (Object.op_Implicit((Object)(object)instance) && !instance.restarting && SemiFunc.IsMasterClientOrSingleplayer() && SemiFunc.NoTextInputsActive() && IsRestartableScene() && Object.op_Implicit((Object)(object)LevelGenerator.Instance)) { return LevelGenerator.Instance.Generated; } return false; } internal static bool IsRestartableScene() { if (!SemiFunc.RunIsLevel()) { return SemiFunc.RunIsShop(); } return true; } internal static void RestartCurrentLevel() { Logger.LogInfo((object)"Restarting the current level from its start."); LevelSnapshot.Restore(); _pendingHealthRestore = true; IsRestarting = true; RunManager instance = RunManager.instance; try { if (SemiFunc.RunIsShop()) { instance.ChangeLevel(false, false, (ChangeLevelType)5); return; } Level previousRunLevel = instance.previousRunLevel; instance.previousRunLevel = instance.levelCurrent; try { instance.ChangeLevel(false, false, (ChangeLevelType)1); } finally { instance.previousRunLevel = previousRunLevel; } } finally { IsRestarting = false; LevelSnapshot.Restore(); } } private static void TickHealthRestore() { RunManager instance = RunManager.instance; if (!Object.op_Implicit((Object)(object)instance) || instance.restarting || !Object.op_Implicit((Object)(object)LevelGenerator.Instance) || !LevelGenerator.Instance.Generated) { LevelSnapshot.RestoreHealth(); LevelSnapshot.RestoreItems(); _healthDeadline = Time.time + 20f; return; } if (!SemiFunc.IsMultiplayer()) { _pendingHealthRestore = false; return; } bool flag = true; foreach (PlayerAvatar item in Object.op_Implicit((Object)(object)GameDirector.instance) ? GameDirector.instance.PlayerList : new List<PlayerAvatar>()) { PlayerHealth val = (Object.op_Implicit((Object)(object)item) ? item.playerHealth : null); if (!Object.op_Implicit((Object)(object)val) || _healthRestored.Contains(val)) { continue; } if (!val.healthSet) { flag = false; continue; } int num = Mathf.Clamp(LevelSnapshot.GetStartHealth(SemiFunc.PlayerGetSteamID(item)), 1, val.maxHealth); if (val.health != num) { val.photonView.RPC("UpdateHealthRPC", (RpcTarget)0, new object[4] { num, val.maxHealth, false, false }); } _healthRestored.Add(val); } if (flag || Time.time > _healthDeadline) { _pendingHealthRestore = false; _healthRestored.Clear(); } } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }