Decompiled source of TheComplexOptimizer v1.2.0

BepInEx/plugins/TheComplexOptimizer.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;

[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("TheComplexOptimizer")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("TheComplexOptimizer")]
[assembly: AssemblyTitle("TheComplexOptimizer")]
[assembly: AssemblyVersion("1.0.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 TheComplexOptimizer
{
	[BepInPlugin("thecomplex.fps.optimizer", "The Complex FPS Optimizer", "1.2.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private struct CachedLight
		{
			public HDAdditionalLightData Hd;

			public Transform Tr;

			public int Cost;
		}

		internal static ManualLogSource Log;

		internal static ConfigEntry<int> CfgShadowBudget;

		internal static ConfigEntry<int> CfgShadowResolution;

		internal static ConfigEntry<float> CfgShadowFadeDist;

		internal static ConfigEntry<float> CfgLightFadeDist;

		internal static ConfigEntry<bool> CfgEnableInstancing;

		internal static ConfigEntry<bool> CfgDisableVolumetrics;

		internal static ConfigEntry<bool> CfgDisablePointShadows;

		private void Awake()
		{
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Expected O, but got Unknown
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			CfgShadowBudget = ((BaseUnityPlugin)this).Config.Bind<int>("Shadows", "Budget", 5, "Maximum simultaneous shadow-casting lights (original: 12). Cost: Spot = 1, Area = 2, Point = 3.");
			CfgShadowResolution = ((BaseUnityPlugin)this).Config.Bind<int>("Shadows", "Resolution", 256, "Shadow map resolution in pixels (original: 1024). Lower values significantly improve GPU performance.");
			CfgShadowFadeDist = ((BaseUnityPlugin)this).Config.Bind<float>("Shadows", "FadeDistance", 25f, "Distance in meters at which real-time shadows fade out (original: 60).");
			CfgDisablePointShadows = ((BaseUnityPlugin)this).Config.Bind<bool>("Shadows", "DisablePointShadows", true, "Disables real-time shadows on Point Lights (each renders 6 shadow maps in HDRP) while keeping overhead Spot Light shadows.");
			CfgLightFadeDist = ((BaseUnityPlugin)this).Config.Bind<float>("Lights", "FadeDistance", 35f, "Native HDRP fade distance in meters for interior lights (does not affect breaker boxes, switches, or flickering).");
			CfgDisableVolumetrics = ((BaseUnityPlugin)this).Config.Bind<bool>("Lights", "DisableVolumetrics", true, "Disables volumetric fog calculations on interior lights for a free GPU performance boost.");
			CfgEnableInstancing = ((BaseUnityPlugin)this).Config.Bind<bool>("Rendering", "EnableGPUInstancing", true, "Enables GPU Instancing on all materials generated by The Complex to reduce draw calls.");
			Harmony val = new Harmony("thecomplex.fps.optimizer");
			Type type = AccessTools.TypeByName("BackroomsLevel0.ShadowBudget");
			MethodInfo methodInfo = ((type != null) ? AccessTools.Method(type, "Run", (Type[])null, (Type[])null) : null);
			if (methodInfo != null)
			{
				val.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Plugin), "ShadowRunPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)"Replaced ShadowBudget.Run with optimized version (v1.2.1).");
			}
			else
			{
				Log.LogWarning((object)"Could not find BackroomsLevel0.ShadowBudget.Run!");
			}
			Type type2 = AccessTools.TypeByName("BackroomsLevel0.MaterialLibrary");
			MethodInfo methodInfo2 = ((type2 != null) ? AccessTools.Method(type2, "BuildAll", (Type[])null, (Type[])null) : null);
			if (methodInfo2 != null)
			{
				val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "BuildAllPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)"Hooked GPU Instancing into MaterialLibrary.BuildAll.");
			}
		}

		private static void BuildAllPostfix()
		{
			if (!CfgEnableInstancing.Value)
			{
				return;
			}
			try
			{
				if (!(AccessTools.Field(AccessTools.TypeByName("BackroomsLevel0.MaterialLibrary"), "built")?.GetValue(null) is Dictionary<string, Material> dictionary))
				{
					return;
				}
				int num = 0;
				foreach (Material value in dictionary.Values)
				{
					if ((Object)(object)value != (Object)null && !value.enableInstancing)
					{
						value.enableInstancing = true;
						num++;
					}
				}
				Log.LogInfo((object)$"Enabled GPU Instancing on {num} materials in The Complex.");
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Error in BuildAllPostfix: " + ex.Message));
			}
		}

		private static bool ShadowRunPrefix(Dungeon d, ref IEnumerator __result)
		{
			__result = OptimizedShadowRun(d);
			return false;
		}

		private static IEnumerator OptimizedShadowRun(Dungeon d)
		{
			yield return (object)new WaitForSeconds(2f);
			if ((Object)(object)d == (Object)null)
			{
				yield break;
			}
			int budget = Mathf.Max(0, CfgShadowBudget.Value);
			int num = Mathf.Clamp(CfgShadowResolution.Value, 128, 2048);
			float shadowFade = Mathf.Max(8f, CfgShadowFadeDist.Value);
			float num2 = Mathf.Max(15f, CfgLightFadeDist.Value);
			bool value = CfgDisableVolumetrics.Value;
			bool value2 = CfgDisablePointShadows.Value;
			HDAdditionalLightData[] componentsInChildren = ((Component)d).GetComponentsInChildren<HDAdditionalLightData>(true);
			List<CachedLight> shadowLights = new List<CachedLight>(componentsInChildren.Length);
			HDAdditionalLightData[] array = componentsInChildren;
			foreach (HDAdditionalLightData val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Light component = ((Component)val).GetComponent<Light>();
				if ((Object)(object)component == (Object)null || (int)component.type == 1)
				{
					continue;
				}
				try
				{
					val.fadeDistance = ((val.fadeDistance > 0.1f) ? Mathf.Min(val.fadeDistance, num2) : num2);
					if (value)
					{
						val.affectsVolumetric = false;
						val.volumetricDimmer = 0f;
					}
				}
				catch
				{
				}
				if ((int)component.shadows == 0)
				{
					continue;
				}
				if (value2 && (int)component.type == 2)
				{
					val.EnableShadows(false);
					continue;
				}
				int num3 = (((int)component.type == 2) ? 3 : (((int)component.type != 3 && (int)component.type != 4) ? 1 : 2));
				try
				{
					val.SetShadowResolutionOverride(true);
					val.SetShadowResolution((num3 == 3) ? Mathf.Max(128, num / 2) : num);
					val.shadowFadeDistance = shadowFade;
					val.shadowUpdateMode = (ShadowUpdateMode)0;
					if (num3 == 3)
					{
						val.shadowNearPlane = Mathf.Max(val.shadowNearPlane, 0.12f);
					}
				}
				catch
				{
				}
				val.EnableShadows(false);
				shadowLights.Add(new CachedLight
				{
					Hd = val,
					Tr = ((Component)val).transform,
					Cost = num3
				});
			}
			Renderer[] componentsInChildren2 = ((Component)d).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val2 in componentsInChildren2)
			{
				if ((Object)(object)val2 != (Object)null && (Object)(object)val2.sharedMaterial != (Object)null)
				{
					string name = ((Object)val2.sharedMaterial).name;
					if (name.Contains("pr_daylight") || name.Contains("redglow"))
					{
						val2.shadowCastingMode = (ShadowCastingMode)0;
					}
				}
			}
			Log.LogInfo((object)$"[Optimizer v1.2.1] Optimized {componentsInChildren.Length} lights ({shadowLights.Count} shadow-casting, budget={budget}, res={num}px, noVol={value}, noPointShad={value2}).");
			if (budget <= 0 || shadowLights.Count == 0)
			{
				yield break;
			}
			HashSet<HDAdditionalLightData> on = new HashSet<HDAdditionalLightData>();
			HashSet<HDAdditionalLightData> want = new HashSet<HDAdditionalLightData>();
			List<HDAdditionalLightData> toRemove = new List<HDAdditionalLightData>();
			float[] dist = new float[shadowLights.Count];
			int[] order = new int[shadowLights.Count];
			WaitForSeconds wait = new WaitForSeconds(0.25f);
			while ((Object)(object)d != (Object)null)
			{
				PlayerControllerB val3 = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
				Camera val4 = (((Object)(object)val3 != (Object)null && (Object)(object)val3.gameplayCamera != (Object)null) ? val3.gameplayCamera : (((Object)(object)StartOfRound.Instance != (Object)null && (Object)(object)StartOfRound.Instance.activeCamera != (Object)null) ? StartOfRound.Instance.activeCamera : Camera.main));
				if ((Object)(object)val4 != (Object)null)
				{
					Vector3 position = ((Component)val4).transform.position;
					float num4 = shadowFade * shadowFade;
					for (int j = 0; j < shadowLights.Count; j++)
					{
						order[j] = j;
						CachedLight cachedLight = shadowLights[j];
						if ((Object)(object)cachedLight.Hd == (Object)null || !((Behaviour)cachedLight.Hd).isActiveAndEnabled)
						{
							dist[j] = float.MaxValue;
							continue;
						}
						Vector3 val5 = cachedLight.Tr.position - position;
						float num5 = ((Vector3)(ref val5)).sqrMagnitude;
						if (num5 > num4)
						{
							dist[j] = float.MaxValue;
							continue;
						}
						if (Mathf.Abs(val5.y) > 3.5f)
						{
							num5 *= 9f;
						}
						dist[j] = num5;
					}
					Array.Sort(dist, order);
					want.Clear();
					int num6 = 0;
					for (int k = 0; k < shadowLights.Count; k++)
					{
						if (num6 >= budget)
						{
							break;
						}
						if (dist[k] == float.MaxValue)
						{
							break;
						}
						CachedLight cachedLight2 = shadowLights[order[k]];
						if (num6 + cachedLight2.Cost <= budget)
						{
							want.Add(cachedLight2.Hd);
							num6 += cachedLight2.Cost;
						}
					}
					toRemove.Clear();
					foreach (HDAdditionalLightData item in on)
					{
						if ((Object)(object)item == (Object)null || !want.Contains(item))
						{
							if ((Object)(object)item != (Object)null)
							{
								item.EnableShadows(false);
							}
							toRemove.Add(item);
						}
					}
					for (int l = 0; l < toRemove.Count; l++)
					{
						on.Remove(toRemove[l]);
					}
					foreach (HDAdditionalLightData item2 in want)
					{
						if (on.Add(item2))
						{
							try
							{
								item2.shadowDimmer = 1f;
							}
							catch
							{
							}
							item2.EnableShadows(true);
						}
					}
				}
				yield return wait;
			}
		}
	}
}