Decompiled source of Too Many Emotes v1.1.0

plugins/TooManyEmotes.dll

Decompiled a month ago
using System;
using System.Collections;
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.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Photon;
using SideLoader;
using SideLoader.Model;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Playables;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
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: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
namespace TooManyEmotes;

public class Emote
{
	public string Name;

	public string DisplayName;

	public string VariantName = "";

	public AnimationClip Clip;

	public AnimationClip LoopClip;

	public bool IsPose;

	public string SyncGroupName = "";

	public int SyncLayer = -1;

	public bool RandomInGroup;

	public List<Emote> SyncGroup;

	public bool Loops
	{
		get
		{
			if (!((Motion)Clip).isLooping)
			{
				return (Object)(object)LoopClip != (Object)null;
			}
			return true;
		}
	}

	public bool ShownInMenu
	{
		get
		{
			if (SyncGroup != null)
			{
				return SyncGroup.IndexOf(this) == 0;
			}
			return true;
		}
	}

	public override string ToString()
	{
		return Name;
	}
}
public static class EmoteCamera
{
	private class State
	{
		public float Target;

		public float Current;

		public bool Applied;

		public Vector3 SavedLocalPosition;
	}

	[HarmonyPatch(typeof(CharacterCamera), "LateUpdate")]
	private static class Apply
	{
		[HarmonyPriority(800)]
		private static void Prefix(CharacterCamera __instance)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			if (states.TryGetValue(__instance, out var value) && value.Applied && (Object)(object)__instance.CameraScript != (Object)null)
			{
				((Component)__instance.CameraScript).transform.localPosition = value.SavedLocalPosition;
				value.Applied = false;
			}
		}

		[HarmonyPriority(0)]
		private static void Postfix(CharacterCamera __instance)
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			if (!states.TryGetValue(__instance, out var value) || (Object)(object)__instance.CameraScript == (Object)null || (Object)(object)__instance.TargetCharacter == (Object)null)
			{
				return;
			}
			value.Current = Mathf.MoveTowards(value.Current, value.Target, 8f * Time.deltaTime * Mathf.Max(1f, Mathf.Abs(value.Target - value.Current)));
			if (Mathf.Abs(value.Current) < 0.001f && value.Target == 0f)
			{
				states.Remove(__instance);
				return;
			}
			Transform transform = ((Component)__instance.CameraScript).transform;
			value.SavedLocalPosition = transform.localPosition;
			value.Applied = true;
			Vector3 val = ((Component)__instance.TargetCharacter).transform.position + Vector3.up * 1.5f;
			float num = Vector3.Distance(transform.position, val);
			float num2 = Mathf.Max(value.Current, 0f - Mathf.Max(0f, num - 0.4f));
			Vector3 val2 = transform.position - transform.forward * num2;
			Vector3 val3 = val2 - val;
			RaycastHit val4 = default(RaycastHit);
			if (((Vector3)(ref val3)).sqrMagnitude > 0.0001f && Physics.SphereCast(new Ray(val, val3), 0.2f, ref val4, ((Vector3)(ref val3)).magnitude, Global.LargeEnvironmentMask))
			{
				val2 = ((RaycastHit)(ref val4)).point + ((RaycastHit)(ref val4)).normal * 0.2f;
			}
			transform.position = val2;
		}
	}

	private const float Step = 0.5f;

	private const float HeldSpeed = 4f;

	private const float MinZoom = -3f;

	private const float MaxZoom = 6f;

	private const float SmoothSpeed = 8f;

	private const float MinPivotDistance = 0.4f;

	private static readonly Dictionary<CharacterCamera, State> states = new Dictionary<CharacterCamera, State>();

	public static float ZoomOf(Character character)
	{
		if (!((Object)(object)character.CharacterCamera != (Object)null) || !states.TryGetValue(character.CharacterCamera, out var value))
		{
			return 0f;
		}
		return value.Target;
	}

	public static void UpdateFor(Character character, bool emoteActive, bool menuOpen, int zoomStep, bool wheelNotch)
	{
		CharacterCamera characterCamera = character.CharacterCamera;
		if ((Object)(object)characterCamera == (Object)null)
		{
			return;
		}
		states.TryGetValue(characterCamera, out var value);
		if (!emoteActive && !menuOpen)
		{
			if (value != null)
			{
				value.Target = 0f;
			}
		}
		else if (!menuOpen && emoteActive && zoomStep != 0)
		{
			if (value == null)
			{
				value = (states[characterCamera] = new State());
			}
			float num = (wheelNotch ? 0.5f : (4f * Time.deltaTime));
			value.Target = Mathf.Clamp(value.Target - (float)zoomStep * num, -3f, 6f);
		}
	}
}
public class EmoteController : MonoBehaviour
{
	private const float FadeInTime = 0.25f;

	private const float FadeOutTime = 0.3f;

	private const float MoveInputThreshold = 0.2f;

	private const float MaxSheatheWait = 2f;

	private Character character;

	private Animator animator;

	private PlayableGraph graph;

	private AnimationPlayableOutput output;

	private AnimationMixerPlayable mixer;

	private AnimationClipPlayable introPlayable;

	private AnimationClipPlayable loopPlayable;

	private bool inLoopPhase;

	private float weight;

	private float targetWeight;

	private bool savedApplyRootMotion;

	private Coroutine pendingStart;

	private Coroutine pendingEntry;

	private bool inSession;

	private bool restoreWeapon;

	private Equipment restoreLeftHand;

	private bool restoreLit;

	private float inactiveSince = -1f;

	private Coroutine restoring;

	private SpellCastType watchedPose = (SpellCastType)(-1);

	private float watchStart;

	private float skillCastStart = -100f;

	public Emote Current { get; private set; }

	public bool IsEmoting
	{
		get
		{
			if (Current != null)
			{
				return targetWeight > 0f;
			}
			return false;
		}
	}

	public float Weight
	{
		get
		{
			if (!((PlayableGraph)(ref graph)).IsValid())
			{
				return 0f;
			}
			return weight;
		}
	}

	private bool WeaponDrawn
	{
		get
		{
			if ((Object)(object)character.CurrentWeapon != (Object)null)
			{
				return !character.Sheathed;
			}
			return false;
		}
	}

	public float CurrentTime
	{
		get
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (((PlayableGraph)(ref graph)).IsValid() && Current != null)
			{
				if (!inLoopPhase)
				{
					return (float)PlayableExtensions.GetTime<AnimationClipPlayable>(introPlayable);
				}
				return Current.Clip.length + (float)PlayableExtensions.GetTime<AnimationClipPlayable>(loopPlayable);
			}
			return 0f;
		}
	}

	private bool SkillEmoteActive
	{
		get
		{
			if (!(Time.time - skillCastStart < 0.5f))
			{
				if (character.IsCasting)
				{
					return Time.time - skillCastStart < 30f;
				}
				return false;
			}
			return true;
		}
	}

	public bool EmoteActive
	{
		get
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Invalid comparison between Unknown and I4
			if (!IsEmoting && (int)watchedPose == -1)
			{
				return SkillEmoteActive;
			}
			return true;
		}
	}

	public static List<EmoteController> PerformersOf(List<Emote> group, Vector3 position, float radius, Character exclude)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		List<EmoteController> list = new List<EmoteController>();
		if (group == null || (Object)(object)CharacterManager.Instance == (Object)null)
		{
			return list;
		}
		foreach (Character value in CharacterManager.Instance.Characters.Values)
		{
			if (!((Object)(object)value == (Object)null) && !((Object)(object)value == (Object)(object)exclude) && !(Vector3.Distance(((Component)value).transform.position, position) > radius))
			{
				EmoteController component = ((Component)value).GetComponent<EmoteController>();
				if ((Object)(object)component != (Object)null && component.IsEmoting && component.Current != null && component.Current.SyncGroup == group)
				{
					list.Add(component);
				}
			}
		}
		list.Sort((EmoteController a, EmoteController b) => Vector3.Distance(((Component)a).transform.position, position).CompareTo(Vector3.Distance(((Component)b).transform.position, position)));
		return list;
	}

	public static EmoteController For(Character character)
	{
		EmoteController emoteController = ((Component)character).GetComponent<EmoteController>();
		if ((Object)(object)emoteController == (Object)null)
		{
			emoteController = ((Component)character).gameObject.AddComponent<EmoteController>();
		}
		return emoteController;
	}

	private void Awake()
	{
		character = ((Component)this).GetComponent<Character>();
		animator = character.Animator;
	}

	public bool CanEmote()
	{
		if ((Object)(object)character != (Object)null && (Object)(object)animator != (Object)null && animator.isHuman && !character.IsDead && character.InLocomotion && !character.IsCasting && !character.Dodging && !character.Blocking)
		{
			return !character.Stunned;
		}
		return false;
	}

	public string DescribeState()
	{
		Animator obj = animator;
		string text = $"human={((obj != null) ? new bool?(obj.isHuman) : ((bool?)null))} dead={character.IsDead} locomotion={character.InLocomotion} ";
		string text2 = $"casting={character.IsCasting} dodging={character.Dodging} blocking={character.Blocking} ";
		object arg = character.Stunned;
		object arg2 = character.Sheathed;
		Weapon currentWeapon = character.CurrentWeapon;
		return text + text2 + string.Format("stunned={0} sheathed={1} weapon={2}", arg, arg2, ((currentWeapon != null) ? ((Item)currentWeapon).Name : null) ?? "none");
	}

	public string DescribeGraph()
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		if (!((PlayableGraph)(ref graph)).IsValid())
		{
			return "graph=none";
		}
		string text = $"graph playing={((PlayableGraph)(ref graph)).IsPlaying()} outputWeight={PlayableOutputExtensions.GetWeight<AnimationPlayableOutput>(output):0.00} weight={weight:0.00} target={targetWeight:0.00} ";
		object[] obj = new object[4]
		{
			PlayableExtensions.GetTime<AnimationClipPlayable>(introPlayable),
			null,
			null,
			null
		};
		Emote current = Current;
		obj[1] = ((current != null) ? new float?(current.Clip.length) : ((float?)null));
		obj[2] = inLoopPhase;
		obj[3] = animator.applyRootMotion;
		return text + string.Format("intro t={0:0.00}/{1:0.00} loopPhase={2} rootMotion={3}", obj);
	}

	private static void Trace(string message)
	{
		if (Plugin.Verbose)
		{
			Plugin.Log.LogMessage((object)("[EmoteController] " + message));
		}
	}

	public void Play(Emote emote, EmoteController syncWith = null)
	{
		if (emote == null)
		{
			return;
		}
		if (!CanEmote())
		{
			Trace("cannot emote: " + DescribeState());
			return;
		}
		if (pendingStart != null)
		{
			((MonoBehaviour)this).StopCoroutine(pendingStart);
		}
		pendingStart = ((MonoBehaviour)this).StartCoroutine(SheatheThenPlay(emote, syncWith));
	}

	private IEnumerator SheatheThenPlay(Emote emote, EmoteController syncWith)
	{
		if (WeaponDrawn)
		{
			Trace("sheathing first: " + DescribeState());
			character.SheatheInput();
			float deadline = Time.time + 2f;
			while (WeaponDrawn || !character.InLocomotion)
			{
				if (Time.time > deadline)
				{
					Trace("gave up waiting for sheathe: " + DescribeState());
					pendingStart = null;
					yield break;
				}
				yield return null;
			}
		}
		pendingStart = null;
		bool flag = (Object)(object)syncWith != (Object)null && syncWith.IsEmoting && syncWith.Current != null && syncWith.Current.SyncGroup == emote.SyncGroup;
		Begin(emote, flag ? syncWith.CurrentTime : 0f);
	}

	public void PlayRemote(Emote emote, float time)
	{
		if (pendingStart != null)
		{
			((MonoBehaviour)this).StopCoroutine(pendingStart);
			pendingStart = null;
		}
		Begin(emote, time);
	}

	private void Begin(Emote emote, float startTime = 0f)
	{
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_010e: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_0211: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: 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)
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
		bool num = ((PlayableGraph)(ref graph)).IsValid();
		if (num)
		{
			((PlayableGraph)(ref graph)).Destroy();
		}
		else
		{
			savedApplyRootMotion = animator.applyRootMotion;
		}
		graph = PlayableGraph.Create("TooManyEmotes_" + UID.op_Implicit(character.UID));
		((PlayableGraph)(ref graph)).SetTimeUpdateMode((DirectorUpdateMode)1);
		output = AnimationPlayableOutput.Create(graph, "Emote", animator);
		mixer = AnimationMixerPlayable.Create(graph, 2, false);
		introPlayable = AnimationClipPlayable.Create(graph, emote.Clip);
		((PlayableGraph)(ref graph)).Connect<AnimationClipPlayable, AnimationMixerPlayable>(introPlayable, 0, mixer, 0);
		PlayableExtensions.SetInputWeight<AnimationMixerPlayable>(mixer, 0, 1f);
		if ((Object)(object)emote.LoopClip != (Object)null)
		{
			loopPlayable = AnimationClipPlayable.Create(graph, emote.LoopClip);
			((PlayableGraph)(ref graph)).Connect<AnimationClipPlayable, AnimationMixerPlayable>(loopPlayable, 0, mixer, 1);
			PlayableExtensions.SetInputWeight<AnimationMixerPlayable>(mixer, 1, 0f);
			PlayableExtensions.Pause<AnimationClipPlayable>(loopPlayable);
		}
		PlayableOutputExtensions.SetSourcePlayable<AnimationPlayableOutput, AnimationMixerPlayable>(output, mixer);
		animator.applyRootMotion = false;
		Current = emote;
		inLoopPhase = false;
		if (startTime > 0f)
		{
			if (PlayableExtensions.IsValid<AnimationClipPlayable>(loopPlayable) && startTime >= emote.Clip.length)
			{
				PlayableExtensions.SetTime<AnimationClipPlayable>(introPlayable, (double)emote.Clip.length);
				PlayableExtensions.Pause<AnimationClipPlayable>(introPlayable);
				PlayableExtensions.SetTime<AnimationClipPlayable>(loopPlayable, (double)(startTime - emote.Clip.length));
				PlayableExtensions.Play<AnimationClipPlayable>(loopPlayable);
				PlayableExtensions.SetInputWeight<AnimationMixerPlayable>(mixer, 0, 0f);
				PlayableExtensions.SetInputWeight<AnimationMixerPlayable>(mixer, 1, 1f);
				inLoopPhase = true;
			}
			else
			{
				PlayableExtensions.SetTime<AnimationClipPlayable>(introPlayable, (double)startTime);
			}
		}
		if (!num)
		{
			weight = 0f;
		}
		targetWeight = 1f;
		PlayableOutputExtensions.SetWeight<AnimationPlayableOutput>(output, weight);
		((PlayableGraph)(ref graph)).Play();
		Trace($"started {emote.Name} at {startTime:0.00} s: {DescribeGraph()}");
		if (character.IsLocalPlayer)
		{
			EmoteNetwork.SendPlay(character, emote, startTime);
		}
	}

	public void Stop()
	{
		if (pendingStart != null)
		{
			((MonoBehaviour)this).StopCoroutine(pendingStart);
			pendingStart = null;
		}
		FadeOut();
	}

	private void FadeOut()
	{
		if (targetWeight > 0f && character.IsLocalPlayer)
		{
			EmoteNetwork.SendStop(character);
		}
		targetWeight = 0f;
	}

	public void StopAll()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Invalid comparison between Unknown and I4
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		Stop();
		if ((int)watchedPose != -1 || (SkillEmoteActive && character.IsCasting))
		{
			Trace("stopping pose/cast: " + DescribeState());
			watchedPose = (SpellCastType)(-1);
			skillCastStart = -100f;
			CancelCast();
		}
	}

	public void PlayEntry(MenuEntry entry)
	{
		if (pendingEntry != null)
		{
			((MonoBehaviour)this).StopCoroutine(pendingEntry);
		}
		pendingEntry = ((MonoBehaviour)this).StartCoroutine(PlayEntryAfterCurrent(entry));
	}

	private IEnumerator PlayEntryAfterCurrent(MenuEntry entry)
	{
		if ((int)watchedPose != -1 || (SkillEmoteActive && character.IsCasting))
		{
			Trace("leaving pose/cast for " + entry.Key + ": " + DescribeState());
			watchedPose = (SpellCastType)(-1);
			skillCastStart = -100f;
			CancelCast();
		}
		BeginSession();
		if (Plugin.UnequipLeftHand.Value)
		{
			UnequipLeftHand();
		}
		float deadline = Time.time + 1.5f;
		while ((!character.InLocomotion || !character.NextIsLocomotion || character.IsCasting) && Time.time < deadline)
		{
			yield return null;
		}
		pendingEntry = null;
		entry.Play(character);
	}

	private void UnequipLeftHand()
	{
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Invalid comparison between Unknown and I4
		Equipment leftHandEquipment = character.LeftHandEquipment;
		if (!((Object)(object)leftHandEquipment == (Object)null) && !((Object)(object)leftHandEquipment == (Object)(object)character.CurrentWeapon) && !leftHandEquipment.TwoHanded)
		{
			Trace("unequipping left hand item " + ((Item)leftHandEquipment).Name);
			if ((Object)(object)restoreLeftHand == (Object)null)
			{
				restoreLeftHand = leftHandEquipment;
				restoreLit = (int)((Item)leftHandEquipment).LitStatus == 1;
			}
			character.Inventory.UnequipItem(leftHandEquipment, false);
		}
	}

	private void BeginSession()
	{
		if (restoring != null)
		{
			((MonoBehaviour)this).StopCoroutine(restoring);
			restoring = null;
		}
		if (!inSession)
		{
			inSession = true;
			restoreWeapon = WeaponDrawn;
			restoreLeftHand = null;
			inactiveSince = -1f;
		}
	}

	private void UpdateSession()
	{
		if (!inSession)
		{
			return;
		}
		if (EmoteActive || pendingEntry != null || pendingStart != null)
		{
			inactiveSince = -1f;
			return;
		}
		if (inactiveSince < 0f)
		{
			inactiveSince = Time.time;
		}
		if (!(Time.time - inactiveSince < 0.3f))
		{
			inSession = false;
			if (!character.IsDead && ((Object)(object)restoreLeftHand != (Object)null || restoreWeapon))
			{
				restoring = ((MonoBehaviour)this).StartCoroutine(RestoreHands(restoreLeftHand, restoreLit, restoreWeapon));
			}
			restoreLeftHand = null;
		}
	}

	private IEnumerator RestoreHands(Equipment leftHand, bool lit, bool drawWeapon)
	{
		if ((Object)(object)leftHand != (Object)null && (Object)(object)character.LeftHandEquipment == (Object)null && character.Inventory.OwnsItem(((Item)leftHand).UID))
		{
			Trace("re-equipping " + ((Item)leftHand).Name);
			character.Inventory.EquipItem(leftHand, false);
			float deadline = Time.time + 2f;
			while ((Object)(object)character.LeftHandEquipment != (Object)(object)leftHand && Time.time < deadline)
			{
				yield return null;
			}
			if (lit && (Object)(object)character.LeftHandEquipment == (Object)(object)leftHand && (int)((Item)leftHand).LitStatus == 2)
			{
				((Item)leftHand).SetLight(true);
			}
		}
		if (drawWeapon && Plugin.DrawWeaponAfterEmote.Value)
		{
			float deadline = Time.time + 2f;
			while ((!character.InLocomotion || !character.NextIsLocomotion) && Time.time < deadline)
			{
				yield return null;
			}
			if ((Object)(object)character.CurrentWeapon != (Object)null && character.Sheathed && !character.IsDead)
			{
				Trace("drawing the weapon again");
				character.SheatheInput();
			}
		}
		restoring = null;
	}

	private void CancelCast()
	{
		character.ForceCancel(true, true);
		EmoteNetwork.SendCancel(character);
	}

	public void WatchPose(SpellCastType pose)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		watchedPose = pose;
		watchStart = Time.time;
	}

	public void NoteSkillCast()
	{
		skillCastStart = Time.time;
	}

	private void UpdatePose()
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Invalid comparison between Unknown and I4
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		if ((int)watchedPose == -1 || Time.time - watchStart < 0.5f)
		{
			return;
		}
		if (!character.IsCasting && character.InLocomotion)
		{
			if (Time.time - watchStart > 1.5f)
			{
				watchedPose = (SpellCastType)(-1);
			}
		}
		else if (character.IsLocalPlayer && PlayerWantsToAct())
		{
			Trace($"leaving pose {watchedPose}: {DescribeState()}");
			watchedPose = (SpellCastType)(-1);
			CancelCast();
		}
	}

	private bool PlayerWantsToAct()
	{
		if ((Object)(object)character.OwnerPlayerSys == (Object)null)
		{
			return false;
		}
		int playerID = character.OwnerPlayerSys.PlayerID;
		float num = ControlsInput.MoveHorizontal(playerID);
		float num2 = ControlsInput.MoveVertical(playerID);
		if (!(num * num + num2 * num2 > 0.040000003f) && !ControlsInput.DodgeButtonDown(playerID))
		{
			return ControlsInput.Attack1Press(playerID);
		}
		return true;
	}

	private void Update()
	{
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		UpdatePose();
		UpdateSession();
		if (((PlayableGraph)(ref graph)).IsValid())
		{
			if (targetWeight > 0f && ShouldInterrupt())
			{
				Trace("interrupted: " + DescribeState());
				FadeOut();
			}
			if (targetWeight > 0f)
			{
				AdvancePhase();
			}
			float num = ((targetWeight > weight) ? 0.25f : 0.3f);
			weight = Mathf.MoveTowards(weight, targetWeight, Time.deltaTime / num);
			PlayableOutputExtensions.SetWeight<AnimationPlayableOutput>(output, weight);
			if (weight <= 0f && targetWeight <= 0f)
			{
				Teardown();
			}
		}
	}

	private void LateUpdate()
	{
		if (((PlayableGraph)(ref graph)).IsValid() && Current != null && weight > 0f)
		{
			FingerCurl.Apply(animator, inLoopPhase ? Current.LoopClip : Current.Clip, weight);
		}
	}

	private void AdvancePhase()
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: 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_0060: 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)
		if (!inLoopPhase && !(PlayableExtensions.GetTime<AnimationClipPlayable>(introPlayable) < (double)Current.Clip.length))
		{
			if (PlayableExtensions.IsValid<AnimationClipPlayable>(loopPlayable))
			{
				PlayableExtensions.SetTime<AnimationClipPlayable>(loopPlayable, 0.0);
				PlayableExtensions.Play<AnimationClipPlayable>(loopPlayable);
				PlayableExtensions.Pause<AnimationClipPlayable>(introPlayable);
				PlayableExtensions.SetInputWeight<AnimationMixerPlayable>(mixer, 0, 0f);
				PlayableExtensions.SetInputWeight<AnimationMixerPlayable>(mixer, 1, 1f);
				inLoopPhase = true;
			}
			else if (!((Motion)Current.Clip).isLooping && !Current.IsPose)
			{
				FadeOut();
			}
		}
	}

	private bool ShouldInterrupt()
	{
		if (!character.IsLocalPlayer)
		{
			return character.IsDead;
		}
		if (character.IsDead || !character.InLocomotion || character.IsCasting || character.Dodging || character.Blocking || character.Stunned || WeaponDrawn)
		{
			return true;
		}
		if (character.IsLocalPlayer && (Object)(object)character.OwnerPlayerSys != (Object)null)
		{
			int playerID = character.OwnerPlayerSys.PlayerID;
			float num = ControlsInput.MoveHorizontal(playerID);
			float num2 = ControlsInput.MoveVertical(playerID);
			if (num * num + num2 * num2 > 0.040000003f)
			{
				return true;
			}
		}
		return false;
	}

	private void Teardown()
	{
		if (((PlayableGraph)(ref graph)).IsValid())
		{
			Trace("teardown " + Current?.Name);
			((PlayableGraph)(ref graph)).Destroy();
			if ((Object)(object)animator != (Object)null)
			{
				animator.applyRootMotion = savedApplyRootMotion;
			}
		}
		Current = null;
		inLoopPhase = false;
	}

	private void OnDisable()
	{
		Teardown();
	}

	private void OnDestroy()
	{
		Teardown();
	}
}
public static class EmoteLibrary
{
	internal static readonly string[] BundleNames = new string[6] { "emotes_complementary", "emotes_0", "emotes_1", "emotes_2", "emotes_3", "emotes_special" };

	public static readonly List<Emote> All = new List<Emote>();

	public static readonly Dictionary<string, Emote> ByName = new Dictionary<string, Emote>();

	public static List<Emote> Menu = new List<Emote>();

	internal static readonly List<AssetBundle> Bundles = new List<AssetBundle>();

	private static readonly Dictionary<string, string> DisplayNameOverrides = new Dictionary<string, string>
	{
		{ "death", "Death Pose" },
		{ "rps", "Rock Paper Scissors" }
	};

	public static bool Ready { get; private set; }

	public static IEnumerator Load(string assetsDir)
	{
		Stopwatch timer = Stopwatch.StartNew();
		Dictionary<string, AnimationClip> clips = new Dictionary<string, AnimationClip>();
		string[] bundleNames = BundleNames;
		foreach (string path in bundleNames)
		{
			string path2 = Path.Combine(assetsDir, path);
			AssetBundleCreateRequest bundleRequest = AssetBundle.LoadFromFileAsync(path2);
			yield return bundleRequest;
			AssetBundle assetBundle = bundleRequest.assetBundle;
			if ((Object)(object)assetBundle == (Object)null)
			{
				Plugin.Log.LogError((object)("Failed to load emote bundle " + path2));
				continue;
			}
			Bundles.Add(assetBundle);
			AssetBundleRequest assetsRequest = assetBundle.LoadAllAssetsAsync<AnimationClip>();
			yield return assetsRequest;
			foreach (AnimationClip item in assetsRequest.allAssets.OfType<AnimationClip>())
			{
				if (!clips.ContainsKey(((Object)item).name))
				{
					clips.Add(((Object)item).name, item);
				}
			}
		}
		Build(clips);
		Ready = true;
		Plugin.Log.LogMessage((object)$"Emote library loaded in {timer.ElapsedMilliseconds} ms (in the background)");
	}

	private static void Build(Dictionary<string, AnimationClip> clips)
	{
		Dictionary<string, List<Emote>> dictionary = new Dictionary<string, List<Emote>>();
		foreach (AnimationClip value2 in clips.Values)
		{
			if (((Object)value2).name.EndsWith("_loop"))
			{
				continue;
			}
			Emote emote = Parse(value2, clips);
			if (emote == null || ByName.ContainsKey(emote.Name))
			{
				continue;
			}
			if (emote.SyncGroupName.Length > 0)
			{
				if (!dictionary.TryGetValue(emote.SyncGroupName, out var value))
				{
					dictionary.Add(emote.SyncGroupName, value = new List<Emote>());
				}
				if (emote.SyncLayer >= 0)
				{
					while (value.Count <= emote.SyncLayer)
					{
						value.Add(null);
					}
					value[emote.SyncLayer] = emote;
				}
				else
				{
					value.Add(emote);
				}
				emote.SyncGroup = value;
			}
			All.Add(emote);
			ByName.Add(emote.Name, emote);
		}
		foreach (List<Emote> value3 in dictionary.Values)
		{
			value3.RemoveAll((Emote e) => e == null);
		}
		Menu = All.Where((Emote e) => e.ShownInMenu).OrderBy<Emote, string>((Emote e) => e.DisplayName, StringComparer.InvariantCultureIgnoreCase).ToList();
		Plugin.Log.LogMessage((object)$"Loaded {clips.Count} clips: {All.Count} emotes, {Menu.Count} in menu, {dictionary.Count} sync groups.");
	}

	private static Emote Parse(AnimationClip clip, Dictionary<string, AnimationClip> clips)
	{
		Emote emote = new Emote
		{
			Clip = clip
		};
		string text = ((Object)clip).name;
		if (text.Contains("_start") && !text.Contains("_start_") && clips.TryGetValue(text.Replace("_start", "_loop"), out var value))
		{
			emote.LoopClip = value;
			text = text.Replace("_start", "");
		}
		else if (text.Contains("_pose"))
		{
			emote.IsPose = true;
			text = text.Replace("_pose", "");
		}
		string text2 = text;
		if (text.Contains("."))
		{
			string[] array = text.Split(new char[1] { '.' });
			if (array.Length > 3 || array[0].Length == 0)
			{
				Plugin.Log.LogWarning((object)("Unexpected emote name format: " + ((Object)clip).name));
				return null;
			}
			emote.SyncGroupName = array[0];
			emote.VariantName = Prettify(array[^1]);
			if (array.Length == 3)
			{
				string text3 = array[1].ToLowerInvariant();
				if (text3.StartsWith("layer_") && int.TryParse(text3.Substring(6), out var result))
				{
					emote.SyncLayer = result;
				}
				else if (text3 == "random")
				{
					emote.RandomInGroup = true;
				}
			}
			text = array[0] + "." + array[^1];
			text2 = array[0];
		}
		emote.Name = text;
		emote.DisplayName = (DisplayNameOverrides.TryGetValue(text2, out var value2) ? value2 : Prettify(text2));
		return emote;
	}

	private static string Prettify(string name)
	{
		string str = name.Replace('_', ' ').Trim();
		return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(str);
	}
}
public static class EmoteNetwork
{
	private const string Magic = "TME1";

	public const string Play = "play";

	public const string Stop = "stop";

	public const string Cancel = "cancel";

	public const string Hello = "hello";

	private static ConfigEntry<int> eventCode;

	internal static Action<object[]> TestSink;

	private static bool Online
	{
		get
		{
			if (PhotonNetwork.inRoom)
			{
				return !PhotonNetwork.offlineMode;
			}
			return false;
		}
	}

	public static void Init(ConfigFile config)
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Expected O, but got Unknown
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Expected O, but got Unknown
		eventCode = config.Bind<int>("Network", "Photon event code", 113, new ConfigDescription("Custom Photon event used to sync emotes in co-op. Change it only if another mod uses the same code (every player must use the same value).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 199), Array.Empty<object>()));
		PhotonNetwork.OnEventCall += new EventCallback(OnEvent);
	}

	public static void SendPlay(Character character, Emote emote, float time)
	{
		Send("play", character, emote.Name, time);
	}

	public static void SendStop(Character character)
	{
		Send("stop", character, "", 0f);
	}

	public static void SendCancel(Character character)
	{
		Send("cancel", character, "", 0f);
	}

	public static void SendHello()
	{
		Send("hello", null, "", 0f);
	}

	private static void Send(string op, Character character, string emote, float time)
	{
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Expected O, but got Unknown
		if (!((Object)(object)character != (Object)null) || character.IsLocalPlayer)
		{
			object[] array = new object[5]
			{
				"TME1",
				op,
				((Object)(object)character != (Object)null) ? ((object)character.UID/*cast due to .constrained prefix*/).ToString() : "",
				emote,
				time
			};
			if (Online)
			{
				PhotonNetwork.RaiseEvent((byte)eventCode.Value, (object)array, true, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)0
				});
				Trace($"sent {op} {array[2]} {emote} {time:0.00}");
			}
			else
			{
				TestSink?.Invoke(array);
			}
		}
	}

	private static void OnEvent(byte code, object content, int senderId)
	{
		if (code != eventCode.Value || !(content is object[] array) || array.Length < 5 || !(array[0] is string text) || text != "TME1")
		{
			return;
		}
		try
		{
			Receive((string)array[1], (string)array[2], (string)array[3], Convert.ToSingle(array[4]), senderId);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Bad emote network message: " + ex.Message));
		}
	}

	internal static void Receive(string op, string characterUID, string emoteName, float time, int senderId)
	{
		Trace($"received {op} {characterUID} {emoteName} {time:0.00} from {senderId}");
		if (op == "hello")
		{
			SendStateOfLocalPlayers();
			return;
		}
		CharacterManager instance = CharacterManager.Instance;
		Character val = ((instance != null) ? instance.GetCharacter(characterUID) : null);
		if ((Object)(object)val == (Object)null || (val.IsLocalPlayer && senderId >= 0))
		{
			return;
		}
		if (senderId >= 0 && (Object)(object)((MonoBehaviour)val).photonView != (Object)null && ((MonoBehaviour)val).photonView.ownerId != senderId)
		{
			Plugin.Log.LogWarning((object)$"Ignored emote message for {val.Name} from player {senderId} (owner {((MonoBehaviour)val).photonView.ownerId})");
			return;
		}
		EmoteController emoteController = EmoteController.For(val);
		switch (op)
		{
		case "play":
		{
			if (EmoteLibrary.ByName.TryGetValue(emoteName, out var value))
			{
				emoteController.PlayRemote(value, time);
				break;
			}
			Plugin.Log.LogWarning((object)("Unknown emote '" + emoteName + "' from " + val.Name + " (different mod version?)"));
			break;
		}
		case "stop":
			emoteController.Stop();
			break;
		case "cancel":
			if (val.IsCasting || !val.InLocomotion)
			{
				val.ForceCancel(true, true);
			}
			break;
		}
	}

	private static void SendStateOfLocalPlayers()
	{
		foreach (Character item in LocalPlayers())
		{
			EmoteController component = ((Component)item).GetComponent<EmoteController>();
			if ((Object)(object)component != (Object)null && component.IsEmoting && component.Current != null)
			{
				SendPlay(item, component.Current, component.CurrentTime);
			}
		}
	}

	private static IEnumerable<Character> LocalPlayers()
	{
		if ((Object)(object)CharacterManager.Instance == (Object)null)
		{
			yield break;
		}
		foreach (Character value in CharacterManager.Instance.Characters.Values)
		{
			if ((Object)(object)value != (Object)null && value.IsLocalPlayer)
			{
				yield return value;
			}
		}
	}

	private static void Trace(string message)
	{
		if (Plugin.Verbose)
		{
			Plugin.Log.LogMessage((object)("[EmoteNetwork] " + message));
		}
	}
}
public class EmotePreview
{
	private const int TextureSize = 512;

	private const float RestartPause = 0.6f;

	private const float PoseHold = 1.5f;

	private static readonly Color Background = new Color(0.075f, 0.065f, 0.055f, 1f);

	private static int layer = -1;

	private static readonly HashSet<Camera> ourCameras = new HashSet<Camera>();

	private static readonly List<Light> ourLights = new List<Light>();

	private readonly int playerID;

	private readonly Vector3 origin;

	private RenderTexture texture;

	private Camera camera;

	private GameObject stage;

	private GameObject holder;

	private Animator animator;

	private PlayableGraph graph;

	private AnimationMixerPlayable mixer;

	private AnimationClipPlayable intro;

	private AnimationClipPlayable loop;

	private MenuEntry shown;

	private Emote emote;

	private int spellType = -1;

	private bool leftIdle;

	private float startedAt;

	private float endedAt = -1f;

	private static AmbientMode savedAmbientMode;

	private static Color savedAmbient;

	private static bool savedFog;

	private static bool overridden;

	public Texture Texture => (Texture)(object)texture;

	public bool Active => (Object)(object)holder != (Object)null;

	internal Animator PreviewAnimator => animator;

	internal Camera PreviewCamera => camera;

	internal MenuEntry Shown => shown;

	private bool InLocomotion
	{
		get
		{
			//IL_0007: 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)
			AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
			if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("Locomotion"))
			{
				return !animator.IsInTransition(0);
			}
			return false;
		}
	}

	public EmotePreview(int playerID)
	{
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		this.playerID = playerID;
		origin = new Vector3((float)playerID * 50f, 6000f, 0f);
	}

	private static void Trace(string message)
	{
		if (Plugin.Verbose)
		{
			Plugin.Log.LogMessage((object)("[EmotePreview] " + message));
		}
	}

	public bool Begin(Character character)
	{
		End();
		Animator val = (((Object)(object)character != (Object)null) ? character.Animator : null);
		if ((Object)(object)val == (Object)null || !val.isHuman || (Object)(object)val.avatar == (Object)null)
		{
			return false;
		}
		if (!EnsureStage(character))
		{
			return false;
		}
		try
		{
			BuildCopy(character, val);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Emote preview unavailable: " + ex));
			End();
			return false;
		}
		((Behaviour)camera).enabled = true;
		Trace($"player {playerID}: model copied, {holder.GetComponentsInChildren<Renderer>().Length} renderers");
		return true;
	}

	public void End()
	{
		StopAll();
		if ((Object)(object)holder != (Object)null)
		{
			Object.Destroy((Object)(object)holder);
		}
		holder = null;
		animator = null;
		shown = null;
		if ((Object)(object)camera != (Object)null)
		{
			((Behaviour)camera).enabled = false;
		}
	}

	public void Destroy()
	{
		End();
		if ((Object)(object)stage != (Object)null)
		{
			ourCameras.Remove(camera);
			Light[] componentsInChildren = stage.GetComponentsInChildren<Light>(true);
			foreach (Light item in componentsInChildren)
			{
				ourLights.Remove(item);
			}
			Object.Destroy((Object)(object)stage);
		}
		if ((Object)(object)texture != (Object)null)
		{
			texture.Release();
			Object.Destroy((Object)(object)texture);
		}
		stage = null;
		camera = null;
		texture = null;
	}

	public void Show(MenuEntry entry, Character character)
	{
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Expected I4, but got Unknown
		if (entry == shown || (Object)(object)animator == (Object)null)
		{
			return;
		}
		Trace("show " + (entry?.Key ?? "nothing"));
		shown = entry;
		StopAll();
		if (!(entry is EmoteEntry emoteEntry))
		{
			if (!(entry is CastEntry castEntry))
			{
				if (entry is SkillEntry skillEntry)
				{
					Skill val = SkillEntry.FindLearned(character, skillEntry.ItemID);
					if ((Object)(object)val != (Object)null)
					{
						PlaySpell(SpellTypeOf(val));
					}
				}
			}
			else
			{
				PlaySpell((int)castEntry.CastType);
			}
		}
		else
		{
			PlayTme(emoteEntry.Emote);
		}
	}

	private static int SpellTypeOf(Skill skill)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Invalid comparison between Unknown and I4
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Expected I4, but got Unknown
		return ((Item)skill).ActivateEffectAnimType + (((int)((Item)skill).CastModifier == 1) ? 1000 : 0);
	}

	public void Update()
	{
		if (!((Object)(object)animator == (Object)null))
		{
			if (emote != null && ((PlayableGraph)(ref graph)).IsValid())
			{
				UpdateTme();
			}
			else if (spellType >= 0)
			{
				UpdateSpell();
			}
		}
	}

	public void LateUpdate()
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)animator == (Object)null) && emote != null && ((PlayableGraph)(ref graph)).IsValid())
		{
			bool flag = PlayableExtensions.IsValid<AnimationClipPlayable>(loop) && PlayableExtensions.GetInputWeight<AnimationMixerPlayable>(mixer, 1) > 0f;
			FingerCurl.Apply(animator, flag ? emote.LoopClip : emote.Clip, 1f);
		}
	}

	private void PlayTme(Emote which)
	{
		//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_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: 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_0061: 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_007d: 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_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		emote = which;
		int num = playerID;
		graph = PlayableGraph.Create("TooManyEmotes_Preview" + num);
		((PlayableGraph)(ref graph)).SetTimeUpdateMode((DirectorUpdateMode)2);
		AnimationPlayableOutput val = AnimationPlayableOutput.Create(graph, "Preview", animator);
		mixer = AnimationMixerPlayable.Create(graph, 2, false);
		intro = AnimationClipPlayable.Create(graph, which.Clip);
		((PlayableGraph)(ref graph)).Connect<AnimationClipPlayable, AnimationMixerPlayable>(intro, 0, mixer, 0);
		PlayableExtensions.SetInputWeight<AnimationMixerPlayable>(mixer, 0, 1f);
		if ((Object)(object)which.LoopClip != (Object)null)
		{
			loop = AnimationClipPlayable.Create(graph, which.LoopClip);
			((PlayableGraph)(ref graph)).Connect<AnimationClipPlayable, AnimationMixerPlayable>(loop, 0, mixer, 1);
			PlayableExtensions.SetInputWeight<AnimationMixerPlayable>(mixer, 1, 0f);
			PlayableExtensions.Pause<AnimationClipPlayable>(loop);
		}
		PlayableOutputExtensions.SetSourcePlayable<AnimationPlayableOutput, AnimationMixerPlayable>(val, mixer);
		PlayableOutputExtensions.SetWeight<AnimationPlayableOutput>(val, 1f);
		((PlayableGraph)(ref graph)).Play();
		endedAt = -1f;
		startedAt = Time.unscaledTime;
	}

	private void UpdateTme()
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: 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_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: 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_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		if (PlayableExtensions.IsValid<AnimationClipPlayable>(loop) && PlayableExtensions.GetInputWeight<AnimationMixerPlayable>(mixer, 1) > 0f)
		{
			return;
		}
		if (endedAt >= 0f)
		{
			if (Time.unscaledTime - endedAt >= (emote.IsPose ? 1.5f : 0.6f))
			{
				PlayableExtensions.SetTime<AnimationClipPlayable>(intro, 0.0);
				PlayableExtensions.Play<AnimationClipPlayable>(intro);
				endedAt = -1f;
			}
		}
		else if (!((Motion)emote.Clip).isLooping && !(PlayableExtensions.GetTime<AnimationClipPlayable>(intro) < (double)emote.Clip.length))
		{
			if (PlayableExtensions.IsValid<AnimationClipPlayable>(loop))
			{
				PlayableExtensions.SetTime<AnimationClipPlayable>(loop, 0.0);
				PlayableExtensions.Play<AnimationClipPlayable>(loop);
				PlayableExtensions.Pause<AnimationClipPlayable>(intro);
				PlayableExtensions.SetInputWeight<AnimationMixerPlayable>(mixer, 0, 0f);
				PlayableExtensions.SetInputWeight<AnimationMixerPlayable>(mixer, 1, 1f);
			}
			else
			{
				PlayableExtensions.SetTime<AnimationClipPlayable>(intro, (double)emote.Clip.length);
				PlayableExtensions.Pause<AnimationClipPlayable>(intro);
				endedAt = Time.unscaledTime;
			}
		}
	}

	private void PlaySpell(int type)
	{
		spellType = type;
		leftIdle = false;
		animator.SetInteger("SpellType", type);
		animator.SetTrigger("Spell");
		startedAt = Time.unscaledTime;
		endedAt = -1f;
	}

	private void UpdateSpell()
	{
		if (Time.unscaledTime - startedAt < 0.3f)
		{
			return;
		}
		if (!InLocomotion)
		{
			leftIdle = true;
			endedAt = -1f;
		}
		else if (leftIdle || !(Time.unscaledTime - startedAt < 2f))
		{
			if (endedAt < 0f)
			{
				endedAt = Time.unscaledTime;
			}
			else if (Time.unscaledTime - endedAt >= 0.6f)
			{
				PlaySpell(spellType);
			}
		}
	}

	private void StopAll()
	{
		if (((PlayableGraph)(ref graph)).IsValid())
		{
			((PlayableGraph)(ref graph)).Destroy();
		}
		emote = null;
		if ((Object)(object)animator != (Object)null && spellType >= 0)
		{
			animator.ResetTrigger("Spell");
			animator.ResetTrigger("ForceLocomotion");
			animator.Play("Locomotion", 0, 0f);
			animator.Update(0f);
		}
		spellType = -1;
		endedAt = -1f;
	}

	private bool EnsureStage(Character character)
	{
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Expected O, but got Unknown
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Expected O, but got Unknown
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Expected O, but got Unknown
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01db: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0206: Unknown result type (might be due to invalid IL or missing references)
		//IL_020b: Unknown result type (might be due to invalid IL or missing references)
		//IL_021b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0236: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_026e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0287: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_0349: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ec: Expected O, but got Unknown
		//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f6: Expected O, but got Unknown
		//IL_0302: Unknown result type (might be due to invalid IL or missing references)
		//IL_030c: Expected O, but got Unknown
		//IL_030c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0316: Expected O, but got Unknown
		if ((Object)(object)camera != (Object)null)
		{
			ExcludeLayerFromGame();
			return true;
		}
		int num = 31;
		while (num >= 3 && layer < 0)
		{
			if (num != 4 && num != 5 && string.IsNullOrEmpty(LayerMask.LayerToName(num)))
			{
				layer = num;
			}
			num--;
		}
		if (layer < 0)
		{
			Plugin.Log.LogWarning((object)"Emote preview unavailable: no free layer");
			return false;
		}
		Camera val = (((Object)(object)character.CharacterCamera != (Object)null) ? character.CharacterCamera.CameraScript : Camera.main);
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		RenderTexture val2 = new RenderTexture(512, 512, 24, (RenderTextureFormat)0);
		int num2 = playerID;
		((Object)val2).name = "TooManyEmotes_Preview" + num2;
		texture = val2;
		num2 = playerID;
		stage = new GameObject("TooManyEmotes_PreviewStage" + num2);
		Object.DontDestroyOnLoad((Object)(object)stage);
		GameObject val3 = new GameObject("Camera");
		val3.transform.SetParent(stage.transform, false);
		camera = val3.AddComponent<Camera>();
		camera.CopyFrom(val);
		((Behaviour)camera).enabled = false;
		camera.clearFlags = (CameraClearFlags)2;
		camera.backgroundColor = Background;
		camera.cullingMask = 1 << layer;
		camera.fieldOfView = 30f;
		camera.nearClipPlane = 0.1f;
		camera.farClipPlane = 30f;
		camera.useOcclusionCulling = false;
		camera.depth = -50f;
		camera.targetTexture = texture;
		ourCameras.Add(camera);
		Vector3 val4 = origin + Vector3.up * 0.88f;
		val3.transform.position = val4 + new Vector3(1.7f, 0.35f, 5.1f);
		val3.transform.LookAt(val4);
		AddLight("Key", new Color(1f, 0.93f, 0.82f), 1.15f, new Vector3(35f, 200f, 0f));
		AddLight("Fill", new Color(0.65f, 0.75f, 1f), 0.45f, new Vector3(10f, 120f, 0f));
		AddLight("Rim", new Color(1f, 0.8f, 0.55f), 0.6f, new Vector3(20f, 20f, 0f));
		if (ourCameras.Count == 1)
		{
			Camera.onPreCull = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(OnPreCull));
			Camera.onPostRender = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPostRender, (Delegate?)new CameraCallback(OnPostRender));
		}
		ExcludeLayerFromGame();
		Trace($"stage {playerID}: layer {layer}, path {camera.actualRenderingPath}, hdr {camera.allowHDR}, copied from {((Object)val).name}");
		return true;
	}

	private void AddLight(string name, Color color, float intensity, Vector3 euler)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: 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_003d: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject(name);
		val.transform.SetParent(stage.transform, false);
		val.transform.rotation = Quaternion.Euler(euler);
		Light val2 = val.AddComponent<Light>();
		val2.type = (LightType)1;
		val2.color = color;
		val2.intensity = intensity;
		val2.shadows = (LightShadows)0;
		val2.cullingMask = 1 << layer;
		ourLights.Add(val2);
	}

	private static void ExcludeLayerFromGame()
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Invalid comparison between Unknown and I4
		int num = ~(1 << layer);
		Camera[] allCameras = Camera.allCameras;
		foreach (Camera val in allCameras)
		{
			if (!ourCameras.Contains(val))
			{
				val.cullingMask &= num;
			}
		}
		Light[] array = Object.FindObjectsOfType<Light>();
		foreach (Light val2 in array)
		{
			if ((int)val2.type == 1 && !ourLights.Contains(val2))
			{
				val2.cullingMask &= num;
			}
		}
	}

	private static void OnPreCull(Camera cam)
	{
		//IL_001b: 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_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		if (ourCameras.Contains(cam) && !overridden)
		{
			overridden = true;
			savedAmbientMode = RenderSettings.ambientMode;
			savedAmbient = RenderSettings.ambientLight;
			savedFog = RenderSettings.fog;
			RenderSettings.ambientMode = (AmbientMode)3;
			RenderSettings.ambientLight = new Color(0.42f, 0.4f, 0.38f);
			RenderSettings.fog = false;
		}
	}

	private static void OnPostRender(Camera cam)
	{
		//IL_001b: 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)
		if (ourCameras.Contains(cam) && overridden)
		{
			overridden = false;
			RenderSettings.ambientMode = savedAmbientMode;
			RenderSettings.ambientLight = savedAmbient;
			RenderSettings.fog = savedFog;
		}
	}

	private void BuildCopy(Character character, Animator source)
	{
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Expected O, but got Unknown
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Expected O, but got Unknown
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Expected O, but got Unknown
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b2: Invalid comparison between Unknown and I4
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0201: Unknown result type (might be due to invalid IL or missing references)
		//IL_0208: Expected O, but got Unknown
		//IL_03d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_03dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_03df: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f8: Expected I4, but got Unknown
		//IL_0510: Unknown result type (might be due to invalid IL or missing references)
		//IL_0515: Unknown result type (might be due to invalid IL or missing references)
		Transform boneTransform = source.GetBoneTransform((HumanBodyBones)0);
		if ((Object)(object)boneTransform == (Object)null || !boneTransform.IsChildOf(((Component)source).transform) || (Object)(object)boneTransform == (Object)(object)((Component)source).transform)
		{
			throw new InvalidOperationException("no hips bone below the animator");
		}
		Transform val = boneTransform;
		while ((Object)(object)val.parent != (Object)(object)((Component)source).transform)
		{
			val = val.parent;
		}
		int num = playerID;
		holder = new GameObject("TooManyEmotes_PreviewModel" + num);
		holder.SetActive(false);
		holder.transform.position = origin;
		GameObject val2 = new GameObject("Character");
		val2.transform.SetParent(holder.transform, false);
		GameObject val3 = Object.Instantiate<GameObject>(((Component)val).gameObject, val2.transform, false);
		((Object)val3).name = ((Object)val).name;
		val3.transform.localPosition = val.localPosition;
		val3.transform.localRotation = val.localRotation;
		val3.transform.localScale = val.localScale;
		val2.transform.localScale = ((Component)source).transform.lossyScale;
		Renderer[] componentsInChildren = ((Component)val).GetComponentsInChildren<Renderer>(true);
		Renderer[] componentsInChildren2 = val3.GetComponentsInChildren<Renderer>(true);
		MaterialPropertyBlock val4 = new MaterialPropertyBlock();
		for (int i = 0; i < componentsInChildren.Length && i < componentsInChildren2.Length; i++)
		{
			if (componentsInChildren[i].HasPropertyBlock())
			{
				componentsInChildren[i].GetPropertyBlock(val4);
				componentsInChildren2[i].SetPropertyBlock(val4);
			}
		}
		HashSet<Transform> hashSet = new HashSet<Transform>();
		for (HumanBodyBones val5 = (HumanBodyBones)0; (int)val5 < 55; val5 = (HumanBodyBones)(val5 + 1))
		{
			Transform boneTransform2 = source.GetBoneTransform(val5);
			if ((Object)(object)boneTransform2 != (Object)null)
			{
				hashSet.Add(boneTransform2);
			}
		}
		int num2 = 0;
		HumanBodyBones[] array = (HumanBodyBones[])(object)new HumanBodyBones[2]
		{
			(HumanBodyBones)17,
			(HumanBodyBones)18
		};
		foreach (HumanBodyBones val6 in array)
		{
			Transform boneTransform3 = source.GetBoneTransform(val6);
			if ((Object)(object)boneTransform3 == (Object)null)
			{
				continue;
			}
			foreach (Transform item in boneTransform3)
			{
				Transform val7 = item;
				if (!hashSet.Contains(val7) && ((Component)val7).GetComponentsInChildren<Renderer>(true).Length != 0)
				{
					Transform val8 = val3.transform.Find(PathFrom(val, val7));
					if ((Object)(object)val8 != (Object)null)
					{
						((Component)val8).gameObject.SetActive(false);
						num2++;
					}
				}
			}
		}
		Strip<MonoBehaviour>(val3);
		Strip<Joint>(val3);
		Strip<Cloth>(val3);
		Strip<ParticleSystem>(val3);
		Strip<Behaviour>(val3);
		Strip<Collider>(val3);
		Strip<Rigidbody>(val3);
		Component[] componentsInChildren3 = val3.GetComponentsInChildren<Component>(true);
		foreach (Component val9 in componentsInChildren3)
		{
			if (!(val9 is Transform) && !(val9 is MeshFilter) && !(val9 is MeshRenderer) && !(val9 is SkinnedMeshRenderer))
			{
				Object.DestroyImmediate((Object)(object)val9);
			}
		}
		SkinnedMeshRenderer[] componentsInChildren4 = val3.GetComponentsInChildren<SkinnedMeshRenderer>(true);
		for (num = 0; num < componentsInChildren4.Length; num++)
		{
			componentsInChildren4[num].updateWhenOffscreen = true;
		}
		Transform[] componentsInChildren5 = holder.GetComponentsInChildren<Transform>(true);
		for (num = 0; num < componentsInChildren5.Length; num++)
		{
			((Component)componentsInChildren5[num]).gameObject.layer = layer;
		}
		animator = val2.AddComponent<Animator>();
		animator.avatar = source.avatar;
		animator.runtimeAnimatorController = source.runtimeAnimatorController;
		animator.cullingMode = (AnimatorCullingMode)0;
		animator.applyRootMotion = false;
		animator.updateMode = (AnimatorUpdateMode)2;
		animator.fireEvents = false;
		holder.SetActive(true);
		AnimatorControllerParameter[] parameters = source.parameters;
		foreach (AnimatorControllerParameter val10 in parameters)
		{
			AnimatorControllerParameterType type = val10.type;
			switch (type - 1)
			{
			case 0:
				animator.SetFloat(val10.nameHash, source.GetFloat(val10.nameHash));
				break;
			case 2:
				animator.SetInteger(val10.nameHash, source.GetInteger(val10.nameHash));
				break;
			case 3:
				animator.SetBool(val10.nameHash, source.GetBool(val10.nameHash));
				break;
			}
		}
		SetIfPresent("moveForward", 0f);
		SetIfPresent("moveSide", 0f);
		SetIfPresent("Turning", 0f);
		SetIfPresent("IdleTypeBlend", 1f);
		if (HasParameter("IsMoving"))
		{
			animator.SetBool("IsMoving", false);
		}
		if (HasParameter("Block"))
		{
			animator.SetBool("Block", false);
		}
		for (int j = 0; j < animator.layerCount && j < source.layerCount; j++)
		{
			animator.SetLayerWeight(j, (j == 0) ? 1f : source.GetLayerWeight(j));
			AnimatorStateInfo currentAnimatorStateInfo = source.GetCurrentAnimatorStateInfo(j);
			animator.Play(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash, j, ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime);
		}
		animator.Update(0f);
		if (!InLocomotion)
		{
			animator.Play("Locomotion", 0, 0f);
		}
		Trace($"copy of '{((Object)val).name}': {num2} hand items hidden, state Locomotion={InLocomotion}");
	}

	private bool HasParameter(string name)
	{
		return animator.parameters.Any((AnimatorControllerParameter p) => p.name == name);
	}

	private void SetIfPresent(string name, float value)
	{
		if (HasParameter(name))
		{
			animator.SetFloat(name, value);
		}
	}

	private static void Strip<T>(GameObject root) where T : Component
	{
		for (int i = 0; i < 3; i++)
		{
			T[] componentsInChildren = root.GetComponentsInChildren<T>(true);
			if (componentsInChildren.Length == 0)
			{
				break;
			}
			T[] array = componentsInChildren;
			for (int j = 0; j < array.Length; j++)
			{
				Object.DestroyImmediate((Object)(object)array[j]);
			}
		}
	}

	private static string PathFrom(Transform root, Transform child)
	{
		List<string> list = new List<string>();
		Transform val = child;
		while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)root)
		{
			list.Add(((Object)val).name);
			val = val.parent;
		}
		list.Reverse();
		return string.Join("/", list);
	}
}
public static class Favorites
{
	private static ConfigEntry<string> entry;

	private static List<string> keys = new List<string>();

	public static IReadOnlyList<string> Keys => keys;

	public static void Bind(ConfigFile config)
	{
		entry = config.Bind<string>("Menu", "Favorites", "", "Favorite emotes, in menu order (managed from the emote menu).");
		keys = entry.Value.Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList();
	}

	public static bool Contains(string key)
	{
		return keys.Contains(key);
	}

	public static void Toggle(string key)
	{
		if (!keys.Remove(key))
		{
			keys.Add(key);
		}
		entry.Value = string.Join("|", keys);
	}
}
public static class FingerCurl
{
	[Flags]
	public enum Hands
	{
		None = 0,
		Left = 1,
		Right = 2
	}

	private enum Shape
	{
		None,
		Fist,
		FoldCurled,
		Flat
	}

	private class Finger
	{
		public Hands Hand;

		public string Name;

		public Transform Base;

		public Transform Middle;

		public Transform Distal;

		public Quaternion BaseRest;

		public Quaternion MiddleRest;

		public Quaternion DistalRest;
	}

	private class Rig
	{
		public Avatar Avatar;

		public List<Finger> Fingers;
	}

	private static readonly Dictionary<string, Shape> Shapes = new Dictionary<string, Shape>
	{
		["rps.random.rock"] = Shape.Fist,
		["rps.random.scissors"] = Shape.FoldCurled,
		["rps.random.paper"] = Shape.Flat
	};

	private static readonly string[] Fingers = new string[4] { "Index", "Middle", "Ring", "Little" };

	private const float DistalRatio = 0.7f;

	private const float FoldBase = 88f;

	private const float FoldMiddle = 105f;

	private const float FoldDistalRatio = 0.8f;

	private const float FoldedFrom = 45f;

	private static readonly Dictionary<string, float> Convergence = new Dictionary<string, float>
	{
		["Index"] = 2.5f,
		["Ring"] = 2.5f,
		["Little"] = 4f
	};

	internal static bool Enabled = true;

	private static readonly Dictionary<Animator, Rig> rigs = new Dictionary<Animator, Rig>();

	private static readonly Dictionary<string, Hands> Static = new Dictionary<string, Hands>
	{
		["a_bar_song_start"] = Hands.Left | Hands.Right,
		["a_tear_in_space_start"] = Hands.Left,
		["afk_loop"] = Hands.Left,
		["attraction_start"] = Hands.Left | Hands.Right,
		["be_seeing_you"] = Hands.Left,
		["best_mates"] = Hands.Left | Hands.Right,
		["bird_is_the_word"] = Hands.Left | Hands.Right,
		["bobbin'"] = Hands.Left,
		["bold_stance"] = Hands.Left | Hands.Right,
		["bratty_start"] = Hands.Left | Hands.Right,
		["bring_it_around"] = Hands.Left | Hands.Right,
		["brite_moves_start"] = Hands.Left | Hands.Right,
		["brokenhearted_start"] = Hands.Left | Hands.Right,
		["bye-bye-bye_loop"] = Hands.Left | Hands.Right,
		["bye-bye-bye_start"] = Hands.Left | Hands.Right,
		["california_gurls"] = Hands.Left | Hands.Right,
		["cheer"] = Hands.Left | Hands.Right,
		["cheer_up"] = Hands.Left | Hands.Right,
		["clix_groove_loop"] = Hands.Left | Hands.Right,
		["controller_crew_loop"] = Hands.Left,
		["death_pose.random.fly_back"] = Hands.Left | Hands.Right,
		["death_pose.random.forward"] = Hands.Left | Hands.Right,
		["deep_explorer_start"] = Hands.Left | Hands.Right,
		["desirable_loop"] = Hands.Left | Hands.Right,
		["desirable_start"] = Hands.Left | Hands.Right,
		["dream_stance_loop"] = Hands.Left,
		["drippin'_flavor"] = Hands.Left | Hands.Right,
		["fancy_feet"] = Hands.Right,
		["fantasy_faceoff_loop"] = Hands.Left | Hands.Right,
		["fantasy_faceoff_start"] = Hands.Left | Hands.Right,
		["fast_slow_disco_start"] = Hands.Left | Hands.Right,
		["feelin'_jaunty"] = Hands.Left | Hands.Right,
		["feelin'_royal_start"] = Hands.Left | Hands.Right,
		["firework_start"] = Hands.Left | Hands.Right,
		["floss"] = Hands.Left | Hands.Right,
		["fly_to_tokyo_start"] = Hands.Left,
		["freedom_wheels"] = Hands.Left | Hands.Right,
		["fresh"] = Hands.Left | Hands.Right,
		["get_HOT_start"] = Hands.Left | Hands.Right,
		["gwen-step_loop"] = Hands.Left | Hands.Right,
		["harmony_loop"] = Hands.Left | Hands.Right,
		["headspin_loop"] = Hands.Left | Hands.Right,
		["hello_friend_loop"] = Hands.Left,
		["hello_friend_start"] = Hands.Left,
		["hip_thrust"] = Hands.Left | Hands.Right,
		["independence_start"] = Hands.Left | Hands.Right,
		["infinite_dab_loop"] = Hands.Left,
		["invisible_stairs_loop"] = Hands.Right,
		["it's_ok_i'm_ok_start"] = Hands.Left | Hands.Right,
		["jubi_slide"] = Hands.Left | Hands.Right,
		["jubilation_loop"] = Hands.Left | Hands.Right,
		["jug_band.layer_1.jug"] = Hands.Right,
		["junk_food_loop"] = Hands.Left,
		["line_dancin'_start"] = Hands.Left | Hands.Right,
		["loser_dance"] = Hands.Left | Hands.Right,
		["miku_live_loop"] = Hands.Left | Hands.Right,
		["miku_live_start"] = Hands.Left | Hands.Right,
		["nana_nana"] = Hands.Left | Hands.Right,
		["no_cure_loop"] = Hands.Right,
		["no_tears_start"] = Hands.Right,
		["no_way"] = Hands.Left | Hands.Right,
		["old_school"] = Hands.Left | Hands.Right,
		["paddle_royale_loop"] = Hands.Left,
		["peace_out_pose"] = Hands.Left,
		["praise_the_sun_pose"] = Hands.Left | Hands.Right,
		["prickly_pose_loop"] = Hands.Right,
		["raise_the_roof"] = Hands.Right,
		["rambunctious"] = Hands.Left | Hands.Right,
		["red_card"] = Hands.Right,
		["ride_the_pony_loop"] = Hands.Left,
		["rocket_rodeo"] = Hands.Left | Hands.Right,
		["rps.random.paper"] = Hands.Left | Hands.Right,
		["rps.random.rock"] = Hands.Left | Hands.Right,
		["rps.random.scissors"] = Hands.Left | Hands.Right,
		["sad_trombone"] = Hands.Left,
		["shimmy_wiggle_loop"] = Hands.Left,
		["showstopper"] = Hands.Left | Hands.Right,
		["skyward_loop"] = Hands.Left,
		["slide_stride"] = Hands.Left | Hands.Right,
		["smitten_loop"] = Hands.Right,
		["smitten_start"] = Hands.Left | Hands.Right,
		["soar_above_loop"] = Hands.Right,
		["soar_above_start"] = Hands.Left | Hands.Right,
		["sprinkler"] = Hands.Right,
		["squeak_step_start"] = Hands.Left | Hands.Right,
		["stand_off_loop"] = Hands.Right,
		["starting_prance_start"] = Hands.Left | Hands.Right,
		["step_it_up_loop"] = Hands.Left | Hands.Right,
		["still_into_you_loop"] = Hands.Left | Hands.Right,
		["still_into_you_start"] = Hands.Left | Hands.Right,
		["the_spark_start"] = Hands.Right,
		["touch_start"] = Hands.Left | Hands.Right,
		["travelers.layer_1.harmonica"] = Hands.Left | Hands.Right,
		["travelers.layer_2.drums"] = Hands.Left | Hands.Right,
		["travelers.layer_4.whistle"] = Hands.Left | Hands.Right,
		["travelers.layer_5.piano"] = Hands.Left | Hands.Right,
		["travelers.layer_6.bow"] = Hands.Left | Hands.Right,
		["twist"] = Hands.Left | Hands.Right,
		["what_you_want_loop"] = Hands.Left,
		["where_is_matt"] = Hands.Left | Hands.Right
	};

	public static Hands For(AnimationClip clip)
	{
		if (!((Object)(object)clip != (Object)null) || !Static.TryGetValue(((Object)clip).name, out var value))
		{
			return Hands.None;
		}
		return value;
	}

	public static void Apply(Animator animator, AnimationClip clip, float weight)
	{
		//IL_0073: 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_008d: 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)
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: 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_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0162: Unknown result type (might be due to invalid IL or missing references)
		//IL_0164: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Unknown result type (might be due to invalid IL or missing references)
		//IL_016e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
		Hands hands = For(clip);
		if (!Enabled || hands == Hands.None || weight <= 0f || (Object)(object)animator == (Object)null || !animator.isHuman)
		{
			return;
		}
		Rig rig = RigOf(animator);
		if (rig == null)
		{
			return;
		}
		Shapes.TryGetValue(((Object)clip).name, out var value);
		foreach (Finger finger in rig.Fingers)
		{
			if ((hands & finger.Hand) == 0)
			{
				continue;
			}
			Vector3 axis;
			float num = CurlOf(finger.MiddleRest, finger.Middle.localRotation, out axis);
			if (float.IsNaN(axis.x) || num < 1f)
			{
				continue;
			}
			bool flag = value switch
			{
				Shape.FoldCurled => num > 45f, 
				Shape.Fist => true, 
				_ => false, 
			};
			if (flag && num < 105f)
			{
				Transform middle = finger.Middle;
				middle.localRotation *= Quaternion.AngleAxis((105f - num) * weight, axis);
				num = Mathf.Lerp(num, 105f, weight);
			}
			float num2 = (flag ? Mathf.Max(num, 88f) : num);
			Vector3 axis2;
			for (int i = 0; i < 2; i++)
			{
				float num3 = num2 - CurlOf(finger.BaseRest, finger.Base.localRotation, out axis2);
				if (num3 <= 0.5f)
				{
					break;
				}
				Transform obj = finger.Base;
				obj.localRotation *= Quaternion.AngleAxis(num3 * weight, finger.MiddleRest * axis);
			}
			if ((Object)(object)finger.Distal != (Object)null)
			{
				float num4 = num * (flag ? 0.8f : 0.7f) - CurlOf(finger.DistalRest, finger.Distal.localRotation, out axis2);
				if (num4 > 0f)
				{
					finger.Distal.localRotation = Quaternion.AngleAxis(num4 * weight, axis) * finger.Distal.localRotation;
				}
			}
		}
		if (value == Shape.Flat)
		{
			CloseSpread(rig, hands, weight);
		}
	}

	private static void CloseSpread(Rig rig, Hands hands, float weight)
	{
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: 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)
		//IL_0107: 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_010e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: 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_015c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0168: Unknown result type (might be due to invalid IL or missing references)
		//IL_016d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0197: Unknown result type (might be due to invalid IL or missing references)
		//IL_019c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		Hands[] array = new Hands[2]
		{
			Hands.Left,
			Hands.Right
		};
		foreach (Hands hand in array)
		{
			if ((hands & hand) == 0)
			{
				continue;
			}
			Dictionary<string, Finger> dictionary = rig.Fingers.Where((Finger f) => f.Hand == hand).ToDictionary((Finger f) => f.Name);
			if (!dictionary.TryGetValue("Middle", out var value) || !dictionary.TryGetValue("Index", out var value2) || !dictionary.TryGetValue("Little", out var value3))
			{
				continue;
			}
			Vector3 val = value.Middle.position - value.Base.position;
			Vector3 val2 = Vector3.Cross(value2.Base.position - value3.Base.position, val);
			Vector3 normalized = ((Vector3)(ref val2)).normalized;
			if (normalized == Vector3.zero)
			{
				continue;
			}
			Vector3 val3 = Vector3.ProjectOnPlane(val, normalized);
			Vector3 val4 = Vector3.Cross(normalized, val3);
			foreach (Finger value5 in dictionary.Values)
			{
				if (value5 != value && Convergence.TryGetValue(value5.Name, out var value4))
				{
					float num = Vector3.SignedAngle(Vector3.ProjectOnPlane(value5.Middle.position - value5.Base.position, normalized), val3, normalized);
					float num2 = Mathf.Sign(Vector3.Dot(value5.Base.position - value.Base.position, val4));
					value5.Base.rotation = Quaternion.AngleAxis((num - num2 * value4) * weight, normalized) * value5.Base.rotation;
				}
			}
		}
	}

	internal static float CurlOf(Quaternion rest, Quaternion current, out Vector3 axis)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: 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_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		Quaternion val = Quaternion.Inverse(rest) * current;
		float num = default(float);
		((Quaternion)(ref val)).ToAngleAxis(ref num, ref axis);
		if (num > 180f)
		{
			num = 360f - num;
			axis = -axis;
		}
		return num;
	}

	private static Rig RigOf(Animator animator)
	{
		if (rigs.TryGetValue(animator, out var value) && (value == null || (Object)(object)value.Avatar == (Object)(object)animator.avatar))
		{
			return value;
		}
		foreach (Animator item in rigs.Keys.Where((Animator a) => (Object)(object)a == (Object)null).ToList())
		{
			rigs.Remove(item);
		}
		value = Setup(animator);
		rigs[animator] = value;
		return value;
	}

	private static Rig Setup(Animator animator)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: 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_002c: 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_00b4: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Dictionary<string, Quaternion> dictionary = new Dictionary<string, Quaternion>();
			SkeletonBone[] skeleton = animator.avatar.humanDescription.skeleton;
			foreach (SkeletonBone val in skeleton)
			{
				dictionary[val.name] = val.rotation;
			}
			Rig rig = new Rig
			{
				Avatar = animator.avatar,
				Fingers = new List<Finger>()
			};
			Hands[] array = new Hands[2]
			{
				Hands.Left,
				Hands.Right
			};
			foreach (Hands hands in array)
			{
				string[] fingers = Fingers;
				foreach (string text in fingers)
				{
					HumanBodyBones val2 = (HumanBodyBones)Enum.Parse(typeof(HumanBodyBones), $"{hands}{text}Proximal");
					Transform boneTransform = animator.GetBoneTransform(val2);
					Transform boneTransform2 = animator.GetBoneTransform((HumanBodyBones)(val2 + 1));
					if (!((Object)(object)boneTransform == (Object)null) && !((Object)(object)boneTransform2 == (Object)null) && !((Object)(object)boneTransform2.parent != (Object)(object)boneTransform) && dictionary.TryGetValue(((Object)boneTransform).name, out var value) && dictionary.TryGetValue(((Object)boneTransform2).name, out var value2))
					{
						Transform val3 = animator.GetBoneTransform((HumanBodyBones)(val2 + 2));
						if ((Object)(object)val3 == (Object)null && boneTransform2.childCount > 0)
						{
							val3 = boneTransform2.GetChild(0);
						}
						Quaternion value3 = Quaternion.identity;
						if ((Object)(object)val3 != (Object)null && !dictionary.TryGetValue(((Object)val3).name, out value3))
						{
							val3 = null;
						}
						rig.Fingers.Add(new Finger
						{
							Hand = hands,
							Name = text,
							Base = boneTransform,
							Middle = boneTransform2,
							Distal = val3,
							BaseRest = value,
							MiddleRest = value2,
							DistalRest = value3
						});
					}
				}
			}
			Plugin.Log.LogInfo((object)($"Finger curl set up on {((Object)animator.avatar).name}: {rig.Fingers.Count} fingers (" + string.Join(", ", rig.Fingers.Select((Finger f) => ((Object)f.Base).name + (((Object)(object)f.Distal != (Object)null) ? ("+" + ((Object)f.Distal).name) : ""))) + ")"));
			return rig;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Finger curl unavailable: " + ex.Message));
			return null;
		}
	}
}
[HarmonyPatch(typeof(IKControl), "LeftHandIK")]
internal static class HandIKPatch
{
	internal static bool Enabled = true;

	private static void Postfix(IKControl __instance, Animator ___m_animator, float ___m_leftHandWeight, float ___m_leftHandRotWeight)
	{
		if (Enabled)
		{
			EmoteController component = ((Component)__instance).GetComponent<EmoteController>();
			if (!((Object)(object)component == (Object)null) && !(component.Weight <= 0f))
			{
				float num = 1f - component.Weight;
				___m_animator.SetIKPositionWeight((AvatarIKGoal)2, ___m_leftHandWeight * num);
				___m_animator.SetIKRotationWeight((AvatarIKGoal)2, ___m_leftHandRotWeight * num);
			}
		}
	}
}
public abstract class MenuEntry
{
	public abstract string Key { get; }

	public abstract string Label { get; }

	public abstract void Play(Character character);
}
public class EmoteEntry : MenuEntry
{
	public const float BandRadius = 10f;

	public readonly Emote Emote;

	private readonly string label;

	private readonly bool joinBand;

	public override string Key
	{
		get
		{
			if (!joinBand)
			{
				return "tme:" + Emote.Name;
			}
			return "tme-band:" + Emote.SyncGroupName;
		}
	}

	public override string Label => label;

	public EmoteEntry(Emote emote, string label = null, bool joinBand = false)
	{
		Emote = emote;
		this.label = label ?? emote.DisplayName;
		this.joinBand = joinBand;
	}

	public override void Play(Character character)
	{
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		Emote emote = Emote;
		if (emote.RandomInGroup && emote.SyncGroup != null && emote.SyncGroup.Count > 0)
		{
			emote = emote.SyncGroup[Random.Range(0, emote.SyncGroup.Count)];
		}
		EmoteController syncWith = null;
		if (emote.SyncLayer >= 0 && emote.SyncGroup != null)
		{
			List<EmoteController> list = EmoteController.PerformersOf(emote.SyncGroup, ((Component)character).transform.position, 10f, character);
			syncWith = UnityEngineExtensions.FirstOrDefault<EmoteController>((IList<EmoteController>)list);
			if (joinBand && list.Count > 0)
			{
				HashSet<int> taken = new HashSet<int>(list.Select((EmoteController p) => p.Current.SyncLayer));
				emote = emote.SyncGroup.FirstOrDefault((Emote m) => !taken.Contains(m.SyncLayer)) ?? emote.SyncGroup[0];
			}
		}
		EmoteController.For(character).Play(emote, syncWith);
	}
}
public class SkillEntry : MenuEntry
{
	private readonly int itemID;

	private readonly string name;

	public int ItemID => itemID;

	public override string Key
	{
		get
		{
			int num = itemID;
			return "skill:" + num;
		}
	}

	public override string Label => name;

	public SkillEntry(Skill skill)
	{
		itemID = ((Item)skill).ItemID;
		name = ((Item)skill).Name;
	}

	public override void Play(Character character)
	{
		Skill val = FindLearned(character, itemID);
		if (!((Object)(object)val == (Object)null))
		{
			EmoteController.For(character).Stop();
			if (Plugin.Verbose)
			{
				Plugin.Log.LogMessage((object)$"[SkillEntry] {itemID} '{name}': {DescribeRequirements(val, character)}");
			}
			((Item)val).TryQuickSlotUse();
			EmoteController.For(character).NoteSkillCast();
		}
	}

	private static string DescribeRequirements(Skill skill, Character character)
	{
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		string text = $"requirements={skill.HasAllRequirements(false)} child={((Item)skill).IsChildToCharacter} ";
		string text2 = $"additional={skill.HasAllAdditionalConditions(false)} dlc={((Item)skill).m_DLCID} owned={((Item)skill).GetIsDLCOwned()} ";
		Character ownerCharacter = ((EffectSynchronizer)skill).OwnerCharacter;
		return text + text2 + $"owner={((ownerCharacter != null) ? ownerCharacter.Name : null)} locomotion={character.InLocomotion}/{character.NextIsLocomotion} " + $"cooldown={skill.InCooldown()} bag={character.IsHandlingBag} weapon={character.IsHandlingWeapon}";
	}

	internal static Skill FindLearned(Character character, int itemID)
	{
		CharacterInventory inventory = character.Inventory;
		CharacterSkillKnowledge obj = ((inventory != null) ? inventory.SkillKnowledge : null);
		if (obj == null)
		{
			return null;
		}
		return ((CharacterKnowledge)obj).GetLearnedItems().OfType<Skill>().FirstOrDefault((Func<Skill, bool>)((Skill s) => ((Item)s).ItemID == itemID));
	}
}
public class CastEntry : MenuEntry
{
	private readonly SpellCastType castType;

	private readonly string label;

	public SpellCastType CastType => castType;

	public override string Key => "cast:" + ((object)castType/*cast due to .constrained prefix*/).ToString();

	public override string Label => label;

	public CastEntry(SpellCastType castType, string label)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		this.castType = castType;
		this.label = label;
	}

	public override void Play(Character character)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		if (character.InLocomotion && !character.IsCasting)
		{
			EmoteController emoteController = EmoteController.For(character);
			emoteController.Stop();
			if (character.CastSpell(castType, ((Component)character).gameObject, (SpellCastModifier)0, 1, -1f))
			{
				emoteController.WatchPose(castType);
			}
			else if (Plugin.Verbose)
			{
				Plugin.Log.LogMessage((object)$"[CastEntry] {castType} refused: {emoteController.DescribeState()} next={character.NextIsLocomotion}");
			}
		}
	}
}
public static class MenuCatalog
{
	private static List<MenuEntry> emoteEntries;

	public const string FavoritesTab = "Favorites";

	public const string AllTab = "All";

	public const string OutwardTab = "Outward";

	public static readonly string TooManyEmotesTab = ModSources.DisplayName("TooManyEmotes");

	public const string OtherModsTab = "Other Mods";

	private static List<MenuEntry> EmoteEntries
	{
		get
		{
			List<MenuEntry> list = emoteEntries;
			if (list == null)
			{
				if (!EmoteLibrary.Ready)
				{
					return new List<MenuEntry>();
				}
				list = (emoteEntries = BuildEmoteEntries());
			}
			return list;
		}
	}

	private static List<MenuEntry> BuildEmoteEntries()
	{
		List<MenuEntry> list = new List<MenuEntry>();
		foreach (Emote emote in EmoteLibrary.Menu)
		{
			bool flag = emote.SyncGroup != null && emote.SyncLayer >= 0;
			list.Add(new EmoteEntry(emote, null, flag));
			if (flag)
			{
				list.AddRange(((IEnumerable<Emote>)emote.SyncGroup).Select((Func<Emote, MenuEntry>)((Emote part) => new EmoteEntry(part, emote.DisplayName + " - " + part.VariantName))));
			}
		}
		return list.OrderBy<MenuEntry, string>((MenuEntry e) => e.Label, StringComparer.InvariantCultureIgnoreCase).ToList();
	}

	private static Dictionary<string, List<MenuEntry>> CosmeticSkillsByTab(Character character)
	{
		Dictionary<string, List<MenuEntry>> dictionary = new Dictionary<string, List<MenuEntry>>();
		CharacterInventory inventory = character.Inventory;
		CharacterSkillKnowledge val = ((inventory != null) ? inventory.SkillKnowledge : null);
		if ((Object)(object)val == (Object)null)
		{
			return dictionary;
		}
		foreach (Skill item in from s in ((CharacterKnowledge)val).GetLearnedItems().OfType<Skill>()
			where s.IsCosmetic
			orderby ((Item)s).Name
			select s)
		{
			string text = ModSources.ModOf(((Item)item).ItemID) ?? ((((Item)item).ItemID >= 0) ? "Outward" : "Other Mods");
			if (text == "Favorites" || text == "All")
			{
				text = "Other Mods";
			}
			if (!dictionary.TryGetValue(text, out var value))
			{
				dictionary.Add(text, value = new List<MenuEntry>());
			}
			value.Add(new SkillEntry(item));
		}
		return dictionary;
	}

	private static List<MenuEntry> OutwardEntries(Dictionary<string, List<MenuEntry>> skills)
	{
		List<MenuEntry> list = new List<MenuEntry>
		{
			new CastEntry((SpellCastType)41, "Sit"),
			new CastEntry((SpellCastType)42, "Idle Stretch")
		};
		if (skills.TryGetValue("Outward", out var value))
		{
			list.AddRange(value);
		}
		return list;
	}

	public static List<string> Tabs(Character character)
	{
		List<string> list = CosmeticSkillsByTab(character).Keys.Where((string k) => k != "Outward").ToList();
		if (!list.Contains(TooManyEmotesTab))
		{
			list.Add(TooManyEmotesTab);
		}
		list.Sort(StringComparer.OrdinalIgnoreCase);
		return new string[3] { "Favorites", "All", "Outward" }.Concat(list).ToList();
	}

	public static List<MenuEntry> Entries(string tab, Character character)
	{
		Dictionary<string, List<MenuEntry>> dictionary = CosmeticSkillsByTab(character);
		if (tab == "Outward")
		{
			return OutwardEntries(dictionary);
		}
		if (tab == TooManyEmotesTab)
		{
			return EmoteEntries;
		}
		if (dictionary.TryGetValue(tab, out var value))
		{
			return value;
		}
		List<MenuEntry> source = (from e in OutwardEntries(dictionary).Concat(dictionary.Where((KeyValuePair<string, List<MenuEntry>> p) => p.Key != "Outward").SelectMany((KeyValuePair<string, List<MenuEntry>> p) => p.Value)).Concat(EmoteEntries)
			group e by e.Key into g
			select g.First()).ToList();
		if (tab == "All")
		{
			return source.OrderBy<MenuEntry, string>((MenuEntry e) => e.Label, StringComparer.InvariantCultureIgnoreCase).ToList();
		}
		if (tab == "Favorites")
		{
			Dictionary<string, MenuEntry> byKey = source.ToDictionary((MenuEntry e) => e.Key);
			return (from k in Favorites.Keys.Where(byKey.ContainsKey)
				select byKey[k]).ToList();
		}
		return new List<MenuEntry>();
	}
}
public static class MenuInput
{
	[HarmonyPatch(typeof(ControlsInput), "RotateCameraHorizontal")]
	private static class BlockCameraHorizontal
	{
		private static bool Prefix(int _playerID, ref float __result)
		{
			return Pass(_playerID, ref __result);
		}
	}

	[HarmonyPatch(typeof(ControlsInput), "RotateCameraVertical")]
	private static class BlockCameraVertical
	{
		private static bool Prefix(int _playerID, ref float __result)
		{
			return Pass(_playerID, ref __result);
		}
	}

	[HarmonyPatch(typeof(LocalCharacterControl), "UpdateMenuInputs")]
	private static class BlockGameMenus
	{
		private static bool Prefix(LocalCharacterControl __instance)
		{
			return !MenuOpenFor(__instance);
		}
	}

	[HarmonyPatch(typeof(LocalCharacterControl), "UpdateTargeting")]
	private static class BlockTargeting
	{
		private static bool Prefix(LocalCharacterControl __instance)
		{
			return !MenuOpenFor(__instance);
		}
	}

	[HarmonyPatch(typeof(LocalCharacterControl), "UpdateQuickSlots")]
	private static class BlockQuickSlots
	{
		private static bool Prefix(LocalCharacterControl __instance)
		{
			return !MenuOpenFor(__instance);
		}
	}

	[HarmonyPatch(typeof(LocalCharacterControl), "UpdateWeapon")]
	private static class BlockWeapon
	{
		private static bool Prefix(LocalCharacterControl __instance)
		{
			if (GuardWeaponInputs)
			{
				if (!MenuOpenFor(__instance))
				{
					return !SwallowingFor(__instance);
				}
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(LocalCharacterControl), "UpdateInteraction")]
	private static class BlockInteraction
	{
		private static bool Prefix(LocalCharacterControl __instance)
		{
			if (GuardWeaponInputs)
			{
				if (!MenuOpenFor(__instance))
				{
					return !SwallowingFor(__instance);
				}
				return false;
			}
			return true;
		}
	}

	public const string OpenAction = "Emote Menu";

	public const string NextPageAction = "Emote Menu - Next Page";

	public const string PreviousPageAction = "Emote Menu - Previous Page";

	public const string NextCategoryAction = "Emote Menu - Next Category";

	public const string FavoriteAction = "Emote Menu - Toggle Favorite";

	public const string ZoomInAction = "Emote Camera - Zoom In";

	public const string ZoomOutAction = "Emote Camera - Zoom Out";

	private static ConfigEntry<KeyboardShortcut> openKey;

	private static ConfigEntry<KeyboardShortcut> nextCategoryKey;

	private static ConfigEntry<KeyboardShortcut> favoriteKey;

	private static ConfigEntry<string> zoomInInput;

	private static ConfigEntry<string> zoomOutInput;

	public static ConfigEntry<float> MouseSensitivity;

	internal static bool ReadingAim;

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

	internal static float? TestScroll;

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

	internal static bool GuardWeaponInputs = true;

	public static string NextCategoryKeyName => ((object)nextCategoryKey.Value/*cast due to .constrained prefix*/).ToString();

	public static string FavoriteKeyName => ((object)favoriteKey.Value/*cast due to .constrained prefix*/).ToString();

	public static void Init(ConfigFile config)
	{
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Invalid comparison between Unknown and I4
		//IL_00f8: 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_015b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Expected O, but got Unknown
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Invalid comparison between Unknown and I4
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		string[] array = new string[7]