Decompiled source of Pitch Black PEAK v2.1.0

tony4twentys-Pitch Black PEAK.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using ExitGames.Client.Photon;
using HarmonyLib;
using Peak;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Zorro.Core;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Pitch Black")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pitch Black")]
[assembly: AssemblyCopyright("Copyright ©  2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("a56511ae-cfa7-4db8-941f-7e56997eb19a")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.1.0.0")]
[module: UnverifiableCode]
namespace Pitch_Black_PEAK;

internal static class PitchBlackRuntime
{
	internal static bool HostModConfirmed;

	internal static bool VanillaHostMode;

	internal static bool IsAwaitingHostSync => PhotonNetwork.InRoom && !PhotonNetwork.IsMasterClient && !HostModConfirmed && !VanillaHostMode;

	internal static bool ShouldApplyModEffects()
	{
		if (VanillaHostMode)
		{
			return false;
		}
		if (PhotonNetwork.InRoom && !PhotonNetwork.IsMasterClient && !HostModConfirmed)
		{
			return false;
		}
		return true;
	}

	internal static void OnJoinedRoom(bool isMaster)
	{
		VanillaHostMode = false;
		HostModConfirmed = isMaster;
		if (isMaster)
		{
			ReapplyModEffects();
		}
	}

	internal static void OnHostSyncReceived()
	{
		HostModConfirmed = true;
		VanillaHostMode = false;
	}

	internal static void OnLeftRoom()
	{
		HostModConfirmed = false;
		VanillaHostMode = false;
		PluginSettings.RefreshFromConfig();
		ReapplyModEffects();
	}

	internal static void OnHostModMissing()
	{
		HostModConfirmed = false;
		VanillaHostMode = true;
		RestoreVanillaGameplay();
	}

	internal static void ReapplyModEffects()
	{
		if (!PhotonNetwork.InRoom || PhotonNetwork.IsMasterClient)
		{
			PluginSettings.RefreshFromConfig();
		}
		EnvironmentController.ForceFullSyncRebuild();
		HipLanternHolster.PurgeIneligibleNpcHolsters();
	}

	internal static void RestoreVanillaGameplay()
	{
		SceneDarknessCache.RestoreCelestialBlackout();
		NightGlobals.RestoreScheduledEffects();
		NightGlobals.RestoreWorldAmbient();
		SceneDarknessCache.SetMirrorMountainsHidden(hide: false);
		EnvironmentController.OnSceneLoadReset();
		CharacterLightHelper.ForceRestoreAllCharacters();
		HipLanternHolster.PurgeAllHolsters();
		SnowMaterialFix.Apply(enhance: false);
		HipLanternNet.ClearRemoteState();
		if ((Object)(object)PitchBlackPlugin.Instance != (Object)null)
		{
			((MonoBehaviour)PitchBlackPlugin.Instance).StartCoroutine(DelayedVanillaRefresh());
		}
	}

	private static IEnumerator DelayedVanillaRefresh()
	{
		yield return null;
		NightGlobals.RestoreWorldAmbient();
		yield return (object)new WaitForSeconds(0.5f);
		NightGlobals.RestoreWorldAmbient();
		yield return (object)new WaitForSeconds(1f);
		NightGlobals.RestoreWorldAmbient();
	}
}
public enum LanternState : byte
{
	Omni,
	Flashlight
}
public enum LanternColorMode
{
	Original,
	SkinColor,
	Custom
}
public enum ScoutmasterLanternColorMode
{
	Vanilla,
	Custom
}
public enum DarknessPreset
{
	FullDark,
	DayNightCycle,
	Custom
}
public enum LanternBurnDuration
{
	Seconds60 = 60,
	Seconds120 = 120,
	Seconds240 = 240,
	Seconds360 = 360,
	Seconds600 = 600,
	Infinite = 100000
}
public enum DayCyclePhase
{
	Sunrise,
	Afternoon,
	Sunset,
	Night,
	PitchBlack
}
public enum TimeHudAnchor
{
	TopLeft,
	TopCenter,
	TopRight,
	BottomLeft,
	BottomCenter,
	BottomRight
}
public enum TimeHudLayout
{
	Vertical,
	Horizontal
}
internal struct DayNightHours
{
	internal float Sunrise;

	internal float Afternoon;

	internal float Sunset;

	internal float Night;

	internal static DayNightHours Defaults => new DayNightHours
	{
		Sunrise = 5f,
		Afternoon = 12f,
		Sunset = 17f,
		Night = 22f
	};
}
[BepInPlugin("tony4twentys.Pitch_Black_PEAK", "Pitch Black PEAK", "2.1.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class PitchBlackPlugin : BaseUnityPlugin
{
	internal const byte EventCode = 147;

	internal const int ProtocolVersion = 204;

	internal static PitchBlackPlugin Instance;

	internal static ConfigEntry<KeyCode> ConfigLanternModeToggleKey;

	internal static ConfigEntry<LanternColorMode> ConfigLanternColorMode;

	internal static ConfigEntry<string> ConfigLanternHex;

	internal static ConfigEntry<LanternBurnDuration> ConfigBurnDuration;

	internal static ConfigEntry<DarknessPreset> ConfigDarknessPreset;

	internal static ConfigEntry<float> ConfigSunriseHour;

	internal static ConfigEntry<float> ConfigAfternoonHour;

	internal static ConfigEntry<float> ConfigSunsetHour;

	internal static ConfigEntry<float> ConfigNightHour;

	internal static ConfigEntry<float> ConfigDarknessMultiplier;

	internal static ConfigEntry<bool> ConfigShowCelestialSky;

	internal static ConfigEntry<float> ConfigLanternIntensity;

	internal static ConfigEntry<float> ConfigFlashlightRange;

	internal static ConfigEntry<bool> ConfigGhostVision;

	internal static ConfigEntry<bool> ConfigGhostGlow;

	internal static ConfigEntry<bool> ConfigStartWithLantern;

	internal static ConfigEntry<bool> ConfigHipLantern;

	internal static ConfigEntry<bool> ConfigScoutmasterHipLantern;

	internal static ConfigEntry<ScoutmasterLanternColorMode> ConfigScoutmasterLanternColorMode;

	internal static ConfigEntry<string> ConfigScoutmasterLanternHex;

	internal static ConfigEntry<bool> ConfigCampfireGlow;

	internal static ConfigEntry<bool> ConfigFlareGlow;

	internal static ConfigEntry<bool> ConfigDisableCharacterLight;

	internal static ConfigEntry<bool> ConfigSnowFix;

	internal static ConfigEntry<bool> ConfigGloomAuraEnabled;

	internal static ConfigEntry<float> ConfigGloomAuraVisualRadius;

	internal static ConfigEntry<float> ConfigGloomAuraFalloff;

	internal static ConfigEntry<float> ConfigGloomAuraOpacity;

	internal static ConfigEntry<bool> ConfigShowTimeDisplay;

	internal static ConfigEntry<bool> ConfigShowPhaseLabel;

	internal static ConfigEntry<bool> ConfigClockUse12Hour;

	internal static ConfigEntry<TimeHudAnchor> ConfigClockAnchor;

	internal static ConfigEntry<TimeHudLayout> ConfigClockLayout;

	internal static ConfigEntry<float> ConfigClockOffsetX;

	internal static ConfigEntry<float> ConfigClockOffsetY;

	internal static ConfigEntry<bool> ConfigClockShowBackground;

	internal static ConfigEntry<string> ConfigClockBackgroundColor;

	internal static ConfigEntry<float> ConfigClockBackgroundAlpha;

	internal static ConfigEntry<string> ConfigClockTimeColor;

	internal static ConfigEntry<string> ConfigClockPhaseColor;

	internal static ConfigEntry<int> ConfigClockTimeFontSize;

	internal static ConfigEntry<int> ConfigClockPhaseFontSize;

	internal static ConfigEntry<bool> ConfigClockTimeBold;

	internal static ConfigEntry<bool> ConfigClockPhaseBold;

	internal static ConfigEntry<float> ConfigClockPadding;

	private Harmony _harmony;

	private Coroutine _envDebounce;

	private void Awake()
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Expected O, but got Unknown
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		Instance = this;
		_harmony = new Harmony("tony4twentys.Pitch_Black_PEAK");
		BindConfig();
		PluginSettings.RefreshFromConfig();
		PatchAllResilient();
		GameObject val = new GameObject("PitchBlack_NetProxy");
		Object.DontDestroyOnLoad((Object)(object)val);
		val.AddComponent<PitchBlackNetProxy>();
		SceneManager.sceneLoaded += OnSceneLoaded;
		((BaseUnityPlugin)this).Config.SettingChanged += OnConfigChanged;
		TimeDisplayHud.EnsureExists();
		TimeThemeCompat.EnsureHooked();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Pitch Black PEAK 2.1.0 loaded.");
	}

	private void PatchAllResilient()
	{
		Type[] types = typeof(PitchBlackPlugin).Assembly.GetTypes();
		foreach (Type type in types)
		{
			try
			{
				_harmony.CreateClassProcessor(type).Patch();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Harmony patch failed for " + type.Name + ": " + ex.Message));
			}
		}
	}

	private void BindConfig()
	{
		//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Expected O, but got Unknown
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Expected O, but got Unknown
		//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0200: Expected O, but got Unknown
		//IL_0233: Unknown result type (might be due to invalid IL or missing references)
		//IL_023d: Expected O, but got Unknown
		//IL_0270: Unknown result type (might be due to invalid IL or missing references)
		//IL_027a: Expected O, but got Unknown
		//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d9: Expected O, but got Unknown
		//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0308: Expected O, but got Unknown
		//IL_032d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0337: Expected O, but got Unknown
		//IL_035c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0366: Expected O, but got Unknown
		//IL_0399: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a3: Expected O, but got Unknown
		//IL_05e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_05ec: Expected O, but got Unknown
		//IL_065d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0667: Expected O, but got Unknown
		//IL_0690: Unknown result type (might be due to invalid IL or missing references)
		//IL_069a: Expected O, but got Unknown
		//IL_070d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0717: Expected O, but got Unknown
		ConfigLanternModeToggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Lantern", "ModeToggleKey", (KeyCode)102, "Key to toggle lantern Omni / Bullseye while held. Also listed under Modded Controls.");
		ConfigLanternColorMode = ((BaseUnityPlugin)this).Config.Bind<LanternColorMode>("Lantern", "ColorMode", LanternColorMode.Original, "Original (warm yellow), SkinColor (scout color), or Custom hex.");
		ConfigLanternHex = ((BaseUnityPlugin)this).Config.Bind<string>("Lantern", "CustomColorHex", "ff6600", "Six-digit hex color when ColorMode is Custom (no #).");
		ConfigBurnDuration = ((BaseUnityPlugin)this).Config.Bind<LanternBurnDuration>("Lantern", "BurnDuration", LanternBurnDuration.Infinite, "Lantern fuel duration. Faerie Lantern is always excluded.");
		ConfigLanternIntensity = ((BaseUnityPlugin)this).Config.Bind<float>("Lantern", "Intensity", 12f, new ConfigDescription("Lantern / flashlight brightness.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), Array.Empty<object>()));
		ConfigFlashlightRange = ((BaseUnityPlugin)this).Config.Bind<float>("Lantern", "FlashlightRange", 80f, new ConfigDescription("Flashlight beam range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 200f), Array.Empty<object>()));
		ConfigStartWithLantern = ((BaseUnityPlugin)this).Config.Bind<bool>("Lantern", "StartWithLantern", true, "Give a lantern when entering level_* scenes. Always given in the airport regardless of this setting.");
		ConfigHipLantern = ((BaseUnityPlugin)this).Config.Bind<bool>("Lantern", "HipLantern", true, "Show lantern on hip when pocketed in hotbar (not backpack). Player characters only unless ScoutmasterHipLantern is enabled.");
		ConfigScoutmasterHipLantern = ((BaseUnityPlugin)this).Config.Bind<bool>("Lantern", "ScoutmasterHipLantern", false, "Allow a hip-holstered lantern on Scoutmaster/NPCs. Always lit. Independent of player lantern inventory. Held torch/lantern is controlled by Scoutmaster's Rampage, not Pitch Black.");
		ConfigScoutmasterLanternColorMode = ((BaseUnityPlugin)this).Config.Bind<ScoutmasterLanternColorMode>("Lantern", "ScoutmasterLanternColorMode", ScoutmasterLanternColorMode.Vanilla, "Vanilla warm lantern, or Custom hex. Host setting syncs to all clients.");
		ConfigScoutmasterLanternHex = ((BaseUnityPlugin)this).Config.Bind<string>("Lantern", "ScoutmasterLanternColorHex", "FF9933", "Six-digit hex when ScoutmasterLanternColorMode is Custom (no #).");
		ConfigGloomAuraEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Lantern", "GloomAuraEnabled", true, "Enable the foggy gloom aura around lit lanterns (held, ground, and hip).");
		ConfigGloomAuraVisualRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Lantern", "GloomAuraVisualRadius", 6f, new ConfigDescription("Size of the foggy particle aura / fog-clear bubble around lit lanterns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 40f), Array.Empty<object>()));
		ConfigGloomAuraFalloff = ((BaseUnityPlugin)this).Config.Bind<float>("Lantern", "GloomAuraFalloff", 3f, new ConfigDescription("How softly fog returns outside the aura (larger = softer edge).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 30f), Array.Empty<object>()));
		ConfigGloomAuraOpacity = ((BaseUnityPlugin)this).Config.Bind<float>("Lantern", "GloomAuraOpacity", 0.1f, new ConfigDescription("Transparency of the foggy aura glow (0 = invisible, 1 = full strength). Does not affect the inner fire.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
		ConfigDarknessPreset = ((BaseUnityPlugin)this).Config.Bind<DarknessPreset>("Darkness", "Preset", DarknessPreset.FullDark, "FullDark = original always-pitch-black. DayNightCycle = sunrise/afternoon/sunset/night loop. Custom = same loop with hours below.");
		AcceptableValueRange<float> val = new AcceptableValueRange<float>(0f, 24f);
		ConfigSunriseHour = ((BaseUnityPlugin)this).Config.Bind<float>("Day/Night Cycle", "Sunrise", 5f, new ConfigDescription("Sunrise fade begins (night ends). Ends when Afternoon begins. Default 05:00.", (AcceptableValueBase)(object)val, Array.Empty<object>()));
		ConfigAfternoonHour = ((BaseUnityPlugin)this).Config.Bind<float>("Day/Night Cycle", "Afternoon", 12f, new ConfigDescription("Full daylight begins (sunrise fade ends). Ends when Sunset begins. Default 12:00.", (AcceptableValueBase)(object)val, Array.Empty<object>()));
		ConfigSunsetHour = ((BaseUnityPlugin)this).Config.Bind<float>("Day/Night Cycle", "Sunset", 17f, new ConfigDescription("Sunset fade begins (afternoon ends). Ends when Night begins. Default 17:00.", (AcceptableValueBase)(object)val, Array.Empty<object>()));
		ConfigNightHour = ((BaseUnityPlugin)this).Config.Bind<float>("Day/Night Cycle", "Night", 22f, new ConfigDescription("Pitch-black night begins (sunset fade ends). Ends when Sunrise begins. Default 22:00.", (AcceptableValueBase)(object)val, Array.Empty<object>()));
		ConfigDarknessMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Darkness", "DarknessMultiplier", 0f, new ConfigDescription("Ambient floor at full darkness (lower = darker).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.15f), Array.Empty<object>()));
		ConfigShowCelestialSky = ((BaseUnityPlugin)this).Config.Bind<bool>("Darkness", "ShowCelestialSky", false, "When false (default), sun/moon/skybox are hidden in FullDark and at night in Day/Night Cycle. When true, they stay visible even during pitch black.");
		ConfigGhostVision = ((BaseUnityPlugin)this).Config.Bind<bool>("Extras", "GhostNightVision", true, "Night-vision filter while you are a ghost.");
		ConfigGhostGlow = ((BaseUnityPlugin)this).Config.Bind<bool>("Extras", "GhostGlow", true, "Soft colored glow on ghost bodies.");
		ConfigCampfireGlow = ((BaseUnityPlugin)this).Config.Bind<bool>("Extras", "CampfireGlow", true, "Extra light on lit campfires.");
		ConfigFlareGlow = ((BaseUnityPlugin)this).Config.Bind<bool>("Extras", "FlareGlow", true, "Boost lit flare brightness.");
		ConfigDisableCharacterLight = ((BaseUnityPlugin)this).Config.Bind<bool>("Extras", "DisableCharacterLight", true, "Disable built-in character lights that bypass darkness.");
		ConfigSnowFix = ((BaseUnityPlugin)this).Config.Bind<bool>("Extras", "AlpineSnowFix", true, "Dim glowing alpine ice materials so they don't blow out the darkness.");
		ConfigShowTimeDisplay = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "ShowClock", true, "Show the on-screen day/night clock.");
		ConfigShowPhaseLabel = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "ShowPhase", true, "Show current cycle phase (Sunrise / Afternoon / Sunset / Night) under or beside the clock.");
		ConfigClockUse12Hour = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "Use12HourClock", true, "Use 12-hour AM/PM clock instead of 24-hour military time.");
		ConfigClockAnchor = ((BaseUnityPlugin)this).Config.Bind<TimeHudAnchor>("UI", "Anchor", TimeHudAnchor.TopCenter, "Screen anchor point for the clock panel.");
		ConfigClockLayout = ((BaseUnityPlugin)this).Config.Bind<TimeHudLayout>("UI", "Layout", TimeHudLayout.Vertical, "Vertical = time above phase. Horizontal = time beside phase.");
		ConfigClockOffsetX = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "OffsetX", 320f, "Horizontal pixel offset from the anchor.");
		ConfigClockOffsetY = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "OffsetY", -12f, "Vertical pixel offset from the anchor.");
		ConfigClockShowBackground = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "ShowBackground", false, "Draw a background panel behind the clock text.");
		ConfigClockBackgroundColor = ((BaseUnityPlugin)this).Config.Bind<string>("UI", "BackgroundColorHex", "000000", "Background color as six-digit hex (no #). Ignored when ShowBackground is false.");
		ConfigClockBackgroundAlpha = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "BackgroundAlpha", 0.55f, new ConfigDescription("Background opacity when ShowBackground is true.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
		ConfigClockTimeColor = ((BaseUnityPlugin)this).Config.Bind<string>("UI", "TimeColorHex", "FFFFFF", "Clock time text color (six-digit hex, no #).");
		ConfigClockPhaseColor = ((BaseUnityPlugin)this).Config.Bind<string>("UI", "PhaseColorHex", "CCCCCC", "Phase label text color (six-digit hex, no #).");
		ConfigClockTimeFontSize = ((BaseUnityPlugin)this).Config.Bind<int>("UI", "TimeFontSize", 28, new ConfigDescription("Clock time font size.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(8, 72), Array.Empty<object>()));
		ConfigClockPhaseFontSize = ((BaseUnityPlugin)this).Config.Bind<int>("UI", "PhaseFontSize", 16, new ConfigDescription("Phase label font size.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(8, 48), Array.Empty<object>()));
		ConfigClockTimeBold = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "TimeBold", false, "Bold clock time text.");
		ConfigClockPhaseBold = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "PhaseBold", false, "Bold phase label text.");
		ConfigClockPadding = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "Padding", 0f, new ConfigDescription("Inner padding around text inside the panel.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 40f), Array.Empty<object>()));
	}

	private void OnConfigChanged(object sender, SettingChangedEventArgs e)
	{
		if (_envDebounce != null)
		{
			((MonoBehaviour)this).StopCoroutine(_envDebounce);
		}
		_envDebounce = ((MonoBehaviour)this).StartCoroutine(ConfigDebounceRoutine());
	}

	private IEnumerator ConfigDebounceRoutine()
	{
		yield return (object)new WaitForSecondsRealtime(0.1f);
		PluginSettings.ParseCustomHex(ConfigLanternHex.Value);
		PluginSettings.ParseScoutmasterHex(ConfigScoutmasterLanternHex.Value);
		PluginSettings.RefreshFromConfig();
		PluginSettings.RefreshUiFromConfig();
		CharacterLightHelper.ApplyConfig();
		TimeDisplayHud.RefreshFromConfig();
		EnvironmentController.ApplyLiveSettings();
		LanternVisuals.ForceRefreshAllColors();
		HipLanternHolster.RefreshAllVisuals();
		HipLanternHolster.PurgeIneligibleNpcHolsters();
		TimeThemeCompat.EnsureHooked();
		PitchBlackNetProxy.ScheduleBroadcast();
		_envDebounce = null;
	}

	private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
	{
		StarterLantern.ResetSession();
		EnvironmentController.OnSceneLoadReset();
		PluginSettings.RefreshFromConfig();
		TimeDisplayHud.RefreshFromConfig();
		TimeThemeCompat.EnsureHooked();
		if (!PitchBlackRuntime.ShouldApplyModEffects())
		{
			if (PitchBlackRuntime.VanillaHostMode)
			{
				PitchBlackRuntime.RestoreVanillaGameplay();
			}
			return;
		}
		CharacterLightHelper.ApplyConfig();
		EnvironmentController.ForceFullSyncRebuild();
		if (ConfigSnowFix.Value)
		{
			SnowMaterialFix.Apply(enhance: true);
		}
		((MonoBehaviour)this).StartCoroutine(StarterLantern.GiveAfterDelay(15f));
	}

	private void OnDestroy()
	{
		try
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}
		catch
		{
		}
		try
		{
			((BaseUnityPlugin)this).Config.SettingChanged -= OnConfigChanged;
		}
		catch
		{
		}
		try
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
		catch
		{
		}
	}
}
internal static class PluginSettings
{
	internal static float DarknessMultiplier;

	internal static float LanternIntensity = 12f;

	internal static float FlashlightRange = 80f;

	internal static DayNightHours CycleHours = DayNightHours.Defaults;

	internal static float BurnDurationSeconds = 100000f;

	internal static bool GhostVision = true;

	internal static bool GhostGlow = true;

	internal static bool CampfireGlow = true;

	internal static bool FlareGlow = true;

	internal static bool StartWithLantern = true;

	internal static bool HipLanternEnabled = true;

	internal static bool ScoutmasterHipLantern;

	internal static ScoutmasterLanternColorMode ScoutmasterColorMode = ScoutmasterLanternColorMode.Vanilla;

	internal static Color ScoutmasterCustomColor = new Color(1f, 0.6f, 0.3f);

	internal static bool DisableCharacterLight = true;

	internal static bool SnowFix = true;

	internal static bool GloomAuraEnabled = true;

	internal static float GloomAuraVisualRadius = 6f;

	internal static float GloomAuraFalloff = 3f;

	internal static float GloomAuraOpacity = 0.1f;

	internal static bool ShowTimeDisplay = true;

	internal static bool ShowPhaseLabel = true;

	internal static bool ClockUse12Hour = true;

	internal static TimeHudAnchor ClockAnchor = TimeHudAnchor.TopCenter;

	internal static TimeHudLayout ClockLayout = TimeHudLayout.Vertical;

	internal static float ClockOffsetX = 320f;

	internal static float ClockOffsetY = -12f;

	internal static bool ClockShowBackground;

	internal static Color ClockBackgroundColor = new Color(0f, 0f, 0f, 0.55f);

	internal static Color ClockTimeColor = Color.white;

	internal static Color ClockPhaseColor = new Color(0.8f, 0.8f, 0.8f);

	internal static int ClockTimeFontSize = 28;

	internal static int ClockPhaseFontSize = 16;

	internal static bool ClockTimeBold;

	internal static bool ClockPhaseBold;

	internal static float ClockPadding;

	internal static bool ShowCelestialSky;

	internal static DarknessPreset Preset = DarknessPreset.FullDark;

	internal static LanternColorMode ColorMode = LanternColorMode.Original;

	internal static Color CustomColor = new Color(1f, 0.4f, 0f);

	internal static bool IsSyncingFromNet;

	internal static Color ScoutmasterLanternColor => (Color)((ScoutmasterColorMode == ScoutmasterLanternColorMode.Custom) ? ScoutmasterCustomColor : new Color(1f, 0.6f, 0.3f));

	internal static void RefreshFromConfig()
	{
		RefreshUiFromConfig();
		if ((!PhotonNetwork.InRoom || PhotonNetwork.IsMasterClient) && !((Object)(object)PitchBlackPlugin.Instance == (Object)null))
		{
			DarknessMultiplier = PitchBlackPlugin.ConfigDarknessMultiplier.Value;
			LanternIntensity = PitchBlackPlugin.ConfigLanternIntensity.Value;
			FlashlightRange = PitchBlackPlugin.ConfigFlashlightRange.Value;
			BurnDurationSeconds = (float)PitchBlackPlugin.ConfigBurnDuration.Value;
			GhostVision = PitchBlackPlugin.ConfigGhostVision.Value;
			GhostGlow = PitchBlackPlugin.ConfigGhostGlow.Value;
			CampfireGlow = PitchBlackPlugin.ConfigCampfireGlow.Value;
			FlareGlow = PitchBlackPlugin.ConfigFlareGlow.Value;
			StartWithLantern = PitchBlackPlugin.ConfigStartWithLantern.Value;
			HipLanternEnabled = PitchBlackPlugin.ConfigHipLantern.Value;
			ScoutmasterHipLantern = PitchBlackPlugin.ConfigScoutmasterHipLantern.Value;
			ScoutmasterColorMode = PitchBlackPlugin.ConfigScoutmasterLanternColorMode.Value;
			ParseScoutmasterHex(PitchBlackPlugin.ConfigScoutmasterLanternHex.Value);
			DisableCharacterLight = PitchBlackPlugin.ConfigDisableCharacterLight.Value;
			SnowFix = PitchBlackPlugin.ConfigSnowFix.Value;
			GloomAuraEnabled = PitchBlackPlugin.ConfigGloomAuraEnabled.Value;
			GloomAuraVisualRadius = PitchBlackPlugin.ConfigGloomAuraVisualRadius.Value;
			GloomAuraFalloff = PitchBlackPlugin.ConfigGloomAuraFalloff.Value;
			GloomAuraOpacity = PitchBlackPlugin.ConfigGloomAuraOpacity.Value;
			ShowCelestialSky = PitchBlackPlugin.ConfigShowCelestialSky.Value;
			Preset = NormalizePreset(PitchBlackPlugin.ConfigDarknessPreset.Value);
			ColorMode = PitchBlackPlugin.ConfigLanternColorMode.Value;
			ParseCustomHex(PitchBlackPlugin.ConfigLanternHex.Value);
			CycleHours = ((Preset == DarknessPreset.Custom) ? ReadCustomHoursFromConfig() : DayNightHours.Defaults);
		}
	}

	internal static void RefreshUiFromConfig()
	{
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)PitchBlackPlugin.Instance == (Object)null))
		{
			ShowTimeDisplay = PitchBlackPlugin.ConfigShowTimeDisplay.Value;
			ShowPhaseLabel = PitchBlackPlugin.ConfigShowPhaseLabel.Value;
			ClockUse12Hour = PitchBlackPlugin.ConfigClockUse12Hour.Value;
			ClockAnchor = PitchBlackPlugin.ConfigClockAnchor.Value;
			ClockLayout = PitchBlackPlugin.ConfigClockLayout.Value;
			ClockOffsetX = PitchBlackPlugin.ConfigClockOffsetX.Value;
			ClockOffsetY = PitchBlackPlugin.ConfigClockOffsetY.Value;
			ClockShowBackground = PitchBlackPlugin.ConfigClockShowBackground.Value;
			ClockBackgroundColor = ParseHexColor(PitchBlackPlugin.ConfigClockBackgroundColor.Value, 1f);
			ClockBackgroundColor.a = PitchBlackPlugin.ConfigClockBackgroundAlpha.Value;
			ClockTimeColor = ParseHexColor(PitchBlackPlugin.ConfigClockTimeColor.Value, 1f);
			ClockPhaseColor = ParseHexColor(PitchBlackPlugin.ConfigClockPhaseColor.Value, 1f);
			ClockTimeFontSize = PitchBlackPlugin.ConfigClockTimeFontSize.Value;
			ClockPhaseFontSize = PitchBlackPlugin.ConfigClockPhaseFontSize.Value;
			ClockTimeBold = PitchBlackPlugin.ConfigClockTimeBold.Value;
			ClockPhaseBold = PitchBlackPlugin.ConfigClockPhaseBold.Value;
			ClockPadding = PitchBlackPlugin.ConfigClockPadding.Value;
		}
	}

	private static DarknessPreset NormalizePreset(DarknessPreset raw)
	{
		if (raw <= DarknessPreset.FullDark)
		{
			return DarknessPreset.FullDark;
		}
		if (raw == DarknessPreset.Custom)
		{
			return DarknessPreset.Custom;
		}
		return DarknessPreset.DayNightCycle;
	}

	private static DayNightHours ReadCustomHoursFromConfig()
	{
		return new DayNightHours
		{
			Sunrise = PitchBlackPlugin.ConfigSunriseHour.Value,
			Afternoon = PitchBlackPlugin.ConfigAfternoonHour.Value,
			Sunset = PitchBlackPlugin.ConfigSunsetHour.Value,
			Night = PitchBlackPlugin.ConfigNightHour.Value
		};
	}

	internal static void ApplyNetworkSnapshot(float mult, float intensity, float range, DayNightHours hours, DarknessPreset preset, bool ghostVision, bool charLight, float burn, LanternColorMode colorMode, Color custom, bool showCelestialSky, bool startWithLantern, bool campfireGlow, bool flareGlow, bool hipLantern, bool scoutmasterHipLantern, bool gloomAuraEnabled, float gloomVisualRadius, float gloomFalloff, float gloomAuraOpacity, ScoutmasterLanternColorMode scoutmasterColorMode, Color scoutmasterColor)
	{
		//IL_003c: 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_0090: 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)
		DarknessMultiplier = mult;
		LanternIntensity = intensity;
		FlashlightRange = range;
		CycleHours = hours;
		Preset = preset;
		GhostVision = ghostVision;
		DisableCharacterLight = charLight;
		BurnDurationSeconds = burn;
		ColorMode = colorMode;
		CustomColor = custom;
		ShowCelestialSky = showCelestialSky;
		StartWithLantern = startWithLantern;
		CampfireGlow = campfireGlow;
		FlareGlow = flareGlow;
		HipLanternEnabled = hipLantern;
		ScoutmasterHipLantern = scoutmasterHipLantern;
		GloomAuraEnabled = gloomAuraEnabled;
		GloomAuraVisualRadius = gloomVisualRadius;
		GloomAuraFalloff = gloomFalloff;
		GloomAuraOpacity = gloomAuraOpacity;
		ScoutmasterColorMode = scoutmasterColorMode;
		ScoutmasterCustomColor = scoutmasterColor;
	}

	internal static void ParseCustomHex(string raw)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		CustomColor = ParseHexColor(raw, 1f);
	}

	internal static void ParseScoutmasterHex(string raw)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		ScoutmasterCustomColor = ParseHexColor(raw, 1f);
	}

	internal static Color ParseHexColor(string raw, float defaultAlpha)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: 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)
		if (string.IsNullOrWhiteSpace(raw))
		{
			return Color.white;
		}
		string text = raw.Trim();
		if (text.StartsWith("#"))
		{
			text = text.Substring(1);
		}
		if (text.Length > 6)
		{
			text = text.Substring(0, 6);
		}
		Color result = default(Color);
		if (ColorUtility.TryParseHtmlString("#" + text, ref result))
		{
			result.a = defaultAlpha;
			return result;
		}
		return Color.white;
	}
}
internal static class NightVisionState
{
	internal static bool BinocularsActive;

	internal static bool HasNightVision => BinocularsActive || (PluginSettings.GhostVision && (Object)(object)Character.localCharacter != (Object)null && Character.localCharacter.IsGhost);
}
internal static class EnvironmentController
{
	private static DarknessPreset _lastPreset = (DarknessPreset)(-1);

	internal static float CurrentWeight { get; private set; }

	internal static void UpdateWeight(float timeOfDay)
	{
		if (PluginSettings.Preset == DarknessPreset.FullDark)
		{
			CurrentWeight = 1f;
			return;
		}
		DayNightHours cycleHours = PluginSettings.CycleHours;
		CurrentWeight = CalcCycleWeight(timeOfDay, cycleHours);
	}

	internal static float CalcCycleWeight(float t, DayNightHours h)
	{
		t = NormalizeHour(t);
		if (InRangeSameDay(t, h.Afternoon, h.Sunset))
		{
			return 0f;
		}
		if (InRangeWrap(t, h.Night, h.Sunrise))
		{
			return 1f;
		}
		if (InRangeSameDay(t, h.Sunset, h.Night))
		{
			float num = h.Night - h.Sunset;
			if (num <= 0f)
			{
				return 1f;
			}
			return SmootherStep((t - h.Sunset) / num);
		}
		if (InRangeSameDay(t, h.Sunrise, h.Afternoon))
		{
			float num2 = h.Afternoon - h.Sunrise;
			if (num2 <= 0f)
			{
				return 0f;
			}
			return 1f - SmootherStep((t - h.Sunrise) / num2);
		}
		return 0f;
	}

	internal static bool InRangeSameDay(float t, float start, float end)
	{
		if (start >= end)
		{
			return false;
		}
		return t >= start && t < end;
	}

	internal static bool InRangeWrap(float t, float start, float end)
	{
		if (start <= end)
		{
			return t >= start && t < end;
		}
		return t >= start || t < end;
	}

	internal static DayCyclePhase GetCurrentPhase(float timeOfDay)
	{
		if (PluginSettings.Preset == DarknessPreset.FullDark)
		{
			return DayCyclePhase.PitchBlack;
		}
		DayNightHours cycleHours = PluginSettings.CycleHours;
		float t = NormalizeHour(timeOfDay);
		if (InRangeSameDay(t, cycleHours.Afternoon, cycleHours.Sunset))
		{
			return DayCyclePhase.Afternoon;
		}
		if (InRangeWrap(t, cycleHours.Night, cycleHours.Sunrise))
		{
			return DayCyclePhase.Night;
		}
		if (InRangeSameDay(t, cycleHours.Sunset, cycleHours.Night))
		{
			return DayCyclePhase.Sunset;
		}
		if (InRangeSameDay(t, cycleHours.Sunrise, cycleHours.Afternoon))
		{
			return DayCyclePhase.Sunrise;
		}
		return DayCyclePhase.Afternoon;
	}

	internal static string GetPhaseLabel(DayCyclePhase phase)
	{
		return phase switch
		{
			DayCyclePhase.Sunrise => "Sunrise", 
			DayCyclePhase.Afternoon => "Afternoon", 
			DayCyclePhase.Sunset => "Sunset", 
			DayCyclePhase.Night => "Night", 
			_ => "Pitch Black", 
		};
	}

	private static float NormalizeHour(float t)
	{
		t %= 24f;
		if (t < 0f)
		{
			t += 24f;
		}
		return t;
	}

	internal static float SmoothStep(float t)
	{
		t = Mathf.Clamp01(t);
		return t * t * (3f - 2f * t);
	}

	internal static float SmootherStep(float t)
	{
		t = Mathf.Clamp01(t);
		return t * t * t * (t * (t * 6f - 15f) + 10f);
	}

	internal static void ForceUpdate()
	{
		if (PitchBlackRuntime.ShouldApplyModEffects() && !((Object)(object)DayNightManager.instance == (Object)null))
		{
			UpdateWeight(DayNightManager.instance.timeOfDay);
			ApplyForCurrentState(DayNightManager.instance, forceOneShots: true);
		}
	}

	internal static void ForceFullSyncRebuild()
	{
		if (PitchBlackRuntime.ShouldApplyModEffects() && !((Object)(object)DayNightManager.instance == (Object)null))
		{
			_lastPreset = (DarknessPreset)(-1);
			SceneDarknessCache.Clear();
			NightGlobals.OnSceneLoadReset();
			SkyMaterialController.ResetSnapshot();
			UpdateWeight(DayNightManager.instance.timeOfDay);
			ApplyForCurrentState(DayNightManager.instance, forceOneShots: true);
		}
	}

	internal static void ApplyLiveSettings()
	{
		if (PitchBlackRuntime.ShouldApplyModEffects() && !((Object)(object)DayNightManager.instance == (Object)null))
		{
			_lastPreset = (DarknessPreset)(-1);
			SceneDarknessCache.RefreshCelestialForCurrentSettings();
			NightGlobals.RestoreScheduledEffects();
			SkyMaterialController.ResetSnapshot();
			UpdateWeight(DayNightManager.instance.timeOfDay);
			ApplyForCurrentState(DayNightManager.instance, forceOneShots: true);
		}
	}

	internal static void ApplyHostTimeOfDay(float timeOfDay)
	{
		if (!((Object)(object)DayNightManager.instance == (Object)null))
		{
			DayNightManager.instance.timeOfDay = ((PluginSettings.Preset == DarknessPreset.FullDark) ? 0f : timeOfDay);
		}
	}

	internal static void ApplyForCurrentState(DayNightManager manager, bool forceOneShots = false)
	{
		if ((Object)(object)manager == (Object)null)
		{
			return;
		}
		if (!PitchBlackRuntime.ShouldApplyModEffects())
		{
			SceneDarknessCache.RestoreCelestialBlackout();
			NightGlobals.RestoreScheduledEffects();
			return;
		}
		HandlePresetChange(forceOneShots);
		SceneDarknessCache.EnsureBuilt();
		if (PluginSettings.Preset == DarknessPreset.FullDark)
		{
			bool flag = ShouldHideCelestial(1f);
			SceneDarknessCache.UpdateCelestialBlackout(flag, forceOneShots);
			NightGlobals.ApplyFullDarknessPerFrame(manager, flag);
			NightGlobals.ClampLavaAlpha();
			return;
		}
		float currentWeight = CurrentWeight;
		if (currentWeight <= 0.001f)
		{
			SceneDarknessCache.UpdateCelestialBlackout(hide: false, forceOneShots);
			if (SceneDarknessCache.ScheduledEffectsActive)
			{
				NightGlobals.RestoreScheduledEffects();
			}
		}
		else
		{
			bool flag2 = ShouldHideCelestial(currentWeight);
			SceneDarknessCache.UpdateCelestialBlackout(flag2, forceOneShots);
			NightGlobals.ApplyScheduledDarkness(manager, currentWeight, NightVisionState.HasNightVision, flag2);
			NightGlobals.ClampLavaAlpha();
		}
	}

	internal static bool ShouldHideCelestial(float weight)
	{
		if (PluginSettings.ShowCelestialSky)
		{
			return false;
		}
		if (PluginSettings.Preset == DarknessPreset.FullDark)
		{
			return true;
		}
		return weight >= 0.97f;
	}

	private static void HandlePresetChange(bool forceOneShots)
	{
		DarknessPreset preset = PluginSettings.Preset;
		if (forceOneShots || preset != _lastPreset)
		{
			if (_lastPreset == DarknessPreset.FullDark && preset != DarknessPreset.FullDark)
			{
				SceneDarknessCache.RestoreCelestialBlackout();
			}
			if (_lastPreset != DarknessPreset.FullDark && preset == DarknessPreset.FullDark)
			{
				SceneDarknessCache.ResetCelestialBlackoutFlag();
			}
			if (_lastPreset != (DarknessPreset)(-1) && preset != _lastPreset)
			{
				NightGlobals.RestoreScheduledEffects();
			}
			_lastPreset = preset;
		}
	}

	internal static void OnSceneLoadReset()
	{
		_lastPreset = (DarknessPreset)(-1);
		SceneDarknessCache.Clear();
		NightGlobals.OnSceneLoadReset();
	}

	internal static void OnNetworkSyncApplied()
	{
		_lastPreset = (DarknessPreset)(-1);
		SceneDarknessCache.RefreshCelestialForCurrentSettings();
		NightGlobals.OnSceneLoadReset();
		SkyMaterialController.ResetSnapshot();
	}
}
internal static class SceneDarknessCache
{
	private sealed class CachedCamera
	{
		internal Camera Cam;

		internal CameraClearFlags OrigClear;

		internal Color OrigBackground;

		internal Skybox Skybox;

		internal bool OrigSkyboxEnabled;
	}

	private sealed class CachedLight
	{
		internal Light Light;

		internal float OrigIntensity;

		internal bool OrigEnabled;
	}

	private sealed class CachedObject
	{
		internal GameObject Go;

		internal bool WasActive;
	}

	private static readonly List<CachedCamera> Cameras = new List<CachedCamera>();

	private static readonly List<CachedLight> DirectionalLights = new List<CachedLight>();

	private static readonly List<CachedObject> SkyTokenObjects = new List<CachedObject>();

	private static readonly List<CachedObject> MirrorMountains = new List<CachedObject>();

	private static readonly string[] SkyTokens = new string[6] { "sky", "cloud", "clouds", "stars", "atmosphere", "atmo" };

	private static bool _built;

	internal static AmbientMode OrigAmbientMode;

	internal static Color OrigAmbientLight;

	internal static float OrigAmbientIntensity;

	internal static float OrigReflectionIntensity;

	internal static Texture OrigCustomReflection;

	internal static Material OrigSkyboxMat;

	internal static Light OrigRenderSun;

	internal static bool RenderSettingsSaved;

	internal static bool CelestialBlackoutApplied { get; private set; }

	internal static bool ScheduledEffectsActive { get; private set; }

	internal static bool MirrorMountainsHidden { get; private set; }

	internal static bool IsHotBiome { get; private set; }

	internal static void Clear()
	{
		if (CelestialBlackoutApplied)
		{
			RestoreCelestialBlackout();
		}
		else if (ScheduledEffectsActive)
		{
			RestoreScheduledState();
		}
		Cameras.Clear();
		DirectionalLights.Clear();
		SkyTokenObjects.Clear();
		MirrorMountains.Clear();
		_built = false;
		CelestialBlackoutApplied = false;
		ScheduledEffectsActive = false;
		MirrorMountainsHidden = false;
		RenderSettingsSaved = false;
		IsHotBiome = false;
	}

	internal static void RefreshCelestialForCurrentSettings()
	{
		EnsureBuilt();
		if (CelestialBlackoutApplied)
		{
			RestoreCelestialBlackout();
		}
	}

	internal static void EnsureBuilt()
	{
		if (!_built)
		{
			Build();
		}
	}

	internal static void ResetCelestialBlackoutFlag()
	{
		CelestialBlackoutApplied = false;
	}

	internal static void UpdateCelestialBlackout(bool hide, bool force)
	{
		if (hide)
		{
			if (force || !CelestialBlackoutApplied)
			{
				ApplyCelestialBlackoutOneShots();
			}
		}
		else if (CelestialBlackoutApplied)
		{
			RestoreCelestialBlackout();
		}
		else if (force)
		{
			RestoreRenderSettings();
		}
	}

	private static void Build()
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Invalid comparison between Unknown and I4
		try
		{
			SnapshotRenderSettings();
			Camera[] array = Object.FindObjectsByType<Camera>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			foreach (Camera val in array)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					Skybox component = ((Component)val).GetComponent<Skybox>();
					Cameras.Add(new CachedCamera
					{
						Cam = val,
						OrigClear = val.clearFlags,
						OrigBackground = val.backgroundColor,
						Skybox = component,
						OrigSkyboxEnabled = (Object.op_Implicit((Object)(object)component) && ((Behaviour)component).enabled)
					});
				}
			}
			Light[] array2 = Object.FindObjectsByType<Light>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			foreach (Light val2 in array2)
			{
				if (Object.op_Implicit((Object)(object)val2))
				{
					string text = (((Object)val2).name ?? "").ToLowerInvariant();
					if ((int)val2.type == 1 || text.Contains("sun") || text.Contains("moon"))
					{
						DirectionalLights.Add(new CachedLight
						{
							Light = val2,
							OrigIntensity = val2.intensity,
							OrigEnabled = ((Behaviour)val2).enabled
						});
					}
				}
			}
			CollectSkyTokenObjects();
			CollectMirrorMountains();
			IsHotBiome = (Object)(object)Object.FindAnyObjectByType<Lava>((FindObjectsInactive)1) != (Object)null || (Object)(object)Object.FindAnyObjectByType<LavaPost>((FindObjectsInactive)1) != (Object)null;
		}
		catch
		{
		}
		_built = true;
	}

	private static void SnapshotRenderSettings()
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//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_001b: Unknown result type (might be due to invalid IL or missing references)
		if (!RenderSettingsSaved)
		{
			OrigAmbientMode = RenderSettings.ambientMode;
			OrigAmbientLight = RenderSettings.ambientLight;
			OrigAmbientIntensity = RenderSettings.ambientIntensity;
			OrigReflectionIntensity = RenderSettings.reflectionIntensity;
			OrigCustomReflection = RenderSettings.customReflectionTexture;
			OrigSkyboxMat = RenderSettings.skybox;
			OrigRenderSun = RenderSettings.sun;
			RenderSettingsSaved = true;
		}
	}

	private static void CollectSkyTokenObjects()
	{
		HashSet<int> hashSet = new HashSet<int>();
		Transform[] array = Object.FindObjectsByType<Transform>((FindObjectsInactive)1, (FindObjectsSortMode)0);
		foreach (Transform val in array)
		{
			if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)((Component)val).gameObject) || IsUnderCanvas(val))
			{
				continue;
			}
			string text = (((Object)val).name ?? "").ToLowerInvariant();
			bool flag = false;
			for (int j = 0; j < SkyTokens.Length; j++)
			{
				if (text.Contains(SkyTokens[j]))
				{
					flag = true;
					break;
				}
			}
			if (flag)
			{
				int instanceID = ((Object)((Component)val).gameObject).GetInstanceID();
				if (hashSet.Add(instanceID))
				{
					SkyTokenObjects.Add(new CachedObject
					{
						Go = ((Component)val).gameObject,
						WasActive = ((Component)val).gameObject.activeSelf
					});
				}
			}
		}
	}

	private static void CollectMirrorMountains()
	{
		HashSet<int> hashSet = new HashSet<int>();
		Transform[] array = Object.FindObjectsByType<Transform>((FindObjectsInactive)1, (FindObjectsSortMode)0);
		foreach (Transform val in array)
		{
			if (!Object.op_Implicit((Object)(object)val))
			{
				continue;
			}
			string text = (((Object)val).name ?? "").ToLowerInvariant();
			if (text != "map" && !text.Contains("[g] map"))
			{
				continue;
			}
			Transform[] componentsInChildren = ((Component)val).GetComponentsInChildren<Transform>(true);
			foreach (Transform val2 in componentsInChildren)
			{
				if (Object.op_Implicit((Object)(object)val2) && !IsUnderCanvas(val2) && (((Object)val2).name ?? "").ToLowerInvariant().Contains("mountains"))
				{
					int instanceID = ((Object)((Component)val2).gameObject).GetInstanceID();
					if (hashSet.Add(instanceID))
					{
						MirrorMountains.Add(new CachedObject
						{
							Go = ((Component)val2).gameObject,
							WasActive = ((Component)val2).gameObject.activeSelf
						});
					}
				}
			}
		}
	}

	internal static void ApplyCelestialBlackoutOneShots()
	{
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		if (CelestialBlackoutApplied)
		{
			return;
		}
		for (int i = 0; i < Cameras.Count; i++)
		{
			CachedCamera cachedCamera = Cameras[i];
			if (Object.op_Implicit((Object)(object)cachedCamera.Cam))
			{
				cachedCamera.Cam.clearFlags = (CameraClearFlags)2;
				cachedCamera.Cam.backgroundColor = Color.black;
				if (Object.op_Implicit((Object)(object)cachedCamera.Skybox))
				{
					((Behaviour)cachedCamera.Skybox).enabled = false;
				}
			}
		}
		RenderSettings.ambientMode = (AmbientMode)3;
		RenderSettings.ambientLight = Color.black;
		RenderSettings.ambientIntensity = 0f;
		RenderSettings.reflectionIntensity = 0f;
		RenderSettings.customReflectionTexture = null;
		RenderSettings.skybox = null;
		RenderSettings.sun = null;
		for (int j = 0; j < DirectionalLights.Count; j++)
		{
			CachedLight cachedLight = DirectionalLights[j];
			if (Object.op_Implicit((Object)(object)cachedLight.Light))
			{
				cachedLight.Light.intensity = 0f;
				((Behaviour)cachedLight.Light).enabled = false;
			}
		}
		for (int k = 0; k < SkyTokenObjects.Count; k++)
		{
			CachedObject cachedObject = SkyTokenObjects[k];
			if (Object.op_Implicit((Object)(object)cachedObject.Go))
			{
				cachedObject.Go.SetActive(false);
			}
		}
		SetMirrorMountainsHidden(hide: true);
		CelestialBlackoutApplied = true;
		ScheduledEffectsActive = false;
	}

	internal static void RestoreCelestialBlackout()
	{
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		if (!CelestialBlackoutApplied)
		{
			return;
		}
		for (int i = 0; i < Cameras.Count; i++)
		{
			CachedCamera cachedCamera = Cameras[i];
			if (Object.op_Implicit((Object)(object)cachedCamera.Cam))
			{
				cachedCamera.Cam.clearFlags = cachedCamera.OrigClear;
				cachedCamera.Cam.backgroundColor = cachedCamera.OrigBackground;
				if (Object.op_Implicit((Object)(object)cachedCamera.Skybox))
				{
					((Behaviour)cachedCamera.Skybox).enabled = cachedCamera.OrigSkyboxEnabled;
				}
			}
		}
		RestoreRenderSettings();
		for (int j = 0; j < DirectionalLights.Count; j++)
		{
			CachedLight cachedLight = DirectionalLights[j];
			if (Object.op_Implicit((Object)(object)cachedLight.Light))
			{
				cachedLight.Light.intensity = cachedLight.OrigIntensity;
				((Behaviour)cachedLight.Light).enabled = cachedLight.OrigEnabled;
			}
		}
		for (int k = 0; k < SkyTokenObjects.Count; k++)
		{
			CachedObject cachedObject = SkyTokenObjects[k];
			if (Object.op_Implicit((Object)(object)cachedObject.Go))
			{
				cachedObject.Go.SetActive(cachedObject.WasActive);
			}
		}
		CelestialBlackoutApplied = false;
	}

	internal static void RestoreScheduledState()
	{
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		RestoreRenderSettings();
		for (int i = 0; i < Cameras.Count; i++)
		{
			CachedCamera cachedCamera = Cameras[i];
			if (Object.op_Implicit((Object)(object)cachedCamera.Cam))
			{
				cachedCamera.Cam.clearFlags = cachedCamera.OrigClear;
				cachedCamera.Cam.backgroundColor = cachedCamera.OrigBackground;
				if (Object.op_Implicit((Object)(object)cachedCamera.Skybox))
				{
					((Behaviour)cachedCamera.Skybox).enabled = cachedCamera.OrigSkyboxEnabled;
				}
			}
		}
		SetMirrorMountainsHidden(hide: false);
		ScheduledEffectsActive = false;
	}

	internal static void RestoreRenderSettings()
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		if (RenderSettingsSaved)
		{
			RenderSettings.ambientMode = OrigAmbientMode;
			RenderSettings.ambientLight = OrigAmbientLight;
			RenderSettings.ambientIntensity = OrigAmbientIntensity;
			RenderSettings.reflectionIntensity = OrigReflectionIntensity;
			RenderSettings.customReflectionTexture = OrigCustomReflection;
			RenderSettings.skybox = OrigSkyboxMat;
			RenderSettings.sun = OrigRenderSun;
		}
	}

	internal static void ApplyScheduledRenderSettings(float w)
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		if (RenderSettingsSaved)
		{
			if (w >= 0.999f)
			{
				ApplyPitchBlackWorldKeepSky();
				ScheduledEffectsActive = true;
				return;
			}
			RenderSettings.ambientMode = OrigAmbientMode;
			RenderSettings.ambientLight = Color.Lerp(OrigAmbientLight, Color.black, w);
			RenderSettings.ambientIntensity = Mathf.Lerp(OrigAmbientIntensity, 0f, w);
			RenderSettings.reflectionIntensity = Mathf.Lerp(OrigReflectionIntensity, 0f, w);
			RenderSettings.skybox = OrigSkyboxMat ?? RenderSettings.skybox;
			RenderSettings.sun = OrigRenderSun ?? RenderSettings.sun;
			ScheduledEffectsActive = w > 0.001f;
		}
	}

	internal static void ApplyPitchBlackWorldKeepSky()
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		if (RenderSettingsSaved)
		{
			RenderSettings.ambientMode = (AmbientMode)3;
			RenderSettings.ambientLight = Color.black;
			RenderSettings.ambientIntensity = 0f;
			RenderSettings.reflectionIntensity = 0f;
			RenderSettings.customReflectionTexture = null;
			RenderSettings.skybox = OrigSkyboxMat ?? RenderSettings.skybox;
			RenderSettings.sun = null;
			ScheduledEffectsActive = true;
		}
	}

	internal static void SuppressDirectionalSceneLights()
	{
		for (int i = 0; i < DirectionalLights.Count; i++)
		{
			CachedLight cachedLight = DirectionalLights[i];
			if (Object.op_Implicit((Object)(object)cachedLight.Light))
			{
				cachedLight.Light.intensity = 0f;
				((Behaviour)cachedLight.Light).enabled = false;
			}
		}
	}

	internal static void EnsureSkyboxesEnabled()
	{
		for (int i = 0; i < Cameras.Count; i++)
		{
			CachedCamera cachedCamera = Cameras[i];
			if (Object.op_Implicit((Object)(object)cachedCamera.Skybox))
			{
				((Behaviour)cachedCamera.Skybox).enabled = true;
			}
		}
	}

	internal static void SetMirrorMountainsHidden(bool hide)
	{
		if (hide == MirrorMountainsHidden)
		{
			return;
		}
		for (int i = 0; i < MirrorMountains.Count; i++)
		{
			CachedObject cachedObject = MirrorMountains[i];
			if (Object.op_Implicit((Object)(object)cachedObject.Go))
			{
				if (hide)
				{
					cachedObject.Go.SetActive(false);
				}
				else
				{
					cachedObject.Go.SetActive(cachedObject.WasActive);
				}
			}
		}
		MirrorMountainsHidden = hide;
	}

	private static bool IsUnderCanvas(Transform tr)
	{
		try
		{
			return Object.op_Implicit((Object)(object)tr) && (Object)(object)((Component)tr).GetComponentInParent<Canvas>(true) != (Object)null;
		}
		catch
		{
			return false;
		}
	}
}
internal static class SkyMaterialController
{
	private static Material _skyMat;

	private static Color _origCloudDensity;

	private static bool _snapshotted;

	private static readonly Color DarkCloudDensity = new Color(0.1f, 0.1f, 0.1f, 0f);

	internal static void EnsureSnapshot()
	{
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		if (_snapshotted)
		{
			return;
		}
		_skyMat = RenderSettings.skybox;
		if (Object.op_Implicit((Object)(object)_skyMat))
		{
			if (_skyMat.HasProperty("_CloudDensity"))
			{
				_origCloudDensity = _skyMat.GetColor("_CloudDensity");
			}
			_snapshotted = true;
		}
	}

	internal static void Apply(float w)
	{
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		EnsureSnapshot();
		_skyMat = RenderSettings.skybox ?? _skyMat;
		if (Object.op_Implicit((Object)(object)_skyMat))
		{
			if (_skyMat.HasProperty("_CloudDensity"))
			{
				_skyMat.SetColor("_CloudDensity", Color.Lerp(_origCloudDensity, DarkCloudDensity, w));
			}
		}
	}

	internal static void Restore()
	{
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		_skyMat = RenderSettings.skybox ?? _skyMat;
		if (_snapshotted && Object.op_Implicit((Object)(object)_skyMat) && _skyMat.HasProperty("_CloudDensity"))
		{
			_skyMat.SetColor("_CloudDensity", _origCloudDensity);
		}
	}

	internal static void ResetSnapshot()
	{
		_snapshotted = false;
		_skyMat = null;
	}
}
internal static class NightGlobals
{
	private static readonly int ID_Brightness = Shader.PropertyToID("brightness");

	private static readonly int ID_AmbienceStrength = Shader.PropertyToID("ambienceStrength");

	private static readonly int ID_AmbienceMin = Shader.PropertyToID("ambienceMin");

	private static readonly int ID_BrightnessAlt = Shader.PropertyToID("_Brightness");

	private static readonly int ID_AmbienceStrengthAlt = Shader.PropertyToID("_AmbienceStrength");

	private static readonly int ID_AmbienceMinAlt = Shader.PropertyToID("_AmbienceMin");

	private static readonly int ID_LavaAlpha = Shader.PropertyToID("LavaAlpha");

	internal static readonly Color SkyBlack = Color.black;

	internal const float AmbientMin = 0f;

	internal const float NightSfxHour = 23.8f;

	internal const float FullDarkLockedHour = 0f;

	internal const float LavaAlphaNormal = 0.75f;

	internal const float LavaAlphaHotBiome = 1f;

	internal static void ApplyFullDarknessPerFrame(DayNightManager manager, bool hideCelestial)
	{
		if (hideCelestial)
		{
			ApplySkyBlackout(manager);
		}
		else
		{
			ApplyCelestialPreservedDarkness(manager);
		}
		ApplyWorldAmbient(NightVisionState.HasNightVision, 1f);
	}

	private static void ApplyCelestialPreservedDarkness(DayNightManager manager)
	{
		ApplyDimmedSky(1f);
		SceneDarknessCache.ApplyPitchBlackWorldKeepSky();
		SceneDarknessCache.EnsureSkyboxesEnabled();
		SceneDarknessCache.SuppressDirectionalSceneLights();
		SceneDarknessCache.SetMirrorMountainsHidden(hide: true);
		DisableCelestialWorldLights(manager);
		SkyMaterialController.Apply(1f);
	}

	private static void ApplySkyBlackout(DayNightManager dnm)
	{
		//IL_0006: 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_0026: Unknown result type (might be due to invalid IL or missing references)
		Shader.SetGlobalColor(DayNightManager.SkyTopColor, SkyBlack);
		Shader.SetGlobalColor(DayNightManager.SkyMidColor, SkyBlack);
		Shader.SetGlobalColor(DayNightManager.SkyBottomColor, SkyBlack);
		Shader.SetGlobalFloat(DayNightManager.FOG, 0f);
		Shader.SetGlobalFloat(DayNightManager.Name, 0f);
		Shader.SetGlobalInt(DayNightManager.IsDayReal, 0);
		Shader.SetGlobalFloat("_GlobalHazeAmount", 0f);
		Shader.SetGlobalFloat("RimFresnelIntensity", 0f);
		Shader.SetGlobalFloat("BandFogAmount", 0f);
		Shader.SetGlobalFloat("SunSizeMult", 0f);
		try
		{
			if (!((Object)(object)dnm == (Object)null))
			{
				if (Object.op_Implicit((Object)(object)dnm.sun))
				{
					dnm.sun.intensity = 0f;
					((Behaviour)dnm.sun).enabled = false;
				}
				if (Object.op_Implicit((Object)(object)dnm.moon))
				{
					dnm.moon.intensity = 0f;
					((Behaviour)dnm.moon).enabled = false;
				}
				if (Object.op_Implicit((Object)(object)dnm.lensFlare))
				{
					dnm.lensFlare.intensity = 0f;
				}
			}
		}
		catch
		{
		}
	}

	internal static void ApplyScheduledDarkness(DayNightManager manager, float weight, bool hasNightVision, bool hideCelestial)
	{
		float num = Mathf.Clamp01(weight);
		ApplyWorldAmbient(hasNightVision, num);
		if (hideCelestial)
		{
			ApplySkyBlackout(manager);
		}
		else
		{
			ApplyDimmedSky(num);
			SkyMaterialController.Apply(num);
			SceneDarknessCache.ApplyScheduledRenderSettings(num);
			SceneDarknessCache.EnsureSkyboxesEnabled();
			if (num >= 0.97f)
			{
				SceneDarknessCache.SuppressDirectionalSceneLights();
				DisableCelestialWorldLights(manager);
			}
			else
			{
				DimCelestialLighting(manager, num);
			}
		}
		if (!hideCelestial)
		{
			SceneDarknessCache.SetMirrorMountainsHidden(num > 0.97f);
		}
	}

	internal static void ApplyAmbientDark(bool hasNightVision)
	{
		if (PluginSettings.Preset == DarknessPreset.FullDark)
		{
			ApplyWorldAmbient(hasNightVision, 1f);
			return;
		}
		float currentWeight = EnvironmentController.CurrentWeight;
		if (!(currentWeight <= 0.001f))
		{
			ApplyWorldAmbient(hasNightVision, Mathf.Clamp01(currentWeight));
		}
	}

	private static void ApplyWorldAmbient(bool hasNightVision, float w)
	{
		float num = (hasNightVision ? 0.35f : PluginSettings.DarknessMultiplier);
		float num2 = (hasNightVision ? 0.35f : PluginSettings.DarknessMultiplier);
		float num3 = (hasNightVision ? 0.03f : 0f);
		float num4 = Mathf.Lerp(1f, num, w);
		float num5 = Mathf.Lerp(1f, num2, w);
		float num6 = Mathf.Lerp(0.2f, num3, w);
		Shader.SetGlobalFloat(ID_Brightness, num4);
		Shader.SetGlobalFloat(ID_AmbienceStrength, num5);
		Shader.SetGlobalFloat(ID_AmbienceMin, num6);
		Shader.SetGlobalFloat(ID_BrightnessAlt, num4);
		Shader.SetGlobalFloat(ID_AmbienceStrengthAlt, num5);
		Shader.SetGlobalFloat(ID_AmbienceMinAlt, num6);
	}

	private static void ApplyDimmedSky(float w)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//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_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: 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_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: 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_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: 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_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		Color globalColor = Shader.GetGlobalColor(DayNightManager.SkyTopColor);
		Color globalColor2 = Shader.GetGlobalColor(DayNightManager.SkyMidColor);
		Color globalColor3 = Shader.GetGlobalColor(DayNightManager.SkyBottomColor);
		Shader.SetGlobalColor(DayNightManager.SkyTopColor, Color.Lerp(globalColor, SkyBlack, w));
		Shader.SetGlobalColor(DayNightManager.SkyMidColor, Color.Lerp(globalColor2, SkyBlack, w));
		Shader.SetGlobalColor(DayNightManager.SkyBottomColor, Color.Lerp(globalColor3, SkyBlack, w));
		float globalFloat = Shader.GetGlobalFloat(DayNightManager.FOG);
		Shader.SetGlobalFloat(DayNightManager.FOG, Mathf.Lerp(globalFloat, 0f, w));
		SetGlobalFloat("_GlobalHazeAmount", Mathf.Lerp(SafeGlobalFloat("_GlobalHazeAmount"), 0f, w));
		SetGlobalFloat("RimFresnelIntensity", Mathf.Lerp(SafeGlobalFloat("RimFresnelIntensity"), 0f, w));
		SetGlobalFloat("BandFogAmount", Mathf.Lerp(SafeGlobalFloat("BandFogAmount"), 0f, w));
	}

	private static float SafeGlobalFloat(string name)
	{
		try
		{
			return Shader.GetGlobalFloat(name);
		}
		catch
		{
			return 0f;
		}
	}

	private static void DimCelestialLighting(DayNightManager manager, float w)
	{
		if ((Object)(object)manager == (Object)null)
		{
			return;
		}
		float num = Mathf.Lerp(1f, 0f, w);
		try
		{
			if (Object.op_Implicit((Object)(object)manager.sun))
			{
				Light sun = manager.sun;
				sun.intensity *= num;
				((Behaviour)manager.sun).enabled = num > 0.02f;
			}
			if (Object.op_Implicit((Object)(object)manager.moon))
			{
				Light moon = manager.moon;
				moon.intensity *= num;
				((Behaviour)manager.moon).enabled = num > 0.02f;
			}
			if (Object.op_Implicit((Object)(object)manager.lensFlare))
			{
				LensFlareComponentSRP lensFlare = manager.lensFlare;
				lensFlare.intensity *= num;
			}
		}
		catch
		{
		}
	}

	private static void DisableCelestialWorldLights(DayNightManager manager)
	{
		if ((Object)(object)manager == (Object)null)
		{
			return;
		}
		try
		{
			if (Object.op_Implicit((Object)(object)manager.sun))
			{
				manager.sun.intensity = 0f;
				((Behaviour)manager.sun).enabled = false;
			}
			if (Object.op_Implicit((Object)(object)manager.moon))
			{
				manager.moon.intensity = 0f;
				((Behaviour)manager.moon).enabled = false;
			}
			if (Object.op_Implicit((Object)(object)manager.lensFlare))
			{
				manager.lensFlare.intensity = 0f;
			}
		}
		catch
		{
		}
	}

	internal static void RestoreWorldAmbient()
	{
		Shader.SetGlobalFloat(ID_Brightness, 1f);
		Shader.SetGlobalFloat(ID_AmbienceStrength, 1f);
		Shader.SetGlobalFloat(ID_AmbienceMin, 0.2f);
		Shader.SetGlobalFloat(ID_BrightnessAlt, 1f);
		Shader.SetGlobalFloat(ID_AmbienceStrengthAlt, 1f);
		Shader.SetGlobalFloat(ID_AmbienceMinAlt, 0.2f);
	}

	internal static void RestoreScheduledEffects()
	{
		SkyMaterialController.Restore();
		SceneDarknessCache.RestoreScheduledState();
		RestoreWorldAmbient();
	}

	private static void SetGlobalFloat(string name, float value)
	{
		try
		{
			Shader.SetGlobalFloat(name, value);
		}
		catch
		{
		}
	}

	private static void LerpGlobalFloat(string name, float target, float w)
	{
		try
		{
			float globalFloat = Shader.GetGlobalFloat(name);
			Shader.SetGlobalFloat(name, Mathf.Lerp(globalFloat, target, w));
		}
		catch
		{
		}
	}

	internal static void OnSceneLoadReset()
	{
		SkyMaterialController.ResetSnapshot();
	}

	internal static void ClampLavaAlpha()
	{
		float num = (SceneDarknessCache.IsHotBiome ? 1f : 0.75f);
		try
		{
			float globalFloat = Shader.GetGlobalFloat(ID_LavaAlpha);
			if (globalFloat > num)
			{
				Shader.SetGlobalFloat(ID_LavaAlpha, num);
			}
		}
		catch
		{
			Shader.SetGlobalFloat(ID_LavaAlpha, num);
		}
	}

	internal static void ForceNightAmbience(AmbienceAudio a)
	{
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)a) || !Object.op_Implicit((Object)(object)a.ambienceVolumes))
		{
			return;
		}
		try
		{
			a.ambienceVolumes.SetFloat("Height", ((Component)a).transform.position.y);
			float num = ((PluginSettings.Preset == DarknessPreset.FullDark) ? 0f : ((EnvironmentController.CurrentWeight >= 0.5f) ? 23.8f : (DayNightManager.instance?.timeOfDay ?? 12f)));
			a.ambienceVolumes.SetFloat("Time", num);
			a.ambienceVolumes.SetBool("Tomb", a.inTomb);
			a.ambienceVolumes.SetBool("Natureless", false);
			a.ambienceVolumes.SetBool("Volcano", a.volcano);
		}
		catch
		{
		}
	}
}
internal static class StarterLantern
{
	internal const ushort StandardLanternId = 42;

	private const string PrefabName = "Lantern";

	private static bool _given;

	internal static void ResetSession()
	{
		_given = false;
	}

	internal static bool IsAirportScene()
	{
		//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)
		try
		{
			Character localCharacter = Character.localCharacter;
			if ((Object)(object)localCharacter != (Object)null && localCharacter.inAirport)
			{
				return true;
			}
		}
		catch
		{
		}
		Scene activeScene = SceneManager.GetActiveScene();
		string text = ((Scene)(ref activeScene)).name ?? string.Empty;
		return text.IndexOf("airport", StringComparison.OrdinalIgnoreCase) >= 0;
	}

	internal static bool IsLevelScene()
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		Scene activeScene = SceneManager.GetActiveScene();
		string text = ((Scene)(ref activeScene)).name ?? string.Empty;
		return text.StartsWith("level_", StringComparison.OrdinalIgnoreCase);
	}

	internal static bool ShouldAutoGiveForCurrentScene()
	{
		if (IsAirportScene())
		{
			return true;
		}
		if (IsLevelScene())
		{
			return PluginSettings.StartWithLantern;
		}
		return false;
	}

	internal static IEnumerator GiveAfterDelay(float seconds)
	{
		yield return (object)new WaitForSeconds(seconds);
		TryGive();
	}

	internal static void TryGive()
	{
		if (!PitchBlackRuntime.ShouldApplyModEffects() || _given || !ShouldAutoGiveForCurrentScene())
		{
			return;
		}
		Character localCharacter = Character.localCharacter;
		if ((Object)(object)localCharacter == (Object)null || HasStandardLantern(localCharacter))
		{
			return;
		}
		try
		{
			localCharacter.refs.items.SpawnItemInHand("Lantern");
			_given = true;
		}
		catch
		{
		}
	}

	private static bool HasStandardLantern(Character ch)
	{
		try
		{
			CharacterData data = ch.data;
			if ((Object)(object)((data != null) ? data.currentItem : null) != (Object)null && ch.data.currentItem.itemID == 42)
			{
				return true;
			}
			ItemSlot[] array = ch.player.itemSlots ?? Array.Empty<ItemSlot>();
			for (byte b = 0; b < array.Length; b++)
			{
				ItemSlot obj = array[b];
				Item val = ((obj != null) ? obj.prefab : null);
				if ((Object)(object)val != (Object)null && val.itemID == 42)
				{
					return true;
				}
			}
		}
		catch
		{
		}
		return false;
	}
}
internal static class LanternVisuals
{
	private static readonly Dictionary<int, Color> ColorsByViewId = new Dictionary<int, Color>();

	internal static bool IsStandardLantern(Lantern ln)
	{
		try
		{
			return (Object)(object)ln?.item != (Object)null && ln.item.itemID == 42;
		}
		catch
		{
			return false;
		}
	}

	internal static bool IsTorch(Lantern ln)
	{
		object obj;
		if (ln == null)
		{
			obj = null;
		}
		else
		{
			Item item = ln.item;
			if (item == null)
			{
				obj = null;
			}
			else
			{
				GameObject gameObject = ((Component)item).gameObject;
				obj = ((gameObject != null) ? ((Object)gameObject).name : null);
			}
		}
		if (obj == null)
		{
			obj = string.Empty;
		}
		string text = (string)obj;
		return text.IndexOf("torch", StringComparison.OrdinalIgnoreCase) >= 0;
	}

	internal static bool IsFaerie(Lantern ln)
	{
		object obj;
		if (ln == null)
		{
			obj = null;
		}
		else
		{
			Item item = ln.item;
			if (item == null)
			{
				obj = null;
			}
			else
			{
				GameObject gameObject = ((Component)item).gameObject;
				obj = ((gameObject != null) ? ((Object)gameObject).name : null);
			}
		}
		if (obj == null)
		{
			obj = string.Empty;
		}
		string text = (string)obj;
		return text.IndexOf("faerie", StringComparison.OrdinalIgnoreCase) >= 0;
	}

	internal static Color ResolveColor(Character holder)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: 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)
		switch (PluginSettings.ColorMode)
		{
		case LanternColorMode.Custom:
			return PluginSettings.CustomColor;
		case LanternColorMode.SkinColor:
			if ((Object)(object)holder?.refs?.customization != (Object)null)
			{
				return holder.refs.customization.PlayerColor;
			}
			break;
		}
		return new Color(1f, 0.6f, 0.3f);
	}

	internal static void RememberColor(Lantern lantern, Color color)
	{
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)((lantern != null) ? ((MonoBehaviourPun)lantern).photonView : null) == (Object)null) && ((MonoBehaviourPun)lantern).photonView.ViewID > 0)
		{
			ColorsByViewId[((MonoBehaviourPun)lantern).photonView.ViewID] = color;
		}
	}

	internal static bool TryGetRememberedColor(Lantern lantern, out Color color)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		color = default(Color);
		if ((Object)(object)((lantern != null) ? ((MonoBehaviourPun)lantern).photonView : null) == (Object)null)
		{
			return false;
		}
		return ColorsByViewId.TryGetValue(((MonoBehaviourPun)lantern).photonView.ViewID, out color);
	}

	internal static Color ResolveColorForItem(Item item)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		Character holder = null;
		try
		{
			if ((Object)(object)item != (Object)null)
			{
				holder = item.holderCharacter ?? item.lastHolderCharacter;
			}
		}
		catch
		{
		}
		return ResolveColor(holder);
	}

	internal static Color GetAppliedColor(Lantern lantern, LanternLightController ctrl)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0193: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		//IL_019e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a2: 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_0035: Invalid comparison between Unknown and I4
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: 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_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: 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)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Unknown result type (might be due to invalid IL or missing references)
		//IL_017d: Unknown result type (might be due to invalid IL or missing references)
		//IL_017f: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)lantern == (Object)null)
		{
			return ResolveColor(null);
		}
		Item item = lantern.item;
		bool flag = false;
		try
		{
			flag = (Object)(object)item != (Object)null && (int)item.itemState == 1 && (Object)(object)item.holderCharacter != (Object)null;
		}
		catch
		{
		}
		if (PluginSettings.ColorMode == LanternColorMode.Custom || PluginSettings.ColorMode == LanternColorMode.Original)
		{
			Color val = ResolveColor(flag ? item.holderCharacter : null);
			LockColor(lantern, ctrl, val);
			TryWriteColorData(lantern, item, val);
			return val;
		}
		if (flag)
		{
			Color val2 = ResolveColor(item.holderCharacter);
			LockColor(lantern, ctrl, val2);
			TryWriteColorData(lantern, item, val2);
			return val2;
		}
		if ((Object)(object)ctrl != (Object)null && ctrl.HasLockedColor)
		{
			RememberColor(lantern, ctrl.LockedColor);
			return ctrl.LockedColor;
		}
		if (TryGetRememberedColor(lantern, out var color))
		{
			LockColor(lantern, ctrl, color);
			return color;
		}
		try
		{
			if (((ItemComponent)lantern).HasData((DataEntryKey)9))
			{
				ColorItemData data = ((ItemComponent)lantern).GetData<ColorItemData>((DataEntryKey)9);
				if (data != null)
				{
					Color value = data.Value;
					if (value.r + value.g + value.b > 0.01f)
					{
						LockColor(lantern, ctrl, value);
						return value;
					}
				}
			}
		}
		catch
		{
		}
		Color val3 = ResolveColorForItem(item);
		LockColor(lantern, ctrl, val3);
		return val3;
	}

	private static void LockColor(Lantern lantern, LanternLightController ctrl, Color target)
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)ctrl != (Object)null)
		{
			ctrl.LockedColor = target;
			ctrl.HasLockedColor = true;
		}
		RememberColor(lantern, target);
	}

	private static void TryWriteColorData(Lantern lantern, Item item, Color target)
	{
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if ((Object)(object)((item != null) ? ((MonoBehaviourPun)item).photonView : null) != (Object)null && ((MonoBehaviourPun)item).photonView.IsMine)
			{
				ColorItemData data = ((ItemComponent)lantern).GetData<ColorItemData>((DataEntryKey)9);
				if (data.Value != target)
				{
					data.Value = target;
				}
			}
		}
		catch
		{
		}
	}

	internal static void OnItemLeavingHand(Item item)
	{
		//IL_0031: 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_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)item == (Object)null)
		{
			return;
		}
		try
		{
			Lantern component = ((Component)item).GetComponent<Lantern>();
			if (IsStandardLantern(component))
			{
				LanternLightController component2 = ((Component)component).GetComponent<LanternLightController>();
				Color appliedColor = GetAppliedColor(component, component2);
				LockColor(component, component2, appliedColor);
				TryWriteColorData(component, item, appliedColor);
			}
		}
		catch
		{
		}
	}

	internal static void SyncColor(Lantern lantern)
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		if (IsStandardLantern(lantern) && !((Object)(object)lantern.lanternLight == (Object)null))
		{
			LanternLightController component = ((Component)lantern).GetComponent<LanternLightController>();
			Color appliedColor = GetAppliedColor(lantern, component);
			if (lantern.lanternLight.color != appliedColor)
			{
				lantern.lanternLight.color = appliedColor;
			}
			lantern.lanternLight.shadows = (LightShadows)0;
		}
	}

	internal static void ApplySyncedColor(Lantern lantern)
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		if (IsStandardLantern(lantern) && !((Object)(object)lantern.lanternLight == (Object)null))
		{
			LanternLightController component = ((Component)lantern).GetComponent<LanternLightController>();
			Color appliedColor = GetAppliedColor(lantern, component);
			if (lantern.lanternLight.color != appliedColor)
			{
				lantern.lanternLight.color = appliedColor;
			}
			LanternGloomAura.ApplyToLantern(lantern, appliedColor, lantern.lit);
		}
	}

	internal static void ForceRefreshAllColors()
	{
		if (!PitchBlackRuntime.ShouldApplyModEffects())
		{
			return;
		}
		Lantern[] array = Object.FindObjectsByType<Lantern>((FindObjectsInactive)0, (FindObjectsSortMode)0);
		foreach (Lantern val in array)
		{
			if (!((Object)(object)val == (Object)null) && !((Object)(object)((Component)val).GetComponentInParent<HipLanternVisualRoot>() != (Object)null) && IsStandardLantern(val))
			{
				Item item = val.item;
				if (!HipLanternRules.IsNpcCharacter((item != null) ? item.holderCharacter : null))
				{
					SyncColor(val);
					ApplySyncedColor(val);
				}
			}
		}
	}
}
internal class LanternLightController : MonoBehaviour, IOnEventCallback
{
	internal Lantern lantern;

	internal LanternState localMode = LanternState.Omni;

	internal LanternState remoteMode = LanternState.Omni;

	internal Color LockedColor = new Color(1f, 0.6f, 0.3f);

	internal bool HasLockedColor;

	private Light _light;

	private PhotonView _view;

	private float _smoothIntensity;

	private LanternState _lastSentMode;

	private Quaternion _remoteRot = Quaternion.identity;

	private Quaternion _lastSentRot = Quaternion.identity;

	private float _lastSyncTime;

	internal void Init(Lantern ln)
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		lantern = ln;
		_light = ln.lanternLight;
		_view = ((MonoBehaviourPun)ln).photonView;
		if (!HasLockedColor && (Object)(object)ln != (Object)null)
		{
			LockedColor = LanternVisuals.GetAppliedColor(ln, this);
			HasLockedColor = true;
		}
	}

	public void OnEvent(EventData e)
	{
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		if (e.Code == 147 && !((Object)(object)_view == (Object)null) && e.CustomData is object[] array && array.Length >= 4 && (int)array[0] == 204 && (byte)array[1] == 0 && (int)array[2] == _view.ViewID)
		{
			remoteMode = (LanternState)(byte)array[3];
			if (array.Length >= 5)
			{
				_remoteRot = (Quaternion)array[4];
			}
		}
	}

	private void OnEnable()
	{
		PhotonNetwork.AddCallbackTarget((object)this);
	}

	private void OnDisable()
	{
		PhotonNetwork.RemoveCallbackTarget((object)this);
	}

	internal void ApplyLight()
	{
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: 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_0208: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_019e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)_light) || !Object.op_Implicit((Object)(object)_view) || !Object.op_Implicit((Object)(object)lantern))
		{
			return;
		}
		Color appliedColor = LanternVisuals.GetAppliedColor(lantern, this);
		_light.color = appliedColor;
		if (!lantern.lit)
		{
			if (((Behaviour)_light).enabled)
			{
				((Behaviour)_light).enabled = false;
			}
			LanternGloomAura.ApplyToLantern(lantern, appliedColor, lit: false);
			return;
		}
		if (!((Behaviour)_light).enabled)
		{
			((Behaviour)_light).enabled = true;
		}
		bool isMine = _view.IsMine;
		LanternState lanternState = (isMine ? localMode : remoteMode);
		_smoothIntensity = Mathf.Lerp(_smoothIntensity, PluginSettings.LanternIntensity, Time.deltaTime * 5f);
		if (lanternState == LanternState.Flashlight)
		{
			_light.type = (LightType)0;
			_light.spotAngle = 45f;
			_light.range = PluginSettings.FlashlightRange;
			_light.intensity = CalcFlashIntensity(_smoothIntensity, PluginSettings.FlashlightRange);
			Quaternion val = ((!isMine) ? _remoteRot : (Object.op_Implicit((Object)(object)Camera.main) ? ((Component)Camera.main).transform.rotation : ((Component)lantern).transform.rotation));
			((Component)_light).transform.rotation = Quaternion.Slerp(((Component)_light).transform.rotation, val, Time.deltaTime * 10f);
		}
		else
		{
			_light.type = (LightType)2;
			_light.intensity = _smoothIntensity;
			_light.range = Mathf.Sqrt(_smoothIntensity / 30f) * 20f;
		}
		LanternGloomAura.ApplyToLantern(lantern, appliedColor, lit: true);
		if (isMine && lantern.lit)
		{
			HandleLocalSync(lanternState);
		}
	}

	private static float CalcFlashIntensity(float baseInt, float range)
	{
		float num = baseInt;
		if (baseInt <= 25f)
		{
			if (range > 50f)
			{
				num = baseInt * (1f + 0.145f * Mathf.Sqrt(range - 50f));
			}
		}
		else if (range > 100f)
		{
			num = baseInt * (1f + 0.095f * Mathf.Sqrt(range - 100f));
		}
		return Mathf.Min(num, 50f);
	}

	private void HandleLocalSync(LanternState mode)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: 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_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		if (!PhotonNetwork.InRoom || _view.ViewID <= 0)
		{
			return;
		}
		Quaternion val = (Object.op_Implicit((Object)(object)Camera.main) ? ((Component)Camera.main).transform.rotation : ((Component)lantern).transform.rotation);
		if (mode != _lastSentMode)
		{
			Send(mode, val, reliable: true);
			_lastSentMode = mode;
			_lastSentRot = val;
		}
		else if (mode == LanternState.Flashlight)
		{
			float num = Time.time - _lastSyncTime;
			if (Quaternion.Angle(_lastSentRot, val) > 10f || (num > 1f && Quaternion.Angle(_lastSentRot, val) > 0.1f))
			{
				Send(mode, val, reliable: false);
				_lastSentRot = val;
				_lastSyncTime = Time.time;
			}
		}
	}

	private void Send(LanternState mode, Quaternion rot, bool reliable)
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Expected O, but got Unknown
		object[] array = new object[5]
		{
			204,
			(byte)0,
			_view.ViewID,
			(byte)mode,
			rot
		};
		PhotonNetwork.RaiseEvent((byte)147, (object)array, new RaiseEventOptions
		{
			Receivers = (ReceiverGroup)0
		}, reliable ? SendOptions.SendReliable : SendOptions.SendUnreliable);
	}

	internal void ToggleMode()
	{
		if (!((Object)(object)_view == (Object)null) && _view.IsMine)
		{
			localMode = ((localMode == LanternState.Omni) ? LanternState.Flashlight : LanternState.Omni);
		}
	}
}
internal static class HipLanternRules
{
	internal static bool AllowsNpcHipLantern => PluginSettings.ScoutmasterHipLantern;

	internal static bool IsNpcCharacter(Character ch)
	{
		if ((Object)(object)ch == (Object)null)
		{
			return false;
		}
		if (ch.isBot)
		{
			return true;
		}
		try
		{
			if ((Object)(object)((Component)ch).GetComponent<Scoutmaster>() != (Object)null)
			{
				return true;
			}
			if (ch.isScoutmaster)
			{
				return true;
			}
			if ((Object)(object)ch.data != (Object)null && ch.data.isScoutmaster)
			{
				return true;
			}
		}
		catch
		{
		}
		GameObject gameObject = ((Component)ch).gameObject;
		string text = (((gameObject != null) ? ((Object)gameObject).name : null) ?? string.Empty).ToLowerInvariant();
		if (text.Contains("scoutmaster"))
		{
			return true;
		}
		return false;
	}

	internal static bool IsEligibleCharacter(Character ch)
	{
		if ((Object)(object)ch == (Object)null || !PitchBlackRuntime.ShouldApplyModEffects())
		{
			return false;
		}
		if (!PluginSettings.HipLanternEnabled)
		{
			return false;
		}
		if (IsNpcCharacter(ch))
		{
			return AllowsNpcHipLantern;
		}
		return (Object)(object)ch.player != (Object)null;
	}

	internal static bool ForceAlwaysLit(Character ch)
	{
		return IsNpcCharacter(ch) && AllowsNpcHipLantern;
	}

	internal static bool CanControlHipLantern(Character ch)
	{
		if (!IsEligibleCharacter(ch) || IsNpcCharacter(ch))
		{
			return false;
		}
		if (ch.IsLocal)
		{
			return true;
		}
		return (Object)(object)((MonoBehaviourPun)ch).photonView != (Object)null && ((MonoBehaviourPun)ch).photonView.IsMine;
	}

	internal static bool ShouldModifyHeldLantern(Lantern ln)
	{
		object obj;
		if (ln == null)
		{
			obj = null;
		}
		else
		{
			Item item = ln.item;
			obj = ((item != null) ? item.holderCharacter : null);
		}
		if ((Object)obj == (Object)null)
		{
			return true;
		}
		return !IsNpcCharacter(ln.item.holderCharacter);
	}
}
internal static class HipLanternNet
{
	private const byte SubHipLit = 3;

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

	internal static void ClearRemoteState()
	{
		RemoteLit.Clear();
	}

	internal static bool TryGetRemoteLit(Character ch, out bool lit)
	{
		lit = false;
		if ((Object)(object)((ch != null) ? ((MonoBehaviourPun)ch).photonView : null) == (Object)null)
		{
			return false;
		}
		return RemoteLit.TryGetValue(((MonoBehaviourPun)ch).photonView.ViewID, out lit);
	}

	internal static void BroadcastLit(Character ch, bool lit)
	{
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Expected O, but got Unknown
		if (!((Object)(object)((ch != null) ? ((MonoBehaviourPun)ch).photonView : null) == (Object)null) && ((MonoBehaviourPun)ch).photonView.IsMine)
		{
			RemoteLit[((MonoBehaviourPun)ch).photonView.ViewID] = lit;
			if (PhotonNetwork.InRoom)
			{
				PhotonNetwork.RaiseEvent((byte)147, (object)new object[4]
				{
					204,
					(byte)3,
					((MonoBehaviourPun)ch).photonView.ViewID,
					lit
				}, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)0
				}, SendOptions.SendReliable);
			}
		}
	}

	internal static void ApplyRemoteLit(int characterViewId, bool lit)
	{
		RemoteLit[characterViewId] = lit;
		PhotonView val = PhotonView.Find(characterViewId);
		if (!((Object)(object)val == (Object)null))
		{
			((Component)val).GetComponent<HipLanternHolster>()?.RefreshFromNetwork();
		}
	}
}
internal static class HipLanternInventory
{
	private static BoolItemData GetOrCreateFlare(ItemInstanceData data)
	{
		BoolItemData result = default(BoolItemData);
		if (!data.TryGetDataEntry<BoolItemData>((DataEntryKey)3, ref result))
		{
			return data.RegisterNewEntry<BoolItemData>((DataEntryKey)3);
		}
		return result;
	}

	internal static bool IsLanternSlot(ItemSlot slot)
	{
		return slot != null && !slot.IsEmpty() && (Object)(object)slot.prefab != (Object)null && slot.prefab.itemID == 42;
	}

	internal static ItemSlot ResolveLanternSlot(Character character)
	{
		if ((Object)(object)((character != null) ? character.player : null) == (Object)null)
		{
			return null;
		}
		CharacterItems val = character.refs?.items;
		if ((Object)(object)val != (Object)null && val.currentSelectedSlot.IsSome)
		{
			ItemSlot itemSlot = character.player.GetItemSlot(val.currentSelectedSlot.Value);
			if (IsLanternSlot(itemSlot))
			{
				return itemSlot;
			}
		}
		if ((Object)(object)val != (Object)null && val.lastSelectedSlot.IsSome)
		{
			ItemSlot itemSlot2 = character.player.GetItemSlot(val.lastSelectedSlot.Value);
			if (IsLanternSlot(itemSlot2))
			{
				return itemSlot2;
			}
		}
		if (IsLanternSlot(character.player.tempFullSlot))
		{
			return character.player.tempFullSlot;
		}
		ItemSlot[] itemSlots = character.player.itemSlots;
		if (itemSlots == null)
		{
			return null;
		}
		for (byte b = 0; b < itemSlots.Length; b++)
		{
			if (b != 3 && IsLanternSlot(itemSlots[b]))
			{
				return itemSlots[b];
			}
		}
		return null;
	}

	internal static bool ReadSlotLit(ItemSlot slot)
	{
		try
		{
			BoolItemData val = default(BoolItemData);
			if (((slot != null) ? slot.data : null) != null && slot.data.TryGetDataEntry<BoolItemData>((DataEntryKey)3, ref val))
			{
				return val.Value;
			}
		}
		catch
		{
		}
		return false;
	}

	internal static void SetSlotLit(ItemSlot slot, bool lit)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Expected O, but got Unknown
		if (slot != null)
		{
			if (slot.data == null)
			{
				slot.data = new ItemInstanceData(Guid.NewGuid());
			}
			GetOrCreateFlare(slot.data).Value = lit;
		}
	}

	internal static void PreserveHolsterState(Item item, Character character)
	{
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if ((Object)(object)item == (Object)null || item.itemID != 42 || (Object)(object)((character != null) ? character.player : null) == (Object)null)
			{
				return;
			}
			ItemSlot val = ResolveLanternSlot(character);
			if (val == null)
			{
				return;
			}
			bool lit = false;
			try
			{
				Lantern component = ((Component)item).GetComponent<Lantern>();
				if ((Object)(object)component != (Object)null)
				{
					lit = component.lit;
				}
			}
			catch
			{
			}
			BoolItemData val2 = default(BoolItemData);
			if (item.data != null && item.data.TryGetDataEntry<BoolItemData>((DataEntryKey)3, ref val2))
			{
				lit = val2.Value;
			}
			if (val.data == null)
			{
				val.data = (ItemInstanceData)(((object)item.data) ?? ((object)new ItemInstanceData(Guid.NewGuid())));
			}
			SetSlotLit(val, lit);
			CopyColor(item.data, val.data);
			CopyFuel(item.data, val.data);
			if (HipLanternRules.CanControlHipLantern(character))
			{
				HipLanternNet.BroadcastLit(character, lit);
			}
		}
		catch
		{
		}
	}

	internal static void SyncHeldLitToSlot(Character character, bool lit)
	{
		ItemSlot val = ResolveLanternSlot(character);
		if (val != null)
		{
			SetSlotLit(val, lit);
		}
	}

	private static void CopyColor(ItemInstanceData from, ItemInstanceData to)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		ColorItemData val = default(ColorItemData);
		if (from != null && to != null && from.TryGetDataEntry<ColorItemData>((DataEntryKey)9, ref val))
		{
			ColorItemData val2 = default(ColorItemData);
			if (!to.TryGetDataEntry<ColorItemData>((DataEntryKey)9, ref val2))
			{
				val2 = to.RegisterNewEntry<ColorItemData>((DataEntryKey)9);
			}
			val2.Value = val.Value;
		}
	}

	private static void CopyFuel(ItemInstanceData from, ItemInstanceData to)
	{
		FloatItemData val = default(FloatItemData);
		if (from != null && to != null && from.TryGetDataEntry<FloatItemData>((DataEntryKey)10, ref val))
		{
			FloatItemData val2 = default(FloatItemData);
			if (!to.TryGetDataEntry<FloatItemData>((DataEntryKey)10, ref val2))
			{
				val2 = to.RegisterNewEntry<FloatItemData>((DataEntryKey)10);
			}
			val2.Value = val.Value;
		}
	}
}
internal sealed class HipLanternVisualRoot : MonoBehaviour
{
}
internal sealed class HipLanternHolster : MonoBehaviour
{
	private static readonly Vector3 HolsterLocalPos = new Vector3(-1.08f, -0.12f, 0.08f);

	private static readonly Vector3 HolsterLocalEuler = new Vector3(23.5998f, 85.0001f, 344.9999f);

	private const float HolsterLocalScale = 2f;

	private static readonly string[] HolsterDisabledChildNames = new string[3] { "Hand_L", "Hand_R", "Mesh" };

	private Character _character;

	private Transform _attachPoint;

	private HipLanternVisualRoot _visualRoot;

	private Light _hipLight;

	private ParticleSystem _hipFire;

	private ParticleSystem _hipLightParticle;

	private ItemSlot _sourceSlot;

	private bool _npcPrefabVisual;

	private float _smoothIntensity;

	private bool _subscribed;

	private void Awake()
	{
		_character = ((Component)this).GetComponent<Character>();
		TryResolveAttachPoint();
	}

	private void Start()
	{
		((MonoBehaviour)this).StartCoroutine(WaitForPlayerAndRefresh());
	}

	private IEnumerator WaitForPlayerAndRefresh()
	{
		if (HipLanternRules.IsNpcCharacter(_character))
		{
			if (HipLanternRules.AllowsNpcHipLantern)
			{
				Subscribe();
				Refresh();
			}
		}
		else
		{
			while (Object.op_Implicit((Object)(object)_character) && (Object)(object)_character.player == (Object)null)
			{
				yield return null;
			}
			Subscribe();
			Refresh();
		}
	}

	private void OnEnable()
	{
		Subscribe();
	}

	private void OnDisable()
	{
		Unsubscribe();
	}

	private void Subscribe()
	{
		if (!_subscribed && !((Object)(object)_character?.refs?.items == (Object)null))
		{
			CharacterItems items = _character.refs.items;
			items.onSlotEquipped = (Action)Delegate.Combine(items.onSlotEquipped, new Action(Refresh));
			if ((Object)(object)_character.player != (Object)null)
			{
				Player player = _character.player;
				player.itemsChangedAction = (Action<ItemSlot[]>)Delegate.Combine(player.itemsChangedAction, new Action<ItemSlot[]>(OnInventoryChanged));
			}
			_subscribed = true;
		}
	}

	private void Unsubscribe()
	{
		if (_subscribed)
		{
			if ((Object)(object)_character?.refs?.items != (Object)null)
			{
				CharacterItems items = _character.refs.items;
				items.onSlotEquipped = (Action)Delegate.Remove(items.onSlotEquipped, new Action(Refresh));
			}
			Character character = _character;
			if ((Object)(object)((character != null) ? character.player : null) != (Object)null)
			{
				Player player = _character.player;
				player.itemsChangedAction = (Action<ItemSlot[]>)Delegate.Remove(player.itemsChangedAction, new Action<ItemSlot[]>(OnInventoryChanged));
			}
			_subscribed = false;
		}
	}

	private void OnInventoryChanged(ItemSlot[] _)
	{
		Refresh();
	}

	private void Update()
	{
		TryToggleHolsterLantern();
	}

	private void LateUpdate()
	{
		if (HipLanternRules.IsNpcCharacter(_character) && !HipLanternRules.AllowsNpcHipLantern)
		{
			ClearVisual();
			((Behaviour)this).enabled = false;
		}
		else
		{
			Refresh();
			UpdateHolsterLight();
		}
	}

	private void TryToggleHolsterLantern()
	{
		//IL_002d: 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_0033: 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)
		if (HipLanternRules.CanControlHipLantern(_character) && TryGetHolsteredSlot(out var slot))
		{
			KeyCode value = PitchBlackPlugin.ConfigLanternModeToggleKey.Value;
			if ((int)value != 0 && Input.GetKeyDown(value))
			{
				bool lit = !GetEffectiveLit(slot);
				HipLanternInventory.SetSlotLit(slot, lit);
				HipLanternNet.BroadcastLit(_character, lit);
				ApplySlotState(slot);
			}
		}
	}

	private bool IsLocalOwner()
	{
		if ((Object)(object)_character == (Object)null)
		{
			return false;
		}
		if (_character.IsLocal)
		{
			return true;
		}
		return (Object)(object)((MonoBehaviourPun)_character).photonView != (Object)null && ((MonoBehaviourPun)_character).photonView.IsMine;
	}

	private void TryResolveAttachPoint()
	{
		if (!Object.op_Implicit((Object)(object)_character))
		{
			return;
		}
		CharacterRefs refs = _character.refs;
		object attachPoint;
		if (refs == null)
		{
			attachPoint = null;
		}
		else
		{
			Bodypart hip = refs.hip;
			attachPoint = ((hip != null) ? hip.transform : null);
		}
		_attachPoint = (Transform)attachPoint;
		if (Object.op_Implicit((Object)(object)_attachPoint))
		{
			return;
		}
		try
		{
			_attachPoint = _character.GetBodypart((BodypartType)0).transform;
		}
		catch
		{
		}
	}

	private void Refresh()
	{
		if (!Object.op_Implicit((Object)(object)_character) || !Object.op_Implicit((Object)(object)_attachPoint))
		{
			TryResolveAttachPoint();
		}
		if (!Object.op_Implicit((Object)(object)_character) || !Object.op_Implicit((Object)(object)_attachPoint))
		{
			return;
		}
		if (!HipLanternRules.IsEligibleCharacter(_character))
		{
			ClearVisual();
		}
		else if (HipLanternRules.IsNpcCharacter(_character))
		{
			if (!HipLanternRules.AllowsNpcHipLantern)
			{
				ClearVisual();
				return;
			}
			if ((Object)(object)_visualRoot == (Object)null || !_npcPrefabVisual)
			{
				RebuildNpcVisual();
			}
			else
			{
				ApplyNpcState();
			}
			if (Object.op_Implicit((Object)(object)_visualRoot) && !((Component)_visualRoot).gameOb