using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using CloudShadows; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("ValheimVisualEnhanced")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.5.7.0")] [assembly: AssemblyInformationalVersion("0.5.7+7fbb0c79423edaa152e4543abbce714abfa24e7f")] [assembly: AssemblyProduct("ValheimVisualEnhanced")] [assembly: AssemblyTitle("ValheimVisualEnhanced")] [assembly: AssemblyVersion("0.5.7.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ValheimVisualEnhanced { [BepInPlugin("dev.local.valheimvisualenhanced", "Valheim Visual Enhanced", "0.5.7")] [BepInProcess("valheim.exe")] public class ValheimVisualEnhancedPlugin : BaseUnityPlugin { private CloudShadowsConfig _settings; private CloudShadowsPostEffect _postEffect; private EnvironmentPaletteController _environmentPalette; private MeadowsFirefliesEffect _meadowsFireflies; private CloudShadowsErrorLimiter _errorLimiter; private bool _lastEnabled; private bool _hasObservedEnabled; private bool _lastEnvironmentPaletteEnabled; private bool _hasObservedEnvironmentPaletteEnabled; private void Awake() { _errorLimiter = new CloudShadowsErrorLimiter(((BaseUnityPlugin)this).Logger); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Valheim Visual Enhanced 0.5.7 loaded"); try { string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location); _settings = new CloudShadowsConfig(((BaseUnityPlugin)this).Config); _lastEnabled = _settings.Enabled; _hasObservedEnabled = true; _lastEnvironmentPaletteEnabled = _settings.EnvironmentPaletteEnabled; _hasObservedEnvironmentPaletteEnabled = true; _environmentPalette = new EnvironmentPaletteController(((BaseUnityPlugin)this).Logger, _settings); _meadowsFireflies = new MeadowsFirefliesEffect(((BaseUnityPlugin)this).Logger, _settings); _postEffect = new CloudShadowsPostEffect(((BaseUnityPlugin)this).Logger, directoryName, _settings); ((BaseUnityPlugin)this).Logger.LogDebug((object)"Valheim Visual Enhanced render initialization deferred until a world is loaded"); } catch (Exception exception) { LogError("Valheim Visual Enhanced post-effect initialization failed", exception); } } private void Update() { HandlePostEffect(); HandleDiagnosticDump(); } private void HandlePostEffect() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //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) try { KeyboardShortcut val; if (_settings != null) { val = _settings.ToggleEnabledShortcut; if (((KeyboardShortcut)(ref val)).IsDown()) { _settings.ToggleEnabled(); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"Valheim Visual Enhanced shortcut: Enabled={_settings.Enabled}"); } } if (_settings != null) { val = _settings.ToggleDebugMaskShortcut; if (((KeyboardShortcut)(ref val)).IsDown()) { _settings.ToggleDebugMaskView(); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"Valheim Visual Enhanced shortcut: DebugMaskView={_settings.DebugMaskView}"); } } if (_settings != null) { val = _settings.ToggleEnvironmentPaletteShortcut; if (((KeyboardShortcut)(ref val)).IsDown()) { _settings.ToggleEnvironmentPalette(); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Valheim Visual Enhanced shortcut: " + $"EnhancedEnvironment={_settings.EnvironmentPaletteEnabled}")); } } ShowEnabledNotificationIfChanged(); ShowEnvironmentPaletteNotificationIfChanged(); _postEffect?.Tick(); _meadowsFireflies?.Tick(); } catch (Exception exception) { LogError("Valheim Visual Enhanced post-effect hotkey handler failed", exception); } } private void HandleDiagnosticDump() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) try { if (_settings == null) { return; } KeyboardShortcut diagnosticDumpShortcut = _settings.DiagnosticDumpShortcut; if (!((KeyboardShortcut)(ref diagnosticDumpShortcut)).IsDown()) { return; } Scene activeScene = SceneManager.GetActiveScene(); if (!((Scene)(ref activeScene)).IsValid() || !((Scene)(ref activeScene)).isLoaded) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"Valheim Visual Enhanced debug dump skipped: the active scene is not loaded"); return; } string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location); CloudShadowsRuntimeSnapshot cloudShadowsRuntimeSnapshot = _postEffect?.CreateDiagnosticsSnapshot(); if (cloudShadowsRuntimeSnapshot != null) { cloudShadowsRuntimeSnapshot.EnvironmentPalette = _environmentPalette?.CreateSnapshot(); cloudShadowsRuntimeSnapshot.MeadowsFireflies = _meadowsFireflies?.CreateSnapshot(); } CloudShadowsDiagnostics.WriteDump(((BaseUnityPlugin)this).Logger, directoryName, cloudShadowsRuntimeSnapshot); } catch (Exception exception) { LogError("Valheim Visual Enhanced diagnostic shortcut handler failed", exception); } } private void ShowEnabledNotificationIfChanged() { if (_settings == null) { return; } bool enabled = _settings.Enabled; if (!_hasObservedEnabled) { _lastEnabled = enabled; _hasObservedEnabled = true; } else if (_lastEnabled != enabled) { _lastEnabled = enabled; MessageHud instance = MessageHud.instance; if (!((Object)(object)instance == (Object)null)) { instance.ShowMessage((MessageType)1, enabled ? "Cloud shadows enabled" : "Cloud shadows disabled", 0, (Sprite)null, false, true); } } } private void ShowEnvironmentPaletteNotificationIfChanged() { if (_settings == null) { return; } bool environmentPaletteEnabled = _settings.EnvironmentPaletteEnabled; if (!_hasObservedEnvironmentPaletteEnabled) { _lastEnvironmentPaletteEnabled = environmentPaletteEnabled; _hasObservedEnvironmentPaletteEnabled = true; } else if (_lastEnvironmentPaletteEnabled != environmentPaletteEnabled) { _lastEnvironmentPaletteEnabled = environmentPaletteEnabled; MessageHud instance = MessageHud.instance; if (!((Object)(object)instance == (Object)null)) { instance.ShowMessage((MessageType)1, environmentPaletteEnabled ? "Enhanced Environment enabled" : "Enhanced Environment disabled", 0, (Sprite)null, false, true); } } } private void OnDestroy() { CloudShadowsPostEffect postEffect = _postEffect; EnvironmentPaletteController environmentPalette = _environmentPalette; MeadowsFirefliesEffect meadowsFireflies = _meadowsFireflies; CloudShadowsConfig settings = _settings; _postEffect = null; _environmentPalette = null; _meadowsFireflies = null; _settings = null; _hasObservedEnabled = false; _hasObservedEnvironmentPaletteEnabled = false; try { meadowsFireflies?.Dispose(); } catch (Exception exception) { LogError("Valheim Visual Enhanced Meadows fireflies cleanup failed", exception); } try { environmentPalette?.Dispose(); } catch (Exception exception2) { LogError("Valheim Visual Enhanced environment palette cleanup failed", exception2); } try { postEffect?.Dispose(); } catch (Exception exception3) { LogError("Valheim Visual Enhanced post-effect cleanup failed", exception3); } try { settings?.Dispose(); } catch (Exception exception4) { LogError("Valheim Visual Enhanced config cleanup failed", exception4); } } private void LogError(string context, Exception exception) { CloudShadowsErrorLimiter errorLimiter = _errorLimiter; if (errorLimiter != null) { errorLimiter.LogError(context, exception); return; } try { ((BaseUnityPlugin)this).Logger.LogError((object)$"{context}: {exception}"); } catch { } } } } namespace CloudShadows { internal enum CloudMaskQuality { Low512 = 0x200, Balanced1024 = 0x400, High2048 = 0x800 } internal enum EnhancedEnvironmentPreset { GoldenSaga, VerdantWilds, Frostbound, Emberfall, AuroraVeil, Custom } internal enum LegacyFantasyEnvironmentPreset { GoldenSaga, VerdantWilds, Frostbound, Custom } internal sealed class CloudShadowsConfig : IDisposable { private sealed class PaletteColorEntries { private readonly ConfigEntry _redEntry; private readonly ConfigEntry _greenEntry; private readonly ConfigEntry _blueEntry; internal Color Value => new Color(_redEntry.Value / 255f, _greenEntry.Value / 255f, _blueEntry.Value / 255f, 1f); internal PaletteColorEntries(ConfigEntry redEntry, ConfigEntry greenEntry, ConfigEntry blueEntry) { _redEntry = redEntry; _greenEntry = greenEntry; _blueEntry = blueEntry; } internal void MigrateLegacyValues(ConfigFile config, string name) { MigrateLegacySetting(config, "Fantasy Environment", name + "Red", _redEntry); MigrateLegacySetting(config, "Fantasy Environment", name + "Green", _greenEntry); MigrateLegacySetting(config, "Fantasy Environment", name + "Blue", _blueEntry); } internal void Subscribe(EventHandler handler) { _redEntry.SettingChanged += handler; _greenEntry.SettingChanged += handler; _blueEntry.SettingChanged += handler; } internal void Unsubscribe(EventHandler handler) { _redEntry.SettingChanged -= handler; _greenEntry.SettingChanged -= handler; _blueEntry.SettingChanged -= handler; } } private const int CurrentConfigSchemaVersion = 4; private const string GeneralSection = "General"; private const string HotkeysSection = "Hotkeys"; private const string CloudShadowsSection = "Cloud Shadows"; private const string WaterCausticLightingSection = "Water Caustic Lighting"; private const string EnvironmentPaletteSection = "Enhanced Environment"; private const string LegacyEnvironmentPaletteSection = "Fantasy Environment"; private const string MeadowsFirefliesSection = "Meadows Fireflies"; private const string AutomationSection = "Automation"; private static readonly ConfigDescription LegacyMigrationDescription = new ConfigDescription("Legacy Enhanced Environment setting used only during migration.", (AcceptableValueBase)null, new object[0]); private readonly ConfigFile _config; private readonly bool _hasLegacyEnvironmentPaletteSection; private readonly ConfigEntry _enabledEntry; private readonly ConfigEntry _debugMaskViewEntry; private readonly ConfigEntry _configSchemaVersionEntry; private readonly ConfigEntry _leaveRequestedDepthModeEntry; private readonly ConfigEntry _toggleEnabledShortcutEntry; private readonly ConfigEntry _diagnosticDumpShortcutEntry; private readonly ConfigEntry _toggleDebugMaskShortcutEntry; private readonly ConfigEntry _toggleEnvironmentPaletteShortcutEntry; private readonly ConfigEntry _shadowStrengthEntry; private readonly ConfigEntry _cloudSizeMetersEntry; private readonly ConfigEntry _edgeSoftnessEntry; private readonly ConfigEntry _cloudCoverageEntry; private readonly ConfigEntry _shadowDrawDistanceEntry; private readonly ConfigEntry _cloudMaskQualityEntry; private readonly ConfigEntry _windSpeedMultiplierEntry; private readonly ConfigEntry _migrateLegacyCloudCoverageEntry; private readonly ConfigEntry _causticsEnabledEntry; private readonly ConfigEntry _causticsIntensityEntry; private readonly ConfigEntry _causticsPatternSizeMetersEntry; private readonly ConfigEntry _causticsAnimationSpeedEntry; private readonly ConfigEntry _causticsFlowingMotionEntry; private readonly ConfigEntry _causticsMaximumDepthMetersEntry; private readonly ConfigEntry _causticsDrawDistanceMetersEntry; private readonly ConfigEntry _environmentPaletteEnabledEntry; private readonly ConfigEntry _environmentPaletteStrengthEntry; private readonly ConfigEntry _environmentPalettePresetEntry; private readonly ConfigEntry _environmentPaletteOverrideSunAngleEntry; private readonly ConfigEntry _environmentPaletteSunAngleEntry; private readonly PaletteColorEntries _morningSunColorEntries; private readonly PaletteColorEntries _morningFogColorEntries; private readonly PaletteColorEntries _daySunColorEntries; private readonly PaletteColorEntries _dayFogColorEntries; private readonly PaletteColorEntries _eveningSunColorEntries; private readonly PaletteColorEntries _eveningFogColorEntries; private readonly PaletteColorEntries _nightSunColorEntries; private readonly PaletteColorEntries _nightFogColorEntries; private readonly ConfigEntry _meadowsFirefliesEnabledEntry; private readonly ConfigEntry _meadowsFirefliesParticleCountEntry; private readonly ConfigEntry _meadowsFirefliesRadiusMetersEntry; private readonly ConfigEntry _meadowsFirefliesBrightnessEntry; private readonly ConfigEntry _autoDisableAtNightEntry; private readonly ConfigEntry _autoDisableInRainEntry; private readonly ConfigEntry _autoDisableUnderRoofEntry; private readonly ConfigEntry _autoDisableMeadowsFirefliesUnderRoofEntry; private bool _applyingConfigMigration; internal bool Enabled { get; private set; } internal bool DebugMaskView { get; private set; } internal int ConfigSchemaVersion { get; private set; } internal bool LeaveRequestedDepthModeForCompatibility { get; private set; } internal KeyboardShortcut ToggleEnabledShortcut { get; private set; } internal KeyboardShortcut DiagnosticDumpShortcut { get; private set; } internal KeyboardShortcut ToggleDebugMaskShortcut { get; private set; } internal KeyboardShortcut ToggleEnvironmentPaletteShortcut { get; private set; } internal float ShadowStrength { get; private set; } internal float CloudSizeMeters { get; private set; } internal float EdgeSoftness { get; private set; } internal float CloudCoverage { get; private set; } internal float ShadowDrawDistance { get; private set; } internal CloudMaskQuality CloudMaskQuality { get; private set; } internal int CloudMaskResolution => (int)CloudMaskQuality; internal float WindSpeedMultiplier { get; private set; } internal bool CausticsEnabled { get; private set; } internal float CausticsIntensity { get; private set; } internal float CausticsPatternSizeMeters { get; private set; } internal float CausticsAnimationSpeed { get; private set; } internal bool CausticsFlowingMotion { get; private set; } internal float CausticsMaximumDepthMeters { get; private set; } internal float CausticsDrawDistanceMeters { get; private set; } internal bool EnvironmentPaletteEnabled { get; private set; } internal float EnvironmentPaletteStrength { get; private set; } internal EnhancedEnvironmentPreset EnvironmentPalettePreset { get; private set; } internal bool EnvironmentPaletteOverrideSunAngle { get; private set; } internal float EnvironmentPaletteSunAngle { get; private set; } internal Color EnvironmentPaletteMorningSunColor { get; private set; } internal Color EnvironmentPaletteMorningFogColor { get; private set; } internal Color EnvironmentPaletteDaySunColor { get; private set; } internal Color EnvironmentPaletteDayFogColor { get; private set; } internal Color EnvironmentPaletteEveningSunColor { get; private set; } internal Color EnvironmentPaletteEveningFogColor { get; private set; } internal Color EnvironmentPaletteNightSunColor { get; private set; } internal Color EnvironmentPaletteNightFogColor { get; private set; } internal bool MeadowsFirefliesEnabled { get; private set; } internal int MeadowsFirefliesParticleCount { get; private set; } internal float MeadowsFirefliesRadiusMeters { get; private set; } internal float MeadowsFirefliesBrightness { get; private set; } internal bool AutoDisableAtNight { get; private set; } internal bool AutoDisableInRain { get; private set; } internal bool AutoDisableUnderRoof { get; private set; } internal bool AutoDisableMeadowsFirefliesUnderRoof { get; private set; } internal int Revision { get; private set; } internal CloudShadowsConfig(ConfigFile config) { //IL_00e7: 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_0177: Unknown result type (might be due to invalid IL or missing references) //IL_0609: Unknown result type (might be due to invalid IL or missing references) //IL_0633: Unknown result type (might be due to invalid IL or missing references) //IL_065d: Unknown result type (might be due to invalid IL or missing references) //IL_0687: Unknown result type (might be due to invalid IL or missing references) //IL_06b1: Unknown result type (might be due to invalid IL or missing references) //IL_06db: Unknown result type (might be due to invalid IL or missing references) //IL_0705: Unknown result type (might be due to invalid IL or missing references) //IL_072f: Unknown result type (might be due to invalid IL or missing references) if (config == null) { throw new ArgumentNullException("config"); } _config = config; _hasLegacyEnvironmentPaletteSection = HasConfigSection(config.ConfigFilePath, "Fantasy Environment"); _enabledEntry = config.Bind("General", "Enabled", true, CreateDescription("General", "Enables or disables cloud shadows.", null, 200)); _debugMaskViewEntry = config.Bind("General", "DebugMaskView", false, CreateDescription("General", "Shows the raw cloud pattern as a black-and-white mask.", null, 190)); _configSchemaVersionEntry = config.Bind("General", "ConfigSchemaVersion", 4, CreateDescription("General", "Tracks configuration migrations. Do not edit manually.", null, -100)); _leaveRequestedDepthModeEntry = config.Bind("General", "LeaveRequestedDepthModeForCompatibility", false, CreateDescription("General", "Leaves a Depth texture request on the main camera after disabling Valheim Visual Enhanced. Enable only if another visual mod relies on it.", null, -90)); _toggleEnabledShortcutEntry = config.Bind("Hotkeys", "ToggleEnabled", KeyboardShortcut.Empty, CreateDescription("Hotkeys", "Toggles cloud shadows. No shortcut is assigned by default.", null, 180)); _diagnosticDumpShortcutEntry = config.Bind("Hotkeys", "WriteDiagnosticDump", KeyboardShortcut.Empty, CreateDescription("Hotkeys", "Writes the complete diagnostic dump. No shortcut is assigned by default.", null, 170)); _toggleDebugMaskShortcutEntry = config.Bind("Hotkeys", "ToggleDebugMaskView", KeyboardShortcut.Empty, CreateDescription("Hotkeys", "Toggles the raw cloud-mask view. No shortcut is assigned by default.", null, 160)); _toggleEnvironmentPaletteShortcutEntry = config.Bind("Hotkeys", "ToggleEnhancedEnvironment", KeyboardShortcut.Empty, CreateDescription("Hotkeys", "Toggles Enhanced Environment. No shortcut is assigned by default.", null, 150)); _shadowStrengthEntry = config.Bind("Cloud Shadows", "ShadowStrength", 1.45f, CreateDescription("Cloud Shadows", "Controls the visibility and darkness of cloud shadows.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 2f), 180)); _cloudSizeMetersEntry = config.Bind("Cloud Shadows", "CloudSizeMeters", 85f, CreateDescription("Cloud Shadows", "Controls the approximate size of one cloud shadow patch in meters.", (AcceptableValueBase)(object)new AcceptableValueRange(20f, 300f), 170)); _edgeSoftnessEntry = config.Bind("Cloud Shadows", "EdgeSoftness", 0.035f, CreateDescription("Cloud Shadows", "Controls the softness and blur of cloud shadow edges.", (AcceptableValueBase)(object)new AcceptableValueRange(0.01f, 0.5f), 160)); _cloudCoverageEntry = config.Bind("Cloud Shadows", "CloudCoverage", 0.4f, CreateDescription("Cloud Shadows", "Controls how much of the world is covered by cloud shadows. 0 disables coverage; 1 gives maximum coverage.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), 150)); _shadowDrawDistanceEntry = config.Bind("Cloud Shadows", "ShadowDrawDistance", 365f, CreateDescription("Cloud Shadows", "Sets the approximate projected radius of the cloud shadow mask. Shadows fade smoothly near the limit.", (AcceptableValueBase)(object)new AcceptableValueRange(100f, 2000f), 140)); _cloudMaskQualityEntry = config.Bind("Cloud Shadows", "MaskQuality", CloudMaskQuality.Low512, CreateDescription("Cloud Shadows", "Controls the cloud-mask resolution. Higher quality uses more GPU memory and bandwidth.", null, 135)); _windSpeedMultiplierEntry = config.Bind("Cloud Shadows", "WindSpeedMultiplier", 0.8f, CreateDescription("Cloud Shadows", "Multiplies the cloud shadow drift speed from the game wind.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 3f), 120)); _migrateLegacyCloudCoverageEntry = config.Bind("Cloud Shadows", "MigrateLegacyCloudCoverageOnce", false, CreateDescription("Cloud Shadows", "When set to true, inverts CloudCoverage once for a configuration created before direct coverage semantics. It resets itself after migration.", null, -100)); _causticsEnabledEntry = config.Bind("Water Caustic Lighting", "Enabled", true, CreateDescription("Water Caustic Lighting", "Enables underwater caustic lighting independently of cloud shadows.", null, 180)); _causticsIntensityEntry = config.Bind("Water Caustic Lighting", "Intensity", 1f, CreateDescription("Water Caustic Lighting", "Controls the brightness of underwater caustic lighting. Values above 1 increase the effect beyond its default intensity.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 3f), 170)); _causticsPatternSizeMetersEntry = config.Bind("Water Caustic Lighting", "PatternSizeMeters", 8f, CreateDescription("Water Caustic Lighting", "Controls the approximate size of the caustic pattern in meters.", (AcceptableValueBase)(object)new AcceptableValueRange(2f, 20f), 160)); _causticsAnimationSpeedEntry = config.Bind("Water Caustic Lighting", "AnimationSpeed", 1f, CreateDescription("Water Caustic Lighting", "Controls how quickly the caustic pattern ripples.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 3f), 150)); _causticsFlowingMotionEntry = config.Bind("Water Caustic Lighting", "FlowingMotion", true, CreateDescription("Water Caustic Lighting", "Adds a world-space flow and changing filament thickness to make caustics feel less repetitive. Disable for the original 0.2.0 motion.", null, 145)); _causticsMaximumDepthMetersEntry = config.Bind("Water Caustic Lighting", "MaximumDepthMeters", 10f, CreateDescription("Water Caustic Lighting", "Sets the maximum water depth reached by caustic lighting.", (AcceptableValueBase)(object)new AcceptableValueRange(2f, 40f), 140)); _causticsDrawDistanceMetersEntry = config.Bind("Water Caustic Lighting", "DrawDistanceMeters", 45f, CreateDescription("Water Caustic Lighting", "Sets the maximum camera distance for caustic lighting.", (AcceptableValueBase)(object)new AcceptableValueRange(20f, 250f), 130)); _environmentPaletteEnabledEntry = config.Bind("Enhanced Environment", "Enabled", false, CreateDescription("Enhanced Environment", "Applies a configurable enhanced color grade to Valheim's morning, day, evening, and night lighting. Biome and weather behavior remain authored by the active Valheim environment.", null, 180)); _environmentPaletteStrengthEntry = config.Bind("Enhanced Environment", "Strength", 0.65f, CreateDescription("Enhanced Environment", "Blends the configured palette with each environment's original colors. Set to 0 for the unmodified Valheim colors.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), 170)); _environmentPalettePresetEntry = config.Bind("Enhanced Environment", "Preset", EnhancedEnvironmentPreset.GoldenSaga, CreateDescription("Enhanced Environment", "Selects a complete environment palette. GoldenSaga is warm and cinematic, VerdantWilds is lush and green, Frostbound is cool and crystalline, Emberfall is fiery and high-contrast, AuroraVeil is vivid teal and violet, and Custom uses the RGB settings below.", null, 168)); _environmentPaletteOverrideSunAngleEntry = config.Bind("Enhanced Environment", "OverrideSunAngle", false, CreateDescription("Enhanced Environment", "When enabled, adjusts the daily sun path using SunAngle. Leave disabled to preserve Valheim's original sun position.", null, 165)); _environmentPaletteSunAngleEntry = config.Bind("Enhanced Environment", "SunAngle", 78f, CreateDescription("Enhanced Environment", "Sets the daily sun-path elevation when OverrideSunAngle is enabled. 0 is horizon-level and 90 is directly overhead.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 90f), 160)); _morningSunColorEntries = BindPaletteColor(config, "MorningSun", new Color(1f, 0.72156864f, 0.38039216f), 150); _morningFogColorEntries = BindPaletteColor(config, "MorningFog", new Color(46f / 51f, 46f / 85f, 0.4117647f), 147); _daySunColorEntries = BindPaletteColor(config, "DaySun", new Color(1f, 46f / 51f, 38f / 51f), 144); _dayFogColorEntries = BindPaletteColor(config, "DayFog", new Color(23f / 51f, 53f / 85f, 0.6156863f), 141); _eveningSunColorEntries = BindPaletteColor(config, "EveningSun", new Color(49f / 51f, 0.38039216f, 39f / 85f), 138); _eveningFogColorEntries = BindPaletteColor(config, "EveningFog", new Color(25f / 51f, 0.23921569f, 0.5019608f), 135); _nightSunColorEntries = BindPaletteColor(config, "NightSun", new Color(0.3019608f, 0.41960785f, 0.78039217f), 132); _nightFogColorEntries = BindPaletteColor(config, "NightFog", new Color(11f / 85f, 0.2f, 0.4f), 129); _meadowsFirefliesEnabledEntry = config.Bind("Meadows Fireflies", "Enabled", true, CreateDescription("Meadows Fireflies", "Shows a small number of subtle yellow fireflies outdoors in the Meadows at night.", null, 180)); _meadowsFirefliesParticleCountEntry = config.Bind("Meadows Fireflies", "ParticleCount", 36, CreateDescription("Meadows Fireflies", "Sets the maximum number of fireflies. This is capped at a deliberately small value to keep the effect inexpensive.", (AcceptableValueBase)(object)new AcceptableValueRange(12, 64), 170)); _meadowsFirefliesRadiusMetersEntry = config.Bind("Meadows Fireflies", "RadiusMeters", 16f, CreateDescription("Meadows Fireflies", "Sets the radius around the player in which fireflies appear.", (AcceptableValueBase)(object)new AcceptableValueRange(6f, 30f), 160)); _meadowsFirefliesBrightnessEntry = config.Bind("Meadows Fireflies", "Brightness", 0.85f, CreateDescription("Meadows Fireflies", "Controls the alpha of the yellow one-pixel firefly sprites without adding lights or bloom.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), 150)); _autoDisableAtNightEntry = config.Bind("Automation", "AutoDisableAtNight", true, CreateDescription("Automation", "Smoothly fades cloud shadows out while it is night.", null, 110)); _autoDisableInRainEntry = config.Bind("Automation", "AutoDisableInRain", true, CreateDescription("Automation", "Smoothly fades cloud shadows out during rain and wet storms.", null, 105)); _autoDisableUnderRoofEntry = config.Bind("Automation", "AutoDisableUnderRoof", true, CreateDescription("Automation", "Smoothly fades cloud shadows out under a roof or inside a cave.", null, 100)); _autoDisableMeadowsFirefliesUnderRoofEntry = config.Bind("Automation", "AutoDisableMeadowsFirefliesUnderRoof", true, CreateDescription("Automation", "Smoothly fades Meadows fireflies out under a roof or inside an interior.", null, 95)); ApplyRequestedConfigMigration(); SubscribeToChanges(); RefreshCache(); } internal void ToggleEnabled() { _enabledEntry.Value = !_enabledEntry.Value; } internal void ToggleDebugMaskView() { _debugMaskViewEntry.Value = !_debugMaskViewEntry.Value; } internal void ToggleEnvironmentPalette() { _environmentPaletteEnabledEntry.Value = !_environmentPaletteEnabledEntry.Value; } public void Dispose() { UnsubscribeFromChanges(); } private static ConfigDescription CreateDescription(string category, string description, AcceptableValueBase acceptableValues, int order) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown return new ConfigDescription(description, acceptableValues, new object[1] { new ConfigurationManagerAttributes { Order = order, Category = category, IsAdvanced = false } }); } private static PaletteColorEntries BindPaletteColor(ConfigFile config, string name, Color defaultColor, int order) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) return new PaletteColorEntries(config.Bind("Enhanced Environment", name + "Red", defaultColor.r * 255f, CreateDescription("Enhanced Environment", "Red channel for the " + FormatPaletteColorName(name) + " color.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 255f), order)), config.Bind("Enhanced Environment", name + "Green", defaultColor.g * 255f, CreateDescription("Enhanced Environment", "Green channel for the " + FormatPaletteColorName(name) + " color.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 255f), order - 1)), config.Bind("Enhanced Environment", name + "Blue", defaultColor.b * 255f, CreateDescription("Enhanced Environment", "Blue channel for the " + FormatPaletteColorName(name) + " color.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 255f), order - 2))); } private static string FormatPaletteColorName(string name) { if (string.IsNullOrEmpty(name)) { return "palette"; } return name.Replace("Morning", "morning ").Replace("Evening", "evening ").Replace("Night", "night ") .Replace("Sun", "sun") .Replace("Fog", "fog") .Trim() .ToLowerInvariant(); } private void SubscribeToChanges() { _enabledEntry.SettingChanged += HandleSettingChanged; _debugMaskViewEntry.SettingChanged += HandleSettingChanged; _configSchemaVersionEntry.SettingChanged += HandleSettingChanged; _leaveRequestedDepthModeEntry.SettingChanged += HandleSettingChanged; _toggleEnabledShortcutEntry.SettingChanged += HandleSettingChanged; _diagnosticDumpShortcutEntry.SettingChanged += HandleSettingChanged; _toggleDebugMaskShortcutEntry.SettingChanged += HandleSettingChanged; _toggleEnvironmentPaletteShortcutEntry.SettingChanged += HandleSettingChanged; _shadowStrengthEntry.SettingChanged += HandleSettingChanged; _cloudSizeMetersEntry.SettingChanged += HandleSettingChanged; _edgeSoftnessEntry.SettingChanged += HandleSettingChanged; _cloudCoverageEntry.SettingChanged += HandleSettingChanged; _shadowDrawDistanceEntry.SettingChanged += HandleSettingChanged; _cloudMaskQualityEntry.SettingChanged += HandleSettingChanged; _windSpeedMultiplierEntry.SettingChanged += HandleSettingChanged; _migrateLegacyCloudCoverageEntry.SettingChanged += HandleSettingChanged; _causticsEnabledEntry.SettingChanged += HandleSettingChanged; _causticsIntensityEntry.SettingChanged += HandleSettingChanged; _causticsPatternSizeMetersEntry.SettingChanged += HandleSettingChanged; _causticsAnimationSpeedEntry.SettingChanged += HandleSettingChanged; _causticsFlowingMotionEntry.SettingChanged += HandleSettingChanged; _causticsMaximumDepthMetersEntry.SettingChanged += HandleSettingChanged; _causticsDrawDistanceMetersEntry.SettingChanged += HandleSettingChanged; _environmentPaletteEnabledEntry.SettingChanged += HandleSettingChanged; _environmentPaletteStrengthEntry.SettingChanged += HandleSettingChanged; _environmentPalettePresetEntry.SettingChanged += HandleSettingChanged; _environmentPaletteOverrideSunAngleEntry.SettingChanged += HandleSettingChanged; _environmentPaletteSunAngleEntry.SettingChanged += HandleSettingChanged; _morningSunColorEntries.Subscribe(HandleSettingChanged); _morningFogColorEntries.Subscribe(HandleSettingChanged); _daySunColorEntries.Subscribe(HandleSettingChanged); _dayFogColorEntries.Subscribe(HandleSettingChanged); _eveningSunColorEntries.Subscribe(HandleSettingChanged); _eveningFogColorEntries.Subscribe(HandleSettingChanged); _nightSunColorEntries.Subscribe(HandleSettingChanged); _nightFogColorEntries.Subscribe(HandleSettingChanged); _meadowsFirefliesEnabledEntry.SettingChanged += HandleSettingChanged; _meadowsFirefliesParticleCountEntry.SettingChanged += HandleSettingChanged; _meadowsFirefliesRadiusMetersEntry.SettingChanged += HandleSettingChanged; _meadowsFirefliesBrightnessEntry.SettingChanged += HandleSettingChanged; _autoDisableAtNightEntry.SettingChanged += HandleSettingChanged; _autoDisableInRainEntry.SettingChanged += HandleSettingChanged; _autoDisableUnderRoofEntry.SettingChanged += HandleSettingChanged; _autoDisableMeadowsFirefliesUnderRoofEntry.SettingChanged += HandleSettingChanged; } private void UnsubscribeFromChanges() { _enabledEntry.SettingChanged -= HandleSettingChanged; _debugMaskViewEntry.SettingChanged -= HandleSettingChanged; _configSchemaVersionEntry.SettingChanged -= HandleSettingChanged; _leaveRequestedDepthModeEntry.SettingChanged -= HandleSettingChanged; _toggleEnabledShortcutEntry.SettingChanged -= HandleSettingChanged; _diagnosticDumpShortcutEntry.SettingChanged -= HandleSettingChanged; _toggleDebugMaskShortcutEntry.SettingChanged -= HandleSettingChanged; _toggleEnvironmentPaletteShortcutEntry.SettingChanged -= HandleSettingChanged; _shadowStrengthEntry.SettingChanged -= HandleSettingChanged; _cloudSizeMetersEntry.SettingChanged -= HandleSettingChanged; _edgeSoftnessEntry.SettingChanged -= HandleSettingChanged; _cloudCoverageEntry.SettingChanged -= HandleSettingChanged; _shadowDrawDistanceEntry.SettingChanged -= HandleSettingChanged; _cloudMaskQualityEntry.SettingChanged -= HandleSettingChanged; _windSpeedMultiplierEntry.SettingChanged -= HandleSettingChanged; _migrateLegacyCloudCoverageEntry.SettingChanged -= HandleSettingChanged; _causticsEnabledEntry.SettingChanged -= HandleSettingChanged; _causticsIntensityEntry.SettingChanged -= HandleSettingChanged; _causticsPatternSizeMetersEntry.SettingChanged -= HandleSettingChanged; _causticsAnimationSpeedEntry.SettingChanged -= HandleSettingChanged; _causticsFlowingMotionEntry.SettingChanged -= HandleSettingChanged; _causticsMaximumDepthMetersEntry.SettingChanged -= HandleSettingChanged; _causticsDrawDistanceMetersEntry.SettingChanged -= HandleSettingChanged; _environmentPaletteEnabledEntry.SettingChanged -= HandleSettingChanged; _environmentPaletteStrengthEntry.SettingChanged -= HandleSettingChanged; _environmentPalettePresetEntry.SettingChanged -= HandleSettingChanged; _environmentPaletteOverrideSunAngleEntry.SettingChanged -= HandleSettingChanged; _environmentPaletteSunAngleEntry.SettingChanged -= HandleSettingChanged; _morningSunColorEntries.Unsubscribe(HandleSettingChanged); _morningFogColorEntries.Unsubscribe(HandleSettingChanged); _daySunColorEntries.Unsubscribe(HandleSettingChanged); _dayFogColorEntries.Unsubscribe(HandleSettingChanged); _eveningSunColorEntries.Unsubscribe(HandleSettingChanged); _eveningFogColorEntries.Unsubscribe(HandleSettingChanged); _nightSunColorEntries.Unsubscribe(HandleSettingChanged); _nightFogColorEntries.Unsubscribe(HandleSettingChanged); _meadowsFirefliesEnabledEntry.SettingChanged -= HandleSettingChanged; _meadowsFirefliesParticleCountEntry.SettingChanged -= HandleSettingChanged; _meadowsFirefliesRadiusMetersEntry.SettingChanged -= HandleSettingChanged; _meadowsFirefliesBrightnessEntry.SettingChanged -= HandleSettingChanged; _autoDisableAtNightEntry.SettingChanged -= HandleSettingChanged; _autoDisableInRainEntry.SettingChanged -= HandleSettingChanged; _autoDisableUnderRoofEntry.SettingChanged -= HandleSettingChanged; _autoDisableMeadowsFirefliesUnderRoofEntry.SettingChanged -= HandleSettingChanged; } private void HandleSettingChanged(object sender, EventArgs eventArgs) { if (!_applyingConfigMigration) { ApplyRequestedConfigMigration(); RefreshCache(); } } private void ApplyRequestedConfigMigration() { bool flag = _configSchemaVersionEntry.Value < 3; bool flag2 = _configSchemaVersionEntry.Value < 4; if (!flag && !flag2 && !_migrateLegacyCloudCoverageEntry.Value) { return; } _applyingConfigMigration = true; try { if (flag2) { MigrateLegacyEnhancedEnvironmentSettings(); } if (flag) { _environmentPaletteEnabledEntry.Value = false; } if (_migrateLegacyCloudCoverageEntry.Value) { _cloudCoverageEntry.Value = 1f - _cloudCoverageEntry.Value; _migrateLegacyCloudCoverageEntry.Value = false; } _configSchemaVersionEntry.Value = 4; } finally { _applyingConfigMigration = false; } } private void MigrateLegacyEnhancedEnvironmentSettings() { if (_hasLegacyEnvironmentPaletteSection) { MigrateLegacySetting(_config, "Hotkeys", "ToggleFantasyEnvironment", _toggleEnvironmentPaletteShortcutEntry); MigrateLegacySetting(_config, "Fantasy Environment", "Enabled", _environmentPaletteEnabledEntry); MigrateLegacySetting(_config, "Fantasy Environment", "Strength", _environmentPaletteStrengthEntry); MigrateLegacyPreset(); MigrateLegacySetting(_config, "Fantasy Environment", "OverrideSunAngle", _environmentPaletteOverrideSunAngleEntry); MigrateLegacySetting(_config, "Fantasy Environment", "SunAngle", _environmentPaletteSunAngleEntry); _morningSunColorEntries.MigrateLegacyValues(_config, "MorningSun"); _morningFogColorEntries.MigrateLegacyValues(_config, "MorningFog"); _daySunColorEntries.MigrateLegacyValues(_config, "DaySun"); _dayFogColorEntries.MigrateLegacyValues(_config, "DayFog"); _eveningSunColorEntries.MigrateLegacyValues(_config, "EveningSun"); _eveningFogColorEntries.MigrateLegacyValues(_config, "EveningFog"); _nightSunColorEntries.MigrateLegacyValues(_config, "NightSun"); _nightFogColorEntries.MigrateLegacyValues(_config, "NightFog"); } } private void MigrateLegacyPreset() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown ConfigDefinition val = new ConfigDefinition("Fantasy Environment", "Preset"); if (Enum.TryParse(_config.Bind(val, LegacyFantasyEnvironmentPreset.GoldenSaga, LegacyMigrationDescription).Value.ToString(), ignoreCase: true, out var result)) { _environmentPalettePresetEntry.Value = result; } _config.Remove(val); } private static void MigrateLegacySetting(ConfigFile config, string section, string key, ConfigEntry target) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown ConfigDefinition val = new ConfigDefinition(section, key); ConfigEntry val2 = config.Bind(val, target.Value, LegacyMigrationDescription); target.Value = val2.Value; config.Remove(val); } private static bool HasConfigSection(string configFilePath, string sectionName) { try { if (!File.Exists(configFilePath)) { return false; } string b = "[" + sectionName + "]"; string[] array = File.ReadAllLines(configFilePath); for (int i = 0; i < array.Length; i++) { if (string.Equals(array[i].Trim(), b, StringComparison.OrdinalIgnoreCase)) { return true; } } } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } private void RefreshCache() { //IL_004b: 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) //IL_006d: 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_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) Enabled = _enabledEntry.Value; DebugMaskView = _debugMaskViewEntry.Value; ConfigSchemaVersion = _configSchemaVersionEntry.Value; LeaveRequestedDepthModeForCompatibility = _leaveRequestedDepthModeEntry.Value; ToggleEnabledShortcut = _toggleEnabledShortcutEntry.Value; DiagnosticDumpShortcut = _diagnosticDumpShortcutEntry.Value; ToggleDebugMaskShortcut = _toggleDebugMaskShortcutEntry.Value; ToggleEnvironmentPaletteShortcut = _toggleEnvironmentPaletteShortcutEntry.Value; ShadowStrength = _shadowStrengthEntry.Value; CloudSizeMeters = _cloudSizeMetersEntry.Value; EdgeSoftness = _edgeSoftnessEntry.Value; CloudCoverage = _cloudCoverageEntry.Value; ShadowDrawDistance = _shadowDrawDistanceEntry.Value; CloudMaskQuality = _cloudMaskQualityEntry.Value; WindSpeedMultiplier = _windSpeedMultiplierEntry.Value; CausticsEnabled = _causticsEnabledEntry.Value; CausticsIntensity = _causticsIntensityEntry.Value; CausticsPatternSizeMeters = _causticsPatternSizeMetersEntry.Value; CausticsAnimationSpeed = _causticsAnimationSpeedEntry.Value; CausticsFlowingMotion = _causticsFlowingMotionEntry.Value; CausticsMaximumDepthMeters = _causticsMaximumDepthMetersEntry.Value; CausticsDrawDistanceMeters = _causticsDrawDistanceMetersEntry.Value; EnvironmentPaletteEnabled = _environmentPaletteEnabledEntry.Value; EnvironmentPaletteStrength = _environmentPaletteStrengthEntry.Value; EnvironmentPalettePreset = _environmentPalettePresetEntry.Value; EnvironmentPaletteOverrideSunAngle = _environmentPaletteOverrideSunAngleEntry.Value; EnvironmentPaletteSunAngle = _environmentPaletteSunAngleEntry.Value; EnvironmentPaletteMorningSunColor = _morningSunColorEntries.Value; EnvironmentPaletteMorningFogColor = _morningFogColorEntries.Value; EnvironmentPaletteDaySunColor = _daySunColorEntries.Value; EnvironmentPaletteDayFogColor = _dayFogColorEntries.Value; EnvironmentPaletteEveningSunColor = _eveningSunColorEntries.Value; EnvironmentPaletteEveningFogColor = _eveningFogColorEntries.Value; EnvironmentPaletteNightSunColor = _nightSunColorEntries.Value; EnvironmentPaletteNightFogColor = _nightFogColorEntries.Value; MeadowsFirefliesEnabled = _meadowsFirefliesEnabledEntry.Value; MeadowsFirefliesParticleCount = _meadowsFirefliesParticleCountEntry.Value; MeadowsFirefliesRadiusMeters = _meadowsFirefliesRadiusMetersEntry.Value; MeadowsFirefliesBrightness = _meadowsFirefliesBrightnessEntry.Value; AutoDisableAtNight = _autoDisableAtNightEntry.Value; AutoDisableInRain = _autoDisableInRainEntry.Value; AutoDisableUnderRoof = _autoDisableUnderRoofEntry.Value; AutoDisableMeadowsFirefliesUnderRoof = _autoDisableMeadowsFirefliesUnderRoofEntry.Value; Revision++; } } internal static class CloudShadowsDiagnostics { private const string BeginMarker = "===== VALHEIM VISUAL ENHANCED DEBUG BEGIN ====="; private const string EndMarker = "===== VALHEIM VISUAL ENHANCED DEBUG END ====="; private const int CameraLimit = 10; private const int LightLimit = 20; private const int ObjectLimit = 150; private const int ShaderLimit = 200; private const int MaterialLimit = 200; private const int RendererSampleLimit = 200; private const int RendererDetailLimit = 30; private static readonly string[] ObjectKeywords = new string[11] { "cloud", "sky", "sun", "fog", "weather", "env", "atmosphere", "shadow", "terrain", "landscape", "ground" }; private static readonly string[] ShaderKeywords = new string[12] { "terrain", "sky", "cloud", "shadow", "nature", "grass", "rock", "water", "fog", "sun", "environment", "atmosphere" }; private static readonly string[] MaterialKeywords = new string[13] { "terrain", "sky", "cloud", "shadow", "nature", "grass", "rock", "water", "fog", "sun", "environment", "atmosphere", "landscape" }; internal static void WriteDump(ManualLogSource logger, string pluginDirectory, CloudShadowsRuntimeSnapshot runtimeSnapshot) { StringBuilder stringBuilder = new StringBuilder(65536); stringBuilder.AppendLine("===== VALHEIM VISUAL ENHANCED DEBUG BEGIN ====="); try { AppendSection(stringBuilder, "A. General information", AppendGeneralInformation); AppendSection(stringBuilder, "B. Valheim Visual Enhanced runtime", delegate(StringBuilder section) { AppendRuntimeState(section, runtimeSnapshot); }); AppendSection(stringBuilder, "C. Cameras", AppendCameras); AppendSection(stringBuilder, "D. RenderSettings", AppendRenderSettings); AppendSection(stringBuilder, "E. Lights", AppendLights); AppendSection(stringBuilder, "F. Related objects", AppendRelatedObjects); AppendSection(stringBuilder, "G. Shaders", AppendShaders); AppendSection(stringBuilder, "H. Materials", AppendMaterials); AppendSection(stringBuilder, "I. Renderers in active scene", AppendRenderers); } catch (Exception exception) { AppendException(stringBuilder, "Unexpected top-level diagnostic error", exception); } finally { stringBuilder.AppendLine("===== VALHEIM VISUAL ENHANCED DEBUG END ====="); } string contents = stringBuilder.ToString(); try { if (string.IsNullOrWhiteSpace(pluginDirectory)) { throw new InvalidOperationException("The plugin directory could not be determined"); } Directory.CreateDirectory(pluginDirectory); string text = Path.Combine(pluginDirectory, "debug_output.txt"); File.WriteAllText(text, contents, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); logger.LogInfo((object)("Valheim Visual Enhanced debug dump written to: " + text)); } catch (Exception exception2) { TryLogError(logger, "Could not write Valheim Visual Enhanced debug_output.txt", exception2); } } private static void AppendSection(StringBuilder dump, string title, Action appendSection) { dump.AppendLine(); dump.AppendLine("--- " + title + " ---"); try { appendSection(dump); } catch (Exception exception) { AppendException(dump, "Section " + title + " failed", exception); } } private static void AppendGeneralInformation(StringBuilder dump) { AppendSafeValue(dump, "Current time", () => DateTime.Now.ToString("O")); AppendSafeValue(dump, "Application version", () => Application.version); AppendSafeValue(dump, "Unity version", () => Application.unityVersion); AppendSafeValue(dump, "Graphics API", () => SystemInfo.graphicsDeviceType); AppendSafeValue(dump, "Graphics device version", () => SystemInfo.graphicsDeviceVersion); AppendSafeValue(dump, "Active scene", () => FormatScene(SceneManager.GetActiveScene())); Camera mainCamera = null; try { mainCamera = Camera.main; dump.AppendLine($"Camera.main exists: {(Object)(object)mainCamera != (Object)null}"); } catch (Exception exception) { AppendException(dump, "Camera.main lookup failed", exception); } if (!((Object)(object)mainCamera == (Object)null)) { AppendSafeValue(dump, "Main camera name", () => ((Object)mainCamera).name); AppendSafeValue(dump, "Main camera position", () => ((Component)mainCamera).transform.position); AppendSafeValue(dump, "Main camera rotation (Euler)", delegate { //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_0013: Unknown result type (might be due to invalid IL or missing references) Quaternion rotation = ((Component)mainCamera).transform.rotation; return ((Quaternion)(ref rotation)).eulerAngles; }); AppendSafeValue(dump, "Main camera fieldOfView", () => mainCamera.fieldOfView); AppendSafeValue(dump, "Main camera nearClipPlane", () => mainCamera.nearClipPlane); AppendSafeValue(dump, "Main camera farClipPlane", () => mainCamera.farClipPlane); AppendSafeValue(dump, "Main camera clearFlags", () => mainCamera.clearFlags); AppendSafeValue(dump, "Main camera has targetTexture", () => (Object)(object)mainCamera.targetTexture != (Object)null); AppendSafeValue(dump, "Main camera targetTexture", () => GetObjectName((Object)(object)mainCamera.targetTexture)); AppendSafeValue(dump, "Main camera cullingMask", () => FormatMask(mainCamera.cullingMask)); AppendSafeValue(dump, "Main camera cameraType", () => mainCamera.cameraType); AppendSafeValue(dump, "Main camera renderingPath", () => mainCamera.renderingPath); AppendSafeValue(dump, "Main camera actualRenderingPath", () => mainCamera.actualRenderingPath); AppendSafeValue(dump, "Main camera depthTextureMode", () => mainCamera.depthTextureMode); AppendSafeValue(dump, "Main camera allowHDR", () => mainCamera.allowHDR); AppendSafeValue(dump, "Main camera pixel size", () => $"{mainCamera.pixelWidth}x{mainCamera.pixelHeight}"); AppendSafeValue(dump, "Main camera commandBufferCount", () => mainCamera.commandBufferCount); } } private static void AppendRuntimeState(StringBuilder dump, CloudShadowsRuntimeSnapshot snapshot) { //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) //IL_0585: Unknown result type (might be due to invalid IL or missing references) if (snapshot == null) { dump.AppendLine(""); return; } dump.AppendLine($"World ready: {snapshot.WorldReady}"); dump.AppendLine($"Enabled: {snapshot.Enabled}"); dump.AppendLine($"Debug mask view: {snapshot.DebugMaskView}"); dump.AppendLine($"Visibility target: {snapshot.VisibilityTarget}"); dump.AppendLine($"Night: {snapshot.IsNight}"); dump.AppendLine($"Wet weather: {snapshot.IsWetWeather}"); dump.AppendLine($"Auto-disable cloud shadows in rain: {snapshot.AutoDisableInRain}"); dump.AppendLine($"Under roof: {snapshot.IsUnderRoof}"); dump.AppendLine($"Effect fade: {snapshot.EffectFade:R}"); dump.AppendLine($"Caustics visibility target: {snapshot.CausticsVisibilityTarget}"); dump.AppendLine($"Caustics fade: {snapshot.CausticsFade:R}"); dump.AppendLine($"Caustics phase: {snapshot.CausticsPhase:R}"); dump.AppendLine($"Cloud render requested: {snapshot.CloudRenderRequested}"); dump.AppendLine($"Full-screen post pass requested: {snapshot.PostEffectRequested}"); dump.AppendLine($"Render requested: {snapshot.RenderRequested}"); dump.AppendLine($"Camera.onPreRender subscribed: {snapshot.PreRenderSubscribed}"); dump.AppendLine($"Settings revision: {snapshot.SettingsRevision}"); dump.AppendLine($"Target wind direction: {snapshot.TargetWindDirection}"); dump.AppendLine($"Target wind speed: {snapshot.TargetWindSpeed:R}"); dump.AppendLine($"Target wind intensity: {snapshot.TargetWindIntensity:R}"); dump.AppendLine($"Smoothed wind speed: {snapshot.SmoothedWindSpeed:R}"); dump.AppendLine($"Smoothed caustics wind direction: {snapshot.SmoothedCausticsWindDirection}"); dump.AppendLine($"Smoothed caustics wind intensity: {snapshot.SmoothedCausticsWindIntensity:R}"); dump.AppendLine($"Cloud offset: {snapshot.CloudOffset}"); dump.AppendLine($"Caustics wind offsets (A.xy, B.zw): {snapshot.CausticsWindOffsets}"); EnvironmentPaletteSnapshot environmentPalette = snapshot.EnvironmentPalette; if (environmentPalette == null) { dump.AppendLine("Enhanced Environment palette: "); } else { dump.AppendLine("Enhanced Environment palette Harmony patch installed: " + $"{environmentPalette.PatchInstalled}"); dump.AppendLine($"Enhanced Environment palette enabled: {environmentPalette.Enabled}"); dump.AppendLine($"Enhanced Environment palette strength: {environmentPalette.Strength:R}"); dump.AppendLine($"Enhanced Environment palette preset: {environmentPalette.Preset}"); dump.AppendLine("Enhanced Environment palette overrides sun angle: " + $"{environmentPalette.OverrideSunAngle}"); dump.AppendLine($"Enhanced Environment palette sun angle: {environmentPalette.SunAngle:R}"); dump.AppendLine("Enhanced Environment palette last environment: " + (environmentPalette.LastEnvironmentName ?? "")); } MeadowsFirefliesSnapshot meadowsFireflies = snapshot.MeadowsFireflies; if (meadowsFireflies == null) { dump.AppendLine("Meadows fireflies: "); } else { dump.AppendLine($"Meadows fireflies resources ready: {meadowsFireflies.ResourcesReady}"); dump.AppendLine($"Meadows fireflies active: {meadowsFireflies.Active}"); dump.AppendLine($"Meadows fireflies enabled: {meadowsFireflies.Enabled}"); dump.AppendLine($"Meadows fireflies particle count: {meadowsFireflies.ParticleCount}"); dump.AppendLine($"Meadows fireflies radius meters: {meadowsFireflies.RadiusMeters:R}"); dump.AppendLine($"Meadows fireflies brightness: {meadowsFireflies.Brightness:R}"); dump.AppendLine("Meadows fireflies auto-disable under roof: " + meadowsFireflies.AutoDisableUnderRoof); dump.AppendLine("Meadows fireflies state reason: " + meadowsFireflies.StateReason); } CloudShadowsRendererSnapshot renderer = snapshot.Renderer; if (renderer == null) { dump.AppendLine("Renderer: "); return; } dump.AppendLine($"Renderer resources ready: {renderer.ResourcesReady}"); dump.AppendLine("Bundle path: " + renderer.BundlePath); dump.AppendLine($"Bundle asset count: {renderer.BundleAssetCount}"); dump.AppendLine("Shader: " + renderer.ShaderName); dump.AppendLine("Runtime material: " + renderer.MaterialName); dump.AppendLine("Caustics texture: " + renderer.CausticsTextureName); dump.AppendLine("Caustics texture size: " + renderer.CausticsTextureSize); dump.AppendLine($"Caustics light color: {renderer.CausticsLightColor}"); dump.AppendLine($"Caustics light intensity: {renderer.CausticsLightIntensity:R}"); dump.AppendLine($"Caustics sun response: {renderer.CausticsSunResponse:R}"); dump.AppendLine($"Caustics enabled setting: {renderer.CausticsEnabled}"); dump.AppendLine($"Caustics intensity setting: {renderer.CausticsIntensity:R}"); dump.AppendLine("Caustics effective strength: " + $"{renderer.CausticsIntensity * snapshot.CausticsFade:R}"); dump.AppendLine($"Caustics pattern size meters setting: {renderer.CausticsPatternSizeMeters:R}"); dump.AppendLine($"Caustics animation speed setting: {renderer.CausticsAnimationSpeed:R}"); dump.AppendLine($"Caustics flowing motion setting: {renderer.CausticsFlowingMotion}"); dump.AppendLine($"Caustics maximum depth meters setting: {renderer.CausticsMaximumDepthMeters:R}"); dump.AppendLine($"Caustics draw distance meters setting: {renderer.CausticsDrawDistanceMeters:R}"); dump.AppendLine("Caustics state reason: " + GetCausticsStateReason(snapshot, renderer)); dump.AppendLine($"Full-screen post buffer attached: {renderer.CommandBufferAttached}"); dump.AppendLine("Attached camera: " + renderer.CameraName); dump.AppendLine("Attached camera actual rendering path: " + renderer.CameraRenderingPath); dump.AppendLine($"Attached camera HDR: {renderer.CameraAllowHdr}"); dump.AppendLine("Depth source: " + renderer.DepthSource); dump.AppendLine("Original depth mode: " + renderer.OriginalDepthMode); dump.AppendLine("Applied depth mode: " + renderer.AppliedDepthMode); dump.AppendLine("Current depth mode: " + renderer.CurrentDepthMode); dump.AppendLine($"Depth mode changed by Valheim Visual Enhanced: {renderer.DepthModeWasChanged}"); dump.AppendLine($"Camera commandBufferCount: {renderer.CameraCommandBufferCount}"); dump.AppendLine($"Last water level: {renderer.LastWaterLevel:R}"); dump.AppendLine($"Applied settings revision: {renderer.AppliedSettingsRevision}"); AppendDirectionalCookieState(dump, renderer.DirectionalCookie); } private static void AppendDirectionalCookieState(StringBuilder dump, CloudShadowsDirectionalCookieSnapshot cookie) { if (cookie == null) { dump.AppendLine("Cloud shadow mask: "); return; } dump.AppendLine($"Cloud shadow mask resources ready: {cookie.ResourcesReady}"); dump.AppendLine($"Cloud shadow mask available: {cookie.MaskAvailable}"); dump.AppendLine($"Cloud shadow lighting available: {cookie.LightingAvailable}"); dump.AppendLine("Cloud shadow generation buffer attached (AfterGBuffer): " + $"{cookie.GenerationBufferAttached}"); dump.AppendLine("Cloud shadow screen-space buffer attached (AfterScreenspaceMask): " + $"{cookie.ScreenSpaceBufferAttached}"); dump.AppendLine("Cloud shadow camera: " + cookie.CameraName); dump.AppendLine("Cloud shadow camera actual rendering path: " + cookie.CameraRenderingPath); dump.AppendLine("Cloud shadow directional light: " + cookie.LightName); dump.AppendLine("Cloud shadow directional light type: " + cookie.LightType); dump.AppendLine("Cloud shadow directional light shadows: " + cookie.LightShadows); dump.AppendLine("Cloud shadow mask texture: " + cookie.TextureName); dump.AppendLine("Cloud shadow mask texture size: " + cookie.TextureSize); dump.AppendLine("Cloud shadow mask texture format: " + cookie.TextureFormat); dump.AppendLine("Cloud shadow state reason: " + cookie.StateReason); } private static string GetCausticsStateReason(CloudShadowsRuntimeSnapshot runtime, CloudShadowsRendererSnapshot renderer) { //IL_00a5: 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_00bb: Unknown result type (might be due to invalid IL or missing references) if (!runtime.WorldReady) { return "world is not ready"; } if (!renderer.CausticsEnabled) { return "disabled by Water Caustic Lighting.Enabled"; } if (renderer.CausticsIntensity <= 0f) { return "disabled because Intensity is zero"; } if (runtime.DebugMaskView) { return "suppressed by cloud debug-mask view"; } if (runtime.IsNight) { return "disabled at night"; } if (runtime.IsUnderRoof) { return "disabled under roof or in a cave"; } if (!runtime.CausticsVisibilityTarget) { return "inactive while controller conditions are changing"; } if (runtime.CausticsFade <= 0.001f) { return "visibility target is active; effect is fading in"; } if (!runtime.RenderRequested) { return "rendering is not requested"; } if (!renderer.ResourcesReady) { return "renderer resources are unavailable"; } if (!renderer.CommandBufferAttached) { return "renderer is waiting for a camera attachment"; } float num = Mathf.Max(renderer.CausticsLightColor.r, Mathf.Max(renderer.CausticsLightColor.g, renderer.CausticsLightColor.b)); if (renderer.CausticsLightIntensity <= 0f || num <= 0f) { return "directional light supplies no usable energy"; } return "active"; } private static void AppendCameras(StringBuilder dump) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) List list = FindComponentsInLoadedScenes(); dump.AppendLine($"Camera count in loaded scenes: {list.Count}"); dump.AppendLine($"First cameras (limit {10}):"); for (int i = 0; i < list.Count && i < 10; i++) { Camera val = list[i]; try { string arg = (((Object)(object)val.targetTexture == (Object)null) ? "" : ((Object)val.targetTexture).name); dump.AppendLine($"[{i}] Name={((Object)val).name}; Type={val.cameraType}; " + $"Active={((Component)val).gameObject.activeInHierarchy}; Enabled={((Behaviour)val).enabled}; " + $"TargetTexture={arg}; ClearFlags={val.clearFlags}; " + "CullingMask=" + FormatMask(val.cullingMask) + "; " + $"RenderingPath={val.renderingPath}; " + $"ActualRenderingPath={val.actualRenderingPath}; " + $"DepthTextureMode={val.depthTextureMode}; HDR={val.allowHDR}; " + $"PixelSize={val.pixelWidth}x{val.pixelHeight}; " + $"CommandBufferCount={val.commandBufferCount}"); } catch (Exception exception) { AppendException(dump, $"Camera [{i}] could not be read", exception); } } } private static void AppendRenderSettings(StringBuilder dump) { Material skybox = null; try { skybox = RenderSettings.skybox; dump.AppendLine($"Skybox material exists: {(Object)(object)skybox != (Object)null}"); } catch (Exception exception) { AppendException(dump, "RenderSettings.skybox lookup failed", exception); } if ((Object)(object)skybox != (Object)null) { AppendSafeValue(dump, "Skybox material name", () => ((Object)skybox).name); AppendSafeValue(dump, "Skybox shader name", () => GetShaderName(skybox)); } AppendSafeValue(dump, "Ambient mode", () => RenderSettings.ambientMode); AppendSafeValue(dump, "Ambient intensity", () => RenderSettings.ambientIntensity); Light sun = null; try { sun = RenderSettings.sun; dump.AppendLine($"RenderSettings.sun exists: {(Object)(object)sun != (Object)null}"); } catch (Exception exception2) { AppendException(dump, "RenderSettings.sun lookup failed", exception2); } if ((Object)(object)sun != (Object)null) { AppendSafeValue(dump, "Sun light name", () => ((Object)sun).name); AppendSafeValue(dump, "Sun light type", () => sun.type); AppendSafeValue(dump, "Sun shadows enabled", () => (int)sun.shadows > 0); AppendSafeValue(dump, "Sun shadow mode", () => sun.shadows); AppendSafeValue(dump, "Sun shadowStrength", () => sun.shadowStrength); AppendSafeValue(dump, "Sun cookie", () => GetObjectName((Object)(object)sun.cookie)); AppendSafeValue(dump, "Sun cookieSize", () => sun.cookieSize); } AppendSafeValue(dump, "Fog enabled", () => RenderSettings.fog); AppendSafeValue(dump, "Fog color", () => RenderSettings.fogColor); AppendSafeValue(dump, "Fog mode", () => RenderSettings.fogMode); AppendSafeValue(dump, "Fog density", () => RenderSettings.fogDensity); AppendSafeValue(dump, "Fog start distance", () => RenderSettings.fogStartDistance); AppendSafeValue(dump, "Fog end distance", () => RenderSettings.fogEndDistance); AppendSafeValue(dump, "Default reflection mode", () => RenderSettings.defaultReflectionMode); } private static void AppendLights(StringBuilder dump) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Invalid comparison between Unknown and I4 //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) List list = FindComponentsInLoadedScenes(); dump.AppendLine($"Light count in loaded scenes: {list.Count}"); dump.AppendLine($"First lights (limit {20}):"); for (int i = 0; i < list.Count && i < 20; i++) { Light val = list[i]; try { dump.AppendLine($"[{i}] Name={((Object)val).name}; Type={val.type}; " + $"ShadowsEnabled={(int)val.shadows > 0}; ShadowMode={val.shadows}; " + $"ShadowStrength={val.shadowStrength}; Range={val.range}; Color={val.color}; " + $"Cookie={GetObjectName((Object)(object)val.cookie)}; CookieSize={val.cookieSize}; " + "CullingMask=" + FormatMask(val.cullingMask)); } catch (Exception exception) { AppendException(dump, $"Light [{i}] could not be read", exception); } } } private static void AppendRelatedObjects(StringBuilder dump) { //IL_0082: Unknown result type (might be due to invalid IL or missing references) GameObject[] array; try { array = Resources.FindObjectsOfTypeAll(); } catch (Exception exception) { AppendException(dump, "GameObject discovery failed", exception); return; } HashSet hashSet = new HashSet(); int num = 0; int num2 = 0; GameObject[] array2 = array; foreach (GameObject val in array2) { try { if ((Object)(object)val == (Object)null || !ContainsKeyword(((Object)val).name, ObjectKeywords)) { continue; } int instanceID = ((Object)val).GetInstanceID(); if (hashSet.Add(instanceID)) { num++; if (num2 < 150) { string arg = FormatScene(val.scene); string hierarchyPath = GetHierarchyPath(val.transform); string objectTypeSummary = GetObjectTypeSummary(val); dump.AppendLine($"[{num2}] Name={((Object)val).name}; Types={objectTypeSummary}; " + $"ActiveSelf={val.activeSelf}; Scene={arg}; Hierarchy={hierarchyPath}"); num2++; } } } catch (Exception exception2) { AppendException(dump, "A related GameObject could not be read", exception2); } } dump.AppendLine($"Unique matching objects: {num}; reported: {num2}; limit: {150}"); } private static void AppendShaders(StringBuilder dump) { Shader[] array; try { array = Resources.FindObjectsOfTypeAll(); } catch (Exception exception) { AppendException(dump, "Shader discovery failed", exception); return; } HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); Shader[] array2 = array; foreach (Shader val in array2) { try { if ((Object)(object)val != (Object)null && ContainsKeyword(((Object)val).name, ShaderKeywords)) { hashSet.Add(((Object)val).name); } } catch (Exception exception2) { AppendException(dump, "A shader could not be read", exception2); } } List list = hashSet.OrderBy((string name) => name, StringComparer.OrdinalIgnoreCase).ToList(); dump.AppendLine($"Unique matching shaders: {list.Count}; reported limit: {200}"); for (int num = 0; num < list.Count && num < 200; num++) { dump.AppendLine($"[{num}] {list[num]}"); } } private static void AppendMaterials(StringBuilder dump) { Material[] array; try { array = Resources.FindObjectsOfTypeAll(); } catch (Exception exception) { AppendException(dump, "Material discovery failed", exception); return; } Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); Material[] array2 = array; foreach (Material val in array2) { try { if (!((Object)(object)val == (Object)null) && ContainsKeyword(((Object)val).name, MaterialKeywords) && !dictionary.ContainsKey(((Object)val).name)) { dictionary.Add(((Object)val).name, GetShaderName(val)); } } catch (Exception exception2) { AppendException(dump, "A material could not be read", exception2); } } List> list = dictionary.OrderBy, string>((KeyValuePair pair) => pair.Key, StringComparer.OrdinalIgnoreCase).ToList(); dump.AppendLine($"Unique matching materials: {list.Count}; reported limit: {200}"); for (int num = 0; num < list.Count && num < 200; num++) { KeyValuePair keyValuePair = list[num]; dump.AppendLine($"[{num}] Name={keyValuePair.Key}; Shader={keyValuePair.Value}"); } } private static void AppendRenderers(StringBuilder dump) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) Scene activeScene; Renderer[] array; try { activeScene = SceneManager.GetActiveScene(); array = Resources.FindObjectsOfTypeAll(); } catch (Exception exception) { AppendException(dump, "Renderer discovery failed", exception); return; } List list = new List(200); int num = 0; Renderer[] array2 = array; foreach (Renderer val in array2) { try { if (IsComponentInScene((Component)(object)val, activeScene)) { num++; if (list.Count < 200) { list.Add(val); } } } catch (Exception exception2) { AppendException(dump, "A renderer could not be assigned to a scene", exception2); } } Dictionary counts = new Dictionary(StringComparer.OrdinalIgnoreCase); Dictionary counts2 = new Dictionary(StringComparer.OrdinalIgnoreCase); List list2 = new List(30); for (int j = 0; j < list.Count; j++) { Renderer val2 = list[j]; try { object obj = ((object)val2.sharedMaterials) ?? ((object)new Material[0]); List list3 = new List(); List list4 = new List(); Material[] array3 = (Material[])obj; foreach (Material val3 in array3) { if ((Object)(object)val3 == (Object)null) { list3.Add(""); list4.Add(""); continue; } string name = ((Object)val3).name; string shaderName = GetShaderName(val3); list3.Add(name); list4.Add(shaderName); IncrementCount(counts2, name); IncrementCount(counts, shaderName); } if (list2.Count < 30) { list2.Add($"[{j}] GameObject={((Object)((Component)val2).gameObject).name}; Layer={((Component)val2).gameObject.layer}; " + "RendererType=" + ((object)val2).GetType().FullName + "; Materials=[" + string.Join(", ", list3) + "]; Shaders=[" + string.Join(", ", list4) + "]"); } } catch (Exception exception3) { AppendException(dump, $"Renderer [{j}] could not be read", exception3); } } dump.AppendLine("Active scene: " + FormatScene(activeScene)); dump.AppendLine($"Renderer count in active scene: {num}"); dump.AppendLine($"Renderer sample size: {list.Count}; limit: {200}"); dump.AppendLine("Shader usage in sampled renderers:"); AppendCounts(dump, counts); dump.AppendLine("Material usage in sampled renderers:"); AppendCounts(dump, counts2); dump.AppendLine($"First renderer details (limit {30}):"); foreach (string item in list2) { dump.AppendLine(item); } } private static List FindComponentsInLoadedScenes() where T : Component { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: 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) //IL_005c: Unknown result type (might be due to invalid IL or missing references) List list = new List(); T[] array; try { array = Resources.FindObjectsOfTypeAll(); } catch { throw; } T[] array2 = array; foreach (T val in array2) { try { if (!((Object)(object)val != (Object)null)) { continue; } Scene scene = ((Component)val).gameObject.scene; if (((Scene)(ref scene)).IsValid()) { scene = ((Component)val).gameObject.scene; if (((Scene)(ref scene)).isLoaded) { list.Add(val); } } } catch { } } return list; } private static bool IsComponentInScene(Component component, Scene scene) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //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) try { int result; if ((Object)(object)component != (Object)null && ((Scene)(ref scene)).IsValid()) { Scene scene2 = component.gameObject.scene; if (((Scene)(ref scene2)).IsValid()) { result = ((component.gameObject.scene == scene) ? 1 : 0); goto IL_003b; } } result = 0; goto IL_003b; IL_003b: return (byte)result != 0; } catch { return false; } } private static string GetObjectTypeSummary(GameObject gameObject) { try { string componentTypeNames = GetComponentTypeNames(gameObject); if (!string.IsNullOrEmpty(componentTypeNames)) { return componentTypeNames; } Transform parent = gameObject.transform.parent; if ((Object)(object)parent != (Object)null) { string componentTypeNames2 = GetComponentTypeNames(((Component)parent).gameObject); if (!string.IsNullOrEmpty(componentTypeNames2)) { return "ParentComponents=" + componentTypeNames2; } } return ((object)gameObject).GetType().FullName; } catch (Exception exception) { return ""; } } private static string GetComponentTypeNames(GameObject gameObject) { try { Component[] components = gameObject.GetComponents(); return string.Join(",", (from component in components where (Object)(object)component != (Object)null select ((object)component).GetType().FullName).Distinct(StringComparer.Ordinal).Take(8)); } catch (Exception exception) { return ""; } } private static string GetHierarchyPath(Transform transform) { try { Stack stack = new Stack(); Transform val = transform; int num = 0; while ((Object)(object)val != (Object)null && num < 64) { stack.Push(((Object)val).name); val = val.parent; num++; } string text = string.Join("/", stack.ToArray()); return ((Object)(object)val == (Object)null) ? text : (".../" + text); } catch (Exception exception) { return ""; } } private static string FormatScene(Scene scene) { try { if (!((Scene)(ref scene)).IsValid()) { return ""; } string arg = (string.IsNullOrEmpty(((Scene)(ref scene)).path) ? "" : ((Scene)(ref scene)).path); return $"Name={((Scene)(ref scene)).name}; Path={arg}; Loaded={((Scene)(ref scene)).isLoaded}"; } catch (Exception exception) { return ""; } } private static string GetObjectName(Object unityObject) { try { return (unityObject == (Object)null) ? "" : unityObject.name; } catch (Exception exception) { return ""; } } private static string GetShaderName(Material material) { try { return ((Object)(object)material == (Object)null || (Object)(object)material.shader == (Object)null) ? "" : ((Object)material.shader).name; } catch (Exception exception) { return ""; } } private static bool ContainsKeyword(string value, IEnumerable keywords) { try { if (string.IsNullOrEmpty(value)) { return false; } foreach (string keyword in keywords) { if (value.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } return false; } catch { return false; } } private static string FormatMask(int mask) { try { return $"{mask} (0x{(uint)mask:X8})"; } catch (Exception exception) { return ""; } } private static void IncrementCount(IDictionary counts, string name) { try { string key = (string.IsNullOrEmpty(name) ? "" : name); counts[key] = ((!counts.TryGetValue(key, out var value)) ? 1 : (value + 1)); } catch { } } private static void AppendCounts(StringBuilder dump, IDictionary counts) { try { if (counts.Count == 0) { dump.AppendLine(""); return; } foreach (KeyValuePair item in counts.OrderByDescending((KeyValuePair pair) => pair.Value).ThenBy, string>((KeyValuePair pair) => pair.Key, StringComparer.OrdinalIgnoreCase)) { dump.AppendLine($"{item.Key}: {item.Value}"); } } catch (Exception exception) { AppendException(dump, "Count aggregation could not be written", exception); } } private static void AppendSafeValue(StringBuilder dump, string label, Func getValue) { try { object obj = getValue(); dump.AppendLine(string.Format("{0}: {1}", label, obj ?? "")); } catch (Exception exception) { AppendException(dump, label + " could not be read", exception); } } private static void AppendException(StringBuilder dump, string context, Exception exception) { try { dump.AppendLine("[ERROR] " + context + ": " + FormatException(exception)); } catch { } } private static string FormatException(Exception exception) { try { return (exception == null) ? "" : (exception.GetType().Name + ": " + exception.Message); } catch { return ""; } } private static void TryLogError(ManualLogSource logger, string context, Exception exception) { try { logger.LogError((object)(context + ": " + FormatException(exception))); } catch { } } } internal sealed class CloudShadowsDirectionalCookieSnapshot { internal bool ResourcesReady { get; set; } internal bool MaskAvailable { get; set; } internal bool LightingAvailable { get; set; } internal bool GenerationBufferAttached { get; set; } internal bool ScreenSpaceBufferAttached { get; set; } internal string CameraName { get; set; } internal string CameraRenderingPath { get; set; } internal string LightName { get; set; } internal string LightType { get; set; } internal string LightShadows { get; set; } internal string TextureName { get; set; } internal string TextureSize { get; set; } internal string TextureFormat { get; set; } internal string StateReason { get; set; } } internal sealed class CloudShadowsDirectionalCookie : IDisposable { private const float CloudPlaneHeightMeters = 1000f; private const float MaskFadeStartFraction = 0.4f; private const float MinimumMaskRadiusMeters = 1f; private const float MinimumLightVerticalComponent = 0.001f; private const float HorizonFadeStart = 0.08f; private const float HorizonFadeEnd = 0.2f; private const float ResourceRetryIntervalSeconds = 5f; private const string MaskTextureName = "CloudShadows Directional Mask"; private const string GenerationBufferName = "CloudShadows Mask Generation"; private const string ApplicationBufferName = "CloudShadows Screen-Space Shadow Mask"; private const int MaskGenerationPass = 1; private const int ScreenSpaceShadowPass = 2; private const CameraEvent GenerationCameraEvent = (CameraEvent)5; private const LightEvent ApplicationLightEvent = (LightEvent)3; private static readonly int CloudScaleId = Shader.PropertyToID("_CloudScale"); private static readonly int CloudCoverageId = Shader.PropertyToID("_CloudCoverage"); private static readonly int CloudSoftnessId = Shader.PropertyToID("_CloudSoftness"); private static readonly int ShadowStrengthId = Shader.PropertyToID("_ShadowStrength"); private static readonly int CloudOffsetId = Shader.PropertyToID("_CloudOffset"); private static readonly int CloudEffectFadeId = Shader.PropertyToID("_CloudEffectFade"); private static readonly int DebugMaskId = Shader.PropertyToID("_DebugMask"); private static readonly int MaskHorizonFadeId = Shader.PropertyToID("_CookieHorizonFade"); private static readonly int MaskFadeStartId = Shader.PropertyToID("_CookieFadeStart"); private static readonly int MaskFadeEndId = Shader.PropertyToID("_CookieFadeEnd"); private static readonly int MaskUvToCloudXzId = Shader.PropertyToID("_CookieUvToCloudXZ"); private static readonly int CloudMaskTextureId = Shader.PropertyToID("_CloudCookieTex"); private static readonly int CloudMaskWorldToUvId = Shader.PropertyToID("_CloudCookieWorldToUv"); private static readonly int FrustumCornersWsId = Shader.PropertyToID("_FrustumCornersWS"); private static readonly int CameraWsId = Shader.PropertyToID("_CameraWS"); private static readonly int UseDepthNormalsId = Shader.PropertyToID("_UseDepthNormals"); private readonly ManualLogSource _logger; private readonly CloudShadowsConfig _settings; private Material _material; private RenderTexture _texture; private Camera _camera; private Light _light; private CommandBuffer _generationBuffer; private CommandBuffer _applicationBuffer; private Matrix4x4 _worldToMaskUv = Matrix4x4.identity; private bool _unsupportedPathWarningWasLogged; private bool _shadowMaskWarningWasLogged; private bool _resourceWarningWasLogged; private bool _detachWarningWasLogged; private bool _r8FallbackWarningWasLogged; private bool _disposed; private int _lastAppliedSettingsRevision = -1; private float _nextResourceRetryTime; private string _stateReason = "inactive"; internal Texture Texture => (Texture)(object)_texture; internal Matrix4x4 WorldToCookieUv => _worldToMaskUv; internal bool MaskAvailable { get { if (!_disposed && (Object)(object)_texture != (Object)null && _texture.IsCreated() && (Object)(object)_camera != (Object)null) { return _generationBuffer != null; } return false; } } internal bool LightingAvailable { get { if (MaskAvailable && (Object)(object)_light != (Object)null) { return _applicationBuffer != null; } return false; } } internal bool HasAttachedBuffers { get { if (!((Object)(object)_camera != (Object)null) && !((Object)(object)_light != (Object)null) && _generationBuffer == null) { return _applicationBuffer != null; } return true; } } internal CloudShadowsDirectionalCookie(ManualLogSource logger, CloudShadowsConfig settings, Material material) { //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) _logger = logger; _settings = settings ?? throw new ArgumentNullException("settings"); _material = material ?? throw new ArgumentNullException("material"); } internal bool UpdateForCamera(Camera camera, bool cloudRenderRequested, float effectFade, Vector2 cloudOffset, Vector3 cameraPosition, float waterLevel, Matrix4x4 frustumCornersWs, bool useDepthNormals) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Invalid comparison between Unknown and I4 //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) if (_disposed) { return false; } if (!cloudRenderRequested) { if (HasAttachedBuffers && !Detach()) { return false; } _stateReason = "cloud rendering is not requested"; return false; } try { if (Time.unscaledTime < _nextResourceRetryTime) { return false; } if ((Object)(object)camera == (Object)null) { Detach(); _stateReason = "Camera.main is unavailable"; return false; } if ((int)camera.actualRenderingPath != 3) { Detach(); _stateReason = $"unsupported camera rendering path: {camera.actualRenderingPath}"; if (!_unsupportedPathWarningWasLogged) { LogWarning("CloudShadows screen-space shadow mask requires DeferredShading; cloud shadows are disabled for " + ((object)camera.actualRenderingPath/*cast due to .constrained prefix*/).ToString()); _unsupportedPathWarningWasLogged = true; } return false; } _unsupportedPathWarningWasLogged = false; Light directionalLight = GetDirectionalLight(); if ((Object)(object)directionalLight == (Object)null) { Detach(); _stateReason = "EnvMan.m_dirLight is unavailable or is not directional"; return false; } if ((Object)(object)_camera != (Object)null && (Object)(object)_camera != (Object)(object)camera && !Detach()) { return false; } if ((Object)(object)_light != (Object)(object)directionalLight) { if (!RemoveApplicationBuffer()) { return false; } _light = null; } float num = CalculateHorizonFade(directionalLight); if (!_settings.DebugMaskView && num <= 0f) { if (!Detach()) { return false; } _stateReason = "directional light is below the cloud-mask horizon"; return false; } EnsureTexture(); EnsureGenerationBuffer(camera); _light = directionalLight; float num2 = Mathf.Max(_settings.ShadowDrawDistance, 1f); float maskSize = num2 * 2f; UpdateMaterial(directionalLight, cameraPosition, waterLevel, num2, maskSize, effectFade, cloudOffset, frustumCornersWs, useDepthNormals, num); if (!HasScreenSpaceShadows(directionalLight)) { if (!RemoveApplicationBuffer()) { return false; } _light = directionalLight; _stateReason = "directional screen-space shadows are disabled"; if (!_shadowMaskWarningWasLogged) { LogWarning("CloudShadows cloud lighting is waiting because directional screen-space shadows are disabled"); _shadowMaskWarningWasLogged = true; } return MaskAvailable; } EnsureApplicationBuffer(directionalLight); _shadowMaskWarningWasLogged = false; _resourceWarningWasLogged = false; _nextResourceRetryTime = 0f; _stateReason = "active"; return MaskAvailable; } catch (Exception exception) { _nextResourceRetryTime = Time.unscaledTime + 5f; string text = (_stateReason = "update failed: " + FormatException(exception)); if (!_resourceWarningWasLogged) { LogWarning("CloudShadows screen-space shadow mask update failed: " + text); _resourceWarningWasLogged = true; } Detach(); _stateReason = text; return false; } } internal bool Detach() { //IL_0023: 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) bool num = RemoveApplicationBuffer(); bool flag = RemoveGenerationBuffer(); if (!num || !flag) { return false; } _camera = null; _light = null; _worldToMaskUv = Matrix4x4.identity; _stateReason = "inactive"; _detachWarningWasLogged = false; return true; } internal CloudShadowsDirectionalCookieSnapshot CreateSnapshot() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) string cameraRenderingPath = ""; try { if ((Object)(object)_camera != (Object)null) { cameraRenderingPath = ((object)_camera.actualRenderingPath/*cast due to .constrained prefix*/).ToString(); } } catch (Exception exception) { cameraRenderingPath = ""; } Light light = _light; return new CloudShadowsDirectionalCookieSnapshot { ResourcesReady = ((Object)(object)_material != (Object)null && (Object)(object)_texture != (Object)null && _texture.IsCreated()), MaskAvailable = MaskAvailable, LightingAvailable = LightingAvailable, GenerationBufferAttached = ((Object)(object)_camera != (Object)null && _generationBuffer != null), ScreenSpaceBufferAttached = ((Object)(object)light != (Object)null && _applicationBuffer != null), CameraName = GetObjectName((Object)(object)_camera), CameraRenderingPath = cameraRenderingPath, LightName = GetObjectName((Object)(object)light), LightType = (((Object)(object)light == (Object)null) ? "" : ((object)light.type/*cast due to .constrained prefix*/).ToString()), LightShadows = (((Object)(object)light == (Object)null) ? "" : ((object)light.shadows/*cast due to .constrained prefix*/).ToString()), TextureName = GetObjectName((Object)(object)_texture), TextureSize = (((Object)(object)_texture == (Object)null) ? "" : $"{((Texture)_texture).width}x{((Texture)_texture).height}"), TextureFormat = (((Object)(object)_texture == (Object)null) ? "" : ((object)_texture.format/*cast due to .constrained prefix*/).ToString()), StateReason = _stateReason }; } public void Dispose() { if (!_disposed) { if (!Detach()) { LogWarning("CloudShadows screen-space mask disposal kept resources alive because a camera or light command buffer could not be detached safely"); return; } _disposed = true; ReleaseTexture(); Material material = _material; _material = null; DestroyUnityObject((Object)(object)material); } } private void EnsureTexture() { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0094: 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_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Expected O, but got Unknown //IL_00e8: Unknown result type (might be due to invalid IL or missing references) int cloudMaskResolution = _settings.CloudMaskResolution; if ((Object)(object)_texture != (Object)null && (((Texture)_texture).width != cloudMaskResolution || ((Texture)_texture).height != cloudMaskResolution)) { if (!RemoveGenerationBuffer()) { throw new InvalidOperationException("previous cloud mask generation buffer remains attached"); } _camera = null; ReleaseTexture(); } if ((Object)(object)_texture == (Object)null) { _texture = new RenderTexture(cloudMaskResolution, cloudMaskResolution, 0, GetMaskTextureFormat(), (RenderTextureReadWrite)1) { name = "CloudShadows Directional Mask", filterMode = (FilterMode)1, wrapMode = (TextureWrapMode)1, useMipMap = false, autoGenerateMips = false, antiAliasing = 1, hideFlags = (HideFlags)61 }; } if (!_texture.IsCreated()) { if (!_texture.Create()) { throw new InvalidOperationException("RenderTexture.Create returned false"); } RenderTexture active = RenderTexture.active; try { RenderTexture.active = _texture; GL.Clear(false, true, Color.black); } finally { RenderTexture.active = active; } _resourceWarningWasLogged = false; } } private void EnsureGenerationBuffer(Camera camera) { //IL_003d: 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) //IL_004e: Expected O, but got Unknown //IL_005a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_camera == (Object)(object)camera && _generationBuffer != null) { return; } if (_generationBuffer != null) { if (!RemoveGenerationBuffer()) { throw new InvalidOperationException("previous cloud mask generation buffer remains attached"); } _camera = null; } CommandBuffer val = null; bool flag = false; try { val = new CommandBuffer { name = "CloudShadows Mask Generation" }; val.Blit((Texture)(object)Texture2D.whiteTexture, RenderTargetIdentifier.op_Implicit((Texture)(object)_texture), _material, 1); camera.AddCommandBuffer((CameraEvent)5, val); flag = true; _camera = camera; _generationBuffer = val; val = null; } catch { if (flag && val != null) { _camera = camera; _generationBuffer = val; val = null; RemoveGenerationBuffer(); } ReleaseCommandBuffer(val); throw; } } private void EnsureApplicationBuffer(Light light) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_004e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_light == (Object)(object)light && _applicationBuffer != null) { return; } if (_applicationBuffer != null && !RemoveApplicationBuffer()) { throw new InvalidOperationException("previous screen-space shadow command buffer remains attached"); } CommandBuffer val = null; bool flag = false; try { val = new CommandBuffer { name = "CloudShadows Screen-Space Shadow Mask" }; val.Blit((Texture)(object)Texture2D.whiteTexture, RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)1), _material, 2); light.AddCommandBuffer((LightEvent)3, val); flag = true; _light = light; _applicationBuffer = val; val = null; } catch { if (flag && val != null) { _light = light; _applicationBuffer = val; val = null; RemoveApplicationBuffer(); } ReleaseCommandBuffer(val); throw; } } private void UpdateMaterial(Light light, Vector3 cameraPosition, float waterLevel, float maskRadius, float maskSize, float effectFade, Vector2 cloudOffset, Matrix4x4 frustumCornersWs, bool useDepthNormals, float horizonFade) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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) //IL_0014: 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) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0024: 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) //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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //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) //IL_0049: 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_0079: 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_007b: 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_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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_00a6: 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) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) Transform transform = ((Component)light).transform; Vector3 forward = transform.forward; Vector3 right = transform.right; Vector3 up = transform.up; Vector3 position = transform.position; Vector3 val = position + forward * Vector3.Dot(cameraPosition - position, forward); bool flag = waterLevel > -9999f && cameraPosition.y < waterLevel; float num = ((_settings.DebugMaskView || flag) ? 0f : Mathf.Clamp01(effectFade)); Matrix4x4 val2 = BuildUvToCloudXz(val, right, up, forward, maskSize); _worldToMaskUv = BuildWorldToMaskUv(transform, val, maskSize); ApplyStaticSettingsIfNeeded(); _material.SetVector(CloudOffsetId, new Vector4(cloudOffset.x, cloudOffset.y, 0f, 0f)); _material.SetFloat(CloudEffectFadeId, num); _material.SetFloat(MaskHorizonFadeId, _settings.DebugMaskView ? 1f : horizonFade); _material.SetFloat(MaskFadeStartId, maskRadius * 0.4f); _material.SetFloat(MaskFadeEndId, maskRadius); _material.SetMatrix(MaskUvToCloudXzId, val2); _material.SetTexture(CloudMaskTextureId, (Texture)(object)_texture); _material.SetMatrix(CloudMaskWorldToUvId, _worldToMaskUv); _material.SetMatrix(FrustumCornersWsId, frustumCornersWs); _material.SetVector(CameraWsId, new Vector4(cameraPosition.x, cameraPosition.y, cameraPosition.z, 1f)); _material.SetFloat(UseDepthNormalsId, useDepthNormals ? 1f : 0f); } private void ApplyStaticSettingsIfNeeded() { if (_lastAppliedSettingsRevision != _settings.Revision) { _material.SetFloat(CloudScaleId, 1f / Mathf.Max(_settings.CloudSizeMeters, 0.0001f)); _material.SetFloat(CloudCoverageId, _settings.CloudCoverage); _material.SetFloat(CloudSoftnessId, _settings.EdgeSoftness); _material.SetFloat(ShadowStrengthId, _settings.ShadowStrength); _material.SetFloat(DebugMaskId, _settings.DebugMaskView ? 1f : 0f); _lastAppliedSettingsRevision = _settings.Revision; } } private RenderTextureFormat GetMaskTextureFormat() { if (SystemInfo.SupportsRenderTextureFormat((RenderTextureFormat)16)) { _r8FallbackWarningWasLogged = false; return (RenderTextureFormat)16; } if (!_r8FallbackWarningWasLogged) { LogWarning("CloudShadows R8 cloud-mask render texture is unsupported; using ARGB32 compatibility fallback"); _r8FallbackWarningWasLogged = true; } return (RenderTextureFormat)0; } private static float CalculateHorizonFade(Light light) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) float num = 0f - ((Component)light).transform.forward.y; return Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.08f, 0.2f, num)); } private bool RemoveGenerationBuffer() { CommandBuffer generationBuffer = _generationBuffer; if (generationBuffer == null) { return true; } if ((Object)(object)_camera != (Object)null && !TryRemoveCameraBuffer(_camera, (CameraEvent)5, generationBuffer)) { LogDetachFailure("cloud mask generation camera buffer"); return false; } _generationBuffer = null; ReleaseCommandBuffer(generationBuffer); return true; } private bool RemoveApplicationBuffer() { CommandBuffer applicationBuffer = _applicationBuffer; if (applicationBuffer == null) { return true; } if ((Object)(object)_light != (Object)null && !TryRemoveLightBuffer(_light, (LightEvent)3, applicationBuffer)) { LogDetachFailure("screen-space shadow light buffer"); return false; } _applicationBuffer = null; ReleaseCommandBuffer(applicationBuffer); return true; } private void LogDetachFailure(string resource) { if (!_detachWarningWasLogged) { LogWarning("CloudShadows could not remove its " + resource); _detachWarningWasLogged = true; } } private void ReleaseTexture() { RenderTexture texture = _texture; _texture = null; if ((Object)(object)texture == (Object)null) { return; } try { if (texture.IsCreated()) { texture.Release(); } } catch (Exception exception) { LogWarning("CloudShadows directional mask RenderTexture.Release failed: " + FormatException(exception)); } DestroyUnityObject((Object)(object)texture); } private static Matrix4x4 BuildUvToCloudXz(Vector3 center, Vector3 right, Vector3 up, Vector3 forward, float maskSize) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000a: 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) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_002f: 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_003d: 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) //IL_004b: 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_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_005b: 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) //IL_005d: 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_006b: 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_0079: 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_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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_0091: 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_0097: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: 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_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) Vector3 val = IntersectCloudPlane(center - right * (maskSize * 0.5f) - up * (maskSize * 0.5f), forward); Vector3 val2 = IntersectCloudPlane(center + right * (maskSize * 0.5f) - up * (maskSize * 0.5f), forward); Vector3 val3 = IntersectCloudPlane(center - right * (maskSize * 0.5f) + up * (maskSize * 0.5f), forward); Vector3 val4 = val2 - val; Vector3 val5 = val3 - val; Matrix4x4 zero = Matrix4x4.zero; ((Matrix4x4)(ref zero)).SetRow(0, new Vector4(val4.x, val5.x, 0f, val.x)); ((Matrix4x4)(ref zero)).SetRow(1, new Vector4(val4.z, val5.z, 0f, val.z)); ((Matrix4x4)(ref zero)).SetRow(2, new Vector4(0f, 0f, 1f, 0f)); ((Matrix4x4)(ref zero)).SetRow(3, new Vector4(0f, 0f, 0f, 1f)); return zero; } private static Vector3 IntersectCloudPlane(Vector3 point, Vector3 direction) { //IL_0000: 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_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) float num = direction.y; if (Mathf.Abs(num) < 0.001f) { num = ((num < 0f) ? (-0.001f) : 0.001f); } float num2 = (1000f - point.y) / num; return point + direction * num2; } private static Matrix4x4 BuildWorldToMaskUv(Transform lightTransform, Vector3 maskCenter, float maskSize) { //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) //IL_000a: 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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: 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_002d: 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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) Matrix4x4 worldToLocalMatrix = lightTransform.worldToLocalMatrix; Vector4 val = ((Matrix4x4)(ref worldToLocalMatrix)).GetRow(0) / maskSize; Vector4 val2 = ((Matrix4x4)(ref worldToLocalMatrix)).GetRow(1) / maskSize; Vector3 val3 = ((Matrix4x4)(ref worldToLocalMatrix)).MultiplyPoint3x4(maskCenter); val.w += 0.5f - val3.x / maskSize; val2.w += 0.5f - val3.y / maskSize; Matrix4x4 identity = Matrix4x4.identity; ((Matrix4x4)(ref identity)).SetRow(0, val); ((Matrix4x4)(ref identity)).SetRow(1, val2); return identity; } private static bool HasScreenSpaceShadows(Light light) { //IL_000a: 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_0017: Invalid comparison between Unknown and I4 if ((Object)(object)light != (Object)null && (int)light.shadows != 0) { return (int)QualitySettings.shadows > 0; } return false; } private static Light GetDirectionalLight() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 EnvMan instance = EnvMan.instance; Light val = (((Object)(object)instance == (Object)null) ? null : instance.m_dirLight); if (!((Object)(object)val != (Object)null) || (int)val.type != 1) { return null; } return val; } private static bool TryRemoveCameraBuffer(Camera camera, CameraEvent cameraEvent, CommandBuffer buffer) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) try { camera.RemoveCommandBuffer(cameraEvent, buffer); return true; } catch { return false; } } private static bool TryRemoveLightBuffer(Light light, LightEvent lightEvent, CommandBuffer buffer) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) try { light.RemoveCommandBuffer(lightEvent, buffer); return true; } catch { return false; } } private static void ReleaseCommandBuffer(CommandBuffer buffer) { try { if (buffer != null) { buffer.Release(); } } catch { } } private static void DestroyUnityObject(Object unityObject) { if (!(unityObject == (Object)null)) { if (Application.isPlaying) { Object.Destroy(unityObject); } else { Object.DestroyImmediate(unityObject); } } } private static string GetObjectName(Object unityObject) { if (!(unityObject == (Object)null)) { return unityObject.name; } return ""; } private static string FormatException(Exception exception) { if (exception != null) { return exception.GetType().Name + ": " + exception.Message; } return ""; } private void LogWarning(string message) { try { ManualLogSource logger = _logger; if (logger != null) { logger.LogWarning((object)message); } } catch { } } } internal sealed class CloudShadowsErrorLimiter { private const int ErrorLogIntervalSeconds = 10; private static readonly long ErrorLogIntervalTicks = Stopwatch.Frequency * 10; private readonly ManualLogSource _logger; private Dictionary _nextLogTimeByContext; internal CloudShadowsErrorLimiter(ManualLogSource logger) { _logger = logger; } internal void LogError(string context, Exception exception) { try { if (TryReserveLog(context, out var key)) { string text = ((exception == null) ? "" : exception.ToString()); ManualLogSource logger = _logger; if (logger != null) { logger.LogError((object)(key + ": " + text)); } } } catch { } } internal void LogError(string context, string detail) { try { if (TryReserveLog(context, out var key)) { ManualLogSource logger = _logger; if (logger != null) { logger.LogError((object)(key + ": " + detail)); } } } catch { } } private bool TryReserveLog(string context, out string key) { key = (string.IsNullOrEmpty(context) ? "" : context); long timestamp = Stopwatch.GetTimestamp(); if (_nextLogTimeByContext != null && _nextLogTimeByContext.TryGetValue(key, out var value) && timestamp < value) { return false; } if (_nextLogTimeByContext == null) { _nextLogTimeByContext = new Dictionary(StringComparer.Ordinal); } _nextLogTimeByContext[key] = timestamp + ErrorLogIntervalTicks; return true; } } internal sealed class CloudShadowsRuntimeSnapshot { internal bool WorldReady { get; set; } internal bool VisibilityTarget { get; set; } internal bool Enabled { get; set; } internal bool DebugMaskView { get; set; } internal bool IsNight { get; set; } internal bool IsWetWeather { get; set; } internal bool IsUnderRoof { get; set; } internal bool AutoDisableInRain { get; set; } internal float EffectFade { get; set; } internal bool CausticsVisibilityTarget { get; set; } internal float CausticsFade { get; set; } internal float CausticsPhase { get; set; } internal bool CloudRenderRequested { get; set; } internal bool PostEffectRequested { get; set; } internal bool RenderRequested { get; set; } internal bool PreRenderSubscribed { get; set; } internal Vector2 TargetWindDirection { get; set; } internal float TargetWindSpeed { get; set; } internal float TargetWindIntensity { get; set; } internal float SmoothedWindSpeed { get; set; } internal Vector2 SmoothedCausticsWindDirection { get; set; } internal float SmoothedCausticsWindIntensity { get; set; } internal Vector2 CloudOffset { get; set; } internal Vector4 CausticsWindOffsets { get; set; } internal int SettingsRevision { get; set; } internal EnvironmentPaletteSnapshot EnvironmentPalette { get; set; } internal MeadowsFirefliesSnapshot MeadowsFireflies { get; set; } internal CloudShadowsRendererSnapshot Renderer { get; set; } } internal sealed class CloudShadowsPostEffect : IDisposable { private const float CameraCheckIntervalSeconds = 1f; private const float WindUpdateIntervalSeconds = 0.1f; private const float WindSmoothingTimeSeconds = 3f; private const float CausticsWindDirectionSmoothingTimeSeconds = 1.5f; private const float EffectFadeTimeSeconds = 1.5f; private const float EffectFadeDetachThreshold = 0.001f; private const float CausticsWetWeatherStrengthMultiplier = 0.5f; private const float CausticsPhaseCycleSeconds = 50f; private const float RoofCheckIntervalSeconds = 1f; private const float RoofCheckDistanceMeters = 50f; private const float RoofRayOriginOffsetMeters = 0.2f; private const float FallbackWindDirectionX = 1f; private const float FallbackWindDirectionZ = 0.3f; private const float FallbackWindSpeed = 5f; private const float WindSpeedPerIntensity = 10f; private const float LegacyCausticsWindDriftMinimumUvPerSecond = 0.0125f; private const float FlowingCausticsWindDriftMinimumUvPerSecond = 0.005f; private const float CausticsStrongWindStartIntensity = 0.35f; private const float CausticsStrongWindFullIntensity = 0.65f; private const float CausticsWindDriftMaximumUvPerSecond = 0.18f; private const float CausticsLayerBTransformM00 = -0.819152f; private const float CausticsLayerBTransformM01 = -0.573576f; private const float CausticsLayerBTransformM10 = -0.573576f; private const float CausticsLayerBTransformM11 = 0.819152f; private const float CausticsLayerBScale = 1.17f; private const float CausticsLayerBWindDriftMultiplier = 0.82f; private const float PreRenderFailureRetrySeconds = 5f; private const int InitialRoofHitCapacity = 32; private const int MaximumRoofHitCapacity = 256; private static readonly Vector2 FallbackWindDirection; private readonly ManualLogSource _logger; private readonly CloudShadowsErrorLimiter _errorLimiter; private readonly CloudShadowsConfig _settings; private readonly CloudShadowsRenderer _renderer; private RaycastHit[] _roofHits = (RaycastHit[])(object)new RaycastHit[32]; private bool _worldReady; private bool _preRenderSubscribed; private bool _renderRequested; private bool _cloudRenderRequested; private bool _postEffectRequested; private bool _preRenderFailed; private bool _cameraMissingWasLogged; private bool _windSyncEnabledWasLogged; private bool _windSyncUnavailableWasLogged; private bool _nightAutomationErrorWasLogged; private bool _weatherAutomationErrorWasLogged; private bool _roofAutomationErrorWasLogged; private bool _visibilityStateWasLogged; private bool _lastVisibilityTarget; private bool _lastVisibilityEnabled; private bool _lastVisibilityNight; private bool _lastVisibilityWetWeather; private bool _lastVisibilityUnderRoof; private bool _isNight; private bool _isWetWeather; private bool _isUnderRoof; private bool _visibilityTarget; private bool _causticsVisibilityTarget; private bool _disposed; private float _nextCameraCheckTime; private float _nextWindUpdateTime; private float _nextRoofCheckTime; private float _preRenderRetryTime; private float _effectFade; private float _causticsFade; private float _causticsPhase; private Vector2 _targetWindDirection = FallbackWindDirection; private float _targetWindSpeed = 5f; private float _targetWindIntensity = 0.5f; private float _smoothedWindSpeed = 5f; private Vector2 _smoothedCausticsWindDirection = FallbackWindDirection; private float _smoothedCausticsWindIntensity = 0.5f; private Vector2 _cloudOffset; private Vector2 _legacyCausticsWindOffsetA; private Vector2 _legacyCausticsWindOffsetB; private Vector2 _flowingCausticsWindOffsetA; private Vector2 _flowingCausticsWindOffsetB; internal CloudShadowsPostEffect(ManualLogSource logger, string pluginDirectory, CloudShadowsConfig settings) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //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) _logger = logger; _errorLimiter = new CloudShadowsErrorLimiter(logger); _settings = settings ?? throw new ArgumentNullException("settings"); _renderer = new CloudShadowsRenderer(logger, pluginDirectory, settings); } internal void Tick() { try { if (_disposed) { return; } if (!HasLoadedWorld()) { if (_worldReady) { LeaveWorld(); } else if (_preRenderSubscribed || (Object)(object)_renderer.AttachedCamera != (Object)null) { StopRendering(); } return; } if (!_worldReady) { EnterWorld(); } float unscaledTime = Time.unscaledTime; float deltaTime = Time.deltaTime; UpdateWindIfDue(unscaledTime); SmoothWindAndAdvanceOffset(deltaTime); AdvanceCausticsAnimation(deltaTime); UpdateRoofStateIfDue(unscaledTime); UpdateVisibilityAndFade(deltaTime); bool flag = ShouldRenderClouds(); bool flag2 = ShouldRenderCaustics(); bool flag3 = _settings.DebugMaskView || flag2; bool flag4 = flag || flag2; bool flag5 = flag4 != _renderRequested || flag3 != _postEffectRequested; _cloudRenderRequested = flag; _postEffectRequested = flag3; _renderRequested = flag4; if (_preRenderFailed) { _preRenderFailed = false; StopRendering(); _nextCameraCheckTime = unscaledTime + 5f; } if (!flag4) { if (_preRenderSubscribed || (Object)(object)_renderer.AttachedCamera != (Object)null) { StopRendering(); } } else if (!(unscaledTime < _preRenderRetryTime) && (flag5 || !(unscaledTime < _nextCameraCheckTime))) { _nextCameraCheckTime = unscaledTime + 1f; RefreshCameraAttachment(unscaledTime); } } catch (Exception exception) { LogError("CloudShadows post-effect update failed", exception); } } internal CloudShadowsRuntimeSnapshot CreateDiagnosticsSnapshot() { //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) return new CloudShadowsRuntimeSnapshot { WorldReady = _worldReady, VisibilityTarget = _visibilityTarget, Enabled = _settings.Enabled, DebugMaskView = _settings.DebugMaskView, IsNight = _isNight, IsWetWeather = _isWetWeather, IsUnderRoof = _isUnderRoof, AutoDisableInRain = _settings.AutoDisableInRain, EffectFade = _effectFade, CausticsVisibilityTarget = _causticsVisibilityTarget, CausticsFade = _causticsFade, CausticsPhase = _causticsPhase, CloudRenderRequested = _cloudRenderRequested, PostEffectRequested = _postEffectRequested, RenderRequested = _renderRequested, PreRenderSubscribed = _preRenderSubscribed, TargetWindDirection = _targetWindDirection, TargetWindSpeed = _targetWindSpeed, TargetWindIntensity = _targetWindIntensity, SmoothedWindSpeed = _smoothedWindSpeed, SmoothedCausticsWindDirection = _smoothedCausticsWindDirection, SmoothedCausticsWindIntensity = _smoothedCausticsWindIntensity, CloudOffset = _cloudOffset, CausticsWindOffsets = GetCausticsWindOffsets(), SettingsRevision = _settings.Revision, Renderer = _renderer.CreateSnapshot() }; } public void Dispose() { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: 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_0070: 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_007b: Unknown result type (might be due to invalid IL or missing references) if (!_disposed) { _disposed = true; _worldReady = false; _cloudRenderRequested = false; _postEffectRequested = false; _renderRequested = false; _effectFade = 0f; _causticsVisibilityTarget = false; _causticsFade = 0f; _causticsPhase = 0f; _legacyCausticsWindOffsetA = Vector2.zero; _legacyCausticsWindOffsetB = Vector2.zero; _flowingCausticsWindOffsetA = Vector2.zero; _flowingCausticsWindOffsetB = Vector2.zero; UnsubscribePreRender(); _renderer.Dispose(); } } private static bool HasLoadedWorld() { try { return (Object)(object)EnvMan.instance != (Object)null && (Object)(object)Player.m_localPlayer != (Object)null; } catch { return false; } } private void EnterWorld() { //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_0034: 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_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) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) _worldReady = true; _effectFade = 0f; _causticsFade = 0f; _causticsPhase = 0f; _legacyCausticsWindOffsetA = Vector2.zero; _legacyCausticsWindOffsetB = Vector2.zero; _flowingCausticsWindOffsetA = Vector2.zero; _flowingCausticsWindOffsetB = Vector2.zero; _cloudRenderRequested = false; _postEffectRequested = false; _renderRequested = false; _nextCameraCheckTime = 0f; _nextWindUpdateTime = 0f; _nextRoofCheckTime = 0f; _preRenderRetryTime = 0f; _preRenderFailed = false; _cameraMissingWasLogged = false; _nightAutomationErrorWasLogged = false; _weatherAutomationErrorWasLogged = false; _roofAutomationErrorWasLogged = false; _visibilityStateWasLogged = false; _isNight = false; _isWetWeather = false; _isUnderRoof = false; _visibilityTarget = false; _causticsVisibilityTarget = false; _windSyncEnabledWasLogged = false; _windSyncUnavailableWasLogged = false; UseFallbackWind(null); _smoothedWindSpeed = _targetWindSpeed; _smoothedCausticsWindDirection = _targetWindDirection; _smoothedCausticsWindIntensity = _targetWindIntensity; LogDebug("CloudShadows world became ready"); } private void LeaveWorld() { //IL_0044: 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_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: 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) StopRendering(); _worldReady = false; _cloudRenderRequested = false; _postEffectRequested = false; _renderRequested = false; _effectFade = 0f; _causticsFade = 0f; _causticsPhase = 0f; _legacyCausticsWindOffsetA = Vector2.zero; _legacyCausticsWindOffsetB = Vector2.zero; _flowingCausticsWindOffsetA = Vector2.zero; _flowingCausticsWindOffsetB = Vector2.zero; _smoothedCausticsWindDirection = FallbackWindDirection; _smoothedCausticsWindIntensity = 0.5f; _nextCameraCheckTime = 0f; _nextWindUpdateTime = 0f; _nextRoofCheckTime = 0f; _preRenderRetryTime = 0f; _preRenderFailed = false; _cameraMissingWasLogged = false; _visibilityStateWasLogged = false; _isNight = false; _isWetWeather = false; _isUnderRoof = false; _visibilityTarget = false; _causticsVisibilityTarget = false; LogDebug("CloudShadows world was lost; renderer detached"); } private bool ShouldRenderClouds() { bool flag = _settings.ShadowStrength > 0f && _settings.CloudCoverage > 0f; if (!_settings.DebugMaskView) { if (flag) { if (!_visibilityTarget) { return _effectFade > 0.001f; } return true; } return false; } return true; } private bool ShouldRenderCaustics() { if (!_settings.DebugMaskView && _settings.CausticsIntensity > 0f) { if (!_causticsVisibilityTarget) { return _causticsFade > 0.001f; } return true; } return false; } private void RefreshCameraAttachment(float currentTime) { //IL_00cf: 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) try { Camera main = Camera.main; if ((Object)(object)main == (Object)null) { StopRendering(); if (!_cameraMissingWasLogged) { LogWarning("CloudShadows Camera.main not found; waiting for a camera"); _cameraMissingWasLogged = true; } return; } _cameraMissingWasLogged = false; Camera attachedCamera = _renderer.AttachedCamera; if ((Object)(object)attachedCamera != (Object)null && (Object)(object)attachedCamera != (Object)(object)main) { UnsubscribePreRender(); if (!_renderer.Detach()) { return; } LogDebug("CloudShadows camera changed: " + GetCameraName(attachedCamera) + " -> " + GetCameraName(main)); } if (_renderer.IsAttachedTo(main) && !_renderer.VerifyAttachment(main)) { UnsubscribePreRender(); } if (_renderer.EnsureAttached(main, currentTime, _cloudRenderRequested, _postEffectRequested, _effectFade, _cloudOffset, _causticsFade, _causticsPhase, GetCausticsWindOffsets())) { if (!SubscribePreRender()) { _renderer.Detach(); _preRenderRetryTime = currentTime + 5f; } else { _preRenderRetryTime = 0f; } } } catch (Exception exception) { LogError("CloudShadows camera attachment refresh failed", exception); } } private void StopRendering() { UnsubscribePreRender(); _renderer.Detach(); } private bool SubscribePreRender() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown if (_preRenderSubscribed) { return true; } try { Camera.onPreRender = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPreRender, (Delegate?)new CameraCallback(HandleCameraPreRender)); _preRenderSubscribed = true; return true; } catch (Exception exception) { LogError("CloudShadows Camera.onPreRender subscription failed", exception); return false; } } private void UnsubscribePreRender() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown if (!_preRenderSubscribed) { return; } try { Camera.onPreRender = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPreRender, (Delegate?)new CameraCallback(HandleCameraPreRender)); _preRenderSubscribed = false; } catch (Exception exception) { LogError("CloudShadows Camera.onPreRender unsubscription failed", exception); } } private void HandleCameraPreRender(Camera renderingCamera) { //IL_002d: 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) if (!_disposed && _worldReady && _renderRequested && !_renderer.UpdateForCamera(renderingCamera, _cloudRenderRequested, _effectFade, _cloudOffset, _causticsFade, _causticsPhase, GetCausticsWindOffsets()) && (Object)(object)renderingCamera == (Object)(object)_renderer.AttachedCamera) { _preRenderFailed = true; } } private void UpdateWindIfDue(float currentTime) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: 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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005b: 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) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) try { if (currentTime < _nextWindUpdateTime) { return; } _nextWindUpdateTime = currentTime + 0.1f; EnvMan instance = EnvMan.instance; if ((Object)(object)instance == (Object)null) { UseFallbackWind("EnvMan.instance is null"); return; } Vector3 windDir = instance.GetWindDir(); float windIntensity = instance.GetWindIntensity(); Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(windDir.x, windDir.z); if (!IsFinite(val.x) || !IsFinite(val.y) || ((Vector2)(ref val)).sqrMagnitude <= 1E-06f) { UseFallbackWind("EnvMan.GetWindDir returned an invalid XZ direction"); return; } if (!IsFinite(windIntensity)) { UseFallbackWind("EnvMan.GetWindIntensity returned an invalid value"); return; } _targetWindDirection = ((Vector2)(ref val)).normalized; _targetWindIntensity = Mathf.Clamp01(windIntensity); _targetWindSpeed = _targetWindIntensity * 10f * _settings.WindSpeedMultiplier; _windSyncUnavailableWasLogged = false; if (!_windSyncEnabledWasLogged) { LogDebug("CloudShadows wind sync enabled: EnvMan.GetWindDir/GetWindIntensity"); _windSyncEnabledWasLogged = true; } } catch (Exception ex) { UseFallbackWind(ex.GetType().Name + ": " + ex.Message); } } private void SmoothWindAndAdvanceOffset(float deltaTime) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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) //IL_008c: 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_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //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) try { if (IsFinite(deltaTime) && !(deltaTime <= 0f)) { float num = 1f - Mathf.Exp((0f - deltaTime) / 3f); _smoothedWindSpeed = Mathf.Lerp(_smoothedWindSpeed, _targetWindSpeed, num); float num2 = 1f - Mathf.Exp((0f - deltaTime) / 1.5f); _smoothedCausticsWindDirection = SmoothDirection(_smoothedCausticsWindDirection, _targetWindDirection, num2); _smoothedCausticsWindIntensity = Mathf.Lerp(_smoothedCausticsWindIntensity, Mathf.Clamp01(_targetWindIntensity), num2); _cloudOffset += _targetWindDirection * _smoothedWindSpeed * deltaTime; } } catch (Exception exception) { LogError("CloudShadows wind smoothing update failed", exception); } } private void AdvanceCausticsAnimation(float deltaTime) { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0083: 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_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_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_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_00a6: 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) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0142: 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_0149: 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_0153: Unknown result type (might be due to invalid IL or missing references) try { if (IsFinite(deltaTime) && !(deltaTime <= 0f)) { float num = deltaTime * _settings.CausticsAnimationSpeed; if (IsFinite(num)) { _causticsPhase = Mathf.Repeat(_causticsPhase + num, 50f); float num2 = Mathf.Clamp01(_targetWindIntensity); float num3 = Mathf.SmoothStep(0f, 1f, num2); float num4 = Mathf.Lerp(0.0125f, 0.18f, num3); Vector2 val = _targetWindDirection * num4 * num; Vector2 val2 = TransformWindOffsetForLayerB(val); _legacyCausticsWindOffsetA = RepeatUv(_legacyCausticsWindOffsetA + val); _legacyCausticsWindOffsetB = RepeatUv(_legacyCausticsWindOffsetB + val2); float num5 = Mathf.InverseLerp(0.35f, 0.65f, _smoothedCausticsWindIntensity); float num6 = Mathf.SmoothStep(0f, 1f, num5); float num7 = Mathf.Lerp(0.005f, 0.18f, num6); Vector2 val3 = _smoothedCausticsWindDirection * num7 * num; Vector2 val4 = TransformWindOffsetForLayerB(val3 * 0.82f); _flowingCausticsWindOffsetA = RepeatUv(_flowingCausticsWindOffsetA + val3); _flowingCausticsWindOffsetB = RepeatUv(_flowingCausticsWindOffsetB + val4); } } } catch (Exception exception) { LogError("CloudShadows caustics animation update failed", exception); } } private void UpdateRoofStateIfDue(float currentTime) { //IL_00b5: 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_00c4: 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_00d0: Unknown result type (might be due to invalid IL or missing references) try { bool num = _settings.AutoDisableUnderRoof && (_settings.Enabled || _visibilityTarget || _effectFade > 0.001f); bool flag = _settings.CausticsEnabled || _causticsVisibilityTarget || _causticsFade > 0.001f; if (!num && !flag) { _isUnderRoof = false; _nextRoofCheckTime = 0f; } else { if (currentTime < _nextRoofCheckTime) { return; } _nextRoofCheckTime = currentTime + 1f; Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { _isUnderRoof = false; return; } Transform transform = ((Component)localPlayer).transform; Vector3 origin = transform.position + Vector3.up * 0.2f; int num2 = RaycastRoof(origin); bool isUnderRoof = _isUnderRoof; _isUnderRoof = false; string text = null; for (int i = 0; i < num2; i++) { Collider collider = ((RaycastHit)(ref _roofHits[i])).collider; if (!((Object)(object)collider == (Object)null) && !IsPlayerOrCharacterCollider(collider, transform) && IsRoofCollider(collider)) { _isUnderRoof = true; text = GetObjectName(((Component)collider).gameObject); break; } } if (isUnderRoof != _isUnderRoof) { LogDebug(_isUnderRoof ? ("CloudShadows roof state: UnderRoof=True, hit=" + text) : "CloudShadows roof state: UnderRoof=False"); } _roofAutomationErrorWasLogged = false; } } catch (Exception exception) { _isUnderRoof = false; if (!_roofAutomationErrorWasLogged) { LogError("CloudShadows roof automation update failed", exception); _roofAutomationErrorWasLogged = true; } } } private int RaycastRoof(Vector3 origin) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) int num; while (true) { num = Physics.RaycastNonAlloc(origin, Vector3.up, _roofHits, 50f, -5, (QueryTriggerInteraction)1); if (num < _roofHits.Length || _roofHits.Length >= 256) { break; } int num2 = Mathf.Min(_roofHits.Length * 2, 256); _roofHits = (RaycastHit[])(object)new RaycastHit[num2]; } return Mathf.Min(num, _roofHits.Length); } private void UpdateVisibilityAndFade(float deltaTime) { try { _isNight = GetIsNight(); _isWetWeather = GetIsWetWeather(); bool flag = _settings.AutoDisableAtNight && _isNight; bool flag2 = _settings.AutoDisableInRain && _isWetWeather; bool flag3 = _settings.AutoDisableUnderRoof && _isUnderRoof; _visibilityTarget = _settings.Enabled && !flag && !flag2 && !flag3; _causticsVisibilityTarget = _settings.CausticsEnabled && !_isNight && !_isUnderRoof; LogVisibilityStateIfChanged(_visibilityTarget, flag, flag2, flag3); if (IsFinite(deltaTime) && !(deltaTime <= 0f)) { float num = (_visibilityTarget ? 1f : 0f); float num2 = ((!_causticsVisibilityTarget) ? 0f : (_isWetWeather ? 0.5f : 1f)); float num3 = 1f - Mathf.Exp((0f - deltaTime) / 1.5f); _effectFade = Mathf.Lerp(_effectFade, num, num3); _causticsFade = Mathf.Lerp(_causticsFade, num2, num3); if (!_visibilityTarget && _effectFade <= 0.001f) { _effectFade = 0f; } else if (_visibilityTarget && _effectFade >= 0.999f) { _effectFade = 1f; } if (!_causticsVisibilityTarget && _causticsFade <= 0.001f) { _causticsFade = 0f; } else if (_causticsVisibilityTarget && _causticsFade >= 0.999f) { _causticsFade = 1f; } } } catch (Exception exception) { LogError("CloudShadows effect fade update failed", exception); } } private bool GetIsNight() { try { bool result = (Object)(object)EnvMan.instance != (Object)null && EnvMan.IsNight(); _nightAutomationErrorWasLogged = false; return result; } catch (Exception exception) { if (!_nightAutomationErrorWasLogged) { LogError("CloudShadows night automation update failed", exception); _nightAutomationErrorWasLogged = true; } return false; } } private bool GetIsWetWeather() { try { bool result = (Object)(object)EnvMan.instance != (Object)null && EnvMan.IsWet(); _weatherAutomationErrorWasLogged = false; return result; } catch (Exception exception) { if (!_weatherAutomationErrorWasLogged) { LogError("CloudShadows weather automation update failed", exception); _weatherAutomationErrorWasLogged = true; } return false; } } private bool IsPlayerOrCharacterCollider(Collider collider, Transform playerTransform) { try { Transform transform = ((Component)collider).transform; if ((Object)(object)transform == (Object)null) { return false; } if ((Object)(object)transform == (Object)(object)playerTransform || transform.IsChildOf(playerTransform) || playerTransform.IsChildOf(transform)) { return true; } return (Object)(object)((Component)collider).GetComponentInParent() != (Object)null; } catch (Exception exception) { LogError("CloudShadows roof collider filtering failed", exception); return false; } } private bool IsRoofCollider(Collider collider) { try { return (Object)(object)((Component)collider).GetComponentInParent() != (Object)null || (Object)(object)((Component)collider).GetComponentInParent() != (Object)null; } catch (Exception exception) { LogError("CloudShadows roof component detection failed", exception); return false; } } private void LogVisibilityStateIfChanged(bool shouldBeVisible, bool isNight, bool isWetWeather, bool isUnderRoof) { bool enabled = _settings.Enabled; if (!_visibilityStateWasLogged || _lastVisibilityTarget != shouldBeVisible || _lastVisibilityEnabled != enabled || _lastVisibilityNight != isNight || _lastVisibilityWetWeather != isWetWeather || _lastVisibilityUnderRoof != isUnderRoof) { _visibilityStateWasLogged = true; _lastVisibilityTarget = shouldBeVisible; _lastVisibilityEnabled = enabled; _lastVisibilityNight = isNight; _lastVisibilityWetWeather = isWetWeather; _lastVisibilityUnderRoof = isUnderRoof; LogDebug("CloudShadows visibility target: " + (shouldBeVisible ? "visible" : "hidden") + " " + $"(Enabled={enabled}, Night={isNight}, " + $"WetWeather={isWetWeather}, UnderRoof={isUnderRoof}, " + $"AutoDisableAtNight={_settings.AutoDisableAtNight}, " + $"AutoDisableInRain={_settings.AutoDisableInRain}, " + $"AutoDisableUnderRoof={_settings.AutoDisableUnderRoof}, " + $"ShadowStrength={_settings.ShadowStrength:R})"); } } private void UseFallbackWind(string reason) { //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) _targetWindDirection = FallbackWindDirection; _targetWindIntensity = 0.5f; _targetWindSpeed = 5f * _settings.WindSpeedMultiplier; _windSyncEnabledWasLogged = false; if (!string.IsNullOrEmpty(reason) && !_windSyncUnavailableWasLogged) { _windSyncUnavailableWasLogged = true; LogWarning("CloudShadows wind sync unavailable: " + reason + "; using fallback direction " + $"({FallbackWindDirection.x:R}, {FallbackWindDirection.y:R}) " + $"and speed {_targetWindSpeed:R}"); } } private Vector4 GetCausticsWindOffsets() { //IL_0016: 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_001b: 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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0037: 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_003e: 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) //IL_0050: Unknown result type (might be due to invalid IL or missing references) Vector2 val = (_settings.CausticsFlowingMotion ? _flowingCausticsWindOffsetA : _legacyCausticsWindOffsetA); Vector2 val2 = (_settings.CausticsFlowingMotion ? _flowingCausticsWindOffsetB : _legacyCausticsWindOffsetB); return new Vector4(val.x, val.y, val2.x, val2.y); } private static Vector2 TransformWindOffsetForLayerB(Vector2 worldOffset) { //IL_0005: 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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0032: 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) return new Vector2(-0.819152f * worldOffset.x + -0.573576f * worldOffset.y, -0.573576f * worldOffset.x + 0.819152f * worldOffset.y) * 1.17f; } private static Vector2 RepeatUv(Vector2 value) { //IL_0000: 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_0020: Unknown result type (might be due to invalid IL or missing references) return new Vector2(Mathf.Repeat(value.x, 1f), Mathf.Repeat(value.y, 1f)); } private static Vector2 SmoothDirection(Vector2 current, Vector2 target, float smoothing) { //IL_0035: 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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_005b: 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) //IL_0047: 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_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: 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_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Clamp01(smoothing); if (num <= 0f) { if (!(((Vector2)(ref current)).sqrMagnitude > 1E-06f)) { return target; } return ((Vector2)(ref current)).normalized; } if (((Vector2)(ref current)).sqrMagnitude <= 1E-06f) { return target; } if (((Vector2)(ref target)).sqrMagnitude <= 1E-06f) { return ((Vector2)(ref current)).normalized; } ((Vector2)(ref current)).Normalize(); ((Vector2)(ref target)).Normalize(); float num2 = Mathf.Clamp(Vector2.Dot(current, target), -1f, 1f); if (num2 >= 0.9999f) { return target; } if (num2 <= -0.9999f) { Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(0f - current.y, current.x); float num3 = (float)Math.PI * num; Vector2 val2 = current * Mathf.Cos(num3) + val * Mathf.Sin(num3); return ((Vector2)(ref val2)).normalized; } float num4 = Mathf.Acos(num2); float num5 = 1f / Mathf.Sin(num4); Vector2 val3 = current * Mathf.Sin((1f - num) * num4) * num5 + target * Mathf.Sin(num * num4) * num5; return ((Vector2)(ref val3)).normalized; } private static bool IsFinite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } private static string GetObjectName(GameObject gameObject) { try { return ((Object)(object)gameObject == (Object)null) ? "" : ((Object)gameObject).name; } catch { return ""; } } private static string GetCameraName(Camera camera) { try { return ((Object)(object)camera == (Object)null) ? "" : ((Object)camera).name; } catch { return ""; } } private void LogDebug(string message) { try { ManualLogSource logger = _logger; if (logger != null) { logger.LogDebug((object)message); } } catch { } } private void LogWarning(string message) { try { ManualLogSource logger = _logger; if (logger != null) { logger.LogWarning((object)message); } } catch { } } private void LogError(string context, Exception exception) { _errorLimiter.LogError(context, exception); } static CloudShadowsPostEffect() { //IL_000a: 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) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) Vector2 val = new Vector2(1f, 0.3f); FallbackWindDirection = ((Vector2)(ref val)).normalized; } } internal enum CloudShadowsDepthSource { None, Depth, DepthNormals } internal sealed class CloudShadowsRendererSnapshot { internal bool ResourcesReady { get; set; } internal string BundlePath { get; set; } internal int BundleAssetCount { get; set; } internal string ShaderName { get; set; } internal string MaterialName { get; set; } internal string CausticsTextureName { get; set; } internal string CausticsTextureSize { get; set; } internal Color CausticsLightColor { get; set; } internal float CausticsLightIntensity { get; set; } internal float CausticsSunResponse { get; set; } internal bool CausticsEnabled { get; set; } internal float CausticsIntensity { get; set; } internal float CausticsPatternSizeMeters { get; set; } internal float CausticsAnimationSpeed { get; set; } internal bool CausticsFlowingMotion { get; set; } internal float CausticsMaximumDepthMeters { get; set; } internal float CausticsDrawDistanceMeters { get; set; } internal bool PostEffectRequested { get; set; } internal bool CommandBufferAttached { get; set; } internal string CameraName { get; set; } internal string CameraRenderingPath { get; set; } internal bool CameraAllowHdr { get; set; } internal string DepthSource { get; set; } internal string OriginalDepthMode { get; set; } internal string AppliedDepthMode { get; set; } internal string CurrentDepthMode { get; set; } internal bool DepthModeWasChanged { get; set; } internal int CameraCommandBufferCount { get; set; } internal float LastWaterLevel { get; set; } internal int AppliedSettingsRevision { get; set; } internal CloudShadowsDirectionalCookieSnapshot DirectionalCookie { get; set; } } internal sealed class CloudShadowsRenderer : IDisposable { private const string ShaderName = "Hidden/ValheimVisualEnhanced/Main"; private const string BundleFileName = "valheimvisualenhanced"; private const string MaterialAssetPath = "assets/valheimvisualenhanced/materials/valheimvisualenhancedmat.mat"; private const string ShaderAssetPath = "assets/valheimvisualenhanced/shaders/valheimvisualenhanced.shader"; private const string CausticsTextureAssetPath = "assets/valheimvisualenhanced/textures/causticsripplemask.png"; private const string CausticsTextureName = "CausticsRippleMask"; private const string TemporaryRenderTargetName = "_ValheimVisualEnhancedTemporaryRT"; private const float ResourceRetryIntervalSeconds = 5f; private const float LiquidSurfaceWaveFactor = 1f; private const float NoLiquidLevel = -10000f; private const float CausticsDistanceFadeStartFraction = 0.6f; private const float CausticsFullSunLuminance = 1.7f; private const float CausticsLuminanceRed = 0.2126f; private const float CausticsLuminanceGreen = 0.7152f; private const float CausticsLuminanceBlue = 0.0722f; private const float MaximumDepthNormalsFarClipPlane = 4096f; private const float FogDisabled = 0f; private const float FogEnabled = 1f; private const float DebugMaskDisabled = 0f; private const float DebugMaskEnabled = 1f; private const float DepthNormalsDisabled = 0f; private const float DepthNormalsEnabled = 1f; private const CameraEvent EffectCameraEvent = (CameraEvent)16; private static readonly int TemporaryRenderTargetId = Shader.PropertyToID("_ValheimVisualEnhancedTemporaryRT"); private static readonly int FrustumCornersWsId = Shader.PropertyToID("_FrustumCornersWS"); private static readonly int CameraWsId = Shader.PropertyToID("_CameraWS"); private static readonly int WaterLevelId = Shader.PropertyToID("_WaterLevel"); private static readonly int ShadowStrengthId = Shader.PropertyToID("_ShadowStrength"); private static readonly int CloudEffectFadeId = Shader.PropertyToID("_CloudEffectFade"); private static readonly int CloudCookieTextureId = Shader.PropertyToID("_CloudCookieTex"); private static readonly int CloudCookieAvailableId = Shader.PropertyToID("_CloudCookieAvailable"); private static readonly int CloudCookieWorldToUvId = Shader.PropertyToID("_CloudCookieWorldToUv"); private static readonly int FogEnabledId = Shader.PropertyToID("_FogEnabled"); private static readonly int FogModeId = Shader.PropertyToID("_FogMode"); private static readonly int FogDensityId = Shader.PropertyToID("_FogDensity"); private static readonly int FogStartId = Shader.PropertyToID("_FogStart"); private static readonly int FogEndId = Shader.PropertyToID("_FogEnd"); private static readonly int FogColorId = Shader.PropertyToID("_FogColor"); private static readonly int SunFogColorId = Shader.PropertyToID("_SunFogColor"); private static readonly int SunDirectionId = Shader.PropertyToID("_SunDirection"); private static readonly int DebugMaskId = Shader.PropertyToID("_DebugMask"); private static readonly int UseDepthNormalsId = Shader.PropertyToID("_UseDepthNormals"); private static readonly int CausticsTextureId = Shader.PropertyToID("_CausticsTex"); private static readonly int CausticsScaleId = Shader.PropertyToID("_CausticsScale"); private static readonly int CausticsMaximumDepthId = Shader.PropertyToID("_CausticsMaximumDepth"); private static readonly int CausticsFadeStartId = Shader.PropertyToID("_CausticsFadeStart"); private static readonly int CausticsFadeEndId = Shader.PropertyToID("_CausticsFadeEnd"); private static readonly int CausticsStrengthId = Shader.PropertyToID("_CausticsStrength"); private static readonly int CausticsPhaseId = Shader.PropertyToID("_CausticsPhase"); private static readonly int CausticsFlowingMotionId = Shader.PropertyToID("_CausticsFlowingMotion"); private static readonly int CausticsWindOffsetId = Shader.PropertyToID("_CausticsWindOffset"); private static readonly int CausticsLightColorId = Shader.PropertyToID("_CausticsLightColor"); private static readonly int CausticsSunResponseId = Shader.PropertyToID("_CausticsSunResponse"); private readonly ManualLogSource _logger; private readonly CloudShadowsErrorLimiter _errorLimiter; private readonly string _pluginDirectory; private readonly CloudShadowsConfig _settings; private readonly Vector3[] _farPlaneCorners = (Vector3[])(object)new Vector3[4]; private readonly Vector3[] _cameraSpaceRays = (Vector3[])(object)new Vector3[4]; private AssetBundle _bundle; private Shader _shader; private Material _material; private CloudShadowsDirectionalCookie _directionalCookie; private Texture2D _causticsTexture; private string _loadedBundlePath; private int _bundleAssetCount; private Camera _attachedCamera; private CommandBuffer _commandBuffer; private DepthTextureMode _originalDepthTextureMode; private DepthTextureMode _appliedDepthTextureMode; private CloudShadowsDepthSource _depthSource; private bool _postEffectRequested; private bool _depthTextureModeWasChanged; private bool _attachedCameraAllowHdr; private int _lastAppliedSettingsRevision = -1; private CloudShadowsDepthSource _lastAppliedDepthSource; private Matrix4x4 _cachedProjectionMatrix; private float _cachedFarClipPlane; private bool _hasCachedFrustum; private bool _useLinearColorSpace; private bool _resourceFailureWasLogged; private bool _attachmentFailureWasLogged; private bool _attachmentHealthWarningWasLogged; private bool _preRenderFailureWasLogged; private bool _detachFailureWasLogged; private bool _waterLevelFallbackWarningWasLogged; private bool _causticsLightWarningWasLogged; private bool _depthRestoreWarningWasLogged; private bool _disposed; private float _nextResourceRetryTime; private float _lastWaterLevel; private Color _lastCausticsLightColor = Color.black; private float _lastCausticsLightIntensity; private float _lastCausticsSunResponse; internal Camera AttachedCamera => _attachedCamera; internal CloudShadowsRenderer(ManualLogSource logger, string pluginDirectory, CloudShadowsConfig settings) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) _logger = logger; _errorLimiter = new CloudShadowsErrorLimiter(logger); _pluginDirectory = pluginDirectory; _settings = settings ?? throw new ArgumentNullException("settings"); } internal bool IsAttachedTo(Camera camera) { if ((Object)(object)camera != (Object)null) { return (Object)(object)_attachedCamera == (Object)(object)camera; } return false; } internal bool EnsureAttached(Camera camera, float currentTime, bool cloudRenderRequested, bool postEffectRequested, float effectFade, Vector2 cloudOffset, float causticsFade, float causticsPhase, Vector4 causticsWindOffsets) { //IL_00c3: 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) if (_disposed || (Object)(object)camera == (Object)null) { return false; } if (camera.orthographic || camera.stereoEnabled) { if (IsAttachedTo(camera) && !Detach()) { LogAttachmentFailure("a previous command buffer could not be removed safely"); return false; } LogAttachmentFailure(camera.orthographic ? ("orthographic cameras are not supported: " + GetCameraName(camera)) : ("stereo cameras are not supported: " + GetCameraName(camera))); return false; } if (IsAttachedTo(camera)) { return EnsurePostEffectBuffer(camera, postEffectRequested); } if (((Object)(object)_attachedCamera != (Object)null || _commandBuffer != null) && !Detach()) { LogAttachmentFailure("a previous command buffer could not be removed safely"); return false; } if (!EnsureResources(currentTime)) { return false; } return Attach(camera, cloudRenderRequested, postEffectRequested, effectFade, cloudOffset, causticsFade, causticsPhase, causticsWindOffsets); } internal bool VerifyAttachment(Camera camera) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) try { if (!IsAttachedTo(camera)) { return false; } if (camera.orthographic || camera.stereoEnabled || !HasSelectedDepthSource(camera.depthTextureMode) || (_depthSource == CloudShadowsDepthSource.DepthNormals && camera.farClipPlane > 4096f)) { LogDebug("CloudShadows renderer state changed; rebuilding camera attachment"); Detach(); return false; } if (camera.allowHDR != _attachedCameraAllowHdr) { LogDebug("CloudShadows camera HDR mode changed; rebuilding command buffer"); Detach(); return false; } _attachmentHealthWarningWasLogged = false; return true; } catch (Exception exception) { if (!_attachmentHealthWarningWasLogged) { LogWarning("CloudShadows could not inspect its camera attachment; keeping the current attachment: " + FormatException(exception)); _attachmentHealthWarningWasLogged = true; } return IsAttachedTo(camera); } } internal bool UpdateForCamera(Camera renderingCamera, bool cloudRenderRequested, float effectFade, Vector2 cloudOffset, float causticsFade, float causticsPhase, Vector4 causticsWindOffsets) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) try { if (_disposed || (Object)(object)renderingCamera == (Object)null || (Object)(object)renderingCamera != (Object)(object)_attachedCamera || (Object)(object)_material == (Object)null) { return false; } UpdateMaterialForCamera(renderingCamera, cloudRenderRequested, effectFade, cloudOffset, causticsFade, causticsPhase, causticsWindOffsets); _preRenderFailureWasLogged = false; return true; } catch (Exception exception) { if (!_preRenderFailureWasLogged) { LogError("CloudShadows pre-render update failed", exception); _preRenderFailureWasLogged = true; } return false; } } internal bool Detach() { //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) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) Camera attachedCamera = _attachedCamera; CommandBuffer commandBuffer = _commandBuffer; string cameraName = GetCameraName(attachedCamera); DepthTextureMode originalDepthTextureMode = _originalDepthTextureMode; DepthTextureMode appliedDepthTextureMode = _appliedDepthTextureMode; bool depthTextureModeWasChanged = _depthTextureModeWasChanged; if (_directionalCookie != null && !_directionalCookie.Detach()) { return false; } try { if (commandBuffer != null && (Object)(object)attachedCamera != (Object)null) { attachedCamera.RemoveCommandBuffer((CameraEvent)16, commandBuffer); } } catch (Exception exception) { if (!_detachFailureWasLogged) { LogError("CloudShadows buffer removal from camera failed", exception); _detachFailureWasLogged = true; } return false; } _detachFailureWasLogged = false; ClearAttachmentState(); RestoreDepthTextureMode(attachedCamera, originalDepthTextureMode, appliedDepthTextureMode, depthTextureModeWasChanged); ReleaseCommandBuffer(commandBuffer); if (commandBuffer != null) { LogDebug("CloudShadows buffer removed: " + cameraName); } return true; } internal unsafe CloudShadowsRendererSnapshot CreateSnapshot() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: 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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) Camera attachedCamera = _attachedCamera; DepthTextureMode val = (DepthTextureMode)0; int cameraCommandBufferCount = 0; string cameraRenderingPath = ""; bool cameraAllowHdr = false; try { if ((Object)(object)attachedCamera != (Object)null) { val = attachedCamera.depthTextureMode; cameraCommandBufferCount = attachedCamera.commandBufferCount; cameraRenderingPath = ((object)attachedCamera.actualRenderingPath/*cast due to .constrained prefix*/).ToString(); cameraAllowHdr = attachedCamera.allowHDR; } } catch (Exception exception) { cameraRenderingPath = ""; } return new CloudShadowsRendererSnapshot { ResourcesReady = ((Object)(object)_bundle != (Object)null && (Object)(object)_shader != (Object)null && (Object)(object)_material != (Object)null && _directionalCookie != null && (Object)(object)_causticsTexture != (Object)null), BundlePath = (string.IsNullOrEmpty(_loadedBundlePath) ? "" : _loadedBundlePath), BundleAssetCount = _bundleAssetCount, ShaderName = GetObjectName((Object)(object)_shader), MaterialName = GetObjectName((Object)(object)_material), CausticsTextureName = GetObjectName((Object)(object)_causticsTexture), CausticsTextureSize = GetTextureSize(_causticsTexture), CausticsLightColor = _lastCausticsLightColor, CausticsLightIntensity = _lastCausticsLightIntensity, CausticsSunResponse = _lastCausticsSunResponse, CausticsEnabled = _settings.CausticsEnabled, CausticsIntensity = _settings.CausticsIntensity, CausticsPatternSizeMeters = _settings.CausticsPatternSizeMeters, CausticsAnimationSpeed = _settings.CausticsAnimationSpeed, CausticsFlowingMotion = _settings.CausticsFlowingMotion, CausticsMaximumDepthMeters = _settings.CausticsMaximumDepthMeters, CausticsDrawDistanceMeters = _settings.CausticsDrawDistanceMeters, PostEffectRequested = _postEffectRequested, CommandBufferAttached = ((Object)(object)attachedCamera != (Object)null && _commandBuffer != null), CameraName = GetCameraName(attachedCamera), CameraRenderingPath = cameraRenderingPath, CameraAllowHdr = cameraAllowHdr, DepthSource = _depthSource.ToString(), OriginalDepthMode = ((object)Unsafe.As(ref _originalDepthTextureMode)/*cast due to .constrained prefix*/).ToString(), AppliedDepthMode = ((object)Unsafe.As(ref _appliedDepthTextureMode)/*cast due to .constrained prefix*/).ToString(), CurrentDepthMode = ((object)(*(DepthTextureMode*)(&val))/*cast due to .constrained prefix*/).ToString(), DepthModeWasChanged = _depthTextureModeWasChanged, CameraCommandBufferCount = cameraCommandBufferCount, LastWaterLevel = _lastWaterLevel, AppliedSettingsRevision = _lastAppliedSettingsRevision, DirectionalCookie = _directionalCookie?.CreateSnapshot() }; } public void Dispose() { if (!_disposed) { if (!Detach()) { LogError("CloudShadows renderer disposal incomplete", "command buffer is still attached; resources were kept alive"); return; } _disposed = true; _directionalCookie?.Dispose(); _directionalCookie = null; DestroyMaterial(); UnloadBundle(unloadAllLoadedObjects: true); } } private bool Attach(Camera camera, bool cloudRenderRequested, bool postEffectRequested, float effectFade, Vector2 cloudOffset, float causticsFade, float causticsPhase, Vector4 causticsWindOffsets) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_012e: 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: 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) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006f: 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_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) CommandBuffer val = null; bool flag = false; DepthTextureMode originalDepthTextureMode = (DepthTextureMode)0; DepthTextureMode appliedDepthTextureMode = (DepthTextureMode)0; bool depthTextureModeWasChanged = false; CloudShadowsDepthSource cloudShadowsDepthSource = CloudShadowsDepthSource.None; try { cloudShadowsDepthSource = (_depthSource = SelectDepthSource(camera, out originalDepthTextureMode, out appliedDepthTextureMode, out depthTextureModeWasChanged)); ResetFrustumCache(); UpdateMaterialForCamera(camera, cloudRenderRequested, effectFade, cloudOffset, causticsFade, causticsPhase, causticsWindOffsets); if (postEffectRequested) { val = CreateCommandBuffer(camera); camera.AddCommandBuffer((CameraEvent)16, val); flag = true; } _attachedCamera = camera; _commandBuffer = val; _postEffectRequested = postEffectRequested; _originalDepthTextureMode = originalDepthTextureMode; _appliedDepthTextureMode = appliedDepthTextureMode; _depthTextureModeWasChanged = depthTextureModeWasChanged; _attachedCameraAllowHdr = camera.allowHDR; _attachmentFailureWasLogged = false; _attachmentHealthWarningWasLogged = false; LogDebug(postEffectRequested ? $"CloudShadows post buffer added: {GetCameraName(camera)}; depth={cloudShadowsDepthSource}" : $"CloudShadows cloud-mask attachment added: {GetCameraName(camera)}; depth={cloudShadowsDepthSource}"); return true; } catch (Exception exception) { LogAttachmentFailure(FormatException(exception)); if (flag && (Object)(object)camera != (Object)null && val != null) { try { camera.RemoveCommandBuffer((CameraEvent)16, val); } catch (Exception exception2) { LogError("CloudShadows failed to roll back added buffer", exception2); _attachedCamera = camera; _commandBuffer = val; _postEffectRequested = postEffectRequested; _originalDepthTextureMode = originalDepthTextureMode; _appliedDepthTextureMode = appliedDepthTextureMode; _depthTextureModeWasChanged = depthTextureModeWasChanged; _depthSource = cloudShadowsDepthSource; return false; } } if (_directionalCookie != null && !_directionalCookie.Detach()) { LogAttachmentFailure("cloud shadow mask buffers could not be rolled back safely"); } ReleaseCommandBuffer(val); RestoreDepthTextureMode(camera, originalDepthTextureMode, appliedDepthTextureMode, depthTextureModeWasChanged); ClearAttachmentState(); return false; } } private bool EnsurePostEffectBuffer(Camera camera, bool postEffectRequested) { CommandBuffer val = _commandBuffer; if (!postEffectRequested) { if (val == null) { _postEffectRequested = false; return true; } try { camera.RemoveCommandBuffer((CameraEvent)16, val); } catch (Exception exception) { if (!_detachFailureWasLogged) { LogError("CloudShadows post buffer removal from camera failed", exception); _detachFailureWasLogged = true; } return false; } _detachFailureWasLogged = false; _commandBuffer = null; _postEffectRequested = false; ReleaseCommandBuffer(val); LogDebug("CloudShadows post buffer removed: " + GetCameraName(camera)); return true; } if (val != null) { _postEffectRequested = true; return true; } try { val = CreateCommandBuffer(camera); camera.AddCommandBuffer((CameraEvent)16, val); _commandBuffer = val; _postEffectRequested = true; _detachFailureWasLogged = false; LogDebug("CloudShadows post buffer added: " + GetCameraName(camera)); return true; } catch (Exception exception2) { ReleaseCommandBuffer(val); LogAttachmentFailure(FormatException(exception2)); return false; } } private bool EnsureResources(float currentTime) { if ((Object)(object)_bundle != (Object)null && (Object)(object)_shader != (Object)null && (Object)(object)_material != (Object)null && _directionalCookie != null && (Object)(object)_causticsTexture != (Object)null) { return true; } if (currentTime < _nextResourceRetryTime) { return false; } _nextResourceRetryTime = currentTime + 5f; if ((Object)(object)_bundle != (Object)null || (Object)(object)_shader != (Object)null || (Object)(object)_material != (Object)null || _directionalCookie != null || (Object)(object)_causticsTexture != (Object)null) { if (_directionalCookie != null) { if (!_directionalCookie.Detach()) { LogError("CloudShadows resource reset postponed", "cloud shadow mask resources are still attached"); return false; } _directionalCookie.Dispose(); _directionalCookie = null; } DestroyMaterial(); UnloadBundle(unloadAllLoadedObjects: true); } string text = (string.IsNullOrWhiteSpace(_pluginDirectory) ? null : Path.Combine(_pluginDirectory, "assets", "valheimvisualenhanced")); string detail; if (string.IsNullOrWhiteSpace(text)) { detail = "plugin directory is unavailable"; } else if (!File.Exists(text)) { detail = text + ": file not found"; } else { if (TryLoadCandidate(text, out var failure)) { _nextResourceRetryTime = 0f; _resourceFailureWasLogged = false; LogDebug("CloudShadows bundle loaded: " + text); return true; } detail = text + ": " + failure; } if (!_resourceFailureWasLogged) { LogError("CloudShadows resource initialization failed", detail); _resourceFailureWasLogged = true; } return false; } private bool TryLoadCandidate(string bundlePath, out string failure) { //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Expected O, but got Unknown //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Expected O, but got Unknown //IL_03bc: Unknown result type (might be due to invalid IL or missing references) //IL_03c1: Unknown result type (might be due to invalid IL or missing references) //IL_03cc: Unknown result type (might be due to invalid IL or missing references) //IL_03d5: Expected O, but got Unknown //IL_042e: Unknown result type (might be due to invalid IL or missing references) //IL_0434: Invalid comparison between Unknown and I4 AssetBundle val = null; Material val2 = null; Material val3 = null; CloudShadowsDirectionalCookie cloudShadowsDirectionalCookie = null; try { val = AssetBundle.LoadFromFile(bundlePath); if ((Object)(object)val == (Object)null) { failure = "AssetBundle.LoadFromFile returned null"; return false; } string[] array = val.GetAllAssetNames() ?? Array.Empty(); int num = CountAssetNames(array, ".mat"); int num2 = CountAssetNames(array, ".shader"); int num3 = CountAssetNames(array, ".png"); if (array.Length != 3 || num != 1 || num2 != 1 || num3 != 1 || !ContainsAssetName(array, "assets/valheimvisualenhanced/materials/valheimvisualenhancedmat.mat") || !ContainsAssetName(array, "assets/valheimvisualenhanced/shaders/valheimvisualenhanced.shader") || !ContainsAssetName(array, "assets/valheimvisualenhanced/textures/causticsripplemask.png")) { failure = $"unexpected asset layout: total={array.Length}, " + $"materials={num}, shaders={num2}, " + string.Format("textures={0}; names=[{1}]", num3, string.Join(", ", array)); return false; } Texture[] array2 = val.LoadAllAssets(); if (array2.Length != 1 || !(array2[0] is Texture2D)) { failure = $"bundle must contain exactly one Texture2D; textures={array2.Length}"; return false; } Texture2D val4 = val.LoadAsset("assets/valheimvisualenhanced/textures/causticsripplemask.png"); if ((Object)(object)val4 == (Object)null) { failure = "texture load returned null: assets/valheimvisualenhanced/textures/causticsripplemask.png"; return false; } if ((Object)(object)array2[0] != (Object)(object)val4) { failure = "the texture at the expected path is not the bundle's only texture"; return false; } if (!TryAcceptCausticsTexture(val4, out var failure2)) { failure = "caustics texture rejected: " + failure2; return false; } Shader val5 = null; string failure3 = null; Material val6 = val.LoadAsset("assets/valheimvisualenhanced/materials/valheimvisualenhancedmat.mat"); if ((Object)(object)val6 == (Object)null) { failure3 = "material load returned null: assets/valheimvisualenhanced/materials/valheimvisualenhancedmat.mat"; } else if (!TryAcceptShader(val6.shader, out failure3)) { failure3 = "material shader rejected: " + failure3; } else { val5 = val6.shader; val2 = new Material(val6); } if ((Object)(object)val2 == (Object)null) { Shader val7 = val.LoadAsset("assets/valheimvisualenhanced/shaders/valheimvisualenhanced.shader"); if (!TryAcceptShader(val7, out var failure4)) { failure = failure3 + "; shader rejected: " + failure4; return false; } val5 = val7; val2 = new Material(val5); } ((Object)val2).name = "CloudShadows Post Effect Material"; ((Object)val2).hideFlags = (HideFlags)61; if (val2.passCount != 3 || val2.FindPass("POST_EFFECT") != 0 || val2.FindPass("CLOUD_MASK") != 1 || val2.FindPass("SCREEN_SPACE_SHADOW_MASK") != 2) { failure = "accepted shader has an unexpected pass layout: " + $"count={val2.passCount}"; return false; } if (!val2.HasProperty(CausticsTextureId)) { failure = "accepted shader does not expose _CausticsTex"; return false; } if (!val2.HasProperty(CausticsWindOffsetId)) { failure = "accepted shader does not expose _CausticsWindOffset"; return false; } if (!val2.HasProperty(CausticsFlowingMotionId)) { failure = "accepted shader does not expose _CausticsFlowingMotion"; return false; } if (!val2.HasProperty(CausticsSunResponseId)) { failure = "accepted shader does not expose _CausticsSunResponse"; return false; } if (!val2.HasProperty(CloudCookieTextureId) || !val2.HasProperty(CloudCookieAvailableId) || !val2.HasProperty(CloudEffectFadeId) || !val2.HasProperty(ShadowStrengthId) || !val2.HasProperty("_CloudScale") || !val2.HasProperty("_CloudCoverage") || !val2.HasProperty("_CloudSoftness") || !val2.HasProperty("_CloudOffset") || !val2.HasProperty("_CookieHorizonFade") || !val2.HasProperty("_CookieFadeStart") || !val2.HasProperty("_CookieFadeEnd")) { failure = "accepted shader does not expose the cloud mask properties"; return false; } val2.SetTexture(CausticsTextureId, (Texture)(object)val4); val3 = new Material(val2) { name = "CloudShadows Directional Mask Material", hideFlags = (HideFlags)61 }; cloudShadowsDirectionalCookie = new CloudShadowsDirectionalCookie(_logger, _settings, val3); val3 = null; _bundle = val; val = null; _shader = val5; _material = val2; _directionalCookie = cloudShadowsDirectionalCookie; _causticsTexture = val4; val2 = null; cloudShadowsDirectionalCookie = null; _loadedBundlePath = bundlePath; _bundleAssetCount = array.Length; _lastAppliedSettingsRevision = -1; _useLinearColorSpace = (int)QualitySettings.activeColorSpace == 1; failure = null; return true; } catch (Exception exception) { failure = FormatException(exception); return false; } finally { cloudShadowsDirectionalCookie?.Dispose(); DestroyUnityObject((Object)(object)val3); DestroyUnityObject((Object)(object)val2); if ((Object)(object)val != (Object)null) { try { val.Unload(true); } catch { } } } } private static bool ContainsAssetName(string[] assetNames, string expectedName) { for (int i = 0; i < assetNames.Length; i++) { if (string.Equals(assetNames[i], expectedName, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } private static int CountAssetNames(string[] assetNames, string suffix) { int num = 0; foreach (string text in assetNames) { if (!string.IsNullOrEmpty(text) && text.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) { num++; } } return num; } private static bool TryAcceptShader(Shader shader, out string failure) { if ((Object)(object)shader == (Object)null) { failure = "shader is null"; return false; } if (!string.Equals(((Object)shader).name, "Hidden/ValheimVisualEnhanced/Main", StringComparison.Ordinal)) { failure = "unexpected shader name: " + ((Object)shader).name; return false; } if (!shader.isSupported) { failure = "shader is unsupported: " + ((Object)shader).name; return false; } failure = null; return true; } private static bool TryAcceptCausticsTexture(Texture2D texture, out string failure) { //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Invalid comparison between Unknown and I4 //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Invalid comparison between Unknown and I4 //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Invalid comparison between Unknown and I4 //IL_012a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)texture == (Object)null) { failure = "texture is null"; return false; } if (!string.Equals(((Object)texture).name, "CausticsRippleMask", StringComparison.OrdinalIgnoreCase)) { failure = "unexpected texture name: " + ((Object)texture).name; return false; } if (((Texture)texture).width != 512 || ((Texture)texture).height != 512) { failure = $"unexpected texture size: {((Texture)texture).width}x{((Texture)texture).height}"; return false; } if (((Texture)texture).mipmapCount <= 1) { failure = $"mipmaps are missing: mipmapCount={((Texture)texture).mipmapCount}"; return false; } if ((int)((Texture)texture).filterMode != 2) { failure = $"unexpected filter mode: {((Texture)texture).filterMode}"; return false; } if ((int)((Texture)texture).wrapMode != 0) { failure = $"unexpected wrap mode: {((Texture)texture).wrapMode}"; return false; } if (((Texture)texture).anisoLevel != 2) { failure = $"unexpected anisotropic level: {((Texture)texture).anisoLevel}"; return false; } if (((Texture)texture).isReadable) { failure = "texture must not be CPU-readable"; return false; } if ((int)texture.format != 26 && (int)texture.format != 63) { failure = $"unexpected texture format: {texture.format}"; return false; } failure = null; return true; } private static CloudShadowsDepthSource SelectDepthSource(Camera camera, out DepthTextureMode originalDepthTextureMode, out DepthTextureMode appliedDepthTextureMode, out bool depthTextureModeWasChanged) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected I4, but got Unknown originalDepthTextureMode = (DepthTextureMode)(int)camera.depthTextureMode; appliedDepthTextureMode = originalDepthTextureMode; depthTextureModeWasChanged = false; if (((uint)originalDepthTextureMode & 1u) != 0) { return CloudShadowsDepthSource.Depth; } if (((uint)originalDepthTextureMode & 2u) != 0 && camera.farClipPlane <= 4096f) { return CloudShadowsDepthSource.DepthNormals; } appliedDepthTextureMode = (DepthTextureMode)((uint)originalDepthTextureMode | 1u); camera.depthTextureMode = appliedDepthTextureMode; depthTextureModeWasChanged = true; return CloudShadowsDepthSource.Depth; } private bool HasSelectedDepthSource(DepthTextureMode depthTextureMode) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 //IL_000f: 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_0013: Invalid comparison between Unknown and I4 return _depthSource switch { CloudShadowsDepthSource.DepthNormals => (depthTextureMode & 2) > 0, CloudShadowsDepthSource.Depth => (depthTextureMode & 1) > 0, _ => false, }; } private CommandBuffer CreateCommandBuffer(Camera camera) { //IL_000f: 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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_002b: 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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) CommandBuffer val = null; try { RenderTextureFormat val2 = (RenderTextureFormat)(camera.allowHDR ? 9 : 7); val = new CommandBuffer { name = "CloudShadows Opaque Surface Lighting" }; val.GetTemporaryRT(TemporaryRenderTargetId, -1, -1, 0, (FilterMode)1, val2); val.Blit(RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2), RenderTargetIdentifier.op_Implicit(TemporaryRenderTargetId)); val.Blit(RenderTargetIdentifier.op_Implicit(TemporaryRenderTargetId), RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2), _material, 0); val.ReleaseTemporaryRT(TemporaryRenderTargetId); return val; } catch { ReleaseCommandBuffer(val); throw; } } private void UpdateMaterialForCamera(Camera camera, bool cloudRenderRequested, float effectFade, Vector2 cloudOffset, float causticsFade, float causticsPhase, Vector4 causticsWindOffsets) { //IL_0066: 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_0073: 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_007d: 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_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: 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_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: 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_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_017f: 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_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)camera == (Object)null || (Object)(object)_material == (Object)null || _directionalCookie == null) { throw new InvalidOperationException("camera or material is missing"); } float farClipPlane = camera.farClipPlane; if (!IsFinite(farClipPlane) || farClipPlane <= 0f) { throw new InvalidOperationException($"invalid far clip plane: {farClipPlane}"); } UpdateCameraSpaceFrustum(camera, farClipPlane); Transform transform = ((Component)camera).transform; Quaternion rotation = transform.rotation; Vector3 vector = rotation * _cameraSpaceRays[0]; Vector3 vector2 = rotation * _cameraSpaceRays[1]; Vector3 vector3 = rotation * _cameraSpaceRays[2]; Vector3 vector4 = rotation * _cameraSpaceRays[3]; Matrix4x4 zero = Matrix4x4.zero; ((Matrix4x4)(ref zero)).SetRow(0, ToDirectionVector(vector)); ((Matrix4x4)(ref zero)).SetRow(1, ToDirectionVector(vector4)); ((Matrix4x4)(ref zero)).SetRow(2, ToDirectionVector(vector2)); ((Matrix4x4)(ref zero)).SetRow(3, ToDirectionVector(vector3)); Vector3 position = transform.position; float num = (_lastWaterLevel = GetWaterLevel(position)); _directionalCookie.UpdateForCamera(camera, cloudRenderRequested, effectFade, cloudOffset, position, num, zero, _depthSource == CloudShadowsDepthSource.DepthNormals); if (_postEffectRequested) { ApplyStaticSettingsIfNeeded(); ApplyDepthSourceIfNeeded(); bool flag = _settings.DebugMaskView && _directionalCookie.MaskAvailable; _material.SetMatrix(FrustumCornersWsId, zero); _material.SetVector(CameraWsId, ToPositionVector(position)); _material.SetFloat(WaterLevelId, num); _material.SetFloat(ShadowStrengthId, _settings.ShadowStrength); _material.SetTexture(CloudCookieTextureId, (Texture)(_directionalCookie.MaskAvailable ? ((object)_directionalCookie.Texture) : ((object)Texture2D.blackTexture))); _material.SetMatrix(CloudCookieWorldToUvId, _directionalCookie.WorldToCookieUv); _material.SetFloat(CloudCookieAvailableId, flag ? 1f : 0f); _material.SetFloat(CloudEffectFadeId, _settings.DebugMaskView ? 1f : Mathf.Clamp01(effectFade)); float num2 = _settings.CausticsIntensity * causticsFade; _material.SetFloat(CausticsStrengthId, num2); _material.SetFloat(CausticsPhaseId, causticsPhase); _material.SetVector(CausticsWindOffsetId, causticsWindOffsets); ApplyFogSettingsToMaterial(); ApplyCausticsLightToMaterial(num2 > 0f); } } private void UpdateCameraSpaceFrustum(Camera camera, float farClipPlane) { //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) //IL_0041: 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) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0065: 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_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) Matrix4x4 projectionMatrix = camera.projectionMatrix; if (!_hasCachedFrustum || !(projectionMatrix == _cachedProjectionMatrix) || !Mathf.Approximately(farClipPlane, _cachedFarClipPlane)) { camera.CalculateFrustumCorners(new Rect(0f, 0f, 1f, 1f), farClipPlane, (MonoOrStereoscopicEye)2, _farPlaneCorners); for (int i = 0; i < _farPlaneCorners.Length; i++) { _cameraSpaceRays[i] = _farPlaneCorners[i] / farClipPlane; } _cachedProjectionMatrix = projectionMatrix; _cachedFarClipPlane = farClipPlane; _hasCachedFrustum = true; } } private void ApplyStaticSettingsIfNeeded() { if (_lastAppliedSettingsRevision != _settings.Revision) { float num = Mathf.Max(_settings.CausticsPatternSizeMeters, 0.0001f); float causticsDrawDistanceMeters = _settings.CausticsDrawDistanceMeters; _material.SetFloat(CausticsScaleId, 1f / num); _material.SetFloat(CausticsMaximumDepthId, _settings.CausticsMaximumDepthMeters); _material.SetFloat(CausticsFadeStartId, causticsDrawDistanceMeters * 0.6f); _material.SetFloat(CausticsFadeEndId, causticsDrawDistanceMeters); _material.SetFloat(CausticsFlowingMotionId, _settings.CausticsFlowingMotion ? 1f : 0f); _material.SetFloat(DebugMaskId, _settings.DebugMaskView ? 1f : 0f); _lastAppliedSettingsRevision = _settings.Revision; } } private void ApplyDepthSourceIfNeeded() { if (_lastAppliedDepthSource != _depthSource) { _material.SetFloat(UseDepthNormalsId, (_depthSource == CloudShadowsDepthSource.DepthNormals) ? 1f : 0f); _lastAppliedDepthSource = _depthSource; } } private void ApplyFogSettingsToMaterial() { //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_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: 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_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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) //IL_0050: 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_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_007c: 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_009f: Unknown result type (might be due to invalid IL or missing references) bool fog = RenderSettings.fog; FogMode fogMode = RenderSettings.fogMode; float fogDensity = RenderSettings.fogDensity; float fogStartDistance = RenderSettings.fogStartDistance; float fogEndDistance = RenderSettings.fogEndDistance; Color renderingColor = GetRenderingColor(RenderSettings.fogColor); Color val = renderingColor; Vector3 vector = Vector3.up; EnvMan instance = EnvMan.instance; if ((Object)(object)instance != (Object)null) { val = GetRenderingColor(instance.GetSunFogColor()); Vector3 sunDirection = instance.GetSunDirection(); if (IsFinite(sunDirection.x) && IsFinite(sunDirection.y) && IsFinite(sunDirection.z) && ((Vector3)(ref sunDirection)).sqrMagnitude > 1E-06f) { vector = ((Vector3)(ref sunDirection)).normalized; } } _material.SetFloat(FogEnabledId, fog ? 1f : 0f); _material.SetFloat(FogModeId, (float)fogMode); _material.SetFloat(FogDensityId, fogDensity); _material.SetFloat(FogStartId, fogStartDistance); _material.SetFloat(FogEndId, fogEndDistance); _material.SetColor(FogColorId, renderingColor); _material.SetColor(SunFogColorId, val); _material.SetVector(SunDirectionId, ToDirectionVector(vector)); } private void ApplyCausticsLightToMaterial(bool warnIfUnavailable) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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) //IL_000b: 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) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0169: 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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: 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_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0085: 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_009f: 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) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: 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_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) Color val = Color.black; Color val2 = Color.black; Color val3 = Color.black; float num = 0f; string text = null; try { EnvMan instance = EnvMan.instance; Light val4 = (((Object)(object)instance == (Object)null) ? null : instance.m_dirLight); if ((Object)(object)val4 == (Object)null) { text = "EnvMan.m_dirLight is unavailable"; } else { val = val4.color; num = val4.intensity; if (!IsFinite(val.r) || !IsFinite(val.g) || !IsFinite(val.b) || val.r < 0f || val.g < 0f || val.b < 0f || !IsFinite(num) || num < 0f) { text = "EnvMan.m_dirLight has invalid color or intensity: " + $"color={val}, intensity={num:R}"; } else { val2 = GetRenderingColor(val) * num; val3 = ((Color)(ref val)).linear * num; if (!IsValidLightEnergy(val2) || !IsValidLightEnergy(val3)) { text = "EnvMan.m_dirLight produced invalid rendering energy: " + $"rendering={val2}, linear={val3}"; } } } } catch (Exception exception) { text = FormatException(exception); } if (text != null) { _lastCausticsLightColor = Color.black; _lastCausticsLightIntensity = 0f; _lastCausticsSunResponse = 0f; _material.SetColor(CausticsLightColorId, Color.black); _material.SetFloat(CausticsSunResponseId, 0f); if (warnIfUnavailable && !_causticsLightWarningWasLogged) { LogWarning("CloudShadows directional light unavailable; caustics use black: " + text); _causticsLightWarningWasLogged = true; } } else { _lastCausticsLightColor = val; _lastCausticsLightIntensity = num; _lastCausticsSunResponse = CalculateCausticsSunResponse(val3); _material.SetColor(CausticsLightColorId, val2); _material.SetFloat(CausticsSunResponseId, _lastCausticsSunResponse); } } private static float CalculateCausticsSunResponse(Color linearLightColor) { //IL_0000: 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) //IL_0019: Unknown result type (might be due to invalid IL or missing references) float num = linearLightColor.r * 0.2126f + linearLightColor.g * 0.7152f + linearLightColor.b * 0.0722f; if (!IsFinite(num) || num <= 0f) { return 0f; } return Mathf.Sqrt(Mathf.Clamp01(num / 1.7f)); } private static bool IsValidLightEnergy(Color color) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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) if (IsFinite(color.r) && IsFinite(color.g) && IsFinite(color.b) && color.r >= 0f && color.g >= 0f) { return color.b >= 0f; } return false; } private float GetWaterLevel(Vector3 cameraPosition) { //IL_0002: 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) Exception exception = null; if (TryGetLiquidLevel(cameraPosition, out var waterLevel, out exception)) { _waterLevelFallbackWarningWasLogged = false; return waterLevel; } Player localPlayer = Player.m_localPlayer; Exception exception2 = null; if ((Object)(object)localPlayer != (Object)null && TryGetLiquidLevel(((Component)localPlayer).transform.position, out waterLevel, out exception2)) { _waterLevelFallbackWarningWasLogged = false; return waterLevel; } if (exception2 != null) { exception = exception2; } try { ZoneSystem instance = ZoneSystem.instance; if ((Object)(object)instance != (Object)null && IsFinite(instance.m_waterLevel)) { _waterLevelFallbackWarningWasLogged = false; return instance.m_waterLevel; } } catch (Exception ex) { exception = ex; } if (!_waterLevelFallbackWarningWasLogged) { string text = ((exception == null) ? "no valid camera, player, or ZoneSystem water level was available" : FormatException(exception)); LogWarning("CloudShadows water level unavailable; using 0: " + text); _waterLevelFallbackWarningWasLogged = true; } return 0f; } private static bool TryGetLiquidLevel(Vector3 position, out float waterLevel, out Exception exception) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) try { waterLevel = Floating.GetLiquidLevel(position, 1f, (LiquidType)0); exception = null; return IsFinite(waterLevel) && waterLevel > -10000f; } catch (Exception ex) { waterLevel = -10000f; exception = ex; return false; } } private Color GetRenderingColor(Color color) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (!_useLinearColorSpace) { return color; } return ((Color)(ref color)).linear; } private void ClearAttachmentState() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) _attachedCamera = null; _commandBuffer = null; _postEffectRequested = false; _originalDepthTextureMode = (DepthTextureMode)0; _appliedDepthTextureMode = (DepthTextureMode)0; _depthSource = CloudShadowsDepthSource.None; _depthTextureModeWasChanged = false; _attachedCameraAllowHdr = false; ResetFrustumCache(); } private void ResetFrustumCache() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) _hasCachedFrustum = false; _cachedProjectionMatrix = Matrix4x4.zero; _cachedFarClipPlane = 0f; } private void RestoreDepthTextureMode(Camera camera, DepthTextureMode originalDepthTextureMode, DepthTextureMode appliedDepthTextureMode, bool depthTextureModeWasChanged) { //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_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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) if (!depthTextureModeWasChanged || (Object)(object)camera == (Object)null) { return; } if (_settings.LeaveRequestedDepthModeForCompatibility) { LogDebug("CloudShadows kept its Depth texture request for compatibility with other visual mods"); return; } try { DepthTextureMode depthTextureMode = camera.depthTextureMode; if (depthTextureMode == appliedDepthTextureMode) { camera.depthTextureMode = originalDepthTextureMode; _depthRestoreWarningWasLogged = false; } else if (!_depthRestoreWarningWasLogged) { LogWarning("CloudShadows left camera depthTextureMode unchanged because another " + $"component modified it: {depthTextureMode}"); _depthRestoreWarningWasLogged = true; } } catch (Exception exception) { LogError("CloudShadows depthTextureMode restore failed", exception); } } private void DestroyMaterial() { Material material = _material; _material = null; _lastAppliedSettingsRevision = -1; _lastAppliedDepthSource = CloudShadowsDepthSource.None; DestroyUnityObject((Object)(object)material); } private void UnloadBundle(bool unloadAllLoadedObjects) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) AssetBundle bundle = _bundle; _bundle = null; _shader = null; _causticsTexture = null; _loadedBundlePath = null; _bundleAssetCount = 0; _lastCausticsLightColor = Color.black; _lastCausticsLightIntensity = 0f; _lastCausticsSunResponse = 0f; if ((Object)(object)bundle == (Object)null) { return; } try { bundle.Unload(unloadAllLoadedObjects); } catch (Exception exception) { LogError("CloudShadows bundle unload failed", exception); } } private static void DestroyUnityObject(Object unityObject) { if (!(unityObject == (Object)null)) { if (Application.isPlaying) { Object.Destroy(unityObject); } else { Object.DestroyImmediate(unityObject); } } } private static void ReleaseCommandBuffer(CommandBuffer buffer) { try { if (buffer != null) { buffer.Release(); } } catch { } } private void LogAttachmentFailure(string detail) { if (!_attachmentFailureWasLogged) { LogError("CloudShadows camera attachment failed", detail); _attachmentFailureWasLogged = true; } } private static Vector4 ToDirectionVector(Vector3 vector) { //IL_0000: 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) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) return new Vector4(vector.x, vector.y, vector.z, 0f); } private static Vector4 ToPositionVector(Vector3 vector) { //IL_0000: 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) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) return new Vector4(vector.x, vector.y, vector.z, 1f); } private static bool IsFinite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } private static string GetCameraName(Camera camera) { try { return ((Object)(object)camera == (Object)null) ? "" : ((Object)camera).name; } catch { return ""; } } private static string GetObjectName(Object unityObject) { try { return (unityObject == (Object)null) ? "" : unityObject.name; } catch { return ""; } } private static string GetTextureSize(Texture2D texture) { try { return ((Object)(object)texture == (Object)null) ? "" : $"{((Texture)texture).width}x{((Texture)texture).height}"; } catch { return ""; } } private static string FormatException(Exception exception) { if (exception != null) { return exception.GetType().Name + ": " + exception.Message; } return ""; } private void LogDebug(string message) { try { ManualLogSource logger = _logger; if (logger != null) { logger.LogDebug((object)message); } } catch { } } private void LogWarning(string message) { try { ManualLogSource logger = _logger; if (logger != null) { logger.LogWarning((object)message); } } catch { } } private void LogError(string context, Exception exception) { _errorLimiter.LogError(context, exception); } private void LogError(string context, string detail) { _errorLimiter.LogError(context, detail); } } internal sealed class ConfigurationManagerAttributes { public int? Order; public string Category; public bool? IsAdvanced; } internal sealed class EnvironmentPaletteSnapshot { internal bool PatchInstalled { get; set; } internal bool Enabled { get; set; } internal float Strength { get; set; } internal EnhancedEnvironmentPreset Preset { get; set; } internal bool OverrideSunAngle { get; set; } internal float SunAngle { get; set; } internal string LastEnvironmentName { get; set; } } internal sealed class EnvironmentPaletteController : IDisposable { private readonly struct EnvironmentPaletteColors { internal Color MorningSunColor { get; } internal Color MorningFogColor { get; } internal Color DaySunColor { get; } internal Color DayFogColor { get; } internal Color EveningSunColor { get; } internal Color EveningFogColor { get; } internal Color NightSunColor { get; } internal Color NightFogColor { get; } internal EnvironmentPaletteColors(Color morningSunColor, Color morningFogColor, Color daySunColor, Color dayFogColor, Color eveningSunColor, Color eveningFogColor, Color nightSunColor, Color nightFogColor) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: 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) //IL_0010: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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) //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_0030: 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_0038: Unknown result type (might be due to invalid IL or missing references) MorningSunColor = morningSunColor; MorningFogColor = morningFogColor; DaySunColor = daySunColor; DayFogColor = dayFogColor; EveningSunColor = eveningSunColor; EveningFogColor = eveningFogColor; NightSunColor = nightSunColor; NightFogColor = nightFogColor; } } private readonly struct EnvironmentPaletteSetEnvState { internal EnvSetup Environment { get; } internal float OriginalSunAngle { get; } internal bool ShouldRestoreSunAngle { get; } internal EnvironmentPaletteSetEnvState(EnvSetup environment, float originalSunAngle) { Environment = environment; OriginalSunAngle = originalSunAngle; ShouldRestoreSunAngle = true; } } [HarmonyPatch(typeof(EnvMan), "SetEnv")] private static class EnvironmentPaletteSetEnvPatch { [HarmonyPrefix] private static void Prefix(EnvSetup env, ref EnvironmentPaletteSetEnvState __state) { GetActive()?.TryApplySunAngle(env, out __state); } [HarmonyPostfix] private static void Postfix(EnvMan __instance, EnvSetup env, float dayInt, float nightInt, float morningInt, float eveningInt) { GetActive()?.ApplyColors(__instance, env, dayInt, nightInt, morningInt, eveningInt); } [HarmonyFinalizer] private static Exception Finalizer(EnvironmentPaletteSetEnvState __state, Exception __exception) { try { GetActive()?.RestoreSunAngle(__state); } catch { } return __exception; } } private const string HarmonyId = "dev.local.valheimvisualenhanced.environmentpalette"; private static readonly int SunColorId = Shader.PropertyToID("_SunColor"); private static readonly EnvironmentPaletteColors GoldenSagaPalette = new EnvironmentPaletteColors(Rgb(255, 206, 128), Rgb(229, 154, 104), Rgb(255, 226, 184), Rgb(103, 151, 145), Rgb(255, 108, 100), Rgb(104, 53, 119), Rgb(100, 122, 216), Rgb(32, 46, 88)); private static readonly EnvironmentPaletteColors VerdantWildsPalette = new EnvironmentPaletteColors(Rgb(250, 216, 130), Rgb(177, 193, 117), Rgb(203, 232, 166), Rgb(81, 132, 101), Rgb(255, 132, 101), Rgb(64, 104, 82), Rgb(91, 122, 202), Rgb(22, 52, 62)); private static readonly EnvironmentPaletteColors FrostboundPalette = new EnvironmentPaletteColors(Rgb(255, 190, 164), Rgb(178, 188, 220), Rgb(188, 217, 255), Rgb(100, 137, 174), Rgb(205, 148, 255), Rgb(82, 84, 132), Rgb(96, 133, 225), Rgb(26, 39, 76)); private static readonly EnvironmentPaletteColors EmberfallPalette = new EnvironmentPaletteColors(Rgb(255, 166, 76), Rgb(255, 112, 53), Rgb(255, 219, 133), Rgb(163, 91, 54), Rgb(255, 71, 41), Rgb(116, 35, 59), Rgb(154, 76, 230), Rgb(38, 12, 73)); private static readonly EnvironmentPaletteColors AuroraVeilPalette = new EnvironmentPaletteColors(Rgb(255, 182, 135), Rgb(82, 181, 173), Rgb(155, 245, 224), Rgb(31, 104, 122), Rgb(224, 93, 255), Rgb(71, 29, 113), Rgb(108, 128, 255), Rgb(13, 16, 64)); private static EnvironmentPaletteController _active; private readonly ManualLogSource _logger; private readonly CloudShadowsErrorLimiter _errorLimiter; private readonly CloudShadowsConfig _settings; private Harmony _harmony; private bool _patchInstalled; private bool _disposed; private string _lastEnvironmentName; internal EnvironmentPaletteController(ManualLogSource logger, CloudShadowsConfig settings) { _logger = logger ?? throw new ArgumentNullException("logger"); _settings = settings ?? throw new ArgumentNullException("settings"); _errorLimiter = new CloudShadowsErrorLimiter(logger); InstallPatch(); } internal EnvironmentPaletteSnapshot CreateSnapshot() { return new EnvironmentPaletteSnapshot { PatchInstalled = _patchInstalled, Enabled = _settings.EnvironmentPaletteEnabled, Strength = _settings.EnvironmentPaletteStrength, Preset = _settings.EnvironmentPalettePreset, OverrideSunAngle = _settings.EnvironmentPaletteOverrideSunAngle, SunAngle = _settings.EnvironmentPaletteSunAngle, LastEnvironmentName = _lastEnvironmentName }; } public void Dispose() { if (_disposed) { return; } _disposed = true; try { if (_patchInstalled) { Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } } catch (Exception exception) { LogError("Environment palette Harmony cleanup failed", exception); } finally { _patchInstalled = false; _harmony = null; if (_active == this) { _active = null; } } } private void InstallPatch() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown try { Harmony val = new Harmony("dev.local.valheimvisualenhanced.environmentpalette"); val.CreateClassProcessor(typeof(EnvironmentPaletteSetEnvPatch)).Patch(); _harmony = val; _patchInstalled = true; _active = this; _logger.LogDebug((object)"Valheim Visual Enhanced environment palette patch installed"); } catch (Exception exception) { _harmony = null; _patchInstalled = false; LogError("Enhanced Environment could not patch EnvMan.SetEnv; the palette is disabled", exception); } } private static EnvironmentPaletteController GetActive() { EnvironmentPaletteController active = _active; if (active != null && !active._disposed) { return active; } return null; } private bool TryApplySunAngle(EnvSetup environment, out EnvironmentPaletteSetEnvState state) { state = default(EnvironmentPaletteSetEnvState); if (!IsEffectActive() || !_settings.EnvironmentPaletteOverrideSunAngle || environment == null) { return false; } float sunAngle = environment.m_sunAngle; if (!IsFinite(sunAngle)) { return false; } float environmentPaletteSunAngle = _settings.EnvironmentPaletteSunAngle; environment.m_sunAngle = Mathf.Lerp(sunAngle, environmentPaletteSunAngle, _settings.EnvironmentPaletteStrength); state = new EnvironmentPaletteSetEnvState(environment, sunAngle); return true; } private void RestoreSunAngle(EnvironmentPaletteSetEnvState state) { if (state.ShouldRestoreSunAngle && state.Environment != null) { state.Environment.m_sunAngle = state.OriginalSunAngle; } } private void ApplyColors(EnvMan environmentManager, EnvSetup environment, float dayIntensity, float nightIntensity, float morningIntensity, float eveningIntensity) { //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_004b: 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_0058: 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_0066: 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) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0093: 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_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: 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_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) if (!IsEffectActive() || (Object)(object)environmentManager == (Object)null || environment == null) { return; } try { float environmentPaletteStrength = _settings.EnvironmentPaletteStrength; EnvironmentPaletteColors selectedPalette = GetSelectedPalette(); Light dirLight = environmentManager.m_dirLight; if (!((Object)(object)dirLight == (Object)null)) { Color val = ComposeTimeOfDayColor(environment.m_sunColorDay, environment.m_sunColorNight, environment.m_sunColorMorning, environment.m_sunColorEvening, selectedPalette.DaySunColor, selectedPalette.NightSunColor, selectedPalette.MorningSunColor, selectedPalette.EveningSunColor, dayIntensity, nightIntensity, morningIntensity, eveningIntensity, environmentPaletteStrength); Color fogColor = ComposeTimeOfDayColor(environment.m_fogColorDay, environment.m_fogColorNight, environment.m_fogColorMorning, environment.m_fogColorEvening, selectedPalette.DayFogColor, selectedPalette.NightFogColor, selectedPalette.MorningFogColor, selectedPalette.EveningFogColor, dayIntensity, nightIntensity, morningIntensity, eveningIntensity, environmentPaletteStrength); dirLight.color = val; RenderSettings.fogColor = fogColor; Shader.SetGlobalColor(SunColorId, val * Mathf.Max(0f, dirLight.intensity)); ApplySunShaftColor(val); _lastEnvironmentName = environment.m_name; } } catch (Exception exception) { LogError("Enhanced Environment could not apply a time-of-day palette", exception); } } private bool IsEffectActive() { if (!_disposed && _settings.EnvironmentPaletteEnabled) { return _settings.EnvironmentPaletteStrength > 0f; } return false; } private static Color ComposeTimeOfDayColor(Color dayColor, Color nightColor, Color morningColor, Color eveningColor, Color paletteDayColor, Color paletteNightColor, Color paletteMorningColor, Color paletteEveningColor, float dayIntensity, float nightIntensity, float morningIntensity, float eveningIntensity, float strength) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005b: 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) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: 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_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0037: 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_0041: 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) //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) //IL_0048: 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_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) Color val = nightColor * nightIntensity; if (dayIntensity > 0f) { val += BlendRgb(dayColor, paletteDayColor, strength) * dayIntensity; val += BlendRgb(morningColor, paletteMorningColor, strength) * morningIntensity; val += BlendRgb(eveningColor, paletteEveningColor, strength) * eveningIntensity; } return val + (BlendRgb(nightColor, paletteNightColor, strength) - nightColor) * nightIntensity; } private static Color BlendRgb(Color source, Color target, float strength) { //IL_0000: 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) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0036: 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) return new Color(Mathf.Lerp(source.r, target.r, strength), Mathf.Lerp(source.g, target.g, strength), Mathf.Lerp(source.b, target.b, strength), source.a); } private EnvironmentPaletteColors GetSelectedPalette() { //IL_004a: 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_0060: 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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) return _settings.EnvironmentPalettePreset switch { EnhancedEnvironmentPreset.VerdantWilds => VerdantWildsPalette, EnhancedEnvironmentPreset.Frostbound => FrostboundPalette, EnhancedEnvironmentPreset.Emberfall => EmberfallPalette, EnhancedEnvironmentPreset.AuroraVeil => AuroraVeilPalette, EnhancedEnvironmentPreset.Custom => new EnvironmentPaletteColors(_settings.EnvironmentPaletteMorningSunColor, _settings.EnvironmentPaletteMorningFogColor, _settings.EnvironmentPaletteDaySunColor, _settings.EnvironmentPaletteDayFogColor, _settings.EnvironmentPaletteEveningSunColor, _settings.EnvironmentPaletteEveningFogColor, _settings.EnvironmentPaletteNightSunColor, _settings.EnvironmentPaletteNightFogColor), _ => GoldenSagaPalette, }; } private static Color Rgb(int red, int green, int blue) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) return new Color((float)red / 255f, (float)green / 255f, (float)blue / 255f, 1f); } private static void ApplySunShaftColor(Color sunColor) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) try { Camera main = Camera.main; if ((Object)(object)main == (Object)null) { return; } Component component = ((Component)main).GetComponent("SunShafts"); if (!((Object)(object)component == (Object)null)) { FieldInfo field = ((object)component).GetType().GetField("sunColor", BindingFlags.Instance | BindingFlags.Public); if (field != null && field.FieldType == typeof(Color)) { field.SetValue(component, sunColor); } } } catch { } } private void LogError(string context, Exception exception) { _errorLimiter.LogError(context, exception); } private static bool IsFinite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } } internal sealed class MeadowsFirefliesSnapshot { internal bool ResourcesReady { get; set; } internal bool Active { get; set; } internal bool Enabled { get; set; } internal int ParticleCount { get; set; } internal float RadiusMeters { get; set; } internal float Brightness { get; set; } internal bool AutoDisableUnderRoof { get; set; } internal string StateReason { get; set; } } internal sealed class MeadowsFirefliesEffect : IDisposable { private const float StateCheckIntervalSeconds = 1f; private const float ParticleRefreshIntervalSeconds = 2f; private const float MaximumGroundSearchHeight = 60f; private const float GroundSearchDistance = 120f; private const float MinimumParticleHeightMeters = 0.35f; private const float MaximumParticleHeightMeters = 2.4f; private const float ParticleSizeMinimumMeters = 0.014f; private const float ParticleSizeMaximumMeters = 0.024f; private const float ParticleLifetimeMinimumSeconds = 10f; private const float ParticleLifetimeMaximumSeconds = 18f; private const float ParticleVelocityMaximumMetersPerSecond = 0.08f; private const float ShelterFadeDurationSeconds = 1.5f; private const float VisibilityEpsilon = 0.001f; private const uint InitialRandomState = 2654435769u; private static readonly Color FireflyYellow = new Color(1f, 0.78f, 0.16f, 1f); private readonly ManualLogSource _logger; private readonly CloudShadowsErrorLimiter _errorLimiter; private readonly CloudShadowsConfig _settings; private GameObject _root; private ParticleSystem _particleSystem; private ParticleSystemRenderer _particleRenderer; private Material _material; private Texture2D _pixelTexture; private Particle[] _particles; private int _appliedParticleCount = -1; private int _lastAppliedSettingsRevision = -1; private bool _active; private bool _resourceFailureWasLogged; private bool _disposed; private float _nextStateCheckTime; private float _nextParticleRefreshTime; private float _shelterVisibility = 1f; private float _shelterVisibilityTarget = 1f; private float _lastShelterVisibilityUpdateTime; private bool _deactivateAfterShelterFade; private uint _randomState = 2654435769u; private string _stateReason = "waiting for a world"; internal MeadowsFirefliesEffect(ManualLogSource logger, CloudShadowsConfig settings) { _logger = logger ?? throw new ArgumentNullException("logger"); _settings = settings ?? throw new ArgumentNullException("settings"); _errorLimiter = new CloudShadowsErrorLimiter(logger); } internal MeadowsFirefliesSnapshot CreateSnapshot() { return new MeadowsFirefliesSnapshot { ResourcesReady = ((Object)(object)_particleSystem != (Object)null && (Object)(object)_material != (Object)null && (Object)(object)_pixelTexture != (Object)null), Active = _active, Enabled = _settings.MeadowsFirefliesEnabled, ParticleCount = _settings.MeadowsFirefliesParticleCount, RadiusMeters = _settings.MeadowsFirefliesRadiusMeters, Brightness = _settings.MeadowsFirefliesBrightness, AutoDisableUnderRoof = _settings.AutoDisableMeadowsFirefliesUnderRoof, StateReason = _stateReason }; } internal void Tick() { //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) if (_disposed) { return; } try { float unscaledTime = Time.unscaledTime; UpdateShelterFade(unscaledTime); if (unscaledTime < _nextStateCheckTime) { return; } _nextStateCheckTime = unscaledTime + 1f; if (!ShouldRender(out var anchorPosition, out var stateReason, out var shouldFadeUnderShelter)) { _stateReason = stateReason; if (shouldFadeUnderShelter) { BeginShelterFadeOut(unscaledTime); } else { Deactivate(); } return; } CancelShelterFade(unscaledTime); if (!EnsureResources()) { _stateReason = "particle resources are unavailable"; Deactivate(); return; } _stateReason = "active"; if (!_active) { Activate(anchorPosition, unscaledTime); } else if (_lastAppliedSettingsRevision != _settings.Revision || _appliedParticleCount != _settings.MeadowsFirefliesParticleCount) { SeedParticles(anchorPosition); _lastAppliedSettingsRevision = _settings.Revision; _nextParticleRefreshTime = unscaledTime + 2f; } else if (unscaledTime >= _nextParticleRefreshTime) { RefreshParticles(anchorPosition); _nextParticleRefreshTime = unscaledTime + 2f; } } catch (Exception exception) { _stateReason = "an exception prevented the firefly update"; LogError("Meadows fireflies update failed", exception); Deactivate(); } } public void Dispose() { if (_disposed) { return; } _disposed = true; _active = false; _particles = null; try { if ((Object)(object)_root != (Object)null) { _root.SetActive(false); } DestroyUnityObject((Object)(object)_root); DestroyUnityObject((Object)(object)_material); DestroyUnityObject((Object)(object)_pixelTexture); } catch (Exception exception) { LogError("Meadows fireflies cleanup failed", exception); } finally { _root = null; _particleSystem = null; _particleRenderer = null; _material = null; _pixelTexture = null; } } private bool ShouldRender(out Vector3 anchorPosition, out string stateReason, out bool shouldFadeUnderShelter) { //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) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Invalid comparison between Unknown and I4 //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) anchorPosition = Vector3.zero; stateReason = null; shouldFadeUnderShelter = false; if (!_settings.MeadowsFirefliesEnabled) { stateReason = "disabled by Meadows Fireflies.Enabled"; return false; } Player localPlayer = Player.m_localPlayer; EnvMan instance = EnvMan.instance; Camera main = Camera.main; if ((Object)(object)localPlayer == (Object)null || (Object)(object)instance == (Object)null || (Object)(object)main == (Object)null) { stateReason = "waiting for the local player, environment, or main camera"; return false; } if (!EnvMan.IsNight()) { stateReason = "inactive outside nighttime"; return false; } if ((int)localPlayer.GetCurrentBiome() != 1) { stateReason = "inactive outside the Meadows"; return false; } if ((localPlayer.InShelter() || ((Character)localPlayer).InInterior()) && _settings.AutoDisableMeadowsFirefliesUnderRoof) { stateReason = "fading out under shelter or indoors"; shouldFadeUnderShelter = true; return false; } anchorPosition = ((Component)localPlayer).transform.position; return true; } private bool EnsureResources() { //IL_005e: 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_006e: 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_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown //IL_0088: 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_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown //IL_00dc: 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) //IL_00ea: Expected O, but got Unknown //IL_00cd: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_particleSystem != (Object)null && (Object)(object)_particleRenderer != (Object)null && (Object)(object)_material != (Object)null && (Object)(object)_pixelTexture != (Object)null) { return true; } GameObject val = null; Material val2 = null; Texture2D val3 = null; try { Material obj = FindNativeFireflyMaterial(); if ((Object)(object)obj == (Object)null) { throw new InvalidOperationException("could not find an existing Thistle particle material in ZNetScene"); } val3 = new Texture2D(1, 1, (TextureFormat)4, false, true) { name = "Valheim Visual Enhanced Firefly Pixel", filterMode = (FilterMode)0, wrapMode = (TextureWrapMode)1, hideFlags = (HideFlags)61 }; val3.SetPixel(0, 0, Color.white); val3.Apply(false, true); val2 = new Material(obj) { name = "Valheim Visual Enhanced Firefly Material", hideFlags = (HideFlags)61 }; ApplyPixelTexture(val2, val3); if (val2.HasProperty("_Color")) { val2.SetColor("_Color", Color.white); } val = new GameObject("Valheim Visual Enhanced Meadows Fireflies") { hideFlags = (HideFlags)61 }; val.SetActive(false); ParticleSystem particleSystem = val.AddComponent(); ParticleSystemRenderer component = val.GetComponent(); ConfigureParticleSystem(particleSystem, component, val2); _root = val; _particleSystem = particleSystem; _particleRenderer = component; _material = val2; _pixelTexture = val3; ApplyParticleMaterialVisibility(1f); _resourceFailureWasLogged = false; val = null; val2 = null; val3 = null; return true; } catch (Exception exception) { DestroyUnityObject((Object)(object)val); DestroyUnityObject((Object)(object)val2); DestroyUnityObject((Object)(object)val3); if (!_resourceFailureWasLogged) { LogError("Meadows fireflies resources could not be created", exception); _resourceFailureWasLogged = true; } return false; } } private static Material FindNativeFireflyMaterial() { ZNetScene instance = ZNetScene.instance; if ((Object)(object)instance == (Object)null) { return null; } Material val = FindParticleMaterial(instance.GetPrefab("Thistle")); if ((Object)(object)val != (Object)null) { return val; } foreach (string prefabName in instance.GetPrefabNames()) { if (prefabName.IndexOf("thistle", StringComparison.OrdinalIgnoreCase) >= 0) { val = FindParticleMaterial(instance.GetPrefab(prefabName)); if ((Object)(object)val != (Object)null) { return val; } } } return null; } private static Material FindParticleMaterial(GameObject prefab) { if ((Object)(object)prefab == (Object)null) { return null; } ParticleSystemRenderer[] componentsInChildren = prefab.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { Material sharedMaterial = ((Renderer)componentsInChildren[i]).sharedMaterial; if ((Object)(object)sharedMaterial != (Object)null && (Object)(object)sharedMaterial.shader != (Object)null) { return sharedMaterial; } } return null; } private static void ApplyPixelTexture(Material material, Texture2D pixelTexture) { if (material.HasProperty("_MainTex")) { material.SetTexture("_MainTex", (Texture)(object)pixelTexture); } if (material.HasProperty("_BaseMap")) { material.SetTexture("_BaseMap", (Texture)(object)pixelTexture); } } private static void ConfigureParticleSystem(ParticleSystem particleSystem, ParticleSystemRenderer particleRenderer, Material material) { //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) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: 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_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: 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) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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_00a0: Unknown result type (might be due to invalid IL or missing references) MainModule main = particleSystem.main; ((MainModule)(ref main)).loop = false; ((MainModule)(ref main)).playOnAwake = false; ((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1; ((MainModule)(ref main)).maxParticles = 64; ((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(18f); ((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0f); ((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(0.024f); ((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(Color.white); EmissionModule emission = particleSystem.emission; ((EmissionModule)(ref emission)).enabled = false; ShapeModule shape = particleSystem.shape; ((ShapeModule)(ref shape)).enabled = false; ColorOverLifetimeModule colorOverLifetime = particleSystem.colorOverLifetime; ((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled = true; ((ColorOverLifetimeModule)(ref colorOverLifetime)).color = new MinMaxGradient(CreateFireflyBrightnessGradient()); particleRenderer.renderMode = (ParticleSystemRenderMode)0; ((Renderer)particleRenderer).sharedMaterial = material; ((Renderer)particleRenderer).shadowCastingMode = (ShadowCastingMode)0; ((Renderer)particleRenderer).receiveShadows = false; particleRenderer.allowRoll = false; } private static Gradient CreateFireflyBrightnessGradient() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: 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_0034: 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) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0061: 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_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) Gradient val = new Gradient(); val.SetKeys((GradientColorKey[])(object)new GradientColorKey[2] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) }, (GradientAlphaKey[])(object)new GradientAlphaKey[6] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(0.86f, 0.16f), new GradientAlphaKey(0.96f, 0.42f), new GradientAlphaKey(0.9f, 0.7f), new GradientAlphaKey(0.72f, 0.82f), new GradientAlphaKey(0f, 1f) }); return val; } private void Activate(Vector3 anchorPosition, float currentTime) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) CancelShelterFade(currentTime); _root.SetActive(true); _particleSystem.Clear(true); SeedParticles(anchorPosition); _particleSystem.Play(true); _active = true; _lastAppliedSettingsRevision = _settings.Revision; _nextParticleRefreshTime = currentTime + 2f; } private void Deactivate() { if (_active) { _deactivateAfterShelterFade = false; _shelterVisibility = 1f; _shelterVisibilityTarget = 1f; ApplyParticleMaterialVisibility(1f); _active = false; ParticleSystem particleSystem = _particleSystem; if (particleSystem != null) { particleSystem.Clear(true); } if ((Object)(object)_root != (Object)null) { _root.SetActive(false); } } } private void BeginShelterFadeOut(float currentTime) { if (_active) { _shelterVisibilityTarget = 0f; _deactivateAfterShelterFade = true; _lastShelterVisibilityUpdateTime = currentTime; } } private void CancelShelterFade(float currentTime) { if (_deactivateAfterShelterFade || !(_shelterVisibilityTarget >= 0.999f)) { _deactivateAfterShelterFade = false; _shelterVisibilityTarget = 1f; _lastShelterVisibilityUpdateTime = currentTime; } } private void UpdateShelterFade(float currentTime) { if (_active && !(Mathf.Abs(_shelterVisibility - _shelterVisibilityTarget) <= 0.001f)) { float num = Mathf.Max(0f, currentTime - _lastShelterVisibilityUpdateTime); _lastShelterVisibilityUpdateTime = currentTime; float num2 = Mathf.MoveTowards(_shelterVisibility, _shelterVisibilityTarget, num / 1.5f); ApplyShelterVisibility(num2); if (_deactivateAfterShelterFade && num2 <= 0.001f) { Deactivate(); } } } private void ApplyShelterVisibility(float visibility) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) float shelterVisibility = _shelterVisibility; _shelterVisibility = visibility; if (!ApplyParticleMaterialVisibility(visibility) && _particles != null && !((Object)(object)_particleSystem == (Object)null) && !(shelterVisibility <= 0.001f)) { float num = visibility / shelterVisibility; int particles = _particleSystem.GetParticles(_particles); for (int i = 0; i < particles; i++) { Color val = Color32.op_Implicit(((Particle)(ref _particles[i])).startColor); val.a *= num; ((Particle)(ref _particles[i])).startColor = Color32.op_Implicit(val); } _particleSystem.SetParticles(_particles, particles); } } private bool ApplyParticleMaterialVisibility(float visibility) { //IL_0046: 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_0090: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_material == (Object)null) { return false; } Color val = default(Color); ((Color)(ref val))..ctor(1f, 1f, 1f, visibility); bool result = false; if (_material.HasProperty("_Color")) { _material.SetColor("_Color", val); result = true; } if (_material.HasProperty("_TintColor")) { _material.SetColor("_TintColor", val); result = true; } if (_material.HasProperty("_BaseColor")) { _material.SetColor("_BaseColor", val); result = true; } return result; } private void SeedParticles(Vector3 anchorPosition) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) int meadowsFirefliesParticleCount = _settings.MeadowsFirefliesParticleCount; EnsureParticleArray(meadowsFirefliesParticleCount); for (int i = 0; i < meadowsFirefliesParticleCount; i++) { _particles[i] = CreateParticle(anchorPosition); } _particleSystem.SetParticles(_particles, meadowsFirefliesParticleCount); _appliedParticleCount = meadowsFirefliesParticleCount; } private void RefreshParticles(Vector3 anchorPosition) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: 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) //IL_005c: Unknown result type (might be due to invalid IL or missing references) int meadowsFirefliesParticleCount = _settings.MeadowsFirefliesParticleCount; EnsureParticleArray(meadowsFirefliesParticleCount); int particles = _particleSystem.GetParticles(_particles); float num = _settings.MeadowsFirefliesRadiusMeters * _settings.MeadowsFirefliesRadiusMeters * 1.44f; for (int i = 0; i < meadowsFirefliesParticleCount; i++) { if (i >= particles || HorizontalDistanceSquared(((Particle)(ref _particles[i])).position, anchorPosition) > num) { _particles[i] = CreateParticle(anchorPosition); } } _particleSystem.SetParticles(_particles, meadowsFirefliesParticleCount); } private Particle CreateParticle(Vector3 anchorPosition) { //IL_002d: 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_0042: 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_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016a: 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) float num = NextRandom01() * (float)Math.PI * 2f; float num2 = Mathf.Sqrt(NextRandom01()) * _settings.MeadowsFirefliesRadiusMeters; Vector3 position = default(Vector3); ((Vector3)(ref position))..ctor(anchorPosition.x + Mathf.Cos(num) * num2, anchorPosition.y, anchorPosition.z + Mathf.Sin(num) * num2); position.y = GetGroundHeight(position, anchorPosition.y) + Mathf.Lerp(0.35f, 2.4f, NextRandom01()); float num3 = Mathf.Lerp(10f, 18f, NextRandom01()); float num4 = _settings.MeadowsFirefliesBrightness * Mathf.Lerp(0.55f, 1f, NextRandom01()); Vector3 velocity = default(Vector3); ((Vector3)(ref velocity))..ctor(Mathf.Lerp(-0.08f, 0.08f, NextRandom01()), Mathf.Lerp(-0.025f, 0.035f, NextRandom01()), Mathf.Lerp(-0.08f, 0.08f, NextRandom01())); Particle result = default(Particle); ((Particle)(ref result)).position = position; ((Particle)(ref result)).velocity = velocity; ((Particle)(ref result)).startLifetime = num3; ((Particle)(ref result)).remainingLifetime = num3; ((Particle)(ref result)).startSize = Mathf.Lerp(0.014f, 0.024f, NextRandom01()); ((Particle)(ref result)).startColor = Color32.op_Implicit(new Color(FireflyYellow.r, FireflyYellow.g, FireflyYellow.b, num4)); ((Particle)(ref result)).randomSeed = NextRandomUInt(); return result; } private static float GetGroundHeight(Vector3 position, float fallbackHeight) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) RaycastHit val = default(RaycastHit); if (Physics.Raycast(new Vector3(position.x, fallbackHeight + 60f, position.z), Vector3.down, ref val, 120f, -5, (QueryTriggerInteraction)1)) { return ((RaycastHit)(ref val)).point.y; } return fallbackHeight; } private void EnsureParticleArray(int particleCount) { if (_particles == null || _particles.Length != particleCount) { _particles = (Particle[])(object)new Particle[particleCount]; } } private float NextRandom01() { return (float)(NextRandomUInt() & 0xFFFFFF) / 16777215f; } private uint NextRandomUInt() { uint randomState = _randomState; randomState ^= randomState << 13; randomState ^= randomState >> 17; return _randomState = randomState ^ (randomState << 5); } private static float HorizontalDistanceSquared(Vector3 a, Vector3 b) { //IL_0000: 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) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) float num = a.x - b.x; float num2 = a.z - b.z; return num * num + num2 * num2; } private void LogError(string context, Exception exception) { _errorLimiter.LogError(context, exception); } private static void DestroyUnityObject(Object unityObject) { if (unityObject != (Object)null) { Object.Destroy(unityObject); } } } }