Decompiled source of PocketBeam v1.0.1

PocketBeam.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering.HighDefinition;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("PocketBeam")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("PocketBeam")]
[assembly: AssemblyTitle("PocketBeam")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PocketBeam
{
	internal class LightRig
	{
		private GameObject lightObj;

		private Light lightComp;

		private HDAdditionalLightData hdData;

		private float appliedIntensity = -1f;

		private float appliedRange = -1f;

		private float appliedAngle = -1f;

		private bool appliedShadows;

		private Color appliedColor;

		private bool hasApplied;

		public PlayerControllerB Player { get; private set; }

		public bool IsAlive
		{
			get
			{
				if ((Object)(object)lightObj != (Object)null)
				{
					return (Object)(object)lightComp != (Object)null;
				}
				return false;
			}
		}

		public static LightRig Create(PlayerControllerB player, bool local)
		{
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Expected O, but got Unknown
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null)
			{
				return null;
			}
			bool flag = false;
			Transform val;
			if (local && (Object)(object)player.gameplayCamera != (Object)null)
			{
				val = ((Component)player.gameplayCamera).transform;
			}
			else if ((Object)(object)player.helmetLight != (Object)null && (Object)(object)((Component)player.helmetLight).transform.parent != (Object)null)
			{
				val = ((Component)player.helmetLight).transform.parent;
				flag = true;
			}
			else
			{
				val = (((Object)(object)player.gameplayCamera != (Object)null) ? ((Component)player.gameplayCamera).transform : ((Component)player).transform);
			}
			LightRig lightRig = new LightRig
			{
				Player = player
			};
			if ((Object)(object)player.helmetLight != (Object)null)
			{
				lightRig.lightObj = Object.Instantiate<GameObject>(((Component)player.helmetLight).gameObject, val, false);
				Component[] components = lightRig.lightObj.GetComponents<Component>();
				foreach (Component val2 in components)
				{
					if (!((Object)(object)val2 == (Object)null) && !(val2 is Transform) && !(((object)val2).GetType().Namespace ?? string.Empty).StartsWith("UnityEngine"))
					{
						Object.Destroy((Object)(object)val2);
					}
				}
				for (int num = lightRig.lightObj.transform.childCount - 1; num >= 0; num--)
				{
					Object.Destroy((Object)(object)((Component)lightRig.lightObj.transform.GetChild(num)).gameObject);
				}
			}
			else
			{
				lightRig.lightObj = new GameObject();
				lightRig.lightObj.transform.SetParent(val, false);
				lightRig.lightObj.AddComponent<Light>();
				lightRig.lightObj.AddComponent<HDAdditionalLightData>();
			}
			((Object)lightRig.lightObj).name = "PocketBeamLight";
			if (!flag)
			{
				lightRig.lightObj.transform.localPosition = (((Object)(object)val == (Object)(object)((Component)player).transform) ? new Vector3(0f, 2.2f, 0.2f) : new Vector3(0f, -0.05f, 0.05f));
				lightRig.lightObj.transform.localRotation = Quaternion.identity;
			}
			lightRig.lightObj.SetActive(true);
			lightRig.lightComp = lightRig.lightObj.GetComponent<Light>();
			lightRig.hdData = lightRig.lightObj.GetComponent<HDAdditionalLightData>();
			if ((Object)(object)lightRig.lightComp == (Object)null)
			{
				lightRig.Destroy();
				return null;
			}
			lightRig.lightComp.type = (LightType)0;
			((Behaviour)lightRig.lightComp).enabled = false;
			return lightRig;
		}

		public void Apply(bool on, float intensity, float range, float angle, Color color, bool shadows)
		{
			//IL_0141: 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_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)lightComp == (Object)null)
			{
				return;
			}
			intensity = Mathf.Max(0f, intensity);
			range = Mathf.Max(0.5f, range);
			angle = Mathf.Clamp(angle, 10f, 170f);
			if (!hasApplied || Mathf.Abs(intensity - appliedIntensity) > 0.5f || range != appliedRange || angle != appliedAngle || shadows != appliedShadows || color != appliedColor)
			{
				if ((Object)(object)hdData != (Object)null)
				{
					try
					{
						hdData.intensity = intensity;
						hdData.range = range;
						hdData.SetSpotAngle(angle, 0f);
						hdData.EnableShadows(shadows);
					}
					catch (Exception ex)
					{
						Plugin.Log.LogWarning((object)("HDRP light settings failed, using basic light settings: " + ex.Message));
						hdData = null;
					}
				}
				if ((Object)(object)hdData == (Object)null)
				{
					lightComp.intensity = intensity;
					lightComp.range = range;
					lightComp.spotAngle = angle;
					lightComp.shadows = (LightShadows)(shadows ? 2 : 0);
				}
				lightComp.color = color;
				appliedIntensity = intensity;
				appliedRange = range;
				appliedAngle = angle;
				appliedShadows = shadows;
				appliedColor = color;
				hasApplied = true;
			}
			if (((Behaviour)lightComp).enabled != on)
			{
				((Behaviour)lightComp).enabled = on;
			}
		}

		public void Destroy()
		{
			if ((Object)(object)lightObj != (Object)null)
			{
				Object.Destroy((Object)(object)lightObj);
			}
			lightObj = null;
			lightComp = null;
			hdData = null;
			Player = null;
		}
	}
	public enum RechargeMode
	{
		Always,
		InShipOnly,
		Never
	}
	public enum IndicatorStyle
	{
		Text,
		Bar,
		Off
	}
	[BepInPlugin("pocketbeam.lethalcompany", "PocketBeam", "1.0.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "pocketbeam.lethalcompany";

		public const string Name = "PocketBeam";

		public const string Version = "1.0.1";

		internal static Plugin Instance;

		internal static ManualLogSource Log;

		internal ConfigEntry<string> ToggleKey;

		internal ConfigEntry<float> Intensity;

		internal ConfigEntry<float> Range;

		internal ConfigEntry<float> Angle;

		internal ConfigEntry<string> LightColor;

		internal ConfigEntry<bool> Shadows;

		internal ConfigEntry<float> BatterySeconds;

		internal ConfigEntry<RechargeMode> Recharge;

		internal ConfigEntry<float> RechargeSeconds;

		internal ConfigEntry<float> RechargeDelay;

		internal ConfigEntry<float> DimBelowPercent;

		internal ConfigEntry<IndicatorStyle> Indicator;

		internal ConfigEntry<float> IndicatorX;

		internal ConfigEntry<float> IndicatorY;

		internal ConfigEntry<int> IndicatorFontSize;

		internal ConfigEntry<bool> HideIndicatorWhenFull;

		internal ConfigEntry<bool> ShareMyLight;

		internal ConfigEntry<bool> ShowOtherLights;

		private void Awake()
		{
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Expected O, but got Unknown
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Expected O, but got Unknown
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Expected O, but got Unknown
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Expected O, but got Unknown
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			ToggleKey = ((BaseUnityPlugin)this).Config.Bind<string>("Controls", "Toggle key", "F", "Keyboard key that turns the pocket light on/off. Use Unity Input System key names, e.g. F, G, L, Backquote, Digit5.");
			Intensity = ((BaseUnityPlugin)this).Config.Bind<float>("Light", "Intensity", 300f, "Brightness of the light.");
			Range = ((BaseUnityPlugin)this).Config.Bind<float>("Light", "Range", 19f, "How far the light reaches, in metres.");
			Angle = ((BaseUnityPlugin)this).Config.Bind<float>("Light", "Beam angle", 75f, new ConfigDescription("Width of the light cone in degrees.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 170f), Array.Empty<object>()));
			LightColor = ((BaseUnityPlugin)this).Config.Bind<string>("Light", "Color", "#FFF4E0", "Light colour as a hex code, e.g. #FFFFFF (white) or #FFF4E0 (warm white).");
			Shadows = ((BaseUnityPlugin)this).Config.Bind<bool>("Light", "Cast shadows", false, "Shadows look nicer but cost performance.");
			BatterySeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Battery", "Battery life (seconds)", 60f, "How many seconds a full battery lasts while the light is on.");
			Recharge = ((BaseUnityPlugin)this).Config.Bind<RechargeMode>("Battery", "Recharge mode", RechargeMode.Always, "Always = recharges whenever the light is off. InShipOnly = only while you are inside the ship. Never = no recharging.");
			RechargeSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Battery", "Full recharge time (seconds)", 45f, "Seconds to go from empty to full while recharging.");
			RechargeDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Battery", "Recharge delay (seconds)", 2f, "Seconds after turning the light off before it starts recharging.");
			DimBelowPercent = ((BaseUnityPlugin)this).Config.Bind<float>("Battery", "Dim below battery %", 10f, new ConfigDescription("The light starts dimming when the battery drops below this percentage. 0 = never dims.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			Indicator = ((BaseUnityPlugin)this).Config.Bind<IndicatorStyle>("Indicator", "Battery indicator", IndicatorStyle.Text, "How the battery level is shown on screen.");
			IndicatorX = ((BaseUnityPlugin)this).Config.Bind<float>("Indicator", "Position X (% of screen width)", 16f, new ConfigDescription("Horizontal position of the indicator.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			IndicatorY = ((BaseUnityPlugin)this).Config.Bind<float>("Indicator", "Position Y (% of screen height)", 92f, new ConfigDescription("Vertical position of the indicator (0 = top).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			IndicatorFontSize = ((BaseUnityPlugin)this).Config.Bind<int>("Indicator", "Font size", 20, "Text size of the indicator.");
			HideIndicatorWhenFull = ((BaseUnityPlugin)this).Config.Bind<bool>("Indicator", "Hide when full and off", true, "Hide the indicator while the light is off and the battery is full.");
			ShareMyLight = ((BaseUnityPlugin)this).Config.Bind<bool>("Multiplayer", "Share my light", true, "Other players who also have PocketBeam can see your light.");
			ShowOtherLights = ((BaseUnityPlugin)this).Config.Bind<bool>("Multiplayer", "Show other players lights", true, "See the pocket lights of other players who have PocketBeam.");
			GameObject val = new GameObject("PocketBeam");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<PocketLightController>();
			Log.LogInfo((object)("PocketBeam 1.0.1 loaded. Toggle key: " + ToggleKey.Value));
		}
	}
	internal class PocketLightController : MonoBehaviour
	{
		private LightRig rig;

		private bool isOn;

		private float charge = 1f;

		private float lastOffTime = -999f;

		private string cachedKeyString;

		private Key toggleKey = (Key)20;

		private string cachedColorString;

		private Color lightColor = Color.white;

		private bool loggedError;

		private bool loggedNetError;

		private GUIStyle textStyle;

		private void Update()
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB val = null;
			float intensity = 0f;
			float range = 0f;
			float angle = 0f;
			try
			{
				val = Tick(out intensity, out range, out angle);
			}
			catch (Exception ex)
			{
				if (!loggedError)
				{
					loggedError = true;
					Plugin.Log.LogError((object)("PocketBeam error (logged once): " + ex));
				}
			}
			try
			{
				PocketLightNet.Update(val, isOn && (Object)(object)val != (Object)null, intensity, range, angle, lightColor);
			}
			catch (Exception ex2)
			{
				if (!loggedNetError)
				{
					loggedNetError = true;
					Plugin.Log.LogError((object)("PocketBeam network error (logged once): " + ex2));
				}
			}
		}

		private PlayerControllerB Tick(out float intensity, out float range, out float angle)
		{
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_031c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			intensity = (range = (angle = 0f));
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return null;
			}
			PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val.gameplayCamera == (Object)null)
			{
				CleanupLocal();
				return null;
			}
			if (rig == null || !rig.IsAlive || (Object)(object)rig.Player != (Object)(object)val)
			{
				CleanupLocal();
				rig = LightRig.Create(val, local: true);
			}
			int num;
			if (!val.isPlayerDead)
			{
				num = (val.isPlayerControlled ? 1 : 0);
				if (num != 0)
				{
					goto IL_00bd;
				}
			}
			else
			{
				num = 0;
			}
			if (isOn)
			{
				TurnOff();
			}
			goto IL_00bd;
			IL_00bd:
			UpdateKey(instance.ToggleKey.Value);
			Keyboard current = Keyboard.current;
			bool flag = val.inTerminalMenu || val.isTypingChat || ((Object)(object)val.quickMenuManager != (Object)null && val.quickMenuManager.isMenuOpen);
			if (num != 0 && !flag && current != null && (int)toggleKey != 0 && ((ButtonControl)current[toggleKey]).wasPressedThisFrame)
			{
				if (isOn)
				{
					TurnOff();
				}
				else if (charge > 0.01f)
				{
					isOn = true;
				}
			}
			float deltaTime = Time.deltaTime;
			if (isOn)
			{
				charge -= deltaTime / Mathf.Max(1f, instance.BatterySeconds.Value);
				if (charge <= 0f)
				{
					charge = 0f;
					TurnOff();
				}
			}
			else if (Time.time - lastOffTime >= instance.RechargeDelay.Value && (instance.Recharge.Value == RechargeMode.Always || (instance.Recharge.Value == RechargeMode.InShipOnly && val.isInHangarShipRoom)))
			{
				charge = Mathf.Min(1f, charge + deltaTime / Mathf.Max(1f, instance.RechargeSeconds.Value));
			}
			if (instance.LightColor.Value != cachedColorString)
			{
				cachedColorString = instance.LightColor.Value;
				if (!ColorUtility.TryParseHtmlString(cachedColorString?.Trim() ?? string.Empty, ref lightColor))
				{
					lightColor = Color.white;
				}
			}
			float num2 = instance.DimBelowPercent.Value / 100f;
			float num3 = ((num2 > 0f && charge < num2) ? Mathf.Lerp(0.2f, 1f, charge / num2) : 1f);
			intensity = Mathf.Max(0f, instance.Intensity.Value) * num3;
			range = Mathf.Max(0.5f, instance.Range.Value);
			angle = Mathf.Clamp(instance.Angle.Value, 10f, 170f);
			rig?.Apply(isOn, intensity, range, angle, lightColor, instance.Shadows.Value);
			return val;
		}

		private void TurnOff()
		{
			isOn = false;
			lastOffTime = Time.time;
		}

		private void UpdateKey(string keyString)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if (!(keyString == cachedKeyString))
			{
				cachedKeyString = keyString;
				if (!Enum.TryParse<Key>(keyString?.Trim(), ignoreCase: true, out toggleKey))
				{
					Plugin.Log.LogWarning((object)("Unknown toggle key '" + keyString + "', using F."));
					toggleKey = (Key)20;
				}
			}
		}

		private void CleanupLocal()
		{
			rig?.Destroy();
			rig = null;
			isOn = false;
		}

		private void OnGUI()
		{
			try
			{
				DrawIndicator();
			}
			catch (Exception ex)
			{
				if (!loggedError)
				{
					loggedError = true;
					Plugin.Log.LogError((object)("PocketBeam indicator error (logged once): " + ex));
				}
			}
		}

		private void DrawIndicator()
		{
			//IL_00e6: 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_00eb: 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_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null || instance.Indicator.Value == IndicatorStyle.Off || rig == null || !rig.IsAlive || (Object)(object)rig.Player == (Object)null)
			{
				return;
			}
			PlayerControllerB player = rig.Player;
			if (player.isPlayerDead || player.inTerminalMenu || (instance.HideIndicatorWhenFull.Value && !isOn && charge >= 0.999f))
			{
				return;
			}
			float num = (float)Screen.width * instance.IndicatorX.Value / 100f;
			float num2 = (float)Screen.height * instance.IndicatorY.Value / 100f;
			Color color = (isOn ? new Color(1f, 0.85f, 0.4f) : new Color(0.7f, 0.7f, 0.7f));
			if (charge < 0.2f)
			{
				((Color)(ref color))..ctor(1f, 0.35f, 0.3f);
			}
			if (instance.Indicator.Value == IndicatorStyle.Text)
			{
				if (textStyle == null)
				{
					textStyle = new GUIStyle(GUI.skin.label)
					{
						fontStyle = (FontStyle)1,
						alignment = (TextAnchor)3
					};
				}
				textStyle.fontSize = Mathf.Max(8, instance.IndicatorFontSize.Value);
				string text = $"Light {Mathf.CeilToInt(charge * 100f)}%";
				Rect val = default(Rect);
				((Rect)(ref val))..ctor(num, num2 - (float)textStyle.fontSize, 300f, (float)textStyle.fontSize * 2f);
				Color color2 = GUI.color;
				GUI.color = new Color(0f, 0f, 0f, 0.8f);
				GUI.Label(new Rect(((Rect)(ref val)).x + 2f, ((Rect)(ref val)).y + 2f, ((Rect)(ref val)).width, ((Rect)(ref val)).height), text, textStyle);
				GUI.color = color;
				GUI.Label(val, text, textStyle);
				GUI.color = color2;
			}
			else
			{
				float num3 = 160f;
				float num4 = 12f;
				Color color3 = GUI.color;
				GUI.color = new Color(0f, 0f, 0f, 0.6f);
				GUI.DrawTexture(new Rect(num - 2f, num2 - 2f, num3 + 4f, num4 + 4f), (Texture)(object)Texture2D.whiteTexture);
				GUI.color = color;
				GUI.DrawTexture(new Rect(num, num2, num3 * charge, num4), (Texture)(object)Texture2D.whiteTexture);
				GUI.color = color3;
			}
		}

		private void OnDestroy()
		{
			CleanupLocal();
			PocketLightNet.Reset();
		}
	}
	internal static class PocketLightNet
	{
		private class Remote
		{
			public LightRig Rig;

			public bool On;

			public float Intensity;

			public float Range;

			public float Angle;

			public Color Color;

			public float LastMessageTime;
		}

		private struct LightState
		{
			public ulong OwnerClientId;

			public bool On;

			public float Intensity;

			public float Range;

			public float Angle;

			public Color Color;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnStateMessage;

			public static HandleNamedMessageDelegate <1>__OnHelloMessage;
		}

		private const string MsgState = "PocketBeam.State";

		private const string MsgHello = "PocketBeam.Hello";

		private const byte Protocol = 1;

		private const float HeartbeatSeconds = 2f;

		private const float MinSendInterval = 0.2f;

		private const float RemoteTimeoutSeconds = 6f;

		private static CustomMessagingManager registeredOn;

		private static readonly HashSet<ulong> moddedClients = new HashSet<ulong>();

		private static bool sentHello;

		private static bool lastSentOn;

		private static float lastSentIntensity = -1f;

		private static float lastSentRange;

		private static float lastSentAngle;

		private static Color lastSentColor;

		private static float lastSendTime = -999f;

		private static readonly Dictionary<ulong, Remote> remotes = new Dictionary<ulong, Remote>();

		public static void Update(PlayerControllerB localPlayer, bool on, float intensity, float range, float angle, Color color)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.CustomMessagingManager == null)
			{
				Reset();
				return;
			}
			if (registeredOn != singleton.CustomMessagingManager)
			{
				Reset();
				registeredOn = singleton.CustomMessagingManager;
				CustomMessagingManager obj = registeredOn;
				object obj2 = <>O.<0>__OnStateMessage;
				if (obj2 == null)
				{
					HandleNamedMessageDelegate val = OnStateMessage;
					<>O.<0>__OnStateMessage = val;
					obj2 = (object)val;
				}
				obj.RegisterNamedMessageHandler("PocketBeam.State", (HandleNamedMessageDelegate)obj2);
				CustomMessagingManager obj3 = registeredOn;
				object obj4 = <>O.<1>__OnHelloMessage;
				if (obj4 == null)
				{
					HandleNamedMessageDelegate val2 = OnHelloMessage;
					<>O.<1>__OnHelloMessage = val2;
					obj4 = (object)val2;
				}
				obj3.RegisterNamedMessageHandler("PocketBeam.Hello", (HandleNamedMessageDelegate)obj4);
			}
			if (!singleton.IsServer && !sentHello && singleton.IsConnectedClient)
			{
				sentHello = true;
				SendHello(singleton);
			}
			Plugin instance = Plugin.Instance;
			if ((Object)(object)localPlayer != (Object)null && instance.ShareMyLight.Value)
			{
				bool flag = on;
				bool flag2 = flag != lastSentOn || (flag && (Mathf.Abs(intensity - lastSentIntensity) > Mathf.Max(5f, lastSentIntensity * 0.1f) || range != lastSentRange || angle != lastSentAngle || color != lastSentColor));
				bool flag3 = flag && Time.time - lastSendTime >= 2f;
				if ((flag2 && Time.time - lastSendTime >= 0.2f) || flag3 || (flag2 && !flag))
				{
					SendOwnState(singleton, localPlayer, flag, intensity, range, angle, color);
				}
			}
			else if (lastSentOn && (Object)(object)localPlayer != (Object)null)
			{
				SendOwnState(singleton, localPlayer, on: false, intensity, range, angle, color);
			}
			UpdateRemotes(localPlayer);
		}

		public static void Reset()
		{
			if (registeredOn != null)
			{
				try
				{
					registeredOn.UnregisterNamedMessageHandler("PocketBeam.State");
					registeredOn.UnregisterNamedMessageHandler("PocketBeam.Hello");
				}
				catch (Exception)
				{
				}
			}
			registeredOn = null;
			moddedClients.Clear();
			sentHello = false;
			lastSentOn = false;
			lastSentIntensity = -1f;
			lastSendTime = -999f;
			foreach (Remote value in remotes.Values)
			{
				value.Rig?.Destroy();
			}
			remotes.Clear();
		}

		private unsafe static void SendHello(NetworkManager nm)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(8, (Allocator)2, -1);
			try
			{
				byte b = 1;
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
				nm.CustomMessagingManager.SendNamedMessage("PocketBeam.Hello", 0uL, val, (NetworkDelivery)2);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static void SendOwnState(NetworkManager nm, PlayerControllerB localPlayer, bool on, float intensity, float range, float angle, Color color)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			LightState lightState = new LightState
			{
				OwnerClientId = nm.LocalClientId,
				On = on,
				Intensity = intensity,
				Range = range,
				Angle = angle,
				Color = color
			};
			if (nm.IsServer)
			{
				RelayToModdedClients(nm, lightState, nm.LocalClientId);
			}
			else
			{
				SendState(nm, lightState, new ulong[1]);
			}
			lastSentOn = on;
			lastSentIntensity = intensity;
			lastSentRange = range;
			lastSentAngle = angle;
			lastSentColor = color;
			lastSendTime = Time.time;
		}

		private static void RelayToModdedClients(NetworkManager nm, LightState state, ulong excludeClientId)
		{
			List<ulong> list = new List<ulong>();
			foreach (ulong moddedClient in moddedClients)
			{
				if (moddedClient != excludeClientId && moddedClient != nm.LocalClientId && IsConnected(nm, moddedClient))
				{
					list.Add(moddedClient);
				}
			}
			if (list.Count > 0)
			{
				SendState(nm, state, list);
			}
		}

		private static bool IsConnected(NetworkManager nm, ulong clientId)
		{
			foreach (ulong connectedClientsId in nm.ConnectedClientsIds)
			{
				if (connectedClientsId == clientId)
				{
					return true;
				}
			}
			return false;
		}

		private unsafe static void SendState(NetworkManager nm, LightState s, IReadOnlyList<ulong> targets)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: 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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: 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_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(64, (Allocator)2, -1);
			try
			{
				byte b = 1;
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref s.OwnerClientId, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref s.On, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref s.Intensity, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref s.Range, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref s.Angle, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref s.Color.r, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref s.Color.g, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref s.Color.b, default(ForPrimitives));
				foreach (ulong target in targets)
				{
					nm.CustomMessagingManager.SendNamedMessage("PocketBeam.State", target, val, (NetworkDelivery)2);
				}
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static void OnHelloMessage(ulong senderClientId, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				byte b = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
				if (b != 1)
				{
					return;
				}
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
				{
					return;
				}
				moddedClients.Add(senderClientId);
				if (lastSentOn && Plugin.Instance.ShareMyLight.Value)
				{
					SendState(singleton, new LightState
					{
						OwnerClientId = singleton.LocalClientId,
						On = true,
						Intensity = lastSentIntensity,
						Range = lastSentRange,
						Angle = lastSentAngle,
						Color = lastSentColor
					}, new ulong[1] { senderClientId });
				}
				foreach (KeyValuePair<ulong, Remote> remote in remotes)
				{
					if (remote.Key != senderClientId && remote.Value.On)
					{
						Remote value = remote.Value;
						SendState(singleton, new LightState
						{
							OwnerClientId = remote.Key,
							On = true,
							Intensity = value.Intensity,
							Range = value.Range,
							Angle = value.Angle,
							Color = value.Color
						}, new ulong[1] { senderClientId });
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("PocketBeam: bad hello message: " + ex.Message));
			}
		}

		private static void OnStateMessage(ulong senderClientId, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				byte b = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
				if (b != 1)
				{
					return;
				}
				LightState lightState = default(LightState);
				((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref lightState.OwnerClientId, default(ForPrimitives));
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref lightState.On, default(ForPrimitives));
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref lightState.Intensity, default(ForPrimitives));
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref lightState.Range, default(ForPrimitives));
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref lightState.Angle, default(ForPrimitives));
				float num = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num, default(ForPrimitives));
				float num2 = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num2, default(ForPrimitives));
				float num3 = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num3, default(ForPrimitives));
				lightState.Color = new Color(num, num2, num3);
				NetworkManager singleton = NetworkManager.Singleton;
				if (!((Object)(object)singleton == (Object)null))
				{
					if (singleton.IsServer)
					{
						lightState.OwnerClientId = senderClientId;
						moddedClients.Add(senderClientId);
						RelayToModdedClients(singleton, lightState, senderClientId);
					}
					if (lightState.OwnerClientId != singleton.LocalClientId)
					{
						ApplyRemote(lightState);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("PocketBeam: bad light message: " + ex.Message));
			}
		}

		private static void ApplyRemote(LightState s)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			if (!remotes.TryGetValue(s.OwnerClientId, out var value))
			{
				value = new Remote();
				remotes[s.OwnerClientId] = value;
			}
			value.On = s.On;
			value.Intensity = Mathf.Clamp(s.Intensity, 0f, 100000f);
			value.Range = Mathf.Clamp(s.Range, 0.5f, 200f);
			value.Angle = Mathf.Clamp(s.Angle, 10f, 170f);
			value.Color = s.Color;
			value.LastMessageTime = Time.time;
		}

		private static void UpdateRemotes(PlayerControllerB localPlayer)
		{
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			if (remotes.Count == 0)
			{
				return;
			}
			bool value = Plugin.Instance.ShowOtherLights.Value;
			List<ulong> list = new List<ulong>();
			foreach (KeyValuePair<ulong, Remote> remote in remotes)
			{
				Remote value2 = remote.Value;
				PlayerControllerB val = FindPlayer(remote.Key);
				if (!((Object)(object)val != (Object)null) || !((Object)(object)val != (Object)(object)localPlayer) || val.isPlayerDead || !val.isPlayerControlled)
				{
					value2.Rig?.Destroy();
					value2.Rig = null;
					if ((Object)(object)val == (Object)null)
					{
						list.Add(remote.Key);
					}
					continue;
				}
				if (value2.On && Time.time - value2.LastMessageTime > 6f)
				{
					value2.On = false;
				}
				bool flag = value && value2.On;
				if (value2.Rig != null && (!value2.Rig.IsAlive || (Object)(object)value2.Rig.Player != (Object)(object)val))
				{
					value2.Rig.Destroy();
					value2.Rig = null;
				}
				if (flag && value2.Rig == null)
				{
					value2.Rig = LightRig.Create(val, local: false);
				}
				value2.Rig?.Apply(flag, value2.Intensity, value2.Range, value2.Angle, value2.Color, shadows: false);
			}
			foreach (ulong item in list)
			{
				remotes.Remove(item);
			}
		}

		private static PlayerControllerB FindPlayer(ulong clientId)
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || instance.allPlayerScripts == null)
			{
				return null;
			}
			PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if ((Object)(object)val != (Object)null && val.isPlayerControlled && val.actualClientId == clientId)
				{
					return val;
				}
			}
			return null;
		}
	}
}