Decompiled source of Bobbymoes Weapon Pack v0.1.0

plugins/com.github.Bobbymoe.BWP.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using FMOD;
using FMOD.Studio;
using FMODUnity;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mirror;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Localization.Components;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("GameAssembly")]
[assembly: IgnoresAccessChecksTo("SharedAssembly")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("com.github.Bobbymoe.BWP")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+13528c82fdd5fb33e276eb91003055b1b614cc50")]
[assembly: AssemblyProduct("com.github.Bobbymoe.BWP")]
[assembly: AssemblyTitle("Bobbymoe's Weapon Pack")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BepInEx
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	[Embedded]
	internal sealed class BepInAutoPluginAttribute : Attribute
	{
		public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace BepInEx.Preloader.Core.Patching
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	[Embedded]
	internal sealed class PatcherAutoPluginAttribute : Attribute
	{
		public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace MyMod
{
	internal sealed class CustomItem
	{
		public ItemType Id;

		public string DisplayName = "";

		public ItemType BaseItem;

		public EquipmentType HeldEquipment;

		public string AssetFolder = "";

		public string FileName = "";

		public uint PickupAssetId;

		public Color? TintColor;

		public float[] StartingChances = new float[6];

		public int DefaultUses = 1;

		public string UseSoundLabel = "Use";

		public ConfigEntry<int> Uses;

		public ConfigEntry<string> ModelFile;

		public ConfigEntry<string> TextureFile;

		public ConfigEntry<string> ModelRotation;

		public ConfigEntry<string> ModelOffset;

		public ConfigEntry<float> ModelScale;

		public ConfigEntry<bool> TintModel;

		public ConfigEntry<string> IconFile;

		public ConfigEntry<float>[] ItemBoxChances;

		public ItemData? Data;

		public Sprite? BaseIcon;

		public CustomItemModel Model;

		public CustomItemPickup Pickup;

		public CustomItemSound AimSound;

		public CustomItemSound UseSound;

		public bool HasAimSound
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Invalid comparison between Unknown and I4
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Invalid comparison between Unknown and I4
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Invalid comparison between Unknown and I4
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Invalid comparison between Unknown and I4
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Invalid comparison between Unknown and I4
				ItemType baseItem = BaseItem;
				if ((int)baseItem <= 7)
				{
					if (baseItem - 2 <= 1 || (int)baseItem == 7)
					{
						goto IL_0021;
					}
				}
				else if ((int)baseItem == 12 || (int)baseItem == 14)
				{
					goto IL_0021;
				}
				return false;
				IL_0021:
				return true;
			}
		}

		public string NameKey => "ITEM_" + (int)Id;

		public override string ToString()
		{
			return DisplayName;
		}

		public void Bind(ConfigFile config)
		{
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Expected O, but got Unknown
			string text = ((object)Unsafe.As<ItemType, ItemType>(ref BaseItem)/*cast due to .constrained prefix*/).ToString();
			string text2 = DisplayName + " Model";
			string text3 = AssetFolder + "/";
			Uses = config.Bind<int>(DisplayName, "Uses", DefaultUses, "How many uses a " + DisplayName + " has. Takes effect the next time the game starts.");
			ModelFile = config.Bind<string>(text2, "ModelFile", text3 + FileName + ".obj", "The " + DisplayName + "'s 3D model, relative to BepInEx\\plugins. The extension doesn't matter: the mod looks for this name as .glb, .gltf and .obj and uses the newest one. If none exists, the " + DisplayName + " looks like a " + (TintColor.HasValue ? "tinted " : "") + text + ".");
			TextureFile = config.Bind<string>(text2, "TextureFile", text3 + FileName + ".png", "Texture (.png or .jpg) for an .obj model, relative to BepInEx\\plugins. Only .obj models use this (a .glb/.gltf brings its own textures). Optional: without it the .obj model is one plain color.");
			ModelRotation = config.Bind<string>(text2, "RotationDegrees", "0, 0, 0", "Extra rotation for the model in degrees (x, y, z). The model is lined up with the " + text + " automatically (longest side along its longest side, second-longest along its second-longest), so this is usually 0, 0, 0. Try 0, 180, 0 if it points backwards, or 0, 0, 180 if it's upside down.");
			ModelOffset = config.Bind<string>(text2, "PositionOffset", "0, 0, 0", "Extra position offset for the model (x, y, z), after it's centered on the " + text + ". Small numbers like 0.02 go a long way.");
			ModelScale = config.Bind<float>(text2, "Scale", 1f, "Size multiplier. 1 = the same length as the " + text + ".");
			TintModel = config.Bind<bool>(text2, "TintModel", false, "Tint the custom model with the item's color. Off = the model keeps its own colors and textures.");
			IconFile = config.Bind<string>(text2, "IconFile", text3 + FileName + "_icon.png", "Hotbar icon image (.png or .jpg), relative to BepInEx\\plugins. Best: square, transparent background, 128x128 to 256x256. If the file doesn't exist, the " + text + "'s icon is used" + (TintColor.HasValue ? ", tinted" : "") + ".");
			(string, string)[] array = new(string, string)[6]
			{
				("AheadOfOwnBallPercent", "the \"ahead of your own ball\" tab (players who ran ahead of their ball)"),
				("LeaderPercent", "the first distance tab (\"In the lead\": the leader and players close to them)"),
				("BehindPercent", "the second distance tab (behind 50m)"),
				("FurtherBehindPercent", "the third distance tab (behind 125m)"),
				("FarBehindPercent", "the fourth distance tab (behind 200m)"),
				("MobilityBoxesPercent", "the mobility item boxes tab")
			};
			ItemBoxChances = new ConfigEntry<float>[array.Length];
			for (int i = 0; i < array.Length; i++)
			{
				ItemBoxChances[i] = config.Bind<float>(DisplayName + " Item Boxes", array[i].Item1, (i < StartingChances.Length) ? StartingChances[i] : 0f, new ConfigDescription("Starting chance (in %) of a " + DisplayName + " in " + array[i].Item2 + ". This is the \"Classic\" value of its slider on that tab of the match setup odds menu; the host can change it there. Takes effect the next time the game starts. Every player should use the same values, so the menus match.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 95f), Array.Empty<object>()));
			}
			AimSound = new CustomItemSound(this, config, "Aim", "when the player starts aiming it", 2f, 30f);
			UseSound = new CustomItemSound(this, config, UseSoundLabel, "when it's used (" + UseSoundLabel.ToLowerInvariant() + ")", 8f, 120f);
			Model = new CustomItemModel(this);
			Pickup = new CustomItemPickup(this);
		}
	}
	internal static class CustomItems
	{
		private static readonly List<CustomItem> all = new List<CustomItem>();

		private static readonly Dictionary<ItemType, CustomItem> byId = new Dictionary<ItemType, CustomItem>();

		internal static IReadOnlyList<CustomItem> All => all;

		internal static int HighestId
		{
			get
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Expected I4, but got Unknown
				int num = 0;
				foreach (CustomItem item in all)
				{
					num = Mathf.Max(num, (int)item.Id);
				}
				return num;
			}
		}

		internal static void Register(CustomItem item)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected I4, but got Unknown
			if (byId.ContainsKey(item.Id))
			{
				Plugin.Log.LogError((object)$"Two custom items use item number {(int)item.Id}; '{item}' is skipped.");
				return;
			}
			all.Add(item);
			byId[item.Id] = item;
		}

		internal static bool TryFind(ItemType id, out CustomItem item)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			if (byId.TryGetValue(id, out CustomItem value))
			{
				item = value;
				return true;
			}
			item = null;
			return false;
		}

		internal static ItemType RealEquippedType(PlayerInventory inventory)
		{
			//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)
			int num = (((NetworkBehaviour)inventory).isLocalPlayer ? inventory.EquippedItemIndex : inventory.PlayerInfo.NetworkedEquippedItemIndex);
			if (num < 0)
			{
				return (ItemType)0;
			}
			return inventory.GetEffectiveSlot(num).itemType;
		}

		internal static bool TryGetHeld(PlayerInventory inventory, out CustomItem item)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return TryFind(RealEquippedType(inventory), out item);
		}

		internal static bool IsHolding(PlayerInventory inventory, CustomItem item)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return RealEquippedType(inventory) == item.Id;
		}
	}
	internal sealed class CustomItemSound
	{
		private static readonly string[] Extensions = new string[3] { ".wav", ".ogg", ".mp3" };

		private readonly CustomItem item;

		private readonly string label;

		private readonly float minDistance;

		private readonly float maxDistance;

		private Sound sound;

		private bool loaded;

		private bool attempted;

		internal ConfigEntry<string> File;

		internal ConfigEntry<float> VolumeSetting;

		internal CustomItemSound(CustomItem item, ConfigFile config, string label, string description, float minDistance, float maxDistance)
		{
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			this.item = item;
			this.label = label;
			this.minDistance = minDistance;
			this.maxDistance = maxDistance;
			string text = item.DisplayName + " Sounds";
			File = config.Bind<string>(text, label + "SoundFile", item.AssetFolder + "/" + item.FileName + "_" + label.ToLowerInvariant() + ".wav", "Sound played " + description + ", relative to BepInEx\\plugins. The extension doesn't matter: the mod looks for this name as .wav, .ogg and .mp3 and uses the newest one. If none exists, the game's normal sound plays.");
			VolumeSetting = config.Bind<float>(text, label + "SoundVolume", 1f, new ConfigDescription("Volume of the " + label.ToLowerInvariant() + " sound (1 = as loud as the file). It also follows the game's SFX volume.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), Array.Empty<object>()));
		}

		internal bool TryPlay(Vector3 position, float volumeMultiplier = 1f)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			if (!EnsureLoaded())
			{
				return false;
			}
			try
			{
				System coreSystem = RuntimeManager.CoreSystem;
				Channel val2 = default(Channel);
				RESULT val = ((System)(ref coreSystem)).playSound(sound, default(ChannelGroup), true, ref val2);
				if ((int)val != 0)
				{
					Plugin.Log.LogWarning((object)$"{item}: couldn't play the {label} sound ({val}).");
					return false;
				}
				VECTOR val3 = new VECTOR
				{
					x = position.x,
					y = position.y,
					z = position.z
				};
				VECTOR val4 = default(VECTOR);
				((Channel)(ref val2)).set3DAttributes(ref val3, ref val4);
				((Channel)(ref val2)).set3DMinMaxDistance(minDistance, maxDistance);
				((Channel)(ref val2)).setVolume(VolumeSetting.Value * volumeMultiplier * Volume.GetEffectsVolume());
				((Channel)(ref val2)).setPaused(false);
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)$"{item}: couldn't play the {label} sound ({ex.Message}).");
				return false;
			}
		}

		internal void Reload()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (loaded)
			{
				((Sound)(ref sound)).release();
			}
			loaded = false;
			attempted = false;
		}

		private bool EnsureLoaded()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			if (attempted)
			{
				return loaded;
			}
			attempted = true;
			string text = FindFile();
			if (text == null)
			{
				Plugin.Log.LogInfo((object)$"{item}: no {label.ToLowerInvariant()} sound file ({Path.ChangeExtension(File.Value, null)}.wav/.ogg/.mp3), using the game's sound.");
				return false;
			}
			try
			{
				MODE val = (MODE)4194577;
				System coreSystem = RuntimeManager.CoreSystem;
				RESULT val2 = ((System)(ref coreSystem)).createSound(text, val, ref sound);
				if ((int)val2 != 0)
				{
					Plugin.Log.LogWarning((object)$"{item}: couldn't read the {label.ToLowerInvariant()} sound {Path.GetFileName(text)} ({val2}), using the game's sound.");
					return false;
				}
				loaded = true;
				uint num = default(uint);
				((Sound)(ref sound)).getLength(ref num, (TIMEUNIT)1);
				Plugin.Log.LogInfo((object)$"{item}: loaded {label.ToLowerInvariant()} sound {Path.GetFileName(text)} ({(float)num / 1000f:0.##} s).");
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)$"{item}: couldn't load the {label.ToLowerInvariant()} sound ({ex.Message}), using the game's sound.");
				return false;
			}
		}

		private string? FindFile()
		{
			if (File.Value.Length == 0)
			{
				return null;
			}
			string text = Path.Combine(CustomItemModel.PluginFolder, Path.ChangeExtension(File.Value, null));
			string text2 = null;
			DateTime dateTime = DateTime.MinValue;
			string[] extensions = Extensions;
			foreach (string text3 in extensions)
			{
				string text4 = text + text3;
				if (System.IO.File.Exists(text4))
				{
					DateTime lastWriteTimeUtc = System.IO.File.GetLastWriteTimeUtc(text4);
					if (text2 == null || lastWriteTimeUtc > dateTime)
					{
						text2 = text4;
						dateTime = lastWriteTimeUtc;
					}
				}
			}
			return text2;
		}
	}
	[HarmonyPatch(typeof(PlayerInventory), "UpdateIsAimingItem")]
	internal static class CustomItemAimSoundStartPatch
	{
		private static void Postfix(PlayerInventory __instance, bool __result)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (__result && __instance.IsAimingItem && !__instance.localPlayerIsEquipmentForceHidden && CustomItems.TryGetHeld(__instance, out CustomItem item) && item.HasAimSound)
			{
				__instance.PlayerInfo.PlayerAudio.PlayItemAimForAllClients(item.Id);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerAudio), "PlayItemAimInternal")]
	internal static class CustomItemAimSoundPatch
	{
		private static bool Prefix(PlayerAudio __instance, ref ItemType item)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected I4, but got Unknown
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (!CustomItems.TryFind(item, out CustomItem item2))
			{
				return true;
			}
			try
			{
				PlayerInfo playerInfo = __instance.playerInfo;
				EquipmentSwitcher val = (((int)item2.BaseItem == 2) ? playerInfo.LeftHandEquipmentSwitcher : playerInfo.RightHandEquipmentSwitcher);
				if (item2.AimSound.TryPlay(((Component)val).transform.position, __instance.GetSmokeBombInvisibleAttenuatedVolume()))
				{
					if (((EventInstance)(ref __instance.itemAimInstance)).isValid())
					{
						((EventInstance)(ref __instance.itemAimInstance)).stop((STOP_MODE)0);
					}
					return false;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)$"{item2}: aim sound failed ({ex.Message}).");
			}
			item = (ItemType)(int)item2.BaseItem;
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerAudio), "PlayPistolShotInternal")]
	internal static class CustomItemShotSoundPatch
	{
		private static bool Prefix(PlayerAudio __instance)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PlayerInventory val = (((Object)(object)__instance.playerInfo != (Object)null) ? __instance.playerInfo.Inventory : null);
				if ((Object)(object)val == (Object)null || !CustomItems.TryGetHeld(val, out CustomItem item) || (int)item.BaseItem != 2)
				{
					return true;
				}
				if (item.UseSound.TryPlay(val.GetDuelingPistolBarrelEndPosition(), __instance.GetSmokeBombInvisibleAttenuatedVolume()))
				{
					return false;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Custom shot sound failed (" + ex.Message + ")."));
			}
			return true;
		}
	}
	internal static class CustomItemBoxes
	{
		private static readonly Dictionary<CustomItem, LocalizeStringEvent> sliderRowNames = new Dictionary<CustomItem, LocalizeStringEvent>();

		private static readonly Dictionary<CustomItem, GameObject> pauseMenuRows = new Dictionary<CustomItem, GameObject>();

		internal static void AddToItemPools(MatchSetupRules rules)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			ItemSpawnerSettings itemSpawnerSettings = rules.itemSpawnerSettings;
			flag |= AddToPool(0, itemSpawnerSettings.AheadOfBallItemPoolDefaults, itemSpawnerSettings.AheadOfBallItemPool);
			for (int i = 0; i < itemSpawnerSettings.ItemPoolsDefaults.Count && i < 4; i++)
			{
				flag |= AddToPool(i + 1, itemSpawnerSettings.ItemPoolsDefaults[i].pool, (i < itemSpawnerSettings.ItemPools.Count) ? itemSpawnerSettings.ItemPools[i].pool : null);
			}
			ItemSpawnerSettings mobilityItemSpawnerSettings = rules.mobilityItemSpawnerSettings;
			if ((Object)(object)mobilityItemSpawnerSettings != (Object)null && mobilityItemSpawnerSettings.ItemPoolsDefaults.Count > 0)
			{
				flag |= AddToPool(5, mobilityItemSpawnerSettings.ItemPoolsDefaults[0].pool, (mobilityItemSpawnerSettings.ItemPools.Count > 0) ? mobilityItemSpawnerSettings.ItemPools[0].pool : null);
			}
			if (flag)
			{
				LogLootTables(rules);
			}
		}

		private static bool AddToPool(int tab, ItemPool? defaultPool, ItemPool? inUsePool)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			bool result = false;
			if ((Object)(object)defaultPool != (Object)null && !ContainsAnyCustomItem(defaultPool))
			{
				ItemSpawnChance[] ours = Weights(defaultPool, tab);
				Insert(defaultPool, ours);
				result = true;
			}
			if ((Object)(object)defaultPool != (Object)null && (Object)(object)inUsePool != (Object)null && (Object)(object)inUsePool != (Object)(object)defaultPool && !ContainsAnyCustomItem(inUsePool))
			{
				List<ItemSpawnChance> list = new List<ItemSpawnChance>();
				foreach (CustomItem item in CustomItems.All)
				{
					list.Add(new ItemSpawnChance
					{
						item = item.Id,
						spawnChanceWeight = defaultPool.GetSpawnChanceWeight(item.Id)
					});
				}
				Insert(inUsePool, list.ToArray());
				result = true;
			}
			return result;
		}

		private static bool ContainsAnyCustomItem(ItemPool pool)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			foreach (CustomItem item in CustomItems.All)
			{
				if (pool.ContainsItemType(item.Id))
				{
					return true;
				}
			}
			return false;
		}

		private static ItemSpawnChance[] Weights(ItemPool pool, int tab)
		{
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: 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)
			IReadOnlyList<CustomItem> all = CustomItems.All;
			float[] array = new float[all.Count];
			float num = 0f;
			for (int i = 0; i < all.Count; i++)
			{
				array[i] = Mathf.Clamp(all[i].ItemBoxChances[tab].Value, 0f, 95f) / 100f;
				num += array[i];
			}
			if (num > 0.95f)
			{
				for (int j = 0; j < array.Length; j++)
				{
					array[j] *= 0.95f / num;
				}
				num = 0.95f;
			}
			float totalSpawnChanceWeight = pool.TotalSpawnChanceWeight;
			ItemSpawnChance[] array2 = (ItemSpawnChance[])(object)new ItemSpawnChance[all.Count];
			for (int k = 0; k < all.Count; k++)
			{
				float num2 = array[k] * totalSpawnChanceWeight / (1f - num);
				array2[k] = new ItemSpawnChance
				{
					item = all[k].Id,
					spawnChanceWeight = Mathf.Clamp(Mathf.Round(num2 * 10f) / 10f, 0f, 100f)
				};
			}
			return array2;
		}

		private static void Insert(ItemPool pool, ItemSpawnChance[] ours)
		{
			ItemSpawnChance[] spawnChances = pool.spawnChances;
			ItemSpawnChance[] array = (ItemSpawnChance[])(object)new ItemSpawnChance[ours.Length + spawnChances.Length];
			Array.Copy(ours, 0, array, 0, ours.Length);
			Array.Copy(spawnChances, 0, array, ours.Length, spawnChances.Length);
			pool.spawnChances = array;
			pool.UpdateTotalWeight();
		}

		private unsafe static void LogLootTables(MatchSetupRules rules)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i <= 5; i++)
			{
				ItemPool val;
				string text;
				try
				{
					val = (ItemPool)(i switch
					{
						0 => rules.itemSpawnerSettings.AheadOfBallItemPoolDefaults, 
						5 => rules.mobilityItemSpawnerSettings.ItemPoolsDefaults[0].pool, 
						_ => rules.itemSpawnerSettings.ItemPoolsDefaults[i - 1].pool, 
					});
					text = i switch
					{
						0 => "ahead of own ball", 
						5 => "mobility item boxes", 
						_ => rules.GetPoolLocString(rules.itemSpawnerSettings.ItemPoolsDefaults[i - 1]), 
					};
				}
				catch (Exception)
				{
					continue;
				}
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				float totalSpawnChanceWeight = val.TotalSpawnChanceWeight;
				List<string> list = new List<string>();
				ItemSpawnChance[] spawnChances = val.SpawnChances;
				foreach (ItemSpawnChance val2 in spawnChances)
				{
					string text2;
					if (!CustomItems.TryFind(val2.item, out CustomItem item))
					{
						ItemType item2 = val2.item;
						text2 = ((object)(*(ItemType*)(&item2))/*cast due to .constrained prefix*/).ToString();
					}
					else
					{
						text2 = item.DisplayName.Replace(" ", "");
					}
					string arg = text2;
					list.Add($"{arg} {((totalSpawnChanceWeight > 0f) ? (val2.spawnChanceWeight / totalSpawnChanceWeight * 100f) : 0f):0.#}%");
				}
				Plugin.Log.LogInfo((object)string.Format("Loot table tab {0} '{1}' ({2}): {3}", i, text, ((Object)val).name, string.Join(", ", list)));
			}
		}

		internal static void AddToItemOrder(MatchSetupRules rules)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected I4, but got Unknown
			foreach (CustomItem item in CustomItems.All)
			{
				if (Array.IndexOf(rules.itemOrder, item.Id) < 0)
				{
					ItemType[] array = rules.itemOrder;
					Array.Resize(ref array, array.Length + 1);
					array[^1] = (ItemType)(int)item.Id;
					rules.itemOrder = array;
				}
			}
			int highestId = CustomItems.HighestId;
			int[] itemOrderLookup = rules.itemOrderLookup;
			int num = Math.Max(highestId, (itemOrderLookup != null) ? itemOrderLookup.Length : 0);
			int[] array2 = new int[num];
			for (int i = 0; i < array2.Length; i++)
			{
				array2[i] = -1;
			}
			for (int j = 0; j < rules.itemOrder.Length; j++)
			{
				int num2 = (int)rules.itemOrder[j] - 1;
				if (num2 >= 0 && num2 < array2.Length)
				{
					array2[num2] = j;
				}
			}
			rules.itemOrderLookup = array2;
		}

		internal static void FindSliderRows(MatchSetupRules rules)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			sliderRowNames.Clear();
			foreach (CustomItem item in CustomItems.All)
			{
				int num = Array.IndexOf(rules.itemOrder, item.Id);
				if (num >= 0 && num < rules.spawnChanceSliders.Count)
				{
					Transform val = ((Component)rules.spawnChanceSliders[num]).transform;
					while ((Object)(object)val.parent != (Object)null && (Object)(object)val.parent != (Object)(object)rules.itemsParent)
					{
						val = val.parent;
					}
					LocalizeStringEvent componentInChildren = ((Component)val).GetComponentInChildren<LocalizeStringEvent>(true);
					if ((Object)(object)componentInChildren != (Object)null)
					{
						sliderRowNames[item] = componentInChildren;
					}
					Plugin.Log.LogInfo((object)$"{item}: added a slider to the match setup odds menu.");
				}
			}
			RefreshNames();
		}

		internal static void RefreshNames()
		{
			foreach (LocalizeStringEvent value in sliderRowNames.Values)
			{
				if ((Object)(object)value != (Object)null)
				{
					value.RefreshString();
				}
			}
		}

		internal static void AddPauseMenuRows(PauseMenu menu)
		{
			foreach (CustomItem item in CustomItems.All)
			{
				if ((!pauseMenuRows.TryGetValue(item, out GameObject value) || !((Object)(object)value != (Object)null)) && item.Data != null)
				{
					GameObject[] array = menu.allItemProbabilities;
					GameObject val = Object.Instantiate<GameObject>(menu.itemProbabilityTemplate, menu.itemProbabilityTemplate.transform.parent);
					((Object)val).name = item.DisplayName + " probability";
					val.SetActive(true);
					((Component)val.transform.GetChild(1)).GetComponent<Image>().sprite = item.Data.Icon;
					if (array.Length != 0)
					{
						val.transform.SetSiblingIndex(array[^1].transform.GetSiblingIndex() + 1);
					}
					Array.Resize(ref array, array.Length + 1);
					array[^1] = val;
					menu.allItemProbabilities = array;
					pauseMenuRows[item] = val;
				}
			}
		}

		internal static void UpdatePauseMenuRows(PauseMenu menu)
		{
			//IL_00c5: 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_0113: Unknown result type (might be due to invalid IL or missing references)
			MatchSetupRules instance = SingletonNetworkBehaviour<MatchSetupRules>.Instance;
			if ((Object)(object)instance == (Object)null || menu.itemPoolLocStrings == null)
			{
				return;
			}
			foreach (KeyValuePair<CustomItem, GameObject> pauseMenuRow in pauseMenuRows)
			{
				CustomItem key = pauseMenuRow.Key;
				GameObject value = pauseMenuRow.Value;
				if (!((Object)(object)value == (Object)null) && key.Data != null)
				{
					((Component)value.transform.GetChild(1)).GetComponent<Image>().sprite = key.Data.Icon;
					bool flag = true;
					string text = "<color=#b05d39>" + key.Data.LocalizedName.GetLocalizedString() + "</color>\n";
					int[] array = new int[6] { 1, 2, 3, 4, 5, 0 };
					foreach (int num in array)
					{
						bool flag2 = instance.IsSpawnChanceDefault(num, key.Id);
						flag = flag && flag2;
						float itemPoolTotalWeight = instance.GetItemPoolTotalWeight(num);
						float num2 = ((itemPoolTotalWeight > 0f) ? (instance.GetWeight(num, key.Id) / itemPoolTotalWeight * 100f) : 0f);
						string arg = (flag2 ? ((num2 > 0f) ? "#312F2F" : "#96928F") : ((instance.GetDefaultItemFactor(num, key.Id) * 100f > num2) ? "#DB4654" : "#4E9444"));
						text += $"<color={arg}>{num2:0}% {menu.itemPoolLocStrings[num]}</color>\n";
					}
					menu.itemProbabilityTooltip.RegisterTooltip(value.GetComponent<RectTransform>(), text, (string)null);
					((Component)value.transform.GetChild(2)).gameObject.SetActive(!flag);
				}
			}
		}
	}
	[HarmonyPatch(typeof(MatchSetupRules), "Deserialize")]
	internal static class CustomItemsBeforeSavedOddsPatch
	{
		private static void Prefix(MatchSetupRules __instance)
		{
			try
			{
				CustomItemBoxes.AddToItemPools(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't add the custom items to the item box odds before loading the saved odds (" + ex.Message + ")."));
			}
		}
	}
	[HarmonyPatch(typeof(MatchSetupRules), "Initialize")]
	internal static class CustomItemOddsMenuPatch
	{
		private static void Prefix(MatchSetupRules __instance)
		{
			try
			{
				CustomItemBoxes.AddToItemPools(__instance);
				CustomItemBoxes.AddToItemOrder(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't add the custom items to the item box odds (" + ex.Message + ")."));
			}
		}

		private static void Postfix(MatchSetupRules __instance)
		{
			try
			{
				CustomItemBoxes.FindSliderRows(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't find the custom items' odds sliders (" + ex.Message + ")."));
			}
		}
	}
	[HarmonyPatch(typeof(PauseMenu), "Awake")]
	internal static class CustomItemPauseMenuRowsPatch
	{
		private static void Postfix(PauseMenu __instance)
		{
			try
			{
				CustomItemBoxes.AddPauseMenuRows(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't add the custom items to the pause menu (" + ex.Message + ")."));
			}
		}
	}
	[HarmonyPatch(typeof(PauseMenu), "UpdateItemProbabilites")]
	internal static class CustomItemPauseMenuOddsPatch
	{
		private static void Postfix(PauseMenu __instance)
		{
			try
			{
				CustomItemBoxes.UpdatePauseMenuRows(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't show the custom items' odds in the pause menu (" + ex.Message + ")."));
			}
		}
	}
	[HarmonyPatch(typeof(ItemSpawnerSettings), "GetRandomItemFor")]
	internal static class CustomItemBoxLogPatch
	{
		private static void Postfix(ItemType __result)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if (CustomItems.TryFind(__result, out CustomItem item))
			{
				Plugin.Log.LogInfo((object)$"{item}: an item box gave one out.");
			}
		}
	}
	internal sealed class ModelPart
	{
		public Texture2D? Texture;

		public Color Color = Color.white;

		public bool DoubleSided;
	}
	internal sealed class CustomItemModel
	{
		private static readonly char[] Whitespace = new char[2] { ' ', '\t' };

		private readonly CustomItem item;

		private bool attempted;

		private Mesh? mesh;

		private List<ModelPart> parts = new List<ModelPart>();

		internal Mesh? Mesh
		{
			get
			{
				EnsureLoaded();
				return mesh;
			}
		}

		internal List<ModelPart> Parts
		{
			get
			{
				EnsureLoaded();
				return parts;
			}
		}

		internal static string PluginFolder => Path.GetDirectoryName(typeof(Plugin).Assembly.Location) ?? "";

		internal CustomItemModel(CustomItem item)
		{
			this.item = item;
		}

		internal void Reload()
		{
			if ((Object)(object)mesh != (Object)null)
			{
				Object.Destroy((Object)(object)mesh);
			}
			HashSet<Texture2D> hashSet = new HashSet<Texture2D>();
			foreach (ModelPart part in parts)
			{
				if ((Object)(object)part.Texture != (Object)null && hashSet.Add(part.Texture))
				{
					Object.Destroy((Object)(object)part.Texture);
				}
			}
			mesh = null;
			parts = new List<ModelPart>();
			attempted = false;
		}

		private void EnsureLoaded()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			if (attempted)
			{
				return;
			}
			attempted = true;
			string text = FindModelFile();
			if (text == null)
			{
				Plugin.Log.LogInfo((object)string.Format("{0}: no custom model ({1}.glb/.gltf/.obj) in {2}, using the {3}{4}.", item, Path.ChangeExtension(item.ModelFile.Value, null), PluginFolder, item.TintColor.HasValue ? "tinted " : "", item.BaseItem));
				return;
			}
			try
			{
				string text2 = Path.GetExtension(text).ToLowerInvariant();
				if (text2 == ".obj")
				{
					mesh = LoadObj(text);
					parts = new List<ModelPart>
					{
						new ModelPart
						{
							Texture = LoadObjTexture()
						}
					};
				}
				else
				{
					mesh = GltfLoader.Load(text, item.ToString(), out parts);
				}
				int num = 0;
				foreach (ModelPart part in parts)
				{
					if ((Object)(object)part.Texture != (Object)null)
					{
						num++;
					}
				}
				ManualLogSource log = Plugin.Log;
				string text3 = $"{item}: loaded model {Path.GetFileName(text)} ({mesh.vertexCount} vertices, {mesh.triangles.Length / 3} triangles, ";
				object arg = parts.Count;
				object arg2 = num;
				Bounds bounds = mesh.bounds;
				log.LogInfo((object)(text3 + $"{arg} part(s), {arg2} with a texture, size {((Bounds)(ref bounds)).size})."));
			}
			catch (Exception ex)
			{
				mesh = null;
				parts = new List<ModelPart>();
				Plugin.Log.LogError((object)$"{item}: couldn't read the model file {text}: {ex.Message}");
			}
		}

		private Texture2D? LoadObjTexture()
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			string text = Path.Combine(PluginFolder, item.TextureFile.Value);
			if (item.TextureFile.Value.Length == 0 || !File.Exists(text))
			{
				Plugin.Log.LogInfo((object)$"{item}: no texture file for the .obj model, it will be one plain color.");
				return null;
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true);
			if (ImageConversion.LoadImage(val, File.ReadAllBytes(text)))
			{
				((Object)val).name = item.DisplayName + " Texture";
				return val;
			}
			Object.Destroy((Object)(object)val);
			Plugin.Log.LogWarning((object)$"{item}: couldn't read the texture {text}; the model will be one plain color.");
			return null;
		}

		private static Mesh LoadObj(string path)
		{
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			List<Vector2> list2 = new List<Vector2>();
			List<Vector3> list3 = new List<Vector3>();
			List<Vector3> list4 = new List<Vector3>();
			List<Vector2> list5 = new List<Vector2>();
			List<Vector3> list6 = new List<Vector3>();
			List<int> list7 = new List<int>();
			Dictionary<(int, int, int), int> dictionary = new Dictionary<(int, int, int), int>();
			bool hasNormals = false;
			List<int> list8 = new List<int>();
			foreach (string item in File.ReadLines(path))
			{
				string text = item.Trim();
				if (text.Length == 0 || text[0] == '#')
				{
					continue;
				}
				string[] array = text.Split(Whitespace, StringSplitOptions.RemoveEmptyEntries);
				switch (array[0])
				{
				case "v":
					list.Add(new Vector3(0f - ParseFloat(array[1]), ParseFloat(array[2]), ParseFloat(array[3])));
					break;
				case "vt":
					list2.Add(new Vector2(ParseFloat(array[1]), (array.Length > 2) ? ParseFloat(array[2]) : 0f));
					break;
				case "vn":
					list3.Add(new Vector3(0f - ParseFloat(array[1]), ParseFloat(array[2]), ParseFloat(array[3])));
					break;
				case "f":
				{
					list8.Clear();
					for (int i = 1; i < array.Length; i++)
					{
						string[] array2 = array[i].Split('/');
						int num = ResolveIndex(array2[0], list.Count);
						int num2 = ((array2.Length > 1 && array2[1].Length > 0) ? ResolveIndex(array2[1], list2.Count) : (-1));
						int num3 = ((array2.Length > 2 && array2[2].Length > 0) ? ResolveIndex(array2[2], list3.Count) : (-1));
						if (num3 >= 0)
						{
							hasNormals = true;
						}
						if (!dictionary.TryGetValue((num, num2, num3), out var value))
						{
							value = list4.Count;
							dictionary[(num, num2, num3)] = value;
							list4.Add(list[num]);
							list5.Add((num2 >= 0) ? list2[num2] : Vector2.zero);
							list6.Add((num3 >= 0) ? list3[num3] : Vector3.zero);
						}
						list8.Add(value);
					}
					for (int j = 1; j + 1 < list8.Count; j++)
					{
						list7.Add(list8[0]);
						list7.Add(list8[j + 1]);
						list7.Add(list8[j]);
					}
					break;
				}
				}
			}
			if (list7.Count == 0)
			{
				throw new InvalidDataException("the file has no faces");
			}
			return BuildMesh(list4, list5, list6, new List<List<int>> { list7 }, hasNormals);
		}

		private string? FindModelFile()
		{
			string text = Path.Combine(PluginFolder, Path.ChangeExtension(item.ModelFile.Value, null));
			string text2 = null;
			DateTime dateTime = DateTime.MinValue;
			string[] array = new string[3] { ".glb", ".gltf", ".obj" };
			foreach (string text3 in array)
			{
				string text4 = text + text3;
				if (File.Exists(text4))
				{
					DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(text4);
					if (text2 == null || lastWriteTimeUtc > dateTime)
					{
						text2 = text4;
						dateTime = lastWriteTimeUtc;
					}
				}
			}
			return text2;
		}

		internal static Mesh BuildMesh(List<Vector3> positions, List<Vector2> uvs, List<Vector3> normals, List<List<int>> submeshes, bool hasNormals)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			Mesh val = new Mesh
			{
				name = "CustomItemModel"
			};
			if (positions.Count > 65000)
			{
				val.indexFormat = (IndexFormat)1;
			}
			val.SetVertices(positions);
			val.SetUVs(0, uvs);
			val.subMeshCount = submeshes.Count;
			for (int i = 0; i < submeshes.Count; i++)
			{
				val.SetTriangles(submeshes[i], i);
			}
			if (hasNormals)
			{
				val.SetNormals(normals);
			}
			else
			{
				val.RecalculateNormals();
			}
			val.RecalculateBounds();
			return val;
		}

		private static int ResolveIndex(string text, int count)
		{
			int num = int.Parse(text, CultureInfo.InvariantCulture);
			if (num <= 0)
			{
				return count + num;
			}
			return num - 1;
		}

		private static float ParseFloat(string text)
		{
			return float.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
		}

		internal static Vector3 ParseVector(string text)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			string[] parts = text.Split(',');
			return new Vector3(Get(0), Get(1), Get(2));
			float Get(int i)
			{
				if (i >= parts.Length || !float.TryParse(parts[i].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					return 0f;
				}
				return result;
			}
		}
	}
	internal sealed class CustomItemPickup
	{
		private readonly CustomItem item;

		private GameObject? template;

		private GameObject? lookObject;

		private readonly List<(Renderer renderer, Material[] originals)> tinted = new List<(Renderer, Material[])>();

		internal CustomItemPickup(CustomItem item)
		{
			this.item = item;
		}

		internal GameObject CreateTemplate(GameObject basePickup)
		{
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_0095: 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)
			if ((Object)(object)template != (Object)null)
			{
				return template;
			}
			try
			{
				GameObject val = new GameObject(item.DisplayName + " Pickup Template");
				val.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)val);
				GameObject val2 = Object.Instantiate<GameObject>(basePickup, val.transform);
				((Object)val2).name = item.DisplayName + " (pickup)";
				PhysicalItem val3 = default(PhysicalItem);
				if (!val2.TryGetComponent<PhysicalItem>(ref val3) || !SetAssetId(val2))
				{
					Plugin.Log.LogWarning((object)$"{item}: couldn't make its pickup; a dropped {item} will look like a {item.BaseItem}.");
					Object.Destroy((Object)(object)val);
					return basePickup;
				}
				val3.itemType = item.Id;
				template = val2;
				ApplyLook();
				Plugin.Log.LogInfo((object)$"{item}: made its pickup (network asset id {item.PickupAssetId:X8}).");
				return template;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)$"{item}: couldn't make its pickup ({ex.Message}); a dropped {item} will look like a {item.BaseItem}.");
				return basePickup;
			}
		}

		private bool SetAssetId(GameObject copy)
		{
			NetworkIdentity val = default(NetworkIdentity);
			if (!copy.TryGetComponent<NetworkIdentity>(ref val))
			{
				return false;
			}
			string[] array = new string[3] { "_assetId", "assetId", "m_AssetId" };
			foreach (string text in array)
			{
				FieldInfo fieldInfo = AccessTools.Field(typeof(NetworkIdentity), text);
				if (fieldInfo != null && fieldInfo.FieldType == typeof(uint))
				{
					fieldInfo.SetValue(val, item.PickupAssetId);
					break;
				}
			}
			return val.assetId == item.PickupAssetId;
		}

		internal void RegisterWithNetwork()
		{
			if (!((Object)(object)template == (Object)null) && (!(AccessTools.Field(typeof(NetworkClient), "prefabs")?.GetValue(null) is IDictionary dictionary) || !dictionary.Contains(item.PickupAssetId)))
			{
				NetworkClient.RegisterPrefab(template);
				Plugin.Log.LogInfo((object)$"{item}: registered its pickup with the network.");
			}
		}

		internal void ApplyLook()
		{
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)template == (Object)null)
			{
				return;
			}
			if ((Object)(object)lookObject != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)lookObject);
			}
			lookObject = null;
			foreach (var (val, sharedMaterials) in tinted)
			{
				if ((Object)(object)val != (Object)null)
				{
					val.sharedMaterials = sharedMaterials;
				}
			}
			tinted.Clear();
			List<Renderer> meshRenderers = CustomItemVisuals.GetMeshRenderers((Component)(object)template.transform);
			foreach (Renderer item in meshRenderers)
			{
				item.enabled = true;
			}
			if (meshRenderers.Count == 0)
			{
				return;
			}
			Mesh mesh = this.item.Model.Mesh;
			if ((Object)(object)mesh != (Object)null)
			{
				try
				{
					(lookObject, _) = CustomItemVisuals.CreateFittedModel(template.transform, meshRenderers, this.item, mesh, "on the dropped pickup");
					foreach (Renderer item2 in meshRenderers)
					{
						item2.enabled = false;
					}
					return;
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)$"{this.item}: couldn't put the model on the pickup ({ex.Message}).");
					if ((Object)(object)lookObject != (Object)null)
					{
						Object.DestroyImmediate((Object)(object)lookObject);
					}
					lookObject = null;
				}
			}
			Color? tintColor = this.item.TintColor;
			if (!tintColor.HasValue)
			{
				return;
			}
			Color valueOrDefault = tintColor.GetValueOrDefault();
			foreach (Renderer item3 in meshRenderers)
			{
				Material[] sharedMaterials2 = item3.sharedMaterials;
				Material[] array = (Material[])(object)new Material[sharedMaterials2.Length];
				for (int i = 0; i < sharedMaterials2.Length; i++)
				{
					array[i] = CustomItemVisuals.GetTintMaterial(sharedMaterials2[i], valueOrDefault);
				}
				tinted.Add((item3, sharedMaterials2));
				item3.sharedMaterials = array;
			}
		}
	}
	[HarmonyPatch(typeof(BNetworkManager), "OnStartClient")]
	internal static class RegisterCustomPickupsPatch
	{
		private static void Postfix()
		{
			foreach (CustomItem item in CustomItems.All)
			{
				try
				{
					item.Pickup.RegisterWithNetwork();
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)$"{item}: couldn't register its pickup with the network ({ex.Message}).");
				}
			}
		}
	}
	internal static class CustomItemRegistration
	{
		private static bool namesRegistered;

		private static float nextNameAttemptTime;

		private static bool subscribedToLanguageChange;

		private static readonly MethodInfo MemberwiseCloneMethod = AccessTools.Method(typeof(object), "MemberwiseClone", (Type[])null, (Type[])null);

		internal static void Tick()
		{
			ItemCollection allItems = GameManager.AllItems;
			if ((Object)(object)allItems != (Object)null)
			{
				EnsureRegistered(allItems);
			}
			TryRegisterNames();
		}

		internal static void EnsureRegistered(ItemCollection items)
		{
			foreach (CustomItem item in CustomItems.All)
			{
				EnsureRegistered(items, item);
			}
		}

		private static void EnsureRegistered(ItemCollection items, CustomItem item)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Expected I4, but got Unknown
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			ItemData val = default(ItemData);
			if (items.allItemData.ContainsKey(item.Id) || !items.TryGetItemData(item.BaseItem, ref val))
			{
				return;
			}
			if (item.Data == null)
			{
				ItemData val2 = (ItemData)MemberwiseCloneMethod.Invoke(val, null);
				val2.Type = item.Id;
				val2.name = null;
				val2.MaxUses = Math.Max(1, item.Uses.Value);
				item.BaseIcon = val.Icon;
				if ((Object)(object)val.Icon != (Object)null)
				{
					ManualLogSource log = Plugin.Log;
					object[] obj = new object[4] { item, item.BaseItem, null, null };
					Rect rect = val.Icon.rect;
					obj[2] = ((Rect)(ref rect)).width;
					rect = val.Icon.rect;
					obj[3] = ((Rect)(ref rect)).height;
					log.LogInfo((object)string.Format("{0}: the {1} icon is {2}x{3} pixels.", obj));
				}
				val2.Icon = CustomItemVisuals.MakeIcon(item);
				val2.Prefab = item.Pickup.CreateTemplate(val.Prefab);
				val2.Initialize();
				item.Data = val2;
			}
			items.allItemData[item.Id] = item.Data;
			Plugin.Log.LogInfo((object)$"{item} registered as item {(int)item.Id} ({item.Data.MaxUses} use(s)), a copy of the {item.BaseItem}.");
		}

		private static void TryRegisterNames()
		{
			if (namesRegistered || Time.unscaledTime < nextNameAttemptTime)
			{
				return;
			}
			nextNameAttemptTime = Time.unscaledTime + 1f;
			try
			{
				if (!subscribedToLanguageChange)
				{
					LocalizationManager.LanguageChanged += delegate
					{
						namesRegistered = false;
					};
					subscribedToLanguageChange = true;
				}
				foreach (CustomItem item in CustomItems.All)
				{
					LocalizationManager.AddStringToAllLocales((StringTable)1, item.NameKey, item.DisplayName);
					Plugin.Log.LogInfo((object)$"{item}: name registered ({item.NameKey} = \"{item.DisplayName}\").");
				}
				namesRegistered = true;
				CustomItemBoxes.RefreshNames();
			}
			catch (Exception)
			{
			}
		}

		internal static void ReloadIcons()
		{
			foreach (CustomItem item in CustomItems.All)
			{
				if (item.Data != null)
				{
					item.Data.Icon = CustomItemVisuals.MakeIcon(item);
				}
			}
			PlayerInventory localPlayerInventory = GameManager.LocalPlayerInventory;
			if ((Object)(object)localPlayerInventory == (Object)null)
			{
				return;
			}
			try
			{
				for (int i = 0; i < localPlayerInventory.slots.Count; i++)
				{
					Hotkeys.UpdatePlayerInventoryIcon(i);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't refresh the hotbar icons (" + ex.Message + ")."));
			}
		}

		internal static void GiveToLocalPlayer(CustomItem item)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			PlayerInventory.GiveItemToLocalPlayer(item.Id);
			Plugin.Log.LogInfo((object)$"Asked the game for a {item} (needs cheats enabled in the match rules).");
		}
	}
	[HarmonyPatch(typeof(ItemCollection), "Initialize")]
	internal static class RegisterAfterItemListLoadsPatch
	{
		private static void Postfix(ItemCollection __instance)
		{
			CustomItemRegistration.EnsureRegistered(__instance);
		}
	}
	[HarmonyPatch(typeof(PlayerInventory), "GetEffectivelyEquippedItem")]
	internal static class DisguiseAsBaseItemPatch
	{
		private static void Postfix(ref ItemType __result)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected I4, but got Unknown
			if (CustomItems.TryFind(__result, out CustomItem item))
			{
				__result = (ItemType)(int)item.BaseItem;
			}
		}
	}
	[HarmonyPatch(typeof(PlayerInventory), "CanUseEquippedItem")]
	internal static class UseAsBaseItemPatch
	{
		private static void Postfix(ref InventorySlot equippedSlot)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (CustomItems.TryFind(equippedSlot.itemType, out CustomItem item))
			{
				equippedSlot.itemType = item.BaseItem;
			}
		}
	}
	[HarmonyPatch(typeof(Hotkeys), "SelectInternal")]
	internal static class CustomItemHotbarNamePatch
	{
		private static void Postfix(Hotkeys __instance)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Invalid comparison between Unknown and I4
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Invalid comparison between Unknown and I4
			if ((int)__instance.currentMode != 0 && (int)__instance.currentMode != 3)
			{
				return;
			}
			int selectedIndex = __instance.selectedIndex;
			if (selectedIndex <= 0 || selectedIndex >= __instance.hotkeyUis.Length)
			{
				return;
			}
			object obj;
			if ((int)__instance.currentMode != 3)
			{
				obj = GameManager.LocalPlayerInventory;
			}
			else
			{
				PlayerSpectator localPlayerAsSpectator = GameManager.LocalPlayerAsSpectator;
				if (localPlayerAsSpectator == null)
				{
					obj = null;
				}
				else
				{
					PlayerInfo targetPlayer = localPlayerAsSpectator.TargetPlayer;
					obj = ((targetPlayer != null) ? targetPlayer.Inventory : null);
				}
			}
			PlayerInventory val = (PlayerInventory)obj;
			if (!((Object)(object)val == (Object)null) && CustomItems.TryGetHeld(val, out CustomItem item) && item.Data != null)
			{
				__instance.hotkeyUis[selectedIndex].SetName(item.Data.LocalizedName);
			}
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	internal static class CustomItemNamePatch
	{
		private static void Postfix(ItemData __instance, ref string __result)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			if (CustomItems.TryFind(__instance.Type, out CustomItem item))
			{
				__result = item.DisplayName;
			}
		}
	}
	[HarmonyPatch(typeof(CourseManager), "ServerSpawnItem", new Type[]
	{
		typeof(ItemType),
		typeof(int),
		typeof(Vector3),
		typeof(Quaternion),
		typeof(Vector3),
		typeof(Vector3),
		typeof(PlayerInventory),
		typeof(ItemUseId),
		typeof(bool)
	})]
	internal static class KeepDroppedCustomItemPatch
	{
		private static void Postfix(ItemType item, PhysicalItem __result)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__result != (Object)null && CustomItems.TryFind(item, out CustomItem _))
			{
				__result.itemType = item;
			}
		}
	}
	internal static class CustomItemVisuals
	{
		private sealed class ItemLook
		{
			public CustomItem Item;

			public readonly List<(Renderer renderer, Material[] originals)> Tinted = new List<(Renderer, Material[])>();

			public readonly List<Renderer> Hidden = new List<Renderer>();

			public GameObject? Model;

			public MeshRenderer? ModelRenderer;
		}

		private static readonly Dictionary<Equipment, ItemLook> looks = new Dictionary<Equipment, ItemLook>();

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

		private static readonly Dictionary<(CustomItem, Material), Material[]> modelMaterials = new Dictionary<(CustomItem, Material), Material[]>();

		private static readonly Dictionary<Equipment, CustomItem> shouldHaveLook = new Dictionary<Equipment, CustomItem>();

		private static readonly List<Equipment> toRestore = new List<Equipment>();

		private static bool loggedShaderInfo;

		internal static Sprite MakeIcon(CustomItem item)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			Sprite val = (((Object)(object)item.BaseIcon != (Object)null) ? LoadCustomIcon(item, item.BaseIcon) : null);
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			if ((Object)(object)item.BaseIcon != (Object)null)
			{
				Color? tintColor = item.TintColor;
				if (tintColor.HasValue)
				{
					Color valueOrDefault = tintColor.GetValueOrDefault();
					return MakeTintedIcon(item, item.BaseIcon, valueOrDefault);
				}
			}
			return item.BaseIcon;
		}

		private static Sprite MakeTintedIcon(CustomItem item, Sprite original, Color color)
		{
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: 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_00c6: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: 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_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: 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)
			RenderTexture active = RenderTexture.active;
			RenderTexture val = null;
			try
			{
				Texture2D texture = original.texture;
				Rect textureRect = original.textureRect;
				val = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0);
				Graphics.Blit((Texture)(object)texture, val);
				RenderTexture.active = val;
				Texture2D val2 = new Texture2D((int)((Rect)(ref textureRect)).width, (int)((Rect)(ref textureRect)).height, (TextureFormat)4, false);
				val2.ReadPixels(textureRect, 0, 0);
				Color[] pixels = val2.GetPixels();
				for (int i = 0; i < pixels.Length; i++)
				{
					Color val3 = pixels[i];
					float num = val3.r * 0.299f + val3.g * 0.587f + val3.b * 0.114f;
					Color val4 = color * (0.25f + num * 1.1f);
					val4 = Color.Lerp(val3, val4, 0.85f);
					val4.a = val3.a;
					pixels[i] = val4;
				}
				val2.SetPixels(pixels);
				val2.Apply();
				((Object)val2).name = item.DisplayName + " Icon";
				float x = original.pivot.x;
				Rect rect = original.rect;
				float num2 = x / ((Rect)(ref rect)).width;
				float y = original.pivot.y;
				rect = original.rect;
				Vector2 val5 = default(Vector2);
				((Vector2)(ref val5))..ctor(num2, y / ((Rect)(ref rect)).height);
				Sprite val6 = Sprite.Create(val2, new Rect(0f, 0f, (float)((Texture)val2).width, (float)((Texture)val2).height), val5, original.pixelsPerUnit);
				((Object)val6).name = item.DisplayName + " Icon";
				return val6;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)$"{item}: couldn't make the tinted icon, using the {item.BaseItem} icon instead. ({ex.Message})");
				return original;
			}
			finally
			{
				RenderTexture.active = active;
				if ((Object)(object)val != (Object)null)
				{
					RenderTexture.ReleaseTemporary(val);
				}
			}
		}

		private static Sprite? LoadCustomIcon(CustomItem item, Sprite baseIcon)
		{
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			string text = Path.Combine(CustomItemModel.PluginFolder, item.IconFile.Value);
			if (item.IconFile.Value.Length == 0 || !File.Exists(text))
			{
				return null;
			}
			try
			{
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, File.ReadAllBytes(text)))
				{
					Object.Destroy((Object)(object)val);
					Plugin.Log.LogWarning((object)$"{item}: the icon {text} isn't a PNG or JPG, using the {item.BaseItem} icon.");
					return null;
				}
				((Object)val).name = item.DisplayName + " Custom Icon";
				((Texture)val).wrapMode = (TextureWrapMode)1;
				float num = baseIcon.pixelsPerUnit * (float)((Texture)val).width;
				Rect rect = baseIcon.rect;
				float num2 = num / Mathf.Max(1f, ((Rect)(ref rect)).width);
				Sprite val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), num2);
				((Object)val2).name = item.DisplayName + " Custom Icon";
				Plugin.Log.LogInfo((object)$"{item}: using custom icon {Path.GetFileName(text)} ({((Texture)val).width}x{((Texture)val).height}).");
				return val2;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)$"{item}: couldn't load the icon {text} ({ex.Message}), using the {item.BaseItem} icon.");
				return null;
			}
		}

		internal static void Tick()
		{
			shouldHaveLook.Clear();
			CheckPlayer(GameManager.LocalPlayerInfo);
			List<PlayerInfo> remotePlayers = GameManager.RemotePlayers;
			if (remotePlayers != null)
			{
				foreach (PlayerInfo item in remotePlayers)
				{
					CheckPlayer(item);
				}
			}
			toRestore.Clear();
			foreach (KeyValuePair<Equipment, ItemLook> look in looks)
			{
				if (!shouldHaveLook.TryGetValue(look.Key, out CustomItem value) || value != look.Value.Item)
				{
					toRestore.Add(look.Key);
				}
			}
			foreach (Equipment item2 in toRestore)
			{
				Restore(item2);
			}
			foreach (KeyValuePair<Equipment, CustomItem> item3 in shouldHaveLook)
			{
				Equipment key = item3.Key;
				if (!looks.TryGetValue(key, out ItemLook value2))
				{
					value2 = ApplyLook(key, item3.Value);
					looks[key] = value2;
				}
				if ((Object)(object)value2.ModelRenderer != (Object)null && value2.Hidden.Count > 0)
				{
					((Renderer)value2.ModelRenderer).enabled = (Object)(object)value2.Hidden[0] != (Object)null && value2.Hidden[0].enabled;
				}
			}
		}

		internal static void ResetAll()
		{
			foreach (Equipment item in new List<Equipment>(looks.Keys))
			{
				Restore(item);
			}
			foreach (Material[] value in modelMaterials.Values)
			{
				Material[] array = value;
				foreach (Material val in array)
				{
					Object.Destroy((Object)(object)val);
				}
			}
			modelMaterials.Clear();
		}

		private static void CheckPlayer(PlayerInfo? player)
		{
			if (!((Object)(object)player == (Object)null) && !((Object)(object)player.Inventory == (Object)null) && CustomItems.TryGetHeld(player.Inventory, out CustomItem item))
			{
				CheckHand(player.LeftHandEquipmentSwitcher, item);
				CheckHand(player.RightHandEquipmentSwitcher, item);
			}
		}

		private static void CheckHand(EquipmentSwitcher? hand, CustomItem item)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			Equipment val = (((Object)(object)hand != (Object)null) ? hand.CurrentEquipment : null);
			if ((Object)(object)val != (Object)null && val.Type == item.HeldEquipment)
			{
				shouldHaveLook[val] = item;
			}
		}

		internal static List<Renderer> GetMeshRenderers(Component equipment)
		{
			List<Renderer> list = new List<Renderer>();
			Renderer[] componentsInChildren = equipment.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if (val is MeshRenderer || val is SkinnedMeshRenderer)
				{
					list.Add(val);
				}
			}
			return list;
		}

		private static ItemLook ApplyLook(Equipment equipment, CustomItem item)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			ItemLook itemLook = new ItemLook
			{
				Item = item
			};
			List<Renderer> meshRenderers = GetMeshRenderers((Component)(object)equipment);
			Mesh mesh = item.Model.Mesh;
			if ((Object)(object)mesh != (Object)null && meshRenderers.Count > 0)
			{
				try
				{
					ShowCustomModel(equipment, meshRenderers, item, mesh, itemLook);
					return itemLook;
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"{item}: couldn't show the custom model, using the {item.BaseItem} instead. ({arg})");
					UndoLook(itemLook);
					itemLook = new ItemLook
					{
						Item = item
					};
				}
			}
			Color? tintColor = item.TintColor;
			if (tintColor.HasValue)
			{
				Color valueOrDefault = tintColor.GetValueOrDefault();
				foreach (Renderer item2 in meshRenderers)
				{
					Material[] sharedMaterials = item2.sharedMaterials;
					Material[] array = (Material[])(object)new Material[sharedMaterials.Length];
					for (int i = 0; i < sharedMaterials.Length; i++)
					{
						array[i] = GetTintMaterial(sharedMaterials[i], valueOrDefault);
					}
					itemLook.Tinted.Add((item2, sharedMaterials));
					item2.sharedMaterials = array;
				}
			}
			return itemLook;
		}

		private static void ShowCustomModel(Equipment equipment, List<Renderer> pistolRenderers, CustomItem item, Mesh model, ItemLook look)
		{
			(GameObject model, MeshRenderer renderer) tuple = CreateFittedModel(((Component)equipment).transform, pistolRenderers, item, model, "in hand");
			GameObject item2 = tuple.model;
			MeshRenderer item3 = tuple.renderer;
			look.Model = item2;
			look.ModelRenderer = item3;
			foreach (Renderer pistolRenderer in pistolRenderers)
			{
				pistolRenderer.forceRenderingOff = true;
				look.Hidden.Add(pistolRenderer);
			}
		}

		internal static (GameObject model, MeshRenderer renderer) CreateFittedModel(Transform root, List<Renderer> pistolRenderers, CustomItem item, Mesh model, string where)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Expected O, but got Unknown
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			Bounds val = MeasureInLocalSpace(root, pistolRenderers);
			Bounds bounds = model.bounds;
			(int longest, int middle) tuple = LongestTwoAxes(((Bounds)(ref bounds)).size);
			int item2 = tuple.longest;
			int item3 = tuple.middle;
			(int longest, int middle) tuple2 = LongestTwoAxes(((Bounds)(ref val)).size);
			int item4 = tuple2.longest;
			int item5 = tuple2.middle;
			Quaternion val2 = Quaternion.LookRotation(AxisVector(item4), AxisVector(item5)) * Quaternion.Inverse(Quaternion.LookRotation(AxisVector(item2), AxisVector(item3))) * Quaternion.Euler(CustomItemModel.ParseVector(item.ModelRotation.Value));
			Vector3 val3 = RotatedSize(val2, ((Bounds)(ref bounds)).size);
			Vector3 size = ((Bounds)(ref val)).size;
			float num = ((Vector3)(ref size))[item4] / Mathf.Max(((Vector3)(ref val3))[item4], 0.0001f) * item.ModelScale.Value;
			Vector3 localPosition = ((Bounds)(ref val)).center - val2 * (((Bounds)(ref bounds)).center * num) + CustomItemModel.ParseVector(item.ModelOffset.Value);
			GameObject val4 = new GameObject(item.DisplayName + " Model");
			val4.layer = ((Component)pistolRenderers[0]).gameObject.layer;
			val4.transform.SetParent(root, false);
			val4.transform.localPosition = localPosition;
			val4.transform.localRotation = val2;
			val4.transform.localScale = Vector3.one * num;
			val4.AddComponent<MeshFilter>().sharedMesh = model;
			MeshRenderer val5 = val4.AddComponent<MeshRenderer>();
			((Renderer)val5).sharedMaterials = GetModelMaterials(item, LargestRenderer(pistolRenderers).sharedMaterial);
			Plugin.Log.LogInfo((object)$"{item}: custom model placed {where}. {item.BaseItem} size {((Bounds)(ref val)).size}, model size {((Bounds)(ref bounds)).size}, scale {num:0.###}.");
			return (model: val4, renderer: val5);
		}

		private static void Restore(Equipment equipment)
		{
			if (looks.TryGetValue(equipment, out ItemLook value))
			{
				UndoLook(value);
				looks.Remove(equipment);
			}
		}

		private static void UndoLook(ItemLook look)
		{
			foreach (var (val, sharedMaterials) in look.Tinted)
			{
				if ((Object)(object)val != (Object)null)
				{
					val.sharedMaterials = sharedMaterials;
				}
			}
			foreach (Renderer item in look.Hidden)
			{
				if ((Object)(object)item != (Object)null)
				{
					item.forceRenderingOff = false;
				}
			}
			if ((Object)(object)look.Model != (Object)null)
			{
				Object.Destroy((Object)(object)look.Model);
			}
		}

		private static Bounds MeasureInLocalSpace(Transform root, List<Renderer> renderers)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: 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_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: 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_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_0105: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			Bounds result = default(Bounds);
			MeshFilter val = default(MeshFilter);
			Vector3 val3 = default(Vector3);
			foreach (Renderer renderer in renderers)
			{
				Bounds bounds;
				if (renderer is MeshRenderer && ((Component)renderer).TryGetComponent<MeshFilter>(ref val) && (Object)(object)val.sharedMesh != (Object)null)
				{
					bounds = val.sharedMesh.bounds;
				}
				else
				{
					SkinnedMeshRenderer val2 = (SkinnedMeshRenderer)(object)((renderer is SkinnedMeshRenderer) ? renderer : null);
					if (val2 == null || !((Object)(object)val2.sharedMesh != (Object)null))
					{
						continue;
					}
					bounds = val2.sharedMesh.bounds;
				}
				Vector3 min = ((Bounds)(ref bounds)).min;
				Vector3 max = ((Bounds)(ref bounds)).max;
				for (int i = 0; i < 8; i++)
				{
					((Vector3)(ref val3))..ctor(((i & 1) == 0) ? min.x : max.x, ((i & 2) == 0) ? min.y : max.y, ((i & 4) == 0) ? min.z : max.z);
					Vector3 val4 = root.InverseTransformPoint(((Component)renderer).transform.TransformPoint(val3));
					if (!flag)
					{
						result = new Bounds(val4, Vector3.zero);
						flag = true;
					}
					else
					{
						((Bounds)(ref result)).Encapsulate(val4);
					}
				}
			}
			return result;
		}

		private static Renderer LargestRenderer(List<Renderer> renderers)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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)
			Renderer result = renderers[0];
			float num = -1f;
			foreach (Renderer renderer in renderers)
			{
				Bounds bounds = renderer.bounds;
				Vector3 size = ((Bounds)(ref bounds)).size;
				float num2 = size.x * size.y * size.z;
				if (num2 > num)
				{
					num = num2;
					result = renderer;
				}
			}
			return result;
		}

		private static (int longest, int middle) LongestTwoAxes(Vector3 size)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			int num = ((!(size.x >= size.y) || !(size.x >= size.z)) ? ((size.y >= size.z) ? 1 : 2) : 0);
			int num2 = (num + 1) % 3;
			int num3 = (num + 2) % 3;
			int item = ((((Vector3)(ref size))[num2] >= ((Vector3)(ref size))[num3]) ? num2 : num3);
			return (longest: num, middle: item);
		}

		private static Vector3 AxisVector(int axis)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return (Vector3)(axis switch
			{
				1 => Vector3.up, 
				0 => Vector3.right, 
				_ => Vector3.forward, 
			});
		}

		private static Vector3 RotatedSize(Quaternion rotation, Vector3 size)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: 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_0077: 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_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = rotation * new Vector3(size.x, 0f, 0f);
			Vector3 val2 = rotation * new Vector3(0f, size.y, 0f);
			Vector3 val3 = rotation * new Vector3(0f, 0f, size.z);
			return new Vector3(Mathf.Abs(val.x) + Mathf.Abs(val2.x) + Mathf.Abs(val3.x), Mathf.Abs(val.y) + Mathf.Abs(val2.y) + Mathf.Abs(val3.y), Mathf.Abs(val.z) + Mathf.Abs(val2.z) + Mathf.Abs(val3.z));
		}

		internal static Material GetTintMaterial(Material original, Color color)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)original == (Object)null)
			{
				return original;
			}
			if (tintMaterials.TryGetValue((original, color), out Material value))
			{
				return value;
			}
			value = new Material(original)
			{
				name = ((Object)original).name + " (Tinted)"
			};
			TintMaterial(value, original, color);
			tintMaterials[(original, color)] = value;
			return value;
		}

		private static Material[] GetModelMaterials(CustomItem item, Material pistolMaterial)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (modelMaterials.TryGetValue((item, pistolMaterial), out Material[] value))
			{
				return value;
			}
			List<ModelPart> parts = item.Model.Parts;
			Material[] array = (Material[])(object)new Material[parts.Count];
			List<string> list = new List<string>();
			for (int i = 0; i < parts.Count; i++)
			{
				array[i] = MakeModelMaterial(item, pistolMaterial, parts[i], i, list);
			}
			Shader shader = pistolMaterial.shader;
			List<string> list2 = new List<string>();
			for (int j = 0; j < shader.GetPropertyCount(); j++)
			{
				list2.Add($"{shader.GetPropertyName(j)} ({shader.GetPropertyType(j)})");
			}
			Plugin.Log.LogInfo((object)($"{item}: made {array.Length} model material(s) from '{((Object)pistolMaterial).name}' (shader '{((Object)shader).name}'), " + "tint " + ((item.TintModel.Value && item.TintColor.HasValue) ? "on" : "off") + ". Texture slots: " + ((list.Count > 0) ? string.Join(", ", list) : "none found") + ". Shader properties: " + string.Join(", ", list2)));
			modelMaterials[(item, pistolMaterial)] = array;
			return array;
		}

		private static Material MakeModelMaterial(CustomItem item, Material pistolMaterial, ModelPart part, int index, List<string> textureSlots)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_008f: 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_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			Material val = new Material(pistolMaterial)
			{
				name = $"{item.DisplayName} Model {index}"
			};
			Texture val2 = (Texture)(((Object)(object)part.Texture != (Object)null) ? ((object)part.Texture) : ((object)Texture2D.whiteTexture));
			string[] array = new string[5] { "_BaseMap", "_MainTex", "_BaseColorMap", "_AlbedoMap", "_Albedo" };
			foreach (string text in array)
			{
				if (val.HasProperty(text))
				{
					val.SetTexture(text, val2);
					val.SetTextureScale(text, Vector2.one);
					val.SetTextureOffset(text, Vector2.zero);
					if (index == 0)
					{
						textureSlots.Add(text);
					}
				}
			}
			if (item.TintModel.Value)
			{
				Color? tintColor = item.TintColor;
				if (tintColor.HasValue)
				{
					Color valueOrDefault = tintColor.GetValueOrDefault();
					TintMaterial(val, pistolMaterial, valueOrDefault);
					goto IL_0195;
				}
			}
			string[] array2 = new string[4] { "_BaseColor", "_Color", "_MainColor", "_Albedo" };
			foreach (string text2 in array2)
			{
				if (val.HasProperty(text2))
				{
					val.SetColor(text2, part.Color);
				}
			}
			string[] array3 = new string[2] { "_Tint", "_TintColor" };
			foreach (string text3 in array3)
			{
				if (val.HasProperty(text3))
				{
					val.SetColor(text3, Color.white);
				}
			}
			goto IL_0195;
			IL_0195:
			if (part.DoubleSided && val.HasProperty("_CullMode"))
			{
				val.SetFloat("_CullMode", 0f);
			}
			return val;
		}

		private static void TintMaterial(Material gold, Material original, Color color)
		{
			//IL_004c: 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)
			bool flag = false;
			string[] array = new string[6] { "_BaseColor", "_Color", "_MainColor", "_Tint", "_TintColor", "_Albedo" };
			foreach (string text in array)
			{
				if (gold.HasProperty(text))
				{
					gold.SetColor(text, color);
					flag = true;
				}
			}
			if (gold.HasProperty("_Metallic"))
			{
				gold.SetFloat("_Metallic", 0.8f);
			}
			if (gold.HasProperty("_Smoothness"))
			{
				gold.SetFloat("_Smoothness", 0.7f);
			}
			if (!flag && !loggedShaderInfo)
			{
				loggedShaderInfo = true;
				Shader shader = original.shader;
				List<string> list = new List<string>();
				for (int j = 0; j < shader.GetPropertyCount(); j++)
				{
					list.Add($"{shader.GetPropertyName(j)} ({shader.GetPropertyType(j)})");
				}
				Plugin.Log.LogWarning((object)("Shader '" + ((Object)shader).name + "' on material '" + ((Object)original).name + "' has no known color property, so the tint may not show. Properties: " + string.Join(", ", list)));
			}
		}
	}
	internal static class GltfLoader
	{
		private sealed class Reader
		{
			public JObject Root;

			public readonly List<byte[]> Buffers = new List<byte[]>();

			public string Folder = "";

			public string Label = "";

			public readonly List<Vector3> Positions = new List<Vector3>();

			public readonly List<Vector2> Uvs = new List<Vector2>();

			public readonly List<Vector3> Normals = new List<Vector3>();

			public bool MissingNormals;

			public int SkippedPrimitives;

			public readonly List<List<int>> Submeshes = new List<List<int>>();

			public readonly List<ModelPart> Parts = new List<ModelPart>();

			public readonly Dictionary<int, int> MaterialToPart = new Dictionary<int, int>();

			public readonly Dictionary<int, Texture2D?> ImageCache = new Dictionary<int, Texture2D>();

			public readonly Dictionary<(Texture2D?, Texture2D?, Color), Texture2D> MetalCache = new Dictionary<(Texture2D, Texture2D, Color), Texture2D>();

			public int TotalTriangles;

			public int MetalParts;
		}

		internal static Mesh Load(string path, string label, out List<ModelPart> parts)
		{
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			Reader reader = new Reader
			{
				Folder = (Path.GetDirectoryName(path) ?? ""),
				Label = label
			};
			byte[] array = File.ReadAllBytes(path);
			byte[] array2 = null;
			if (array.Length >= 12 && BitConverter.ToUInt32(array, 0) == 1179937895)
			{
				string text = null;
				int num;
				for (int i = 12; i + 8 <= array.Length; i += 8 + num)
				{
					num = BitConverter.ToInt32(array, i);
					switch (BitConverter.ToUInt32(array, i + 4))
					{
					case 1313821514u:
						text = Encoding.UTF8.GetString(array, i + 8, num);
						break;
					case 5130562u:
						array2 = new byte[num];
						Buffer.BlockCopy(array, i + 8, array2, 0, num);
						break;
					}
				}
				if (text == null)
				{
					throw new InvalidDataException("the .glb file has no JSON part");
				}
				reader.Root = JObject.Parse(text);
			}
			else
			{
				reader.Root = JObject.Parse(Encoding.UTF8.GetString(array));
			}
			JToken obj = reader.Root["extensionsRequired"];
			JArray val = (JArray)(object)((obj is JArray) ? obj : null);
			if (val != null)
			{
				foreach (JToken item in val)
				{
					string text2 = ((object)item).ToString();
					if (text2 == "KHR_draco_mesh_compression" || text2 == "EXT_meshopt_compression")
					{
						throw new InvalidDataException("the model is compressed (" + text2 + "). Open it in Blender and export it again with compression turned off.");
					}
				}
			}
			LoadBuffers(reader, array2);
			foreach (int item2 in RootNodes(reader))
			{
				AddNode(reader, item2, Matrix4x4.identity);
			}
			if (reader.TotalTriangles == 0)
			{
				throw new InvalidDataException("the file has no triangle meshes");
			}
			if (reader.SkippedPrimitives > 0)
			{
				Plugin.Log.LogWarning((object)$"{reader.Label}: skipped {reader.SkippedPrimitives} part(s) of the model that aren't made of triangles.");
			}
			if (reader.MetalParts > 0)
			{
				Plugin.Log.LogInfo((object)$"{reader.Label}: {reader.MetalParts} part(s) use a colored metal shine; baked it into their textures so the game's shader shows it.");
			}
			HashSet<Texture2D> hashSet = new HashSet<Texture2D>();
			foreach (ModelPart part in reader.Parts)
			{
				if ((Object)(object)part.Texture != (Object)null)
				{
					hashSet.Add(part.Texture);
				}
			}
			foreach (Texture2D value in reader.ImageCache.Values)
			{
				if ((Object)(object)value != (Object)null && !hashSet.Contains(value))
				{
					Object.Destroy((Object)(object)value);
				}
			}
			parts = reader.Parts;
			return CustomItemModel.BuildMesh(reader.Positions, reader.Uvs, reader.Normals, reader.Submeshes, !reader.MissingNormals);
		}

		private static void LoadBuffers(Reader r, byte[]? glbBinary)
		{
			JToken obj = r.Root["buffers"];
			JArray val = (JArray)(object)((obj is JArray) ? obj : null);
			if (val == null)
			{
				return;
			}
			foreach (JToken item in val)
			{
				string text = ((object)item[(object)"uri"])?.ToString();
				if (text == null)
				{
					r.Buffers.Add(glbBinary ?? throw new InvalidDataException("a buffer is missing its data"));
				}
				else
				{
					r.Buffers.Add(ReadUri(r, text));
				}
			}
		}

		private static byte[] ReadUri(Reader r, string uri)
		{
			if (uri.StartsWith("data:", StringComparison.Ordinal))
			{
				int num = uri.IndexOf(',');
				return Convert.FromBase64String(uri.Substring(num + 1));
			}
			string path = Path.Combine(r.Folder, Uri.UnescapeDataString(uri));
			if (!File.Exists(path))
			{
				throw new FileNotFoundException("the model needs the file '" + uri + "' next to it");
			}
			return File.ReadAllBytes(path);
		}

		private static IEnumerable<int> RootNodes(Reader r)
		{
			JToken obj = r.Root["scenes"];
			JArray val = (JArray)(object)((obj is JArray) ? obj : null);
			int num = GetInt((JToken?)(object)r.Root, "scene", 0);
			if (val != null && num < ((JContainer)val).Count)
			{
				JToken obj2 = val[num][(object)"nodes"];
				JArray val2 = (JArray)(object)((obj2 is JArray) ? obj2 : null);
				if (val2 != null)
				{
					foreach (JToken item in val2)
					{
						yield return item.ToObject<int>();
					}
					yield break;
				}
			}
			JToken val3 = r.Root["nodes"];
			JArray nodes = (JArray)(object)((val3 is JArray) ? val3 : null);
			if (nodes == null)
			{
				yield break;
			}
			HashSet<int> children = new HashSet<int>();
			foreach (JToken item2 in nodes)
			{
				JToken obj3 = item2[(object)"children"];
				JArray val4 = (JArray)(object)((obj3 is JArray) ? obj3 : null);
				if (val4 == null)
				{
					continue;
				}
				foreach (JToken item3 in val4)
				{
					children.Add(item3.ToObject<int>());
				}
			}
			for (int i = 0; i < ((JContainer)nodes).Count; i++)
			{
				if (!children.Contains(i))
				{
					yield return i;
				}
			}
		}

		private static void AddNode(Reader r, int nodeIndex, Matrix4x4 parent)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			JToken obj = r.Root["nodes"];
			JArray val = (JArray)(object)((obj is JArray) ? obj : null);
			if (val == null || nodeIndex < 0 || nodeIndex >= ((JContainer)val).Count)
			{
				return;
			}
			JToken val2 = val[nodeIndex];
			Matrix4x4 val3 = parent * LocalMatrix(val2);
			int num = GetInt(val2, "mesh", -1);
			if (num >= 0)
			{
				AddMesh(r, num, val3);
			}
			JToken obj2 = val2[(object)"children"];
			JArray val4 = (JArray)(object)((obj2 is JArray) ? obj2 : null);
			if (val4 == null)
			{
				return;
			}
			foreach (JToken item in val4)
			{
				AddNode(r, item.ToObject<int>(), val3);
			}
		}

		private static Matrix4x4 LocalMatrix(JToken node)
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			JToken val = node[(object)"matrix"];
			JArray m = (JArray)(object)((val is JArray) ? val : null);
			if