Decompiled source of CartWorkshop v0.2.23

plugins/CartWorkshop.dll

Decompiled 8 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
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 BepInEx.Logging;
using CartChargingStation;
using CartWorkshop;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using ScalerCore;
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("CartWorkshop")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.23.0")]
[assembly: AssemblyInformationalVersion("0.2.23")]
[assembly: AssemblyProduct("CartWorkshop")]
[assembly: AssemblyTitle("CartWorkshop")]
[assembly: AssemblyVersion("0.2.23.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 Func<Component, float, float>? _chargeHoragai;

		private static Type _battery = null;

		private static Type _attributes = null;

		private static FieldInfo _itemId = 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 = AccessTools.TypeByName("WeaponUpgradeStation.Integration.EnemyBeacon");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "ReceiveCartCharge", new Type[2]
			{
				typeof(Component),
				typeof(float)
			}, (Type[])null));
			if ((object)methodInfo != null && methodInfo.IsStatic && methodInfo.ReturnType == typeof(float))
			{
				_chargeHoragai = (Func<Component, float, float>)methodInfo.CreateDelegate(typeof(Func<Component, float, float>));
			}
			Type type2 = ChargingFeature.GameType("PhysGrabCart");
			_battery = ChargingFeature.GameType("ItemBattery");
			_attributes = ChargingFeature.GameType("ItemAttributes");
			_itemId = ChargingFeature.Field(_attributes, "instanceName");
			Type type3 = ChargingFeature.GameType("ChargingStation");
			_small = ChargingFeature.Field(type2, "isSmallCart");
			_contents = ChargingFeature.Field(type2, "itemsInCart");
			_basket = ChargingFeature.Field(type2, "inCart");
			_cartMesh = ChargingFeature.Field(type2, "cartMesh");
			_grabbed = ChargingFeature.Field(ChargingFeature.GameType("PhysGrabObject"), "grabbed");
			_stationInstance = ChargingFeature.Field(type3, "instance");
			_chargeArea = ChargingFeature.Field(type3, "chargeArea");
			_chargerCylinder = ChargingFeature.Field(type3, "crystalCylinder");
			_stationCharge = ChargingFeature.Field(type3, "chargeFloat");
			_stationTotal = ChargingFeature.Field(type3, "chargeTotal");
			_crystalEnergy = ChargingFeature.Field(type3, "energyPerCrystal");
			_batteryCost = ChargingFeature.Field(type3, "batteryChargeCost");
			_unchargable = ChargingFeature.Field(_battery, "isUnchargable");
			_receiveCharge = ChargingFeature.Method(_battery, "ReceiveCharge", typeof(float), typeof(float));
			harmony.Patch((MethodBase)ChargingFeature.Method(type2, "Start", typeof(void)), (HarmonyMethod)null, Hook("AttachReadout"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ChargingFeature.Method(type3, "ChargeAreaCheck", typeof(void)), Hook("ScanDock"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ChargingFeature.Method(type3, "ChargeItems", typeof(float)), (HarmonyMethod)null, Hook("ChargeFromTruck"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void AttachReadout(Component __instance)
		{
			if (ChargingFeature.Mission() || ChargingFeature.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), __instance.GetComponent(_attributes));
					Carts.Add(cartReadout);
				}
			}
		}

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

		internal static string? GetNativeId(Component attributes)
		{
			return _itemId.GetValue(attributes) as string;
		}

		internal static bool HasCartKey(CartReadout candidate, string key)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			foreach (CartReadout cart in Carts)
			{
				if ((Object)(object)cart != (Object)null && (Object)(object)cart != (Object)(object)candidate && ((Component)cart).gameObject.scene == ((Component)candidate).gameObject.scene && cart.StateKey == key)
				{
					return true;
				}
			}
			return false;
		}

		internal static void CollectNetworkCarts(SortedDictionary<int, CartBatteryState> carts)
		{
			foreach (CartReadout cart in Carts)
			{
				if ((Object)(object)cart != (Object)null && ((Behaviour)cart).isActiveAndEnabled && cart.ViewId > 0)
				{
					CartBatteryState hostBattery = cart.GetHostBattery();
					if (hostBattery != null)
					{
						carts[cart.ViewId] = hostBattery;
					}
				}
			}
		}

		internal static void UpdateContents(Component cart, CartBatteryState state, float elapsed)
		{
			if (!ChargingFeature.Active || !NetworkSession.CanAct)
			{
				return;
			}
			Func<GameObject, bool>? isStowed = WorkshopShop.IsStowed;
			if ((isStowed != null && isStowed(cart.gameObject)) || !(_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))
				{
					if (!expansionItem.ForSale && expansionItem.Kind == UpgradeKind.Battery && expansionItem.Consume())
					{
						state.Capacity += ChargingFeature.ExpansionCapacity.Value;
						ChargingFeature.LogInfo($"Cart upgraded to {state.Capacity:F2} crystals.");
					}
				}
				else
				{
					if (state.Charge <= 0f)
					{
						continue;
					}
					Component componentInChildren = val2.GetComponentInChildren(_battery);
					if ((Object)(object)componentInChildren != (Object)null)
					{
						value2 = _unchargable.GetValue(componentInChildren);
						if (value2 is bool && (bool)value2)
						{
							continue;
						}
					}
					float num4 = Mathf.Min(20f * elapsed, state.Charge / num);
					float num5 = (((Object)(object)componentInChildren != (Object)null) ? ((float)_receiveCharge.Invoke(componentInChildren, new object[1] { num4 })) : (_chargeHoragai?.Invoke(val2, num4) ?? 0f));
					state.Charge = Mathf.Max(0f, state.Charge - num5 * num);
				}
			}
		}

		private static void ScanDock(Component __instance)
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: 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)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			if (!ChargingFeature.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)
				{
					continue;
				}
				Func<GameObject, bool>? isStowed = WorkshopShop.IsStowed;
				if (isStowed != null && isStowed(((Component)cart).gameObject))
				{
					continue;
				}
				CartBatteryState hostBattery = cart.GetHostBattery();
				if (hostBattery != null && !(hostBattery.Charge >= hostBattery.Capacity))
				{
					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)
			{
				CartBatteryState hostBattery2 = cartReadout.GetHostBattery();
				if (hostBattery2 != null)
				{
					float num3 = (float)_stationCharge.GetValue(__instance);
					ChargingFeature.LogInfo($"Cart dock detected ({num:F2} m). Charger energy: {num3:P1}. Cart: {hostBattery2.Charge:F2}/{hostBattery2.Capacity:F2} crystals.");
				}
			}
			if ((Object)(object)cartReadout != (Object)(object)_dockedCart)
			{
				_loggedTransfer = false;
			}
			_dockedCart = cartReadout;
		}

		private static void ChargeFromTruck(Component __instance, ref float __result)
		{
			if (!ChargingFeature.Active || !NetworkSession.CanAct || (Object)(object)_scannedStation != (Object)(object)__instance || (Object)(object)_dockedCart == (Object)null)
			{
				return;
			}
			Func<GameObject, bool>? isStowed = WorkshopShop.IsStowed;
			if (isStowed != null && isStowed(((Component)_dockedCart).gameObject))
			{
				return;
			}
			CartBatteryState hostBattery = _dockedCart.GetHostBattery();
			if (hostBattery == null || hostBattery.Charge >= hostBattery.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,
				hostBattery.Capacity - hostBattery.Charge,
				num3 / num4
			});
			if (!(num5 <= 0f))
			{
				num3 = Mathf.Max(0f, num3 - num5 * num4);
				hostBattery.Charge = Mathf.Min(hostBattery.Capacity, hostBattery.Charge + num5);
				_stationCharge.SetValue(__instance, num3);
				_stationTotal.SetValue(__instance, Mathf.Clamp((int)(num3 * 100f), 0, 100));
				if (!_loggedTransfer)
				{
					_loggedTransfer = true;
					ChargingFeature.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 Component? _attributes;

		private PhotonView? _view;

		private CartBatteryState? _hostBattery;

		private int _batteryGeneration = -1;

		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 string? StateKey { get; private set; }

		internal int ViewId
		{
			get
			{
				if (!((Object)(object)_view != (Object)null))
				{
					return 0;
				}
				return _view.ViewID;
			}
		}

		internal void Initialize(Component cart, Transform? basket, MeshRenderer? body, Component? attributes)
		{
			//IL_0031: 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_003a: 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_00af: 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_00c4: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: 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_00ae: Expected O, but got Unknown
			//IL_00e3: 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_0132: 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_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: 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_019b: 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_01ae: 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_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			_cart = cart;
			_attributes = attributes;
			_view = cart.GetComponent<PhotonView>();
			_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)
			{
				ChargingFeature.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(ChargingFeature.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);
			}
		}

		internal CartBatteryState? GetHostBattery()
		{
			if (_batteryGeneration != RunState.Generation)
			{
				_batteryGeneration = RunState.Generation;
				_hostBattery = null;
				StateKey = null;
			}
			if (_hostBattery != null)
			{
				return _hostBattery;
			}
			if ((Object)(object)_attributes != (Object)null)
			{
				string nativeId = CartCharge.GetNativeId(_attributes);
				if (string.IsNullOrWhiteSpace(nativeId))
				{
					return null;
				}
				StateKey = "item:" + nativeId;
			}
			else
			{
				StateKey = "truck:default";
			}
			if (CartCharge.HasCartKey(this, StateKey))
			{
				StateKey = null;
				return _hostBattery = RunState.NewCart();
			}
			return _hostBattery = RunState.GetCart(StateKey);
		}

		internal CartBatteryState? BatteryForDisplay()
		{
			if (!NetworkSession.CanAct)
			{
				return NetworkSession.RemoteBattery(ViewId);
			}
			return GetHostBattery();
		}

		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;
			CartBatteryState cartBatteryState = null;
			if (ChargingFeature.Active)
			{
				if (NetworkSession.CanAct)
				{
					cartBatteryState = GetHostBattery();
					if (cartBatteryState != null)
					{
						CartCharge.UpdateContents(_cart, cartBatteryState, 0.2f);
					}
				}
				else
				{
					cartBatteryState = NetworkSession.RemoteBattery(ViewId);
				}
			}
			foreach (GameObject panel in _panels)
			{
				panel.SetActive(cartBatteryState != null);
			}
			if (cartBatteryState != null)
			{
				string text = FormattableString.Invariant($"{cartBatteryState.Charge:F2}/{cartBatteryState.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 = ChargingFeature.GameType("ShopKeeper");
				Type type2 = ChargingFeature.GameType("PhysGrabObject");
				_target = ChargingFeature.Field(type, "itemReactObject");
				_range = ChargingFeature.Field(type, "itemLikeDiscountRange");
				_minimum = ChargingFeature.Field(type, "itemLikeDiscountMinimumValue");
				_center = ChargingFeature.Field(type2, "centerPoint");
				_targetValid = ChargingFeature.Method(type, "ItemTargetValid", typeof(bool));
				_feedback = ChargingFeature.Method(type, "ItemDiscountLogic", typeof(void), type2, typeof(Vector3), typeof(int));
				MethodInfo methodInfo = ChargingFeature.Method(type, "ItemDiscountTargetValid", typeof(bool), type2);
				MethodInfo methodInfo2 = ChargingFeature.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)
			{
				ChargingFeature.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
				});
				ChargingFeature.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)
			{
				ChargingFeature.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) || !ChargingFeature.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 UpgradeKind Kind;

		internal int PriceK;

		private bool _consumed;

		internal bool Consume()
		{
			if (_consumed)
			{
				return false;
			}
			_consumed = true;
			if (Banked)
			{
				ref int reference = ref RunState.PendingOf(Kind);
				reference = Math.Max(0, reference - 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 == 7 && instantiationData[3] is bool forSale && instantiationData[4] is bool banked && instantiationData[5] is int priceK && (instantiationData[6] is bool || instantiationData[6] is int))
			{
				ForSale = forSale;
				Banked = banked;
				PriceK = priceK;
				Kind = ((instantiationData[6] is int num) ? ((UpgradeKind)num) : (((bool)instantiationData[6]) ? UpgradeKind.Compression : UpgradeKind.Battery));
				if (ForSale)
				{
					ExpansionShop.TrackSale(this);
				}
				ExpansionShop.ProtectBattery(((Component)this).gameObject);
			}
		}

		internal void SetPrice(int price)
		{
			PriceK = price;
			PhotonView val = default(PhotonView);
			if (ChargingFeature.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
	{
		internal static readonly Vector3 BatteryScale = new Vector3(0.18f, 0.18f, 0.24f);

		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 = ChargingFeature.GameType("ExtractionPoint");
			Type type2 = ChargingFeature.GameType("ShopManager");
			Type type3 = ChargingFeature.GameType("SemiFunc");
			Type type4 = ChargingFeature.GameType("PhysGrabber");
			Type type5 = ChargingFeature.GameType("WorldSpaceUIValue");
			_room = ChargingFeature.GameType("RoomVolume");
			_grabComponents = Array.ConvertAll(new string[6] { "Photon.Pun.PhotonView", "Photon.Pun.PhotonTransformView", "RoomVolumeCheck", "PhysGrabObjectCollider", "PhysGrabObjectImpactDetector", "PhysGrabObject" }, ChargingFeature.GameType);
			_extractShop = ChargingFeature.Field(type, "isShop");
			_checkoutState = ChargingFeature.Field(type, "currentState");
			_extractRoom = ChargingFeature.Field(type, "roomVolume");
			_roomExtraction = ChargingFeature.Field(_room, "Extraction");
			_total = ChargingFeature.Field(type2, "totalCost");
			_updateCost = ChargingFeature.Method(type3, "ShopUpdateCost", typeof(void));
			_funds = (Func<int>)ChargingFeature.Method(type3, "StatGetRunCurrency", typeof(int)).CreateDelegate(typeof(Func<int>));
			_setFunds = (Func<int, int>)ChargingFeature.Method(type3, "StatSetRunCurrency", typeof(int), typeof(int)).CreateDelegate(typeof(Func<int, int>));
			_ui = ChargingFeature.Field(type5, "instance");
			_aimed = ChargingFeature.Field(type4, "currentlyLookingAtPhysGrabObject");
			_held = ChargingFeature.Field(type4, "grabbedPhysGrabObject");
			_grabbed = ChargingFeature.Field(type4, "grabbed");
			_local = ChargingFeature.Field(type4, "isLocal");
			_showPrice = ChargingFeature.Method(type5, "Show", typeof(void), _grabComponents[5], typeof(int), typeof(bool), typeof(Vector3));
			_indestructible = ChargingFeature.Method(_grabComponents[5], "OverrideIndestructible", typeof(void), typeof(float));
			harmony.Patch((MethodBase)ChargingFeature.Method(type, "ShopSetup", typeof(void)), (HarmonyMethod)null, Hook("ShopSetup"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ChargingFeature.Method(type, "ShopHasItems", typeof(bool)), (HarmonyMethod)null, Hook("HasStockInCheckout"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ChargingFeature.Method(type, "OnShopClick", typeof(void)), Hook("BeforeCheckout"), Hook("AfterCheckout"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ChargingFeature.Method(type2, "ShopCheck", typeof(void)), (HarmonyMethod)null, Hook("AddCost"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ChargingFeature.Method(ChargingFeature.GameType("PunManager"), "UpdateShoppingListRPC", typeof(void), typeof(int), typeof(string[]), typeof(int[]), ChargingFeature.GameType("Photon.Pun.PhotonMessageInfo")), Hook("AddReceipt"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ChargingFeature.Method(type, "DestroyAllPhysObjectsInShoppingList", typeof(void)), (HarmonyMethod)null, Hook("Purchase"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ChargingFeature.Method(type4, "ShowValue", typeof(void)), (HarmonyMethod)null, Hook("ShowPrice"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ChargingFeature.Method(ChargingFeature.GameType("TruckSafetySpawnPoint"), "Awake", typeof(void)), (HarmonyMethod)null, Hook("TruckAwake"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ChargingFeature.Method(ChargingFeature.GameType("ChargingStation"), "Start", typeof(void)), (HarmonyMethod)null, Hook("ChargerStart"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Type type6 = ChargingFeature.GameType("Photon.Pun.PhotonMessageInfo");
			string[] array = new string[3] { "ImpactLightRPC", "ImpactMediumRPC", "ImpactHeavyRPC" };
			foreach (string name in array)
			{
				harmony.Patch((MethodBase)ChargingFeature.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 || !ChargingFeature.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 (ChargingFeature.Multiplayer())
			{
				NetworkSession.SpawnRack(val3, val4);
			}
			else
			{
				GameObject obj = BuildRack(networked: false);
				obj.transform.SetParent(transform, true);
				obj.transform.SetPositionAndRotation(val3, val4);
				obj.SetActive(true);
			}
			Dictionary<UpgradeKind, int> dictionary = new Dictionary<UpgradeKind, int>();
			UpgradeKind[] upgrades = WorkshopShop.Upgrades;
			int num = WorkshopShop.PocketStockLimit?.Invoke() ?? 0;
			List<UpgradeKind> list = new List<UpgradeKind>();
			if (upgrades.Length == 0)
			{
				for (int i = 0; i < ChargingFeature.ShopCount.Value; i++)
				{
					list.Add(UpgradeKind.Battery);
				}
			}
			else
			{
				list.Add(UpgradeKind.Battery);
				list.Add(UpgradeKind.Battery);
				List<UpgradeKind> list2 = new List<UpgradeKind> { UpgradeKind.Battery };
				UpgradeKind[] array = upgrades;
				foreach (UpgradeKind upgradeKind in array)
				{
					if (upgradeKind != UpgradeKind.Pocket || num != 0)
					{
						list.Add(upgradeKind);
						list2.Add(upgradeKind);
						if (upgradeKind == UpgradeKind.Pocket && --num == 0)
						{
							list2.Remove(upgradeKind);
						}
					}
				}
				while (list.Count < 12)
				{
					UpgradeKind upgradeKind2 = list2[Random.Range(0, list2.Count)];
					list.Add(upgradeKind2);
					if (upgradeKind2 == UpgradeKind.Pocket && --num == 0)
					{
						list2.Remove(upgradeKind2);
					}
				}
			}
			for (int k = 0; k < list.Count; k++)
			{
				Vector3 position2 = position + normalized * ((float)(k % 5 - 2) * 0.26f) + val2 * ((float)(k / 5 % 3 - 1) * 0.26f) + Vector3.up * (0.53f + (float)(k / 15) * 0.25f);
				UpgradeKind upgradeKind3 = list[k];
				TrackSale(Spawn(position2, forSale: true, banked: false, upgradeKind3));
				dictionary.TryGetValue(upgradeKind3, out var value);
				dictionary[upgradeKind3] = value + 1;
			}
			foreach (KeyValuePair<UpgradeKind, int> item in dictionary)
			{
				ChargingFeature.LogInfo($"SHOP stocked {item.Value} x {WorkshopShop.Label(item.Key)}.");
			}
			int previous = -1;
			WaitForSeconds interval = new WaitForSeconds(0.2f);
			while ((Object)(object)checkout != (Object)null && ChargingFeature.Shop())
			{
				int count = InCheckout(checkout).Count;
				if (count != previous)
				{
					if (count > 0 || previous > 0)
					{
						ChargingFeature.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 (ChargingFeature.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 || !ChargingFeature.Active || !NetworkSession.CanAct)
			{
				yield break;
			}
			Scene activeScene = SceneManager.GetActiveScene();
			int num = SceneHandle.op_Implicit(((Scene)(ref activeScene)).handle);
			if (num == _stockScene && RunState.Generation == _stockGeneration)
			{
				yield break;
			}
			_stockScene = num;
			_stockGeneration = RunState.Generation;
			if (ChargingFeature.TestItems.Value && !RunState.TestGranted)
			{
				RunState.Pending += 5;
				RunState.TestGranted = true;
			}
			Vector3 val = Vector3.ProjectOnPlane(anchor.right, Vector3.up);
			Vector3 right = ((Vector3)(ref val)).normalized;
			Vector3 forward = Vector3.Cross(right, Vector3.up);
			int index = 0;
			Place(UpgradeKind.Battery, RunState.Pending, banked: true);
			UpgradeKind[] upgrades = WorkshopShop.Upgrades;
			foreach (UpgradeKind upgradeKind in upgrades)
			{
				Place(upgradeKind, RunState.PendingOf(upgradeKind), banked: true);
				if (ChargingFeature.Mission())
				{
					Place(upgradeKind, WorkshopShop.TestCount?.Invoke(upgradeKind) ?? 0, banked: false);
				}
			}
			if (ChargingFeature.TestItems.Value && !ChargingFeature.Multiplayer())
			{
				yield return TestHandgun.Place(anchor);
			}
			void Place(UpgradeKind kind, int count, bool banked)
			{
				//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_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: 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_006f: 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_008f: Unknown result type (might be due to invalid IL or missing references)
				int num2 = 0;
				while (num2 < count)
				{
					Spawn(FloorAt(anchor.position + right * ((float)(index % 5 - 2) * 0.29f) + forward * (0.65f + (float)(index / 5 % 3) * 0.28f), anchor.position.y) + Vector3.up * (0.23f + (float)(index / 15) * 0.28f), forSale: false, banked, kind);
					num2++;
					index++;
				}
				if (count > 0)
				{
					ChargingFeature.LogInfo(string.Format("Placed {0} {1} x {2} in the truck.", count, banked ? "stored" : "test", WorkshopShop.Label(kind)));
				}
			}
		}

		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, UpgradeKind kind)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			int num = (forSale ? ((kind == UpgradeKind.Battery) ? ChargingFeature.Price.Value : (WorkshopShop.PriceK?.Invoke(kind) ?? ChargingFeature.Price.Value)) : 0);
			if (ChargingFeature.Multiplayer())
			{
				return NetworkSession.SpawnBattery(position, forSale, banked, num, kind).GetComponent<ExpansionItem>();
			}
			GameObject val = BuildBatteryPrefab(networked: false, kind);
			val.transform.position = position;
			ExpansionItem component = val.GetComponent<ExpansionItem>();
			component.ForSale = forSale;
			component.Banked = banked;
			component.PriceK = num;
			component.Kind = kind;
			val.SetActive(true);
			ProtectBattery(val);
			return component;
		}

		internal static GameObject BuildBatteryPrefab(bool networked, UpgradeKind kind = UpgradeKind.Battery)
		{
			//IL_003b: 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)
			GameObject val = GameObject.CreatePrimitive((PrimitiveType)3);
			val.SetActive(false);
			((Object)val).name = WorkshopShop.Label(kind);
			val.layer = LayerMask.NameToLayer("PhysGrabObject");
			val.tag = "Phys Grab Object";
			val.transform.localScale = BatteryScale;
			BuildBatteryShell(val, kind);
			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, UpgradeKind kind)
		{
			//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_00a8: 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_00c0: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: 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_0137: 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_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_034a: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0363: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: 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 = (Color)(kind switch
			{
				UpgradeKind.Compression => new Color(0.58f, 0.24f, 0.84f), 
				UpgradeKind.Stamina => new Color(0.95f, 0.65f, 0.1f), 
				UpgradeKind.Pocket => new Color(0.14f, 0.62f, 0.92f), 
				UpgradeKind.Weight => new Color(0.96f, 0.35f, 0.18f), 
				_ => new Color(0.16f, 0.64f, 0.47f), 
			});
			Color color3 = default(Color);
			((Color)(ref color3))..ctor(0.71f, 0.76f, 0.76f);
			Paint(root, color);
			AddPart("Colored 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 (!ChargingFeature.Shop() || !NetworkSession.Usable || (Object)(object)_checkout == (Object)null)
			{
				return;
			}
			List<ExpansionItem> list = InCheckout(_checkout);
			if (list.Count == 0)
			{
				return;
			}
			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>();
			}
			List<string> list2 = new List<string>(__1);
			List<int> list3 = new List<int>(__2);
			foreach (UpgradeKind value in Enum.GetValues(typeof(UpgradeKind)))
			{
				int num2 = 0;
				int num3 = 0;
				foreach (ExpansionItem item in list)
				{
					if (item.Kind == value)
					{
						num2++;
						num3 += item.PriceK;
					}
				}
				if (num2 > 0)
				{
					list2.Add($"{WorkshopShop.Label(value)} x{num2}");
					list3.Add(num3);
				}
			}
			__1 = list2.ToArray();
			__2 = list3.ToArray();
		}

		private static void HasStockInCheckout(Component __instance, ref bool __result)
		{
			if (!__result && ChargingFeature.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 (ChargingFeature.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 && ChargingFeature.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 || !ChargingFeature.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)
			{
				ChargingFeature.LogInfo($"Cart expansion purchase needs {num}K, with {num2}K available.");
				return;
			}
			_setFunds(num2 - num);
			foreach (ExpansionItem item in list)
			{
				RunState.PendingOf(item.Kind)++;
				item.Consume();
			}
			_updateCost.Invoke(null, null);
			ChargingFeature.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 || !ChargingFeature.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 Snapshot = "ccs:carts";

		private const string SnapshotScene = "ccs:scene";

		private const string SnapshotRoom = "ccs:room";

		private const string BatteryPrefab = "CartChargingStation/Expansion";

		private const string CompressionPrefab = "CartChargingStation/CompressionExpansion";

		private const string StaminaPrefab = "CartWorkshop/StaminaUpgrade";

		private const string PocketPrefab = "CartWorkshop/PocketUpgrade";

		private const string WeightPrefab = "CartWorkshop/WeightUpgrade";

		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 string _protocol = "";

		private int _initialHost;

		private float _nextTick;

		private int _sceneHandle = -1;

		private string? _snapshot;

		private readonly Dictionary<int, CartBatteryState> _remote = new Dictionary<int, CartBatteryState>();

		private readonly SortedDictionary<int, CartBatteryState> _local = new SortedDictionary<int, CartBatteryState>();

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

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

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

		internal static CartBatteryState? RemoteBattery(int viewId)
		{
			if (!((Object)(object)_instance != (Object)null) || !_instance._remote.TryGetValue(viewId, out CartBatteryState value))
			{
				return null;
			}
			return value;
		}

		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 != instance._protocol)
				{
					return false;
				}
			}
			return true;
		}

		internal void Initialize(Harmony harmony, string protocol)
		{
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			_instance = this;
			_protocol = protocol;
			try
			{
				Type type = ChargingFeature.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.BuildBatteryPrefab(networked: true, UpgradeKind.Compression), "CartChargingStation/CompressionExpansion");
				Register(ExpansionShop.BuildBatteryPrefab(networked: true, UpgradeKind.Stamina), "CartWorkshop/StaminaUpgrade");
				Register(ExpansionShop.BuildBatteryPrefab(networked: true, UpgradeKind.Pocket), "CartWorkshop/PocketUpgrade");
				Register(ExpansionShop.BuildBatteryPrefab(networked: true, UpgradeKind.Weight), "CartWorkshop/WeightUpgrade");
				Register(ExpansionShop.BuildRack(networked: true), "CartChargingStation/ShopRack");
				harmony.Patch((MethodBase)ChargingFeature.Method(ChargingFeature.GameType("RunManager"), "RestartScene", typeof(void)), new HarmonyMethod(typeof(NetworkSession), "ClearSceneObjects", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_prefabsReady = true;
				ChargingFeature.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)
			{
				ChargingFeature.Warn("Cart multiplayer unavailable: " + ex.GetBaseException().Message);
			}
		}

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

		internal static GameObject SpawnBattery(Vector3 position, bool forSale, bool banked, int price, UpgradeKind kind)
		{
			//IL_0042: 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)
			return Spawn(kind switch
			{
				UpgradeKind.Compression => "CartChargingStation/CompressionExpansion", 
				UpgradeKind.Stamina => "CartWorkshop/StaminaUpgrade", 
				UpgradeKind.Pocket => "CartWorkshop/PocketUpgrade", 
				UpgradeKind.Weight => "CartWorkshop/WeightUpgrade", 
				_ => "CartChargingStation/Expansion", 
			}, position, Quaternion.identity, new object[7]
			{
				ExpansionShop.BatteryScale.x,
				ExpansionShop.BatteryScale.y,
				ExpansionShop.BatteryScale.z,
				forSale,
				banked,
				price,
				(_instance?._protocol == "4") ? ((object)(kind == UpgradeKind.Compression)) : ((object)(int)kind)
			});
		}

		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_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			//IL_00c9: Expected O, but got Unknown
			//IL_00d2: 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_00da: 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_00f4: 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_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Expected O, but got Unknown
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Expected O, but got Unknown
			//IL_021d: 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);
				_sceneHandle = -1;
				_objects.Clear();
			}
			if (val == null || PhotonNetwork.LocalPlayer == null)
			{
				return;
			}
			string text = (_prefabsReady ? _protocol : "");
			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;
			}
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).handle != SceneHandle.op_Implicit(_sceneHandle))
			{
				_sceneHandle = SceneHandle.op_Implicit(((Scene)(ref activeScene)).handle);
				_snapshot = null;
				_remote.Clear();
			}
			if (PhotonNetwork.IsMasterClient)
			{
				_local.Clear();
				CartCharge.CollectNetworkCarts(_local);
				StringBuilder stringBuilder = new StringBuilder();
				foreach (KeyValuePair<int, CartBatteryState> item in _local)
				{
					stringBuilder.Append(FormattableString.Invariant($"{item.Key},{item.Value.Charge:F2},{item.Value.Capacity:F2};"));
				}
				string text2 = stringBuilder.ToString();
				if (_snapshot != text2)
				{
					Player localPlayer2 = PhotonNetwork.LocalPlayer;
					Hashtable val3 = new Hashtable();
					((Dictionary<object, object>)val3).Add((object)"ccs:carts", (object)text2);
					((Dictionary<object, object>)val3).Add((object)"ccs:room", (object)val.Name);
					((Dictionary<object, object>)val3).Add((object)"ccs:scene", (object)((Scene)(ref activeScene)).name);
					if (localPlayer2.SetCustomProperties(val3, (Hashtable)null, (WebFlags)null))
					{
						_snapshot = text2;
					}
				}
				return;
			}
			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:scene", out object value3) || !object.Equals(value3, ((Scene)(ref activeScene)).name) || !((Dictionary<object, object>)(object)player.CustomProperties).TryGetValue((object)"ccs:carts", out object value4) || !(value4 is string text3) || !(_snapshot != text3))
			{
				return;
			}
			_remote.Clear();
			string[] array = text3.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split(',');
				if (array2.Length == 3 && int.TryParse(array2[0], NumberStyles.None, CultureInfo.InvariantCulture, out var result) && float.TryParse(array2[1], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var result2) && float.TryParse(array2[2], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var result3) && result > 0 && result3 > 0f && result2 >= 0f && result2 <= result3 && !float.IsInfinity(result3))
				{
					_remote[result] = new CartBatteryState(result2, result3);
				}
			}
			_snapshot = text3;
		}
	}
	internal static class ChargingFeature
	{
		private static ManualLogSource _log;

		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;

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

		internal static void Initialize(GameObject host, ConfigFile config, Harmony harmony, ManualLogSource log, string protocol = "4", ConfigFile? legacy = null)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Expected O, but got Unknown
			_log = log;
			StartingCapacity = config.Bind<float>("Charge", "StartingCapacity", Previous<float>("Charge", "StartingCapacity", 1f), new ConfigDescription("Initial maximum energy in crystal units.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 100f), Array.Empty<object>()));
			ExpansionCapacity = config.Bind<float>("Charge", "CapacityPerExpansion", Previous<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>()));
			int fallback = Previous<int>("Shop", "PriceK", 50);
			Price = Settings.BindPrice(config, "PriceK", "Charge", fallback, "Price per battery expansion in thousands.");
			int fallback2 = Previous<int>("Shop", "Stock", 10);
			ConfigDescription description = new ConfigDescription("Total number of cart upgrades offered per Shop.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 30), Array.Empty<object>());
			ShopCount = Settings.Move(config, "Shop", "Stock", "Stock", "Count", fallback2, description);
			TestItems = config.Bind<bool>("Testing", "SpawnFiveExpansions", Previous<bool>("Testing", "SpawnFiveExpansions", fallback: false), "Grant five free battery expansions once per run for testing.");
			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);
			host.AddComponent<NetworkSession>().Initialize(harmony, protocol);
			T Previous<T>(string section, string key, T val)
			{
				if (legacy != null)
				{
					return legacy.Bind<T>(section, key, val, (ConfigDescription)null).Value;
				}
				return val;
			}
		}

		internal static void LogInfo(string message)
		{
			_log.LogInfo((object)message);
		}

		internal static void Warn(string message)
		{
			_log.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 sealed class CartBatteryState
	{
		internal float Charge;

		internal float Capacity;

		internal CartBatteryState(float charge, float capacity)
		{
			Charge = charge;
			Capacity = capacity;
		}
	}
	internal static class RunState
	{
		private static readonly Dictionary<string, CartBatteryState> Carts = new Dictionary<string, CartBatteryState>(StringComparer.Ordinal);

		private static CartBatteryState? _legacyCart;

		internal static int Pending;

		internal static int PendingCompression;

		internal static int PendingStamina;

		internal static int PendingWeight;

		internal static int PendingPocket;

		internal static bool TestGranted;

		private static FieldInfo _saveName = null;

		private static FieldInfo _saveReady = null;

		private static MethodInfo _checkpoint = null;

		internal static int Generation { get; private set; }

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

		internal static void Reset()
		{
			Carts.Clear();
			_legacyCart = null;
			Pending = 0;
			PendingCompression = 0;
			PendingStamina = 0;
			PendingWeight = 0;
			PendingPocket = 0;
			TestGranted = false;
			Generation++;
		}

		internal static CartBatteryState NewCart()
		{
			return new CartBatteryState(Mathf.Min(1f, ChargingFeature.StartingCapacity.Value), ChargingFeature.StartingCapacity.Value);
		}

		internal static CartBatteryState GetCart(string id)
		{
			if (!Carts.TryGetValue(id, out CartBatteryState value))
			{
				value = _legacyCart ?? NewCart();
				if (_legacyCart != null)
				{
					ChargingFeature.LogInfo("Assigned the previous shared cart state to " + id + ".");
				}
				_legacyCart = null;
				Carts.Add(id, value);
			}
			return value;
		}

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

		internal static ref int PendingOf(UpgradeKind kind)
		{
			return kind switch
			{
				UpgradeKind.Compression => ref PendingCompression, 
				UpgradeKind.Stamina => ref PendingStamina, 
				UpgradeKind.Pocket => ref PendingPocket, 
				UpgradeKind.Weight => ref PendingWeight, 
				_ => ref Pending, 
			};
		}

		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";
				XElement xElement = new XElement("cart", new XAttribute("checkpoint", (int)_checkpoint.Invoke(__instance, null)), new XAttribute("version", 2), new XAttribute("pending", Pending), new XAttribute("testGranted", TestGranted), new XAttribute("pendingCompression", PendingCompression), new XAttribute("pendingStamina", PendingStamina), new XAttribute("pendingPocket", PendingPocket), new XAttribute("pendingWeight", PendingWeight));
				foreach (KeyValuePair<string, CartBatteryState> cart in Carts)
				{
					xElement.Add(WriteBattery("battery", cart.Value, new XAttribute("id", cart.Key)));
				}
				if (_legacyCart != null)
				{
					xElement.Add(WriteBattery("legacyBattery", _legacyCart));
				}
				xElement.Save(text2);
				if (File.Exists(text))
				{
					File.Replace(text2, text, null);
				}
				else
				{
					File.Move(text2, text);
				}
			}
			catch (Exception ex)
			{
				ChargingFeature.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))
				{
					ChargingFeature.Warn("Cart save does not match the selected game checkpoint.");
					return;
				}
				int valueOrDefault = ((int?)xElement.Attribute("pending")).GetValueOrDefault();
				int valueOrDefault2 = ((int?)xElement.Attribute("pendingCompression")).GetValueOrDefault();
				int valueOrDefault3 = ((int?)xElement.Attribute("pendingStamina")).GetValueOrDefault();
				int valueOrDefault4 = ((int?)xElement.Attribute("pendingPocket")).GetValueOrDefault();
				int valueOrDefault5 = ((int?)xElement.Attribute("pendingWeight")).GetValueOrDefault();
				bool valueOrDefault6 = (bool?)xElement.Attribute("testGranted") == true;
				if (valueOrDefault < 0 || valueOrDefault2 < 0 || valueOrDefault3 < 0 || valueOrDefault4 < 0 || valueOrDefault5 < 0)
				{
					throw new InvalidDataException("Invalid cart state.");
				}
				int num = ((int?)xElement.Attribute("version")) ?? 1;
				if (num != 1 && num != 2)
				{
					throw new InvalidDataException("Unsupported cart state version.");
				}
				Dictionary<string, CartBatteryState> dictionary = new Dictionary<string, CartBatteryState>(StringComparer.Ordinal);
				foreach (XElement item in xElement.Elements("battery"))
				{
					string text2 = (string?)item.Attribute("id");
					if (string.IsNullOrWhiteSpace(text2) || dictionary.ContainsKey(text2))
					{
						throw new InvalidDataException("Missing or duplicate cart ID.");
					}
					dictionary.Add(text2, ReadBattery(item));
				}
				XElement xElement2 = xElement.Element("legacyBattery");
				CartBatteryState legacyCart = ((xElement2 != null) ? ReadBattery(xElement2) : ((num == 1) ? ReadBattery(xElement) : null));
				foreach (KeyValuePair<string, CartBatteryState> item2 in dictionary)
				{
					Carts.Add(item2.Key, item2.Value);
				}
				_legacyCart = legacyCart;
				Pending = valueOrDefault;
				PendingCompression = valueOrDefault2;
				PendingStamina = valueOrDefault3;
				PendingPocket = valueOrDefault4;
				PendingWeight = valueOrDefault5;
				TestGranted = valueOrDefault6;
				ChargingFeature.LogInfo($"Restored {Carts.Count} individual carts, pending expansions {Pending}.");
			}
			catch (Exception ex)
			{
				ChargingFeature.Warn("Cart load faile