Decompiled source of CompanyRnD v0.3.0

plugins/CompanyRnD/CompanyRnD.dll

Decompiled an hour 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.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CompanyRnD")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: AssemblyInformationalVersion("0.3.0+6c8af3cbbf88533a0fd7243400dbcec061a1f6af")]
[assembly: AssemblyProduct("CompanyRnD")]
[assembly: AssemblyTitle("CompanyRnD")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.3.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CompanyRnD
{
	internal static class BrokenRobotItem
	{
		public const string ItemName = "Broken robot";

		public static Item Item;

		private const int Rarity = 8;

		private static float halfHeight = 0.35f;

		public static void Register(AssetBundle bundle)
		{
			//IL_00ad: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: 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_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = ((bundle != null) ? bundle.LoadAsset<GameObject>("CompanyRnD_BrokenRobotModel") : null);
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)"No broken robot model in the bundle; the item is off.");
				return;
			}
			GameObject val2 = NetworkPrefabs.CreateNetworkPrefab("CompanyRnD_BrokenRobot");
			int num = LayerMask.NameToLayer("Props");
			if (num >= 0)
			{
				val2.layer = num;
			}
			val2.tag = "PhysicsProp";
			GameObject val3 = Object.Instantiate<GameObject>(val, val2.transform);
			((Object)val3).name = "Model";
			Transform[] componentsInChildren = val3.GetComponentsInChildren<Transform>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				((Component)componentsInChildren[i]).gameObject.layer = val2.layer;
			}
			MeshRenderer[] componentsInChildren2 = val3.GetComponentsInChildren<MeshRenderer>(true);
			Bounds bounds = ((Renderer)componentsInChildren2[0]).bounds;
			MeshRenderer[] array = componentsInChildren2;
			foreach (MeshRenderer val4 in array)
			{
				((Bounds)(ref bounds)).Encapsulate(((Renderer)val4).bounds);
			}
			Transform transform = val3.transform;
			transform.localPosition -= ((Bounds)(ref bounds)).center - val2.transform.position;
			halfHeight = ((Bounds)(ref bounds)).extents.y;
			BoxCollider val5 = val2.AddComponent<BoxCollider>();
			val5.center = Vector3.zero;
			val5.size = ((Bounds)(ref bounds)).size;
			GameObject val6 = new GameObject("ScanNode");
			val6.transform.SetParent(val2.transform, false);
			val6.transform.localPosition = val5.center;
			int num2 = LayerMask.NameToLayer("ScanNode");
			if (num2 >= 0)
			{
				val6.layer = num2;
			}
			BoxCollider obj = val6.AddComponent<BoxCollider>();
			((Collider)obj).isTrigger = true;
			obj.size = Vector3.one * 0.5f;
			ScanNodeProperties obj2 = val6.AddComponent<ScanNodeProperties>();
			obj2.headerText = "Broken robot";
			obj2.subText = "Value: ";
			obj2.nodeType = 2;
			obj2.maxRange = 13;
			obj2.minRange = 1;
			obj2.requiresLineOfSight = true;
			Item = ScriptableObject.CreateInstance<Item>();
			((Object)Item).name = "CompanyRnD_BrokenRobotItem";
			Item.itemName = "Broken robot";
			Item.spawnPrefab = val2;
			Item.isScrap = true;
			Item.twoHanded = true;
			Item.twoHandedAnimation = true;
			Item.weight = 1.45f;
			Item.minValue = 120;
			Item.maxValue = 220;
			Item.canBeGrabbedBeforeGameStart = true;
			Item.isConductiveMetal = true;
			Item.verticalOffset = halfHeight;
			Item.restingRotation = Vector3.zero;
			Item.positionOffset = new Vector3(0f, 0.1f, 0.25f);
			Item.rotationOffset = new Vector3(0f, 90f, 0f);
			Item.grabAnim = "HoldLung";
			Item.toolTips = new string[0];
			Item.meshVariants = (Mesh[])(object)new Mesh[0];
			Item.materialVariants = (Material[])(object)new Material[0];
			Item.clinkAudios = (AudioClip[])(object)new AudioClip[0];
			Item.spawnPositionTypes = new List<ItemGroup>();
			PhysicsProp obj3 = val2.AddComponent<PhysicsProp>();
			((GrabbableObject)obj3).grabbable = true;
			((GrabbableObject)obj3).grabbableToEnemies = true;
			((GrabbableObject)obj3).itemProperties = Item;
			((GrabbableObject)obj3).mainObjectRenderer = componentsInChildren2[0];
			val2.AddComponent<BrokenRobotLook>();
			AudioSource obj4 = val2.AddComponent<AudioSource>();
			obj4.playOnAwake = false;
			obj4.spatialBlend = 1f;
			obj4.rolloffMode = (AudioRolloffMode)1;
			obj4.maxDistance = 25f;
			NetworkPrefabs.RegisterNetworkPrefab(val2);
			Items.RegisterScrap(Item, 8, (LevelTypes)(-1));
			Plugin.Log.LogInfo((object)"Broken robot scrap registered");
		}

		public static void BorrowFromVanilla()
		{
			//IL_015e: 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)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Item == (Object)null)
			{
				return;
			}
			Item val = StartOfRound.Instance?.allItemsList?.itemsList?.FirstOrDefault((Func<Item, bool>)((Item i) => (Object)(object)i != (Object)null && i.itemName == "Large axle"));
			if (!((Object)(object)val == (Object)null))
			{
				Item.grabSFX = val.grabSFX;
				Item.dropSFX = val.dropSFX;
				Item.pocketSFX = val.pocketSFX;
				Item.throwSFX = val.throwSFX;
				Item.itemIcon = val.itemIcon;
				Item.grabAnim = val.grabAnim;
				Item.grabAnimationTime = val.grabAnimationTime;
				Item.clinkAudios = val.clinkAudios;
				Item val2 = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => (Object)(object)i != (Object)null && i.itemName == "Cash register")) ?? ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => (Object)(object)i != (Object)null && i.itemName == "V-type engine"));
				if ((Object)(object)val2 != (Object)null)
				{
					Item.positionOffset = val2.positionOffset;
					Item.rotationOffset = val2.rotationOffset;
					Item.grabAnim = val2.grabAnim;
					Item.grabAnimationTime = val2.grabAnimationTime;
					Plugin.Log.LogInfo((object)$"Broken robot held like the {val2.itemName}: offset {val2.positionOffset}, rotation {val2.rotationOffset}, anim {val2.grabAnim}");
				}
			}
		}

		public static string PaletteFor(ulong networkObjectId)
		{
			List<string> list = (from p in PaintShop.All
				select p.name into n
				where n != "factory"
				select n).ToList();
			if (list.Count != 0)
			{
				return list[(int)(networkObjectId % (ulong)list.Count)];
			}
			return "factory";
		}
	}
	internal class BrokenRobotLook : MonoBehaviour
	{
		private bool done;

		private void Update()
		{
			if (done)
			{
				return;
			}
			NetworkObject component = ((Component)this).GetComponent<NetworkObject>();
			if ((Object)(object)component == (Object)null || !component.IsSpawned)
			{
				return;
			}
			Material val = PaintShop.Get(BrokenRobotItem.PaletteFor(component.NetworkObjectId));
			if (!((Object)(object)val == (Object)null))
			{
				MeshRenderer[] componentsInChildren = ((Component)this).GetComponentsInChildren<MeshRenderer>();
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((Renderer)componentsInChildren[i]).sharedMaterial = val;
				}
				done = true;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "Start")]
	internal static class BorrowPatch
	{
		private static void Postfix()
		{
			Stations.FixShaders();
			BrokenRobotItem.BorrowFromVanilla();
		}
	}
	[HarmonyPatch(typeof(GrabbableObject), "LateUpdate")]
	internal static class BrokenRobotHoldHigher
	{
		public const float Lift = 0.18f;

		private static void Postfix(GrabbableObject __instance)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.isHeld && !__instance.isPocketed && (Object)(object)__instance.itemProperties != (Object)null && __instance.itemProperties.itemName == "Broken robot")
			{
				Transform transform = ((Component)__instance).transform;
				transform.position += Vector3.up * 0.18f;
			}
		}
	}
	internal class GearDef
	{
		public string Id;

		public string Name;

		public string Effect;

		public string[] Items = new string[0];

		public string[] Tags = new string[0];

		public int BasePrice;

		public int MaxEffect;

		public Func<int, string> DescribeLevel;

		public string Look;

		public Color Tint = Color.white;

		public float Battery;

		public string SpawnItem;

		public string SpawnExtra;

		public int SpawnExtraCount;

		public string Vanilla;

		public string[] VTracks;

		public string Requires;

		public float Cooldown = 10f;

		public string Model;

		public string ModelFrom;

		public string ModelPart;
	}
	internal static class Catalog
	{
		private class ExternalTags
		{
			public Dictionary<string, string[]> items;
		}

		public static readonly List<GearDef> Gear = new List<GearDef>
		{
			new GearDef
			{
				Id = "robot",
				Name = "Robot repair",
				Effect = "Repairs it into a new research robot, in its colour.",
				Items = new string[1] { "Broken robot" },
				BasePrice = 0,
				DescribeLevel = (int l) => ""
			},
			new GearDef
			{
				Id = "featherfall",
				Name = "Featherfall",
				Effect = "Less fall damage.",
				Items = new string[2] { "Hairdryer", "Cracked jetpack thruster" },
				Tags = new string[1] { "air" },
				BasePrice = 40,
				MaxEffect = 5,
				DescribeLevel = (int l) => (l < 5) ? $"{Math.Round(100f * (1f - Effects.FeatherfallMult(l)))}% less fall damage" : "no fall damage"
			},
			new GearDef
			{
				Id = "plating",
				Name = "Plating",
				Effect = "Less damage taken.",
				Items = new string[3] { "Metal sheet", "Stop sign", "Yield sign" },
				Tags = new string[1] { "metal" },
				BasePrice = 60,
				DescribeLevel = (int l) => $"{Math.Round(100f * (1f - Effects.PlatingMult(l)))}% less damage"
			},
			new GearDef
			{
				Id = "hushed",
				Name = "Hushed Steps",
				Effect = "Enemies hear you from less far away.",
				Items = new string[6] { "Whoopie cushion", "Toilet paper", "Earth Leviathan tissue sample", "Forest Keeper tissue sample", "Old Bird tissue sample", "Eyeless dog tissue sample" },
				Tags = new string[1] { "soft" },
				BasePrice = 50,
				MaxEffect = 0,
				DescribeLevel = (int l) => $"heard {Math.Round(100f * (1f - GearEffects.HushedMult(l)))}% less far"
			},
			new GearDef
			{
				Id = "lowprofile",
				Name = "Low Profile",
				Effect = "Enemies see you from less far away.",
				Items = new string[6] { "Comedy", "Tragedy", "Earth Leviathan tissue sample", "Forest Keeper tissue sample", "Old Bird tissue sample", "Eyeless dog tissue sample" },
				Tags = new string[1] { "disguise" },
				BasePrice = 70,
				MaxEffect = 0,
				DescribeLevel = (int l) => $"seen {Math.Round(100f * (1f - GearEffects.LowProfileMult(l)))}% less far"
			},
			new GearDef
			{
				Id = "headlamp",
				Name = "Headlamp",
				Effect = "A hands-free light that's always on.",
				Items = new string[1] { "Fancy lamp" },
				Tags = new string[1] { "light" },
				BasePrice = 35,
				MaxEffect = 0,
				DescribeLevel = (int l) => $"{14 + 5 * l} m beam"
			},
			new GearDef
			{
				Id = "wayfinder",
				Name = "Wayfinder",
				Effect = "A compass bar at the top of the screen pointing to the exits.",
				Items = new string[1] { "Steering wheel" },
				Tags = new string[1] { "navigation" },
				BasePrice = 45,
				MaxEffect = 3,
				DescribeLevel = (int l) => (l > 1) ? ((l != 2) ? "all exits, with distances" : "main entrance and fire exits") : "main entrance"
			},
			new GearDef
			{
				Id = "fogvision",
				Name = "Fog Vision",
				Effect = "See further in fog.",
				Items = new string[1] { "Magnifying glass" },
				Tags = new string[1] { "optics" },
				BasePrice = 40,
				MaxEffect = 0,
				DescribeLevel = (int l) => $"fog {GearEffects.FogMult(l):0.#}x thinner"
			},
			new GearDef
			{
				Id = "recall",
				Name = "Recall Beacon",
				Effect = "Teleports you back to the ship.",
				Items = new string[1] { "Broken teleporter core" },
				BasePrice = 70,
				MaxEffect = 2,
				Look = "Remote",
				Model = "RecallBeacon",
				Tint = new Color(0.4f, 0.9f, 1f),
				DescribeLevel = (int l) => (l < 2) ? "you drop what you carry" : "keeps what you carry"
			},
			new GearDef
			{
				Id = "relay",
				Name = "Relay Beacon",
				Effect = "Use once to mark a spot; use again to teleport back to it.",
				Items = new string[1] { "Broken teleporter core" },
				Requires = "recall",
				BasePrice = 90,
				MaxEffect = 2,
				Cooldown = 20f,
				Look = "Remote",
				Model = "RelayBeacon",
				Tint = new Color(0.6f, 0.5f, 1f),
				DescribeLevel = (int l) => (l < 2) ? "you drop what you carry" : "keeps what you carry"
			},
			new GearDef
			{
				Id = "lidar",
				Name = "LIDAR Pulse",
				Effect = "Briefly outlines the walls and rooms around you with glowing dots.",
				Items = new string[1] { "Laser pointer" },
				Tags = new string[1] { "optics" },
				BasePrice = 40,
				Cooldown = 15f,
				Look = "Laser pointer",
				Model = "LidarDevice",
				Tint = new Color(0.4f, 1f, 0.9f),
				DescribeLevel = (int l) => $"{Lidar.Range(l):0} m, shows {Lidar.Seconds(l):0} s"
			},
			new GearDef
			{
				Id = "jammer",
				Name = "Trap Jammer",
				Effect = "Shuts off nearby turrets and mines for a while.",
				Items = new string[1] { "Remote" },
				Tags = new string[1] { "electronic" },
				BasePrice = 60,
				Look = "Laser pointer",
				Model = "TrapJammer",
				Tint = new Color(1f, 0.85f, 0.2f),
				DescribeLevel = (int l) => $"{12 + 4 * l} m, {6 + 3 * l} s"
			},
			new GearDef
			{
				Id = "scare",
				Name = "Scare Horn",
				Effect = "A blast that stuns nearby enemies for a moment.",
				Items = new string[2] { "Airhorn", "Clown horn" },
				Tags = new string[1] { "noisy" },
				BasePrice = 45,
				Look = "Airhorn",
				Tint = new Color(1f, 0.35f, 0.3f),
				DescribeLevel = (int l) => $"{10 + 3 * l} m, {1.5f + 0.75f * (float)l:0.#} s stun"
			},
			new GearDef
			{
				Id = "stim",
				Name = "Stim Shot",
				Effect = "Full stamina and a burst of speed.",
				Items = new string[2] { "Flask", "Chemical jug" },
				Tags = new string[1] { "chemical" },
				BasePrice = 30,
				Look = "TZP-Inhalant",
				Model = "StimShot",
				Tint = new Color(0.5f, 1f, 0.45f),
				DescribeLevel = (int l) => $"+{15 * l}% speed for {6 + 2 * l} s"
			},
			new GearDef
			{
				Id = "flare",
				Name = "Flare Pack",
				Effect = "Drops a bright flare that burns for a while.",
				Items = new string[1] { "Old phone" },
				Tags = new string[1] { "light" },
				BasePrice = 20,
				Look = "Old phone",
				Tint = new Color(1f, 0.45f, 0.35f),
				DescribeLevel = (int l) => $"burns {60 + 30 * l} s"
			},
			V("v_shovel", "Shovel", new string[2] { "effect", "cooldown" }, "Hits harder; swings come round faster.", (int l) => $"hits {l}x as hard"),
			V("v_knife", "Kitchen knife", new string[2] { "effect", "cooldown" }, "Hits harder; stabs come faster.", (int l) => $"+{l - 1} damage a hit"),
			V("v_flashlight", "Flashlight", new string[2] { "effect", "duration" }, "Brighter and further; the battery lasts longer.", (int l) => $"{100 + 25 * (l - 1)}% light"),
			V("v_proflashlight", "Pro-flashlight", new string[2] { "effect", "duration" }, "Brighter and further; the battery lasts longer.", (int l) => $"{100 + 25 * (l - 1)}% light"),
			V("v_walkie", "Walkie-talkie", new string[2] { "effect", "duration" }, "Picks up voices from further away; the battery lasts longer.", (int l) => $"{100 + 25 * (l - 1)}% pickup range"),
			V("v_boombox", "Boombox", new string[1] { "duration" }, "The battery lasts longer.", null),
			V("v_jetpack", "Jetpack", new string[2] { "effect", "duration" }, "More thrust; the fuel lasts longer.", (int l) => $"{100 + 25 * (l - 1)}% thrust"),
			V("v_ladder", "Extension ladder", new string[1] { "duration" }, "Stays up longer.", null),
			V("v_lockpicker", "Lockpicker", new string[1] { "cooldown" }, "Picks locks faster.", null),
			V("v_tzp", "TZP-Inhalant", new string[1] { "duration" }, "Each can lasts longer.", null),
			V("v_radar", "Radar-booster", new string[1] { "cooldown" }, "Its flash recharges faster.", null),
			V("v_spray", "Spray paint", new string[1] { "duration" }, "Each can holds more paint.", null),
			V("v_weed", "Weed killer", new string[1] { "duration" }, "Each bottle holds more.", null),
			V("v_stun", "Stun grenade", new string[1] { "effect" }, "Stuns every enemy around it, further away and for longer.", (int l) => (l > 1) ? $"stuns everything within {VanillaUpgrades.StunRadius(l):0} m for {VanillaUpgrades.StunSeconds(l):0.#} s" : "vanilla stun"),
			V("v_zap", "Zap gun", new string[2] { "effect", "duration" }, "Locks on and stuns faster; the battery lasts longer.", (int l) => $"locks on {100 + 25 * (l - 1)}% as fast"),
			V("v_shotgun", "Shotgun", new string[3] { "effect", "duration", "cooldown" }, "More damage a shot; holds more shells; reloads faster.", (int l) => $"+{l - 1} damage a shot"),
			new GearDef
			{
				Id = "hammer",
				Name = "Breaching Hammer",
				Effect = "A slower, heavier shovel that also breaks locked doors open.",
				Items = new string[2] { "Large axle", "Big bolt" },
				Tags = new string[1] { "metal" },
				BasePrice = 80,
				MaxEffect = 1,
				SpawnItem = "Breaching Hammer",
				DescribeLevel = (int l) => "hits twice as hard as a shovel, breaks locks"
			},
			new GearDef
			{
				Id = "mine",
				Name = "Portable Mine",
				Effect = "Pull the pin and throw it like a stun grenade; it arms as a landmine where it lands. Enemies set it off too.",
				Items = new string[1] { "Easter egg" },
				Tags = new string[1] { "explosive" },
				BasePrice = 50,
				MaxEffect = 1,
				SpawnItem = "Portable Mine",
				DescribeLevel = (int l) => "a thrown landmine anyone or anything can trigger"
			},
			new GearDef
			{
				Id = "frag",
				Name = "Frag Grenade",
				Effect = "A grenade that explodes instead of flashing.",
				Items = new string[1] { "Easter egg" },
				Tags = new string[1] { "explosive" },
				Requires = "mine",
				BasePrice = 40,
				MaxEffect = 0,
				SpawnItem = "Frag Grenade",
				DescribeLevel = (int l) => $"kills within {2f + 0.5f * (float)l:0.#} m, hurts within {5 + l} m"
			},
			new GearDef
			{
				Id = "shotgun",
				Name = "Company Shotgun",
				Effect = "A shotgun from the Company, with shells.",
				Items = new string[2] { "Shotgun", "Ammo" },
				BasePrice = 250,
				MaxEffect = 1,
				SpawnItem = "Shotgun",
				SpawnExtra = "Ammo",
				SpawnExtraCount = 2,
				DescribeLevel = (int l) => "a shotgun and two shells"
			},
			new GearDef
			{
				Id = "smg",
				Name = "Turret SMG",
				Effect = "A reprogrammed turret. Low damage, but enemies flinch back. Runs on a battery.",
				Items = new string[1] { "Shotgun" },
				Tags = new string[1] { "electronic" },
				BasePrice = 150,
				MaxEffect = 1,
				Battery = 0.04f,
				Cooldown = 0.15f,
				ModelFrom = "Turret",
				Look = "Pro-flashlight",
				Tint = Color.white,
				DescribeLevel = (int l) => "1 damage a shot, enemies flinch"
			},
			new GearDef
			{
				Id = "arc",
				Name = "Arc Rifle",
				Effect = "An electric shot that damages and stuns. Kills small enemies.",
				Items = new string[1] { "Apparatus" },
				BasePrice = 200,
				MaxEffect = 0,
				Battery = 0.12f,
				Cooldown = 0.8f,
				Look = "Pro-flashlight",
				Tint = new Color(0.3f, 1f, 0.35f),
				DescribeLevel = (int l) => $"{1 + l} damage, stuns {1.5f + 0.5f * (float)l:0.#} s"
			},
			new GearDef
			{
				Id = "shrink",
				Name = "Shrink Ray",
				Effect = "Shrinks an enemy to half size: slower, and easy to catch in a Specimen Jar.",
				Items = new string[2] { "Apparatus", "Magnifying glass" },
				Tags = new string[1] { "optics" },
				Requires = "arc",
				BasePrice = 220,
				MaxEffect = 0,
				Battery = 0.2f,
				Cooldown = 1f,
				Look = "Pro-flashlight",
				Tint = new Color(1f, 0.3f, 0.9f),
				DescribeLevel = (int l) => $"half size for {15 + 10 * l} s"
			},
			new GearDef
			{
				Id = "freeze",
				Name = "Freeze Ray",
				Effect = "Each hit chills an enemy and slows it more; enough hits freeze it solid, and a frozen enemy takes double damage.",
				Items = new string[2] { "Apparatus", "Chemical jug" },
				Tags = new string[1] { "chemical" },
				Requires = "arc",
				BasePrice = 220,
				MaxEffect = 0,
				Battery = 0.15f,
				Cooldown = 0.8f,
				Look = "Pro-flashlight",
				Tint = new Color(0.3f, 0.7f, 1f),
				DescribeLevel = (int l) => $"{FreezeRay.HitsToFreeze(l)} hits freeze it for {FreezeRay.FrozenSeconds(l):0} s, double damage while frozen"
			},
			new GearDef
			{
				Id = "exo",
				Name = "Hoarding Exoskeleton",
				Effect = "What you carry feels lighter.",
				Items = new string[1] { Specimens.ItemOf("hoarder") },
				BasePrice = 70,
				MaxEffect = 0,
				DescribeLevel = (int l) => $"carried weight feels {Mathf.RoundToInt(100f * (1f - Exoskeleton.Mult(l)))}% lighter"
			},
			new GearDef
			{
				Id = "jar",
				Name = "Specimen Jar",
				Effect = "Catch a small creature (dead, stunned or shrunk), or take a tissue sample from a living big one.",
				Items = new string[1] { "Jar of pickles" },
				BasePrice = 60,
				MaxEffect = 0,
				Cooldown = 2f,
				Look = "Jar of pickles",
				Model = "SpecimenJar",
				DescribeLevel = (int l) => $"reach {Specimens.Reach(l):0.#} m" + ((l >= 3) ? ", catches small creatures even awake" : "")
			},
			new GearDef
			{
				Id = "sporebomb",
				Name = "Spore Bomb",
				Effect = "Bursts into a spore cloud. Enemies can't see anyone inside it.",
				Items = new string[1] { Specimens.ItemOf("spore") },
				BasePrice = 70,
				MaxEffect = 0,
				Cooldown = 20f,
				Look = "Easter egg",
				Tint = new Color(0.55f, 1f, 0.4f),
				DescribeLevel = (int l) => $"{Specimens.CloudRadius(l):0} m cloud for {Specimens.CloudSeconds(l):0} s"
			},
			new GearDef
			{
				Id = "slimetrap",
				Name = "Slime Trap",
				Effect = "Leaves a sticky puddle that slows enemies down.",
				Items = new string[1] { Specimens.ItemOf("blob") },
				BasePrice = 60,
				MaxEffect = 0,
				Cooldown = 10f,
				Look = "Jar of pickles",
				Tint = new Color(0.35f, 1f, 0.5f),
				DescribeLevel = (int l) => $"lasts {Specimens.SlimeSeconds(l):0} s"
			},
			new GearDef
			{
				Id = "hook",
				Name = "Ceiling Hook",
				Effect = "A short grapple: pulls you up to the ledge or ceiling you're looking at.",
				Items = new string[1] { Specimens.ItemOf("flea") },
				BasePrice = 80,
				MaxEffect = 0,
				Cooldown = 5f,
				Look = "Spray paint",
				Model = "GrappleHook",
				ModelPart = "GrappleClaw",
				DescribeLevel = (int l) => $"reach {Specimens.HookReach(l):0} m"
			},
			new GearDef
			{
				Id = "cloak",
				Name = "Shade Cloak",
				Effect = "Enemies can't see you for a short time.",
				Items = new string[1] { Specimens.ItemOf("bracken") },
				BasePrice = 120,
				MaxEffect = 0,
				Cooldown = 30f,
				Look = "Tragedy",
				Tint = new Color(0.3f, 0.3f, 0.38f),
				DescribeLevel = (int l) => $"unseen for {Specimens.CloakSeconds(l):0.#} s"
			},
			new GearDef
			{
				Id = "stasis",
				Name = "Stasis Mine",
				Effect = "Freezes the first enemy that steps on it.",
				Items = new string[1] { Specimens.ItemOf("coil") },
				BasePrice = 90,
				MaxEffect = 0,
				Cooldown = 5f,
				Look = "Stun grenade",
				Tint = new Color(0.5f, 0.9f, 1f),
				DescribeLevel = (int l) => $"frozen for {Specimens.StasisSeconds(l):0} s"
			},
			new GearDef
			{
				Id = "decoy",
				Name = "Music Box Decoy",
				Effect = "Plays a tune that draws enemies to it.",
				Items = new string[1] { Specimens.ItemOf("jester") },
				BasePrice = 90,
				MaxEffect = 0,
				Cooldown = 20f,
				Look = "Toy robot",
				Tint = new Color(1f, 0.5f, 0.8f),
				DescribeLevel = (int l) => $"plays for {Specimens.DecoySeconds(l):0} s"
			},
			new GearDef
			{
				Id = "floatvest",
				Name = "Float Vest",
				Effect = "Sink more slowly and hold your breath longer.",
				Items = new string[2] { "Rubber Ducky", "Plastic fish" },
				Tags = new string[1] { "floaty" },
				BasePrice = 35,
				MaxEffect = 0,
				DescribeLevel = (int l) => $"sink and lose air {Math.Round(100f * (1f - GearEffects.FloatMult(l)))}% slower"
			}
		};

		private static readonly Dictionary<string, HashSet<string>> explicitTags = new Dictionary<string, HashSet<string>>();

		private static readonly Dictionary<string, string[]> guessWords = new Dictionary<string, string[]>
		{
			["air"] = new string[6] { "dryer", "fan", "blower", "thruster", "jetpack", "balloon" },
			["metal"] = new string[10] { "metal", "steel", "iron", "sheet", "sign", "bolt", "axle", "pipe", "wrench", "girder" },
			["soft"] = new string[7] { "cushion", "pillow", "plush", "paper", "towel", "sock", "blanket" },
			["disguise"] = new string[6] { "mask", "costume", "wig", "comedy", "tragedy", "disguise" },
			["light"] = new string[6] { "lamp", "lantern", "bulb", "flashlight", "candle", "torch" },
			["navigation"] = new string[5] { "compass", "map", "wheel", "globe", "sextant" },
			["optics"] = new string[6] { "magnif", "lens", "binocular", "telescope", "spyglass", "glasses" },
			["floaty"] = new string[6] { "duck", "float", "buoy", "raft", "inflat", "pool" },
			["electronic"] = new string[8] { "remote", "radio", "phone", "circuit", "chip", "battery", "console", "controller" },
			["noisy"] = new string[7] { "horn", "bell", "whistle", "siren", "drum", "speaker", "cymbal" },
			["explosive"] = new string[8] { "egg", "grenade", "bomb", "dynamite", "mine", "explosive", "tnt", "firework" },
			["chemical"] = new string[7] { "flask", "chemical", "jug", "vial", "potion", "beaker", "bottle" }
		};

		private static bool configParsed;

		private static GearDef V(string id, string item, string[] tracks, string effect, Func<int, string> describe)
		{
			GearDef gearDef = new GearDef();
			gearDef.Id = id;
			gearDef.Name = item + " upgrades";
			gearDef.Vanilla = item;
			gearDef.VTracks = tracks;
			gearDef.Items = new string[1] { item };
			gearDef.Effect = effect;
			gearDef.BasePrice = 0;
			gearDef.MaxEffect = 0;
			gearDef.DescribeLevel = describe ?? ((Func<int, string>)((int l) => effect));
			return gearDef;
		}

		public static string[] Tracks(GearDef g)
		{
			if (g.Id == "robot")
			{
				return new string[1] { "repair" };
			}
			if (g.Vanilla != null)
			{
				return g.VTracks;
			}
			if (!(g.Battery > 0f))
			{
				if (g.SpawnItem == null)
				{
					if (g.Look == null)
					{
						return new string[2] { "effect", "duration" };
					}
					return new string[4] { "effect", "duration", "yield", "cooldown" };
				}
				return new string[2] { "effect", "yield" };
			}
			return new string[2] { "effect", "cooldown" };
		}

		public static bool Has(GearDef g, string track)
		{
			return Array.IndexOf(Tracks(g), track) >= 0;
		}

		public static string Summary(GearDef g, GearProgress p)
		{
			string text = ((g.DescribeLevel != null) ? g.DescribeLevel(p.EffectLevel) : g.Effect);
			if (g.Vanilla != null)
			{
				List<string> list = new List<string>();
				if (Has(g, "effect"))
				{
					list.Add(text);
				}
				if (Has(g, "duration"))
				{
					list.Add((g.Id == "v_shotgun") ? $"holds {2 + p.DurationLevel} shells" : $"lasts {VanillaUpgrades.Lasts(g, p.DurationLevel):0.#}x as long");
				}
				if (Has(g, "cooldown"))
				{
					list.Add($"{Math.Round(100f * (1f - VanillaUpgrades.TimeShare(p.CooldownLevel)))}% faster");
				}
				return string.Join(", ", list);
			}
			if (g.Battery > 0f)
			{
				return $"{text}, {Weapons.Shots(g, p.CooldownLevel)} shots per charge";
			}
			if (g.SpawnItem != null)
			{
				if (p.YieldLevel <= 0)
				{
					return text;
				}
				return $"{text}, {1 + p.YieldLevel} at a time";
			}
			if (g.Look != null)
			{
				return $"{text}, {Research.UsesName(p.DurationLevel)}, {1 + p.YieldLevel} at a time, {Research.CooldownFor(g, p.CooldownLevel):0.#} s recharge";
			}
			return text + ", lasts " + Research.DurationName(p.DurationLevel);
		}

		public static GearDef Get(string id)
		{
			return Gear.FirstOrDefault((GearDef g) => g.Id == id);
		}

		public static string Norm(string s)
		{
			return new string((s ?? "").ToLowerInvariant().Where(char.IsLetterOrDigit).ToArray());
		}

		private static void AddTag(string item, string tag)
		{
			string key = Norm(item);
			if (!explicitTags.TryGetValue(key, out var value))
			{
				value = (explicitTags[key] = new HashSet<string>());
			}
			value.Add(tag.Trim().ToLowerInvariant());
		}

		public static void LoadExternalTagFiles(string pluginRoot)
		{
			try
			{
				string[] files = Directory.GetFiles(pluginRoot, "CompanyRnD.json", SearchOption.AllDirectories);
				foreach (string text in files)
				{
					foreach (KeyValuePair<string, string[]> item in JsonConvert.DeserializeObject<ExternalTags>(File.ReadAllText(text))?.items ?? new Dictionary<string, string[]>())
					{
						string[] value = item.Value;
						foreach (string tag in value)
						{
							AddTag(item.Key, tag);
						}
					}
					Plugin.Log.LogInfo((object)("Loaded research tags from " + text));
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't read CompanyRnD.json files: " + ex.Message));
			}
		}

		private static void ParseConfigTags()
		{
			if (configParsed)
			{
				return;
			}
			configParsed = true;
			string[] array = (Plugin.Config2.ExtraTags.Value ?? "").Split(';');
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split('=');
				if (array2.Length != 2)
				{
					continue;
				}
				string[] array3 = array2[1].Split(',');
				foreach (string text in array3)
				{
					if (text.Trim() != "")
					{
						AddTag(array2[0], text);
					}
				}
			}
		}

		public static HashSet<string> TagsFor(string itemName)
		{
			ParseConfigTags();
			if (explicitTags.TryGetValue(Norm(itemName), out var value))
			{
				return value;
			}
			string n = Norm(itemName);
			return new HashSet<string>(from kv in guessWords
				where kv.Value.Any((string w) => n.Contains(w))
				select kv.Key);
		}

		public static bool Feeds(GearDef g, string itemName)
		{
			string n = Norm(itemName);
			if (!g.Items.Any((string i) => Norm(i) == n))
			{
				return TagsFor(itemName).Overlaps(g.Tags);
			}
			return true;
		}

		public static IEnumerable<GearDef> GearFedBy(string itemName)
		{
			return Gear.Where((GearDef g) => Feeds(g, itemName));
		}
	}
	internal static class Codex
	{
		private static Dictionary<string, List<(string moon, float pct)>> where;

		private static int levelsSeen = -1;

		public static readonly Dictionary<string, string> Lore = new Dictionary<string, string>
		{
			["robot"] = "Company research units, model MANUL. Discarded in bulk after the Restructuring. They curl up when they power down, which the Company insists is a safety feature.",
			["featherfall"] = "Soft-landing servos salvaged from hair dryers and burnt-out jetpacks. Not rated for catwalks. Rated for catwalks now.",
			["plating"] = "Road signs, hammered thin and stitched into the suit lining. The Company reminds you that traffic laws still apply.",
			["hushed"] = "Suit soles packed with whoopie-cushion rubber and toilet paper. Smells faintly of a party nobody enjoyed.",
			["lowprofile"] = "A woven mask-mesh over the visor that breaks up your outline. Comedy and tragedy, in equal parts.",
			["headlamp"] = "A lamp bulb grafted onto the helmet. Hands-free, always on, and impossible to turn off. Bring spare eyelids.",
			["wayfinder"] = "A steering wheel's gyro, sewn into the visor. It points home. It does not judge you for needing it.",
			["fogvision"] = "Ground magnifying lenses that sharpen the visor through fog. Side effects: seeing what's in the fog.",
			["floatvest"] = "Inflatable lining harvested from rubber ducks. It squeaks under pressure. So will you.",
			["recall"] = "One shard of a broken ship teleporter, cradled in a phone handset. Press, pray, arrive. The first models forgot to bring your luggage.",
			["relay"] = "Two shards of teleporter core in a radio housing, tuned to each other. One stays where you leave it. The other brings you back.",
			["lidar"] = "A camera rebuilt around a laser pointer. It paints the walls with light for a few seconds, which is longer than most employees need.",
			["jammer"] = "A remote with every button hard-wired to 'off'. Turrets and mines forget their purpose for a while.",
			["scare"] = "An air horn, overclocked. Everything nearby flinches, including you.",
			["stim"] = "Industrial-grade stimulant in a small green bottle. Do not read the label. There is no label.",
			["flare"] = "A phone battery wired to burn red for a very long time. Everyone will know where you are. Everything will too.",
			["mine"] = "A landmine with a carrying handle. The Company reminds you which end goes down.",
			["hammer"] = "A shovel that went to the gym. Doors are now a suggestion.",
			["frag"] = "A stun grenade with the flash swapped for something less forgiving.",
			["shotgun"] = "Confiscated from a Nutcracker, inspected, approved and resold to you at a modest markup.",
			["smg"] = "A turret, gently convinced to work for you. It still thinks everything is an intruder.",
			["arc"] = "An apparatus in a gun-shaped housing. Point away from face.",
			["shrink"] = "The apparatus, focused through a lens. Things come out smaller. The Company is not liable for what comes out of the jar later.",
			["freeze"] = "The apparatus, run through chemical coolant. Chill it, freeze it, then hit it hard: frozen things break easily.",
			["exo"] = "Hoarding bug leg joints, braced along your spine. It wants to carry everything home. So do you.",
			["jar"] = "A pickle jar, emptied and blessed by R&D. It holds anything small enough and anything too tired to argue.",
			["sporebomb"] = "A spore lizard's defensive puff, bottled. Breathe through your mouth.",
			["slimetrap"] = "A thimble of hygrodere, spread thin. Enemies wade; you don't.",
			["hook"] = "A snare flea's silk, wound on a spool. It wants to go up. Let it.",
			["cloak"] = "Bracken hide, cured and hooded. While you wear it, things forget you were ever there.",
			["stasis"] = "A coil-head's spring, wound tight and pointed upward. Don't look away from it either.",
			["decoy"] = "A jester's music box, tuned to stop just before the last note."
		};

		public static List<(string moon, float pct)> Where(string item)
		{
			Build();
			if (where == null || !where.TryGetValue(Catalog.Norm(item), out List<(string, float)> value))
			{
				return new List<(string, float)>();
			}
			return value;
		}

		public static List<(string item, float pct)> OnMoon(SelectableLevel lvl)
		{
			List<(string, float)> list = new List<(string, float)>();
			if (lvl?.spawnableScrap == null)
			{
				return list;
			}
			float num = lvl.spawnableScrap.Where((SpawnableItemWithRarity s) => (Object)(object)s?.spawnableItem != (Object)null).Sum((Func<SpawnableItemWithRarity, float>)((SpawnableItemWithRarity s) => s.rarity));
			if (num <= 0f)
			{
				return list;
			}
			foreach (SpawnableItemWithRarity item in lvl.spawnableScrap)
			{
				if (!((Object)(object)item?.spawnableItem == (Object)null) && item.rarity > 0 && Catalog.GearFedBy(item.spawnableItem.itemName).Any())
				{
					list.Add((item.spawnableItem.itemName, 100f * (float)item.rarity / num));
				}
			}
			return list.OrderByDescending(((string, float) x) => x.Item2).ToList();
		}

		private static void Build()
		{
			SelectableLevel[] array = StartOfRound.Instance?.levels;
			if (array == null || (where != null && levelsSeen == array.Length))
			{
				return;
			}
			levelsSeen = array.Length;
			where = new Dictionary<string, List<(string, float)>>();
			SelectableLevel[] array2 = array;
			foreach (SelectableLevel val in array2)
			{
				foreach (var item3 in OnMoon(val))
				{
					string item = item3.item;
					float item2 = item3.pct;
					string key = Catalog.Norm(item);
					if (!where.TryGetValue(key, out List<(string, float)> value))
					{
						value = (where[key] = new List<(string, float)>());
					}
					value.Add((MoonName(val), item2));
				}
			}
			foreach (List<(string, float)> value2 in where.Values)
			{
				value2.Sort(((string moon, float pct) a, (string moon, float pct) b) => b.pct.CompareTo(a.pct));
			}
		}

		public static string MoonName(SelectableLevel l)
		{
			if (!string.IsNullOrEmpty(l.PlanetName))
			{
				return l.PlanetName;
			}
			return ((Object)l).name;
		}

		public static string WhereLine(string item, int max = 3)
		{
			List<(string, float)> list = Where(item);
			if (list.Count == 0)
			{
				return "not found on any moon's scrap list";
			}
			return string.Join(", ", from x in list.Take(max)
				select $"{x.moon} {x.pct:0.#}%") + ((list.Count > max) ? $" (+{list.Count - max} more)" : "");
		}

		public static string For(string id)
		{
			if (!Lore.TryGetValue(id, out var value))
			{
				return "";
			}
			return value;
		}

		public static string Collection()
		{
			StringBuilder stringBuilder = new StringBuilder("COMPANY R&D: SPECIMEN COLLECTION\n\n");
			int num = 0;
			Specimens.Kind[] kinds = Specimens.Kinds;
			foreach (Specimens.Kind k in kinds)
			{
				bool flag = Store.S.SeenItems.Any((string x) => Catalog.Norm(x) == Catalog.Norm(k.Item));
				if (flag)
				{
					num++;
				}
				stringBuilder.AppendLine("[" + (flag ? "x" : " ") + "] " + ((flag || Plugin.Config2.Spoilers.Value) ? k.Name : "???") + (k.Big ? " (tissue sample)" : ""));
			}
			stringBuilder.AppendLine($"\n{num}/{Specimens.Kinds.Length} researched." + ((num == Specimens.Kinds.Length) ? " A complete collection. The Company is mildly impressed." : ""));
			return stringBuilder.ToString();
		}
	}
	internal static class CompanyDecor
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static UnityAction <0>__Hold;
		}

		private static BoxCollider shipBox;

		private static Vector3 shipBoxSize;

		private static bool stretched;

		private static bool hooked;

		private static PlaceableShipObject lastMoving;

		private static readonly Dictionary<int, PlaceableShipObject> byId = new Dictionary<int, PlaceableShipObject>();

		private static float lookupTimer;

		private static readonly Dictionary<GameObject, List<(Component c, bool was)>> hiddenState = new Dictionary<GameObject, List<(Component, bool)>>();

		private static readonly Dictionary<int, (PlaceableShipObject p, Vector3 at, int frame)> pending = new Dictionary<int, (PlaceableShipObject, Vector3, int)>();

		private static ShipBuildModeManager Build => ShipBuildModeManager.Instance;

		public static bool AllowedHere()
		{
			if (Research.AtCompany && (Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.shipHasLanded)
			{
				return !StartOfRound.Instance.shipIsLeaving;
			}
			return false;
		}

		private static bool CompanyMapLoaded()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			Scene sceneByName = SceneManager.GetSceneByName("CompanyBuilding");
			if (((Scene)(ref sceneByName)).IsValid())
			{
				return ((Scene)(ref sceneByName)).isLoaded;
			}
			return false;
		}

		private static List<Transform> Parts(PlaceableShipObject p)
		{
			Transform val = (((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.elevatorTransform : null);
			List<Transform> list = ((IEnumerable<Transform>)(object)new Transform[5]
			{
				((Object)(object)p.parentObject != (Object)null) ? ((Component)p.parentObject).transform : null,
				p.parentObjectSecondary,
				((Component)p).transform,
				p.mainTransform,
				((Object)(object)p.mainMesh != (Object)null) ? ((Component)p.mainMesh).transform : null
			}).Where((Transform t) => (Object)(object)t != (Object)null).Distinct().ToList();
			HashSet<Component> hashSet = new HashSet<Component>();
			foreach (Transform item3 in list)
			{
				Renderer[] componentsInChildren = ((Component)item3).GetComponentsInChildren<Renderer>(true);
				foreach (Renderer item in componentsInChildren)
				{
					hashSet.Add((Component)(object)item);
				}
				Collider[] componentsInChildren2 = ((Component)item3).GetComponentsInChildren<Collider>(true);
				foreach (Collider item2 in componentsInChildren2)
				{
					hashSet.Add((Component)(object)item2);
				}
			}
			HashSet<Transform> hashSet2 = new HashSet<Transform>();
			foreach (Transform item4 in list)
			{
				hashSet2.Add(Lift(item4, val, hashSet));
			}
			foreach (Component item5 in hashSet)
			{
				hashSet2.Add(Lift(item5.transform, val, hashSet));
			}
			hashSet2.Remove(val);
			List<Transform> all = hashSet2.Where((Transform t) => (Object)(object)t != (Object)null).ToList();
			return all.Where((Transform t) => !all.Any((Transform o) => (Object)(object)o != (Object)(object)t && t.IsChildOf(o))).ToList();
		}

		private static Transform Lift(Transform t, Transform ship, HashSet<Component> ours)
		{
			if ((Object)(object)ship == (Object)null || !t.IsChildOf(ship) || (Object)(object)t == (Object)(object)ship)
			{
				return t;
			}
			while ((Object)(object)t.parent != (Object)null && (Object)(object)t.parent != (Object)(object)ship)
			{
				Transform parent = t.parent;
				if (!((Component)parent).GetComponentsInChildren<Renderer>(true).All(ours.Contains) || !((Component)parent).GetComponentsInChildren<Collider>(true).All(ours.Contains) || !((Component)parent).GetComponentsInChildren<PlaceableShipObject>(true).All((PlaceableShipObject x) => ((Component)x).transform.IsChildOf(t) || ours.Contains((Component)(object)x.placeObjectCollider)))
				{
					break;
				}
				t = parent;
			}
			return t;
		}

		private static string PathOf(Transform t)
		{
			List<string> list = new List<string>();
			Transform val = t;
			while ((Object)(object)val != (Object)null)
			{
				list.Add(((Object)val).name);
				val = val.parent;
			}
			list.Reverse();
			return string.Join("/", list);
		}

		public static void Tick()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_006c: 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_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			if (!hooked)
			{
				object obj = <>O.<0>__Hold;
				if (obj == null)
				{
					UnityAction val = Hold;
					<>O.<0>__Hold = val;
					obj = (object)val;
				}
				Application.onBeforeRender += (UnityAction)obj;
				hooked = true;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if ((Object)(object)shipBox == (Object)null)
			{
				Collider shipInnerRoomBounds = instance.shipInnerRoomBounds;
				shipBox = (BoxCollider)(object)((shipInnerRoomBounds is BoxCollider) ? shipInnerRoomBounds : null);
				if ((Object)(object)shipBox != (Object)null)
				{
					shipBoxSize = shipBox.size;
				}
			}
			bool flag = AllowedHere() && (Object)(object)Build != (Object)null && Build.InBuildMode;
			if ((Object)(object)shipBox != (Object)null && flag != stretched)
			{
				stretched = flag;
				shipBox.size = (flag ? (shipBoxSize + new Vector3(160f, 60f, 160f)) : shipBoxSize);
			}
			WatchBuildMode();
			RecordPending();
			Hold();
		}

		private static void Hold()
		{
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			List<DecorSpot> companyDecor = Store.S.CompanyDecor;
			if (companyDecor.Count == 0)
			{
				return;
			}
			bool flag = CompanyMapLoaded();
			foreach (DecorSpot item in companyDecor)
			{
				PlaceableShipObject val = Find(item.Id);
				if ((Object)(object)val == (Object)null || ((Object)(object)Build != (Object)null && Build.InBuildMode && (Object)(object)Build.placingObject == (Object)(object)val) || pending.ContainsKey(item.Id))
				{
					continue;
				}
				if ((Object)(object)val.parentObject != (Object)null)
				{
					((Behaviour)val.parentObject).enabled = !flag;
				}
				List<Transform> list = Parts(val);
				for (int i = 0; i < list.Count; i++)
				{
					if (flag)
					{
						float[] array = item.PoseFor(PathOf(list[i]), i);
						if (array != null)
						{
							list[i].SetPositionAndRotation(new Vector3(array[0], array[1], array[2]), Quaternion.Euler(array[3], array[4], array[5]));
						}
					}
					Show(((Component)list[i]).gameObject, flag);
				}
			}
		}

		private static void WatchBuildMode()
		{
			PlaceableShipObject moving = (((Object)(object)Build != (Object)null && Build.InBuildMode) ? Build.placingObject : null);
			if ((Object)(object)moving != (Object)null && (Object)(object)moving != (Object)(object)lastMoving && Store.S.CompanyDecor.Any((DecorSpot d) => d.Id == moving.unlockableID))
			{
				Release(moving);
			}
			lastMoving = moving;
		}

		private static PlaceableShipObject Find(int id)
		{
			if (Time.time >= lookupTimer || !byId.ContainsKey(id))
			{
				lookupTimer = Time.time + 2f;
				byId.Clear();
				PlaceableShipObject[] array = Object.FindObjectsOfType<PlaceableShipObject>();
				foreach (PlaceableShipObject val in array)
				{
					byId[val.unlockableID] = val;
				}
			}
			byId.TryGetValue(id, out var value);
			return value;
		}

		private static bool OutsideShip(Vector3 world)
		{
			//IL_0019: 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)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)shipBox == (Object)null)
			{
				return false;
			}
			Vector3 val = ((Component)shipBox).transform.InverseTransformPoint(world) - shipBox.center;
			Vector3 val2 = shipBoxSize * 0.5f;
			if (!(Mathf.Abs(val.x) > val2.x) && !(Mathf.Abs(val.y) > val2.y))
			{
				return Mathf.Abs(val.z) > val2.z;
			}
			return true;
		}

		private static void Show(GameObject go, bool on)
		{
			if (!on)
			{
				if (!hiddenState.ContainsKey(go))
				{
					List<(Component, bool)> list = new List<(Component, bool)>();
					Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true);
					foreach (Renderer val in componentsInChildren)
					{
						list.Add(((Component)(object)val, val.enabled));
						val.enabled = false;
					}
					Collider[] componentsInChildren2 = go.GetComponentsInChildren<Collider>(true);
					foreach (Collider val2 in componentsInChildren2)
					{
						list.Add(((Component)(object)val2, val2.enabled));
						val2.enabled = false;
					}
					Light[] componentsInChildren3 = go.GetComponentsInChildren<Light>(true);
					foreach (Light val3 in componentsInChildren3)
					{
						list.Add(((Component)(object)val3, ((Behaviour)val3).enabled));
						((Behaviour)val3).enabled = false;
					}
					AudioSource[] componentsInChildren4 = go.GetComponentsInChildren<AudioSource>(true);
					foreach (AudioSource val4 in componentsInChildren4)
					{
						list.Add(((Component)(object)val4, val4.mute));
						val4.mute = true;
					}
					hiddenState[go] = list;
				}
			}
			else
			{
				if (!hiddenState.TryGetValue(go, out List<(Component, bool)> value))
				{
					return;
				}
				foreach (var (val5, flag) in value)
				{
					if ((Object)(object)val5 == (Object)null)
					{
						continue;
					}
					Renderer val6 = (Renderer)(object)((val5 is Renderer) ? val5 : null);
					if (val6 == null)
					{
						Collider val7 = (Collider)(object)((val5 is Collider) ? val5 : null);
						if (val7 == null)
						{
							Light val8 = (Light)(object)((val5 is Light) ? val5 : null);
							if (val8 == null)
							{
								AudioSource val9 = (AudioSource)(object)((val5 is AudioSource) ? val5 : null);
								if (val9 != null)
								{
									val9.mute = flag;
								}
							}
							else
							{
								((Behaviour)val8).enabled = flag;
							}
						}
						else
						{
							val7.enabled = flag;
						}
					}
					else
					{
						val6.enabled = flag;
					}
				}
				hiddenState.Remove(go);
			}
		}

		private static void Release(PlaceableShipObject p)
		{
			if ((Object)(object)p == (Object)null)
			{
				return;
			}
			if ((Object)(object)p.parentObject != (Object)null)
			{
				((Behaviour)p.parentObject).enabled = true;
			}
			foreach (Transform item in Parts(p))
			{
				Show(((Component)item).gameObject, on: true);
			}
		}

		public static void OnPlaced(PlaceableShipObject p, Vector3 placedAt)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)p == (Object)null))
			{
				Store.S.CompanyDecor.RemoveAll((DecorSpot d) => d.Id == p.unlockableID);
				if ((Object)(object)p.parentObject != (Object)null)
				{
					((Behaviour)p.parentObject).enabled = true;
					p.parentObject.MoveToOffset();
				}
				Release(p);
				pending[p.unlockableID] = (p, placedAt, Time.frameCount + 3);
			}
		}

		private static void RecordPending()
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: 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_00c2: 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_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: 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_018a: Unknown result type (might be due to invalid IL or missing references)
			if (pending.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<int, (PlaceableShipObject, Vector3, int)> item3 in pending.ToList())
			{
				if (Time.frameCount < item3.Value.Item3)
				{
					continue;
				}
				pending.Remove(item3.Key);
				PlaceableShipObject item = item3.Value.Item1;
				Vector3 item2 = item3.Value.Item2;
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				if (Research.AtCompany && OutsideShip(item2))
				{
					DecorSpot decorSpot = new DecorSpot
					{
						Id = item.unlockableID
					};
					foreach (Transform item4 in Parts(item))
					{
						Vector3 eulerAngles = item4.eulerAngles;
						decorSpot.Paths.Add(PathOf(item4));
						decorSpot.Poses.Add(new float[6]
						{
							item4.position.x,
							item4.position.y,
							item4.position.z,
							eulerAngles.x,
							eulerAngles.y,
							eulerAngles.z
						});
					}
					Store.S.CompanyDecor.Add(decorSpot);
					Plugin.Log.LogInfo((object)string.Format("Decoration {0} ({1}) placed at the Company at {2}, parts: {3}", item.unlockableID, ((Object)item).name, item2, string.Join(" | ", decorSpot.Paths)));
				}
				else
				{
					Plugin.Log.LogInfo((object)$"Decoration {item.unlockableID} ({((Object)item).name}) placed inside the ship at {item2}");
				}
				if (Net.IsHost)
				{
					Store.Save();
					Net.BroadcastState();
				}
			}
		}

		public static void OnStored(int unlockableId)
		{
			if (Store.S.CompanyDecor.RemoveAll((DecorSpot d) => d.Id == unlockableId) != 0)
			{
				Release(Find(unlockableId));
				if (Net.IsHost)
				{
					Store.Save();
					Net.BroadcastState();
				}
			}
		}
	}
	internal class DecorSpot
	{
		public int Id;

		public List<float[]> Poses = new List<float[]>();

		public List<string> Paths = new List<string>();

		public float X;

		public float Y;

		public float Z;

		public float RX;

		public float RY;

		public float RZ;

		public float[] PoseFor(string path, int i)
		{
			int num = Paths.IndexOf(path);
			if (num >= 0 && num < Poses.Count)
			{
				return Poses[num];
			}
			if (Paths.Count != 0)
			{
				return null;
			}
			return PoseOf(i);
		}

		public float[] PoseOf(int i)
		{
			if (i >= Poses.Count)
			{
				if (i != 0 || Poses.Count != 0)
				{
					return null;
				}
				return new float[6] { X, Y, Z, RX, RY, RZ };
			}
			return Poses[i];
		}
	}
	[HarmonyPatch(typeof(ShipBuildModeManager))]
	internal static class BuildModePatches
	{
		[HarmonyPostfix]
		[HarmonyPatch("PlayerMeetsConditionsToBuild")]
		private static void Conditions(ref bool __result)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (!__result && CompanyDecor.AllowedHere())
			{
				PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
				if (!((Object)(object)val == (Object)null) && !val.isPlayerDead && !val.isTypingChat && !val.inSpecialInteractAnimation && !val.inTerminalMenu && !(Vector3.Distance(((Component)val).transform.position, StartOfRound.Instance.elevatorTransform.position) > 80f))
				{
					__result = true;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("PlaceShipObject")]
		private static void Placed(Vector3 placementPosition, PlaceableShipObject placeableObject)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			CompanyDecor.OnPlaced(placeableObject, placementPosition);
		}

		[HarmonyPostfix]
		[HarmonyPatch("StoreShipObjectClientRpc")]
		private static void Stored(int unlockableID)
		{
			CompanyDecor.OnStored(unlockableID);
		}
	}
	internal static class CompanyStorage
	{
		private static bool restoredThisVisit;

		private static float arrivedAt = -1f;

		private static float saveSnapshotGuard;

		private static float dropshipCheck;

		private static List<StoredItem> Snapshot()
		{
			//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_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: 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)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			List<StoredItem> list = new List<StoredItem>();
			GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
			foreach (GrabbableObject val in array)
			{
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val.itemProperties == (Object)null) && !val.isHeld && !val.isPocketed && !val.isInShipRoom && !val.isInElevator && !val.deactivated && !((Object)(object)((NetworkBehaviour)val).NetworkObject == (Object)null) && ((NetworkBehaviour)val).NetworkObject.IsSpawned)
				{
					Transform transform = ((Component)val).transform;
					Vector3 eulerAngles = transform.eulerAngles;
					list.Add(new StoredItem
					{
						Name = val.itemProperties.itemName,
						Value = val.scrapValue,
						X = transform.position.x,
						Y = transform.position.y,
						Z = transform.position.z,
						RX = eulerAngles.x,
						RY = eulerAngles.y,
						RZ = eulerAngles.z,
						Charge = ((val.insertedBattery != null) ? val.insertedBattery.charge : (-1f))
					});
				}
			}
			return list;
		}

		public static void BeforeDespawn()
		{
			if (Net.IsHost && Research.AtCompany)
			{
				Store.S.StoredItems = Snapshot();
				restoredThisVisit = false;
				Plugin.Log.LogInfo((object)$"Company storage: {Store.S.StoredItems.Count} items left at the Company are kept");
				Store.Save();
			}
		}

		public static void OnGameSaved()
		{
			if (Net.IsHost && Research.AtCompany && restoredThisVisit && !(Time.time < saveSnapshotGuard))
			{
				saveSnapshotGuard = Time.time + 1f;
				Store.S.StoredItems = Snapshot();
				Store.Save();
			}
		}

		public static void Tick(bool atBase)
		{
			if (!atBase)
			{
				restoredThisVisit = false;
				arrivedAt = -1f;
			}
			else
			{
				if (!Net.IsHost)
				{
					return;
				}
				StartOfRound instance = StartOfRound.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					return;
				}
				if (!restoredThisVisit)
				{
					if (arrivedAt < 0f)
					{
						arrivedAt = Time.time;
					}
					if (Time.time - arrivedAt > 1.5f)
					{
						restoredThisVisit = true;
						Restore();
					}
				}
				if (instance.shipHasLanded)
				{
					OpenDropship();
				}
			}
		}

		private static void Restore()
		{
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			List<StoredItem> storedItems = Store.S.StoredItems;
			if (storedItems.Count == 0)
			{
				return;
			}
			List<Item> itemsList = StartOfRound.Instance.allItemsList.itemsList;
			List<NetworkObjectReference> list = new List<NetworkObjectReference>();
			List<int> list2 = new List<int>();
			int num = 0;
			foreach (StoredItem s in storedItems)
			{
				Item val = ((IEnumerable<Item>)itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => (Object)(object)i != (Object)null && i.itemName == s.Name));
				if ((Object)(object)val?.spawnPrefab == (Object)null)
				{
					Plugin.Log.LogWarning((object)("Company storage: no item called " + s.Name + " any more; skipped"));
					continue;
				}
				GameObject obj = Object.Instantiate<GameObject>(val.spawnPrefab, new Vector3(s.X, s.Y + 0.1f, s.Z), Quaternion.Euler(s.RX, s.RY, s.RZ), RoundManager.Instance.spawnedScrapContainer);
				GrabbableObject component = obj.GetComponent<GrabbableObject>();
				component.fallTime = 0f;
				NetworkObject component2 = obj.GetComponent<NetworkObject>();
				component2.Spawn(false);
				if (val.isScrap)
				{
					component.SetScrapValue(s.Value);
					list.Add(NetworkObjectReference.op_Implicit(component2));
					list2.Add(s.Value);
				}
				if (s.Charge >= 0f && component.insertedBattery != null)
				{
					component.insertedBattery.charge = s.Charge;
					component.SyncBatteryServerRpc((int)(s.Charge * 100f));
				}
				num++;
			}
			if (list.Count > 0)
			{
				RoundManager.Instance.SyncScrapValuesClientRpc(list.ToArray(), list2.ToArray());
			}
			storedItems.Clear();
			Store.Save();
			Plugin.Log.LogInfo((object)$"Company storage: put back {num} items");
		}

		private static void OpenDropship()
		{
			if (!(Time.time < dropshipCheck))
			{
				dropshipCheck = Time.time + 0.5f;
				ItemDropship val = Object.FindObjectOfType<ItemDropship>();
				if (!((Object)(object)val == (Object)null) && val.shipLanded && !val.shipDoorsOpened && !val.deliveringVehicle)
				{
					Plugin.Log.LogInfo((object)"Company: opening the drop ship");
					val.TryOpeningShip();
				}
			}
		}

		public static void OnFired()
		{
			if (!Plugin.Config2.KeepScrap.Value)
			{
				Store.S.StoredItems.Clear();
			}
		}
	}
	internal class StoredItem
	{
		public string Name;

		public int Value;

		public float X;

		public float Y;

		public float Z;

		public float RX;

		public float RY;

		public float RZ;

		public float Charge = -1f;
	}
	[HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")]
	internal static class StorageDespawnPatch
	{
		private static void Prefix()
		{
			CompanyStorage.BeforeDespawn();
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "SaveGame")]
	internal static class StorageSavePatch
	{
		private static void Prefix()
		{
			CompanyStorage.OnGameSaved();
		}
	}
	[HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")]
	internal static class DebugCommands
	{
		private static readonly (string, int)[] TestVanilla = new(string, int)[14]
		{
			("Shovel", 3),
			("Shotgun", 2),
			("Ammo", 4),
			("Stun grenade", 2),
			("Lockpicker", 1),
			("Zap gun", 1),
			("Flashlight", 1),
			("Pro-flashlight", 1),
			("Jetpack", 1),
			("Walkie-talkie", 1),
			("Radar-booster", 1),
			("Kitchen knife", 1),
			("V-type engine", 1),
			("Large axle", 1)
		};

		private static int spawnSlot;

		private static string[] TestScrap => (from g in Catalog.Gear
			where g.Id != "robot"
			select g.Items.FirstOrDefault() into i
			where i != null
			select i).Distinct().ToArray();

		private static void Prefix(HUDManager __instance)
		{
			if (!Plugin.Config2.DebugCommands.Value || (Object)(object)__instance?.chatTextField == (Object)null)
			{
				return;
			}
			string text = __instance.chatTextField.text?.Trim() ?? "";
			if (text.ToLowerInvariant().StartsWith("crd") || text.ToLowerInvariant().StartsWith("/crd"))
			{
				__instance.chatTextField.text = "";
				Run((from a in text.TrimStart('/').Split(' ')
					where a != ""
					select a).Skip(1).ToArray());
			}
		}

		private static void Say(string msg)
		{
			HUDManager instance = HUDManager.Instance;
			if (instance != null)
			{
				instance.DisplayTip("CRD debug", msg, false, false, "");
			}
		}

		private static void Run(string[] a)
		{
			//IL_0053: 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_0b23: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b28: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b69: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b3a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b4d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0507: Unknown result type (might be due to invalid IL or missing references)
			//IL_0531: Unknown result type (might be due to invalid IL or missing references)
			//IL_0994: Unknown result type (might be due to invalid IL or missing references)
			//IL_09a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_09aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_09af: Unknown result type (might be due to invalid IL or missing references)
			//IL_09b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_09bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_09c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_09d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0739: Unknown result type (might be due to invalid IL or missing references)
			//IL_0769: Unknown result type (might be due to invalid IL or missing references)
			//IL_076e: Unknown result type (might be due to invalid IL or missing references)
			string text = ((a.Length != 0) ? a[0].ToLowerInvariant() : "help");
			if (text == "where")
			{
				PlayerControllerB val = StartOfRound.Instance?.localPlayerController;
				for (int i = 0; i < Stations.All.Count; i++)
				{
					float num = (((Object)(object)val != (Object)null) ? Vector3.Distance(((Component)val).transform.position, Stations.All[i].Root.transform.position) : (-1f));
					string arg = Stations.Describe(i);
					Plugin.Log.LogInfo((object)$"crd where: station {i} {num:0.0} m away, {arg}");
					Say($"Station {i}: {num:0.0} m away. Details are in the log.");
				}
				if (Stations.All.Count == 0)
				{
					Say("No stations spawned (are you landed at the Company?).");
				}
				return;
			}
			if (text != "help" && !Net.IsHost)
			{
				Say("Only the host can run debug commands.");
				return;
			}
			switch (text)
			{
			case "test":
				TestKit();
				GoToCompany();
				break;
			case "scrap":
				SpawnTestScrap();
				break;
			case "brokenbot":
			{
				int result;
				int count = ((a.Length <= 1 || !int.TryParse(a[1], out result)) ? 1 : Mathf.Clamp(result, 1, 20));
				SpawnInShip("Broken robot", count);
				break;
			}
			case "company":
				GoToCompany();
				break;
			case "finish":
			{
				int num5 = 0;
				foreach (Robot robot in Store.S.Robots)
				{
					if (robot.Current != null)
					{
						robot.Current.FinishQuota = -1;
						num5++;
					}
				}
				Say((num5 == 0) ? "No research in progress." : $"Finishing {num5} project(s) now.");
				Research.Tick();
				break;
			}
			case "credits":
			{
				Terminal val2 = Object.FindObjectOfType<Terminal>();
				if ((Object)(object)val2 != (Object)null && a.Length > 1 && int.TryParse(a[1], out var result2))
				{
					val2.groupCredits = result2;
					val2.SyncGroupCreditsClientRpc(result2, val2.numberOfItemsInDropship);
					Say($"Credits set to {result2}.");
				}
				else
				{
					Say("Usage: crd credits 1000");
				}
				break;
			}
			case "here":
			{
				int result7;
				int num6 = ((a.Length > 1 && int.TryParse(a[1], out result7)) ? result7 : 0);
				PlayerControllerB val6 = StartOfRound.Instance?.localPlayerController;
				if ((Object)(object)val6 == (Object)null || num6 < 0 || num6 >= Store.S.Robots.Count)
				{
					Say("Usage: crd here [station number]");
					break;
				}
				Vector3 position2 = ((Component)val6).transform.position;
				float y = ((Component)val6).transform.eulerAngles.y;
				Request request = new Request();
				request.Type = "move";
				request.Robot = num6;
				request.Pos = new float[4] { position2.x, position2.y, position2.z, y };
				Net.Send(request);
				Plugin.Log.LogInfo((object)$"crd here: station {num6} -> {position2}, yaw {y:0}");
				Say($"Station {num6} moved to where you're standing.");
				break;
			}
			case "paint":
			{
				if (a.Length < 2)
				{
					Say("Colours: " + string.Join(", ", Stations.PaletteNames));
					break;
				}
				int result3;
				int num4 = ((a.Length > 2 && int.TryParse(a[2], out result3)) ? result3 : 0);
				if (num4 < 0 || num4 >= Store.S.Robots.Count || !Stations.PaletteNames.Contains(a[1].ToLowerInvariant()))
				{
					Say("Usage: crd paint rainbow [station]");
					break;
				}
				Store.S.Robots[num4].Palette = a[1].ToLowerInvariant();
				Store.Save();
				Net.BroadcastState();
				Say($"Station {num4} is now {a[1]}.");
				break;
			}
			case "lineup":
			{
				int num2 = 0;
				foreach (string item in Stations.PalettesNewestFirst.ToList())
				{
					Store.S.Robots.Add(new Robot
					{
						Name = Names.Random(),
						Palette = item
					});
					num2++;
				}
				Store.Save();
				Net.BroadcastState();
				Say($"Added {num2} robots, one in each colour ({Store.S.Robots.Count} now).");
				break;
			}
			case "turn":
			{
				GrabbableObject currentlyHeldObjectServer = StartOfRound.Instance.localPlayerController.currentlyHeldObjectServer;
				Transform val3 = (((Object)(object)currentlyHeldObjectServer != (Object)null) ? ((Component)currentlyHeldObjectServer).transform.Find("Look") : null);
				if ((Object)(object)val3 == (Object)null || a.Length < 4 || !float.TryParse(a[1], out var result4) || !float.TryParse(a[2], out var result5) || !float.TryParse(a[3], out var result6))
				{
					Say("Hold a gear item, then: crd turn <x> <y> <z> (degrees), e.g. crd turn 90 0 0");
					break;
				}
				(val3.Find("Turn") ?? val3).localRotation = Quaternion.Euler(result4, result5, result6);
				if (currentlyHeldObjectServer is GearItem { GearId: "smg" })
				{
					UsableItems.TurretTurn = new Vector3(result4, result5, result6);
				}
				Say($"Turned to {result4} {result5} {result6}.");
				TestLog.Log("MODEL", $"turn item=\"{currentlyHeldObjectServer.itemProperties.itemName}\" euler=({result4},{result5},{result6})");
				break;
			}
			case "limited":
				Store.S.DebugUnlimited = false;
				Store.Save();
				Net.BroadcastState();
				Say("Gear uses count down again.");
				break;
			case "enemy":
			{
				string want = string.Join(" ", a.Skip(1)).Trim().ToLowerInvariant();
				List<EnemyType> source = (from s in StartOfRound.Instance.levels.SelectMany((SelectableLevel l) => (l.Enemies ?? new List<SpawnableEnemyWithRarity>()).Concat(l.OutsideEnemies ?? new List<SpawnableEnemyWithRarity>()).Concat(l.DaytimeEnemies ?? new List<SpawnableEnemyWithRarity>()))
					select s?.enemyType into t
					where (Object)(object)t != (Object)null && (Object)(object)t.enemyPrefab != (Object)null
					group t by t.enemyName into g
					select g.First()).ToList();
				EnemyType val4 = ((want == "") ? null : (((IEnumerable<EnemyType>)source).FirstOrDefault((Func<EnemyType, bool>)((EnemyType t) => t.enemyName.ToLowerInvariant() == want)) ?? ((IEnumerable<EnemyType>)source).FirstOrDefault((Func<EnemyType, bool>)((EnemyType t) => t.enemyName.ToLowerInvariant().Contains(want)))));
				if ((Object)(object)val4 == (Object)null)
				{
					Say("crd enemy <name>: " + string.Join(", ", source.Select((EnemyType t) => t.enemyName)));
					break;
				}
				PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
				Vector3 val5 = ((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 4f;
				RoundManager.Instance.SpawnEnemyGameObject(val5, ((Component)localPlayerController).transform.eulerAngles.y + 180f, -1, val4);
				Say("Spawned a " + val4.enemyName + ".");
				break;
			}
			case "unlock":
				foreach (GearDef item2 in Catalog.Gear.Where((GearDef x) => x.Id != "robot"))
				{
					Store.S.Progress(item2.Id).Unlocked = true;
				}
				Store.Save();
				Net.BroadcastState();
				Say("Every piece of gear is unlocked.");
				break;
			case "gear":
			{
				string text2 = ((a.Length > 1) ? a[1].ToLowerInvariant() : "");
				GearDef gearDef = Catalog.Get(text2);
				if (gearDef == null || (!UsableItems.IsItemGear(text2) && gearDef.SpawnItem == null))
				{
					Say("Gear items: " + string.Join(", ", from x in Catalog.Gear
						where UsableItems.IsItemGear(x.Id) || x.SpawnItem != null
						select x.Id));
					break;
				}
				Vector3 position = ((Component)StartOfRound.Instance.localPlayerController).transform.position;
				if (gearDef.SpawnItem != null)
				{
					UsableItems.SpawnByName(gearDef.SpawnItem, position);
					for (int num3 = 0; num3 < gearDef.SpawnExtraCount; num3++)
					{
						UsableItems.SpawnByName(gearDef.SpawnExtra, position);
					}
				}
				else
				{
					UsableItems.SpawnFor(text2, position);
				}
				Say("Here's a " + Catalog.Get(text2)?.Name + ".");
				break;
			}
			case "robot":
				Store.S.Robots.Add(new Robot
				{
					Name = Names.Random(),
					Palette = (Stations.PaletteNames.Skip(Random.Range(0, Mathf.Max(1, Stations.PaletteNames.Count()))).FirstOrDefault() ?? "factory")
				});
				Store.Save();
				Net.BroadcastState();
				Say($"Added a robot ({Store.S.Robots.Count} now).");
				break;
			default:
				Say("crd test = test scrap into the ship + fly to the Company and land\ncrd scrap | crd company | crd finish (finish all research now)\ncrd brokenbot [n] (broken robot scrap in the ship)\ncrd turn <x> <y> <z> (turn the held gear's model) | crd enemy <name> (spawn a creature to test on) | crd limited (uses count again)\ncrd unlock (unlock all gear) | crd gear <id> (e.g. recall, lidar, arc, frag)\ncrd credits <n> | crd robot (add a robot) | crd where (find the robots) | crd here (move station 0 to you) | crd paint <colour> | crd lineup (one robot per colour)");
				break;
			}
		}

		private static void TestKit()
		{
			foreach (GearDef item in Catalog.Gear.Where((GearDef x) => x.Id != "robot" && x.Vanilla == null))
			{
				Store.S.Progress(item.Id).Unlocked = true;
			}
			Store.Save();
			Net.BroadcastState();
			Terminal val = Object.FindObjectOfType<Terminal>();
			if ((Object)(object)val != (Object)null)
			{
				val.groupCredits = Mathf.Max(val.groupCredits, 5000);
				val.SyncGroupCreditsClientRpc(val.groupCredits, val.numberOfItemsInDropship);
			}
			SpawnTestGear();
			(string, int)[] testVanilla = TestVanilla;
			for (int num = 0; num < testVanilla.Length; num++)
			{
				var (itemName, count) = testVanilla[num];
				SpawnInShip(itemName, count, quiet: true);
			}
			PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
			if ((Object)(object)localPlayerController != (Object)null)
			{
				List<ActiveEffect> list = Store.S.EffectsOf(Effects.PlayerKey(localPlayerController));
				list.RemoveAll((ActiveEffect e) => e.GearId == "exo");
				list.Add(new ActiveEffect
				{
					GearId = "exo",
					Level = Mathf.Max(1, Store.S.Progress("exo").EffectLevel),
					Permanent = true
				});
				Store.Save();
				Net.BroadcastState();
			}
			Say("Test kit: all gear unlocked, 5000 credits, every gear item and weapon (unlimited uses), the vanilla gear to test, and the Hoarding Exoskeleton on. Flying to the Company.");
			TestLog.Log("DEBUG", "crd test kit spawned");
		}

		private static void SpawnTestScrap()
		{
			string[] testScrap = TestScrap;
			for (int i = 0; i < testScrap.Length; i++)
			{
				SpawnInShip(testScrap[i], 1);
			}
		}

		private static void SpawnTestGear()
		{
			Store.S.DebugUnlimited = true;
			Store.Save();
			Net.BroadcastState();
			foreach (GearDef item in Catalog.Gear.Where((GearDef x) => UsableItems.IsItemGear(x.Id)))
			{
				foreach (NetworkObject item2 in SpawnInShip(item.Name, 1, quiet: true))
				{
					Net.NoticeAllRaw(new Reply
					{
						Type = "uses",
						NetId = item2.NetworkObjectId,
						Slot = int.MaxValue
					});
				}
			}
			foreach (GearDef item3 in Catalog.Gear.Where((GearDef x) => x.SpawnItem != null))
			{
				SpawnInShip(item3.SpawnItem, 1, quiet: true);
				if (item3.SpawnExtra != null)
				{
					SpawnInShip(item3.SpawnExtra, item3.SpawnExtraCount, quiet: true);
				}
			}
			Say("Spawned one of every gear item and weapon (usable gear with unlimited uses).");
		}

		private static List<NetworkObject> SpawnInShip(string itemName, int count, bool quiet = false)
		{
			//IL_00bb: 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_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: 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)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			List<NetworkObject> list = new List<NetworkObject>();
			StartOfRound instance = StartOfRound.Instance;
			Item val = instance?.allItemsList?.itemsList?.FirstOrDefault((Func<Item, bool>)((Item x) => (Object)(object)x != (Object)null && x.itemName == itemName));
			if ((Object)(object)val?.spawnPrefab == (Object)null)
			{
				Say("No item called " + itemName + ".");
				TestLog.Log("SPAWN", "missing item=\"" + itemName + "\"");
				return list;
			}
			List<NetworkObjectReference> list2 = new List<NetworkObjectReference>();
			List<int> list3 = new List<int>();
			for (int num = 0; num < count; num++)
			{
				Vector3 val2 = instance.elevatorTransform.position + instance.elevatorTransform.rotation * new Vector3(-2f + (float)(spawnSlot++ % 8) * 0.6f, 0.5f, -5f);
				GameObject obj = Object.Instantiate<GameObject>(val.spawnPrefab, val2, Quaternion.identity, instance.elevatorTransform);
				GrabbableObject component = obj.GetComponent<GrabbableObject>();
				component.fallTime = 0f;
				component.isInShipRoom = true;
				component.isInElevator = true;
				component.scrapPersistedThroughRounds = true;
				NetworkObject component2 = obj.GetComponent<NetworkObject>();
				component2.Spawn(false);
				int num2 = (int)((float)Random.Range(val.minValue, val.maxValue + 1) * 0.4f);
				component.SetScrapValue(num2);
				list2.Add(NetworkObjectReference.op_Implicit(component2));
				list3.Add(num2);
				list.Add(component2);
			}
			RoundManager.Instance.SyncScrapValuesClientRpc(list2.ToArray(), list3.ToArray());
			if (!quiet)
			{
				Say($"Spawned {count} {itemName} in the ship.");
			}
			foreach (NetworkObject item in list)
			{
				((MonoBehaviour)StartOfRound.Instance).StartCoroutine(LogWhereItLands(item, itemName));
			}
			return list;
		}

		private static IEnumerator LogWhereItLands(NetworkObject no, string itemName)
		{
			yield return (object)new WaitForSeconds(2f);
			if ((Object)(object)no == (Object)null)
			{
				TestLog.Log("SPAWN", "gone item=\"" + itemName + "\"");
				yield break;
			}
			StartOfRound instance = StartOfRound.Instance;
			Vector3 v = instance.elevatorTransform.InverseTransformPoint(((Component)no).transform.position);
			int num;
			if ((Object)(object)instance.shipInnerRoomBounds != (Object)null)
			{
				Bounds bounds = instance.shipInnerRoomBounds.bounds;
				num = (((Bounds)(ref bounds)).Contains(((Component)no).transform.position) ? 1 : 0);
			}
			else
			{
				num = 0;
			}
			bool flag = (byte)num != 0;
			GrabbableObject component = ((Component)no).GetComponent<GrabbableObject>();
			TestLog.Log("SPAWN", $"item=\"{itemName}\" ship_local={TestLog.P(v)} in_ship={flag} renderers_on={((component != null) ? ((Component)component).GetComponentsInChildren<Renderer>().Count((Renderer r) => r.enabled) : 0)}");
		}

		private static void GoToCompany()
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (!instance.inShipPhase)
			{
				Say("The ship has to be in orbit first.");
				return;
			}
			int num = Array.FindIndex(instance.levels, (SelectableLevel l) => l.sceneName == "CompanyBuilding");
			if (num < 0)
			{
				Say("Couldn't find the Company moon.");
				return;
			}
			Terminal val = Object.FindObjectOfType<Terminal>();
			if (instance.currentLevelID != num)
			{
				instance.ChangeLevelServerRpc(num, ((Object)(object)val != (Object)null) ? val.groupCredits : 0);
			}
			((MonoBehaviour)instance).StartCoroutine(LandWhenArrived());
		}

		private static IEnumerator LandWhenArrived()
		{
			StartOfRound sor = StartOfRound.Instance;
			float give = Time.time + 30f;
			yield return (object)new WaitForSeconds(1f);
			while (sor.travellingToNewLevel && Time.time < give)
			{
				yield return (object)new WaitForSeconds(0.5f);
			}
			yield return (object)new WaitForSeconds(1f);
			if (sor.inShipPhase)
			{
				sor.StartGameServerRpc();
				Say("Landing at the Company.");
			}
		}
	}
	internal static class Effects
	{
		public static float FeatherfallMult(int level)
		{
			if (level < 5)
			{
				return Mathf.Pow(0.6f, (float)level);
			}
			return 0f;
		}

		public static float PlatingMult(int level)
		{
			return Mathf.Pow(0.85f, (float)level);
		}

		public static string PlayerKey(PlayerControllerB p)
		{
			if (!((Object)(object)p == (Object)null))
			{
				if (p.playerSteamId == 0L)
				{
					return p.playerUsername;
				}
				return p.playerSteamId.ToString();
			}
			return null;
		}

		public static int LevelOf(PlayerControllerB p, string gearId)
		{
			string text = PlayerKey(p);
			if (text == null || !Store.S.Players.TryGetValue(text, out var value))
			{
				return 0;
			}
			return (from e in value
				where e.GearId == gearId
				select e.Level).DefaultIfEmpty(0).Max();
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "DamagePlayer")]
	internal static class DamagePatch
	{
		private static void Prefix(PlayerControllerB __instance, ref int damageNumber, bool fallDamage, CauseOfDeath causeOfDeath)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Invalid comparison between Unknown and I4
			if ((Object)(object)__instance != (Object)(object)GameNetworkManager.Instance?.localPlayerController)
			{
				return;
			}
			float num = 1f;
			if (fallDamage || (int)causeOfDeath == 2)
			{
				int num2 = Effects.LevelOf(__instance, "featherfall");
				if (num2 > 0)
				{
					num *= Effects.FeatherfallMult(num2);
				}
			}
			int num3 = Effects.LevelOf(__instance, "plating");
			if (num3 > 0)
			{
				num *= Effects.PlatingMult(num3);
			}
			if (num < 1f)
			{
				damageNumber = Mathf.Max(0, Mathf.RoundToInt((float)damageNumber * num));
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SetHoverTipAndCurrentInteractTrigger")]
	internal static class HoverTipPatch
	{
		private static void Postfix(PlayerControllerB __instance)
		{
			string hoverTip = Runner.HoverTip;
			if (hoverTip != null && !((Object)(object)__instance != (Object)(object)GameNetworkManager.Instance?.localPlayerController) && !((Object)(object)__instance.cursorTip == (Object)null))
			{
				((TMP_Text)__instance.cursorTip).text = hoverTip;
				if ((Object)(object)__instance.cursorIcon != (Object)null)
				{
					((Behaviour)__instance.cursorIcon).enabled = true;
					__instance.cursorIcon.sprite = __instance.grabItemIcon;
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "Start")]
	internal static class StartPatch
	{
		private static void Postfix()
		{
			if (Net.IsHost)
			{
				Store.Load();
			}
			else
			{
				Store.S = Store.NewState();
			}
			Net.Init();
			Runner.LogItemNamesOnce();
		}
	}
	[HarmonyPatch(typeof(DeleteFileButton), "DeleteFile")]
	internal static class DeleteSavePatch
	{
		private static void Postfix()
		{
			Store.CleanUpOrphans();
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "SaveGame")]
	internal static class SavePatch
	{
		private static void Postfix()
		{
			if (Net.IsHost)
			{
				Store.Save();
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "ShipHasLeft")]
	internal static class ShipLeftPatch
	{
		private static void Postfix()
		{
			Research.OnShipLeft(Research.AtCompany);
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "playersFiredGameOver")]
	internal static class FiredPatch
	{
		private static void Prefix()
		{
			Research.OnFired();
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "Update")]
	internal static class Exoskeleton
	{
		public static float Mult(int l)
		{
			return Mathf.Pow(0.85f, (float)l);
		}

		private static void Prefix(PlayerControllerB __instance, out (bool on, float real, float shown) __state)
		{
			__state = (on: false, real: 0f, shown: 0f);
			if (!((Object)(object)__instance == (Object)null) && ((NetworkBehaviour)__instance).IsOwner && !(__instance.carryWeight <= 1f))
			{
				int num = Effects.LevelOf(__instance, "exo");
				if (num > 0)
				{
					float carryWeight = __instance.carryWeight;
					float num2 = (__instance.carryWeight = 1f + (carryWeight - 1f) * Mult(num));
					TestLog.Log("EXO", $"lvl={num} real_weight={carryWeight:0.00} feels={num2:0.00}", 10f);
					__state = (on: true, real: carryWeight, shown: num2);
				}
			}
		}

		private static void Postfix(PlayerControllerB __instance, (bool on, float real, float shown) __state)
		{
			if (__state.on && !((Object)(object)__instance == (Object)null))
			{
				__instance.carryWeight = __state.real + (__instance.carryWeight - __state.shown);
			}
		}
	}
	internal static class FreezeRay
	{
		[HarmonyPatch(typeof(EnemyAI), "HitEnemyOnLocalClient")]
		internal static class ShatterPatch
		{
			private static void Prefix(EnemyAI __instance, ref int force)
			{
				if (IsFrozen(__instance) && force > 0)
				{
					TestLog.Log("FREEZE", $"shatter enemy={TestLog.E(__instance)} force={force}->{force * 2}");
					force *= 2;
				}
			}
		}

		public const float ChillFor = 6f;

		private static readonly Dictionary<ulong, (int hits, float until)> chill = new Dictionary<ulong, (int, float)>();

		private static readonly Dictionary<ulong, (int hits, float until)> chilled = new Dictionary<ulong, (int, float)>();

		private static readonly Dictionary<ulong, float> frozen = new Dictionary<ulong, float>();

		public static int HitsToFreeze(int lvl)
		{
			return Mathf.Max(2, 5 - lvl);
		}

		public static float FrozenSeconds(int lvl)
		{
			return 2f + (float)lvl;
		}

		public static bool IsFrozen(EnemyAI e)
		{
			if ((Object)(object)e != (Object)null && frozen.TryGetValue(((NetworkBehaviour)e).NetworkObjectId, out var value))
			{
				return Time.time < value;
			}
			return false;
		}

		public static void OnHostHit(EnemyAI e, int lvl)
		{
			ulong networkObjectId = ((NetworkBehaviour)e).NetworkObjectId;
			(int, float) value;
			int num = ((!chill.TryGetValue(networkObjectId, out value) || !(Time.time < value.Item2)) ? 1 : (value.Item1 + 1));
			if (num >= HitsToFreeze(lvl))
			{
				chill.Remove(networkObjectId);
				float num2 = FrozenSeconds(lvl);
				Weapons.StunAll(e, num2);
				Reply reply = new Reply();
				reply.Type = "frozen";
				reply.NetId = networkObjectId;
				reply.Pos = new float[4] { num2, 0f, 0f, 0f };
				Net.NoticeAllRaw(reply);
				TestLog.Log("FREEZE", $"frozen enemy={TestLog.E(e)} seconds={num2:0} after_hits={num}");
			}
			else
			{
				chill[networkObjectId] = (num, Time.time + 6f);
				TestLog.Log("FREEZE", $"chill enemy={TestLog.E(e)} hits={num}/{HitsToFreeze(lvl)}");
				Reply reply = new Reply();
				reply.Type = "chill";
				reply.NetId = networkObjectId;
				reply.Slot = num;
				reply.Pos = new float[4]
				{
					HitsToFreeze(lvl),
					0f,
					0f,
					0f
				};
				Net.NoticeAllRaw(reply);
			}
		}

		public static void Chill(ulong id, int hits, float needed)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(id, out var value))
			{
				return;
			}
			EnemyAI component = ((Component)value).GetComponent<EnemyAI>();
			if (!((Object)(object)component == (Object)null))
			{
				bool num = chilled.ContainsKey(id) && Time.time < chilled[id].until;
				chilled[id] = (hits, Time.time + 6f);
				float num2 = Mathf.Clamp01((float)hits / Mathf.Max(1f, needed));
				Frost(component, 0.6f + num2, 6f, new Color(0.55f, 0.85f, 1f));
				Blue(component, 0.25f + 0.5f * num2);
				if (!num)
				{
					((MonoBehaviour)StartOfRound.Instance).StartCoroutine(SlowWhileChilled(component, id));
				}
			}
		}

		public static void Freeze(ulong id, float seconds)
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			frozen[id] = Time.time + seconds;
			chilled.Remove(id);
			if (NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(id, out var value))
			{
				EnemyAI component = ((Component)value).GetComponent<EnemyAI>();
				if (component != null)
				{
					Frost(component, 2.2f, seconds, new Color(0.75f, 0.95f, 1f));
					Blue(component, 1f);
					((MonoBehaviour)StartOfRound.Instance).StartCoroutine(UnblueAfter(component, id, seconds));
				}
			}
		}

		private static IEnumerator SlowWhileChilled(EnemyAI e, ulong id)
		{
			float baseSpeed = -1f;
			(int, float) value;
			while ((Object)(object)e != (Object)null && !e.isEnemyDead && chilled.TryGetValue(id, out value) && Time.time < value.Item2)
			{
				if (((NetworkBehaviour)e).IsOwner && (Object)(object)e.agent != (Object)null)
				{
					if (baseSpeed < 0f)
					{
						baseSpeed = e.agent.speed;
					}
					e.agent.speed = Mathf.Min(e.agent.speed, Mathf.Max(0.5f, baseSpeed * (1f - 0.2f * (float)value.Item1)));
					TestLog.Log("FREEZE", $"slowing enemy={TestLog.E(e)} speed={e.agent.speed:0.0} base={baseSpeed:0.0}", 2f, "slow" + id);
				}
				yield return null;
			}
			chilled.Remove(id);
			if ((Object)(object)e != (Object)null && !IsFrozen(e))
			{
				Blue(e, 0f);
			}
		}

		private static IEnumerator UnblueAfter(EnemyAI e, ulong id, float seconds)
		{
			yield return (object)new WaitForSeconds(seconds);
			if ((Object)(object)e != (Object)null && !IsFrozen(e) && !chilled.ContainsKey(id))
			{
				Blue(e, 0f);
			}
		}

		private static void Blue(EnemyAI e, float amount)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: 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_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)e == (Object)null)
			{
				return;
			}
			Color val = default(Color);
			((Color)(ref val))..ctor(0.45f, 0.75f, 1f);
			Renderer[] componentsInChildren = ((Component)e).GetComponentsInChildren<Renderer>();
			foreach (Renderer val2 in componentsInChildren)
			{
				if ((Object)(object)val2 == (Object)null || (!(val2 is MeshRenderer) && !(val2 is SkinnedMeshRenderer)))
				{
					continue;
				}
				if (amount <= 0f)
				{
					val2.SetPropertyBlock((MaterialPropertyBlock)null);
					continue;
				}
				Material sharedMaterial = val2.sharedMaterial;
				if (!((Object)(object)sharedMaterial == (Object)null))
				{
					MaterialPropertyBlock val3 = new MaterialPropertyBlock();
					if (sharedMaterial.HasProperty("_BaseColor"))
					{
						val3.SetColor("_BaseColor", Color.Lerp(sharedMaterial.GetColor("_BaseColor"), val, amount));
					}
					if (sharedMaterial.HasProperty("_EmissiveColor"))
					{
						val3.SetColor("_EmissiveColor", val * (0.6f * amount));
					}
					val2.SetPropertyBlock(val3);
				}
			}
		}

		private static void Frost(EnemyAI e, float amount, float seconds, Color col)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: 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_0094: 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)
			Material val = Lidar.Glow(col);
			if (!((Object)(object)val == (Object)null))
			{
				Transform val2 = ((Component)e).transform.Find("CompanyRnD.Frost");
				if ((Object)(object)val2 != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)val2).gameObject);
				}
				GameObject val3 = new GameObject("CompanyRnD.Frost");
				val3.transform.SetParent(((Component)e).transform, false);
				List<Vector3> list = new List<Vector3>();
				int num = Mathf.RoundToInt(20f * amount);
				for (int i = 0; i < num; i++)
				{
					Vector2 val4 = Random.insideUnitCircle * 0.7f;
					list.Add(new Vector3(val4.x, Random.Range(0.1f, 1.6f), val4.y));
				}
				Mesh val5 = Lidar.Dots(list, 0.035f);
				val3.AddComponent<MeshFilter>().sharedMesh = val5;
				MeshRenderer obj = val3.AddComponent<MeshRenderer>();
				((Renderer)obj).sharedMaterial = val;
				((Renderer)obj).shadowCastingMode = (ShadowCastingMode)0;
				Object.Destroy((Object)(object)val3, seconds);
				Object.Destroy((Object)(object)val5, seconds + 0.1f);
			}
		}
	}
	internal static class GearEffects
	{
		private static readonly Dictionary<PlayerControllerB, Light> lamps = new Dictionary<PlayerControllerB, Light>();

		public static readonly HashSet<ulong> LampOff = new HashSet<ulong>();

		private static readonly Dictionary<Object, float> fogOriginal = new Dictionary<Object, float>();

		private static float fogTimer;

		private static int fogApplied;

		private static float lastSink = -1f;

		private static float lastAir = -1f;

		private static PlayerControllerB Local => GameNetworkManager.Instance?.localPlayerController;

		public static float HushedMult(int l)
		{
			return Mathf.Pow(0.75f, (float)l);
		}

		public static float LowProfileMult(int l)
		{
			return Mathf.Pow(0.8f, (float)l);
		}

		public static float FogMult(int l)
		{
			return 1f + 1.5f * (float)l;
		}

		public static float FloatMult(int l)
		{
			return Mathf.Pow(0.6f, (float)l);
		}

		public static void Tick()
		{
			Headlamps();
			Wayfinder.Update();
			FogVision();
			FloatVest();
		}

		public static void ToggleLamp(PlayerControllerB me)
		{
			bool flag = !LampOff.Contains(me.playerClientId);
			Net.Send(new Request
			{
				Type = "lamp",
				Slot = (int)me.playerClientId,
				Value = ((!flag) ? 1 : 0)
			});
			TestLog.Log("HEADLAMP", $"toggle on={!flag}");
		}

		public static void SetLamp(ulong clientId, bool on)
		{
			if (on)
			{
				LampOff.Remove(clientId);
			}
			else
			{
				LampOff.Add(clientId);
			}
		}

		private static void Headlamps()
		{
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB[] array = StartOfRound.Instance?.allPlayerScripts;
			if (array == null)
			{
				return;
			}
			PlayerControllerB[] array2 = array;
			foreach (PlayerControllerB val in array2)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				int num = ((val.isPlayerControlled && !val.isPlayerDead) ? Effects.LevelOf(val, "headlamp") : 0);
				lamps.TryGetValue(val, out var value);
				if (num <= 0 || LampOff.Contains(val.playerClientId))
				{
					if ((Object)(object)value != (Object)null)
					{
						((Behaviour)value).enabled = false;
					}
					continue;
				}
				if ((Object)(object)value == (Object)null)
				{
					Light val2 = ((val.allHelmetLights != null && val.allHelmetLights.Length != 0) ? val.allHelmetLights[0] : val.helmetLight);
					if ((Object)(object)val2 == (Object)null || (Object)(object)val.gameplayCamera == (Object)null)
					{
						continue;
					}
					value = Object.Instantiate<GameObject>(((Component)val2).gameObject, ((Component)val.gameplayCamera).transform).GetComponent<Light>();
					((Object)value).name = "CompanyRnD.Headlamp";
					((Component)value).transform.localPosition = new Vector3(0f, 0.15f, 0.1f);
					((Component)value).transform.localRotation = Quaternion.identity;
					lamps[val] = value;
					((Component)value).gameObject.SetActive(true);
				}
				((Behaviour)value).enabled = true;
				value.range = 14f + 5f * (float)num;
				value.spotAngle = Mathf.Min(90f, 55f + 8f * (float)num);
			}
		}

		private static void FogVision()
		{
			PlayerControllerB local = Local;
			int num = (((Object)(object)local != (Object)null && !local.isPlayerDead && !Research.AtCompany) ? Effects.LevelOf(local, "fogvision") : 0);
			if ((fogTimer -= Time.deltaTime) > 0f && num == fogApplied)
			{
				return;
			}
			fogTimer = 2f;
			if (num == 0)
			{
				RestoreFog();
				fogApplied = 0;
				return;
			}
			float num2 = FogMult(num);
			LocalVolumetricFog[] array = Object.FindObjectsOfType<LocalVolumetricFog>();
			foreach (LocalVolumetricFog val in array)
			{
				if (!fogOriginal.ContainsKey((Object)(object)val))
				{
					fogOriginal[(Object)(object)val] = val.parameters.meanFreePath;
				}
				val.parameters.meanFreePath = fogOriginal[(Object)(object)val] * num2;
			}
			Volume[] array2 = Object.FindObjectsOfType<Volume>();
			Fog val3 = default(Fog);
			foreach (Volume val2 in array2)
			{
				if (!((Object)(object)val2.sharedProfile == (Object)null) && val2.sharedProfile.TryGet<Fog>(ref val3))
				{
					if (!fogOriginal.ContainsKey((Object)(object)val3))
					{
						fogOriginal[(Object)(object)val3] = ((VolumeParameter<float>)(object)val3.meanFreePath).value;
					}
					((VolumeParameter<float>)(object)val3.meanFreePath).value = fogOriginal[(Object)(object)val3] * num2;
				}
			}
			fogApplied = num;
		}

		private static void RestoreFog()
		{
			foreach (KeyValuePair<Object, float> item in fogOriginal)
			{
				Object key = item.Key;
				LocalVolumetricFog val = (LocalVolumetricFog)(object)((key is LocalVolumetricFog) ? key : null);
				if (val != null && (Object)(object)val != (Object)null)
				{
					val.parameters.meanFreePath = item.Value;
					continue;
				}
				Object key2 = item.Key;
				Fog val2 = (Fog)(object)((key2 is Fog) ? key2 : null);
				if (val2 != null && (Object)(object)val2 != (Object)null)
				{
					((VolumeParameter<float>)(object)val2.meanFreePath).value = item.Value;
				}
			}
			fogOriginal.Clear();
		}

		private static void FloatVest()
		{
			PlayerControllerB local = Local;
			if ((Object)(object)local == (Object)null || loc