Decompiled source of TheDrill v0.1.10

BepInEx/plugins/TheDrill/TheDrill.dll

Decompiled 35 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using TMPro;
using TheDrill.Drill;
using TheDrill.Effects;
using TheDrill.Items;
using TheDrill.Models;
using TheDrill.NetcodePatcher;
using TheDrill.Networking;
using TheDrill.Patches;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Audio;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
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("TheDrillTeam")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Makes the giant drill under the Company building (71-Gordion) functional.")]
[assembly: AssemblyFileVersion("0.1.10.0")]
[assembly: AssemblyInformationalVersion("0.1.10")]
[assembly: AssemblyProduct("TheDrill")]
[assembly: AssemblyTitle("TheDrill")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.10.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TheDrill
{
	internal sealed class DrillConfig
	{
		public readonly ConfigEntry<bool> EnableMod;

		public readonly ConfigEntry<string> DrillObjectName;

		public readonly ConfigEntry<bool> ResetDrillWhenFired;

		public readonly Dictionary<DrillSlotId, ConfigEntry<string>> SlotAcceptedItems = new Dictionary<DrillSlotId, ConfigEntry<string>>();

		public readonly Dictionary<DrillSlotId, ConfigEntry<bool>> SlotRequired = new Dictionary<DrillSlotId, ConfigEntry<bool>>();

		public readonly ConfigEntry<string> SoundDonorItem;

		public readonly Dictionary<string, ConfigEntry<string>> HoldPositionOverride = new Dictionary<string, ConfigEntry<string>>();

		public readonly Dictionary<string, ConfigEntry<string>> HoldRotationOverride = new Dictionary<string, ConfigEntry<string>>();

		public readonly ConfigEntry<float> ChargerCooldownSeconds;

		public readonly ConfigEntry<int> ChargerOverloadDamage;

		public readonly ConfigEntry<float> SpinUpSeconds;

		public readonly ConfigEntry<float> TravelSeconds;

		public readonly ConfigEntry<float> TravelDistanceOverride;

		public readonly ConfigEntry<float> WallStopMargin;

		public readonly ConfigEntry<float> HeadSpinRpm;

		public readonly ConfigEntry<float> ShakeAmplitude;

		public readonly ConfigEntry<bool> CameraShake;

		public readonly ConfigEntry<bool> EffectsEnabled;

		public readonly ConfigEntry<float> EffectsVolume;

		public readonly ConfigEntry<bool> EffectLights;

		public readonly ConfigEntry<bool> EffectParticles;

		public readonly ConfigEntry<float> EffectsCullDistance;

		public readonly ConfigEntry<bool> DebugLogging;

		public readonly ConfigEntry<bool> ShowSlotGizmos;

		public readonly ConfigEntry<bool> DebugAcceptAnyItem;

		public DrillConfig(ConfigFile cfg)
		{
			//IL_03f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fe: Expected O, but got Unknown
			EnableMod = cfg.Bind<bool>("General", "EnableMod", true, "Master switch. When false the mod registers nothing.");
			DrillObjectName = cfg.Bind<string>("General", "DrillObjectName", "GiantDrill", "Name of the drill GameObject searched for in every loaded scene (vanilla: GiantDrill in CompanyBuilding). Change only if a Gordion overhaul mod renames it.");
			ResetDrillWhenFired = cfg.Bind<bool>("General", "ResetDrillWhenFired", true, "Host only. When the crew is fired (save reset), the drill loses all inserted parts and returns to its start position.");
			DrillSlotDefinition[] all = DrillSlotDefinitions.All;
			foreach (DrillSlotDefinition drillSlotDefinition in all)
			{
				string text = "Slot." + drillSlotDefinition.Id;
				SlotAcceptedItems[drillSlotDefinition.Id] = cfg.Bind<string>(text, "AcceptedItems", drillSlotDefinition.DefaultAcceptedItems, "Comma-separated rules. 'type:ClassName' matches a GrabbableObject class or base class (e.g. type:LungProp = any apparatus); anything else matches the item's in-game name (case-insensitive); '*' matches anything.");
				string text2 = PartNames.MigrateRules(SlotAcceptedItems[drillSlotDefinition.Id].Value);
				if (text2 != SlotAcceptedItems[drillSlotDefinition.Id].Value)
				{
					SlotAcceptedItems[drillSlotDefinition.Id].Value = text2;
				}
				SlotRequired[drillSlotDefinition.Id] = cfg.Bind<bool>(text, "RequiredToArm", drillSlotDefinition.RequiredToArm, "If true this slot must be filled before the drill can be started.");
			}
			SoundDonorItem = cfg.Bind<string>("Items", "SoundDonorItem", "Big bolt", "Vanilla item whose grab/drop sounds the drill parts borrow.");
			DrillPartSpec[] all2 = DrillPartSpec.All;
			foreach (DrillPartSpec drillPartSpec in all2)
			{
				string text3 = "Hold." + drillPartSpec.Key;
				HoldPositionOverride[drillPartSpec.Key] = cfg.Bind<string>(text3, "PositionOffset", "", "Local only, for tuning how '" + drillPartSpec.ItemName + "' sits in the hand. \"x,y,z\" overrides the built-in offset " + $"({drillPartSpec.PositionOffset.x}, {drillPartSpec.PositionOffset.y}, {drillPartSpec.PositionOffset.z}); empty = built-in. Applied on the next grab (LethalConfig edits work live).");
				HoldRotationOverride[drillPartSpec.Key] = cfg.Bind<string>(text3, "RotationOffset", "", $"Local only. \"x,y,z\" Euler degrees overriding the built-in ({drillPartSpec.RotationOffset.x}, {drillPartSpec.RotationOffset.y}, {drillPartSpec.RotationOffset.z}); empty = built-in.");
			}
			ChargerCooldownSeconds = cfg.Bind<float>("Battery", "ChargerCooldownSeconds", 30f, "Host only. After charging a High-Voltage Battery, the ship's charger is 'too hot to touch' for this many seconds.");
			ChargerOverloadDamage = cfg.Bind<int>("Battery", "ChargerOverloadDamage", 10, "Damage dealt to the player charging a High-Voltage Battery (never lethal). 0 disables.");
			SpinUpSeconds = cfg.Bind<float>("Motion", "SpinUpSeconds", 6f, "Seconds the drill head spins up before the drill starts moving.");
			TravelSeconds = cfg.Bind<float>("Motion", "TravelSeconds", 45f, "Seconds the drill takes to travel along its rail to the wall.");
			TravelDistanceOverride = cfg.Bind<float>("Motion", "TravelDistanceOverride", -1f, "Metres the drill travels. -1 = automatic: stop at the yellow DrillWallMark on the Company wall.");
			WallStopMargin = cfg.Bind<float>("Motion", "WallStopMargin", 0.3f, "Automatic mode only: metres short of the wall mark where the drill tip stops.");
			HeadSpinRpm = cfg.Bind<float>("Motion", "HeadSpinRpm", 90f, "Drill head spin speed at full power.");
			ShakeAmplitude = cfg.Bind<float>("Motion", "ShakeAmplitude", 0.02f, "Body vibration in metres while running (visual only).");
			CameraShake = cfg.Bind<bool>("Motion", "CameraShake", true, "Shake the camera of players near the running drill.");
			EffectsEnabled = cfg.Bind<bool>("Effects", "Enabled", true, "Local only. Sounds, sparks, lights and lamps for inserting parts and running the drill.");
			EffectsVolume = cfg.Bind<float>("Effects", "Volume", 1f, new ConfigDescription("Local only. Volume multiplier for all drill sounds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			EffectLights = cfg.Bind<bool>("Effects", "Lights", true, "Local only. Extra glow lights (no shadows). Turn off on low-end PCs.");
			EffectParticles = cfg.Bind<bool>("Effects", "Particles", true, "Local only. Spark particles.");
			EffectsCullDistance = cfg.Bind<float>("Effects", "CullDistance", 80f, "Local only. Beyond this distance (m) visual effects stop updating (sounds still fade naturally).");
			DebugLogging = cfg.Bind<bool>("Debug", "DebugLogging", false, "Verbose logging.");
			ShowSlotGizmos = cfg.Bind<bool>("Debug", "ShowSlotGizmos", false, "Draw translucent boxes over every slot's interact area (for tuning slot positions). Local only.");
			DebugAcceptAnyItem = cfg.Bind<bool>("Debug", "DebugAcceptAnyItem", false, "Host only. Every slot accepts any item. For testing the full sequence without the real parts.");
		}

		public string BuildSyncedRules()
		{
			List<string> list = new List<string>();
			DrillSlotDefinition[] all = DrillSlotDefinitions.All;
			foreach (DrillSlotDefinition drillSlotDefinition in all)
			{
				string arg = (DebugAcceptAnyItem.Value ? "*" : SlotAcceptedItems[drillSlotDefinition.Id].Value.Replace("|", "").Replace("=", ""));
				string arg2 = (SlotRequired[drillSlotDefinition.Id].Value ? "1" : "0");
				list.Add($"{(int)drillSlotDefinition.Id}={arg2}{arg}");
			}
			return string.Join("|", list);
		}
	}
	[BepInPlugin("TheDrillTeam.TheDrill", "TheDrill", "0.1.10")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		public static Plugin Instance { get; private set; }

		internal static ManualLogSource Log { get; private set; }

		internal static DrillConfig Cfg { get; private set; }

		private void Awake()
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Cfg = new DrillConfig(((BaseUnityPlugin)this).Config);
			if (!Cfg.EnableMod.Value)
			{
				Log.LogWarning((object)"TheDrill is disabled in config (General.EnableMod = false). Nothing was loaded.");
				return;
			}
			InitializeNetcodePatcherRpcs();
			DrillItems.CreateAndRegister();
			DrillNetworkHandler.CreatePrefab();
			_harmony = new Harmony("TheDrillTeam.TheDrill");
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			DrillSceneBinder.Initialize();
			Log.LogInfo((object)"TheDrill 0.1.10 loaded.");
		}

		private static void InitializeNetcodePatcherRpcs()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			foreach (Type type in types)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0)
					{
						try
						{
							methodInfo.Invoke(null, null);
						}
						catch (Exception arg)
						{
							Log.LogError((object)$"Netcode init failed for {type.FullName}.{methodInfo.Name}: {arg}");
						}
					}
				}
			}
		}

		internal static void Debug(string message)
		{
			if (Cfg != null && Cfg.DebugLogging.Value)
			{
				Log.LogInfo((object)("[debug] " + message));
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "TheDrillTeam.TheDrill";

		public const string PLUGIN_NAME = "TheDrill";

		public const string PLUGIN_VERSION = "0.1.10";
	}
}
namespace TheDrill.Patches
{
	[HarmonyPatch]
	internal static class ChipTerminal
	{
		private const int PurchaseSound = 0;

		private const int ErrorSound = 1;

		private static TerminalNode _confirm;

		private static TerminalNode _pending;

		private static TerminalNode _reply;

		private static Terminal _buyer;

		private static TerminalNode Screen(ref TerminalNode node, string text, bool clear, int sound, int maxChars)
		{
			if ((Object)(object)node == (Object)null)
			{
				node = ScriptableObject.CreateInstance<TerminalNode>();
				node.terminalOptions = Array.Empty<CompatibleNoun>();
			}
			node.displayText = text;
			node.clearPreviousText = clear;
			node.playSyncedClip = sound;
			node.maxCharactersToType = maxChars;
			return node;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
		private static bool Parse(Terminal __instance, ref TerminalNode __result)
		{
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			string text = __instance.screenText.text;
			int textAdded = __instance.textAdded;
			if (textAdded < 1 || textAdded > text.Length)
			{
				return true;
			}
			string text2 = text.Substring(text.Length - textAdded).Trim();
			bool flag = (Object)(object)_confirm != (Object)null && (Object)(object)__instance.currentNode == (Object)(object)_confirm;
			bool flag2 = !flag && AcquisitionRules.IsOrder(text2);
			if (!flag2 && !flag)
			{
				return true;
			}
			if (flag && !AcquisitionRules.IsConfirm(text2) && !AcquisitionRules.IsDeny(text2))
			{
				return true;
			}
			DrillNetworkHandler instance = DrillNetworkHandler.Instance;
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if ((Object)(object)instance == (Object)null || !((NetworkBehaviour)instance).IsSpawned || (Object)(object)val == (Object)null)
			{
				__result = Screen(ref _reply, "The ordering system is offline.\n\n", clear: false, 1, 35);
				return false;
			}
			if (flag && AcquisitionRules.IsDeny(text2))
			{
				__result = Screen(ref _reply, "Cancelled order.\n\n", clear: false, -1, 35);
				return false;
			}
			string text3 = AcquisitionRules.Reject(instance.ChipState, __instance.groupCredits, __instance.numberOfItemsInDropship, __instance.vehicleInDropship);
			if (text3 != null)
			{
				__result = Screen(ref _reply, text3, clear: false, 1, 35);
			}
			else if (flag2)
			{
				__result = Screen(ref _confirm, AcquisitionRules.RequestText, clear: true, -1, 15);
			}
			else
			{
				_buyer = __instance;
				__result = Screen(ref _pending, "Processing order...\n\n", clear: true, -1, 35);
				instance.BuyDataChipServerRpc((int)val.playerClientId);
			}
			return false;
		}

		internal static void Receipt(string message, bool success)
		{
			if ((Object)(object)_buyer != (Object)null && _buyer.terminalInUse && (Object)(object)_buyer.currentNode == (Object)(object)_pending)
			{
				_buyer.LoadNewNode(Screen(ref _reply, message, success, (!success) ? 1 : 0, 35));
			}
			_buyer = null;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ItemDropship), "Update")]
		private static void Dispatch(ItemDropship __instance, Terminal ___terminalScript)
		{
			DrillNetworkHandler instance = DrillNetworkHandler.Instance;
			if (!((Object)(object)instance == (Object)null) && ((NetworkBehaviour)instance).IsServer && instance.ChipState == ChipOrder.Queued && !__instance.deliveringOrder && !__instance.deliveringVehicle && !((Object)(object)___terminalScript == (Object)null) && ___terminalScript.orderedItemsFromTerminal.Count == 0 && ___terminalScript.orderedVehicleFromTerminal == -1 && !((Object)(object)StartOfRound.Instance == (Object)null) && StartOfRound.Instance.shipHasLanded)
			{
				if (__instance.playersFirstOrder)
				{
					__instance.playersFirstOrder = false;
					__instance.shipTimer = 20f;
				}
				__instance.shipTimer += Time.deltaTime;
				if (__instance.shipTimer > 40f)
				{
					AccessTools.Method(typeof(ItemDropship), "LandShipOnServer", (Type[])null, (Type[])null).Invoke(__instance, null);
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ItemDropship), "LandShipOnServer")]
		private static void OnFlight(ItemDropship __instance)
		{
			DrillNetworkHandler instance = DrillNetworkHandler.Instance;
			if ((Object)(object)instance != (Object)null && ((NetworkBehaviour)instance).IsServer && instance.ChipState == ChipOrder.Queued)
			{
				instance.ChipFlight = __instance;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ItemDropship), "OpenShipDoorsOnServer")]
		private static void Deliver(ItemDropship __instance, List<int> ___itemsToDeliver)
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			DrillNetworkHandler instance = DrillNetworkHandler.Instance;
			if (!((Object)(object)instance == (Object)null) && ((NetworkBehaviour)instance).IsServer && instance.ChipState == ChipOrder.Queued && !((Object)(object)instance.ChipFlight != (Object)(object)__instance) && __instance.shipLanded && !__instance.shipDoorsOpened && __instance.itemSpawnPositions != null && __instance.itemSpawnPositions.Length != 0)
			{
				Transform val = __instance.itemSpawnPositions[___itemsToDeliver.Count % __instance.itemSpawnPositions.Length];
				Item item = DrillItems.ByKey["DataChip"];
				if (!((Object)(object)val == (Object)null) && !((Object)(object)instance.ServerSpawnItem(item, val.position, DrillItems.RollValue(item), 0, levelScrap: false, StartOfRound.Instance.propsContainer) == (Object)null))
				{
					instance.ChipState = ChipOrder.Delivered;
					instance.ChipFlight = null;
					instance.ChipDelivered();
					Plugin.Debug("Data chip delivered. Further purchases locked for this campaign.");
				}
			}
		}
	}
	internal static class DebugCommands
	{
		public static void Run(string args)
		{
			DrillNetworkHandler handler = DrillNetworkHandler.Instance;
			string[] array = args.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			string text = ((array.Length != 0) ? array[0].ToLowerInvariant() : "status");
			if ((Object)(object)handler == (Object)null)
			{
				Tip("TheDrill", "Network handler not spawned yet.");
				return;
			}
			if (text == "status")
			{
				string body = string.Join("\n", DrillSlotDefinitions.All.Select((DrillSlotDefinition d) => string.Format("{0}: {1}", d.Id, (!handler.IsSlotFilled(d.Id)) ? "-" : (handler.GetSlotItem(d.Id)?.itemName ?? "?"))));
				Tip($"Drill: {handler.Phase}", body);
				return;
			}
			if (!((NetworkBehaviour)handler).IsServer)
			{
				Tip("TheDrill", "Only the host can use /drill " + text);
				return;
			}
			switch (text)
			{
			case "fill":
				handler.ServerDebugFillAll();
				Tip("TheDrill", (handler.Phase == DrillPhase.Armed) ? "All slots filled." : "Install any existing loose cable or battery by hand.");
				break;
			case "start":
				handler.ServerDebugFillAll();
				if (handler.Phase != DrillPhase.Armed)
				{
					Tip("TheDrill", "Install existing loose parts before starting.");
					break;
				}
				handler.ServerSetPhase(DrillPhase.SpinningUp);
				Tip("TheDrill", "Drill started.");
				break;
			case "reset":
				handler.ServerResetAll();
				Tip("TheDrill", "Drill reset.");
				break;
			case "chip":
				if (array.Length > 1 && array[1].Equals("reset", StringComparison.OrdinalIgnoreCase))
				{
					ChipOrder chipOrder = handler.ServerResetChipOrder();
					Tip("TheDrill", $"Data chip order reset (was {chipOrder}). It can be ordered again. Saved next time the game saves.");
				}
				else
				{
					Tip("TheDrill", $"Data chip order: {handler.ChipState}. Use /drill chip reset to clear it.");
				}
				break;
			case "give":
				Give(handler, (array.Length > 1) ? string.Join(" ", array.Skip(1)) : "Battery");
				break;
			default:
				Tip("TheDrill", "Commands: status, fill, start, reset, give <Battery|DataChip|Cable|Apparatus|Key|name>, chip [reset]");
				break;
			}
		}

		private static void Give(DrillNetworkHandler handler, string key)
		{
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			Item val = DrillItems.ByKey.FirstOrDefault((KeyValuePair<string, Item> pair) => string.Equals(pair.Key, key, StringComparison.OrdinalIgnoreCase)).Value;
			IEnumerable<Item> source = StartOfRound.Instance.allItemsList.itemsList.Where((Item i) => (Object)(object)i != (Object)null && (Object)(object)i.spawnPrefab != (Object)null && (Object)(object)i.spawnPrefab.GetComponent<GrabbableObject>() != (Object)null && (Object)(object)i.spawnPrefab.GetComponent<NetworkObject>() != (Object)null);
			if ((Object)(object)val == (Object)null)
			{
				val = source.FirstOrDefault((Func<Item, bool>)((Item i) => string.Equals(i.itemName, key, StringComparison.OrdinalIgnoreCase)));
			}
			if ((Object)(object)val == (Object)null && key.Equals("Apparatus", StringComparison.OrdinalIgnoreCase))
			{
				val = source.FirstOrDefault((Func<Item, bool>)((Item i) => (Object)(object)i.spawnPrefab.GetComponent<LungProp>() != (Object)null));
			}
			if ((Object)(object)val == (Object)null && key.Equals("Key", StringComparison.OrdinalIgnoreCase))
			{
				val = source.FirstOrDefault((Func<Item, bool>)((Item i) => (Object)(object)i.spawnPrefab.GetComponent<KeyItem>() != (Object)null));
			}
			if ((Object)(object)val == (Object)null)
			{
				val = source.FirstOrDefault((Func<Item, bool>)delegate(Item i)
				{
					string itemName = i.itemName;
					return itemName != null && itemName.IndexOf(key, StringComparison.OrdinalIgnoreCase) >= 0;
				});
			}
			if ((Object)(object)val == (Object)null)
			{
				Tip("TheDrill", "Unknown item: " + key);
				return;
			}
			if (handler.IsDuplicate(val))
			{
				Tip("TheDrill", val.itemName + " already exists.");
				return;
			}
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			Vector3 position = ((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 1.2f + Vector3.up * 0.5f;
			NetworkObject val2 = handler.ServerSpawnItem(val, position, DrillItems.RollValue(val), 0);
			Tip("TheDrill", (((Object)(object)val2 != (Object)null) ? "Spawned " : "Could not spawn ") + val.itemName);
		}

		private static void Tip(string header, string body)
		{
			if ((Object)(object)HUDManager.Instance != (Object)null)
			{
				HUDManager.Instance.DisplayTip(header, body, false, false, "LC_Tip1");
			}
			Plugin.Log.LogInfo((object)(header + ": " + body));
		}
	}
	[HarmonyPatch]
	internal static class GamePatches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		private static void StartOfRound_Awake(StartOfRound __instance)
		{
			DrillItems.FinalizeAssets(__instance);
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton != (Object)null && singleton.IsServer)
			{
				DrillSaveData.MigrateLethalLibItemOrder();
			}
			if (!((Object)(object)singleton == (Object)null) && singleton.IsServer && !((Object)(object)DrillNetworkHandler.Prefab == (Object)null))
			{
				Object.Instantiate<GameObject>(DrillNetworkHandler.Prefab).GetComponent<NetworkObject>().Spawn(false);
				Plugin.Debug("Spawned DrillNetworkHandler.");
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(GameNetworkManager), "SaveGame")]
		private static void GameNetworkManager_SaveGame_Pre(out bool __state)
		{
			GameNetworkManager instance = GameNetworkManager.Instance;
			StartOfRound instance2 = StartOfRound.Instance;
			__state = (Object)(object)instance != (Object)null && (Object)(object)instance2 != (Object)null && DrillSaveData.VanillaSavesProgress(instance.isHostingGame, instance2.isChallengeFile, instance2.inShipPhase, instance2.beganLoadingNewLevel, (Object)(object)RoundManager.Instance != (Object)null && RoundManager.Instance.dungeonIsGenerating);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "SaveGame")]
		private static void GameNetworkManager_SaveGame(bool __state)
		{
			DrillNetworkHandler instance = DrillNetworkHandler.Instance;
			if (!((Object)(object)instance == (Object)null) && ((NetworkBehaviour)instance).IsServer)
			{
				if (__state)
				{
					DrillSaveData.Save(instance);
				}
				else
				{
					Plugin.Debug("Vanilla save skipped game progress (not in orbit); drill state not saved either.");
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "ResetShip")]
		private static void StartOfRound_ResetShip()
		{
			DrillNetworkHandler instance = DrillNetworkHandler.Instance;
			if (!((Object)(object)instance == (Object)null) && ((NetworkBehaviour)instance).IsServer)
			{
				instance.ResetCampaign();
				if (!Plugin.Cfg.ResetDrillWhenFired.Value)
				{
					DrillSaveData.Save(instance);
					return;
				}
				instance.ServerResetAll();
				DrillSaveData.Delete();
				Plugin.Log.LogInfo((object)"Crew fired: drill reset.");
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlayerControllerB), "Interact_performed")]
		private static bool Player_Interact(PlayerControllerB __instance, CallbackContext __0)
		{
			//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)
			CallbackContext val = __0;
			if (((CallbackContext)(ref val)).performed)
			{
				return !ChargerInput.HandlePress(__instance);
			}
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "SetHoverTipAndCurrentInteractTrigger")]
		private static void Player_Hover(PlayerControllerB __instance)
		{
			ChargerInput.AfterHover(__instance);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ItemCharger), "ChargeItem")]
		private static bool ItemCharger_ChargeItem()
		{
			DrillNetworkHandler instance = DrillNetworkHandler.Instance;
			if ((Object)(object)instance != (Object)null && (instance.ChargerHot || instance.ChargerInUse.Value))
			{
				return false;
			}
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if (!(val?.currentlyHeldObjectServer is DrillPartItem { HasBattery: not false } drillPartItem))
			{
				return true;
			}
			ChargerInput.Request(val, drillPartItem);
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ItemCharger), "Update")]
		private static void ItemCharger_Update(ItemCharger __instance)
		{
			InteractTrigger triggerScript = __instance.triggerScript;
			if (!((Object)(object)triggerScript == (Object)null))
			{
				DrillNetworkHandler instance = DrillNetworkHandler.Instance;
				bool flag = (Object)(object)instance != (Object)null && instance.ChargerHot;
				GrabbableObject val = GameNetworkManager.Instance?.localPlayerController?.currentlyHeldObjectServer;
				bool flag2 = val is DrillPartItem drillPartItem && drillPartItem.HasBattery;
				ChargerOverload chargerOverload = ((Component)__instance).GetComponent<ChargerOverload>();
				if ((Object)(object)chargerOverload == (Object)null && (flag || flag2 || ((Object)(object)instance != (Object)null && instance.ChargerInUse.Value)))
				{
					chargerOverload = ((Component)__instance).gameObject.AddComponent<ChargerOverload>();
				}
				if ((Object)(object)chargerOverload != (Object)null)
				{
					chargerOverload.Prompt.Sync(triggerScript, flag, val, (Object)(object)instance != (Object)null && instance.ChargerInUse.Value);
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")]
		private static void HUDManager_SubmitChat(HUDManager __instance)
		{
			string text = (((Object)(object)__instance.chatTextField != (Object)null) ? __instance.chatTextField.text : null);
			if (!string.IsNullOrEmpty(text) && text.StartsWith("/drill"))
			{
				DebugCommands.Run(text.Substring(6).Trim());
				__instance.chatTextField.text = string.Empty;
			}
		}
	}
	[HarmonyPatch]
	internal static class PartScrap
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(RoundManager), "waitForScrapToSpawnToSync")]
		internal static void AddParts(RoundManager __instance, ref NetworkObjectReference[] __0, ref int[] __1)
		{
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			DrillNetworkHandler instance = DrillNetworkHandler.Instance;
			SelectableLevel currentLevel = __instance.currentLevel;
			if ((Object)(object)instance == (Object)null || !((NetworkBehaviour)instance).IsServer || !((NetworkBehaviour)instance).IsSpawned || (Object)(object)currentLevel == (Object)null || !currentLevel.spawnEnemiesAndScrap || (Object)(object)TimeOfDay.Instance == (Object)null || __0 == null || __1 == null || __0.Length != __1.Length)
			{
				return;
			}
			int timesFulfilledQuota = TimeOfDay.Instance.timesFulfilledQuota;
			Item item = DrillItems.ByKey["Cable"];
			Item item2 = DrillItems.ByKey["Battery"];
			bool flag = AcquisitionRules.Cable(currentLevel.riskLevel, timesFulfilledQuota, instance.HasPart(item));
			bool flag2 = AcquisitionRules.Battery(currentLevel.sceneName, currentLevel.PlanetName, timesFulfilledQuota, instance.BatteryQuota, instance.HasPart(item2));
			Plugin.Debug($"Scrap on {currentLevel.PlanetName} ({currentLevel.riskLevel}), quotas={timesFulfilledQuota}, battery unlock={instance.BatteryQuota}, add cable={flag}, add battery={flag2}.");
			if (!flag && !flag2)
			{
				return;
			}
			RandomScrapSpawn[] points = Object.FindObjectsOfType<RandomScrapSpawn>();
			Random rng = new Random(StartOfRound.Instance.randomMapSeed ^ 0x6CCF78);
			List<Vector3> list = new List<Vector3>();
			NetworkObjectReference[] array = __0;
			NetworkObject val2 = default(NetworkObject);
			for (int i = 0; i < array.Length; i++)
			{
				NetworkObjectReference val = array[i];
				if (((NetworkObjectReference)(ref val)).TryGet(ref val2, (NetworkManager)null))
				{
					list.Add(((Component)val2).transform.position);
				}
			}
			if (flag)
			{
				Spawn(__instance, instance, item, points, rng, list, ref __0, ref __1);
			}
			if (flag2)
			{
				Spawn(__instance, instance, item2, points, rng, list, ref __0, ref __1);
			}
		}

		private static void Spawn(RoundManager round, DrillNetworkHandler handler, Item item, RandomScrapSpawn[] points, Random rng, List<Vector3> occupied, ref NetworkObjectReference[] objects, ref int[] values)
		{
			//IL_020e: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: 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)
			//IL_0176: 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_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			int num = rng.Next(points.Length);
			Vector3? position = null;
			for (int i = 0; i < points.Length; i++)
			{
				RandomScrapSpawn val = points[(num + i) % points.Length];
				if ((Object)(object)val == (Object)null || val.spawnUsed)
				{
					continue;
				}
				Vector3 candidate = (val.spawnedItemsCopyPosition ? (((Object)(object)val.spawnWithParent != (Object)null) ? val.spawnWithParent : ((Component)val).transform).position : (round.GetRandomNavMeshPositionInBoxPredictable(((Component)val).transform.position, val.itemSpawnRange, default(NavMeshHit), rng, -8193, 1f) + Vector3.up * item.verticalOffset));
				if (!occupied.Exists(delegate(Vector3 p)
				{
					//IL_0000: 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_000c: Unknown result type (might be due to invalid IL or missing references)
					Vector3 val4 = p - candidate;
					return ((Vector3)(ref val4)).sqrMagnitude < 0.36f;
				}))
				{
					position = candidate;
					if (val.spawnedItemsCopyPosition)
					{
						val.spawnUsed = true;
					}
					break;
				}
			}
			if (!position.HasValue && round.insideAINodes != null && round.insideAINodes.Length != 0)
			{
				GameObject[] insideAINodes = round.insideAINodes;
				num = rng.Next(insideAINodes.Length);
				for (int num2 = 0; num2 < insideAINodes.Length; num2++)
				{
					GameObject val2 = insideAINodes[(num + num2) % insideAINodes.Length];
					if (!((Object)(object)val2 == (Object)null))
					{
						position = val2.transform.position + Vector3.up * item.verticalOffset;
						if (!occupied.Exists(delegate(Vector3 p)
						{
							//IL_0000: 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_000c: Unknown result type (might be due to invalid IL or missing references)
							//IL_0011: Unknown result type (might be due to invalid IL or missing references)
							Vector3 val4 = p - position.Value;
							return ((Vector3)(ref val4)).sqrMagnitude < 0.36f;
						}))
						{
							break;
						}
					}
				}
			}
			if (!position.HasValue)
			{
				Plugin.Log.LogWarning((object)("No interior scrap point available for " + item.itemName + "."));
				return;
			}
			int num3 = DrillItems.RollValue(item);
			NetworkObject val3 = handler.ServerSpawnItem(item, position.Value, num3, 0, levelScrap: true);
			if (!((Object)(object)val3 == (Object)null))
			{
				occupied.Add(position.Value);
				Array.Resize(ref objects, objects.Length + 1);
				Array.Resize(ref values, values.Length + 1);
				objects[objects.Length - 1] = NetworkObjectReference.op_Implicit(val3);
				values[values.Length - 1] = num3;
				Plugin.Debug($"Added one {item.itemName} at {position.Value} worth {num3}.");
			}
		}
	}
	[HarmonyPatch]
	internal static class SlotPickup
	{
		private static readonly RaycastHit[] Hits = (RaycastHit[])(object)new RaycastHit[32];

		[HarmonyTargetMethods]
		private static IEnumerable<MethodBase> Targets()
		{
			yield return AccessTools.Method(typeof(PlayerControllerB), "SetHoverTipAndCurrentInteractTrigger", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(PlayerControllerB), "BeginGrabObject", (Type[])null, (Type[])null);
		}

		[HarmonyPrefix]
		private static void Before(PlayerControllerB __instance, int ___interactableObjectsMask, out List<Collider> __state)
		{
			//IL_005b: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			if ((Object)(object)DrillRig.Current == (Object)null || (Object)(object)__instance != (Object)(object)GameNetworkManager.Instance?.localPlayerController || __instance.twoHanded || (Object)(object)__instance.gameplayCamera == (Object)null || !DrillRig.LocalPlayerNearDrill(15f))
			{
				return;
			}
			Transform transform = ((Component)__instance.gameplayCamera).transform;
			int num = Physics.RaycastNonAlloc(new Ray(transform.position, transform.forward), Hits, __instance.grabDistance, ___interactableObjectsMask);
			if (num == 0 || num == Hits.Length)
			{
				return;
			}
			float num2 = float.PositiveInfinity;
			Collider val = null;
			for (int i = 0; i < num; i++)
			{
				RaycastHit val2 = Hits[i];
				if (!(((RaycastHit)(ref val2)).distance >= num2) && !((Object)(object)((Component)((RaycastHit)(ref val2)).collider).GetComponent<DrillSlotInteract>() != (Object)null))
				{
					num2 = ((RaycastHit)(ref val2)).distance;
					val = ((RaycastHit)(ref val2)).collider;
				}
			}
			if ((Object)(object)val == (Object)null || ((Component)val).gameObject.layer == 8 || !((Component)val).CompareTag("PhysicsProp"))
			{
				return;
			}
			GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
			if ((Object)(object)component == (Object)null || !component.grabbable || component.isHeld || component.isPocketed)
			{
				return;
			}
			InteractTrigger hoveringOverTrigger = __instance.hoveringOverTrigger;
			if ((Object)(object)hoveringOverTrigger != (Object)null && (Object)(object)((Component)hoveringOverTrigger).GetComponent<DrillSlotInteract>() != (Object)null)
			{
				hoveringOverTrigger.StopInteraction();
				hoveringOverTrigger.isBeingHeldByPlayer = false;
				__instance.hoveringOverTrigger = null;
			}
			for (int j = 0; j < num; j++)
			{
				Collider collider = ((RaycastHit)(ref Hits[j])).collider;
				if (!(((RaycastHit)(ref Hits[j])).distance > num2) && !((Object)(object)((Component)collider).GetComponent<DrillSlotInteract>() == (Object)null))
				{
					if (__state == null)
					{
						__state = new List<Collider>(2);
					}
					__state.Add(collider);
					collider.enabled = false;
				}
			}
		}

		[HarmonyPostfix]
		private static void After(List<Collider> __state)
		{
			if (__state == null)
			{
				return;
			}
			foreach (Collider item in __state)
			{
				if ((Object)(object)item != (Object)null)
				{
					item.enabled = true;
				}
			}
		}
	}
}
namespace TheDrill.Networking
{
	public class DrillNetworkHandler : NetworkBehaviour
	{
		internal int BatteryQuota;

		public readonly NetworkVariable<int> ChipProgress = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		internal ItemDropship ChipFlight;

		private bool _chipSlotReserved;

		public NetworkList<int> SlotItems;

		public NetworkList<int> SlotValues;

		public NetworkList<int> SlotCharges;

		public readonly NetworkVariable<byte> PhaseVar = new NetworkVariable<byte>((byte)0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public readonly NetworkVariable<double> PhaseStartTime = new NetworkVariable<double>(0.0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public readonly NetworkVariable<FixedString4096Bytes> SyncedRules = new NetworkVariable<FixedString4096Bytes>(default(FixedString4096Bytes), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public readonly NetworkVariable<Vector2> SyncedTimings = new NetworkVariable<Vector2>(new Vector2(6f, 45f), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public readonly NetworkVariable<bool> ChargerInUse = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public readonly NetworkVariable<double> ChargerHotUntil = new NetworkVariable<double>(0.0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		private readonly ItemRules[] _rules = new ItemRules[DrillSlotDefinitions.Count];

		private readonly bool[] _required = new bool[DrillSlotDefinitions.Count];

		private string _parsedRulesSource;

		private const float WallTipLead = 3f;

		private double _wallTipShownFor = -1.0;

		internal ChipOrder ChipState
		{
			get
			{
				return (ChipOrder)ChipProgress.Value;
			}
			set
			{
				ChipProgress.Value = (int)value;
			}
		}

		public static DrillNetworkHandler Instance { get; private set; }

		internal static GameObject Prefab { get; private set; }

		public DrillPhase Phase => (DrillPhase)PhaseVar.Value;

		public float SpinUpSeconds => Mathf.Max(0.1f, SyncedTimings.Value.x);

		public float TravelSeconds => Mathf.Max(0.1f, SyncedTimings.Value.y);

		public double ServerNow
		{
			get
			{
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)((NetworkBehaviour)this).NetworkManager != (Object)null))
				{
					return 0.0;
				}
				NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime;
				return ((NetworkTime)(ref serverTime)).Time;
			}
		}

		public bool ChargerHot => ServerNow < ChargerHotUntil.Value;

		public float ChargerHotRemaining => (float)Math.Max(0.0, ChargerHotUntil.Value - ServerNow);

		public float PhaseElapsed
		{
			get
			{
				//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)
				if (!((Object)(object)((NetworkBehaviour)this).NetworkManager != (Object)null))
				{
					return 0f;
				}
				NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime;
				return (float)Math.Max(0.0, ((NetworkTime)(ref serverTime)).Time - PhaseStartTime.Value);
			}
		}

		public static event Action StateChanged;

		public static event Action<DrillSlotId> SlotFilled;

		public static event Action<DrillSlotId, int> SlotEmptied;

		internal bool HasPart(Item item)
		{
			int num = ItemLookup.Hash(item);
			for (int i = 0; i < DrillSlotDefinitions.Count; i++)
			{
				if (GetSlotItemHash((DrillSlotId)i) == num)
				{
					return true;
				}
			}
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				if ((Object)(object)val.currentlyHeldObjectServer != (Object)null && (Object)(object)val.currentlyHeldObjectServer.itemProperties == (Object)(object)item)
				{
					return true;
				}
				if (val.ItemSlots == null)
				{
					continue;
				}
				GrabbableObject[] itemSlots = val.ItemSlots;
				foreach (GrabbableObject val2 in itemSlots)
				{
					if ((Object)(object)val2 != (Object)null && (Object)(object)val2.itemProperties == (Object)(object)item)
					{
						return true;
					}
				}
			}
			DrillPartItem[] array = Object.FindObjectsOfType<DrillPartItem>(true);
			foreach (DrillPartItem drillPartItem in array)
			{
				if ((Object)(object)drillPartItem != (Object)null && ((NetworkBehaviour)drillPartItem).IsSpawned && (Object)(object)((GrabbableObject)drillPartItem).itemProperties == (Object)(object)item)
				{
					return true;
				}
			}
			return false;
		}

		internal bool IsDuplicate(Item item)
		{
			if ((Object)(object)item == (Object)(object)DrillItems.ByKey["Cable"] || (Object)(object)item == (Object)(object)DrillItems.ByKey["Battery"])
			{
				return HasPart(item);
			}
			return false;
		}

		[ServerRpc(RequireOwnership = false)]
		internal void BuyDataChipServerRpc(int playerId, ServerRpcParams rpc = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1619454223u, rpc, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val, playerId);
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 1619454223u, rpc, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			base.__rpc_exec_stage = (__RpcExecStage)0;
			if (IsRequester(playerId, rpc))
			{
				Terminal val2 = Object.FindObjectOfType<Terminal>();
				string text = (((Object)(object)val2 == (Object)null) ? "Terminal offline." : AcquisitionRules.Reject(ChipState, val2.groupCredits, val2.numberOfItemsInDropship, val2.vehicleInDropship));
				if (text == null)
				{
					ChipState = ChipOrder.Queued;
					val2.groupCredits -= 120;
					val2.numberOfItemsInDropship++;
					_chipSlotReserved = true;
					val2.SyncGroupCreditsClientRpc(val2.groupCredits, val2.numberOfItemsInDropship);
					Plugin.Debug($"Data chip purchased by player {playerId}. Reserved for next dropship.");
				}
				bool success = text == null;
				ChipReceiptClientRpc(playerId, text ?? AcquisitionRules.OrderedText(val2.groupCredits), success);
			}
		}

		[ClientRpc]
		private void ChipReceiptClientRpc(int playerId, string message, bool success)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val2 = default(ClientRpcParams);
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(1473958516u, val2, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val, playerId);
				bool flag = message != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(message, false);
				}
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref success, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 1473958516u, val2, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				base.__rpc_exec_stage = (__RpcExecStage)0;
				PlayerControllerB val3 = GameNetworkManager.Instance?.localPlayerController;
				if ((Object)(object)val3 != (Object)null && (int)val3.playerClientId == playerId)
				{
					((MonoBehaviour)this).StartCoroutine(ShowReceipt(message, success));
				}
			}
		}

		private static IEnumerator ShowReceipt(string message, bool success)
		{
			yield return null;
			ChipTerminal.Receipt(message, success);
		}

		internal void ChipDelivered()
		{
			_chipSlotReserved = false;
		}

		internal ChipOrder ServerResetChipOrder()
		{
			ChipOrder chipState = ChipState;
			if (!((NetworkBehaviour)this).IsServer)
			{
				return chipState;
			}
			if (chipState == ChipOrder.Queued && (Object)(object)ChipFlight == (Object)null && _chipSlotReserved)
			{
				Terminal val = Object.FindObjectOfType<Terminal>();
				if ((Object)(object)val != (Object)null && val.numberOfItemsInDropship > 0)
				{
					val.numberOfItemsInDropship--;
					val.SyncGroupCreditsClientRpc(val.groupCredits, val.numberOfItemsInDropship);
				}
			}
			_chipSlotReserved = false;
			ChipFlight = null;
			ChipState = ChipOrder.Available;
			if ((Object)(object)DrillRig.Current != (Object)null)
			{
				DrillRig.Current.RespawnChipNote();
			}
			Plugin.Log.LogInfo((object)$"Data chip order reset ({chipState} -> Available).");
			return chipState;
		}

		internal void ResetCampaign()
		{
			_chipSlotReserved = false;
			ChipState = ChipOrder.Available;
			ChipFlight = null;
			BatteryQuota = AcquisitionRules.BatteryQuota(0, new Random());
		}

		private void Awake()
		{
			SlotItems = new NetworkList<int>();
			SlotValues = new NetworkList<int>();
			SlotCharges = new NetworkList<int>();
		}

		internal static void CreatePrefab()
		{
			Prefab = NetworkPrefabs.CreateNetworkPrefab("TheDrillNetworkHandler");
			Prefab.AddComponent<DrillNetworkHandler>();
		}

		public override void OnNetworkSpawn()
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			((NetworkBehaviour)this).OnNetworkSpawn();
			Instance = this;
			SlotItems.OnListChanged += OnSlotListChanged;
			NetworkVariable<byte> phaseVar = PhaseVar;
			phaseVar.OnValueChanged = (OnValueChangedDelegate<byte>)(object)Delegate.Combine((Delegate?)(object)phaseVar.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<byte>(OnPhaseChanged));
			NetworkVariable<FixedString4096Bytes> syncedRules = SyncedRules;
			syncedRules.OnValueChanged = (OnValueChangedDelegate<FixedString4096Bytes>)(object)Delegate.Combine((Delegate?)(object)syncedRules.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<FixedString4096Bytes>(OnRulesChanged));
			if (((NetworkBehaviour)this).IsServer)
			{
				SyncedRules.Value = new FixedString4096Bytes(Plugin.Cfg.BuildSyncedRules());
				SyncedTimings.Value = new Vector2(Plugin.Cfg.SpinUpSeconds.Value, Plugin.Cfg.TravelSeconds.Value);
				while (SlotItems.Count < DrillSlotDefinitions.Count)
				{
					SlotItems.Add(0);
				}
				while (SlotValues.Count < DrillSlotDefinitions.Count)
				{
					SlotValues.Add(0);
				}
				while (SlotCharges.Count < DrillSlotDefinitions.Count)
				{
					SlotCharges.Add(0);
				}
				DrillSaveData.LoadAcquisition(this);
				((MonoBehaviour)this).StartCoroutine(LoadSaveNextFrame());
			}
			Plugin.Debug($"DrillNetworkHandler spawned (server={((NetworkBehaviour)this).IsServer}).");
			DrillNetworkHandler.StateChanged?.Invoke();
		}

		private IEnumerator LoadSaveNextFrame()
		{
			yield return null;
			DrillSaveData.LoadInto(this);
		}

		public override void OnNetworkDespawn()
		{
			SlotItems.OnListChanged -= OnSlotListChanged;
			NetworkVariable<byte> phaseVar = PhaseVar;
			phaseVar.OnValueChanged = (OnValueChangedDelegate<byte>)(object)Delegate.Remove((Delegate?)(object)phaseVar.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<byte>(OnPhaseChanged));
			NetworkVariable<FixedString4096Bytes> syncedRules = SyncedRules;
			syncedRules.OnValueChanged = (OnValueChangedDelegate<FixedString4096Bytes>)(object)Delegate.Remove((Delegate?)(object)syncedRules.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<FixedString4096Bytes>(OnRulesChanged));
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
			((NetworkBehaviour)this).OnNetworkDespawn();
		}

		private void OnPhaseChanged(byte previous, byte current)
		{
			DrillNetworkHandler.StateChanged?.Invoke();
		}

		private void OnRulesChanged(FixedString4096Bytes previous, FixedString4096Bytes current)
		{
			DrillNetworkHandler.StateChanged?.Invoke();
		}

		private void OnSlotListChanged(NetworkListEvent<int> change)
		{
			//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_0007: Invalid comparison between Unknown and I4
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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_0049: 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)
			if ((int)change.Type == 4 && change.Index < DrillSlotDefinitions.Count)
			{
				if (change.Value != 0)
				{
					DrillNetworkHandler.SlotFilled?.Invoke((DrillSlotId)change.Index);
				}
				else if (change.PreviousValue != 0)
				{
					DrillNetworkHandler.SlotEmptied?.Invoke((DrillSlotId)change.Index, change.PreviousValue);
				}
			}
			DrillNetworkHandler.StateChanged?.Invoke();
		}

		public int GetSlotItemHash(DrillSlotId id)
		{
			return Get(SlotItems, id);
		}

		public int GetSlotValue(DrillSlotId id)
		{
			return Get(SlotValues, id);
		}

		public int GetSlotCharge(DrillSlotId id)
		{
			return Get(SlotCharges, id);
		}

		private static int Get(NetworkList<int> list, DrillSlotId id)
		{
			if (list == null || (int)id >= list.Count)
			{
				return 0;
			}
			return list[(int)id];
		}

		public bool IsSlotFilled(DrillSlotId id)
		{
			return GetSlotItemHash(id) != 0;
		}

		public Item GetSlotItem(DrillSlotId id)
		{
			return ItemLookup.Find(GetSlotItemHash(id));
		}

		public ItemRules GetRules(DrillSlotId id)
		{
			EnsureRulesParsed();
			return _rules[(int)id];
		}

		public bool IsSlotRequired(DrillSlotId id)
		{
			EnsureRulesParsed();
			return _required[(int)id];
		}

		public bool AllRequiredSlotsFilled()
		{
			DrillSlotDefinition[] all = DrillSlotDefinitions.All;
			foreach (DrillSlotDefinition drillSlotDefinition in all)
			{
				if (IsSlotRequired(drillSlotDefinition.Id) && !IsSlotFilled(drillSlotDefinition.Id))
				{
					return false;
				}
			}
			return true;
		}

		private void EnsureRulesParsed()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			string text = ((object)SyncedRules.Value/*cast due to .constrained prefix*/).ToString();
			if (text == _parsedRulesSource)
			{
				return;
			}
			_parsedRulesSource = text;
			DrillSlotDefinition[] all = DrillSlotDefinitions.All;
			foreach (DrillSlotDefinition drillSlotDefinition in all)
			{
				_rules[(int)drillSlotDefinition.Id] = new ItemRules(drillSlotDefinition.DefaultAcceptedItems);
				_required[(int)drillSlotDefinition.Id] = drillSlotDefinition.RequiredToArm;
			}
			string[] array = text.Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string text2 in array)
			{
				int num = text2.IndexOf('=');
				if (num > 0 && int.TryParse(text2.Substring(0, num), out var result) && result >= 0 && result < _rules.Length)
				{
					string text3 = text2.Substring(num + 1);
					_required[result] = text3.Length == 0 || text3[0] != '0';
					_rules[result] = new ItemRules((text3.Length > 0) ? text3.Substring(1) : string.Empty);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void InsertItemServerRpc(int slotIndex, int itemHash, int scrapValue, int charge, Vector3 refundPosition)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: 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_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val2 = default(ServerRpcParams);
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(3147985843u, val2, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val, slotIndex);
				BytePacker.WriteValueBitPacked(val, itemHash);
				BytePacker.WriteValueBitPacked(val, scrapValue);
				BytePacker.WriteValueBitPacked(val, charge);
				((FastBufferWriter)(ref val)).WriteValueSafe(ref refundPosition);
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 3147985843u, val2, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			base.__rpc_exec_stage = (__RpcExecStage)0;
			if (slotIndex >= 0 && slotIndex < DrillSlotDefinitions.Count)
			{
				DrillSlotDefinition drillSlotDefinition = DrillSlotDefinitions.Get((DrillSlotId)slotIndex);
				Item val3 = ItemLookup.Find(itemHash);
				bool flag = (Object)(object)val3 != (Object)null && GetRules((DrillSlotId)slotIndex).Matches(val3, null) && (drillSlotDefinition.MinBatteryCharge <= 0 || charge >= drillSlotDefinition.MinBatteryCharge);
				if (IsSlotFilled((DrillSlotId)slotIndex) || !flag || (int)Phase >= 2)
				{
					Plugin.Log.LogInfo((object)$"Insert into {(DrillSlotId)slotIndex} rejected (filled={IsSlotFilled((DrillSlotId)slotIndex)}, accepted={flag}, phase={Phase}); refunding.");
					ServerSpawnItem(val3, refundPosition, scrapValue, charge);
				}
				else
				{
					SlotValues[slotIndex] = scrapValue;
					SlotCharges[slotIndex] = charge;
					SlotItems[slotIndex] = itemHash;
					Plugin.Log.LogInfo((object)$"Drill slot {(DrillSlotId)slotIndex} filled with '{val3.itemName}'.");
					ServerEvaluateArmed();
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void RemoveItemServerRpc(int slotIndex, int playerId, Vector3 spawnPosition, ServerRpcParams rpc = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: 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_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: 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_0188: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(3251596412u, rpc, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val, slotIndex);
				BytePacker.WriteValueBitPacked(val, playerId);
				((FastBufferWriter)(ref val)).WriteValueSafe(ref spawnPosition);
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 3251596412u, rpc, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			base.__rpc_exec_stage = (__RpcExecStage)0;
			if (slotIndex < 0 || slotIndex >= DrillSlotDefinitions.Count)
			{
				return;
			}
			if (IsSlotFilled((DrillSlotId)slotIndex) && (int)Phase < 2 && IsRequester(playerId, rpc) && DrillSlotDefinitions.Get((DrillSlotId)slotIndex).Removable)
			{
				Item slotItem = GetSlotItem((DrillSlotId)slotIndex);
				int slotValue = GetSlotValue((DrillSlotId)slotIndex);
				int slotCharge = GetSlotCharge((DrillSlotId)slotIndex);
				NetworkObject val2 = ServerSpawnItem(slotItem, spawnPosition, slotValue, slotCharge);
				if (!((Object)(object)val2 == (Object)null))
				{
					SlotItems[slotIndex] = 0;
					SlotValues[slotIndex] = 0;
					SlotCharges[slotIndex] = 0;
					ServerEvaluateArmed();
					GiveToPlayerClientRpc(NetworkObjectReference.op_Implicit(val2), playerId);
					Plugin.Log.LogInfo((object)$"Drill slot {(DrillSlotId)slotIndex} emptied by player {playerId}.");
				}
			}
		}

		[ClientRpc]
		private void GiveToPlayerClientRpc(NetworkObjectReference itemRef, int playerId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val2 = default(ClientRpcParams);
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(1856243747u, val2, (RpcDelivery)0);
				((FastBufferWriter)(ref val)).WriteValueSafe<NetworkObjectReference>(ref itemRef, default(ForNetworkSerializable));
				BytePacker.WriteValueBitPacked(val, playerId);
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 1856243747u, val2, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				base.__rpc_exec_stage = (__RpcExecStage)0;
				PlayerControllerB val3 = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
				if (!((Object)(object)val3 == (Object)null) && (int)val3.playerClientId == playerId)
				{
					((MonoBehaviour)this).StartCoroutine(GrabWhenReady(val3, itemRef));
				}
			}
		}

		private IEnumerator GrabWhenReady(PlayerControllerB player, NetworkObjectReference itemRef)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			float deadline = Time.realtimeSinceStartup + 2f;
			NetworkObject val = default(NetworkObject);
			do
			{
				yield return null;
				if (((NetworkObjectReference)(ref itemRef)).TryGet(ref val, (NetworkManager)null))
				{
					ItemGrabber.TryGrab(player, ((Component)val).GetComponent<GrabbableObject>());
					break;
				}
			}
			while (Time.realtimeSinceStartup < deadline);
		}

		private static bool IsRequester(int id, ServerRpcParams rpc)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB[] array = StartOfRound.Instance?.allPlayerScripts;
			if (array != null && id >= 0 && id < array.Length && (Object)(object)array[id] != (Object)null && array[id].actualClientId == rpc.Receive.SenderClientId)
			{
				return !array[id].isPlayerDead;
			}
			return false;
		}

		[ServerRpc(RequireOwnership = false)]
		public void PullStartCordServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val2 = default(ServerRpcParams);
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(2473836673u, val2, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 2473836673u, val2, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				base.__rpc_exec_stage = (__RpcExecStage)0;
				ServerEvaluateArmed();
				if (Phase == DrillPhase.Armed)
				{
					ServerSetPhase(DrillPhase.SpinningUp);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void ChargeBatteryServerRpc(NetworkObjectReference batteryRef, int playerId, ServerRpcParams rpc = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: 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_01e6: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(778222308u, rpc, (RpcDelivery)0);
				((FastBufferWriter)(ref val)).WriteValueSafe<NetworkObjectReference>(ref batteryRef, default(ForNetworkSerializable));
				BytePacker.WriteValueBitPacked(val, playerId);
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 778222308u, rpc, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			base.__rpc_exec_stage = (__RpcExecStage)0;
			if (ChargerHot || ChargerInUse.Value)
			{
				return;
			}
			NetworkObject val2 = default(NetworkObject);
			if (!IsRequester(playerId, rpc) || !((NetworkObjectReference)(ref batteryRef)).TryGet(ref val2, (NetworkManager)null))
			{
				Plugin.Debug($"Charger rejected player {playerId}: sender or battery could not be resolved.");
				return;
			}
			DrillPartItem component = ((Component)val2).GetComponent<DrillPartItem>();
			if ((Object)(object)component == (Object)null || !component.HasBattery || component.Charge >= 100 || (Object)(object)StartOfRound.Instance.allPlayerScripts[playerId].currentlyHeldObjectServer != (Object)(object)component)
			{
				Plugin.Debug($"Charger rejected player {playerId}: battery full, invalid or no longer held.");
				return;
			}
			ItemCharger val3 = Object.FindObjectOfType<ItemCharger>();
			if (!((Object)(object)val3 == (Object)null))
			{
				PlayerControllerB val4 = StartOfRound.Instance.allPlayerScripts[playerId];
				if (!(Vector3.Distance(((Component)val4).transform.position, ((Component)val3).transform.position) > val4.grabDistance + 2f))
				{
					double contactAt = ServerNow + 0.8500000238418579;
					ChargerInUse.Value = true;
					BatteryReachClientRpc(batteryRef, contactAt);
					((MonoBehaviour)this).StartCoroutine(ServerReach(component, val4, val3, contactAt));
				}
			}
		}

		[ClientRpc]
		private void BatteryReachClientRpc(NetworkObjectReference batteryRef, double contactAt)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: 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_00f7: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val2 = default(ClientRpcParams);
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(1168049548u, val2, (RpcDelivery)0);
				((FastBufferWriter)(ref val)).WriteValueSafe<NetworkObjectReference>(ref batteryRef, default(ForNetworkSerializable));
				((FastBufferWriter)(ref val)).WriteValueSafe<double>(ref contactAt, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 1168049548u, val2, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				base.__rpc_exec_stage = (__RpcExecStage)0;
				NetworkObject val3 = default(NetworkObject);
				if (((NetworkObjectReference)(ref batteryRef)).TryGet(ref val3, (NetworkManager)null))
				{
					((Component)val3).GetComponent<BatteryGrip>()?.BeginReach(Object.FindObjectOfType<ItemCharger>(), contactAt);
				}
			}
		}

		private IEnumerator ServerReach(DrillPartItem battery, PlayerControllerB player, ItemCharger station, double contactAt)
		{
			while (((NetworkBehaviour)this).IsSpawned && ServerNow < contactAt && StillHolding(battery, player) && !((Object)(object)station == (Object)null))
			{
				yield return null;
			}
			if (!((NetworkBehaviour)this).IsSpawned)
			{
				yield break;
			}
			ChargerInUse.Value = false;
			if (StillHolding(battery, player) && !((Object)(object)station == (Object)null) && !(ServerNow < contactAt))
			{
				Vector3 val = Vector3.ProjectOnPlane(((Component)player).transform.position - ((Component)station).transform.position, Vector3.up);
				if (!(((Vector3)(ref val)).sqrMagnitude > 2.56f))
				{
					Plugin.Debug("High-Voltage Battery at coil. Starting overload.");
					ChargerHotUntil.Value = ServerNow + 3.0 + (double)Mathf.Max(0f, Plugin.Cfg.ChargerCooldownSeconds.Value);
					BatteryOverloadClientRpc(NetworkObjectReference.op_Implicit(((NetworkBehaviour)battery).NetworkObject), (int)player.playerClientId, Plugin.Cfg.ChargerOverloadDamage.Value);
					((MonoBehaviour)this).StartCoroutine(ServerFinishCharge(battery));
					yield break;
				}
			}
			Plugin.Debug("Charger reach interrupted before contact.");
		}

		private static bool StillHolding(DrillPartItem battery, PlayerControllerB player)
		{
			if ((Object)(object)battery != (Object)null && ((NetworkBehaviour)battery).IsSpawned && (Object)(object)player != (Object)null && player.isPlayerControlled && !player.isPlayerDead)
			{
				return (Object)(object)player.currentlyHeldObjectServer == (Object)(object)battery;
			}
			return false;
		}

		private IEnumerator ServerFinishCharge(DrillPartItem battery)
		{
			yield return (object)new WaitForSeconds(1.6f);
			if ((Object)(object)battery != (Object)null && ((NetworkBehaviour)battery).IsSpawned)
			{
				battery.ServerSetCharge(100);
				Plugin.Debug("High-Voltage Battery reached 100% charge.");
			}
			ShipSurgeClientRpc();
		}

		[ClientRpc]
		private void ShipSurgeClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val2 = default(ClientRpcParams);
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(1719884319u, val2, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 1719884319u, val2, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				base.__rpc_exec_stage = (__RpcExecStage)0;
				if ((Object)(object)StartOfRound.Instance != (Object)null)
				{
					StartOfRound.Instance.PowerSurgeShip();
				}
			}
		}

		[ClientRpc]
		private void BatteryOverloadClientRpc(NetworkObjectReference batteryRef, int playerId, int damage)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val2 = default(ClientRpcParams);
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(2518503179u, val2, (RpcDelivery)0);
				((FastBufferWriter)(ref val)).WriteValueSafe<NetworkObjectReference>(ref batteryRef, default(ForNetworkSerializable));
				BytePacker.WriteValueBitPacked(val, playerId);
				BytePacker.WriteValueBitPacked(val, damage);
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 2518503179u, val2, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				base.__rpc_exec_stage = (__RpcExecStage)0;
				NetworkObject val3 = default(NetworkObject);
				((NetworkObjectReference)(ref batteryRef)).TryGet(ref val3, (NetworkManager)null);
				if ((Object)(object)val3 != (Object)null)
				{
					((Component)val3).GetComponent<BatteryGrip>()?.Recoil();
				}
				ChargerOverload.Play(((Object)(object)val3 != (Object)null) ? ((Component)val3).GetComponent<DrillPartItem>() : null, playerId, damage);
			}
		}

		private void ShowWallTipIfDue()
		{
			if (Phase == DrillPhase.Drilling && !(PhaseElapsed < TravelSeconds - 3f) && _wallTipShownFor != PhaseStartTime.Value && !((Object)(object)HUDManager.Instance == (Object)null))
			{
				_wallTipShownFor = PhaseStartTime.Value;
				HUDManager.Instance.DisplayTip("Wall 1, Drill 0", "The Company reinforced it. What's past this wall isn't finished yet. Thanks for playing!", false, false, "LC_Tip1");
			}
		}

		private void Update()
		{
			if (((NetworkBehaviour)this).IsSpawned)
			{
				ShowWallTipIfDue();
			}
			if (!((NetworkBehaviour)this).IsServer || !((NetworkBehaviour)this).IsSpawned)
			{
				return;
			}
			switch (Phase)
			{
			case DrillPhase.SpinningUp:
				if (PhaseElapsed >= SpinUpSeconds)
				{
					ServerSetPhase(DrillPhase.Drilling);
				}
				break;
			case DrillPhase.Drilling:
				if (PhaseElapsed >= TravelSeconds)
				{
					ServerSetPhase(DrillPhase.Finished);
				}
				break;
			}
		}

		private void ServerEvaluateArmed()
		{
			if (((NetworkBehaviour)this).IsServer)
			{
				if (Phase == DrillPhase.Dormant && AllRequiredSlotsFilled())
				{
					ServerSetPhase(DrillPhase.Armed);
				}
				else if (Phase == DrillPhase.Armed && !AllRequiredSlotsFilled())
				{
					ServerSetPhase(DrillPhase.Dormant);
				}
			}
		}

		internal void ServerSetPhase(DrillPhase phase, double elapsedAlready = 0.0, bool fireEvents = true)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if (((NetworkBehaviour)this).IsServer)
			{
				NetworkVariable<double> phaseStartTime = PhaseStartTime;
				NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime;
				phaseStartTime.Value = ((NetworkTime)(ref serverTime)).Time - elapsedAlready;
				PhaseVar.Value = (byte)phase;
				Plugin.Log.LogInfo((object)$"Drill phase -> {phase}");
				if (fireEvents && phase == DrillPhase.Finished)
				{
					OnDrillFinishedServer();
				}
			}
		}

		private void OnDrillFinishedServer()
		{
			DrillFinishedClientRpc();
		}

		[ClientRpc]
		private void DrillFinishedClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val2 = default(ClientRpcParams);
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(2280542012u, val2, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 2280542012u, val2, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				base.__rpc_exec_stage = (__RpcExecStage)0;
				if (Plugin.Cfg.CameraShake.Value && (Object)(object)HUDManager.Instance != (Object)null && DrillRig.LocalPlayerNearDrill(60f))
				{
					HUDManager.Instance.ShakeCamera((ScreenShakeType)1);
				}
			}
		}

		internal NetworkObject ServerSpawnItem(Item item, Vector3 position, int scrapValue, int charge, bool levelScrap = false, Transform container = null)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			if (!((NetworkBehaviour)this).IsServer || (Object)(object)item == (Object)null || (Object)(object)item.spawnPrefab == (Object)null || (Object)(object)item.spawnPrefab.GetComponent<GrabbableObject>() == (Object)null || (Object)(object)item.spawnPrefab.GetComponent<NetworkObject>() == (Object)null)
			{
				return null;
			}
			Transform val = (levelScrap ? null : (((Object)(object)container != (Object)null) ? container : RoundManager.Instance?.spawnedScrapContainer));
			GameObject val2 = Object.Instantiate<GameObject>(item.spawnPrefab, position, Quaternion.identity, val);
			GrabbableObject component = val2.GetComponent<GrabbableObject>();
			component.fallTime = 0f;
			if (levelScrap)
			{
				val2.transform.rotation = Quaternion.Euler(item.restingRotation);
				component.SetScrapValue(scrapValue);
			}
			DrillPartItem component2 = val2.GetComponent<DrillPartItem>();
			if ((Object)(object)component2 != (Object)null)
			{
				component2.chargePercent.Value = Mathf.Clamp(charge, 0, 100);
			}
			NetworkObject component3 = val2.GetComponent<NetworkObject>();
			component3.Spawn(false);
			if (!levelScrap && (item.isScrap || component is LungProp))
			{
				ConfigureItemClientRpc(NetworkObjectReference.op_Implicit(component3), scrapValue);
			}
			return component3;
		}

		[ClientRpc]
		private void ConfigureItemClientRpc(NetworkObjectReference itemRef, int value)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val2 = default(ClientRpcParams);
					FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(1613854657u, val2, (RpcDelivery)0);
					((FastBufferWriter)(ref val)).WriteValueSafe<NetworkObjectReference>(ref itemRef, default(ForNetworkSerializable));
					BytePacker.WriteValueBitPacked(val, value);
					((NetworkBehaviour)this).__endSendClientRpc(ref val, 1613854657u, val2, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					base.__rpc_exec_stage = (__RpcExecStage)0;
					((MonoBehaviour)this).StartCoroutine(ConfigureWhenSpawned(itemRef, value));
				}
			}
		}

		private static IEnumerator ConfigureWhenSpawned(NetworkObjectReference itemRef, int value)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			float deadline = Time.realtimeSinceStartup + 2f;
			NetworkObject val = default(NetworkObject);
			while (!((NetworkObjectReference)(ref itemRef)).TryGet(ref val, (NetworkManager)null))
			{
				if (Time.realtimeSinceStartup >= deadline)
				{
					yield break;
				}
				yield return null;
			}
			GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
			if ((Object)(object)component == (Object)null)
			{
				yield break;
			}
			if (component.itemProperties.isScrap)
			{
				component.SetScrapValue(value);
			}
			LungProp val2 = (LungProp)(object)((component is LungProp) ? component : null);
			if (val2 != null)
			{
				val2.isLungDocked = false;
				val2.isLungDockedInElevator = false;
				val2.isLungPowered = false;
				AudioSource component2 = ((Component)val2).GetComponent<AudioSource>();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.Stop();
				}
			}
		}

		internal void ServerResetAll()
		{
			if (((NetworkBehaviour)this).IsServer)
			{
				for (int i = 0; i < SlotItems.Count; i++)
				{
					SlotItems[i] = 0;
					SlotValues[i] = 0;
					SlotCharges[i] = 0;
				}
				ServerSetPhase(DrillPhase.Dormant);
			}
		}

		internal void ServerApplyLoaded(IList<int> slotHashes, IList<int> values, IList<int> charges, DrillPhase phase, float phaseElapsed)
		{
			for (int i = 0; i < SlotItems.Count; i++)
			{
				SlotValues[i] = ((i < values.Count) ? values[i] : 0);
				SlotCharges[i] = ((i < charges.Count) ? charges[i] : 0);
				SlotItems[i] = ((i < slotHashes.Count) ? slotHashes[i] : 0);
			}
			ServerSetPhase(phase, phaseElapsed, fireEvents: false);
			ServerEvaluateArmed();
		}

		internal void ServerDebugFillAll()
		{
			if (!((NetworkBehaviour)this).IsServer)
			{
				return;
			}
			List<Item> itemsList = StartOfRound.Instance.allItemsList.itemsList;
			DrillSlotDefinition[] all = DrillSlotDefinitions.All;
			foreach (DrillSlotDefinition drillSlotDefinition in all)
			{
				if (!IsSlotFilled(drillSlotDefinition.Id))
				{
					ItemRules rules = GetRules(drillSlotDefinition.Id);
					Item val = itemsList.Find((Item it) => (Object)(object)it != (Object)null && rules.Matches(it, null)) ?? itemsList.Find((Item it) => (Object)(object)it != (Object)null && (Object)(object)it.spawnPrefab != (Object)null);
					if (!((Object)(object)val == (Object)null) && !IsDuplicate(val))
					{
						SlotValues[(int)drillSlotDefinition.Id] = DrillItems.RollValue(val);
						SlotCharges[(int)drillSlotDefinition.Id] = ((drillSlotDefinition.MinBatteryCharge > 0) ? 100 : 0);
						SlotItems[(int)drillSlotDefinition.Id] = ItemLookup.Hash(val);
					}
				}
			}
			ServerEvaluateArmed();
		}

		protected override void __initializeVariables()
		{
			if (ChipProgress == null)
			{
				throw new Exception("DrillNetworkHandler.ChipProgress cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)ChipProgress).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)ChipProgress, "ChipProgress");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)ChipProgress);
			if (SlotItems == null)
			{
				throw new Exception("DrillNetworkHandler.SlotItems cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SlotItems).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SlotItems, "SlotItems");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SlotItems);
			if (SlotValues == null)
			{
				throw new Exception("DrillNetworkHandler.SlotValues cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SlotValues).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SlotValues, "SlotValues");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SlotValues);
			if (SlotCharges == null)
			{
				throw new Exception("DrillNetworkHandler.SlotCharges cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SlotCharges).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SlotCharges, "SlotCharges");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SlotCharges);
			if (PhaseVar == null)
			{
				throw new Exception("DrillNetworkHandler.PhaseVar cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)PhaseVar).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PhaseVar, "PhaseVar");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)PhaseVar);
			if (PhaseStartTime == null)
			{
				throw new Exception("DrillNetworkHandler.PhaseStartTime cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)PhaseStartTime).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PhaseStartTime, "PhaseStartTime");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)PhaseStartTime);
			if (SyncedRules == null)
			{
				throw new Exception("DrillNetworkHandler.SyncedRules cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SyncedRules).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SyncedRules, "SyncedRules");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SyncedRules);
			if (SyncedTimings == null)
			{
				throw new Exception("DrillNetworkHandler.SyncedTimings cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SyncedTimings).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SyncedTimings, "SyncedTimings");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SyncedTimings);
			if (ChargerInUse == null)
			{
				throw new Exception("DrillNetworkHandler.ChargerInUse cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)ChargerInUse).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)ChargerInUse, "ChargerInUse");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)ChargerInUse);
			if (ChargerHotUntil == null)
			{
				throw new Exception("DrillNetworkHandler.ChargerHotUntil cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)ChargerHotUntil).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)ChargerHotUntil, "ChargerHotUntil");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)ChargerHotUntil);
			((NetworkBehaviour)this).__initializeVariables();
		}

		protected override void __initializeRpcs()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Expected O, but got Unknown
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected O, but got Unknown
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Expected O, but got Unknown
			((NetworkBehaviour)this).__registerRpc(1619454223u, new RpcReceiveHandler(__rpc_handler_1619454223), "BuyDataChipServerRpc");
			((NetworkBehaviour)this).__registerRpc(1473958516u, new RpcReceiveHandler(__rpc_handler_1473958516), "ChipReceiptClientRpc");
			((NetworkBehaviour)this).__registerRpc(3147985843u, new RpcReceiveHandler(__rpc_handler_3147985843), "InsertItemServerRpc");
			((NetworkBehaviour)this).__registerRpc(3251596412u, new RpcReceiveHandler(__rpc_handler_3251596412), "RemoveItemServerRpc");
			((NetworkBehaviour)this).__registerRpc(1856243747u, new RpcReceiveHandler(__rpc_handler_1856243747), "GiveToPlayerClientRpc");
			((NetworkBehaviour)this).__registerRpc(2473836673u, new RpcReceiveHandler(__rpc_handler_2473836673), "PullStartCordServerRpc");
			((NetworkBehaviour)this).__registerRpc(778222308u, new RpcReceiveHandler(__rpc_handler_778222308), "ChargeBatteryServerRpc");
			((NetworkBehaviour)this).__registerRpc(1168049548u, new RpcReceiveHandler(__rpc_handler_1168049548), "BatteryReachClientRpc");
			((NetworkBehaviour)this).__registerRpc(1719884319u, new RpcReceiveHandler(__rpc_handler_1719884319), "ShipSurgeClientRpc");
			((NetworkBehaviour)this).__registerRpc(2518503179u, new RpcReceiveHandler(__rpc_handler_2518503179), "BatteryOverloadClientRpc");
			((NetworkBehaviour)this).__registerRpc(2280542012u, new RpcReceiveHandler(__rpc_handler_2280542012), "DrillFinishedClientRpc");
			((NetworkBehaviour)this).__registerRpc(1613854657u, new RpcReceiveHandler(__rpc_handler_1613854657), "ConfigureItemClientRpc");
			((NetworkBehaviour)this).__initializeRpcs();
		}

		private static void __rpc_handler_1619454223(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_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_0040: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				ServerRpcParams server = rpcParams.Server;
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((DrillNetworkHandler)(object)target).BuyDataChipServerRpc(playerId, server);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1473958516(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: 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_007a: 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_00ab: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string message = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref message, false);
				}
				bool success = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref success, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((DrillNetworkHandler)(object)target).ChipReceiptClientRpc(playerId, message, success);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3147985843(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: 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_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int slotIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref slotIndex);
				int itemHash