Decompiled source of ForgeEmote v1.0.0

ForgeEmote.dll

Decompiled 5 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Agents;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using ForgeAudio;
using ForgeCore;
using ForgeEmote.Api;
using ForgeUI;
using ForgeVisual;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using UnityEngine;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ForgeEmote
{
	internal static class EmoteFile
	{
		private static readonly string[] Fields = new string[21]
		{
			"Id", "Name", "Icon", "Page", "Slot", "Clip", "FirstPersonClip", "Body", "Loop", "FadeIn",
			"FadeOut", "View", "Move", "HideHeld", "CancelOnHit", "Crude", "Comms", "Ping", "Sound", "Pair",
			"PairHold"
		};

		private static string Text(JsonElement value, string at, string field, string? fallback)
		{
			//IL_005d: 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)
			if (value.TryGetProperty(field, out var value2))
			{
				if (value2.ValueKind != JsonValueKind.String || value2.GetString().Length == 0)
				{
					throw new StrictJsonException(at + field, at + field + " must be text.");
				}
				return value2.GetString();
			}
			return fallback ?? throw new StrictJsonException(at + field, at + field + " is missing.");
		}

		internal static List<EmoteDefinition> Parse(string json, string folder)
		{
			//IL_002c: 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_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ae: Unknown result type (might be due to invalid IL or missing references)
			using JsonDocument jsonDocument = JsonDocument.Parse(json);
			if (jsonDocument.RootElement.ValueKind != JsonValueKind.Array)
			{
				throw new StrictJsonException("", "A definition file is an array.");
			}
			List<EmoteDefinition> list = new List<EmoteDefinition>();
			int num = 0;
			JsonElement value = jsonDocument.RootElement;
			foreach (JsonElement item in value.EnumerateArray())
			{
				string text = "[" + num++ + "].";
				StrictJson.OnlyKnown(item, text, Fields, (string[])null, (string)null);
				string text2 = Text(item, text, "Page", null);
				bool num2 = text2 == "tactical";
				bool num3 = text2 == "gesture";
				bool flag = text2 == "dance";
				bool flag2 = num3;
				bool flag3 = num2;
				string body = Text(item, text, "Body", flag3 ? "left-arm" : (flag ? "full" : "upper"));
				string id = Text(item, text, "Id", null);
				string text3 = Text(item, text, "View", flag ? "third-person" : "first-person");
				if ((!(text3 == "first-person") && !(text3 == "third-person")) || 1 == 0)
				{
					throw new StrictJsonException(text + "View", text + "View must be first-person or third-person.");
				}
				string text4 = Text(item, text, "Move", flag3 ? "free" : "locked");
				if ((!(text4 == "free") && !(text4 == "locked")) || 1 == 0)
				{
					throw new StrictJsonException(text + "Move", text + "Move must be free or locked.");
				}
				EmoteDefinition emoteDefinition = new EmoteDefinition
				{
					Id = id,
					Name = Text(item, text, "Name", null),
					Icon = (item.TryGetProperty("Icon", out value) ? Text(item, text, "Icon", null) : null),
					Page = text2,
					Slot = (int)StrictJson.Integer(item, text, "Slot", (double?)0.0, 0.0, 7.0),
					Clip = Text(item, text, "Clip", null),
					FirstPersonClip = (item.TryGetProperty("FirstPersonClip", out value) ? Text(item, text, "FirstPersonClip", null) : null),
					Body = body,
					Loop = StrictJson.Bool(item, text, "Loop", (bool?)flag),
					FadeIn = (float)StrictJson.Number(item, text, "FadeIn", (double?)0.15, 0.0, 5.0),
					FadeOut = (float)StrictJson.Number(item, text, "FadeOut", (double?)0.2, 0.0, 5.0),
					View = ((!(text3 == "first-person")) ? EmoteView.ThirdPerson : EmoteView.FirstPerson),
					Move = ((!(text4 == "free")) ? EmoteMove.Locked : EmoteMove.Free),
					HideHeld = StrictJson.Bool(item, text, "HideHeld", (bool?)(flag2 || flag)),
					CancelOnHit = StrictJson.Bool(item, text, "CancelOnHit", (bool?)flag),
					Crude = StrictJson.Bool(item, text, "Crude", (bool?)false),
					Comms = (uint)StrictJson.Integer(item, text, "Comms", (double?)0.0, 0.0, 4294967295.0),
					Ping = StrictJson.Bool(item, text, "Ping", (bool?)false),
					Sound = (item.TryGetProperty("Sound", out value) ? Text(item, text, "Sound", null) : null),
					Pair = StrictJson.Bool(item, text, "Pair", (bool?)false),
					PairHold = (float)StrictJson.Number(item, text, "PairHold", (double?)0.0, 0.0, 60.0),
					Folder = folder
				};
				(string, string)? tuple = EmoteRules.Validate(emoteDefinition);
				if (tuple.HasValue)
				{
					(string, string) valueOrDefault = tuple.GetValueOrDefault();
					throw new StrictJsonException(text + valueOrDefault.Item1, text + valueOrDefault.Item2);
				}
				list.Add(emoteDefinition);
			}
			return list;
		}
	}
	internal sealed class EmotePair
	{
		internal enum Phase : byte
		{
			None,
			Offering,
			Accepting,
			Paired
		}

		internal const float Range = 1.5f;

		internal const float Gap = 1.2f;

		internal const float MaxStep = 0.6f;

		internal const float WaitSeconds = 15f;

		internal const float AcceptSeconds = 3f;

		internal const float Slack = 0.4f;

		internal const float ClaspSeconds = 1.5f;

		internal const float WobbleSpan = 0.3f;

		internal const float WobbleHz = 2f;

		private float _since;

		internal Phase Now { get; private set; }

		internal ulong Partner { get; private set; }

		internal static bool InRange(float distance, bool sameDimension)
		{
			if (sameDimension)
			{
				return distance <= 1.5f;
			}
			return false;
		}

		internal void Wait(float now)
		{
			Now = Phase.Offering;
			Partner = 0uL;
			_since = now;
		}

		internal void Accept(ulong partner, float now)
		{
			Now = Phase.Accepting;
			Partner = partner;
			_since = now;
		}

		internal bool Pair(ulong partner, float distance, bool sameDimension)
		{
			if (!InRange(distance - 0.4f, sameDimension) || Now != Phase.Offering)
			{
				return false;
			}
			Now = Phase.Paired;
			Partner = partner;
			return true;
		}

		internal void Seal()
		{
			if (Now == Phase.Accepting)
			{
				Now = Phase.Paired;
			}
		}

		internal bool Expired(float now)
		{
			return Now switch
			{
				Phase.Offering => now - _since >= 15f, 
				Phase.Accepting => now - _since >= 3f, 
				_ => false, 
			};
		}

		internal void Clear()
		{
			Now = Phase.None;
			Partner = 0uL;
		}

		internal static float ClipTime(Phase phase, float elapsed, float hold)
		{
			if (phase - 1 <= Phase.Offering)
			{
				return hold;
			}
			if (elapsed <= hold)
			{
				return elapsed;
			}
			float num = elapsed - hold;
			if (num >= 1.5f)
			{
				return elapsed - 1.5f;
			}
			return hold + 0.3f * (0.5f - 0.5f * MathF.Cos((float)Math.PI * 4f * num));
		}
	}
	internal static class EmoteRules
	{
		internal const int SlotsPerPage = 8;

		internal static readonly string[] Bodies = new string[5] { "left-arm", "right-arm", "arms", "upper", "full" };

		internal static (string Field, string Message)? Validate(EmoteDefinition d)
		{
			if (!string.IsNullOrEmpty(d.Id) && d.Id.IndexOf(':') > 0)
			{
				string id = d.Id;
				if (id[id.Length - 1] != ':')
				{
					if (string.IsNullOrEmpty(d.Name))
					{
						return ("Name", "Name must be text.");
					}
					if (string.IsNullOrEmpty(d.Page))
					{
						return ("Page", "Page must be text.");
					}
					if (string.IsNullOrEmpty(d.Clip))
					{
						return ("Clip", "Clip must be text.");
					}
					if (d.Slot < 0 || d.Slot >= 8)
					{
						return ("Slot", "Slot must be from 0 to " + 7 + ".");
					}
					if (Array.IndexOf(Bodies, d.Body) < 0)
					{
						return ("Body", "Body must be one of " + string.Join(", ", Bodies) + ".");
					}
					if (!Enum.IsDefined(typeof(EmoteView), d.View))
					{
						return ("View", "View must be first-person or third-person.");
					}
					if (!Enum.IsDefined(typeof(EmoteMove), d.Move))
					{
						return ("Move", "Move must be free or locked.");
					}
					if (!(d.FadeIn >= 0f) || !(d.FadeIn <= 5f))
					{
						return ("FadeIn", "FadeIn must be from 0 to 5.");
					}
					if (!(d.FadeOut >= 0f) || !(d.FadeOut <= 5f))
					{
						return ("FadeOut", "FadeOut must be from 0 to 5.");
					}
					if (!(d.PairHold >= 0f) || !(d.PairHold <= 60f))
					{
						return ("PairHold", "PairHold must be from 0 to 60.");
					}
					return null;
				}
			}
			return ("Id", "Id must be pack:entry.");
		}

		internal static bool CanStart(PlayerMotion motion, EmoteMove move)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			if ((int)motion > 1)
			{
				if ((int)motion == 2)
				{
					return move == EmoteMove.Free;
				}
				if ((int)motion != 17)
				{
					return false;
				}
			}
			return true;
		}

		internal static bool Interrupts(PlayerMotion motion)
		{
			//IL_0000: 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)
			//IL_0034: Expected I4, but got Unknown
			switch (motion - 6)
			{
			case 0:
			case 1:
			case 2:
			case 3:
			case 6:
			case 7:
			case 10:
				return true;
			default:
				return false;
			}
		}

		internal static List<string> FavouritePage(IReadOnlyList<string> favourites, IReadOnlyList<string> recent, Func<string, bool> installed)
		{
			return favourites.Concat(recent).Distinct<string>(StringComparer.Ordinal).Where(installed)
				.Take(8)
				.ToList();
		}

		internal static bool Toggle(List<string> favourites, string id, Func<string, bool> installed)
		{
			if (favourites.Remove(id))
			{
				return true;
			}
			if (favourites.Count(installed) >= 8)
			{
				return false;
			}
			favourites.Add(id);
			return true;
		}

		internal static bool Remember(List<string> recent, string id)
		{
			if (recent.Count > 0 && recent[0] == id)
			{
				return false;
			}
			recent.Remove(id);
			recent.Insert(0, id);
			if (recent.Count > 8)
			{
				recent.RemoveRange(8, recent.Count - 8);
			}
			return true;
		}

		internal static List<(string Page, List<EmoteDefinition> Items)> Arrange(IReadOnlyList<EmoteDefinition> all, IReadOnlyDictionary<string, string[]>? player, List<string> problems)
		{
			List<string> list = new List<string> { "tactical", "gesture", "dance" };
			foreach (EmoteDefinition item in all)
			{
				if (!list.Contains(item.Page))
				{
					list.Add(item.Page);
				}
			}
			Dictionary<string, EmoteDefinition> dictionary = all.ToDictionary<EmoteDefinition, string>((EmoteDefinition definition) => definition.Id, StringComparer.Ordinal);
			List<(string, List<EmoteDefinition>)> list2 = new List<(string, List<EmoteDefinition>)>();
			foreach (string page in list)
			{
				List<EmoteDefinition> list3 = (from definition in all
					where definition.Page == page
					orderby definition.Slot
					select definition).ThenBy<EmoteDefinition, string>((EmoteDefinition definition) => definition.Id, StringComparer.Ordinal).ToList();
				if (player != null && player.TryGetValue(page, out string[] value))
				{
					List<EmoteDefinition> list4 = new List<EmoteDefinition>();
					string[] array = value;
					foreach (string text in array)
					{
						if (dictionary.TryGetValue(text, out var value2))
						{
							if (!list4.Contains(value2))
							{
								list4.Add(value2);
							}
						}
						else
						{
							problems.Add("the wheel file names " + text + ", which is not installed");
						}
					}
					list3 = list4;
				}
				if (list3.Count > 8)
				{
					problems.Add("page " + page + " has " + list3.Count + " actions; the wheel shows the first " + 8);
					list3 = list3.Take(8).ToList();
				}
				if (list3.Count > 0)
				{
					list2.Add((page, list3));
				}
			}
			return list2;
		}
	}
	public static class EmoteControl
	{
		private static string Effective(EmoteDefinition d)
		{
			if (!EmoteRunner.ThirdPerson(d))
			{
				return "first";
			}
			return "third";
		}

		private static Emotes.Entry? Find(string? id, out string? refusal)
		{
			refusal = null;
			if (string.IsNullOrEmpty(id))
			{
				return Emotes.Entries.FirstOrDefault();
			}
			Emotes.Entry entry = Emotes.Find(id);
			if (entry != null)
			{
				return entry;
			}
			List<Emotes.Entry> list = Emotes.Entries.Where((Emotes.Entry e) => e.Definition.Id.EndsWith(":" + id)).ToList();
			if (list.Count == 1)
			{
				return list[0];
			}
			refusal = "refused: " + ((list.Count == 0) ? ("no action " + id) : (id + " matches " + string.Join(", ", list.Select((Emotes.Entry e) => e.Definition.Id))));
			return null;
		}

		public static string List()
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (Emotes.Entry entry in Emotes.Entries)
			{
				EmoteDefinition definition = entry.Definition;
				if (stringBuilder.Length > 0)
				{
					stringBuilder.Append('\n');
				}
				stringBuilder.Append("emote ").Append(definition.Id).Append(" page=")
					.Append(definition.Page)
					.Append(" view=")
					.Append(Effective(definition))
					.Append(" loop=")
					.Append(definition.Loop ? "true" : "false")
					.Append(" sound=")
					.Append(definition.Sound ?? "none")
					.Append(" pair=")
					.Append(definition.Pair ? "true" : "false")
					.Append(" body=")
					.Append(definition.Body)
					.Append(" move=")
					.Append((definition.Move == EmoteMove.Free) ? "free" : "locked");
			}
			if (stringBuilder.Length != 0)
			{
				return stringBuilder.ToString();
			}
			return "no actions";
		}

		public static string Play(string? id = null)
		{
			string refusal;
			Emotes.Entry entry = Find(id, out refusal);
			if (entry == null)
			{
				return refusal ?? "refused: no actions";
			}
			string text = EmoteRunner.Start(entry);
			if (text != null)
			{
				return "refused: " + text;
			}
			return "playing " + entry.Definition.Id + " seq=" + EmoteRunner.Seq + " view=" + (EmoteRunner.ThirdPersonView ? "third" : "first") + " sound=" + (entry.Definition.Sound ?? "none");
		}

		public static string Stop()
		{
			Emotes.Entry current = EmoteRunner.Current;
			if (current == null)
			{
				return "idle";
			}
			EmoteRunner.StopLocal();
			return "stopped " + current.Definition.Id;
		}

		public static string State()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			Emotes.Entry current = EmoteRunner.Current;
			PlayerAgent local = Players.Local;
			string text = ((local != null) ? ((object)Players.Motion(local)/*cast due to .constrained prefix*/).ToString() : "none");
			if (current == null)
			{
				return "idle motion=" + text;
			}
			EmoteDefinition definition = current.Definition;
			return "playing " + definition.Id + " elapsed=" + EmoteRunner.Elapsed.ToString("0.00") + " view=" + (EmoteRunner.ThirdPersonView ? "third" : "first") + " sound=" + ((definition.Sound == null) ? "none" : (EmoteRunner.SoundPlaying ? "playing" : "silent")) + " body=" + definition.Body + " move=" + ((definition.Move == EmoteMove.Free) ? "free" : "locked") + " motion=" + text;
		}

		public static string Favourite(string? id, string mode = "on")
		{
			string refusal;
			Emotes.Entry entry = Find(id, out refusal);
			if (entry == null || string.IsNullOrEmpty(id))
			{
				return refusal ?? "refused: no action named";
			}
			if ((!(mode == "on") && !(mode == "off")) || 1 == 0)
			{
				return "refused: mode is on or off";
			}
			string id2 = entry.Definition.Id;
			if (EmoteWheel.IsFavourite(id2) != (mode == "on") && !EmoteWheel.Toggle(id2))
			{
				return "refused: " + Favourites();
			}
			return "favourite " + id2 + " " + mode + " (" + EmoteWheel.Starred.Count + "/" + 8 + ")";
		}

		public static string Favourites()
		{
			return "favourites " + EmoteWheel.Starred.Count + "/" + 8 + ((EmoteWheel.Starred.Count > 0) ? (": " + string.Join(" ", EmoteWheel.Starred)) : "");
		}

		public static string Highlight()
		{
			PlayerAgent local = Players.Local;
			if (local == null)
			{
				return "refused: no local player";
			}
			HashSet<string> hashSet = EmoteRunner.Answers(local);
			if (hashSet.Count != 0)
			{
				return "highlight " + string.Join(" ", hashSet);
			}
			return "highlight none";
		}
	}
	internal static class EmotePeers
	{
		private static NetManifest _list;

		internal static void Load(NetChannel channel, Action<ulong> recheck)
		{
			_list = channel.Manifest("actions");
			Publish();
			Emotes.Changed += Publish;
			_list.Changed += delegate(ulong player)
			{
				Report(player);
				recheck(player);
			};
		}

		private static void Publish()
		{
			_list.Set(Emotes.Entries.Select((Emotes.Entry entry) => (NetId: entry.NetId, Fnv.Hash64(entry.Hash))));
		}

		internal static bool Shows(ulong player, uint id)
		{
			//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_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected I4, but got Unknown
			ContentMatch val = _list.Match(player, id);
			switch (val - 1)
			{
			case 0:
				return true;
			case 1:
				Plugin.Logger.ErrorOnce("ForgeEmote: " + EmoteRunner.NameOf(player) + " played " + Emotes.Find(id).Definition.Id + " but their copy has different clips; it is not shown.");
				return false;
			case 3:
				Plugin.Logger.ErrorOnce("ForgeEmote: " + EmoteRunner.NameOf(player) + " played action #" + id + ", which this side does not have; their log names its pack.");
				return false;
			default:
				return false;
			}
		}

		private static void Report(ulong player)
		{
			ContentDifferences val = _list.Differences(player);
			if (val != null && !val.None)
			{
				string text = EmoteRunner.NameOf(player);
				if (val.OnlyHere.Count > 0)
				{
					Plugin.Logger.ErrorOnce("ForgeEmote: " + text + " does not have " + Names(val.OnlyHere) + "; they do not see these actions.");
				}
				if (val.Mismatched.Count > 0)
				{
					Plugin.Logger.ErrorOnce("ForgeEmote: " + text + " has different clips for " + Names(val.Mismatched) + "; these actions are refused both ways.");
				}
				if (val.OnlyThere.Count > 0)
				{
					Plugin.Logger.ErrorOnce("ForgeEmote: " + text + " has " + val.OnlyThere.Count + " action(s) this side does not have; they are not shown here.");
				}
			}
		}

		private static string Names(IReadOnlyList<uint> ids)
		{
			return string.Join(", ", ids.Select((uint id) => Emotes.Find(id).Definition.Id));
		}
	}
	internal static class EmoteRunner
	{
		private sealed class PlayedBody
		{
			private IntPtr _agent;

			private JointPlayer? _joints;

			private JointTrack _track;

			private HeldHiding? _held;

			private AudioHandle? _sound;

			internal bool Playing => ((JointTrack)(ref _track)).Playing;

			internal bool SoundPlaying
			{
				get
				{
					//IL_000e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0014: Invalid comparison between Unknown and I4
					if (_sound != null)
					{
						return (int)_sound.State != 3;
					}
					return false;
				}
			}

			internal bool Bound(PlayerAgent agent)
			{
				if (_agent == ((Il2CppObjectBase)agent).Pointer)
				{
					if (_joints != null)
					{
						if ((Object)(object)_joints.Root != (Object)null)
						{
							return !((Il2CppObjectBase)_joints.Root).WasCollected;
						}
						return false;
					}
					return true;
				}
				return false;
			}

			internal bool Bind(PlayerAgent agent)
			{
				if (_joints == null || _agent != ((Il2CppObjectBase)agent).Pointer || (Object)(object)_joints.Root == (Object)null || ((Il2CppObjectBase)_joints.Root).WasCollected)
				{
					_agent = ((Il2CppObjectBase)agent).Pointer;
					_joints = Models.BindJoints(agent);
				}
				return _joints != null;
			}

			internal bool Play(PlayerAgent agent, Emotes.Entry entry, JointMask mask, float start)
			{
				//IL_0057: 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_0064: 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)
				HeldHiding? held = _held;
				if (held != null)
				{
					held.Dispose();
				}
				_held = null;
				if (!Bind(agent))
				{
					return false;
				}
				EmoteDefinition definition = entry.Definition;
				JointPlayer? joints = _joints;
				ref JointTrack track = ref _track;
				JointClip clip = entry.Clip;
				JointPlayback val = new JointPlayback(start, definition.Loop, mask, 1f, definition.FadeIn, definition.FadeOut);
				_track = joints.CrossFade(ref track, clip, ref val, 0.15f);
				if (definition.HideHeld)
				{
					_held = Models.HideHeld(agent);
				}
				AudioHandle? sound = _sound;
				if (sound != null)
				{
					sound.Stop(0.15f);
				}
				_sound = entry.PlaySound(agent, start);
				return true;
			}

			internal string Readout(PlayerAgent agent)
			{
				//IL_004c: 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_0098: 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_014d: Unknown result type (might be due to invalid IL or missing references)
				//IL_017d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0182: Unknown result type (might be due to invalid IL or missing references)
				if (_joints != null && !((Object)(object)_joints.Root == (Object)null) && !((Il2CppObjectBase)_joints.Root).WasCollected)
				{
					Transform val = _joints.Bone(0);
					if (val != null && !((Il2CppObjectBase)val).WasCollected)
					{
						float y = ((Agent)agent).Position.y;
						float num = float.MaxValue;
						int[] array = new int[2] { 3, 6 };
						foreach (int num2 in array)
						{
							Transform val2 = _joints.Bone(num2);
							if (val2 != null && !((Il2CppObjectBase)val2).WasCollected)
							{
								num = Mathf.Min(num, val2.position.y);
							}
						}
						float num3 = ((Agent)agent).EyePosition.y - y;
						bool flag = (Object)(object)agent.SyncIK != (Object)null && !((Il2CppObjectBase)agent.SyncIK).WasCollected && agent.SyncIK.IsEnabled();
						return "hipY=" + (val.position.y - y).ToString("0.000") + " footLowY=" + (num - y).ToString("0.000") + " bodyRootY=" + (_joints.Root.position.y - y).ToString("0.000") + " bodyScale=" + _joints.Root.lossyScale.y.ToString("0.000") + " eyeY=" + num3.ToString("0.000") + " agentY=" + y.ToString("0.000") + " syncIk=" + flag + " playing=" + Playing;
					}
				}
				return "no-body";
			}

			internal void Hold(float clipTime)
			{
				((JointTrack)(ref _track)).Seek(clipTime);
			}

			internal void Stop(float fade)
			{
				((JointTrack)(ref _track)).Stop(fade);
				AudioHandle? sound = _sound;
				if (sound != null)
				{
					sound.Stop(fade);
				}
				_sound = null;
				HeldHiding? held = _held;
				if (held != null)
				{
					held.Dispose();
				}
				_held = null;
			}
		}

		private sealed class Watched
		{
			internal readonly PlayedBody Body = new PlayedBody();

			internal uint Shown;

			internal byte ShownSeq;

			internal bool Waiting;

			internal EmotePair.Phase Phase;

			internal ulong Partner;

			internal float Start;

			internal float Hold;

			internal bool Pair;
		}

		private struct State
		{
			internal uint Id;

			internal byte Seq;

			internal byte Phase;

			internal ulong Partner;
		}

		private const float QuickFade = 0.1f;

		private const float CrossFade = 0.15f;

		private static NetChannel _channel = null;

		private const float FollowRange = 8f;

		private static readonly EmotePair Link = new EmotePair();

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

		private const float AnswerGrace = 60f;

		private static readonly Dictionary<ulong, float> Unanswered = new Dictionary<ulong, float>();

		private static readonly List<ulong> Judged = new List<ulong>();

		private static InteractPrompt? _prompt;

		private static Emotes.Entry? _promptFor;

		private static string _promptText = "";

		private static string _promptKey = "";

		private static bool _promptUp;

		private static bool _useWas;

		private static bool _useHeld;

		private static PlayerStateSlot<State> _slot = null;

		private static byte _seq;

		private static int _warm;

		private static int _agentCount = -1;

		private static bool _bindPending;

		private static bool _watching;

		private static readonly Dictionary<ulong, Watched> Others = new Dictionary<ulong, Watched>();

		private static bool _anyWaiting;

		private static Emotes.Entry? _current;

		private static float _began;

		private static readonly PlayedBody Body = new PlayedBody();

		private static InventorySlot _wielded;

		private static float _health;

		private static FirstPersonArms? _arms;

		private static PlayerAgent? _local;

		private static CameraLease? _lease;

		private static InputLease? _input;

		private static OwnBodyView? _own;

		private static bool _leaving;

		private static float _yaw;

		private static float _pitch;

		private static string _readId = "";

		private static float _readAt;

		internal static Emotes.Entry? Current => _current;

		internal static byte Seq => _seq;

		internal static float Elapsed
		{
			get
			{
				if (_current != null)
				{
					return Time.time - _began;
				}
				return 0f;
			}
		}

		internal static bool ThirdPersonView => _lease != null;

		internal static bool SoundPlaying => Body.SoundPlaying;

		internal static void Load()
		{
			_channel = Net.Open("NAinfini.ForgeEmote", 512);
			_slot = _channel.PlayerState<State>("state");
			_slot.Changed += Seen;
			EmotePeers.Load(_channel, delegate(ulong player)
			{
				State state = default(State);
				float num = default(float);
				if (_slot.TryGet(player, ref state, ref num))
				{
					Seen(player, active: true);
				}
			});
			_channel.FollowWorld((Func<bool>)delegate
			{
				PlayerAgent local = Players.Local;
				return local != null && !((Il2CppObjectBase)local).WasCollected;
			});
			_channel.Refused += delegate(ulong player, string reason)
			{
				Plugin.Logger.Error("ForgeEmote " + NameOf(player) + " does not match: " + reason);
			};
			_channel.PeerSilent += delegate(ulong player)
			{
				Unanswered[player] = Time.time + 60f;
			};
			_channel.PeerSynced += delegate(ulong player)
			{
				Unanswered.Remove(player);
			};
			_prompt = UIKit.Mod("NAinfini.ForgeEmote").AddInteractPrompt("Answer");
			UIKit.LanguageChanged += delegate
			{
				_promptFor = null;
			};
			GameEvents.LevelEnded += Cleanup;
			GameEvents.CheckpointReloaded += Cleanup;
		}

		internal static string NameOf(ulong player)
		{
			PlayerAgent val = AgentOf(player);
			if (!((Object)(object)val != (Object)null))
			{
				return player.ToString();
			}
			return val.PlayerName;
		}

		private static PlayerAgent? AgentOf(ulong player)
		{
			return Level.PlayerByLookup(player);
		}

		private static InventorySlot Wielded(PlayerAgent agent)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			PlayerInventoryBase inventory = agent.Inventory;
			if (!((Object)(object)inventory == (Object)null))
			{
				return inventory.WieldedSlot;
			}
			return (InventorySlot)0;
		}

		internal unsafe static string? Start(Emotes.Entry entry)
		{
			//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_002b: 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_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: 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)
			PlayerAgent local = Players.Local;
			if ((Object)(object)local == (Object)null || ((Il2CppObjectBase)local).WasCollected)
			{
				return "no local player";
			}
			EmoteDefinition definition = entry.Definition;
			PlayerMotion motion = Players.Motion(local);
			if (!EmoteRules.CanStart(motion, definition.Move))
			{
				return "the player is " + ((object)(*(PlayerMotion*)(&motion))/*cast due to .constrained prefix*/).ToString() + " and the action is " + definition.Move;
			}
			if (UIKit.GameScreenOpen)
			{
				return "a game screen is open";
			}
			ulong offerer = (definition.Pair ? Offerer(local, entry) : 0);
			float num = (definition.Pair ? (Time.time - definition.PairHold) : (Follow(local, entry) ?? Time.time));
			bool flag = ThirdPerson(definition);
			if (!Body.Play(local, entry, flag ? entry.Mask : entry.FirstPersonMask, num))
			{
				return "the body cannot play clips";
			}
			_local = local;
			_current = entry;
			_began = num;
			_wielded = Wielded(local);
			_health = ((Dam_SyncedDamageBase)local.Damage).Health;
			Link.Clear();
			if (definition.Pair)
			{
				StartPair(local, offerer);
			}
			_slot.Publish(new State
			{
				Id = entry.NetId,
				Seq = ++_seq,
				Phase = (byte)Link.Now,
				Partner = Link.Partner
			}, num);
			EmoteWheel.Used(definition.Id);
			if (flag)
			{
				FirstPersonArms? arms = _arms;
				if (arms != null)
				{
					arms.Stop();
				}
				EnterView(local);
			}
			else
			{
				EndView();
				if (entry.FirstPerson == null)
				{
					FirstPersonArms? arms2 = _arms;
					if (arms2 != null)
					{
						arms2.Stop();
					}
				}
				else
				{
					BindArms(local);
					FirstPersonArms? arms3 = _arms;
					if (arms3 != null)
					{
						JointClip? firstPerson = entry.FirstPerson;
						JointPlayback val = new JointPlayback(num, definition.Loop, (JointMask)null, 1f, 0f, 0f);
						arms3.Play(firstPerson, ref val, definition.HideHeld);
					}
				}
			}
			Read("start", local, entry.Definition.Id);
			if (definition.Comms != 0 && !Comms.Say(local, definition.Comms, (PlayerAgent)null))
			{
				Plugin.Logger.ErrorOnce("ForgeEmote: the game has no communication line " + definition.Comms + " or its menu is not up (" + definition.Id + ").");
			}
			Vector3 val2 = default(Vector3);
			if (definition.Ping && UIKit.AimPoint(ref val2))
			{
				UIKit.Ping(local, val2, (eNavMarkerStyle)1);
			}
			return null;
		}

		internal static void StopLocal()
		{
			Stop(0.15f, cut: false);
		}

		internal static bool ThirdPerson(EmoteDefinition definition)
		{
			if (definition.View != EmoteView.ThirdPerson || !Plugin.ThirdPerson.Value)
			{
				if (definition.Page == "gesture")
				{
					return Plugin.ThirdPersonGestures.Value;
				}
				return false;
			}
			return true;
		}

		private static void StartPair(PlayerAgent local, ulong offerer)
		{
			if (offerer != 0L)
			{
				PlayerAgent val = AgentOf(offerer);
				if (val != null)
				{
					Link.Accept(offerer, Time.time);
					Meet(local, val);
					return;
				}
			}
			Link.Wait(Time.time);
		}

		private static ulong Offerer(PlayerAgent local, Emotes.Entry entry)
		{
			foreach (var (num2, watched2) in Others)
			{
				if (watched2.Shown == entry.NetId && watched2.Phase == EmotePair.Phase.Offering)
				{
					PlayerAgent val = AgentOf(num2);
					if (val != null && Near(local, val))
					{
						return num2;
					}
				}
			}
			return 0uL;
		}

		private static void Meet(PlayerAgent local, PlayerAgent other)
		{
			//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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: 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_0051: 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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: 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)
			//IL_007a: 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_0089: 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_008f: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ((Agent)local).Position - ((Agent)other).Position;
			val.y = 0f;
			if (((Vector3)(ref val)).sqrMagnitude < 0.0001f)
			{
				Players.Face(local, ((Agent)other).Position);
				return;
			}
			((Vector3)(ref val)).Normalize();
			Vector3 val2 = ((Agent)other).Position + val * 1.2f;
			Vector3 val3 = default(Vector3);
			if (Vector3.Distance(val2, ((Agent)local).Position) <= 0.6f && Level.TrySnap(val2, 0.4f, ref val3) && !Level.Blocked(((Agent)local).Position, val3))
			{
				WarpResult val4 = Players.Warp(local, ((Agent)local).DimensionIndex, val3, -val, (WarpMode)1);
				if (((WarpResult)(ref val4)).Accepted)
				{
					return;
				}
			}
			Players.Face(local, ((Agent)other).Position);
		}

		private static float Distance(PlayerAgent local, PlayerAgent other)
		{
			//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)
			return Vector3.Distance(((Agent)local).Position, ((Agent)other).Position);
		}

		private static bool SameDimension(PlayerAgent local, PlayerAgent other)
		{
			//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)
			return ((Agent)local).DimensionIndex == ((Agent)other).DimensionIndex;
		}

		private static bool Near(PlayerAgent local, PlayerAgent other)
		{
			return EmotePair.InRange(Distance(local, other), SameDimension(local, other));
		}

		private static void HighlightAnswers(PlayerAgent local)
		{
			EmoteWheel.Highlight(Answers(local));
		}

		internal static HashSet<string> Answers(PlayerAgent local)
		{
			Answerable.Clear();
			if (_current == null)
			{
				foreach (var (player, watched2) in Others)
				{
					if (watched2.Phase != EmotePair.Phase.Offering)
					{
						continue;
					}
					Emotes.Entry entry = Emotes.Find(watched2.Shown);
					if (entry != null && entry.Definition.Pair)
					{
						PlayerAgent val = AgentOf(player);
						if (val != null && Near(local, val))
						{
							Answerable.Add(entry.Definition.Id);
						}
					}
				}
			}
			return Answerable;
		}

		private static void WatchIfAny()
		{
			foreach (Watched value in Others.Values)
			{
				if (value.Shown != 0)
				{
					return;
				}
			}
			Watching(on: false);
		}

		private static void BindArms(PlayerAgent local)
		{
			if (_arms == null || !_arms.Alive)
			{
				_arms = Models.BindFirstPersonArms(local);
			}
		}

		private static float? Follow(PlayerAgent local, Emotes.Entry entry)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if (entry.Definition.Page != "dance")
			{
				return null;
			}
			State state = default(State);
			float value = default(float);
			foreach (var (num2, watched2) in Others)
			{
				if (watched2.Shown == entry.NetId && watched2.Body.Playing && _slot.TryGet(num2, ref state, ref value))
				{
					PlayerAgent val = AgentOf(num2);
					if ((Object)(object)val != (Object)null && Vector3.Distance(((Agent)val).Position, ((Agent)local).Position) <= 8f)
					{
						return value;
					}
				}
			}
			return null;
		}

		private static void EnterView(PlayerAgent local)
		{
			//IL_0045: 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_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			_leaving = false;
			if (_lease == null)
			{
				_lease = CameraLease.Take("NAinfini.ForgeEmote");
				_input = InputLease.Take("NAinfini.ForgeEmote");
				_input.Block((InputAction[])(object)new InputAction[2]
				{
					(InputAction)3,
					(InputAction)4
				});
				Quaternion val = Quaternion.LookRotation(((Agent)local).TargetLookDir);
				Vector3 eulerAngles = ((Quaternion)(ref val)).eulerAngles;
				_yaw = eulerAngles.y;
				_pitch = Mathf.Clamp(Mathf.DeltaAngle(0f, eulerAngles.x), -30f, 60f);
				_own = Models.ShowOwnBody(local, (OwnBodyOptions)null);
			}
		}

		private static void Stop(float fade, bool cut)
		{
			if (_current != null)
			{
				_readId = _current.Definition.Id;
				_current = null;
				Link.Clear();
				Body.Stop(fade);
				if (Plugin.Readback.Value && (Object)(object)_local != (Object)null)
				{
					Read("end", _local, _readId);
					_readAt = Time.time + 1f;
				}
				_slot.Clear();
				FirstPersonArms? arms = _arms;
				if (arms != null)
				{
					arms.Stop();
				}
				if (cut || _lease == null)
				{
					EndView();
				}
				else
				{
					_leaving = true;
				}
			}
		}

		private static void Read(string when, PlayerAgent local, string id)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.Readback.Value)
			{
				Plugin.Info.LogInfo((object)("ForgeEmote readback " + when + " " + id + " " + Body.Readout(local) + " motion=" + ((object)Players.Motion(local)/*cast due to .constrained prefix*/).ToString() + " view=" + ((_lease != null) ? "third" : "first")));
			}
		}

		private static void EndView()
		{
			InputLease? input = _input;
			if (input != null)
			{
				input.Dispose();
			}
			_input = null;
			CameraLease? lease = _lease;
			if (lease != null)
			{
				lease.Dispose();
			}
			_lease = null;
			OwnBodyView? own = _own;
			if (own != null)
			{
				own.Dispose();
			}
			_own = null;
			_leaving = false;
		}

		private static void Cleanup()
		{
			Stop(0f, cut: true);
			EndView();
			_local = null;
			Link.Clear();
			foreach (Watched value in Others.Values)
			{
				value.Body.Stop(0f);
			}
			Others.Clear();
			_anyWaiting = false;
			_warm = 0;
			_agentCount = -1;
			Watching(on: false);
		}

		private static void Watching(bool on)
		{
			if (on != _watching)
			{
				_watching = on;
				if (on)
				{
					Players.MotionChanged += MotionChanged;
				}
				else
				{
					Players.MotionChanged -= MotionChanged;
				}
			}
		}

		private static void Warm(PlayerAgent local)
		{
			if (_warm < 2 && _current == null)
			{
				if (_warm == 0)
				{
					Body.Bind(local);
				}
				else
				{
					if (!Models.FirstPersonArmsReady(local))
					{
						return;
					}
					BindArms(local);
				}
				_warm++;
				return;
			}
			List<PlayerAgent> playerAgentsInLevel = PlayerManager.PlayerAgentsInLevel;
			if (playerAgentsInLevel == null)
			{
				return;
			}
			int count = playerAgentsInLevel.Count;
			if (count != _agentCount)
			{
				_agentCount = count;
				_bindPending = true;
			}
			if (!_bindPending)
			{
				return;
			}
			_bindPending = false;
			for (int i = 0; i < count; i++)
			{
				PlayerAgent val = playerAgentsInLevel[i];
				if ((Object)(object)val == (Object)null || ((Il2CppObjectBase)val).WasCollected || ((Agent)val).IsLocallyOwned)
				{
					continue;
				}
				SNet_Player owner = val.Owner;
				if (!((Object)(object)owner == (Object)null))
				{
					ulong lookup = owner.Lookup;
					if (!Others.TryGetValue(lookup, out Watched value))
					{
						Others.Add(lookup, value = new Watched());
					}
					if (!value.Body.Bound(val))
					{
						value.Body.Bind(val);
						_bindPending = true;
						break;
					}
				}
			}
		}

		internal static void Update()
		{
			//IL_0169: 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_01b1: 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_0237: Unknown result type (might be due to invalid IL or missing references)
			_channel.Pump();
			EmoteWheel.Flush();
			if (!Emotes.Closed && SNet.IsInLobby)
			{
				Emotes.Close();
			}
			if (_anyWaiting)
			{
				RetryWaiting();
			}
			if (Unanswered.Count != 0)
			{
				JudgeUnanswered();
			}
			if (_readAt > 0f && Time.time >= _readAt)
			{
				PlayerAgent local = Players.Local;
				if (local != null && !((Il2CppObjectBase)local).WasCollected)
				{
					_readAt = 0f;
					Read("end+1s", local, _readId);
				}
			}
			foreach (Watched value in Others.Values)
			{
				if (value.Pair && value.Shown != 0 && value.Body.Playing)
				{
					value.Body.Hold(EmotePair.ClipTime(value.Phase, Time.time - value.Start, value.Hold));
				}
			}
			PlayerAgent local2 = Players.Local;
			if ((Object)(object)local2 == (Object)null || ((Il2CppObjectBase)local2).WasCollected)
			{
				return;
			}
			if (EmoteWheel.IsOpen)
			{
				for (int i = 0; i < 2; i++)
				{
					if (_warm >= 2)
					{
						break;
					}
					if (_current != null)
					{
						break;
					}
					Warm(local2);
				}
			}
			Warm(local2);
			if (EmoteWheel.IsOpen)
			{
				HighlightAnswers(local2);
			}
			if (_current == null)
			{
				if (EmoteWheel.IsOpen)
				{
					EmoteWheel.Refresh(Players.Motion(local2));
				}
				if (_leaving && !EmoteWheel.HoldsInput && GameActionKey())
				{
					EndView();
				}
				AnswerPrompt(local2);
				return;
			}
			_promptUp = false;
			InteractPrompt? prompt = _prompt;
			if (prompt != null)
			{
				prompt.Hide();
			}
			PlayerMotion motion = Players.Motion(local2);
			if (EmoteWheel.IsOpen)
			{
				EmoteWheel.Refresh(motion);
			}
			float time = Time.time;
			if (_current.Definition.Pair)
			{
				Body.Hold(EmotePair.ClipTime(Link.Now, time - _began, _current.Definition.PairHold));
			}
			if (Link.Expired(time))
			{
				Stop(0.15f, cut: false);
			}
			else if (!Body.Playing)
			{
				Stop(0f, cut: false);
			}
			else if (Interrupted(local2, motion, _current.Definition))
			{
				Stop(0.1f, cut: true);
			}
		}

		private static bool Interrupted(PlayerAgent local, PlayerMotion motion, EmoteDefinition definition)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			if (EmoteRules.Interrupts(motion) || UIKit.GameScreenOpen)
			{
				return true;
			}
			if (Wielded(local) != _wielded)
			{
				return true;
			}
			if (definition.CancelOnHit)
			{
				float health = ((Dam_SyncedDamageBase)local.Damage).Health;
				if (health < _health)
				{
					return true;
				}
				_health = health;
			}
			bool flag = definition.Move == EmoteMove.Locked;
			if (flag && !EmoteRules.CanStart(motion, EmoteMove.Locked))
			{
				return true;
			}
			if (EmoteWheel.HoldsInput)
			{
				return false;
			}
			if (_useHeld)
			{
				_useHeld = InputLease.Down((InputAction)6);
			}
			if (!flag)
			{
				if (!InputLease.Down((InputAction)11))
				{
					return InputLease.Down((InputAction)12);
				}
				return true;
			}
			if (!GameActionKey(_useHeld))
			{
				return Moving();
			}
			return true;
		}

		private static bool GameActionKey(bool ignoreUse = false)
		{
			if (!InputLease.Down((InputAction)8) && !InputLease.Down((InputAction)7) && (ignoreUse || !InputLease.Down((InputAction)6)) && !InputLease.Down((InputAction)11))
			{
				return InputLease.Down((InputAction)12);
			}
			return true;
		}

		private static void AnswerPrompt(PlayerAgent local)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			Emotes.Entry entry = null;
			foreach (var (player, watched2) in Others)
			{
				if (watched2.Phase != EmotePair.Phase.Offering)
				{
					continue;
				}
				Emotes.Entry entry2 = Emotes.Find(watched2.Shown);
				if (entry2 != null)
				{
					PlayerAgent val = AgentOf(player);
					if (val != null && Near(local, val))
					{
						entry = entry2;
						break;
					}
				}
			}
			if (entry == null || EmoteWheel.IsOpen || UIKit.GameScreenOpen || ((Object)(object)local.Interaction != (Object)null && local.Interaction.HasWorldInteraction) || !EmoteRules.CanStart(Players.Motion(local), entry.Definition.Move))
			{
				_promptUp = false;
				InteractPrompt? prompt = _prompt;
				if (prompt != null)
				{
					prompt.Hide();
				}
				return;
			}
			if (_promptFor != entry)
			{
				_promptFor = entry;
				_promptText = UIKit.Mod("NAinfini.ForgeEmote").Text("pair.answer", new object[1] { entry.Texts.Text(entry.Definition.Name) });
				_promptKey = "[" + UIKitKeys.Binding((InputAction)6, "E") + "]";
			}
			InteractPrompt? prompt2 = _prompt;
			if (prompt2 != null)
			{
				prompt2.Show(_promptText, _promptKey);
			}
			bool num2 = InputLease.Down((InputAction)6);
			bool flag = num2 && !_useWas && _promptUp;
			_useWas = num2;
			_promptUp = true;
			if (flag)
			{
				InteractPrompt? prompt3 = _prompt;
				if (prompt3 != null)
				{
					prompt3.Hide();
				}
				_useHeld = true;
				if (Start(entry) != null)
				{
					_useHeld = false;
				}
			}
		}

		private static void JudgeUnanswered()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			Judged.Clear();
			float time = Time.time;
			foreach (var (num3, num4) in Unanswered)
			{
				if ((int)_channel.State(num3) != 0)
				{
					Judged.Add(num3);
				}
				else if (time >= num4)
				{
					Judged.Add(num3);
					Plugin.Logger.ErrorOnce("ForgeEmote: " + NameOf(num3) + " has not answered ForgeEmote (not installed, still loading, or another version); they may not see your actions.");
				}
			}
			foreach (ulong item in Judged)
			{
				Unanswered.Remove(item);
			}
		}

		private static bool Moving()
		{
			if (!InputLease.Down((InputAction)5) && !InputLease.Down((InputAction)10) && !(Mathf.Abs(InputLease.Axis((InputAction)1)) > 0.1f))
			{
				return Mathf.Abs(InputLease.Axis((InputAction)2)) > 0.1f;
			}
			return true;
		}

		internal static void LateUpdate()
		{
			//IL_0083: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: 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: Unknown result type (might be due to invalid IL or missing references)
			if (_lease == null)
			{
				return;
			}
			if (!_lease.IsHeld || (Object)(object)_local == (Object)null || ((Il2CppObjectBase)_local).WasCollected)
			{
				EndView();
				return;
			}
			if (!_leaving && Plugin.Orbit.Value && !EmoteWheel.HoldsInput)
			{
				_yaw += InputLease.Axis((InputAction)3);
				_pitch = Mathf.Clamp(_pitch - InputLease.Axis((InputAction)4), -30f, 60f);
			}
			Vector3 val = ((Agent)_local).EyePosition + Vec.Up * Plugin.Height.Value;
			float num = _lease.Orbit(val, _yaw, _pitch, Plugin.Distance.Value, Plugin.Shoulder.Value, Plugin.BlendSeconds.Value, _leaving);
			if (_leaving && num <= 0f)
			{
				EndView();
			}
		}

		private static void Seen(ulong player, bool active)
		{
			if (!Others.TryGetValue(player, out Watched value))
			{
				Others.Add(player, value = new Watched());
			}
			value.Waiting = false;
			State state = default(State);
			float start = default(float);
			if (!active || !_slot.TryGet(player, ref state, ref start))
			{
				Forget(player, value, 0.15f);
				return;
			}
			uint id = state.Id;
			if (id == value.Shown && state.Seq == value.ShownSeq)
			{
				return;
			}
			Emotes.Entry entry = Emotes.Find(id);
			if (!EmotePeers.Shows(player, id) || entry == null || (entry.Definition.Crude && !Plugin.CrudeGestures.Value))
			{
				Forget(player, value, 0.15f);
				return;
			}
			PlayerAgent val = AgentOf(player);
			if ((Object)(object)val == (Object)null)
			{
				value.Waiting = (_anyWaiting = true);
				return;
			}
			value.Shown = id;
			value.ShownSeq = state.Seq;
			value.Pair = entry.Definition.Pair;
			value.Hold = entry.Definition.PairHold;
			value.Phase = (EmotePair.Phase)state.Phase;
			value.Partner = state.Partner;
			value.Start = start;
			if ((Object)(object)_local != (Object)null && _current != null && _current.Definition.Pair)
			{
				Pairing(player, value, val);
			}
			if (value.Body.Play(val, entry, entry.Mask, start))
			{
				Watching(on: true);
			}
		}

		private static void Forget(ulong player, Watched other, float fade)
		{
			other.Shown = 0u;
			other.Phase = EmotePair.Phase.None;
			other.Partner = 0uL;
			other.Body.Stop(fade);
			WatchIfAny();
			bool flag = _current != null && Link.Partner == player;
			if (flag)
			{
				EmotePair.Phase now = Link.Now;
				bool flag2 = now - 2 <= EmotePair.Phase.Offering;
				flag = flag2;
			}
			if (flag)
			{
				Stop(0.15f, cut: false);
			}
		}

		private static void Pairing(ulong player, Watched other, PlayerAgent agent)
		{
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			PlayerAgent local = _local;
			ulong lookup = local.Owner.Lookup;
			bool flag = Link.Partner == player;
			if (flag)
			{
				EmotePair.Phase now = Link.Now;
				bool flag2 = now - 2 <= EmotePair.Phase.Offering;
				flag = flag2;
			}
			int num;
			if (flag)
			{
				if (other.Shown == _current.NetId)
				{
					if (Link.Now != EmotePair.Phase.Paired)
					{
						if (other.Phase == EmotePair.Phase.Offering)
						{
							num = 1;
							goto IL_00aa;
						}
						if (other.Phase == EmotePair.Phase.Paired)
						{
							num = ((other.Partner == lookup) ? 1 : 0);
							goto IL_009c;
						}
						num = 0;
					}
					else
					{
						if (other.Partner == lookup)
						{
							num = ((other.Phase == EmotePair.Phase.Paired) ? 1 : 0);
							goto IL_009c;
						}
						num = 0;
					}
				}
				else
				{
					num = 0;
				}
				goto IL_009f;
			}
			goto IL_00ad;
			IL_00ad:
			if (Link.Now == EmotePair.Phase.Offering && other.Phase == EmotePair.Phase.Offering && other.Shown == _current.NetId && lookup > player && Near(local, agent))
			{
				Link.Accept(player, Time.time);
				Meet(local, agent);
				_slot.Publish(new State
				{
					Id = _current.NetId,
					Seq = ++_seq,
					Phase = (byte)Link.Now,
					Partner = player
				}, _began);
			}
			else if (other.Shown == _current.NetId && other.Partner == lookup)
			{
				if (Link.Now == EmotePair.Phase.Offering && other.Phase == EmotePair.Phase.Accepting && Link.Pair(player, Distance(local, agent), SameDimension(local, agent)))
				{
					_began = Time.time - _current.Definition.PairHold;
					Players.Face(local, ((Agent)agent).Position);
					_slot.Publish(new State
					{
						Id = _current.NetId,
						Seq = ++_seq,
						Phase = 3,
						Partner = player
					}, _began);
				}
				else if (Link.Now == EmotePair.Phase.Accepting && Link.Partner == player && other.Phase == EmotePair.Phase.Paired)
				{
					Link.Seal();
					_began = other.Start;
					_slot.Publish(new State
					{
						Id = _current.NetId,
						Seq = ++_seq,
						Phase = 3,
						Partner = player
					}, _began);
				}
			}
			return;
			IL_009f:
			Stop(0.15f, cut: false);
			goto IL_00aa;
			IL_00aa:
			if (num == 0)
			{
				return;
			}
			goto IL_00ad;
			IL_009c:
			if (num == 0)
			{
				goto IL_009f;
			}
			goto IL_00aa;
		}

		private static void RetryWaiting()
		{
			_anyWaiting = false;
			foreach (var (player, watched2) in Others)
			{
				if (watched2.Waiting)
				{
					Seen(player, active: true);
				}
			}
		}

		private static void MotionChanged(PlayerAgent agent, PlayerMotion from, PlayerMotion to)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (!((Agent)agent).IsLocallyOwned && EmoteRules.Interrupts(to) && !((Object)(object)agent.Owner == (Object)null) && Others.TryGetValue(agent.Owner.Lookup, out Watched value))
			{
				value.Waiting = false;
				Forget(agent.Owner.Lookup, value, 0.1f);
			}
		}
	}
	internal static class EmoteWheel
	{
		private sealed class Memory
		{
			public List<string>? Favourites { get; set; }

			public List<string>? Recent { get; set; }
		}

		private static HudWheel? _wheel;

		private static readonly List<(WheelItem Item, EmoteDefinition Definition)> Items = new List<(WheelItem, EmoteDefinition)>();

		private static PlayerMotion _lastMotion = (PlayerMotion)11;

		private static readonly List<string> Favourites = new List<string>();

		private static readonly List<string> Recent = new List<string>();

		private static readonly List<string> PageKeys = new List<string>();

		private static bool _unsaved;

		private static Dictionary<string, string[]>? _playerPages;

		private static string? _playerProblem;

		internal static bool HoldsInput
		{
			get
			{
				HudWheel wheel = _wheel;
				if (wheel != null)
				{
					return wheel.HoldsInput;
				}
				return false;
			}
		}

		internal static bool IsOpen
		{
			get
			{
				HudWheel wheel = _wheel;
				if (wheel != null)
				{
					return wheel.IsOpen;
				}
				return false;
			}
		}

		internal static IReadOnlyList<string> Starred => Favourites;

		private static void LoadMemory()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			StoreRead<Memory> val = Store.Read<Memory>("NAinfini.ForgeEmote");
			if ((int)val.Status == 1)
			{
				Memory value = val.Value;
				if (value != null)
				{
					Favourites.AddRange(value.Favourites ?? new List<string>());
					Recent.AddRange(value.Recent ?? new List<string>());
				}
			}
		}

		private static void SaveMemory()
		{
			_unsaved = true;
		}

		internal static void Flush()
		{
			if (_unsaved && !IsOpen)
			{
				_unsaved = false;
				Store.Write<Memory>("NAinfini.ForgeEmote", new Memory
				{
					Favourites = Favourites,
					Recent = Recent
				});
			}
		}

		internal static void Used(string id)
		{
			if (EmoteRules.Remember(Recent, id))
			{
				SaveMemory();
				Fill();
			}
		}

		private static void Star(WheelItem item)
		{
			Toggle(item.Id);
		}

		internal static bool Toggle(string id)
		{
			if (!EmoteRules.Toggle(Favourites, id, Installed))
			{
				Plugin.Logger.ErrorOnce("ForgeEmote: the favourites page holds " + 8 + " actions; take one off first.");
				return false;
			}
			SaveMemory();
			Fill();
			return true;
		}

		private static bool Installed(string id)
		{
			return Emotes.Find(id) != null;
		}

		internal static bool IsFavourite(string id)
		{
			return Favourites.Contains(id);
		}

		internal static void Load()
		{
			UIKitMod val = UIKit.Mod("NAinfini.ForgeEmote");
			KeyAction val2 = val.AddKeyAction("Wheel", "keys.wheel", "keys.group", "H", (KeyMode)3, "on-foot", (KeyModes)31);
			if (val2 == null)
			{
				Plugin.Logger.Error("ForgeEmote: ForgeUI refused the wheel key; the wheel is off (see its error).");
				return;
			}
			_wheel = val.AddWheel("Wheel", val2);
			if (_wheel == null)
			{
				return;
			}
			_wheel.Chosen += delegate(WheelItem item)
			{
				Emotes.Entry entry = Emotes.Find(item.Id);
				if (entry != null)
				{
					EmoteRunner.Start(entry);
				}
			};
			_wheel.Secondary += Star;
			LoadMemory();
			ReadPlayerFile();
			_wheel.CanOpen = delegate
			{
				PlayerAgent local = Players.Local;
				return local != null && ((Agent)local).Alive;
			};
			Emotes.Changed += Fill;
			UIKit.LanguageChanged += Fill;
			Fill();
		}

		private static void ReadPlayerFile()
		{
			//IL_0165: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			string text = Path.Combine(Paths.ConfigPath, "ForgeEmote", "wheel.forge");
			if (!File.Exists(text))
			{
				return;
			}
			try
			{
				using JsonDocument jsonDocument = JsonDocument.Parse(File.ReadAllText(text));
				JsonElement rootElement = jsonDocument.RootElement;
				if (rootElement.ValueKind != JsonValueKind.Object)
				{
					throw new StrictJsonException("", "must be an object of page names to action lists.");
				}
				StrictJson.UniqueMembers(rootElement, "");
				Dictionary<string, string[]> dictionary = new Dictionary<string, string[]>();
				foreach (JsonProperty item in rootElement.EnumerateObject())
				{
					if (item.Value.ValueKind != JsonValueKind.Array)
					{
						throw new StrictJsonException(item.Name, "must be a list of action IDs.");
					}
					List<string> list = new List<string>();
					foreach (JsonElement item2 in item.Value.EnumerateArray())
					{
						if (item2.ValueKind != JsonValueKind.String)
						{
							throw new StrictJsonException(item.Name, "must hold only action IDs (text).");
						}
						list.Add(item2.GetString());
					}
					dictionary[item.Name] = list.ToArray();
				}
				_playerPages = dictionary;
			}
			catch (StrictJsonException ex)
			{
				StrictJsonException ex2 = ex;
				_playerProblem = text + ": " + ((ex2.Field.Length == 0) ? "" : (ex2.Field + " ")) + ((Exception)(object)ex2).Message;
			}
			catch (Exception ex3) when (((ex3 is IOException || ex3 is JsonException) ? 1 : 0) != 0)
			{
				_playerProblem = text + ": " + ex3.Message;
			}
		}

		private static void Fill()
		{
			//IL_00ab: 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_012b: Expected O, but got Unknown
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Expected O, but got Unknown
			if (_wheel == null)
			{
				return;
			}
			List<string> list = new List<string>();
			if (_playerProblem != null)
			{
				list.Add(_playerProblem);
			}
			string text = ((_wheel.Page < PageKeys.Count) ? PageKeys[_wheel.Page] : null);
			List<EmoteDefinition> list2 = new List<EmoteDefinition>();
			foreach (Emotes.Entry entry2 in Emotes.Entries)
			{
				list2.Add(entry2.Definition);
			}
			List<WheelPage> list3 = new List<WheelPage>();
			Items.Clear();
			PageKeys.Clear();
			_lastMotion = (PlayerMotion)11;
			List<string> list4 = EmoteRules.FavouritePage(Favourites, Recent, Installed);
			if (list4.Count > 0)
			{
				list3.Add(new WheelPage(UIText.Key("page.favorites", Array.Empty<object>()), Make(list4.Select((string id) => Emotes.Find(id).Definition))));
				PageKeys.Add("favorites");
			}
			foreach (var (text2, list5) in EmoteRules.Arrange(list2, _playerPages, list))
			{
				bool flag;
				switch (text2)
				{
				case "tactical":
				case "gesture":
				case "dance":
					flag = true;
					break;
				default:
					flag = false;
					break;
				}
				UIText val = (flag ? UIText.Key("page." + text2, Array.Empty<object>()) : UIText.op_Implicit(Emotes.Find(list5[0].Id).Texts.Text("page." + text2)));
				list3.Add(new WheelPage(val, Make(list5)));
				PageKeys.Add(text2);
			}
			_wheel.SetPages(list3.ToArray());
			int num = ((text == null) ? (-1) : PageKeys.IndexOf(text));
			if (num >= 0)
			{
				_wheel.Page = num;
			}
			foreach (string item in list)
			{
				Plugin.Logger.ErrorOnce("ForgeEmote: " + item);
			}
			static WheelItem[] Make(IEnumerable<EmoteDefinition> chosen)
			{
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				//IL_005f: Expected O, but got Unknown
				List<WheelItem> list6 = new List<WheelItem>();
				foreach (EmoteDefinition item2 in chosen)
				{
					Emotes.Entry entry = Emotes.Find(item2.Id);
					Sprite val2 = ((item2.Icon == null) ? null : UIKit.Icon(item2.Icon));
					WheelItem val3 = new WheelItem(item2.Id, UIText.op_Implicit(entry.Texts.Text(item2.Name)), val2);
					list6.Add(val3);
					Items.Add((val3, item2));
				}
				return list6.ToArray();
			}
		}

		internal static void Highlight(HashSet<string> ids)
		{
			HudWheel? wheel = _wheel;
			if (wheel != null)
			{
				wheel.Highlight(ids);
			}
		}

		internal static void Refresh(PlayerMotion motion)
		{
			//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_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			if (motion == _lastMotion)
			{
				return;
			}
			_lastMotion = motion;
			foreach (var (val, emoteDefinition) in Items)
			{
				val.Usable = EmoteRules.CanStart(motion, emoteDefinition.Move);
			}
		}
	}
	[BepInPlugin("NAinfini.ForgeEmote", "Forge Emote", "1.0.0")]
	[BepInDependency("NAinfini.ForgeCore", ">=1.0.0")]
	[BepInDependency("NAinfini.ForgeUI", ">=1.0.0")]
	[BepInDependency("NAinfini.ForgeVisual", ">=1.0.0")]
	[BepInDependency("NAinfini.ForgeAudio", ">=1.0.0")]
	internal sealed class Plugin : BasePlugin
	{
		internal const string Id = "NAinfini.ForgeEmote";

		internal const string Version = "1.0.0";

		internal static ConfigEntry<bool> Readback;

		internal static ConfigEntry<bool> ThirdPerson;

		internal static ConfigEntry<bool> ThirdPersonGestures;

		internal static ConfigEntry<bool> Orbit;

		internal static ConfigEntry<bool> CrudeGestures;

		internal static ConfigEntry<float> Distance;

		internal static ConfigEntry<float> Shoulder;

		internal static ConfigEntry<float> Height;

		internal static ConfigEntry<float> BlendSeconds;

		internal static ModLog Logger { get; private set; }

		internal static ManualLogSource Info { get; private set; }

		public override void Load()
		{
			Logger = Log.For("NAinfini.ForgeEmote");
			Info = ((BasePlugin)this).Log;
			Readback = ((BasePlugin)this).Config.Bind<bool>("Debug", "Readback", false, "Write one line of body heights to the log at the start and end of your own actions and one second after (for finding why a body floats). Off by default.");
			ThirdPerson = ((BasePlugin)this).Config.Bind<bool>("View", "ThirdPerson", true, "Dances switch to a view of yourself from behind; every other action stays in first person. Off: dances stay in first person too.");
			ThirdPersonGestures = ((BasePlugin)this).Config.Bind<bool>("View", "ThirdPersonGestures", false, "Gestures also switch to the view from behind. Off: gestures stay in first person.");
			Distance = ((BasePlugin)this).Config.Bind<float>("View", "Distance", 2.4f, "How far behind you the view stands, in metres.");
			Shoulder = ((BasePlugin)this).Config.Bind<float>("View", "Shoulder", 0.35f, "How far to the side of you the view stands, in metres.");
			Height = ((BasePlugin)this).Config.Bind<float>("View", "Height", 0.25f, "How far above your head the view looks from, in metres.");
			BlendSeconds = ((BasePlugin)this).Config.Bind<float>("View", "BlendSeconds", 0.3f, "Seconds the view takes to move out and back.");
			Orbit = ((BasePlugin)this).Config.Bind<bool>("View", "Orbit", true, "The mouse turns the view around you during an action.");
			CrudeGestures = ((BasePlugin)this).Config.Bind<bool>("Display", "CrudeGestures", true, "Show rude gestures other players make. Off: they keep their normal animation on your screen.");
			Emotes.Load();
			EmoteWheel.Load();
			EmoteRunner.Load();
			Frame.OnUpdate("NAinfini.ForgeEmote", (Action)EmoteRunner.Update);
			Frame.OnLateUpdate("NAinfini.ForgeEmote", (Action)EmoteRunner.LateUpdate);
		}

		public override bool Unload()
		{
			return false;
		}
	}
}
namespace ForgeEmote.Api
{
	public enum EmoteView
	{
		FirstPerson,
		ThirdPerson
	}
	public enum EmoteMove
	{
		Free,
		Locked
	}
	public sealed class EmoteDefinition
	{
		public string Id { get; init; } = "";

		public string Name { get; init; } = "";

		public string? Icon { get; init; }

		public string Page { get; init; } = "";

		public int Slot { get; init; }

		public string Clip { get; init; } = "";

		public string? FirstPersonClip { get; init; }

		public string Body { get; init; } = "upper";

		public bool Loop { get; init; }

		public float FadeIn { get; init; } = 0.15f;

		public float FadeOut { get; init; } = 0.2f;

		public EmoteView View { get; init; }

		public EmoteMove Move { get; init; }

		public bool HideHeld { get; init; }

		public bool CancelOnHit { get; init; }

		public bool Crude { get; init; }

		public uint Comms { get; init; }

		public bool Ping { get; init; }

		public string? Sound { get; init; }

		public bool Pair { get; init; }

		public float PairHold { get; init; }

		public string Folder { get; init; } = "";
	}
	public static class Emotes
	{
		internal sealed class Entry
		{
			internal EmoteDefinition Definition;

			internal JointClip Clip;

			internal JointClip? FirstPerson;

			internal JointMask Mask;

			internal JointMask FirstPersonMask;

			internal uint NetId;

			internal string Hash = "";

			internal UITexts Texts;

			internal AudioLibrary? Audio;

			internal AudioHandle? PlaySound(PlayerAgent agent, float start)
			{
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				//IL_0076: Unknown result type (might be due to invalid IL or missing references)
				//IL_0087: Expected O, but got Unknown
				//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)
				if (Audio == null)
				{
					return null;
				}
				float num = Time.time - start - (Definition.Pair ? Definition.PairHold : 0f);
				if (!Definition.Loop && num > 0.5f)
				{
					return null;
				}
				AudioLibrary? audio = Audio;
				string? sound = Definition.Sound;
				Transform transform = ((Component)agent).transform;
				PlayOptions val = new PlayOptions();
				val.set_StartSeconds(Mathf.Max(0f, num));
				val.set_IsSelf(((Agent)agent).IsLocallyOwned);
				PlayResult val2 = audio.Play(sound, transform, val);
				if (!((PlayResult)(ref val2)).Accepted)
				{
					return null;
				}
				return ((PlayResult)(ref val2)).Handle;
			}
		}

		private const float SoundJoinSeconds = 0.5f;

		private static readonly List<Entry> All = new List<Entry>();

		private static readonly Dictionary<uint, Entry> ByNet = new Dictionary<uint, Entry>();

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

		private static bool _closed;

		internal static IReadOnlyList<Entry> Entries => All;

		internal static bool Closed => _closed;

		internal static event Action? Changed;

		internal static Entry? Find(uint netId)
		{
			if (!ByNet.TryGetValue(netId, out Entry value))
			{
				return null;
			}
			return value;
		}

		internal static Entry? Find(string id)
		{
			return All.FirstOrDefault((Entry entry) => entry.Definition.Id == id);
		}

		public static bool Register(EmoteDefinition definition, out string? error)
		{
			error = null;
			if (definition == null)
			{
				error = "definition is null";
				return false;
			}
			if (_closed)
			{
				error = "registration has closed";
				return false;
			}
			(string, string)? tuple = EmoteRules.Validate(definition);
			if (tuple.HasValue)
			{
				(string, string) valueOrDefault = tuple.GetValueOrDefault();
				error = definition.Id + ": " + valueOrDefault.Item2;
				return false;
			}
			try
			{
				uint num = Fnv.Hash32(definition.Id);
				if (ByNet.TryGetValue(num, out Entry value))
				{
					error = ((value.Definition.Id == definition.Id) ? (definition.Id + " is already registered") : (definition.Id + " has the same number as " + value.Definition.Id));
					return false;
				}
				byte[] array = File.ReadAllBytes(Path.Combine(definition.Folder, definition.Clip));
				byte[] array2 = ((definition.FirstPersonClip == null) ? null : File.ReadAllBytes(Path.Combine(definition.Folder, definition.FirstPersonClip)));
				string text = Encoding.UTF8.GetString(array);
				string text2 = ((array2 == null) ? null : Encoding.UTF8.GetString(array2));
				using IncrementalHash incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
				incrementalHash.AppendData(array);
				if (array2 != null)
				{
					incrementalHash.AppendData(array2);
				}
				if (definition.Sound != null)
				{
					incrementalHash.AppendData(Encoding.UTF8.GetBytes(definition.Sound));
				}
				Encoding uTF = Encoding.UTF8;
				IFormatProvider invariantCulture = CultureInfo.InvariantCulture;
				DefaultInterpolatedStringHandler handler = new DefaultInterpolatedStringHandler(3, 4, invariantCulture);
				handler.AppendFormatted(definition.Loop);
				handler.AppendLiteral("|");
				handler.AppendFormatted(definition.Body);
				handler.AppendLiteral("|");
				handler.AppendFormatted(definition.Pair);
				handler.AppendLiteral("|");
				handler.AppendFormatted(definition.PairHold);
				incrementalHash.AppendData(uTF.GetBytes(string.Create(invariantCulture, ref handler)));
				JointClip val = JointClip.Parse(text, "NAinfini.ForgeEmote/" + definition.Id);
				if (definition.Pair && definition.PairHold >= val.Duration)
				{
					error = definition.Id + ": PairHold must be less than the clip's length (" + val.Duration.ToString("0.##", CultureInfo.InvariantCulture) + " s).";
					return false;
				}
				if (definition.Body == "full")
				{
					val.SeatOnFloor();
				}
				Entry entry = new Entry();
				entry.Definition = definition;
				entry.Clip = val;
				entry.FirstPerson = ((text2 == null) ? null : JointClip.Parse(text2));
				entry.Mask = MaskOf(definition.Body);
				Entry entry2 = entry;
				string body = definition.Body;
				bool flag = ((body == "left-arm" || body == "right-arm") ? true : false);
				entry2.FirstPersonMask = MaskOf(flag ? definition.Body : "arms");
				entry.NetId = num;
				entry.Hash = Convert.ToHexString(incrementalHash.GetHashAndReset());
				entry.Texts = UIKit.Texts(Path.Combine(definition.Folder, "lang"));
				entry.Audio = ((definition.Sound == null) ? null : LibraryOf(definition));
				Entry entry3 = entry;
				All.Add(entry3);
				ByNet.Add(num, entry3);
				Emotes.Changed?.Invoke();
				return true;
			}
			catch (Exception ex) when (((ex is IOException || ex is FormatException || ex is UnauthorizedAccessException || ex is ArgumentException || ex is JsonException || ex is InvalidOperationException) ? 1 : 0) != 0)
			{
				error = definition.Id + ": " + ex.Message;
				return false;
			}
		}

		internal static void Close()
		{
			_closed = true;
		}

		private static AudioLibrary LibraryOf(EmoteDefinition definition)
		{
			if (Libraries.TryGetValue(definition.Folder, out AudioLibrary value))
			{
				return value;
			}
			string text = Regex.Replace(definition.Id.Substring(0, definition.Id.IndexOf(':')), "[^A-Za-z0-9_.-]", "_");
			value = AudioKit.Load("NAinfini.ForgeEmote." + text, Path.Combine(definition.Folder, "audio"));
			Libraries.Add(definition.Folder, value);
			return value;
		}

		private static JointMask MaskOf(string body)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: 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)
			return (JointMask)(body switch
			{
				"left-arm" => new JointMask().Add((BodyPart)6, 1f), 
				"right-arm" => new JointMask().Add((BodyPart)7, 1f), 
				"arms" => new JointMask().Add((BodyPart)6, 1f).Add((BodyPart)7, 1f), 
				"upper" => JointMask.UpperBody, 
				_ => JointMask.FullBody, 
			});
		}

		internal static void Load()
		{
			string text = Path.Combine(Path.GetDirectoryName(typeof(Emotes).Assembly.Location), "ForgeEmote", "Icons");
			List<string> list = new List<string>();
			if (Directory.Exists(text))
			{
				string[] files = Directory.GetFiles(text, "*.png");
				foreach (string path in files)
				{
					list.Add(Path.GetFileNameWithoutExtension(path));
				}
			}
			if (list.Count > 0)
			{
				IconPack obj = UIKit.Mod("NAinfini.ForgeEmote").Icons("ForgeEmote");
				if (obj != null)
				{
					obj.RegisterFolder(text, list.ToArray());
				}
			}
			List<string> list2 = new List<string>();
			foreach (string item in ContentFolders.Find("ForgeEmote", list2))
			{
				string[] files = Directory.GetFiles(item, "*.emote.forge");
				foreach (string text2 in files)
				{
					try
					{
						foreach (EmoteDefinition item2 in EmoteFile.Parse(File.ReadAllText(text2), item))
						{
							if (!Register(item2, out string error))
							{
								Report(text2, error);
							}
						}
					}
					catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException || ex is StrictJsonException || ex is JsonException) ? 1 : 0) != 0)
					{
						Report(text2, ex.Message);
					}
				}
			}
			foreach (string item3 in list2)
			{
				Plugin.Logger.Error("ForgeEmote: " + item3);
			}
		}

		private static void Report(string file, string reason)
		{
			Plugin.Logger.Error("ForgeEmote " + Path.GetFileName(file) + ": " + reason);
		}
	}
}