Decompiled source of CartChargingStation v0.2.0

plugins/CartChargingStation.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Linq;
using BepInEx;
using BepInEx.Configuration;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CartChargingStation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0")]
[assembly: AssemblyProduct("CartChargingStation")]
[assembly: AssemblyTitle("CartChargingStation")]
[assembly: AssemblyVersion("0.2.0.0")]
[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 CartChargingStation
{
	internal static class CartCharge
	{
		private static Type _battery = null;

		private static FieldInfo _small = null;

		private static FieldInfo _contents = null;

		private static FieldInfo _grabbed = null;

		private static FieldInfo _basket = null;

		private static FieldInfo _cartMesh = null;

		private static FieldInfo _stationInstance = null;

		private static FieldInfo _chargeArea = null;

		private static FieldInfo _stationCharge = null;

		private static FieldInfo _stationTotal = null;

		private static FieldInfo _crystalEnergy = null;

		private static FieldInfo _batteryCost = null;

		private static FieldInfo _unchargable = null;

		private static FieldInfo _chargerCylinder = null;

		private static MethodInfo _receiveCharge = null;

		private static Component? _scannedStation;

		private static CartReadout? _dockedCart;

		private static readonly HashSet<CartReadout> Carts = new HashSet<CartReadout>();

		private static float _nextDockScan;

		private static bool _loggedTransfer;

		internal static void Install(Harmony harmony)
		{
			Type type = Plugin.GameType("PhysGrabCart");
			_battery = Plugin.GameType("ItemBattery");
			Type type2 = Plugin.GameType("ChargingStation");
			_small = Plugin.Field(type, "isSmallCart");
			_contents = Plugin.Field(type, "itemsInCart");
			_basket = Plugin.Field(type, "inCart");
			_cartMesh = Plugin.Field(type, "cartMesh");
			_grabbed = Plugin.Field(Plugin.GameType("PhysGrabObject"), "grabbed");
			_stationInstance = Plugin.Field(type2, "instance");
			_chargeArea = Plugin.Field(type2, "chargeArea");
			_chargerCylinder = Plugin.Field(type2, "crystalCylinder");
			_stationCharge = Plugin.Field(type2, "chargeFloat");
			_stationTotal = Plugin.Field(type2, "chargeTotal");
			_crystalEnergy = Plugin.Field(type2, "energyPerCrystal");
			_batteryCost = Plugin.Field(type2, "batteryChargeCost");
			_unchargable = Plugin.Field(_battery, "isUnchargable");
			_receiveCharge = Plugin.Method(_battery, "ReceiveCharge", typeof(float), typeof(float));
			harmony.Patch((MethodBase)Plugin.Method(type, "Start", typeof(void)), (HarmonyMethod)null, Hook("AttachReadout"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(type2, "ChargeAreaCheck", typeof(void)), Hook("ScanDock"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(type2, "ChargeItems", typeof(float)), (HarmonyMethod)null, Hook("ChargeFromTruck"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void AttachReadout(Component __instance)
		{
			if (Plugin.Mission() || Plugin.Preparation())
			{
				object value = _small.GetValue(__instance);
				if (!(value is bool) || !(bool)value)
				{
					CartReadout cartReadout = __instance.gameObject.AddComponent<CartReadout>();
					object basket = (object)/*isinst with value type is only supported in some contexts*/;
					object? value2 = _cartMesh.GetValue(__instance);
					cartReadout.Initialize(__instance, (Transform?)basket, (MeshRenderer?)((value2 is MeshRenderer) ? value2 : null));
					Carts.Add(cartReadout);
				}
			}
		}

		internal static void Unregister(CartReadout readout)
		{
			Carts.Remove(readout);
		}

		internal static void UpdateContents(Component cart, float elapsed)
		{
			if (!Plugin.Active || !NetworkSession.CanAct || !(_contents.GetValue(cart) is IList list))
			{
				return;
			}
			float num = 0.01f;
			object? value = _stationInstance.GetValue(null);
			Component val = (Component)((value is Component) ? value : null);
			if (val != null && (Object)(object)val != (Object)null && _crystalEnergy.GetValue(val) is int num2 && num2 > 0 && _batteryCost.GetValue(val) is float num3 && num3 > 0f)
			{
				num = num3 * 100f / (float)num2;
			}
			ExpansionItem expansionItem = default(ExpansionItem);
			foreach (object item in list)
			{
				Component val2 = (Component)((item is Component) ? item : null);
				if (val2 == null || (Object)(object)val2 == (Object)null)
				{
					continue;
				}
				object value2 = _grabbed.GetValue(val2);
				if (value2 is bool && (bool)value2)
				{
					continue;
				}
				if (val2.TryGetComponent<ExpansionItem>(ref expansionItem) && !expansionItem.ForSale)
				{
					if (expansionItem.Consume())
					{
						RunState.Capacity += Plugin.ExpansionCapacity.Value;
						Plugin.LogInfo($"Cart upgraded to {RunState.Capacity:F2} crystals.");
					}
				}
				else
				{
					if (RunState.Charge <= 0f)
					{
						continue;
					}
					Component componentInChildren = val2.GetComponentInChildren(_battery);
					if (!((Object)(object)componentInChildren == (Object)null))
					{
						value2 = _unchargable.GetValue(componentInChildren);
						if (!(value2 is bool) || !(bool)value2)
						{
							float num4 = Mathf.Min(20f * elapsed, RunState.Charge / num);
							float num5 = (float)_receiveCharge.Invoke(componentInChildren, new object[1] { num4 });
							RunState.Charge = Mathf.Max(0f, RunState.Charge - num5 * num);
						}
					}
				}
			}
		}

		private static void ScanDock(Component __instance)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: 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_00c4: 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)
			if (!Plugin.Active || !NetworkSession.CanAct || ((Object)(object)_scannedStation == (Object)(object)__instance && Time.time < _nextDockScan))
			{
				return;
			}
			_scannedStation = __instance;
			_nextDockScan = Time.time + 0.2f;
			CartReadout cartReadout = null;
			float num = 1.15f;
			object? value = _chargeArea.GetValue(__instance);
			Transform val = (Transform)((value is Transform) ? value : null);
			object? value2 = _chargerCylinder.GetValue(__instance);
			Transform val2 = (Transform)((value2 is Transform) ? value2 : null);
			foreach (CartReadout cart in Carts)
			{
				if (!((Object)(object)cart == (Object)null) && ((Behaviour)cart).isActiveAndEnabled && !(((Component)cart).gameObject.scene != __instance.gameObject.scene))
				{
					float num2 = cart.DistanceTo(((Object)(object)val != (Object)null) ? val.position : __instance.transform.position);
					if ((Object)(object)val2 != (Object)null)
					{
						num2 = Mathf.Min(num2, cart.DistanceTo(val2.position));
					}
					if (!(num2 > num))
					{
						cartReadout = cart;
						num = num2;
					}
				}
			}
			if ((Object)(object)cartReadout != (Object)null && (Object)(object)cartReadout != (Object)(object)_dockedCart)
			{
				float num3 = (float)_stationCharge.GetValue(__instance);
				Plugin.LogInfo($"Cart dock detected ({num:F2} m). Charger energy: {num3:P1}. Cart: {RunState.Charge:F2}/{RunState.Capacity:F2} crystals.");
			}
			if ((Object)(object)cartReadout != (Object)(object)_dockedCart)
			{
				_loggedTransfer = false;
			}
			_dockedCart = cartReadout;
		}

		private static void ChargeFromTruck(Component __instance, ref float __result)
		{
			if (!Plugin.Active || !NetworkSession.CanAct || (Object)(object)_scannedStation != (Object)(object)__instance || (Object)(object)_dockedCart == (Object)null || RunState.Charge >= RunState.Capacity || !(_crystalEnergy.GetValue(__instance) is int num) || num <= 0 || !(_batteryCost.GetValue(__instance) is float num2) || num2 <= 0f)
			{
				return;
			}
			float num3 = (float)_stationCharge.GetValue(__instance);
			float num4 = (float)num / 100f;
			float num5 = Mathf.Min(new float[3]
			{
				0.2f * Time.deltaTime,
				RunState.Capacity - RunState.Charge,
				num3 / num4
			});
			if (!(num5 <= 0f))
			{
				num3 = Mathf.Max(0f, num3 - num5 * num4);
				RunState.Charge += num5;
				_stationCharge.SetValue(__instance, num3);
				_stationTotal.SetValue(__instance, Mathf.Clamp((int)(num3 * 100f), 0, 100));
				if (!_loggedTransfer)
				{
					_loggedTransfer = true;
					Plugin.LogInfo("Truck charging station started transferring energy to the cart.");
				}
				__result += num5 * num4 / num2;
			}
		}

		private static HarmonyMethod Hook(string name)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return new HarmonyMethod(typeof(CartCharge), name, (Type[])null);
		}
	}
	internal sealed class CartReadout : MonoBehaviour
	{
		private Component _cart;

		private static readonly Color ReadoutColor = new Color(1f, 0.83f, 0.16f);

		private static Mesh? _crystalMesh;

		private static Material? _crystalMaterial;

		private Mesh? _digits;

		private readonly List<GameObject> _panels = new List<GameObject>(2);

		private float _textWidth;

		private float _textHeight;

		private Transform? _basket;

		private Collider[] _cartColliders = Array.Empty<Collider>();

		private float _nextTick;

		private string? _lastText;

		internal void Initialize(Component cart, Transform? basket, MeshRenderer? body)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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_009b: 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_00b0: Expected O, but got Unknown
			//IL_007a: 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_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_009a: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: 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_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: 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_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: 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_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			_cart = cart;
			_basket = basket;
			_cartColliders = cart.GetComponentsInChildren<Collider>(true);
			Bounds val = CartBodyBounds(body);
			_textWidth = ((Bounds)(ref val)).size.z * 0.63f;
			_textHeight = ((Bounds)(ref val)).size.y * 0.24f;
			Shader val2 = Shader.Find("Sprites/Default");
			if ((Object)(object)val2 == (Object)null)
			{
				Plugin.Warn("Cart readout shader is unavailable.");
				return;
			}
			if (_crystalMaterial == null)
			{
				_crystalMaterial = new Material(val2)
				{
					mainTexture = (Texture)(object)Texture2D.whiteTexture,
					color = ReadoutColor
				};
			}
			_digits = new Mesh
			{
				name = "Cart charge digits"
			};
			_digits.MarkDynamic();
			for (int i = 0; i < 2; i++)
			{
				int num = ((i != 0) ? 1 : (-1));
				Transform transform = new GameObject("Cart side readout").transform;
				_panels.Add(((Component)transform).gameObject);
				((Component)transform).gameObject.SetActive(Plugin.Active);
				transform.SetParent(((Component)this).transform, false);
				transform.localPosition = new Vector3(((Bounds)(ref val)).center.x + (float)num * (((Bounds)(ref val)).extents.x + 0.025f), ((Bounds)(ref val)).min.y + ((Bounds)(ref val)).size.y * 0.43f, ((Bounds)(ref val)).center.z);
				transform.localRotation = Quaternion.LookRotation(Vector3.left * (float)num, Vector3.up);
				GameObject val3 = new GameObject("Crystal charge");
				val3.transform.SetParent(transform, false);
				val3.transform.localPosition = new Vector3((0f - ((Bounds)(ref val)).size.z) * 0.045f, 0f, 0f);
				val3.AddComponent<MeshFilter>().sharedMesh = _digits;
				((Renderer)val3.AddComponent<MeshRenderer>()).sharedMaterial = _crystalMaterial;
				float size = Mathf.Min(((Bounds)(ref val)).size.z * 0.053f, _textHeight);
				AddCrystalIcon(transform, _textWidth * 0.5f + ((Bounds)(ref val)).size.z * 0.008f, size);
			}
		}

		private Bounds CartBodyBounds(MeshRenderer? body)
		{
			//IL_0059: 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_0074: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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_0021: 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)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: 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_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: 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_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: 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_00f6: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)body == (Object)null)
			{
				return new Bounds(((Object)(object)_basket != (Object)null) ? ((Component)this).transform.InverseTransformPoint(_basket.position) : (Vector3.up * 0.45f), new Vector3(1.16f, 0.5f, 1.8f));
			}
			Bounds localBounds = ((Renderer)body).localBounds;
			Bounds result = default(Bounds);
			((Bounds)(ref result))..ctor(((Component)this).transform.InverseTransformPoint(((Component)body).transform.TransformPoint(((Bounds)(ref localBounds)).center)), Vector3.zero);
			Vector3 val = default(Vector3);
			for (int i = 0; i < 8; i++)
			{
				((Vector3)(ref val))..ctor(((i & 1) == 0) ? (-1f) : 1f, ((i & 2) == 0) ? (-1f) : 1f, ((i & 4) == 0) ? (-1f) : 1f);
				Vector3 val2 = ((Bounds)(ref localBounds)).center + Vector3.Scale(((Bounds)(ref localBounds)).extents, val);
				((Bounds)(ref result)).Encapsulate(((Component)this).transform.InverseTransformPoint(((Component)body).transform.TransformPoint(val2)));
			}
			return result;
		}

		private static void AddCrystalIcon(Transform panel, float x, float size)
		{
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: 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_013b: 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_0147: 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_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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_006a: 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_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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_0095: 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_00a1: 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_00b9: 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_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			if (_crystalMesh == null)
			{
				Mesh val = new Mesh();
				val.vertices = (Vector3[])(object)new Vector3[4]
				{
					new Vector3(-0.37f, 0f),
					new Vector3(0f, 0.5f),
					new Vector3(0.37f, 0f),
					new Vector3(0f, -0.5f)
				};
				val.uv = (Vector2[])(object)new Vector2[4]
				{
					Vector2.one,
					Vector2.one,
					Vector2.one,
					Vector2.one
				};
				val.colors = (Color[])(object)new Color[4]
				{
					Color.white,
					Color.white,
					Color.white,
					Color.white
				};
				val.triangles = new int[6] { 0, 1, 2, 0, 2, 3 };
				_crystalMesh = val;
			}
			GameObject val2 = new GameObject("Crystal icon");
			val2.transform.SetParent(panel, false);
			val2.transform.localPosition = new Vector3(x, 0f, 0f);
			val2.transform.localScale = Vector3.one * size;
			val2.AddComponent<MeshFilter>().sharedMesh = _crystalMesh;
			((Renderer)val2.AddComponent<MeshRenderer>()).sharedMaterial = _crystalMaterial;
		}

		internal float DistanceTo(Vector3 point)
		{
			//IL_0021: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			float num = Vector3.Distance(((Object)(object)_basket != (Object)null) ? _basket.position : ((Component)this).transform.position, point);
			Collider[] cartColliders = _cartColliders;
			foreach (Collider val in cartColliders)
			{
				if (!((Object)(object)val == (Object)null) && val.enabled && !val.isTrigger && ((Component)val).gameObject.activeInHierarchy)
				{
					float num2 = num;
					Bounds bounds = val.bounds;
					num = Mathf.Min(num2, Vector3.Distance(((Bounds)(ref bounds)).ClosestPoint(point), point));
				}
			}
			return num;
		}

		private void OnDestroy()
		{
			CartCharge.Unregister(this);
			if ((Object)(object)_digits != (Object)null)
			{
				Object.Destroy((Object)(object)_digits);
			}
		}

		private void LateUpdate()
		{
			if (Time.time < _nextTick)
			{
				return;
			}
			_nextTick = Time.time + 0.2f;
			foreach (GameObject panel in _panels)
			{
				panel.SetActive(Plugin.Active);
			}
			if (Plugin.Active)
			{
				CartCharge.UpdateContents(_cart, 0.2f);
				string text = FormattableString.Invariant($"{RunState.Charge:F2}/{RunState.Capacity:F2}");
				if (!(_lastText == text) && !((Object)(object)_digits == (Object)null))
				{
					ChargeDigits.Draw(_digits, text, _textWidth, _textHeight);
					_lastText = text;
				}
			}
		}
	}
	internal static class ChargeDigits
	{
		private static readonly int[] Masks = new int[10] { 63, 6, 91, 79, 102, 109, 125, 7, 127, 111 };

		private static readonly (Vector2 Start, Vector2 End)[] Segments = new(Vector2, Vector2)[7]
		{
			(new Vector2(0.09f, 0.43f), new Vector2(0.46f, 0.43f)),
			(new Vector2(0.5f, 0.39f), new Vector2(0.5f, 0.06f)),
			(new Vector2(0.5f, -0.06f), new Vector2(0.5f, -0.39f)),
			(new Vector2(0.09f, -0.43f), new Vector2(0.46f, -0.43f)),
			(new Vector2(0.05f, -0.39f), new Vector2(0.05f, -0.06f)),
			(new Vector2(0.05f, 0.06f), new Vector2(0.05f, 0.39f)),
			(new Vector2(0.09f, 0f), new Vector2(0.46f, 0f))
		};

		internal static void Draw(Mesh mesh, string value, float width, float height)
		{
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			float num = 0f;
			string text = value;
			foreach (char symbol in text)
			{
				num += Advance(symbol);
			}
			float scale = Mathf.Min(height, width / Mathf.Max(7.66f, num));
			float x = (0f - num) * 0.5f;
			List<Vector3> vertices = new List<Vector3>(value.Length * 20);
			List<int> triangles = new List<int>(value.Length * 30);
			text = value;
			foreach (char c in text)
			{
				if (c >= '0' && c <= '9')
				{
					int num2 = Masks[c - 48];
					for (int j = 0; j < Segments.Length; j++)
					{
						if ((num2 & (1 << j)) != 0)
						{
							AddStroke(Segments[j].Start, Segments[j].End);
						}
					}
				}
				else
				{
					switch (c)
					{
					case '.':
						AddStroke(new Vector2(0.08f, -0.43f), new Vector2(0.16f, -0.43f));
						break;
					case '/':
						AddStroke(new Vector2(0.08f, -0.43f), new Vector2(0.44f, 0.43f));
						break;
					}
				}
				x += Advance(c);
			}
			Vector2[] uv = (Vector2[])(object)new Vector2[vertices.Count];
			Color32[] array = (Color32[])(object)new Color32[vertices.Count];
			for (int k = 0; k < array.Length; k++)
			{
				array[k] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);
			}
			mesh.Clear();
			mesh.SetVertices(vertices);
			mesh.uv = uv;
			mesh.colors32 = array;
			mesh.SetTriangles(triangles, 0);
			void AddStroke(Vector2 start, Vector2 end)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: 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_0010: 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_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: 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_0062: 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_006e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: Unknown result type (might be due to invalid IL or missing references)
				//IL_0085: Unknown result type (might be due to invalid IL or missing references)
				//IL_0090: 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_00a5: 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_00a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: 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_00c7: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
				Vector2 val = end - start;
				Vector2 normalized = ((Vector2)(ref val)).normalized;
				Vector2 val2 = new Vector2(0f - normalized.y, normalized.x) * 0.047f;
				start.x += x;
				end.x += x;
				int count = vertices.Count;
				vertices.Add(Vector2.op_Implicit((start - val2) * scale));
				vertices.Add(Vector2.op_Implicit((start + val2) * scale));
				vertices.Add(Vector2.op_Implicit((end + val2) * scale));
				vertices.Add(Vector2.op_Implicit((end - val2) * scale));
				triangles.AddRange(new int[6]
				{
					count,
					count + 2,
					count + 1,
					count,
					count + 3,
					count + 2
				});
			}
		}

		private static float Advance(char symbol)
		{
			return symbol switch
			{
				'/' => 0.58f, 
				'.' => 0.24f, 
				_ => 0.66f, 
			};
		}
	}
	internal static class ExpansionDiscount
	{
		private static FieldInfo _target;

		private static FieldInfo _range;

		private static FieldInfo _minimum;

		private static FieldInfo _center;

		private static MethodInfo _targetValid;

		private static MethodInfo _feedback;

		internal static void Install(Harmony harmony)
		{
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Expected O, but got Unknown
			try
			{
				Type type = Plugin.GameType("ShopKeeper");
				Type type2 = Plugin.GameType("PhysGrabObject");
				_target = Plugin.Field(type, "itemReactObject");
				_range = Plugin.Field(type, "itemLikeDiscountRange");
				_minimum = Plugin.Field(type, "itemLikeDiscountMinimumValue");
				_center = Plugin.Field(type2, "centerPoint");
				_targetValid = Plugin.Method(type, "ItemTargetValid", typeof(bool));
				_feedback = Plugin.Method(type, "ItemDiscountLogic", typeof(void), type2, typeof(Vector3), typeof(int));
				MethodInfo methodInfo = Plugin.Method(type, "ItemDiscountTargetValid", typeof(bool), type2);
				MethodInfo methodInfo2 = Plugin.Method(type, "ItemDiscountApply", typeof(void));
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(ExpansionDiscount), "AllowDiscount", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(ExpansionDiscount), "ApplyDiscount", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				Plugin.Warn("Could not install shopkeeper discount: " + ex.GetBaseException().Message);
			}
		}

		private static void AllowDiscount(Component __0, ref bool __result)
		{
			if (!__result)
			{
				ExpansionItem expansion = GetExpansion(__0);
				if (expansion != null && expansion.PriceK > 0)
				{
					__result = true;
				}
			}
		}

		private static bool ApplyDiscount(Component __instance)
		{
			//IL_0067: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			object? value = _target.GetValue(__instance);
			Component val = (Component)((value is Component) ? value : null);
			ExpansionItem expansion = GetExpansion(val);
			if ((Object)(object)expansion == (Object)null)
			{
				return true;
			}
			try
			{
				if (!NetworkSession.CanAct || expansion.PriceK <= 0)
				{
					goto IL_0054;
				}
				object obj = _targetValid.Invoke(__instance, null);
				if (!(obj is bool) || !(bool)obj)
				{
					goto IL_0054;
				}
				Vector2 val2 = (Vector2)_range.GetValue(__instance);
				float num = Random.Range(Mathf.Clamp01(Mathf.Min(val2.x, val2.y)), Mathf.Clamp01(Mathf.Max(val2.x, val2.y)));
				int num2 = Mathf.CeilToInt((float)Mathf.Max(0, (int)_minimum.GetValue(__instance)) / 1000f);
				int num3 = Mathf.Min(expansion.PriceK, Mathf.Max(num2, Mathf.CeilToInt((float)expansion.PriceK * num)));
				if (num3 <= 0)
				{
					return false;
				}
				expansion.SetPrice(expansion.PriceK - num3);
				ExpansionShop.RefreshPrice();
				_feedback.Invoke(__instance, new object[3]
				{
					val,
					_center.GetValue(val),
					num3
				});
				Plugin.LogInfo($"Shopkeeper discounted an expansion battery by {num3}K to {expansion.PriceK}K.");
				goto end_IL_0024;
				IL_0054:
				return false;
				end_IL_0024:;
			}
			catch (Exception ex)
			{
				Plugin.Warn("Shopkeeper discount failed: " + ex.GetBaseException().Message);
			}
			return false;
		}

		private static ExpansionItem? GetExpansion(Component? target)
		{
			ExpansionItem expansionItem = default(ExpansionItem);
			if (!((Object)(object)target != (Object)null) || !Plugin.Shop() || !NetworkSession.Usable || !target.TryGetComponent<ExpansionItem>(ref expansionItem) || !expansionItem.ForSale)
			{
				return null;
			}
			return expansionItem;
		}
	}
	internal sealed class ExpansionItem : MonoBehaviour, IPunInstantiateMagicCallback
	{
		internal bool ForSale;

		internal bool Banked;

		internal int PriceK;

		private bool _consumed;

		internal bool Consume()
		{
			if (_consumed)
			{
				return false;
			}
			_consumed = true;
			if (Banked)
			{
				RunState.Pending = Math.Max(0, RunState.Pending - 1);
			}
			PhotonView val = default(PhotonView);
			if (PhotonNetwork.InRoom && !PhotonNetwork.OfflineMode && ((Component)this).TryGetComponent<PhotonView>(ref val) && val.ViewID > 0)
			{
				PhotonNetwork.Destroy(val);
			}
			else
			{
				((Component)this).gameObject.SetActive(false);
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
			return true;
		}

		public void OnPhotonInstantiate(PhotonMessageInfo info)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			object[] instantiationData = info.photonView.InstantiationData;
			if (instantiationData != null && instantiationData.Length == 3 && instantiationData[0] is bool forSale && instantiationData[1] is bool banked && instantiationData[2] is int priceK)
			{
				ForSale = forSale;
				Banked = banked;
				PriceK = priceK;
				if (ForSale)
				{
					ExpansionShop.TrackSale(this);
				}
				ExpansionShop.ProtectBattery(((Component)this).gameObject);
			}
		}

		internal void SetPrice(int price)
		{
			PriceK = price;
			PhotonView val = default(PhotonView);
			if (Plugin.Multiplayer() && NetworkSession.CanAct && ((Component)this).TryGetComponent<PhotonView>(ref val) && val.ViewID > 0)
			{
				val.RPC("ReceiveExpansionPrice", (RpcTarget)4, new object[1] { price });
			}
		}

		[PunRPC]
		private void ReceiveExpansionPrice(int price, PhotonMessageInfo info)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if (ForSale && price >= 0 && info.Sender == PhotonNetwork.MasterClient)
			{
				PriceK = price;
			}
		}

		private void OnDestroy()
		{
			ExpansionShop.UntrackSale(this);
		}
	}
	internal static class ExpansionShop
	{
		private static Type _room = null;

		private static Type[] _grabComponents = null;

		private static FieldInfo _extractShop = null;

		private static FieldInfo _extractRoom = null;

		private static FieldInfo _roomExtraction = null;

		private static FieldInfo _total = null;

		private static FieldInfo _ui = null;

		private static FieldInfo _aimed = null;

		private static FieldInfo _held = null;

		private static FieldInfo _grabbed = null;

		private static FieldInfo _local = null;

		private static FieldInfo _checkoutState = null;

		private static MethodInfo _updateCost = null;

		private static MethodInfo _showPrice = null;

		private static MethodInfo _indestructible = null;

		private static Func<int> _funds = null;

		private static Func<int, int> _setFunds = null;

		private static readonly List<ExpansionItem> Sale = new List<ExpansionItem>();

		private static readonly Dictionary<Color, Material> PaintedMaterials = new Dictionary<Color, Material>();

		private static Mesh? _batteryCylinder;

		private static Component? _checkout;

		private static List<ExpansionItem>? _checkoutItems;

		private static int _stockScene = -1;

		private static int _stockGeneration = -1;

		internal static void Install(Harmony harmony)
		{
			Type type = Plugin.GameType("ExtractionPoint");
			Type type2 = Plugin.GameType("ShopManager");
			Type type3 = Plugin.GameType("SemiFunc");
			Type type4 = Plugin.GameType("PhysGrabber");
			Type type5 = Plugin.GameType("WorldSpaceUIValue");
			_room = Plugin.GameType("RoomVolume");
			_grabComponents = Array.ConvertAll(new string[6] { "Photon.Pun.PhotonView", "Photon.Pun.PhotonTransformView", "RoomVolumeCheck", "PhysGrabObjectCollider", "PhysGrabObjectImpactDetector", "PhysGrabObject" }, Plugin.GameType);
			_extractShop = Plugin.Field(type, "isShop");
			_checkoutState = Plugin.Field(type, "currentState");
			_extractRoom = Plugin.Field(type, "roomVolume");
			_roomExtraction = Plugin.Field(_room, "Extraction");
			_total = Plugin.Field(type2, "totalCost");
			_updateCost = Plugin.Method(type3, "ShopUpdateCost", typeof(void));
			_funds = (Func<int>)Plugin.Method(type3, "StatGetRunCurrency", typeof(int)).CreateDelegate(typeof(Func<int>));
			_setFunds = (Func<int, int>)Plugin.Method(type3, "StatSetRunCurrency", typeof(int), typeof(int)).CreateDelegate(typeof(Func<int, int>));
			_ui = Plugin.Field(type5, "instance");
			_aimed = Plugin.Field(type4, "currentlyLookingAtPhysGrabObject");
			_held = Plugin.Field(type4, "grabbedPhysGrabObject");
			_grabbed = Plugin.Field(type4, "grabbed");
			_local = Plugin.Field(type4, "isLocal");
			_showPrice = Plugin.Method(type5, "Show", typeof(void), _grabComponents[5], typeof(int), typeof(bool), typeof(Vector3));
			_indestructible = Plugin.Method(_grabComponents[5], "OverrideIndestructible", typeof(void), typeof(float));
			harmony.Patch((MethodBase)Plugin.Method(type, "ShopSetup", typeof(void)), (HarmonyMethod)null, Hook("ShopSetup"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(type, "ShopHasItems", typeof(bool)), (HarmonyMethod)null, Hook("HasStockInCheckout"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(type, "OnShopClick", typeof(void)), Hook("BeforeCheckout"), Hook("AfterCheckout"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(type2, "ShopCheck", typeof(void)), (HarmonyMethod)null, Hook("AddCost"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(Plugin.GameType("PunManager"), "UpdateShoppingListRPC", typeof(void), typeof(int), typeof(string[]), typeof(int[]), Plugin.GameType("Photon.Pun.PhotonMessageInfo")), Hook("AddReceipt"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(type, "DestroyAllPhysObjectsInShoppingList", typeof(void)), (HarmonyMethod)null, Hook("Purchase"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(type4, "ShowValue", typeof(void)), (HarmonyMethod)null, Hook("ShowPrice"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(Plugin.GameType("TruckSafetySpawnPoint"), "Awake", typeof(void)), (HarmonyMethod)null, Hook("TruckAwake"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(Plugin.GameType("ChargingStation"), "Start", typeof(void)), (HarmonyMethod)null, Hook("ChargerStart"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Type type6 = Plugin.GameType("Photon.Pun.PhotonMessageInfo");
			string[] array = new string[3] { "ImpactLightRPC", "ImpactMediumRPC", "ImpactHeavyRPC" };
			foreach (string name in array)
			{
				harmony.Patch((MethodBase)Plugin.Method(_grabComponents[4], name, typeof(void), typeof(float), typeof(Vector3), type6), Hook("PlayNativeImpact"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool PlayNativeImpact(Component __instance)
		{
			ExpansionItem expansionItem = default(ExpansionItem);
			return !__instance.TryGetComponent<ExpansionItem>(ref expansionItem);
		}

		private static void ShopSetup(MonoBehaviour __instance)
		{
			object value = _extractShop.GetValue(__instance);
			if (value is bool && (bool)value)
			{
				__instance.StartCoroutine(PlaceShopStock((Component)(object)__instance));
			}
		}

		private static IEnumerator PlaceShopStock(Component checkout)
		{
			yield return (object)new WaitForSeconds(1f);
			yield return NetworkSession.WaitForRoom();
			if ((Object)(object)checkout == (Object)null || !Plugin.Shop() || !NetworkSession.Usable || ((Object)(object)_checkout != (Object)null && _checkout.gameObject.scene == checkout.gameObject.scene))
			{
				yield break;
			}
			_checkout = checkout;
			_checkoutItems = null;
			if (!NetworkSession.CanAct)
			{
				yield break;
			}
			Transform transform = checkout.transform;
			Vector3 val = Vector3.ProjectOnPlane(transform.right, Vector3.up);
			Vector3 normalized = ((Vector3)(ref val)).normalized;
			Vector3 val2 = Vector3.Cross(normalized, Vector3.up);
			Vector3 position = transform.position - normalized * 2.8f + val2 * 0.55f;
			position = FloorAt(position, transform.position.y);
			Vector3 val3 = position + Vector3.up * 0.38f;
			Quaternion val4 = Quaternion.LookRotation(val2);
			if (Plugin.Multiplayer())
			{
				NetworkSession.SpawnRack(val3, val4);
			}
			else
			{
				GameObject obj = BuildRack(networked: false);
				obj.transform.SetParent(transform, true);
				obj.transform.SetPositionAndRotation(val3, val4);
				obj.SetActive(true);
			}
			for (int i = 0; i < Plugin.ShopCount.Value; i++)
			{
				TrackSale(Spawn(position + normalized * ((float)(i % 5 - 2) * 0.26f) + val2 * ((float)(i / 5 % 3 - 1) * 0.26f) + Vector3.up * (0.53f + (float)(i / 15) * 0.25f), forSale: true, banked: false));
			}
			Plugin.LogInfo($"Placed {Sale.Count} cart expansions in SHOP at {Plugin.Price.Value}K each.");
			int previous = -1;
			WaitForSeconds interval = new WaitForSeconds(0.2f);
			while ((Object)(object)checkout != (Object)null && Plugin.Shop())
			{
				int count = InCheckout(checkout).Count;
				if (count != previous)
				{
					if (count > 0 || previous > 0)
					{
						Plugin.LogInfo($"SHOP checkout detected {count} cart expansions.");
					}
					previous = count;
					_updateCost.Invoke(null, null);
				}
				yield return interval;
			}
		}

		private static void TruckAwake(MonoBehaviour __instance)
		{
			__instance.StartCoroutine(PlaceTruckStock(((Component)__instance).transform));
		}

		private static void ChargerStart(MonoBehaviour __instance)
		{
			if (Plugin.Preparation())
			{
				__instance.StartCoroutine(PlaceTruckStock(((Component)__instance).transform));
			}
		}

		private static IEnumerator PlaceTruckStock(Transform anchor)
		{
			yield return null;
			yield return NetworkSession.WaitForRoom();
			if ((Object)(object)anchor == (Object)null || !Plugin.Active || !NetworkSession.CanAct)
			{
				yield break;
			}
			Scene activeScene = SceneManager.GetActiveScene();
			int num = SceneHandle.op_Implicit(((Scene)(ref activeScene)).handle);
			if (num != _stockScene || RunState.Generation != _stockGeneration)
			{
				_stockScene = num;
				_stockGeneration = RunState.Generation;
				if (Plugin.TestItems.Value && !RunState.TestGranted)
				{
					RunState.Pending += 5;
					RunState.TestGranted = true;
				}
				Vector3 val = Vector3.ProjectOnPlane(anchor.right, Vector3.up);
				Vector3 normalized = ((Vector3)(ref val)).normalized;
				Vector3 val2 = Vector3.Cross(normalized, Vector3.up);
				for (int i = 0; i < RunState.Pending; i++)
				{
					Spawn(FloorAt(anchor.position + normalized * ((float)(i % 5 - 2) * 0.29f) + val2 * (0.65f + (float)(i / 5 % 3) * 0.28f), anchor.position.y) + Vector3.up * (0.23f + (float)(i / 15) * 0.28f), forSale: false, banked: true);
				}
				if (RunState.Pending > 0)
				{
					Plugin.LogInfo($"Placed {RunState.Pending} cart expansions in the truck.");
				}
				if (Plugin.TestItems.Value && !Plugin.Multiplayer())
				{
					yield return TestHandgun.Place(anchor);
				}
			}
		}

		private static Vector3 FloorAt(Vector3 position, float height)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			RaycastHit val = default(RaycastHit);
			if (Physics.Raycast(new Vector3(position.x, height + 0.55f, position.z), Vector3.down, ref val, 2f, LayerMask.GetMask(new string[1] { "Default" }), (QueryTriggerInteraction)1))
			{
				position.y = ((RaycastHit)(ref val)).point.y;
			}
			return position;
		}

		private static ExpansionItem Spawn(Vector3 position, bool forSale, bool banked)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			int num = (forSale ? Plugin.Price.Value : 0);
			if (Plugin.Multiplayer())
			{
				return NetworkSession.SpawnBattery(position, forSale, banked, num).GetComponent<ExpansionItem>();
			}
			GameObject val = BuildBatteryPrefab(networked: false);
			val.transform.position = position;
			ExpansionItem component = val.GetComponent<ExpansionItem>();
			component.ForSale = forSale;
			component.Banked = banked;
			component.PriceK = num;
			val.SetActive(true);
			ProtectBattery(val);
			return component;
		}

		internal static GameObject BuildBatteryPrefab(bool networked)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.CreatePrimitive((PrimitiveType)3);
			val.SetActive(false);
			((Object)val).name = "Cart Capacity Expansion";
			val.layer = LayerMask.NameToLayer("PhysGrabObject");
			val.tag = "Phys Grab Object";
			val.transform.localScale = new Vector3(0.18f, 0.18f, 0.24f);
			BuildBatteryShell(val);
			val.AddComponent<ExpansionItem>();
			val.AddComponent<Rigidbody>();
			Type[] grabComponents = _grabComponents;
			foreach (Type type in grabComponents)
			{
				val.AddComponent(type);
			}
			if (networked)
			{
				PhotonView component = val.GetComponent<PhotonView>();
				component.ObservedComponents = new List<Component> { val.GetComponent(_grabComponents[1]) };
				component.Synchronization = (ViewSynchronization)3;
			}
			return val;
		}

		internal static GameObject BuildRack(bool networked)
		{
			//IL_002e: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.CreatePrimitive((PrimitiveType)3);
			val.SetActive(false);
			((Object)val).name = "Cart Expansion Shelf";
			val.transform.localScale = new Vector3(1.44f, 0.09f, 0.9f);
			Paint(val, new Color(0.12f, 0.2f, 0.23f));
			if (networked)
			{
				val.AddComponent<PhotonView>().Synchronization = (ViewSynchronization)0;
			}
			return val;
		}

		internal static void TrackSale(ExpansionItem item)
		{
			if (!Sale.Contains(item))
			{
				Sale.Add(item);
			}
		}

		internal static void UntrackSale(ExpansionItem item)
		{
			Sale.Remove(item);
		}

		internal static void ProtectBattery(GameObject battery)
		{
			_indestructible.Invoke(battery.GetComponent(_grabComponents[5]), new object[1] { float.MaxValue });
		}

		private static void BuildBatteryShell(GameObject root)
		{
			//IL_0094: 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_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: 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_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			MeshFilter component = root.GetComponent<MeshFilter>();
			Mesh sharedMesh = component.sharedMesh;
			Material material = ((Renderer)root.GetComponent<MeshRenderer>()).sharedMaterial;
			Mesh mesh = (component.sharedMesh = _batteryCylinder ?? (_batteryCylinder = BuildBatteryCylinder()));
			Color color = default(Color);
			((Color)(ref color))..ctor(0.14f, 0.16f, 0.17f);
			Color color2 = default(Color);
			((Color)(ref color2))..ctor(0.16f, 0.64f, 0.47f);
			Color color3 = default(Color);
			((Color)(ref color3))..ctor(0.71f, 0.76f, 0.76f);
			Paint(root, color);
			AddPart("Green cell band", mesh, Vector3.zero, new Vector3(1.015f, 1.015f, 0.36f), color2);
			float[] array = new float[2] { -1f, 1f };
			foreach (float num in array)
			{
				AddPart("Armored end cap", mesh, new Vector3(0f, 0f, num * 0.385f), new Vector3(1.23f, 1.23f, 0.19f), color);
				AddPart("Terminal ring", mesh, new Vector3(0f, 0f, num * 0.487f), new Vector3(0.84f, 0.84f, 0.045f), color2);
			}
			AddPart("Positive terminal", mesh, new Vector3(0f, 0f, -0.523f), new Vector3(0.48f, 0.48f, 0.06f), color3);
			AddPart("Negative contact", mesh, new Vector3(0f, 0f, 0.515f), new Vector3(0.64f, 0.64f, 0.035f), color3);
			AddPart("Battery marking stroke", sharedMesh, new Vector3(0f, 0.379f, 0f), new Vector3(0.3f, 0.025f, 0.052f), Color.white);
			AddPart("Battery marking stem", sharedMesh, new Vector3(0f, 0.384f, 0f), new Vector3(0.075f, 0.025f, 0.19f), Color.white);
			for (int j = 0; j < 4; j++)
			{
				Quaternion val2 = Quaternion.Euler(0f, 0f, 45f + (float)j * 90f);
				AddPart("Protective rail", sharedMesh, val2 * (Vector3.up * 0.447f), new Vector3(0.18f, 0.13f, 0.87f), color, val2);
			}
			void AddPart(string name, Mesh sharedMesh2, Vector3 position, Vector3 scale, Color color4, Quaternion? rotation = null)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: 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_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_0051: 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_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: 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_0080: Expected O, but got Unknown
				GameObject val3 = new GameObject(name);
				val3.transform.SetParent(root.transform, false);
				val3.transform.localPosition = position;
				val3.transform.localScale = scale;
				val3.transform.localRotation = (Quaternion)(((??)rotation) ?? Quaternion.identity);
				val3.AddComponent<MeshFilter>().sharedMesh = sharedMesh2;
				((Renderer)val3.AddComponent<MeshRenderer>()).sharedMaterial = material;
				Paint(val3, color4);
			}
		}

		private static Mesh BuildBatteryCylinder()
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: 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_0081: 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_0090: 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_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: 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_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: 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_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: 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_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: 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_00f3: 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)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: 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_0167: Expected O, but got Unknown
			List<Vector3> list = new List<Vector3>(48);
			List<int> list2 = new List<int>(84);
			for (int i = 0; i < 8; i++)
			{
				float num = ((float)i + 0.5f) * MathF.PI * 2f / 8f;
				float num2 = num + MathF.PI / 4f;
				Vector3 val = new Vector3(Mathf.Cos(num), Mathf.Sin(num), 0f) * 0.4f;
				Vector3 val2 = new Vector3(Mathf.Cos(num2), Mathf.Sin(num2), 0f) * 0.4f;
				Vector3 val3 = Vector3.forward * 0.5f;
				int count = list.Count;
				list.AddRange((IEnumerable<Vector3>)(object)new Vector3[6]
				{
					val - val3,
					val2 - val3,
					val2 + val3,
					val + val3,
					-val3,
					val3
				});
				int[] array = new int[12]
				{
					0, 1, 2, 0, 2, 3, 4, 1, 0, 5,
					3, 2
				};
				foreach (int num3 in array)
				{
					list2.Add(count + num3);
				}
			}
			Mesh val4 = new Mesh
			{
				name = "Octagonal capacity battery"
			};
			val4.SetVertices(list);
			val4.SetTriangles(list2, 0);
			val4.RecalculateNormals();
			return val4;
		}

		private static void Paint(GameObject target, Color color)
		{
			//IL_000c: 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_0022: Expected O, but got Unknown
			//IL_0028: 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_003f: Unknown result type (might be due to invalid IL or missing references)
			MeshRenderer component = target.GetComponent<MeshRenderer>();
			if (!PaintedMaterials.TryGetValue(color, out Material value))
			{
				value = new Material(((Renderer)component).sharedMaterial);
				value.SetColor("_Color", color);
				value.SetColor("_BaseColor", color);
				PaintedMaterials.Add(color, value);
			}
			((Renderer)component).sharedMaterial = value;
		}

		private static List<ExpansionItem> InCheckout(Component? checkout)
		{
			//IL_0089: 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_009f: 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)
			List<ExpansionItem> list = new List<ExpansionItem>();
			GameObject val = (GameObject)(((Object)(object)checkout != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
			Component val2 = (((Object)(object)val != (Object)null) ? (val.GetComponentInChildren(_room, true) ?? val.GetComponentInParent(_room)) : null);
			foreach (ExpansionItem item in Sale)
			{
				if ((Object)(object)item == (Object)null || !((Component)item).gameObject.activeInHierarchy)
				{
					continue;
				}
				Collider[] array = Physics.OverlapBox(((Component)item).transform.position, ((Component)item).transform.lossyScale * 0.5f, ((Component)item).transform.rotation, LayerMask.GetMask(new string[1] { "RoomVolume" }), (QueryTriggerInteraction)2);
				for (int i = 0; i < array.Length; i++)
				{
					Component componentInParent = ((Component)array[i]).GetComponentInParent(_room);
					if ((Object)(object)val2 == (Object)null || (Object)(object)val2 != (Object)(object)componentInParent)
					{
						if ((Object)(object)componentInParent == (Object)null)
						{
							continue;
						}
						object value = _roomExtraction.GetValue(componentInParent);
						if (!(value is bool) || !(bool)value)
						{
							continue;
						}
					}
					list.Add(item);
					break;
				}
			}
			return list;
		}

		private static void AddReceipt(ref int __0, ref string[] __1, ref int[] __2)
		{
			if (!Plugin.Shop() || !NetworkSession.Usable || (Object)(object)_checkout == (Object)null)
			{
				return;
			}
			List<ExpansionItem> list = InCheckout(_checkout);
			int count = list.Count;
			if (count != 0)
			{
				int num = TotalPrice(list);
				__0 = (int)Math.Min(2147483647L, (long)__0 + (long)num);
				if (__1 == null)
				{
					__1 = Array.Empty<string>();
				}
				if (__2 == null)
				{
					__2 = Array.Empty<int>();
				}
				Array.Resize(ref __1, __1.Length + 1);
				Array.Resize(ref __2, __2.Length + 1);
				__1[__1.Length - 1] = $"Cart capacity expansion x{count}";
				__2[__2.Length - 1] = num;
			}
		}

		private static void HasStockInCheckout(Component __instance, ref bool __result)
		{
			if (!__result && Plugin.Shop() && NetworkSession.Usable)
			{
				object value = _extractShop.GetValue(__instance);
				if (value is bool && (bool)value)
				{
					__result = InCheckout(__instance).Count > 0;
				}
			}
		}

		private static void AddCost(Component __instance)
		{
			if (Plugin.Shop() && NetworkSession.Usable)
			{
				_total.SetValue(__instance, (int)Math.Min(2147483647L, (long)(int)_total.GetValue(__instance) + (long)TotalPrice(InCheckout(_checkout))));
			}
		}

		private static void BeforeCheckout(Component __instance, out List<ExpansionItem>? __state)
		{
			__state = null;
			if (NetworkSession.CanAct && Plugin.Shop() && (Object)(object)__instance == (Object)(object)_checkout && Convert.ToInt32(_checkoutState.GetValue(__instance)) == 2)
			{
				__state = InCheckout(__instance);
			}
		}

		private static void AfterCheckout(Component __instance, List<ExpansionItem>? __state)
		{
			if (__state != null)
			{
				_checkoutItems = ((Convert.ToInt32(_checkoutState.GetValue(__instance)) == 3) ? __state : null);
			}
		}

		private static void Purchase(Component __instance)
		{
			if (!NetworkSession.CanAct || !Plugin.Shop())
			{
				return;
			}
			object value = _extractShop.GetValue(__instance);
			if (!(value is bool) || !(bool)value)
			{
				return;
			}
			List<ExpansionItem> list = (((Object)(object)__instance == (Object)(object)_checkout && _checkoutItems != null) ? _checkoutItems : InCheckout(__instance));
			_checkoutItems = null;
			list.RemoveAll((ExpansionItem item) => (Object)(object)item == (Object)null || !((Component)item).gameObject.activeInHierarchy);
			int num = TotalPrice(list);
			int num2 = _funds();
			if (list.Count == 0)
			{
				return;
			}
			if (num > num2)
			{
				Plugin.LogInfo($"Cart expansion purchase needs {num}K, with {num2}K available.");
				return;
			}
			_setFunds(num2 - num);
			RunState.Pending += list.Count;
			foreach (ExpansionItem item in list)
			{
				item.Consume();
			}
			_updateCost.Invoke(null, null);
			Plugin.LogInfo($"Purchased {list.Count} cart expansions for {num}K.");
		}

		private static void ShowPrice(Component __instance)
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkSession.Usable || !Plugin.Shop() || Cursor.visible)
			{
				return;
			}
			object value = _local.GetValue(__instance);
			if (!(value is bool) || !(bool)value)
			{
				return;
			}
			value = _grabbed.GetValue(__instance);
			object? value2 = ((value is bool && (bool)value) ? _held : _aimed).GetValue(__instance);
			Component val = (Component)((value2 is Component) ? value2 : null);
			ExpansionItem expansionItem = default(ExpansionItem);
			if ((Object)(object)val != (Object)null && val.TryGetComponent<ExpansionItem>(ref expansionItem) && expansionItem.ForSale)
			{
				object? value3 = _ui.GetValue(null);
				Component val2 = (Component)((value3 is Component) ? value3 : null);
				if (val2 != null && (Object)(object)val2 != (Object)null)
				{
					_showPrice.Invoke(val2, new object[4]
					{
						val,
						expansionItem.PriceK,
						true,
						Vector3.zero
					});
				}
			}
		}

		internal static void RefreshPrice()
		{
			_updateCost.Invoke(null, null);
		}

		private static int TotalPrice(List<ExpansionItem> items)
		{
			int num = 0;
			foreach (ExpansionItem item in items)
			{
				num += item.PriceK;
			}
			return num;
		}

		private static HarmonyMethod Hook(string name)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return new HarmonyMethod(typeof(ExpansionShop), name, (Type[])null);
		}
	}
	internal sealed class NetworkSession : MonoBehaviour
	{
		private const string Capability = "ccs:protocol";

		private const string Protocol = "1";

		private const string Energy = "ccs:energy";

		private const string Capacity = "ccs:capacity";

		private const string SnapshotRoom = "ccs:room";

		private const string BatteryPrefab = "CartChargingStation/Expansion";

		private const string RackPrefab = "CartChargingStation/ShopRack";

		private static NetworkSession? _instance;

		private readonly List<PhotonView> _objects = new List<PhotonView>();

		private Room? _room;

		private bool _prefabsReady;

		private int _initialHost;

		private float _nextTick;

		private float _sentEnergy = -1f;

		private float _sentCapacity = -1f;

		internal static bool Usable
		{
			get
			{
				if (Plugin.Multiplayer())
				{
					return CompatibleRoom();
				}
				return true;
			}
		}

		internal static bool CanAct
		{
			get
			{
				if (Usable)
				{
					if (Plugin.Multiplayer())
					{
						return PhotonNetwork.IsMasterClient;
					}
					return true;
				}
				return false;
			}
		}

		internal static bool CanSave
		{
			get
			{
				if (Plugin.Multiplayer())
				{
					return PhotonNetwork.IsMasterClient;
				}
				return true;
			}
		}

		private static bool CompatibleRoom()
		{
			NetworkSession instance = _instance;
			Room currentRoom = PhotonNetwork.CurrentRoom;
			if ((Object)(object)instance == (Object)null || !instance._prefabsReady || !PhotonNetwork.InRoom || currentRoom == null || currentRoom != instance._room || currentRoom.MasterClientId != instance._initialHost)
			{
				return false;
			}
			foreach (Player value2 in currentRoom.Players.Values)
			{
				if (!((Dictionary<object, object>)(object)value2.CustomProperties).TryGetValue((object)"ccs:protocol", out object value) || !(value is string text) || text != "1")
				{
					return false;
				}
			}
			return true;
		}

		internal void Initialize(Harmony harmony)
		{
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Expected O, but got Unknown
			_instance = this;
			try
			{
				Type type = Plugin.GameType("REPOLib.Modules.NetworkPrefabs");
				MethodInfo register = AccessTools.Method(type, "RegisterNetworkPrefab", new Type[2]
				{
					typeof(string),
					typeof(GameObject)
				}, (Type[])null) ?? throw new MissingMethodException(type.FullName, "RegisterNetworkPrefab");
				Register(ExpansionShop.BuildBatteryPrefab(networked: true), "CartChargingStation/Expansion");
				Register(ExpansionShop.BuildRack(networked: true), "CartChargingStation/ShopRack");
				harmony.Patch((MethodBase)Plugin.Method(Plugin.GameType("RunManager"), "RestartScene", typeof(void)), new HarmonyMethod(typeof(NetworkSession), "ClearSceneObjects", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_prefabsReady = true;
				Plugin.LogInfo("Cart multiplayer prefabs registered.");
				void Register(GameObject template, string prefabId)
				{
					try
					{
						Object.DontDestroyOnLoad((Object)(object)template);
						if (register.Invoke(null, new object[2] { prefabId, template }) == null)
						{
							throw new InvalidOperationException("Registration failed for " + prefabId + ".");
						}
					}
					catch
					{
						Object.Destroy((Object)(object)template);
						throw;
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Warn("Cart multiplayer unavailable: " + ex.GetBaseException().Message);
			}
		}

		internal static IEnumerator WaitForRoom()
		{
			float deadline = Time.realtimeSinceStartup + 30f;
			while (Plugin.Multiplayer() && !Usable && Time.realtimeSinceStartup < deadline)
			{
				yield return null;
			}
		}

		internal static GameObject SpawnBattery(Vector3 position, bool forSale, bool banked, int price)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return Spawn("CartChargingStation/Expansion", position, Quaternion.identity, new object[3] { forSale, banked, price });
		}

		internal static GameObject SpawnRack(Vector3 position, Quaternion rotation)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return Spawn("CartChargingStation/ShopRack", position, rotation, null);
		}

		private static GameObject Spawn(string prefab, Vector3 position, Quaternion rotation, object[]? data)
		{
			//IL_001a: 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)
			if (!CanAct || !PhotonNetwork.InRoom)
			{
				throw new InvalidOperationException("Only a compatible room host can spawn cart objects.");
			}
			GameObject obj = PhotonNetwork.InstantiateRoomObject(prefab, position, rotation, (byte)0, data) ?? throw new InvalidOperationException("Photon could not spawn " + prefab + ".");
			PhotonView item = default(PhotonView);
			if (obj.TryGetComponent<PhotonView>(ref item))
			{
				NetworkSession? instance = _instance;
				if (instance == null)
				{
					return obj;
				}
				instance._objects.Add(item);
			}
			return obj;
		}

		private static void ClearSceneObjects()
		{
			if ((Object)(object)_instance == (Object)null || !PhotonNetwork.InRoom || !PhotonNetwork.IsMasterClient)
			{
				return;
			}
			foreach (PhotonView @object in _instance._objects)
			{
				if ((Object)(object)@object != (Object)null && @object.ViewID > 0)
				{
					PhotonNetwork.Destroy(@object);
				}
			}
			_instance._objects.Clear();
		}

		private void Update()
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d5: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Expected O, but got Unknown
			//IL_0175: Expected O, but got Unknown
			if (Time.unscaledTime < _nextTick)
			{
				return;
			}
			_nextTick = Time.unscaledTime + 0.2f;
			Room val = ((PhotonNetwork.InRoom && !PhotonNetwork.OfflineMode) ? PhotonNetwork.CurrentRoom : null);
			if (val != _room)
			{
				_room = val;
				_initialHost = ((val != null) ? val.MasterClientId : 0);
				_sentEnergy = (_sentCapacity = -1f);
				_objects.Clear();
			}
			if (val == null || PhotonNetwork.LocalPlayer == null)
			{
				return;
			}
			string text = (_prefabsReady ? "1" : "");
			if (!((Dictionary<object, object>)(object)PhotonNetwork.LocalPlayer.CustomProperties).TryGetValue((object)"ccs:protocol", out object value) || !object.Equals(value, text))
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val2 = new Hashtable();
				((Dictionary<object, object>)val2).Add((object)"ccs:protocol", (object)text);
				localPlayer.SetCustomProperties(val2, (Hashtable)null, (WebFlags)null);
			}
			if (!CompatibleRoom())
			{
				return;
			}
			if (PhotonNetwork.IsMasterClient)
			{
				float num = Mathf.Round(RunState.Charge * 100f) / 100f;
				float num2 = Mathf.Round(RunState.Capacity * 100f) / 100f;
				if (_sentEnergy != num || _sentCapacity != num2)
				{
					Player localPlayer2 = PhotonNetwork.LocalPlayer;
					Hashtable val3 = new Hashtable();
					((Dictionary<object, object>)val3).Add((object)"ccs:energy", (object)num);
					((Dictionary<object, object>)val3).Add((object)"ccs:capacity", (object)num2);
					((Dictionary<object, object>)val3).Add((object)"ccs:room", (object)val.Name);
					if (localPlayer2.SetCustomProperties(val3, (Hashtable)null, (WebFlags)null))
					{
						_sentEnergy = num;
						_sentCapacity = num2;
					}
				}
			}
			else
			{
				Player player = val.GetPlayer(_initialHost, false);
				if (player != null && ((Dictionary<object, object>)(object)player.CustomProperties).TryGetValue((object)"ccs:room", out object value2) && object.Equals(value2, val.Name) && ((Dictionary<object, object>)(object)player.CustomProperties).TryGetValue((object)"ccs:energy", out object value3) && value3 is float num3 && ((Dictionary<object, object>)(object)player.CustomProperties).TryGetValue((object)"ccs:capacity", out object value4) && value4 is float num4 && num4 > 0f && num3 >= 0f && num3 <= num4)
				{
					RunState.Charge = num3;
					RunState.Capacity = num4;
				}
			}
		}
	}
	[BepInPlugin("ponyo.cartchargingstation", "Cart Charging Station", "0.2.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal const string Guid = "ponyo.cartchargingstation";

		internal const string Version = "0.2.0";

		internal static ConfigEntry<float> StartingCapacity;

		internal static ConfigEntry<float> ExpansionCapacity;

		internal static ConfigEntry<bool> TestItems;

		internal static ConfigEntry<int> Price;

		internal static ConfigEntry<int> ShopCount;

		internal static Func<bool> Mission;

		internal static Func<bool> Preparation;

		internal static Func<bool> Shop;

		internal static Func<bool> Multiplayer;

		private Harmony? _harmony;

		internal static Plugin Instance { get; private set; }

		internal static bool Active
		{
			get
			{
				if (NetworkSession.Usable)
				{
					if (!Mission())
					{
						return Preparation();
					}
					return true;
				}
				return false;
			}
		}

		private void Awake()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			Instance = this;
			StartingCapacity = ((BaseUnityPlugin)this).Config.Bind<float>("Charge", "StartingCapacity", 1f, new ConfigDescription("Initial maximum energy in crystal units.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 100f), Array.Empty<object>()));
			ExpansionCapacity = ((BaseUnityPlugin)this).Config.Bind<float>("Charge", "CapacityPerExpansion", 0.5f, new ConfigDescription("Capacity gained per expansion in crystal units.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 100f), Array.Empty<object>()));
			Price = ((BaseUnityPlugin)this).Config.Bind<int>("Shop", "PriceK", 50, new ConfigDescription("Price per expansion in thousands.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1000), Array.Empty<object>()));
			ShopCount = ((BaseUnityPlugin)this).Config.Bind<int>("Shop", "Stock", 10, new ConfigDescription("Expansions offered per Shop.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 30), Array.Empty<object>()));
			TestItems = ((BaseUnityPlugin)this).Config.Bind<bool>("Testing", "SpawnFiveExpansions", false, "Grant five free expansions once per run for testing.");
			_harmony = new Harmony("ponyo.cartchargingstation");
			try
			{
				Mission = Procedure("RunIsLevel");
				Preparation = Procedure("RunIsLobby");
				Shop = Procedure("RunIsShop");
				Multiplayer = Procedure("IsMultiplayer");
				RunState.Reset();
				RunState.Install(_harmony);
				CartCharge.Install(_harmony);
				ExpansionShop.Install(_harmony);
				ExpansionDiscount.Install(_harmony);
				((Component)this).gameObject.AddComponent<NetworkSession>().Initialize(_harmony);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Cart Charging Station 0.2.0 loaded.");
			}
			catch (Exception arg)
			{
				_harmony.UnpatchSelf();
				((BaseUnityPlugin)this).Logger.LogError((object)$"Cart Charging Station could not initialize: {arg}");
			}
		}

		private void OnDestroy()
		{
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		internal static void LogInfo(string message)
		{
			((BaseUnityPlugin)Instance).Logger.LogInfo((object)message);
		}

		internal static void Warn(string message)
		{
			((BaseUnityPlugin)Instance).Logger.LogWarning((object)message);
		}

		private static Func<bool> Procedure(string name)
		{
			return (Func<bool>)Method(GameType("SemiFunc"), name, typeof(bool)).CreateDelegate(typeof(Func<bool>));
		}

		internal static Type GameType(string name)
		{
			return AccessTools.TypeByName(name) ?? throw new TypeLoadException(name);
		}

		internal static FieldInfo Field(Type type, string name)
		{
			return AccessTools.Field(type, name) ?? throw new MissingFieldException(type.FullName, name);
		}

		internal static MethodInfo Method(Type type, string name, Type result, params Type[] args)
		{
			MethodInfo methodInfo = AccessTools.Method(type, name, args, (Type[])null);
			if (methodInfo?.ReturnType != result)
			{
				throw new MissingMethodException(type.FullName, name);
			}
			return methodInfo;
		}
	}
	internal static class RunState
	{
		internal static float Charge;

		internal static float Capacity;

		internal static int Pending;

		internal static bool TestGranted;

		private static FieldInfo _saveName;

		private static FieldInfo _saveReady;

		private static MethodInfo _checkpoint;

		internal static int Generation { get; private set; }

		internal static void Install(Harmony harmony)
		{
			Type type = Plugin.GameType("StatsManager");
			_saveName = Plugin.Field(type, "saveFileCurrent");
			_saveReady = Plugin.Field(type, "saveFileReady");
			_checkpoint = Plugin.Method(type, "GetRunStatSaveLevel", typeof(int));
			harmony.Patch((MethodBase)Plugin.Method(type, "SaveGame", typeof(void), typeof(string)), (HarmonyMethod)null, Hook("Save"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(type, "LoadGame", typeof(void), typeof(string), typeof(List<string>)), (HarmonyMethod)null, Hook("Load"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(type, "SaveFileCreate", typeof(void), typeof(string), typeof(bool)), (HarmonyMethod)null, Hook("NewSave"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Plugin.Method(Plugin.GameType("RunManager"), "ResetProgress", typeof(void)), (HarmonyMethod)null, Hook("Reset"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static void Reset()
		{
			Capacity = Plugin.StartingCapacity.Value;
			Charge = Mathf.Min(1f, Capacity);
			Pending = 0;
			TestGranted = false;
			Generation++;
		}

		private static void NewSave()
		{
			Reset();
		}

		private static void Save(object __instance, string __0)
		{
			if (!NetworkSession.CanSave || string.IsNullOrEmpty(__0))
			{
				return;
			}
			try
			{
				string text = PathFor(__0);
				Directory.CreateDirectory(Path.GetDirectoryName(text));
				string text2 = text + ".tmp";
				new XElement("cart", new XAttribute("checkpoint", (int)_checkpoint.Invoke(__instance, null)), new XAttribute("charge", Charge), new XAttribute("capacity", Capacity), new XAttribute("pending", Pending), new XAttribute("testGranted", TestGranted)).Save(text2);
				if (File.Exists(text))
				{
					File.Replace(text2, text, null);
				}
				else
				{
					File.Move(text2, text);
				}
			}
			catch (Exception ex)
			{
				Plugin.Warn("Cart save failed: " + ex.GetBaseException().Message);
			}
		}

		private static void Load(object __instance, string __0)
		{
			if (!NetworkSession.CanSave || string.IsNullOrEmpty(__0))
			{
				return;
			}
			object value = _saveReady.GetValue(__instance);
			if (!(value is bool) || !(bool)value || !string.Equals(_saveName.GetValue(__instance) as string, __0, StringComparison.Ordinal))
			{
				return;
			}
			Reset();
			try
			{
				string text = PathFor(__0);
				if (!File.Exists(text))
				{
					return;
				}
				XElement xElement = XElement.Load(text);
				if ((int?)xElement.Attribute("checkpoint") != (int)_checkpoint.Invoke(__instance, null))
				{
					Plugin.Warn("Cart save does not match the selected game checkpoint.");
					return;
				}
				float num = ((float?)xElement.Attribute("capacity")) ?? Capacity;
				float num2 = ((float?)xElement.Attribute("charge")) ?? Charge;
				int valueOrDefault = ((int?)xElement.Attribute("pending")).GetValueOrDefault();
				bool valueOrDefault2 = (bool?)xElement.Attribute("testGranted") == true;
				if (float.IsNaN(num) || float.IsInfinity(num) || num <= 0f || float.IsNaN(num2) || float.IsInfinity(num2) || valueOrDefault < 0)
				{
					throw new InvalidDataException("Invalid cart state.");
				}
				Capacity = num;
				Charge = Mathf.Clamp(num2, 0f, Capacity);
				Pending = valueOrDefault;
				TestGranted = valueOrDefault2;
				Plugin.LogInfo($"Restored cart energy {Charge:F2}/{Capacity:F2}, pending expansions {Pending}.");
			}
			catch (Exception ex)
			{
				Plugin.Warn("Cart load failed: " + ex.GetBaseException().Message);
			}
		}

		private static HarmonyMethod Hook(string name)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return new HarmonyMethod(typeof(RunState), name, (Type[])null);
		}

		private static string PathFor(string name)
		{
			using SHA256 sHA = SHA256.Create();
			string text = BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(name))).Replace("-", "");
			return Path.Combine(Paths.ConfigPath, "CartChargingStation", text + ".xml");
		}
	}
	internal static class TestHandgun
	{
		private static bool _spawned;

		internal static IEnumerator Place(Transform anchor)
		{
			if (_spawned)
			{
				yield break;
			}
			Type type = Plugin.GameType("StatsManager");
			FieldInfo instance = Plugin.Field(type, "instance");
			FieldInfo catalog = Plugin.Field(type, "itemDictionary");
			GameObject prefab = null;
			float deadline = Time.realtimeSinceStartup + 8f;
			while ((Object)(object)anchor != (Object)null && Plugin.Active && Time.realtimeSinceStartup < deadline)
			{
				object value = instance.GetValue(null);
				if (value != null && catalog.GetValue(value) is IDictionary dictionary)
				{
					object obj = dictionary["Item Gun Handgun"];
					if (obj != null)
					{
						object value2 = Plugin.Field(obj.GetType(), "prefab").GetValue(obj);
						if (value2 != null)
						{
							object? obj2 = Plugin.Method(value2.GetType(), "get_Prefab", typeof(GameObject)).Invoke(value2, null);
							prefab = (GameObject)((obj2 is GameObject) ? obj2 : null);
							if ((Object)(object)prefab != (Object)null)
							{
								break;
							}
						}
					}
				}
				yield return null;
			}
			if ((Object)(object)anchor == (Object)null || !Plugin.Active)
			{
				yield break;
			}
			if ((Object)(object)prefab == (Object)null)
			{
				Plugin.Warn("Could not find the native handgun prefab for the cart test.");
				yield break;
			}
			Type battery = Plugin.GameType("ItemBattery");
			FieldInfo life = Plugin.Field(battery, "batteryLife");
			Vector3 val = Vector3.ProjectOnPlane(anchor.right, Vector3.up);
			Vector3 normalized = ((Vector3)(ref val)).normalized;
			Vector3 val2 = Vector3.Cross(normalized, Vector3.up);
			Vector3 val3 = anchor.position + normalized * 0.85f + val2 * 0.95f;
			RaycastHit val4 = default(RaycastHit);
			if (Physics.Raycast(val3 + Vector3.up * 0.6f, Vector3.down, ref val4, 2f, LayerMask.GetMask(new string[1] { "Default" }), (QueryTriggerInteraction)1))
			{
				val3.y = ((RaycastHit)(ref val4)).point.y;
			}
			GameObject handgun = Object.Instantiate<GameObject>(prefab, val3 + Vector3.up * 0.34f, Quaternion.LookRotation(val2));
			_spawned = true;
			yield return null;
			if ((Object)(object)handgun != (Object)null)
			{
				Component componentInChildren = handgun.GetComponentInChildren(battery, true);
				if (componentInChildren != null && (Object)(object)componentInChildren != (Object)null)
				{
					life.SetValue(componentInChildren, 20f);
					Plugin.LogInfo("Placed a test handgun with 20% battery for cart charging.");
				}
			}
		}
	}
}