Decompiled source of FieldFilleting v1.0.3

BepInEx/plugins/dannanboi_FieldFilleting.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Field Filleting")]
[assembly: AssemblyDescription("Hand filleting with optional crafting animation, server-authoritative settings and species-specific fillets.")]
[assembly: AssemblyCompany("dannanboi")]
[assembly: AssemblyFileVersion("1.0.3.0")]
[assembly: AssemblyInformationalVersion("1.0.3")]
[assembly: AssemblyVersion("1.0.3.0")]
[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 FishGrazingAsImGoing
{
	internal static class ActionHooks
	{
		private static Harmony owner;

		private static bool dedicated;

		private static readonly Type[] movementPatches = new Type[3]
		{
			typeof(CaptureMovementPatch),
			typeof(ActionUpdatePatch),
			typeof(HandAnimationControlsPatch)
		};

		private static readonly Type[] animationPatches = new Type[7]
		{
			typeof(HandAnimationPlayerPatch),
			typeof(HandAnimationJumpPatch),
			typeof(HandAnimationHidePatch),
			typeof(HandAnimationBoolNamePatch),
			typeof(HandAnimationBoolHashPatch),
			typeof(HandAnimationIntNamePatch),
			typeof(HandAnimationIntHashPatch)
		};

		internal static bool Installing { get; private set; }

		internal static bool AnimationEnabled { get; private set; }

		internal static bool MovementEnabled { get; private set; }

		internal static void Start()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			Dispose();
			owner = new Harmony("dannanboi.fieldfilleting.actions");
			dedicated = (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated();
			Refresh(force: true);
		}

		internal static void Refresh(bool force = false)
		{
			if (ModSettings.ActionAnimation == null || ModSettings.CancelOnMovement == null)
			{
				return;
			}
			bool value = ModSettings.ActionAnimation.Value;
			bool flag = value || ModSettings.CancelOnMovement.Value;
			if (!force && value == AnimationEnabled && flag == MovementEnabled)
			{
				return;
			}
			if (AnimationEnabled)
			{
				HandCraftAnimation.Stop();
			}
			MovementGuard.Reset();
			Harmony obj = owner;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			AnimationEnabled = value;
			MovementEnabled = flag;
			if (owner == null || !flag || dedicated)
			{
				return;
			}
			Installing = true;
			try
			{
				if (value)
				{
					HandCraftAnimation.ValidateApi();
				}
				Type[] array = movementPatches;
				foreach (Type type in array)
				{
					owner.CreateClassProcessor(type).Patch();
				}
				if (value)
				{
					array = animationPatches;
					foreach (Type type2 in array)
					{
						owner.CreateClassProcessor(type2).Patch();
					}
				}
			}
			catch (Exception ex)
			{
				owner.UnpatchSelf();
				Plugin.Warn("Optional action hooks could not be enabled: " + ex.Message);
			}
			finally
			{
				Installing = false;
			}
		}

		internal static void SetNetwork(ZNet network)
		{
			bool flag = (Object)(object)network != (Object)null && network.IsDedicated();
			if (dedicated != flag)
			{
				dedicated = flag;
				Refresh(force: true);
			}
		}

		internal static void Dispose()
		{
			if (AnimationEnabled)
			{
				HandCraftAnimation.Stop();
			}
			MovementGuard.Reset();
			Harmony obj = owner;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			owner = null;
		}
	}
	internal sealed class CraftState
	{
		internal Player Player;

		internal Inventory Inventory;

		internal string OutputName;

		internal int OutputBefore;

		internal int Attempts;

		internal CraftState Previous;
	}
	[HarmonyPatch(typeof(Recipe), "GetAmount")]
	internal static class FishYieldPatch
	{
		[HarmonyPostfix]
		internal static void Postfix(Recipe __instance, int __1, ref int __result)
		{
			if (Filleting.IsHandRecipe(__instance) && __result > 0)
			{
				float num = ModSettings.FiniteRange(ModSettings.FishYieldMultiplier.Value, 0.01f, 5f, 1f);
				if (num != 1f)
				{
					int num2 = Math.Max(1, __1);
					decimal num3 = (decimal)__result / (decimal)num2;
					decimal num4 = Math.Max(1m, Math.Ceiling(num3 * (decimal)num));
					__result = (int)Math.Min(2147483647m, num4 * (decimal)num2);
				}
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
	internal static class CraftPatch
	{
		[ThreadStatic]
		internal static CraftState Active;

		internal static int CountOutput(Inventory inventory, string name)
		{
			int num = 0;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (allItem != null && allItem.m_shared != null && allItem.m_shared.m_name == name)
				{
					num += allItem.m_stack;
				}
			}
			return num;
		}

		[HarmonyPrefix]
		internal static bool Prefix(InventoryGui __instance, Player __0, Recipe ___m_craftRecipe, bool ___m_multiCrafting, int ___m_multiCraftAmount, ref float ___m_craftTimer, out CraftState __state)
		{
			__state = null;
			if (Filleting.RawFishCraftingDisabled && Filleting.IsRawFishRecipe(___m_craftRecipe))
			{
				MovementGuard.Cancel(ref ___m_craftTimer);
				return false;
			}
			if (UniqueFilletRecipes.IsTableRecipe(___m_craftRecipe))
			{
				if (Filleting.CanUseTable(__0, ___m_craftRecipe))
				{
					return true;
				}
				___m_craftTimer = -1f;
				Plugin.RefreshPending = (Plugin.ForceRefresh = true);
				return false;
			}
			if (!Filleting.IsHandRecipe(___m_craftRecipe))
			{
				return true;
			}
			HandCraftAnimation.Stop();
			if (!Filleting.CanUse(__0, ___m_craftRecipe))
			{
				___m_craftTimer = -1f;
				Plugin.RefreshPending = (Plugin.ForceRefresh = true);
				return false;
			}
			int num = ((!___m_multiCrafting) ? 1 : Math.Max(1, ___m_multiCraftAmount));
			Inventory inventory = ((Humanoid)__0).GetInventory();
			int num2 = default(int);
			ItemData val = default(ItemData);
			int amount = ___m_craftRecipe.GetAmount(1, ref num2, ref val, num);
			if (amount <= 0 || num2 <= 0 || val == null || val.m_stack < num2 || !inventory.GetAllItems().Contains(val) || !__0.HaveRequirements(___m_craftRecipe, false, 1, num) || !inventory.CanAddItem(___m_craftRecipe.m_item.m_itemData, amount))
			{
				___m_craftTimer = -1f;
				Plugin.RefreshPending = (Plugin.ForceRefresh = true);
				return false;
			}
			float num3 = ModSettings.EffectiveChance(((Character)__0).GetSkillFactor((SkillType)105));
			if (ModSettings.Fumbles(num3, (num3 > 0f) ? Random.value : 1f))
			{
				bool num4 = inventory.RemoveItem(val, num2);
				___m_craftTimer = -1f;
				Plugin.RefreshPending = (Plugin.ForceRefresh = true);
				string value = ModSettings.FumbleMessage.Value;
				if (num4)
				{
					HandBloodEffect.Show(__0, fumble: true);
				}
				if (num4 && !string.IsNullOrWhiteSpace(value))
				{
					MessageCompat.Show(__0, value);
				}
				return false;
			}
			__state = new CraftState
			{
				Player = __0,
				Inventory = inventory,
				OutputName = ___m_craftRecipe.m_item.m_itemData.m_shared.m_name,
				OutputBefore = CountOutput(inventory, ___m_craftRecipe.m_item.m_itemData.m_shared.m_name),
				Attempts = num,
				Previous = Active
			};
			Active = __state;
			return true;
		}

		[HarmonyPostfix]
		internal static void Postfix(CraftState __state)
		{
			if (__state == null)
			{
				return;
			}
			if (Active == __state)
			{
				Active = __state.Previous;
			}
			if (CountOutput(__state.Inventory, __state.OutputName) <= __state.OutputBefore)
			{
				return;
			}
			HandBloodEffect.Show(__state.Player, fumble: false);
			float num = ModSettings.Experience(1);
			if (num > 0f)
			{
				for (int i = 0; i < __state.Attempts; i++)
				{
					((Character)__state.Player).RaiseSkill((SkillType)105, num);
				}
			}
		}

		[HarmonyFinalizer]
		internal static Exception Finalizer(Exception __exception, CraftState __state, Recipe ___m_craftRecipe, ref float ___m_craftTimer)
		{
			if (__state != null && Active == __state)
			{
				Active = __state.Previous;
			}
			if (__exception != null && Filleting.IsHandRecipe(___m_craftRecipe))
			{
				___m_craftTimer = -1f;
				Plugin.RefreshPending = (Plugin.ForceRefresh = true);
			}
			return __exception;
		}
	}
	[HarmonyPatch(typeof(Player), "RaiseSkill")]
	internal static class NativeCraftExperiencePatch
	{
		[HarmonyPrefix]
		internal static bool Prefix(Player __instance, SkillType __0)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Invalid comparison between Unknown and I4
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			CraftState active = CraftPatch.Active;
			if (active != null && !((Object)(object)active.Player != (Object)(object)__instance))
			{
				if ((int)__0 != 105)
				{
					return (int)__0 != 107;
				}
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class ToolTooltipPatch
	{
		internal const string Hint = "Can be used to fillet fish";

		[HarmonyPrefix]
		private static void Prefix(ItemData __0)
		{
			UniqueFilletItems.RefreshData(__0);
		}

		private static MethodBase TargetMethod()
		{
			return AccessTools.Method(typeof(ItemData), "GetTooltip", new Type[6]
			{
				typeof(ItemData),
				typeof(int),
				typeof(bool),
				typeof(float),
				typeof(int),
				typeof(bool)
			}, (Type[])null) ?? AccessTools.Method(typeof(ItemData), "GetTooltip", new Type[5]
			{
				typeof(ItemData),
				typeof(int),
				typeof(bool),
				typeof(float),
				typeof(int)
			}, (Type[])null) ?? throw new MissingMethodException("No supported ItemData.GetTooltip overload was found.");
		}

		[HarmonyPostfix]
		internal static void Postfix(ItemData __0, ref string __result)
		{
			string value = ModSettings.TooltipText.Value;
			if (ModSettings.AddToTooltip.Value && !string.IsNullOrWhiteSpace(value) && Filleting.IsEligibleTool(__0) && (__result == null || __result.IndexOf(value, StringComparison.Ordinal) < 0))
			{
				__result = (__result ?? "").TrimEnd() + "\n\n" + value;
			}
		}
	}
	internal static class UniqueFilletCooking
	{
		private sealed class State
		{
			internal readonly Dictionary<string, ItemConversion> Owned = new Dictionary<string, ItemConversion>(StringComparer.Ordinal);
		}

		private static ConditionalWeakTable<CookingStation, State> states = new ConditionalWeakTable<CookingStation, State>();

		private static readonly List<WeakReference<CookingStation>> stations = new List<WeakReference<CookingStation>>();

		private static readonly HashSet<string> warnings = new HashSet<string>(StringComparer.Ordinal);

		internal static void Track(CookingStation station)
		{
			if ((Object)(object)station == (Object)null || (Object)(object)((Component)station).gameObject == (Object)null)
			{
				return;
			}
			string text = ((Object)((Component)station).gameObject).name;
			if (text.EndsWith("(Clone)", StringComparison.Ordinal))
			{
				text = text.Substring(0, text.Length - 7).TrimEnd();
			}
			if (text != "piece_cookingstation" && text != "piece_cookingstation_iron")
			{
				return;
			}
			try
			{
				if (states.TryGetValue(station, out var _))
				{
					return;
				}
				states.Add(station, new State());
				stations.Add(new WeakReference<CookingStation>(station));
				if (stations.Count % 64 == 0)
				{
					for (int num = stations.Count - 1; num >= 0; num--)
					{
						if (!stations[num].TryGetTarget(out var target) || (Object)(object)target == (Object)null)
						{
							stations.RemoveAt(num);
						}
					}
				}
				station.m_conversion = ((station.m_conversion == null) ? new List<ItemConversion>() : new List<ItemConversion>(station.m_conversion));
				ObjectDB instance = ObjectDB.instance;
				UniqueFilletItems.Ensure(instance);
				Refresh(station, states.GetValue(station, (CookingStation _) => new State()), instance, UniqueFilletItems.Registered(instance));
			}
			catch (Exception ex)
			{
				WarnOnce("track:" + ex.Message, "Could not add unique fillets to a cooking station; native cooking remains available. " + ex);
			}
		}

		internal static void RefreshAll(ObjectDB database)
		{
			if (stations.Count == 0)
			{
				return;
			}
			List<ItemDrop> fillets = UniqueFilletItems.Registered(database);
			for (int num = stations.Count - 1; num >= 0; num--)
			{
				State value;
				if (!stations[num].TryGetTarget(out var target) || (Object)(object)target == (Object)null)
				{
					stations.RemoveAt(num);
				}
				else if (states.TryGetValue(target, out value))
				{
					try
					{
						Refresh(target, value, database, fillets);
					}
					catch (Exception ex)
					{
						WarnOnce("refresh:" + ex.Message, "Could not refresh unique fillet cooking data; native cooking remains available. " + ex);
					}
				}
			}
		}

		private static void Refresh(CookingStation station, State state, ObjectDB database, List<ItemDrop> fillets)
		{
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Expected O, but got Unknown
			List<ItemConversion> conversion = station.m_conversion;
			if (conversion == null || (Object)(object)database == (Object)null || fillets.Count == 0)
			{
				return;
			}
			ItemConversion val = null;
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			foreach (ItemConversion item in conversion)
			{
				if (!((Object)(object)item?.m_from == (Object)null))
				{
					string name = ((Object)((Component)item.m_from).gameObject).name;
					hashSet.Add(name);
					if (name == "FishRaw" && (Object)(object)item.m_to != (Object)null)
					{
						val = item;
					}
				}
			}
			if (val == null)
			{
				return;
			}
			foreach (ItemDrop fillet in fillets)
			{
				string name2 = ((Object)((Component)fillet).gameObject).name;
				ItemDrop to = val.m_to;
				string text = FilletData.Instance?.Effective.Find(name2)?.PrefabnameCooked;
				if (!string.IsNullOrEmpty(text))
				{
					GameObject itemPrefab = database.GetItemPrefab(text);
					ItemDrop val2 = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
					if ((Object)(object)itemPrefab != (Object)null && ((Object)itemPrefab).name == text && val2?.m_itemData?.m_shared != null)
					{
						to = val2;
					}
					else
					{
						WarnOnce("output:" + text, "Cooked fillet prefab '" + text + "' is unavailable; using the station's Raw Fish output until it is registered.");
					}
				}
				state.Owned.TryGetValue(name2, out var value);
				if (value != null && !conversion.Contains(value))
				{
					state.Owned.Remove(name2);
					value = null;
				}
				if (value == null)
				{
					if (hashSet.Contains(name2))
					{
						continue;
					}
					value = new ItemConversion();
					state.Owned.Add(name2, value);
					conversion.Add(value);
					hashSet.Add(name2);
				}
				value.m_from = fillet;
				value.m_to = to;
				value.m_cookTime = val.m_cookTime;
			}
		}

		private static void WarnOnce(string key, string message)
		{
			if (warnings.Add(key))
			{
				Plugin.Warn(message);
			}
		}

		internal static void Reset()
		{
			states = new ConditionalWeakTable<CookingStation, State>();
			stations.Clear();
			warnings.Clear();
		}
	}
	[HarmonyPatch(typeof(CookingStation), "Awake")]
	internal static class UniqueFilletCookingPatch
	{
		private static void Prefix(CookingStation __instance)
		{
			UniqueFilletCooking.Track(__instance);
		}
	}
	internal sealed class FilletEntry
	{
		internal string Prefabname = "";

		internal string PrefabnameCooked = "";

		internal string Title = "";

		internal string Description = "";

		internal string UseModel = "FishRaw";

		internal float? WeightPerUnit;
	}
	internal sealed class FilletCatalog
	{
		internal static readonly FilletCatalog Empty = new FilletCatalog(new List<FilletEntry>());

		internal readonly List<FilletEntry> Entries;

		private readonly Dictionary<string, FilletEntry> byName = new Dictionary<string, FilletEntry>(StringComparer.Ordinal);

		private readonly string signature;

		internal FilletCatalog(List<FilletEntry> entries)
		{
			if (entries.Count > 256)
			{
				throw new FormatException("At most 256 fillet entries are supported.");
			}
			foreach (FilletEntry entry in entries)
			{
				entry.Prefabname = FilletApi.CanonicalPrefabName(entry.Prefabname);
				if (entry.PrefabnameCooked != null)
				{
					entry.PrefabnameCooked = entry.PrefabnameCooked.Trim();
				}
				if (entry.UseModel != null)
				{
					entry.UseModel = (string.IsNullOrWhiteSpace(entry.UseModel) ? "FishRaw" : entry.UseModel.Trim());
				}
			}
			entries.Sort((FilletEntry a, FilletEntry b) => string.Compare(a.Prefabname, b.Prefabname, StringComparison.Ordinal));
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			foreach (FilletEntry entry2 in entries)
			{
				if (entry2.Prefabname == null || entry2.PrefabnameCooked == null || entry2.Title == null || entry2.Description == null || entry2.UseModel == null || !entry2.Prefabname.StartsWith("dbff_RawFish_", StringComparison.Ordinal) || entry2.Prefabname.Length <= "dbff_RawFish_".Length || entry2.Prefabname.Length > 256 || entry2.Title.Length > 512 || entry2.Description.Length > 8192 || entry2.UseModel.Length > 256 || entry2.PrefabnameCooked.Length > 256 || (entry2.WeightPerUnit.HasValue && (float.IsNaN(entry2.WeightPerUnit.Value) || float.IsInfinity(entry2.WeightPerUnit.Value) || entry2.WeightPerUnit.Value < 0f)))
				{
					throw new FormatException("Invalid fillet entry or weight: " + entry2.Prefabname);
				}
				if (byName.ContainsKey(entry2.Prefabname))
				{
					throw new FormatException("Duplicate prefab: " + entry2.Prefabname);
				}
				byName.Add(entry2.Prefabname, entry2);
				string[] array = new string[6]
				{
					entry2.Prefabname,
					entry2.PrefabnameCooked,
					entry2.Title,
					entry2.Description,
					entry2.UseModel,
					entry2.WeightPerUnit?.ToString("R", CultureInfo.InvariantCulture) ?? ""
				};
				foreach (string text in array)
				{
					num += Encoding.UTF8.GetByteCount(text) + 8;
					stringBuilder.Append(text.Length).Append(':').Append(text);
				}
			}
			if (num > 32768)
			{
				throw new FormatException("Fillet item data exceeds the 32 KiB synchronization limit.");
			}
			Entries = entries;
			signature = stringBuilder.ToString();
		}

		internal FilletEntry Find(string prefab)
		{
			if (!byName.TryGetValue(prefab, out var value))
			{
				return null;
			}
			return value;
		}

		internal bool Same(FilletCatalog other)
		{
			if (other != null)
			{
				return signature == other.signature;
			}
			return false;
		}

		internal void Write(ZPackage data)
		{
			data.Write(Entries.Count);
			foreach (FilletEntry entry in Entries)
			{
				data.Write(entry.Prefabname);
				data.Write(entry.Title);
				data.Write(entry.Description);
				data.Write(entry.WeightPerUnit.HasValue);
				if (entry.WeightPerUnit.HasValue)
				{
					data.Write(entry.WeightPerUnit.Value);
				}
				bool flag = entry.UseModel != "FishRaw";
				data.Write(flag);
				if (flag)
				{
					data.Write(entry.UseModel);
				}
				bool flag2 = entry.PrefabnameCooked.Length > 0;
				data.Write(flag2);
				if (flag2)
				{
					data.Write(entry.PrefabnameCooked);
				}
			}
		}

		internal static FilletCatalog Read(ZPackage data)
		{
			int num = data.ReadInt();
			if (num < 0 || num > 256)
			{
				throw new FormatException("Invalid fillet entry count.");
			}
			List<FilletEntry> list = new List<FilletEntry>();
			for (int i = 0; i < num; i++)
			{
				list.Add(new FilletEntry
				{
					Prefabname = data.ReadString(),
					Title = data.ReadString(),
					Description = data.ReadString(),
					WeightPerUnit = (data.ReadBool() ? new float?(data.ReadSingle()) : ((float?)null)),
					UseModel = (data.ReadBool() ? data.ReadString() : "FishRaw"),
					PrefabnameCooked = (data.ReadBool() ? data.ReadString() : "")
				});
			}
			return new FilletCatalog(list);
		}
	}
	internal static class FilletYaml
	{
		internal const string Header = "# Field Filleting - unique fillet item data\n# Live file: BepInEx/config/FieldFilleting/fillet.yaml\n# Multiplayer uses the server's values; single-player uses your local file.\n# Save valid changes to update crafting previews, inventory items and tooltips live.\n# Top-level keys select existing dbff_ fillets; fields use two-space indentation.\n# Blank displayName, description or weightPerUnit inherits the native default.\n# Blank PrefabnameCooked uses Raw Fish's cooked output, normally FishCooked.\n# useModel controls appearance only; blank defaults to FishRaw.\n# Text supports localization tokens. Weight is per item; zero is allowed.\n\n";

		private static string Key(string value)
		{
			switch (Scalar(value).Replace(" ", "").Replace("_", "").Replace("-", "")
				.ToLowerInvariant())
			{
			case "prefab":
			case "prefabname":
				return "prefab";
			case "prefabnamecooked":
				return "cooked";
			case "title":
			case "commonname":
			case "displayname":
				return "title";
			case "description":
			case "desc":
				return "description";
			case "weight":
			case "weightperunit":
				return "weight";
			case "usemodel":
				return "model";
			default:
				throw new FormatException("Unknown field: " + value);
			}
		}

		private static string Uncomment(string line)
		{
			char c = '\0';
			bool flag = true;
			for (int i = 0; i < line.Length; i++)
			{
				char c2 = line[i];
				if (c != 0)
				{
					if (c == '"' && c2 == '\\')
					{
						i++;
					}
					else if (c == '\'' && c2 == '\'' && i + 1 < line.Length && line[i + 1] == '\'')
					{
						i++;
					}
					else if (c2 == c)
					{
						c = '\0';
					}
					continue;
				}
				if (c2 == '#' && (i == 0 || char.IsWhiteSpace(line[i - 1])))
				{
					return line.Substring(0, i);
				}
				if (flag && (c2 == '\'' || c2 == '"'))
				{
					c = c2;
					flag = false;
				}
				else if (c2 == ':' && (i + 1 == line.Length || char.IsWhiteSpace(line[i + 1])))
				{
					flag = true;
				}
				else if ((!flag || c2 != '-' || i + 1 >= line.Length || !char.IsWhiteSpace(line[i + 1])) && !char.IsWhiteSpace(c2))
				{
					flag = false;
				}
			}
			if (c != 0)
			{
				throw new FormatException("Unclosed quote.");
			}
			return line;
		}

		private static string Scalar(string value)
		{
			value = value.Trim();
			if (value.Length == 0 || value == "~" || value.Equals("null", StringComparison.OrdinalIgnoreCase))
			{
				return "";
			}
			char c = value[0];
			if (c != '\'' && c != '"')
			{
				if ("[{&*!".IndexOf(c) >= 0)
				{
					throw new FormatException("Use a scalar value, not a YAML collection, anchor or tag.");
				}
				return value;
			}
			if (value.Length < 2 || value[value.Length - 1] != c)
			{
				throw new FormatException("Invalid quoted value.");
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 1; i < value.Length - 1; i++)
			{
				char c2 = value[i];
				if (c2 == c)
				{
					if (c == '\'' && i + 1 < value.Length - 1 && value[i + 1] == '\'')
					{
						stringBuilder.Append('\'');
						i++;
						continue;
					}
					throw new FormatException("Escape a quote inside a quoted value.");
				}
				if (c == '"' && c2 == '\\')
				{
					if (++i >= value.Length - 1)
					{
						throw new FormatException("Incomplete escape.");
					}
					c2 = value[i];
					int num;
					int num2;
					int result;
					switch (c2)
					{
					case 'n':
						c2 = '\n';
						break;
					case 'r':
						c2 = '\r';
						break;
					case 't':
						c2 = '\t';
						break;
					case 'b':
						c2 = '\b';
						break;
					case 'f':
						c2 = '\f';
						break;
					case '0':
						c2 = '\0';
						break;
					case 'x':
						num = 2;
						goto IL_01a0;
					case 'u':
						num = 4;
						goto IL_01a0;
					default:
						throw new FormatException("Unsupported escape. Use quoted \\n or a Description: | block for line breaks.");
					case '"':
					case '/':
					case '\\':
						break;
						IL_01a0:
						num2 = num;
						if (i + num2 >= value.Length - 1 || !int.TryParse(value.Substring(i + 1, num2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result))
						{
							throw new FormatException("Invalid Unicode escape.");
						}
						stringBuilder.Append((char)result);
						i += num2;
						continue;
					}
				}
				stringBuilder.Append(c2);
			}
			return stringBuilder.ToString();
		}

		private static int Indent(string line)
		{
			int i;
			for (i = 0; i < line.Length && line[i] == ' '; i++)
			{
			}
			if (i < line.Length && line[i] == '\t')
			{
				throw new FormatException("Use spaces for indentation, not tabs.");
			}
			return i;
		}

		private static string Block(string[] lines, ref int index, int fieldIndent, string style)
		{
			List<string> list = new List<string>();
			int num = -1;
			while (index + 1 < lines.Length)
			{
				string text = lines[index + 1];
				int num2 = Indent(text);
				if (text.Trim().Length != 0 && num2 <= fieldIndent)
				{
					break;
				}
				if (text.Trim().Length != 0)
				{
					if (num < 0)
					{
						num = num2;
					}
					if (num2 < num)
					{
						throw new FormatException("Inconsistent block-scalar indentation.");
					}
				}
				list.Add((text.Trim().Length == 0) ? "" : text.Substring(num));
				index++;
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < list.Count; i++)
			{
				if (i > 0)
				{
					if (style[0] == '|')
					{
						stringBuilder.Append('\n');
					}
					else if (list[i].Length == 0)
					{
						stringBuilder.Append('\n');
					}
					else if (list[i - 1].Length != 0)
					{
						stringBuilder.Append((list[i].StartsWith(" ") || list[i - 1].StartsWith(" ")) ? '\n' : ' ');
					}
				}
				stringBuilder.Append(list[i]);
			}
			string text2 = stringBuilder.ToString();
			if (style.EndsWith("-"))
			{
				return text2.TrimEnd('\n');
			}
			if (style.EndsWith("+"))
			{
				return text2 + ((list.Count > 0) ? "\n" : "");
			}
			return text2.TrimEnd('\n') + ((text2.Length > 0) ? "\n" : "");
		}

		internal static FilletCatalog Parse(string yaml)
		{
			if (yaml == null || Encoding.UTF8.GetByteCount(yaml) > 262144)
			{
				throw new FormatException("YAML file is missing or exceeds 256 KiB.");
			}
			string[] array = yaml.TrimStart('\ufeff').Replace("\r\n", "\n").Replace('\r', '\n')
				.Split('\n');
			if (array.Length != 0 && array[^1].Length == 0)
			{
				Array.Resize(ref array, array.Length - 1);
			}
			List<FilletEntry> list = new List<FilletEntry>();
			FilletEntry filletEntry = null;
			HashSet<string> hashSet = new HashSet<string>();
			bool? flag = null;
			bool flag2 = false;
			for (int i = 0; i < array.Length; i++)
			{
				try
				{
					int num = Indent(array[i]);
					string text = Uncomment(array[i]).Trim();
					if (text.Length == 0)
					{
						continue;
					}
					switch (text)
					{
					case "...":
						goto end_IL_008c;
					case "[]":
					case "{}":
						if (filletEntry != null || list.Count != 0)
						{
							break;
						}
						goto end_IL_008c;
					}
					if (num == 0)
					{
						if (filletEntry != null)
						{
							if (filletEntry.Prefabname.Length == 0)
							{
								throw new FormatException("Every entry needs a Prefabname.");
							}
							list.Add(filletEntry);
						}
						bool flag3 = text == "-" || text.StartsWith("- ", StringComparison.Ordinal);
						if (flag.HasValue && flag.Value != flag3)
						{
							throw new FormatException("Do not mix list entries and prefab mappings.");
						}
						flag = flag3;
						flag2 = false;
						filletEntry = new FilletEntry();
						hashSet.Clear();
						if (flag3)
						{
							text = text.Substring(1).Trim();
							num = 2;
							if (text.Length != 0)
							{
								goto IL_0292;
							}
							continue;
						}
						int num2 = text.LastIndexOf(':');
						if (num2 <= 0 || text.Substring(num2 + 1).Trim().Length != 0)
						{
							throw new FormatException("Use a prefab name followed by ':' and fields indented by two spaces.");
						}
						filletEntry.Prefabname = Scalar(text.Substring(0, num2));
						hashSet.Add("prefab");
						continue;
					}
					if (filletEntry == null)
					{
						throw new FormatException("Every field needs a prefab entry.");
					}
					if (flag == false && num == 2 && text == "basics:")
					{
						if (flag2 || hashSet.Count != 1)
						{
							throw new FormatException("Do not mix grouped and flat fields.");
						}
						flag2 = true;
						continue;
					}
					if (num != (flag2 ? 4 : 2))
					{
						throw new FormatException("Use two spaces for flat fields, or four inside legacy basics.");
					}
					if (flag2 && text.StartsWith("- ", StringComparison.Ordinal))
					{
						text = text.Substring(2).TrimStart();
					}
					goto IL_0292;
					IL_0292:
					int num3 = text.IndexOf(':');
					if (num3 <= 0)
					{
						throw new FormatException("Expected a field followed by ':'.");
					}
					string text2 = Key(text.Substring(0, num3));
					if (!hashSet.Add(text2))
					{
						throw new FormatException("Duplicate field: " + text2);
					}
					string text3 = text.Substring(num3 + 1).Trim();
					string text4;
					switch (text3)
					{
					case "|":
					case "|-":
					case "|+":
					case ">":
					case ">-":
					case ">+":
						text4 = Block(array, ref i, num, text3);
						break;
					default:
						text4 = Scalar(text3);
						break;
					}
					switch (text2)
					{
					case "prefab":
						filletEntry.Prefabname = text4;
						continue;
					case "cooked":
						filletEntry.PrefabnameCooked = text4;
						continue;
					case "title":
						filletEntry.Title = text4;
						continue;
					case "description":
						filletEntry.Description = text4;
						continue;
					case "model":
						filletEntry.UseModel = text4;
						continue;
					}
					if (text4.Length > 0)
					{
						if (!float.TryParse(text4, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || float.IsNaN(result) || float.IsInfinity(result) || result < 0f)
						{
							throw new FormatException("weightPerUnit must be a finite non-negative number; use a decimal point.");
						}
						filletEntry.WeightPerUnit = result;
					}
					end_IL_008c:;
				}
				catch (FormatException ex)
				{
					throw new FormatException("YAML line " + (i + 1) + ": " + ex.Message, ex);
				}
			}
			if (filletEntry != null)
			{
				if (filletEntry.Prefabname.Length == 0)
				{
					throw new FormatException("Every entry needs a Prefabname.");
				}
				list.Add(filletEntry);
			}
			return new FilletCatalog(list);
		}

		private static string Quote(string value)
		{
			StringBuilder stringBuilder = new StringBuilder("\"");
			foreach (char c in value)
			{
				switch (c)
				{
				case '\\':
					stringBuilder.Append("\\\\");
					continue;
				case '"':
					stringBuilder.Append("\\\"");
					continue;
				case '\n':
					stringBuilder.Append("\\n");
					continue;
				case '\r':
					stringBuilder.Append("\\r");
					continue;
				case '\t':
					stringBuilder.Append("\\t");
					continue;
				}
				if (char.IsControl(c) || c == '\u0085' || c == '\u2028' || c == '\u2029')
				{
					StringBuilder stringBuilder2 = stringBuilder.Append("\\u");
					int num = c;
					stringBuilder2.Append(num.ToString("x4", CultureInfo.InvariantCulture));
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.Append('"').ToString();
		}

		internal static string Serialize(FilletCatalog catalog)
		{
			StringBuilder stringBuilder = new StringBuilder("# Field Filleting - unique fillet item data\n# Live file: BepInEx/config/FieldFilleting/fillet.yaml\n# Multiplayer uses the server's values; single-player uses your local file.\n# Save valid changes to update crafting previews, inventory items and tooltips live.\n# Top-level keys select existing dbff_ fillets; fields use two-space indentation.\n# Blank displayName, description or weightPerUnit inherits the native default.\n# Blank PrefabnameCooked uses Raw Fish's cooked output, normally FishCooked.\n# useModel controls appearance only; blank defaults to FishRaw.\n# Text supports localization tokens. Weight is per item; zero is allowed.\n\n");
			if (catalog.Entries.Count == 0)
			{
				return stringBuilder.Append("{}\n").ToString();
			}
			foreach (FilletEntry entry in catalog.Entries)
			{
				bool flag = true;
				string prefabname = entry.Prefabname;
				foreach (char c in prefabname)
				{
					if (!char.IsLetterOrDigit(c) && c != '_')
					{
						flag = false;
						break;
					}
				}
				stringBuilder.Append(flag ? entry.Prefabname : Quote(entry.Prefabname)).Append(":\n").Append("  displayName: ")
					.Append(Quote(entry.Title))
					.Append('\n')
					.Append("  description: ")
					.Append(Quote(entry.Description))
					.Append('\n')
					.Append("  useModel: ")
					.Append((entry.UseModel == "FishRaw") ? "FishRaw" : Quote(entry.UseModel))
					.Append('\n')
					.Append("  weightPerUnit: ")
					.Append(entry.WeightPerUnit?.ToString("R", CultureInfo.InvariantCulture) ?? "")
					.Append('\n')
					.Append("  PrefabnameCooked:")
					.Append((entry.PrefabnameCooked.Length == 0) ? "" : (" " + Quote(entry.PrefabnameCooked)))
					.Append("\n\n");
			}
			return stringBuilder.ToString();
		}

		internal static string WithCurrentSchema(string yaml)
		{
			FilletCatalog filletCatalog = Parse(yaml);
			string[] array = yaml.TrimStart('\ufeff').Replace("\r\n", "\n").Replace('\r', '\n')
				.Split('\n');
			bool flag = true;
			for (int i = 0; i < array.Length && flag; i++)
			{
				int num = Indent(array[i]);
				string text = Uncomment(array[i]).Trim();
				if (text.Length == 0)
				{
					continue;
				}
				switch (text)
				{
				case "---":
				case "...":
				case "{}":
					continue;
				}
				if (num == 0)
				{
					int num2 = text.LastIndexOf(':');
					flag = num2 > 0 && text.Substring(num2 + 1).Trim().Length == 0;
					if (flag)
					{
						string text2 = Scalar(text.Substring(0, num2));
						flag = FilletApi.CanonicalPrefabName(text2) == text2;
					}
					continue;
				}
				int num3 = text.IndexOf(':');
				string text3 = ((num3 > 0) ? text.Substring(0, num3).Trim() : "");
				int num4;
				if (num == 2)
				{
					switch (text3)
					{
					default:
						num4 = ((text3 == "PrefabnameCooked") ? 1 : 0);
						break;
					case "displayName":
					case "description":
					case "useModel":
					case "weightPerUnit":
						num4 = 1;
						break;
					}
				}
				else
				{
					num4 = 0;
				}
				flag = (byte)num4 != 0;
				if (flag)
				{
					string text4 = text.Substring(num3 + 1).Trim();
					switch (text4)
					{
					case "|":
					case "|-":
					case "|+":
					case ">":
					case ">-":
					case ">+":
						Block(array, ref i, num, text4);
						break;
					}
				}
			}
			if (flag)
			{
				return yaml;
			}
			string text5 = Serialize(filletCatalog);
			if (!filletCatalog.Same(Parse(text5)))
			{
				throw new FormatException("YAML migration would change existing item values.");
			}
			return text5;
		}
	}
	internal sealed class FilletData : IDisposable
	{
		private struct FileStamp
		{
			internal bool Exists;

			internal long Length;

			internal long Write;

			internal long Created;

			internal static FileStamp Read(string path)
			{
				FileInfo fileInfo = new FileInfo(path);
				if (!fileInfo.Exists)
				{
					return default(FileStamp);
				}
				return new FileStamp
				{
					Exists = true,
					Length = fileInfo.Length,
					Write = fileInfo.LastWriteTimeUtc.Ticks,
					Created = fileInfo.CreationTimeUtc.Ticks
				};
			}

			internal bool Same(FileStamp other)
			{
				if (Exists == other.Exists && Length == other.Length && Write == other.Write)
				{
					return Created == other.Created;
				}
				return false;
			}
		}

		internal static FilletData Instance;

		internal const string DirectoryName = "FieldFilleting";

		internal const string FileName = "fillet.yaml";

		internal const string ItemsFileName = "FilletItems.yaml";

		internal const string PreviousFileName = "FieldFilleting.Fillets.yaml";

		internal readonly string FilePath;

		internal FilletCatalog Local = FilletCatalog.Empty;

		internal FilletCatalog Remote;

		private readonly bool observeFiles;

		private FileSystemWatcher watcher;

		private long reloadAt;

		private long pollAt;

		private long watcherRetryAt;

		private long applyAt;

		private int watcherFailed;

		private volatile bool disposed;

		private bool retryApply;

		private bool haveStamp;

		private FileStamp observed;

		private string reloadError;

		private string watcherError;

		private string applyError;

		private string migrationError;

		internal FilletCatalog Effective
		{
			get
			{
				if (!Locked)
				{
					return Local;
				}
				return Remote ?? FilletCatalog.Empty;
			}
		}

		internal bool Locked { get; private set; }

		internal event Action AuthorityChanged;

		internal static string GetPath(string configDirectory)
		{
			return Path.Combine(configDirectory, "FieldFilleting", "fillet.yaml");
		}

		private static string CanonicalPath(string path)
		{
			string fullPath = Path.GetFullPath(path);
			string fileName = Path.GetFileName(fullPath);
			if (!string.Equals(fileName, "FieldFilleting.Fillets.yaml", StringComparison.OrdinalIgnoreCase) && !string.Equals(fileName, "FishGrazingAsImGoing.Fillets.yaml", StringComparison.OrdinalIgnoreCase) && !string.Equals(fileName, "FilletItems.yaml", StringComparison.OrdinalIgnoreCase))
			{
				return fullPath;
			}
			string directoryName = Path.GetDirectoryName(fullPath);
			if (!string.Equals(Path.GetFileName(directoryName), "FieldFilleting", StringComparison.OrdinalIgnoreCase))
			{
				return GetPath(directoryName);
			}
			return Path.Combine(directoryName, "fillet.yaml");
		}

		internal FilletData(string path, bool watch = true)
		{
			FilePath = CanonicalPath(path);
			observeFiles = watch;
			Instance = this;
			try
			{
				Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
				List<string> list = LegacyPaths();
				if (!File.Exists(FilePath))
				{
					if (list.Count > 0)
					{
						ImportLegacy(list);
					}
					else
					{
						using FileStream stream = new FileStream(FilePath, FileMode.CreateNew, FileAccess.Write);
						using StreamWriter streamWriter = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
						streamWriter.Write(ReadApprovedDefaults());
					}
				}
				if (UpdateSchema())
				{
					foreach (string item in list)
					{
						ArchiveLegacyFile(item);
					}
				}
				Reload();
			}
			catch (Exception ex)
			{
				Plugin.Warn("Fillet YAML setup failed: " + ex.Message);
			}
			if (observeFiles)
			{
				Observe(DateTime.UtcNow.Ticks);
				StartWatcher(DateTime.UtcNow.Ticks);
			}
		}

		private List<string> LegacyPaths()
		{
			string directoryName = Path.GetDirectoryName(FilePath);
			bool flag = string.Equals(Path.GetFileName(directoryName), "FieldFilleting", StringComparison.OrdinalIgnoreCase);
			List<string> list = new List<string>();
			string[] array = ((!flag) ? new string[1] { directoryName } : new string[2]
			{
				directoryName,
				Path.GetDirectoryName(directoryName)
			});
			foreach (string text in array)
			{
				if (!Directory.Exists(text))
				{
					continue;
				}
				string[] files = Directory.GetFiles(text);
				Array.Sort(files, (IComparer<string>?)StringComparer.Ordinal);
				string[] array2 = new string[4] { "FilletItems.yaml", "FieldFilleting.Fillets.yaml", "FishGrazingAsImGoing.Fillets.yaml", "fillet.yaml" };
				foreach (string text2 in array2)
				{
					string[] array3 = files;
					foreach (string text3 in array3)
					{
						if (text3 != FilePath && (string.Equals(Path.GetFileName(text3), text2, StringComparison.OrdinalIgnoreCase) || string.Equals(Path.GetFileName(text3), Path.ChangeExtension(text2, ".yml"), StringComparison.OrdinalIgnoreCase)))
						{
							list.Add(text3);
						}
					}
				}
				if (!flag || !(text == directoryName))
				{
					continue;
				}
				array2 = files;
				foreach (string text4 in array2)
				{
					if (text4 != FilePath && !list.Contains(text4) && (string.Equals(Path.GetExtension(text4), ".yaml", StringComparison.OrdinalIgnoreCase) || string.Equals(Path.GetExtension(text4), ".yml", StringComparison.OrdinalIgnoreCase)))
					{
						list.Add(text4);
					}
				}
			}
			return list;
		}

		private static string ReadStable(string path, out FileStamp stamp)
		{
			stamp = FileStamp.Read(path);
			if (!stamp.Exists || stamp.Length > 262144)
			{
				throw new IOException("Fillet YAML is missing or exceeds 256 KiB: " + path);
			}
			byte[] array = File.ReadAllBytes(path);
			if (array.Length > 262144 || !stamp.Same(FileStamp.Read(path)))
			{
				throw new IOException("Fillet YAML changed while being read: " + path);
			}
			return Encoding.UTF8.GetString(array);
		}

		private void ImportLegacy(List<string> paths)
		{
			List<FilletEntry> list = new List<FilletEntry>();
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			Dictionary<string, FileStamp> dictionary = new Dictionary<string, FileStamp>(StringComparer.Ordinal);
			string text = null;
			foreach (string path in paths)
			{
				try
				{
					FileStamp stamp;
					string text2 = ReadStable(path, out stamp);
					string text3 = (IsLegacyDefault(text2) ? ReadApprovedDefaults() : FilletYaml.WithCurrentSchema(text2));
					FilletCatalog filletCatalog = FilletYaml.Parse(text3);
					dictionary.Add(path, stamp);
					if (text == null)
					{
						text = text3;
					}
					foreach (FilletEntry entry in filletCatalog.Entries)
					{
						if (hashSet.Add(entry.Prefabname))
						{
							list.Add(entry);
						}
					}
				}
				catch (Exception ex)
				{
					Plugin.Warn("Could not migrate fillet YAML; the original file is kept: " + path + ". " + ex.Message);
				}
			}
			if (text == null)
			{
				throw new FormatException("No existing fillet YAML is valid; fix the original file before migration.");
			}
			string text4 = ((dictionary.Count == 1) ? text : FilletYaml.Serialize(new FilletCatalog(list)));
			FilletYaml.Parse(text4);
			string text5 = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp";
			try
			{
				File.WriteAllText(text5, text4, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				foreach (KeyValuePair<string, FileStamp> item in dictionary)
				{
					if (!item.Value.Same(FileStamp.Read(item.Key)))
					{
						throw new IOException("Fillet YAML changed during migration: " + item.Key);
					}
				}
				File.Move(text5, FilePath);
				Plugin.LogInfo("Migrated " + dictionary.Count + " fillet YAML file(s) to " + FilePath + ". Earlier files take priority for duplicate species; original files are backed up.");
			}
			finally
			{
				if (File.Exists(text5))
				{
					File.Delete(text5);
				}
			}
		}

		private void ArchiveLegacyFile(string source)
		{
			if (!File.Exists(source))
			{
				return;
			}
			try
			{
				FilletYaml.Parse(ReadStable(source, out var stamp));
				string text = Path.Combine(Path.GetDirectoryName(FilePath), Path.GetFileName(source) + ".bak");
				if (File.Exists(text))
				{
					text = text + "." + Guid.NewGuid().ToString("N");
				}
				if (!stamp.Same(FileStamp.Read(source)))
				{
					throw new IOException("Fillet YAML changed before archival.");
				}
				File.Move(source, text);
				Plugin.LogInfo("Backed up obsolete fillet YAML to " + text + ". Edit " + FilePath + " for live changes.");
			}
			catch (IOException ex)
			{
				Plugin.Warn("Could not archive obsolete fillet YAML; the active file is " + FilePath + ". " + ex.Message);
			}
			catch (UnauthorizedAccessException ex2)
			{
				Plugin.Warn("Could not archive obsolete fillet YAML; the active file is " + FilePath + ". " + ex2.Message);
			}
			catch (FormatException ex3)
			{
				Plugin.Warn("Invalid legacy fillet YAML is kept for correction: " + source + ". " + ex3.Message);
			}
		}

		private static string ReadApprovedDefaults()
		{
			using Stream stream = typeof(Plugin).Assembly.GetManifestResourceStream("FieldFilleting.FilletsDefaults");
			using StreamReader streamReader = new StreamReader(stream ?? throw new FileNotFoundException("Bundled fillet YAML is unavailable."));
			return streamReader.ReadToEnd();
		}

		private static bool IsLegacyDefault(string text)
		{
			if (text.IndexOf("Prefabname: FGAGI_RawFish_", StringComparison.Ordinal) < 0)
			{
				return false;
			}
			FilletCatalog filletCatalog = FilletYaml.Parse(text);
			FilletCatalog filletCatalog2 = FilletYaml.Parse(ReadApprovedDefaults());
			if (filletCatalog.Entries.Count != filletCatalog2.Entries.Count)
			{
				return false;
			}
			foreach (FilletEntry entry in filletCatalog2.Entries)
			{
				FilletEntry filletEntry = filletCatalog.Find(entry.Prefabname);
				string text2 = entry.Prefabname.Substring("dbff_RawFish_".Length).ToLowerInvariant();
				if (text2 == "fish4_cave")
				{
					text2 = "fish4";
				}
				if (filletEntry == null || filletEntry.Title != "$item_fish_raw ($animal_" + text2 + ")" || filletEntry.Description != "" || filletEntry.WeightPerUnit.GetValueOrDefault() != 1f || filletEntry.UseModel != "FishRaw" || filletEntry.PrefabnameCooked != "")
				{
					return false;
				}
			}
			return true;
		}

		private string NormalizeFile(string text, FileStamp before)
		{
			string text2 = null;
			try
			{
				bool flag = IsLegacyDefault(text);
				string text3 = (flag ? ReadApprovedDefaults() : FilletYaml.WithCurrentSchema(text));
				if (text3 == text)
				{
					return text;
				}
				text2 = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp";
				File.WriteAllText(text2, text3, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				if (!before.Same(FileStamp.Read(FilePath)))
				{
					throw new IOException("Fillet YAML changed during migration; waiting for the save to finish.");
				}
				string text4 = FilePath + (flag ? ".legacy-default.bak" : ".schema.bak");
				if (File.Exists(text4))
				{
					text4 = text4 + "." + Guid.NewGuid().ToString("N");
				}
				File.Replace(text2, FilePath, text4);
				text2 = null;
				Plugin.LogInfo("Converted fillet YAML to flat dbff entries in " + FilePath + ". Original data is backed up at " + text4 + ".");
				return text3;
			}
			finally
			{
				if (text2 != null)
				{
					try
					{
						File.Delete(text2);
					}
					catch (IOException)
					{
					}
					catch (UnauthorizedAccessException)
					{
					}
				}
			}
		}

		private bool UpdateSchema()
		{
			try
			{
				FileStamp stamp;
				string text = ReadStable(FilePath, out stamp);
				NormalizeFile(text, stamp);
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Warn("Could not migrate fillet YAML; original files are kept. " + ex.Message);
				return false;
			}
		}

		private bool IsTarget(string path)
		{
			return string.Equals(path, FilePath, StringComparison.OrdinalIgnoreCase);
		}

		private void FileChanged(object sender, FileSystemEventArgs args)
		{
			if (IsTarget(args.FullPath))
			{
				QueueReload();
			}
		}

		private void FileRenamed(object sender, RenamedEventArgs args)
		{
			if (IsTarget(args.FullPath) || IsTarget(args.OldFullPath))
			{
				QueueReload();
			}
		}

		private void WatchError(object sender, ErrorEventArgs args)
		{
			Interlocked.Exchange(ref watcherFailed, 1);
			QueueReload();
		}

		private void StartWatcher(long now)
		{
			watcherRetryAt = now + 50000000;
			try
			{
				watcher?.Dispose();
				watcher = null;
				watcher = new FileSystemWatcher(Path.GetDirectoryName(FilePath), "*");
				watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime;
				watcher.Changed += FileChanged;
				watcher.Created += FileChanged;
				watcher.Deleted += FileChanged;
				watcher.Renamed += FileRenamed;
				watcher.Error += WatchError;
				watcher.EnableRaisingEvents = true;
				watcherError = null;
			}
			catch (Exception ex)
			{
				watcher?.Dispose();
				watcher = null;
				if (watcherError != ex.Message)
				{
					Plugin.Warn("Fillet YAML watcher unavailable; file checks remain active. " + ex.Message);
				}
				watcherError = ex.Message;
			}
		}

		internal void QueueReload()
		{
			if (!disposed)
			{
				Interlocked.Exchange(ref reloadAt, DateTime.UtcNow.AddMilliseconds(750.0).Ticks);
			}
		}

		private void Observe(long now)
		{
			try
			{
				FileStamp fileStamp = FileStamp.Read(FilePath);
				if (haveStamp && !fileStamp.Same(observed))
				{
					Interlocked.CompareExchange(ref reloadAt, now + 7500000, 0L);
				}
				observed = fileStamp;
				haveStamp = true;
			}
			catch (IOException)
			{
				Interlocked.CompareExchange(ref reloadAt, now + 10000000, 0L);
			}
			catch (UnauthorizedAccessException)
			{
				Interlocked.CompareExchange(ref reloadAt, now + 10000000, 0L);
			}
		}

		internal void Tick()
		{
			Tick(DateTime.UtcNow);
		}

		internal void Tick(DateTime utcNow)
		{
			if (disposed)
			{
				return;
			}
			long ticks = utcNow.Ticks;
			if (observeFiles && ticks >= pollAt)
			{
				pollAt = ticks + 10000000;
				Observe(ticks);
				if (ticks >= watcherRetryAt && (watcher == null || Interlocked.CompareExchange(ref watcherFailed, 0, 0) != 0))
				{
					Interlocked.Exchange(ref watcherFailed, 0);
					StartWatcher(ticks);
				}
			}
			long num = Interlocked.Read(in reloadAt);
			if (num != 0L && ticks >= num && Interlocked.CompareExchange(ref reloadAt, 0L, num) == num)
			{
				Reload(utcNow);
			}
			if (retryApply && ticks >= applyAt)
			{
				Apply(utcNow);
			}
		}

		private FilletCatalog ReadCatalog()
		{
			FileStamp fileStamp = FileStamp.Read(FilePath);
			if (!fileStamp.Exists)
			{
				throw new FileNotFoundException("Fillet YAML is missing.", FilePath);
			}
			if (fileStamp.Length > 262144)
			{
				throw new FormatException("YAML file exceeds 256 KiB.");
			}
			string text;
			using (FileStream stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
			{
				using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
				char[] array = new char[4096];
				StringBuilder stringBuilder = new StringBuilder();
				int num;
				while ((num = streamReader.Read(array, 0, array.Length)) > 0)
				{
					if (stringBuilder.Length + num > 262144)
					{
						throw new FormatException("YAML file exceeds 256 KiB.");
					}
					stringBuilder.Append(array, 0, num);
				}
				text = stringBuilder.ToString();
			}
			FileStamp fileStamp2 = FileStamp.Read(FilePath);
			if (!fileStamp.Same(fileStamp2))
			{
				throw new IOException("Fillet YAML changed during reading; waiting for the save to finish.");
			}
			FilletCatalog result = FilletYaml.Parse(text);
			try
			{
				string text2 = NormalizeFile(text, fileStamp2);
				if (text2 != text)
				{
					result = FilletYaml.Parse(text2);
					fileStamp2 = FileStamp.Read(FilePath);
				}
				migrationError = null;
			}
			catch (IOException)
			{
				throw;
			}
			catch (Exception ex2)
			{
				if (migrationError != ex2.Message)
				{
					Plugin.Warn("Valid legacy fillet data loaded, but its on-disk conversion failed: " + ex2.Message);
				}
				migrationError = ex2.Message;
			}
			observed = fileStamp2;
			haveStamp = true;
			return result;
		}

		internal void Reload()
		{
			Reload(DateTime.UtcNow);
		}

		private void Reload(DateTime now)
		{
			if (disposed)
			{
				return;
			}
			FilletCatalog filletCatalog;
			try
			{
				filletCatalog = ReadCatalog();
				reloadError = null;
			}
			catch (Exception ex)
			{
				string text = ex.GetType().Name + ": " + ex.Message;
				if (reloadError != text)
				{
					Plugin.Warn("Fillet YAML reload failed; keeping the last valid catalog. " + FilePath + ": " + text);
				}
				reloadError = text;
				if (ex is IOException && !(ex is FileNotFoundException) && !(ex is DirectoryNotFoundException))
				{
					Interlocked.Exchange(ref reloadAt, now.AddMilliseconds(750.0).Ticks);
				}
				return;
			}
			if (!filletCatalog.Same(Local))
			{
				Local = filletCatalog;
				if (!Locked)
				{
					Apply(now);
					this.AuthorityChanged?.Invoke();
				}
				Plugin.LogInfo("Loaded " + filletCatalog.Entries.Count + " fillet YAML entries from " + FilePath + (Locked ? ". Local preferences saved; multiplayer item data is controlled by the server." : (retryApply ? ". Catalog accepted; item refresh is pending and will retry." : (". " + UniqueFilletItems.DataStatus()))));
			}
		}

		private void Apply(DateTime now)
		{
			try
			{
				UniqueFilletCooking.RefreshAll(ObjectDB.instance);
				UniqueFilletItems.RefreshData();
				retryApply = false;
				applyError = null;
			}
			catch (Exception innerException)
			{
				retryApply = true;
				applyAt = now.AddSeconds(1.0).Ticks;
				if (innerException is TargetInvocationException && innerException.InnerException != null)
				{
					innerException = innerException.InnerException;
				}
				if (applyError != innerException.Message)
				{
					Plugin.Warn("Fillet YAML was accepted, but item refresh is pending and will retry. " + innerException);
				}
				applyError = innerException.Message;
			}
			FilletUiRefresh.Queue();
		}

		internal void SetClient(bool client)
		{
			if (Locked != client)
			{
				Locked = client;
				Remote = null;
				Apply(DateTime.UtcNow);
			}
		}

		internal void Receive(FilletCatalog data)
		{
			if (Locked && data != null)
			{
				Remote = data;
				Apply(DateTime.UtcNow);
			}
		}

		internal void WaitForServer()
		{
			if (Locked && Remote != null)
			{
				Remote = null;
				Apply(DateTime.UtcNow);
			}
		}

		public void Dispose()
		{
			if (!disposed)
			{
				watcher?.Dispose();
				watcher = null;
				SetClient(client: false);
				disposed = true;
				retryApply = false;
				Interlocked.Exchange(ref reloadAt, 0L);
				if (Instance == this)
				{
					Instance = null;
				}
			}
		}
	}
	internal static class FilletDiscovery
	{
		internal const string SaveKey = "dannanboi.fieldfilleting.recipeNotifications.v1";

		private static Player character;

		private static Dictionary<string, string> customData;

		private static readonly HashSet<string> announced = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<string> seen = new HashSet<string>(StringComparer.Ordinal);

		private static FieldInfo playerData;

		private static FieldInfo hudInstance;

		private static Action<MessageHud, Sprite, string, string> queueUnlock;

		private static Func<ItemData, Sprite> getIcon;

		private static bool pending;

		private static bool waitingForTool;

		private static bool warned;

		private static float retryAt;

		internal static void Queue()
		{
			pending = true;
			retryAt = 0f;
		}

		internal static void InventoryChanged(Player player)
		{
			if (character != player || waitingForTool)
			{
				Queue();
			}
		}

		private static void ResolveApi()
		{
			if (playerData == null)
			{
				playerData = AccessTools.Field(typeof(Player), "m_customData");
			}
			if (hudInstance == null)
			{
				hudInstance = AccessTools.Field(typeof(MessageHud), "m_instance");
			}
			if (queueUnlock == null)
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(MessageHud), "QueueUnlockMsg", new Type[3]
				{
					typeof(Sprite),
					typeof(string),
					typeof(string)
				}, (Type[])null);
				if (methodInfo == null)
				{
					throw new MissingMethodException("MessageHud", "QueueUnlockMsg");
				}
				queueUnlock = (Action<MessageHud, Sprite, string, string>)Delegate.CreateDelegate(typeof(Action<MessageHud, Sprite, string, string>), methodInfo);
			}
			if (getIcon == null)
			{
				MethodInfo methodInfo2 = AccessTools.Method(typeof(ItemData), "GetIcon", Type.EmptyTypes, (Type[])null);
				if (methodInfo2 == null)
				{
					throw new MissingMethodException("ItemData", "GetIcon");
				}
				getIcon = (Func<ItemData, Sprite>)Delegate.CreateDelegate(typeof(Func<ItemData, Sprite>), methodInfo2);
			}
			if (playerData?.FieldType != typeof(Dictionary<string, string>) || hudInstance?.FieldType != typeof(MessageHud))
			{
				throw new MissingMemberException("Character discovery save/HUD API is unavailable.");
			}
		}

		internal static void Tick(float now)
		{
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Invalid comparison between Unknown and I4
			if (!pending || now < retryAt)
			{
				return;
			}
			retryAt = now + 1f;
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated())
			{
				pending = false;
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || !SettingsNetwork.CanFillet || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return;
			}
			bool changed = false;
			try
			{
				ResolveApi();
				object? value = hudInstance.GetValue(null);
				MessageHud val = (MessageHud)((value is MessageHud) ? value : null);
				if ((Object)(object)val == (Object)null || !(playerData.GetValue(localPlayer) is Dictionary<string, string> dictionary))
				{
					return;
				}
				if (character != localPlayer || customData != dictionary)
				{
					character = localPlayer;
					customData = dictionary;
					announced.Clear();
					if (dictionary.TryGetValue("dannanboi.fieldfilleting.recipeNotifications.v1", out var value2) && !string.IsNullOrEmpty(value2))
					{
						string[] array = value2.Split('\n');
						foreach (string text in array)
						{
							if (!string.IsNullOrEmpty(text))
							{
								announced.Add(text);
							}
						}
					}
				}
				Recipe handRecipe = Filleting.GetHandRecipe();
				Recipe sourceRecipe = Filleting.SourceRecipe;
				if ((Object)(object)handRecipe == (Object)null || sourceRecipe?.m_resources == null)
				{
					return;
				}
				bool flag = Filleting.HasFilletingTool(localPlayer);
				bool flag2 = Filleting.RecipeDiscovered(localPlayer, handRecipe);
				bool flag3 = !Filleting.RawFishCraftingDisabled;
				waitingForTool = flag3 && !flag && flag2 && !announced.Contains("hand:FishRaw");
				int num;
				if (ModSettings.UniqueFillets.Value)
				{
					num = (sourceRecipe.m_requireOnlyOneIngredient ? 1 : 0);
					if (num != 0)
					{
						if ((Object)(object)ZNetScene.instance != (Object)null)
						{
							UniqueFilletItems.RegisterScene(ZNetScene.instance, beforeAwake: false);
						}
						else
						{
							UniqueFilletItems.Ensure(ObjectDB.instance);
						}
					}
				}
				else
				{
					num = 0;
				}
				pending = false;
				seen.Clear();
				if (flag3 && flag && flag2)
				{
					Notify(val, "hand:FishRaw", sourceRecipe.m_item, "Hand filleting", ref changed);
				}
				if (num == 0)
				{
					return;
				}
				Requirement[] resources = sourceRecipe.m_resources;
				foreach (Requirement val2 in resources)
				{
					ItemDrop val3 = val2?.m_resItem;
					if (val3 == null || (int)(val3.m_itemData?.m_shared?.m_itemType).GetValueOrDefault() != 21 || val2.m_amount <= 0 || !localPlayer.IsKnownMaterial(val3.m_itemData.m_shared.m_name))
					{
						continue;
					}
					string name = ((Object)((Component)val3).gameObject).name;
					if (!seen.Add(name))
					{
						continue;
					}
					string text2 = Uri.EscapeDataString(name);
					if (!flag && !announced.Contains("hand:" + text2))
					{
						waitingForTool = true;
					}
					bool flag4 = !announced.Contains("table:" + text2);
					bool flag5 = flag && !announced.Contains("hand:" + text2);
					if (!flag4 && !flag5)
					{
						continue;
					}
					ItemDrop val4 = UniqueFilletItems.Find(ObjectDB.instance, name);
					if ((Object)(object)val4 == (Object)null)
					{
						pending = true;
						continue;
					}
					if (flag4)
					{
						Notify(val, "table:" + text2, val4, sourceRecipe.m_craftingStation?.m_name ?? "Preparation table", ref changed);
					}
					if (flag5)
					{
						Notify(val, "hand:" + text2, val4, "Hand filleting", ref changed);
					}
				}
			}
			catch (Exception ex)
			{
				pending = true;
				if (!warned)
				{
					warned = true;
					Plugin.Warn("Fillet discovery notifications will retry: " + ex.GetBaseException().Message);
				}
			}
			finally
			{
				if (changed && customData != null)
				{
					List<string> list = new List<string>(announced);
					list.Sort(StringComparer.Ordinal);
					customData["dannanboi.fieldfilleting.recipeNotifications.v1"] = string.Join("\n", list);
				}
			}
		}

		private static void Notify(MessageHud hud, string key, ItemDrop item, string context, ref bool changed)
		{
			if (!announced.Contains(key) && item?.m_itemData?.m_shared != null)
			{
				queueUnlock(hud, getIcon(item.m_itemData), "$msg_newrecipe", item.m_itemData.m_shared.m_name + " (" + context + ")");
				announced.Add(key);
				changed = true;
			}
		}

		internal static void Reset()
		{
			character = null;
			customData = null;
			announced.Clear();
			seen.Clear();
			pending = (waitingForTool = false);
			retryAt = 0f;
		}
	}
	[HarmonyPatch(typeof(Player), "Load")]
	internal static class FilletDiscoveryLoadPatch
	{
		private static void Postfix(Player __instance)
		{
			if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
			{
				FilletDiscovery.Reset();
				FilletDiscovery.Queue();
			}
		}
	}
	internal sealed class FilletIcons : IDisposable
	{
		private sealed class Entry
		{
			internal Sprite[] Icons;

			internal Texture2D Texture;

			internal byte[] Bytes;

			internal Stamp Observed;

			internal bool Seen;

			internal string Error;

			internal int Retries;
		}

		private struct Stamp
		{
			internal string Path;

			internal long Length;

			internal long Write;

			internal long Created;

			internal static Stamp Read(string path)
			{
				if (path == null)
				{
					return default(Stamp);
				}
				FileInfo fileInfo = new FileInfo(path);
				if (!fileInfo.Exists)
				{
					return default(Stamp);
				}
				return new Stamp
				{
					Path = path,
					Length = fileInfo.Length,
					Write = fileInfo.LastWriteTimeUtc.Ticks,
					Created = fileInfo.CreationTimeUtc.Ticks
				};
			}

			internal bool Same(Stamp other)
			{
				if (Path == other.Path && Length == other.Length && Write == other.Write)
				{
					return Created == other.Created;
				}
				return false;
			}
		}

		internal static FilletIcons Instance;

		internal readonly string DirectoryPath;

		private const int MaxBytes = 8388608;

		private const int MaxDimension = 2048;

		private readonly Dictionary<string, Entry> entries = new Dictionary<string, Entry>(StringComparer.Ordinal);

		private readonly bool observeFiles;

		private FileSystemWatcher watcher;

		private long reloadAt;

		private long pollAt;

		private long watcherRetryAt;

		private int watcherFailed;

		private volatile bool disposed;

		private bool suspended;

		private string directoryError;

		private string watcherError;

		private static bool Headless
		{
			get
			{
				//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)
				{
					if ((Object)(object)ZNet.instance != (Object)null)
					{
						return ZNet.instance.IsDedicated();
					}
					return false;
				}
				return true;
			}
		}

		internal static string GetPath(string configDirectory)
		{
			return Path.Combine(configDirectory, "FieldFilleting", "icons");
		}

		internal FilletIcons(string path, bool watch = true)
		{
			DirectoryPath = Path.GetFullPath(path);
			observeFiles = watch;
			Instance = this;
			try
			{
				Directory.CreateDirectory(DirectoryPath);
			}
			catch (Exception ex)
			{
				WarnDirectory(ex);
			}
			Plugin.LogInfo("Fillet icons: " + DirectoryPath + " (local PNG files, matched by prefab name).");
			if (observeFiles && !Headless)
			{
				StartWatcher(DateTime.UtcNow.Ticks);
			}
		}

		internal void Register(string prefab)
		{
			if (!disposed && !entries.ContainsKey(prefab))
			{
				entries.Add(prefab, new Entry());
				Interlocked.Exchange(ref reloadAt, DateTime.UtcNow.Ticks);
			}
		}

		internal Sprite[] Find(string prefab)
		{
			Register(prefab);
			if (!entries.TryGetValue(prefab, out var value))
			{
				return null;
			}
			return value.Icons;
		}

		private static bool IsIcon(string path)
		{
			if (Path.GetFileNameWithoutExtension(path).StartsWith("dbff_RawFish_", StringComparison.Ordinal))
			{
				return string.Equals(Path.GetExtension(path), ".png", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		private void Changed(object sender, FileSystemEventArgs args)
		{
			if (IsIcon(args.FullPath))
			{
				QueueReload();
			}
		}

		private void Renamed(object sender, RenamedEventArgs args)
		{
			if (IsIcon(args.FullPath) || IsIcon(args.OldFullPath))
			{
				QueueReload();
			}
		}

		private void WatchError(object sender, ErrorEventArgs args)
		{
			Interlocked.Exchange(ref watcherFailed, 1);
			QueueReload();
		}

		internal void QueueReload()
		{
			if (!disposed)
			{
				Interlocked.Exchange(ref reloadAt, DateTime.UtcNow.AddMilliseconds(750.0).Ticks);
			}
		}

		private void WarnDirectory(Exception ex)
		{
			if (directoryError != ex.Message)
			{
				Plugin.Warn("Fillet icons could not be checked; existing icons are retained. " + ex.Message);
			}
			directoryError = ex.Message;
		}

		private void StartWatcher(long now)
		{
			watcherRetryAt = now + 50000000;
			try
			{
				watcher?.Dispose();
				watcher = null;
				Directory.CreateDirectory(DirectoryPath);
				watcher = new FileSystemWatcher(DirectoryPath, "*");
				watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime;
				watcher.Changed += Changed;
				watcher.Created += Changed;
				watcher.Deleted += Changed;
				watcher.Renamed += Renamed;
				watcher.Error += WatchError;
				watcher.EnableRaisingEvents = true;
				watcherError = null;
			}
			catch (Exception ex)
			{
				watcher?.Dispose();
				watcher = null;
				if (watcherError != ex.Message)
				{
					Plugin.Warn("Fillet icon watcher unavailable; metadata checks remain active. " + ex.Message);
				}
				watcherError = ex.Message;
			}
		}

		private Dictionary<string, string> Paths()
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
			if (!Directory.Exists(DirectoryPath))
			{
				return dictionary;
			}
			string[] files = Directory.GetFiles(DirectoryPath);
			Array.Sort(files, (IComparer<string>?)StringComparer.Ordinal);
			string[] array = files;
			foreach (string text in array)
			{
				if (IsIcon(text))
				{
					string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
					if (entries.ContainsKey(fileNameWithoutExtension) && !dictionary.ContainsKey(fileNameWithoutExtension))
					{
						dictionary.Add(fileNameWithoutExtension, text);
					}
				}
			}
			return dictionary;
		}

		internal void Tick()
		{
			Tick(DateTime.UtcNow);
		}

		internal void Tick(DateTime utcNow)
		{
			if (disposed)
			{
				return;
			}
			if (Headless)
			{
				if (!suspended)
				{
					watcher?.Dispose();
					watcher = null;
					suspended = true;
				}
				return;
			}
			long ticks = utcNow.Ticks;
			if (suspended)
			{
				suspended = false;
				pollAt = (watcherRetryAt = 0L);
				Interlocked.Exchange(ref reloadAt, ticks);
			}
			if (observeFiles && ticks >= pollAt)
			{
				pollAt = ticks + 20000000;
				try
				{
					if (entries.Count > 0)
					{
						Dictionary<string, string> dictionary = Paths();
						foreach (KeyValuePair<string, Entry> entry in entries)
						{
							dictionary.TryGetValue(entry.Key, out var value);
							Stamp observed = Stamp.Read(value);
							Entry value2 = entry.Value;
							if (!value2.Seen || !observed.Same(value2.Observed))
							{
								Interlocked.CompareExchange(ref reloadAt, ticks + 7500000, 0L);
							}
							value2.Observed = observed;
							value2.Seen = true;
						}
					}
					if (ticks >= watcherRetryAt && (watcher == null || Interlocked.CompareExchange(ref watcherFailed, 0, 0) != 0))
					{
						Interlocked.Exchange(ref watcherFailed, 0);
						StartWatcher(ticks);
					}
				}
				catch (Exception ex)
				{
					WarnDirectory(ex);
				}
			}
			long num = Interlocked.Read(in reloadAt);
			if (num != 0L && ticks >= num && Interlocked.CompareExchange(ref reloadAt, 0L, num) == num)
			{
				Reload(utcNow);
			}
		}

		internal void Reload()
		{
			Reload(DateTime.UtcNow);
		}

		private void Reload(DateTime utcNow)
		{
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Expected O, but got Unknown
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			if (disposed || Headless || entries.Count == 0)
			{
				return;
			}
			Dictionary<string, string> dictionary;
			try
			{
				dictionary = Paths();
				directoryError = null;
			}
			catch (Exception ex)
			{
				WarnDirectory(ex);
				return;
			}
			bool flag = false;
			foreach (KeyValuePair<string, Entry> entry in entries)
			{
				Entry value = entry.Value;
				Texture2D val = null;
				Sprite val2 = null;
				try
				{
					dictionary.TryGetValue(entry.Key, out var value2);
					Stamp stamp = (value.Observed = Stamp.Read(value2));
					value.Seen = true;
					if (stamp.Path == null)
					{
						if (value.Icons != null)
						{
							Retire(value);
							value.Icons = null;
							value.Texture = null;
							flag = true;
						}
						value.Bytes = null;
						value.Error = null;
						value.Retries = 0;
						continue;
					}
					if (stamp.Length < 24 || stamp.Length > 8388608)
					{
						throw new FormatException("PNG must be between 24 bytes and 8 MiB.");
					}
					byte[] array;
					using (FileStream fileStream = new FileStream(value2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
					{
						if (fileStream.Length < 24 || fileStream.Length > 8388608)
						{
							throw new IOException("PNG changed during reading.");
						}
						array = new byte[(int)fileStream.Length];
						int i;
						int num;
						for (i = 0; i < array.Length; i += num)
						{
							if ((num = fileStream.Read(array, i, array.Length - i)) <= 0)
							{
								break;
							}
						}
						if (i != array.Length || fileStream.ReadByte() != -1)
						{
							throw new IOException("PNG changed during reading.");
						}
					}
					if (!stamp.Same(Stamp.Read(value2)))
					{
						throw new IOException("PNG changed during reading.");
					}
					if (value.Bytes != null && array.SequenceEqual(value.Bytes))
					{
						value.Error = null;
						value.Retries = 0;
						continue;
					}
					ValidatePng(array);
					val = new Texture2D(2, 2, (TextureFormat)4, false)
					{
						name = entry.Key + "_Icon",
						filterMode = (FilterMode)1,
						wrapMode = (TextureWrapMode)1
					};
					if (!ImageConversion.LoadImage(val, array, true))
					{
						throw new FormatException("Unity could not decode this PNG.");
					}
					val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f, 0u, (SpriteMeshType)0);
					if ((Object)(object)val2 == (Object)null)
					{
						throw new FormatException("Unity could not create the icon sprite.");
					}
					((Object)val2).name = entry.Key + "_Icon";
					Retire(value);
					value.Texture = val;
					value.Icons = (Sprite[])(object)new Sprite[1] { val2 };
					value.Bytes = array;
					value.Error = null;
					value.Retries = 0;
					val = null;
					val2 = null;
					flag = true;
				}
				catch (Exception ex2)
				{
					if ((Object)(object)val2 != (Object)null)
					{
						Object.Destroy((Object)(object)val2);
					}
					if ((Object)(object)val != (Object)null)
					{
						Object.Destroy((Object)(object)val);
					}
					if (value.Error != ex2.Message)
					{
						Plugin.Warn("Could not load fillet icon " + entry.Key + ".png; keeping its previous/default icon. " + ex2.Message);
					}
					value.Error = ex2.Message;
					if (ex2 is IOException && value.Retries++ < 3)
					{
						Interlocked.CompareExchange(ref reloadAt, utcNow.AddSeconds(1.0).Ticks, 0L);
					}
				}
			}
			if (flag)
			{
				UniqueFilletItems.RefreshIcons();
				FilletUiRefresh.Queue();
			}
		}

		internal static void ValidatePng(byte[] bytes)
		{
			byte[] array = new byte[16]
			{
				137, 80, 78, 71, 13, 10, 26, 10, 0, 0,
				0, 13, 73, 72, 68, 82
			};
			if (bytes.Length < 24 || !bytes.Take(array.Length).SequenceEqual(array))
			{
				throw new FormatException("Expected a PNG image with an IHDR header.");
			}
			long num = (long)(((ulong)bytes[16] << 24) | ((ulong)bytes[17] << 16) | ((ulong)bytes[18] << 8) | bytes[19]);
			long num2 = (long)(((ulong)bytes[20] << 24) | ((ulong)bytes[21] << 16) | ((ulong)bytes[22] << 8) | bytes[23]);
			if (num < 1 || num2 < 1 || num > 2048 || num2 > 2048)
			{
				throw new FormatException("PNG dimensions must be between 1 and 2048 pixels per side.");
			}
		}

		private static void Retire(Entry entry)
		{
			if (entry.Icons != null)
			{
				Sprite[] icons = entry.Icons;
				for (int i = 0; i < icons.Length; i++)
				{
					Object.Destroy((Object)(object)icons[i], 120f);
				}
			}
			if ((Object)(object)entry.Texture != (Object)null)
			{
				Object.Destroy((Object)(object)entry.Texture, 120f);
			}
		}

		public void Dispose()
		{
			if (disposed)
			{
				return;
			}
			disposed = true;
			watcher?.Dispose();
			watcher = null;
			if (Instance == this)
			{
				Instance = null;
				UniqueFilletItems.RefreshIcons();
			}
			foreach (Entry value in entries.Values)
			{
				if (value.Icons != null)
				{
					Sprite[] icons = value.Icons;
					for (int i = 0; i < icons.Length; i++)
					{
						Object.Destroy((Object)(object)icons[i]);
					}
				}
				if ((Object)(object)value.Texture != (Object)null)
				{
					Object.Destroy((Object)(object)value.Texture);
				}
			}
			entries.Clear();
		}
	}
	[HarmonyPatch(typeof(ItemData), "GetIcon")]
	internal static class FilletItemIconPatch
	{
		internal static void Prefix(ItemData __instance)
		{
			UniqueFilletItems.RefreshIcon(__instance);
		}
	}
	internal sealed class FilletModelTag : MonoBehaviour
	{
		public string Model;

		public bool[] NativeRenderers;

		public bool[] NativeLods;
	}
	internal static class FilletModels
	{
		private sealed class State
		{
			internal GameObject Original;

			internal GameObject Current;

			internal GameObject Source;

			internal Renderer[] Renderers;

			internal LODGroup[] Lods;

			internal bool[] RendererFlags;

			internal bool[] LodFlags;

			internal string Model = "FishRaw";
		}

		private const string OriginalName = "__dbff_original_model";

		private static ConditionalWeakTable<ItemDrop, State> states = new ConditionalWeakTable<ItemDrop, State>();

		private static readonly HashSet<string> warnings = new HashSet<string>(StringComparer.Ordinal);

		private static GameObject scratch;

		private static bool VisualComponent(Component component)
		{
			if (!(component is Transform) && !(component is MeshFilter) && !(component is MeshRenderer) && !(component is SkinnedMeshRenderer) && !(component is LODGroup))
			{
				return component is Animator;
			}
			return true;
		}

		private static State Bind(ItemDrop drop)
		{
			Transform transform = ((Component)drop).transform;
			Transform val = transform.Find("__dbff_original_model");
			Transform val2 = transform.Find("attach");
			if ((Object)(object)val == (Object)null)
			{
				val = val2;
			}
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			FilletModelTag filletModelTag = ((val2 != null) ? ((Component)val2).GetComponent<FilletModelTag>() : null);
			State state = new State
			{
				Original = ((Component)val).gameObject,
				Current = (((Object)(object)filletModelTag != (Object)null) ? ((Component)val2).gameObject : null),
				Renderers = ((Component)val).GetComponentsInChildren<Renderer>(true),
				Lods = ((Component)val).GetComponentsInChildren<LODGroup>(true),
				Model = (filletModelTag?.Model ?? "FishRaw")
			};
			state.RendererFlags = filletModelTag?.NativeRenderers ?? state.Renderers.Select((Renderer r) => r.enabled).ToArray();
			state.LodFlags = filletModelTag?.NativeLods ?? state.Lods.Select((LODGroup l) => l.enabled).ToArray();
			states.Add(drop, state);
			return state;
		}

		private static void OriginalVisibility(State state, bool visible)
		{
			for (int i = 0; i < state.Renderers.Length; i++)
			{
				if ((Object)(object)state.Renderers[i] != (Object)null)
				{
					state.Renderers[i].enabled = visible && i < state.RendererFlags.Length && state.RendererFlags[i];
				}
			}
			for (int j = 0; j < state.Lods.Length; j++)
			{
				if ((Object)(object)state.Lods[j] != (Object)null)
				{
					state.Lods[j].enabled = visible && j < state.LodFlags.Length && state.LodFlags[j];
				}
			}
			((Object)state.Original).name = (visible ? "attach" : "__dbff_original_model");
		}

		private static void Retire(GameObject visual)
		{
			if (!((Object)(object)visual == (Object)null))
			{
				((Object)visual).name = "__dbff_retired_model";
				visual.SetActive(false);
				Object.Destroy((Object)(object)visual);
			}
		}

		private static GameObject CopyVisual(GameObject source)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if ((Object)(object)scratch == (Object)null)
			{
				scratch = new GameObject("FieldFilleting_ModelCopies");
				scratch.SetActive(false);
				((Object)scratch).hideFlags = (HideFlags)61;
				Object.DontDestroyOnLoad((Object)(object)scratch);
			}
			Transform val = source.transform.Find("attach");
			GameObject val2 = Object.Instantiate<GameObject>(((Object)(object)val == (Object)null) ? source : ((Component)val).gameObject, scratch.transform, false);
			try
			{
				MonoBehaviour[] componentsInChildren = val2.GetComponentsInChildren<MonoBehaviour>(true);
				foreach (MonoBehaviour val3 in componentsInChildren)
				{
					if (!(val3 is ZNetView))
					{
						Object.DestroyImmediate((Object)(object)val3);
					}
				}
				ZNetView[] componentsInChildren2 = val2.GetComponentsInChildren<ZNetView>(true);
				for (int i = 0; i < componentsInChildren2.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
				}
				Component[] componentsInChildren3 = val2.GetComponentsInChildren<Component>(true);
				Component[] array = componentsInChildren3;
				foreach (Component val4 in array)
				{
					if ((Object)(object)val4 != (Object)null && ((object)val4).GetType().Name == "ParticleSystem")
					{
						Object.DestroyImmediate((Object)(object)val4);
					}
				}
				array = componentsInChildren3;
				foreach (Component val5 in array)
				{
					if ((Object)(object)val5 != (Object)null && !VisualComponent(val5))
					{
						Object.DestroyImmediate((Object)(object)val5);
					}
				}
				if (val2.GetComponentsInChildren<Component>(true).Any((Component c) => !VisualComponent(c)) || !val2.GetComponentsInChildren<Renderer>(true).Any((Renderer r) => r is MeshRenderer || r is SkinnedMeshRenderer))
				{
					throw new InvalidOperationException("The requested item has no usable mesh-only model.");
				}
				return val2;
			}
			catch
			{
				Object.Destroy((Object)(object)val2);
				throw;
			}
		}

		internal static void Apply(ItemDrop drop, string model, ObjectDB database)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			if ((Object)(object)drop == (Object)null || (Object)(object)database == (Object)null || (int)SystemInfo.graphicsDeviceType == 4 || ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated()))
			{
				return;
			}
			model = (string.IsNullOrWhiteSpace(model) ? "FishRaw" : model);
			if (!states.TryGetValue(drop, out var value))
			{
				value = Bind(drop);
			}
			if (value == null)
			{
				if (model != "FishRaw" && warnings.Add("attach:" + drop.m_itemData.m_shared.m_name))
				{
					Plugin.Warn("Fillet useModel could not find its native attach visual; retaining Raw Fish.");
				}
				return;
			}
			GameObject val = null;
			if (model != "FishRaw")
			{
				val = ((model.StartsWith("dbff_RawFish_", StringComparison.Ordinal) || model.StartsWith("FGAGI_RawFish_", StringComparison.Ordinal)) ? null : database.GetItemPrefab(model));
				if ((Object)(object)((val != null) ? val.GetComponent<ItemDrop>() : null) == (Object)null)
				{
					if (warnings.Add("missing:" + model))
					{
						Plugin.Warn("Fillet useModel item '" + model + "' is unavailable; using Raw Fish. Choose an existing non-fillet item prefab name.");
					}
					model = "FishRaw";
					val = null;
				}
			}
			if (value.Model == model && ((Object)(object)val == (Object)null || (Object)(object)value.Source == (Object)(object)val || ((Object)(object)value.Current != (Object)null && (Object)(object)value.Source == (Object)null)))
			{
				value.Source = val;
				return;
			}
			if (model == "FishRaw")
			{
				Retire(value.Current);
				value.Current = null;
				OriginalVisibility(value, visible: true);
				value.Model = model;
				value.Source = null;
				return;
			}
			GameObject val2 = null;
			try
			{
				val2 = CopyVisual(val);
				FilletModelTag filletModelTag = val2.AddComponent<FilletModelTag>();
				filletModelTag.Model = model;
				filletModelTag.NativeRenderers = value.RendererFlags;
				filletModelTag.NativeLods = value.LodFlags;
				Retire(value.Current);
				OriginalVisibility(value, visible: false);
				((Object)val2).name = "attach";
				val2.transform.SetParent(((Component)drop).transform, false);
				val2.SetActive(true);
				value.Current = val2;
				value.Model = model;
				value.Source = val;
			}
			catch (Exception ex)
			{
				if ((Object)(object)val2 != (Object)null)
				{
					Object.Destroy((Object)(object)val2);
				}
				Retire(value.Current);
				value.Current = null;
				OriginalVisibility(value, visible: true);
				value.Model = "FishRaw";
				value.Source = null;
				if (warnings.Add("failed:" + model))
				{
					Plugin.Warn("Fillet useModel '" + model + "' could not be copied; using Raw Fish. " + ex.Message);
				}
			}
		}

		internal static void Reset()
		{
			states = new ConditionalWeakTable<ItemDrop, State>();
			warnings.Clear();
			if ((Object)(object)scratch != (Object)null)
			{
				Object.Destroy((Object)(object)scratch);
			}
			scratch = null;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "UpdateRecipe")]
	internal static class FilletRecipeHintPatch
	{
		internal const string HintKey = "$inventory_onlyoneingredient";

		private static readonly FieldInfo selected = AccessTools.Field(typeof(InventoryGui), "m_selectedRecipe");

		private static readonly FieldInfo recipeField = ((selected == null) ? null : AccessTools.Field(selected.FieldType, "Recipe"));

		private static readonly PropertyInfo recipeProperty = selected?.FieldType.GetProperty("Recipe", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly MethodInfo filter = AccessTools.Method(typeof(FilletRecipeHintPatch), "Filter", new Type[2]
		{
			typeof(string),
			typeof(InventoryGui)
		}, (Type[])null);

		[HarmonyTranspiler]
		internal static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			foreach (CodeInstruction instruction in instructions)
			{
				yield return instruction;
				if (instruction.opcode == OpCodes.Ldstr && instruction.operand is string text && text.IndexOf("$inventory_onlyoneingredient", StringComparison.Ordinal) >= 0)
				{
					yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
					yield return new CodeInstruction(OpCodes.Call, (object)filter);
				}
			}
		}

		internal static string Filter(string hint, InventoryGui gui)
		{
			if ((Object)(object)gui == (Object)null || selected == null || (recipeField == null && recipeProperty == null))
			{
				return hint;
			}
			object value = selected.GetValue(gui);
			if (value == null)
			{
				return hint;
			}
			object? obj = recipeField?.GetValue(value) ?? recipeProperty?.GetValue(value, null);
			if (!UniqueFilletRecipes.IsRecipe((Recipe)((obj is Recipe) ? obj : null)))
			{
				return hint;
			}
			return "";
		}
	}
	internal static class FilletUiRefresh
	{
		private sealed class Binding
		{
			internal InventoryGrid Grid;

			internal ItemData Item;
		}

		private static ConditionalWeakTable<UITooltip, Binding> bindings = new ConditionalWeakTable<UITooltip, Binding>();

		private static readonly FieldInfo current = AccessTools.Field(typeof(UITooltip), "m_current");

		private static readonly FieldInfo containerGrid = AccessTools.Field(typeof(InventoryGui), "m_containerGrid");

		private static readonly MethodInfo create = AccessTools.Method(typeof(InventoryGrid), "CreateItemTooltip", new Type[2]
		{
			typeof(ItemData),
			typeof(UITooltip)
		}, (Type[])null);

		private static readonly MethodInfo update = AccessTools.Method(typeof(UITooltip), "UpdateTextElements", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo inventory = AccessTools.Method(typeof(InventoryGrid), "GetInventory", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo weight = AccessTools.Method(typeof(Inventory), "UpdateTotalWeight", Type.EmptyTypes, (Type[])null);

		internal static bool Pending;

		private static bool warned;

		internal static void Queue()
		{
			Pending = true;
			Plugin.RefreshPending = (Plugin.ForceRefresh = true);
		}

		internal static void Track(InventoryGrid grid, ItemData item, UITooltip tooltip)
		{
			if ((Object)(object)tooltip == (Object)null)
			{
				return;
			}
			if (!UniqueFilletItems.IsFillet(item) && !Filleting.IsPotentialTool(item))
			{
				bindings.Remove(tooltip);
				return;
			}
			if (!bindings.TryGetValue(tooltip, out var value))
			{
				value = new Binding();
				bindings.Add(tooltip, value);
			}
			value.Grid = grid;
			value.Item = item;
		}

		internal static void Refresh(InventoryGui gui, Player player)
		{
			try
			{
				object? obj = containerGrid?.GetValue(gui);
				InventoryGrid val = (InventoryGrid)((obj is InventoryGrid) ? obj : null);
				Inventory val2 = ((player != null) ? ((Humanoid)player).GetInventory() : null);
				Inventory val3 = (Inventory)(((Object)(object)val == (Object)null) ? null : /*isinst with value type is only supported in some contexts*/);
				if (val3 != null && val3 != val2)
				{
					weight?.Invoke(val3, null);
				}
				object? obj2 = current?.GetValue(null);
				UITooltip val4 = (UITooltip)((obj2 is UITooltip) ? obj2 : null);
				if (!((Object)(object)val4 == (Object)null) && bindings.TryGetValue(val4, out var value) && !((Object)(object)value.Grid == (Object)null) && (UniqueFilletItems.IsFillet(value.Item) || Filleting.IsPotentialTool(value.Item)))
				{
					if (create == null || update == null)
					{
						throw new MissingMemberException("Unsupported live item-tooltip API.");
					}
					UniqueFilletItems.RefreshData(value.Item);
					create.Invoke(value.Grid, new object[2] { value.Item, val4 });
					update.Invoke(val4, null);
				}
			}
			catch (Exception innerException)
			{
				if (!warned)
				{
					warned = true;
					if (innerException is TargetInvocationException && innerException.InnerException != null)
					{
						innerException = innerException.InnerException;
					}
					Plugin.Warn("Could not refresh the visible fillet UI. " + innerException);
				}
			}
		}

		internal static void Reset()
		{
			bindings = new ConditionalWeakTable<UITooltip, Binding>();
			Pending = (warned = false);
		}
	}
	[HarmonyPatch(typeof(InventoryGrid), "CreateItemTooltip", new Type[]
	{
		typeof(ItemData),
		typeof(UITooltip)
	})]
	internal static class FilletTooltipDataPatch
	{
		private static void Prefix(InventoryGrid __instance, ItemData __0, UITooltip __1)
		{
			UniqueFilletItems.RefreshData(__0);
			FilletUiRefresh.Track(__instance, __0, __1);
		}
	}
	internal static class HandBloodEffect
	{
		private static GameObject root;

		private static GameObject template;

		private static GameObject source;

		private static GameObject soundSource;

		private static FieldInfo equipment;

		private static FieldInfo leftHand;

		private static FieldInfo rightHand;

		private static FieldInfo playOnAwake;

		private static bool warned;

		internal static void Show(Player player, bool fumble)
		{
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			string text = ModSettings.VisualEffect?.Value;
			if ((text != "Every craft" && (!fumble || text != "Fumbles only")) || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated()))
			{
				return;
			}
			try
			{
				ZNetScene instance = ZNetScene.instance;
				GameObject val = ((instance != null) ? instance.GetPrefab("vfx_BloodHit") : null);
				ConfigEntry<bool> disableSoundSfx = ModSettings.DisableSoundSfx;
				object obj;
				if (disableSoundSfx == null || !disableSoundSfx.Value)
				{
					ZNetScene instance2 = ZNetScene.instance;
					obj = ((instance2 != null) ? instance2.GetPrefab("sfx_blob_hit") : null);
				}
				else
				{
					obj = null;
				}
				GameObject val2 = (GameObject)obj;
				if (!((Object)(object)val == (Object)null))
				{
					if ((Object)(object)template == (Object)null || (Object)(object)source != (Object)(object)val || (Object)(object)soundSource != (Object)(object)val2)
					{
						BuildTemplate(val, val2);
					}
					if (equipment == null)
					{
						equipment = AccessTools.Field(typeof(Humanoid), "m_visEquipment");
						leftHand = AccessTools.Field(typeof(VisEquipment), "m_leftHand");
						rightHand = AccessTools.Field(typeof(VisEquipment), "m_rightHand");
					}
					object obj2 = equipment?.GetValue(player);
					Transform val3 = (Transform)((obj2 == null) ? null : /*isinst with value type is only supported in some contexts*/);
					Transform val4 = (Transform)((obj2 == null) ? null : /*isinst with value type is only supported in some contexts*/);
					Vector3 val5 = (((Object)(object)val3 != (Object)null && (Object)(object)val4 != (Object)null) ? ((val3.position + val4.position) * 0.5f) : (((Object)(object)val4 != (Object)null) ? val4.position : (((Object)(object)val3 != (Object)null) ? val3.position : (((Character)player).GetCenterPoint() + ((Component)player).transform.forward * 0.35f))));
					Object.Destroy((Object)(object)Object.Instantiate<GameObject>(template, val5, ((Component)player).transform.rotation), 3f);
				}
			}
			catch (Exception ex)
			{
				if (!warned)
				{
					warned = true;
					Plugin.Warn("Local filleting blood effect was unavailable: " + ex.Message);
				}
			}
		}

		private static void BuildTemplate(GameObject prefab, GameObject sound)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			Dispose();
			root = new GameObject("FieldFilleting_LocalEffects");
			root.SetActive(false);
			((Object)root).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)root);
			template = Object.Instantiate<GameObject>(prefab, root.transform, false);
			if ((Object)(object)sound != (Object)null)
			{
				GameObject val = Object.Instantiate<GameObject>(sound, template.transform, false);
				val.transform.localPosition = Vector3.zero;
				val.SetActive(true);
				if (playOnAwake == null)
				{
					playOnAwake = AccessTools.Field(typeof(ZSFX), "m_playOnAwake");
				}
				if (playOnAwake?.FieldType == typeof(bool))
				{
					ZSFX[] componentsInChildren = val.GetComponentsInChildren<ZSFX>(true);
					foreach (ZSFX obj in componentsInChildren)
					{
						playOnAwake.SetValue(obj, true);
					}
				}
			}
			TimedDestruction[] componentsInChildren2 = template.GetComponentsInChildren<TimedDestruction>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
			}
			ZNetView[] componentsInChildren3 = template.GetComponentsInChildren<ZNetView>(true);
			for (int i = 0; i < componentsInChildren3.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren3[i]);
			}
			((Object)template).name = "FieldFilleting_LocalBlood";
			template.transform.localScale = Vector3.one * 0.25f;
			template.SetActive(true);
			source = prefab;
			soundSource = sound;
		}

		internal static void Dispose()
		{
			if ((Object)(object)root != (Object)null)
			{
				Object.Destroy((Object)(object)root);
			}
			root = (template = (source = (soundSource = null)));
		}
	}
	internal static class HandCraftAnimation
	{
		private static MethodInfo getAnimation;

		private static MethodInfo getHash;

		private static MethodInfo hasParameter;

		private static Func<Humanoid, ItemData> rightItem;

		private static Func<Humanoid, ItemData> leftItem;

		private static Func<Humanoid, bool, bool, bool> hideItems;

		private static Func<Player, bool> minorAction;

		private static FieldInfo craftRecipe;

		private static FieldInfo craftTimer;

		private static Player player;

		private static Player pendingPlayer;

		private static ZSyncAnimation animation;

		private static ZSyncAnimation pendingAnimation;

		private static float sheathReadyAt;

		private static bool hashesReady;

		private static bool integerCrafting;

		private static bool warnedParameters;

		private static int stationAnimation;

		private static int craftingHash;

		private static int stationHash;

		private static int craftingAnimatorHash;

		private static int stationAnimatorHash;

		internal static int StationAnimation => stationAnimation;

		internal static void ValidateApi()
		{
			if (getAnimation == null)
			{
				getAnimation = AccessTools.Method(typeof(Player), "GetZAnim", Type.EmptyTypes, (Type[])null);
			}
			if (getHash == null)
			{
				getHash = AccessTools.Method(typeof(ZSyncAnimation), "GetHash", new Type[1] { typeof(string) }, (Type[])null);
			}
			if (hasParameter == null)
			{
				hasParameter = AccessTools.Method(typeof(ZSyncAnimation), "HasParameter", new Type[2]
				{
					typeof(string),
					typeof(AnimatorControllerParameterType)
				}, (Type[])null);
			}
			if (craftRecipe == null)
			{
				craftRecipe = AccessTools.Field(typeof(InventoryGui), "m_craftRecipe");
			}
			if (craftTimer == null)
			{
				craftTimer = AccessTools.Field(typeof(InventoryGui), "m_craftTimer");
			}
			if (rightItem == null)
			{
				rightItem = Resolve<Func<Humanoid, ItemData>>(typeof(Humanoid), "GetRightItem", Type.EmptyTypes);
			}
			if (leftItem == null)
			{
				leftItem = Resolve<Func<Humanoid, ItemData>>(typeof(Humanoid), "GetLeftItem", Type.EmptyTypes);
			}
			if (hideItems == null)
			{
				hideItems = Resolve<Func<Humanoid, bool, bool, bool>>(typeof(Humanoid), "HideHandItems", new Type[2]
				{
					typeof(bool),
					typeof(bool)
				});
			}
			if (minorAction == null)
			{
				minorAction = Resolve<Func<Player, bool>>(typeof(Player), "InMinorAction", Type.EmptyTypes);
			}
			if (getAnimation?.ReturnType != typeof(ZSyncAnimation) || getHash?.ReturnType != typeof(int) || hasParameter?.ReturnType != typeof(bool))
			{
				throw new MissingMemberException("Native crafting animation state/API is unavailable.");
			}
		}

		private static T Resolve<T>(Type owner, string name, Type[] arguments) where T : class
		{
			MethodInfo methodInfo = AccessTools.Method(owner, name, arguments, (Type[])null);
			if (methodInfo == null)
			{
				throw new MissingMethodException(owner.Name, name);
			}
			return (T)(object)Delegate.CreateDelegate(typeof(T), methodInfo);
		}

		private static bool HasHeldItems(Player target)
		{
			if (rightItem((Humanoid)(object)target) == null)
			{
				return leftItem((Humanoid)(object)target) != null;
			}
			return true;
		}

		internal static bool Owns(Player target)
		{
			if ((Object)(object)player != (Object)null)
			{
				return player == target;
			}
			return false;
		}

		internal static bool Active(Player target)
		{
			if (!Owns(target))
			{
				if ((Object)(object)pendingPlayer != (Object)null)
				{
					return pendingPlayer == target;
				}
				return false;
			}
			return true;
		}

		internal static bool Owns(ZSyncAnimation target)
		{
			if ((Object)(object)player != (Object)null)
			{
				return animation == target;
			}
			return false;
		}

		internal static bool CraftingParameter(string name)
		{
			if (!integerCrafting)
			{
				return name == "crafting";
			}
			return false;
		}

		internal static bool CraftingParameter(int hash)
		{
			if (!integerCrafting)
			{
				if (hash != craftingHash)
				{
					return hash == craftingAnimatorHash;
				}
				return true;
			}
			return false;
		}

		internal static bool StationParameter(string name)
		{
			return name == (integerCrafting ? "crafting" : "crafting_station");
		}

		internal static bool StationParameter(int hash)
		{
			if (!integerCrafting)
			{
				if (hash != stationHash)
				{
					return hash == stationAnimatorHash;
				}
				return true;
			}
			if (hash != craftingHash)
			{
				return hash == craftingAnimatorHash;
			}
			return true;
		}

		internal static void Sync(Player target, Recipe recipe, float timer)
		{
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			if ((Object)(object)target != (Object)null && (Object)(object)target != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			if (!((Object)(object)target != (Object)null) || !((Object)(object)target == (Object)(object)Player.m_localPlayer) || !(timer >= 0f) || !ActionHooks.AnimationEnabled || !SettingsNetwork.CanFillet || !InventoryGui.IsVisible() || !((Object)(object)target.GetCurrentCraftingStation() == (Object)null) || !Filleting.IsHandRecipe(recipe) || (UniqueFilletRecipes.IsHandRecipe(recipe) && !ModSettings.UniqueFillets.Value))
			{
				Stop();
			}
			else
			{
				if (Owns(target))
				{
					return;
				}
				if ((Object)(object)pendingPlayer == (Object)(object)target)
				{
					if (HasHeldItems(target))
					{
						Cancel(target);
					}
					else if (!(Time.realtimeSinceStartup < sheathReadyAt) && !minorAction(target))
					{
						StartAnimation(target, pendingAnimation);
					}
					return;
				}
				Stop();
				ValidateApi();
				ZSyncAnimation val = (ZSyncAnimation)getAnimation.Invoke(target, null);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				ZNetScene instance = ZNetScene.instance;
				object obj;
				if (instance == null)
				{
					obj = null;
				}
				else
				{
					GameObject prefab = instance.GetPrefab("piece_workbench");
					obj = ((prefab != null) ? prefab.GetComponent<CraftingStation>() : null);
				}
				CraftingStation val2 = (CraftingStation)obj;
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = Filleting.SourceStation;
				}
				if ((Object)(object)val2 == (Object)null)
				{
					return;
				}
				bool flag = HasParameter(val, "crafting", (AnimatorControllerParameterType)3);
				if (!flag && (!HasParameter(val, "crafting", (AnimatorControllerParameterType)4) || !HasParameter(val, "crafting_station", (AnimatorControllerParameterType)3)))
				{
					if (!warnedParameters)
					{
						warnedParameters = true;
						Plugin.Warn("The character controller has no supported crafting animation parameters.");
					}
					return;
				}
				if (!hashesReady)
				{
					craftingHash = (int)getHash.Invoke(null, new object[1] { "crafting" });
					stationHash = (int)getHash.Invoke(null, new object[1] { "crafting_station" });
					craftingAnimatorHash = Animator.StringToHash("crafting");
					stationAnimatorHash = Animator.StringToHash("crafting_station");
					hashesReady = tr