Decompiled source of Fertilizer v1.7.0

Fertilizer.dll

Decompiled 3 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Fertilizer")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.7.0.0")]
[assembly: AssemblyInformationalVersion("1.7.0+3939b2385f3e7265ccfa1742e0b78dfb59270fad")]
[assembly: AssemblyProduct("Fertilizer")]
[assembly: AssemblyTitle("Fertilizer")]
[assembly: AssemblyVersion("1.7.0.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 Fertilizer
{
	internal class DueCommand : ConsoleCommand
	{
		public override string Name => "fertilizer_due";

		public override string Help => "Lists the regrowing plants nearby and when each is next ready. Optionally takes a radius in metres.";

		public override void Run(string[] args, Terminal context)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)ZNet.instance == (Object)null)
			{
				context.AddString("Not in a world.");
				return;
			}
			float num = Scanner.ScanRadius();
			if (args.Length != 0 && float.TryParse(args[0], out var result) && result > 0f)
			{
				num = result;
			}
			Vector3 position = ((Component)localPlayer).transform.position;
			float num2 = num * num;
			List<string> list = new List<string>();
			Pickable[] array = Object.FindObjectsOfType<Pickable>();
			foreach (Pickable val in array)
			{
				if ((Object)(object)val == (Object)null || val.m_respawnTimeMinutes <= 0f)
				{
					continue;
				}
				Vector3 val2 = ((Component)val).transform.position - position;
				if (((Vector3)(ref val2)).sqrMagnitude > num2)
				{
					continue;
				}
				ZNetView component = ((Component)val).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					continue;
				}
				ZDO zDO = component.GetZDO();
				string prefabName = Utils.GetPrefabName(((Component)val).gameObject);
				float num3 = Vector3.Distance(((Component)val).transform.position, position);
				Vine component2 = ((Component)val).GetComponent<Vine>();
				string text = "";
				if ((Object)(object)component2 != (Object)null)
				{
					Tier tier = VineGrowth.TreatedTier(component2);
					if (tier != null)
					{
						text = text + "  [growth: " + tier.DisplayName + "]";
					}
					if (!component2.IsDoneGrowing)
					{
						text = "  still spreading" + text;
					}
				}
				Tier tier2 = Fertilization.TreatedTier(val);
				if (tier2 != null)
				{
					text += (((Object)(object)component2 != (Object)null) ? ("  [berries: " + tier2.DisplayName + "]") : ("  [" + tier2.DisplayName + "]"));
				}
				if (!zDO.GetBool(ZDOVars.s_picked, false))
				{
					list.Add($"{num3:0.0}m  {prefabName}  ready now{text}");
					continue;
				}
				long num4 = zDO.GetLong(ZDOVars.s_pickedTime, 0L);
				if (num4 <= 1)
				{
					list.Add($"{num3:0.0}m  {prefabName}  waiting for its timer{text}");
					continue;
				}
				double num5 = (double)val.m_respawnTimeMinutes - (ZNet.instance.GetTime() - new DateTime(num4)).TotalMinutes;
				list.Add((num5 <= 0.0) ? $"{num3:0.0}m  {prefabName}  due, within a minute{text}" : $"{num3:0.0}m  {prefabName}  {Spell(num5)}{text}");
			}
			if (list.Count == 0)
			{
				context.AddString($"No regrowing plants within {num:0.0}m.");
				Logger.LogInfo((object)$"No regrowing plants within {num:0.0}m.");
				return;
			}
			string text2 = $"Regrowing plants within {num:0.0}m:";
			context.AddString(text2);
			Logger.LogInfo((object)text2);
			foreach (string item in list.OrderBy((string l) => l))
			{
				context.AddString(item);
				Logger.LogInfo((object)("  " + item));
			}
		}

		private static string Spell(double minutes)
		{
			if (minutes < 60.0)
			{
				return $"{minutes:0} min";
			}
			int num = (int)(minutes / 60.0);
			int num2 = (int)(minutes % 60.0);
			if (num2 != 0)
			{
				return $"{num}h {num2}m";
			}
			return $"{num}h";
		}
	}
	internal class FertilizedScale : MonoBehaviour
	{
	}
	internal static class Fertilization
	{
		internal static void Apply(Plant plant)
		{
			if ((Object)(object)plant == (Object)null || !ModConfig.EnableMod.Value || (Object)(object)((Component)plant).GetComponent<FertilizedScale>() != (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)plant).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			if (zDO == null)
			{
				return;
			}
			int num = zDO.GetInt(FertilizerPiece.FertilizedHash, 0);
			if (num > 0)
			{
				Tier tier = Tier.ByLevel(num);
				if (tier?.Reduction != null)
				{
					float num2 = 1f - Mathf.Clamp(tier.Reduction.Value, 0f, 99f) / 100f;
					plant.m_growTime *= num2;
					plant.m_growTimeMax *= num2;
					((Component)plant).gameObject.AddComponent<FertilizedScale>();
				}
			}
		}

		internal static Tier TreatedTier(Pickable pickable)
		{
			ZNetView component = ((Component)pickable).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return null;
			}
			return Tier.ByLevel(component.GetZDO().GetInt(FertilizerPiece.PickedTierHash, 0));
		}
	}
	[HarmonyPatch(typeof(Plant), "GetHoverText")]
	internal static class PlantHoverTextPatch
	{
		private static void Postfix(Plant __instance, ref string __result)
		{
			if (!ModConfig.EnableMod.Value || string.IsNullOrEmpty(__result))
			{
				return;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return;
			}
			int num = component.GetZDO().GetInt(FertilizerPiece.FertilizedHash, 0);
			if (num > 0)
			{
				Tier tier = Tier.ByLevel(num);
				if (tier != null)
				{
					__result = __result + "\n" + tier.DisplayName;
				}
			}
		}
	}
	[HarmonyPatch(typeof(Pickable), "GetHoverText")]
	internal static class PickableHoverTextPatch
	{
		private static void Postfix(Pickable __instance, ref string __result)
		{
			if (!ModConfig.EnableMod.Value)
			{
				return;
			}
			Vine component = ((Component)__instance).GetComponent<Vine>();
			Tier tier = (((Object)(object)component != (Object)null) ? VineGrowth.TreatedTier(component) : null);
			Tier tier2 = Fertilization.TreatedTier(__instance);
			if (tier == null && tier2 == null)
			{
				return;
			}
			string text = __result;
			if (string.IsNullOrEmpty(text))
			{
				text = Localization.instance.Localize(__instance.GetHoverName());
			}
			if ((Object)(object)component == (Object)null)
			{
				__result = text + "\n" + tier2.DisplayName;
				return;
			}
			if (tier != null)
			{
				text = text + "\n" + Localization.instance.Localize("$DHG_fert_growth") + ": " + tier.DisplayName;
			}
			if (tier2 != null)
			{
				text = text + "\n" + Localization.instance.Localize("$DHG_fert_berries") + ": " + tier2.DisplayName;
			}
			__result = text;
		}
	}
	[HarmonyPatch(typeof(Plant), "Awake")]
	internal static class PlantAwakePatch
	{
		private static void Postfix(Plant __instance)
		{
			Fertilization.Apply(__instance);
		}
	}
	[HarmonyPatch(typeof(Plant), "SUpdate")]
	internal static class PlantSUpdatePatch
	{
		private static void Prefix(Plant __instance)
		{
			Fertilization.Apply(__instance);
		}
	}
	internal class FertilizerPiece : MonoBehaviour, IPlaced
	{
		internal static readonly int FertilizedHash = StringExtensionMethods.GetStableHashCode("jelaw_fert_tier");

		internal static readonly int PickedFertilizedHash = StringExtensionMethods.GetStableHashCode("jelaw_fert_picked");

		internal static readonly int PickedTierHash = StringExtensionMethods.GetStableHashCode("jelaw_fert_picked_tier");

		internal static readonly int VineFertilizedHash = StringExtensionMethods.GetStableHashCode("jelaw_fert_vine");

		internal static readonly Func<Plant, float> GetGrowTime = AccessTools.MethodDelegate<Func<Plant, float>>(AccessTools.Method(typeof(Plant), "GetGrowTime", (Type[])null, (Type[])null), (object)null, true);

		private static readonly FieldRef<Pickable, long> PickedTime = AccessTools.FieldRefAccess<Pickable, long>("m_pickedTime");

		private const float VineLinkRadius = 2f;

		private const int VineLinkLimit = 400;

		internal static float Radius()
		{
			Player localPlayer = Player.m_localPlayer;
			float num = (((Object)(object)localPlayer != (Object)null) ? ((Character)localPlayer).GetSkillFactor((SkillType)106) : 0f);
			return Mathf.Lerp(ModConfig.RadiusAtSkill0.Value, ModConfig.RadiusAtSkill100.Value, num);
		}

		private void Awake()
		{
		}

		public void OnPlaced()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if (!ModConfig.EnableMod.Value)
			{
				ZNetScene.instance.Destroy(((Component)this).gameObject);
				return;
			}
			int currentTier = Plugin.CurrentTier;
			float num = Radius();
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			int num6 = 0;
			HashSet<Plant> hashSet = new HashSet<Plant>();
			Collider[] hits = Physics.OverlapSphere(((Component)this).transform.position, num);
			hits = WithConnectedVines(hits);
			Collider[] array = hits;
			for (int i = 0; i < array.Length; i++)
			{
				Plant componentInParent = ((Component)array[i]).GetComponentInParent<Plant>();
				if ((Object)(object)componentInParent == (Object)null || !hashSet.Add(componentInParent))
				{
					continue;
				}
				if ((int)componentInParent.GetStatus() != 0)
				{
					num3++;
					continue;
				}
				ZNetView component = ((Component)componentInParent).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					continue;
				}
				if (!component.IsOwner())
				{
					component.ClaimOwnership();
				}
				if (!component.IsOwner())
				{
					num6++;
					continue;
				}
				ZDO zDO = component.GetZDO();
				if (zDO.GetInt(FertilizedHash, 0) != 0)
				{
					num4++;
					Float(((Component)componentInParent).transform, (TextType)0, "$DHG_already_fertilized");
					continue;
				}
				long ticks = zDO.GetLong(ZDOVars.s_plantTime, ZNet.instance.GetTime().Ticks);
				if ((ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds >= (double)GetGrowTime(componentInParent))
				{
					num5++;
					continue;
				}
				zDO.Set(FertilizedHash, currentTier, false);
				Fertilization.Apply(componentInParent);
				Float(((Component)componentInParent).transform, (TextType)7, $"+{PercentFor(currentTier):0}%");
				num2++;
			}
			num2 += FertilizeVines(hits, currentTier, out var already);
			num4 += already;
			num2 += FertilizePickables(hits, currentTier, out var already2, out var notPickedYet, out var neverRegrows, out var noTimestamp);
			num4 += already2;
			if (num2 > 0)
			{
				PlayEffect();
				RaiseFarming(num2);
			}
			else
			{
				Refund(currentTier);
			}
			if (ModConfig.DebugLogging.Value)
			{
				HashSet<Pickable> hashSet2 = new HashSet<Pickable>();
				array = hits;
				foreach (Collider val in array)
				{
					Pickable val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponentInParent<Pickable>());
					if (!((Object)(object)val2 == (Object)null) && hashSet2.Add(val2))
					{
						ZNetView component2 = ((Component)val2).GetComponent<ZNetView>();
						bool flag = (Object)(object)component2 != (Object)null && component2.IsValid();
						ZDO val3 = (flag ? component2.GetZDO() : null);
						Logger.LogInfo((object)("In range: " + Utils.GetPrefabName(((Component)val2).gameObject) + " id=" + ((val3 == null) ? "none" : ((object)Unsafe.As<ZDOID, ZDOID>(ref val3.m_uid)/*cast due to .constrained prefix*/).ToString()) + " " + $"respawn={val2.m_respawnTimeMinutes:0.#} " + "vine=" + VineState(val2) + " znetview=" + (((Object)(object)component2 == (Object)null) ? "none" : (flag ? "valid" : "invalid")) + " owner=" + ((flag && component2.IsOwner()) ? "yes" : "no") + " " + $"picked={val3 != null && val3.GetBool(ZDOVars.s_picked, false)} " + $"pickedTicks={((val3 == null) ? 0 : val3.GetLong(ZDOVars.s_pickedTime, 0L))}"));
					}
				}
				float num7 = PercentFor(currentTier);
				Logger.LogInfo((object)($"Tier {currentTier} ({num7:0}%) fertilized {num2} plant(s) " + $"from a {num:0.0}m placement " + $"(skipped: {num4} already fertilized, {num3} unhealthy, " + $"{num5} fully grown, {num6} not owned, {notPickedYet} not picked yet, " + $"{already} vines already done, {neverRegrows} never regrow, " + $"{noTimestamp} no pick time yet)"));
			}
			ZNetScene.instance.Destroy(((Component)this).gameObject);
		}

		private static void Refund(int tierLevel)
		{
			Player localPlayer = Player.m_localPlayer;
			ItemDrop val = Tier.ByLevel(tierLevel)?.Drop;
			if (!((Object)(object)localPlayer == (Object)null) && !((Object)(object)val == (Object)null))
			{
				if (!((Humanoid)localPlayer).GetInventory().AddItem(((Component)val).gameObject, 1))
				{
					Logger.LogWarning((object)"Nothing was fertilized and the bone meal could not be returned - inventory full.");
				}
				else if (ModConfig.DebugLogging.Value)
				{
					Logger.LogInfo((object)"Nothing fertilized; bone meal returned.");
				}
			}
		}

		private static void RaiseFarming(int plants)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			Skill val = FarmingSkill(localPlayer);
			float num = val?.m_level ?? (-1f);
			float num2 = val?.m_accumulator ?? (-1f);
			((Character)localPlayer).RaiseSkill((SkillType)106, (float)plants);
			if (ModConfig.DebugLogging.Value)
			{
				Skill val2 = FarmingSkill(localPlayer);
				if (val == null || val2 == null)
				{
					Logger.LogInfo((object)$"Raised Farming by {plants} (skill not readable)");
					return;
				}
				Logger.LogInfo((object)($"Farming +{plants} action(s) for {plants} plant(s): " + $"level {num:0.##} -> {val2.m_level:0.##}, " + $"progress {num2:0.##} -> {val2.m_accumulator:0.##} " + $"({val2.GetLevelPercentage() * 100f:0.#}% to next)" + ((val2.m_level > num) ? "  [LEVEL UP]" : string.Empty)));
			}
		}

		private static Skill FarmingSkill(Player player)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			Skills skills = ((Character)player).GetSkills();
			if ((Object)(object)skills == (Object)null)
			{
				return null;
			}
			foreach (Skill skill in skills.GetSkillList())
			{
				if (skill != null && skill.m_info != null && (int)skill.m_info.m_skill == 106)
				{
					return skill;
				}
			}
			return null;
		}

		private static int FertilizeVines(Collider[] hits, int tierLevel, out int already)
		{
			already = 0;
			HashSet<Vine> hashSet = new HashSet<Vine>();
			int num = 0;
			for (int i = 0; i < hits.Length; i++)
			{
				Vine componentInParent = ((Component)hits[i]).GetComponentInParent<Vine>();
				if ((Object)(object)componentInParent == (Object)null || !hashSet.Add(componentInParent) || componentInParent.IsDoneGrowing)
				{
					continue;
				}
				ZNetView component = ((Component)componentInParent).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					continue;
				}
				if (!component.IsOwner())
				{
					component.ClaimOwnership();
				}
				if (component.IsOwner())
				{
					ZDO zDO = component.GetZDO();
					if (zDO.GetInt(VineFertilizedHash, 0) != 0)
					{
						already++;
						Float(((Component)componentInParent).transform, (TextType)0, "$DHG_already_fertilized");
						continue;
					}
					zDO.Set(VineFertilizedHash, tierLevel, false);
					VineGrowth.Apply(componentInParent);
					Float(((Component)componentInParent).transform, (TextType)7, $"+{PercentFor(tierLevel):0}%");
					num++;
				}
			}
			return num;
		}

		private static int FertilizePickables(Collider[] hits, int tierLevel, out int already, out int notPickedYet, out int neverRegrows, out int noTimestamp)
		{
			already = 0;
			notPickedYet = 0;
			neverRegrows = 0;
			noTimestamp = 0;
			float num = PercentFor(tierLevel);
			HashSet<Pickable> hashSet = new HashSet<Pickable>();
			int num2 = 0;
			for (int i = 0; i < hits.Length; i++)
			{
				Pickable componentInParent = ((Component)hits[i]).GetComponentInParent<Pickable>();
				if ((Object)(object)componentInParent == (Object)null || !hashSet.Add(componentInParent))
				{
					continue;
				}
				if (componentInParent.m_respawnTimeMinutes <= 0f)
				{
					neverRegrows++;
					continue;
				}
				ZNetView component = ((Component)componentInParent).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					continue;
				}
				if (!component.IsOwner())
				{
					component.ClaimOwnership();
				}
				if (!component.IsOwner())
				{
					continue;
				}
				ZDO zDO = component.GetZDO();
				if (!zDO.GetBool(ZDOVars.s_picked, false))
				{
					notPickedYet++;
					continue;
				}
				long num3 = zDO.GetLong(ZDOVars.s_pickedTime, 0L);
				if (num3 <= 1)
				{
					noTimestamp++;
					continue;
				}
				if (zDO.GetInt(PickedTierHash, 0) > 0)
				{
					already++;
					Float(((Component)componentInParent).transform, (TextType)0, "$DHG_already_fertilized");
					continue;
				}
				double totalMinutes = (ZNet.instance.GetTime() - new DateTime(num3)).TotalMinutes;
				double num4 = (double)componentInParent.m_respawnTimeMinutes - totalMinutes;
				if (!(num4 <= 0.0))
				{
					long num5 = num3 - (long)(num4 * ((double)num / 100.0) * 600000000.0);
					if (num5 < 1)
					{
						num5 = 1L;
					}
					zDO.Set(ZDOVars.s_pickedTime, num5);
					PickedTime.Invoke(componentInParent) = num5;
					zDO.Set(PickedTierHash, tierLevel, false);
					if (ModConfig.DebugLogging.Value)
					{
						Logger.LogInfo((object)($"{Utils.GetPrefabName(((Component)componentInParent).gameObject)}: {num4:0.0} min left of " + $"{componentInParent.m_respawnTimeMinutes:0.0}, now {num4 * (1.0 - (double)num / 100.0):0.0}"));
					}
					Float(((Component)componentInParent).transform, (TextType)7, $"+{num:0}%");
					num2++;
				}
			}
			return num2;
		}

		private static string VineState(Pickable pickable)
		{
			Vine component = ((Component)pickable).GetComponent<Vine>();
			if ((Object)(object)component == (Object)null)
			{
				return "none";
			}
			if (!component.IsDoneGrowing)
			{
				return "growing";
			}
			return "done";
		}

		private static Collider[] WithConnectedVines(Collider[] hits)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			HashSet<Vine> hashSet = new HashSet<Vine>();
			Queue<Vine> queue = new Queue<Vine>();
			Collider[] array = hits;
			foreach (Collider val in array)
			{
				Vine val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponentInParent<Vine>());
				if ((Object)(object)val2 != (Object)null && hashSet.Add(val2))
				{
					queue.Enqueue(val2);
				}
			}
			if (queue.Count == 0)
			{
				return hits;
			}
			while (queue.Count > 0 && hashSet.Count < 400)
			{
				array = Physics.OverlapSphere(((Component)queue.Dequeue()).transform.position, 2f);
				foreach (Collider val3 in array)
				{
					Vine val4 = (((Object)(object)val3 == (Object)null) ? null : ((Component)val3).GetComponentInParent<Vine>());
					if ((Object)(object)val4 != (Object)null && hashSet.Add(val4))
					{
						queue.Enqueue(val4);
					}
				}
			}
			List<Collider> list = new List<Collider>(hits);
			foreach (Vine item in hashSet)
			{
				list.AddRange(((Component)item).GetComponentsInChildren<Collider>());
			}
			if (ModConfig.DebugLogging.Value)
			{
				Logger.LogInfo((object)($"Vine reached: {hashSet.Count} segment(s) connected to the {hits.Length} " + "collider(s) in range" + ((hashSet.Count >= 400) ? " (capped)" : "")));
			}
			return list.ToArray();
		}

		private static float PercentFor(int tierLevel)
		{
			return (Tier.ByLevel(tierLevel)?.Reduction?.Value).GetValueOrDefault();
		}

		private static void Float(Transform over, TextType type, string text)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (ModConfig.ShowFloatingText.Value && !((Object)(object)DamageText.instance == (Object)null) && !((Object)(object)over == (Object)null))
			{
				DamageText.instance.ShowText(type, over.position + Vector3.up * 0.4f, Localization.instance.Localize(text), true);
			}
		}

		private void PlayEffect()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			string value = ModConfig.PlaceEffect.Value;
			if (string.IsNullOrEmpty(value))
			{
				return;
			}
			GameObject prefab = PrefabManager.Instance.GetPrefab(value);
			if ((Object)(object)prefab == (Object)null)
			{
				if (ModConfig.DebugLogging.Value)
				{
					Logger.LogWarning((object)("Effect prefab '" + value + "' not found."));
				}
			}
			else
			{
				Object.Instantiate<GameObject>(prefab, ((Component)this).transform.position, Quaternion.identity);
			}
		}
	}
	internal static class Icons
	{
		internal static Sprite Recolour(Sprite source, Color tint)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			Texture2D texture = source.texture;
			Rect textureRect = source.textureRect;
			int num = Mathf.Max(1, (int)((Rect)(ref textureRect)).width);
			int num2 = Mathf.Max(1, (int)((Rect)(ref textureRect)).height);
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0);
			RenderTexture active = RenderTexture.active;
			try
			{
				Graphics.Blit((Texture)(object)texture, temporary);
				RenderTexture.active = temporary;
				Texture2D val = new Texture2D(num, num2, (TextureFormat)5, false);
				val.ReadPixels(new Rect(((Rect)(ref textureRect)).x, ((Rect)(ref textureRect)).y, (float)num, (float)num2), 0, 0);
				Color[] pixels = val.GetPixels();
				for (int i = 0; i < pixels.Length; i++)
				{
					Color val2 = pixels[i];
					float num3 = val2.r * 0.299f + val2.g * 0.587f + val2.b * 0.114f;
					pixels[i] = new Color(num3 * tint.r, num3 * tint.g, num3 * tint.b, val2.a);
				}
				val.SetPixels(pixels);
				val.Apply();
				return Sprite.Create(val, new Rect(0f, 0f, (float)num, (float)num2), new Vector2(0.5f, 0.5f), source.pixelsPerUnit);
			}
			catch (Exception ex)
			{
				Logger.LogWarning((object)("Could not tint icon, keeping the original: " + ex.Message));
				return null;
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
			}
		}
	}
	internal static class ModConfig
	{
		internal static ConfigEntry<bool> EnableMod;

		internal static ConfigEntry<float> RadiusAtSkill0;

		internal static ConfigEntry<float> RadiusAtSkill100;

		internal static ConfigEntry<bool> ShowFloatingText;

		internal static ConfigEntry<bool> EnableScanner;

		internal static ConfigEntry<string> PlaceEffect;

		internal static ConfigEntry<bool> DebugLogging;

		private static ConfigurationManagerAttributes Synced => new ConfigurationManagerAttributes
		{
			IsAdminOnly = true
		};

		internal static void Bind(ConfigFile cfg)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			EnableMod = cfg.Bind<bool>("General", "EnableMod", true, new ConfigDescription("Master switch.", (AcceptableValueBase)null, new object[1] { Synced }));
			RadiusAtSkill0 = cfg.Bind<float>("Area", "RadiusAtSkill0", 1.5f, new ConfigDescription("Radius in metres covered at Farming skill 0.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 20f), new object[1] { Synced }));
			RadiusAtSkill100 = cfg.Bind<float>("Area", "RadiusAtSkill100", 4f, new ConfigDescription("Radius in metres covered at Farming skill 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 20f), new object[1] { Synced }));
			float[] array = new float[3] { 25f, 50f, 75f };
			Tier[] all = Tier.All;
			foreach (Tier tier in all)
			{
				tier.Reduction = cfg.Bind<float>("Fertilizer", $"Reduction{tier.Level} - {tier.DisplayName}", array[tier.Level - 1], new ConfigDescription("Percent of remaining grow time removed by " + tier.DisplayName + ".", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), new object[1] { Synced }));
			}
			ShowFloatingText = cfg.Bind<bool>("Feedback", "ShowFloatingText", true, "Shows a floating figure over each plant as it is fertilized, and over any that were already done.");
			EnableScanner = cfg.Bind<bool>("Feedback", "EnableScanner", true, "Shows picked plants that would otherwise be invisible, while the Cultivator is out with Fertilize selected.");
			PlaceEffect = cfg.Bind<string>("Feedback", "PlaceEffect", "vfx_Place_replant", "Vanilla effect prefab played where the fertilizer is spread. Blank for none.");
			DebugLogging = cfg.Bind<bool>("Debug", "DebugLogging", false, "Logs how many plants each placement affected, and why any were skipped.");
		}
	}
	internal static class PickedTime
	{
		private static readonly FieldRef<Pickable, long> Cached = AccessTools.FieldRefAccess<Pickable, long>("m_pickedTime");

		internal static void Reapply(Pickable pickable)
		{
			if (!ModConfig.EnableMod.Value || pickable.m_respawnTimeMinutes <= 0f)
			{
				return;
			}
			ZNetView component = ((Component)pickable).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			Tier tier = Tier.ByLevel(zDO.GetInt(FertilizerPiece.PickedTierHash, 0));
			if (tier?.Reduction == null)
			{
				return;
			}
			double num = Math.Min(Math.Max(tier.Reduction.Value, 0f), 99f);
			long num2 = zDO.GetLong(ZDOVars.s_pickedTime, 0L);
			if (num2 > 1)
			{
				long num3 = num2 - (long)((double)pickable.m_respawnTimeMinutes * (num / 100.0) * 600000000.0);
				if (num3 < 1)
				{
					num3 = 1L;
				}
				zDO.Set(ZDOVars.s_pickedTime, num3);
				Cached.Invoke(pickable) = num3;
			}
		}

		internal static void Clear(Pickable pickable)
		{
			ZNetView component = ((Component)pickable).GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.IsValid() && component.IsOwner())
			{
				component.GetZDO().Set(FertilizerPiece.PickedTierHash, 0, false);
			}
		}
	}
	[HarmonyPatch(typeof(Pickable), "SetPicked")]
	internal static class PickableSetPickedPatch
	{
		private static void Postfix(Pickable __instance, bool picked)
		{
			if (picked)
			{
				PickedTime.Reapply(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Pickable), "RPC_Pick")]
	internal static class PickableRpcPickPatch
	{
		private static void Prefix(Pickable __instance)
		{
			if (ModConfig.EnableMod.Value)
			{
				PickedTime.Clear(__instance);
			}
		}
	}
	[BepInPlugin("elric.Fertilizer", "Fertilizer", "1.7.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	internal class Plugin : BaseUnityPlugin
	{
		public const string PluginGUID = "elric.Fertilizer";

		public const string PluginName = "Fertilizer";

		public const string PluginVersion = "1.7.0";

		private const string ItemBasePrefab = "PowderedDragonEgg";

		private const string PiecePrefabName = "jelaw_fertilizer_piece";

		internal static int CurrentTier = 1;

		private static int _lastLoggedTier = -1;

		private static float _nativeRadius = 2f;

		private static Vector3 _nativeGhostScale = Vector3.one;

		private static readonly FieldRef<Player, GameObject> GhostOf = AccessTools.FieldRefAccess<Player, GameObject>("m_placementGhost");

		private void Awake()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			ModConfig.Bind(((BaseUnityPlugin)this).Config);
			new Harmony("elric.Fertilizer").PatchAll();
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new DueCommand());
			PrefabManager.OnVanillaPrefabsAvailable += AddContent;
		}

		private void Update()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				Scanner.HideAll();
				return;
			}
			Piece selectedPiece = localPlayer.GetSelectedPiece();
			if (!((Object)(object)selectedPiece != (Object)null) || !(Utils.GetPrefabName(((Component)selectedPiece).gameObject) == "jelaw_fertilizer_piece"))
			{
				Scanner.HideAll();
				return;
			}
			Scanner.Tick(ModConfig.EnableScanner.Value, ((Component)localPlayer).transform.position, Scanner.ScanRadius());
			Tier tier = Selected(localPlayer) ?? Tier.All[0];
			CurrentTier = tier.Level;
			if ((Object)(object)tier.Drop == (Object)null)
			{
				return;
			}
			if (selectedPiece.m_resources == null || selectedPiece.m_resources.Length == 0)
			{
				selectedPiece.m_resources = (Requirement[])(object)new Requirement[1]
				{
					new Requirement()
				};
				if (ModConfig.DebugLogging.Value)
				{
					Logger.LogInfo((object)"Fertilizer piece had no requirements; created one.");
				}
			}
			Requirement val = selectedPiece.m_resources[0];
			if (val == null)
			{
				val = new Requirement();
				selectedPiece.m_resources[0] = val;
			}
			val.m_resItem = tier.Drop;
			val.m_amount = 1;
			val.m_amountPerLevel = 0;
			val.m_recover = false;
			if (ModConfig.DebugLogging.Value && _lastLoggedTier != tier.Level)
			{
				_lastLoggedTier = tier.Level;
				Logger.LogInfo((object)("Held piece '" + Utils.GetPrefabName(((Component)selectedPiece).gameObject) + "' cost set to " + $"'{((Object)tier.Drop).name}' (tier {tier.Level})"));
			}
			ScaleGhost(localPlayer);
		}

		private static Tier Selected(Player player)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null)
			{
				return null;
			}
			ItemData val = ((Humanoid)player).GetAmmoItem();
			if (val != null && (!inventory.ContainsItem(val) || val.m_shared.m_ammoType != "$ammo_fertilizer"))
			{
				val = null;
			}
			val = val ?? inventory.GetAmmoItem("$ammo_fertilizer", (string)null);
			if (val == null || (Object)(object)val.m_dropPrefab == (Object)null)
			{
				return null;
			}
			return Tier.ByItemName(((Object)val.m_dropPrefab).name);
		}

		private static string FirstExisting(string names)
		{
			if (string.IsNullOrEmpty(names))
			{
				return null;
			}
			string[] array = names.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length != 0 && (Object)(object)Resolve(text) != (Object)null)
				{
					return text;
				}
			}
			return null;
		}

		private static void CaptureIndicatorScale(GameObject prefab)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			TerrainOp componentInChildren = prefab.GetComponentInChildren<TerrainOp>(true);
			if ((Object)(object)componentInChildren != (Object)null && componentInChildren.GetRadius() > 0f)
			{
				_nativeRadius = componentInChildren.GetRadius();
			}
			else
			{
				TerrainModifier componentInChildren2 = prefab.GetComponentInChildren<TerrainModifier>(true);
				if ((Object)(object)componentInChildren2 != (Object)null && componentInChildren2.GetRadius() > 0f)
				{
					_nativeRadius = componentInChildren2.GetRadius();
				}
			}
			Transform val = prefab.transform.Find("_GhostOnly");
			if ((Object)(object)val != (Object)null)
			{
				_nativeGhostScale = val.localScale;
			}
			if (ModConfig.DebugLogging.Value)
			{
				Logger.LogInfo((object)($"Indicator native radius {_nativeRadius:0.##}m at scale {_nativeGhostScale}" + (((Object)(object)val == (Object)null) ? " (no _GhostOnly child found)" : "")));
			}
		}

		internal static GameObject Resolve(string name)
		{
			GameObject prefab = PrefabManager.Instance.GetPrefab(name);
			if ((Object)(object)prefab != (Object)null)
			{
				return prefab;
			}
			if (ZNetScene.instance?.m_prefabs == null)
			{
				return null;
			}
			foreach (GameObject prefab2 in ZNetScene.instance.m_prefabs)
			{
				if ((Object)(object)prefab2 != (Object)null && ((Object)prefab2).name == name)
				{
					return prefab2;
				}
			}
			return null;
		}

		private static void ScaleGhost(Player player)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GhostOf.Invoke(player);
			if (!((Object)(object)val == (Object)null))
			{
				Transform val2 = val.transform.Find("_GhostOnly");
				if (!((Object)(object)val2 == (Object)null))
				{
					float num = FertilizerPiece.Radius() / Mathf.Max(_nativeRadius, 0.01f);
					val2.localScale = _nativeGhostScale * num;
				}
			}
		}

		private void AddContent()
		{
			AddLocalization();
			Tier[] all = Tier.All;
			for (int i = 0; i < all.Length; i++)
			{
				AddMeal(all[i]);
			}
			AddPlaceable();
			PrefabManager.OnVanillaPrefabsAvailable -= AddContent;
		}

		private static void AddMeal(Tier tier)
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Expected O, but got Unknown
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = PrefabManager.Instance.CreateClonedPrefab(tier.ItemName, "PowderedDragonEgg");
			if ((Object)(object)val == (Object)null)
			{
				Logger.LogError((object)("Could not clone 'PowderedDragonEgg' for " + tier.DisplayName + "."));
				return;
			}
			ItemDrop component = val.GetComponent<ItemDrop>();
			component.m_itemData.m_shared.m_name = "$" + tier.ItemName;
			component.m_itemData.m_shared.m_description = "$" + tier.ItemName + "_desc";
			component.m_itemData.m_shared.m_itemType = (ItemType)9;
			component.m_itemData.m_shared.m_ammoType = "$ammo_fertilizer";
			component.m_itemData.m_shared.m_maxStackSize = 50;
			Sprite[] icons = component.m_itemData.m_shared.m_icons;
			if (icons != null && icons.Length != 0)
			{
				Sprite val2 = Icons.Recolour(icons[0], tier.Tint);
				if ((Object)(object)val2 != (Object)null)
				{
					component.m_itemData.m_shared.m_icons = (Sprite[])(object)new Sprite[1] { val2 };
				}
			}
			ItemConfig val3 = new ItemConfig
			{
				Amount = 2,
				CraftingStation = CraftingStations.Workbench,
				Requirements = ((IEnumerable<(string, int)>)tier.Ingredients).Select((Func<(string, int), RequirementConfig>)(((string Item, int Amount) i) => new RequirementConfig(i.Item, i.Amount, 0, true))).ToArray()
			};
			ItemManager.Instance.AddItem(new CustomItem(val, false, val3));
			tier.Drop = component;
		}

		private static void AddPlaceable()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Expected O, but got Unknown
			PieceConfig val = new PieceConfig();
			val.Name = "$DHG_fertilize";
			val.Description = "$DHG_fertilize_desc";
			val.PieceTable = PieceTables.Cultivator;
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
			{
				new RequirementConfig(Tier.All[0].ItemName, 1, 0, true)
			};
			PieceConfig val2 = val;
			string text = FirstExisting("cultivate_v2,cultivate,wood_pole");
			bool num = text != null;
			if (ModConfig.DebugLogging.Value)
			{
				Logger.LogInfo((object)("Fertilizer base prefab: " + (text ?? "none - using a cube")));
			}
			CustomPiece val3;
			if (num)
			{
				val3 = new CustomPiece("jelaw_fertilizer_piece", text, val2);
			}
			else
			{
				Logger.LogWarning((object)("Base prefab '" + text + "' not found; falling back to a plain cube."));
				val3 = new CustomPiece("jelaw_fertilizer_piece", true, val2);
			}
			if ((Object)(object)val3.PiecePrefab == (Object)null)
			{
				Logger.LogError((object)"Could not create the fertilizer placeable.");
				return;
			}
			CaptureIndicatorScale(val3.PiecePrefab);
			StripInheritedBehaviour(val3.PiecePrefab);
			val3.PiecePrefab.AddComponent<FertilizerPiece>();
			PieceManager.Instance.AddPiece(val3);
			Piece component = val3.PiecePrefab.GetComponent<Piece>();
			if ((Object)(object)component != (Object)null)
			{
				ItemDrop drop = Tier.All[0].Drop;
				if ((Object)(object)drop != (Object)null)
				{
					component.m_resources = (Requirement[])(object)new Requirement[1]
					{
						new Requirement
						{
							m_resItem = drop,
							m_amount = 1,
							m_amountPerLevel = 0,
							m_recover = false
						}
					};
				}
			}
			if (ModConfig.DebugLogging.Value && (Object)(object)component != (Object)null)
			{
				Requirement[] resources = component.m_resources;
				int num2 = ((resources != null) ? resources.Length : 0);
				string arg = ((num2 > 0 && (Object)(object)component.m_resources[0]?.m_resItem != (Object)null) ? ((Object)component.m_resources[0].m_resItem).name : "none");
				Logger.LogInfo((object)$"Fertilizer piece registered with {num2} requirement(s), first = {arg}");
			}
			if ((Object)(object)component != (Object)null)
			{
				component.m_craftingStation = null;
				component.m_groundOnly = false;
				component.m_notOnFloor = false;
				component.m_noInWater = false;
				component.m_onlyInTeleportArea = false;
				component.m_allowedInDungeons = true;
			}
		}

		private static void StripInheritedBehaviour(GameObject prefab)
		{
			PrivateArea[] componentsInChildren = prefab.GetComponentsInChildren<PrivateArea>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren[i]);
			}
			Container[] componentsInChildren2 = prefab.GetComponentsInChildren<Container>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren2[i]);
			}
			CraftingStation[] componentsInChildren3 = prefab.GetComponentsInChildren<CraftingStation>(true);
			for (int i = 0; i < componentsInChildren3.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren3[i]);
			}
			TerrainOp[] componentsInChildren4 = prefab.GetComponentsInChildren<TerrainOp>(true);
			for (int i = 0; i < componentsInChildren4.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren4[i]);
			}
			TerrainModifier[] componentsInChildren5 = prefab.GetComponentsInChildren<TerrainModifier>(true);
			for (int i = 0; i < componentsInChildren5.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren5[i]);
			}
		}

		private static void AddLocalization()
		{
			CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
			Dictionary<string, string> dictionary = new Dictionary<string, string>
			{
				{ "ammo_fertilizer", "Fertilizer" },
				{ "DHG_fertilize", "Fertilize" },
				{ "DHG_already_fertilized", "Already Fertilized" },
				{ "DHG_fert_growth", "Growth" },
				{ "DHG_fert_berries", "Berries" },
				{ "DHG_fertilize_desc", "Spreads the selected bone meal. Covers a wider area as Farming rises." }
			};
			Tier[] all = Tier.All;
			foreach (Tier tier in all)
			{
				dictionary[tier.ItemName] = tier.DisplayName;
				dictionary[tier.ItemName + "_desc"] = tier.Description;
			}
			string text = "English";
			localization.AddTranslation(ref text, dictionary);
		}
	}
	internal static class Scanner
	{
		private sealed class Revealed
		{
			internal Pickable Pickable;

			internal GameObject Visual;

			internal bool Treated;

			internal Vector3 Scale;
		}

		private const float RescanSeconds = 0.4f;

		private static readonly Color UntreatedGlow = new Color(0.22f, 0.46f, 0.4f);

		private static readonly Color TreatedGlow = new Color(0.48f, 0.34f, 0.08f);

		private const float RevealScale = 0.75f;

		private static readonly List<Revealed> Shown = new List<Revealed>();

		private static readonly Dictionary<string, bool> Vanishes = new Dictionary<string, bool>();

		private static float _nextScan;

		internal static float ScanRadius()
		{
			return Mathf.Max(6f, FertilizerPiece.Radius());
		}

		internal static void Tick(bool active, Vector3 centre, float radius)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			if (!active)
			{
				HideAll();
			}
			else
			{
				if (Time.time < _nextScan)
				{
					return;
				}
				_nextScan = Time.time + 0.4f;
				float num = radius * radius;
				Vector3 val;
				for (int num2 = Shown.Count - 1; num2 >= 0; num2--)
				{
					Revealed revealed = Shown[num2];
					if (!((Object)(object)revealed.Pickable == (Object)null) && !((Object)(object)revealed.Visual == (Object)null))
					{
						val = ((Component)revealed.Pickable).transform.position - centre;
						if (!(((Vector3)(ref val)).sqrMagnitude > num) && IsPicked(revealed.Pickable))
						{
							bool flag = Fertilization.TreatedTier(revealed.Pickable) != null;
							if (flag != revealed.Treated)
							{
								revealed.Treated = flag;
								Paint(revealed);
							}
							continue;
						}
					}
					Hide(revealed);
					Shown.RemoveAt(num2);
				}
				Pickable[] array = Object.FindObjectsOfType<Pickable>();
				foreach (Pickable val2 in array)
				{
					if ((Object)(object)val2 == (Object)null || val2.m_respawnTimeMinutes <= 0f)
					{
						continue;
					}
					val = ((Component)val2).transform.position - centre;
					if (!(((Vector3)(ref val)).sqrMagnitude > num))
					{
						GameObject hideWhenPicked = val2.m_hideWhenPicked;
						if (!((Object)(object)hideWhenPicked == (Object)null) && !hideWhenPicked.activeSelf && VanishesEntirely(val2, hideWhenPicked) && IsPicked(val2) && !AlreadyShown(val2))
						{
							Show(val2, hideWhenPicked);
						}
					}
				}
			}
		}

		private static bool VanishesEntirely(Pickable pickable, GameObject visual)
		{
			string prefabName = Utils.GetPrefabName(((Component)pickable).gameObject);
			if (Vanishes.TryGetValue(prefabName, out var value))
			{
				return value;
			}
			bool flag = true;
			Renderer[] componentsInChildren = ((Component)pickable).GetComponentsInChildren<Renderer>(false);
			foreach (Renderer val in componentsInChildren)
			{
				if (val.enabled && !((Component)val).transform.IsChildOf(visual.transform))
				{
					flag = false;
					break;
				}
			}
			Vanishes[prefabName] = flag;
			return flag;
		}

		private static bool IsPicked(Pickable pickable)
		{
			ZNetView component = ((Component)pickable).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return false;
			}
			return component.GetZDO().GetBool(ZDOVars.s_picked, false);
		}

		private static bool AlreadyShown(Pickable pickable)
		{
			foreach (Revealed item in Shown)
			{
				if ((Object)(object)item.Pickable == (Object)(object)pickable)
				{
					return true;
				}
			}
			return false;
		}

		private static void Show(Pickable pickable, GameObject visual)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			Revealed revealed = new Revealed
			{
				Pickable = pickable,
				Visual = visual,
				Treated = (Fertilization.TreatedTier(pickable) != null),
				Scale = visual.transform.localScale
			};
			visual.transform.localScale = revealed.Scale * 0.75f;
			visual.SetActive(true);
			Paint(revealed);
			Shown.Add(revealed);
		}

		private static void Paint(Revealed revealed)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)MaterialMan.instance == (Object)null) && !((Object)(object)revealed.Visual == (Object)null))
			{
				MaterialMan.instance.SetValue<Color>(revealed.Visual, ShaderProps._EmissionColor, revealed.Treated ? TreatedGlow : UntreatedGlow, true);
			}
		}

		private static void Hide(Revealed revealed)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)revealed.Visual == (Object)null))
			{
				if ((Object)(object)MaterialMan.instance != (Object)null)
				{
					MaterialMan.instance.ResetValue(revealed.Visual, ShaderProps._EmissionColor);
				}
				revealed.Visual.transform.localScale = revealed.Scale;
				if ((Object)(object)revealed.Pickable == (Object)null || IsPicked(revealed.Pickable))
				{
					revealed.Visual.SetActive(false);
				}
			}
		}

		internal static void HideAll()
		{
			if (Shown.Count == 0)
			{
				return;
			}
			foreach (Revealed item in Shown)
			{
				Hide(item);
			}
			Shown.Clear();
		}
	}
	internal class Tier
	{
		internal const string AmmoType = "$ammo_fertilizer";

		internal int Level;

		internal string ItemName;

		internal string DisplayName;

		internal string Description;

		internal ConfigEntry<float> Reduction;

		internal Color Tint;

		internal (string Item, int Amount)[] Ingredients;

		internal ItemDrop Drop;

		internal static readonly Tier[] All = new Tier[3]
		{
			new Tier
			{
				Level = 1,
				ItemName = "jelaw_bonemeal",
				DisplayName = "Bone Meal",
				Description = "Ground bone. Hastens a crop a little.",
				Tint = new Color(1f, 0.97f, 0.9f),
				Ingredients = new(string, int)[1] { ("BoneFragments", 5) }
			},
			new Tier
			{
				Level = 2,
				ItemName = "jelaw_bonemeal_enriched",
				DisplayName = "Enriched Bone Meal",
				Description = "Bone meal ground with fang and charcoal.",
				Tint = new Color(0.62f, 0.6f, 0.58f),
				Ingredients = new(string, int)[3]
				{
					("jelaw_bonemeal", 1),
					("WolfFang", 1),
					("Coal", 1)
				}
			},
			new Tier
			{
				Level = 3,
				ItemName = "jelaw_bonemeal_enhanced",
				DisplayName = "Enhanced Bone Meal",
				Description = "Bone meal ground with charred bone and sap.",
				Tint = new Color(0.22f, 0.31f, 0.2f),
				Ingredients = new(string, int)[3]
				{
					("jelaw_bonemeal", 1),
					("CharredBone", 1),
					("Sap", 1)
				}
			}
		};

		internal static Tier ByItemName(string prefabName)
		{
			Tier[] all = All;
			foreach (Tier tier in all)
			{
				if (tier.ItemName == prefabName)
				{
					return tier;
				}
			}
			return null;
		}

		internal static Tier ByLevel(int level)
		{
			Tier[] all = All;
			foreach (Tier tier in all)
			{
				if (tier.Level == level)
				{
					return tier;
				}
			}
			return null;
		}
	}
	internal class VineFertilizedScale : MonoBehaviour
	{
	}
	internal static class VineGrowth
	{
		internal static void Apply(Vine vine)
		{
			if ((Object)(object)vine == (Object)null || !ModConfig.EnableMod.Value || (Object)(object)((Component)vine).GetComponent<VineFertilizedScale>() != (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)vine).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			if (zDO == null)
			{
				return;
			}
			int num = zDO.GetInt(FertilizerPiece.VineFertilizedHash, 0);
			if (num <= 0)
			{
				return;
			}
			Tier tier = Tier.ByLevel(num);
			if (tier?.Reduction != null)
			{
				float num2 = 1f - Mathf.Clamp(tier.Reduction.Value, 0f, 99f) / 100f;
				float growTime = vine.m_growTime;
				vine.m_growTime *= num2;
				vine.m_growTimePerBranch *= num2;
				if (ModConfig.DebugLogging.Value)
				{
					Logger.LogInfo((object)(Utils.GetPrefabName(((Component)vine).gameObject) + " growth scaled by " + tier.DisplayName + ": " + $"{growTime:0.##}s -> {vine.m_growTime:0.##}s per step " + $"(+{vine.m_growTimePerBranch:0.##}s per branch)"));
				}
				((Component)vine).gameObject.AddComponent<VineFertilizedScale>();
			}
		}

		internal static Tier TreatedTier(Vine vine)
		{
			ZNetView component = ((Component)vine).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return null;
			}
			return Tier.ByLevel(component.GetZDO().GetInt(FertilizerPiece.VineFertilizedHash, 0));
		}
	}
	[HarmonyPatch(typeof(Vine), "Awake")]
	internal static class VineAwakePatch
	{
		private static void Postfix(Vine __instance)
		{
			VineGrowth.Apply(__instance);
		}
	}
	[HarmonyPatch(typeof(Vine), "UpdateGrow")]
	internal static class VineUpdateGrowPatch
	{
		private static void Prefix(Vine __instance)
		{
			VineGrowth.Apply(__instance);
		}
	}
}