Decompiled source of Treehouse Branch Clear v0.2.19

plugins/TreehouseBranchClear.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using AzNean.SotfCommon;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Construction;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using Sons.Crafting.Structures;
using Sons.Gameplay;
using Sons.Gameplay.GameSetup;
using Sons.Gameplay.Grabber;
using Sons.Gui;
using Sons.Gui.Input;
using Sons.Input;
using Sons.Save;
using Sons.TerrainDetail;
using TheForest.Utils;
using TreehouseBranchClear.Logic;
using TreehouseBranchClear.Patches;
using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("TreehouseBranchClear")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.19.0")]
[assembly: AssemblyInformationalVersion("0.2.19+80a3aa27cd3b73f812b17f65efd9a434ef062c5c")]
[assembly: AssemblyProduct("TreehouseBranchClear")]
[assembly: AssemblyTitle("TreehouseBranchClear")]
[assembly: AssemblyVersion("0.2.19.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal static class SettingMove
{
	internal static void Move(ConfigFile config, string oldSection, string oldKey, ConfigEntryBase to)
	{
		bool saveOnConfigSet = config.SaveOnConfigSet;
		config.SaveOnConfigSet = false;
		try
		{
			ConfigEntry<string> val = config.Bind<string>(oldSection, oldKey, "\u0001", "Old place of a moved setting.");
			bool num = val.Value != "\u0001";
			if (num)
			{
				to.SetSerializedValue(((ConfigEntryBase)val).GetSerializedValue());
			}
			config.Remove(((ConfigEntryBase)val).Definition);
			if (num)
			{
				config.Save();
			}
		}
		finally
		{
			config.SaveOnConfigSet = saveOnConfigSet;
		}
	}
}
namespace AzNean.SotfCommon
{
	internal static class ModLog
	{
		private static ManualLogSource _log;

		private static ConfigEntry<bool> _full;

		private static readonly HashSet<string> _once = new HashSet<string>();

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

		internal static bool Full => _full.Value;

		internal static void Init(ManualLogSource log, ConfigEntry<bool> full)
		{
			_log = log;
			_full = full;
		}

		internal static void Trace(string message)
		{
			if (_full.Value)
			{
				_log.LogInfo((object)message);
			}
		}

		internal static bool Changed(int id, string what, int state)
		{
			if (!_full.Value || (_state.TryGetValue((id, what), out var value) && value == state))
			{
				return false;
			}
			_state[(id, what)] = state;
			return true;
		}

		internal static void Once(string key, string message, LogLevel level = (LogLevel)16)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (_once.Add(key))
			{
				_log.Log(level, (object)message);
			}
		}
	}
	internal static class GameSlot
	{
		[HarmonyPatch(typeof(SaveGameManager), "Load", new Type[]
		{
			typeof(string),
			typeof(SaveGameType)
		})]
		private static class Loading
		{
			private static void Prefix(string dir, SaveGameType saveGameType)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Invalid comparison between Unknown and I4
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Invalid comparison between Unknown and I4
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				if ((int)saveGameType == 2)
				{
					ModLog.Trace("Game loads a guest's own character: not a world, save slot kept");
					return;
				}
				Slot = Of(dir);
				MultiplayerSave = (int)saveGameType == 1;
				_newKey = null;
				ModLog.Trace($"Game loads save slot {Slot} ({saveGameType})");
			}
		}

		[HarmonyPatch(typeof(SaveGameManager), "Save", new Type[]
		{
			typeof(string),
			typeof(string),
			typeof(bool)
		})]
		private static class Saving
		{
			private static void Postfix(string dir, bool savePlayerOnly)
			{
				if (savePlayerOnly)
				{
					ModLog.Trace("Game saved a guest's own character only: save slot kept");
					return;
				}
				uint num = Of(dir);
				if (num == 0)
				{
					ModLog.Once("noslot " + dir, "Game saved to a folder without a slot id ('" + dir + "'): this world's key stays " + Key, (LogLevel)4);
				}
				else if (num != Slot)
				{
					string key = Key;
					Slot = num;
					_newKey = null;
					ModLog.Trace($"Game saved to slot {num}: this world's key {key} -> {Key}");
					GameSlot.Moved?.Invoke(key, Key);
				}
			}
		}

		private static bool _inWorld;

		private static string _newKey;

		internal static uint Slot { get; private set; }

		internal static bool MultiplayerSave { get; private set; }

		internal static string Key
		{
			get
			{
				string text;
				if (Slot == 0)
				{
					text = _newKey;
					if (text == null)
					{
						return _newKey = "new-" + DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
					}
				}
				else
				{
					text = "slot-" + Slot.ToString(CultureInfo.InvariantCulture);
				}
				return text;
			}
		}

		internal static event Action<string, string> Moved;

		internal static uint Of(string dir)
		{
			if (!uint.TryParse(Path.GetFileName(dir?.TrimEnd('/', '\\')), NumberStyles.None, CultureInfo.InvariantCulture, out var result))
			{
				return 0u;
			}
			return result;
		}

		internal static void Track(bool inWorld)
		{
			if (_inWorld && !inWorld)
			{
				ModLog.Trace($"Left the world: save slot {Slot} forgotten");
				Slot = 0u;
				MultiplayerSave = false;
				_newKey = null;
			}
			_inWorld = inWorld;
		}
	}
}
namespace TreehouseBranchClear
{
	[BepInPlugin("aznan.sotf.treehousebranchclear", "TreehouseBranchClear", "0.2.19")]
	public class Plugin : BasePlugin
	{
		internal const string Version = "0.2.19";

		internal static ManualLogSource Logger;

		internal static ConfigEntry<bool> FullLogging;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> ShowPrompt;

		internal static ConfigEntry<string> Keywords;

		internal static ConfigEntry<string> TrunkKeywords;

		internal static ConfigEntry<string> HiddenMessage;

		internal static ConfigEntry<string> ShownMessage;

		internal static ConfigEntry<string> PromptIcon;

		internal static ConfigEntry<float> GuestLinkMeters;

		internal static ConfigEntry<float> Radius;

		internal static ConfigEntry<float> SafetyNetSeconds;

		internal static ConfigEntry<float> NeighbourRadius;

		internal static ConfigEntry<float> PromptReach;

		internal static ConfigEntry<float> PromptAimWidth;

		internal static ConfigEntry<float> PromptHeight;

		internal static ConfigEntry<float> PromptCheckSeconds;

		internal static ConfigEntry<float> MessageSeconds;

		private void MigrateReach()
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			string path = Path.Combine(Paths.ConfigPath, "aznan.sotf.treehousebranchclear.reach-0.2.11.done");
			if (!File.Exists(path))
			{
				float value = PromptReach.Value;
				float value2 = PromptAimWidth.Value;
				PromptReach.Value = ReachDefaults.Upgrade(PromptReach.Value, 3f, 1.9f);
				PromptAimWidth.Value = ReachDefaults.Upgrade(PromptAimWidth.Value, 1f, 0.6f);
				File.WriteAllText(path, "Prompt reach defaults updated once (see NOTES).");
				ManualLogSource logger = Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(105, 4, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Prompt reach defaults checked once (0.2.11): Reach ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(value);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" -> ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(PromptReach.Value);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" m, AimWidth ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(value2);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" -> ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(PromptAimWidth.Value);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" m (only the old defaults change)");
				}
				logger.LogInfo(val);
			}
		}

		public override void Load()
		{
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Expected O, but got Unknown
			//IL_03b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d4: Expected O, but got Unknown
			//IL_03d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f2: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			Texts.SelfCheck();
			ReachDefaults.SelfCheck();
			Enabled = ((BasePlugin)this).Config.Bind<bool>("General", "Enabled", true, "True = branches and leaves are hidden on trees that carry something you built.");
			Keywords = ((BasePlugin)this).Config.Bind<string>("Trees", "Keywords", "leaf,leaves,branch,frond,foliage,canopy", "A material of a built-on tree (leaves, branches) is made invisible when its name contains one of these words (comma-separated). The log lists each cleared tree's materials.");
			TrunkKeywords = ((BasePlugin)this).Config.Bind<string>("Trees", "TrunkKeywords", "trunk,bark,stem", "A material whose name contains one of these words is never hidden (comma-separated).");
			Radius = ((BasePlugin)this).Config.Bind<float>("Trees", "Radius", 150f, "Trees within this distance of you are checked for builds, in metres. Advised: 10 to 1000.");
			NeighbourRadius = ((BasePlugin)this).Config.Bind<float>("Trees", "NeighbourRadius", 0f, "Also clear trees standing within this distance of a built-on tree, in metres, for branches poking in from next door. 0 = only the trees you built on. Advised: 0 to 50.");
			ShowPrompt = ((BasePlugin)this).Config.Bind<bool>("Prompt", "Enabled", true, "True = looking at the trunk of a tree you built on shows the game's use prompt, to hide or show the branches of that tree only (remembered per save).");
			PromptIcon = ((BasePlugin)this).Config.Bind<string>("Prompt", "Icon", PromptIcons.All[0], new ConfigDescription("Which of the game's prompt icons shows on the trunk. screen.use = the game's use prompt (shows how long you hold the key). An icon the game has not loaded where you are shows nothing (the log says which ids are loaded when the prompt first appears).", (AcceptableValueBase)(object)new AcceptableValueList<string>(PromptIcons.All), Array.Empty<object>()));
			PromptHeight = ((BasePlugin)this).Config.Bind<float>("Prompt", "Height", 1.6f, "Height of the prompt above the base of the trunk, in metres. It stays there and does not follow your view. Advised: 0 to 10.");
			PromptReach = ((BasePlugin)this).Config.Bind<float>("Prompt", "Reach", 1.9f, "How far from you the middle of the trunk may be for the prompt to appear, in metres (default: the game's own reach for picking things up, 1.6 m, plus the trunk's thickness). Advised: 0.5 to 20.");
			PromptAimWidth = ((BasePlugin)this).Config.Bind<float>("Prompt", "AimWidth", 0.6f, "How far beside the middle of the trunk your view may pass and still count as looking at it, in metres (default: the width of the game's pick-up zone plus the trunk's thickness). Advised: 0.1 to 10.");
			MigrateReach();
			HiddenMessage = ((BasePlugin)this).Config.Bind<string>("Texts", "HiddenMessage", "", "Message when you hide a tree's branches. Empty = automatic, in the game's language.");
			ShownMessage = ((BasePlugin)this).Config.Bind<string>("Texts", "ShownMessage", "", "Message when you show a tree's branches again. Empty = automatic, in the game's language.");
			MessageSeconds = ((BasePlugin)this).Config.Bind<float>("Texts", "MessageSeconds", 3f, "How long the confirmation stays on screen, in seconds. 0 = no message. Advised: 0 to 30.");
			GuestLinkMeters = ((BasePlugin)this).Config.Bind<float>("Multiplayer", "GuestLinkMeters", 2f, "Multiplayer guest: the game never tells a joining player which trees carry a build, so the mod reads the tree each piece built on a tree is attached to, or else takes the tree whose trunk is nearest to the piece, within this distance on the ground, in metres. 0 = off (the guest sees every branch). Default 2. Advised: 1 to 4.");
			SafetyNetSeconds = ((BasePlugin)this).Config.Bind<float>("Performance", "SafetyNetSeconds", 30f, "Safety net: nearby trees are also re-checked this often, in seconds. Builds are normally caught as soon as the game registers them. 0 = never. Advised: 0 to 600.");
			PromptCheckSeconds = ((BasePlugin)this).Config.Bind<float>("Performance", "PromptCheckSeconds", 0.2f, "How often the mod checks which trunk you look at, in seconds. Advised: 0.05 to 2.");
			FullLogging = ((BasePlugin)this).Config.Bind<bool>("Debug", "FullLogging", false, "True = the BepInEx log gets every step useful to diagnose a problem (decisions, values read, object aimed at, failures with their cause). False = only loading, version and errors.");
			ModLog.Init(Logger, FullLogging);
			SettingMove.Move(((BasePlugin)this).Config, "Prompt", "HiddenMessage", (ConfigEntryBase)(object)HiddenMessage);
			SettingMove.Move(((BasePlugin)this).Config, "Prompt", "ShownMessage", (ConfigEntryBase)(object)ShownMessage);
			SettingMove.Move(((BasePlugin)this).Config, "Prompt", "MessageSeconds", (ConfigEntryBase)(object)MessageSeconds);
			SettingMove.Move(((BasePlugin)this).Config, "Trees", "SafetyNetSeconds", (ConfigEntryBase)(object)SafetyNetSeconds);
			SettingMove.Move(((BasePlugin)this).Config, "Prompt", "CheckSeconds", (ConfigEntryBase)(object)PromptCheckSeconds);
			BranchHider.Choices = new TreeChoices(Path.Combine(Paths.ConfigPath, "aznan.sotf.treehousebranchclear.trees.txt"));
			ModLog.Trace($"{BranchHider.Choices.Count} tree choice(s) read from the mod's file");
			GameSlot.Moved += BranchHider.SlotMoved;
			((BasePlugin)this).Config.SettingChanged += delegate
			{
				BranchHider.Reset();
			};
			new Harmony("aznan.sotf.treehousebranchclear").PatchAll();
			ClassInjector.RegisterTypeInIl2Cpp<Watcher>();
			GameObject val = new GameObject("TreehouseBranchClear");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<Watcher>();
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(28, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("TreehouseBranchClear ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>("0.2.19");
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" loaded");
			}
			logger.LogInfo(val2);
		}
	}
	public class Watcher : MonoBehaviour
	{
		private float _nextRefresh;

		public Watcher(IntPtr ptr)
			: base(ptr)
		{
		}

		private void Update()
		{
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			GameSlot.Track((Object)(object)LocalPlayer.Inventory != (Object)null);
			bool flag = Plugin.SafetyNetSeconds.Value > 0f && Time.unscaledTime >= _nextRefresh;
			bool flag2 = BranchHider.Built.Count > 0 || TreePrompt.Visible;
			if (!BranchHider.Dirty && !flag && !flag2)
			{
				return;
			}
			Camera main = Camera.main;
			if (ModLog.Changed(0, "camera", (!((Object)(object)main == (Object)null)) ? 1 : 0))
			{
				ModLog.Trace(((Object)(object)main == (Object)null) ? "No main camera: tree scan and prompt wait for one" : "Main camera found: tree scan and prompt run");
			}
			if ((Object)(object)main == (Object)null)
			{
				return;
			}
			if (BranchHider.Dirty || flag)
			{
				_nextRefresh = Time.unscaledTime + Plugin.SafetyNetSeconds.Value;
				try
				{
					BranchHider.Scan(((Component)main).transform.position);
				}
				catch (Exception ex)
				{
					ModLog.Once("refresh " + ex.Message, $"Tree refresh failed: {ex}", (LogLevel)2);
				}
			}
			try
			{
				TreePrompt.Update(main);
			}
			catch (Exception ex2)
			{
				ModLog.Once("prompt " + ex2.Message, $"Tree prompt failed: {ex2}", (LogLevel)2);
			}
		}
	}
}
namespace TreehouseBranchClear.Patches
{
	[HarmonyPatch(typeof(WorldObjectLocator), "OnRefreshedLods")]
	public static class BranchHider
	{
		private record Swap(Renderer Renderer, Il2CppReferenceArray<Material> Original);

		private static readonly Dictionary<int, List<Swap>> HiddenModels = new Dictionary<int, List<Swap>>();

		private static readonly HashSet<IntPtr> Neighbours = new HashSet<IntPtr>();

		private static readonly Dictionary<int, Material> Invisible = new Dictionary<int, Material>();

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

		private static readonly HashSet<IntPtr> Logged = new HashSet<IntPtr>();

		internal static readonly Dictionary<IntPtr, WorldObjectLocator> Built = new Dictionary<IntPtr, WorldObjectLocator>();

		internal static TreeChoices Choices;

		private static string _world = "";

		private static readonly List<WorldObjectLocator> Found = new List<WorldObjectLocator>();

		private static readonly List<WorldObjectLocator> Near = new List<WorldObjectLocator>();

		private static readonly HashSet<IntPtr> GuestBuilt = new HashSet<IntPtr>();

		private static string[] _keywords;

		private static string[] _trunkWords;

		private static TreeManager _trees;

		internal static bool Dirty = true;

		private static readonly HashSet<string> Adopted = new HashSet<string>();

		private static readonly List<(Vector2 Foot, WorldObjectLocator Tree)> Flat = new List<(Vector2, WorldObjectLocator)>();

		private static TreeManager Trees
		{
			get
			{
				if (!((Object)(object)_trees != (Object)null))
				{
					return _trees = Object.FindObjectOfType<TreeManager>();
				}
				return _trees;
			}
		}

		private static void Postfix(WorldObjectLocator __instance)
		{
			try
			{
				Refresh(__instance);
			}
			catch (Exception ex)
			{
				ModLog.Once("update " + ex.Message, $"Tree update failed: {ex}", (LogLevel)2);
			}
		}

		private static void Refresh(WorldObjectLocator tree)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Enabled.Value || tree == null || !tree.IsTree || (Object)(object)Trees == (Object)null)
			{
				return;
			}
			bool flag = IsBuilt(tree);
			if (flag)
			{
				Built[((Il2CppObjectBase)tree).Pointer] = tree;
			}
			if (flag && KeepsBranches(tree))
			{
				flag = false;
				if (ModLog.Changed(((Il2CppObjectBase)tree).Pointer.GetHashCode(), "kept", 1))
				{
					ModLog.Trace($"Tree {tree.DataName} at {tree.Position}: branches kept, as the player chose for this world");
				}
			}
			bool flag2 = flag || Neighbours.Contains(((Il2CppObjectBase)tree).Pointer);
			if (!flag2 && HiddenModels.Count == 0)
			{
				return;
			}
			Transform currentLodTransform = tree.CurrentLodTransform;
			if ((Object)(object)currentLodTransform == (Object)null)
			{
				return;
			}
			if (!flag2)
			{
				Restore(((Object)currentLodTransform).GetInstanceID());
				return;
			}
			Hide(tree, currentLodTransform, flag ? "built on" : "next to a built-on tree");
			if (flag && Plugin.NeighbourRadius.Value > 0f)
			{
				ClearNeighbours(tree);
			}
		}

		internal static bool KeepsBranches(WorldObjectLocator tree)
		{
			if (Choices.Count > 0)
			{
				return Choices.IsShown(_world, ((Object)tree.UniqueId).ToString());
			}
			return false;
		}

		internal static bool Toggle(WorldObjectLocator tree)
		{
			_world = World();
			bool result = Choices.Toggle(_world, ((Object)tree.UniqueId).ToString());
			Dirty = true;
			return result;
		}

		private static string World()
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			if (BoltNetwork.isClient)
			{
				string gameId = GameSetupManager.GetGameId();
				if (!string.IsNullOrEmpty(gameId))
				{
					return gameId.Replace(' ', '_');
				}
				return "0";
			}
			string key = GameSlot.Key;
			if (GameSlot.Slot != 0 && Adopted.Add(key) && !Choices.HasAny(key))
			{
				string text = (GameSlot.MultiplayerSave ? GameSetupManager.GetGameId() : null);
				int num = ((!string.IsNullOrEmpty(text)) ? Choices.Adopt(text.Replace(' ', '_'), key) : 0);
				if (num == 0)
				{
					num = Choices.Adopt(GameSlot.Slot.ToString(CultureInfo.InvariantCulture), key);
				}
				if (num == 0)
				{
					num = Choices.Adopt("0", key);
				}
				if (num > 0)
				{
					ManualLogSource logger = Plugin.Logger;
					bool flag = default(bool);
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(62, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" tree choice(s) kept by 0.2.18 and before copied to save slot ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(GameSlot.Slot);
					}
					logger.LogInfo(val);
				}
			}
			return key;
		}

		internal static void SlotMoved(string from, string to)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			int num = Choices.Adopt(from, to);
			if (num > 0)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(66, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" tree choice(s) copied from ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(from);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" to ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(to);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": the world was saved to that slot");
				}
				logger.LogInfo(val);
			}
			else
			{
				ModLog.Trace($"World saved to a new slot ({from} -> {to}): no tree choice to copy");
			}
		}

		private static void Hide(WorldObjectLocator tree, Transform model, string why)
		{
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)model).GetInstanceID();
			if (HiddenModels.ContainsKey(instanceID))
			{
				return;
			}
			List<Swap> list = new List<Swap>();
			SortedSet<string> sortedSet = ((ModLog.Full && Logged.Add(((Il2CppObjectBase)tree).Pointer)) ? new SortedSet<string>() : null);
			int num = 0;
			int num2 = 0;
			foreach (Renderer componentsInChild in ((Component)model).GetComponentsInChildren<Renderer>(true))
			{
				Il2CppReferenceArray<Material> sharedMaterials = componentsInChild.sharedMaterials;
				Il2CppReferenceArray<Material> val = null;
				for (int i = 0; i < ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length; i++)
				{
					Material val2 = ((Il2CppArrayBase<Material>)(object)sharedMaterials)[i];
					num++;
					if ((Object)(object)val2 == (Object)null)
					{
						continue;
					}
					Material val3 = InvisibleFor(val2);
					sortedSet?.Add(((Object)(object)val3 == (Object)null) ? ((Object)val2).name : (((Object)val2).name + " (hidden)"));
					if (!((Object)(object)val3 == (Object)null))
					{
						if (val == null)
						{
							val = componentsInChild.sharedMaterials;
						}
						((Il2CppArrayBase<Material>)(object)val)[i] = val3;
						num2++;
					}
				}
				if (val != null)
				{
					componentsInChild.sharedMaterials = val;
					list.Add(new Swap(componentsInChild, sharedMaterials));
				}
			}
			HiddenModels[instanceID] = list;
			if (sortedSet != null)
			{
				ModLog.Trace($"Cleared tree {tree.DataName} at {tree.Position} ({why}): {num2}/{num} material slots hidden; materials [{string.Join(", ", sortedSet)}]");
			}
		}

		private static void Restore(int modelId)
		{
			if (!HiddenModels.Remove(modelId, out var value))
			{
				return;
			}
			foreach (Swap item in value)
			{
				Restore(item);
			}
		}

		private static void Restore(Swap s)
		{
			if ((Object)(object)s.Renderer == (Object)null)
			{
				return;
			}
			Il2CppReferenceArray<Material> sharedMaterials = s.Renderer.sharedMaterials;
			bool flag = false;
			for (int i = 0; i < ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length && i < ((Il2CppArrayBase<Material>)(object)s.Original).Length; i++)
			{
				if (!((Object)(object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[i] == (Object)null) && OurCopies.Contains(((Object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[i]).GetInstanceID()))
				{
					((Il2CppArrayBase<Material>)(object)sharedMaterials)[i] = ((Il2CppArrayBase<Material>)(object)s.Original)[i];
					flag = true;
				}
			}
			if (flag)
			{
				s.Renderer.sharedMaterials = sharedMaterials;
			}
		}

		private static void RestoreAll()
		{
			foreach (List<Swap> value in HiddenModels.Values)
			{
				foreach (Swap item in value)
				{
					Restore(item);
				}
			}
			HiddenModels.Clear();
			Neighbours.Clear();
		}

		private static Material InvisibleFor(Material m)
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)m).GetInstanceID();
			if (Invisible.TryGetValue(instanceID, out var value))
			{
				if (value == null || (Object)(object)value != (Object)null)
				{
					return value;
				}
				ModLog.Trace("Invisible copy of material " + ((Object)m).name + " was unloaded by the game (world change): made again");
			}
			if (_keywords == null)
			{
				_keywords = Texts.Words(Plugin.Keywords.Value);
			}
			if (_trunkWords == null)
			{
				_trunkWords = Texts.Words(Plugin.TrunkKeywords.Value);
			}
			value = null;
			if (Texts.IsLeafMaterial(((Object)m).name, _keywords, _trunkWords))
			{
				value = new Material(m)
				{
					name = ((Object)m).name + " (hidden by TreehouseBranchClear)"
				};
				ShaderTagId val = default(ShaderTagId);
				((ShaderTagId)(ref val))..ctor("LightMode");
				for (int i = 0; i < value.passCount; i++)
				{
					value.SetShaderPassEnabled(value.GetPassName(i), false);
					ShaderTagId val2 = value.shader.FindPassTagValue(i, val);
					string name = ((ShaderTagId)(ref val2)).name;
					if (!string.IsNullOrEmpty(name))
					{
						value.SetShaderPassEnabled(name, false);
					}
				}
				OurCopies.Add(((Object)value).GetInstanceID());
			}
			Invisible[instanceID] = value;
			return value;
		}

		private static void ClearNeighbours(WorldObjectLocator tree)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			List<WorldObjectLocator> val = new List<WorldObjectLocator>();
			Trees.GetTreesInSphere(val, tree.Position, Plugin.NeighbourRadius.Value);
			Enumerator<WorldObjectLocator> enumerator = val.GetEnumerator();
			while (enumerator.MoveNext())
			{
				WorldObjectLocator current = enumerator.Current;
				if (current != null)
				{
					Neighbours.Add(((Il2CppObjectBase)current).Pointer);
					Transform currentLodTransform = current.CurrentLodTransform;
					if ((Object)(object)currentLodTransform != (Object)null)
					{
						Hide(current, currentLodTransform, "next to a built-on tree");
					}
				}
			}
		}

		public static void Scan(Vector3 center)
		{
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			Dirty = false;
			RestoreAll();
			Built.Clear();
			int num = ((!Plugin.Enabled.Value) ? 1 : (((Object)(object)Trees == (Object)null) ? 2 : 0));
			if (ModLog.Changed(0, "scan", num))
			{
				ModLog.Trace(num switch
				{
					2 => "Scan: no TreeManager in this scene (menus or loading), nothing to clear", 
					1 => "Scan: mod off (General/Enabled), every branch shown", 
					_ => "Scan: TreeManager found, clearing the built-on trees around you", 
				});
			}
			if (num != 0)
			{
				return;
			}
			_world = World();
			if (ModLog.Changed(0, "world", _world.GetHashCode()))
			{
				ModLog.Trace($"World id {_world}: the player's tree choices are kept under it ({Choices.Count} line(s) in the file)");
			}
			Found.Clear();
			Trees.GetTreesInSphere(Found, center, Plugin.Radius.Value);
			GuestBuilt.Clear();
			bool isClient = BoltNetwork.isClient;
			ModLog.Once("role " + _world, (!isClient) ? "Host or solo: built-on trees read from the game's own registry" : ((Plugin.GuestLinkMeters.Value > 0f) ? $"Multiplayer guest: the game does not tell a guest which trees carry a build, so build pieces are linked to trees (GuestLinkMeters {Plugin.GuestLinkMeters.Value} m)" : "Multiplayer guest: GuestLinkMeters is 0, so no tree is linked and every branch shows"), (LogLevel)16);
			if (isClient ? (Plugin.GuestLinkMeters.Value > 0f) : ModLog.Full)
			{
				LinkBuilds(isClient);
			}
			int num2 = 0;
			Enumerator<WorldObjectLocator> enumerator = Found.GetEnumerator();
			while (enumerator.MoveNext())
			{
				WorldObjectLocator current = enumerator.Current;
				if (current != null && IsBuilt(current))
				{
					num2++;
					Refresh(current);
				}
			}
			if (ModLog.Changed(0, "built", num2))
			{
				ModLog.Trace($"{num2} tree(s) with a build within {Plugin.Radius.Value} m");
			}
		}

		private static bool IsBuilt(WorldObjectLocator tree)
		{
			if (!Trees.HasStructure(tree))
			{
				return GuestBuilt.Contains(((Il2CppObjectBase)tree).Pointer);
			}
			return true;
		}

		private static void LinkBuilds(bool guest)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			Flat.Clear();
			Enumerator<WorldObjectLocator> enumerator = Found.GetEnumerator();
			while (enumerator.MoveNext())
			{
				WorldObjectLocator current = enumerator.Current;
				if (current != null && current.IsTree)
				{
					Flat.Add((new Vector2(current.Position.x, current.Position.z), current));
				}
			}
			int pieces = 0;
			int byId = 0;
			int byDistance = 0;
			int noId = 0;
			List<ScrewTreeLinker>[] array = new List<ScrewTreeLinker>[2]
			{
				ScrewTreeLinkerSaveManager._treeBuiltLinkers,
				ScrewTreeLinkerSaveManager._treeNodeLinkers
			};
			foreach (List<ScrewTreeLinker> val in array)
			{
				if (val == null)
				{
					continue;
				}
				Enumerator<ScrewTreeLinker> enumerator2 = val.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					ScrewTreeLinker current2 = enumerator2.Current;
					if ((Object)(object)current2 != (Object)null && ((Component)current2).gameObject.activeInHierarchy)
					{
						SaveData treeData = current2._treeData;
						Link((Component)(object)current2, (treeData != null) ? treeData._locatorId : null, "ScrewTreeLinker", guest, ref pieces, ref byId, ref byDistance, ref noId);
					}
				}
			}
			List<TreeStructure> treeStructures = TreeStructureSaveManager._treeStructures;
			if (treeStructures != null)
			{
				Enumerator<TreeStructure> enumerator3 = treeStructures.GetEnumerator();
				while (enumerator3.MoveNext())
				{
					TreeStructure current3 = enumerator3.Current;
					if ((Object)(object)current3 != (Object)null && ((Component)current3).gameObject.activeInHierarchy)
					{
						SaveData treeData2 = current3._treeData;
						Link((Component)(object)current3, (treeData2 != null) ? treeData2._locatorId : null, "TreeStructure", guest, ref pieces, ref byId, ref byDistance, ref noId);
					}
				}
			}
			string text = $"{(guest ? $"Multiplayer guest: {GuestBuilt.Count} tree(s) linked to a build" : "Host check of the guest linking")}; {pieces} tree build piece(s) found: {byId} by the game's tree id, {byDistance} by distance ({Plugin.GuestLinkMeters.Value} m), {pieces - byId - byDistance} unlinked, {noId} of them without a tree id";
			if (ModLog.Full)
			{
				if (ModLog.Changed(0, "tree links", text.GetHashCode()))
				{
					ModLog.Trace(text);
				}
			}
			else
			{
				ModLog.Once($"guest links {_world} {GuestBuilt.Count > 0}", text, (LogLevel)16);
			}
		}

		private static void Link(Component piece, WorldLocatorId id, string kind, bool guest, ref int pieces, ref int byId, ref int byDistance, ref int noId)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			pieces++;
			Vector3 position = piece.transform.position;
			WorldObjectLocator val = ((id == (WorldLocatorId)null) ? null : ById(id));
			bool flag = val != null;
			float num = float.MaxValue;
			if (!flag)
			{
				foreach (var item3 in Flat)
				{
					Vector2 item = item3.Foot;
					WorldObjectLocator item2 = item3.Tree;
					Vector2 val2 = item - new Vector2(position.x, position.z);
					float magnitude = ((Vector2)(ref val2)).magnitude;
					if (magnitude <= Plugin.GuestLinkMeters.Value && magnitude < num)
					{
						val = item2;
						num = magnitude;
					}
				}
			}
			if (val != null)
			{
				if (flag)
				{
					byId++;
				}
				else
				{
					byDistance++;
				}
				if (guest)
				{
					GuestBuilt.Add(((Il2CppObjectBase)val).Pointer);
				}
			}
			else if (id == (WorldLocatorId)null)
			{
				noId++;
			}
			if (ModLog.Full)
			{
				bool flag2 = val != null && !guest && Trees.HasStructure(val);
				bool flag3 = ((val == null) ? (id == (WorldLocatorId)null) : (flag && (guest || flag2)));
				if (ModLog.Changed(((Il2CppObjectBase)piece).Pointer.GetHashCode(), "tree link", HashCode.Combine((val != null) ? ((Il2CppObjectBase)val).Pointer : IntPtr.Zero, flag, flag2)) && !flag3)
				{
					ModLog.Trace((val == null) ? $"Tree link: {kind} at {position} has the game's tree id {id} but no tree there within {Plugin.GuestLinkMeters.Value} m" : $"Tree link: {kind} at {position} -> tree {val.DataName} {(flag ? "by the game's tree id" : $"{num:F2} m from its axis")}{(guest ? ", linked as guest" : $" (game's registry says built: {flag2})")}");
				}
			}
		}

		private static WorldObjectLocator ById(WorldLocatorId id)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			Near.Clear();
			Trees.GetTreesInSphere(Near, id.GetLossyPosition(), Plugin.GuestLinkMeters.Value);
			Enumerator<WorldObjectLocator> enumerator = Near.GetEnumerator();
			while (enumerator.MoveNext())
			{
				WorldObjectLocator current = enumerator.Current;
				if (current != null && current.UniqueId != (WorldLocatorId)null && current.UniqueId.Equals(id))
				{
					return current;
				}
			}
			return null;
		}

		public static void Reset()
		{
			RestoreAll();
			foreach (Material value in Invisible.Values)
			{
				if ((Object)(object)value != (Object)null)
				{
					Object.Destroy((Object)(object)value);
				}
			}
			Invisible.Clear();
			OurCopies.Clear();
			Logged.Clear();
			_keywords = (_trunkWords = null);
			Dirty = true;
		}
	}
	[HarmonyPatch(typeof(TreeManager), "RegisterTreeStructure")]
	internal static class BuildAdded
	{
		private static void Postfix()
		{
			BranchHider.Dirty = true;
		}
	}
	[HarmonyPatch(typeof(TreeManager), "UnRegisterTreeStructure")]
	internal static class BuildRemoved
	{
		private static void Postfix()
		{
			BranchHider.Dirty = true;
		}
	}
	public static class TreePrompt
	{
		private static GameObject _prompt;

		private static LinkUiElement _link;

		private static WorldObjectLocator _target;

		private static float _nextCheck;

		private static bool _logged;

		internal static bool Visible
		{
			get
			{
				if (_target == null)
				{
					if ((Object)(object)_prompt != (Object)null)
					{
						return _prompt.activeSelf;
					}
					return false;
				}
				return true;
			}
		}

		public static void Update(Camera cam)
		{
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			if (_target != null && InputSystem.GetButtonDown(Actions.Use))
			{
				Use(_target);
			}
			else
			{
				if (Time.unscaledTime < _nextCheck)
				{
					return;
				}
				_nextCheck = Time.unscaledTime + Plugin.PromptCheckSeconds.Value;
				bool flag = Plugin.ShowPrompt.Value && Plugin.Enabled.Value;
				WorldObjectLocator val = (_target = (flag ? Aimed(cam) : null));
				if ((val != null || !flag) && ModLog.Changed(0, "prompt", (val == null) ? 1 : ((Il2CppObjectBase)val).Pointer.GetHashCode()))
				{
					ModLog.Trace((val != null) ? $"Prompt shown on the trunk of {val.DataName} at {val.Position}" : "Prompt off (Prompt/Enabled or General/Enabled)");
				}
				if (val == null)
				{
					if ((Object)(object)_prompt != (Object)null && _prompt.activeSelf)
					{
						_prompt.SetActive(false);
					}
					return;
				}
				Prompt().transform.position = val.Position + Vector3.up * Plugin.PromptHeight.Value;
				if (_prompt.activeSelf)
				{
					return;
				}
				_link.SetId(IconId(), true);
				_link._maxDistance = Plugin.PromptReach.Value + Plugin.PromptAimWidth.Value;
				_prompt.SetActive(true);
				if (!_logged)
				{
					_logged = true;
					ModLog.Trace("Prompt icon '" + IconId() + "'; prompt ids the game has: " + KnownIds());
					if (ModLog.Full)
					{
						TraceGrabber(cam);
					}
				}
			}
		}

		private static void TraceGrabber(Camera cam)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: 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_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			GrabberSimplePhysicsTriggers val = Object.FindObjectOfType<GrabberSimplePhysicsTriggers>();
			if ((Object)(object)val == (Object)null)
			{
				ModLog.Trace("Pick-up zone: grabber not found");
				return;
			}
			Transform transform = ((Component)val).transform;
			foreach (BoxCollider component in ((Component)val).GetComponents<BoxCollider>())
			{
				Vector3 val2 = ((Component)cam).transform.InverseTransformPoint(transform.TransformPoint(component.center + new Vector3(0f, 0f, component.size.z / 2f)));
				Vector3 val3 = ((Component)cam).transform.InverseTransformPoint(transform.TransformPoint(component.center - new Vector3(0f, 0f, component.size.z / 2f)));
				ModLog.Trace($"Pick-up zone box: {val3.z:F2} to {val2.z:F2} m ahead of the eye, {component.size.x * transform.lossyScale.x:F2} m wide, {component.size.y * transform.lossyScale.y:F2} m high (Reach {Plugin.PromptReach.Value:F2} m, AimWidth {Plugin.PromptAimWidth.Value:F2} m)");
			}
		}

		private static string IconId()
		{
			if (Plugin.PromptIcon.Value.Trim().Length <= 0)
			{
				return PickUp.ScreenUseUiElementId;
			}
			return Plugin.PromptIcon.Value.Trim();
		}

		private static string KnownIds()
		{
			UiManager instance = UiManager._instance;
			if ((Object)(object)instance == (Object)null || instance._elements == null)
			{
				return "(UI manager not found)";
			}
			SortedSet<string> sortedSet = new SortedSet<string>();
			Enumerator<UiElement> enumerator = instance._elements.GetEnumerator();
			while (enumerator.MoveNext())
			{
				UiElement current = enumerator.Current;
				if (current != null && !string.IsNullOrEmpty(current.Id))
				{
					sortedSet.Add(current.Id);
				}
			}
			return string.Join(", ", sortedSet);
		}

		private static WorldObjectLocator Aimed(Camera cam)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: 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_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			if (BranchHider.Built.Count == 0)
			{
				return null;
			}
			Vector3 position = ((Component)cam).transform.position;
			Vector3 forward = ((Component)cam).transform.forward;
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(forward.x, forward.z);
			if (((Vector2)(ref val)).sqrMagnitude < 0.01f)
			{
				return null;
			}
			((Vector2)(ref val)).Normalize();
			WorldObjectLocator result = null;
			float num = float.MaxValue;
			Vector2 val2 = default(Vector2);
			foreach (WorldObjectLocator value in BranchHider.Built.Values)
			{
				if (value == null)
				{
					continue;
				}
				Vector3 position2 = value.Position;
				((Vector2)(ref val2))..ctor(position2.x - position.x, position2.z - position.z);
				float num2 = Vector2.Dot(val2, val);
				if (!(num2 < 0f) && !(num2 > Plugin.PromptReach.Value) && !(Mathf.Abs(position.y - (position2.y + Plugin.PromptHeight.Value)) > Plugin.PromptReach.Value))
				{
					Vector2 val3 = val2 - val * num2;
					if (!(((Vector2)(ref val3)).magnitude > Plugin.PromptAimWidth.Value) && !(num2 >= num))
					{
						result = value;
						num = num2;
					}
				}
			}
			return result;
		}

		private static GameObject Prompt()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			if ((Object)(object)_prompt != (Object)null)
			{
				return _prompt;
			}
			_prompt = new GameObject("TreehouseBranchClearPrompt");
			_prompt.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)_prompt);
			_link = _prompt.AddComponent<LinkUiElement>();
			_link._maxDistance = Plugin.PromptReach.Value + Plugin.PromptAimWidth.Value;
			_link.SetId(IconId(), false);
			return _prompt;
		}

		private static void Use(WorldObjectLocator tree)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			bool flag = BranchHider.Toggle(tree);
			ModLog.Trace($"Tree {tree.DataName} at {tree.Position}: branches {(flag ? "shown" : "hidden")} by the player");
			float value = Plugin.MessageSeconds.Value;
			if (!(value <= 0f))
			{
				string text = (flag ? Plugin.ShownMessage.Value : Plugin.HiddenMessage.Value);
				string text2;
				if (text.Length <= 0)
				{
					Locale selectedLocale = LocalizationSettings.SelectedLocale;
					text2 = Texts.Get((selectedLocale != null) ? selectedLocale.Identifier.Code : null, flag ? "Shown" : "Hidden");
				}
				else
				{
					text2 = text;
				}
				string text3 = text2;
				HudGui instance = HudGui._instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.DisplayGeneralMessage(text3, value, (ItemUiData)null);
				}
				else
				{
					ModLog.Once("hud", "Game HUD not found: the branches hidden/shown confirmation was not shown", (LogLevel)4);
				}
			}
		}
	}
}
namespace TreehouseBranchClear.Logic
{
	public static class PromptIcons
	{
		public static readonly string[] All = new string[42]
		{
			"screen.use", "screen.cancel", "screen.climbRaft", "screen.closeBook", "screen.droppedBag", "screen.eatCookedFoodFromPot", "screen.escape", "screen.golfCartRadioNextTrack", "screen.golfCartRadioOnOff", "screen.gotoBuilding",
			"screen.gotoTutorials", "screen.iconOnly", "screen.igniteFire", "screen.interact", "screen.kickWindow", "screen.logSled", "screen.open", "screen.openCookingBag", "screen.openHatch", "screen.playerName",
			"screen.radioNextTrack", "screen.radioOnOff", "screen.radioPlace", "screen.resetTrap", "screen.revivePlayer", "screen.rotate", "screen.save", "screen.shoulderTap", "screen.shoulderTapOption", "screen.shoulderTapSelected",
			"screen.sleep", "screen.sleepDisabled", "screen.storageCount", "screen.storageInteract", "screen.swapAmmo", "screen.take", "screen.takeAndConsume", "screen.takeAndConsumeKnownBad", "screen.takeAndConsumeKnownGood", "screen.takeAndUse",
			"screen.toggleInventoryMode", "screen.virtualPickupDebug"
		};
	}
	public static class ReachDefaults
	{
		public const float OldReach = 3f;

		public const float OldAimWidth = 1f;

		public const float Reach = 1.9f;

		public const float AimWidth = 0.6f;

		public static float Upgrade(float current, float oldDefault, float newDefault)
		{
			if (current != oldDefault)
			{
				return current;
			}
			return newDefault;
		}

		public static void SelfCheck()
		{
			if (Upgrade(3f, 3f, 1.9f) != 1.9f || Upgrade(2.2f, 3f, 1.9f) != 2.2f || Upgrade(1f, 1f, 0.6f) != 0.6f)
			{
				throw new InvalidOperationException("ReachDefaults self-check failed");
			}
		}
	}
	public static class Texts
	{
		public const string Hidden = "Hidden";

		public const string Shown = "Shown";

		private static readonly Dictionary<string, Dictionary<string, string>> ByLanguage = new Dictionary<string, Dictionary<string, string>>
		{
			["en"] = new Dictionary<string, string>
			{
				["Hidden"] = "Branches hidden on this tree",
				["Shown"] = "Branches shown on this tree"
			},
			["fr"] = new Dictionary<string, string>
			{
				["Hidden"] = "Branches masquées sur cet arbre",
				["Shown"] = "Branches affichées sur cet arbre"
			},
			["zh"] = new Dictionary<string, string>
			{
				["Hidden"] = "此树枝干已隐藏",
				["Shown"] = "此树枝干已显示"
			},
			["zh-hant"] = new Dictionary<string, string>
			{
				["Hidden"] = "此樹枝幹已隱藏",
				["Shown"] = "此樹枝幹已顯示"
			},
			["cs"] = new Dictionary<string, string>
			{
				["Hidden"] = "Větve tohoto stromu jsou skryté",
				["Shown"] = "Větve tohoto stromu jsou zobrazené"
			},
			["fi"] = new Dictionary<string, string>
			{
				["Hidden"] = "Oksat piilotettu tästä puusta",
				["Shown"] = "Oksat näkyvissä tässä puussa"
			},
			["de"] = new Dictionary<string, string>
			{
				["Hidden"] = "Äste an diesem Baum ausgeblendet",
				["Shown"] = "Äste an diesem Baum eingeblendet"
			},
			["it"] = new Dictionary<string, string>
			{
				["Hidden"] = "Rami nascosti su questo albero",
				["Shown"] = "Rami mostrati su questo albero"
			},
			["ja"] = new Dictionary<string, string>
			{
				["Hidden"] = "この木の枝を非表示にしました",
				["Shown"] = "この木の枝を表示しました"
			},
			["ko"] = new Dictionary<string, string>
			{
				["Hidden"] = "이 나무의 나뭇가지 숨김",
				["Shown"] = "이 나무의 나뭇가지 표시됨"
			},
			["pl"] = new Dictionary<string, string>
			{
				["Hidden"] = "Gałęzie tego drzewa są ukryte",
				["Shown"] = "Gałęzie tego drzewa są widoczne"
			},
			["pt"] = new Dictionary<string, string>
			{
				["Hidden"] = "Galhos ocultados nesta árvore",
				["Shown"] = "Galhos visíveis nesta árvore"
			},
			["ru"] = new Dictionary<string, string>
			{
				["Hidden"] = "Ветки на этом дереве скрыты",
				["Shown"] = "Ветки на этом дереве видны"
			},
			["es"] = new Dictionary<string, string>
			{
				["Hidden"] = "Ramas ocultas en este árbol",
				["Shown"] = "Ramas visibles en este árbol"
			},
			["sv"] = new Dictionary<string, string>
			{
				["Hidden"] = "Grenar dolda på detta träd",
				["Shown"] = "Grenar synliga på detta träd"
			},
			["tr"] = new Dictionary<string, string>
			{
				["Hidden"] = "Bu ağaçtaki dallar gizlendi",
				["Shown"] = "Bu ağaçtaki dallar gösterildi"
			}
		};

		public static string Get(string localeCode, string key)
		{
			string text = (localeCode ?? "en").ToLowerInvariant();
			string key2 = (ByLanguage.ContainsKey(text) ? text : text.Split('-')[0]);
			if (!ByLanguage.TryGetValue(key2, out var value) || !value.TryGetValue(key, out var value2))
			{
				return ByLanguage["en"][key];
			}
			return value2;
		}

		public static string[] Words(string list)
		{
			return (from k in (list ?? "").Split(',')
				select k.Trim() into k
				where k.Length > 0
				select k).ToArray();
		}

		public static bool Matches(string name, string[] words)
		{
			if (!string.IsNullOrEmpty(name))
			{
				return words.Any((string k) => name.IndexOf(k, StringComparison.OrdinalIgnoreCase) >= 0);
			}
			return false;
		}

		public static bool IsLeafMaterial(string material, string[] keywords, string[] trunkWords)
		{
			if (Matches(material, keywords))
			{
				return !Matches(material, trunkWords);
			}
			return false;
		}

		public static void SelfCheck()
		{
			string[] keywords = Words("leaves");
			string[] trunkWords = Words("bark");
			if (!Matches("Tree_Leaves_LOD0", Words("branch, leaves")) || Matches("Trunk", Words("branch, leaves")) || Words(" , ").Length != 0 || Matches(null, Words("a")) || !IsLeafMaterial("Pine_Leaves", keywords, trunkWords) || IsLeafMaterial("Pine_Bark", keywords, trunkWords) || IsLeafMaterial("Leaves_Bark", keywords, trunkWords) || IsLeafMaterial(null, keywords, trunkWords) || Get("fr-FR", "Shown") != "Branches affichées sur cet arbre" || Get("xx", "Hidden") != "Branches hidden on this tree" || Get(null, "Shown") != "Branches shown on this tree")
			{
				throw new InvalidOperationException("Texts self-check failed.");
			}
		}
	}
	public class TreeChoices
	{
		private readonly string _path;

		private readonly HashSet<string> _shown = new HashSet<string>();

		public int Count => _shown.Count;

		public TreeChoices(string path)
		{
			_path = path;
			if (!File.Exists(path))
			{
				return;
			}
			string[] array = File.ReadAllLines(path);
			foreach (string text in array)
			{
				if (text.Trim().Length > 0)
				{
					_shown.Add(text.Trim());
				}
			}
		}

		public static string Key(string world, string treeId)
		{
			return world + " " + treeId;
		}

		public bool IsShown(string world, string treeId)
		{
			return _shown.Contains(Key(world, treeId));
		}

		public int Adopt(string from, string to)
		{
			string text = from + " ";
			List<string> list = new List<string>();
			foreach (string item in _shown)
			{
				if (item.StartsWith(text))
				{
					list.Add(to + " " + item.Substring(text.Length));
				}
			}
			int num = 0;
			foreach (string item2 in list)
			{
				if (_shown.Add(item2))
				{
					num++;
				}
			}
			if (num > 0)
			{
				File.WriteAllLines(_path, _shown);
			}
			return num;
		}

		public bool HasAny(string world)
		{
			foreach (string item in _shown)
			{
				if (item.StartsWith(world + " "))
				{
					return true;
				}
			}
			return false;
		}

		public bool Toggle(string world, string treeId)
		{
			string item = Key(world, treeId);
			bool result = _shown.Add(item) || !_shown.Remove(item);
			File.WriteAllLines(_path, _shown);
			return result;
		}

		public static void SelfCheck(string tempPath)
		{
			File.Delete(tempPath);
			TreeChoices treeChoices = new TreeChoices(tempPath);
			bool num = treeChoices.Toggle("7", "a") && treeChoices.IsShown("7", "a") && !treeChoices.IsShown("8", "a") && new TreeChoices(tempPath).IsShown("7", "a") && !treeChoices.Toggle("7", "a") && new TreeChoices(tempPath).Count == 0 && treeChoices.Toggle("7", "b") && !treeChoices.HasAny("w") && treeChoices.Adopt("7", "w") == 1 && new TreeChoices(tempPath).IsShown("w", "b") && treeChoices.HasAny("w") && treeChoices.Adopt("7", "w") == 0;
			File.Delete(tempPath);
			if (!num)
			{
				throw new InvalidOperationException("TreeChoices self-check failed.");
			}
		}
	}
}