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 SakeysWeatherControlt v0.0.1
BepInEx/plugins/Sakey's Weather Control/Sakey's Weather Control.dll
Decompiled 14 hours agousing 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 BepInEx.Logging; using HarmonyLib; 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("Sakey's Weather Control")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Sakey's Weather Control")] [assembly: AssemblyTitle("Sakey's Weather Control")] [assembly: AssemblyVersion("1.0.0.0")] namespace SakeysWeatherControl; [BepInPlugin("com.sakey.weathercontrol", "Sakey's Weather Control", "0.0.1")] public class Plugin : BaseUnityPlugin { private sealed class ConfigurationManagerAttributes { public string Category; public string DispName; } public const string PluginGuid = "com.sakey.weathercontrol"; public const string PluginName = "Sakey's Weather Control"; public const string PluginVersion = "0.0.1"; internal static Plugin Instance; internal static ManualLogSource LogSource; internal static ConfigEntry<bool> ForceClearWeather; internal static ConfigEntry<bool> RemoveMistlandsMist; internal static ConfigEntry<bool> RemoveDungeonHaze; internal static ConfigEntry<bool> RemoveDungeonFog; internal static ConfigEntry<bool> ReduceDungeonEnvironmentFog; internal static ConfigEntry<bool> ForceClearDungeonEnvironment; internal static ConfigEntry<bool> ForceClearEventEnvironment; private Harmony _harmony; private void Awake() { //IL_04a1: Unknown result type (might be due to invalid IL or missing references) //IL_04ab: Expected O, but got Unknown Instance = this; LogSource = ((BaseUnityPlugin)this).Logger; ForceClearWeather = BindLocalized("天候", "全バイオームを晴天に固定", "有効にすると、屋外の全バイオームの天候を晴天(Clear)に固定します。ボス戦・襲撃の晴天設定も有効な間は、イベント中だけバイオーム側の強制を一時解除し、イベント環境と元のバイオーム環境を分けて適用します。", "Weather", "Force clear weather in all biomes", "Forces Clear outdoors. During events, biome forcing is suspended so event settings take priority.", "Wetter", "Klares Wetter in allen Biomen", "Erzwingt Clear im Freien. Während Ereignissen hat die Ereigniseinstellung Vorrang.", "Météo", "Imposer un temps clair dans tous les biomes", "Impose le temps clair en extérieur. Pendant les événements, le réglage des événements est prioritaire.", "날씨", "모든 생물군계 맑은 날씨 고정", "야외에서 맑은 날씨를 강제합니다. 이벤트 중에는 이벤트 설정이 우선합니다."); RemoveMistlandsMist = BindLocalized("霧の地", "霧の地の霧を除去", "有効にすると霧の地専用の霧を除去します。全域晴天設定とは独立して動作します。", "Mistlands", "Remove Mistlands mist", "Removes Mistlands mist independently of clear weather.", "Nebelgebiete", "Nebel entfernen", "Entfernt den Nebel unabhängig vom klaren Wetter.", "Terres brumeuses", "Supprimer la brume des Terres brumeuses", "Supprime la brume indépendamment du réglage de temps clair.", "안개 지대", "안개 지대 안개 제거", "맑은 날씨 설정과 별도로 안개를 제거합니다."); RemoveDungeonHaze = BindLocalized("ダンジョン", "ダンジョン内のもやを除去", "ダンジョン内の名前にHazeまたはSmokeを含むParticleSystemを無効化します。", "Dungeons", "Remove dungeon haze", "Disables dungeon particles named Haze or Smoke.", "Verliese", "Dunst entfernen", "Deaktiviert Partikel mit Haze oder Smoke im Namen.", "Donjons", "Supprimer la brume légère des donjons", "Désactive les particules dont le nom contient Haze ou Smoke.", "던전", "던전 연무 제거", "Haze 또는 Smoke 이름의 파티클을 비활성화합니다."); RemoveDungeonFog = BindLocalized("ダンジョン", "ダンジョン内の霧を除去", "ダンジョン内の名前にFogまたはMistを含むParticleSystemを無効化します。", "Dungeons", "Remove dungeon mist", "Disables dungeon particles named Fog or Mist.", "Verliese", "Nebel entfernen", "Deaktiviert Partikel mit Fog oder Mist im Namen.", "Donjons", "Supprimer le brouillard des donjons", "Désactive les particules dont le nom contient Fog ou Mist.", "던전", "던전 안개 제거", "Fog 또는 Mist 이름의 파티클을 비활성화합니다."); ReduceDungeonEnvironmentFog = BindLocalized("ダンジョン", "ダンジョン環境の視界Fogを除去", "有効時は全EnvSetupの時間帯別Fog密度を一括で0にします。環境名やパーティクルは変更しません。OFFにすると保存した元の密度へ戻します。", "Dungeons", "Remove environment fog density", "Sets time-of-day fog densities of all EnvSetups to zero. Restores original values when disabled.", "Verliese", "Umgebungsnebeldichte entfernen", "Setzt alle zeitabhängigen Nebeldichten auf null. Stellt beim Ausschalten die Originalwerte wieder her.", "Donjons", "Supprimer la densité du brouillard ambiant", "Met à zéro les densités de brouillard de tous les EnvSetup selon le moment de la journée. Restaure les valeurs initiales à la désactivation.", "던전", "환경 안개 밀도 제거", "모든 EnvSetup의 시간대별 안개 밀도를 0으로 설정하고 해제 시 복원합니다."); ForceClearDungeonEnvironment = BindLocalized("ダンジョン", "ダンジョン内も晴天環境を強制", "有効時はダンジョン内でClear環境を固定します。Clearと元のダンジョン環境が交互に適用される競合をSetEnv側でも抑止します。", "Dungeons", "Force clear dungeon environment", "Forces Clear inside dungeons and suppresses competing environment changes.", "Verliese", "Klares Verlieswetter erzwingen", "Erzwingt Clear in Verliesen und unterbindet konkurrierende Umgebungswechsel.", "Donjons", "Imposer un environnement clair dans les donjons", "Impose un environnement Clear dans les donjons et empêche les changements concurrents.", "던전", "던전 맑은 환경 강제", "던전에서 맑은 환경을 강제하고 환경 전환 충돌을 억제합니다."); ForceClearEventEnvironment = BindLocalized("イベント", "ボス戦・襲撃時も晴天環境を強制", "イベント環境がある間は、全バイオーム晴天固定をこの設定のON/OFFに関係なく一時停止します。ONならイベント専用環境をClearに置き換え、OFFならEikthyr・Bonemass等の元のイベント環境を維持します。ボス名・襲撃名ごとの登録は不要です。イベント自体やスポーンには干渉しません。ダンジョン内でもボス戦・襲撃設定を優先します。", "Events", "Force clear weather during bosses and raids", "During events, biome forcing is suspended. On: Clear. Off: original event environment. Event settings also take priority inside dungeons. Does not change spawning or events.", "Ereignisse", "Klares Wetter bei Bossen und Überfällen", "Pausiert Biomwetter während Ereignissen. An: Clear. Aus: Originalumgebung. Ereignisse haben auch in Verliesen Vorrang. Gegner und Ereignisse bleiben unverändert.", "Événements", "Imposer un temps clair pendant les combats de boss et les raids", "Suspend la météo forcée des biomes pendant les événements. Activé : Clear. Désactivé : environnement original. Les événements sont prioritaires même dans les donjons. Ne modifie ni les événements ni les apparitions.", "이벤트", "보스전 및 습격 맑은 날씨 강제", "이벤트 중 생물군계 날씨 강제를 중단합니다. 켜면 맑음, 끄면 원래 이벤트 환경을 유지합니다. 던전에서도 이벤트 설정이 우선하며 이벤트와 생성은 변경하지 않습니다."); ForceClearWeather.SettingChanged += OnClearWeatherSettingChanged; RemoveMistlandsMist.SettingChanged += OnMistSettingChanged; RemoveDungeonHaze.SettingChanged += OnDungeonEffectsSettingChanged; RemoveDungeonFog.SettingChanged += OnDungeonEffectsSettingChanged; ReduceDungeonEnvironmentFog.SettingChanged += OnDungeonEnvironmentFogChanged; ForceClearDungeonEnvironment.SettingChanged += OnClearWeatherSettingChanged; ForceClearEventEnvironment.SettingChanged += OnEventEnvironmentSettingChanged; _harmony = new Harmony("com.sakey.weathercontrol"); _harmony.PatchAll(Assembly.GetExecutingAssembly()); ((Component)this).gameObject.AddComponent<DungeonAtmosphereController>(); ((Component)this).gameObject.AddComponent<DungeonEnvironmentFogController>(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Sakey's Weather Control 0.1.20 loaded. Weather and atmosphere options default to OFF."); } private ConfigEntry<bool> BindLocalized(params string[] translations) { //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Expected O, but got Unknown string text = ""; try { text = PlayerPrefs.GetString("language", "English"); } catch { } int num = 3; switch (text.ToLowerInvariant()) { case "japanese": case "日本語": num = 0; break; case "german": case "deutsch": num = 6; break; case "français": case "french": num = 9; break; case "한국어": case "korean": num = 12; break; } return ((BaseUnityPlugin)this).Config.Bind<bool>(translations[0], translations[1], false, new ConfigDescription(translations[num + 2], (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = translations[num], DispName = translations[num + 1] } })); } private void OnClearWeatherSettingChanged(object sender, EventArgs e) { ApplyClearWeather(); } private void OnMistSettingChanged(object sender, EventArgs e) { MistlandsMistController.ApplyCurrentSetting(); } private void OnDungeonEffectsSettingChanged(object sender, EventArgs e) { DungeonAtmosphereController.ApplyNow(); } private void OnDungeonEnvironmentFogChanged(object sender, EventArgs e) { DungeonEnvironmentFogController.ApplyNow(); } private void OnEventEnvironmentSettingChanged(object sender, EventArgs e) { ForceEnvironmentController.ApplyCurrentSetting(); try { EnvMan instance = EnvMan.instance; if ((Object)(object)instance != (Object)null) { instance.ForceInstantEnvironmentSwitch(); } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Event environment refresh failed: " + ex.Message)); } } internal void ApplyClearWeather() { ForceEnvironmentController.ForceReapply(); } private void OnDestroy() { try { if (_harmony != null) { _harmony.UnpatchSelf(); } if ((Object)(object)EnvMan.instance != (Object)null) { EnvMan.instance.SetForceEnvironment(""); } ForceEnvironmentController.ResetCache(); EventEnvironmentOverride.Reset(); PlayerEnvironmentTransitionTracker.Reset(); MistlandsMistController.RestoreVanillaMist(); DungeonAtmosphereController.RestoreAll(); DungeonEnvironmentFogController.Restore(); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Cleanup warning: " + ex.Message)); } } } [HarmonyPatch(typeof(EnvMan), "UpdateEnvironment", new Type[] { typeof(long), typeof(BiomeSector) })] internal static class EnvManUpdateEnvironmentPatch { private static void Postfix(long sec, BiomeSector biome) { PlayerEnvironmentTransitionTracker.ObserveSelectedBiome(((object)Unsafe.As<Biome, Biome>(ref biome.Biome)/*cast due to .constrained prefix*/).ToString()); ForceEnvironmentController.ApplyCurrentSetting(); } } [HarmonyPatch] internal static class PlayerEnvironmentTransitionPatch { private static MethodBase TargetMethod() { return AccessTools.Method(typeof(Player), "Update", Type.EmptyTypes, (Type[])null); } private static bool Prepare() { return TargetMethod() != null; } private static void Postfix(Player __instance) { PlayerEnvironmentTransitionTracker.Check(__instance); } } internal static class PlayerEnvironmentTransitionTracker { private static Player _trackedPlayer; private static string _lastBiome; private static bool _lastInside; private static bool _lastBoss; private static float _nextCheckTime; private static readonly MethodInfo BossMethod = typeof(Character).GetMethod("IsBoss", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); internal static bool IndoorBoss => _lastBoss; internal static void Check(Player player) { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: 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) if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || Time.unscaledTime < _nextCheckTime) { return; } _nextCheckTime = Time.unscaledTime + 0.5f; bool flag = InteriorDetector.IsPlayerInside(); bool flag2 = false; if (flag && BossMethod != null) { bool flag3 = default(bool); foreach (Character allCharacter in Character.GetAllCharacters()) { if ((Object)(object)allCharacter == (Object)null || allCharacter.IsDead()) { continue; } Vector3 val = ((Component)allCharacter).transform.position - ((Component)player).transform.position; if (!(((Vector3)(ref val)).sqrMagnitude > 10000f)) { object obj = BossMethod.Invoke(allCharacter, null); int num; if (obj is bool) { flag3 = (bool)obj; num = 1; } else { num = 0; } if (((uint)num & (flag3 ? 1u : 0u)) != 0) { flag2 = true; break; } } } } bool num2 = (Object)(object)_trackedPlayer != (Object)(object)player || _lastInside != flag || _lastBoss != flag2; _trackedPlayer = player; _lastInside = flag; _lastBoss = flag2; if (num2) { ForceEnvironmentController.ForceReapply(); } } internal static void ObserveSelectedBiome(string biomeName) { if (!(_lastBiome == biomeName)) { _lastBiome = biomeName; if (!InteriorDetector.IsPlayerInside() && Plugin.ForceClearWeather.Value) { ForceEnvironmentController.ForceReapply(); } } } internal static void Reset() { _trackedPlayer = null; _lastBiome = null; _lastInside = false; _lastBoss = false; _nextCheckTime = 0f; } } internal static class ForceEnvironmentController { private static string _lastRequested; private static bool _hasRequest; private static bool _isApplying; internal static void ApplyCurrentSetting() { if (_isApplying) { return; } _isApplying = true; try { EnvMan instance = EnvMan.instance; if ((Object)(object)instance == (Object)null) { return; } string text = ""; bool flag = InteriorDetector.IsPlayerInside(); bool flag2 = EventEnvironmentOverride.IsActive || (flag && PlayerEnvironmentTransitionTracker.IndoorBoss); bool flag3 = Plugin.ForceClearWeather != null && Plugin.ForceClearWeather.Value && !flag && !flag2; if (Plugin.ForceClearDungeonEnvironment != null && Plugin.ForceClearDungeonEnvironment.Value && flag) { _ = !flag2; } else _ = 0; if (!flag && (flag3 || (flag2 && Plugin.ForceClearEventEnvironment.Value))) { text = "Clear"; } if (!_hasRequest || !string.Equals(_lastRequested, text, StringComparison.Ordinal)) { string lastRequested = _lastRequested; if (!flag || string.Equals(lastRequested, "Clear", StringComparison.Ordinal)) { instance.SetForceEnvironment(text); } _lastRequested = text; _hasRequest = true; if (flag || text == "Clear" || string.Equals(lastRequested, "Clear", StringComparison.Ordinal)) { instance.ForceInstantEnvironmentSwitch(); } } } catch (Exception ex) { ManualLogSource logSource = Plugin.LogSource; if (logSource != null) { logSource.LogWarning((object)("Force-environment update failed: " + ex.Message)); } _hasRequest = false; } finally { _isApplying = false; } } internal static void ForceReapply() { if (!_isApplying) { _hasRequest = false; ApplyCurrentSetting(); } } internal static void ResetCache() { _hasRequest = false; _lastRequested = null; _isApplying = false; } } internal static class InteriorDetector { private static MethodInfo _inInteriorMethod; private static Type _cachedPlayerType; internal static bool IsPlayerInside() { try { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return true; } Type type = ((object)localPlayer).GetType(); if (_cachedPlayerType != type || _inInteriorMethod == null) { _cachedPlayerType = type; _inInteriorMethod = AccessTools.Method(type, "InInterior", Type.EmptyTypes, (Type[])null); } if (_inInteriorMethod == null) { return true; } return !(_inInteriorMethod.Invoke(localPlayer, null) is bool flag) || flag; } catch (Exception ex) { ManualLogSource logSource = Plugin.LogSource; if (logSource != null) { logSource.LogWarning((object)("Interior detection failed; weather override skipped safely: " + ex.Message)); } return true; } } } internal static class WeatherBiomeHelper { internal static bool IsMistlands(BiomeSector sector) { if (sector == null) { return false; } try { FieldInfo[] fields = ((object)sector).GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.Name.ToLowerInvariant().Contains("biome")) { object value = fieldInfo.GetValue(sector); if (value != null && value.ToString().IndexOf("Mistlands", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } } PropertyInfo[] properties = ((object)sector).GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (PropertyInfo propertyInfo in properties) { if (propertyInfo.Name.ToLowerInvariant().Contains("biome") && propertyInfo.CanRead) { object value2 = propertyInfo.GetValue(sector, null); if (value2 != null && value2.ToString().IndexOf("Mistlands", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } } } catch { } return false; } internal static bool IsMistlands() { try { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return false; } MethodInfo methodInfo = AccessTools.Method(((object)localPlayer).GetType(), "GetCurrentBiome", (Type[])null, (Type[])null); if (methodInfo != null) { object obj = methodInfo.Invoke(localPlayer, null); if (obj != null && obj.ToString().IndexOf("Mistlands", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } FieldInfo[] fields = ((object)localPlayer).GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.Name.ToLowerInvariant().Contains("biome")) { object value = fieldInfo.GetValue(localPlayer); if (value != null && value.ToString().IndexOf("Mistlands", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } } } catch { } return false; } } [HarmonyPatch] internal static class RandEventEnvironmentOverridePatch { private static MethodBase TargetMethod() { Type type = AccessTools.TypeByName("RandEventSystem"); if (!(type == null)) { return AccessTools.Method(type, "GetEnvOverride", Type.EmptyTypes, (Type[])null); } return null; } private static bool Prepare() { return TargetMethod() != null; } private static void Postfix(ref string __result) { EventEnvironmentOverride.Apply(ref __result, "RandEventSystem"); } } [HarmonyPatch] internal static class PersistentEventEnvironmentOverridePatch { private static MethodBase TargetMethod() { Type type = AccessTools.TypeByName("PersistentEventSystem"); if (!(type == null)) { return AccessTools.Method(type, "GetEnvironmentOverride", Type.EmptyTypes, (Type[])null); } return null; } private static bool Prepare() { return TargetMethod() != null; } private static void Postfix(ref string __result) { EventEnvironmentOverride.Apply(ref __result, "PersistentEventSystem"); } } internal static class EventEnvironmentOverride { private static bool _randomEventHasEnvironment; private static bool _persistentEventHasEnvironment; internal static bool IsActive { get { if (!_randomEventHasEnvironment) { return _persistentEventHasEnvironment; } return true; } } internal static void Apply(ref string environmentName, string source) { bool isActive = IsActive; bool flag = !string.IsNullOrEmpty(environmentName); if (string.Equals(source, "RandEventSystem", StringComparison.Ordinal)) { _randomEventHasEnvironment = flag; } else if (string.Equals(source, "PersistentEventSystem", StringComparison.Ordinal)) { _persistentEventHasEnvironment = flag; } if (flag && Plugin.ForceClearEventEnvironment != null && Plugin.ForceClearEventEnvironment.Value) { environmentName = "Clear"; } if (isActive != IsActive) { ForceEnvironmentController.ApplyCurrentSetting(); } } internal static void Reset() { _randomEventHasEnvironment = false; _persistentEventHasEnvironment = false; } } [HarmonyPatch(typeof(EnvMan), "SetEnv")] internal static class EnvManSetEnvPatch { private static void Prefix(ref EnvSetup env) { try { bool flag = InteriorDetector.IsPlayerInside(); if (!((EventEnvironmentOverride.IsActive || (flag && PlayerEnvironmentTransitionTracker.IndoorBoss)) ? Plugin.ForceClearEventEnvironment.Value : (flag ? Plugin.ForceClearDungeonEnvironment.Value : Plugin.ForceClearWeather.Value)) || env == null) { return; } EnvMan instance = EnvMan.instance; if ((Object)(object)instance == (Object)null || instance.m_environments == null) { return; } foreach (EnvSetup environment in instance.m_environments) { if (environment != null && string.Equals(environment.m_name, "Clear", StringComparison.OrdinalIgnoreCase)) { env = environment; break; } } } catch (Exception ex) { ManualLogSource logSource = Plugin.LogSource; if (logSource != null) { logSource.LogWarning((object)("Clear environment redirect failed: " + ex.Message)); } } } private static void Postfix() { MistlandsMistController.ApplyCurrentSetting(); DungeonEnvironmentFogController.ApplyNow(); } } internal static class MistlandsMistController { private static bool _capturedActiveState; private static bool _mistObjectWasActive; private static ParticleMist _capturedMist; private static bool _particlesClearedForCurrentEnable; internal static void ClearParticlesOnce(ParticleMist mist) { if ((Object)(object)mist == (Object)null || _particlesClearedForCurrentEnable) { return; } try { FieldInfo fieldInfo = AccessTools.Field(typeof(ParticleMist), "m_ps"); ParticleSystem val = (ParticleSystem)((fieldInfo != null) ? /*isinst with value type is only supported in some contexts*/: null); if ((Object)(object)val != (Object)null) { val.Clear(true); } _particlesClearedForCurrentEnable = true; } catch (Exception ex) { ManualLogSource logSource = Plugin.LogSource; if (logSource != null) { logSource.LogWarning((object)("Mist particle clearing failed: " + ex.Message)); } } } internal static void ApplyCurrentSetting() { ParticleMist instance = ParticleMist.instance; if ((Object)(object)instance == (Object)null) { return; } try { GameObject gameObject = ((Component)instance).gameObject; if (Plugin.RemoveMistlandsMist.Value) { if (!_capturedActiveState || (Object)(object)_capturedMist != (Object)(object)instance) { _mistObjectWasActive = gameObject.activeSelf; _capturedActiveState = true; _capturedMist = instance; _particlesClearedForCurrentEnable = false; } ClearParticlesOnce(instance); if (gameObject.activeSelf) { gameObject.SetActive(false); } } else if (_capturedActiveState) { if ((Object)(object)_capturedMist != (Object)null) { ((Component)_capturedMist).gameObject.SetActive(_mistObjectWasActive); } _capturedActiveState = false; _capturedMist = null; _particlesClearedForCurrentEnable = false; } } catch (Exception ex) { ManualLogSource logSource = Plugin.LogSource; if (logSource != null) { logSource.LogWarning((object)("Mist object state change failed: " + ex.Message)); } } } internal static void RestoreVanillaMist() { try { if ((Object)(object)_capturedMist != (Object)null && _capturedActiveState) { ((Component)_capturedMist).gameObject.SetActive(_mistObjectWasActive); } } catch { } _capturedActiveState = false; _capturedMist = null; _particlesClearedForCurrentEnable = false; } } internal sealed class DungeonEnvironmentFogController : MonoBehaviour { internal static void ApplyNow() { DungeonEnvSetupFogAdjuster.ApplyCurrentSetting(); } internal static void Restore() { DungeonEnvSetupFogAdjuster.RestoreAll(); } } internal static class DungeonEnvSetupFogAdjuster { private sealed class FogValues { internal float Morning; internal float Day; internal float Evening; internal float Night; } private static readonly Dictionary<EnvSetup, FogValues> Originals = new Dictionary<EnvSetup, FogValues>(); private static bool _lastApplied; private static bool _hasApplied; internal static void ApplyCurrentSetting() { try { EnvMan instance = EnvMan.instance; if ((Object)(object)instance == (Object)null || instance.m_environments == null) { return; } bool flag = Plugin.ReduceDungeonEnvironmentFog != null && Plugin.ReduceDungeonEnvironmentFog.Value; if (_hasApplied && _lastApplied == flag) { return; } if (flag) { foreach (EnvSetup environment in instance.m_environments) { if (environment != null && IsDungeonEnvironmentName(environment.m_name)) { if (!Originals.ContainsKey(environment)) { Originals[environment] = new FogValues { Morning = environment.m_fogDensityMorning, Day = environment.m_fogDensityDay, Evening = environment.m_fogDensityEvening, Night = environment.m_fogDensityNight }; } environment.m_fogDensityMorning = 0f; environment.m_fogDensityDay = 0f; environment.m_fogDensityEvening = 0f; environment.m_fogDensityNight = 0f; } } } else { RestoreAll(); } _lastApplied = flag; _hasApplied = true; } catch (Exception ex) { ManualLogSource logSource = Plugin.LogSource; if (logSource != null) { logSource.LogWarning((object)("Dungeon EnvSetup fog adjustment failed: " + ex.Message)); } _hasApplied = false; } } private static bool IsDungeonEnvironmentName(string name) { if (string.IsNullOrEmpty(name)) { return false; } string text = name.ToLowerInvariant(); if (!text.Contains("crypt") && !text.Contains("sunken") && !text.Contains("infectedmine") && !text.Contains("mine") && !text.Contains("cave") && !text.Contains("dungeon") && !text.Contains("cairn") && !text.Contains("tomb")) { return text.Contains("catacomb"); } return true; } internal static void RestoreAll() { foreach (KeyValuePair<EnvSetup, FogValues> original in Originals) { try { EnvSetup key = original.Key; FogValues value = original.Value; if (key != null && value != null) { key.m_fogDensityMorning = value.Morning; key.m_fogDensityDay = value.Day; key.m_fogDensityEvening = value.Evening; key.m_fogDensityNight = value.Night; } } catch { } } Originals.Clear(); _hasApplied = false; } } internal sealed class DungeonAtmosphereController : MonoBehaviour { private sealed class OriginalParticleState { internal bool WasActive; internal bool WasPlaying; } private static readonly Dictionary<ParticleSystem, OriginalParticleState> OriginalStates = new Dictionary<ParticleSystem, OriginalParticleState>(); private static float _nextScanTime; private static bool _wasInside; private void Update() { if ((Plugin.RemoveDungeonHaze == null || !Plugin.RemoveDungeonHaze.Value) && (Plugin.RemoveDungeonFog == null || !Plugin.RemoveDungeonFog.Value)) { if (OriginalStates.Count > 0) { RestoreAll(); } _wasInside = false; return; } if (!InteriorDetector.IsPlayerInside()) { if (_wasInside || OriginalStates.Count > 0) { RestoreAll(); } _wasInside = false; return; } if (!_wasInside) { _nextScanTime = 0f; } _wasInside = true; if (!(Time.unscaledTime < _nextScanTime)) { _nextScanTime = Time.unscaledTime + 5f; ApplyNow(); } } internal static void ApplyNow() { if (Plugin.RemoveDungeonHaze == null || Plugin.RemoveDungeonFog == null) { return; } if (!InteriorDetector.IsPlayerInside()) { RestoreAll(); return; } try { List<ParticleSystem> list = new List<ParticleSystem>(); foreach (KeyValuePair<ParticleSystem, OriginalParticleState> originalState in OriginalStates) { ParticleSystem key = originalState.Key; if ((Object)(object)key == (Object)null) { list.Add(key); continue; } string name = ((Object)((Component)key).gameObject).name; if ((!Plugin.RemoveDungeonHaze.Value || !ContainsAny(name, "haze", "smoke", "dustcloud", "dust cloud", "murk")) && (!Plugin.RemoveDungeonFog.Value || !ContainsAny(name, "fog", "mist", "miasma", "vapour", "vapor"))) { RestoreParticle(key, originalState.Value); list.Add(key); } } foreach (ParticleSystem item in list) { OriginalStates.Remove(item); } if (!Plugin.RemoveDungeonHaze.Value && !Plugin.RemoveDungeonFog.Value) { return; } ParticleSystem[] array = Object.FindObjectsOfType<ParticleSystem>(); foreach (ParticleSystem val in array) { if ((Object)(object)val == (Object)null) { continue; } string source = ((Object)((Component)val).gameObject).name + " " + ((Object)val).name; bool flag = ContainsAny(source, "haze", "smoke", "dustcloud", "dust cloud", "murk"); bool flag2 = ContainsAny(source, "fog", "mist", "miasma", "vapour", "vapor"); OriginalParticleState value; if ((Plugin.RemoveDungeonHaze.Value && flag) || (Plugin.RemoveDungeonFog.Value && flag2)) { if (!OriginalStates.ContainsKey(val)) { OriginalStates[val] = new OriginalParticleState { WasActive = ((Component)val).gameObject.activeSelf, WasPlaying = val.isPlaying }; } if (((Component)val).gameObject.activeSelf) { ((Component)val).gameObject.SetActive(false); } if (val.isPlaying) { val.Stop(true, (ParticleSystemStopBehavior)0); } } else if (OriginalStates.TryGetValue(val, out value)) { RestoreParticle(val, value); OriginalStates.Remove(val); } } } catch (Exception ex) { ManualLogSource logSource = Plugin.LogSource; if (logSource != null) { logSource.LogWarning((object)("Dungeon atmosphere scan failed: " + ex.Message)); } } } private static bool ContainsAny(string source, params string[] needles) { if (string.IsNullOrEmpty(source)) { return false; } foreach (string value in needles) { if (source.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } return false; } private static void RestoreParticle(ParticleSystem ps, OriginalParticleState state) { if (!((Object)(object)ps == (Object)null) && state != null) { ((Component)ps).gameObject.SetActive(state.WasActive); if (state.WasActive && state.WasPlaying) { ps.Play(true); } } } internal static void RestoreAll() { foreach (KeyValuePair<ParticleSystem, OriginalParticleState> originalState in OriginalStates) { try { if ((Object)(object)originalState.Key != (Object)null) { RestoreParticle(originalState.Key, originalState.Value); } } catch { } } OriginalStates.Clear(); } }