Decompiled source of Foglands Temporary Fix v1.0.3

Foglands.dll

Decompiled 2 weeks ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("Foglands")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Foglands Valheim Mod")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2")]
[assembly: AssemblyProduct("Foglands")]
[assembly: AssemblyTitle("Foglands")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Foglands
{
	public static class VeilController
	{
		public enum VeilState
		{
			Day,
			Dusk,
			Night,
			Dawn
		}

		private const float DawnPoint = 0.25f;

		private const float DuskPoint = 0.75f;

		private static float _lastLoggedFraction = -1f;

		private static string _lastWeather = "";

		public static VeilState CurrentState { get; private set; } = VeilState.Day;

		public static float CurrentIntensity { get; private set; }

		public static float WeatherMultiplier { get; private set; } = 1f;

		public static void UpdateVeilState()
		{
			if (!FoglandsPlugin._enableEitrVeil.Value.IsOn() || (Object)(object)EnvMan.instance == (Object)null)
			{
				CurrentIntensity = 0f;
				CurrentState = VeilState.Day;
				return;
			}
			float dayFraction = EnvMan.instance.GetDayFraction();
			float num = FoglandsPlugin._transitionDuration.Value / 24f;
			VeilState veilState;
			float num3;
			if (dayFraction >= 0.25f - num && dayFraction < 0.25f + num)
			{
				veilState = VeilState.Dawn;
				float num2 = (dayFraction - (0.25f - num)) / (num * 2f);
				num3 = 1f - Mathf.Clamp01(num2);
			}
			else if (dayFraction >= 0.75f - num && dayFraction < 0.75f + num)
			{
				veilState = VeilState.Dusk;
				num3 = Mathf.Clamp01((dayFraction - (0.75f - num)) / (num * 2f));
			}
			else if (EnvMan.IsDay())
			{
				veilState = VeilState.Day;
				num3 = 0f;
			}
			else
			{
				veilState = VeilState.Night;
				num3 = 1f;
			}
			if (Mathf.Abs(dayFraction - _lastLoggedFraction) >= 0.04f || _lastLoggedFraction < 0f)
			{
				FoglandsPlugin.FoglandsLogger.LogDebug((object)$"DayFraction: {dayFraction:F3} | Veil: {veilState} | Intensity: {num3:F2}");
				_lastLoggedFraction = dayFraction;
			}
			CurrentState = veilState;
			CurrentIntensity = num3;
			UpdateWeatherMultiplier();
		}

		private static void UpdateWeatherMultiplier()
		{
			if (!FoglandsPlugin._enableWeatherIntegration.Value.IsOn() || (Object)(object)EnvMan.instance == (Object)null)
			{
				WeatherMultiplier = 1f;
				return;
			}
			string text = EnvMan.instance.GetCurrentEnvironment()?.m_name ?? "";
			if (text != _lastWeather)
			{
				FoglandsPlugin.FoglandsLogger.LogDebug((object)("Weather changed: '" + _lastWeather + "' -> '" + text + "'"));
				_lastWeather = text;
				if (text.IndexOf("storm", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					WeatherMultiplier = FoglandsPlugin._stormFogMultiplier.Value;
				}
				else if (text.IndexOf("rain", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					WeatherMultiplier = FoglandsPlugin._rainFogMultiplier.Value;
				}
				else if (text.IndexOf("snow", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					WeatherMultiplier = FoglandsPlugin._rainFogMultiplier.Value * 0.8f;
				}
				else
				{
					WeatherMultiplier = 1f;
				}
			}
		}

		public static float GetEmissionMultiplier()
		{
			float num = 0.4f * FoglandsPlugin._nightFogMultiplier.Value;
			return Mathf.Lerp(0.4f, num, CurrentIntensity) * WeatherMultiplier;
		}

		public static float GetCurrentAlpha()
		{
			float value = FoglandsPlugin._dayFogAlpha.Value;
			float value2 = FoglandsPlugin._nightFogAlpha.Value;
			return Mathf.Min(Mathf.Lerp(value, value2, CurrentIntensity) * Mathf.Lerp(1f, WeatherMultiplier * 0.7f, 0.5f), 0.7f);
		}

		public static float GetSizeMultiplier()
		{
			return Mathf.Lerp(1f, 1.3f, CurrentIntensity) * Mathf.Lerp(1f, 1.1f, (WeatherMultiplier - 1f) / 0.5f);
		}
	}
	public class MistControllerBehaviour : MonoBehaviour
	{
		private readonly float _scanInterval = 2f;

		private float _timeSinceLastScan;

		private readonly float _veilUpdateInterval = 0.5f;

		private float _timeSinceVeilUpdate;

		private Biome _lastBiome;

		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)
			//IL_0017: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Invalid comparison between Unknown and I4
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			Biome currentBiome = localPlayer.GetCurrentBiome();
			if (currentBiome != _lastBiome)
			{
				if ((int)_lastBiome == 512)
				{
					MistObjectController.Reset();
					ParticleMistPatches.ResetModificationState();
				}
				_lastBiome = currentBiome;
			}
			if ((int)currentBiome == 512)
			{
				_timeSinceVeilUpdate += Time.deltaTime;
				if (_timeSinceVeilUpdate >= _veilUpdateInterval)
				{
					_timeSinceVeilUpdate = 0f;
					VeilController.UpdateVeilState();
				}
				_timeSinceLastScan += Time.deltaTime;
				if (_timeSinceLastScan >= _scanInterval)
				{
					_timeSinceLastScan = 0f;
					MistObjectController.ScanAndModifyMistObjects();
				}
			}
		}
	}
	public static class MistObjectController
	{
		private static bool _hasScannedForMist;

		private static GameObject _localMistCloud;

		private static GameObject _globalMist;

		private static ParticleSystem _globalMistPS;

		private static Color _originalStartColor;

		private static float _originalStartSize;

		private static float _originalEmissionRate;

		private static bool _originalValuesStored;

		private static int _failedSearchAttempts;

		private const int MaxBackoffAttempts = 5;

		public static bool ScanAndModifyMistObjects()
		{
			if (_hasScannedForMist && (Object)(object)_globalMist != (Object)null)
			{
				return false;
			}
			if (_failedSearchAttempts > 0)
			{
				int num = Mathf.Min(_failedSearchAttempts, 5);
				if (_failedSearchAttempts % (num + 1) != 0)
				{
					_failedSearchAttempts++;
					return false;
				}
			}
			if (FindMistObjects())
			{
				_failedSearchAttempts = 0;
				if ((Object)(object)_globalMist != (Object)null && (Object)(object)_globalMistPS != (Object)null)
				{
					ModifyGlobalMist();
				}
			}
			else
			{
				_failedSearchAttempts++;
			}
			return true;
		}

		private static bool FindMistObjects()
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Invalid comparison between Unknown and I4
			if ((Object)(object)_localMistCloud == (Object)null)
			{
				GameObject val = GameObject.Find("_GameMain");
				if ((Object)(object)val != (Object)null)
				{
					Transform val2 = val.transform.Find("_Environment/FollowPlayer/Mist/cloud (1)");
					if ((Object)(object)val2 != (Object)null)
					{
						_localMistCloud = ((Component)val2).gameObject;
					}
				}
			}
			if ((Object)(object)_globalMist != (Object)null)
			{
				return true;
			}
			ParticleMist[] array = Object.FindObjectsByType<ParticleMist>((FindObjectsSortMode)0);
			foreach (ParticleMist val3 in array)
			{
				if ((int)val3.m_biome == 512)
				{
					_globalMist = ((Component)val3).gameObject;
					_globalMistPS = ((Component)val3).GetComponent<ParticleSystem>() ?? ((Component)val3).GetComponentInChildren<ParticleSystem>();
					_hasScannedForMist = true;
					return true;
				}
			}
			ParticleSystem[] array2 = Object.FindObjectsByType<ParticleSystem>((FindObjectsSortMode)0);
			foreach (ParticleSystem val4 in array2)
			{
				if (((Object)((Component)val4).gameObject).name.IndexOf("Globalmist", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					_globalMist = ((Component)val4).gameObject;
					_globalMistPS = val4;
					_hasScannedForMist = true;
					return true;
				}
			}
			return (Object)(object)_globalMist != (Object)null;
		}

		private static void ModifyGlobalMist()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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)
			if (!((Object)(object)_globalMistPS == (Object)null))
			{
				if (!_originalValuesStored)
				{
					MainModule main = _globalMistPS.main;
					MinMaxGradient startColor = ((MainModule)(ref main)).startColor;
					_originalStartColor = ((MinMaxGradient)(ref startColor)).color;
					MinMaxCurve val = ((MainModule)(ref main)).startSize;
					_originalStartSize = ((MinMaxCurve)(ref val)).constant;
					EmissionModule emission = _globalMistPS.emission;
					val = ((EmissionModule)(ref emission)).rateOverTime;
					_originalEmissionRate = ((MinMaxCurve)(ref val)).constant;
					_originalValuesStored = true;
				}
				if (FoglandsPlugin.IsParticleMistDisabled)
				{
					_globalMistPS.Clear();
				}
			}
		}

		public static void Reset()
		{
			_hasScannedForMist = false;
			_localMistCloud = null;
			_globalMist = null;
			_globalMistPS = null;
			_failedSearchAttempts = 0;
		}
	}
	[HarmonyPatch]
	public static class ParticleMistPatches
	{
		private static bool _hasInitializedParticleSystem;

		private static int _originalLocalEmission;

		private static int _originalLocalEmissionPerUnit;

		private static float _originalEmissionMax;

		private static float _originalEmissionPerUnit;

		private static float _originalDistantEmissionMax;

		private static float _originalMinDistance;

		private static bool _originalValuesStored;

		[HarmonyPatch(typeof(ParticleMist), "Update")]
		[HarmonyPrefix]
		private static bool ParticleMist_Update_Prefix(ParticleMist __instance)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			if ((int)__instance.m_biome != 512)
			{
				return true;
			}
			ParticleSystem val = ((Component)__instance).GetComponent<ParticleSystem>() ?? ((Component)__instance).GetComponentInChildren<ParticleSystem>();
			if ((Object)(object)val == (Object)null)
			{
				return true;
			}
			if (FoglandsPlugin.IsParticleMistDisabled)
			{
				val.Clear();
				return false;
			}
			if (!_originalValuesStored)
			{
				_originalLocalEmission = __instance.m_localEmission;
				_originalLocalEmissionPerUnit = __instance.m_localEmissionPerUnit;
				_originalEmissionMax = __instance.m_emissionMax;
				_originalEmissionPerUnit = __instance.m_emissionPerUnit;
				_originalDistantEmissionMax = __instance.m_distantEmissionMax;
				_originalMinDistance = __instance.m_minDistance;
				_originalValuesStored = true;
			}
			if (!_hasInitializedParticleSystem)
			{
				MainModule main = val.main;
				((MainModule)(ref main)).maxParticles = 2000;
				((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(4f);
				((MainModule)(ref main)).simulationSpeed = 0.75f;
				_hasInitializedParticleSystem = true;
			}
			float emissionMultiplier = VeilController.GetEmissionMultiplier();
			__instance.m_localEmission = (int)((float)_originalLocalEmission * emissionMultiplier);
			__instance.m_localEmissionPerUnit = (int)((float)_originalLocalEmissionPerUnit * emissionMultiplier);
			__instance.m_emissionMax = _originalEmissionMax * emissionMultiplier;
			__instance.m_emissionPerUnit = _originalEmissionPerUnit * emissionMultiplier;
			__instance.m_distantEmissionMax = _originalDistantEmissionMax * emissionMultiplier;
			float num = Mathf.Lerp(1.5f, 1f, VeilController.CurrentIntensity);
			__instance.m_minDistance = _originalMinDistance * num;
			MainModule main2 = val.main;
			float currentAlpha = VeilController.GetCurrentAlpha();
			Color val2 = default(Color);
			((Color)(ref val2))..ctor(FoglandsPlugin._fogColorR.Value, FoglandsPlugin._fogColorG.Value, FoglandsPlugin._fogColorB.Value, currentAlpha);
			((MainModule)(ref main2)).startColor = new MinMaxGradient(val2);
			float sizeMultiplier = VeilController.GetSizeMultiplier();
			((MainModule)(ref main2)).startSize = MinMaxCurve.op_Implicit(5f * sizeMultiplier);
			return true;
		}

		[HarmonyPatch(typeof(ParticleMist), "IsInMist")]
		[HarmonyPrefix]
		private static bool IsInMist_Prefix(ref bool __result, Vector3 p0)
		{
			if (!FoglandsPlugin.IsParticleMistDisabled && !(VeilController.CurrentIntensity < 0.3f))
			{
				return true;
			}
			__result = false;
			return false;
		}

		[HarmonyPatch(typeof(ParticleMist), "IsMistBlocked")]
		[HarmonyPrefix]
		private static bool IsMistBlocked_Prefix(ref bool __result)
		{
			if (!FoglandsPlugin.IsParticleMistDisabled && !(VeilController.CurrentIntensity < 0.3f))
			{
				return true;
			}
			__result = false;
			return false;
		}

		public static void ResetModificationState()
		{
			_hasInitializedParticleSystem = false;
		}
	}
	[BepInPlugin("Azumatt.Foglands", "Foglands", "1.0.2")]
	public class FoglandsPlugin : BaseUnityPlugin
	{
		public enum Toggle
		{
			On = 1,
			Off = 0
		}

		private readonly Harmony _harmony = new Harmony("Azumatt.Foglands");

		public static readonly ManualLogSource FoglandsLogger = Logger.CreateLogSource("Foglands");

		private static string ConfigFileName = "Azumatt.Foglands.cfg";

		private static string ConfigFileFullPath = Path.Combine(Paths.ConfigPath, ConfigFileName);

		internal static string ConnectionError = "";

		private FileSystemWatcher _watcher;

		private readonly object _reloadLock = new object();

		private DateTime _lastConfigReloadTime;

		internal static ConfigEntry<Toggle> _disableParticleMist;

		internal static ConfigEntry<float> _fogColorR;

		internal static ConfigEntry<float> _fogColorG;

		internal static ConfigEntry<float> _fogColorB;

		internal static ConfigEntry<Toggle> _enableEitrVeil;

		internal static ConfigEntry<float> _transitionDuration;

		internal static ConfigEntry<float> _nightFogMultiplier;

		internal static ConfigEntry<float> _nightFogAlpha;

		internal static ConfigEntry<float> _dayFogAlpha;

		internal static ConfigEntry<Toggle> _enableWeatherIntegration;

		internal static ConfigEntry<float> _stormFogMultiplier;

		internal static ConfigEntry<float> _rainFogMultiplier;

		public static bool IsParticleMistDisabled
		{
			get
			{
				if (_disableParticleMist.Value.IsOn())
				{
					return !Chainloader.PluginInfos.ContainsKey("Azumatt.MistBeGone");
				}
				return false;
			}
		}

		public void Awake()
		{
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			_disableParticleMist = config("2 - Fog Settings", "Disable Particle Mist", Toggle.Off, "Removes ground fog particles.");
			_fogColorR = config("2 - Fog Settings", "Fog Color Red", 0.45f, "Red component.");
			_fogColorG = config("2 - Fog Settings", "Fog Color Green", 0.45f, "Green component.");
			_fogColorB = config("2 - Fog Settings", "Fog Color Blue", 0.5f, "Blue component.");
			_enableEitrVeil = config("3 - Fog System", "Enable Time-Based Veil", Toggle.On, "Time based system.");
			_transitionDuration = config("3 - Fog System", "Transition Duration Hours", 1.5f, "Transition timing.");
			_nightFogMultiplier = config("3 - Fog System", "Night Fog Multiplier", 2.5f, "Thickness multiplier.");
			_nightFogAlpha = config("3 - Fog System", "Night Fog Alpha", 0.5f, "Opacity at night.");
			_dayFogAlpha = config("3 - Fog System", "Day Fog Alpha", 0.25f, "Opacity during day.");
			_enableWeatherIntegration = config("4 - Weather", "Enable Weather Integration", Toggle.On, "Weather thickness trigger.");
			_stormFogMultiplier = config("4 - Weather", "Storm Fog Multiplier", 1.5f, "Storm thickness.");
			_rainFogMultiplier = config("4 - Weather", "Rain Fog Multiplier", 1.25f, "Rain thickness.");
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			SetupWatcher();
			((Component)this).gameObject.AddComponent<MistControllerBehaviour>();
			((BaseUnityPlugin)this).Config.Save();
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
			_watcher?.Dispose();
		}

		private void SetupWatcher()
		{
			_watcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			_watcher.Changed += ReadConfigValues;
			_watcher.Created += ReadConfigValues;
			_watcher.EnableRaisingEvents = true;
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			if ((DateTime.Now - _lastConfigReloadTime).TotalSeconds < 5.0)
			{
				return;
			}
			lock (_reloadLock)
			{
				if (!File.Exists(ConfigFileFullPath))
				{
					return;
				}
				try
				{
					((BaseUnityPlugin)this).Config.Reload();
					FoglandsLogger.LogInfo((object)"Configuration reloaded successfully.");
				}
				catch (Exception ex)
				{
					FoglandsLogger.LogError((object)("Error reloading configuration: " + ex.Message));
				}
			}
			_lastConfigReloadTime = DateTime.Now;
		}

		private ConfigEntry<T> config<T>(string group, string name, T value, string description)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			ConfigDescription val = new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>());
			return ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val);
		}
	}
	public static class ToggleExtensions
	{
		public static bool IsOn(this FoglandsPlugin.Toggle value)
		{
			return value == FoglandsPlugin.Toggle.On;
		}

		public static bool IsOff(this FoglandsPlugin.Toggle value)
		{
			return value == FoglandsPlugin.Toggle.Off;
		}
	}
}