Decompiled source of Beeswax v1.0.0

Beeswax.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: AssemblyCompany("Beeswax")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Beeswax")]
[assembly: AssemblyTitle("Beeswax")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Beeswax
{
	internal static class ApplySound
	{
		private static EffectList _effect;

		internal static void PlayAt(Vector3 position)
		{
			//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)
			EffectList effect = GetEffect();
			if (effect != null)
			{
				effect.Create(position, Quaternion.identity, (Transform)null, 1f, -1);
			}
		}

		private static EffectList GetEffect()
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			if (_effect != null)
			{
				return _effect;
			}
			if ((Object)(object)ObjectDB.instance != (Object)null)
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Hoe");
				EffectList val = (((Object)(object)itemPrefab != (Object)null) ? itemPrefab.GetComponent<ItemDrop>() : null)?.m_itemData?.m_shared?.m_buildEffect;
				if (val != null && val.m_effectPrefabs.Length != 0)
				{
					_effect = val;
					return _effect;
				}
			}
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				return null;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab("sfx_build_hoe");
			if ((Object)(object)prefab == (Object)null)
			{
				BeeswaxPlugin.Log.LogWarning((object)"Could not find beeswax apply sound (sfx_build_hoe).");
				return null;
			}
			EffectList val2 = new EffectList();
			val2.m_effectPrefabs = (EffectData[])(object)new EffectData[1]
			{
				new EffectData
				{
					m_prefab = prefab
				}
			};
			_effect = val2;
			return _effect;
		}
	}
	internal static class BeehivePatches
	{
		[HarmonyPatch(typeof(Beehive), "UpdateBees")]
		private static class UpdateBeesPatch
		{
			private static void Postfix(Beehive __instance)
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.IsValid() && component.IsOwner() && __instance.CheckBiome() && __instance.HaveFreeSpace())
				{
					float elapsedSeconds = GetElapsedSeconds(component);
					float num = component.GetZDO().GetFloat("beeswax_product", 0f);
					num += elapsedSeconds;
					float num2 = __instance.m_secPerUnit * BeeswaxConfig.HiveProductionSlowdown.Value;
					if (num > num2)
					{
						int num3 = (int)(num / num2);
						int num4 = component.GetZDO().GetInt("beeswax_count", 0);
						num4 = Mathf.Min(num4 + num3 * BeeswaxConfig.HivePerCycle.Value, BeeswaxConfig.HiveMaxStored.Value);
						component.GetZDO().Set("beeswax_count", num4);
						num = 0f;
					}
					component.GetZDO().Set("beeswax_product", num);
				}
			}

			private static float GetElapsedSeconds(ZNetView nview)
			{
				long ticks = nview.GetZDO().GetLong("beeswax_lastTime", ZNet.instance.GetTime().Ticks);
				DateTime dateTime = new DateTime(ticks);
				DateTime time = ZNet.instance.GetTime();
				nview.GetZDO().Set("beeswax_lastTime", time.Ticks);
				double totalSeconds = (time - dateTime).TotalSeconds;
				if (!(totalSeconds < 0.0))
				{
					return (float)totalSeconds;
				}
				return 0f;
			}
		}

		[HarmonyPatch(typeof(Beehive), "Interact")]
		private static class InteractPatch
		{
			private static bool Prefix(Beehive __instance, Humanoid character, bool repeat, bool alt, ref bool __result)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				if (repeat || !PrivateArea.CheckAccess(((Component)__instance).transform.position, 0f, true, false))
				{
					return true;
				}
				if (GetHoneyLevel(__instance) > 0)
				{
					return true;
				}
				if (GetStoredCount(__instance) <= 0)
				{
					return true;
				}
				ExtractMethod.Invoke(__instance, null);
				Game.instance.IncrementPlayerStat((PlayerStatType)76, 1f);
				__result = true;
				return false;
			}
		}

		[HarmonyPatch(typeof(Beehive), "RPC_Extract")]
		private static class ExtractPatch
		{
			private static void Postfix(Beehive __instance)
			{
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					return;
				}
				int num = component.GetZDO().GetInt("beeswax_count", 0);
				if (num > 0)
				{
					if ((Object)(object)BeeswaxItem.Prefab == (Object)null && (Object)(object)ObjectDB.instance != (Object)null)
					{
						BeeswaxItem.Register(ObjectDB.instance);
					}
					__instance.m_spawnEffect.Create(__instance.m_spawnPoint.position, Quaternion.identity, (Transform)null, 1f, -1);
					SpawnBeeswax(__instance, num);
					component.GetZDO().Set("beeswax_count", 0);
				}
			}

			private static void SpawnBeeswax(Beehive hive, int amount)
			{
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				int num = amount;
				int num2 = 0;
				while (num > 0)
				{
					int num3 = Mathf.Min(num, BeeswaxConfig.MaxStack.Value);
					Vector2 val = Random.insideUnitCircle * 0.5f;
					Vector3 position = hive.m_spawnPoint.position + new Vector3(val.x, 0.25f * (float)num2, val.y);
					BeeswaxItem.Drop(num3, position, Quaternion.identity);
					num -= num3;
					num2++;
				}
			}
		}

		[HarmonyPatch(typeof(Beehive), "GetHoverText")]
		private static class HoverTextPatch
		{
			private static void Postfix(Beehive __instance, ref string __result)
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					return;
				}
				int num = component.GetZDO().GetInt("beeswax_count", 0);
				if (num > 0)
				{
					string arg = Localization.instance.Localize("$item_beeswax");
					string text = $"{arg}: {num}/{BeeswaxConfig.HiveMaxStored.Value}";
					int num2 = __result.IndexOf("[<color=yellow>");
					if (num2 < 0)
					{
						num2 = __result.IndexOf("$KEY_Use");
					}
					if (num2 >= 0)
					{
						__result = __result.Insert(num2, text + "\n");
					}
					else
					{
						__result = __result + "\n" + text;
					}
					if (GetHoneyLevel(__instance) == 0)
					{
						string oldValue = Localization.instance.Localize(__instance.m_checkText);
						string newValue = Localization.instance.Localize(__instance.m_extractText);
						__result = __result.Replace(oldValue, newValue);
					}
				}
			}
		}

		private static readonly MethodInfo ExtractMethod = AccessTools.Method(typeof(Beehive), "Extract", (Type[])null, (Type[])null);

		internal const string BeeswaxProductKey = "beeswax_product";

		internal const string BeeswaxCountKey = "beeswax_count";

		internal const string BeeswaxLastTimeKey = "beeswax_lastTime";

		private static int GetHoneyLevel(Beehive hive)
		{
			ZNetView component = ((Component)hive).GetComponent<ZNetView>();
			if (!((Object)(object)component != (Object)null) || !component.IsValid())
			{
				return 0;
			}
			return component.GetZDO().GetInt(ZDOVars.s_level, 0);
		}

		internal static int GetStoredCount(Beehive hive)
		{
			ZNetView component = ((Component)hive).GetComponent<ZNetView>();
			if (!((Object)(object)component != (Object)null) || !component.IsValid())
			{
				return 0;
			}
			return component.GetZDO().GetInt("beeswax_count", 0);
		}
	}
	internal static class BeeswaxConfig
	{
		internal static ConfigEntry<int> MaxStack;

		internal static ConfigEntry<int> HiveMaxStored;

		internal static ConfigEntry<int> HivePerCycle;

		internal static ConfigEntry<float> HiveProductionSlowdown;

		internal static ConfigEntry<int> WildNestDropCount;

		internal static ConfigEntry<float> HandVisualScale;

		internal static ConfigEntry<float> HandNudgeX;

		internal static ConfigEntry<float> HandNudgeY;

		internal static ConfigEntry<float> HandNudgeZ;

		internal static ConfigEntry<float> HandRotationX;

		internal static ConfigEntry<float> HandRotationY;

		internal static ConfigEntry<float> HandRotationZ;

		internal static ConfigEntry<bool> ShowWaxedVisuals;

		internal static ConfigEntry<bool> ShowHoverTextWithVisuals;

		internal static ConfigEntry<bool> ShowWaxedLabel;

		internal static ConfigEntry<bool> ShowAlreadyWaxedLabel;

		internal static ConfigEntry<bool> ShowApplyLabel;

		internal static void Init(ConfigFile config)
		{
			MaxStack = config.Bind<int>("Item", "MaxStack", 30, "");
			HiveMaxStored = config.Bind<int>("Beehive", "MaxStored", 10, "");
			HivePerCycle = config.Bind<int>("Beehive", "PerCycle", 2, "");
			HiveProductionSlowdown = config.Bind<float>("Beehive", "ProductionSlowdown", 1.3f, "");
			WildNestDropCount = config.Bind<int>("Wild Nest", "DropCount", 1, "");
			HandVisualScale = config.Bind<float>("Hand Visual", "Scale", 0.14f, "");
			HandNudgeX = config.Bind<float>("Hand Visual", "NudgeX", 0f, "");
			HandNudgeY = config.Bind<float>("Hand Visual", "NudgeY", 0f, "");
			HandNudgeZ = config.Bind<float>("Hand Visual", "NudgeZ", 0f, "");
			HandRotationX = config.Bind<float>("Hand Visual", "RotationX", 0f, "");
			HandRotationY = config.Bind<float>("Hand Visual", "RotationY", 0f, "");
			HandRotationZ = config.Bind<float>("Hand Visual", "RotationZ", 0f, "");
			ShowWaxedVisuals = config.Bind<bool>("Waxed Visuals", "ShowWaxedVisuals", true, "Show the warm glossy look on waxed wood. When off, hover text labels are shown instead.");
			ShowHoverTextWithVisuals = config.Bind<bool>("Waxed Visuals", "ShowHoverTextWithVisuals", false, "Also show hover text labels while waxed visuals are on. Off by default.");
			config.Bind<string>("Hover Text", "Overview", "—", "These labels only apply when waxed visuals are off, or when ShowHoverTextWithVisuals is on.");
			ShowWaxedLabel = config.Bind<bool>("Hover Text", "ShowWaxedLabel", false, "Show 'Waxed' when looking at a waxed piece without beeswax equipped.");
			ShowAlreadyWaxedLabel = config.Bind<bool>("Hover Text", "ShowAlreadyWaxedLabel", true, "Show 'Already waxed' when holding beeswax and looking at a waxed piece.");
			ShowApplyLabel = config.Bind<bool>("Hover Text", "ShowApplyLabel", false, "Show the left-click apply hint when holding beeswax and looking at un-waxed wood.");
		}

		internal static bool IsHoverTextAllowed()
		{
			if (ShowWaxedVisuals.Value)
			{
				return ShowHoverTextWithVisuals.Value;
			}
			return true;
		}
	}
	internal static class BeeswaxItem
	{
		[HarmonyPatch(typeof(Humanoid), "EquipItem")]
		private static class EquipItemPatch
		{
			private static void Prefix(ItemData item)
			{
				EnsureItemConfigured(item);
			}
		}

		[HarmonyPatch(typeof(ItemData), "GetTooltip", new Type[]
		{
			typeof(ItemData),
			typeof(int),
			typeof(bool),
			typeof(float),
			typeof(int)
		})]
		private static class TooltipPatch
		{
			private static void Postfix(ItemData item, ref string __result)
			{
				if (IsBeeswaxItem(item))
				{
					__result = __result.Replace("\n$item_twohanded", "\n$item_onehanded");
				}
			}
		}

		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		private static class ObjectDBAwakePatch
		{
			private static void Postfix(ObjectDB __instance)
			{
				Register(__instance);
			}
		}

		[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
		private static class ObjectDBCopyPatch
		{
			private static void Postfix(ObjectDB __instance)
			{
				Register(__instance);
			}
		}

		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static class ZNetSceneAwakePatch
		{
			private static void Postfix(ZNetScene __instance)
			{
				RegisterWithZNetScene(__instance);
			}
		}

		[HarmonyPatch(typeof(Game), "Start")]
		private static class GameStartPatch
		{
			private static void Postfix()
			{
				if ((Object)(object)ObjectDB.instance != (Object)null)
				{
					Register(ObjectDB.instance);
				}
			}
		}

		[HarmonyPatch(typeof(ItemDrop), "Awake")]
		private static class ItemDropAwakePatch
		{
			private static void Postfix(ItemDrop __instance)
			{
				if ((Object)(object)ObjectDB.instance == (Object)null)
				{
					return;
				}
				string prefabName = Utils.GetPrefabName(((Object)((Component)__instance).gameObject).name);
				if (prefabName != "Beeswax" || IsTemplateInstance(((Component)__instance).gameObject))
				{
					return;
				}
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefabName);
				if ((Object)(object)itemPrefab == (Object)null)
				{
					return;
				}
				ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
				if (!((Object)(object)component == (Object)null))
				{
					__instance.m_itemData.m_shared = component.m_itemData.m_shared;
					__instance.m_itemData.m_dropPrefab = itemPrefab;
					if (!((Component)__instance).gameObject.activeSelf)
					{
						((Component)__instance).gameObject.SetActive(true);
					}
				}
			}
		}

		[HarmonyPatch(typeof(VisEquipment), "SetRightItem")]
		private static class VisEquipmentSetRightItemPatch
		{
			private static void Postfix(VisEquipment __instance, string name)
			{
				ConfigureEquippedHandVisual(__instance, name);
			}
		}

		[HarmonyPatch(typeof(VisEquipment), "SetRightItemVisual")]
		private static class VisEquipmentSetRightItemVisualPatch
		{
			private static void Postfix(VisEquipment __instance, string name)
			{
				ConfigureEquippedHandVisual(__instance, name);
			}
		}

		internal const string PrefabName = "Beeswax";

		private const float IconDarkenRed = 0.55f;

		private const float IconDarkenGreen = 0.42f;

		private const float IconDarkenBlue = 0.22f;

		private const string EmbeddedIconResource = "Beeswax.icon.png";

		private static readonly MethodInfo UpdateRegistersMethod = AccessTools.Method(typeof(ObjectDB), "UpdateRegisters", (Type[])null, (Type[])null);

		private static GameObject _prefabParent;

		private static Sprite _iconSprite;

		internal static GameObject Prefab { get; private set; }

		internal static ItemDrop ItemDrop { get; private set; }

		private static float HandVisualScale => BeeswaxConfig.HandVisualScale.Value;

		private static Vector3 HandVisualNudge => new Vector3(BeeswaxConfig.HandNudgeX.Value, BeeswaxConfig.HandNudgeY.Value, BeeswaxConfig.HandNudgeZ.Value);

		private static Vector3 HandVisualRotation => new Vector3(BeeswaxConfig.HandRotationX.Value, BeeswaxConfig.HandRotationY.Value, BeeswaxConfig.HandRotationZ.Value);

		internal static void EnsureItemConfigured(ItemData item)
		{
			if (item != null && IsBeeswaxItem(item))
			{
				if ((Object)(object)ObjectDB.instance != (Object)null)
				{
					Register(ObjectDB.instance);
				}
				if ((Object)(object)ItemDrop != (Object)null)
				{
					item.m_shared = ItemDrop.m_itemData.m_shared;
				}
				if ((Object)(object)Prefab != (Object)null && (Object)(object)item.m_dropPrefab == (Object)null)
				{
					item.m_dropPrefab = Prefab;
				}
			}
		}

		internal static void ConfigureSharedData(SharedData shared)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			if (shared != null)
			{
				shared.m_equipDuration = 0f;
				shared.m_equipEffect = null;
				shared.m_unequipEffect = null;
				shared.m_holdStartEffect = null;
				shared.m_blockPower = 0f;
				shared.m_blockPowerPerLevel = 0f;
				shared.m_timedBlockBonus = 0f;
				shared.m_attackForce = 0f;
				shared.m_backstabBonus = 0f;
				shared.m_movementModifier = 0f;
				shared.m_blockable = false;
				shared.m_skillType = (SkillType)1;
			}
		}

		internal static bool IsBeeswaxItem(ItemData item)
		{
			if (item == null)
			{
				return false;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null)
			{
				return ((Object)item.m_dropPrefab).name == "Beeswax";
			}
			if (item.m_shared != null)
			{
				return item.m_shared.m_name == "$item_beeswax";
			}
			return false;
		}

		internal static void Register(ObjectDB db)
		{
			if (!((Object)(object)db == (Object)null) && !((Object)(object)db.GetItemPrefab("Honey") == (Object)null))
			{
				GameObject itemPrefab = db.GetItemPrefab("Honey");
				if ((Object)(object)Prefab == (Object)null)
				{
					Prefab = CreateTemplate(itemPrefab, db);
					ItemDrop = Prefab.GetComponent<ItemDrop>();
					BeeswaxPlugin.Log.LogInfo((object)"Created Beeswax item template.");
				}
				EnsureNetworkView(itemPrefab);
				if ((Object)(object)db.GetItemPrefab("Beeswax") == (Object)null)
				{
					db.m_items.Add(Prefab);
					UpdateRegistersMethod.Invoke(db, null);
					BeeswaxPlugin.Log.LogInfo((object)"Registered Beeswax with ObjectDB.");
				}
				if ((Object)(object)ZNetScene.instance != (Object)null)
				{
					RegisterWithZNetScene(ZNetScene.instance);
				}
			}
		}

		internal static void RegisterWithZNetScene(ZNetScene scene)
		{
			if ((Object)(object)scene == (Object)null || (Object)(object)Prefab == (Object)null)
			{
				return;
			}
			int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)Prefab).name);
			if (!(AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs").GetValue(scene) is Dictionary<int, GameObject> dictionary))
			{
				BeeswaxPlugin.Log.LogWarning((object)"Could not access ZNetScene prefab table.");
				return;
			}
			if (!dictionary.ContainsKey(stableHashCode))
			{
				dictionary.Add(stableHashCode, Prefab);
			}
			if (!scene.m_prefabs.Contains(Prefab))
			{
				scene.m_prefabs.Add(Prefab);
			}
		}

		internal static void Drop(int amount, Vector3 position, Quaternion rotation)
		{
			//IL_0039: 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)
			if ((Object)(object)ObjectDB.instance != (Object)null)
			{
				Register(ObjectDB.instance);
			}
			if ((Object)(object)ItemDrop == (Object)null)
			{
				BeeswaxPlugin.Log.LogWarning((object)"Beeswax drop skipped: item is not registered yet.");
				return;
			}
			ItemDrop val = Object.Instantiate<ItemDrop>(ItemDrop, position, rotation);
			if ((Object)(object)val == (Object)null)
			{
				BeeswaxPlugin.Log.LogWarning((object)"Beeswax drop skipped: instantiate failed.");
				return;
			}
			((Component)val).gameObject.SetActive(true);
			int num = Mathf.Max(1, amount);
			if ((Object)(object)Game.instance != (Object)null)
			{
				num = Game.instance.ScaleDrops(val.m_itemData, num);
			}
			val.SetStack(num);
		}

		private static GameObject GetPrefabParent()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if ((Object)(object)_prefabParent == (Object)null)
			{
				_prefabParent = new GameObject("Beeswax_ModPrefabs");
				_prefabParent.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)_prefabParent);
			}
			return _prefabParent;
		}

		private static bool IsTemplateInstance(GameObject gameObject)
		{
			if ((Object)(object)Prefab != (Object)null)
			{
				return (Object)(object)gameObject == (Object)(object)Prefab;
			}
			return false;
		}

		private static void EnsureNetworkView(GameObject honeyPrefab)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Prefab == (Object)null) && !((Object)(object)honeyPrefab == (Object)null) && ZDOMan.instance != null && !((Object)(object)Prefab.GetComponent<ZNetView>() != (Object)null))
			{
				ZNetView component = honeyPrefab.GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null)
				{
					BeeswaxPlugin.Log.LogWarning((object)"Honey template is missing ZNetView; Beeswax cannot sync.");
					return;
				}
				ZNetView.StartGhostInit();
				ZNetView obj = Prefab.AddComponent<ZNetView>();
				obj.m_persistent = component.m_persistent;
				obj.m_distant = component.m_distant;
				obj.m_type = component.m_type;
				obj.m_syncInitialScale = component.m_syncInitialScale;
				ZNetView.FinishGhostInit();
				BeeswaxPlugin.Log.LogInfo((object)"Attached network view to Beeswax template.");
			}
		}

		private static GameObject CreateTemplate(GameObject honeyPrefab, ObjectDB db)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			ZNetView.m_forceDisableInit = true;
			GameObject val = Object.Instantiate<GameObject>(honeyPrefab, GetPrefabParent().transform);
			((Object)val).name = "Beeswax";
			ZNetView.m_forceDisableInit = false;
			ItemDrop component = val.GetComponent<ItemDrop>();
			SharedData val2 = CloneSharedData(component.m_itemData.m_shared);
			ItemData val3 = component.m_itemData.Clone();
			val3.m_shared = val2;
			val3.m_dropPrefab = val;
			component.m_itemData = val3;
			val2.m_name = "$item_beeswax";
			val2.m_description = "$item_beeswax_description";
			val2.m_itemType = (ItemType)19;
			val2.m_animationState = (AnimationState)1;
			val2.m_maxStackSize = BeeswaxConfig.MaxStack.Value;
			val2.m_food = 0f;
			val2.m_foodStamina = 0f;
			val2.m_foodEitr = 0f;
			val2.m_foodBurnTime = 0f;
			val2.m_foodRegen = 0f;
			val2.m_consumeStatusEffect = null;
			val2.m_setStatusEffect = null;
			val2.m_equipStatusEffect = null;
			val2.m_useDurability = false;
			val2.m_useDurabilityDrain = 0f;
			val2.m_damages = default(DamageTypes);
			val2.m_damagesPerLevel = default(DamageTypes);
			val2.m_attackStatusEffect = null;
			val2.m_attackStatusEffectChance = 0f;
			val2.m_attack = null;
			val2.m_secondaryAttack = null;
			val2.m_icons = BuildIcons(val2.m_icons);
			ConfigureSharedData(val2);
			TintRenderers(val);
			SetupHandAttach(val, db);
			ItemDrop.OnCreateNew(component);
			return val;
		}

		private static void SetupHandAttach(GameObject beeswaxPrefab, ObjectDB db)
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: 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_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			Transform val = beeswaxPrefab.transform.Find("attach");
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)val).gameObject);
			}
			MeshRenderer val2 = FindPrimaryDropRenderer(beeswaxPrefab);
			if ((Object)(object)val2 == (Object)null)
			{
				BeeswaxPlugin.Log.LogWarning((object)"Beeswax prefab has no mesh for hand attach.");
				return;
			}
			MeshFilter component = ((Component)val2).GetComponent<MeshFilter>();
			if ((Object)(object)component == (Object)null || (Object)(object)component.sharedMesh == (Object)null)
			{
				BeeswaxPlugin.Log.LogWarning((object)"Beeswax prefab mesh filter is missing for hand attach.");
				return;
			}
			Transform transform = ((Component)val2).transform;
			Bounds bounds = component.sharedMesh.bounds;
			Vector3 val3 = Vector3.Scale(((Bounds)(ref bounds)).center, transform.localScale);
			Vector3 localPosition = transform.localPosition + transform.localRotation * val3;
			GameObject val4 = new GameObject("attach");
			val4.transform.SetParent(beeswaxPrefab.transform, false);
			val4.transform.localPosition = localPosition;
			val4.transform.localRotation = transform.localRotation;
			val4.transform.localScale = Vector3.one;
			bounds = component.sharedMesh.bounds;
			Vector3 val5 = Vector3.Scale(((Bounds)(ref bounds)).center, Vector3.one * HandVisualScale);
			GameObject val6 = new GameObject("beeswax_visual");
			val6.transform.SetParent(val4.transform, false);
			val6.transform.localPosition = HandVisualNudge - val5;
			val6.transform.localRotation = Quaternion.Euler(HandVisualRotation);
			val6.transform.localScale = Vector3.one * HandVisualScale;
			val6.AddComponent<MeshFilter>().sharedMesh = component.sharedMesh;
			((Renderer)val6.AddComponent<MeshRenderer>()).sharedMaterials = ((Renderer)val2).sharedMaterials;
		}

		internal static void ConfigureEquippedHandVisual(VisEquipment visEquipment, string itemName)
		{
			if ((Object)(object)visEquipment == (Object)null || itemName != "Beeswax")
			{
				return;
			}
			Transform val = FindEquippedItemRoot(visEquipment, itemName);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Transform val2 = val.Find("attach");
			MeshRenderer[] componentsInChildren = ((Component)val).GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val3 in componentsInChildren)
			{
				if ((Object)(object)val2 != (Object)null && ((Component)val3).transform.IsChildOf(val2))
				{
					((Renderer)val3).enabled = true;
				}
				else
				{
					((Renderer)val3).enabled = false;
				}
			}
		}

		private static Transform FindEquippedItemRoot(VisEquipment visEquipment, string itemName)
		{
			Transform[] componentsInChildren = ((Component)visEquipment).GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				if (Utils.GetPrefabName(((Object)((Component)val).gameObject).name) == itemName)
				{
					return val;
				}
			}
			return null;
		}

		private static MeshRenderer FindPrimaryDropRenderer(GameObject beeswaxPrefab)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			MeshRenderer result = null;
			float num = 0f;
			MeshRenderer[] componentsInChildren = beeswaxPrefab.GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val in componentsInChildren)
			{
				if ((Object)(object)((Component)val).transform.parent != (Object)null && ((Object)((Component)val).transform.parent).name == "attach")
				{
					continue;
				}
				MeshFilter component = ((Component)val).GetComponent<MeshFilter>();
				if (!((Object)(object)component == (Object)null) && !((Object)(object)component.sharedMesh == (Object)null))
				{
					Bounds bounds = component.sharedMesh.bounds;
					Vector3 size = ((Bounds)(ref bounds)).size;
					float num2 = size.x * size.y * size.z;
					if (!(num2 <= num))
					{
						num = num2;
						result = val;
					}
				}
			}
			return result;
		}

		private static SharedData CloneSharedData(SharedData source)
		{
			return MemberwiseClone<SharedData>(source);
		}

		private static T MemberwiseClone<T>(T source) where T : class
		{
			return (T)typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(source, null);
		}

		private static Sprite[] BuildIcons(Sprite[] honeyIcons)
		{
			Sprite iconSprite = GetIconSprite(honeyIcons);
			if ((Object)(object)iconSprite == (Object)null)
			{
				return honeyIcons;
			}
			if (honeyIcons == null || honeyIcons.Length == 0)
			{
				return (Sprite[])(object)new Sprite[1] { iconSprite };
			}
			Sprite[] array = (Sprite[])(object)new Sprite[honeyIcons.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = iconSprite;
			}
			return array;
		}

		private static Sprite GetIconSprite(Sprite[] honeyIcons)
		{
			if ((Object)(object)_iconSprite != (Object)null)
			{
				return _iconSprite;
			}
			Sprite val = LoadEmbeddedIconSprite(honeyIcons);
			if ((Object)(object)val != (Object)null)
			{
				_iconSprite = val;
				return _iconSprite;
			}
			if (honeyIcons == null || honeyIcons.Length == 0 || (Object)(object)honeyIcons[0] == (Object)null)
			{
				return null;
			}
			_iconSprite = DarkenSprite(honeyIcons[0]);
			return _iconSprite;
		}

		private static Sprite LoadEmbeddedIconSprite(Sprite[] honeyIcons)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			using Stream stream = typeof(BeeswaxItem).Assembly.GetManifestResourceStream("Beeswax.icon.png");
			if (stream == null)
			{
				BeeswaxPlugin.Log.LogWarning((object)"Embedded beeswax icon was not found in the mod DLL.");
				return null;
			}
			byte[] array = new byte[stream.Length];
			if (stream.Read(array, 0, array.Length) != array.Length)
			{
				BeeswaxPlugin.Log.LogWarning((object)"Failed to read embedded beeswax icon.");
				return null;
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			((Texture)val).filterMode = (FilterMode)1;
			((Texture)val).wrapMode = (TextureWrapMode)1;
			if (!TryLoadPng(val, array))
			{
				Object.Destroy((Object)(object)val);
				BeeswaxPlugin.Log.LogWarning((object)"Failed to decode embedded beeswax icon.");
				return null;
			}
			float num = ((honeyIcons != null && honeyIcons.Length != 0 && (Object)(object)honeyIcons[0] != (Object)null) ? honeyIcons[0].pixelsPerUnit : 100f);
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2((float)((Texture)val).width * 0.5f, (float)((Texture)val).height * 0.5f), num);
		}

		private static bool TryLoadPng(Texture2D texture, byte[] pngBytes)
		{
			Type type = Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule");
			if (type != null)
			{
				MethodInfo method = type.GetMethod("LoadImage", BindingFlags.Static | BindingFlags.Public, null, new Type[2]
				{
					typeof(Texture2D),
					typeof(byte[])
				}, null);
				if (method != null)
				{
					return (bool)method.Invoke(null, new object[2] { texture, pngBytes });
				}
			}
			MethodInfo method2 = typeof(Texture2D).GetMethod("LoadImage", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(byte[]) }, null);
			if (method2 != null)
			{
				return (bool)method2.Invoke(texture, new object[1] { pngBytes });
			}
			return false;
		}

		private static Sprite DarkenSprite(Sprite source)
		{
			//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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_0090: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			Rect textureRect = source.textureRect;
			int num = (int)((Rect)(ref textureRect)).width;
			int num2 = (int)((Rect)(ref textureRect)).height;
			if (num <= 0 || num2 <= 0)
			{
				return null;
			}
			Texture2D texture = source.texture;
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
			Graphics.Blit((Texture)(object)texture, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D(num, num2, (TextureFormat)4, false);
			((Texture)val).filterMode = (FilterMode)1;
			((Texture)val).wrapMode = (TextureWrapMode)1;
			val.ReadPixels(new Rect(((Rect)(ref textureRect)).x, ((Rect)(ref textureRect)).y, (float)num, (float)num2), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			Color[] pixels = val.GetPixels();
			for (int i = 0; i < pixels.Length; i++)
			{
				Color val2 = pixels[i];
				pixels[i] = new Color(val2.r * 0.55f, val2.g * 0.42f, val2.b * 0.22f, val2.a);
			}
			val.SetPixels(pixels);
			val.Apply();
			return Sprite.Create(val, new Rect(0f, 0f, (float)num, (float)num2), source.pivot, source.pixelsPerUnit);
		}

		private static void TintRenderers(GameObject prefab)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			Renderer[] componentsInChildren = prefab.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Material[] materials = val.materials;
				foreach (Material val2 in materials)
				{
					if (!((Object)(object)val2 == (Object)null) && val2.HasProperty("_Color"))
					{
						Color color = val2.color;
						val2.color = new Color(color.r * 0.55f, color.g * 0.42f, color.b * 0.22f, color.a);
					}
				}
			}
		}
	}
	[BepInPlugin("ModdedWolf.Beeswax", "Beeswax", "1.0.0")]
	public class BeeswaxPlugin : BaseUnityPlugin
	{
		public const string GUID = "ModdedWolf.Beeswax";

		public const string NAME = "Beeswax";

		public const string VERSION = "1.0.0";

		internal static BeeswaxPlugin Instance;

		internal static ManualLogSource Log;

		private void Awake()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			BeeswaxConfig.Init(((BaseUnityPlugin)this).Config);
			LocalizationSetup.Apply();
			new Harmony("ModdedWolf.Beeswax").PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Beeswax v1.0.0 loaded.");
		}
	}
	internal static class LocalizationSetup
	{
		internal const string ItemName = "$item_beeswax";

		internal const string ItemDescription = "$item_beeswax_description";

		internal const string SealedLabel = "$beeswax_sealed";

		internal const string AlreadyWaxedLabel = "$beeswax_already_waxed";

		internal const string ApplyLabel = "$beeswax_apply";

		private static readonly MethodInfo AddWordMethod = AccessTools.Method(typeof(Localization), "AddWord", (Type[])null, (Type[])null);

		internal static void Apply()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			new Harmony("ModdedWolf.Beeswax.Localization").Patch((MethodBase)AccessTools.Method(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LocalizationSetup), "SetupLanguagePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			if (Localization.instance != null)
			{
				RegisterWords(Localization.instance);
			}
		}

		private static void SetupLanguagePostfix(Localization __instance)
		{
			RegisterWords(__instance);
		}

		private static void RegisterWords(Localization localization)
		{
			if (localization != null && !(AddWordMethod == null))
			{
				AddWord(localization, "item_beeswax", "Beeswax");
				AddWord(localization, "item_beeswax_description", "A heavy lump of beeswax. Rub it on timber to seal out the weather.");
				AddWord(localization, "beeswax_sealed", "Waxed");
				AddWord(localization, "beeswax_already_waxed", "Already waxed");
				AddWord(localization, "beeswax_apply", "Apply beeswax");
			}
		}

		private static void AddWord(Localization localization, string key, string value)
		{
			AddWordMethod.Invoke(localization, new object[2] { key, value });
		}
	}
	internal static class StructureVisuals
	{
		[HarmonyPatch(typeof(WearNTear), "Start")]
		private static class StartPatch
		{
			private static void Postfix(WearNTear __instance)
			{
				EnsureApplied(__instance);
			}
		}

		[HarmonyPatch(typeof(WearNTear), "UpdateWear")]
		private static class UpdateWearPatch
		{
			private static void Postfix(WearNTear __instance)
			{
				EnsureApplied(__instance);
			}
		}

		private const float WarmRed = 1.14f;

		private const float WarmGreen = 1.05f;

		private const float WarmBlue = 0.72f;

		private const float GlossBoost = 0.18f;

		private static readonly Color EmissionTint = new Color(0.18f, 0.12f, 0.04f);

		private static readonly HashSet<int> AppliedIds = new HashSet<int>();

		internal static void Apply(WearNTear wear)
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			if (!BeeswaxConfig.ShowWaxedVisuals.Value || (Object)(object)wear == (Object)null || IsApplied(wear))
			{
				return;
			}
			Renderer[] componentsInChildren = ((Component)wear).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val == (Object)null || ((object)val).GetType().Name == "ParticleSystemRenderer" || val is TrailRenderer)
				{
					continue;
				}
				Material[] materials = val.materials;
				foreach (Material val2 in materials)
				{
					if (!((Object)(object)val2 == (Object)null))
					{
						if (val2.HasProperty("_Color"))
						{
							Color color = val2.color;
							val2.color = new Color(Mathf.Min(color.r * 1.14f, 1f), Mathf.Min(color.g * 1.05f, 1f), Mathf.Min(color.b * 0.72f, 1f), color.a);
						}
						if (val2.HasProperty("_Glossiness"))
						{
							val2.SetFloat("_Glossiness", Mathf.Min(val2.GetFloat("_Glossiness") + 0.18f, 1f));
						}
						else if (val2.HasProperty("_Smoothness"))
						{
							val2.SetFloat("_Smoothness", Mathf.Min(val2.GetFloat("_Smoothness") + 0.18f, 1f));
						}
						if (val2.HasProperty("_EmissionColor"))
						{
							val2.EnableKeyword("_EMISSION");
							val2.SetColor("_EmissionColor", EmissionTint);
						}
					}
				}
			}
			AppliedIds.Add(((Object)wear).GetInstanceID());
		}

		internal static void EnsureApplied(WearNTear wear)
		{
			if (BeeswaxConfig.ShowWaxedVisuals.Value && Waterproofing.IsSealed(wear))
			{
				Apply(wear);
			}
		}

		private static bool IsApplied(WearNTear wear)
		{
			return AppliedIds.Contains(((Object)wear).GetInstanceID());
		}
	}
	internal static class Waterproofing
	{
		[HarmonyPatch(typeof(Humanoid), "UseItem")]
		private static class UseItemPatch
		{
			private static void Prefix(ItemData item)
			{
				BeeswaxItem.EnsureItemConfigured(item);
			}
		}

		[HarmonyPatch(typeof(Player), "UseHotbarItem")]
		private static class UseHotbarItemPatch
		{
			private static void Prefix(Player __instance, int index)
			{
				BeeswaxItem.EnsureItemConfigured(((Humanoid)__instance).GetInventory().GetItemAt(index - 1, 0));
			}
		}

		[HarmonyPatch(typeof(Player), "OnSpawned")]
		private static class PlayerSpawnedPatch
		{
			private static void Postfix(Player __instance)
			{
				if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
				{
					RepairInventoryBeeswax(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "StartAttack")]
		private static class StartAttackPatch
		{
			private static bool Prefix(Humanoid __instance, Character target, bool secondaryAttack)
			{
				if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || !IsHoldingBeeswax(__instance))
				{
					return true;
				}
				if (!secondaryAttack)
				{
					ItemData rightItem = __instance.GetRightItem();
					TryApplyOnce(__instance, __instance.GetInventory(), rightItem);
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(Player), "Update")]
		private static class PlayerUpdatePatch
		{
			private static void Postfix(Player __instance)
			{
				if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
				{
					RecoverLocalPlayerState(__instance);
					CleanupDepletedBeeswax(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(WearNTear), "IsWet")]
		private static class IsWetPatch
		{
			private static void Postfix(WearNTear __instance, ref bool __result)
			{
				if (__result && IsSealed(__instance))
				{
					__result = false;
				}
			}
		}

		[HarmonyPatch(typeof(Hud), "UpdateCrosshair")]
		private static class HudCrosshairPatch
		{
			private static readonly FieldInfo HoverNameField = AccessTools.Field(typeof(Hud), "m_hoverName");

			private static readonly PropertyInfo HoverTextProperty = HoverNameField?.FieldType.GetProperty("text", BindingFlags.Instance | BindingFlags.Public);

			private static readonly FieldInfo CrosshairField = AccessTools.Field(typeof(Hud), "m_crosshair");

			private static readonly PropertyInfo CrosshairColorProperty = CrosshairField?.FieldType.GetProperty("color", BindingFlags.Instance | BindingFlags.Public);

			private static void Postfix(Hud __instance, Player player)
			{
				//IL_010e: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)player != (Object)(object)Player.m_localPlayer || HoverNameField == null || HoverTextProperty == null)
				{
					return;
				}
				GameObject hoverObject = ((Humanoid)player).GetHoverObject();
				if ((Object)(object)hoverObject == (Object)null)
				{
					return;
				}
				string text = BuildStructureHoverLine(hoverObject.GetComponentInParent<WearNTear>(), (Humanoid)(object)player);
				if (string.IsNullOrEmpty(text))
				{
					return;
				}
				object value = HoverNameField.GetValue(__instance);
				if (value == null)
				{
					return;
				}
				string text2 = (HoverTextProperty.GetValue(value) as string) ?? string.Empty;
				string value2 = Localization.instance.Localize("$beeswax_sealed");
				string value3 = Localization.instance.Localize("$beeswax_already_waxed");
				if (!text2.Contains(value2) && !text2.Contains(value3))
				{
					string text3 = (string.IsNullOrEmpty(text2) ? text : (text2 + "\n" + text));
					HoverTextProperty.SetValue(value, text3);
					if (text3.Length > 0 && CrosshairField != null && CrosshairColorProperty != null)
					{
						object value4 = CrosshairField.GetValue(__instance);
						CrosshairColorProperty.SetValue(value4, Color.yellow);
					}
				}
			}
		}

		internal const string SealedKey = "beeswax_sealed";

		private static int _lastApplyFrame = -1;

		private static bool _recoveredLocalPlayerState;

		internal static string BuildStructureHoverLine(WearNTear wear, Humanoid player)
		{
			if ((Object)(object)wear == (Object)null || !BeeswaxConfig.IsHoverTextAllowed())
			{
				return null;
			}
			bool flag = (Object)(object)player != (Object)null && IsHoldingBeeswax(player);
			if (IsSealed(wear))
			{
				if (flag)
				{
					if (!BeeswaxConfig.ShowAlreadyWaxedLabel.Value)
					{
						return null;
					}
					return "[<color=orange>★</color>] " + Localization.instance.Localize("$beeswax_already_waxed");
				}
				if (!BeeswaxConfig.ShowWaxedLabel.Value)
				{
					return null;
				}
				return "[<color=orange>★</color>] " + Localization.instance.Localize("$beeswax_sealed");
			}
			if (!CanCoat(wear) || !flag || !BeeswaxConfig.ShowApplyLabel.Value)
			{
				return null;
			}
			return "[<color=yellow><b>$KEY_Attack</b></color>] " + Localization.instance.Localize("$beeswax_apply");
		}

		private static void RepairInventoryBeeswax(Player player)
		{
			foreach (ItemData allItem in ((Humanoid)player).GetInventory().GetAllItems())
			{
				BeeswaxItem.EnsureItemConfigured(allItem);
			}
		}

		private static void RecoverLocalPlayerState(Player player)
		{
			if (!_recoveredLocalPlayerState)
			{
				_recoveredLocalPlayerState = true;
				RepairInventoryBeeswax(player);
				ItemData rightItem = ((Humanoid)player).GetRightItem();
				if (BeeswaxItem.IsBeeswaxItem(rightItem))
				{
					RefreshEquippedBeeswax(player, rightItem);
				}
			}
		}

		private static void RefreshEquippedBeeswax(Player player, ItemData item)
		{
			BeeswaxItem.EnsureItemConfigured(item);
			((Humanoid)player).UnequipItem(item, false);
			BeeswaxItem.EnsureItemConfigured(item);
			((Humanoid)player).EquipItem(item, false);
		}

		private static bool TryApplyOnce(Humanoid user, Inventory inventory, ItemData item)
		{
			if (Time.frameCount == _lastApplyFrame)
			{
				return false;
			}
			if (!TryApply(user, inventory, item))
			{
				return false;
			}
			_lastApplyFrame = Time.frameCount;
			return true;
		}

		internal static bool TryApply(Humanoid user, Inventory inventory, ItemData item)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)user == (Object)null || inventory == null || item == null)
			{
				return false;
			}
			GameObject hoverObject = user.GetHoverObject();
			if ((Object)(object)hoverObject == (Object)null)
			{
				return false;
			}
			WearNTear componentInParent = hoverObject.GetComponentInParent<WearNTear>();
			if (!CanCoat(componentInParent) || IsSealed(componentInParent))
			{
				return false;
			}
			ZNetView component = ((Component)componentInParent).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return false;
			}
			if (!PrivateArea.CheckAccess(((Component)componentInParent).transform.position, 0f, true, false))
			{
				((Character)user).Message((MessageType)2, "$msg_privatearea", 0, (Sprite)null);
				return true;
			}
			inventory.RemoveItem(item, 1);
			component.GetZDO().Set("beeswax_sealed", 1);
			StructureVisuals.Apply(componentInParent);
			ApplySound.PlayAt(((Component)componentInParent).transform.position);
			((Character)user).Message((MessageType)2, Localization.instance.Localize("$beeswax_sealed"), 0, (Sprite)null);
			((Character)user).m_zanim.SetTrigger("interact");
			CleanupAfterApply(user, inventory, item);
			return true;
		}

		private static void CleanupAfterApply(Humanoid user, Inventory inventory, ItemData item)
		{
			if (item.m_stack <= 0 || !inventory.ContainsItem(item))
			{
				user.UnequipItem(item, true);
			}
		}

		private static void CleanupDepletedBeeswax(Player player)
		{
			ItemData rightItem = ((Humanoid)player).GetRightItem();
			if (BeeswaxItem.IsBeeswaxItem(rightItem) && (rightItem.m_stack <= 0 || !((Humanoid)player).GetInventory().ContainsItem(rightItem)))
			{
				((Humanoid)player).UnequipItem(rightItem, true);
			}
		}

		internal static bool IsSealed(WearNTear wear)
		{
			if ((Object)(object)wear == (Object)null)
			{
				return false;
			}
			ZNetView component = ((Component)wear).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid())
			{
				return component.GetZDO().GetInt("beeswax_sealed", 0) == 1;
			}
			return false;
		}

		private static bool CanCoat(WearNTear wear)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Invalid comparison between Unknown and I4
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Invalid comparison between Unknown and I4
			if ((Object)(object)wear == (Object)null)
			{
				return false;
			}
			if ((int)wear.m_materialType == 0 || (int)wear.m_materialType == 3)
			{
				return true;
			}
			if ((int)wear.m_materialType != 2)
			{
				return false;
			}
			Piece piece = wear.m_piece;
			if ((Object)(object)piece == (Object)null)
			{
				return false;
			}
			return Utils.GetPrefabName(((Object)((Component)piece).gameObject).name).StartsWith("woodiron");
		}

		private static bool IsHoldingBeeswax(Humanoid humanoid)
		{
			ItemData rightItem = humanoid.GetRightItem();
			if (!BeeswaxItem.IsBeeswaxItem(rightItem))
			{
				return false;
			}
			BeeswaxItem.EnsureItemConfigured(rightItem);
			if (rightItem.m_stack > 0)
			{
				return humanoid.GetInventory().ContainsItem(rightItem);
			}
			return false;
		}
	}
	internal static class WildBeehivePatches
	{
		[HarmonyPatch(typeof(DropOnDestroyed), "OnDestroyed")]
		private static class OnDestroyedPatch
		{
			private static void Postfix(DropOnDestroyed __instance)
			{
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0098: 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)
				try
				{
					if (!((Object)(object)__instance == (Object)null) && !(Utils.GetPrefabName(((Object)((Component)__instance).gameObject).name) != "Beehive") && !((Object)(object)ZoneSystem.instance == (Object)null))
					{
						Vector3 position = ((Component)__instance).transform.position;
						float groundHeight = ZoneSystem.instance.GetGroundHeight(position);
						if (position.y < groundHeight)
						{
							position.y = groundHeight + 0.1f;
						}
						position += Vector3.up * (__instance.m_spawnYOffset + __instance.m_spawnYStep);
						BeeswaxItem.Drop(BeeswaxConfig.WildNestDropCount.Value, position, Quaternion.Euler(0f, (float)Random.Range(0, 360), 0f));
					}
				}
				catch (Exception arg)
				{
					BeeswaxPlugin.Log.LogError((object)$"Beeswax wild nest drop failed: {arg}");
				}
			}
		}

		private const string WildBeehivePrefabName = "Beehive";
	}
	internal static class WorldRepair
	{
		[HarmonyPatch(typeof(Game), "Start")]
		private static class GameStartPatch
		{
			private static void Postfix()
			{
				if (!((Object)(object)BeeswaxPlugin.Instance == (Object)null))
				{
					((MonoBehaviour)BeeswaxPlugin.Instance).StartCoroutine(RepairOnceDelayed());
				}
			}
		}

		private const string RepairPrefKeyPrefix = "Beeswax.BeehiveRepair.";

		private const string WildBeehivePrefabName = "Beehive";

		private const float RepairDelaySeconds = 5f;

		private static readonly int WildBeehiveHash = StringExtensionMethods.GetStableHashCode("Beehive");

		private static readonly int BeeswaxHash = StringExtensionMethods.GetStableHashCode("Beeswax");

		private static IEnumerator RepairOnceDelayed()
		{
			yield return (object)new WaitForSeconds(5f);
			while ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				yield return null;
			}
			if (!ZNet.instance.IsServer())
			{
				yield break;
			}
			World world = ZNet.World;
			if (world == null)
			{
				yield break;
			}
			string text = "Beeswax.BeehiveRepair." + world.m_uid;
			if (PlayerPrefs.GetInt(text, 0) != 1)
			{
				int num = FixStuckWildBeehives();
				int num2 = CleanupRogueBeeswaxObjects();
				PlayerPrefs.SetInt(text, 1);
				PlayerPrefs.Save();
				if (num > 0 || num2 > 0)
				{
					BeeswaxPlugin.Log.LogInfo((object)$"One-time world repair applied: fixed {num} wild bee nest(s), removed {num2} rogue beeswax object(s).");
				}
				else
				{
					BeeswaxPlugin.Log.LogInfo((object)"One-time world repair check completed (nothing needed fixing).");
				}
			}
		}

		private static int FixStuckWildBeehives()
		{
			float num = GetWildBeehiveHealth();
			if (num <= 0f)
			{
				num = 20f;
			}
			int num2 = 0;
			HashSet<ZDO> allZdos = GetAllZdos();
			if (allZdos != null)
			{
				foreach (ZDO item in allZdos)
				{
					if (item != null && item.GetPrefab() == WildBeehiveHash && TryResetBeehiveHealth(item, num))
					{
						num2++;
					}
				}
			}
			Destructible[] array = Object.FindObjectsByType<Destructible>((FindObjectsSortMode)0);
			foreach (Destructible val in array)
			{
				if (!((Object)(object)val == (Object)null) && !((Object)(object)((Component)val).GetComponent<DropOnDestroyed>() == (Object)null) && !(Utils.GetPrefabName(((Object)((Component)val).gameObject).name) != "Beehive"))
				{
					ZNetView component = ((Component)val).GetComponent<ZNetView>();
					if (!((Object)(object)component == (Object)null) && component.IsValid() && TryResetBeehiveHealth(component.GetZDO(), num))
					{
						num2++;
					}
				}
			}
			return num2;
		}

		private static bool TryResetBeehiveHealth(ZDO zdo, float defaultHealth)
		{
			if (zdo == null)
			{
				return false;
			}
			float num = zdo.GetFloat(ZDOVars.s_health, defaultHealth);
			if (num > 0f && !float.IsNaN(num) && !float.IsInfinity(num))
			{
				return false;
			}
			zdo.Set(ZDOVars.s_health, defaultHealth);
			return true;
		}

		private static float GetWildBeehiveHealth()
		{
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				return 0f;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab("Beehive");
			Destructible val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<Destructible>() : null);
			if ((Object)(object)val == (Object)null)
			{
				return 0f;
			}
			return val.m_health + (float)Game.m_worldLevel * val.m_health * Game.instance.m_worldLevelMineHPMultiplier;
		}

		private static int CleanupRogueBeeswaxObjects()
		{
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNetScene.instance == (Object)null || ZDOMan.instance == null)
			{
				return 0;
			}
			int num = 0;
			GameObject val = GameObject.Find("Beeswax_ModPrefabs");
			ZNetView[] array = Object.FindObjectsByType<ZNetView>((FindObjectsSortMode)0);
			foreach (ZNetView val2 in array)
			{
				if (!((Object)(object)val2 == (Object)null) && val2.IsValid() && !(Utils.GetPrefabName(((Object)((Component)val2).gameObject).name) != "Beeswax") && (!((Object)(object)val != (Object)null) || !((Component)val2).transform.IsChildOf(val.transform)) && !((Object)(object)((Component)val2).GetComponent<ItemDrop>() == (Object)null))
				{
					ZNetScene.instance.Destroy(((Component)val2).gameObject);
					num++;
				}
			}
			HashSet<ZDO> allZdos = GetAllZdos();
			if (allZdos == null)
			{
				return num;
			}
			foreach (ZDO item in allZdos)
			{
				if (item != null && item.GetPrefab() == BeeswaxHash && !((Object)(object)ZNetScene.instance.FindInstance(item) != (Object)null))
				{
					Vector3 position = item.GetPosition();
					if (!(((Vector3)(ref position)).sqrMagnitude > 1f))
					{
						ZDOMan.instance.DestroyZDO(item);
						num++;
					}
				}
			}
			return num;
		}

		private static HashSet<ZDO> GetAllZdos()
		{
			if (ZDOMan.instance == null)
			{
				return null;
			}
			if (AccessTools.Field(typeof(ZDOMan), "m_objectsByID")?.GetValue(ZDOMan.instance) is Dictionary<ZDOID, ZDO> dictionary)
			{
				return new HashSet<ZDO>(dictionary.Values);
			}
			return null;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}