Decompiled source of Magic Supremacy v2.1.8

plugins/Magic_Supremacy.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using LocalizationManager;
using Magic_Supremacy;
using Microsoft.CodeAnalysis;
using PieceManager;
using ServerSync;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.BufferedDeserialization;
using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: AssemblyFileVersion("2.1.8")]
[assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyProduct("Magic_Supremacy")]
[assembly: AssemblyCompany("Dreanegade")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("Magic_Supremacy")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.1.8.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<89859f32-1e98-4d16-b4ea-ae4ec592e756>Embedded]
	internal sealed class <89859f32-1e98-4d16-b4ea-ae4ec592e756>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<89859f32-1e98-4d16-b4ea-ae4ec592e756>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <5b0afac3-e875-42b6-8a29-598d3c134504>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <5b0afac3-e875-42b6-8a29-598d3c134504>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <5b0afac3-e875-42b6-8a29-598d3c134504>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<89859f32-1e98-4d16-b4ea-ae4ec592e756>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
internal sealed class ConfigurationManagerAttributes
{
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)]
	public delegate void CustomHotkeyDrawerFunc(ConfigEntryBase setting, ref bool isCurrentlyAcceptingInput);

	public bool? ShowRangeAsPercent;

	public Action<ConfigEntryBase> CustomDrawer;

	public CustomHotkeyDrawerFunc CustomHotkeyDrawer;

	public bool? Browsable;

	public string Category;

	public object DefaultValue;

	public bool? HideDefaultButton;

	public bool? HideSettingName;

	public string Description;

	public string DispName;

	public int? Order;

	public bool? ReadOnly;

	public bool? IsAdvanced;

	public Func<object, string> ObjToStr;

	public Func<string, object> StrToObj;
}
[HarmonyPatch]
[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
public static class LivingContainerSpawner
{
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	private class LivingContainerDef
	{
		public string Prefab;

		public Biome Biomes;

		public float CheckInterval;

		public float SpawnChance;

		public int MaxInWorld;

		public float MinDistance;

		public float MaxDistance;

		public float MinAltitude;

		public float MaxAltitude;

		public bool AllowInWater;

		public int MaxSpawnAttempts;

		public float DestroyDelay;

		public string VfxPrefab;

		public string PinSprite;

		public string PinText;

		public bool PinAnimate;

		public bool PinDoubleSize;
	}

	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)]
	private struct PrefabContainerTuning
	{
		public int Width;

		public int Height;

		public int LootMin;

		public int LootMax;

		public bool Equals(PrefabContainerTuning other)
		{
			if (Width == other.Width && Height == other.Height && LootMin == other.LootMin)
			{
				return LootMax == other.LootMax;
			}
			return false;
		}
	}

	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	private class LivingContainerPinComponent : MonoBehaviour
	{
		public string PinSprite;

		public string PinText;

		public bool PinAnimate;

		public bool PinDoubleSize;

		private PinData Pin;

		private void Update()
		{
			//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)
			if (!LivingContainerConfig.IsRikoEnabled())
			{
				if (Pin != null && (Object)(object)Minimap.instance != (Object)null)
				{
					Minimap.instance.RemovePin(Pin);
					Pin = null;
				}
				Object.Destroy((Object)(object)this);
			}
			else if (Pin != null)
			{
				Pin.m_pos = ((Component)this).transform.position;
			}
			else
			{
				TryCreatePin();
			}
		}

		private void TryCreatePin()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			if (!string.IsNullOrEmpty(PinSprite) && !((Object)(object)Minimap.instance == (Object)null) && Magic_SupremacyPlugin.PinSprites != null && Magic_SupremacyPlugin.PinSprites.TryGetValue(PinSprite, out var value) && !((Object)(object)value == (Object)null))
			{
				PinData val = Minimap.instance.AddPin(((Component)this).transform.position, (PinType)8, PinText ?? "", false, false, 0L, default(PlatformUserID));
				val.m_icon = value;
				val.m_animate = PinAnimate;
				val.m_doubleSize = PinDoubleSize;
				Pin = val;
			}
		}

		private void OnDestroy()
		{
			if (Pin != null && (Object)(object)Minimap.instance != (Object)null)
			{
				Minimap.instance.RemovePin(Pin);
			}
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "Hide")]
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	private static class InventoryGui_Hide_Patch
	{
		private static void Prefix(InventoryGui __instance, out Container __state)
		{
			__state = (((Object)(object)__instance != (Object)null) ? __instance.m_currentContainer : null);
		}

		private static void Postfix(Container __state)
		{
			if ((Object)(object)__state != (Object)null)
			{
				HandleContainerClosed(__state);
			}
		}
	}

	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)]
	private class RikoSpawnStabilizer : MonoBehaviour
	{
		private bool _started;

		public void Init()
		{
			if (!_started)
			{
				_started = true;
				((MonoBehaviour)this).StartCoroutine(StabilizeRoutine());
			}
		}

		[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
		private IEnumerator StabilizeRoutine()
		{
			StabilizeOnce(((Component)this).gameObject);
			yield return null;
			StabilizeOnce(((Component)this).gameObject);
			yield return (object)new WaitForSeconds(0.35f);
			StabilizeOnce(((Component)this).gameObject);
		}
	}

	private static readonly LivingContainerDef[] Defs = new LivingContainerDef[6]
	{
		new LivingContainerDef
		{
			Prefab = "EncounterCreatureRikoBlackforestDO",
			Biomes = (Biome)8,
			CheckInterval = 360f,
			SpawnChance = 0.3f,
			MaxInWorld = 3,
			MinDistance = 18f,
			MaxDistance = 36f,
			MinAltitude = 0f,
			MaxAltitude = 2000f,
			AllowInWater = false,
			MaxSpawnAttempts = 15,
			DestroyDelay = 0.6f,
			VfxPrefab = "fx_riko_disappear_DO",
			PinSprite = "PinRikoDO",
			PinText = "",
			PinAnimate = false,
			PinDoubleSize = true
		},
		new LivingContainerDef
		{
			Prefab = "EncounterCreatureRikoSwampDO",
			Biomes = (Biome)2,
			CheckInterval = 360f,
			SpawnChance = 0.3f,
			MaxInWorld = 3,
			MinDistance = 18f,
			MaxDistance = 36f,
			MinAltitude = -1f,
			MaxAltitude = 2000f,
			AllowInWater = false,
			MaxSpawnAttempts = 18,
			DestroyDelay = 0.6f,
			VfxPrefab = "fx_riko_disappear_DO",
			PinSprite = "PinRikoDO",
			PinText = "",
			PinAnimate = false,
			PinDoubleSize = true
		},
		new LivingContainerDef
		{
			Prefab = "EncounterCreatureRikoMountainDO",
			Biomes = (Biome)4,
			CheckInterval = 360f,
			SpawnChance = 0.3f,
			MaxInWorld = 3,
			MinDistance = 18f,
			MaxDistance = 36f,
			MinAltitude = 10f,
			MaxAltitude = 2000f,
			AllowInWater = false,
			MaxSpawnAttempts = 15,
			DestroyDelay = 0.6f,
			VfxPrefab = "fx_riko_disappear_DO",
			PinSprite = "PinRikoDO",
			PinText = "",
			PinAnimate = false,
			PinDoubleSize = true
		},
		new LivingContainerDef
		{
			Prefab = "EncounterCreatureRikoPlainsDO",
			Biomes = (Biome)16,
			CheckInterval = 360f,
			SpawnChance = 0.3f,
			MaxInWorld = 3,
			MinDistance = 18f,
			MaxDistance = 36f,
			MinAltitude = 0f,
			MaxAltitude = 2000f,
			AllowInWater = false,
			MaxSpawnAttempts = 15,
			DestroyDelay = 0.6f,
			VfxPrefab = "fx_riko_disappear_DO",
			PinSprite = "PinRikoDO",
			PinText = "",
			PinAnimate = false,
			PinDoubleSize = true
		},
		new LivingContainerDef
		{
			Prefab = "EncounterCreatureRikoMistlandsDO",
			Biomes = (Biome)512,
			CheckInterval = 360f,
			SpawnChance = 0.3f,
			MaxInWorld = 3,
			MinDistance = 15f,
			MaxDistance = 40f,
			MinAltitude = 12f,
			MaxAltitude = 2000f,
			AllowInWater = false,
			MaxSpawnAttempts = 18,
			DestroyDelay = 0.6f,
			VfxPrefab = "fx_riko_disappear_DO",
			PinSprite = "PinRikoDO",
			PinText = "",
			PinAnimate = false,
			PinDoubleSize = true
		},
		new LivingContainerDef
		{
			Prefab = "EncounterCreatureRikoAshlandsDO",
			Biomes = (Biome)32,
			CheckInterval = 360f,
			SpawnChance = 0.3f,
			MaxInWorld = 3,
			MinDistance = 18f,
			MaxDistance = 36f,
			MinAltitude = 0f,
			MaxAltitude = 2000f,
			AllowInWater = false,
			MaxSpawnAttempts = 15,
			DestroyDelay = 0.6f,
			VfxPrefab = "fx_riko_disappear_DO",
			PinSprite = "PinRikoDO",
			PinText = "",
			PinAnimate = false,
			PinDoubleSize = true
		}
	};

	private static readonly Dictionary<long, float[]> NextCheckByPlayer = new Dictionary<long, float[]>();

	private static readonly Dictionary<long, float> LastUpdateByPlayer = new Dictionary<long, float>();

	private static readonly Dictionary<string, int> WorldCounts = new Dictionary<string, int>();

	private static readonly Dictionary<string, LivingContainerDef> DefByPrefab = new Dictionary<string, LivingContainerDef>();

	private static float NextWorldScanTime;

	private static readonly Dictionary<string, PrefabContainerTuning> AppliedPrefabTuning = new Dictionary<string, PrefabContainerTuning>();

	private static readonly int SolidMask = LayerMask.GetMask(new string[3] { "terrain", "static_solid", "Default" });

	private static readonly int WaterMask = LayerMask.GetMask(new string[2] { "WaterVolume", "Water" });

	private const float MaxAllowedWaterDepth = 0.3f;

	[HarmonyPatch(typeof(ZoneSystem), "Update")]
	[HarmonyPostfix]
	private static void ZoneSystem_Update_Postfix()
	{
		//IL_0113: 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_011d: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || (Object)(object)ZNetScene.instance == (Object)null || !LivingContainerConfig.IsRikoEnabled())
		{
			return;
		}
		BuildDefCache();
		RefreshDefsFromConfig();
		EnsureWorldCounts();
		List<Player> allPlayers = Player.GetAllPlayers();
		if (allPlayers == null || allPlayers.Count == 0)
		{
			return;
		}
		float time = Time.time;
		foreach (Player item in allPlayers)
		{
			if ((Object)(object)item == (Object)null)
			{
				continue;
			}
			ZNetView component = ((Component)item).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				continue;
			}
			ZDO zDO = component.GetZDO();
			if (zDO == null)
			{
				continue;
			}
			long num = ((ZDOID)(ref zDO.m_uid)).ID;
			if (num == 0L)
			{
				continue;
			}
			float[] checks = GetChecks(num);
			if (!LastUpdateByPlayer.TryGetValue(num, out var value))
			{
				value = time;
			}
			float num2 = time - value;
			if (num2 < 0f)
			{
				num2 = 0f;
			}
			if (num2 > 2f)
			{
				num2 = 2f;
			}
			LastUpdateByPlayer[num] = time;
			Biome val = Heightmap.FindBiome(((Component)item).transform.position);
			for (int i = 0; i < Defs.Length; i++)
			{
				LivingContainerDef livingContainerDef = Defs[i];
				if ((val & livingContainerDef.Biomes) != 0)
				{
					checks[i] -= num2;
					if (!(checks[i] > 0f))
					{
						TrySpawn(item, livingContainerDef);
						float num3 = Mathf.Max(1f, livingContainerDef.CheckInterval);
						checks[i] = num3;
					}
				}
			}
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(ZNetView), "Awake")]
	private static void ZNetView_Awake_Postfix(ZNetView __instance)
	{
		if (!LivingContainerConfig.IsRikoEnabled() || (Object)(object)__instance == (Object)null)
		{
			return;
		}
		GameObject gameObject = ((Component)__instance).gameObject;
		if (!((Object)(object)gameObject == (Object)null))
		{
			BuildDefCache();
			string prefabName = Utils.GetPrefabName(((Object)gameObject).name);
			if (DefByPrefab.TryGetValue(prefabName, out var value))
			{
				AttachPinComponent(gameObject, value);
			}
		}
	}

	private static void TrySpawn(Player player, LivingContainerDef def)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: 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_0120: 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)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		Vector3 position = ((Component)player).transform.position;
		if ((Heightmap.FindBiome(position) & def.Biomes) == 0 || Random.value > def.SpawnChance || (WorldCounts.TryGetValue(def.Prefab, out var value) && value >= def.MaxInWorld))
		{
			return;
		}
		GameObject prefab = ZNetScene.instance.GetPrefab(def.Prefab);
		if ((Object)(object)prefab == (Object)null)
		{
			return;
		}
		ApplyContainerConfigToPrefab(def, prefab);
		for (int i = 0; i < def.MaxSpawnAttempts; i++)
		{
			if (!TryGetGround(PickPoint(position, def.MinDistance, def.MaxDistance), out var g, out var water) || (!def.AllowInWater && water) || (Heightmap.FindBiome(g) & def.Biomes) == 0)
			{
				continue;
			}
			if ((def.Biomes & 0x20) != 0)
			{
				Heightmap val = Heightmap.FindHeightmap(g);
				if ((Object)(object)val != (Object)null && val.IsLava(g, 0.4f))
				{
					continue;
				}
			}
			if (g.y < def.MinAltitude || g.y > def.MaxAltitude)
			{
				continue;
			}
			Quaternion val2 = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f);
			GameObject val3 = Object.Instantiate<GameObject>(prefab, g, val2);
			if (!((Object)(object)val3 == (Object)null))
			{
				FixSpawnInsideGeometry(val3);
				Container component = val3.GetComponent<Container>();
				if ((Object)(object)component != (Object)null)
				{
					component.m_autoDestroyEmpty = false;
				}
				AttachPinComponent(val3, def);
				WorldCounts[def.Prefab] = value + 1;
			}
			break;
		}
	}

	private static void ApplyContainerConfigToPrefab(LivingContainerDef def, GameObject prefab)
	{
		if (def == null || (Object)(object)prefab == (Object)null || !LivingContainerConfig.RikoConfigs.TryGetValue(GetRikoId(def), out var value))
		{
			return;
		}
		Container component = prefab.GetComponent<Container>();
		if ((Object)(object)component == (Object)null)
		{
			return;
		}
		PrefabContainerTuning prefabContainerTuning = default(PrefabContainerTuning);
		prefabContainerTuning.Width = Mathf.Max(1, value.ContainerWidth.Value);
		prefabContainerTuning.Height = Mathf.Max(1, value.ContainerHeight.Value);
		prefabContainerTuning.LootMin = Mathf.Max(0, value.ContainerLootMin.Value);
		prefabContainerTuning.LootMax = Mathf.Max(0, value.ContainerLootMax.Value);
		PrefabContainerTuning prefabContainerTuning2 = prefabContainerTuning;
		if (prefabContainerTuning2.LootMax < prefabContainerTuning2.LootMin)
		{
			prefabContainerTuning2.LootMax = prefabContainerTuning2.LootMin;
		}
		if (!AppliedPrefabTuning.TryGetValue(def.Prefab, out var value2) || !value2.Equals(prefabContainerTuning2))
		{
			component.m_width = prefabContainerTuning2.Width;
			component.m_height = prefabContainerTuning2.Height;
			if (component.m_defaultItems != null)
			{
				component.m_defaultItems.m_dropMin = prefabContainerTuning2.LootMin;
				component.m_defaultItems.m_dropMax = prefabContainerTuning2.LootMax;
			}
			AppliedPrefabTuning[def.Prefab] = prefabContainerTuning2;
		}
	}

	private static void AttachPinComponent(GameObject go, LivingContainerDef def)
	{
		if (!((Object)(object)go == (Object)null) && def != null && !string.IsNullOrEmpty(def.PinSprite))
		{
			LivingContainerPinComponent livingContainerPinComponent = go.GetComponent<LivingContainerPinComponent>();
			if ((Object)(object)livingContainerPinComponent == (Object)null)
			{
				livingContainerPinComponent = go.AddComponent<LivingContainerPinComponent>();
			}
			livingContainerPinComponent.PinSprite = def.PinSprite;
			livingContainerPinComponent.PinText = def.PinText ?? "";
			livingContainerPinComponent.PinAnimate = def.PinAnimate;
			livingContainerPinComponent.PinDoubleSize = def.PinDoubleSize;
		}
	}

	private static void HandleContainerClosed(Container container)
	{
		if ((Object)(object)container == (Object)null)
		{
			return;
		}
		BuildDefCache();
		GameObject gameObject = ((Component)container).gameObject;
		if ((Object)(object)gameObject == (Object)null)
		{
			return;
		}
		string prefabName = Utils.GetPrefabName(((Object)gameObject).name);
		if (!DefByPrefab.TryGetValue(prefabName, out var value))
		{
			return;
		}
		ZNetView component = gameObject.GetComponent<ZNetView>();
		if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner())
		{
			return;
		}
		Inventory inventory = container.GetInventory();
		if (inventory != null && inventory.NrOfItems() == 0)
		{
			if (value.DestroyDelay <= 0f)
			{
				SpawnVfx(value, gameObject);
				component.Destroy();
			}
			else
			{
				((MonoBehaviour)container).StartCoroutine(DestroyAfterDelay(value, gameObject, component));
			}
		}
	}

	private static IEnumerator DestroyAfterDelay(LivingContainerDef def, GameObject go, ZNetView nview)
	{
		SpawnVfx(def, go);
		yield return (object)new WaitForSeconds(def.DestroyDelay);
		if ((Object)(object)nview != (Object)null && nview.IsValid() && nview.IsOwner())
		{
			nview.Destroy();
		}
	}

	private static void SpawnVfx(LivingContainerDef def, GameObject go)
	{
		//IL_003d: 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)
		if (!string.IsNullOrEmpty(def.VfxPrefab) && !((Object)(object)ZNetScene.instance == (Object)null))
		{
			GameObject prefab = ZNetScene.instance.GetPrefab(def.VfxPrefab);
			if ((Object)(object)prefab != (Object)null)
			{
				Object.Instantiate<GameObject>(prefab, go.transform.position, go.transform.rotation);
			}
		}
	}

	private static void FixSpawnInsideGeometry(GameObject go)
	{
		if (!((Object)(object)go == (Object)null))
		{
			RikoSpawnStabilizer rikoSpawnStabilizer = go.GetComponent<RikoSpawnStabilizer>();
			if ((Object)(object)rikoSpawnStabilizer == (Object)null)
			{
				rikoSpawnStabilizer = go.AddComponent<RikoSpawnStabilizer>();
			}
			rikoSpawnStabilizer.Init();
		}
	}

	private static void StabilizeOnce(GameObject go)
	{
		//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_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: 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_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_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c3: 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_00d2: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)go == (Object)null))
		{
			Vector3 position = go.transform.position;
			go.transform.position = position + Vector3.up * 0.35f;
			if (TryFindDrySolidBelow(go.transform.position + Vector3.up * 0.25f, 8f, out var ground))
			{
				go.transform.position = ground + Vector3.up * 0.03f;
			}
			else
			{
				go.transform.position = position + Vector3.up * 0.1f;
			}
			if (IsBodyOverlapping(go.transform.position))
			{
				Transform transform = go.transform;
				transform.position += Vector3.up * 0.6f;
			}
		}
	}

	private static bool TryFindDrySolidBelow(Vector3 origin, float maxDist, out Vector3 ground)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: 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_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_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		ground = origin;
		RaycastHit[] array = Physics.RaycastAll(origin, Vector3.down, maxDist, SolidMask, (QueryTriggerInteraction)1);
		if (array == null || array.Length == 0)
		{
			return false;
		}
		Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance));
		RaycastHit[] array2 = array;
		for (int i = 0; i < array2.Length; i++)
		{
			RaycastHit val = array2[i];
			if (!((Object)(object)((RaycastHit)(ref val)).collider == (Object)null) && !((RaycastHit)(ref val)).collider.isTrigger)
			{
				Vector3 val2 = ((RaycastHit)(ref val)).point + ((RaycastHit)(ref val)).normal * 0.02f;
				if (!IsPointInWater(val2))
				{
					ground = val2;
					return true;
				}
			}
		}
		return false;
	}

	private static bool IsPointInWater(Vector3 p)
	{
		//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_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)
		return Physics.CheckSphere(p + Vector3.up * 0.1f, 0.35f, WaterMask, (QueryTriggerInteraction)1);
	}

	private static bool IsBodyOverlapping(Vector3 basePos)
	{
		//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_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_0015: 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_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_002a: 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)
		Vector3 val = basePos + Vector3.up * 0.25f;
		Vector3 val2 = basePos + Vector3.up * 1.05f;
		float num = 0.2f;
		return Physics.CheckCapsule(val, val2, num, SolidMask, (QueryTriggerInteraction)1);
	}

	private static float[] GetChecks(long pid)
	{
		if (!NextCheckByPlayer.TryGetValue(pid, out var value) || value.Length != Defs.Length)
		{
			value = new float[Defs.Length];
			for (int i = 0; i < value.Length; i++)
			{
				float num = Mathf.Max(1f, Defs[i].CheckInterval);
				value[i] = Random.Range(0f, num);
			}
			NextCheckByPlayer[pid] = value;
		}
		return value;
	}

	private static Vector3 PickPoint(Vector3 o, float min, float max)
	{
		//IL_0008: 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_0010: 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_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: 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_0042: Unknown result type (might be due to invalid IL or missing references)
		float num = Random.Range(min, max);
		Vector2 insideUnitCircle = Random.insideUnitCircle;
		Vector2 val = ((Vector2)(ref insideUnitCircle)).normalized * num;
		return new Vector3(o.x + val.x, o.y + 2f, o.z + val.y);
	}

	private static bool IsTooDeepInWater(Vector3 groundPoint, float maxAllowedDepth)
	{
		//IL_003f: 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_0046: 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_005a: 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_006e: 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_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		List<WaterVolume> instances = WaterVolume.Instances;
		if (instances == null || instances.Count == 0)
		{
			return false;
		}
		for (int i = 0; i < instances.Count; i++)
		{
			WaterVolume val = instances[i];
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			Collider component = ((Component)val).GetComponent<Collider>();
			if (!((Object)(object)component == (Object)null))
			{
				Bounds bounds = component.bounds;
				if (!(groundPoint.x < ((Bounds)(ref bounds)).min.x) && !(groundPoint.x > ((Bounds)(ref bounds)).max.x) && !(groundPoint.z < ((Bounds)(ref bounds)).min.z) && !(groundPoint.z > ((Bounds)(ref bounds)).max.z) && val.GetWaterSurface(groundPoint, 1f) - groundPoint.y > maxAllowedDepth)
				{
					return true;
				}
			}
		}
		return false;
	}

	private static bool IsInsideWaterVolume(Vector3 point)
	{
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		List<WaterVolume> instances = WaterVolume.Instances;
		if (instances == null)
		{
			return false;
		}
		for (int i = 0; i < instances.Count; i++)
		{
			WaterVolume val = instances[i];
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			Collider component = ((Component)val).GetComponent<Collider>();
			if (!((Object)(object)component == (Object)null))
			{
				Bounds bounds = component.bounds;
				if (((Bounds)(ref bounds)).Contains(point))
				{
					return true;
				}
			}
		}
		return false;
	}

	private static bool TryGetGround(Vector3 p, out Vector3 g, out bool water)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: 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_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: 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_00ab: Unknown result type (might be due to invalid IL or missing references)
		g = p;
		water = false;
		RaycastHit val = default(RaycastHit);
		if (!Physics.Raycast(p + Vector3.up * 200f, Vector3.down, ref val, 500f))
		{
			return false;
		}
		g = ((RaycastHit)(ref val)).point;
		Heightmap val2 = Heightmap.FindHeightmap(g);
		bool flag = ((((Object)(object)val2 != (Object)null) ? ((int)val2.GetBiome(g, 0.02f, false)) : 0) & 2) != 0;
		if (!flag && IsInsideWaterVolume(g))
		{
			water = true;
			return false;
		}
		if ((Object)(object)val2 != (Object)null && val2.GetOceanDepth(g) > 0.5f)
		{
			water = true;
			return false;
		}
		if (!flag && IsTooDeepInWater(g, 0.3f))
		{
			water = true;
			return false;
		}
		return true;
	}

	private static void EnsureWorldCounts()
	{
		if (Time.time < NextWorldScanTime)
		{
			return;
		}
		NextWorldScanTime = Time.time + 10f;
		WorldCounts.Clear();
		ZNetView[] array = Object.FindObjectsOfType<ZNetView>();
		for (int i = 0; i < array.Length; i++)
		{
			string prefabName = Utils.GetPrefabName(((Object)((Component)array[i]).gameObject).name);
			if (DefByPrefab.ContainsKey(prefabName))
			{
				WorldCounts[prefabName] = ((!WorldCounts.TryGetValue(prefabName, out var value)) ? 1 : (value + 1));
			}
		}
	}

	private static void BuildDefCache()
	{
		if (DefByPrefab.Count <= 0)
		{
			LivingContainerDef[] defs = Defs;
			foreach (LivingContainerDef livingContainerDef in defs)
			{
				ApplyConfig(livingContainerDef);
				DefByPrefab[livingContainerDef.Prefab] = livingContainerDef;
			}
		}
	}

	private static void RefreshDefsFromConfig()
	{
		for (int i = 0; i < Defs.Length; i++)
		{
			ApplyConfig(Defs[i]);
		}
	}

	private static void ApplyConfig(LivingContainerDef def)
	{
		if (def != null && LivingContainerConfig.RikoConfigs.TryGetValue(GetRikoId(def), out var value))
		{
			def.CheckInterval = Mathf.Max(1f, value.CheckInterval.Value);
			def.SpawnChance = Mathf.Clamp01(value.SpawnChance.Value);
			def.MaxInWorld = Mathf.Max(0, value.MaxInWorld.Value);
			def.MinDistance = Mathf.Max(0f, value.MinDistance.Value);
			def.MaxDistance = Mathf.Max(def.MinDistance, value.MaxDistance.Value);
			def.MinAltitude = value.MinAltitude.Value;
			def.MaxAltitude = Mathf.Max(def.MinAltitude, value.MaxAltitude.Value);
		}
	}

	private static string GetRikoId(LivingContainerDef def)
	{
		string prefab = def.Prefab;
		if (!prefab.StartsWith("EncounterCreatureRiko") || !prefab.EndsWith("DO"))
		{
			return prefab;
		}
		return prefab.Substring("EncounterCreatureRiko".Length, prefab.Length - "EncounterCreatureRiko".Length - "DO".Length);
	}
}
[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
public static class ExtraStats
{
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)]
	public enum ExtraStatType
	{
		Health,
		Stamina,
		Eitr
	}

	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)]
	public enum ExtraSourceType
	{
		ItemDrop,
		StatusEffect
	}

	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	public class ExtraStatEntry
	{
		public string PrefabName;

		public ExtraStatType StatType;

		public float Value;

		public ExtraSourceType SourceType;

		public ExtraStatEntry(string prefab, ExtraStatType stat, float value, ExtraSourceType source)
		{
			PrefabName = prefab;
			StatType = stat;
			Value = value;
			SourceType = source;
		}
	}

	[HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)]
	public static class Player_GetTotalFoodValue_ExtraStatsPatch
	{
		[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
		private static void Postfix(Player __instance, ref float hp, ref float stamina, ref float eitr)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			float num = 0f;
			float num2 = 0f;
			float num3 = 0f;
			try
			{
				Inventory inventory = ((Humanoid)__instance).GetInventory();
				if (inventory != null)
				{
					foreach (ItemData equippedItem in inventory.GetEquippedItems())
					{
						if (equippedItem != null && !((Object)(object)equippedItem.m_dropPrefab == (Object)null))
						{
							string name = ((Object)equippedItem.m_dropPrefab).name;
							float extraHp = 0f;
							float extraStamina = 0f;
							float extraEitr = 0f;
							GetItemDropBonusesForPrefab(name, out extraHp, out extraStamina, out extraEitr);
							if (extraHp != 0f || extraStamina != 0f || extraEitr != 0f)
							{
								num += extraHp;
								num2 += extraStamina;
								num3 += extraEitr;
								LogInfo($"ItemDrop matched for stats: {name} → +HP {extraHp}, +Stamina {extraStamina}, +Eitr {extraEitr}");
							}
						}
					}
				}
				if (((Character)__instance).m_seman != null && ((Character)__instance).m_seman.m_statusEffects != null)
				{
					foreach (StatusEffect statusEffect in ((Character)__instance).m_seman.m_statusEffects)
					{
						if (!((Object)(object)statusEffect == (Object)null))
						{
							string name2 = ((Object)statusEffect).name;
							float extraHp2 = 0f;
							float extraStamina2 = 0f;
							float extraEitr2 = 0f;
							GetStatusEffectBonuses(name2, out extraHp2, out extraStamina2, out extraEitr2);
							if (extraHp2 != 0f || extraStamina2 != 0f || extraEitr2 != 0f)
							{
								num += extraHp2;
								num2 += extraStamina2;
								num3 += extraEitr2;
								string prefabName = Utils.GetPrefabName(name2);
								LogInfo($"StatusEffect matched for stats: {name2} (clean={prefabName}) → +HP {extraHp2}, +Stamina {extraStamina2}, +Eitr {extraEitr2}");
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				LogError("Exception in ExtraStats Player.GetTotalFoodValue Postfix: " + ex);
			}
			if (num != 0f || num2 != 0f || num3 != 0f)
			{
				LogInfo($"Total bonuses applied to player: +HP {num}, +Stamina {num2}, +Eitr {num3}");
				hp += num;
				stamina += num2;
				eitr += num3;
			}
		}
	}

	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	[HarmonyPatch]
	public static class ItemData_StaticGetTooltip_ExtraStatsPatch
	{
		private static MethodBase TargetMethod()
		{
			return AccessTools.Method(typeof(ItemData), "GetTooltip", new Type[5]
			{
				typeof(ItemData),
				typeof(int),
				typeof(bool),
				typeof(float),
				typeof(int)
			}, (Type[])null);
		}

		private static void Postfix(ItemData item, int qualityLevel, bool crafting, float worldLevel, int stackOverride, ref string __result)
		{
			try
			{
				if (item == null || (Object)(object)item.m_dropPrefab == (Object)null)
				{
					return;
				}
				string name = ((Object)item.m_dropPrefab).name;
				LogInfo($"[TooltipPatch] Static GetTooltip Postfix called for {name}, q={qualityLevel}, crafting={crafting}, worldLevel={worldLevel}, stackOverride={stackOverride}");
				GetItemDropBonusesForPrefab(name, out var extraHp, out var extraStamina, out var extraEitr);
				if (extraHp != 0f || extraStamina != 0f || extraEitr != 0f)
				{
					string text = BuildExtraStatsTooltipBlock(extraHp, extraStamina, extraEitr);
					if (!string.IsNullOrEmpty(text))
					{
						LogInfo($"[TooltipPatch] Appending extras for {name}: HP {extraHp}, Stamina {extraStamina}, Eitr {extraEitr}");
						__result += text;
					}
				}
			}
			catch (Exception ex)
			{
				LogError("Exception in ItemData_StaticGetTooltip_ExtraStatsPatch: " + ex);
			}
		}
	}

	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)]
	[HarmonyPatch(typeof(SE_Stats), "GetTooltipString")]
	public static class SE_Stats_GetTooltipString_ExtraStatsPatch
	{
		[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
		private static void Postfix(SE_Stats __instance, ref string __result)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null)
				{
					return;
				}
				string name = ((Object)__instance).name;
				string prefabName = Utils.GetPrefabName(name);
				LogInfo("[SE TooltipPatch] GetTooltipString for " + name + " (clean=" + prefabName + ")");
				GetStatusEffectBonuses(name, out var extraHp, out var extraStamina, out var extraEitr);
				if (extraHp != 0f || extraStamina != 0f || extraEitr != 0f)
				{
					string text = BuildExtraStatsTooltipBlock(extraHp, extraStamina, extraEitr);
					if (!string.IsNullOrEmpty(text))
					{
						LogInfo($"[SE TooltipPatch] Appending extras for {name} (clean={prefabName}): HP {extraHp}, Stamina {extraStamina}, Eitr {extraEitr}");
						__result += text;
					}
				}
			}
			catch (Exception ex)
			{
				LogError("Exception in SE_Stats_GetTooltipString_ExtraStatsPatch: " + ex);
			}
		}
	}

	public static bool DEBUG = false;

	public static readonly List<ExtraStatEntry> ExtraStatsConfig = new List<ExtraStatEntry>
	{
		new ExtraStatEntry("SE_BloodcallerArmor_DO", ExtraStatType.Health, 50f, ExtraSourceType.StatusEffect),
		new ExtraStatEntry("ArmorBloodcallerCapeDO", ExtraStatType.Health, 30f, ExtraSourceType.ItemDrop)
	};

	private static void LogInfo(string msg)
	{
		if (DEBUG)
		{
			Debug.Log((object)("[ExtraStats] " + msg));
		}
	}

	private static void LogError(string msg)
	{
		if (DEBUG)
		{
			Debug.LogError((object)("[ExtraStats] " + msg));
		}
	}

	private static void GetItemDropBonusesForPrefab(string prefabName, out float extraHp, out float extraStamina, out float extraEitr)
	{
		extraHp = 0f;
		extraStamina = 0f;
		extraEitr = 0f;
		if (string.IsNullOrEmpty(prefabName))
		{
			return;
		}
		for (int i = 0; i < ExtraStatsConfig.Count; i++)
		{
			ExtraStatEntry extraStatEntry = ExtraStatsConfig[i];
			if (extraStatEntry.SourceType == ExtraSourceType.ItemDrop && string.Equals(prefabName, extraStatEntry.PrefabName, StringComparison.OrdinalIgnoreCase))
			{
				switch (extraStatEntry.StatType)
				{
				case ExtraStatType.Health:
					extraHp += extraStatEntry.Value;
					break;
				case ExtraStatType.Stamina:
					extraStamina += extraStatEntry.Value;
					break;
				case ExtraStatType.Eitr:
					extraEitr += extraStatEntry.Value;
					break;
				}
			}
		}
	}

	private static void GetStatusEffectBonuses(string seRawName, out float extraHp, out float extraStamina, out float extraEitr)
	{
		extraHp = 0f;
		extraStamina = 0f;
		extraEitr = 0f;
		if (string.IsNullOrEmpty(seRawName))
		{
			return;
		}
		string prefabName = Utils.GetPrefabName(seRawName);
		for (int i = 0; i < ExtraStatsConfig.Count; i++)
		{
			ExtraStatEntry extraStatEntry = ExtraStatsConfig[i];
			if (extraStatEntry.SourceType == ExtraSourceType.StatusEffect && string.Equals(prefabName, extraStatEntry.PrefabName, StringComparison.OrdinalIgnoreCase))
			{
				switch (extraStatEntry.StatType)
				{
				case ExtraStatType.Health:
					extraHp += extraStatEntry.Value;
					break;
				case ExtraStatType.Stamina:
					extraStamina += extraStatEntry.Value;
					break;
				case ExtraStatType.Eitr:
					extraEitr += extraStatEntry.Value;
					break;
				}
			}
		}
	}

	private static string BuildExtraStatsTooltipBlock(float extraHp, float extraStamina, float extraEitr)
	{
		if (extraHp == 0f && extraStamina == 0f && extraEitr == 0f)
		{
			return string.Empty;
		}
		StringBuilder stringBuilder = new StringBuilder();
		string text = "$do_extrastats_health";
		string text2 = "$do_extrastats_stamina";
		string text3 = "$do_extrastats_eitr";
		if (Localization.instance != null)
		{
			text = Localization.instance.Localize(text);
			text2 = Localization.instance.Localize(text2);
			text3 = Localization.instance.Localize(text3);
		}
		if (extraHp != 0f)
		{
			stringBuilder.Append($"\n{text}: <color=#f27979>+{extraHp:F0}</color>");
		}
		if (extraStamina != 0f)
		{
			stringBuilder.Append($"\n{text2}: <color=#ffff80>+{extraStamina:F0}</color>");
		}
		if (extraEitr != 0f)
		{
			stringBuilder.Append($"\n{text3}: <color=#8686ee>+{extraEitr:F0}</color>");
		}
		return stringBuilder.ToString();
	}
}
[HarmonyPatch(typeof(RandomSpeak), "Speak")]
[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
public static class RandomSpeakUpgrade
{
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	private struct WeightedText
	{
		public string text;

		public float weight;

		public WeightedText(string text, float weight)
		{
			this.text = text;
			this.weight = weight;
		}
	}

	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)]
	private class RikoPrefabConfig
	{
		public bool useGreeting;

		public bool useGeneral;

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(1)]
		public WeightedText[] localTexts;
	}

	private const string ZdoGreetingKey = "riko_greeted";

	private const string ZdoCycleKey = "riko_cycle";

	private const string ZdoCycleIndexKey = "riko_cycle_index";

	private static readonly WeightedText[] GeneralTexts = new WeightedText[12]
	{
		new WeightedText("$encounter_riko_general_text_1_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_2_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_3_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_4_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_5_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_6_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_7_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_8_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_9_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_10_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_11_DO", 0.05f),
		new WeightedText("$encounter_riko_general_text_12_DO", 0.05f)
	};

	private static readonly WeightedText[] BlackforestLocalTexts = new WeightedText[5]
	{
		new WeightedText("$encounter_riko_blackforest_text_1_DO", 1f),
		new WeightedText("$encounter_riko_blackforest_text_2_DO", 0.8f),
		new WeightedText("$encounter_riko_blackforest_text_3_DO", 0.8f),
		new WeightedText("$encounter_riko_blackforest_text_4_DO", 0.8f),
		new WeightedText("$encounter_riko_blackforest_text_5_DO", 0.8f)
	};

	private static readonly WeightedText[] SwampLocalTexts = new WeightedText[5]
	{
		new WeightedText("$encounter_riko_swamp_text_1_DO", 1f),
		new WeightedText("$encounter_riko_swamp_text_2_DO", 0.8f),
		new WeightedText("$encounter_riko_swamp_text_3_DO", 0.8f),
		new WeightedText("$encounter_riko_swamp_text_4_DO", 0.8f),
		new WeightedText("$encounter_riko_swamp_text_5_DO", 0.8f)
	};

	private static readonly WeightedText[] MountainLocalTexts = new WeightedText[5]
	{
		new WeightedText("$encounter_riko_mountain_text_1_DO", 1f),
		new WeightedText("$encounter_riko_mountain_text_2_DO", 0.8f),
		new WeightedText("$encounter_riko_mountain_text_3_DO", 0.8f),
		new WeightedText("$encounter_riko_mountain_text_4_DO", 0.8f),
		new WeightedText("$encounter_riko_mountain_text_5_DO", 0.8f)
	};

	private static readonly WeightedText[] PlainsLocalTexts = new WeightedText[5]
	{
		new WeightedText("$encounter_riko_plains_text_1_DO", 1f),
		new WeightedText("$encounter_riko_plains_text_2_DO", 0.8f),
		new WeightedText("$encounter_riko_plains_text_3_DO", 0.8f),
		new WeightedText("$encounter_riko_plains_text_4_DO", 0.8f),
		new WeightedText("$encounter_riko_plains_text_5_DO", 0.8f)
	};

	private static readonly WeightedText[] MistlandsLocalTexts = new WeightedText[5]
	{
		new WeightedText("$encounter_riko_mistlands_text_1_DO", 1f),
		new WeightedText("$encounter_riko_mistlands_text_2_DO", 0.8f),
		new WeightedText("$encounter_riko_mistlands_text_3_DO", 0.8f),
		new WeightedText("$encounter_riko_mistlands_text_4_DO", 0.8f),
		new WeightedText("$encounter_riko_mistlands_text_5_DO", 0.8f)
	};

	private static readonly WeightedText[] AshlandsLocalTexts = new WeightedText[5]
	{
		new WeightedText("$encounter_riko_ashlands_text_1_DO", 1f),
		new WeightedText("$encounter_riko_ashlands_text_2_DO", 0.8f),
		new WeightedText("$encounter_riko_ashlands_text_3_DO", 0.8f),
		new WeightedText("$encounter_riko_ashlands_text_4_DO", 0.8f),
		new WeightedText("$encounter_riko_ashlands_text_5_DO", 0.8f)
	};

	private static readonly Dictionary<string, RikoPrefabConfig> PrefabConfigs = new Dictionary<string, RikoPrefabConfig>
	{
		{
			"EncounterCreatureRikoBlackforestDO",
			new RikoPrefabConfig
			{
				useGreeting = true,
				useGeneral = true,
				localTexts = BlackforestLocalTexts
			}
		},
		{
			"EncounterCreatureRikoSwampDO",
			new RikoPrefabConfig
			{
				useGreeting = true,
				useGeneral = true,
				localTexts = SwampLocalTexts
			}
		},
		{
			"EncounterCreatureRikoMountainDO",
			new RikoPrefabConfig
			{
				useGreeting = true,
				useGeneral = true,
				localTexts = MountainLocalTexts
			}
		},
		{
			"EncounterCreatureRikoPlainsDO",
			new RikoPrefabConfig
			{
				useGreeting = true,
				useGeneral = true,
				localTexts = PlainsLocalTexts
			}
		},
		{
			"EncounterCreatureRikoMistlandsDO",
			new RikoPrefabConfig
			{
				useGreeting = true,
				useGeneral = true,
				localTexts = MistlandsLocalTexts
			}
		},
		{
			"EncounterCreatureRikoAshlandsDO",
			new RikoPrefabConfig
			{
				useGreeting = true,
				useGeneral = true,
				localTexts = AshlandsLocalTexts
			}
		}
	};

	private static bool Prefix(RandomSpeak __instance)
	{
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_013b: 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_0164: Unknown result type (might be due to invalid IL or missing references)
		if (!((MonoBehaviour)__instance).IsInvoking())
		{
			((MonoBehaviour)__instance).InvokeRepeating("Speak", Random.Range(0f, __instance.m_interval), __instance.m_interval);
		}
		string prefabName = Utils.GetPrefabName(((Component)__instance).gameObject);
		if (!PrefabConfigs.TryGetValue(prefabName, out var value))
		{
			return true;
		}
		if (Random.value > __instance.m_chance)
		{
			return false;
		}
		if ((Object)(object)Player.m_localPlayer == (Object)null)
		{
			return false;
		}
		if (Vector3.Distance(((Component)__instance).transform.position, ((Component)Player.m_localPlayer).transform.position) > __instance.m_triggerDistance)
		{
			return false;
		}
		if (__instance.m_onlyOnItemStand && !Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponentInParent<ItemStand>()))
		{
			return false;
		}
		float dayFraction = EnvMan.instance.GetDayFraction();
		if (!IsTimeAllowed(__instance, dayFraction))
		{
			return false;
		}
		ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
		if ((Object)(object)component == (Object)null || !component.IsValid())
		{
			return false;
		}
		ZDO zDO = component.GetZDO();
		string text;
		if (value.useGreeting && !zDO.GetBool("riko_greeted", false))
		{
			zDO.Set("riko_greeted", true);
			text = value.localTexts[0].text;
		}
		else
		{
			text = GetNextFromCycle(zDO, value);
			if (string.IsNullOrEmpty(text))
			{
				return false;
			}
		}
		__instance.m_speakEffects.Create(((Component)__instance).transform.position, ((Component)__instance).transform.rotation, (Transform)null, 1f, -1);
		Chat.instance.SetNpcText(((Component)__instance).gameObject, __instance.m_offset, __instance.m_cullDistance, __instance.m_ttl, __instance.m_topic, text, __instance.m_useLargeDialog);
		return false;
	}

	private static string GetNextFromCycle(ZDO zdo, RikoPrefabConfig config)
	{
		string text = zdo.GetString("riko_cycle", "");
		int num = zdo.GetInt("riko_cycle_index", 0);
		if (string.IsNullOrEmpty(text))
		{
			text = BuildNewCycle(config);
			num = 0;
		}
		string[] array = text.Split(new char[1] { ',' });
		if (num >= array.Length)
		{
			text = BuildNewCycle(config);
			num = 0;
			array = text.Split(new char[1] { ',' });
		}
		int index = int.Parse(array[num]);
		zdo.Set("riko_cycle_index", num + 1);
		zdo.Set("riko_cycle", text);
		return ResolveTextByIndex(index, config);
	}

	private static string BuildNewCycle(RikoPrefabConfig config)
	{
		List<int> list = new List<int>();
		List<float> list2 = new List<float>();
		for (int i = 1; i < config.localTexts.Length; i++)
		{
			list.Add(i);
			list2.Add(config.localTexts[i].weight);
		}
		if (config.useGeneral)
		{
			for (int j = 0; j < GeneralTexts.Length; j++)
			{
				list.Add(100 + j);
				list2.Add(GeneralTexts[j].weight);
			}
		}
		List<int> list3 = new List<int>();
		while (list.Count > 0)
		{
			float num = 0f;
			foreach (float item in list2)
			{
				num += item;
			}
			float num2 = Random.Range(0f, num);
			float num3 = 0f;
			for (int k = 0; k < list.Count; k++)
			{
				num3 += list2[k];
				if (num2 <= num3)
				{
					list3.Add(list[k]);
					list.RemoveAt(k);
					list2.RemoveAt(k);
					break;
				}
			}
		}
		StringBuilder stringBuilder = new StringBuilder();
		for (int l = 0; l < list3.Count; l++)
		{
			if (l > 0)
			{
				stringBuilder.Append(",");
			}
			stringBuilder.Append(list3[l]);
		}
		return stringBuilder.ToString();
	}

	private static string ResolveTextByIndex(int index, RikoPrefabConfig config)
	{
		if (index >= 100)
		{
			return GeneralTexts[index - 100].text;
		}
		return config.localTexts[index].text;
	}

	private static bool IsTimeAllowed(RandomSpeak rs, float dayFraction)
	{
		if (!rs.m_invertTod)
		{
			if (!(dayFraction < rs.m_minTOD))
			{
				return !(dayFraction > rs.m_maxTOD);
			}
			return false;
		}
		if (!(dayFraction > rs.m_minTOD))
		{
			return !(dayFraction < rs.m_maxTOD);
		}
		return false;
	}
}
namespace SharedTools
{
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	public static class ZDOCleanup
	{
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
		public static class ZDOCleanupPatch
		{
			private static void Postfix(ZNetScene __instance)
			{
				((MonoBehaviour)__instance).StartCoroutine(DelayedCleanup());
			}

			private static IEnumerator DelayedCleanup()
			{
				yield return (object)new WaitForSeconds(1f);
				RunCleanup();
			}
		}

		private static readonly string[] _oldProjectilePrefabs = new string[3] { "projectile_stormcaller_staff_sphere_DO", "projectile_frostcaller_staff_shard_DO", "projectile_lightcaller_staff_sphere_DO" };

		public static void RunCleanup()
		{
			if ((Object)(object)ZNetScene.instance == (Object)null || ZDOMan.instance == null)
			{
				return;
			}
			int num = 0;
			int num2 = 0;
			foreach (ZDO item in ZDOMan.instance.m_objectsByID.Values.ToList())
			{
				GameObject prefab = ZNetScene.instance.GetPrefab(item.m_prefab);
				if ((Object)(object)prefab == (Object)null)
				{
					ZDOMan.instance.DestroyZDO(item);
					num2++;
				}
				else if (_oldProjectilePrefabs.Contains(((Object)prefab).name))
				{
					ZDOMan.instance.DestroyZDO(item);
					num++;
				}
			}
			if (num > 0 || num2 > 0)
			{
				ZLog.Log((object)$"ZDOCleanup: Cleaned {num} old projectiles and {num2} orphan ZDO(s).");
			}
			else
			{
				ZLog.Log((object)"ZDOCleanup: No old or orphan ZDOs found.");
			}
		}
	}
}
namespace StationLevelFix
{
	[HarmonyPatch(typeof(CraftingStation), "GetLevel")]
	public static class UnlimitedStationLevel
	{
		[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
		private static void Postfix(CraftingStation __instance, ref int __result)
		{
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "CanRepair")]
	public static class UnlimitedRepairFix
	{
		[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
		private static void Postfix(ItemData item, ref bool __result)
		{
			if (!__result && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				CraftingStation currentCraftingStation = Player.m_localPlayer.GetCurrentCraftingStation();
				if ((Object)(object)currentCraftingStation != (Object)null && currentCraftingStation.GetLevel(true) > 4)
				{
					__result = true;
				}
			}
		}
	}
}
namespace PieceManager
{
	[PublicAPI]
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
	public static class MaterialReplacer
	{
		[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)]
		public enum ShaderType
		{
			PieceShader,
			VegetationShader,
			RockShader,
			RugShader,
			GrassShader,
			CustomCreature,
			UseUnityShader
		}

		private static readonly Dictionary<GameObject, bool> ObjectToSwap;

		private static readonly Dictionary<string, Material> OriginalMaterials;

		private static readonly Dictionary<GameObject, ShaderType> ObjectsForShaderReplace;

		private static readonly HashSet<Shader> CachedShaders;

		private static bool hasRun;

		static MaterialReplacer()
		{
			//IL_0033: 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_006c: Expected O, but got Unknown
			CachedShaders = new HashSet<Shader>();
			hasRun = false;
			OriginalMaterials = new Dictionary<string, Material>();
			ObjectToSwap = new Dictionary<GameObject, bool>();
			ObjectsForShaderReplace = new Dictionary<GameObject, ShaderType>();
			new Harmony("org.bepinex.helpers.PieceManager").Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZoneSystem), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(MaterialReplacer), "ReplaceAllMaterialsWithOriginal", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		public static void RegisterGameObjectForShaderSwap(GameObject go, ShaderType type)
		{
			if (!ObjectsForShaderReplace.ContainsKey(go))
			{
				ObjectsForShaderReplace.Add(go, type);
			}
		}

		public static void RegisterGameObjectForMatSwap(GameObject go, bool isJotunnMock = false)
		{
			if (!ObjectToSwap.ContainsKey(go))
			{
				ObjectToSwap.Add(go, isJotunnMock);
			}
		}

		private static void GetAllMaterials()
		{
			Material[] array = Resources.FindObjectsOfTypeAll<Material>();
			foreach (Material val in array)
			{
				OriginalMaterials[((Object)val).name] = val;
			}
		}

		[HarmonyPriority(700)]
		private static void ReplaceAllMaterialsWithOriginal()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			if ((int)SystemInfo.graphicsDeviceType == 4 || hasRun)
			{
				return;
			}
			if (OriginalMaterials.Count == 0)
			{
				GetAllMaterials();
			}
			foreach (KeyValuePair<GameObject, bool> item in ObjectToSwap)
			{
				GameObject key = item.Key;
				bool value = item.Value;
				ProcessGameObjectMaterials(key, value);
			}
			AssetBundle[] array = Resources.FindObjectsOfTypeAll<AssetBundle>();
			foreach (AssetBundle val in array)
			{
				IEnumerable<Shader> enumerable3;
				try
				{
					IEnumerable<Shader> enumerable2;
					if (!val.isStreamedSceneAssetBundle || !Object.op_Implicit((Object)(object)val))
					{
						IEnumerable<Shader> enumerable = val.LoadAllAssets<Shader>();
						enumerable2 = enumerable;
					}
					else
					{
						enumerable2 = from shader in ((IEnumerable<string>)val.GetAllAssetNames()).Select((Func<string, Shader>)val.LoadAsset<Shader>)
							where (Object)(object)shader != (Object)null
							select shader;
					}
					enumerable3 = enumerable2;
				}
				catch (Exception)
				{
					continue;
				}
				if (enumerable3 == null)
				{
					continue;
				}
				foreach (Shader item2 in enumerable3)
				{
					CachedShaders.Add(item2);
				}
			}
			foreach (KeyValuePair<GameObject, ShaderType> item3 in ObjectsForShaderReplace)
			{
				GameObject key2 = item3.Key;
				ShaderType value2 = item3.Value;
				ProcessGameObjectShaders(key2, value2);
			}
			hasRun = true;
		}

		private static void ProcessGameObjectMaterials(GameObject go, bool isJotunnMock)
		{
			Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer obj in componentsInChildren)
			{
				Material[] sharedMaterials = obj.sharedMaterials.Select([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (Material material) => ReplaceMaterial(material, isJotunnMock)).ToArray();
				obj.sharedMaterials = sharedMaterials;
			}
		}

		private static Material ReplaceMaterial(Material originalMaterial, bool isJotunnMock)
		{
			string text = (isJotunnMock ? "JVLmock_" : "_REPLACE_");
			if (!((Object)originalMaterial).name.StartsWith(text, StringComparison.Ordinal))
			{
				return originalMaterial;
			}
			string text2 = ((Object)originalMaterial).name.Replace(" (Instance)", "").Replace(text, "");
			if (OriginalMaterials.TryGetValue(text2, out var value))
			{
				return value;
			}
			Debug.LogWarning((object)("No suitable material found to replace: " + text2));
			return originalMaterial;
		}

		private static void ProcessGameObjectShaders(GameObject go, ShaderType shaderType)
		{
			Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Material[] sharedMaterials = componentsInChildren[i].sharedMaterials;
				foreach (Material val in sharedMaterials)
				{
					if ((Object)(object)val != (Object)null)
					{
						val.shader = GetShaderForType(val.shader, shaderType, ((Object)val.shader).name);
					}
				}
			}
		}

		private static Shader GetShaderForType(Shader orig, ShaderType shaderType, string originalShaderName)
		{
			return (Shader)(shaderType switch
			{
				ShaderType.PieceShader => FindShaderWithName(orig, "Custom/Piece"), 
				ShaderType.VegetationShader => FindShaderWithName(orig, "Custom/Vegetation"), 
				ShaderType.RockShader => FindShaderWithName(orig, "Custom/StaticRock"), 
				ShaderType.RugShader => FindShaderWithName(orig, "Custom/Rug"), 
				ShaderType.GrassShader => FindShaderWithName(orig, "Custom/Grass"), 
				ShaderType.CustomCreature => FindShaderWithName(orig, "Custom/Creature"), 
				ShaderType.UseUnityShader => FindShaderWithName(orig, ((Object)(object)FindShaderWithName(orig, originalShaderName) != (Object)null) ? originalShaderName : "ToonDeferredShading2017"), 
				_ => FindShaderWithName(orig, "Standard"), 
			});
		}

		public static Shader FindShaderWithName(Shader origShader, string name)
		{
			foreach (Shader cachedShader in CachedShaders)
			{
				if (((Object)cachedShader).name == name)
				{
					return cachedShader;
				}
			}
			return origShader;
		}
	}
	[PublicAPI]
	public enum CraftingTable
	{
		None,
		[InternalName("piece_workbench")]
		Workbench,
		[InternalName("piece_cauldron")]
		Cauldron,
		[InternalName("forge")]
		Forge,
		[InternalName("piece_artisanstation")]
		ArtisanTable,
		[InternalName("piece_stonecutter")]
		StoneCutter,
		[InternalName("piece_magetable")]
		MageTable,
		[InternalName("blackforge")]
		BlackForge,
		[InternalName("piece_preptable")]
		FoodPreparationTable,
		[InternalName("piece_MeadCauldron")]
		MeadKetill,
		Custom
	}
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
	public class InternalName : Attribute
	{
		public readonly string internalName;

		public InternalName(string internalName)
		{
			this.internalName = internalName;
		}
	}
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	[PublicAPI]
	public class ExtensionList
	{
		public readonly List<ExtensionConfig> ExtensionStations = new List<ExtensionConfig>();

		public void Set(CraftingTable table, int maxStationDistance = 5)
		{
			ExtensionStations.Add(new ExtensionConfig
			{
				Table = table,
				maxStationDistance = maxStationDistance
			});
		}

		public void Set(string customTable, int maxStationDistance = 5)
		{
			ExtensionStations.Add(new ExtensionConfig
			{
				Table = CraftingTable.Custom,
				custom = customTable,
				maxStationDistance = maxStationDistance
			});
		}
	}
	public struct ExtensionConfig
	{
		public CraftingTable Table;

		public float maxStationDistance;

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
		public string custom;
	}
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	[PublicAPI]
	public class CraftingStationList
	{
		public readonly List<CraftingStationConfig> Stations = new List<CraftingStationConfig>();

		public void Set(CraftingTable table)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = table
			});
		}

		public void Set(string customTable)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = CraftingTable.Custom,
				custom = customTable
			});
		}
	}
	public struct CraftingStationConfig
	{
		public CraftingTable Table;

		public int level;

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
		public string custom;
	}
	[PublicAPI]
	public enum BuildPieceCategory
	{
		Misc = 0,
		Crafting = 1,
		BuildingWorkbench = 2,
		BuildingStonecutter = 3,
		Furniture = 4,
		All = 100,
		Custom = 99
	}
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	[PublicAPI]
	public class RequiredResourcesList
	{
		public readonly List<Requirement> Requirements = new List<Requirement>();

		public void Add(string item, int amount, bool recover)
		{
			Requirements.Add(new Requirement
			{
				itemName = item,
				amount = amount,
				recover = recover
			});
		}
	}
	public struct Requirement
	{
		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(1)]
		public string itemName;

		public int amount;

		public bool recover;
	}
	public struct SpecialProperties
	{
		[Description("Admins should be the only ones that can build this piece.")]
		public bool AdminOnly;

		[Description("Turns off generating a config for this build piece.")]
		public bool NoConfig;
	}
	[PublicAPI]
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	public class BuildingPieceCategory
	{
		public BuildPieceCategory Category;

		public string custom = "";

		public void Set(BuildPieceCategory category)
		{
			Category = category;
		}

		public void Set(string customCategory)
		{
			Category = BuildPieceCategory.Custom;
			custom = customCategory;
		}
	}
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	[PublicAPI]
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
	public class PieceTool
	{
		public readonly HashSet<string> Tools = new HashSet<string>();

		public void Add(string tool)
		{
			Tools.Add(tool);
		}
	}
	[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(1)]
	[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
	[PublicAPI]
	public class BuildPiece
	{
		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
		internal class PieceConfig
		{
			public ConfigEntry<string> craft;

			public ConfigEntry<BuildPieceCategory> category;

			public ConfigEntry<string> customCategory;

			public ConfigEntry<string> tools;

			public ConfigEntry<CraftingTable> extensionTable;

			public ConfigEntry<string> customExtentionTable;

			public ConfigEntry<float> maxStationDistance;

			public ConfigEntry<CraftingTable> table;

			public ConfigEntry<string> customTable;
		}

		[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
			[UsedImplicitly]
			public string Category;

			[UsedImplicitly]
			[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(new byte[] { 2, 1 })]
			public Action<ConfigEntryBase> CustomDrawer;
		}

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(0)]
		private class SerializedRequirements
		{
			public readonly List<Requirement> Reqs;

			public SerializedRequirements(List<Requirement> reqs)
			{
				Reqs = reqs;
			}

			public SerializedRequirements(string reqs)
			{
				Reqs = reqs.Split(new char[1] { ',' }).Select([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (string r) =>
				{
					string[] array = r.Split(new char[1] { ':' });
					Requirement result = default(Requirement);
					result.itemName = array[0];
					result.amount = ((array.Length <= 1 || !int.TryParse(array[1], out var result2)) ? 1 : result2);
					bool result3 = default(bool);
					result.recover = array.Length <= 2 || !bool.TryParse(array[2], out result3) || result3;
					return result;
				}).ToList();
			}

			public override string ToString()
			{
				return string.Join(",", Reqs.Select([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}:{r.recover}"));
			}

			[return: <5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
			public static ItemDrop fetchByName(ObjectDB objectDB, string name)
			{
				GameObject itemPrefab = objectDB.GetItemPrefab(name);
				ItemDrop obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if ((Object)(object)obj == (Object)null)
				{
					Debug.LogWarning((object)(((!string.IsNullOrWhiteSpace(((Object)plugin).name)) ? ("[" + ((Object)plugin).name + "]") : "") + " The required item '" + name + "' does not exist."));
				}
				return obj;
			}

			public static Requirement[] toPieceReqs(SerializedRequirements craft)
			{
				return craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func<Requirement, string>)([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (Requirement r) => r.itemName), (Func<Requirement, Requirement>)([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (Requirement r) =>
				{
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0011: Unknown result type (might be due to invalid IL or missing references)
					//IL_001d: Unknown result type (might be due to invalid IL or missing references)
					//IL_0024: Unknown result type (might be due to invalid IL or missing references)
					//IL_0031: Expected O, but got Unknown
					ItemDrop val = ResItem(r);
					return (val != null) ? new Requirement
					{
						m_amount = r.amount,
						m_resItem = val,
						m_recover = r.recover
					} : ((Requirement)null);
				})).Values.Where([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (Requirement v) => v != null).ToArray();
				[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(2)]
				static ItemDrop ResItem(Requirement r)
				{
					return fetchByName(ObjectDB.instance, r.itemName);
				}
			}
		}

		internal static readonly List<BuildPiece> registeredPieces = new List<BuildPiece>();

		private static readonly Dictionary<Piece, BuildPiece> pieceMap = new Dictionary<Piece, BuildPiece>();

		internal static Dictionary<BuildPiece, PieceConfig> pieceConfigs = new Dictionary<BuildPiece, PieceConfig>();

		internal List<Conversion> Conversions = new List<Conversion>();

		internal List<ItemConversion> conversions = new List<ItemConversion>();

		[Description("Disables generation of the configs for your pieces. This is global, this turns it off for all pieces in your mod.")]
		public static bool ConfigurationEnabled = true;

		public readonly GameObject Prefab;

		[Description("Specifies the resources needed to craft the piece.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the building piece should need.")]
		public readonly RequiredResourcesList RequiredItems = new RequiredResourcesList();

		[Description("Sets the category for the building piece.")]
		public readonly BuildingPieceCategory Category = new BuildingPieceCategory();

		[Description("Specifies the tool needed to build your piece.\nUse .Add to add a tool.")]
		public readonly PieceTool Tool = new PieceTool();

		[Description("Specifies the crafting station needed to build your piece.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.")]
		public CraftingStationList Crafting = new CraftingStationList();

		[Description("Makes this piece a station extension")]
		public ExtensionList Extension = new ExtensionList();

		[Description("Change the extended/special properties of your build piece.")]
		public SpecialProperties SpecialProperties;

		[Description("Specifies a config entry which toggles whether a recipe is active.")]
		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
		public ConfigEntryBase RecipeIsActive;

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
		private LocalizeKey _name;

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
		private LocalizeKey _description;

		internal string[] activeTools;

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
		private static object configManager;

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
		private static Localization _english;

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
		internal static BaseUnityPlugin _plugin = null;

		private static bool hasConfigSync = true;

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
		private static object _configSync;

		public LocalizeKey Name
		{
			get
			{
				LocalizeKey name = _name;
				if (name != null)
				{
					return name;
				}
				Piece component = Prefab.GetComponent<Piece>();
				if (component.m_name.StartsWith("$"))
				{
					_name = new LocalizeKey(component.m_name);
				}
				else
				{
					string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_");
					_name = new LocalizeKey(text).English(component.m_name);
					component.m_name = text;
				}
				return _name;
			}
		}

		public LocalizeKey Description
		{
			get
			{
				LocalizeKey description = _description;
				if (description != null)
				{
					return description;
				}
				Piece component = Prefab.GetComponent<Piece>();
				if (component.m_description.StartsWith("$"))
				{
					_description = new LocalizeKey(component.m_description);
				}
				else
				{
					string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_") + "_description";
					_description = new LocalizeKey(text).English(component.m_description);
					component.m_description = text;
				}
				return _description;
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		internal static BaseUnityPlugin plugin
		{
			get
			{
				//IL_009f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a9: Expected O, but got Unknown
				if (_plugin != null)
				{
					return _plugin;
				}
				IEnumerable<TypeInfo> source;
				try
				{
					source = Assembly.GetExecutingAssembly().DefinedTypes.ToList();
				}
				catch (ReflectionTypeLoadException ex)
				{
					source = from t in ex.Types
						where t != null
						select t.GetTypeInfo();
				}
				_plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
				return _plugin;
			}
		}

		[<5b0afac3-e875-42b6-8a29-598d3c134504>Nullable(2)]
		private static object configSync
		{
			[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(2)]
			get
			{
				if (_configSync != null || !hasConfigSync)
				{
					return _configSync;
				}
				Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
				if ((object)type != null)
				{
					_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " PieceManager");
					type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
					type.GetProperty("IsLocked").SetValue(_configSync, true);
				}
				else
				{
					hasConfigSync = false;
				}
				return _configSync;
			}
		}

		public BuildPiece(string assetBundleFileName, string prefabName, string folderName = "assets")
			: this(PiecePrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName)
		{
		}

		public BuildPiece(AssetBundle bundle, string prefabName)
		{
			Prefab = PiecePrefabManager.RegisterPrefab(bundle, prefabName);
			registeredPieces.Add(this);
		}

		internal static void Patch_FejdStartup(FejdStartup __instance)
		{
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_029e: Expected O, but got Unknown
			//IL_0337: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Expected O, but got Unknown
			//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03af: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0428: Unknown result type (might be due to invalid IL or missing references)
			//IL_0432: Expected O, but got Unknown
			//IL_0586: Unknown result type (might be due to invalid IL or missing references)
			//IL_0590: Expected O, but got Unknown
			//IL_0849: Unknown result type (might be due to invalid IL or missing references)
			//IL_0853: Expected O, but got Unknown
			//IL_05f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0600: Expected O, but got Unknown
			//IL_0697: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a1: Expected O, but got Unknown
			//IL_08b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_08c3: Expected O, but got Unknown
			//IL_0ac1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0acb: Expected O, but got Unknown
			//IL_0b5a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b64: Expected O, but got Unknown
			Type configManagerType = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager");
			configManager = ((configManagerType == null) ? null : Chainloader.ManagerObject.GetComponent(configManagerType));
			foreach (BuildPiece registeredPiece in registeredPieces)
			{
				registeredPiece.activeTools = registeredPiece.Tool.Tools.DefaultIfEmpty("Hammer").ToArray();
				if (registeredPiece.Category.Category != BuildPieceCategory.Custom)
				{
					registeredPiece.Prefab.GetComponent<Piece>().m_category = (PieceCategory)registeredPiece.Category.Category;
				}
				else
				{
					registeredPiece.Prefab.GetComponent<Piece>().m_category = PiecePrefabManager.GetCategory(registeredPiece.Category.custom);
				}
			}
			if (!ConfigurationEnabled)
			{
				return;
			}
			bool saveOnConfigSet = plugin.Config.SaveOnConfigSet;
			plugin.Config.SaveOnConfigSet = false;
			foreach (BuildPiece registeredPiece2 in registeredPieces)
			{
				BuildPiece piece = registeredPiece2;
				if (piece.SpecialProperties.NoConfig)
				{
					continue;
				}
				PieceConfig pieceConfig2 = (pieceConfigs[piece] = new PieceConfig());
				PieceConfig cfg = pieceConfig2;
				Piece piecePrefab2 = piece.Prefab.GetComponent<Piece>();
				string pieceName = piecePrefab2.m_name;
				string englishName = new Regex("[=\\n\\t\\\\\"\\'\\[\\]]*").Replace(english.Localize(pieceName), "").Trim();
				string localizedName = Localization.instance.Localize(pieceName).Trim();
				int order = 0;
				cfg.category = config(englishName, "Build Table Category", piece.Category.Category, new ConfigDescription("Build Category where " + localizedName + " is available.", (AcceptableValueBase)null, new object[1]
				{
					new ConfigurationManagerAttributes
					{
						Order = (order -= 1),
						Category = localizedName
					}
				}));
				ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes
				{
					Order = (order -= 1),
					Browsable = (cfg.category.Value == BuildPieceCategory.Custom),
					Category = localizedName
				};
				cfg.customCategory = config(englishName, "Custom Build Category", piece.Category.custom, new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
				cfg.category.SettingChanged += BuildTableConfigChanged;
				cfg.customCategory.SettingChanged += BuildTableConfigChanged;
				if (cfg.category.Value == BuildPieceCategory.Custom)
				{
					piecePrefab2.m_category = PiecePrefabManager.GetCategory(cfg.customCategory.Value);
				}
				else
				{
					piecePrefab2.m_category = (PieceCategory)cfg.category.Value;
				}
				cfg.tools = config(englishName, "Tools", string.Join(", ", piece.activeTools), new ConfigDescription("Comma separated list of tools where " + localizedName + " is available.", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
				piece.activeTools = (from s in cfg.tools.Value.Split(new char[1] { ',' })
					select s.Trim()).ToArray();
				cfg.tools.SettingChanged += [<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (object _, EventArgs _) =>
				{
					Inventory[] source = (from c in Player.s_players.Select([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsOfType<Container>()
							select c.GetInventory())
						where c != null
						select c).ToArray();
					Dictionary<string, List<PieceTable>> dictionary = (from kv in (from i in (from p in ObjectDB.instance.m_items
								select p.GetComponent<ItemDrop>() into c
								where Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((Component)c).GetComponent<ZNetView>())
								select c).Concat(ItemDrop.s_instances)
							select new KeyValuePair<string, ItemData>(Utils.GetPrefabName(((Component)i).gameObject), i.m_itemData)).Concat(from i in source.SelectMany([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (Inventory i) => i.GetAllItems())
							select new KeyValuePair<string, ItemData>(((Object)i.m_dropPrefab).name, i))
						where Object.op_Implicit((Object)(object)kv.Value.m_shared.m_buildPieces)
						group kv by kv.Key).ToDictionary([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (IGrouping<string, KeyValuePair<string, ItemData>> g) => g.Key, [<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (IGrouping<string, KeyValuePair<string, ItemData>> g) => g.Select([<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (KeyValuePair<string, ItemData> kv) => kv.Value.m_shared.m_buildPieces).Distinct().ToList());
					string[] array5 = piece.activeTools;
					foreach (string key in array5)
					{
						if (dictionary.TryGetValue(key, out var value2))
						{
							foreach (PieceTable item3 in value2)
							{
								item3.m_pieces.Remove(piece.Prefab);
							}
						}
					}
					piece.activeTools = (from s in cfg.tools.Value.Split(new char[1] { ',' })
						select s.Trim()).ToArray();
					if (Object.op_Implicit((Object)(object)ObjectDB.instance))
					{
						array5 = piece.activeTools;
						foreach (string key2 in array5)
						{
							if (dictionary.TryGetValue(key2, out var value3))
							{
								foreach (PieceTable item4 in value3)
								{
									if (!item4.m_pieces.Contains(piece.Prefab))
									{
										item4.m_pieces.Add(piece.Prefab);
									}
								}
							}
						}
						if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces))
						{
							PiecePrefabManager.CategoryRefreshNeeded = true;
							((Humanoid)Player.m_localPlayer).SetPlaceMode(Player.m_localPlayer.m_buildPieces);
						}
					}
				};
				StationExtension pieceExtensionComp;
				List<ConfigurationManagerAttributes> hideWhenNoneAttributes2;
				if (piece.Extension.ExtensionStations.Count > 0)
				{
					pieceExtensionComp = piece.Prefab.GetOrAddComponent<StationExtension>();
					PieceConfig pieceConfig3 = cfg;
					string group = englishName;
					CraftingTable table = piece.Extension.ExtensionStations.First().Table;
					string text = "Crafting station that " + localizedName + " extends.";
					object[] array = new object[1];
					ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes();
					int num = order - 1;
					order = num;
					configurationManagerAttributes.Order = num;
					array[0] = configurationManagerAttributes;
					pieceConfig3.extensionTable = config(group, "Extends Station", table, new ConfigDescription(text, (AcceptableValueBase)null, array));
					cfg.customExtentionTable = config(englishName, "Custom Extend Station", piece.Extension.ExtensionStations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
					PieceConfig pieceConfig4 = cfg;
					string group2 = englishName;
					float maxStationDistance = piece.Extension.ExtensionStations.First().maxStationDistance;
					string text2 = "Distance from the station that " + localizedName + " can be placed.";
					object[] array2 = new object[1];
					ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes();
					num = order - 1;
					order = num;
					configurationManagerAttributes2.Order = num;
					array2[0] = configurationManagerAttributes2;
					pieceConfig4.maxStationDistance = config(group2, "Max Station Distance", maxStationDistance, new ConfigDescription(text2, (AcceptableValueBase)null, array2));
					hideWhenNoneAttributes2 = new List<ConfigurationManagerAttributes>();
					cfg.extensionTable.SettingChanged += ExtensionTableConfigChanged;
					cfg.customExtentionTable.SettingChanged += ExtensionTableConfigChanged;
					cfg.maxStationDistance.SettingChanged += ExtensionTableConfigChanged;
					ConfigurationManagerAttributes configurationManagerAttributes3 = new ConfigurationManagerAttributes();
					num = order - 1;
					order = num;
					configurationManagerAttributes3.Order = num;
					configurationManagerAttributes3.Browsable = cfg.extensionTable.Value != CraftingTable.None;
					ConfigurationManagerAttributes item = configurationManagerAttributes3;
					hideWhenNoneAttributes2.Add(item);
				}
				List<ConfigurationManagerAttributes> hideWhenNoneAttributes;
				if (piece.Crafting.Stations.Count > 0)
				{
					hideWhenNoneAttributes = new List<ConfigurationManagerAttributes>();
					PieceConfig pieceConfig5 = cfg;
					string group3 = englishName;
					CraftingTable table2 = piece.Crafting.Stations.First().Table;
					string text3 = "Crafting station where " + localizedName + " is available.";
					object[] array3 = new object[1];
					ConfigurationManagerAttributes configurationManagerAttributes4 = new ConfigurationManagerAttributes();
					int num = order - 1;
					order = num;
					configurationManagerAttributes4.Order = num;
					array3[0] = configurationManagerAttributes4;
					pieceConfig5.table = config(group3, "Crafting Station", table2, new ConfigDescription(text3, (AcceptableValueBase)null, array3));
					cfg.customTable = config(englishName, "Custom Crafting Station", piece.Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
					cfg.table.SettingChanged += TableConfigChanged;
					cfg.customTable.SettingChanged += TableConfigChanged;
					ConfigurationManagerAttributes configurationManagerAttributes5 = new ConfigurationManagerAttributes();
					num = order - 1;
					order = num;
					configurationManagerAttributes5.Order = num;
					configurationManagerAttributes5.Browsable = cfg.table.Value != CraftingTable.None;
					ConfigurationManagerAttributes item2 = configurationManagerAttributes5;
					hideWhenNoneAttributes.Add(item2);
				}
				cfg.craft = itemConfig("Crafting Costs", new SerializedRequirements(piece.RequiredItems.Requirements).ToString(), "Item costs to craft " + localizedName);
				cfg.craft.SettingChanged += [<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (object _, EventArgs _) =>
				{
					if (Object.op_Implicit((Object)(object)ObjectDB.instance) && (Object)(object)ObjectDB.instance.GetItemPrefab("YmirRemains") != (Object)null)
					{
						Requirement[] resources = SerializedRequirements.toPieceReqs(new SerializedRequirements(cfg.craft.Value));
						piecePrefab2.m_resources = resources;
						Piece[] array4 = Object.FindObjectsOfType<Piece>();
						foreach (Piece val in array4)
						{
							if (val.m_name == pieceName)
							{
								val.m_resources = resources;
							}
						}
					}
				};
				for (int j = 0; j < piece.Conversions.Count; j++)
				{
					string text4 = ((piece.Conversions.Count > 1) ? $"{j + 1}. " : "");
					Conversion conversion = piece.Conversions[j];
					conversion.config = new Conversion.ConversionConfig();
					int index = j;
					conversion.config.input = config(englishName, text4 + "Conversion Input Item", conversion.Input, new ConfigDescription("Conversion input item within " + englishName, (AcceptableValueBase)null, new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = localizedName
						}
					}));
					conversion.config.input.SettingChanged += [<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (object _, EventArgs _) =>
					{
						if (index < piece.conversions.Count)
						{
							ObjectDB instance2 = ObjectDB.instance;
							if (instance2 != null)
							{
								ItemDrop from = SerializedRequirements.fetchByName(instance2, conversion.config.input.Value);
								piece.conversions[index].m_from = from;
							}
						}
					};
					conversion.config.output = config(englishName, text4 + "Conversion Output Item", conversion.Output, new ConfigDescription("Conversion output item within " + englishName, (AcceptableValueBase)null, new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = localizedName
						}
					}));
					conversion.config.output.SettingChanged += [<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(0)] (object _, EventArgs _) =>
					{
						if (index < piece.conversions.Count)
						{
							ObjectDB instance = ObjectDB.instance;
							if (instance != null)
							{
								ItemDrop to = SerializedRequirements.fetchByName(instance, conversion.config.output.Value);
								piece.conversions[index].m_to = to;
							}
						}
					};
				}
				void BuildTableConfigChanged(object o, EventArgs e)
				{
					//IL_0059: 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_003c: Unknown result type (might be due to invalid IL or missing references)
					if (registeredPieces.Count > 0)
					{
						if (cfg.category.Value == BuildPieceCategory.Custom)
						{
							piecePrefab2.m_category = PiecePrefabManager.GetCategory(cfg.customCategory.Value);
						}
						else
						{
							piecePrefab2.m_category = (PieceCategory)cfg.category.Value;
						}
						if (Object.op_Implicit((Object)(object)Hud.instance))
						{
							PiecePrefabManager.CategoryRefreshNeeded = true;
							PiecePrefabManager.CreateCategoryTabs();
						}
					}
					customTableAttributes.Browsable = cfg.category.Value == BuildPieceCategory.Custom;
					ReloadConfigDisplay();
				}
				void ExtensionTableConfigChanged(object o, EventArgs e)
				{
					if (piece.RequiredItems.Requirements.Count > 0)
					{
						if (cfg.extensionTable.Value == CraftingTable.Custom)
						{
							StationExtension obj2 = pieceExtensionComp;
							GameObject prefab2 = ZNetScene.instance.GetPrefab(cfg.customExtentionTable.Value);
							obj2.m_craftingStation = ((prefab2 != null) ? prefab2.GetComponent<CraftingStation>() : null);
						}
						else
						{
							pieceExtensionComp.m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(cfg.extensionTable.Value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>();
						}
						pieceExtensionComp.m_maxStationDistance = cfg.maxStationDistance.Value;
					}
					customTableAttributes.Browsable = cfg.extensionTable.Value == CraftingTable.Custom;
					foreach (ConfigurationManagerAttributes item5 in hideWhenNoneAttributes2)
					{
						item5.Browsable = cfg.extensionTable.Value != CraftingTable.None;
					}
					ReloadConfigDisplay();
					plugin.Config.Save();
				}
				void TableConfigChanged(object o, EventArgs e)
				{
					if (piece.RequiredItems.Requirements.Count > 0)
					{
						switch (cfg.table.Value)
						{
						case CraftingTable.None:
							piecePrefab2.m_craftingStation = null;
							break;
						case CraftingTable.Custom:
						{
							Piece obj = piecePrefab2;
							GameObject prefab = ZNetScene.instance.GetPrefab(cfg.customTable.Value);
							obj.m_craftingStation = ((prefab != null) ? prefab.GetComponent<CraftingStation>() : null);
							break;
						}
						default:
							piecePrefab2.m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(cfg.table.Value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>();
							break;
						}
					}
					customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom;
					foreach (ConfigurationManagerAttributes item6 in hideWhenNoneAttributes)
					{
						item6.Browsable = cfg.table.Value != CraftingTable.None;
					}
					ReloadConfigDisplay();
					plugin.Config.Save();
				}
				ConfigEntry<string> itemConfig(string name, string value, string desc)
				{
					//IL_0054: Unknown result type (might be due to invalid IL or missing references)
					//IL_005e: Expected O, but got Unknown
					ConfigurationManagerAttributes configurationManagerAttributes6 = new ConfigurationManagerAttributes
					{
						CustomDrawer = DrawConfigTable,
						Order = (order -= 1),
						Category = localizedName
					};
					return config(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes6 }));
				}
			}
			foreach (BuildPiece registeredPiece3 in registeredPieces)
			{
				ConfigEntryBase enabledCfg = registeredPiece3.RecipeIsActive;
				Piece piecePrefab;
				if (enabledCfg != null)
				{
					piecePrefab = registeredPiece3.Prefab.GetComponent<Piece>();
					ConfigChanged(null, null);
					((object)enabledCfg).GetType().GetEvent("SettingChanged").AddEventHandler(enabledCfg, new EventHandler(ConfigChanged));
				}
				registeredPiece3.InitializeNewRegisteredPiece(registeredPiece3);
				[<f4dc6c63-4b2f-4a67-89cf-29f7a1e9cdb9>NullableContext(2)]
				void ConfigChanged(object o, EventArgs e)
				{
					piecePrefab.m_enabled = (int)enabledCfg.BoxedValue != 0;
				}
			}
			if (saveOnConfigSet)
			{
				plugin.Config.SaveOnConfigSet = true;
				plugin.Config.Save();
			}
			void ReloadConfigDisplay()
			{
				object obj3 = configManagerType?.GetProperty("DisplayingWindow").GetValue(configManager);
				if (obj3 is bool && (bool)obj3)
				{
					configManagerType.GetMethod("BuildSettingList").Invoke(configManager, Array.Empty<object>());
				}
			}
		}

		private void InitializeNewRegisteredPiece(BuildPiece piece)
		{
			ConfigEntryBase recipeIsActive = piece.RecipeIsActive;
			PieceConfig cfg;
			Piece piecePrefab;
			string pieceName;
			if (recipeIsActive != null)
			{
				pieceConfigs.TryGetValue(piece, out cfg);
				piecePrefab = piece.Prefab.GetComponent<Piece>();
				pieceName = piecePrefab.m_name;
				((object)recipeIsActive).GetType().GetEvent("SettingChanged").AddEventHandler(recipeIsActive, new EventHandler(ConfigChanged));
			}
			void ConfigChanged(object o, EventArgs e)
			{
				if (Object.op_Implicit((Object)(object)ObjectDB.instance) && (Object)(object)ObjectDB.instance.GetItemPrefab("YmirRemains") != (Object)null && cfg != null)
				{
					Requirement[] resources = SerializedRequirements.toPieceReqs(new SerializedRequirements(cfg.craft.Value));
					piecePrefab.m_resources = resources;
					Piece[] array = Object.FindObjectsOfType<Piece>();
					foreach (Piece val in array)
					{
						if (val.m_name == pieceName)
						{
							val.m_resources = resources;
						}
					}
				}
			}
		}

		[HarmonyPriority(700)]
		internal static void Patch_ObjectDBInit(ObjectDB __instance)
		{
			//IL_0441: Unknown result type (might be due to invalid IL or missing references)
			//IL_0446: Unknown result type (might be due to invalid IL or missing references)
			//IL_0479: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b1: Expected O, but got Unknown
			if ((Object)(object)__instance.GetItemPrefab("YmirRemains") == (Object)null)
			{
				return;
			}
			foreach (BuildPiece registeredPiece in registeredPieces)
			{
				pieceConfigs.TryGetValue(registeredPiece, out var value);
				registeredPiece.Prefab.GetComponent<Piece>().m_resources = SerializedRequirements.toPieceReqs((value == null) ? new SerializedRequirements(registeredPiece.RequiredItems.Requirements) : new SerializedRequirements(value.craft.Value));
				foreach (ExtensionConfig extensionStation in registeredPiece.Extension.ExtensionStations)
				{
					switch ((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.Table : value.extensionTable.Value)
					{
					case CraftingTable.None:
						registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = null;
						break;
					case CraftingTable.Custom:
					{
						GameObject prefab = ZNetScene.instance.GetPrefab((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.custom : value.customExtentionTable.Value);
						if (prefab != null)
						{
							registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = prefab.GetComponent<CraftingStation>();
						}
						else
						{
							Debug.LogWarning((object)("Custom crafting station '" + ((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.custom : value.customExtentionTable.Value) + "' does not exist"));
						}
						break;
					}
					default:
						if (value != null && value.table.Value == CraftingTable.None)
						{
							registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = null;
						}
						else
						{
							registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.Table : value.extensionTable.Value).ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>();
						}
						break;
					}
				}
				foreach (CraftingStationConfig station in registeredPiece.Crafting.Stations)
				{
					switch ((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.Table : value.table.Value)
					{
					case CraftingTable.None:
						registeredPiece.Prefab.GetComponent<Piece>().m_craftingStation = null;
						break;
					case CraftingTable.Custom:
					{
						GameObject prefab2 = Z