Decompiled source of flashlight as antifog v1.0.0

flashlight-antifog.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using Agents;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CullingSystem;
using GameData;
using Gear;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using Player;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("flashlight-antifog")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+fbbc0a23649aa9bb6895862d8fc61262aaf1d5f4")]
[assembly: AssemblyProduct("flashlight-antifog")]
[assembly: AssemblyTitle("flashlight-antifog")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FlashlightAntifog
{
	public sealed class FlashlightFogCut : MonoBehaviour
	{
		private FogCutWork _work;

		private void LateUpdate()
		{
			if (_work == null)
			{
				_work = new FogCutWork();
			}
			_work.Tick();
		}

		private void OnDestroy()
		{
			if (_work != null)
			{
				_work.Dispose();
			}
		}
	}
	internal sealed class FogCutWork
	{
		private struct SphereWrite
		{
			public Vector3 Position;

			public float Radius;

			public float Density;

			public bool RadianceSet;

			public bool Valid;
		}

		private struct WallCast
		{
			public int AgentId;

			public Vector3 Origin;

			public Vector3 Direction;

			public float Reach;

			public float Stopped;

			public float NextTime;

			public bool Valid;
		}

		private struct Sample
		{
			public Vector3 Position;

			public float Radius;

			public float Density;

			public int Beam;
		}

		private struct Site
		{
			public Vector3 Position;

			public float Radius;

			public float Density;

			public float Charge;

			public float AbsentFor;

			public float Missed;

			public float Fade;

			public bool Alive;

			public bool Covered;

			public bool Drawn;

			public int Beam;
		}

		private const int MaxBeam = 12;

		private const int MaxSamples = 48;

		private const int MaxDrawn = 24;

		private const float MissGrace = 0.12f;

		private const float EstablishedCharge = 0.35f;

		private const float OriginBias = 0.35f;

		private const float MinRadius = 0.2f;

		private const float ChainStart = 0.45f;

		private const float TunnelRadius = 2.6f;

		private const float Overlap = 1.2f;

		private const float DensityScale = 8f;

		private const float ReferenceBrightness = 1f;

		private const float ReferenceReach = 14f;

		private const float MaxClear = 64f;

		private const float MinClear = 4f;

		private const float NearSkip = 0.75f;

		private const float CastInterval = 0.1f;

		private const float CastMoveSqr = 0.0001f;

		private const float CastDirDot = 0.9998f;

		private const float PositionMoveSqr = 0.0004f;

		private const float RadiusEpsilon = 0.02f;

		private const int MaxSites = 32;

		private readonly List<FogSphereAllocator> _pool = new List<FogSphereAllocator>(24);

		private readonly SphereWrite[] _written = new SphereWrite[24];

		private readonly WallCast[] _casts = new WallCast[8];

		private readonly Sample[] _samples = new Sample[48];

		private readonly Site[] _sites = new Site[32];

		private int _sampleCount;

		private float _openReach;

		private float _beamRange;

		private float _loggedBrightness;

		private float _loggedRange;

		private int _beamLogs;

		private int _used;

		private int _beamMask;

		private bool _beamMaskReady;

		private bool _loggedBudget;

		private bool _loggedFailure;

		public void Tick()
		{
			//IL_0116: 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)
			try
			{
				_used = 0;
				if (!Plugin.CutFog.Value)
				{
					ClearSites();
					ReleaseUnused();
					return;
				}
				List<PlayerAgent> playerAgentsInLevel = PlayerManager.PlayerAgentsInLevel;
				if (playerAgentsInLevel == null || playerAgentsInLevel.Count == 0 || (Object)(object)PreLitVolume.Current == (Object)null)
				{
					ClearSites();
					ReleaseUnused();
					return;
				}
				float num = Plugin.CutDensity.Value * 8f;
				if (Mathf.Abs(num) < 0.0001f)
				{
					ClearSites();
					ReleaseUnused();
					return;
				}
				LogBudgetOnce();
				_sampleCount = 0;
				bool value = Plugin.CutShared.Value;
				int num2 = (value ? 48 : 12);
				int count = playerAgentsInLevel.Count;
				for (int i = 0; i < 2; i++)
				{
					if (_sampleCount >= num2)
					{
						break;
					}
					for (int j = 0; j < count; j++)
					{
						if (_sampleCount >= num2)
						{
							break;
						}
						PlayerAgent val = playerAgentsInLevel[j];
						if ((Object)(object)val == (Object)null || ((Agent)val).IsLocallyOwned != (i == 0))
						{
							continue;
						}
						PlayerInventoryBase inventory = val.Inventory;
						if (!((Object)(object)inventory == (Object)null) && TryGetBeam(val, inventory, out var origin, out var direction, out var reach, out var brightness))
						{
							int num3 = ((Object)val).GetInstanceID();
							if (num3 == 0)
							{
								num3 = j + 1;
							}
							PlaceChain(origin, direction, reach, brightness, num, num3, value);
						}
					}
				}
				float num4 = Time.deltaTime;
				if (num4 < 0f)
				{
					num4 = 0f;
				}
				else if (num4 > 0.1f)
				{
					num4 = 0.1f;
				}
				float num5 = Plugin.CutDelay.Value;
				if (num5 < 0f)
				{
					num5 = 0f;
				}
				float num6 = Plugin.CutHold.Value;
				if (num6 < 0f)
				{
					num6 = 0f;
				}
				float num7 = Plugin.CutReturn.Value;
				if (num7 < 0f)
				{
					num7 = 0f;
				}
				SettleSites(num4, num5, num6, num7, value);
				FitTrail();
				WriteSites();
				ReleaseUnused();
			}
			catch (Exception ex)
			{
				if (!_loggedFailure)
				{
					_loggedFailure = true;
					Plugin.Logger.LogError((object)("Flashlight fog cut failed: " + ex));
					ReleaseUnused();
				}
			}
		}

		public void Dispose()
		{
			for (int i = 0; i < _pool.Count; i++)
			{
				FogSphereAllocator val = _pool[i];
				if (val != null && val.IsAllocated)
				{
					val.Deallocate();
				}
			}
			_pool.Clear();
		}

		private void LogBudgetOnce()
		{
			if (!_loggedBudget)
			{
				_loggedBudget = true;
				Plugin.Logger.LogInfo((object)("Fog sphere slots: " + PreLitVolume.SUPPORTED_FOG_SPHERE_COUNT + ". Flashlight draws at most " + 24 + "."));
			}
		}

		private static bool IsFlashlightOn(PlayerInventoryBase inventory)
		{
			if (inventory.FlashlightEnabled)
			{
				return true;
			}
			MeshRenderer flashlightConeRenderer = inventory.m_flashlightConeRenderer;
			if ((Object)(object)flashlightConeRenderer != (Object)null && ((Renderer)flashlightConeRenderer).enabled)
			{
				return ((Component)flashlightConeRenderer).gameObject.activeInHierarchy;
			}
			return false;
		}

		private bool TryGetBeam(PlayerAgent agent, PlayerInventoryBase inventory, out Vector3 origin, out Vector3 direction, out float reach, out float brightness)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: 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)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			origin = default(Vector3);
			direction = default(Vector3);
			reach = 0f;
			brightness = 0f;
			if (!IsFlashlightOn(inventory))
			{
				return false;
			}
			Light val = inventory.m_flashlight;
			C_LightDynamic flashlightCLight = inventory.m_flashlightCLight;
			if (flashlightCLight != null && (Object)(object)((C_Light)flashlightCLight).m_unityLight != (Object)null)
			{
				val = ((C_Light)flashlightCLight).m_unityLight;
			}
			bool flag = false;
			if (flashlightCLight != null)
			{
				Vector3 forward = ((C_Light)flashlightCLight).m_forward;
				if (((Vector3)(ref forward)).sqrMagnitude > 0.01f)
				{
					direction = ((C_Light)flashlightCLight).m_forward;
					origin = ((C_Light)flashlightCLight).m_position;
					flag = true;
					goto IL_00b5;
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				direction = ((Component)val).transform.forward;
				origin = ((Component)val).transform.position;
				flag = true;
			}
			goto IL_00b5;
			IL_00b5:
			if (!flag || ((Vector3)(ref direction)).sqrMagnitude < 0.0001f)
			{
				return false;
			}
			((Vector3)(ref direction)).Normalize();
			MeasureBeam(inventory, val, (C_Light)(object)flashlightCLight, out brightness, out var hardwareRange);
			float num = Modifier(Plugin.CutLength.Value);
			float num2 = 14f * Mathf.Sqrt(brightness / 1f) * num;
			float num3 = hardwareRange * num;
			float num4 = ((num2 > num3) ? num2 : num3);
			float num5 = 4f * num;
			if (num4 < num5)
			{
				num4 = num5;
			}
			float num6 = 64f * num;
			if (num4 > num6)
			{
				num4 = num6;
			}
			_beamRange = hardwareRange;
			origin += direction * 0.35f;
			reach = Mathf.Max(num4 - 0.35f, 1f);
			_openReach = reach;
			reach = StopAtGeometry(((Object)agent).GetInstanceID(), ((Component)agent).transform, origin, direction, reach);
			return reach > 0.2f;
		}

		private static void MeasureBeam(PlayerInventoryBase inventory, Light light, C_Light clustered, out float brightness, out float hardwareRange)
		{
			//IL_0030: 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_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_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			brightness = 1f;
			hardwareRange = 20f;
			if ((Object)(object)light != (Object)null)
			{
				if (light.range > 1f)
				{
					hardwareRange = light.range;
				}
				brightness = Luminance(light.color, light.intensity);
			}
			GearPartFlashlight currentGearPartFlashlight = inventory.m_currentGearPartFlashlight;
			if ((Object)(object)currentGearPartFlashlight != (Object)null && GameDataBlockBase<FlashlightSettingsDataBlock>.HasBlock(currentGearPartFlashlight.m_settingsID))
			{
				FlashlightSettingsDataBlock block = GameDataBlockBase<FlashlightSettingsDataBlock>.GetBlock(currentGearPartFlashlight.m_settingsID);
				if (block != null)
				{
					float num = Luminance(block.color, block.intensity);
					if (num > brightness)
					{
						brightness = num;
					}
					if (block.range > hardwareRange)
					{
						hardwareRange = block.range;
					}
				}
			}
			if (clustered == null || (Object)(object)clustered.m_clusterLight == (Object)null)
			{
				return;
			}
			CL_SpotLight val = ((Il2CppObjectBase)clustered.m_clusterLight).TryCast<CL_SpotLight>();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			sCL_SpotLight data = val.Data;
			float magnitude = ((Vector3)(ref data.Irradiance)).magnitude;
			if (magnitude > brightness)
			{
				brightness = magnitude;
			}
			else
			{
				float x = val.m_lightScale.x;
				if (x > 1f)
				{
					brightness *= x;
				}
			}
			if (data.InvRangeSqr > 1E-06f)
			{
				float num2 = 1f / Mathf.Sqrt(data.InvRangeSqr);
				if (num2 > hardwareRange && num2 < 64f)
				{
					hardwareRange = num2;
				}
			}
		}

		private static float Luminance(Color color, float intensity)
		{
			float num = ((Color)(ref color)).grayscale;
			if (num < 0.05f)
			{
				num = 0.05f;
			}
			float num2 = intensity;
			if (num2 < 0.01f)
			{
				num2 = 0.01f;
			}
			return num2 * num;
		}

		private static float Modifier(float value)
		{
			if (value < 0.05f)
			{
				return 0.05f;
			}
			return value;
		}

		private int BeamMask()
		{
			if (_beamMaskReady)
			{
				return _beamMask;
			}
			int mask = -5;
			mask = ExcludeLayer(mask, "PlayerSynced");
			mask = ExcludeLayer(mask, "PlayerMover");
			mask = ExcludeLayer(mask, "FirstPersonItem");
			mask = (_beamMask = ExcludeLayer(mask, "ThirdPersonItem"));
			_beamMaskReady = true;
			return mask;
		}

		private static int ExcludeLayer(int mask, string layerName)
		{
			int num = LayerMask.NameToLayer(layerName);
			if (num < 0)
			{
				return mask;
			}
			return mask & ~(1 << num);
		}

		private int FindCast(int agentId)
		{
			int num = -1;
			for (int i = 0; i < _casts.Length; i++)
			{
				if (_casts[i].Valid && _casts[i].AgentId == agentId)
				{
					return i;
				}
				if (num < 0 && !_casts[i].Valid)
				{
					num = i;
				}
			}
			if (num < 0)
			{
				return 0;
			}
			return num;
		}

		private float StopAtGeometry(int agentId, Transform holder, Vector3 origin, Vector3 direction, float reach)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			int num = FindCast(agentId);
			ref WallCast reference = ref _casts[num];
			int num2;
			int num3;
			if (reference.Valid)
			{
				num2 = ((reference.AgentId == agentId) ? 1 : 0);
				if (num2 != 0)
				{
					Vector3 val = origin - reference.Origin;
					num3 = ((((Vector3)(ref val)).sqrMagnitude > 0.0001f || Vector3.Dot(direction, reference.Direction) < 0.9998f || Mathf.Abs(reference.Reach - reach) > 0.05f) ? 1 : 0);
					goto IL_0077;
				}
			}
			else
			{
				num2 = 0;
			}
			num3 = 0;
			goto IL_0077;
			IL_0077:
			bool flag = (byte)num3 != 0;
			if (num2 != 0 && !flag && Time.time < reference.NextTime)
			{
				return Mathf.Min(reference.Stopped, reach);
			}
			float num4 = CastPastHolder(holder, origin, direction, reach);
			reference.AgentId = agentId;
			reference.Origin = origin;
			reference.Direction = direction;
			reference.Reach = reach;
			reference.Stopped = num4;
			reference.NextTime = Time.time + 0.1f;
			reference.Valid = true;
			return num4;
		}

		private float CastPastHolder(Transform holder, Vector3 origin, Vector3 direction, float reach)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			float num = 0.75f;
			if (num > reach)
			{
				num = 0f;
			}
			float num2 = num;
			Vector3 val = origin + direction * num;
			float num3 = reach - num;
			int num4 = BeamMask();
			RaycastHit val2 = default(RaycastHit);
			for (int i = 0; i < 6; i++)
			{
				if (!(num3 > 0.05f))
				{
					break;
				}
				if (!Physics.Raycast(val, direction, ref val2, num3, num4, (QueryTriggerInteraction)1))
				{
					return reach;
				}
				if (!IsUnder(((RaycastHit)(ref val2)).collider, holder))
				{
					return num2 + ((RaycastHit)(ref val2)).distance;
				}
				float num5 = ((RaycastHit)(ref val2)).distance + 0.05f;
				if (num5 < 0.05f)
				{
					num5 = 0.05f;
				}
				num2 += num5;
				if (num2 >= reach)
				{
					return reach;
				}
				val += direction * num5;
				num3 -= num5;
			}
			return Mathf.Min(num2, reach);
		}

		private static bool IsUnder(Collider collider, Transform holder)
		{
			if ((Object)(object)collider == (Object)null || (Object)(object)holder == (Object)null)
			{
				return false;
			}
			Transform val = ((Component)collider).transform;
			int num = 0;
			while ((Object)(object)val != (Object)null && num < 32)
			{
				if ((Object)(object)val == (Object)(object)holder)
				{
					return true;
				}
				val = val.parent;
				num++;
			}
			return false;
		}

		private void PlaceChain(Vector3 origin, Vector3 direction, float reach, float brightness, float density, int beam, bool shared)
		{
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			float num = reach - 0.45f;
			int num2 = (shared ? 12 : (12 - _sampleCount));
			if (shared)
			{
				int num3 = 48 - _sampleCount;
				if (num2 > num3)
				{
					num2 = num3;
				}
			}
			if (num < 0.2f || num2 <= 0)
			{
				return;
			}
			int sampleCount = _sampleCount;
			float num4 = 2.6f * Modifier(Plugin.CutRadius.Value);
			float num5 = num4 * 1.2f;
			if (num5 < 0.2f)
			{
				num5 = 0.2f;
			}
			int num6 = Mathf.CeilToInt(num / num5);
			if (num6 < 1)
			{
				num6 = 1;
			}
			if (num6 > num2)
			{
				num6 = num2;
			}
			float num7 = num4 * 2.5f;
			bool flag = Mathf.Abs(_loggedBrightness - brightness) > 0.2f || Mathf.Abs(_loggedRange - _beamRange) > 2f;
			if (_beamLogs < 4 && (_beamLogs == 0 || flag))
			{
				_beamLogs++;
				_loggedBrightness = brightness;
				_loggedRange = _beamRange;
				Plugin.Logger.LogInfo((object)("Flashlight fog cut brightness " + brightness.ToString("0.00") + ", throw " + _beamRange.ToString("0.0") + " m. Open " + _openReach.ToString("0.0") + " m, after walls " + reach.ToString("0.0") + " m, spheres " + num6 + ", radius " + num4.ToString("0.0") + ", density " + density.ToString("0.0") + "."));
			}
			for (int i = 0; i < num6; i++)
			{
				float num8 = 0.45f + num5 * ((float)i + 0.5f);
				if (num8 >= reach)
				{
					if (i > 0)
					{
						break;
					}
					num8 = 0.45f + num * 0.5f;
				}
				float num9 = num4;
				float num10 = reach - num8;
				if (num9 > num10)
				{
					num9 = num10;
				}
				if (!(num9 < 0.2f))
				{
					_samples[_sampleCount] = new Sample
					{
						Position = origin + direction * num8,
						Radius = num9,
						Density = density,
						Beam = beam
					};
					_sampleCount++;
				}
			}
			if (_sampleCount > sampleCount)
			{
				int num11 = _sampleCount - 1;
				float num12 = Vector3.Dot(_samples[num11].Position - origin, direction);
				float num13 = reach - num12;
				float num14 = _samples[num11].Radius;
				if (num14 < num13)
				{
					num14 = num13;
				}
				if (num14 > num7)
				{
					num14 = num7;
				}
				float num15 = reach - num12;
				if (num14 > num15)
				{
					num14 = num15;
				}
				if (num14 < 0.2f)
				{
					num14 = 0.2f;
				}
				_samples[num11].Radius = num14;
			}
		}

		private float HitLimit(ref Site site)
		{
			float num = 2.6f * Modifier(Plugin.CutRadius.Value) * 1.2f;
			if (num < 0.2f)
			{
				num = 0.2f;
			}
			float num2 = num * 0.62f;
			float num3 = site.Radius * 0.75f;
			if (num3 > num2)
			{
				num3 = num2;
			}
			float num4 = num * 0.35f;
			if (num4 < 0.35f)
			{
				num4 = 0.35f;
			}
			if (num4 > num2)
			{
				num4 = num2;
			}
			if (num3 < num4)
			{
				num3 = num4;
			}
			return num3;
		}

		private bool Hits(ref Site site, Vector3 position)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			float num = HitLimit(ref site);
			Vector3 val = site.Position - position;
			return ((Vector3)(ref val)).sqrMagnitude <= num * num;
		}

		private bool Represents(ref Site site, Vector3 position)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if (!site.Alive)
			{
				return false;
			}
			if (Hits(ref site, position))
			{
				return true;
			}
			if (site.Missed >= 0.12f)
			{
				return false;
			}
			float num = site.Radius;
			if (num < 0.5f)
			{
				num = 0.5f;
			}
			Vector3 val = site.Position - position;
			return ((Vector3)(ref val)).sqrMagnitude <= num * num;
		}

		private static bool OtherBeamCovers(ref Site site, Vector3 position, float radius, int beam)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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)
			if (!site.Alive || site.Beam == 0 || beam == 0 || site.Beam == beam)
			{
				return false;
			}
			float num = site.Radius;
			if (num < radius)
			{
				num = radius;
			}
			Vector3 val = site.Position - position;
			return ((Vector3)(ref val)).sqrMagnitude <= num * num;
		}

		private static bool InBeam(ref Site site)
		{
			if (site.Alive)
			{
				if (!site.Covered)
				{
					return site.Missed < 0.12f;
				}
				return true;
			}
			return false;
		}

		private static float ChargeStep(float delay, float dt)
		{
			if (delay <= 0.001f)
			{
				return 1f;
			}
			return dt / delay;
		}

		private void SettleSites(float dt, float delay, float hold, float recover, bool shared)
		{
			//IL_0032: 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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Unknown result type (might be due to invalid IL or missing references)
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < 32; i++)
			{
				_sites[i].Covered = false;
			}
			for (int j = 0; j < _sampleCount; j++)
			{
				Vector3 position = _samples[j].Position;
				float density = _samples[j].Density;
				float radius = _samples[j].Radius;
				int beam = _samples[j].Beam;
				for (int k = 0; k < 32; k++)
				{
					ref Site reference = ref _sites[k];
					if (!reference.Alive)
					{
						continue;
					}
					bool num = Hits(ref reference, position);
					bool flag = shared && OtherBeamCovers(ref reference, position, radius, beam);
					if (!num && !flag)
					{
						continue;
					}
					reference.Covered = true;
					if (!flag)
					{
						reference.Density = density;
						if (radius > reference.Radius)
						{
							reference.Radius = radius;
						}
						if (reference.Beam == 0)
						{
							reference.Beam = beam;
						}
					}
				}
			}
			float num2 = ChargeStep(delay, dt);
			for (int l = 0; l < 32; l++)
			{
				ref Site reference2 = ref _sites[l];
				if (!reference2.Alive)
				{
					continue;
				}
				if (reference2.Covered)
				{
					reference2.Missed = 0f;
					float num3 = dt / 0.2f;
					if (num3 < num2)
					{
						num3 = num2;
					}
					if (num3 > 1f)
					{
						num3 = 1f;
					}
					reference2.Fade += num3;
					if (reference2.Fade > 1f)
					{
						reference2.Fade = 1f;
					}
					reference2.Charge += num2;
					if (reference2.Charge > 1f)
					{
						reference2.Charge = 1f;
					}
					if (reference2.Fade >= 1f)
					{
						reference2.AbsentFor = 0f;
					}
					continue;
				}
				reference2.Missed += dt;
				if (reference2.Missed < 0.12f)
				{
					continue;
				}
				reference2.AbsentFor += dt;
				if (reference2.AbsentFor > hold)
				{
					float num4 = ((recover > 0.001f) ? recover : 0.001f);
					float num5 = (reference2.AbsentFor - hold) / num4;
					if (num5 >= 1f)
					{
						reference2.Fade = 0f;
						reference2.Alive = false;
					}
					else
					{
						reference2.Fade = 1f - num5;
					}
				}
			}
			for (int m = 0; m < _sampleCount; m++)
			{
				Vector3 position2 = _samples[m].Position;
				float radius2 = _samples[m].Radius;
				int beam2 = _samples[m].Beam;
				if (shared && CoveredByOtherBeam(position2, radius2, beam2))
				{
					continue;
				}
				bool flag2 = false;
				for (int n = 0; n < 32; n++)
				{
					if (Represents(ref _sites[n], position2))
					{
						flag2 = true;
						break;
					}
				}
				if (!flag2)
				{
					int num6 = MakeSlot();
					if (num6 >= 0)
					{
						_sites[num6] = new Site
						{
							Position = position2,
							Radius = radius2,
							Density = _samples[m].Density,
							Charge = ((num2 > 1f) ? 1f : num2),
							AbsentFor = 0f,
							Missed = 0f,
							Fade = 1f,
							Alive = true,
							Covered = true,
							Beam = beam2
						};
					}
				}
			}
		}

		private bool CoveredByOtherBeam(Vector3 position, float radius, int beam)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < 32; i++)
			{
				if (OtherBeamCovers(ref _sites[i], position, radius, beam))
				{
					return true;
				}
			}
			return false;
		}

		private int FreeSite()
		{
			for (int i = 0; i < 32; i++)
			{
				if (!_sites[i].Alive)
				{
					return i;
				}
			}
			return -1;
		}

		private int MakeSlot()
		{
			int num = FreeSite();
			if (num >= 0)
			{
				return num;
			}
			if (TryMergeLingering())
			{
				num = FreeSite();
				if (num >= 0)
				{
					return num;
				}
			}
			return EvictLingering();
		}

		private int EvictLingering()
		{
			int num = -1;
			float num2 = 0f;
			for (int i = 0; i < 32; i++)
			{
				if (_sites[i].Alive && !InBeam(ref _sites[i]) && (num < 0 || !(_sites[i].AbsentFor <= num2)))
				{
					num = i;
					num2 = _sites[i].AbsentFor;
				}
			}
			if (num >= 0)
			{
				_sites[num].Alive = false;
			}
			return num;
		}

		private static float DrawnRadius(ref Site site)
		{
			return site.Radius * site.Charge * Mathf.Lerp(0.65f, 1f, site.Fade);
		}

		private static bool NeedsSphere(ref Site site)
		{
			if (Visible(ref site))
			{
				return DrawnRadius(ref site) >= 0.05f;
			}
			return false;
		}

		private int BeamSlots()
		{
			int num = 0;
			for (int i = 0; i < 32; i++)
			{
				if (InBeam(ref _sites[i]) && NeedsSphere(ref _sites[i]))
				{
					num++;
				}
			}
			return num;
		}

		private int LingeringSlots()
		{
			int num = 0;
			for (int i = 0; i < 32; i++)
			{
				if (!InBeam(ref _sites[i]) && NeedsSphere(ref _sites[i]))
				{
					num++;
				}
			}
			return num;
		}

		private void FitTrail()
		{
			int num = 32;
			while (num-- > 0)
			{
				int num2 = 24 - BeamSlots();
				if (num2 < 0)
				{
					num2 = 0;
				}
				if (LingeringSlots() <= num2 || !TryMergeLingering())
				{
					break;
				}
			}
		}

		private bool TryMergeLingering()
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			int num = -1;
			int drop = -1;
			float num2 = 0f;
			for (int i = 0; i < 32; i++)
			{
				if (InBeam(ref _sites[i]) || !NeedsSphere(ref _sites[i]))
				{
					continue;
				}
				for (int j = i + 1; j < 32; j++)
				{
					if (!InBeam(ref _sites[j]) && NeedsSphere(ref _sites[j]))
					{
						float num3 = Vector3.Distance(_sites[i].Position, _sites[j].Position);
						float num4 = _sites[i].Radius + _sites[j].Radius + 0.2f;
						if (!(num3 > num4) && (num < 0 || !(num3 >= num2)))
						{
							num = i;
							drop = j;
							num2 = num3;
						}
					}
				}
			}
			if (num < 0)
			{
				return false;
			}
			Unite(num, drop);
			return true;
		}

		private void Unite(int keep, int drop)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			ref Site reference = ref _sites[keep];
			ref Site reference2 = ref _sites[drop];
			Vector3 val = reference2.Position - reference.Position;
			float magnitude = ((Vector3)(ref val)).magnitude;
			bool num = magnitude < 0.001f || magnitude + reference.Radius <= reference2.Radius;
			bool flag = magnitude >= 0.001f && magnitude + reference2.Radius > reference.Radius && magnitude + reference.Radius > reference2.Radius;
			if (num && reference2.Radius > reference.Radius)
			{
				reference.Position = reference2.Position;
				reference.Radius = reference2.Radius;
			}
			else if (flag)
			{
				float num2 = (magnitude + reference.Radius + reference2.Radius) * 0.5f;
				ref Vector3 position = ref reference.Position;
				position += val * ((num2 - reference.Radius) / magnitude);
				reference.Radius = num2;
			}
			if (reference2.Charge > reference.Charge)
			{
				reference.Charge = reference2.Charge;
			}
			if (reference2.Fade > reference.Fade)
			{
				reference.Fade = reference2.Fade;
			}
			if (reference2.AbsentFor < reference.AbsentFor)
			{
				reference.AbsentFor = reference2.AbsentFor;
			}
			if (reference2.Missed < reference.Missed)
			{
				reference.Missed = reference2.Missed;
			}
			if (Mathf.Abs(reference2.Density) > Mathf.Abs(reference.Density))
			{
				reference.Density = reference2.Density;
			}
			if (reference2.Covered)
			{
				reference.Covered = true;
			}
			reference2.Alive = false;
		}

		private void WriteSites()
		{
			for (int i = 0; i < 32; i++)
			{
				_sites[i].Drawn = false;
			}
			if (DrawPass(inBeam: true, established: true) && DrawPass(inBeam: false, established: true) && DrawPass(inBeam: true, established: false))
			{
				DrawPass(inBeam: false, established: false);
			}
		}

		private bool DrawPass(bool inBeam, bool established)
		{
			while (_used < 24)
			{
				int num = -1;
				float num2 = 0f;
				for (int i = 0; i < 32; i++)
				{
					ref Site reference = ref _sites[i];
					if (!reference.Drawn && InBeam(ref reference) == inBeam && NeedsSphere(ref reference) && reference.Charge >= 0.35f == established && (num < 0 || !(reference.AbsentFor >= num2)))
					{
						num = i;
						num2 = reference.AbsentFor;
					}
				}
				if (num < 0)
				{
					return true;
				}
				if (!Draw(ref _sites[num]))
				{
					return false;
				}
			}
			return true;
		}

		private static bool Visible(ref Site site)
		{
			if (site.Alive && site.Charge > 0.02f)
			{
				return site.Fade > 0.02f;
			}
			return false;
		}

		private bool Draw(ref Site site)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			site.Drawn = true;
			float num = DrawnRadius(ref site);
			if (num < 0.05f)
			{
				return true;
			}
			if (!Rent(out var allocator, out var slot))
			{
				return false;
			}
			ApplySphere(allocator, slot, site.Position, num, site.Density * site.Fade);
			return true;
		}

		private void ClearSites()
		{
			for (int i = 0; i < 32; i++)
			{
				_sites[i].Alive = false;
			}
			_sampleCount = 0;
		}

		private void ApplySphere(FogSphereAllocator allocator, int slot, Vector3 position, float radius, float density)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			ref SphereWrite reference = ref _written[slot];
			if (reference.Valid)
			{
				Vector3 val = reference.Position - position;
				if (!(((Vector3)(ref val)).sqrMagnitude > 0.0004f) && !(Mathf.Abs(reference.Radius - radius) > 0.02f))
				{
					goto IL_005d;
				}
			}
			allocator.SetPositionRange(position, radius);
			reference.Position = position;
			reference.Radius = radius;
			goto IL_005d;
			IL_005d:
			if (!reference.Valid || reference.Density != density)
			{
				allocator.SetDensity(density);
				reference.Density = density;
			}
			if (!reference.Valid || !reference.RadianceSet)
			{
				allocator.SetRadiance(Color.white, 0.02f);
				reference.RadianceSet = true;
			}
			reference.Valid = true;
		}

		private bool Rent(out FogSphereAllocator allocator, out int slot)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			slot = _used;
			if (_used < _pool.Count)
			{
				allocator = _pool[_used];
			}
			else
			{
				allocator = new FogSphereAllocator();
				_pool.Add(allocator);
			}
			bool flag = !allocator.IsAllocated;
			if (flag && !allocator.TryAllocate())
			{
				if (!_loggedFailure)
				{
					_loggedFailure = true;
					Plugin.Logger.LogWarning((object)"No free fog-sphere slot for the flashlight. A repeller or turbine is using the remaining slots.");
				}
				return false;
			}
			if (flag)
			{
				_written[slot].Valid = false;
				_written[slot].RadianceSet = false;
			}
			_used++;
			return true;
		}

		private void ReleaseUnused()
		{
			for (int i = _used; i < _pool.Count; i++)
			{
				FogSphereAllocator val = _pool[i];
				if (val != null && val.IsAllocated)
				{
					val.Deallocate();
				}
				if (i < _written.Length)
				{
					_written[i].Valid = false;
					_written[i].RadianceSet = false;
				}
			}
		}
	}
	[BepInPlugin("flashlight-antifog", "flashlight-antifog", "1.4.6")]
	public sealed class Plugin : BasePlugin
	{
		public const string Guid = "flashlight-antifog";

		internal static ManualLogSource Logger;

		internal static ConfigEntry<bool> CutFog;

		internal static ConfigEntry<float> CutDensity;

		internal static ConfigEntry<float> CutLength;

		internal static ConfigEntry<float> CutRadius;

		internal static ConfigEntry<float> CutDelay;

		internal static ConfigEntry<float> CutHold;

		internal static ConfigEntry<float> CutReturn;

		internal static ConfigEntry<bool> CutShared;

		public override void Load()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected O, but got Unknown
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Expected O, but got Unknown
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			CutFog = ((BasePlugin)this).Config.Bind<bool>("Flashlight", "Cut fog in the beam", true, "While a flashlight is on, carve fog along the beam the same way a fog repeller or heavy fog turbine does. How far the carve reaches follows the light's brightness and how far that light throws, so a long range flashlight clears farther than a weapon light. Anti-fog delay, Anti-fog full clear, and Anti-fog return period decide when a lit spot clears, how long it stays fully clear, and how long fog takes to fill back in.");
			CutDensity = ((BasePlugin)this).Config.Bind<float>("Flashlight", "Cut density", -6f, "How hard the beam clears fog. Negative values remove it. Positive - will produce instead");
			CutLength = ((BasePlugin)this).Config.Bind<float>("Flashlight", "Cut length modifier", 1.5f, new ConfigDescription("Multiplies how far the flashlight clears fog. 1 keeps the distance from the light's brightness and throw. Walls still stop the carve.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 5f), Array.Empty<object>()));
			CutRadius = ((BasePlugin)this).Config.Bind<float>("Flashlight", "Cut radius modifier", 1.2f, new ConfigDescription("Multiplies how wide the cleared tunnel is. 1 is the normal width. This does not change how far the carve reaches.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 5f), Array.Empty<object>()));
			CutDelay = ((BasePlugin)this).Config.Bind<float>("Flashlight", "Anti-fog delay", 1.5f, new ConfigDescription("Seconds a lit spot takes to reach a full clear. The hole grows in that spot while the light is on it. 0 uses the full size immediately.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 15f), Array.Empty<object>()));
			float num = 0f;
			float num2 = 2.2f;
			ConfigEntry<float> val = default(ConfigEntry<float>);
			if (((BasePlugin)this).Config.TryGetEntry<float>("Flashlight", "Anti-fog persist period", ref val))
			{
				num = val.Value;
				num2 = val.Value;
				((BasePlugin)this).Config.Remove(((ConfigEntryBase)val).Definition);
			}
			CutHold = ((BasePlugin)this).Config.Bind<float>("Flashlight", "Anti-fog full clear", num, new ConfigDescription("Duration in seconds, when a spot stays fully clear after the flashlight leaves it. 0 starts the return as soon as the light moves off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 15f), Array.Empty<object>()));
			CutReturn = ((BasePlugin)this).Config.Bind<float>("Flashlight", "Anti-fog return period", num2, new ConfigDescription("Seconds fog takes to fill a spot back in after the full clear ends. 0 fills that spot back at once.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 15f), Array.Empty<object>()));
			CutShared = ((BasePlugin)this).Config.Bind<bool>("Flashlight", "Additive light antifog", true, "Flashlights that shine on the same place clear it at the strength and speed of a single beam. Set this to false and every beam adds its own clear on the same spot.");
			ClassInjector.RegisterTypeInIl2Cpp<FlashlightFogCut>();
			((BasePlugin)this).AddComponent<FlashlightFogCut>();
			Logger.LogInfo((object)"flashlight-antifog loaded.");
		}
	}
}