Decompiled source of LocalSaveControl v1.1.1

plugins/LocalSaveControl.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
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: AssemblyVersion("0.0.0.0")]
namespace LocalSaveControl;

[BepInPlugin("timur4el.valheim.localsavecontrol", "timur4el Local Save Control", "1.1.1")]
public sealed class LocalSaveControlPlugin : BaseUnityPlugin
{
	public const string PluginGuid = "timur4el.valheim.localsavecontrol";

	public const string PluginName = "timur4el Local Save Control";

	public const string PluginVersion = "1.1.1";

	private static ConfigEntry<int> _saveIntervalMinutes;

	private static ConfigEntry<bool> _pauseDuringBossCombat;

	private static ConfigEntry<bool> _pauseWhileControllingShip;

	private static ConfigEntry<bool> _pauseWhileUsingCart;

	private static ConfigEntry<bool> _saveOnLocationEntry;

	private static ConfigEntry<bool> _saveBeforeBossFight;

	private static ConfigEntry<bool> _saveOnDisconnect;

	private static ConfigEntry<bool> _saveOnGameExit;

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

	private static readonly Dictionary<int, float> BossEncounterLastActive = new Dictionary<int, float>();

	private static LocalSaveControlPlugin _instance;

	private static bool _isQuitting;

	private static bool _saveIsBlocked;

	private const float BossEncounterResetSeconds = 15f;

	private float _nextPolicyRefresh;

	internal static float SaveIntervalSeconds => (float)_saveIntervalMinutes.Value * 60f;

	internal static bool SaveOnDisconnect => _saveOnDisconnect.Value;

	internal static bool SaveOnGameExit => _saveOnGameExit.Value;

	private void Awake()
	{
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Expected O, but got Unknown
		//IL_0121: Unknown result type (might be due to invalid IL or missing references)
		_instance = this;
		_saveIntervalMinutes = ((BaseUnityPlugin)this).Config.Bind<int>("General", "SaveIntervalMinutes", 10, new ConfigDescription("Интервал автосохранения мира в минутах.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1440), Array.Empty<object>()));
		_pauseDuringBossCombat = ((BaseUnityPlugin)this).Config.Bind<bool>("Conditions", "PauseDuringBossCombat", true, "Откладывать автосохранение, пока босс атакует игрока.");
		_pauseWhileControllingShip = ((BaseUnityPlugin)this).Config.Bind<bool>("Conditions", "PauseWhileControllingShip", true, "Откладывать автосохранение, пока игрок управляет кораблём.");
		_pauseWhileUsingCart = ((BaseUnityPlugin)this).Config.Bind<bool>("Conditions", "PauseWhileUsingCart", true, "Откладывать автосохранение, пока игрок запряжён в повозку.");
		_saveOnLocationEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("Events", "SaveOnLocationEntry", true, "Сохранять мир при входе игрока в локацию, например пещеру или данж.");
		_saveBeforeBossFight = ((BaseUnityPlugin)this).Config.Bind<bool>("Events", "SaveBeforeBossFight", true, "Сохранять мир при появлении босса рядом с игроками или начале боя.");
		_saveOnDisconnect = ((BaseUnityPlugin)this).Config.Bind<bool>("Shutdown", "SaveOnWorldDisconnect", true, "Принудительно сохранять мир при выходе из мира в меню.");
		_saveOnGameExit = ((BaseUnityPlugin)this).Config.Bind<bool>("Shutdown", "SaveOnGameExit", true, "Принудительно сохранять мир при закрытии игры.");
		new Harmony("timur4el.valheim.localsavecontrol").PatchAll(typeof(LocalSaveControlPlugin).Assembly);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"timur4el Local Save Control загружен.");
	}

	private void Update()
	{
		if (!(Time.unscaledTime < _nextPolicyRefresh))
		{
			_nextPolicyRefresh = Time.unscaledTime + 0.5f;
			TrackLocationEntries();
			CleanupBossEncounters();
			_saveIsBlocked = IsSaveBlocked();
		}
	}

	internal static void ApplySaveInterval()
	{
		Game.m_saveInterval = (_saveIsBlocked ? float.MaxValue : SaveIntervalSeconds);
	}

	internal static void MarkGameAsQuitting()
	{
		_isQuitting = true;
	}

	internal static void SaveBeforeBossFight(Character boss)
	{
		if (_saveBeforeBossFight.Value && !((Object)(object)boss == (Object)null) && boss.IsBoss())
		{
			List<Player> allPlayers = Player.GetAllPlayers();
			if (allPlayers != null && allPlayers.Count != 0)
			{
				SaveWorld("boss encounter");
				BossEncounterLastActive[((Object)boss).GetInstanceID()] = Time.unscaledTime;
			}
		}
	}

	internal static void CheckBossCombat(BaseAI ai)
	{
		if (!_saveBeforeBossFight.Value || (Object)(object)ai == (Object)null)
		{
			return;
		}
		Character componentInParent = ((Component)ai).GetComponentInParent<Character>();
		if ((Object)(object)componentInParent == (Object)null || !componentInParent.IsBoss())
		{
			return;
		}
		int instanceID = ((Object)componentInParent).GetInstanceID();
		Character targetCreature = ai.GetTargetCreature();
		if ((Object)(object)targetCreature != (Object)null && targetCreature.IsPlayer())
		{
			if (!BossEncounterLastActive.TryGetValue(instanceID, out var value) || Time.unscaledTime - value > 15f)
			{
				SaveWorld("boss combat started");
			}
			BossEncounterLastActive[instanceID] = Time.unscaledTime;
		}
	}

	internal static void EnsureSaveOnShutdown(ref bool save)
	{
		if (_isQuitting ? SaveOnGameExit : SaveOnDisconnect)
		{
			save = true;
		}
	}

	private void TrackLocationEntries()
	{
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		List<Player> allPlayers = Player.GetAllPlayers();
		if (allPlayers == null || allPlayers.Count == 0)
		{
			PlayerLocations.Clear();
			return;
		}
		HashSet<int> hashSet = new HashSet<int>();
		foreach (Player item in allPlayers)
		{
			if ((Object)(object)item == (Object)null)
			{
				continue;
			}
			int instanceID = ((Object)item).GetInstanceID();
			hashSet.Add(instanceID);
			Location location = Location.GetLocation(((Component)item).transform.position, true);
			int num = ((!((Object)(object)location == (Object)null)) ? ((Object)location).GetInstanceID() : 0);
			if (!PlayerLocations.TryGetValue(instanceID, out var value))
			{
				PlayerLocations.Add(instanceID, num);
				continue;
			}
			if (num != 0 && num != value)
			{
				SaveWorld("location entered");
			}
			PlayerLocations[instanceID] = num;
		}
		List<int> list = new List<int>();
		foreach (int key in PlayerLocations.Keys)
		{
			if (!hashSet.Contains(key))
			{
				list.Add(key);
			}
		}
		foreach (int item2 in list)
		{
			PlayerLocations.Remove(item2);
		}
	}

	private static void CleanupBossEncounters()
	{
		List<int> list = new List<int>();
		foreach (KeyValuePair<int, float> item in BossEncounterLastActive)
		{
			if (Time.unscaledTime - item.Value > 15f)
			{
				list.Add(item.Key);
			}
		}
		foreach (int item2 in list)
		{
			BossEncounterLastActive.Remove(item2);
		}
	}

	private static void SaveWorld(string reason)
	{
		if (!((Object)(object)Game.instance == (Object)null) && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
		{
			Game.instance.SavePlayerProfile(true, false);
			ZNet.instance.Save(true, false, false);
			((BaseUnityPlugin)_instance).Logger.LogInfo((object)("World saved: " + reason + "."));
		}
	}

	private static bool IsSaveBlocked()
	{
		List<Player> allPlayers = Player.GetAllPlayers();
		if (allPlayers == null || allPlayers.Count == 0)
		{
			return false;
		}
		if (_pauseWhileControllingShip.Value)
		{
			foreach (Player item in allPlayers)
			{
				if ((Object)(object)item != (Object)null && (Object)(object)item.GetControlledShip() != (Object)null)
				{
					return true;
				}
			}
		}
		if (_pauseWhileUsingCart.Value)
		{
			Vagon[] array = Object.FindObjectsByType<Vagon>((FindObjectsSortMode)0);
			foreach (Vagon val in array)
			{
				foreach (Player item2 in allPlayers)
				{
					if ((Object)(object)val != (Object)null && (Object)(object)item2 != (Object)null && val.IsAttached((Character)(object)item2))
					{
						return true;
					}
				}
			}
		}
		if (_pauseDuringBossCombat.Value)
		{
			List<BaseAI> allInstances = BaseAI.GetAllInstances();
			if (allInstances != null)
			{
				foreach (BaseAI item3 in allInstances)
				{
					if (!((Object)(object)item3 == (Object)null))
					{
						Character targetCreature = item3.GetTargetCreature();
						Character componentInParent = ((Component)item3).GetComponentInParent<Character>();
						if ((Object)(object)targetCreature != (Object)null && targetCreature.IsPlayer() && (Object)(object)componentInParent != (Object)null && componentInParent.IsBoss())
						{
							return true;
						}
					}
				}
			}
		}
		return false;
	}
}
[HarmonyPatch(typeof(Game), "Update")]
internal static class GameUpdatePatch
{
	[HarmonyPrefix]
	private static void Prefix()
	{
		LocalSaveControlPlugin.ApplySaveInterval();
	}
}
[HarmonyPatch(typeof(Game), "OnApplicationQuit")]
internal static class GameQuitPatch
{
	[HarmonyPrefix]
	private static void Prefix()
	{
		LocalSaveControlPlugin.MarkGameAsQuitting();
	}
}
[HarmonyPatch(typeof(Game), "Shutdown")]
internal static class GameShutdownPatch
{
	[HarmonyPrefix]
	private static void Prefix(ref bool __0)
	{
		LocalSaveControlPlugin.EnsureSaveOnShutdown(ref __0);
	}
}
[HarmonyPatch(typeof(ZNet), "Shutdown")]
internal static class NetworkShutdownPatch
{
	[HarmonyPrefix]
	private static void Prefix(ref bool __0)
	{
		LocalSaveControlPlugin.EnsureSaveOnShutdown(ref __0);
	}
}
[HarmonyPatch(typeof(Character), "Awake")]
internal static class BossSpawnPatch
{
	[HarmonyPostfix]
	private static void Postfix(Character __instance)
	{
		LocalSaveControlPlugin.SaveBeforeBossFight(__instance);
	}
}
[HarmonyPatch(typeof(BaseAI), "UpdateAI")]
internal static class BossCombatStartedPatch
{
	[HarmonyPostfix]
	private static void Postfix(BaseAI __instance)
	{
		LocalSaveControlPlugin.CheckBossCombat(__instance);
	}
}