Decompiled source of OptiHouse v1.4.0

OptiHouse.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using OptiHouse.Configuration;
using OptiHouse.Modules;
using OptiHouse.UI;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Rendering;

[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("OptiHouse")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.0+da60fa80d4c903848850d553798e1a6a71824902")]
[assembly: AssemblyProduct("OptiHouse")]
[assembly: AssemblyTitle("OptiHouse")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/UncleBugDev/OptiHouse")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 OptiHouse
{
	[BepInPlugin("com.unclebug.optihouse", "OptiHouse", "1.4.0")]
	public class OptiHousePlugin : BaseUnityPlugin
	{
		public const string ModGUID = "com.unclebug.optihouse";

		public const string ModName = "OptiHouse";

		public const string ModVersion = "1.4.0";

		private Harmony _harmony;

		public static OptiHousePlugin Instance { get; private set; }

		public static ManualLogSource Log => ((BaseUnityPlugin)Instance).Logger;

		public static bool IsOptimizationActive
		{
			get
			{
				if (ModConfig.MasterOptimizationEnabled != null)
				{
					return ModConfig.MasterOptimizationEnabled.Value;
				}
				return false;
			}
		}

		private void Awake()
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			Instance = this;
			ModConfig.Init(((BaseUnityPlugin)this).Config);
			BootConfigTweaker.Initialize();
			((Component)this).gameObject.AddComponent<OptiHouseHUD>();
			((Component)this).gameObject.AddComponent<InteriorOcclusionOptimizer>();
			((Component)this).gameObject.AddComponent<DecorativeColliderOptimizer>();
			((Component)this).gameObject.AddComponent<DetailPieceLOD>();
			((Component)this).gameObject.AddComponent<ItemDropOptimizer>();
			((Component)this).gameObject.AddComponent<TerrainOptimizationHelper>();
			_harmony = new Harmony("com.unclebug.optihouse");
			_harmony.PatchAll();
			Log.LogInfo((object)"[OptiHouse] v1.4.0 initialized successfully. Special thanks to DaymonMontage (https://twitch.tv/daymonmontage)!");
		}

		private void Update()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: 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)
			if (ModConfig.ToggleHotkey != null && (int)ModConfig.ToggleHotkey.Value != 0 && Input.GetKeyDown(ModConfig.ToggleHotkey.Value))
			{
				bool num = Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303);
				bool flag = ModConfig.BenchmarkHudHotkey != null && ModConfig.BenchmarkHudHotkey.Value == ModConfig.ToggleHotkey.Value && ModConfig.BenchmarkHudRequireShift != null && ModConfig.BenchmarkHudRequireShift.Value;
				if (!num || !flag)
				{
					ToggleOptimizations();
				}
			}
		}

		public void ToggleOptimizations()
		{
			bool flag = !ModConfig.MasterOptimizationEnabled.Value;
			ModConfig.MasterOptimizationEnabled.Value = flag;
			string text = (flag ? "<color=#00FF66><b>OPTIMIZATIONS ENABLED</b></color>" : "<color=#FF4444><b>OPTIMIZATIONS DISABLED</b></color>");
			if (ModConfig.ShowNotificationOnToggle.Value && (Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowMessage((MessageType)2, "OptiHouse: " + text, 0, (Sprite)null, false, true);
			}
			if (ModConfig.EnableLogging.Value)
			{
				Log.LogInfo((object)("[OptiHouse] Optimizations runtime toggle: " + (flag ? "ENABLED" : "DISABLED")));
			}
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
}
namespace OptiHouse.UI
{
	public class OptiHouseHUD : MonoBehaviour
	{
		private const int FrameBufferSize = 180;

		private readonly float[] _frameTimeBuffer = new float[180];

		private readonly float[] _sortedBuffer = new float[180];

		private int _frameBufferIndex;

		private int _frameBufferCount;

		private float _metricTimer;

		private float _liveFps;

		private float _avgFps;

		private float _onePercentLowFps;

		private float _avgFrameTimeMs;

		private int _totalBasePieces;

		private int _activeShadowLights;

		private int _culledShadowLights;

		private int _totalShadowLights;

		private int _smokePuffs;

		private int _smokeCap = 25;

		private int _clothCulled;

		private int _clothTotal;

		private int _standsCulled;

		private int _standsTotal;

		private int _tamedLod;

		private int _tamedTotal;

		private int _stationsCulled;

		private int _stationsTotal;

		private int _interiorCulled;

		private int _interiorTotal;

		private int _collidersCulled;

		private int _collidersTotal;

		private int _detailCulled;

		private int _detailTotal;

		private int _droppedTotal;

		private int _droppedMerged;

		private int _droppedSleeping;

		private bool _gfxJobsActive;

		private Texture2D? _bgTexture;

		private Texture2D? _borderTexture;

		private Texture2D? _headerTexture;

		private GUIStyle? _labelStyle;

		private GUIStyle? _titleStyle;

		private GUIStyle? _subTitleStyle;

		private GUIStyle? _dimStyle;

		private int _lastFontSize = -1;

		private static readonly FieldInfo? _pieceListField = typeof(Piece).GetField("s_allPieces", BindingFlags.Static | BindingFlags.NonPublic);

		public static OptiHouseHUD? Instance { get; private set; }

		public static bool IsVisible { get; set; } = false;

		private void Awake()
		{
			Instance = this;
			InitTextures();
		}

		private void OnDestroy()
		{
			if ((Object)(object)_bgTexture != (Object)null)
			{
				Object.Destroy((Object)(object)_bgTexture);
			}
			if ((Object)(object)_borderTexture != (Object)null)
			{
				Object.Destroy((Object)(object)_borderTexture);
			}
			if ((Object)(object)_headerTexture != (Object)null)
			{
				Object.Destroy((Object)(object)_headerTexture);
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private void InitTextures()
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_0029: 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_004b: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			_bgTexture = new Texture2D(1, 1);
			_bgTexture.SetPixel(0, 0, new Color(0.06f, 0.08f, 0.11f, 0.88f));
			_bgTexture.Apply();
			_borderTexture = new Texture2D(1, 1);
			_borderTexture.SetPixel(0, 0, new Color(0.22f, 0.32f, 0.44f, 0.95f));
			_borderTexture.Apply();
			_headerTexture = new Texture2D(1, 1);
			_headerTexture.SetPixel(0, 0, new Color(0.11f, 0.15f, 0.22f, 0.95f));
			_headerTexture.Apply();
		}

		private void Update()
		{
			CheckToggleHotkey();
			float num = Mathf.Max(1E-05f, Time.unscaledDeltaTime);
			_frameTimeBuffer[_frameBufferIndex] = num;
			_frameBufferIndex = (_frameBufferIndex + 1) % 180;
			if (_frameBufferCount < 180)
			{
				_frameBufferCount++;
			}
			if (IsVisible)
			{
				_metricTimer += num;
				if (_metricTimer >= 0.25f)
				{
					_metricTimer = 0f;
					CalculateFramerateMetrics();
					CollectModuleMetrics();
				}
			}
		}

		private void CheckToggleHotkey()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (ModConfig.EnableBenchmarkHUD == null || !ModConfig.EnableBenchmarkHUD.Value)
			{
				if (IsVisible)
				{
					IsVisible = false;
				}
			}
			else if (ModConfig.BenchmarkHudHotkey != null && (int)ModConfig.BenchmarkHudHotkey.Value != 0 && Input.GetKeyDown(ModConfig.BenchmarkHudHotkey.Value))
			{
				bool num = ModConfig.BenchmarkHudRequireShift != null && ModConfig.BenchmarkHudRequireShift.Value;
				bool flag = Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303);
				if (!num || flag)
				{
					IsVisible = !IsVisible;
				}
			}
		}

		private void CalculateFramerateMetrics()
		{
			if (_frameBufferCount != 0)
			{
				int num = Mathf.Min(5, _frameBufferCount);
				float num2 = 0f;
				for (int i = 0; i < num; i++)
				{
					int num3 = (_frameBufferIndex - 1 - i + 180) % 180;
					num2 += _frameTimeBuffer[num3];
				}
				_liveFps = (float)num / Mathf.Max(0.0001f, num2);
				float num4 = 0f;
				for (int j = 0; j < _frameBufferCount; j++)
				{
					num4 += _frameTimeBuffer[j];
					_sortedBuffer[j] = _frameTimeBuffer[j];
				}
				_avgFps = (float)_frameBufferCount / Mathf.Max(0.0001f, num4);
				_avgFrameTimeMs = num4 / (float)_frameBufferCount * 1000f;
				Array.Sort(_sortedBuffer, 0, _frameBufferCount);
				int num5 = Mathf.Clamp((int)((float)_frameBufferCount * 0.99f), 0, _frameBufferCount - 1);
				float num6 = _sortedBuffer[num5];
				_onePercentLowFps = 1f / Mathf.Max(0.0001f, num6);
			}
		}

		private void CollectModuleMetrics()
		{
			_totalBasePieces = GetTotalBasePieces();
			_activeShadowLights = LightShadowOptimizer.ActiveShadowLights;
			_culledShadowLights = LightShadowOptimizer.CulledShadowLights;
			_totalShadowLights = LightShadowOptimizer.TotalLights;
			try
			{
				_smokePuffs = Smoke.GetTotalSmoke();
				_smokeCap = SmokeOptimizer.GetConfiguredSmokeCap();
			}
			catch
			{
				_smokePuffs = 0;
			}
			try
			{
				_clothCulled = ClothOptimizer.CulledClothCount;
				_clothTotal = ClothOptimizer.TotalClothCount;
			}
			catch
			{
				_clothCulled = 0;
				_clothTotal = 0;
			}
			try
			{
				_standsCulled = ItemStandOptimizer.CulledStandCount;
				_standsTotal = ItemStandOptimizer.TotalStandCount;
			}
			catch
			{
				_standsCulled = 0;
				_standsTotal = 0;
			}
			CollectTamedAnimalMetrics();
			CollectCraftingStationMetrics();
			try
			{
				_interiorCulled = InteriorOcclusionOptimizer.CulledInteriorPieces;
				_interiorTotal = InteriorOcclusionOptimizer.TotalInteriorPieces;
			}
			catch
			{
				_interiorCulled = 0;
				_interiorTotal = 0;
			}
			try
			{
				_collidersCulled = DecorativeColliderOptimizer.CulledColliderCount;
				_collidersTotal = DecorativeColliderOptimizer.TotalDecorativePieces;
			}
			catch
			{
				_collidersCulled = 0;
				_collidersTotal = 0;
			}
			try
			{
				_detailCulled = DetailPieceLOD.CulledDetailPieces;
				_detailTotal = DetailPieceLOD.TotalDetailPieces;
			}
			catch
			{
				_detailCulled = 0;
				_detailTotal = 0;
			}
			try
			{
				_droppedTotal = ItemDropOptimizer.TotalDroppedItems;
				_droppedMerged = ItemDropOptimizer.MergedDropsCount;
				_droppedSleeping = ItemDropOptimizer.SleepingItemsCount;
			}
			catch
			{
				_droppedTotal = 0;
				_droppedMerged = 0;
				_droppedSleeping = 0;
			}
			try
			{
				_gfxJobsActive = BootConfigTweaker.IsGfxJobsActive;
			}
			catch
			{
				_gfxJobsActive = false;
			}
		}

		private static int GetTotalBasePieces()
		{
			try
			{
				if (_pieceListField?.GetValue(null) is List<Piece> list)
				{
					return list.Count;
				}
			}
			catch
			{
			}
			return PieceShadowCuller.TrackedPieceCount;
		}

		private void CollectTamedAnimalMetrics()
		{
			try
			{
				_tamedTotal = TamedAnimalOptimizer.TotalTamedAnimals;
				_tamedLod = TamedAnimalOptimizer.CulledTamedAnimals;
			}
			catch
			{
				_tamedTotal = 0;
				_tamedLod = 0;
			}
		}

		private void CollectCraftingStationMetrics()
		{
			try
			{
				_stationsTotal = CraftingStationOptimizer.TotalStations;
				_stationsCulled = CraftingStationOptimizer.CulledStations;
			}
			catch
			{
				_stationsTotal = 0;
				_stationsCulled = 0;
			}
		}

		private void OnGUI()
		{
			//IL_00c9: 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_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			if (IsVisible)
			{
				int fontSize = ((ModConfig.HudTextSize != null) ? ModConfig.HudTextSize.Value : 13);
				UpdateStyles(fontSize);
				float num = 380f;
				float num2 = 545f;
				float num3 = 16f;
				HudAnchorPosition hudAnchorPosition = ((ModConfig.HudPosition != null) ? ModConfig.HudPosition.Value : HudAnchorPosition.TopLeft);
				float num4 = num3;
				float num5 = num3;
				switch (hudAnchorPosition)
				{
				case HudAnchorPosition.TopRight:
					num4 = (float)Screen.width - num - num3;
					num5 = num3;
					break;
				case HudAnchorPosition.BottomLeft:
					num4 = num3;
					num5 = (float)Screen.height - num2 - num3;
					break;
				case HudAnchorPosition.BottomRight:
					num4 = (float)Screen.width - num - num3;
					num5 = (float)Screen.height - num2 - num3;
					break;
				default:
					num4 = num3;
					num5 = num3;
					break;
				}
				Rect val = default(Rect);
				((Rect)(ref val))..ctor(num4, num5, num, num2);
				if ((Object)(object)_borderTexture != (Object)null)
				{
					GUI.DrawTexture(val, (Texture)(object)_borderTexture);
				}
				if ((Object)(object)_bgTexture != (Object)null)
				{
					GUI.DrawTexture(new Rect(((Rect)(ref val)).x + 1f, ((Rect)(ref val)).y + 1f, ((Rect)(ref val)).width - 2f, ((Rect)(ref val)).height - 2f), (Texture)(object)_bgTexture);
				}
				Rect val2 = default(Rect);
				((Rect)(ref val2))..ctor(((Rect)(ref val)).x + 1f, ((Rect)(ref val)).y + 1f, ((Rect)(ref val)).width - 2f, 32f);
				if ((Object)(object)_headerTexture != (Object)null)
				{
					GUI.DrawTexture(val2, (Texture)(object)_headerTexture);
				}
				GUILayout.BeginArea(new Rect(((Rect)(ref val)).x + 12f, ((Rect)(ref val)).y + 7f, ((Rect)(ref val)).width - 24f, ((Rect)(ref val)).height - 14f));
				string obj = (OptiHousePlugin.IsOptimizationActive ? "<color=#00FF66><b>[OptiHouse: ACTIVE]</b></color>" : "<color=#FF4444><b>[OptiHouse: DISABLED]</b></color>");
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				GUILayout.Label("<color=#55CCFF><b>⚡ OptiHouse v1.4.0</b></color>", _titleStyle, Array.Empty<GUILayoutOption>());
				GUILayout.FlexibleSpace();
				GUILayout.Label(obj, _subTitleStyle, Array.Empty<GUILayoutOption>());
				GUILayout.EndHorizontal();
				GUILayout.Space(6f);
				string text = ((_onePercentLowFps >= 45f) ? "#00FF66" : ((_onePercentLowFps >= 30f) ? "#FFFF55" : "#FF5555"));
				string text2 = ((_liveFps >= 55f) ? "#00FF66" : ((_liveFps >= 35f) ? "#FFFF55" : "#FF5555"));
				GUILayout.Label($"<b>FPS:</b> <color={text2}>{_liveFps:F1}</color>  |  <b>Avg:</b> {_avgFps:F1}  |  <b>1% Low:</b> <color={text}>{_onePercentLowFps:F1}</color>", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"<b>Frametime:</b> {_avgFrameTimeMs:F1} ms", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label("<color=#2F4156>────────────────────────────────────────────</color>", _dimStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83c\udfdb\ufe0f  Base Pieces: <b>{_totalBasePieces:N0}</b>", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83d\udca1  Shadow Lights: <color=#00FF66><b>{_activeShadowLights}</b> active</color> / <color=#FFAA44><b>{_culledShadowLights}</b> culled</color> ({_totalShadowLights} total)", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83d\udca8  Smoke Puffs: <b>{_smokePuffs}</b> active / {_smokeCap} cap", _labelStyle, Array.Empty<GUILayoutOption>());
				string text3 = ((ModConfig.EnableFastParticleFade != null && ModConfig.EnableFastParticleFade.Value) ? "<color=#00FF66>Active (~3x faster fade)</color>" : "<color=#FFAA44>Vanilla</color>");
				GUILayout.Label("✨  Particle Fade: " + text3, _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83d\udea9  Banner Cloths: <color=#00FF66><b>{_clothCulled}</b> culled</color> / {_clothTotal} total", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83d\udce6  Item & Trophy Stands: <color=#00FF66><b>{_standsCulled}</b> culled</color> / {_standsTotal} total", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83d\udc17  Tamed Animals: <color=#00FF66><b>{_tamedLod}</b> in LOD</color> / {_tamedTotal} total", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83d\udd28  Crafting Stations: <color=#00FF66><b>{_stationsCulled}</b> culled</color> / {_stationsTotal} total", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83d\udeaa  Interior Culling: <color=#00FF66><b>{_interiorCulled}</b> culled</color> / {_interiorTotal} total", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83d\udee1\ufe0f  Decor Colliders: <color=#00FF66><b>{_collidersCulled}</b> disabled</color> / {_collidersTotal} total", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83d\udcd0  Detail Pieces LOD: <color=#00FF66><b>{_detailCulled}</b> culled</color> / {_detailTotal} total", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label($"\ud83d\udc8e  Ground Loot Clutter: <b>{_droppedTotal}</b> (<color=#00FF66><b>{_droppedSleeping}</b> sleep</color>, <color=#55CCFF><b>{_droppedMerged}</b> merged</color>)", _labelStyle, Array.Empty<GUILayoutOption>());
				string text4 = (_gfxJobsActive ? "<color=#00FF66>Active (Multi-Threaded)</color>" : (BootConfigTweaker.RestartRequired ? "<color=#FFFF55>Pending Restart</color>" : "<color=#FFAA44>Inactive</color>"));
				GUILayout.Label("⚡  Gfx Jobs: " + text4, _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label("<color=#2F4156>────────────────────────────────────────────</color>", _dimStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label("<size=10><color=#7E94A8><b>[Shift+F7]</b> Toggle HUD  |  <b>[F7]</b> Toggle Optimizations</color></size>", _dimStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label("<size=9><color=#FFAA44>Special thanks to <b>DaymonMontage</b> (twitch.tv/daymonmontage)</color></size>", _dimStyle, Array.Empty<GUILayoutOption>());
				GUILayout.EndArea();
			}
		}

		private void UpdateStyles(int fontSize)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: 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_0104: Expected O, but got Unknown
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			if (_labelStyle == null || _lastFontSize != fontSize)
			{
				_lastFontSize = fontSize;
				_labelStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = fontSize,
					richText = true,
					wordWrap = false
				};
				_labelStyle.normal.textColor = Color.white;
				_titleStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = fontSize + 1,
					richText = true,
					wordWrap = false
				};
				_titleStyle.normal.textColor = Color.white;
				_subTitleStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = fontSize,
					richText = true,
					wordWrap = false
				};
				_subTitleStyle.normal.textColor = Color.white;
				_dimStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = fontSize - 1,
					richText = true,
					wordWrap = false
				};
				_dimStyle.normal.textColor = new Color(0.6f, 0.7f, 0.8f, 1f);
			}
		}
	}
}
namespace OptiHouse.Modules
{
	public static class BootConfigTweaker
	{
		private static bool _initialized;

		public static bool IsGfxJobsActive { get; internal set; }

		public static bool RestartRequired { get; internal set; }

		public static bool BackupCreated { get; internal set; }

		public static string? BootConfigPath { get; private set; }

		public static void Initialize()
		{
			ApplyBootConfigTweaks();
		}

		public static void ApplyBootConfigTweaks()
		{
			if (_initialized)
			{
				return;
			}
			_initialized = true;
			try
			{
				string text = FindBootConfigPath();
				if (string.IsNullOrEmpty(text) || !File.Exists(text))
				{
					ManualLogSource log = OptiHousePlugin.Log;
					if (log != null)
					{
						log.LogWarning((object)("[BootConfigTweaker] boot.config could not be located via Application.dataPath (" + Application.dataPath + "). Engine tweak skipped."));
					}
					return;
				}
				BootConfigPath = text;
				string[] array = File.ReadAllLines(text);
				bool flag = array.Any((string l) => l.Trim().Equals("gfx-enable-gfx-jobs=1", StringComparison.OrdinalIgnoreCase));
				bool flag2 = array.Any((string l) => l.Trim().Equals("gfx-enable-native-gfx-jobs=1", StringComparison.OrdinalIgnoreCase));
				if (flag && flag2)
				{
					IsGfxJobsActive = true;
					RestartRequired = false;
					ManualLogSource log2 = OptiHousePlugin.Log;
					if (log2 != null)
					{
						log2.LogInfo((object)"[BootConfigTweaker] Multi-threaded Gfx Jobs (gfx-enable-gfx-jobs=1, gfx-enable-native-gfx-jobs=1) are already configured and active.");
					}
					return;
				}
				if (flag)
				{
					IsGfxJobsActive = true;
				}
				if (ModConfig.EnableGfxJobsTweak == null || !ModConfig.EnableGfxJobsTweak.Value)
				{
					ManualLogSource log3 = OptiHousePlugin.Log;
					if (log3 != null)
					{
						log3.LogInfo((object)"[BootConfigTweaker] EnableGfxJobsTweak is false in ModConfig. Skipping injection.");
					}
					return;
				}
				string text2 = text + ".bak";
				if (!File.Exists(text2))
				{
					File.Copy(text, text2, overwrite: false);
					BackupCreated = true;
					ManualLogSource log4 = OptiHousePlugin.Log;
					if (log4 != null)
					{
						log4.LogInfo((object)("[BootConfigTweaker] Created engine config backup at: " + text2));
					}
				}
				List<string> list = new List<string> { "gfx-enable-gfx-jobs=1", "gfx-enable-native-gfx-jobs=1" };
				string[] array2 = array;
				for (int num = 0; num < array2.Length; num++)
				{
					string text3 = array2[num].Trim();
					if (!string.IsNullOrWhiteSpace(text3) && !text3.StartsWith("gfx-enable-gfx-jobs=", StringComparison.OrdinalIgnoreCase) && !text3.StartsWith("gfx-enable-native-gfx-jobs=", StringComparison.OrdinalIgnoreCase))
					{
						list.Add(text3);
					}
				}
				File.WriteAllLines(text, list, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				IsGfxJobsActive = true;
				RestartRequired = true;
				ManualLogSource log5 = OptiHousePlugin.Log;
				if (log5 != null)
				{
					log5.LogInfo((object)("[BootConfigTweaker] Successfully injected multi-threaded Gfx Jobs into " + text + ". A game restart is required for changes to take full effect."));
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log6 = OptiHousePlugin.Log;
				if (log6 != null)
				{
					log6.LogError((object)("[BootConfigTweaker] Failed to evaluate or inject boot.config tweaks: " + ex.Message));
				}
			}
		}

		private static string? FindBootConfigPath()
		{
			if (!string.IsNullOrEmpty(Application.dataPath))
			{
				string text = Path.Combine(Application.dataPath, "boot.config");
				if (File.Exists(text))
				{
					return text;
				}
				string text2 = Path.Combine(Application.dataPath, "valheim_Data", "boot.config");
				if (File.Exists(text2))
				{
					return text2;
				}
			}
			try
			{
				string gameRootPath = Paths.GameRootPath;
				if (!string.IsNullOrEmpty(gameRootPath))
				{
					string text3 = Path.Combine(gameRootPath, "valheim_Data", "boot.config");
					if (File.Exists(text3))
					{
						return text3;
					}
				}
			}
			catch
			{
			}
			string text4 = Path.Combine(Directory.GetCurrentDirectory(), "valheim_Data", "boot.config");
			if (File.Exists(text4))
			{
				return text4;
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(OptiHousePlugin), "Awake")]
	public static class BootConfigTweaker_Plugin_Patch
	{
		[HarmonyPriority(800)]
		[HarmonyPostfix]
		public static void Postfix()
		{
			BootConfigTweaker.Initialize();
		}
	}
	public class ClothOptimizer : MonoBehaviour
	{
		private class TrackedCloth
		{
			public Piece Piece;

			public Cloth Cloth;

			public Transform Transform;

			public bool IsCulled;
		}

		private static ClothOptimizer? _instance;

		private static readonly List<TrackedCloth> _trackedCloths = new List<TrackedCloth>();

		private static readonly Dictionary<int, List<TrackedCloth>> _pieceLookup = new Dictionary<int, List<TrackedCloth>>();

		private static int _culledClothCount;

		private int _currentIndex;

		private bool _wasOptimizationActive = true;

		public static ClothOptimizer? Instance => _instance;

		public static int TotalClothCount => _trackedCloths.Count;

		public static int CulledClothCount => _culledClothCount;

		private void Awake()
		{
			_instance = this;
			ScanExistingPieces();
		}

		private void OnDestroy()
		{
			RestoreAllCloths();
			_trackedCloths.Clear();
			_pieceLookup.Clear();
			_culledClothCount = 0;
			if ((Object)(object)_instance == (Object)(object)this)
			{
				_instance = null;
			}
		}

		public static void ScanExistingPieces()
		{
			Piece[] array = Object.FindObjectsByType<Piece>((FindObjectsSortMode)0);
			if (array == null)
			{
				return;
			}
			foreach (Piece val in array)
			{
				if ((Object)(object)val != (Object)null)
				{
					RegisterPiece(val);
				}
			}
		}

		private void Update()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			if (!OptiHousePlugin.IsOptimizationActive || ModConfig.EnableClothOptimization == null || !ModConfig.EnableClothOptimization.Value)
			{
				if (_wasOptimizationActive)
				{
					_wasOptimizationActive = false;
					RestoreAllCloths();
				}
				return;
			}
			_wasOptimizationActive = true;
			int count = _trackedCloths.Count;
			if (count == 0)
			{
				return;
			}
			Vector3 referencePosition = GetReferencePosition();
			float num = ((ModConfig.BannerClothCullDistance != null) ? ModConfig.BannerClothCullDistance.Value : 15f);
			float num2 = num * num;
			float num3 = Mathf.Max(0f, num - 3f);
			float num4 = num3 * num3;
			int num5 = Mathf.Min(50, count);
			for (int i = 0; i < num5; i++)
			{
				_currentIndex++;
				if (_currentIndex >= _trackedCloths.Count)
				{
					_currentIndex = 0;
				}
				TrackedCloth trackedCloth = _trackedCloths[_currentIndex];
				if ((Object)(object)trackedCloth.Cloth == (Object)null || (Object)(object)trackedCloth.Transform == (Object)null || (Object)(object)trackedCloth.Piece == (Object)null)
				{
					if (trackedCloth.IsCulled && _culledClothCount > 0)
					{
						_culledClothCount--;
					}
					_trackedCloths.RemoveAt(_currentIndex);
					if (_currentIndex > 0)
					{
						_currentIndex--;
					}
				}
				else
				{
					if (!((Component)trackedCloth.Cloth).gameObject.activeInHierarchy)
					{
						continue;
					}
					Vector3 val = trackedCloth.Transform.position - referencePosition;
					float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
					if (sqrMagnitude > num2)
					{
						if (!trackedCloth.IsCulled)
						{
							trackedCloth.Cloth.enabled = false;
							trackedCloth.IsCulled = true;
							_culledClothCount++;
						}
					}
					else if (sqrMagnitude < num4 && trackedCloth.IsCulled)
					{
						trackedCloth.Cloth.enabled = true;
						trackedCloth.IsCulled = false;
						if (_culledClothCount > 0)
						{
							_culledClothCount--;
						}
					}
				}
			}
		}

		public static void RegisterPiece(Piece piece)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)piece == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)piece).GetInstanceID();
			if (_pieceLookup.ContainsKey(instanceID))
			{
				return;
			}
			Cloth[] componentsInChildren = ((Component)piece).GetComponentsInChildren<Cloth>(true);
			if (componentsInChildren == null || componentsInChildren.Length == 0)
			{
				return;
			}
			List<TrackedCloth> list = new List<TrackedCloth>(componentsInChildren.Length);
			Vector3 referencePosition = GetReferencePosition();
			float num = ((ModConfig.BannerClothCullDistance != null) ? ModConfig.BannerClothCullDistance.Value : 15f);
			float num2 = num * num;
			bool flag = OptiHousePlugin.IsOptimizationActive && ModConfig.EnableClothOptimization != null && ModConfig.EnableClothOptimization.Value;
			foreach (Cloth val in componentsInChildren)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				TrackedCloth trackedCloth = new TrackedCloth
				{
					Piece = piece,
					Cloth = val,
					Transform = ((Component)val).transform,
					IsCulled = false
				};
				if (flag)
				{
					Vector3 val2 = trackedCloth.Transform.position - referencePosition;
					if (((Vector3)(ref val2)).sqrMagnitude > num2)
					{
						trackedCloth.Cloth.enabled = false;
						trackedCloth.IsCulled = true;
						_culledClothCount++;
					}
				}
				_trackedCloths.Add(trackedCloth);
				list.Add(trackedCloth);
			}
			if (list.Count > 0)
			{
				_pieceLookup[instanceID] = list;
			}
		}

		public static void UnregisterPiece(Piece piece)
		{
			if ((Object)(object)piece == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)piece).GetInstanceID();
			if (!_pieceLookup.TryGetValue(instanceID, out List<TrackedCloth> value))
			{
				return;
			}
			for (int i = 0; i < value.Count; i++)
			{
				TrackedCloth trackedCloth = value[i];
				if (trackedCloth.IsCulled && _culledClothCount > 0)
				{
					_culledClothCount--;
				}
				if ((Object)(object)trackedCloth.Cloth != (Object)null)
				{
					trackedCloth.Cloth.enabled = true;
					trackedCloth.IsCulled = false;
				}
				_trackedCloths.Remove(trackedCloth);
			}
			_pieceLookup.Remove(instanceID);
		}

		public static void RestoreAllCloths()
		{
			for (int i = 0; i < _trackedCloths.Count; i++)
			{
				TrackedCloth trackedCloth = _trackedCloths[i];
				if ((Object)(object)trackedCloth.Cloth != (Object)null)
				{
					trackedCloth.Cloth.enabled = true;
					trackedCloth.IsCulled = false;
				}
			}
			_culledClothCount = 0;
		}

		private static Vector3 GetReferencePosition()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				return ((Component)Player.m_localPlayer).transform.position;
			}
			Camera mainCamera = Utils.GetMainCamera();
			if ((Object)(object)mainCamera != (Object)null)
			{
				return ((Component)mainCamera).transform.position;
			}
			return Vector3.zero;
		}
	}
	[HarmonyPatch(typeof(OptiHousePlugin), "Awake")]
	public static class ClothOptimizer_Plugin_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(OptiHousePlugin __instance)
		{
			if ((Object)(object)__instance != (Object)null && (Object)(object)((Component)__instance).gameObject.GetComponent<ClothOptimizer>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<ClothOptimizer>();
			}
		}
	}
	[HarmonyPatch(typeof(Piece), "Awake")]
	public static class ClothOptimizer_Piece_Awake_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Piece __instance)
		{
			ClothOptimizer.RegisterPiece(__instance);
		}
	}
	[HarmonyPatch(typeof(Piece), "OnDestroy")]
	public static class ClothOptimizer_Piece_OnDestroy_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Piece __instance)
		{
			ClothOptimizer.UnregisterPiece(__instance);
		}
	}
	public class CraftingStationOptimizer : MonoBehaviour
	{
		private class TrackedStation
		{
			public int InstanceId;

			public Component Station;

			public Transform Transform;

			public ParticleSystem[] ParticleSystems = Array.Empty<ParticleSystem>();

			public AudioSource[] AudioSources = Array.Empty<AudioSource>();

			public bool IsCulled;

			public readonly HashSet<ParticleSystem> PausedParticles = new HashSet<ParticleSystem>();

			public readonly HashSet<AudioSource> PausedAudio = new HashSet<AudioSource>();
		}

		private const float UpdateInterval = 0.35f;

		private const float HysteresisMargin = 3f;

		private float _timer;

		private bool _wasActive = true;

		private static readonly List<TrackedStation> _stations = new List<TrackedStation>();

		private static readonly Dictionary<int, TrackedStation> _stationLookup = new Dictionary<int, TrackedStation>();

		public static CraftingStationOptimizer? Instance { get; private set; }

		public static int TotalStations { get; private set; }

		public static int CulledStations { get; private set; }

		private void Awake()
		{
			Instance = this;
		}

		private void Start()
		{
			ScanExistingStations();
		}

		private void OnDestroy()
		{
			RestoreAllStations();
			_stations.Clear();
			_stationLookup.Clear();
			TotalStations = 0;
			CulledStations = 0;
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private void Update()
		{
			if (!OptiHousePlugin.IsOptimizationActive || ModConfig.EnableStationOptimization == null || !ModConfig.EnableStationOptimization.Value)
			{
				if (_wasActive)
				{
					_wasActive = false;
					RestoreAllStations();
					CulledStations = 0;
				}
				return;
			}
			_wasActive = true;
			_timer += Time.deltaTime;
			if (!(_timer < 0.35f))
			{
				_timer = 0f;
				EvaluateStations();
			}
		}

		public static void ScanExistingStations()
		{
			try
			{
				Smelter[] array = Object.FindObjectsByType<Smelter>((FindObjectsSortMode)0);
				for (int i = 0; i < array.Length; i++)
				{
					RegisterStation((Component)(object)array[i]);
				}
				Fermenter[] array2 = Object.FindObjectsByType<Fermenter>((FindObjectsSortMode)0);
				for (int i = 0; i < array2.Length; i++)
				{
					RegisterStation((Component)(object)array2[i]);
				}
				CookingStation[] array3 = Object.FindObjectsByType<CookingStation>((FindObjectsSortMode)0);
				for (int i = 0; i < array3.Length; i++)
				{
					RegisterStation((Component)(object)array3[i]);
				}
				CraftingStation[] array4 = Object.FindObjectsByType<CraftingStation>((FindObjectsSortMode)0);
				for (int i = 0; i < array4.Length; i++)
				{
					RegisterStation((Component)(object)array4[i]);
				}
				Windmill[] array5 = Object.FindObjectsByType<Windmill>((FindObjectsSortMode)0);
				for (int i = 0; i < array5.Length; i++)
				{
					RegisterStation((Component)(object)array5[i]);
				}
			}
			catch (Exception ex)
			{
				if (ModConfig.EnableLogging != null && ModConfig.EnableLogging.Value)
				{
					OptiHousePlugin.Log.LogWarning((object)("[CraftingStationOptimizer] ScanExistingStations error: " + ex.Message));
				}
			}
		}

		public static void RegisterStation(Component station)
		{
			if (!((Object)(object)station == (Object)null))
			{
				int instanceID = ((Object)station).GetInstanceID();
				if (!_stationLookup.ContainsKey(instanceID))
				{
					TrackedStation trackedStation = new TrackedStation
					{
						InstanceId = instanceID,
						Station = station,
						Transform = station.transform,
						ParticleSystems = station.GetComponentsInChildren<ParticleSystem>(true),
						AudioSources = station.GetComponentsInChildren<AudioSource>(true),
						IsCulled = false
					};
					_stations.Add(trackedStation);
					_stationLookup[instanceID] = trackedStation;
					TotalStations = _stations.Count;
				}
			}
		}

		public static void UnregisterStation(Component station)
		{
			if (!((Object)(object)station == (Object)null))
			{
				int instanceID = ((Object)station).GetInstanceID();
				if (_stationLookup.TryGetValue(instanceID, out TrackedStation value))
				{
					RestoreStation(value);
					_stationLookup.Remove(instanceID);
					_stations.Remove(value);
					TotalStations = _stations.Count;
				}
			}
		}

		private void EvaluateStations()
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			for (int num = _stations.Count - 1; num >= 0; num--)
			{
				TrackedStation trackedStation = _stations[num];
				if ((Object)(object)trackedStation.Station == (Object)null || (Object)(object)trackedStation.Transform == (Object)null)
				{
					_stationLookup.Remove(trackedStation.InstanceId);
					_stations.RemoveAt(num);
				}
			}
			TotalStations = _stations.Count;
			if (_stations.Count == 0)
			{
				CulledStations = 0;
				return;
			}
			Vector3 val = Vector3.zero;
			bool flag = false;
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				val = ((Component)Player.m_localPlayer).transform.position;
				flag = true;
			}
			else if ((Object)(object)Camera.main != (Object)null)
			{
				val = ((Component)Camera.main).transform.position;
				flag = true;
			}
			if (!flag)
			{
				return;
			}
			float num2 = ((ModConfig.StationCullDistance != null) ? Mathf.Max(5f, ModConfig.StationCullDistance.Value) : 18f);
			float num3 = num2 * num2;
			float num4 = Mathf.Max(0f, num2 - 3f);
			float num5 = num4 * num4;
			int num6 = 0;
			for (int i = 0; i < _stations.Count; i++)
			{
				TrackedStation trackedStation2 = _stations[i];
				Vector3 val2 = trackedStation2.Transform.position - val;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				if (sqrMagnitude > num3)
				{
					CullStation(trackedStation2);
					num6++;
				}
				else if (sqrMagnitude < num5)
				{
					if (trackedStation2.IsCulled)
					{
						RestoreStation(trackedStation2);
					}
				}
				else if (trackedStation2.IsCulled)
				{
					num6++;
				}
			}
			CulledStations = num6;
		}

		private static void CullStation(TrackedStation entry)
		{
			entry.IsCulled = true;
			for (int i = 0; i < entry.ParticleSystems.Length; i++)
			{
				ParticleSystem val = entry.ParticleSystems[i];
				if ((Object)(object)val != (Object)null && val.isPlaying && !entry.PausedParticles.Contains(val))
				{
					val.Pause();
					entry.PausedParticles.Add(val);
				}
			}
			for (int j = 0; j < entry.AudioSources.Length; j++)
			{
				AudioSource val2 = entry.AudioSources[j];
				if ((Object)(object)val2 != (Object)null && val2.loop && val2.isPlaying && !entry.PausedAudio.Contains(val2))
				{
					val2.Pause();
					entry.PausedAudio.Add(val2);
				}
			}
		}

		private static void RestoreStation(TrackedStation entry)
		{
			entry.IsCulled = false;
			foreach (ParticleSystem pausedParticle in entry.PausedParticles)
			{
				if ((Object)(object)pausedParticle != (Object)null && pausedParticle.isPaused)
				{
					pausedParticle.Play();
				}
			}
			entry.PausedParticles.Clear();
			foreach (AudioSource item in entry.PausedAudio)
			{
				if ((Object)(object)item != (Object)null)
				{
					item.UnPause();
				}
			}
			entry.PausedAudio.Clear();
		}

		public static void RestoreAllStations()
		{
			for (int i = 0; i < _stations.Count; i++)
			{
				RestoreStation(_stations[i]);
			}
			CulledStations = 0;
		}
	}
	[HarmonyPatch(typeof(OptiHousePlugin), "Awake")]
	public static class CraftingStationOptimizer_Plugin_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(OptiHousePlugin __instance)
		{
			if ((Object)(object)__instance != (Object)null && (Object)(object)((Component)__instance).gameObject.GetComponent<CraftingStationOptimizer>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<CraftingStationOptimizer>();
			}
		}
	}
	[HarmonyPatch(typeof(Smelter), "Awake")]
	public static class Smelter_Awake_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Smelter __instance)
		{
			CraftingStationOptimizer.RegisterStation((Component)(object)__instance);
		}
	}
	[HarmonyPatch(typeof(Smelter), "OnDestroyed")]
	public static class Smelter_OnDestroyed_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Smelter __instance)
		{
			CraftingStationOptimizer.UnregisterStation((Component)(object)__instance);
		}
	}
	[HarmonyPatch(typeof(Fermenter), "Awake")]
	public static class Fermenter_Awake_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Fermenter __instance)
		{
			CraftingStationOptimizer.RegisterStation((Component)(object)__instance);
		}
	}
	[HarmonyPatch(typeof(Fermenter), "OnDestroyed")]
	public static class Fermenter_OnDestroyed_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Fermenter __instance)
		{
			CraftingStationOptimizer.UnregisterStation((Component)(object)__instance);
		}
	}
	[HarmonyPatch(typeof(CookingStation), "Awake")]
	public static class CookingStation_Awake_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(CookingStation __instance)
		{
			CraftingStationOptimizer.RegisterStation((Component)(object)__instance);
		}
	}
	[HarmonyPatch(typeof(CookingStation), "OnDestroyed")]
	public static class CookingStation_OnDestroyed_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(CookingStation __instance)
		{
			CraftingStationOptimizer.UnregisterStation((Component)(object)__instance);
		}
	}
	[HarmonyPatch(typeof(CraftingStation), "Start")]
	public static class CraftingStation_Start_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(CraftingStation __instance)
		{
			CraftingStationOptimizer.RegisterStation((Component)(object)__instance);
		}
	}
	[HarmonyPatch(typeof(CraftingStation), "OnDestroy")]
	public static class CraftingStation_OnDestroy_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(CraftingStation __instance)
		{
			CraftingStationOptimizer.UnregisterStation((Component)(object)__instance);
		}
	}
	[HarmonyPatch(typeof(Windmill), "Start")]
	public static class Windmill_Start_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Windmill __instance)
		{
			CraftingStationOptimizer.RegisterStation((Component)(object)__instance);
		}
	}
	public class DecorativeColliderOptimizer : MonoBehaviour
	{
		private class TrackedDecorativePiece
		{
			public Piece Piece;

			public Transform Transform;

			public Collider[] Colliders;

			public bool CollidersCulled;
		}

		private static DecorativeColliderOptimizer? _instance;

		private static readonly List<TrackedDecorativePiece> _trackedPieces = new List<TrackedDecorativePiece>();

		private static readonly Dictionary<int, TrackedDecorativePiece> _pieceLookup = new Dictionary<int, TrackedDecorativePiece>();

		private static int _culledColliderCount;

		private static bool _areCollidersCulled;

		private float _cleanupTimer;

		public static DecorativeColliderOptimizer? Instance => _instance;

		public static int TotalDecorativePieces => _trackedPieces.Count;

		public static int CulledColliderCount => _culledColliderCount;

		public static bool AreCollidersCulled => _areCollidersCulled;

		private void Awake()
		{
			_instance = this;
		}

		private void Start()
		{
			ScanExistingPieces();
		}

		private void OnDestroy()
		{
			RestoreAllColliders();
			_trackedPieces.Clear();
			_pieceLookup.Clear();
			_culledColliderCount = 0;
			_areCollidersCulled = false;
			if ((Object)(object)_instance == (Object)(object)this)
			{
				_instance = null;
			}
		}

		private void Update()
		{
			bool num = OptiHousePlugin.IsOptimizationActive && ModConfig.EnableStructuralOptimization != null && ModConfig.EnableStructuralOptimization.Value && ModConfig.EnableDecorativeColliderOptimization != null && ModConfig.EnableDecorativeColliderOptimization.Value;
			bool flag = IsBuildToolEquipped();
			if (num && !flag)
			{
				if (!_areCollidersCulled)
				{
					CullAllDecorativeColliders();
				}
			}
			else if (_areCollidersCulled)
			{
				RestoreAllColliders();
			}
			_cleanupTimer += Time.deltaTime;
			if (_cleanupTimer >= 2f)
			{
				_cleanupTimer = 0f;
				CleanupStalePieces();
			}
		}

		public static void ScanExistingPieces()
		{
			Piece[] array = Object.FindObjectsByType<Piece>((FindObjectsSortMode)0);
			if (array == null)
			{
				return;
			}
			foreach (Piece val in array)
			{
				if ((Object)(object)val != (Object)null)
				{
					RegisterPiece(val);
				}
			}
		}

		public static void RegisterPiece(Piece piece)
		{
			if ((Object)(object)piece == (Object)null || (Object)(object)((Component)piece).gameObject == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)piece).GetInstanceID();
			if (_pieceLookup.ContainsKey(instanceID) || !IsPurelyDecorativePiece(piece))
			{
				return;
			}
			Collider[] componentsInChildren = ((Component)piece).GetComponentsInChildren<Collider>(true);
			if (componentsInChildren == null || componentsInChildren.Length == 0)
			{
				return;
			}
			List<Collider> list = new List<Collider>(componentsInChildren.Length);
			foreach (Collider val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && !val.isTrigger)
				{
					list.Add(val);
				}
			}
			if (list.Count == 0)
			{
				return;
			}
			TrackedDecorativePiece trackedDecorativePiece = new TrackedDecorativePiece
			{
				Piece = piece,
				Transform = ((Component)piece).transform,
				Colliders = list.ToArray(),
				CollidersCulled = false
			};
			if (_areCollidersCulled)
			{
				for (int j = 0; j < trackedDecorativePiece.Colliders.Length; j++)
				{
					Collider val2 = trackedDecorativePiece.Colliders[j];
					if ((Object)(object)val2 != (Object)null)
					{
						val2.enabled = false;
					}
				}
				trackedDecorativePiece.CollidersCulled = true;
				_culledColliderCount += trackedDecorativePiece.Colliders.Length;
			}
			_trackedPieces.Add(trackedDecorativePiece);
			_pieceLookup[instanceID] = trackedDecorativePiece;
		}

		public static void UnregisterPiece(Piece piece)
		{
			if ((Object)(object)piece == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)piece).GetInstanceID();
			if (!_pieceLookup.TryGetValue(instanceID, out TrackedDecorativePiece value))
			{
				return;
			}
			if (value.CollidersCulled && value.Colliders != null)
			{
				for (int i = 0; i < value.Colliders.Length; i++)
				{
					Collider val = value.Colliders[i];
					if ((Object)(object)val != (Object)null)
					{
						val.enabled = true;
					}
				}
				_culledColliderCount = Mathf.Max(0, _culledColliderCount - value.Colliders.Length);
			}
			_trackedPieces.Remove(value);
			_pieceLookup.Remove(instanceID);
		}

		public static void CullAllDecorativeColliders()
		{
			int num = 0;
			for (int i = 0; i < _trackedPieces.Count; i++)
			{
				TrackedDecorativePiece trackedDecorativePiece = _trackedPieces[i];
				if (trackedDecorativePiece == null || (Object)(object)trackedDecorativePiece.Piece == (Object)null)
				{
					continue;
				}
				if (!trackedDecorativePiece.CollidersCulled && trackedDecorativePiece.Colliders != null)
				{
					for (int j = 0; j < trackedDecorativePiece.Colliders.Length; j++)
					{
						Collider val = trackedDecorativePiece.Colliders[j];
						if ((Object)(object)val != (Object)null && val.enabled)
						{
							val.enabled = false;
						}
					}
					trackedDecorativePiece.CollidersCulled = true;
				}
				if (trackedDecorativePiece.Colliders != null)
				{
					num += trackedDecorativePiece.Colliders.Length;
				}
			}
			_culledColliderCount = num;
			_areCollidersCulled = true;
		}

		public static void RestoreAllColliders()
		{
			for (int i = 0; i < _trackedPieces.Count; i++)
			{
				TrackedDecorativePiece trackedDecorativePiece = _trackedPieces[i];
				if (trackedDecorativePiece == null || (Object)(object)trackedDecorativePiece.Piece == (Object)null || !trackedDecorativePiece.CollidersCulled || trackedDecorativePiece.Colliders == null)
				{
					continue;
				}
				for (int j = 0; j < trackedDecorativePiece.Colliders.Length; j++)
				{
					Collider val = trackedDecorativePiece.Colliders[j];
					if ((Object)(object)val != (Object)null && !val.enabled)
					{
						val.enabled = true;
					}
				}
				trackedDecorativePiece.CollidersCulled = false;
			}
			_culledColliderCount = 0;
			_areCollidersCulled = false;
		}

		public static bool IsBuildToolEquipped()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return false;
			}
			if (((Character)localPlayer).InPlaceMode() || localPlayer.InRepairMode())
			{
				return true;
			}
			if ((Object)(object)localPlayer.GetBuildTool() != (Object)null)
			{
				return true;
			}
			ItemData rightItem = ((Humanoid)localPlayer).RightItem;
			if (rightItem != null && rightItem.m_shared != null && (Object)(object)rightItem.m_shared.m_buildPieces != (Object)null)
			{
				return true;
			}
			ItemData leftItem = ((Humanoid)localPlayer).LeftItem;
			if (leftItem != null && leftItem.m_shared != null && (Object)(object)leftItem.m_shared.m_buildPieces != (Object)null)
			{
				return true;
			}
			return false;
		}

		public static bool IsNeverCulled(Piece piece)
		{
			if ((Object)(object)piece == (Object)null || (Object)(object)((Component)piece).gameObject == (Object)null)
			{
				return true;
			}
			if ((Object)(object)((Component)piece).GetComponent<Door>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Container>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Bed>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Chair>() != (Object)null || (Object)(object)((Component)piece).GetComponent<CraftingStation>() != (Object)null || (Object)(object)((Component)piece).GetComponent<StationExtension>() != (Object)null || (Object)(object)((Component)piece).GetComponent<TeleportWorld>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Sign>() != (Object)null || (Object)(object)((Component)piece).GetComponent<ItemStand>() != (Object)null || (Object)(object)((Component)piece).GetComponent<ArmorStand>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Fireplace>() != (Object)null || (Object)(object)((Component)piece).GetComponent<CookingStation>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Smelter>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Fermenter>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Ship>() != (Object)null)
			{
				return true;
			}
			if (piece.m_groundPiece || piece.m_groundOnly)
			{
				return true;
			}
			string text = ((Object)((Component)piece).gameObject).name.ToLowerInvariant();
			if (text.Contains("floor") || text.Contains("stair") || text.Contains("step") || text.Contains("ladder") || text.Contains("door") || text.Contains("gate") || text.Contains("chest") || text.Contains("cart") || text.Contains("bed") || text.Contains("chair") || text.Contains("stool") || text.Contains("bench") || text.Contains("table") || text.Contains("portal") || text.Contains("ship") || text.Contains("raft") || text.Contains("foundation") || text.Contains("hearth") || text.Contains("iron_grate") || text.Contains("stone_floor") || text.Contains("stone_wall") || text.Contains("stone_pillar") || text.Contains("stone_arch") || text.Contains("blackmarble_floor") || text.Contains("blackmarble_stair") || text.Contains("blackmarble_pillar") || text.Contains("pillar") || text.Contains("wall"))
			{
				return true;
			}
			if (text.Contains("roof") && !text.Contains("roof_ridge") && !text.Contains("roof_top") && !text.Contains("roof_pole") && !text.Contains("roof_crest") && !text.Contains("roof_finial"))
			{
				return true;
			}
			return false;
		}

		public static bool IsPurelyDecorativePiece(Piece piece)
		{
			if ((Object)(object)piece == (Object)null || (Object)(object)((Component)piece).gameObject == (Object)null)
			{
				return false;
			}
			if (IsNeverCulled(piece))
			{
				return false;
			}
			string text = ((Object)((Component)piece).gameObject).name.ToLowerInvariant();
			if (text.Contains("cross_26") || text.Contains("cross_45") || text.Contains("beam_cross") || text.Contains("wood_beam_cross") || text.Contains("darkwood_beam_cross"))
			{
				return true;
			}
			if (text.Contains("roof_ridge") || text.Contains("roof_top") || text.Contains("shingle_ridge") || text.Contains("straw_roof_top") || text.Contains("straw_roof_ridge") || text.Contains("tarp_roof_ridge") || text.Contains("ridge_26") || text.Contains("ridge_45") || text.Contains("ridge_cap") || text.Contains("roof_crest") || text.Contains("roof_finial"))
			{
				return true;
			}
			if (text.Contains("dragonhead") || text.Contains("carving_raven") || text.Contains("carving_wolf") || text.Contains("finial") || text.Contains("wood_trim") || text.Contains("bracket") || text.Contains("wood_arch") || text.Contains("darkwood_arch"))
			{
				return true;
			}
			if ((text.Contains("roof_pole") || text.Contains("roof_beam") || text.Contains("wood_pole") || text.Contains("darkwood_pole") || text.Contains("wood_beam") || text.Contains("darkwood_beam") || text.Contains("iron_beam") || text.Contains("iron_pole")) && IsElevatedAboveWalkable(piece))
			{
				return true;
			}
			return false;
		}

		public static bool IsElevatedAboveWalkable(Piece piece, float minElevation = 3.5f)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)piece == (Object)null)
			{
				return false;
			}
			Vector3 position = ((Component)piece).transform.position;
			float num = position.y;
			float num2 = default(float);
			float num3 = default(float);
			if ((Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGroundHeight(position, ref num2))
			{
				num = num2;
			}
			else if (Heightmap.GetHeight(position, ref num3))
			{
				num = num3;
			}
			if (position.y - num < minElevation)
			{
				return false;
			}
			int mask = LayerMask.GetMask(new string[3] { "piece", "Default", "terrain" });
			if (mask == 0)
			{
				mask = LayerMask.GetMask(new string[1] { "piece" });
			}
			RaycastHit[] array = Physics.RaycastAll(position + Vector3.down * 0.2f, Vector3.down, minElevation, mask, (QueryTriggerInteraction)1);
			if (array != null && array.Length != 0)
			{
				for (int i = 0; i < array.Length; i++)
				{
					Collider collider = ((RaycastHit)(ref array[i])).collider;
					if ((Object)(object)collider != (Object)null)
					{
						Piece componentInParent = ((Component)collider).GetComponentInParent<Piece>();
						if (!((Object)(object)componentInParent != (Object)null) || !((Object)(object)componentInParent == (Object)(object)piece))
						{
							return false;
						}
					}
				}
			}
			return true;
		}

		private static void CleanupStalePieces()
		{
			for (int num = _trackedPieces.Count - 1; num >= 0; num--)
			{
				TrackedDecorativePiece trackedDecorativePiece = _trackedPieces[num];
				if (trackedDecorativePiece == null || (Object)(object)trackedDecorativePiece.Piece == (Object)null || (Object)(object)trackedDecorativePiece.Transform == (Object)null)
				{
					if (trackedDecorativePiece != null && trackedDecorativePiece.CollidersCulled && trackedDecorativePiece.Colliders != null)
					{
						_culledColliderCount = Mathf.Max(0, _culledColliderCount - trackedDecorativePiece.Colliders.Length);
					}
					_trackedPieces.RemoveAt(num);
				}
			}
		}
	}
	[HarmonyPatch(typeof(OptiHousePlugin), "Awake")]
	public static class DecorativeColliderOptimizer_Plugin_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(OptiHousePlugin __instance)
		{
			if ((Object)(object)__instance != (Object)null && (Object)(object)((Component)__instance).gameObject.GetComponent<DecorativeColliderOptimizer>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<DecorativeColliderOptimizer>();
			}
		}
	}
	[HarmonyPatch(typeof(Piece), "Awake")]
	public static class DecorativeColliderOptimizer_Piece_Awake_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Piece __instance)
		{
			DecorativeColliderOptimizer.RegisterPiece(__instance);
		}
	}
	[HarmonyPatch(typeof(Piece), "OnDestroy")]
	public static class DecorativeColliderOptimizer_Piece_OnDestroy_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Piece __instance)
		{
			DecorativeColliderOptimizer.UnregisterPiece(__instance);
		}
	}
	[HarmonyPatch(typeof(Player), "PieceRayTest")]
	public static class DecorativeColliderOptimizer_PieceRayTest_Patch
	{
		[HarmonyPrefix]
		public static void Prefix(Player __instance)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && DecorativeColliderOptimizer.AreCollidersCulled)
			{
				DecorativeColliderOptimizer.RestoreAllColliders();
			}
		}
	}
	[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
	public static class DecorativeColliderOptimizer_UpdatePlacementGhost_Patch
	{
		[HarmonyPrefix]
		public static void Prefix(Player __instance)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && DecorativeColliderOptimizer.AreCollidersCulled)
			{
				DecorativeColliderOptimizer.RestoreAllColliders();
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "EquipItem")]
	public static class DecorativeColliderOptimizer_Humanoid_EquipItem_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Humanoid __instance, ItemData item)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && (Object)(object)item?.m_shared?.m_buildPieces != (Object)null && DecorativeColliderOptimizer.AreCollidersCulled)
			{
				DecorativeColliderOptimizer.RestoreAllColliders();
			}
		}
	}
	public class DetailPieceLOD : MonoBehaviour
	{
		private class TrackedDetailPiece
		{
			public int InstanceId;

			public Piece Piece;

			public Transform Transform;

			public readonly List<Renderer> Renderers = new List<Renderer>();

			public bool IsCulled;

			public void SetRenderersEnabled(bool enabled)
			{
				for (int i = 0; i < Renderers.Count; i++)
				{
					Renderer val = Renderers[i];
					if ((Object)(object)val != (Object)null)
					{
						val.enabled = enabled;
					}
				}
			}
		}

		private static DetailPieceLOD? _instance;

		private static readonly List<TrackedDetailPiece> _trackedPieces = new List<TrackedDetailPiece>();

		private static readonly Dictionary<int, TrackedDetailPiece> _pieceLookup = new Dictionary<int, TrackedDetailPiece>();

		private static int _culledDetailCount;

		private int _currentIndex;

		private bool _wasOptimizationActive = true;

		private bool _wasBuilding;

		public static DetailPieceLOD? Instance => _instance;

		public static int TotalDetailPieces => _trackedPieces.Count;

		public static int CulledDetailPieces => _culledDetailCount;

		private void Awake()
		{
			_instance = this;
			ScanExistingPieces();
		}

		private void OnDestroy()
		{
			RestoreAllRenderers();
			_trackedPieces.Clear();
			_pieceLookup.Clear();
			_culledDetailCount = 0;
			if ((Object)(object)_instance == (Object)(object)this)
			{
				_instance = null;
			}
		}

		public static void ScanExistingPieces()
		{
			Piece[] array = Object.FindObjectsByType<Piece>((FindObjectsSortMode)0);
			if (array == null)
			{
				return;
			}
			foreach (Piece val in array)
			{
				if ((Object)(object)val != (Object)null)
				{
					RegisterPiece(val);
				}
			}
		}

		private void Update()
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			if (!OptiHousePlugin.IsOptimizationActive || ModConfig.EnableDetailPieceLOD == null || !ModConfig.EnableDetailPieceLOD.Value)
			{
				if (_wasOptimizationActive)
				{
					_wasOptimizationActive = false;
					RestoreAllRenderers();
				}
				return;
			}
			_wasOptimizationActive = true;
			if (DecorativeColliderOptimizer.IsBuildToolEquipped())
			{
				if (!_wasBuilding || _culledDetailCount > 0)
				{
					_wasBuilding = true;
					RestoreAllRenderers();
				}
				return;
			}
			_wasBuilding = false;
			int count = _trackedPieces.Count;
			if (count == 0)
			{
				return;
			}
			Vector3 referencePosition = GetReferencePosition();
			float num = ((ModConfig.DetailPieceCullDistance != null) ? ModConfig.DetailPieceCullDistance.Value : 32f);
			float num2 = ((ModConfig.DetailPieceRestoreDistance != null) ? ModConfig.DetailPieceRestoreDistance.Value : Mathf.Max(5f, num - 6f));
			float num3 = num * num;
			float num4 = num2 * num2;
			int num5 = Mathf.Min(350, count);
			for (int i = 0; i < num5; i++)
			{
				_currentIndex++;
				if (_currentIndex >= _trackedPieces.Count)
				{
					_currentIndex = 0;
				}
				TrackedDetailPiece trackedDetailPiece = _trackedPieces[_currentIndex];
				if ((Object)(object)trackedDetailPiece.Piece == (Object)null || (Object)(object)trackedDetailPiece.Transform == (Object)null)
				{
					if (trackedDetailPiece.IsCulled && _culledDetailCount > 0)
					{
						_culledDetailCount--;
					}
					_pieceLookup.Remove(trackedDetailPiece.InstanceId);
					_trackedPieces.RemoveAt(_currentIndex);
					if (_currentIndex > 0)
					{
						_currentIndex--;
					}
				}
				else
				{
					if (!((Component)trackedDetailPiece.Piece).gameObject.activeInHierarchy)
					{
						continue;
					}
					Vector3 val = trackedDetailPiece.Transform.position - referencePosition;
					float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
					if (sqrMagnitude > num3)
					{
						if (!trackedDetailPiece.IsCulled)
						{
							trackedDetailPiece.SetRenderersEnabled(enabled: false);
							trackedDetailPiece.IsCulled = true;
							_culledDetailCount++;
						}
					}
					else if (sqrMagnitude < num4 && trackedDetailPiece.IsCulled)
					{
						trackedDetailPiece.SetRenderersEnabled(enabled: true);
						trackedDetailPiece.IsCulled = false;
						if (_culledDetailCount > 0)
						{
							_culledDetailCount--;
						}
					}
				}
			}
		}

		public static void RegisterPiece(Piece piece)
		{
			if ((Object)(object)piece == (Object)null || (Object)(object)((Component)piece).gameObject == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)piece).GetInstanceID();
			if (_pieceLookup.ContainsKey(instanceID) || !IsSmallDetailPiece(piece))
			{
				return;
			}
			Renderer[] componentsInChildren = ((Component)piece).GetComponentsInChildren<Renderer>(true);
			if (componentsInChildren == null || componentsInChildren.Length == 0)
			{
				return;
			}
			List<Renderer> list = new List<Renderer>(componentsInChildren.Length);
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null)
				{
					list.Add(val);
				}
			}
			if (list.Count != 0)
			{
				TrackedDetailPiece trackedDetailPiece = new TrackedDetailPiece
				{
					InstanceId = instanceID,
					Piece = piece,
					Transform = ((Component)piece).transform,
					IsCulled = false
				};
				trackedDetailPiece.Renderers.AddRange(list);
				_trackedPieces.Add(trackedDetailPiece);
				_pieceLookup[instanceID] = trackedDetailPiece;
			}
		}

		public static void UnregisterPiece(Piece piece)
		{
			if ((Object)(object)piece == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)piece).GetInstanceID();
			if (!_pieceLookup.TryGetValue(instanceID, out TrackedDetailPiece value))
			{
				return;
			}
			if (value.IsCulled)
			{
				value.SetRenderersEnabled(enabled: true);
				value.IsCulled = false;
				if (_culledDetailCount > 0)
				{
					_culledDetailCount--;
				}
			}
			_trackedPieces.Remove(value);
			_pieceLookup.Remove(instanceID);
		}

		public static void RestoreAllRenderers()
		{
			for (int i = 0; i < _trackedPieces.Count; i++)
			{
				TrackedDetailPiece trackedDetailPiece = _trackedPieces[i];
				if (trackedDetailPiece.IsCulled)
				{
					trackedDetailPiece.SetRenderersEnabled(enabled: true);
					trackedDetailPiece.IsCulled = false;
				}
			}
			_culledDetailCount = 0;
		}

		public static bool IsSmallDetailPiece(Piece piece)
		{
			if ((Object)(object)piece == (Object)null || (Object)(object)((Component)piece).gameObject == (Object)null)
			{
				return false;
			}
			string text = ((Object)((Component)piece).gameObject).name.ToLowerInvariant();
			if (text.Contains("wall") || text.Contains("floor") || text.Contains("stair") || text.Contains("door") || text.Contains("gate") || text.Contains("portal") || text.Contains("chest") || text.Contains("bed") || text.Contains("chair") || text.Contains("table") || text.Contains("ladder") || text.Contains("stone_") || text.Contains("blackmarble_") || text.Contains("ashwood_wall") || text.Contains("ashwood_floor"))
			{
				return false;
			}
			if (text.Contains("roof") && !text.Contains("roof_ridge") && !text.Contains("roof_top") && !text.Contains("roof_pole") && !text.Contains("roof_crest") && !text.Contains("roof_finial") && !text.Contains("ridge_") && !text.Contains("straw_roof_top") && !text.Contains("straw_roof_ridge"))
			{
				return false;
			}
			if (text.Contains("beam_1") || text.Contains("pole_1") || text.Contains("beam_26_1") || text.Contains("beam_45_1") || text.Contains("pole_core_1") || text.Contains("beam_core_1") || text.Contains("darkwood_beam_1") || text.Contains("darkwood_pole_1") || text.Contains("iron_beam_1") || text.Contains("iron_pole_1"))
			{
				return true;
			}
			if (text.Contains("cross_26") || text.Contains("cross_45") || text.Contains("beam_cross"))
			{
				return true;
			}
			if (text.Contains("roof_ridge") || text.Contains("roof_top") || text.Contains("shingle_ridge") || text.Contains("straw_roof_top") || text.Contains("straw_roof_ridge") || text.Contains("tarp_roof_ridge") || text.Contains("ridge_26") || text.Contains("ridge_45") || text.Contains("ridge_cap") || text.Contains("roof_crest") || text.Contains("roof_finial"))
			{
				return true;
			}
			if (text.Contains("dragonhead") || text.Contains("carving_raven") || text.Contains("carving_wolf") || text.Contains("finial") || text.Contains("wood_trim") || text.Contains("bracket") || text.Contains("wood_arch") || text.Contains("darkwood_arch"))
			{
				return true;
			}
			return false;
		}

		private static Vector3 GetReferencePosition()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				return ((Component)Player.m_localPlayer).transform.position;
			}
			Camera mainCamera = Utils.GetMainCamera();
			if ((Object)(object)mainCamera != (Object)null)
			{
				return ((Component)mainCamera).transform.position;
			}
			return Vector3.zero;
		}
	}
	[HarmonyPatch(typeof(OptiHousePlugin), "Awake")]
	public static class DetailPieceLOD_Plugin_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(OptiHousePlugin __instance)
		{
			if ((Object)(object)__instance != (Object)null && (Object)(object)((Component)__instance).gameObject.GetComponent<DetailPieceLOD>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<DetailPieceLOD>();
			}
		}
	}
	[HarmonyPatch(typeof(Piece), "Awake")]
	public static class DetailPieceLOD_Piece_Awake_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Piece __instance)
		{
			DetailPieceLOD.RegisterPiece(__instance);
		}
	}
	[HarmonyPatch(typeof(Piece), "OnDestroy")]
	public static class DetailPieceLOD_Piece_OnDestroy_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Piece __instance)
		{
			DetailPieceLOD.UnregisterPiece(__instance);
		}
	}
	[HarmonyPatch(typeof(Player), "PieceRayTest")]
	public static class DetailPieceLOD_PieceRayTest_Patch
	{
		[HarmonyPrefix]
		public static void Prefix(Player __instance)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && DetailPieceLOD.CulledDetailPieces > 0)
			{
				DetailPieceLOD.RestoreAllRenderers();
			}
		}
	}
	[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
	public static class DetailPieceLOD_UpdatePlacementGhost_Patch
	{
		[HarmonyPrefix]
		public static void Prefix(Player __instance)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && DetailPieceLOD.CulledDetailPieces > 0)
			{
				DetailPieceLOD.RestoreAllRenderers();
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "EquipItem")]
	public static class DetailPieceLOD_Humanoid_EquipItem_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Humanoid __instance, ItemData item)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && (Object)(object)item?.m_shared?.m_buildPieces != (Object)null && DetailPieceLOD.CulledDetailPieces > 0)
			{
				DetailPieceLOD.RestoreAllRenderers();
			}
		}
	}
	public class InteriorOcclusionOptimizer : MonoBehaviour
	{
		private class TrackedInteriorPiece
		{
			public int InstanceId;

			public Piece Piece;

			public Transform Transform;

			public readonly List<Renderer> Renderers = new List<Renderer>();

			public bool IsCulled;

			public bool IsEnclosed;

			public void SetRenderersEnabled(bool enabled)
			{
				for (int i = 0; i < Renderers.Count; i++)
				{
					Renderer val = Renderers[i];
					if ((Object)(object)val != (Object)null)
					{
						val.enabled = enabled;
					}
				}
			}
		}

		private static InteriorOcclusionOptimizer? _instance;

		private static readonly List<TrackedInteriorPiece> _trackedPieces = new List<TrackedInteriorPiece>();

		private static readonly Dictionary<int, TrackedInteriorPiece> _pieceLookup = new Dictionary<int, TrackedInteriorPiece>();

		private static int _culledPieceCount;

		private static int _totalEnclosedCount;

		private int _currentIndex;

		private bool _wasOptimizationActive = true;

		private bool _wasPlayerInShelter;

		private static readonly FieldRef<WearNTear, bool>? _haveRoofRef = AccessTools.FieldRefAccess<WearNTear, bool>("m_haveRoof");

		private static readonly FieldRef<WearNTear, bool>? _haveAshRoofRef = AccessTools.FieldRefAccess<WearNTear, bool>("m_haveAshRoof");

		public static InteriorOcclusionOptimizer? Instance => _instance;

		public static int TotalInteriorPieces => _totalEnclosedCount;

		public static int CulledInteriorPieces => _culledPieceCount;

		public static int TrackedPiecesCount => _trackedPieces.Count;

		public static bool IsCullingActive => _culledPieceCount > 0;

		private void Awake()
		{
			_instance = this;
			ScanExistingPieces();
		}

		private void OnDestroy()
		{
			RestoreAllRenderers();
			_trackedPieces.Clear();
			_pieceLookup.Clear();
			_culledPieceCount = 0;
			_totalEnclosedCount = 0;
			if ((Object)(object)_instance == (Object)(object)this)
			{
				_instance = null;
			}
		}

		public static void ScanExistingPieces()
		{
			Piece[] array = Object.FindObjectsByType<Piece>((FindObjectsSortMode)0);
			if (array == null)
			{
				return;
			}
			foreach (Piece val in array)
			{
				if ((Object)(object)val != (Object)null)
				{
					RegisterPiece(val);
				}
			}
		}

		private void Update()
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			if (!OptiHousePlugin.IsOptimizationActive || ModConfig.EnableInteriorCulling == null || !ModConfig.EnableInteriorCulling.Value)
			{
				if (_wasOptimizationActive)
				{
					_wasOptimizationActive = false;
					RestoreAllRenderers();
				}
				return;
			}
			_wasOptimizationActive = true;
			Player localPlayer = Player.m_localPlayer;
			bool flag = (Object)(object)localPlayer != (Object)null && localPlayer.InShelter();
			bool flag2 = ModConfig.EnableSmartInteriorCulling != null && ModConfig.EnableSmartInteriorCulling.Value;
			if (flag && !flag2)
			{
				if (!_wasPlayerInShelter || _culledPieceCount > 0)
				{
					_wasPlayerInShelter = true;
					RestoreAllRenderers();
				}
				return;
			}
			_wasPlayerInShelter = flag;
			int count = _trackedPieces.Count;
			if (count == 0)
			{
				return;
			}
			Vector3 referencePosition = GetReferencePosition();
			float num = ((ModConfig.InteriorCullDistance != null) ? ModConfig.InteriorCullDistance.Value : 18f);
			float num2 = num * num;
			float num3 = Mathf.Max(0f, num - 3f);
			float num4 = num3 * num3;
			int num5 = Mathf.Min(300, count);
			for (int i = 0; i < num5; i++)
			{
				_currentIndex++;
				if (_currentIndex >= _trackedPieces.Count)
				{
					_currentIndex = 0;
				}
				TrackedInteriorPiece trackedInteriorPiece = _trackedPieces[_currentIndex];
				if ((Object)(object)trackedInteriorPiece.Piece == (Object)null || (Object)(object)trackedInteriorPiece.Transform == (Object)null)
				{
					if (trackedInteriorPiece.IsCulled && _culledPieceCount > 0)
					{
						_culledPieceCount--;
					}
					if (trackedInteriorPiece.IsEnclosed && _totalEnclosedCount > 0)
					{
						_totalEnclosedCount--;
					}
					_pieceLookup.Remove(trackedInteriorPiece.InstanceId);
					_trackedPieces.RemoveAt(_currentIndex);
					if (_currentIndex > 0)
					{
						_currentIndex--;
					}
				}
				else
				{
					if (!((Component)trackedInteriorPiece.Piece).gameObject.activeInHierarchy)
					{
						continue;
					}
					if (!trackedInteriorPiece.IsEnclosed)
					{
						if (!IsEnclosedPiece(trackedInteriorPiece.Piece))
						{
							if (trackedInteriorPiece.IsCulled)
							{
								trackedInteriorPiece.SetRenderersEnabled(enabled: true);
								trackedInteriorPiece.IsCulled = false;
								if (_culledPieceCount > 0)
								{
									_culledPieceCount--;
								}
							}
							continue;
						}
						trackedInteriorPiece.IsEnclosed = true;
						_totalEnclosedCount++;
					}
					Vector3 val = trackedInteriorPiece.Transform.position - referencePosition;
					float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
					if (sqrMagnitude > num2)
					{
						if (!trackedInteriorPiece.IsCulled)
						{
							trackedInteriorPiece.SetRenderersEnabled(enabled: false);
							trackedInteriorPiece.IsCulled = true;
							_culledPieceCount++;
						}
					}
					else if (sqrMagnitude < num4 && trackedInteriorPiece.IsCulled)
					{
						trackedInteriorPiece.SetRenderersEnabled(enabled: true);
						trackedInteriorPiece.IsCulled = false;
						if (_culledPieceCount > 0)
						{
							_culledPieceCount--;
						}
					}
				}
			}
		}

		public static void RegisterPiece(Piece piece)
		{
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)piece == (Object)null || (Object)(object)((Component)piece).gameObject == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)piece).GetInstanceID();
			if (_pieceLookup.ContainsKey(instanceID) || !IsInteriorPiece(piece))
			{
				return;
			}
			Renderer[] componentsInChildren = ((Component)piece).GetComponentsInChildren<Renderer>(true);
			if (componentsInChildren == null || componentsInChildren.Length == 0)
			{
				return;
			}
			List<Renderer> list = new List<Renderer>(componentsInChildren.Length);
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null)
				{
					list.Add(val);
				}
			}
			if (list.Count == 0)
			{
				return;
			}
			bool flag = IsEnclosedPiece(piece);
			TrackedInteriorPiece trackedInteriorPiece = new TrackedInteriorPiece
			{
				InstanceId = instanceID,
				Piece = piece,
				Transform = ((Component)piece).transform,
				IsCulled = false,
				IsEnclosed = flag
			};
			trackedInteriorPiece.Renderers.AddRange(list);
			if (flag)
			{
				_totalEnclosedCount++;
				bool num = OptiHousePlugin.IsOptimizationActive && ModConfig.EnableInteriorCulling != null && ModConfig.EnableInteriorCulling.Value;
				Player localPlayer = Player.m_localPlayer;
				bool flag2 = (Object)(object)localPlayer == (Object)null || !localPlayer.InShelter();
				bool flag3 = ModConfig.EnableSmartInteriorCulling != null && ModConfig.EnableSmartInteriorCulling.Value;
				if (num && (flag2 || flag3))
				{
					Vector3 referencePosition = GetReferencePosition();
					float num2 = ((ModConfig.InteriorCullDistance != null) ? ModConfig.InteriorCullDistance.Value : 18f);
					Vector3 val2 = trackedInteriorPiece.Transform.position - referencePosition;
					if (((Vector3)(ref val2)).sqrMagnitude > num2 * num2)
					{
						trackedInteriorPiece.SetRenderersEnabled(enabled: false);
						trackedInteriorPiece.IsCulled = true;
						_culledPieceCount++;
					}
				}
			}
			_trackedPieces.Add(trackedInteriorPiece);
			_pieceLookup[instanceID] = trackedInteriorPiece;
		}

		public static void UnregisterPiece(Piece piece)
		{
			if ((Object)(object)piece == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)piece).GetInstanceID();
			if (!_pieceLookup.TryGetValue(instanceID, out TrackedInteriorPiece value))
			{
				return;
			}
			if (value.IsCulled)
			{
				value.SetRenderersEnabled(enabled: true);
				value.IsCulled = false;
				if (_culledPieceCount > 0)
				{
					_culledPieceCount--;
				}
			}
			if (value.IsEnclosed && _totalEnclosedCount > 0)
			{
				_totalEnclosedCount--;
			}
			_trackedPieces.Remove(value);
			_pieceLookup.Remove(instanceID);
		}

		public static void RefreshPiece(Piece piece)
		{
			if ((Object)(object)piece == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)piece).GetInstanceID();
			if (!_pieceLookup.TryGetValue(instanceID, out TrackedInteriorPiece value))
			{
				return;
			}
			Renderer[] componentsInChildren = ((Component)piece).GetComponentsInChildren<Renderer>(true);
			value.Renderers.Clear();
			if (componentsInChildren == null)
			{
				return;
			}
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null)
				{
					value.Renderers.Add(val);
					if (value.IsCulled)
					{
						val.enabled = false;
					}
				}
			}
		}

		public static void RestoreAllRenderers()
		{
			for (int i = 0; i < _trackedPieces.Count; i++)
			{
				TrackedInteriorPiece trackedInteriorPiece = _trackedPieces[i];
				if (trackedInteriorPiece.IsCulled)
				{
					trackedInteriorPiece.SetRenderersEnabled(enabled: true);
					trackedInteriorPiece.IsCulled = false;
				}
			}
			_culledPieceCount = 0;
		}

		public static bool IsInteriorPiece(Piece piece)
		{
			//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Invalid comparison between Unknown and I4
			if ((Object)(object)piece == (Object)null || (Object)(object)((Component)piece).gameObject == (Object)null)
			{
				return false;
			}
			string text = ((Object)((Component)piece).gameObject).name.ToLowerInvariant();
			if (text.Contains("wall") || text.Contains("roof") || text.Contains("floor") || text.Contains("gate") || text.Contains("door") || text.Contains("window") || text.Contains("shutter") || text.Contains("beam") || text.Contains("pole") || text.Contains("pillar") || text.Contains("post") || text.Contains("arch") || text.Contains("stair") || text.Contains("ladder") || text.Contains("steps") || text.Contains("support") || text.Contains("foundation") || text.Contains("portal") || text.Contains("chimney") || text.Contains("stone_") || text.Contains("blackmarble_") || text.Contains("ashwood_wall") || text.Contains("ashwood_roof") || text.Contains("ashwood_floor") || text.Contains("turret") || text.Contains("ballista") || text.Contains("stake") || text.Contains("sharpstakes") || text.Contains("cart") || text.Contains("ship") || text.Contains("karve") || text.Contains("vikingboat") || text.Contains("cultivate") || text.Contains("sapling") || text.Contains("plant") || text.Contains("beehive") || text.Contains("windmill") || text.Contains("blastfurnace") || text.Contains("smelter") || text.Contains("kiln"))
			{
				return false;
			}
			if ((Object)(object)((Component)piece).GetComponent<Bed>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Chair>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Container>() != (Object)null || (Object)(object)((Component)piece).GetComponent<ItemStand>() != (Object)null || (Object)(object)((Component)piece).GetComponent<ArmorStand>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Sign>() != (Object)null)
			{
				return true;
			}
			if ((int)piece.m_category == 4)
			{
				return true;
			}
			if (piece.m_comfort > 0)
			{
				return true;
			}
			if (text.Contains("chest") || text.Contains("bed") || text.Contains("chair") || text.Contains("table") || text.Contains("bench") || text.Contains("stool") || text.Contains("throne") || text.Contains("couch") || text.Contains("rug") || text.Contains("carpet") || text.Contains("tapestry") || text.Contains("banner") || text.Contains("curtain") || text.Contains("sconce") || text.Contains("chandelier") || text.Contains("brazier") || text.Contains("lantern") || text.Contains("shelf") || text.Contains("cupboard") || text.Contains("bookcase") || text.Contains("cabinet") || text.Contains("drawer") || text.Contains("barrel") || text.Contains("cask") || text.Contains("bath") || text.Contains("tub") || text.Contains("hottub") || text.Contains("armorstand") || text.Contains("itemstand") || text.Contains("sign"))
			{
				return true;
			}
			return false;
		}

		public static bool IsEnclosedPiece(Piece piece)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)piece == (Object)null)
			{
				return false;
			}
			WearNTear component = ((Component)piece).GetComponent<WearNTear>();
			if ((Object)(object)component != (Object)null)
			{
				try
				{
					if (_haveRoofRef != null && _haveRoofRef.Invoke(component))
					{
						return true;
					}
					if (_haveAshRoofRef != null && _haveAshRoofRef.Invoke(component))
					{
						return true;
					}
				}
				catch
				{
				}
			}
			Vector3 val = ((Component)piece).transform.position + Vector3.up * 0.15f;
			int num = LayerMask.GetMask(new string[3] { "piece", "Default", "static_solid" });
			if (num == 0)
			{
				num = -1;
			}
			RaycastHit val2 = default(RaycastHit);
			if (Physics.Raycast(val, Vector3.up, ref val2, 25f, num, (QueryTriggerInteraction)1))
			{
				return true;
			}
			return false;
		}

		private static Vector3 GetReferencePosition()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				return ((Component)Player.m_localPlayer).transform.position;
			}
			Camera mainCamera = Utils.GetMainCamera();
			if ((Object)(object)mainCamera != (Object)null)
			{
				return ((Component)mainCamera).transform.position;
			}
			return Vector3.zero;
		}
	}
	[HarmonyPatch(typeof(OptiHousePlugin), "Awake")]
	public static class InteriorOcclusionOptimizer_Plugin_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(OptiHousePlugin __instance)
		{
			if ((Object)(object)__instance != (Object)null && (Object)(object)((Component)__instance).gameObject.GetComponent<InteriorOcclusionOptimizer>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<InteriorOcclusionOptimizer>();
			}
		}
	}
	[HarmonyPatch(typeof(Piece), "Awake")]
	public static class InteriorOcclusionOptimizer_Piece_Awake_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Piece __instance)
		{
			InteriorOcclusionOptimizer.RegisterPiece(__instance);
		}
	}
	[HarmonyPatch(typeof(Piece), "OnDestroy")]
	public static class InteriorOcclusionOptimizer_Piece_OnDestroy_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Piece __instance)
		{
			InteriorOcclusionOptimizer.UnregisterPiece(__instance);
		}
	}
	[HarmonyPatch(typeof(ItemStand), "UpdateVisual")]
	public static class InteriorOcclusionOptimizer_ItemStand_Visual_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(ItemStand __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				Piece component = ((Component)__instance).GetComponent<Piece>();
				if ((Object)(object)component != (Object)null)
				{
					InteriorOcclusionOptimizer.RefreshPiece(component);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ArmorStand), "UpdateVisual")]
	public static class InteriorOcclusionOptimizer_ArmorStand_Visual_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(ArmorStand __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				Piece component = ((Component)__instance).GetComponent<Piece>();
				if ((Object)(object)component != (Object)null)
				{
					InteriorOcclusionOptimizer.RefreshPiece(component);
				}
			}
		}
	}
	public class ItemDropOptimizer : MonoBehaviour
	{
		private static ItemDropOptimizer? _instance;

		private static readonly List<ItemDrop> _allItemDrops = new List<ItemDrop>();

		private static int _stackedItemsCount;

		private static int _sleepingRigidbodiesCount;

		private float _stackTimer;

		private float _physicsTimer;

		private int _lodIndex;

		public static ItemDropOptimizer? Instance => _instance;

		public static int TotalDroppedItems => _allItemDrops.Count;

		public static int MergedDropsCount => _stackedItemsCount;

		public static int SleepingItemsCount => _sleepingRigidbodiesCount;

		private void Awake()
		{
			_instance = this;
			ScanExistingDrops();
		}

		private void OnDestroy()
		{
			_allItemDrops.Clear();
			_stackedItemsCount = 0;
			_sleepingRigidbodiesCount = 0;
			if ((Object)(object)_instance == (Object)(object)this)
			{
				_instance = null;
			}
		}

		public static void ScanExistingDrops()
		{
			ItemDrop[] array = Object.FindObjectsByType<ItemDrop>((FindObjectsSortMode)0);
			if (array != null)
			{
				for (int i = 0; i < array.Length; i++)
				{
					RegisterItemDrop(array[i]);
				}
			}
		}

		public static void RegisterItemDrop(ItemDrop drop)
		{
			if (!((Object)(object)drop == (Object)null) && !_allItemDrops.Contains(drop))
			{
				_allItemDrops.Add(drop);
			}
		}

		public static void UnregisterItemDrop(ItemDrop drop)
		{
			if (!((Object)(object)drop == (Object)null))
			{
				_allItemDrops.Remove(drop);
			}
		}

		private void Update()
		{
			if (!OptiHousePlugin.IsOptimizationActive || ModConfig.EnableItemDropOptimization == null || !ModConfig.EnableItemDropOptimization.Value)
			{
				return;
			}
			float deltaTime = Time.deltaTime;
			if (ModConfig.EnableAutoStackNearbyItems != null && ModConfig.EnableAutoStackNearbyItems.Value)
			{
				_stackTimer += deltaTime;
				if (_stackTimer >= 2.5f)
				{
					_stackTimer = 0f;
					ProcessAutoStacking();
				}
			}
			_physicsTimer += deltaTime;
			if (_physicsTimer >= 0.5f)
			{
				_physicsTimer = 0f;
				ProcessPhysicsSleepAndLOD();
			}
		}

		private void ProcessAutoStacking()
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			if (_allItemDrops.Count < 2)
			{
				return;
			}
			float num = ((ModConfig.AutoStackRadius != null) ? ModConfig.AutoStackRadius.Value : 3.5f);
			float num2 = num * num;
			_allItemDrops.RemoveAll((ItemDrop d) => (Object)(object)d == (Object)null || (Object)(object)((Component)d).gameObject == (Object)null);
			for (int num3 = 0; num3 < _allItemDrops.Count; num3++)
			{
				ItemDrop val = _allItemDrops[num3];
				if ((Object)(object)val == (Object)null || val.m_itemData == null)
				{
					continue;
				}
				ZNetView component = ((Component)val).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					continue;
				}
				int maxStackSize = val.m_itemData.m_shared.m_maxStackSize;
				if (maxStackSize <= 1 || val.m_itemData.m_stack >= maxStackSize)
				{
					continue;
				}
				Vector3 position = ((Component)val).transform.position;
				string name = val.m_itemData.m_shared.m_name;
				int quality = val.m_itemData.m_quality;
				int variant = val.m_itemData.m_variant;
				for (int num4 = num3 + 1; num4 < _allItemDrops.Count; num4++)
				{
					ItemDrop val2 = _allItemDrops[num4];
					if ((Object)(object)val2 == (Object)null || val2.m_itemData == null)
					{
						continue;
					}
					ZNetView component2 = ((Component)val2).GetComponent<ZNetView>();
					if ((Object)(object)component2 == (Object)null || !component2.IsValid() || val2.m_itemData.m_shared.m_name != name || val2.m_itemData.m_quality != quality || val2.m_itemData.m_variant != variant)
					{
						continue;
					}
					Vector3 val3 = ((Component)val2).transform.position - position;
					if (!(((Vector3)(ref val3)).sqrMagnitude <= num2))
					{
						continue;
					}
					int num5 = Mathf.Min(maxStackSize - val.m_itemData.m_stack, val2.m_itemData.m_stack);
					if (num5 <= 0)
					{
						continue;
					}
					val.SetStack(val.m_itemData.m_stack + num5);
					if (val2.m_itemData.m_stack <= num5)
					{
						if (!component2.IsOwner())
						{
							component2.ClaimOwnership();
						}
						if ((Object)(object)ZNetScene.instance != (Object)null)
						{
							ZNetScene.instance.Destroy(((Component)val2).gameObject);
						}
						else
						{
							Object.Destroy((Object)(object)((Component)val2).gameObject);
						}
						_stackedItemsCount++;
					}
					else
					{
						val2.SetStack(val2.m_itemData.m_stack - num5);
					}
					if (val.m_itemData.m_stack >= maxStackSize)
					{
						break;
					}
				}
			}
		}

		private void ProcessPhysicsSleepAndLOD()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			if (_allItemDrops.Count == 0)
			{
				return;
			}
			Vector3 referencePosition = GetReferencePosition();
			float num = ((ModConfig.DroppedItemVfxCullDistance != null) ? ModConfig.DroppedItemVfxCullDistance.Value : 15f);
			float num2 = num * num;
			bool flag = ModConfig.EnableDroppedItemPhysicsSleep != null && ModConfig.EnableDroppedItemPhysicsSleep.Value;
			int num3 = 0;
			int count = _allItemDrops.Count;
			int num4 = Mathf.Min(100, count);
			for (int i = 0; i < num4; i++)
			{
				_lodIndex++;
				if (_lodIndex >= _allItemDrops.Count)
				{
					_lodIndex = 0;
				}
				ItemDrop val = _allItemDrops[_lodIndex];
				if ((Object)(object)val == (Object)null || (Object)(object)((Component)val).gameObject == (Object)null)
				{
					continue;
				}
				Vector3 val2;
				if (flag)
				{
					Rigidbody component = ((Component)val).GetComponent<Rigidbody>();
					if ((Object)(object)component != (Object)null && !component.isKinematic)
					{
						if (component.IsSleeping())
						{
							num3++;
						}
						else
						{
							val2 = component.velocity;
							if (((Vector3)(ref val2)).sqrMagnitude < 0.04f)
							{
								val2 = component.angularVelocity;
								if (((Vector3)(ref val2)).sqrMagnitude < 0.04f)
								{
									component.Sleep();
									num3++;
								}
							}
						}
					}
				}
				val2 = ((Component)val).transform.position - referencePosition;
				bool flag2 = ((Vector3)(ref val2)).sqrMagnitude > num2;
				ParticleSystem[] componentsInChildren = ((Component)val).GetComponentsInChildren<ParticleSystem>(true);
				foreach (ParticleSystem val3 in componentsInChildren)
				{
					if (!((Object)(object)val3 == (Object)null))
					{
						if (flag2 && val3.isPlaying)
						{
							val3.Pause();
						}
						else if (!flag2 && val3.isPaused)
						{
							val3.Play();
						}
					}
				}
				Floating component2 = ((Component)val).GetComponent<Floating>();
				if ((Object)(object)component2 != (Object)null)
				{
					((Behaviour)component2).enabled = !flag2;
				}
			}
			_sleepingRigidbodiesCount = num3;
		}

		private static Vector3 GetReferencePosition()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				return ((Component)Player.m_localPlayer).transform.position;
			}
			Camera mainCamera = Utils.GetMainCamera();
			if ((Object)(object)mainCamera != (Object)null)
			{
				return ((Component)mainCamera).transform.position;
			}
			return Vector3.zero;
		}
	}
	[HarmonyPatch(typeof(OptiHousePlugin), "Awake")]
	public static class ItemDropOptimizer_Plugin_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(OptiHousePlugin __instance)
		{
			if ((Object)(object)__instance != (Object)null && (Object)(object)((Component)__instance).gameObject.GetComponent<ItemDropOptimizer>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<ItemDropOptimizer>();
			}
		}
	}
	[HarmonyPatch(typeof(ItemDrop), "Awake")]
	public static class ItemDropOptimizer_Awake_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(ItemDrop __instance)
		{
			ItemDropOptimizer.RegisterItemDrop(__instance);
		}
	}
	[HarmonyPatch(typeof(ItemDrop), "OnDestroy")]
	public static class ItemDropOptimizer_OnDestroy_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(ItemDrop __instance)
		{
			ItemDropOptimizer.UnregisterItemDrop(__instance);
		}
	}
	public class ItemStandOptimizer : MonoBehaviour
	{
		private class TrackedStand
		{
			public Component Stand;

			public Transform Transform;

			public bool IsArmorStand;

			public bool IsCulled;

			public readonly List<ParticleSystem> Particles = new List<ParticleSystem>();

			public readonly List<ParticleSystemRenderer> ParticleRend