Decompiled source of ScrollToArms v0.2.4

ScrollToArms.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;

[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("isimp")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2026 isimp")]
[assembly: AssemblyDescription("Pick the weapon or tool in your hand with the mouse wheel, while the game still decides when it can be changed.")]
[assembly: AssemblyFileVersion("0.2.4.0")]
[assembly: AssemblyInformationalVersion("0.2.4+3b76a569a01d170df4489a0a373d098dac87245d")]
[assembly: AssemblyProduct("ScrollToArms")]
[assembly: AssemblyTitle("ScrollToArms")]
[assembly: InternalsVisibleTo("ScrollToArms.SelfTest")]
[assembly: AssemblyVersion("0.2.4.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 ScrollToArms
{
	internal static class BuildToolHint
	{
		private static readonly HintWatch<ItemData> Arrival = new HintWatch<ItemData>();

		public static void Watch(ItemData item, float now)
		{
			Arrival.Watch(item, KindOf(item), now);
		}

		private static HintKind KindOf(ItemData item)
		{
			if (item?.m_shared != null)
			{
				return WheelWords.HintKindOf(StepAside.Listed(item), (Object)(object)item.m_shared.m_buildPieces != (Object)null, WheelReads.PlacementReady, Plugin.PlainScroll);
			}
			return HintKind.None;
		}

		public static void Update(Player player, float now)
		{
			ItemData watched = Arrival.Watched;
			if (Arrival.Arrived(now, watched?.m_equipped ?? false, out var item, out var kind))
			{
				Show(player, item, kind);
			}
		}

		private static void Show(Player player, ItemData item, HintKind kind)
		{
			if (Plugin.ShowCenterHints)
			{
				string name = ItemNameList.ShownName(item.m_shared.m_name);
				((Character)player).Message((MessageType)2, WheelWords.Hint(kind, name, KeyText.Modifier, KeyText.Hide, Plugin.FlipBack), 0, (Sprite)null, false);
			}
		}
	}
	internal static class HotbarView
	{
		private const string VanillaBarName = "HotKeyBar";

		private static readonly FieldInfo ElementsField = AccessTools.Field(typeof(HotkeyBar), "m_elements");

		private static readonly FieldInfo SelectedField = AccessTools.Field(typeof(HotkeyBar), "m_selected");

		private static readonly Type ElementType = AccessTools.Inner(typeof(HotkeyBar), "ElementData");

		private static readonly FieldInfo SelectionField = ((ElementType == null) ? null : AccessTools.Field(ElementType, "m_selection"));

		private static readonly FieldInfo QueuedField = ((ElementType == null) ? null : AccessTools.Field(ElementType, "m_queued"));

		private static readonly FieldInfo GoField = ((ElementType == null) ? null : AccessTools.Field(ElementType, "m_go"));

		internal static readonly bool Available = CheckAvailable();

		private static Hud _hud;

		private static HotkeyBar _bar;

		private static bool _drawn;

		private const float NameGap = 6f;

		private const float NameScale = 0.95f;

		private static TMP_Text _name;

		private static readonly Color FlashColor = new Color(1f, 0.25f, 0.2f, 1f);

		private static GameObject _flashed;

		private static Graphic[] _flashedGraphics;

		private static Color[] _flashedColors;

		private static CanvasGroup _pulsed;

		private static bool CheckAvailable()
		{
			if (ElementsField != null && SelectedField != null && SelectionField != null && QueuedField != null)
			{
				return true;
			}
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)"ScrollToArms: the hotbar's markers were not found. Scrolling still works, but the pick is not shown on the bar.");
			}
			return false;
		}

		public static void Draw()
		{
			if (!Available)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			HotkeyBar val = FindBar();
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)val == (Object)null)
			{
				HideName();
				_drawn = false;
			}
			else
			{
				if (!(ElementsField.GetValue(val) is IList list))
				{
					return;
				}
				int num = PickLook.Frame(Picker.Choosing, Picker.Cursor, Picker.PendingSlot);
				int pendingSlot = Picker.PendingSlot;
				float num2 = Time.time - Picker.LostAt;
				int num3 = PickLook.Flash(Picker.LostSlot, num2, num);
				if (!PickLook.Shows(num, pendingSlot, num3))
				{
					if (_drawn)
					{
						Restore(val, localPlayer);
					}
					_drawn = false;
					DrawLabel(val, localPlayer, list, -1, -1, 0f);
					return;
				}
				if (num3 < 0)
				{
					StopFlash();
				}
				for (int i = 0; i < list.Count; i++)
				{
					object obj = list[i];
					if (obj != null)
					{
						object? value = SelectionField.GetValue(obj);
						GameObject val2 = (GameObject)((value is GameObject) ? value : null);
						SetActive(val2, i == num || i == num3);
						if (i == num)
						{
							Pulse(val2, PickLook.Pulses(Picker.Choosing, Picker.Waiting));
						}
						if (i == num3)
						{
							Flash(val2, num2);
						}
						ItemData val3 = Picker.ItemAt(localPlayer, i);
						bool active = PickLook.Queued(i, pendingSlot, val3 != null && localPlayer.IsEquipActionQueued(val3));
						object? value2 = QueuedField.GetValue(obj);
						SetActive((GameObject)((value2 is GameObject) ? value2 : null), active);
					}
				}
				DrawLabel(val, localPlayer, list, num, num3, num2);
				_drawn = true;
			}
		}

		private static void DrawLabel(HotkeyBar bar, Player player, IList elements, int frame, int flash, float flashAge)
		{
			//IL_00b4: 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_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: 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_0123: Unknown result type (might be due to invalid IL or missing references)
			int num = PickLook.NamedSlot(frame, flash);
			ItemData val = ((num >= 0) ? Picker.ItemAt(player, num) : null);
			string text = null;
			bool flag = PickLook.LostName(val != null, frame);
			if (val != null)
			{
				if (Plugin.ShowItemName)
				{
					text = ItemNameList.ShownName(val.m_shared.m_name);
				}
			}
			else
			{
				text = WheelMode.Text(player);
			}
			GameObject val2 = (GameObject)((text != null && GoField != null && elements.Count > 0) ? /*isinst with value type is only supported in some contexts*/: null);
			if ((Object)(object)val2 == (Object)null)
			{
				HideName();
				return;
			}
			TMP_Text val3 = NameLabel(bar, val2);
			if (!((Object)(object)val3 == (Object)null))
			{
				val3.text = text;
				Color color = (flag ? FlashColor : Color.white);
				color.a = PickLook.NameAlpha(flag, PickLook.Fade(flashAge));
				((Graphic)val3).color = color;
				Vector3[] array = (Vector3[])(object)new Vector3[4];
				((RectTransform)val2.transform).GetWorldCorners(array);
				((Transform)val3.rectTransform).position = array[1] + Vector3.up * (6f * val2.transform.lossyScale.y);
				if (!((Component)val3).gameObject.activeSelf)
				{
					((Component)val3).gameObject.SetActive(true);
				}
			}
		}

		private static TMP_Text NameLabel(HotkeyBar bar, GameObject slot)
		{
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_name != (Object)null)
			{
				return _name;
			}
			TMP_Text val = null;
			Transform val2 = slot.transform.Find("binding");
			if ((Object)(object)val2 != (Object)null)
			{
				val = ((Component)val2).GetComponent<TMP_Text>();
			}
			if ((Object)(object)val == (Object)null)
			{
				val = slot.GetComponentInChildren<TMP_Text>(true);
			}
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			GameObject obj = Object.Instantiate<GameObject>(((Component)val).gameObject, ((Component)bar).transform, false);
			((Object)obj).name = "ScrollToArmsItemName";
			_name = obj.GetComponent<TMP_Text>();
			_name.alignment = (TextAlignmentOptions)1025;
			_name.textWrappingMode = (TextWrappingModes)0;
			_name.overflowMode = (TextOverflowModes)0;
			_name.fontSize = val.fontSize * 0.95f;
			((Graphic)_name).raycastTarget = false;
			RectTransform rectTransform = _name.rectTransform;
			rectTransform.pivot = new Vector2(0f, 0f);
			rectTransform.sizeDelta = new Vector2(400f, rectTransform.sizeDelta.y);
			return _name;
		}

		private static void HideName()
		{
			if ((Object)(object)_name != (Object)null && ((Component)_name).gameObject.activeSelf)
			{
				((Component)_name).gameObject.SetActive(false);
			}
		}

		private static void Flash(GameObject selection, float age)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)selection == (Object)null)
			{
				return;
			}
			if ((Object)(object)_flashed != (Object)(object)selection)
			{
				StopFlash();
				_flashed = selection;
				_flashedGraphics = selection.GetComponentsInChildren<Graphic>(true);
				_flashedColors = (Color[])(object)new Color[_flashedGraphics.Length];
				for (int i = 0; i < _flashedGraphics.Length; i++)
				{
					_flashedColors[i] = _flashedGraphics[i].color;
					Color flashColor = FlashColor;
					flashColor.a = _flashedColors[i].a;
					_flashedGraphics[i].color = flashColor;
				}
			}
			CanvasGroup val = GroupOf(selection);
			if ((Object)(object)_pulsed == (Object)(object)val)
			{
				_pulsed = null;
			}
			val.alpha = PickLook.Fade(age);
		}

		private static void StopFlash()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_flashed == (Object)null)
			{
				return;
			}
			for (int i = 0; i < _flashedGraphics.Length; i++)
			{
				if ((Object)(object)_flashedGraphics[i] != (Object)null)
				{
					_flashedGraphics[i].color = _flashedColors[i];
				}
			}
			CanvasGroup component = _flashed.GetComponent<CanvasGroup>();
			if ((Object)(object)component != (Object)null)
			{
				component.alpha = 1f;
			}
			_flashed = null;
			_flashedGraphics = null;
			_flashedColors = null;
		}

		private static void Pulse(GameObject selection, bool on)
		{
			if ((Object)(object)selection == (Object)null)
			{
				return;
			}
			if (!on)
			{
				StopPulse();
				return;
			}
			CanvasGroup val = GroupOf(selection);
			if ((Object)(object)_pulsed != (Object)(object)val)
			{
				StopPulse();
			}
			_pulsed = val;
			val.alpha = PickLook.PulseAlpha(Time.time - Picker.WaitingSince);
		}

		private static CanvasGroup GroupOf(GameObject selection)
		{
			CanvasGroup val = selection.GetComponent<CanvasGroup>();
			if ((Object)(object)val == (Object)null)
			{
				val = selection.AddComponent<CanvasGroup>();
			}
			return val;
		}

		private static void StopPulse()
		{
			if ((Object)(object)_pulsed != (Object)null)
			{
				_pulsed.alpha = 1f;
			}
			_pulsed = null;
		}

		private static void Restore(HotkeyBar bar, Player player)
		{
			StopPulse();
			StopFlash();
			HideName();
			if (!(ElementsField.GetValue(bar) is IList list))
			{
				return;
			}
			bool flag = ZInput.IsGamepadActive();
			int num = (int)SelectedField.GetValue(bar);
			for (int i = 0; i < list.Count; i++)
			{
				object obj = list[i];
				if (obj != null)
				{
					object? value = SelectionField.GetValue(obj);
					SetActive((GameObject)((value is GameObject) ? value : null), flag && i == num);
					ItemData val = Picker.ItemAt(player, i);
					object? value2 = QueuedField.GetValue(obj);
					SetActive((GameObject)((value2 is GameObject) ? value2 : null), val != null && player.IsEquipActionQueued(val));
				}
			}
		}

		private static HotkeyBar FindBar()
		{
			Hud instance = Hud.instance;
			if ((Object)(object)instance == (Object)null)
			{
				_hud = null;
				_bar = null;
				return null;
			}
			if ((Object)(object)instance == (Object)(object)_hud)
			{
				return _bar;
			}
			_hud = instance;
			_bar = null;
			HotkeyBar[] componentsInChildren = ((Component)instance).GetComponentsInChildren<HotkeyBar>(true);
			foreach (HotkeyBar val in componentsInChildren)
			{
				if (!(((Object)val).name != "HotKeyBar"))
				{
					_bar = val;
					break;
				}
			}
			return _bar;
		}

		private static void SetActive(GameObject go, bool active)
		{
			if ((Object)(object)go != (Object)null && go.activeSelf != active)
			{
				go.SetActive(active);
			}
		}
	}
	internal static class HotbarWalk
	{
		public static int NextStop(int width, int from, int step, bool wrap, Func<int, bool> isStop)
		{
			if (width <= 0)
			{
				return -1;
			}
			int num = from;
			if (num < 0)
			{
				num = ((step > 0) ? (-1) : width);
			}
			for (int i = 0; i < width; i++)
			{
				num += step;
				if (num < 0 || num >= width)
				{
					if (!wrap)
					{
						if (from < 0)
						{
							return -1;
						}
						return from;
					}
					num = (num + width) % width;
				}
				if (isStop(num))
				{
					return num;
				}
			}
			if (from < 0 || !isStop(from))
			{
				return -1;
			}
			return from;
		}
	}
	internal sealed class Notches
	{
		private const float Threshold = 0.1f;

		private const float Memory = 0.3f;

		private float _wheel;

		public float LastNotch { get; private set; }

		public void Clear()
		{
			_wheel = 0f;
		}

		public int Read(float delta, float now, bool invert)
		{
			if (delta == 0f)
			{
				if (now - LastNotch > 0.3f)
				{
					_wheel = 0f;
				}
				return 0;
			}
			_wheel += delta;
			if (Math.Abs(_wheel) < 0.1f)
			{
				return 0;
			}
			int num = ((!(_wheel > 0f)) ? 1 : (-1));
			if (invert)
			{
				num = -num;
			}
			_wheel = 0f;
			LastNotch = now;
			return num;
		}
	}
	internal sealed class ItemNameList
	{
		private readonly Func<string> _source;

		private HashSet<string> _names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private string _parsed;

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

		public ItemNameList(Func<string> source)
		{
			_source = source;
		}

		public bool Contains(ItemData item)
		{
			if (item?.m_shared == null)
			{
				return false;
			}
			Refresh();
			if (_names.Count == 0)
			{
				return false;
			}
			GameObject dropPrefab = item.m_dropPrefab;
			return Contains(((Object)(object)dropPrefab != (Object)null) ? ((Object)dropPrefab).name : null, item.m_shared.m_name, ShownName);
		}

		internal bool Contains(string prefab, string token, Func<string, string> shown)
		{
			Refresh();
			if (_names.Count == 0)
			{
				return false;
			}
			if (prefab != null && _names.Contains(prefab))
			{
				return true;
			}
			if (string.IsNullOrEmpty(token))
			{
				return false;
			}
			if (_names.Contains(token))
			{
				return true;
			}
			return _names.Contains(shown(token));
		}

		public static string ShownName(string token)
		{
			if (string.IsNullOrEmpty(token))
			{
				return "";
			}
			if (Shown.TryGetValue(token, out var value))
			{
				return value;
			}
			Localization instance = Localization.instance;
			if (instance == null)
			{
				return token;
			}
			value = instance.Localize(token);
			Shown[token] = value;
			return value;
		}

		private void Refresh()
		{
			string text = _source() ?? "";
			if (text == _parsed)
			{
				return;
			}
			_parsed = text;
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			string[] array = text.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length > 0)
				{
					hashSet.Add(text2);
				}
			}
			_names = hashSet;
		}
	}
	internal static class KeyText
	{
		public static string Modifier => WheelWords.Spaced(((object)Plugin.Modifier/*cast due to .constrained prefix*/).ToString());

		public static string Hide
		{
			get
			{
				string text = ((ZInput.instance != null) ? ZInput.instance.GetBoundKeyString("Hide", true) : "");
				Localization instance = Localization.instance;
				string text2;
				if (string.IsNullOrEmpty(text) || instance == null)
				{
					text2 = text;
					if (text2 == null)
					{
						return "";
					}
				}
				else
				{
					text2 = instance.Localize(text);
				}
				return text2;
			}
		}
	}
	public enum PlainScroll
	{
		Zoom,
		Hotbar
	}
	public enum Commit
	{
		OnRelease,
		AfterPause
	}
	internal static class Picker
	{
		private sealed class PlayerWorld : IPickWorld<ItemData>
		{
			public Player Player;

			public PlainScroll PlainScroll => Plugin.PlainScroll;

			public Commit Commit => Plugin.EffectiveCommit;

			public float PauseTime => Plugin.PauseTime;

			public bool Wrap => Plugin.Wrap;

			public bool Invert => Plugin.Invert;

			public bool FlipBack => Plugin.FlipBack;

			public float WaitWhileBusy => Plugin.WaitWhileBusy;

			public bool CanPick => CanPick(Player);

			public bool OwnsWheel => HotbarOwnsWheel();

			public float Wheel => ZInput.GetMouseScrollWheel();

			public bool ModifierDown => Input.GetKeyDown(Plugin.Modifier);

			public bool ModifierHeld => Input.GetKey(Plugin.Modifier);

			public bool ModifierUp => Input.GetKeyUp(Plugin.Modifier);

			public bool OtherKeyDown => Input.anyKeyDown;

			public bool Focused => Application.isFocused;

			public ItemData Right => ((Humanoid)Player).RightItem;

			public ItemData Left => ((Humanoid)Player).LeftItem;

			public ItemData StowedRight => Stow.Right(Player);

			public ItemData StowedLeft => Stow.Left(Player);

			public int Width => Width(Player);

			public ItemData ItemAt(int slot)
			{
				return Picker.ItemAt(Player, slot);
			}

			public bool IsStop(ItemData item)
			{
				return Picker.IsStop(item);
			}

			public bool Equipped(ItemData item)
			{
				return item.m_equipped;
			}

			public bool Queued(ItemData item)
			{
				return Player.IsEquipActionQueued(item);
			}

			public bool IsStowed(ItemData item)
			{
				return Stow.IsStowed(Player, item);
			}

			public string Busy(ItemData item)
			{
				return BusyReason(Player, item);
			}

			public void Equip(ItemData item)
			{
				ToggleEquipped(Player, item);
			}

			public void Unstow()
			{
				Stow.Unstow(Player);
			}

			public void Withdraw(ItemData item)
			{
				((Humanoid)Player).RemoveEquipAction(item);
			}

			public void Tick()
			{
				Sound.Play(Sound.Cue.Tick);
			}

			public void Lost()
			{
				Sound.Play(Sound.Cue.Lost);
			}

			public void Watch(ItemData item, float now)
			{
				BuildToolHint.Watch(item, now);
			}
		}

		public const int Slots = 8;

		private static readonly Func<Player, ItemData, bool> ToggleEquipped = ResolveToggleEquipped();

		private static readonly ItemNameList Skipped = new ItemNameList(() => Plugin.SkipItems);

		private static readonly PlayerWorld World = new PlayerWorld();

		private static readonly List<ItemData> Bound = new List<ItemData>();

		internal static readonly PickFlow<ItemData> Flow = new PickFlow<ItemData>(World);

		private static bool _warnedNotPatched;

		internal static bool EquipFound => ToggleEquipped != null;

		public static bool Choosing => Flow.Choosing;

		public static int Cursor => Flow.Cursor;

		public static ItemData Pending => Flow.Pending;

		public static int PendingSlot => Flow.PendingSlot;

		public static bool Waiting => Flow.Waiting;

		public static float WaitingSince => Flow.WaitingSince;

		public static int LostSlot => Flow.LostSlot;

		public static float LostAt => Flow.LostAt;

		private static Func<Player, ItemData, bool> ResolveToggleEquipped()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(Player), "ToggleEquipped", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					return AccessTools.MethodDelegate<Func<Player, ItemData, bool>>(methodInfo, (object)null, true);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("ScrollToArms: Player.ToggleEquipped could not be resolved (" + ex.Message + ")."));
				}
				return null;
			}
			ManualLogSource log2 = Plugin.Log;
			if (log2 != null)
			{
				log2.LogWarning((object)"ScrollToArms: Player.ToggleEquipped was not found.");
			}
			return null;
		}

		public static bool HotbarOwnsWheel()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Enabled || ToggleEquipped == null || !WheelReads.CameraReady)
			{
				return false;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || !CanPick(localPlayer))
			{
				return false;
			}
			if (StepAside.Holding(localPlayer))
			{
				return false;
			}
			return PickRules.OwnsWheel(Input.GetKey(Plugin.Modifier), ((Character)localPlayer).InPlaceMode(), WheelReads.PlacementReady, Plugin.PlainScroll);
		}

		public static void Update(float dt)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || !Plugin.Enabled || ToggleEquipped == null)
			{
				Flow.EndPick();
				return;
			}
			if (!WheelReads.CameraRan && !_warnedNotPatched)
			{
				_warnedNotPatched = true;
				Plugin.Log.LogWarning((object)"ScrollToArms: the camera patch has not been applied yet, so hotbar scrolling waits for it.");
			}
			float time = Time.time;
			BuildToolHint.Update(localPlayer, time);
			World.Player = localPlayer;
			Flow.Update(time);
		}

		public static bool Usable(Player player)
		{
			return CanPick(player);
		}

		private static bool CanPick(Player player)
		{
			if (((Character)player).IsDead() || ((Character)player).InCutscene() || ((Character)player).IsTeleporting())
			{
				return false;
			}
			if (InventoryGui.IsVisible())
			{
				return false;
			}
			if (StoreGui.IsVisible())
			{
				return false;
			}
			if (Menu.IsVisible())
			{
				return false;
			}
			if (Console.IsVisible())
			{
				return false;
			}
			if (TextInput.IsVisible())
			{
				return false;
			}
			if ((Object)(object)Minimap.instance != (Object)null && Minimap.IsOpen())
			{
				return false;
			}
			if (Hud.IsPieceSelectionVisible())
			{
				return false;
			}
			if (Hud.InRadial())
			{
				return false;
			}
			if ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus())
			{
				return false;
			}
			if (PlayerCustomizaton.IsBarberGuiVisible())
			{
				return false;
			}
			if (GameCamera.InFreeFly())
			{
				return false;
			}
			return true;
		}

		private static bool IsStop(ItemData item)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (item != null)
			{
				return PickRules.IsStop(item.IsEquipable(), item.m_shared.m_itemType, (Object)(object)item.m_shared.m_buildPieces != (Object)null, Plugin.SkipBuildTools, Skipped.Contains(item), item.m_shared.m_useDurability, item.m_durability);
			}
			return false;
		}

		private static string BusyReason(Player player, ItemData item)
		{
			return PickRules.Busy(((Character)player).InAttack(), ((Character)player).InDodge(), ((Character)player).IsSwimming(), ((Character)player).IsOnGround(), item.m_shared.m_equipDuration > 0f, ((Character)player).IsRunning(), Stow.IsStowed(player, item));
		}

		private static int Width(Player player)
		{
			return Mathf.Min(8, ((Humanoid)player).GetInventory().GetWidth());
		}

		public static ItemData ItemAt(Player player, int slot)
		{
			if (slot < 0 || slot >= Width(player))
			{
				return null;
			}
			((Humanoid)player).GetInventory().GetBoundItems(Bound);
			foreach (ItemData item in Bound)
			{
				if (item.m_gridPos.x == slot)
				{
					return item;
				}
			}
			return null;
		}

		internal static int NextStop(Player player, int from, int step)
		{
			return HotbarWalk.NextStop(Width(player), from, step, Plugin.Wrap, (int slot) => IsStop(ItemAt(player, slot)));
		}
	}
	internal interface IPickWorld<TItem> where TItem : class
	{
		PlainScroll PlainScroll { get; }

		Commit Commit { get; }

		float PauseTime { get; }

		bool Wrap { get; }

		bool Invert { get; }

		bool FlipBack { get; }

		float WaitWhileBusy { get; }

		bool CanPick { get; }

		bool OwnsWheel { get; }

		float Wheel { get; }

		bool ModifierDown { get; }

		bool ModifierHeld { get; }

		bool ModifierUp { get; }

		bool OtherKeyDown { get; }

		bool Focused { get; }

		TItem Right { get; }

		TItem Left { get; }

		TItem StowedRight { get; }

		TItem StowedLeft { get; }

		int Width { get; }

		TItem ItemAt(int slot);

		bool IsStop(TItem item);

		bool Equipped(TItem item);

		bool Queued(TItem item);

		bool IsStowed(TItem item);

		string Busy(TItem item);

		void Equip(TItem item);

		void Unstow();

		void Withdraw(TItem item);

		void Tick();

		void Lost();

		void Watch(TItem item, float now);
	}
	internal sealed class PickFlow<TItem> where TItem : class
	{
		private const float TapTime = 0.3f;

		private readonly IPickWorld<TItem> _world;

		private readonly Notches _wheel = new Notches();

		private float _pendingUntil;

		private bool _unequip;

		private bool _asked;

		private bool _queueSeen;

		private string _lastBusy;

		private TItem _heldRight;

		private TItem _heldLeft;

		private TItem _current;

		private TItem _previous;

		private float _tapStart;

		private bool _tapSpoiled = true;

		public bool Choosing { get; private set; }

		public int Cursor { get; private set; } = -1;

		public TItem Pending { get; private set; }

		public int PendingSlot { get; private set; } = -1;

		public bool Waiting
		{
			get
			{
				if (Pending != null)
				{
					return _lastBusy != null;
				}
				return false;
			}
		}

		public float WaitingSince { get; private set; }

		public int LostSlot { get; private set; } = -1;

		public float LostAt { get; private set; }

		public PickFlow(IPickWorld<TItem> world)
		{
			_world = world;
		}

		public void Update(float now)
		{
			TrackHands();
			bool flag = ReadTap(now);
			if (!_world.CanPick)
			{
				_tapSpoiled = true;
				EndPick();
				return;
			}
			if (Pending != null && Done(Pending))
			{
				ClearPending();
				RememberHands();
			}
			if ((Choosing || Pending != null) && HandsChanged())
			{
				EndPick();
				return;
			}
			ReadWheel(now);
			if (Choosing)
			{
				bool num = _world.PlainScroll == PlainScroll.Zoom && !_world.ModifierHeld;
				bool flag2 = _world.Commit == Commit.AfterPause && now - _wheel.LastNotch >= _world.PauseTime;
				if (num || flag2)
				{
					CommitPick(now);
				}
			}
			else if (flag && _world.FlipBack)
			{
				Flip(now);
			}
			if (Pending != null)
			{
				TryEquipPending(now);
			}
		}

		public void EndPick()
		{
			Choosing = false;
			Cursor = -1;
			ClearPending();
			_wheel.Clear();
		}

		private void TrackHands()
		{
			TItem val = _world.Right ?? _world.Left;
			if (val != null && val != _current)
			{
				_previous = _current;
				_current = val;
			}
		}

		private bool ReadTap(float now)
		{
			if (_world.ModifierDown)
			{
				_tapStart = now;
				_tapSpoiled = false;
				return false;
			}
			if (_world.ModifierHeld)
			{
				if (_world.OtherKeyDown || !_world.Focused || _world.Wheel != 0f)
				{
					_tapSpoiled = true;
				}
				return false;
			}
			if (!_world.ModifierUp)
			{
				return false;
			}
			bool result = !_tapSpoiled && now - _tapStart <= 0.3f;
			_tapSpoiled = true;
			return result;
		}

		internal void Flip(float now)
		{
			bool flag = _world.Right == null && _world.Left == null;
			TItem item = ((Pending != null || flag) ? _current : _previous);
			int num = SlotOf(item);
			if (num >= 0)
			{
				PickSlot(num, now, mayUnequip: false);
			}
		}

		private void ReadWheel(float now)
		{
			if (!_world.OwnsWheel)
			{
				_wheel.Clear();
				return;
			}
			int num = _wheel.Read(_world.Wheel, now, _world.Invert);
			if (num != 0)
			{
				Step(num);
			}
		}

		internal void Step(int step)
		{
			if (!Choosing)
			{
				int num = ((Pending != null) ? PendingSlot : SlotOfHeld());
				int num2 = NextStop(num, step);
				if (num2 < 0 || num2 == num)
				{
					return;
				}
				Choosing = true;
				Cursor = num;
				RememberHands();
			}
			_tapSpoiled = true;
			int num3 = NextStop(Cursor, step);
			if (num3 >= 0 && num3 != Cursor)
			{
				Cursor = num3;
				_world.Tick();
			}
		}

		private void CommitPick(float now)
		{
			Choosing = false;
			int cursor = Cursor;
			Cursor = -1;
			if (cursor >= 0)
			{
				PickSlot(cursor, now, mayUnequip: true);
			}
		}

		private void PickSlot(int slot, float now, bool mayUnequip)
		{
			TItem val = _world.ItemAt(slot);
			if (val == null || (val == Pending && (mayUnequip || !_unequip)))
			{
				return;
			}
			TItem pending = Pending;
			if (pending != null)
			{
				if (_world.Queued(pending))
				{
					_world.Withdraw(pending);
				}
				ClearPending();
			}
			if (!_world.Queued(val))
			{
				bool flag = _world.Equipped(val);
				if (!flag || (mayUnequip && pending == null))
				{
					Pending = val;
					PendingSlot = slot;
					_unequip = flag;
					_pendingUntil = now + _world.WaitWhileBusy;
					_asked = false;
					_queueSeen = false;
					_lastBusy = null;
					RememberHands();
				}
			}
		}

		private void TryEquipPending(float now)
		{
			TItem pending = Pending;
			if (_world.ItemAt(PendingSlot) != pending)
			{
				ClearPending();
				return;
			}
			if (_world.Queued(pending))
			{
				_queueSeen = true;
				_pendingUntil = now + _world.WaitWhileBusy;
				return;
			}
			string text = _world.Busy(pending);
			if (text != null)
			{
				if (now >= _pendingUntil)
				{
					Lose(now);
					ClearPending();
					return;
				}
				if (_lastBusy == null)
				{
					WaitingSince = now;
				}
				_lastBusy = text;
				return;
			}
			_lastBusy = null;
			if (_asked && !_queueSeen)
			{
				Lose(now);
				ClearPending();
				return;
			}
			if (!_asked && !_unequip)
			{
				_world.Watch(pending, now);
			}
			_asked = true;
			_queueSeen = false;
			if (_world.IsStowed(pending))
			{
				_world.Unstow();
			}
			else
			{
				_world.Equip(pending);
			}
			if (Done(pending))
			{
				ClearPending();
			}
			else if (_world.Queued(pending))
			{
				_queueSeen = true;
			}
		}

		private int NextStop(int from, int step)
		{
			return HotbarWalk.NextStop(_world.Width, from, step, _world.Wrap, (int slot) => _world.IsStop(_world.ItemAt(slot)));
		}

		private int SlotOf(TItem item)
		{
			if (item == null)
			{
				return -1;
			}
			int width = _world.Width;
			for (int i = 0; i < width; i++)
			{
				if (_world.ItemAt(i) == item)
				{
					return i;
				}
			}
			return -1;
		}

		private int SlotOfHeld()
		{
			if (_world.Right != null || _world.Left != null)
			{
				int num = SlotOf(_world.Right);
				if (num < 0)
				{
					return SlotOf(_world.Left);
				}
				return num;
			}
			int num2 = SlotOf(_world.StowedRight);
			if (num2 < 0)
			{
				return SlotOf(_world.StowedLeft);
			}
			return num2;
		}

		private void RememberHands()
		{
			_heldRight = _world.Right;
			_heldLeft = _world.Left;
		}

		private bool HandsChanged()
		{
			if (_world.Right == _heldRight)
			{
				return _world.Left != _heldLeft;
			}
			return true;
		}

		private void Lose(float now)
		{
			LostSlot = PendingSlot;
			LostAt = now;
			_world.Lost();
		}

		private bool Done(TItem item)
		{
			return _world.Equipped(item) != _unequip;
		}

		private void ClearPending()
		{
			Pending = null;
			PendingSlot = -1;
			_unequip = false;
			_lastBusy = null;
		}
	}
	internal static class PickLook
	{
		private const float FlashTime = 0.5f;

		private const float PulseLow = 0.15f;

		private const float PulseRate = (float)Math.PI * 4f;

		private const float NameFaintness = 0.55f;

		public static int Frame(bool choosing, int cursor, int pendingSlot)
		{
			if (!choosing)
			{
				return pendingSlot;
			}
			return cursor;
		}

		public static int Flash(int lostSlot, float age, int frame)
		{
			if (lostSlot < 0 || !(age < 0.5f) || lostSlot == frame)
			{
				return -1;
			}
			return lostSlot;
		}

		public static float Fade(float age)
		{
			return 1f - Clamp01(age / 0.5f);
		}

		public static bool Pulses(bool choosing, bool waiting)
		{
			return !choosing && waiting;
		}

		public static float PulseAlpha(float sinceWait)
		{
			float value = 0.5f - 0.5f * (float)Math.Cos(sinceWait * ((float)Math.PI * 4f));
			return 0.15f + 0.85f * Clamp01(value);
		}

		public static bool Shows(int frame, int waiting, int flash)
		{
			if (frame < 0 && waiting < 0)
			{
				return flash >= 0;
			}
			return true;
		}

		public static bool Queued(int slot, int waitingSlot, bool itemQueued)
		{
			return slot == waitingSlot || itemQueued;
		}

		public static int NamedSlot(int frame, int flash)
		{
			if (frame < 0)
			{
				return flash;
			}
			return frame;
		}

		public static bool LostName(bool hasItem, int frame)
		{
			if (hasItem)
			{
				return frame < 0;
			}
			return false;
		}

		public static float NameAlpha(bool lostName, float fade)
		{
			return (lostName ? fade : 1f) * 0.55f;
		}

		private static float Clamp01(float value)
		{
			if (!(value < 0f))
			{
				if (!(value > 1f))
				{
					return value;
				}
				return 1f;
			}
			return 0f;
		}
	}
	internal sealed class TickGate
	{
		private const float MinTickGap = 0.04f;

		private float _last = -1f;

		public bool Allow(float now)
		{
			if (now - _last < 0.04f)
			{
				return false;
			}
			_last = now;
			return true;
		}
	}
	internal static class PickRules
	{
		public static bool IsStop(bool equipable, ItemType type, bool buildTool, bool skipBuildTools, bool listed, bool wears, float durability)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_0010: 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_0015: Invalid comparison between Unknown and I4
			if (!equipable)
			{
				return false;
			}
			if ((int)type <= 15)
			{
				if (type - 3 > 2 && type - 14 > 1)
				{
					goto IL_0023;
				}
			}
			else if ((int)type != 19 && (int)type != 22)
			{
				goto IL_0023;
			}
			if (skipBuildTools && buildTool)
			{
				return false;
			}
			if (listed)
			{
				return false;
			}
			if (wears)
			{
				return !(durability <= 0f);
			}
			return true;
			IL_0023:
			return false;
		}

		public static string Busy(bool attacking, bool dodging, bool swimming, bool onGround, bool equipTime, bool running, bool stowed)
		{
			if (attacking)
			{
				return "attacking";
			}
			if (dodging)
			{
				return "dodging";
			}
			if (swimming && !onGround)
			{
				return "swimming";
			}
			if (equipTime && running && !stowed)
			{
				return "running";
			}
			return null;
		}

		public static bool OwnsWheel(bool modifierHeld, bool placing, bool placementReady, PlainScroll plain)
		{
			if (placing)
			{
				return modifierHeld && placementReady;
			}
			if (plain != PlainScroll.Zoom)
			{
				return !modifierHeld;
			}
			return modifierHeld;
		}

		public static Commit EffectiveCommit(PlainScroll plain, Commit setting)
		{
			if (plain != PlainScroll.Hotbar)
			{
				return setting;
			}
			return Commit.AfterPause;
		}
	}
	[BepInPlugin("isimp.ScrollToArms", "ScrollToArms", "0.2.4")]
	[BepInProcess("valheim.exe")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "isimp.ScrollToArms";

		public const string Version = "0.2.4";

		internal static ManualLogSource Log;

		private static bool _broken;

		private static ConfigEntry<bool> _enabled;

		private static ConfigEntry<KeyCode> _modifier;

		private static ConfigEntry<PlainScroll> _plainScroll;

		private static ConfigEntry<Commit> _commit;

		private static ConfigEntry<float> _pauseTime;

		private static ConfigEntry<bool> _wrap;

		private static ConfigEntry<bool> _invert;

		private static ConfigEntry<bool> _skipBuildTools;

		private static ConfigEntry<string> _stepAsideTools;

		private static ConfigEntry<string> _skipItems;

		private static ConfigEntry<bool> _flipBack;

		private static ConfigEntry<bool> _showItemName;

		private static ConfigEntry<bool> _showWheelMode;

		private static ConfigEntry<bool> _showCenterHints;

		private static ConfigEntry<bool> _playSounds;

		private static ConfigEntry<float> _waitWhileBusy;

		private const string DefaultStepAsideTools = "BlueprintRune, PlanHammer";

		private static Harmony _harmony;

		public static bool Enabled
		{
			get
			{
				if (!_broken)
				{
					if (_enabled != null)
					{
						return _enabled.Value;
					}
					return true;
				}
				return false;
			}
		}

		public static KeyCode Modifier => (KeyCode)(((??)_modifier?.Value) ?? 308);

		public static PlainScroll PlainScroll => _plainScroll?.Value ?? PlainScroll.Zoom;

		public static Commit CommitSetting => _commit?.Value ?? Commit.OnRelease;

		public static float PauseTime => _pauseTime?.Value ?? 0.4f;

		public static bool Wrap
		{
			get
			{
				if (_wrap != null)
				{
					return _wrap.Value;
				}
				return true;
			}
		}

		public static bool Invert
		{
			get
			{
				if (_invert != null)
				{
					return _invert.Value;
				}
				return false;
			}
		}

		public static bool SkipBuildTools
		{
			get
			{
				if (_skipBuildTools != null)
				{
					return _skipBuildTools.Value;
				}
				return false;
			}
		}

		public static string StepAsideTools => _stepAsideTools?.Value ?? "BlueprintRune, PlanHammer";

		public static string SkipItems => _skipItems?.Value ?? "";

		public static bool FlipBack
		{
			get
			{
				if (_flipBack != null)
				{
					return _flipBack.Value;
				}
				return true;
			}
		}

		public static bool ShowItemName
		{
			get
			{
				if (_showItemName != null)
				{
					return _showItemName.Value;
				}
				return true;
			}
		}

		public static bool ShowWheelMode
		{
			get
			{
				if (_showWheelMode != null)
				{
					return _showWheelMode.Value;
				}
				return true;
			}
		}

		public static bool ShowCenterHints
		{
			get
			{
				if (_showCenterHints != null)
				{
					return _showCenterHints.Value;
				}
				return true;
			}
		}

		public static bool PlaySounds
		{
			get
			{
				if (_playSounds != null)
				{
					return _playSounds.Value;
				}
				return true;
			}
		}

		public static float WaitWhileBusy => _waitWhileBusy?.Value ?? 2f;

		public static Commit EffectiveCommit
		{
			get
			{
				if (PlainScroll != PlainScroll.Hotbar)
				{
					return CommitSetting;
				}
				return Commit.AfterPause;
			}
		}

		private void Awake()
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Expected O, but got Unknown
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Expected O, but got Unknown
			//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Turn hotbar scrolling off without removing the mod.");
			_modifier = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "Modifier", (KeyCode)308, "Hold this while scrolling to use the other half of the wheel: the hotbar when PlainScroll is Zoom, the camera zoom when PlainScroll is Hotbar. In build mode the plain wheel rotates the piece being placed, so there this always picks from the hotbar.");
			_plainScroll = ((BaseUnityPlugin)this).Config.Bind<PlainScroll>("General", "PlainScroll", PlainScroll.Zoom, "What the mouse wheel does without the modifier. Zoom keeps the game's camera zoom on the wheel and scrolls the hotbar with the modifier held. Hotbar swaps the two. With a build tool out, the plain wheel rotates the piece either way and the modifier with the wheel picks from the hotbar; with Hotbar a message says so when the wheel takes a build tool out.");
			_commit = ((BaseUnityPlugin)this).Config.Bind<Commit>("Selection", "Commit", Commit.OnRelease, "When the picked slot is equipped. OnRelease equips it when you let go of the modifier. AfterPause equips it once the wheel has been still for PauseTime. When PlainScroll is Hotbar there is no modifier to release, so AfterPause is always used.");
			_pauseTime = ((BaseUnityPlugin)this).Config.Bind<float>("Selection", "PauseTime", 0.4f, new ConfigDescription("Seconds the wheel has to be still before the picked slot is equipped, when AfterPause applies.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1.5f), Array.Empty<object>()));
			_wrap = ((BaseUnityPlugin)this).Config.Bind<bool>("Selection", "Wrap", true, "Scrolling past the last slot continues at the first, and the other way round.");
			_invert = ((BaseUnityPlugin)this).Config.Bind<bool>("Selection", "InvertDirection", false, "By default scrolling down moves right along the hotbar and scrolling up moves left. Turn this on to swap them.");
			_skipBuildTools = ((BaseUnityPlugin)this).Config.Bind<bool>("Selection", "SkipBuildTools", false, "Pass over the hammer, hoe, cultivator and other tools that open build mode. With them in hand the plain wheel rotates the piece being placed, and the modifier with the wheel still picks from the hotbar.");
			_skipItems = ((BaseUnityPlugin)this).Config.Bind<string>("Selection", "SkipItems", "", "Items the wheel passes over, separated by commas. Use the name shown in game, such as Bronze Pickaxe, or the item's prefab name.");
			_stepAsideTools = ((BaseUnityPlugin)this).Config.Bind<string>("Selection", "StepAsideTools", "BlueprintRune, PlanHammer", "Tools whose own controls use the modifier with the wheel. While one of them is in hand, the modifier and the wheel are left to the tool, and the Hide key, a number key or a tap on the modifier switches away. Names shown in game or prefab names, separated by commas. The defaults are the Blueprint Rune and Plan Hammer from PlanBuild.");
			_flipBack = ((BaseUnityPlugin)this).Config.Bind<bool>("Selection", "FlipBack", true, "Tap the modifier without scrolling to go back to the weapon or tool held before. A tap is a short press with no other key, mouse button or wheel in between. While a pick is still on its way, a tap cancels it and keeps what is in hand.");
			_showItemName = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowItemName", true, "Show the name of the item under the frame above the hotbar while picking.");
			_showWheelMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowWheelMode", true, "Show what the wheel does in the same spot above the hotbar when it is worth knowing: while the modifier is held, while a build tool takes the plain wheel for rotating the piece with PlainScroll on Hotbar, and while a tool on the StepAsideTools list keeps the wheel. Nothing is shown in ordinary play.");
			_showCenterHints = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowCenterHints", true, "Show a message in the middle of the screen when the wheel takes out a tool that changes what the wheel does.");
			_playSounds = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "PlaySounds", true, "Play a soft tick as the frame moves and a short sound when a pick is lost. Only you hear them, at the game's own sound effects volume.");
			_waitWhileBusy = ((BaseUnityPlugin)this).Config.Bind<float>("Rules", "WaitWhileBusy", 2f, new ConfigDescription("The game refuses to change what you hold while you attack, dodge or swim, and cancels an item's equip time while you run, jump or attack. A pick refused or cancelled that way is kept for this many seconds, with its slot pulsing on the hotbar, and equipped as soon as the game allows it. If the time runs out first, the slot flashes red and the pick is dropped. The game's own equip bar does not count against this time. 0 drops the pick at once, the way the number keys do.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), Array.Empty<object>()));
			_harmony = new Harmony("isimp.ScrollToArms");
			_broken = !WheelReads.Apply(_harmony);
			if (_broken)
			{
				Log.LogError((object)"ScrollToArms: hotbar scrolling is off for this session. The camera zoom is untouched.");
			}
			else
			{
				Log.LogInfo((object)string.Format("ScrollToArms {0}: plain scroll {1}, modifier {2}.", "0.2.4", PlainScroll, Modifier));
			}
		}

		private void OnDestroy()
		{
			Sound.Mute();
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void Update()
		{
			Sound.Prepare();
			Picker.Update(Time.deltaTime);
		}

		private void LateUpdate()
		{
			HotbarView.Draw();
		}
	}
	internal static class Sound
	{
		public enum Cue
		{
			Tick,
			Lost
		}

		private static readonly Dictionary<Cue, string> CueNames = new Dictionary<Cue, string>
		{
			{
				Cue.Tick,
				"sfx_gui_inventory_open"
			},
			{
				Cue.Lost,
				"sfx_gui_inventory_close"
			}
		};

		private const float Lifetime = 5f;

		private static readonly TickGate Ticks = new TickGate();

		private static readonly Dictionary<Cue, GameObject> Cues = new Dictionary<Cue, GameObject>();

		private static bool _prepared;

		private static bool _muted;

		private static GameObject _holder;

		private static Dictionary<string, GameObject> _effects;

		private static readonly Dictionary<Type, FieldInfo[]> EffectFieldCache = new Dictionary<Type, FieldInfo[]>();

		public static void Prepare()
		{
			if (_prepared || !Plugin.PlaySounds || (Object)(object)ZNetScene.instance == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			_prepared = true;
			foreach (KeyValuePair<Cue, string> cueName in CueNames)
			{
				GameObject val = Find(cueName.Value);
				Cues[cueName.Key] = val;
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Log.LogInfo((object)("ScrollToArms could not find \"" + cueName.Value + "\"; that cue stays silent."));
				}
			}
		}

		public static void Play(Cue cue)
		{
			if (!_muted && _prepared && Plugin.PlaySounds && (cue != Cue.Tick || Ticks.Allow(Time.unscaledTime)) && Cues.TryGetValue(cue, out var value) && (Object)(object)value != (Object)null)
			{
				Play(value);
			}
		}

		internal static bool Found(Cue cue)
		{
			if (Cues.TryGetValue(cue, out var value))
			{
				return (Object)(object)value != (Object)null;
			}
			return false;
		}

		public static void Mute()
		{
			_muted = true;
		}

		private static void Play(GameObject prefab)
		{
			//IL_00a8: 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)
			bool forceDisableInit = ZNetView.m_forceDisableInit;
			ZNetView.m_forceDisableInit = true;
			try
			{
				GameObject val = Object.Instantiate<GameObject>(prefab, Holder().transform, false);
				AudioMixerGroup val2 = (((Object)(object)AudioMan.instance != (Object)null) ? AudioMan.instance.m_guiMixer : null);
				AudioSource[] componentsInChildren = val.GetComponentsInChildren<AudioSource>(true);
				foreach (AudioSource val3 in componentsInChildren)
				{
					if ((Object)(object)val2 != (Object)null)
					{
						val3.outputAudioMixerGroup = val2;
					}
					val3.spatialBlend = 0f;
				}
				Camera mainCamera = Utils.GetMainCamera();
				val.transform.SetParent((Transform)null, false);
				val.transform.position = (((Object)(object)mainCamera != (Object)null) ? ((Component)mainCamera).transform.position : Vector3.zero);
				Object.Destroy((Object)(object)val, 5f);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogDebug((object)("ScrollToArms could not play a sound: " + ex.Message));
			}
			finally
			{
				ZNetView.m_forceDisableInit = forceDisableInit;
			}
		}

		private static GameObject Holder()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			if ((Object)(object)_holder != (Object)null)
			{
				return _holder;
			}
			_holder = new GameObject("ScrollToArmsSounds");
			_holder.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)_holder);
			return _holder;
		}

		private static GameObject Find(string name)
		{
			ZNetScene instance = ZNetScene.instance;
			if ((Object)(object)instance == (Object)null || string.IsNullOrEmpty(name))
			{
				return null;
			}
			GameObject prefab = instance.GetPrefab(name);
			if ((Object)(object)prefab != (Object)null)
			{
				return prefab;
			}
			Dictionary<string, GameObject> dictionary = Effects();
			if (dictionary == null || !dictionary.TryGetValue(name, out var value))
			{
				return null;
			}
			return value;
		}

		private static Dictionary<string, GameObject> Effects()
		{
			if (_effects != null)
			{
				return _effects;
			}
			ZNetScene instance = ZNetScene.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return null;
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			Dictionary<string, GameObject> dictionary = new Dictionary<string, GameObject>(StringComparer.OrdinalIgnoreCase);
			try
			{
				foreach (string prefabName in instance.GetPrefabNames())
				{
					GameObject prefab = instance.GetPrefab(prefabName);
					if ((Object)(object)prefab == (Object)null)
					{
						continue;
					}
					Component[] componentsInChildren = prefab.GetComponentsInChildren<Component>(true);
					foreach (Component val in componentsInChildren)
					{
						if ((Object)(object)val == (Object)null)
						{
							continue;
						}
						Gather(val, dictionary);
						SharedData val2 = ((ItemDrop)(object)((val is ItemDrop) ? val : null)).OrNull<ItemDrop>()?.m_itemData?.m_shared;
						if (val2 != null)
						{
							Gather(val2, dictionary);
							if (val2.m_attack != null)
							{
								Gather(val2.m_attack, dictionary);
							}
							if (val2.m_secondaryAttack != null)
							{
								Gather(val2.m_secondaryAttack, dictionary);
							}
						}
					}
				}
				ObjectDB instance2 = ObjectDB.instance;
				if ((Object)(object)instance2 != (Object)null)
				{
					foreach (StatusEffect statusEffect in instance2.m_StatusEffects)
					{
						if ((Object)(object)statusEffect != (Object)null)
						{
							Gather(statusEffect, dictionary);
						}
					}
				}
				HashSet<Transform> hashSet = new HashSet<Transform>();
				AddRoot((Component)(object)InventoryGui.instance, hashSet);
				AddRoot((Component)(object)Hud.instance, hashSet);
				AddRoot((Component)(object)StoreGui.instance, hashSet);
				AddRoot((Component)(object)Minimap.instance, hashSet);
				AddRoot((Component)(object)MessageHud.instance, hashSet);
				AddRoot((Component)(object)Menu.instance, hashSet);
				AddRoot((Component)(object)Chat.instance, hashSet);
				foreach (Transform item in hashSet)
				{
					Component[] componentsInChildren = ((Component)item).GetComponentsInChildren<Component>(true);
					foreach (Component val3 in componentsInChildren)
					{
						if ((Object)(object)val3 != (Object)null)
						{
							Gather(val3, dictionary);
						}
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("ScrollToArms could not finish indexing the game's effects: " + ex.Message));
			}
			_effects = dictionary;
			Plugin.Log.LogInfo((object)$"ScrollToArms indexed {dictionary.Count} effect prefabs in {stopwatch.ElapsedMilliseconds} ms.");
			return _effects;
		}

		private static void AddRoot(Component part, HashSet<Transform> roots)
		{
			if ((Object)(object)part != (Object)null)
			{
				roots.Add(part.transform.root);
			}
		}

		private static void Gather(object owner, Dictionary<string, GameObject> index)
		{
			FieldInfo[] array = EffectFields(owner.GetType());
			for (int i = 0; i < array.Length; i++)
			{
				object? value = array[i].GetValue(owner);
				EffectList val = (EffectList)((value is EffectList) ? value : null);
				if (val == null || val.m_effectPrefabs == null)
				{
					continue;
				}
				EffectData[] effectPrefabs = val.m_effectPrefabs;
				for (int j = 0; j < effectPrefabs.Length; j++)
				{
					GameObject val2 = effectPrefabs[j]?.m_prefab;
					if ((Object)(object)val2 != (Object)null && !index.ContainsKey(((Object)val2).name))
					{
						index[((Object)val2).name] = val2;
					}
				}
			}
		}

		private static FieldInfo[] EffectFields(Type type)
		{
			if (EffectFieldCache.TryGetValue(type, out var value))
			{
				return value;
			}
			List<FieldInfo> list = new List<FieldInfo>();
			Type type2 = type;
			while (type2 != null && type2 != typeof(object))
			{
				FieldInfo[] fields = type2.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (FieldInfo fieldInfo in fields)
				{
					if (fieldInfo.FieldType == typeof(EffectList))
					{
						list.Add(fieldInfo);
					}
				}
				type2 = type2.BaseType;
			}
			value = list.ToArray();
			EffectFieldCache[type] = value;
			return value;
		}
	}
	internal static class StepAside
	{
		private static readonly ItemNameList Tools = new ItemNameList(() => Plugin.StepAsideTools);

		public static bool Holding(Player player)
		{
			if (!Listed(((Humanoid)player).RightItem))
			{
				return Listed(((Humanoid)player).LeftItem);
			}
			return true;
		}

		public static bool Listed(ItemData item)
		{
			return Tools.Contains(item);
		}
	}
	internal static class Stow
	{
		private static readonly FieldRef<Humanoid, ItemData> HiddenRight = Field("m_hiddenRightItem");

		private static readonly FieldRef<Humanoid, ItemData> HiddenLeft = Field("m_hiddenLeftItem");

		private static readonly Action<Humanoid, bool, bool> ShowHandItems = ResolveShow();

		public static bool Available
		{
			get
			{
				if (HiddenRight != null && HiddenLeft != null)
				{
					return ShowHandItems != null;
				}
				return false;
			}
		}

		private static FieldRef<Humanoid, ItemData> Field(string name)
		{
			try
			{
				return AccessTools.FieldRefAccess<Humanoid, ItemData>(name);
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("ScrollToArms: Humanoid." + name + " could not be read (" + ex.Message + "). Stowed items are treated as empty hands."));
				}
				return null;
			}
		}

		private static Action<Humanoid, bool, bool> ResolveShow()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(Humanoid), "ShowHandItems", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					return AccessTools.MethodDelegate<Action<Humanoid, bool, bool>>(methodInfo, (object)null, true);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("ScrollToArms: Humanoid.ShowHandItems could not be resolved (" + ex.Message + "). Stowed items are treated as empty hands."));
				}
				return null;
			}
			ManualLogSource log2 = Plugin.Log;
			if (log2 != null)
			{
				log2.LogWarning((object)"ScrollToArms: Humanoid.ShowHandItems was not found. Stowed items are treated as empty hands.");
			}
			return null;
		}

		public static ItemData Right(Player player)
		{
			if (!Available)
			{
				return null;
			}
			return HiddenRight.Invoke((Humanoid)(object)player);
		}

		public static ItemData Left(Player player)
		{
			if (!Available)
			{
				return null;
			}
			return HiddenLeft.Invoke((Humanoid)(object)player);
		}

		public static bool IsStowed(Player player, ItemData item)
		{
			if (!Available || item == null)
			{
				return false;
			}
			if (((Humanoid)player).RightItem != null || ((Humanoid)player).LeftItem != null)
			{
				return false;
			}
			if (item != HiddenRight.Invoke((Humanoid)(object)player))
			{
				return item == HiddenLeft.Invoke((Humanoid)(object)player);
			}
			return true;
		}

		public static void Unstow(Player player)
		{
			ShowHandItems((Humanoid)(object)player, arg2: false, arg3: true);
		}
	}
	internal static class UnityNull
	{
		public static T OrNull<T>(this T thing) where T : Object
		{
			if (!((Object)(object)thing != (Object)null))
			{
				return default(T);
			}
			return thing;
		}
	}
	internal static class WheelMode
	{
		private static WheelState _state;

		private static ItemData _tool;

		private static KeyCode _modifier;

		private static bool _flipBack;

		private static string _text;

		public static string Text(Player player)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.ShowWheelMode || !Plugin.Enabled || !WheelReads.CameraReady || !Picker.Usable(player))
			{
				return null;
			}
			ItemData val = (StepAside.Listed(((Humanoid)player).RightItem) ? ((Humanoid)player).RightItem : (StepAside.Listed(((Humanoid)player).LeftItem) ? ((Humanoid)player).LeftItem : null));
			WheelState wheelState = WheelWords.State(val != null, Input.GetKey(Plugin.Modifier), ((Character)player).InPlaceMode(), WheelReads.PlacementReady, Plugin.PlainScroll);
			if (wheelState == WheelState.None)
			{
				return null;
			}
			if (wheelState != _state || val != _tool || Plugin.Modifier != _modifier || Plugin.FlipBack != _flipBack || _text == null)
			{
				_state = wheelState;
				_tool = val;
				_modifier = Plugin.Modifier;
				_flipBack = Plugin.FlipBack;
				_text = WheelWords.Line(wheelState, KeyText.Modifier, KeyText.Hide, Plugin.FlipBack, (val != null) ? ItemNameList.ShownName(val.m_shared.m_name) : null);
			}
			return _text;
		}
	}
	internal static class WheelReads
	{
		private static readonly MethodInfo Original = AccessTools.Method(typeof(ZInput), "GetMouseScrollWheel", (Type[])null, (Type[])null);

		private static readonly MethodInfo Replacement = AccessTools.Method(typeof(WheelReads), "Read", (Type[])null, (Type[])null);

		private static readonly MethodInfo Camera = AccessTools.Method(typeof(GameCamera), "UpdateCamera", (Type[])null, (Type[])null);

		private static readonly MethodInfo Placement = AccessTools.Method(typeof(Player), "UpdatePlacement", (Type[])null, (Type[])null);

		private static readonly Dictionary<MethodBase, int> Found = new Dictionary<MethodBase, int>();

		private static readonly PatchReports<MethodBase> Reported = new PatchReports<MethodBase>();

		public static bool CameraReady => ReadyFor(Camera);

		public static bool PlacementReady => ReadyFor(Placement);

		public static bool CameraRan
		{
			get
			{
				if (Camera != null)
				{
					return Found.ContainsKey(Camera);
				}
				return false;
			}
		}

		private static bool ReadyFor(MethodBase method)
		{
			if (method != null && Found.TryGetValue(method, out var value))
			{
				return value > 0;
			}
			return false;
		}

		public static bool Apply(Harmony harmony)
		{
			if (Original == null || Camera == null)
			{
				Plugin.Log.LogError((object)"ScrollToArms: GameCamera.UpdateCamera or ZInput.GetMouseScrollWheel was not found.");
				return false;
			}
			if (!Patch(harmony, Camera, "GameCamera.UpdateCamera"))
			{
				return false;
			}
			if (Placement == null)
			{
				Plugin.Log.LogWarning((object)"ScrollToArms: Player.UpdatePlacement was not found. Hotbar scrolling stays off in build mode.");
			}
			else
			{
				Patch(harmony, Placement, "Player.UpdatePlacement");
			}
			return true;
		}

		private static bool Patch(Harmony harmony, MethodBase target, string name)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			try
			{
				harmony.Patch(target, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(WheelReads), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("ScrollToArms: could not patch " + name + " - " + ex.Message));
				return false;
			}
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase original)
		{
			int replaced = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.Calls(instruction, Original))
				{
					instruction.operand = Replacement;
					replaced++;
				}
				yield return instruction;
			}
			Found[original] = replaced;
			Report(original, replaced);
		}

		private static void Report(MethodBase method, int replaced)
		{
			if (Reported.IsNew(method, replaced))
			{
				ReportLevel level;
				string text = WheelWords.PatchReport(method == Camera, replaced, out level);
				switch (level)
				{
				case ReportLevel.Error:
					Plugin.Log.LogError((object)text);
					break;
				case ReportLevel.Warning:
					Plugin.Log.LogWarning((object)text);
					break;
				default:
					Plugin.Log.LogInfo((object)text);
					break;
				}
			}
		}

		public static float Read()
		{
			float mouseScrollWheel = ZInput.GetMouseScrollWheel();
			if (!Picker.HotbarOwnsWheel())
			{
				return mouseScrollWheel;
			}
			return 0f;
		}
	}
	internal enum WheelState
	{
		None,
		ModifierPicks,
		ModifierZooms,
		BuildRotates,
		BuildStuck,
		ToolKeeps
	}
	internal enum HintKind
	{
		None,
		KeepsTheWheel,
		WheelRotates
	}
	internal static class WheelWords
	{
		public static WheelState State(bool toolKeeps, bool modifierHeld, bool placing, bool placementReady, PlainScroll plain)
		{
			if (toolKeeps)
			{
				return WheelState.ToolKeeps;
			}
			if (placing)
			{
				if (!placementReady)
				{
					return WheelState.BuildStuck;
				}
				if (modifierHeld)
				{
					return WheelState.ModifierPicks;
				}
				if (plain != PlainScroll.Hotbar)
				{
					return WheelState.None;
				}
				return WheelState.BuildRotates;
			}
			if (!modifierHeld)
			{
				return WheelState.None;
			}
			if (plain != PlainScroll.Zoom)
			{
				return WheelState.ModifierZooms;
			}
			return WheelState.ModifierPicks;
		}

		public static string Line(WheelState state, string modifier, string hide, bool flipBack, string tool)
		{
			string text = "[" + modifier + "]";
			string text2 = (string.IsNullOrEmpty(hide) ? "" : ("  |  [" + hide + "] put away"));
			string text3 = (flipBack ? ("  |  tap " + text + " back") : "");
			return state switch
			{
				WheelState.ModifierPicks => "Wheel: hotbar", 
				WheelState.ModifierZooms => "Wheel: zoom", 
				WheelState.BuildRotates => "Wheel: rotate  |  " + text + " + wheel: hotbar", 
				WheelState.BuildStuck => "Wheel: rotate" + text2 + text3, 
				WheelState.ToolKeeps => tool + " keeps the wheel" + text2 + text3, 
				_ => null, 
			};
		}

		public static HintKind HintKindOf(bool listed, bool buildTool, bool placementReady, PlainScroll plain)
		{
			if (listed)
			{
				return HintKind.KeepsTheWheel;
			}
			if (!buildTool)
			{
				return HintKind.None;
			}
			if (!placementReady)
			{
				return HintKind.KeepsTheWheel;
			}
			if (plain != PlainScroll.Hotbar)
			{
				return HintKind.None;
			}
			return HintKind.WheelRotates;
		}

		public static string Hint(HintKind kind, string name, string modifier, string hide, bool flipBack)
		{
			string text = Marked(modifier);
			if (kind == HintKind.WheelRotates)
			{
				return name + " is out: the wheel rotates the piece. " + text + " with the wheel switches.";
			}
			string text2 = (string.IsNullOrEmpty(hide) ? (name + " keeps the wheel. Put it away to scroll the hotbar again.") : (name + " keeps the wheel. " + Marked(hide) + " puts it away."));
			if (!flipBack)
			{
				return text2;
			}
			return text2 + " A tap on " + text + " goes back.";
		}

		public static string PatchReport(bool camera, int replaced, out ReportLevel level)
		{
			if (replaced > 0)
			{
				level = ReportLevel.Info;
				string arg = (camera ? "camera zoom" : "piece rotation");
				return string.Format("ScrollToArms: {0} hands over the wheel at {1} {2}.", arg, replaced, (replaced == 1) ? "read" : "reads");
			}
			if (camera)
			{
				level = ReportLevel.Error;
				return "ScrollToArms: GameCamera.UpdateCamera no longer reads the mouse wheel where expected. Hotbar scrolling stays off; the camera zoom is untouched.";
			}
			level = ReportLevel.Warning;
			return "ScrollToArms: Player.UpdatePlacement no longer reads the mouse wheel where expected. Hotbar scrolling stays off in build mode.";
		}

		public static string Spaced(string raw)
		{
			StringBuilder stringBuilder = new StringBuilder(raw.Length + 4);
			for (int i = 0; i < raw.Length; i++)
			{
				if (i > 0 && char.IsUpper(raw[i]) && !char.IsUpper(raw[i - 1]))
				{
					stringBuilder.Append(' ');
				}
				stringBuilder.Append(raw[i]);
			}
			return stringBuilder.ToString();
		}

		public static string Marked(string label)
		{
			return "[<color=yellow><b>" + label + "</b></color>]";
		}
	}
	internal enum ReportLevel
	{
		Info,
		Warning,
		Error
	}
	internal sealed class PatchReports<TKey>
	{
		private readonly Dictionary<TKey, int> _told = new Dictionary<TKey, int>();

		public bool IsNew(TKey method, int replaced)
		{
			if (_told.TryGetValue(method, out var value) && value == replaced)
			{
				return false;
			}
			_told[method] = replaced;
			return true;
		}
	}
	internal sealed class HintWatch<TItem> where TItem : class
	{
		private const float WatchTime = 5f;

		private HintKind _kind;

		private float _until;

		public TItem Watched { get; private set; }

		public void Watch(TItem item, HintKind kind, float now)
		{
			_kind = kind;
			Watched = ((kind == HintKind.None) ? null : item);
			_until = now + 5f;
		}

		public bool Arrived(float now, bool equipped, out TItem item, out HintKind kind)
		{
			item = null;
			kind = HintKind.None;
			if (Watched == null)
			{
				return false;
			}
			if (now > _until)
			{
				Watched = null;
				return false;
			}
			if (!equipped)
			{
				return false;
			}
			item = Watched;
			kind = _kind;
			Watched = null;
			return true;
		}
	}
}