Decompiled source of REPOOptimizer v1.1.0

REPOOptimizer.dll

Decompiled 24 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("REPOOptimizer")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("REPOOptimizer")]
[assembly: AssemblyTitle("REPOOptimizer")]
[assembly: AssemblyVersion("1.1.0.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 REPOOptimizer
{
	internal sealed class GraphicsOptimizer
	{
		private readonly struct EffectState
		{
			public readonly Object Component;

			public readonly bool OriginalActive;

			public EffectState(Object component, bool originalActive)
			{
				Component = component;
				OriginalActive = originalActive;
			}
		}

		private struct ActiveMember
		{
			public PropertyInfo Property;

			public FieldInfo Field;

			public bool IsValid
			{
				get
				{
					if (!(Property != null))
					{
						return Field != null;
					}
					return true;
				}
			}
		}

		private const BindingFlags InstanceFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly PropertyInfo GlobalTextureMipmapLimitProperty = typeof(QualitySettings).GetProperty("globalTextureMipmapLimit", BindingFlags.Static | BindingFlags.Public);

		private static readonly PropertyInfo MasterTextureLimitProperty = typeof(QualitySettings).GetProperty("masterTextureLimit", BindingFlags.Static | BindingFlags.Public);

		private static GraphicsOptimizer _instance;

		private readonly ManualLogSource _log;

		private readonly OptimizerConfig _config;

		private readonly Harmony _harmony;

		private bool _qualitySnapshotValid;

		private int _originalTextureMipLimit;

		private int _originalAntiAliasing;

		private AnisotropicFiltering _originalAnisotropicFiltering;

		private bool _originalSoftParticles;

		private float _originalLodBias;

		private int _originalMaximumLodLevel;

		private ShadowQuality _originalShadows;

		private float _originalShadowDistance;

		private int _originalShadowCascades;

		private bool _originalLodCrossFade;

		private RenderPipelineAsset _urpAsset;

		private bool _urpSettingsCaptured;

		private bool _hasRenderScale;

		private float _originalRenderScale;

		private bool _hasMsaa;

		private int _originalMsaa;

		private Type _volumeType;

		private Type _ppVolumeType;

		private MemberInfo _volumeProfileMember;

		private MemberInfo _volumeComponentsMember;

		private MemberInfo _ppVolumeProfileMember;

		private MemberInfo _ppSettingsMember;

		private MethodInfo _findObjectsByTypeMethod;

		private MethodInfo _findObjectsOfTypeMethod;

		private bool _volumePatchApplied;

		private bool _ppVolumePatchApplied;

		private bool _volumePatchFailureLogged;

		private bool _ppVolumePatchFailureLogged;

		private bool _urpMissingLogged;

		private bool _textureMipWarningLogged;

		private string _lastDisabledEffectsRaw;

		private readonly Dictionary<Type, ActiveMember> _activeMemberCache = new Dictionary<Type, ActiveMember>();

		private readonly Dictionary<int, EffectState> _urpEffectStates = new Dictionary<int, EffectState>();

		private readonly Dictionary<int, EffectState> _ppEffectStates = new Dictionary<int, EffectState>();

		private HashSet<string> _disabledEffectNames;

		private readonly HashSet<string> _protectedEffectNames;

		public bool LastUrpFound { get; private set; }

		public bool LastRenderScaleApplied { get; private set; }

		public bool LastMsaaApplied { get; private set; }

		public int LastVolumesScanned { get; private set; }

		public int LastEffectsDisabled { get; private set; }

		public bool IsEnabled { get; set; } = true;

		public GraphicsOptimizer(ManualLogSource log, OptimizerConfig config, Harmony harmony)
		{
			_log = log ?? throw new ArgumentNullException("log");
			_config = config ?? throw new ArgumentNullException("config");
			_harmony = harmony ?? throw new ArgumentNullException("harmony");
			_instance = this;
			_lastDisabledEffectsRaw = config.DisabledPostEffects.Value;
			_disabledEffectNames = ParseNameSet(_lastDisabledEffectsRaw);
			_protectedEffectNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "ColorAdjustments", "Tonemapping", "LiftGammaGain", "WhiteBalance", "ColorGrading", "AutoExposure" };
			EnsureReflectionInitialized();
		}

		public void Apply()
		{
			ApplySettings();
			ScanVolumes();
		}

		public void ApplySettings()
		{
			try
			{
				EnsureReflectionInitialized();
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("[Rendering] Reflection initialization failed: " + ex.Message));
			}
			if (!_qualitySnapshotValid)
			{
				try
				{
					CaptureQualitySettings();
				}
				catch (Exception ex2)
				{
					_log.LogWarning((object)("[Rendering] Failed to capture QualitySettings: " + ex2.Message));
				}
			}
			try
			{
				ApplyQualitySettings();
			}
			catch (Exception ex3)
			{
				_log.LogWarning((object)("[Rendering] Failed to apply QualitySettings: " + ex3.Message));
			}
			try
			{
				ApplyUrpSettings();
			}
			catch (Exception ex4)
			{
				_log.LogWarning((object)("[Rendering] Failed to apply URP settings: " + ex4.Message));
			}
		}

		public void Restore()
		{
			try
			{
				RestoreQualitySettings();
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("[Rendering] Failed to restore QualitySettings: " + ex.Message));
			}
			try
			{
				RestoreUrpSettings();
			}
			catch (Exception ex2)
			{
				_log.LogWarning((object)("[Rendering] Failed to restore URP settings: " + ex2.Message));
			}
			try
			{
				RestoreVolumes();
			}
			catch (Exception ex3)
			{
				_log.LogWarning((object)("[PostFX] Failed to restore post-processing: " + ex3.Message));
			}
			LastVolumesScanned = 0;
			LastEffectsDisabled = 0;
			LastRenderScaleApplied = false;
			LastMsaaApplied = false;
		}

		public void ScanVolumes()
		{
			LastVolumesScanned = 0;
			LastEffectsDisabled = 0;
			if (!IsEnabled || !_config.EnablePostProcessingCleanup.Value)
			{
				return;
			}
			try
			{
				RefreshDisabledEffectNames();
				EnsureReflectionInitialized();
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("[PostFX] Reflection initialization failed: " + ex.Message));
				return;
			}
			try
			{
				if (_volumeType != null)
				{
					ScanUrpVolumes();
				}
				if (_ppVolumeType != null)
				{
					ScanPpVolumes();
				}
			}
			catch (Exception ex2)
			{
				_log.LogWarning((object)("[PostFX] Volume scan failed: " + ex2.Message));
			}
		}

		private void ScanUrpVolumes()
		{
			Object[] array = FindObjects(_volumeType);
			if (array == null)
			{
				return;
			}
			foreach (Object val in array)
			{
				if (!(val == (Object)null))
				{
					LastVolumesScanned++;
					TryOptimizeVolume(val);
				}
			}
		}

		public void TryOptimizeVolume(object volume)
		{
			if (!IsEnabled || !_config.EnablePostProcessingCleanup.Value || volume == null || _volumeType == null || !_volumeType.IsInstanceOfType(volume))
			{
				return;
			}
			RefreshDisabledEffectNames();
			try
			{
				if (TryGetMemberValue(volume, _volumeProfileMember, out var value) && value != null && TryGetMemberValue(value, _volumeComponentsMember, out var value2) && value2 is IEnumerable components)
				{
					OptimizeEffects(components, _urpEffectStates, "URP");
				}
			}
			catch (Exception ex)
			{
				if (_config.VerboseLogging.Value)
				{
					_log.LogWarning((object)("[PostFX/URP] Failed to process volume: " + ex.Message));
				}
			}
		}

		private void ScanPpVolumes()
		{
			Object[] array = FindObjects(_ppVolumeType);
			if (array == null)
			{
				return;
			}
			foreach (Object val in array)
			{
				if (!(val == (Object)null))
				{
					LastVolumesScanned++;
					TryOptimizePpVolume(val);
				}
			}
		}

		public void TryOptimizePpVolume(object volume)
		{
			if (!IsEnabled || !_config.EnablePostProcessingCleanup.Value || volume == null || _ppVolumeType == null || !_ppVolumeType.IsInstanceOfType(volume))
			{
				return;
			}
			RefreshDisabledEffectNames();
			try
			{
				if (TryGetMemberValue(volume, _ppVolumeProfileMember, out var value) && value != null && TryGetMemberValue(value, _ppSettingsMember, out var value2) && value2 is IEnumerable components)
				{
					OptimizeEffects(components, _ppEffectStates, "PPv2");
				}
			}
			catch (Exception ex)
			{
				if (_config.VerboseLogging.Value)
				{
					_log.LogWarning((object)("[PostFX/PPv2] Failed to process volume: " + ex.Message));
				}
			}
		}

		private void OptimizeEffects(IEnumerable components, Dictionary<int, EffectState> states, string tag)
		{
			foreach (object component in components)
			{
				if (component == null)
				{
					continue;
				}
				Object val = (Object)((component is Object) ? component : null);
				if (val == null)
				{
					continue;
				}
				string name = component.GetType().Name;
				if (_protectedEffectNames.Contains(name) || !_disabledEffectNames.Contains(name))
				{
					continue;
				}
				ActiveMember activeMember = GetActiveMember(component.GetType());
				if (!activeMember.IsValid || !GetActive(component, activeMember))
				{
					continue;
				}
				int instanceID = val.GetInstanceID();
				if (!states.ContainsKey(instanceID))
				{
					states.Add(instanceID, new EffectState(val, originalActive: true));
				}
				if (SetActive(component, activeMember, value: false))
				{
					LastEffectsDisabled++;
					if (_config.VerboseLogging.Value)
					{
						_log.LogInfo((object)("[PostFX/" + tag + "] Disabled " + name + " on " + val.name));
					}
				}
			}
		}

		private void RestoreVolumes()
		{
			RestoreEffectStates(_urpEffectStates);
			RestoreEffectStates(_ppEffectStates);
		}

		private void RestoreEffectStates(Dictionary<int, EffectState> states)
		{
			foreach (KeyValuePair<int, EffectState> state in states)
			{
				EffectState value = state.Value;
				Object component = value.Component;
				if (!(component == (Object)null))
				{
					ActiveMember activeMember = GetActiveMember(((object)component).GetType());
					if (activeMember.IsValid)
					{
						SetActive(component, activeMember, value.OriginalActive);
					}
				}
			}
			states.Clear();
		}

		private void EnsureReflectionInitialized()
		{
			if (_volumeType == null)
			{
				_volumeType = FindType("UnityEngine.Rendering.Volume", "Unity.RenderPipelines.Core.Runtime");
				if (_volumeType != null)
				{
					_volumeProfileMember = FindMember(_volumeType, "profileRef") ?? FindMember(_volumeType, "profile");
					Type memberType = GetMemberType(_volumeProfileMember);
					_volumeComponentsMember = ((memberType != null) ? FindMember(memberType, "components") : null);
				}
			}
			if (_ppVolumeType == null)
			{
				_ppVolumeType = FindType("UnityEngine.Rendering.PostProcessing.PostProcessVolume", "Unity.Postprocessing.Runtime");
				if (_ppVolumeType != null)
				{
					_ppVolumeProfileMember = FindMember(_ppVolumeType, "profileRef") ?? FindMember(_ppVolumeType, "profile");
					Type memberType2 = GetMemberType(_ppVolumeProfileMember);
					_ppSettingsMember = ((memberType2 != null) ? FindMember(memberType2, "settings") : null);
				}
			}
			if (_volumeType != null && !_volumePatchApplied)
			{
				TryPatchOnEnable(_volumeType, "VolumeOnEnablePostfix", ref _volumePatchApplied, ref _volumePatchFailureLogged);
			}
			if (_ppVolumeType != null && !_ppVolumePatchApplied)
			{
				TryPatchOnEnable(_ppVolumeType, "PpVolumeOnEnablePostfix", ref _ppVolumePatchApplied, ref _ppVolumePatchFailureLogged);
			}
			if (_findObjectsByTypeMethod == null)
			{
				_findObjectsByTypeMethod = typeof(Object).GetMethod("FindObjectsByType", BindingFlags.Static | BindingFlags.Public, null, new Type[3]
				{
					typeof(Type),
					typeof(FindObjectsInactive),
					typeof(FindObjectsSortMode)
				}, null);
			}
			if (_findObjectsOfTypeMethod == null)
			{
				_findObjectsOfTypeMethod = typeof(Object).GetMethod("FindObjectsOfType", BindingFlags.Static | BindingFlags.Public, null, new Type[2]
				{
					typeof(Type),
					typeof(bool)
				}, null);
			}
		}

		private void TryPatchOnEnable(Type type, string postfixName, ref bool applied, ref bool failureLogged)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			if (applied || type == null || !_config.PatchVolumeOnEnable.Value)
			{
				return;
			}
			try
			{
				MethodInfo method = type.GetMethod("OnEnable", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
				if (method == null)
				{
					_log.LogDebug((object)("[PostFX] " + type.Name + ".OnEnable not found; scene scan will be used."));
					return;
				}
				MethodInfo method2 = typeof(GraphicsOptimizer).GetMethod(postfixName, BindingFlags.Static | BindingFlags.NonPublic);
				if (!(method2 == null))
				{
					_harmony.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					applied = true;
					_log.LogInfo((object)("[PostFX] Harmony patch applied to " + type.FullName + ".OnEnable."));
				}
			}
			catch (Exception ex)
			{
				if (!failureLogged)
				{
					failureLogged = true;
					_log.LogWarning((object)("[PostFX] Failed to patch " + type.FullName + ".OnEnable: " + ex));
				}
				else
				{
					_log.LogDebug((object)("[PostFX] Retry failed for " + type.FullName + ".OnEnable: " + ex.Message));
				}
			}
		}

		private static void VolumeOnEnablePostfix(object __instance)
		{
			try
			{
				_instance?.TryOptimizeVolume(__instance);
			}
			catch (Exception ex)
			{
				GraphicsOptimizer instance = _instance;
				if (instance != null)
				{
					instance._log.LogWarning((object)("[PostFX] Volume.OnEnable postfix failed: " + ex.Message));
				}
			}
		}

		private static void PpVolumeOnEnablePostfix(object __instance)
		{
			try
			{
				_instance?.TryOptimizePpVolume(__instance);
			}
			catch (Exception ex)
			{
				GraphicsOptimizer instance = _instance;
				if (instance != null)
				{
					instance._log.LogWarning((object)("[PostFX] PostProcessVolume.OnEnable postfix failed: " + ex.Message));
				}
			}
		}

		private static Type FindType(string fullName, string assemblyName)
		{
			try
			{
				Type type = Type.GetType(fullName + ", " + assemblyName, throwOnError: false);
				if (type != null)
				{
					return type;
				}
			}
			catch
			{
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				try
				{
					Type type2 = assemblies[i].GetType(fullName, throwOnError: false);
					if (type2 != null)
					{
						return type2;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private static MemberInfo FindMember(Type type, string name)
		{
			if (type == null)
			{
				return null;
			}
			PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null)
			{
				return property;
			}
			return type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		}

		private static Type GetMemberType(MemberInfo member)
		{
			if (member is PropertyInfo propertyInfo)
			{
				return propertyInfo.PropertyType;
			}
			if (member is FieldInfo fieldInfo)
			{
				return fieldInfo.FieldType;
			}
			return null;
		}

		private static bool TryGetMemberValue(object target, MemberInfo member, out object value)
		{
			value = null;
			if (target == null || member == null)
			{
				return false;
			}
			try
			{
				if (member is PropertyInfo propertyInfo)
				{
					value = propertyInfo.GetValue(target, null);
					return true;
				}
				if (member is FieldInfo fieldInfo)
				{
					value = fieldInfo.GetValue(target);
					return true;
				}
			}
			catch
			{
			}
			return false;
		}

		private ActiveMember GetActiveMember(Type type)
		{
			if (type == null)
			{
				return default(ActiveMember);
			}
			if (_activeMemberCache.TryGetValue(type, out var value))
			{
				return value;
			}
			ActiveMember activeMember = default(ActiveMember);
			PropertyInfo property = type.GetProperty("active", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null && property.PropertyType == typeof(bool) && property.CanRead && property.CanWrite)
			{
				activeMember.Property = property;
			}
			else
			{
				FieldInfo field = type.GetField("active", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field != null && field.FieldType == typeof(bool))
				{
					activeMember.Field = field;
				}
			}
			_activeMemberCache[type] = activeMember;
			return activeMember;
		}

		private static bool GetActive(object component, ActiveMember member)
		{
			if (component == null)
			{
				return false;
			}
			try
			{
				if (member.Property != null)
				{
					return (bool)member.Property.GetValue(component, null);
				}
				if (member.Field != null)
				{
					return (bool)member.Field.GetValue(component);
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool SetActive(object component, ActiveMember member, bool value)
		{
			if (component == null)
			{
				return false;
			}
			try
			{
				if (member.Property != null)
				{
					member.Property.SetValue(component, value, null);
					return true;
				}
				if (member.Field != null)
				{
					member.Field.SetValue(component, value);
					return true;
				}
			}
			catch
			{
			}
			return false;
		}

		private Object[] FindObjects(Type type)
		{
			//IL_0128: 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)
			if (type == null)
			{
				return Array.Empty<Object>();
			}
			try
			{
				if (_findObjectsByTypeMethod != null && _findObjectsByTypeMethod.Invoke(null, new object[3]
				{
					type,
					(object)(FindObjectsInactive)1,
					(object)(FindObjectsSortMode)0
				}) is Object[] result)
				{
					return result;
				}
			}
			catch (Exception ex)
			{
				_log.LogDebug((object)("[PostFX] FindObjectsByType failed: " + ex.Message));
			}
			try
			{
				if (_findObjectsOfTypeMethod != null && _findObjectsOfTypeMethod.Invoke(null, new object[2] { type, true }) is Object[] result2)
				{
					return result2;
				}
			}
			catch (Exception ex2)
			{
				_log.LogDebug((object)("[PostFX] FindObjectsOfType failed: " + ex2.Message));
			}
			try
			{
				Object[] array = Resources.FindObjectsOfTypeAll(type);
				if (array == null || array.Length == 0)
				{
					return Array.Empty<Object>();
				}
				List<Object> list = new List<Object>(array.Length);
				foreach (Object val in array)
				{
					if (val == (Object)null)
					{
						continue;
					}
					Component val2 = (Component)(object)((val is Component) ? val : null);
					if (val2 != null)
					{
						Scene scene = val2.gameObject.scene;
						if (((Scene)(ref scene)).IsValid())
						{
							list.Add(val);
						}
					}
				}
				return list.ToArray();
			}
			catch (Exception ex3)
			{
				_log.LogDebug((object)("[PostFX] Resources fallback failed: " + ex3.Message));
				return Array.Empty<Object>();
			}
		}

		private void RefreshDisabledEffectNames()
		{
			string value = _config.DisabledPostEffects.Value;
			if (!string.Equals(value, _lastDisabledEffectsRaw, StringComparison.Ordinal))
			{
				_lastDisabledEffectsRaw = value;
				_disabledEffectNames = ParseNameSet(value);
			}
		}

		private static HashSet<string> ParseNameSet(string value)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			if (string.IsNullOrEmpty(value))
			{
				return hashSet;
			}
			string[] array = value.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length > 0)
				{
					hashSet.Add(text);
				}
			}
			return hashSet;
		}

		private void CaptureQualitySettings()
		{
			//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_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)
			_originalTextureMipLimit = GetTextureMipLimit();
			_originalAntiAliasing = QualitySettings.antiAliasing;
			_originalAnisotropicFiltering = QualitySettings.anisotropicFiltering;
			_originalSoftParticles = QualitySettings.softParticles;
			_originalLodBias = QualitySettings.lodBias;
			_originalMaximumLodLevel = QualitySettings.maximumLODLevel;
			_originalShadows = QualitySettings.shadows;
			_originalShadowDistance = QualitySettings.shadowDistance;
			_originalShadowCascades = QualitySettings.shadowCascades;
			_originalLodCrossFade = QualitySettings.enableLODCrossFade;
			_qualitySnapshotValid = true;
		}

		private void ApplyQualitySettings()
		{
			if (_config.EnableTextureMipLimit.Value)
			{
				SetTextureMipLimit(_config.TextureMipLimit.Value);
			}
			if (_config.DisableMsaa.Value)
			{
				QualitySettings.antiAliasing = 0;
			}
			if (_config.DisableAnisotropicFiltering.Value)
			{
				QualitySettings.anisotropicFiltering = (AnisotropicFiltering)0;
			}
			if (_config.DisableSoftParticles.Value)
			{
				QualitySettings.softParticles = false;
			}
			if (_config.EnableLodControl.Value)
			{
				QualitySettings.lodBias = _config.LodBias.Value;
				QualitySettings.maximumLODLevel = _config.MaximumLodLevel.Value;
			}
			if (_config.EnableLightOptimization.Value && _config.DisableLightShadows.Value)
			{
				QualitySettings.shadows = (ShadowQuality)0;
				QualitySettings.shadowDistance = 0f;
			}
			if (_config.DisableShadowCascades.Value)
			{
				QualitySettings.shadowCascades = 0;
			}
			if (_config.DisableLodCrossFade.Value)
			{
				QualitySettings.enableLODCrossFade = false;
			}
		}

		private void RestoreQualitySettings()
		{
			//IL_0021: 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)
			if (_qualitySnapshotValid)
			{
				SetTextureMipLimit(_originalTextureMipLimit);
				QualitySettings.antiAliasing = _originalAntiAliasing;
				QualitySettings.anisotropicFiltering = _originalAnisotropicFiltering;
				QualitySettings.softParticles = _originalSoftParticles;
				QualitySettings.lodBias = _originalLodBias;
				QualitySettings.maximumLODLevel = _originalMaximumLodLevel;
				QualitySettings.shadows = _originalShadows;
				QualitySettings.shadowDistance = _originalShadowDistance;
				QualitySettings.shadowCascades = _originalShadowCascades;
				QualitySettings.enableLODCrossFade = _originalLodCrossFade;
				_qualitySnapshotValid = false;
			}
		}

		private int GetTextureMipLimit()
		{
			try
			{
				if (GlobalTextureMipmapLimitProperty != null)
				{
					return (int)GlobalTextureMipmapLimitProperty.GetValue(null, null);
				}
				if (MasterTextureLimitProperty != null)
				{
					return (int)MasterTextureLimitProperty.GetValue(null, null);
				}
			}
			catch (Exception ex)
			{
				if (!_textureMipWarningLogged)
				{
					_textureMipWarningLogged = true;
					_log.LogWarning((object)("[Rendering] Failed to read texture mip limit: " + ex.Message));
				}
			}
			return 0;
		}

		private void SetTextureMipLimit(int value)
		{
			try
			{
				if (GlobalTextureMipmapLimitProperty != null)
				{
					GlobalTextureMipmapLimitProperty.SetValue(null, value, null);
					return;
				}
				if (MasterTextureLimitProperty != null)
				{
					MasterTextureLimitProperty.SetValue(null, value, null);
					return;
				}
			}
			catch (Exception ex)
			{
				if (!_textureMipWarningLogged)
				{
					_textureMipWarningLogged = true;
					_log.LogWarning((object)("[Rendering] Failed to set texture mip limit: " + ex.Message));
				}
				return;
			}
			if (!_textureMipWarningLogged)
			{
				_textureMipWarningLogged = true;
				_log.LogWarning((object)"[Rendering] Neither globalTextureMipmapLimit nor masterTextureLimit is available.");
			}
		}

		private void ApplyUrpSettings()
		{
			RenderPipelineAsset val = GraphicsSettings.currentRenderPipeline;
			if ((Object)(object)val == (Object)null)
			{
				val = QualitySettings.renderPipeline;
			}
			LastUrpFound = (Object)(object)val != (Object)null;
			if ((Object)(object)val == (Object)null)
			{
				if (!_urpMissingLogged)
				{
					_urpMissingLogged = true;
					_log.LogInfo((object)"[Rendering] No SRP asset detected (Built-in Render Pipeline?). URP renderScale/MSAA skipped.");
				}
				LastRenderScaleApplied = false;
				LastMsaaApplied = false;
				return;
			}
			if (!_urpSettingsCaptured || (Object)(object)_urpAsset != (Object)(object)val)
			{
				RestoreUrpSettings();
				_urpAsset = val;
				_hasRenderScale = TryGetFloatMember(val, "renderScale", "m_RenderScale", out _originalRenderScale);
				_hasMsaa = TryGetIntMember(val, "msaaSampleCount", "m_MSAA", out _originalMsaa);
				_urpSettingsCaptured = true;
			}
			LastRenderScaleApplied = false;
			LastMsaaApplied = false;
			if (_config.EnableRenderScale.Value && _hasRenderScale)
			{
				float value = Mathf.Clamp(_config.RenderScale.Value, 0.5f, 1f);
				LastRenderScaleApplied = TrySetFloatMember(val, "renderScale", "m_RenderScale", value);
			}
			if (_config.DisableMsaa.Value && _hasMsaa)
			{
				LastMsaaApplied = TrySetIntMember(val, "msaaSampleCount", "m_MSAA", 1);
			}
			if (!_hasRenderScale && !_hasMsaa && _config.VerboseLogging.Value)
			{
				_log.LogInfo((object)("[Rendering] SRP asset found, but renderScale/msaaSampleCount are not exposed: " + ((object)val).GetType().FullName));
			}
		}

		private void RestoreUrpSettings()
		{
			if (!_urpSettingsCaptured || (Object)(object)_urpAsset == (Object)null)
			{
				_urpSettingsCaptured = false;
				_urpAsset = null;
				_hasRenderScale = false;
				_hasMsaa = false;
				return;
			}
			if (_hasRenderScale)
			{
				TrySetFloatMember(_urpAsset, "renderScale", "m_RenderScale", _originalRenderScale);
			}
			if (_hasMsaa)
			{
				TrySetIntMember(_urpAsset, "msaaSampleCount", "m_MSAA", _originalMsaa);
			}
			_urpSettingsCaptured = false;
			_urpAsset = null;
			_hasRenderScale = false;
			_hasMsaa = false;
		}

		private static bool TryGetFloatMember(object target, string propertyName, string fieldName, out float value)
		{
			value = 0f;
			if (target == null)
			{
				return false;
			}
			Type type = target.GetType();
			try
			{
				PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null && property.PropertyType == typeof(float) && property.CanRead)
				{
					value = (float)property.GetValue(target, null);
					return true;
				}
				FieldInfo fieldInfo = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? type.GetField(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (fieldInfo != null && fieldInfo.FieldType == typeof(float))
				{
					value = (float)fieldInfo.GetValue(target);
					return true;
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool TrySetFloatMember(object target, string propertyName, string fieldName, float value)
		{
			if (target == null)
			{
				return false;
			}
			Type type = target.GetType();
			try
			{
				PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null && property.PropertyType == typeof(float) && property.CanWrite)
				{
					property.SetValue(target, value, null);
					return true;
				}
				FieldInfo fieldInfo = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? type.GetField(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (fieldInfo != null && fieldInfo.FieldType == typeof(float))
				{
					fieldInfo.SetValue(target, value);
					return true;
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool TryGetIntMember(object target, string propertyName, string fieldName, out int value)
		{
			value = 0;
			if (target == null)
			{
				return false;
			}
			Type type = target.GetType();
			try
			{
				PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null && property.PropertyType == typeof(int) && property.CanRead)
				{
					value = (int)property.GetValue(target, null);
					return true;
				}
				FieldInfo fieldInfo = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? type.GetField(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (fieldInfo != null && fieldInfo.FieldType == typeof(int))
				{
					value = (int)fieldInfo.GetValue(target);
					return true;
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool TrySetIntMember(object target, string propertyName, string fieldName, int value)
		{
			if (target == null)
			{
				return false;
			}
			Type type = target.GetType();
			try
			{
				PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null && property.PropertyType == typeof(int) && property.CanWrite)
				{
					property.SetValue(target, value, null);
					return true;
				}
				FieldInfo fieldInfo = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? type.GetField(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (fieldInfo != null && fieldInfo.FieldType == typeof(int))
				{
					fieldInfo.SetValue(target, value);
					return true;
				}
			}
			catch
			{
			}
			return false;
		}
	}
	internal enum FlashlightRenderModeOption
	{
		Auto,
		ForcePixel
	}
	internal sealed class OptimizerConfig
	{
		public ConfigEntry<bool> Enabled { get; }

		public ConfigEntry<KeyboardShortcut> ToggleHotkey { get; }

		public ConfigEntry<float> ScanIntervalSeconds { get; }

		public ConfigEntry<bool> VerboseLogging { get; }

		public ConfigEntry<bool> ReapplyQualitySettings { get; }

		public ConfigEntry<bool> EnableRenderScale { get; }

		public ConfigEntry<float> RenderScale { get; }

		public ConfigEntry<bool> EnableTextureMipLimit { get; }

		public ConfigEntry<int> TextureMipLimit { get; }

		public ConfigEntry<bool> DisableMsaa { get; }

		public ConfigEntry<bool> DisableAnisotropicFiltering { get; }

		public ConfigEntry<bool> DisableSoftParticles { get; }

		public ConfigEntry<bool> EnableLodControl { get; }

		public ConfigEntry<float> LodBias { get; }

		public ConfigEntry<int> MaximumLodLevel { get; }

		public ConfigEntry<bool> DisableShadowCascades { get; }

		public ConfigEntry<bool> DisableLodCrossFade { get; }

		public ConfigEntry<bool> DisableCameraHdr { get; }

		public ConfigEntry<bool> EnablePostProcessingCleanup { get; }

		public ConfigEntry<string> DisabledPostEffects { get; }

		public ConfigEntry<bool> PatchVolumeOnEnable { get; }

		public ConfigEntry<bool> EnableLightOptimization { get; }

		public ConfigEntry<bool> DisableLightShadows { get; }

		public ConfigEntry<bool> ForceVertexLighting { get; }

		public ConfigEntry<bool> PreservePlayerFlashlight { get; }

		public ConfigEntry<FlashlightRenderModeOption> FlashlightRenderMode { get; }

		public ConfigEntry<string> FlashlightNameHints { get; }

		public ConfigEntry<bool> EnableParticleOptimization { get; }

		public ConfigEntry<int> MaxParticles { get; }

		public ConfigEntry<bool> DisableParticleCollisions { get; }

		public ConfigEntry<bool> DisableParticleTriggers { get; }

		public OptimizerConfig(ConfigFile config)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_0043: 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)
			//IL_005d: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Expected O, but got Unknown
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Expected O, but got Unknown
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Expected O, but got Unknown
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Expected O, but got Unknown
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Expected O, but got Unknown
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Expected O, but got Unknown
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Expected O, but got Unknown
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Expected O, but got Unknown
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Expected O, but got Unknown
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Expected O, but got Unknown
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Expected O, but got Unknown
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_030f: Expected O, but got Unknown
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Expected O, but got Unknown
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_0361: Expected O, but got Unknown
			//IL_037e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0388: Expected O, but got Unknown
			//IL_03a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03af: Expected O, but got Unknown
			//IL_03cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d6: Expected O, but got Unknown
			//IL_03f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fd: Expected O, but got Unknown
			//IL_041a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Expected O, but got Unknown
			//IL_0441: Unknown result type (might be due to invalid IL or missing references)
			//IL_044b: Expected O, but got Unknown
			//IL_046c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0476: Expected O, but got Unknown
			//IL_0493: Unknown result type (might be due to invalid IL or missing references)
			//IL_049d: Expected O, but got Unknown
			//IL_04c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cf: Expected O, but got Unknown
			//IL_04ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f6: Expected O, but got Unknown
			//IL_0513: Unknown result type (might be due to invalid IL or missing references)
			//IL_051d: Expected O, but got Unknown
			Enabled = config.Bind<bool>("General", "Enabled", true, new ConfigDescription("EN: Enable aggressive optimization at startup. / RU: Включать агрессивную оптимизацию при запуске.", (AcceptableValueBase)null, Array.Empty<object>()));
			ToggleHotkey = config.Bind<KeyboardShortcut>("General", "ToggleHotkey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), new ConfigDescription("EN: Hotkey to toggle aggressive mode in game. / RU: Горячая клавиша переключения агрессивного режима.", (AcceptableValueBase)null, Array.Empty<object>()));
			ScanIntervalSeconds = config.Bind<float>("General", "ScanIntervalSeconds", 2f, new ConfigDescription("EN: How often to look for newly spawned lights/particles. / RU: Интервал поиска новых источников света и частиц (сек).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>()));
			VerboseLogging = config.Bind<bool>("General", "VerboseLogging", false, new ConfigDescription("EN: Log every scan and per-object details. / RU: Подробный лог каждого сканирования.", (AcceptableValueBase)null, Array.Empty<object>()));
			ReapplyQualitySettings = config.Bind<bool>("General", "ReapplyQualitySettings", true, new ConfigDescription("EN: Re-assert QualitySettings every few seconds, because the in-game graphics menu overwrites them. / RU: Повторно применять QualitySettings каждые несколько секунд, так как меню графики игры их перезаписывает.", (AcceptableValueBase)null, Array.Empty<object>()));
			EnableRenderScale = config.Bind<bool>("Rendering", "EnableRenderScale", true, new ConfigDescription("EN: Apply URP render scale. / RU: Применять URP render scale.", (AcceptableValueBase)null, Array.Empty<object>()));
			RenderScale = config.Bind<float>("Rendering", "RenderScale", 0.75f, new ConfigDescription("EN: URP render scale (0.5-1.0). Lower = faster, blurrier 3D. / RU: Масштаб рендера URP (0.5-1.0). Ниже = быстрее, но размытее 3D.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 1f), Array.Empty<object>()));
			EnableTextureMipLimit = config.Bind<bool>("Rendering", "EnableTextureMipLimit", true, new ConfigDescription("EN: Reduce texture resolution via global mipmap limit. / RU: Снижать разрешение текстур через глобальный mipmap limit.", (AcceptableValueBase)null, Array.Empty<object>()));
			TextureMipLimit = config.Bind<int>("Rendering", "TextureMipLimit", 1, new ConfigDescription("EN: Texture mip limit: 0 = full, 1 = half, 2 = quarter, 3 = eighth. / RU: Лимит мип-уровней текстур: 0 = полное, 1 = половина, 2 = четверть, 3 = восьмая часть.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 3), Array.Empty<object>()));
			DisableMsaa = config.Bind<bool>("Rendering", "DisableMsaa", true, new ConfigDescription("EN: Disable MSAA in QualitySettings and URP asset. / RU: Отключить MSAA в QualitySettings и URP-ассете.", (AcceptableValueBase)null, Array.Empty<object>()));
			DisableAnisotropicFiltering = config.Bind<bool>("Rendering", "DisableAnisotropicFiltering", true, new ConfigDescription("EN: Disable anisotropic filtering. / RU: Отключить анизотропную фильтрацию.", (AcceptableValueBase)null, Array.Empty<object>()));
			DisableSoftParticles = config.Bind<bool>("Rendering", "DisableSoftParticles", true, new ConfigDescription("EN: Disable soft particles. / RU: Отключить мягкие частицы.", (AcceptableValueBase)null, Array.Empty<object>()));
			EnableLodControl = config.Bind<bool>("Rendering", "EnableLodControl", true, new ConfigDescription("EN: Apply LOD bias / maximum LOD level. / RU: Применять LOD bias и максимальный LOD-уровень.", (AcceptableValueBase)null, Array.Empty<object>()));
			LodBias = config.Bind<float>("Rendering", "LodBias", 0.55f, new ConfigDescription("EN: LOD bias. Lower = lower-detail LODs sooner. / RU: LOD bias. Ниже = раньше включаются низкодетальные LOD.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 2f), Array.Empty<object>()));
			MaximumLodLevel = config.Bind<int>("Rendering", "MaximumLodLevel", 0, new ConfigDescription("EN: Maximum LOD level (0 = all LODs, 1+ = more aggressive). / RU: Максимальный LOD-уровень (0 = все LOD, 1+ = агрессивнее).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 2), Array.Empty<object>()));
			DisableShadowCascades = config.Bind<bool>("Rendering", "DisableShadowCascades", true, new ConfigDescription("EN: Set shadow cascades to 0 (free once shadows are disabled). / RU: Обнулить каскады теней (бесплатно, когда тени уже отключены).", (AcceptableValueBase)null, Array.Empty<object>()));
			DisableLodCrossFade = config.Bind<bool>("Rendering", "DisableLodCrossFade", true, new ConfigDescription("EN: Disable LOD cross-fade to remove popping and save CPU. / RU: Отключить LOD cross-fade, чтобы убрать «прыжки» объектов и разгрузить CPU.", (AcceptableValueBase)null, Array.Empty<object>()));
			DisableCameraHdr = config.Bind<bool>("Rendering", "DisableCameraHdr", false, new ConfigDescription("EN: Disable HDR on scene cameras. Saves fill rate, slightly changes lighting. / RU: Отключить HDR у камер сцены. Экономит fill rate, немного меняет освещение.", (AcceptableValueBase)null, Array.Empty<object>()));
			EnablePostProcessingCleanup = config.Bind<bool>("Post-Processing", "EnablePostProcessingCleanup", true, new ConfigDescription("EN: Disable only heavy post-processing effects, keep color/exposure. / RU: Отключать только тяжёлые пост-эффекты, сохраняя цвет и экспозицию.", (AcceptableValueBase)null, Array.Empty<object>()));
			DisabledPostEffects = config.Bind<string>("Post-Processing", "DisabledPostEffects", "Bloom,MotionBlur,ScreenSpaceAmbientOcclusion,DepthOfField,ChromaticAberration,FilmGrain,Vignette,AmbientOcclusion,Grain", new ConfigDescription("EN: Comma-separated effect type names to disable. / RU: Имена типов эффектов через запятую. URP: Bloom, MotionBlur, ScreenSpaceAmbientOcclusion, DepthOfField, ChromaticAberration, FilmGrain, Vignette. PPv2: Bloom, MotionBlur, AmbientOcclusion, DepthOfField, ChromaticAberration, Grain, Vignette.", (AcceptableValueBase)null, Array.Empty<object>()));
			PatchVolumeOnEnable = config.Bind<bool>("Post-Processing", "PatchVolumeOnEnable", true, new ConfigDescription("EN: Harmony patch Volume.OnEnable/PostProcessVolume.OnEnable so new volumes are cleaned automatically. / RU: Harmony-патч OnEnable новых Volume/PostProcessVolume.", (AcceptableValueBase)null, Array.Empty<object>()));
			EnableLightOptimization = config.Bind<bool>("Lighting", "EnableLightOptimization", true, new ConfigDescription("EN: Optimize lights and global shadows. / RU: Оптимизировать источники света и глобальные тени.", (AcceptableValueBase)null, Array.Empty<object>()));
			DisableLightShadows = config.Bind<bool>("Lighting", "DisableLightShadows", true, new ConfigDescription("EN: Disable all real-time shadows. / RU: Отключить все реалтайм-тени.", (AcceptableValueBase)null, Array.Empty<object>()));
			ForceVertexLighting = config.Bind<bool>("Lighting", "ForceVertexLighting", true, new ConfigDescription("EN: Force vertex lighting for non-flashlight lights. / RU: Вершинное освещение для всех источников, кроме фонарика.", (AcceptableValueBase)null, Array.Empty<object>()));
			PreservePlayerFlashlight = config.Bind<bool>("Lighting", "PreservePlayerFlashlight", true, new ConfigDescription("EN: Keep the player flashlight on Auto/ForcePixel to avoid blocky walls. / RU: Оставлять фонарик игрока на Auto/ForcePixel, чтобы стены не стали «лесенкой».", (AcceptableValueBase)null, Array.Empty<object>()));
			FlashlightRenderMode = config.Bind<FlashlightRenderModeOption>("Lighting", "FlashlightRenderMode", FlashlightRenderModeOption.Auto, new ConfigDescription("EN: Render mode for detected player flashlight. / RU: Режим рендера для найденного фонарика игрока.", (AcceptableValueBase)null, Array.Empty<object>()));
			FlashlightNameHints = config.Bind<string>("Lighting", "FlashlightNameHints", "flashlight,torch,lantern,headlamp,player", new ConfigDescription("EN: Comma-separated name fragments used to detect the player flashlight. / RU: Фрагменты имён для поиска фонарика игрока через запятую.", (AcceptableValueBase)null, Array.Empty<object>()));
			EnableParticleOptimization = config.Bind<bool>("Particles", "EnableParticleOptimization", true, new ConfigDescription("EN: Limit particle counts and disable particle physics. / RU: Ограничивать количество частиц и отключать физику частиц.", (AcceptableValueBase)null, Array.Empty<object>()));
			MaxParticles = config.Bind<int>("Particles", "MaxParticles", 25, new ConfigDescription("EN: Maximum particles per ParticleSystem. / RU: Максимум частиц на одну ParticleSystem.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000), Array.Empty<object>()));
			DisableParticleCollisions = config.Bind<bool>("Particles", "DisableParticleCollisions", true, new ConfigDescription("EN: Disable ParticleSystem collision module. / RU: Отключить модуль коллизий частиц.", (AcceptableValueBase)null, Array.Empty<object>()));
			DisableParticleTriggers = config.Bind<bool>("Particles", "DisableParticleTriggers", true, new ConfigDescription("EN: Disable ParticleSystem trigger module. / RU: Отключить модуль триггеров частиц.", (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[BepInPlugin("com.nlp-core-team.repooptimizer", "R.E.P.O. Performance Optimizer", "1.1.0")]
	[BepInProcess("REPO.exe")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.nlp-core-team.repooptimizer";

		public const string PluginName = "R.E.P.O. Performance Optimizer";

		public const string PluginVersion = "1.1.0";

		private Harmony _harmony;

		private OptimizerConfig _config;

		private GraphicsOptimizer _graphics;

		private SceneObjectOptimizer _sceneObjects;

		private HotkeyService _hotkey;

		private bool _aggressiveMode;

		private Coroutine _sceneApplyCoroutine;

		private Coroutine _summaryCoroutine;

		private Coroutine _reapplyCoroutine;

		private bool _toggleQueued;

		internal static Plugin Instance { get; private set; }

		private void Awake()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			Instance = this;
			_config = new OptimizerConfig(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("com.nlp-core-team.repooptimizer");
			_graphics = new GraphicsOptimizer(((BaseUnityPlugin)this).Logger, _config, _harmony);
			_sceneObjects = ((Component)this).gameObject.AddComponent<SceneObjectOptimizer>();
			_sceneObjects.Initialize(((BaseUnityPlugin)this).Logger, _config);
			_hotkey = new HotkeyService(((BaseUnityPlugin)this).Logger, _config.ToggleHotkey);
			SceneManager.sceneLoaded += OnSceneLoaded;
			_aggressiveMode = _config.Enabled.Value;
			_graphics.IsEnabled = _aggressiveMode;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("R.E.P.O. Performance Optimizer v1.1.0 loaded. Aggressive mode: " + (_aggressiveMode ? "ON" : "OFF") + "."));
			((MonoBehaviour)this).StartCoroutine(InitialApplyRoutine());
		}

		private IEnumerator Start()
		{
			yield return null;
			if (_hotkey != null)
			{
				_hotkey.TryInitializeInputSystemFallback();
			}
		}

		private IEnumerator InitialApplyRoutine()
		{
			yield return null;
			if (_aggressiveMode)
			{
				EnableAggressiveMode();
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			if (_aggressiveMode)
			{
				if (_sceneApplyCoroutine != null)
				{
					((MonoBehaviour)this).StopCoroutine(_sceneApplyCoroutine);
				}
				_sceneApplyCoroutine = ((MonoBehaviour)this).StartCoroutine(ApplyAfterSceneLoad(((Scene)(ref scene)).name));
			}
		}

		private IEnumerator ApplyAfterSceneLoad(string sceneName)
		{
			yield return null;
			if (!_aggressiveMode)
			{
				_sceneApplyCoroutine = null;
				yield break;
			}
			try
			{
				_graphics.ApplySettings();
				_graphics.ScanVolumes();
				_sceneObjects.OnSceneLoaded();
				if (_hotkey != null)
				{
					_hotkey.TryInitializeInputSystemFallback();
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)("[Scene] '" + sceneName + "' global settings applied; scene scan started."));
				StartSummaryLog();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("[Scene] Failed to apply scene optimization: " + ex));
			}
			_sceneApplyCoroutine = null;
		}

		private void Update()
		{
			if (_hotkey != null && !_toggleQueued && _hotkey.WasPressed())
			{
				_toggleQueued = true;
				((MonoBehaviour)this).StartCoroutine(ProcessToggleNextFrame());
			}
		}

		private IEnumerator ProcessToggleNextFrame()
		{
			yield return null;
			_toggleQueued = false;
			ToggleAggressiveMode();
		}

		private void ToggleAggressiveMode()
		{
			if (_aggressiveMode)
			{
				DisableAggressiveMode();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"[Hotkey] Aggressive mode OFF. Original settings restored.");
			}
			else
			{
				EnableAggressiveMode();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"[Hotkey] Aggressive mode ON.");
			}
		}

		private void EnableAggressiveMode()
		{
			_aggressiveMode = true;
			try
			{
				_graphics.IsEnabled = true;
				_graphics.Apply();
				_sceneObjects.StartScanning(waitOneFrame: true);
				if (_reapplyCoroutine == null)
				{
					_reapplyCoroutine = ((MonoBehaviour)this).StartCoroutine(ReapplyQualityLoop());
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)"[Optimizer] Aggressive mode ON; applying settings and scanning the scene...");
				StartSummaryLog();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("[Optimizer] Failed to enable aggressive mode: " + ex));
			}
		}

		private void DisableAggressiveMode()
		{
			_aggressiveMode = false;
			try
			{
				if (_sceneApplyCoroutine != null)
				{
					((MonoBehaviour)this).StopCoroutine(_sceneApplyCoroutine);
					_sceneApplyCoroutine = null;
				}
				if (_summaryCoroutine != null)
				{
					((MonoBehaviour)this).StopCoroutine(_summaryCoroutine);
					_summaryCoroutine = null;
				}
				if (_reapplyCoroutine != null)
				{
					((MonoBehaviour)this).StopCoroutine(_reapplyCoroutine);
					_reapplyCoroutine = null;
				}
				_sceneObjects.StopScanning();
				_sceneObjects.RestoreAll();
				_graphics.IsEnabled = false;
				_graphics.Restore();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"[Optimizer] Restored QualitySettings, post-processing and scene objects.");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("[Optimizer] Failed to restore original settings: " + ex));
			}
		}

		private void StartSummaryLog()
		{
			if (_summaryCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(_summaryCoroutine);
			}
			_summaryCoroutine = ((MonoBehaviour)this).StartCoroutine(LogSummaryAfterFirstScan());
		}

		private IEnumerator LogSummaryAfterFirstScan()
		{
			int generation = _sceneObjects.ScanGeneration;
			float deadline = Time.realtimeSinceStartup + 10f;
			while (_aggressiveMode && _sceneObjects.ScanGeneration == generation && Time.realtimeSinceStartup < deadline)
			{
				yield return null;
			}
			if (_aggressiveMode)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("[Optimizer] Summary: URP asset=" + (_graphics.LastUrpFound ? "found" : "none") + ", renderScale=" + (_graphics.LastRenderScaleApplied ? _config.RenderScale.Value.ToString("0.00") : "n/a") + ", MSAA=" + (_graphics.LastMsaaApplied ? "off" : "n/a") + ", volumes=" + _graphics.LastVolumesScanned + ", post-FX disabled=" + _graphics.LastEffectsDisabled + ", lights=" + _sceneObjects.TotalLightsChanged + "/" + _sceneObjects.TotalLightsProcessed + ", particles=" + _sceneObjects.TotalParticlesChanged + "/" + _sceneObjects.TotalParticlesProcessed + ", cameras HDR off=" + _sceneObjects.LastNewCameras + "."));
			}
			_summaryCoroutine = null;
		}

		private IEnumerator ReapplyQualityLoop()
		{
			WaitForSeconds wait = new WaitForSeconds(Mathf.Max(10f, _config.ScanIntervalSeconds.Value * 5f));
			while (_aggressiveMode)
			{
				yield return wait;
				if (_aggressiveMode && _config.ReapplyQualitySettings.Value)
				{
					try
					{
						_graphics.ApplySettings();
					}
					catch (Exception ex)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("[Optimizer] QualitySettings reapply failed: " + ex.Message));
					}
				}
			}
			_reapplyCoroutine = null;
		}

		private void OnDestroy()
		{
			try
			{
				SceneManager.sceneLoaded -= OnSceneLoaded;
				if (_sceneApplyCoroutine != null)
				{
					((MonoBehaviour)this).StopCoroutine(_sceneApplyCoroutine);
				}
				if (_summaryCoroutine != null)
				{
					((MonoBehaviour)this).StopCoroutine(_summaryCoroutine);
				}
				if (_reapplyCoroutine != null)
				{
					((MonoBehaviour)this).StopCoroutine(_reapplyCoroutine);
				}
				if ((Object)(object)_sceneObjects != (Object)null)
				{
					_sceneObjects.StopScanning();
					_sceneObjects.RestoreAll();
					Object.Destroy((Object)(object)_sceneObjects);
				}
				if (_graphics != null)
				{
					_graphics.IsEnabled = false;
					_graphics.Restore();
				}
				if (_harmony != null)
				{
					_harmony.UnpatchSelf();
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("[Optimizer] Cleanup failed: " + ex));
			}
			Instance = null;
		}
	}
	internal sealed class HotkeyService
	{
		private readonly ManualLogSource _log;

		private readonly ConfigEntry<KeyboardShortcut> _shortcut;

		private bool _useInputSystem;

		private bool _inputSystemInitialized;

		private bool _fallbackUnavailable;

		private bool _fallbackWarningLogged;

		private int _fallbackAttempts;

		private Type _keyEnumType;

		private Func<object> _keyboardCurrentGetter;

		private Func<object, object, object> _keyboardIndexer;

		private Func<object, bool> _wasPressed;

		private Func<object, bool> _isPressed;

		private object _mainKeyValue;

		private object[] _modifierKeyValues = Array.Empty<object>();

		public HotkeyService(ManualLogSource log, ConfigEntry<KeyboardShortcut> shortcut)
		{
			_log = log;
			_shortcut = shortcut;
			if (!IsLegacyInputAvailable())
			{
				_useInputSystem = true;
				_log.LogInfo((object)"[Hotkey] Legacy UnityEngine.Input is disabled; using the Input System fallback.");
			}
			TryInitializeInputSystemFallback();
		}

		private static bool IsLegacyInputAvailable()
		{
			try
			{
				Input.GetKey((KeyCode)0);
				return true;
			}
			catch
			{
				return false;
			}
		}

		public bool WasPressed()
		{
			//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)
			if (!_useInputSystem)
			{
				try
				{
					KeyboardShortcut value = _shortcut.Value;
					return ((KeyboardShortcut)(ref value)).IsPressed();
				}
				catch (Exception ex)
				{
					_useInputSystem = true;
					_log.LogWarning((object)("[Hotkey] Legacy UnityEngine.Input is unavailable; switching to Input System fallback. " + ex.GetType().Name + ": " + ex.Message));
				}
			}
			if (!_inputSystemInitialized)
			{
				if (!_fallbackWarningLogged)
				{
					_fallbackWarningLogged = true;
					_log.LogWarning((object)"[Hotkey] Input System fallback is not ready or unavailable; hotkey is disabled.");
				}
				return false;
			}
			return WasPressedInputSystem();
		}

		internal bool TryInitializeInputSystemFallback()
		{
			if (_inputSystemInitialized)
			{
				return true;
			}
			if (_fallbackUnavailable)
			{
				return false;
			}
			_fallbackAttempts++;
			if (TryInitializeInputSystem())
			{
				_inputSystemInitialized = true;
				_log.LogDebug((object)"[Hotkey] Input System fallback ready.");
				return true;
			}
			if (_fallbackAttempts >= 3)
			{
				_fallbackUnavailable = true;
				_log.LogWarning((object)"[Hotkey] Input System fallback could not be initialized; the hotkey will use legacy Input only.");
			}
			return false;
		}

		private unsafe bool TryInitializeInputSystem()
		{
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Type type = Type.GetType("UnityEngine.InputSystem.Keyboard, Unity.InputSystem", throwOnError: false);
				if (type == null)
				{
					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
					for (int i = 0; i < assemblies.Length; i++)
					{
						Type type2 = assemblies[i].GetType("UnityEngine.InputSystem.Keyboard", throwOnError: false);
						if (type2 != null)
						{
							type = type2;
							break;
						}
					}
				}
				if (type == null)
				{
					return false;
				}
				_keyEnumType = type.Assembly.GetType("UnityEngine.InputSystem.Key", throwOnError: false);
				PropertyInfo property = type.GetProperty("current", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo propertyInfo = FindKeyboardIndexer(type, _keyEnumType);
				Type type3 = type.Assembly.GetType("UnityEngine.InputSystem.Controls.ButtonControl", throwOnError: false);
				PropertyInfo propertyInfo2 = type3?.GetProperty("wasPressedThisFrame", BindingFlags.Instance | BindingFlags.Public);
				PropertyInfo propertyInfo3 = type3?.GetProperty("isPressed", BindingFlags.Instance | BindingFlags.Public);
				if (_keyEnumType == null || property == null || propertyInfo == null || type3 == null || propertyInfo2 == null || propertyInfo3 == null)
				{
					return false;
				}
				_keyboardCurrentGetter = Expression.Lambda<Func<object>>(Expression.Convert(Expression.Property(null, property), typeof(object)), Array.Empty<ParameterExpression>()).Compile();
				ParameterExpression parameterExpression = Expression.Parameter(typeof(object), "keyboard");
				ParameterExpression parameterExpression2 = Expression.Parameter(typeof(object), "key");
				MethodCallExpression expression = Expression.Call(Expression.Convert(parameterExpression, type), propertyInfo.GetGetMethod(), Expression.Convert(parameterExpression2, _keyEnumType));
				_keyboardIndexer = Expression.Lambda<Func<object, object, object>>(Expression.Convert(expression, typeof(object)), new ParameterExpression[2] { parameterExpression, parameterExpression2 }).Compile();
				ParameterExpression parameterExpression3 = Expression.Parameter(typeof(object), "control");
				_wasPressed = Expression.Lambda<Func<object, bool>>(Expression.Property(Expression.Convert(parameterExpression3, type3), propertyInfo2), new ParameterExpression[1] { parameterExpression3 }).Compile();
				ParameterExpression parameterExpression4 = Expression.Parameter(typeof(object), "control");
				_isPressed = Expression.Lambda<Func<object, bool>>(Expression.Property(Expression.Convert(parameterExpression4, type3), propertyInfo3), new ParameterExpression[1] { parameterExpression4 }).Compile();
				KeyboardShortcut value = _shortcut.Value;
				_mainKeyValue = TryGetKeyValue(((KeyboardShortcut)(ref value)).MainKey);
				if (_mainKeyValue == null)
				{
					_log.LogWarning((object)("[Hotkey] Unsupported hotkey: " + ((object)((KeyboardShortcut)(ref value)).MainKey/*cast due to .constrained prefix*/).ToString() + ". Hotkey disabled."));
					return false;
				}
				IEnumerable<KeyCode> modifiers = ((KeyboardShortcut)(ref value)).Modifiers;
				if (modifiers == null)
				{
					_modifierKeyValues = Array.Empty<object>();
					return true;
				}
				List<object> list = new List<object>();
				foreach (KeyCode item in modifiers)
				{
					object obj = TryGetKeyValue(item);
					if (obj == null)
					{
						_log.LogWarning((object)("[Hotkey] Unsupported hotkey modifier: " + ((object)(*(KeyCode*)(&item))/*cast due to .constrained prefix*/).ToString() + ". Hotkey disabled."));
						return false;
					}
					list.Add(obj);
				}
				_modifierKeyValues = ((list.Count > 0) ? list.ToArray() : Array.Empty<object>());
				return true;
			}
			catch (Exception ex)
			{
				_log.LogDebug((object)("[Hotkey] Input System fallback initialization failed: " + ex.Message));
				return false;
			}
		}

		private static PropertyInfo FindKeyboardIndexer(Type keyboardType, Type keyEnumType)
		{
			if (keyboardType == null || keyEnumType == null)
			{
				return null;
			}
			PropertyInfo[] properties = keyboardType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
			foreach (PropertyInfo propertyInfo in properties)
			{
				if (!(propertyInfo.Name != "Item"))
				{
					ParameterInfo[] indexParameters = propertyInfo.GetIndexParameters();
					if (indexParameters.Length == 1 && indexParameters[0].ParameterType == keyEnumType)
					{
						return propertyInfo;
					}
				}
			}
			return null;
		}

		private bool WasPressedInputSystem()
		{
			try
			{
				object obj = _keyboardCurrentGetter();
				if (obj == null)
				{
					return false;
				}
				object obj2 = _keyboardIndexer(obj, _mainKeyValue);
				if (obj2 == null)
				{
					return false;
				}
				if (!_wasPressed(obj2))
				{
					return false;
				}
				for (int i = 0; i < _modifierKeyValues.Length; i++)
				{
					object obj3 = _keyboardIndexer(obj, _modifierKeyValues[i]);
					if (obj3 == null)
					{
						return false;
					}
					if (!_isPressed(obj3))
					{
						return false;
					}
				}
				return true;
			}
			catch
			{
				return false;
			}
		}

		private unsafe object TryGetKeyValue(KeyCode key)
		{
			//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)
			if ((int)key == 0)
			{
				return null;
			}
			string text = MapKeyCodeName(key);
			if (string.IsNullOrEmpty(text))
			{
				return null;
			}
			try
			{
				return Enum.Parse(_keyEnumType, text, ignoreCase: true);
			}
			catch
			{
				_log.LogWarning((object)("[Hotkey] Input System has no key named '" + text + "' (from " + ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString() + ")."));
				return null;
			}
		}

		private unsafe static string MapKeyCodeName(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Invalid comparison between Unknown and I4
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Invalid comparison between Unknown and I4
			//IL_003b: 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_00d0: Expected I4, but got Unknown
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Invalid comparison between Unknown and I4
			//IL_00fe: 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)
			//IL_020a: Expected I4, but got Unknown
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected I4, but got Unknown
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if ((int)key <= 19)
			{
				if ((int)key <= 9)
				{
					if ((int)key == 8)
					{
						return "Backspace";
					}
					if ((int)key == 9)
					{
						return "Tab";
					}
				}
				else
				{
					if ((int)key == 13)
					{
						return "Enter";
					}
					if ((int)key == 19)
					{
						return "Pause";
					}
				}
			}
			else if ((int)key <= 96)
			{
				switch (key - 27)
				{
				default:
					switch (key - 91)
					{
					case 5:
						return "Backquote";
					case 0:
						return "LeftBracket";
					case 2:
						return "RightBracket";
					case 1:
						return "Backslash";
					}
					break;
				case 21:
					return "Digit0";
				case 22:
					return "Digit1";
				case 23:
					return "Digit2";
				case 24:
					return "Digit3";
				case 25:
					return "Digit4";
				case 26:
					return "Digit5";
				case 27:
					return "Digit6";
				case 28:
					return "Digit7";
				case 29:
					return "Digit8";
				case 30:
					return "Digit9";
				case 0:
					return "Escape";
				case 5:
					return "Space";
				case 12:
					return "Quote";
				case 17:
					return "Comma";
				case 19:
					return "Period";
				case 20:
					return "Slash";
				case 32:
					return "Semicolon";
				case 18:
					return "Minus";
				case 34:
					return "Equals";
				case 1:
				case 2:
				case 3:
				case 4:
				case 6:
				case 7:
				case 8:
				case 9:
				case 10:
				case 11:
				case 13:
				case 14:
				case 15:
				case 16:
				case 31:
				case 33:
					break;
				}
			}
			else
			{
				if ((int)key == 127)
				{
					return "Delete";
				}
				switch (key - 256)
				{
				case 0:
					return "Numpad0";
				case 1:
					return "Numpad1";
				case 2:
					return "Numpad2";
				case 3:
					return "Numpad3";
				case 4:
					return "Numpad4";
				case 5:
					return "Numpad5";
				case 6:
					return "Numpad6";
				case 7:
					return "Numpad7";
				case 8:
					return "Numpad8";
				case 9:
					return "Numpad9";
				case 11:
					return "NumpadDivide";
				case 12:
					return "NumpadMultiply";
				case 13:
					return "NumpadMinus";
				case 14:
					return "NumpadPlus";
				case 10:
					return "NumpadPeriod";
				case 16:
					return "NumpadEquals";
				case 15:
					return "NumpadEnter";
				case 50:
					return "LeftCtrl";
				case 49:
					return "RightCtrl";
				case 48:
					return "LeftShift";
				case 47:
					return "RightShift";
				case 52:
					return "LeftAlt";
				case 51:
					return "RightAlt";
				case 57:
					return "RightAlt";
				case 54:
					return "LeftMeta";
				case 53:
					return "RightMeta";
				case 55:
					return "LeftMeta";
				case 56:
					return "RightMeta";
				case 21:
					return "Insert";
				case 22:
					return "Home";
				case 23:
					return "End";
				case 24:
					return "PageUp";
				case 25:
					return "PageDown";
				case 17:
					return "UpArrow";
				case 18:
					return "DownArrow";
				case 20:
					return "LeftArrow";
				case 19:
					return "RightArrow";
				case 45:
					return "CapsLock";
				case 44:
					return "NumLock";
				case 46:
					return "ScrollLock";
				case 60:
					return "PrintScreen";
				case 61:
					return "PrintScreen";
				case 62:
					return "Pause";
				case 63:
					return "ContextMenu";
				}
			}
			return ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString();
		}
	}
	public sealed class SceneObjectOptimizer : MonoBehaviour
	{
		private struct LightState
		{
			public Light Light;

			public LightShadows Shadows;

			public LightRenderMode RenderMode;
		}

		private struct ParticleState
		{
			public ParticleSystem System;

			public bool HasMaxParticles;

			public int MaxParticles;

			public bool HasCollision;

			public bool CollisionEnabled;

			public bool HasTrigger;

			public bool TriggerEnabled;
		}

		private struct CameraState
		{
			public Camera Camera;

			public bool AllowHdr;
		}

		private const int BatchSize = 64;

		private ManualLogSource _log;

		private OptimizerConfig _config;

		private Coroutine _scanCoroutine;

		private bool _running;

		private readonly HashSet<int> _processedLights = new HashSet<int>();

		private readonly HashSet<int> _processedParticles = new HashSet<int>();

		private readonly HashSet<int> _processedCameras = new HashSet<int>();

		private readonly Dictionary<int, LightState> _lightStates = new Dictionary<int, LightState>();

		private readonly Dictionary<int, ParticleState> _particleStates = new Dictionary<int, ParticleState>();

		private readonly Dictionary<int, CameraState> _cameraStates = new Dictionary<int, CameraState>();

		private string[] _flashlightHints = Array.Empty<string>();

		public int TotalLightsProcessed => _processedLights.Count;

		public int TotalParticlesProcessed => _processedParticles.Count;

		public int TotalLightsChanged => _lightStates.Count;

		public int TotalParticlesChanged => _particleStates.Count;

		public int LastNewLights { get; private set; }

		public int LastNewParticles { get; private set; }

		public int LastNewCameras { get; private set; }

		public bool IsRunning => _running;

		public int ScanGeneration { get; private set; }

		internal void Initialize(ManualLogSource log, OptimizerConfig config)
		{
			_log = log ?? throw new ArgumentNullException("log");
			_config = config ?? throw new ArgumentNullException("config");
			RefreshFlashlightHints();
			_log.LogInfo((object)"[Scene] SceneObjectOptimizer initialized.");
		}

		public void StartScanning(bool waitOneFrame)
		{
			if (((Behaviour)this).isActiveAndEnabled)
			{
				if (_scanCoroutine != null)
				{
					((MonoBehaviour)this).StopCoroutine(_scanCoroutine);
				}
				_running = true;
				_scanCoroutine = ((MonoBehaviour)this).StartCoroutine(ScanLoop(waitOneFrame));
			}
		}

		public void StopScanning()
		{
			_running = false;
			if (_scanCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(_scanCoroutine);
				_scanCoroutine = null;
			}
		}

		public void OnSceneLoaded()
		{
			RestoreAll();
			ClearCaches();
			if (_running)
			{
				StartScanning(waitOneFrame: true);
			}
		}

		private IEnumerator ScanLoop(bool waitOneFrame)
		{
			if (waitOneFrame)
			{
				yield return null;
			}
			while (_running)
			{
				yield return ScanOnce();
				ScanGeneration++;
				float num = Mathf.Max(0.5f, _config.ScanIntervalSeconds.Value);
				yield return (object)new WaitForSeconds(num);
			}
			_scanCoroutine = null;
		}

		private IEnumerator ScanOnce()
		{
			LastNewLights = 0;
			LastNewParticles = 0;
			LastNewCameras = 0;
			if (_config.EnableLightOptimization.Value)
			{
				yield return ScanLights();
			}
			if (_config.EnableParticleOptimization.Value)
			{
				yield return ScanParticles();
			}
			if (_config.DisableCameraHdr.Value)
			{
				yield return ScanCameras();
			}
			if (LastNewLights > 0 || LastNewParticles > 0 || LastNewCameras > 0)
			{
				_log.LogInfo((object)("[Scene] New objects processed: lights +" + LastNewLights + " (changed " + TotalLightsChanged + "/" + TotalLightsProcessed + "), particles +" + LastNewParticles + " (changed " + TotalParticlesChanged + "/" + TotalParticlesProcessed + "), cameras +" + LastNewCameras + "."));
			}
			else if (_config.VerboseLogging.Value)
			{
				_log.LogInfo((object)"[Scene] Scan complete: no new lights, particle systems or cameras.");
			}
		}

		private IEnumerator ScanLights()
		{
			RefreshFlashlightHints();
			Light[] lights;
			try
			{
				lights = FindAll<Light>();
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("[Scene] Light scan failed: " + ex.Message));
				yield break;
			}
			int processedInBatch = 0;
			foreach (Light val in lights)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				int instanceID;
				try
				{
					instanceID = ((Object)val).GetInstanceID();
				}
				catch
				{
					continue;
				}
				if (!_processedLights.Contains(instanceID))
				{
					_processedLights.Add(instanceID);
					try
					{
						OptimizeLight(val, instanceID);
						LastNewLights++;
					}
					catch (Exception ex2)
					{
						_log.LogWarning((object)("[Scene] Failed to optimize light '" + SafeName((Object)(object)val) + "': " + ex2.Message));
					}
					processedInBatch++;
					if (processedInBatch >= 64)
					{
						processedInBatch = 0;
						yield return null;
					}
				}
			}
		}

		private IEnumerator ScanParticles()
		{
			ParticleSystem[] systems;
			try
			{
				systems = FindAll<ParticleSystem>();
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("[Scene] Particle scan failed: " + ex.Message));
				yield break;
			}
			int processedInBatch = 0;
			foreach (ParticleSystem val in systems)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				int instanceID;
				try
				{
					instanceID = ((Object)val).GetInstanceID();
				}
				catch
				{
					continue;
				}
				if (!_processedParticles.Contains(instanceID))
				{
					_processedParticles.Add(instanceID);
					try
					{
						OptimizeParticles(val, instanceID);
						LastNewParticles++;
					}
					catch (Exception ex2)
					{
						_log.LogWarning((object)("[Scene] Failed to optimize ParticleSystem '" + SafeName((Object)(object)val) + "': " + ex2.Message));
					}
					processedInBatch++;
					if (processedInBatch >= 64)
					{
						processedInBatch = 0;
						yield return null;
					}
				}
			}
		}

		private IEnumerator ScanCameras()
		{
			Camera[] cameras;
			try
			{
				cameras = FindAll<Camera>();
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("[Scene] Camera scan failed: " + ex.Message));
				yield break;
			}
			int processedInBatch = 0;
			foreach (Camera val in cameras)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				int instanceID;
				try
				{
					instanceID = ((Object)val).GetInstanceID();
				}
				catch
				{
					continue;
				}
				if (_processedCameras.Contains(instanceID))
				{
					continue;
				}
				_processedCameras.Add(instanceID);
				try
				{
					if (OptimizeCamera(val, instanceID))
					{
						LastNewCameras++;
					}
				}
				catch (Exception ex2)
				{
					_log.LogWarning((object)("[Scene] Failed to optimize Camera '" + SafeName((Object)(object)val) + "': " + ex2.Message));
				}
				processedInBatch++;
				if (processedInBatch >= 64)
				{
					processedInBatch = 0;
					yield return null;
				}
			}
		}

		private bool OptimizeCamera(Camera camera, int id)
		{
			if (!camera.allowHDR)
			{
				return false;
			}
			if (!_cameraStates.ContainsKey(id))
			{
				_cameraStates.Add(id, new CameraState
				{
					Camera = camera,
					AllowHdr = true
				});
			}
			camera.allowHDR = false;
			return true;
		}

		private bool OptimizeLight(Light light, int id)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0041: 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_009f: Invalid comparison between Unknown and I4
			//IL_0083: 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_008a: 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)
			bool flag = false;
			LightState value = new LightState
			{
				Light = light,
				Shadows = light.shadows,
				RenderMode = light.renderMode
			};
			if (_config.DisableLightShadows.Value && (int)light.shadows != 0)
			{
				light.shadows = (LightShadows)0;
				flag = true;
			}
			if (_config.ForceVertexLighting.Value)
			{
				if (IsPlayerFlashlight(light))
				{
					LightRenderMode val = (LightRenderMode)(_config.FlashlightRenderMode.Value == FlashlightRenderModeOption.ForcePixel);
					if (light.renderMode != val)
					{
						light.renderMode = val;
						flag = true;
					}
				}
				else if ((int)light.renderMode != 2)
				{
					light.renderMode = (LightRenderMode)2;
					flag = true;
				}
			}
			if (flag && !_lightStates.ContainsKey(id))
			{
				_lightStates.Add(id, value);
			}
			return flag;
		}

		private bool OptimizeParticles(ParticleSystem system, int id)
		{
			//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_0069: 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_00a6: 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)
			bool flag = false;
			ParticleState value = new ParticleState
			{
				System = system
			};
			MainModule main = system.main;
			int maxParticles = ((MainModule)(ref main)).maxParticles;
			int value2 = _config.MaxParticles.Value;
			if (maxParticles > value2)
			{
				value.HasMaxParticles = true;
				value.MaxParticles = maxParticles;
				((MainModule)(ref main)).maxParticles = value2;
				flag = true;
			}
			if (_config.DisableParticleCollisions.Value)
			{
				CollisionModule collision = system.collision;
				if (((CollisionModule)(ref collision)).enabled)
				{
					value.HasCollision = true;
					value.CollisionEnabled = true;
					((CollisionModule)(ref collision)).enabled = false;
					flag = true;
				}
			}
			if (_config.DisableParticleTriggers.Value)
			{
				TriggerModule trigger = system.trigger;
				if (((TriggerModule)(ref trigger)).enabled)
				{
					value.HasTrigger = true;
					value.TriggerEnabled = true;
					((TriggerModule)(ref trigger)).enabled = false;
					flag = true;
				}
			}
			if (flag && !_particleStates.ContainsKey(id))
			{
				_particleStates.Add(id, value);
			}
			return flag;
		}

		public void RestoreAll()
		{
			//IL_0031: 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_00f8: 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_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyValuePair<int, LightState> lightState in _lightStates)
			{
				LightState value = lightState.Value;
				Light light = value.Light;
				if ((Object)(object)light == (Object)null)
				{
					continue;
				}
				try
				{
					light.shadows = value.Shadows;
					light.renderMode = value.RenderMode;
				}
				catch (Exception ex)
				{
					if (_log != null && _config != null && _config.VerboseLogging.Value)
					{
						_log.LogWarning((object)("[Scene] Failed to restore light: " + ex.Message));
					}
				}
			}
			_lightStates.Clear();
			foreach (KeyValuePair<int, ParticleState> particleState in _particleStates)
			{
				ParticleState value2 = particleState.Value;
				ParticleSystem system = value2.System;
				if ((Object)(object)system == (Object)null)
				{
					continue;
				}
				try
				{
					if (value2.HasMaxParticles)
					{
						MainModule main = system.main;
						((MainModule)(ref main)).maxParticles = value2.MaxParticles;
					}
					if (value2.HasCollision)
					{
						CollisionModule collision = system.collision;
						((CollisionModule)(ref collision)).enabled = value2.CollisionEnabled;
					}
					if (value2.HasTrigger)
					{
						TriggerModule trigger = system.trigger;
						((TriggerModule)(ref trigger)).enabled = value2.TriggerEnabled;
					}
				}
				catch (Exception ex2)
				{
					if (_log != null && _config != null && _config.VerboseLogging.Value)
					{
						_log.LogWarning((object)("[Scene] Failed to restore ParticleSystem: " + ex2.Message));
					}
				}
			}
			_particleStates.Clear();
			foreach (KeyValuePair<int, CameraState> cameraState in _cameraStates)
			{
				CameraState value3 = cameraState.Value;
				Camera camera = value3.Camera;
				if ((Object)(object)camera == (Object)null)
				{
					continue;
				}
				try
				{
					camera.allowHDR = value3.AllowHdr;
				}
				catch (Exception ex3)
				{
					if (_log != null && _config != null && _config.VerboseLogging.Value)
					{
						_log.LogWarning((object)("[Scene] Failed to restore Camera: " + ex3.Message));
					}
				}
			}
			_cameraStates.Clear();
			_processedLights.Clear();
			_processedParticles.Clear();
			_processedCameras.Clear();
		}

		private void ClearCaches()
		{
			_processedLights.Clear();
			_processedParticles.Clear();
			_processedCameras.Clear();
			_lightStates.Clear();
			_particleStates.Clear();
			_cameraStates.Clear();
		}

		private bool IsPlayerFlashlight(Light light)
		{
			if (!_config.PreservePlayerFlashlight.Value)
			{
				return false;
			}
			try
			{
				if ((Object)(object)((Component)light).GetComponentInParent<Camera>() != (Object)null)
				{
					return true;
				}
				if (_flashlightHints.Length == 0)
				{
					return false;
				}
				Transform val = ((Component)light).transform;
				int num = 0;
				while ((Object)(object)val != (Object)null && num < 16)
				{
					string name = ((Object)val).name;
					if (!string.IsNullOrEmpty(name))
					{
						for (int i = 0; i < _flashlightHints.Length; i++)
						{
							if (name.IndexOf(_flashlightHints[i], StringComparison.OrdinalIgnoreCase) >= 0)
							{
								return true;
							}
						}
					}
					val = val.parent;
					num++;
				}
			}
			catch (Exception ex)
			{
				if (_config.VerboseLogging.Value)
				{
					_log.LogWarning((object)("[Scene] Flashlight detection failed: " + ex.Message));
				}
			}
			return false;
		}

		private void RefreshFlashlightHints()
		{
			string value = _config.FlashlightNameHints.Value;
			if (string.IsNullOrEmpty(value))
			{
				_flashlightHints = Array.Empty<string>();
				return;
			}
			string[] array = value.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
			List<string> list = new List<string>(array.Length);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length > 0)
				{
					list.Add(text);
				}
			}
			_flashlightHints = ((list.Count > 0) ? list.ToArray() : Array.Empty<string>());
		}

		private static T[] FindAll<T>() where T : Object
		{
			try
			{
				return Object.FindObjectsByType<T>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			}
			catch (Exception)
			{
				return Object.FindObjectsOfType<T>(true);
			}
		}

		private static string SafeName(Object obj)
		{
			try
			{
				return (obj != (Object)null) ? obj.name : "<destroyed>";
			}
			catch
			{
				return "<unknown>";
			}
		}

		private void OnDisable()
		{
			StopScanning();
		}

		private void OnDestroy()
		{
			StopScanning();
		}
	}
}