Decompiled source of CrowdControl UltraKill v1.3.1

BepInEx/plugins/CrowdControl/ConnectorLib.JSON.dll

Decompiled 10 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Warp World, Inc.")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© 2025 Warp World, Inc.")]
[assembly: AssemblyFileVersion("5.0.9701.42276")]
[assembly: AssemblyInformationalVersion("5.0.9701.42276+b34ccf365517177630fa9cf7cf6057a6c609ff58")]
[assembly: AssemblyProduct("ConnectorLib.JSON")]
[assembly: AssemblyTitle("ConnectorLib.JSON")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.0.9701.42276")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[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 ConnectorLib.JSON
{
	internal class AnnotatedEnumConverter<T> : JsonConverter<T> where T : unmanaged, Enum
	{
		[AttributeUsage(AttributeTargets.Field)]
		public class JsonValueAttribute(string value) : Attribute()
		{
			public readonly string Value = value;
		}

		private static readonly Dictionary<T, JsonValueAttribute?> _attributes;

		static AnnotatedEnumConverter()
		{
			_attributes = ((T[])Enum.GetValues(typeof(T))).Select((T m) => new KeyValuePair<T, JsonValueAttribute>(m, GetAttributeOfType<JsonValueAttribute>(m))).ToDictionary();
		}

		private static T? GetAttributeOfType<T>(Enum enumVal) where T : Attribute
		{
			object[] array = enumVal.GetType().GetTypeInfo().DeclaredMembers.First((MemberInfo m) => string.Equals(m.Name, enumVal.ToString(), StringComparison.Ordinal)).GetCustomAttributes(typeof(T), inherit: false).ToArray();
			if (array.Length == 0)
			{
				return null;
			}
			return (T)array[0];
		}

		public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
		{
			JsonValueAttribute jsonValueAttribute = _attributes[value];
			if (jsonValueAttribute != null)
			{
				serializer.Serialize(writer, (object)jsonValueAttribute.Value);
			}
			else
			{
				serializer.Serialize(writer, (object)Enum.GetName(typeof(T), value));
			}
		}

		public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			string value = serializer.Deserialize<string>(reader);
			if (value == null)
			{
				return default(T);
			}
			KeyValuePair<T, JsonValueAttribute>? keyValuePair = _attributes.Cast<KeyValuePair<T, JsonValueAttribute>?>().FirstOrDefault((KeyValuePair<T, JsonValueAttribute>? a) => a?.Value?.Value?.Equals(value, StringComparison.OrdinalIgnoreCase) == true);
			if (keyValuePair.HasValue)
			{
				return keyValuePair.Value.Key;
			}
			if (Enum.TryParse<T>(value, ignoreCase: true, out var result))
			{
				return result;
			}
			return default(T);
		}
	}
	public class CamelCaseStringEnumConverter : JsonConverter<Enum>
	{
		public override void WriteJson(JsonWriter writer, Enum? value, JsonSerializer serializer)
		{
			if (value == null)
			{
				serializer.Serialize(writer, (object)null);
			}
			else
			{
				serializer.Serialize(writer, (object)value.ToCamelCase());
			}
		}

		public override Enum ReadJson(JsonReader reader, Type objectType, Enum? existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			return ReadJToken(JToken.ReadFrom(reader), objectType);
		}

		public static Enum ReadJToken(JToken reader, Type objectType)
		{
			//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_0009: Invalid comparison between Unknown and I4
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			JTokenType type = reader.Type;
			if ((int)type != 6)
			{
				if ((int)type == 8)
				{
					string text = Extensions.Value<string>((IEnumerable<JToken>)reader);
					if (text == null)
					{
						throw new SerializationException("The value was null.");
					}
					if (Enum.TryParse(objectType, text, ignoreCase: true, out object result))
					{
						return (Enum)result;
					}
					throw new SerializationException("The value was not recognized.");
				}
				throw new SerializationException("The value was not a string or number.");
			}
			int? num = Extensions.Value<int>((IEnumerable<JToken>)reader);
			if (!num.HasValue)
			{
				throw new SerializationException("The value was null.");
			}
			return (Enum)Enum.ToObject(objectType, num.Value);
		}
	}
	[Serializable]
	public class DataRequest : SimpleJSONRequest
	{
		public string key;

		public DataRequest(string key)
		{
			this.key = key;
			type = RequestType.DataRequest;
		}
	}
	[Serializable]
	public class DataResponse : SimpleJSONResponse
	{
		public string key;

		public JToken? value;

		public EffectStatus status;

		public long timeRemaining;

		public string? message;

		[JsonConstructor]
		public DataResponse(string key, EffectStatus status, object? value = null, long timeRemaining = 0L, string? message = null)
		{
			this.key = key;
			this.value = value.IfNotNull((Func<object, JToken?>)JToken.FromObject);
			this.status = status;
			this.timeRemaining = timeRemaining;
			this.message = message;
			type = ResponseType.DataResponse;
		}

		public static DataResponse SuccessIfDefined(string key, object? value, string failMessage = "")
		{
			if (value == null)
			{
				return Retry(key, 0L, failMessage);
			}
			if (value is string input && input.IsNullOrWhiteSpace())
			{
				return Retry(key, 0L, failMessage);
			}
			return Success(key, value);
		}

		public static DataResponse Success(string key, object? value)
		{
			return new DataResponse(key, EffectStatus.Success, value, 0L);
		}

		public static DataResponse Success(string key, object? value, string? message)
		{
			return new DataResponse(key, EffectStatus.Success, value, 0L, message);
		}

		public static DataResponse Failure(string key)
		{
			return new DataResponse(key, EffectStatus.Failure, null, 0L);
		}

		public static DataResponse Failure(string key, string? message)
		{
			return new DataResponse(key, EffectStatus.Failure, null, 0L, message);
		}

		public static DataResponse Failure(string key, object? value, string? message = null)
		{
			return new DataResponse(key, EffectStatus.Failure, value, 0L, message);
		}

		public static DataResponse Retry(string key, long delay = 0L, string? message = null)
		{
			return new DataResponse(key, EffectStatus.Retry, null, delay, message);
		}
	}
	[Serializable]
	public class EffectRequest : SimpleJSONRequest
	{
		[Serializable]
		public class Target
		{
			public string? service;

			public string? id;

			public string? name;

			public string? avatar;
		}

		public string? code;

		public string? message;

		public JToken? parameters;

		public uint? quantity;

		public JArray? targets;

		public long? duration;

		public string? viewer;

		public JArray? viewers;

		public long? cost;

		public Guid? requestID;

		[JsonConverter(typeof(IEffectSourceDetails.Converter))]
		public IEffectSourceDetails? sourceDetails;

		public EffectRequest()
		{
			type = RequestType.Start;
		}
	}
	[Serializable]
	public class EffectResponse : SimpleJSONResponse
	{
		private class MetadataConverter : JsonConverter<Dictionary<string, DataResponse>?>
		{
			public override void WriteJson(JsonWriter writer, Dictionary<string, DataResponse>? value, JsonSerializer serializer)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Expected O, but got Unknown
				if (value == null)
				{
					serializer.Serialize(writer, (object)null);
					return;
				}
				JObject val = new JObject();
				foreach (KeyValuePair<string, DataResponse> item in value)
				{
					JObject val2 = JObject.FromObject((object)item.Value);
					val2.Remove("key");
					val[item.Key] = (JToken)(object)val2;
				}
				serializer.Serialize(writer, (object)val);
			}

			public override Dictionary<string, DataResponse>? ReadJson(JsonReader reader, Type objectType, Dictionary<string, DataResponse>? existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Expected O, but got Unknown
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_003b: Expected O, but got Unknown
				JObject val = (JObject)serializer.Deserialize(reader);
				if (val == null)
				{
					return null;
				}
				Dictionary<string, DataResponse> dictionary = new Dictionary<string, DataResponse>();
				foreach (JProperty item in val.Properties())
				{
					JObject val2 = (JObject)item.Value;
					val2["key"] = JToken.op_Implicit(item.Name);
					dictionary.Add(item.Name, ((JToken)val2).ToObject<DataResponse>());
				}
				return dictionary;
			}
		}

		public EffectStatus status;

		public string? message;

		public StandardErrors messageID;

		public long timeRemaining;

		[JsonConverter(typeof(MetadataConverter))]
		public Dictionary<string, DataResponse>? metadata;

		public EffectResponse()
		{
		}

		public EffectResponse(uint id, EffectStatus status)
			: this(id, status, 0L, null)
		{
		}

		public EffectResponse(uint id, EffectStatus status, StandardErrors messageID)
			: this(id, status, 0L, messageID)
		{
		}

		public EffectResponse(uint id, EffectStatus status, string? message)
			: this(id, status, 0L, message)
		{
		}

		public EffectResponse(uint id, EffectStatus status, TimeSpan timeRemaining)
			: this(id, status, checked((long)timeRemaining.TotalMilliseconds), null)
		{
		}

		public EffectResponse(uint id, EffectStatus status, TimeSpan timeRemaining, StandardErrors messageID)
			: this(id, status, checked((long)timeRemaining.TotalMilliseconds), messageID)
		{
		}

		public EffectResponse(uint id, EffectStatus status, TimeSpan timeRemaining, string? message)
			: this(id, status, checked((long)timeRemaining.TotalMilliseconds), message)
		{
		}

		public EffectResponse(uint id, EffectStatus status, long timeRemaining)
			: this(id, status, timeRemaining, null)
		{
		}

		public EffectResponse(uint id, EffectStatus status, long timeRemaining, StandardErrors messageID)
			: this(id, status, timeRemaining)
		{
			this.messageID = messageID;
		}

		[JsonConstructor]
		public EffectResponse(uint id, EffectStatus status, long timeRemaining, string? message)
		{
			base.id = id;
			this.status = status;
			this.timeRemaining = timeRemaining;
			this.message = message;
			type = ResponseType.EffectRequest;
		}

		public static EffectResponse Success(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Success, message);
		}

		public static EffectResponse Success(uint id, long delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Success, delay, message);
		}

		public static EffectResponse Success(uint id, TimeSpan delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Success, delay, message);
		}

		public static EffectResponse Failure(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Failure, message);
		}

		public static EffectResponse Failure(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Failure, error);
		}

		public static EffectResponse Unavailable(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Unavailable, message);
		}

		public static EffectResponse Unavailable(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Unavailable, error);
		}

		public static EffectResponse Retry(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Retry, 0L, message);
		}

		public static EffectResponse Retry(uint id, long delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, message);
		}

		public static EffectResponse Retry(uint id, TimeSpan delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, message);
		}

		public static EffectResponse Retry(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Retry, 0L, error);
		}

		public static EffectResponse Retry(uint id, long delay, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, error);
		}

		public static EffectResponse Retry(uint id, TimeSpan delay, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, error);
		}

		public static EffectResponse Paused(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Paused, 0L, message);
		}

		public static EffectResponse Paused(uint id, long timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, message);
		}

		public static EffectResponse Paused(uint id, TimeSpan timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, message);
		}

		public static EffectResponse Paused(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Paused, 0L, error);
		}

		public static EffectResponse Paused(uint id, long timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, error);
		}

		public static EffectResponse Paused(uint id, TimeSpan timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, error);
		}

		public static EffectResponse Resumed(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Resumed, 0L, message);
		}

		public static EffectResponse Resumed(uint id, long timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, message);
		}

		public static EffectResponse Resumed(uint id, TimeSpan timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, message);
		}

		public static EffectResponse Resumed(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Resumed, 0L, error);
		}

		public static EffectResponse Resumed(uint id, long timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, error);
		}

		public static EffectResponse Resumed(uint id, TimeSpan timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, error);
		}

		public static EffectResponse Finished(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Finished, 0L, message);
		}

		public static EffectResponse Finished(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Finished, 0L, error);
		}
	}
	public interface IEffectSourceDetails
	{
		public class Converter : JsonConverter<IEffectSourceDetails?>
		{
			public static readonly Converter Instance = new Converter();

			public override IEffectSourceDetails? ReadJson(JsonReader reader, Type objectType, IEffectSourceDetails? existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Invalid comparison between Unknown and I4
				if ((int)reader.TokenType == 11)
				{
					return null;
				}
				JObject val = JObject.Load(reader);
				JToken obj = val["type"];
				return ((obj != null) ? Extensions.Value<string>((IEnumerable<JToken>)obj) : null) switch
				{
					"twitch-channel-reward" => ((JToken)val).ToObject<TwitchChannelRewardSourceDetails>(), 
					"stream-labs-donation" => ((JToken)val).ToObject<StreamLabsDonationSourceDetails>(), 
					"event-hype-train" => ((JToken)val).ToObject<HypeTrainSourceDetails>(), 
					"tiktok-gift" => ((JToken)val).ToObject<TikTokGiftSourceDetails>(), 
					"tiktok-like" => ((JToken)val).ToObject<TikTokLikeSourceDetails>(), 
					"tiktok-follow" => ((JToken)val).ToObject<TikTokFollowSourceDetails>(), 
					"tiktok-share" => ((JToken)val).ToObject<TikTokShareSourceDetails>(), 
					"pulsoid-trigger" => ((JToken)val).ToObject<PulsoidTriggerSourceDetails>(), 
					"crowd-control-test" => ((JToken)val).ToObject<CrowdControlTestSourceDetails>(), 
					"crowd-control-chaos-mode" => ((JToken)val).ToObject<CrowdControlChaosModeSourceDetails>(), 
					"crowd-control-retry" => ((JToken)val).ToObject<CrowdControlRetrySourceDetails>(), 
					_ => null, 
				};
			}

			public override void WriteJson(JsonWriter writer, IEffectSourceDetails? value, JsonSerializer serializer)
			{
				serializer.Serialize(writer, (object)((value == null) ? null : JObject.FromObject((object)value)));
			}
		}

		[JsonProperty("type")]
		string Type { get; }
	}
	public class TwitchChannelRewardSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "twitch-channel-reward";

		[JsonProperty("rewardID")]
		public string RewardID { get; set; }

		[JsonProperty("redemptionID")]
		public string RedemptionID { get; set; }

		[JsonProperty("twitchID")]
		public string TwitchID { get; set; }

		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("cost")]
		public int Cost { get; set; }
	}
	public class StreamLabsDonationSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "stream-labs-donation";

		[JsonProperty("donationID")]
		public string DonationID { get; set; }

		[JsonProperty("cost")]
		public string Cost { get; set; }

		[JsonProperty("currency")]
		public string Currency { get; set; }

		[JsonProperty("name")]
		public string? Name { get; set; }

		[JsonProperty("message")]
		public string? Message { get; set; }
	}
	public class HypeTrainSourceDetails : IEffectSourceDetails
	{
		public class Contribution
		{
			[JsonProperty("user_id")]
			public string UserID { get; set; }

			[JsonProperty("user_login")]
			public string UserLogin { get; set; }

			[JsonProperty("user_name")]
			public string UserName { get; set; }

			[JsonProperty("type")]
			public string Type { get; set; }

			[JsonProperty("total")]
			public int Total { get; set; }
		}

		[JsonProperty("type")]
		public string Type => "event-hype-train";

		[JsonProperty("total")]
		public int Total { get; set; }

		[JsonProperty("progress")]
		public int Progress { get; set; }

		[JsonProperty("goal")]
		public int Goal { get; set; }

		[JsonProperty("top_contributions")]
		public List<Contribution> TopContributions { get; set; }

		[JsonProperty("last_contribution")]
		public Contribution LastContribution { get; set; }

		[JsonProperty("level")]
		public int Level { get; set; }
	}
	public abstract class TikTokSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public abstract string Type { get; }

		[JsonProperty("cost")]
		public int Cost { get; set; }

		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("userID")]
		public string UserID { get; set; }
	}
	public class TikTokGiftSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-gift";

		[JsonProperty("giftID")]
		public int GiftID { get; set; }

		[JsonProperty("giftName")]
		public string GiftName { get; set; }

		[JsonProperty("transactionID")]
		public string? TransactionID { get; set; }
	}
	public class TikTokLikeSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-like";
	}
	public class TikTokFollowSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-follow";
	}
	public class TikTokShareSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-share";
	}
	public class PulsoidTriggerSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "pulsoid-trigger";

		[JsonProperty("heartRate")]
		public int HeartRate { get; set; }

		[JsonProperty("uuid")]
		public Guid Uuid { get; set; }

		[JsonProperty("triggerType")]
		public string TriggerType { get; set; }

		[JsonProperty("targetHeartRate")]
		public int TargetHeartRate { get; set; }

		[JsonProperty("holdTime")]
		public int HoldTime { get; set; }

		[JsonProperty("cooldown")]
		public int Cooldown { get; set; }
	}
	public class CrowdControlTestSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "crowd-control-test";
	}
	public class CrowdControlChaosModeSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "crowd-control-chaos-mode";
	}
	public class CrowdControlRetrySourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "crowd-control-retry";
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum EffectStatus
	{
		Success = 0,
		Failure = 1,
		Unavailable = 2,
		Retry = 3,
		Queue = 4,
		Running = 5,
		Paused = 6,
		Resumed = 7,
		Finished = 8,
		Wait = 9,
		RemoteScheduled = 10,
		Visible = 128,
		NotVisible = 129,
		Selectable = 130,
		NotSelectable = 131,
		Reserved0 = 160,
		NotReady = 255
	}
	[Serializable]
	public class EffectUpdate : SimpleJSONResponse
	{
		[JsonConverter(typeof(CamelCaseStringEnumConverter))]
		public enum IdentifierType
		{
			Effect,
			Group,
			Category
		}

		[Obsolete("This field is deprecated. Please use the ids field instead.")]
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string? code;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string[]? ids;

		public IdentifierType idType;

		public EffectStatus status;

		public string? message;

		public EffectUpdate()
		{
		}

		public EffectUpdate(string code, EffectStatus status, string? message = null)
		{
			ids = new string[1] { code };
			idType = IdentifierType.Effect;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}

		public EffectUpdate(string[] ids, EffectStatus status, string? message = null)
		{
			this.ids = ids;
			idType = IdentifierType.Effect;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}

		public EffectUpdate(IEnumerable<string> ids, EffectStatus status, string? message = null)
		{
			this.ids = ids.ToArray();
			idType = IdentifierType.Effect;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}
	}
	[Serializable]
	public class EmptyRequest : SimpleJSONRequest
	{
	}
	[Serializable]
	public class EmptyResponse : SimpleJSONResponse
	{
	}
	internal static class EnumEx
	{
		internal static string ToCamelCase(this Enum value)
		{
			return value.ToString("G").ToCamelCase();
		}
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum GameState
	{
		Unknown = 0,
		Ready = 1,
		Error = -1,
		Unmodded = -2,
		BadGameSettings = -3,
		WrongVersion = -4,
		NotFocused = -5,
		Loading = -6,
		Paused = -7,
		WrongMode = -8,
		SafeArea = -9,
		UntimedArea = -10,
		Cutscene = -11,
		BadPlayerState = -12,
		Menu = -13,
		Map = -14,
		InCombat = -15,
		NotInCombat = -16,
		PipelineBusy = -128
	}
	[Serializable]
	public class GameUpdate : SimpleJSONResponse
	{
		public GameState state;

		public string? message;

		public GameUpdate(GameState state, string? message = null)
		{
			this.state = state;
			this.message = message;
			type = ResponseType.GameUpdate;
		}
	}
	[Serializable]
	public class GenericEventRequest : SimpleJSONRequest
	{
		[JsonProperty(PropertyName = "internal")]
		public bool @internal;

		public string eventType;

		public Dictionary<string, object>? data;

		public GenericEventRequest(string eventType)
		{
			type = RequestType.GenericEvent;
			this.eventType = eventType;
		}

		[JsonConstructor]
		public GenericEventRequest(string eventType, IEnumerable<KeyValuePair<string, object>>? data)
			: this(eventType)
		{
			this.data = ((data != null) ? data.ToDictionary() : null);
		}

		[JsonConstructor]
		public GenericEventRequest(string eventType, IEnumerable<KeyValuePair<string, object>>? data, bool @internal)
			: this(eventType, data)
		{
			this.@internal = @internal;
		}
	}
	[Serializable]
	public class GenericEventResponse : SimpleJSONResponse
	{
		[JsonProperty(PropertyName = "internal")]
		public bool @internal;

		public string eventType;

		public Dictionary<string, object>? data;

		public GenericEventResponse(string eventType)
		{
			type = ResponseType.GenericEvent;
			this.eventType = eventType;
		}

		public GenericEventResponse(string eventType, IEnumerable<KeyValuePair<string, object>>? data, bool @internal = false)
			: this(eventType)
		{
			this.data = ((data != null) ? data.ToDictionary() : null);
			this.@internal = @internal;
		}

		[JsonConstructor]
		public GenericEventResponse(string eventType, Dictionary<string, object>? data, [JsonProperty(PropertyName = "internal")] bool @internal)
			: this(eventType, data)
		{
			this.@internal = @internal;
		}
	}
	internal class HexColorConverter : JsonConverter<ParameterColorValue>
	{
		private static readonly Dictionary<char, byte> CHAR_LOOKUP = new Dictionary<char, byte>
		{
			{ '0', 0 },
			{ '1', 1 },
			{ '2', 2 },
			{ '3', 3 },
			{ '4', 4 },
			{ '5', 5 },
			{ '6', 6 },
			{ '7', 7 },
			{ '8', 8 },
			{ '9', 9 },
			{ 'A', 10 },
			{ 'B', 11 },
			{ 'C', 12 },
			{ 'D', 13 },
			{ 'E', 14 },
			{ 'F', 15 }
		};

		public override void WriteJson(JsonWriter writer, ParameterColorValue value, JsonSerializer serializer)
		{
			serializer.Serialize(writer, (object)string.Format("#{0}{1:X2}{2:X2}{3:X2}", (value.A != byte.MaxValue) ? value.A.ToString("X2") : string.Empty, value.R, value.G, value.B));
		}

		public override ParameterColorValue ReadJson(JsonReader reader, Type objectType, ParameterColorValue existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			if (TryParse(serializer.Deserialize<string>(reader), out var color))
			{
				return color;
			}
			throw new SerializationException("Unrecognized color code.");
		}

		public static bool TryParse(string? value, out ParameterColorValue color)
		{
			if (value == null)
			{
				color = default(ParameterColorValue);
				return false;
			}
			value = value.TrimStart('#');
			switch (value.Length)
			{
			case 6:
			{
				string[] array2 = value.Chop(2);
				byte result2;
				byte red3 = (byte)(byte.TryParse(array2[0], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result2) ? result2 : 0);
				byte green3 = (byte)(byte.TryParse(array2[1], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result2) ? result2 : 0);
				byte blue3 = (byte)(byte.TryParse(array2[2], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result2) ? result2 : 0);
				color = ParameterColorValue.FromArgb(red3, green3, blue3);
				return true;
			}
			case 8:
			{
				string[] array = value.Chop(2);
				byte result;
				byte alpha2 = (byte)(byte.TryParse(array[0], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				byte red2 = (byte)(byte.TryParse(array[1], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				byte green2 = (byte)(byte.TryParse(array[2], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				byte blue2 = (byte)(byte.TryParse(array[3], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				color = ParameterColorValue.FromArgb(alpha2, red2, green2, blue2);
				return true;
			}
			case 3:
			{
				byte value3;
				byte red4 = (byte)(CHAR_LOOKUP.TryGetValue(value[0], out value3) ? checked((byte)(value3 * 16)) : 0);
				byte green4 = (byte)(CHAR_LOOKUP.TryGetValue(value[1], out value3) ? checked((byte)(value3 * 16)) : 0);
				byte blue4 = (byte)(CHAR_LOOKUP.TryGetValue(value[2], out value3) ? checked((byte)(value3 * 16)) : 0);
				color = ParameterColorValue.FromArgb(red4, green4, blue4);
				return true;
			}
			case 4:
			{
				byte value2;
				byte alpha = (byte)(CHAR_LOOKUP.TryGetValue(value[0], out value2) ? checked((byte)(value2 * 16)) : 0);
				byte red = (byte)(CHAR_LOOKUP.TryGetValue(value[1], out value2) ? checked((byte)(value2 * 16)) : 0);
				byte green = (byte)(CHAR_LOOKUP.TryGetValue(value[2], out value2) ? checked((byte)(value2 * 16)) : 0);
				byte blue = (byte)(CHAR_LOOKUP.TryGetValue(value[3], out value2) ? checked((byte)(value2 * 16)) : 0);
				color = ParameterColorValue.FromArgb(alpha, red, green, blue);
				return true;
			}
			default:
				color = default(ParameterColorValue);
				return false;
			}
		}
	}
	internal static class IEnumerableEx
	{
		internal static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> values) where TKey : notnull
		{
			Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
			foreach (KeyValuePair<TKey, TValue> value in values)
			{
				dictionary.Add(value.Key, value.Value);
			}
			return dictionary;
		}
	}
	public interface IParameterValue
	{
		string ID { get; }

		string Name { get; }

		ParameterBase.ParameterType Type { get; }

		object? Value { get; }
	}
	[Serializable]
	public class LoginRequest : SimpleJSONRequest
	{
		public string? login;

		public string? password;
	}
	[Serializable]
	public class MessageRequest : SimpleJSONRequest
	{
		public string? message;
	}
	[Serializable]
	public class MessageResponse : SimpleJSONResponse
	{
		public string? message;
	}
	internal static class ObjectEx
	{
		internal static T2? IfNotNull<T1, T2>(this T1? value, Func<T1, T2?> selector) where T2 : class
		{
			if (value == null)
			{
				return null;
			}
			return selector(value);
		}
	}
	public abstract class ParameterBase
	{
		[JsonConverter(typeof(AnnotatedEnumConverter<ParameterType>))]
		public enum ParameterType
		{
			[AnnotatedEnumConverter<ParameterType>.JsonValue("options")]
			Options,
			[AnnotatedEnumConverter<ParameterType>.JsonValue("hex-color")]
			HexColor
		}

		[JsonIgnore]
		public readonly string ID;

		[JsonProperty(PropertyName = "title")]
		public readonly string Name;

		[JsonProperty(PropertyName = "type")]
		public readonly ParameterType Type;

		protected ParameterBase(string name, string id, ParameterType type)
		{
			ID = id;
			Name = name;
			Type = type;
		}
	}
	public class ParameterColor : ParameterBase, IParameterValue
	{
		[JsonProperty(PropertyName = "value")]
		[JsonConverter(typeof(HexColorConverter))]
		public ParameterColorValue Value;

		[JsonIgnore]
		string IParameterValue.ID => ID;

		[JsonIgnore]
		string IParameterValue.Name => Name;

		[JsonIgnore]
		ParameterType IParameterValue.Type => Type;

		[JsonIgnore]
		object? IParameterValue.Value => Value;

		[JsonConstructor]
		public ParameterColor(string name, string id, ParameterColorValue value)
			: base(name, id, ParameterType.HexColor)
		{
			Value = value;
		}

		[JsonConstructor]
		public ParameterColor(string name, string id, string value)
			: base(name, id, ParameterType.HexColor)
		{
			if (!HexColorConverter.TryParse(value, out Value))
			{
				throw new ArgumentException("Unknown color code.", "value");
			}
		}
	}
	[Serializable]
	[DebuggerDisplay("{NameAndARGBValue}")]
	[TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
	public readonly struct ParameterColorValue : IEquatable<ParameterColorValue>
	{
		public static readonly ParameterColorValue Empty;

		private const short StateARGBValueValid = 2;

		private const short StateValueMask = 2;

		private const short StateNameValid = 8;

		private const long NotDefinedValue = 0L;

		internal const int ARGBAlphaShift = 24;

		internal const int ARGBRedShift = 16;

		internal const int ARGBGreenShift = 8;

		internal const int ARGBBlueShift = 0;

		internal const uint ARGBAlphaMask = 4278190080u;

		internal const uint ARGBRedMask = 16711680u;

		internal const uint ARGBGreenMask = 65280u;

		internal const uint ARGBBlueMask = 255u;

		private readonly long value;

		private readonly short state;

		public byte R => (byte)(Value >> 16);

		public byte G => (byte)(Value >> 8);

		public byte B => (byte)Value;

		public byte A => (byte)(Value >> 24);

		public bool IsEmpty => state == 0;

		private long Value
		{
			get
			{
				if ((state & 2) != 0)
				{
					return value;
				}
				return 0L;
			}
		}

		private ParameterColorValue(long value, short state)
		{
			this.value = value;
			this.state = state;
		}

		private static ParameterColorValue FromArgb(uint argb)
		{
			return new ParameterColorValue(argb, 2);
		}

		public static ParameterColorValue FromArgb(int argb)
		{
			return FromArgb((uint)argb);
		}

		public static ParameterColorValue FromArgb(byte alpha, byte red, byte green, byte blue)
		{
			return FromArgb((uint)((alpha << 24) | (red << 16) | (green << 8) | blue));
		}

		public static ParameterColorValue FromArgb(int alpha, ParameterColorValue baseColor)
		{
			return FromArgb(checked(((uint)alpha << 24) | ((uint)baseColor.Value & 0xFFFFFF)));
		}

		public static ParameterColorValue FromArgb(byte red, byte green, byte blue)
		{
			return FromArgb(byte.MaxValue, red, green, blue);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void GetRgbValues(out byte r, out byte g, out byte b)
		{
			checked
			{
				uint num = (uint)Value;
				r = (byte)((num & 0xFF0000) >> 16);
				g = (byte)((num & 0xFF00) >> 8);
				b = (byte)(num & 0xFF);
			}
		}

		public float GetBrightness()
		{
			GetRgbValues(out var r, out var g, out var b);
			int num = Math.Min(Math.Min(r, g), b);
			return (float)checked(Math.Max(Math.Max(r, g), b) + num) / 510f;
		}

		public float GetHue()
		{
			GetRgbValues(out var r, out var g, out var b);
			if (r == g && g == b)
			{
				return 0f;
			}
			int num = Math.Min(Math.Min(r, g), b);
			int num2 = Math.Max(Math.Max(r, g), b);
			checked
			{
				float num3 = num2 - num;
				float num4 = ((r == num2) ? ((float)(g - b) / num3) : ((g != num2) ? ((float)(r - g) / num3 + 4f) : ((float)(b - r) / num3 + 2f)));
				num4 *= 60f;
				if (num4 < 0f)
				{
					num4 += 360f;
				}
				return num4;
			}
		}

		public float GetSaturation()
		{
			GetRgbValues(out var r, out var g, out var b);
			if (r == g && g == b)
			{
				return 0f;
			}
			int num = Math.Min(Math.Min(r, g), b);
			int num2 = Math.Max(Math.Max(r, g), b);
			checked
			{
				int num3 = num2 + num;
				if (num3 > 255)
				{
					num3 = 510 - num2 - num;
				}
				return (float)(num2 - num) / (float)num3;
			}
		}

		public int ToArgb()
		{
			return (int)Value;
		}

		public override string ToString()
		{
			if ((state & 2) != 0)
			{
				return "ParameterColorValue [A=" + A + ", R=" + R + ", G=" + G + ", B=" + B + "]";
			}
			return "ParameterColorValue [Empty]";
		}

		public static bool operator ==(ParameterColorValue left, ParameterColorValue right)
		{
			if (left.value == right.value)
			{
				return left.state == right.state;
			}
			return false;
		}

		public static bool operator !=(ParameterColorValue left, ParameterColorValue right)
		{
			return !(left == right);
		}

		public override bool Equals(object? obj)
		{
			if (obj is ParameterColorValue other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(ParameterColorValue other)
		{
			return this == other;
		}

		public override int GetHashCode()
		{
			return (value.GetHashCode() * 397) ^ state.GetHashCode();
		}
	}
	public class ParameterValue<TValue> : ParameterBase, IParameterValue
	{
		[JsonProperty(PropertyName = "value")]
		public TValue? Value;

		[JsonIgnore]
		string IParameterValue.ID => ID;

		[JsonIgnore]
		string IParameterValue.Name => Name;

		[JsonIgnore]
		ParameterType IParameterValue.Type => Type;

		[JsonIgnore]
		object? IParameterValue.Value => Value;

		[JsonConstructor]
		public ParameterValue(string name, string id, TValue? value)
			: base(name, id, ParameterType.Options)
		{
			Value = value;
		}

		public override string ToString()
		{
			return Name;
		}
	}
	[Serializable]
	public class PlayerInfo : SimpleJSONRequest
	{
		public JObject? player;

		public PlayerInfo()
		{
			type = RequestType.PlayerInfo;
		}
	}
	[Serializable]
	[JsonConverter(typeof(Converter))]
	public class RequestParameters : IReadOnlyList<string>, IEnumerable<string>, IEnumerable, IReadOnlyCollection<string>, IReadOnlyDictionary<string, IParameterValue>, IEnumerable<KeyValuePair<string, IParameterValue>>, IReadOnlyCollection<KeyValuePair<string, IParameterValue>>
	{
		private class Converter : JsonConverter<RequestParameters>
		{
			public override void WriteJson(JsonWriter writer, RequestParameters? value, JsonSerializer serializer)
			{
				serializer.Serialize(writer, (object)value?._parameters);
			}

			public override RequestParameters? ReadJson(JsonReader reader, Type objectType, RequestParameters? existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				JObject obj = JObject.Load(reader);
				List<IParameterValue> list = new List<IParameterValue>();
				foreach (KeyValuePair<string, JToken> item in obj)
				{
					string key = item.Key;
					string name = Extensions.Value<string>((IEnumerable<JToken>)item.Value[(object)"name"]);
					switch (Extensions.Value<ParameterBase.ParameterType>((IEnumerable<JToken>)item.Value[(object)"type"]))
					{
					case ParameterBase.ParameterType.Options:
					{
						string value = Extensions.Value<string>((IEnumerable<JToken>)item.Value[(object)"value"]);
						list.Add(new ParameterValue<string>(name, key, value));
						break;
					}
					case ParameterBase.ParameterType.HexColor:
					{
						if (HexColorConverter.TryParse(Extensions.Value<string>((IEnumerable<JToken>)item.Value[(object)"value"]), out var color))
						{
							list.Add(new ParameterColor(name, key, color));
						}
						break;
					}
					default:
						throw new SerializationException();
					}
				}
				return new RequestParameters(list);
			}
		}

		private readonly Dictionary<string, IParameterValue> _parameters;

		private readonly List<string> _parameter_list;

		int IReadOnlyCollection<string>.Count => _parameters.Count;

		int IReadOnlyCollection<KeyValuePair<string, IParameterValue>>.Count => _parameters.Count;

		public string this[int index] => _parameter_list[index];

		public IParameterValue this[string key] => _parameters[key];

		public IEnumerable<string> Keys => _parameters.Keys;

		public IEnumerable<IParameterValue> Values => _parameters.Values;

		public int Count => _parameters.Count;

		private RequestParameters()
		{
			_parameters = new Dictionary<string, IParameterValue>();
			_parameter_list = new List<string>();
		}

		public RequestParameters(IEnumerable<IParameterValue> parameters)
		{
			parameters = parameters.ToArray();
			_parameters = parameters.ToDictionary((IParameterValue d) => d.ID);
			_parameter_list = parameters.Select((IParameterValue v) => v.Value.ToString()).ToList();
		}

		public RequestParameters(IEnumerable<KeyValuePair<string, IParameterValue>> parameters)
		{
			_parameters = parameters.ToDictionary();
			_parameter_list = _parameters.Values.Select((IParameterValue p) => p.Value.ToString()).ToList();
		}

		IEnumerator<KeyValuePair<string, IParameterValue>> IEnumerable<KeyValuePair<string, IParameterValue>>.GetEnumerator()
		{
			return _parameters.GetEnumerator();
		}

		IEnumerator<string> IEnumerable<string>.GetEnumerator()
		{
			return _parameters.Values.Select((IParameterValue v) => v.Value?.ToString()).GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return ((IEnumerable<string>)this).GetEnumerator();
		}

		public bool ContainsKey(string key)
		{
			return _parameters.ContainsKey(key);
		}

		public bool TryGetValue(string key, out IParameterValue value)
		{
			return _parameters.TryGetValue(key, out value);
		}

		public IEnumerable<string> Where(Func<string, bool> predicate)
		{
			return Enumerable.Where(this, predicate);
		}

		public IEnumerable<TResult> Select<TResult>(Func<string, TResult> selector)
		{
			return Enumerable.Select(this, selector);
		}

		public IEnumerable<TResult> SelectMany<TResult>(Func<string, IEnumerable<TResult>> selector)
		{
			return Enumerable.SelectMany(this, selector);
		}

		public IEnumerable<TResult> SelectMany<TResult>(Func<string, int, IEnumerable<TResult>> selector)
		{
			return Enumerable.SelectMany(this, selector);
		}

		public string First()
		{
			return this.First<string>();
		}

		public string First(Func<string, bool> predicate)
		{
			return Enumerable.First(this, predicate);
		}

		public string? FirstOrDefault()
		{
			return this.FirstOrDefault<string>();
		}

		public string FirstOrDefault(string defaultValue)
		{
			return this.FirstOrDefault<string>() ?? defaultValue;
		}

		public string? FirstOrDefault(Func<string, bool> predicate)
		{
			return Enumerable.FirstOrDefault(this, predicate);
		}

		public string FirstOrDefault(Func<string, bool> predicate, string defaultValue)
		{
			return Enumerable.FirstOrDefault(this, predicate) ?? defaultValue;
		}

		public bool Any()
		{
			return this.Any<string>();
		}

		public bool Any(Func<string, bool> predicate)
		{
			return Enumerable.Any(this, predicate);
		}
	}
	public enum RequestType : byte
	{
		[Obsolete("Use EffectTest instead.")]
		Test = 0,
		EffectTest = 0,
		[Obsolete("Use EffectStart instead.")]
		Start = 1,
		EffectStart = 1,
		[Obsolete("Use EffectStop instead.")]
		Stop = 2,
		EffectStop = 2,
		GenericEvent = 16,
		DataRequest = 32,
		RpcResponse = 208,
		PlayerInfo = 224,
		Login = 240,
		GameUpdate = 253,
		KeepAlive = byte.MaxValue
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum ResponseType : byte
	{
		EffectRequest = 0,
		EffectStatus = 1,
		GenericEvent = 16,
		LoadEvent = 24,
		SaveEvent = 25,
		DataResponse = 32,
		RpcRequest = 208,
		Login = 240,
		LoginSuccess = 241,
		GameUpdate = 253,
		Disconnect = 254,
		KeepAlive = byte.MaxValue
	}
	[Serializable]
	public class RpcRequest : SimpleJSONResponse
	{
		public string? method;

		public object?[]? args;

		public RpcRequest()
		{
			type = ResponseType.RpcRequest;
		}
	}
	[Serializable]
	public class RpcResponse : SimpleJSONRequest
	{
		public object? value;

		public RpcResponse()
		{
			type = RequestType.RpcResponse;
		}
	}
	public abstract class SimpleJSONMessage
	{
		public static readonly JsonSerializerSettings JSON_SERIALIZER_SETTINGS;

		public static readonly JsonSerializer JSON_SERIALIZER;

		private static int _next_id;

		public static uint NextID
		{
			get
			{
				uint result;
				while ((result = (uint)Interlocked.Increment(ref _next_id)) == 0)
				{
				}
				return result;
			}
		}

		public abstract uint ID { get; }

		public abstract bool IsKeepAlive { get; }

		static SimpleJSONMessage()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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_0059: Expected O, but got Unknown
			JSON_SERIALIZER_SETTINGS = new JsonSerializerSettings
			{
				NullValueHandling = (NullValueHandling)1,
				MissingMemberHandling = (MissingMemberHandling)0,
				Formatting = (Formatting)0
			};
			JSON_SERIALIZER = new JsonSerializer
			{
				NullValueHandling = JSON_SERIALIZER_SETTINGS.NullValueHandling,
				MissingMemberHandling = JSON_SERIALIZER_SETTINGS.MissingMemberHandling,
				Formatting = JSON_SERIALIZER_SETTINGS.Formatting
			};
			_next_id = 0;
			AppDomain.CurrentDomain.AssemblyResolve += delegate(object _, ResolveEventArgs args)
			{
				string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), new AssemblyName(args.Name).Name + ".dll");
				return (!File.Exists(text)) ? null : Assembly.LoadFrom(text);
			};
		}

		public string Serialize()
		{
			return JsonConvert.SerializeObject((object)this, JSON_SERIALIZER_SETTINGS);
		}
	}
	[Serializable]
	public class SimpleJSONRequest : SimpleJSONMessage
	{
		public uint id = SimpleJSONMessage.NextID;

		public RequestType type;

		[JsonIgnore]
		public override uint ID => id;

		[JsonIgnore]
		public override bool IsKeepAlive => type == RequestType.KeepAlive;

		public static bool TryParse(string json, [MaybeNullWhen(false)] out SimpleJSONRequest request)
		{
			return TryParse(JObject.Parse(json), out request);
		}

		public static bool TryParse(JObject j, [MaybeNullWhen(false)] out SimpleJSONRequest request)
		{
			try
			{
				JToken value = j.GetValue("type");
				RequestType requestType = ((value != null) ? ((RequestType)(object)CamelCaseStringEnumConverter.ReadJToken(value, typeof(RequestType))) : RequestType.Test);
				switch (requestType)
				{
				case RequestType.Stop:
					if (requestType != RequestType.Stop)
					{
						break;
					}
					request = ((JToken)j).ToObject<EffectRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.Test:
				case RequestType.Start:
					request = ((JToken)j).ToObject<EffectRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.DataRequest:
					request = ((JToken)j).ToObject<DataRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.RpcResponse:
					request = ((JToken)j).ToObject<RpcResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.PlayerInfo:
					request = ((JToken)j).ToObject<PlayerInfo>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.Login:
					request = ((JToken)j).ToObject<MessageRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.GameUpdate:
					request = ((JToken)j).ToObject<EmptyRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.KeepAlive:
					request = ((JToken)j).ToObject<EmptyRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				}
			}
			catch
			{
			}
			request = null;
			return false;
		}
	}
	[Serializable]
	public class SimpleJSONResponse : SimpleJSONMessage
	{
		public uint id;

		public ResponseType type;

		[JsonIgnore]
		public override uint ID => id;

		[JsonIgnore]
		public override bool IsKeepAlive => type == ResponseType.KeepAlive;

		[JsonIgnore]
		public static SimpleJSONResponse KeepAlive { get; } = new EmptyResponse
		{
			type = ResponseType.KeepAlive
		};

		public static bool TryParse(string json, [MaybeNullWhen(false)] out SimpleJSONResponse response)
		{
			return TryParse(JObject.Parse(json), out response);
		}

		public static bool TryParse(JObject j, [MaybeNullWhen(false)] out SimpleJSONResponse response)
		{
			try
			{
				JToken value = j.GetValue("type");
				ResponseType responseType = ((value != null) ? ((ResponseType)(object)CamelCaseStringEnumConverter.ReadJToken(value, typeof(ResponseType))) : ResponseType.EffectRequest);
				switch (responseType)
				{
				case ResponseType.EffectStatus:
					if (responseType != ResponseType.EffectStatus)
					{
						break;
					}
					response = ((JToken)j).ToObject<EffectUpdate>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.EffectRequest:
					response = ((JToken)j).ToObject<EffectResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.RpcRequest:
					response = ((JToken)j).ToObject<RpcRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.GenericEvent:
					response = ((JToken)j).ToObject<GenericEventResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.DataResponse:
					response = ((JToken)j).ToObject<DataResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.Login:
					response = ((JToken)j).ToObject<EmptyResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.LoginSuccess:
					response = ((JToken)j).ToObject<EmptyResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.GameUpdate:
					response = ((JToken)j).ToObject<GameUpdate>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.Disconnect:
					response = ((JToken)j).ToObject<MessageResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.KeepAlive:
					response = ((JToken)j).ToObject<EmptyResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				}
			}
			catch
			{
			}
			response = null;
			return false;
		}
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum StandardErrors
	{
		Unknown = 0,
		ExceptionThrown = 1,
		BadRequest = 4096,
		[Obsolete("Use EffectUnknown instead.")]
		UnknownEffect = 4097,
		EffectUnknown = 4097,
		EffectDisabled = 4098,
		AlreadyFailed = 4099,
		CannotParseNumber = 4112,
		UnknownSelection = 4113,
		ConnectorError = 8192,
		ConnectorReadFailure = 8193,
		ConnectorWriteFailure = 8194,
		ConnectorNotConnected = 8195,
		ConnectorNotSupported = 8196,
		SettingsError = 12288,
		CooldownPerEffect = 12545,
		CooldownGlobal = 12546,
		RetryMaxTime = 12291,
		RetryMaxAttempts = 12292,
		NoSession = 20480,
		SessionEnding = 20481,
		BadGameState = 16384,
		GameObjectNotFound = 16640,
		PlayerNotFound = 16641,
		CharacterNotFound = 16642,
		EnemyNotFound = 16643,
		ObjectNotFound = 16644,
		PrerequisiteNotFound = 16645,
		ObjectStateError = 16896,
		AlreadyInState = 16897,
		AlreadyAcquired = 16898,
		AlreadyFinished = 16899,
		NoEmptyContainers = 16912,
		PartyFull = 16913,
		InvalidArea = 16928,
		InvalidTarget = 16929,
		NoValidTargets = 16930,
		SpawnNotAllowedHere = 16932,
		RangeError = 17152,
		AlreadyMinimum = 17153,
		AlreadyMaximum = 17154,
		EffectNotImplemented = 24576,
		PackResourceMissing = 24577,
		ConflictingEffectRunning = 32768,
		UnqueueablePending = 32769,
		EmulatorNotSupported = 28672,
		EmulatorInvalidSetting = 28673
	}
	internal static class StringEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsNullOrWhiteSpace(this string? input)
		{
			return string.IsNullOrWhiteSpace(input);
		}

		internal static string ToCamelCase(this string input)
		{
			bool flag = false;
			string text = "";
			checked
			{
				for (int i = 0; i < input.Length; i++)
				{
					if (char.IsUpper(input[i]))
					{
						if (flag)
						{
							text += input.Substring(i);
							break;
						}
						text += char.ToLower(input[i]);
					}
					else
					{
						flag = true;
						text = ((i <= 1 || !char.IsUpper(input[i - 1]) || !char.IsUpper(input[i - 2])) ? (text + input[i]) : (text.Substring(0, text.Length - 1) + char.ToUpper(input[i - 1]) + input[i]));
					}
				}
				return text;
			}
		}

		internal unsafe static string[] Chop(this string value, int chopLength)
		{
			int length = value.Length;
			char* ptr = stackalloc char[chopLength];
			string[] array = new string[length];
			for (int i = 0; i < length; i = checked(i + chopLength))
			{
				int j;
				for (j = 0; j < chopLength; j = checked(j + 1))
				{
					int num = checked(i + j);
					if (num >= length)
					{
						break;
					}
					*(char*)((byte*)ptr + checked(unchecked((nint)j) * (nint)2)) = value[num];
				}
				array[i / chopLength] = new string(ptr, 0, j);
			}
			return array;
		}
	}
}

BepInEx/plugins/CrowdControl/CrowdControl.dll

Decompiled 10 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Logging;
using ConnectorLib.JSON;
using CrowdControl.Delegates.Effects;
using CrowdControl.Delegates.Metadata;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Sandbox;
using Sandbox.Arm;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[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 CrowdControl
{
	internal static class CameraEffectState
	{
		private static bool _loggedMissingCamera;

		public static bool InvertActive { get; set; }

		public static bool DrunkActive { get; set; }

		public static float DrunkTime { get; set; }

		public static void Apply(CameraController camera)
		{
			//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)
			if (!((Object)(object)camera == (Object)null))
			{
				if (InvertActive)
				{
					camera.transitionRotationZ = 180f;
					camera.transitionRotationZSmooth = 180f;
				}
				else if (DrunkActive)
				{
					DrunkTime += Time.unscaledDeltaTime;
					float num = Mathf.Sin(DrunkTime * 2.2f) * 14f;
					float num2 = Mathf.Sin(DrunkTime * 3.1f) * 5f;
					float num3 = Mathf.Cos(DrunkTime * 2.4f) * 6f;
					camera.tiltRotationZ = num;
					camera.tiltRotationZSmooth = num;
					camera.rotationOffset = Quaternion.Euler(num2, num3, num * 0.5f);
				}
			}
		}

		public static void ApplyAndRefresh(CameraController? camera)
		{
			if ((Object)(object)camera == (Object)null)
			{
				if (!_loggedMissingCamera)
				{
					_loggedMissingCamera = true;
					CrowdControlMod.Instance.Logger.LogWarning((object)"CameraHelper: no active CameraController (invert/drunk cam inactive)");
				}
			}
			else
			{
				_loggedMissingCamera = false;
				Apply(camera);
				camera.ApplyRotations(false);
			}
		}

		public static void ResetVisuals(CameraController? camera)
		{
			//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)
			if (!((Object)(object)camera == (Object)null))
			{
				camera.transitionRotationZ = 0f;
				camera.transitionRotationZSmooth = 0f;
				camera.tiltRotationZ = 0f;
				camera.tiltRotationZSmooth = 0f;
				camera.rotationOffset = Quaternion.identity;
				camera.ApplyRotations(false);
			}
		}
	}
	internal static class CameraHelper
	{
		public static CameraController? Get()
		{
			CameraController val = MonoSingleton<CameraController>.Instance;
			if ((Object)(object)val != (Object)null && (Object)(object)val.cam != (Object)null)
			{
				return val;
			}
			NewMovement player = GameHelper.Player;
			if ((Object)(object)player?.cc != (Object)null && (Object)(object)player.cc.cam != (Object)null)
			{
				return player.cc;
			}
			if (val == null)
			{
				val = Object.FindObjectOfType<CameraController>();
			}
			if (!((Object)(object)val?.cam != (Object)null))
			{
				return null;
			}
			return val;
		}
	}
	internal static class CombatFlags
	{
		public static bool NoPunchActive { get; set; }
	}
	[BepInPlugin("WarpWorld.CrowdControl", "Crowd Control", "1.3.1.0")]
	public class CrowdControlMod : BaseUnityPlugin
	{
		internal sealed class CrowdControlRunner : MonoBehaviour
		{
			private void Update()
			{
				Instance?.OnGameTick();
			}

			private void OnDestroy()
			{
				s_runner = null;
				CrowdControlMod instance = Instance;
				if (instance != null)
				{
					instance.Logger.LogWarning((object)"Crowd Control tick runner destroyed — will be recreated next tick.");
				}
			}
		}

		public const string MOD_GUID = "WarpWorld.CrowdControl";

		public const string MOD_NAME = "Crowd Control";

		public const string MOD_VERSION = "1.3.1.0";

		private readonly Harmony harmony = new Harmony("WarpWorld.CrowdControl");

		private const float GAME_STATUS_UPDATE_INTERVAL = 1f;

		private float m_gameStatusUpdateTimer;

		private int m_lastTickFrame = -1;

		private const float MANUAL_RECONNECT_BACKOFF = 5f;

		private float m_lastManualReconnect = float.NegativeInfinity;

		private bool m_awaitingReconnectResult;

		private bool m_newInputBroken;

		private bool m_legacyInputBroken;

		private static GameObject? s_runner;

		public static float DeltaTime => Time.fixedDeltaTime / Mathf.Max(Time.timeScale, 0.01f);

		public static float UnscaledTickDelta => Mathf.Min(Time.unscaledDeltaTime, 0.05f);

		public ManualLogSource Logger => ((BaseUnityPlugin)this).Logger;

		internal static CrowdControlMod Instance { get; private set; }

		public GameStateManager GameStateManager { get; private set; }

		public EffectLoader EffectLoader { get; private set; }

		public bool ClientConnected => Client.Connected;

		public NetworkClient Client { get; private set; }

		public Scheduler Scheduler { get; private set; }

		private void Awake()
		{
			Instance = this;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			EnsureRunner();
			Logger.LogInfo((object)"Loaded WarpWorld.CrowdControl. Patching.");
			harmony.PatchAll();
			Logger.LogInfo((object)"Initializing Crowd Control");
			try
			{
				GameStateManager = new GameStateManager(this);
				Client = new NetworkClient(this);
				EffectLoader = new EffectLoader(this, Client);
				Scheduler = new Scheduler(this, Client);
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Crowd Control Init Error: {arg}");
			}
			Logger.LogInfo((object)"Crowd Control Initialized");
		}

		private void OnApplicationQuit()
		{
			try
			{
				Client?.Stop();
				Client?.Dispose();
			}
			catch
			{
			}
		}

		private void OnDestroy()
		{
			Logger.LogWarning((object)"CrowdControlMod object destroyed (scene transition?) — network client left running.");
		}

		private void Update()
		{
			OnGameTick();
		}

		private void HandleManualReconnect()
		{
			if (m_awaitingReconnectResult && ClientConnected)
			{
				m_awaitingReconnectResult = false;
				ShowHudMessage("Crowd Control: Connected!");
			}
			if (F9PressedThisFrame())
			{
				Logger.LogInfo((object)"F9 pressed — manual reconnect requested");
				if (!(Time.unscaledTime - m_lastManualReconnect < 5f))
				{
					m_lastManualReconnect = Time.unscaledTime;
					m_awaitingReconnectResult = true;
					ShowHudMessage("Crowd Control: Reconnecting...");
					Client?.RequestReconnect();
				}
			}
		}

		private bool F9PressedThisFrame()
		{
			if (!m_newInputBroken)
			{
				try
				{
					bool? flag = F9PressedNewInput();
					if (flag.HasValue)
					{
						return flag.Value;
					}
				}
				catch (Exception ex)
				{
					m_newInputBroken = true;
					Logger.LogWarning((object)("InputSystem unavailable for F9 (" + ex.GetType().Name + "), falling back to legacy input"));
				}
			}
			if (!m_legacyInputBroken)
			{
				try
				{
					return F9PressedLegacyInput();
				}
				catch (Exception ex2)
				{
					m_legacyInputBroken = true;
					Logger.LogWarning((object)("Legacy input unavailable for F9 (" + ex2.GetType().Name + "); F9 reconnect disabled"));
				}
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool? F9PressedNewInput()
		{
			Keyboard current = Keyboard.current;
			if (current == null)
			{
				return null;
			}
			return ((ButtonControl)current.f9Key).wasPressedThisFrame;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool F9PressedLegacyInput()
		{
			return Input.GetKeyDown((KeyCode)290);
		}

		private static void ShowHudMessage(string message)
		{
			try
			{
				HudMessageReceiver instance = MonoSingleton<HudMessageReceiver>.Instance;
				if (instance != null)
				{
					instance.SendHudMessage(message, "", "", 0, false, false, true);
				}
			}
			catch
			{
			}
		}

		internal static void EnsureRunner()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			if (!((Object)(object)s_runner != (Object)null))
			{
				s_runner = new GameObject("CrowdControlRunner")
				{
					hideFlags = (HideFlags)61
				};
				Object.DontDestroyOnLoad((Object)(object)s_runner);
				s_runner.AddComponent<CrowdControlRunner>();
				CrowdControlMod instance = Instance;
				if (instance != null)
				{
					instance.Logger.LogInfo((object)"Crowd Control tick runner created");
				}
			}
		}

		internal void OnGameTick()
		{
			EnsureRunner();
			if (m_lastTickFrame != Time.frameCount)
			{
				m_lastTickFrame = Time.frameCount;
				HandleManualReconnect();
				m_gameStatusUpdateTimer += Time.unscaledDeltaTime;
				if (m_gameStatusUpdateTimer >= 1f)
				{
					GameStateManager.UpdateGameState();
					m_gameStatusUpdateTimer = 0f;
				}
				Scheduler?.Tick();
			}
		}
	}
	public class DelimitedStreamReader(NetworkStream stream) : IDisposable
	{
		private readonly MemoryStream _memory_stream = new MemoryStream();

		~DelimitedStreamReader()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposing)
			{
				return;
			}
			try
			{
				_memory_stream.Dispose();
			}
			catch
			{
			}
		}

		public string ReadUntilNullTerminator()
		{
			int num;
			while ((num = stream.ReadByte()) != -1 && num != 0)
			{
				_memory_stream.WriteByte(checked((byte)num));
			}
			if (num == -1)
			{
				throw new EndOfStreamException("Reached end of stream without finding a null terminator.");
			}
			string result = Encoding.UTF8.GetString(_memory_stream.ToArray());
			_memory_stream.SetLength(0L);
			return result;
		}
	}
	public static class GameHelper
	{
		public static NewMovement? Player => MonoSingleton<NewMovement>.Instance ?? Object.FindObjectOfType<NewMovement>();

		public static float MaxHealth(NewMovement player)
		{
			float num = 100f;
			int property = player.GetProperty<int>("difficulty");
			if (property == 0 || (property == 1 && player.sameCheckpointRestarts > 2))
			{
				num = 200f;
			}
			return num - player.antiHp;
		}

		public static List<EnemyIdentifier> GetLivingEnemies(bool excludeBoss = true)
		{
			List<EnemyIdentifier> list = Object.FindObjectsOfType<EnemyIdentifier>().ToList();
			list.RemoveAll((EnemyIdentifier x) => x.dead || (excludeBoss && x.isBoss));
			return list;
		}

		public static List<EnemyIdentifier> GetBuffableEnemies()
		{
			List<EnemyIdentifier> list = Object.FindObjectsOfType<EnemyIdentifier>().ToList();
			list.RemoveAll((EnemyIdentifier x) => x.dead || x.healthBuff);
			return list;
		}

		public static void UpdateMoneyUI()
		{
			MoneyText[] array = Object.FindObjectsOfType<MoneyText>();
			for (int i = 0; i < array.Length; i++)
			{
				array[i].UpdateMoney();
			}
		}
	}
	public readonly struct GameStateInfo
	{
		public GameState State { get; }

		public string Reason { get; }

		public GameStateInfo(GameState state, string reason)
		{
			//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)
			State = state;
			Reason = reason;
		}
	}
	public class GameStateManager(CrowdControlMod mod)
	{
		private GameState? _last_game_state;

		private string? _last_reason;

		public bool IsReady(string code = "")
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Invalid comparison between Unknown and I4
			return (int)GetGameStateInfo().State == 1;
		}

		public bool IsEffectTickReady()
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Invalid comparison between Unknown and I4
			return (int)GetGameStateInfo().State == 1;
		}

		public GameState GetGameState()
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			return GetGameStateInfo().State;
		}

		public GameStateInfo GetGameStateInfo()
		{
			try
			{
				OptionsManager instance = MonoSingleton<OptionsManager>.Instance;
				if (Object.op_Implicit((Object)(object)instance))
				{
					if (instance.frozen)
					{
						return new GameStateInfo((GameState)(-11), "OptionsManager.frozen");
					}
					if (instance.inIntro)
					{
						return new GameStateInfo((GameState)(-11), "OptionsManager.inIntro");
					}
					if (instance.paused)
					{
						return new GameStateInfo((GameState)(-7), "OptionsManager.paused");
					}
					if (instance.mainMenu)
					{
						return new GameStateInfo((GameState)(-13), "OptionsManager.mainMenu");
					}
				}
				NewMovement player = GameHelper.Player;
				if ((Object)(object)player == (Object)null)
				{
					return new GameStateInfo((GameState)(-6), "no NewMovement instance");
				}
				if (player.dead)
				{
					return new GameStateInfo((GameState)(-12), "player.dead");
				}
				if (player.levelOver)
				{
					return new GameStateInfo((GameState)(-11), "player.levelOver");
				}
				return new GameStateInfo((GameState)1, "in gameplay");
			}
			catch (Exception ex)
			{
				CrowdControlMod.Instance.Logger.LogError((object)$"Game state error: {ex}");
				return new GameStateInfo((GameState)(-1), ex.Message);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool UpdateGameState(bool force = false)
		{
			return UpdateGameState(GetGameStateInfo(), force);
		}

		public bool UpdateGameState(GameStateInfo info, bool force = false)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return UpdateGameState(info.State, info.Reason, force);
		}

		public bool UpdateGameState(GameState newState, bool force)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return UpdateGameState(newState, null, force);
		}

		public bool UpdateGameState(GameState newState, string? message = null, bool force = false)
		{
			//IL_0043: 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_0080: 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_008c: Expected O, but got Unknown
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: 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_0027: Unknown result type (might be due to invalid IL or missing references)
			string text = message ?? GetGameStateInfo().Reason;
			if (force || _last_game_state != (GameState?)newState || _last_reason != text)
			{
				_last_game_state = newState;
				_last_reason = text;
				CrowdControlMod.Instance.Logger.LogInfo((object)$"Game state: {newState} ({text})");
				return mod.Client.Send((SimpleJSONResponse?)new GameUpdate(newState, text));
			}
			return true;
		}
	}
	public static class HypeTrainHelper
	{
		private static AssetBundle? s_bundle;

		private static GameObject? s_hypetrainPrefab;

		private static bool s_loaded;

		private static string ResolveBundlePath()
		{
			string[] array = new string[3]
			{
				Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "", "warpworld.hypetrain"),
				Path.Combine(Paths.PluginPath, "CrowdControl", "warpworld.hypetrain"),
				Path.Combine(Paths.PluginPath, "warpworld.hypetrain")
			};
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (File.Exists(text))
				{
					return text;
				}
			}
			return array[0];
		}

		public static bool EnsureLoaded()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (s_loaded && (Object)(object)s_hypetrainPrefab != (Object)null)
			{
				return true;
			}
			new HypeTrainBoxData();
			string text = ResolveBundlePath();
			s_bundle = AssetBundle.LoadFromFile(text);
			if ((Object)(object)s_bundle == (Object)null)
			{
				CrowdControlMod.Instance.Logger.LogError((object)("Failed to load Hype Train AssetBundle from " + text));
				return false;
			}
			s_hypetrainPrefab = s_bundle.LoadAsset<GameObject>("HypeTrain");
			if ((Object)(object)s_hypetrainPrefab == (Object)null)
			{
				CrowdControlMod.Instance.Logger.LogError((object)"Hype Train prefab not found in AssetBundle.");
				return false;
			}
			s_loaded = true;
			CrowdControlMod.Instance.Logger.LogInfo((object)("Loaded Hype Train AssetBundle from " + text));
			return true;
		}

		public static bool Spawn(EffectRequest request)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: 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_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: 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_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: 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_0134: 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_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Expected O, but got Unknown
			if (!EnsureLoaded() || (Object)(object)s_hypetrainPrefab == (Object)null)
			{
				return false;
			}
			NewMovement player = GameHelper.Player;
			if ((Object)(object)player == (Object)null)
			{
				return false;
			}
			Camera main = Camera.main;
			object obj = ((main != null) ? ((Component)main).transform : null);
			if (obj == null)
			{
				Camera obj2 = Object.FindObjectOfType<Camera>();
				obj = ((obj2 != null) ? ((Component)obj2).transform : null);
			}
			Transform val = (Transform)obj;
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			IEffectSourceDetails sourceDetails = request.sourceDetails;
			HypeTrainSourceDetails val2 = (HypeTrainSourceDetails)(object)((sourceDetails is HypeTrainSourceDetails) ? sourceDetails : null);
			if (val2 == null)
			{
				return false;
			}
			float num = Random.Range(0.1f, 1f);
			Vector3 forward = val.forward;
			Vector3 val3 = default(Vector3);
			((Vector3)(ref val3))..ctor(val.position.x + forward.x * num, val.position.y + 1f, val.position.z + forward.z * num);
			HypeTrain component = Object.Instantiate<GameObject>(s_hypetrainPrefab, val3, Quaternion.identity).GetComponent<HypeTrain>();
			if ((Object)(object)component == (Object)null)
			{
				CrowdControlMod.Instance.Logger.LogError((object)"Failed to instantiate Hype Train.");
				return false;
			}
			Vector3 position = ((Component)player).transform.position;
			Vector3 val4 = position + val.TransformDirection(Vector3.forward) * 10f;
			Vector3 val5 = position - val.TransformDirection(Vector3.forward) * 10f;
			HypeTrainBoxData[] array = BuildBoxDataList(val2, val4, val5);
			float num2 = 1f;
			float num3 = (float)val2.Level * 0.1f;
			float value = Mathf.Min(num2 + num3, 10f);
			component.StartHypeTrain(val4, val5, array, ((Component)player).transform, new HypeTrainOptions
			{
				max_bits_per_car = 100,
				distance_per_second = value
			});
			return true;
		}

		private static HypeTrainBoxData[] BuildBoxDataList(HypeTrainSourceDetails sourceDetails, Vector3 startPos, Vector3 stopPos)
		{
			//IL_00c0: 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_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: 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_0109: 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_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Expected O, but got Unknown
			List<HypeTrainBoxData> list = new List<HypeTrainBoxData>();
			foreach (Contribution item in sourceDetails.TopContributions ?? new List<Contribution>())
			{
				list.Add(CreateBox(item));
			}
			List<Contribution> topContributions = sourceDetails.TopContributions;
			if ((topContributions == null || !topContributions.Any(delegate(Contribution contribution)
			{
				string userID = contribution.UserID;
				Contribution lastContribution = sourceDetails.LastContribution;
				return userID == ((lastContribution != null) ? lastContribution.UserID : null);
			})) && sourceDetails.LastContribution != null)
			{
				list.Add(CreateBox(sourceDetails.LastContribution));
			}
			if (list.Count < 1)
			{
				list.Add(CreateDefaultBox("Crowd Control"));
			}
			float num = Vector3.Distance(startPos, stopPos);
			int num2 = Mathf.Max(3, checked(Mathf.CeilToInt(num / 3f) + 2));
			int num3 = 0;
			while (list.Count < num2)
			{
				HypeTrainBoxData val = list[num3 % list.Count];
				list.Add(new HypeTrainBoxData
				{
					name = val.name,
					box_color = val.box_color,
					bit_amount = 0
				});
				num3 = checked(num3 + 1);
			}
			return list.ToArray();
		}

		private static HypeTrainBoxData CreateBox(Contribution contribution)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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_0038: 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)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			string text = (string.IsNullOrWhiteSpace(contribution.UserName) ? contribution.UserLogin : contribution.UserName);
			if (string.IsNullOrWhiteSpace(text))
			{
				text = "Viewer";
			}
			return new HypeTrainBoxData
			{
				name = text,
				box_color = ConvertUserNameToColor(text),
				bit_amount = ((contribution.Type == "bits") ? contribution.Total : 0)
			};
		}

		private static HypeTrainBoxData CreateDefaultBox(string name)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			return new HypeTrainBoxData
			{
				name = name,
				box_color = ConvertUserNameToColor(name),
				bit_amount = 0
			};
		}

		private static Color ConvertUserNameToColor(string userName)
		{
			//IL_0036: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			using SHA256 sHA = SHA256.Create();
			byte[] array = sHA.ComputeHash(Encoding.UTF8.GetBytes(userName));
			return new Color((float)(int)array[0] / 255f, (float)(int)array[1] / 255f, (float)(int)array[2] / 255f);
		}
	}
	public class NetworkClient : IDisposable
	{
		private const bool PROCESS_LOOKUP_FALLBACK = true;

		private static readonly SITimeSpan TIMEOUT_NO_PROCESS = 5.0;

		private static readonly SITimeSpan TIMEOUT_NO_CONNECTION = 2.0;

		public static readonly string CV_HOST = "127.0.0.1";

		public static readonly int CV_PORT = 51337;

		private TcpClient? m_client;

		private DelimitedStreamReader? m_streamReader;

		private readonly CrowdControlMod m_mod;

		private readonly CancellationTokenSource m_quitting = new CancellationTokenSource();

		private readonly object m_shutdownLock = new object();

		private readonly object m_sendLock = new object();

		private volatile bool m_disposed;

		private readonly Thread m_readLoop;

		private readonly Thread m_maintenanceLoop;

		private readonly AutoResetEvent m_reconnectRequest = new AutoResetEvent(initialState: false);

		private static readonly EmptyResponse KEEPALIVE = new EmptyResponse
		{
			type = (ResponseType)255
		};

		public bool Connected => m_client?.Connected ?? false;

		~NetworkClient()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposing)
			{
				return;
			}
			lock (m_shutdownLock)
			{
				if (m_disposed)
				{
					return;
				}
				m_disposed = true;
			}
			try
			{
				m_quitting.Cancel();
			}
			catch
			{
			}
			CloseConnection();
		}

		private void CloseConnection()
		{
			lock (m_sendLock)
			{
				try
				{
					m_streamReader?.Dispose();
				}
				catch
				{
				}
				finally
				{
					m_streamReader = null;
				}
				try
				{
					TcpClient? client = m_client;
					if (client != null && client.Connected)
					{
						m_client.Client.Shutdown(SocketShutdown.Both);
					}
					m_client?.Close();
					m_client?.Dispose();
				}
				catch
				{
				}
				finally
				{
					m_client = null;
				}
			}
		}

		private static bool IsBenignShutdownException(Exception e, bool quitting)
		{
			if (!quitting && !(e is ThreadAbortException) && !(e is ObjectDisposedException) && !(e is OperationCanceledException) && (!(e is IOException { InnerException: SocketException innerException }) || !IsBenignSocketError(innerException.SocketErrorCode)))
			{
				if (e is SocketException ex2)
				{
					return IsBenignSocketError(ex2.SocketErrorCode);
				}
				return false;
			}
			return true;
		}

		private static bool IsBenignSocketError(SocketError code)
		{
			switch (code)
			{
			case SocketError.OperationAborted:
			case SocketError.Interrupted:
			case SocketError.ConnectionAborted:
			case SocketError.ConnectionReset:
			case SocketError.Shutdown:
				return true;
			default:
				return false;
			}
		}

		public void RequestReconnect()
		{
			if (m_disposed || m_quitting.IsCancellationRequested)
			{
				CrowdControlMod.Instance.Logger.LogWarning((object)"Manual reconnect requested but the network client is shut down — restart the game to reconnect.");
				return;
			}
			CrowdControlMod.Instance.Logger.LogInfo((object)"Manual reconnect requested");
			m_reconnectRequest.Set();
			CloseConnection();
		}

		public NetworkClient(CrowdControlMod mod)
		{
			m_mod = mod;
			m_readLoop = new Thread(NetworkLoop)
			{
				IsBackground = true,
				Name = "CrowdControl.NetworkRead"
			};
			m_maintenanceLoop = new Thread(MaintenanceLoop)
			{
				IsBackground = true,
				Name = "CrowdControl.NetworkMaintenance"
			};
			m_readLoop.Start();
			m_maintenanceLoop.Start();
		}

		private void NetworkLoop()
		{
			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
			while (!m_quitting.IsCancellationRequested)
			{
				if (!IsCrowdControlSemaphorePresent() && !IsCrowdControlProcessRunning())
				{
					CrowdControlMod.Instance.Logger.LogMessage((object)"No CrowdControl process found, skipping connection attempt...");
					WaitHandle.WaitAny(new WaitHandle[2]
					{
						m_quitting.Token.WaitHandle,
						m_reconnectRequest
					}, (TimeSpan)TIMEOUT_NO_PROCESS);
					continue;
				}
				CrowdControlMod.Instance.Logger.LogInfo((object)"Attempting to connect to Crowd Control");
				try
				{
					m_client = new TcpClient();
					m_client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, optionValue: true);
					m_client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue: true);
					if (m_client.BeginConnect(CV_HOST, CV_PORT, null, null).AsyncWaitHandle.WaitOne(2000, exitContext: true) && m_client.Connected)
					{
						ClientLoop();
					}
					else
					{
						CrowdControlMod.Instance.Logger.LogInfo((object)"Failed to connect to Crowd Control");
					}
				}
				catch (Exception ex)
				{
					if (!IsBenignShutdownException(ex, m_quitting.IsCancellationRequested))
					{
						CrowdControlMod.Instance.Logger.LogError((object)ex);
						CrowdControlMod.Instance.Logger.LogError((object)"Failed to connect to Crowd Control");
					}
				}
				finally
				{
					CloseConnection();
				}
				if (!m_quitting.IsCancellationRequested)
				{
					WaitHandle.WaitAny(new WaitHandle[2]
					{
						m_quitting.Token.WaitHandle,
						m_reconnectRequest
					}, (TimeSpan)TIMEOUT_NO_CONNECTION);
					continue;
				}
				break;
			}
		}

		private void MaintenanceLoop()
		{
			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
			while (!m_quitting.IsCancellationRequested)
			{
				try
				{
					if (!m_disposed)
					{
						TcpClient? client = m_client;
						if (client != null && client.Connected)
						{
							KeepAlive();
						}
					}
				}
				catch
				{
				}
				m_quitting.Token.WaitHandle.WaitOne(1000);
			}
		}

		private void ClientLoop()
		{
			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
			try
			{
				m_streamReader = new DelimitedStreamReader(m_client.GetStream());
				CrowdControlMod.Instance.Logger.LogInfo((object)"Connected to Crowd Control");
				m_mod.GameStateManager.UpdateGameState(force: true);
				EnableAllEffects();
				try
				{
					while (!m_quitting.IsCancellationRequested)
					{
						string text = m_streamReader.ReadUntilNullTerminator();
						OnMessage(text.Trim());
					}
				}
				catch (EndOfStreamException)
				{
					if (!m_quitting.IsCancellationRequested)
					{
						CrowdControlMod.Instance.Logger.LogInfo((object)"Disconnected from Crowd Control");
					}
				}
				catch (Exception ex2)
				{
					if (!IsBenignShutdownException(ex2, m_quitting.IsCancellationRequested))
					{
						CrowdControlMod.Instance.Logger.LogError((object)ex2);
						CrowdControlMod.Instance.Logger.LogError((object)"Disconnected from Crowd Control");
					}
				}
			}
			finally
			{
				CloseConnection();
			}
		}

		private void OnMessage(string message)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Invalid comparison between Unknown and I4
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			if (m_disposed || m_quitting.IsCancellationRequested || string.IsNullOrWhiteSpace(message))
			{
				return;
			}
			try
			{
				SimpleJSONRequest val = default(SimpleJSONRequest);
				if (!SimpleJSONRequest.TryParse(message, ref val))
				{
					CrowdControlMod.Instance.Logger.LogWarning((object)("Failed to parse CC message: " + message));
					return;
				}
				if ((int)val.type != 255)
				{
					CrowdControlMod.Instance.Logger.LogDebug((object)$"CC recv type={val.type} id={val.id}");
				}
				m_mod.Scheduler.ProcessRequest(val);
			}
			catch (Exception ex)
			{
				CrowdControlMod.Instance.Logger.LogError((object)ex);
			}
		}

		private static bool IsCrowdControlSemaphorePresent()
		{
			Semaphore result;
			return Semaphore.TryOpenExisting("CrowdControl", out result);
		}

		private static bool IsCrowdControlProcessRunning()
		{
			checked
			{
				try
				{
					Process[] processes = Process.GetProcesses();
					int num = 0;
					Process[] array = processes;
					foreach (Process process in array)
					{
						try
						{
							if (process.ProcessName.IndexOf("crowdcontrol", StringComparison.OrdinalIgnoreCase) >= 0)
							{
								CrowdControlMod.Instance.Logger.LogMessage((object)$"Found CrowdControl process: {process.ProcessName} (PID: {process.Id})");
								return true;
							}
						}
						catch (UnauthorizedAccessException)
						{
							num++;
						}
						catch (Exception ex2)
						{
							CrowdControlMod.Instance.Logger.LogMessage((object)("Could not access process: " + ex2.Message));
							num++;
						}
					}
					if (num > 0)
					{
						CrowdControlMod.Instance.Logger.LogMessage((object)$"Found {num} inaccessible processes (possibly running with different privileges). Attempting connection anyway.");
						return true;
					}
					return false;
				}
				catch (Exception ex3)
				{
					CrowdControlMod.Instance.Logger.LogMessage((object)("Error checking for CrowdControl processes: " + ex3.Message));
					return true;
				}
			}
		}

		public bool Send(SimpleJSONResponse? response)
		{
			try
			{
				if (response == null || m_disposed || m_quitting.IsCancellationRequested)
				{
					return false;
				}
				byte[] bytes = Encoding.UTF8.GetBytes(((SimpleJSONMessage)response).Serialize());
				int num = 0;
				byte[] array = new byte[1 + bytes.Length];
				ReadOnlySpan<byte> readOnlySpan = new ReadOnlySpan<byte>(bytes);
				readOnlySpan.CopyTo(new Span<byte>(array).Slice(num, readOnlySpan.Length));
				num += readOnlySpan.Length;
				array[num] = 0;
				byte[] array2 = array;
				lock (m_sendLock)
				{
					TcpClient? client = m_client;
					if (client == null || !client.Connected)
					{
						return false;
					}
					m_client.GetStream().Write(array2, 0, array2.Length);
					return true;
				}
			}
			catch (Exception ex)
			{
				if (!IsBenignShutdownException(ex, m_quitting.IsCancellationRequested))
				{
					CrowdControlMod.Instance.Logger.LogError((object)$"Error sending a message to the Crowd Control client: {ex}");
				}
				return false;
			}
		}

		public Task<bool> SendAsync(SimpleJSONResponse? response)
		{
			return Task.Run(() => Send(response));
		}

		public void Stop(string? message = null)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			if (!m_disposed)
			{
				if (message != null)
				{
					Send((SimpleJSONResponse?)new MessageResponse
					{
						type = (ResponseType)254,
						message = message
					});
				}
				try
				{
					m_quitting.Cancel();
				}
				catch
				{
				}
				CloseConnection();
			}
		}

		public Task StopAsync(string? message = null)
		{
			return Task.Run(delegate
			{
				Stop(message);
			});
		}

		public bool KeepAlive()
		{
			return Send((SimpleJSONResponse?)(object)KEEPALIVE);
		}

		public Task<bool> KeepAliveAsync()
		{
			return Task.Run((Func<bool>)KeepAlive);
		}

		public void AttachMetadata(EffectResponse response)
		{
			response.metadata = new Dictionary<string, DataResponse>();
			string[] commonMetadata = MetadataDelegates.CommonMetadata;
			foreach (string text in commonMetadata)
			{
				if (MetadataLoader.Metadata.TryGetValue(text, out MetadataDelegate value))
				{
					response.metadata.Add(text, value(m_mod));
				}
				else
				{
					CrowdControlMod.Instance.Logger.LogError((object)("Metadata delegate \"" + text + "\" could not be found. Available delegates: " + string.Join(", ", MetadataLoader.Metadata.Keys)));
				}
			}
		}

		public bool ShowEffects(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)128, (string)null));
		}

		public bool ShowEffects([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)128, (string)null));
		}

		public Task<bool> ShowEffectsAsync(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)128, (string)null));
		}

		public Task<bool> ShowEffectsAsync([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)128, (string)null));
		}

		public bool ShowAllEffects()
		{
			return ShowEffects(m_mod.EffectLoader.Effects.Keys);
		}

		public Task<bool> ShowAllEffectsAsync()
		{
			return ShowEffectsAsync(m_mod.EffectLoader.Effects.Keys);
		}

		public bool HideEffects(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)129, (string)null));
		}

		public bool HideEffects([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)129, (string)null));
		}

		public Task<bool> HideEffectsAsync(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)129, (string)null));
		}

		public Task<bool> HideEffectsAsync([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)129, (string)null));
		}

		public bool HideAllEffects()
		{
			return HideEffects(m_mod.EffectLoader.Effects.Keys);
		}

		public Task<bool> HideAllEffectsAsync()
		{
			return HideEffectsAsync(m_mod.EffectLoader.Effects.Keys);
		}

		public bool EnableEffects(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)130, (string)null));
		}

		public bool EnableEffects([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)130, (string)null));
		}

		public Task<bool> EnableEffectsAsync(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)130, (string)null));
		}

		public Task<bool> EnableEffectsAsync([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)130, (string)null));
		}

		public bool EnableAllEffects()
		{
			return EnableEffects(m_mod.EffectLoader.Effects.Keys);
		}

		public Task<bool> EnableAllEffectsAsync()
		{
			return EnableEffectsAsync(m_mod.EffectLoader.Effects.Keys);
		}

		public bool DisableEffects(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)131, (string)null));
		}

		public bool DisableEffects([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)131, (string)null));
		}

		public Task<bool> DisableEffectsAsync(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)131, (string)null));
		}

		public Task<bool> DisableEffectsAsync([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)131, (string)null));
		}

		public bool DisableAllEffects()
		{
			return DisableEffects(m_mod.EffectLoader.Effects.Keys);
		}

		public Task<bool> DisableAllEffectsAsync()
		{
			return DisableEffectsAsync(m_mod.EffectLoader.Effects.Keys);
		}
	}
	internal static class ReflectionEx
	{
		private const BindingFlags BINDING_FLAGS = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public static void SetField(this object obj, string prop, object val)
		{
			obj.GetType().GetField(prop, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).SetValue(obj, val);
		}

		public static T GetField<T>(this object obj, string prop)
		{
			return (T)obj.GetType().GetField(prop, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(obj);
		}

		public static void SetProperty(this object obj, string prop, object val)
		{
			obj.GetType().GetField(prop, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).SetValue(obj, val);
		}

		public static T GetProperty<T>(this object obj, string prop)
		{
			return (T)obj.GetType().GetField(prop, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(obj);
		}

		public static void CallMethod(this object obj, string methodName, params object[] vals)
		{
			obj.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Invoke(obj, vals);
		}

		public static T CallMethod<T>(this object obj, string methodName, params object[] vals)
		{
			return (T)obj.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Invoke(obj, vals);
		}
	}
	public class Scheduler(CrowdControlMod mod, NetworkClient networkClient)
	{
		private class RequestState
		{
			private IEnumerator? m_enumerator;

			public EffectRequest Request { get; }

			public Effect Effect { get; }

			public TimedEffectState? TimedEffectState { get; }

			public bool MoveNext()
			{
				if (m_enumerator != null)
				{
					if (m_enumerator.MoveNext())
					{
						return true;
					}
					(m_enumerator as IDisposable)?.Dispose();
					m_enumerator = null;
				}
				switch (TimedEffectState?.State)
				{
				case CrowdControl.Delegates.Effects.TimedEffectState.EffectState.NotStarted:
					m_enumerator = TimedEffectState.Start();
					break;
				case CrowdControl.Delegates.Effects.TimedEffectState.EffectState.Running:
				case CrowdControl.Delegates.Effects.TimedEffectState.EffectState.Paused:
					m_enumerator = TimedEffectState.Tick();
					break;
				default:
					return false;
				}
				if (!m_enumerator.MoveNext())
				{
					(m_enumerator as IDisposable)?.Dispose();
					m_enumerator = null;
				}
				return true;
			}

			public void Pause()
			{
				(m_enumerator as IDisposable)?.Dispose();
				m_enumerator = null;
				TimedEffectState.EffectState? effectState = TimedEffectState?.State;
				if (effectState.HasValue && effectState == CrowdControl.Delegates.Effects.TimedEffectState.EffectState.Running)
				{
					m_enumerator = TimedEffectState.Pause();
				}
			}

			public void Resume()
			{
				(m_enumerator as IDisposable)?.Dispose();
				m_enumerator = null;
				TimedEffectState.EffectState? effectState = TimedEffectState?.State;
				if (effectState.HasValue && effectState == CrowdControl.Delegates.Effects.TimedEffectState.EffectState.Paused)
				{
					m_enumerator = TimedEffectState.Resume();
				}
			}

			public void Stop()
			{
				(m_enumerator as IDisposable)?.Dispose();
				m_enumerator = null;
				TimedEffectState.EffectState? effectState = TimedEffectState?.State;
				if (effectState.HasValue)
				{
					TimedEffectState.EffectState valueOrDefault = effectState.GetValueOrDefault();
					if ((uint)(valueOrDefault - 1) <= 1u)
					{
						m_enumerator = TimedEffectState.Stop();
					}
				}
			}

			public RequestState(EffectRequest request, Effect effect)
			{
				Request = request;
				Effect = effect;
				if (Effect.IsTimed)
				{
					long num = ResolveDurationMs(request, effect);
					TimedEffectState = new TimedEffectState(effect, request, SITimeSpan.FromMilliseconds(num));
				}
			}
		}

		private CrowdControlMod m_mod = mod;

		private NetworkClient m_networkClient = networkClient;

		private readonly ConcurrentQueue<RequestState> m_requestQueue = new ConcurrentQueue<RequestState>();

		private readonly ConcurrentDictionary<uint, RequestState> m_runningEffects = new ConcurrentDictionary<uint, RequestState>();

		public bool IsRunning(string id, uint? excludeRequestID = null)
		{
			foreach (RequestState item in m_requestQueue.Concat(m_runningEffects.Values))
			{
				TimedEffectState timedEffectState = item.TimedEffectState;
				bool flag = timedEffectState == null;
				if (!flag)
				{
					TimedEffectState.EffectState state = timedEffectState.State;
					bool flag2 = (uint)(state - 3) <= 1u;
					flag = flag2;
				}
				if (!flag && ((SimpleJSONRequest)item.Request).id != excludeRequestID && item.Effect.EffectAttribute.IDs.Contains(id))
				{
					return true;
				}
			}
			return false;
		}

		public void ProcessRequest(SimpleJSONRequest? request)
		{
			//IL_0010: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Invalid comparison between Unknown and I4
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected I4, but got Unknown
			//IL_0062: 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_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Expected O, but got Unknown
			//IL_020f: 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_0115: 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_0121: Expected O, but got Unknown
			RequestType? val = request?.type;
			if (!val.HasValue)
			{
				return;
			}
			RequestType valueOrDefault = val.GetValueOrDefault();
			if ((int)valueOrDefault <= 240)
			{
				switch ((int)valueOrDefault)
				{
				default:
					_ = 240;
					break;
				case 0:
				{
					EffectRequest val5 = (EffectRequest)(object)((request is EffectRequest) ? request : null);
					if (val5 != null)
					{
						EffectRequest val4 = val5;
						if (val4.code == null)
						{
							val4.code = string.Empty;
						}
						if (!mod.EffectLoader.Effects.ContainsKey(val5.code))
						{
							networkClient.Send((SimpleJSONResponse?)new EffectResponse(((SimpleJSONRequest)val5).id, (EffectStatus)2, (StandardErrors)4097));
							CrowdControlMod.Instance.Logger.LogError((object)("Unknown effect: " + val5.code));
						}
						else
						{
							EffectStatus val6 = (EffectStatus)((!mod.GameStateManager.IsReady(val5.code)) ? 3 : 0);
							networkClient.Send((SimpleJSONResponse?)new EffectResponse(((SimpleJSONRequest)val5).id, val6));
						}
					}
					break;
				}
				case 1:
				{
					EffectRequest val3 = (EffectRequest)(object)((request is EffectRequest) ? request : null);
					if (val3 == null)
					{
						break;
					}
					EffectRequest val4 = val3;
					if (val4.code == null)
					{
						val4.code = string.Empty;
					}
					CrowdControlMod.Instance.Logger.LogInfo((object)$"Effect start: {val3.code} (id {((SimpleJSONRequest)val3).id})");
					if (!mod.EffectLoader.Effects.TryGetValue(val3.code, out Effect value2))
					{
						networkClient.Send((SimpleJSONResponse?)new EffectResponse(((SimpleJSONRequest)val3).id, (EffectStatus)2, (StandardErrors)4097));
						CrowdControlMod.Instance.Logger.LogError((object)("Unknown effect: " + val3.code));
						break;
					}
					GameStateInfo gameStateInfo = mod.GameStateManager.GetGameStateInfo();
					if (!mod.GameStateManager.IsReady(val3.code))
					{
						CrowdControlMod.Instance.Logger.LogInfo((object)$"Effect {val3.code} retrying — {gameStateInfo.State} ({gameStateInfo.Reason})");
						networkClient.Send((SimpleJSONResponse?)(object)EffectResponse.Retry(((SimpleJSONRequest)val3).id, (string)null));
						break;
					}
					if (value2.IsTimed)
					{
						long num = ResolveDurationMs(val3, value2);
						CrowdControlMod.Instance.Logger.LogInfo((object)$"Timed effect {val3.code}: {num}ms");
					}
					m_requestQueue.Enqueue(new RequestState(val3, value2));
					break;
				}
				case 2:
				{
					EffectRequest val2 = (EffectRequest)(object)((request is EffectRequest) ? request : null);
					if (val2 != null)
					{
						if (!m_runningEffects.TryGetValue(((SimpleJSONRequest)val2).id, out RequestState value))
						{
							networkClient.Send((SimpleJSONResponse?)new EffectResponse(((SimpleJSONRequest)val2).id, (EffectStatus)1, (StandardErrors)16899));
							CrowdControlMod.Instance.Logger.LogError((object)(StandardErrors)16899);
						}
						else
						{
							value.Stop();
						}
					}
					break;
				}
				}
			}
			else if ((int)valueOrDefault != 253)
			{
				_ = 255;
			}
			else
			{
				mod.GameStateManager.UpdateGameState(force: true);
			}
		}

		public void Enqueue(EffectRequest request, Effect effect)
		{
			m_requestQueue.Enqueue(new RequestState(request, effect));
		}

		public void PauseAll()
		{
			foreach (KeyValuePair<uint, RequestState> runningEffect in m_runningEffects)
			{
				runningEffect.Value.Pause();
			}
		}

		public void ResumeAll()
		{
			foreach (KeyValuePair<uint, RequestState> runningEffect in m_runningEffects)
			{
				runningEffect.Value.Resume();
			}
		}

		public void Tick()
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			RequestState result;
			while (m_requestQueue.TryDequeue(out result))
			{
				if (!mod.GameStateManager.IsReady(result.Request.code))
				{
					networkClient.Send((SimpleJSONResponse?)(object)EffectResponse.Retry(((SimpleJSONRequest)result.Request).id, (string)null));
					continue;
				}
				if (result.TimedEffectState != null)
				{
					m_runningEffects.TryAdd(((SimpleJSONRequest)result.Request).id, result);
					continue;
				}
				EffectResponse val;
				try
				{
					val = result.Effect.Start(result.Request);
				}
				catch (Exception ex)
				{
					val = EffectResponse.Failure(((SimpleJSONRequest)result.Request).id, (StandardErrors)1);
					CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
				}
				networkClient.AttachMetadata(val);
				networkClient.Send((SimpleJSONResponse?)(object)val);
				CrowdControlMod.Instance.Logger.LogInfo((object)$"Effect {result.Request.code} => {val.status}");
			}
			ConsumeEnumerators();
		}

		private static long ResolveDurationMs(EffectRequest request, Effect effect)
		{
			long? duration = request.duration;
			long num = ((!duration.HasValue || duration.GetValueOrDefault() <= 0) ? checked((long)effect.EffectAttribute.DefaultDuration.TotalMilliseconds) : request.duration.Value);
			if (num <= 0)
			{
				num = 30000L;
			}
			if (num < 1000)
			{
				num = 1000L;
			}
			else if (num > 1800000)
			{
				CrowdControlMod.Instance.Logger.LogWarning((object)$"Clamping effect {request.code} duration from {num}ms to {1800000L}ms");
				num = 1800000L;
			}
			return num;
		}

		private void ConsumeEnumerators()
		{
			foreach (KeyValuePair<uint, RequestState> runningEffect in m_runningEffects)
			{
				if (!runningEffect.Value.MoveNext())
				{
					m_runningEffects.TryRemove(runningEffect.Key, out RequestState _);
				}
			}
		}
	}
	[Serializable]
	[JsonConverter(typeof(Converter))]
	public struct SITimeSpan : IEquatable<SITimeSpan>, IEquatable<TimeSpan>, IEquatable<double>, IComparable<SITimeSpan>, IComparable<TimeSpan>, IComparable<double>, IFormattable
	{
		private class Converter : JsonConverter<SITimeSpan>
		{
			public override void WriteJson(JsonWriter writer, SITimeSpan value, JsonSerializer serializer)
			{
				writer.WriteValue(value._value.TotalSeconds);
			}

			public override SITimeSpan ReadJson(JsonReader reader, Type objectType, SITimeSpan existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				if (reader.Value is TimeSpan timeSpan)
				{
					return timeSpan;
				}
				if (reader.Value is string s)
				{
					if (TimeSpan.TryParse(s, out var result))
					{
						return result;
					}
					if (double.TryParse(s, out var result2))
					{
						return result2;
					}
				}
				return Convert.ToDouble(reader.Value);
			}
		}

		public static readonly SITimeSpan Zero = new SITimeSpan(TimeSpan.Zero);

		public static readonly SITimeSpan MinValue = new SITimeSpan(TimeSpan.MinValue);

		public static readonly SITimeSpan MaxValue = new SITimeSpan(TimeSpan.MaxValue);

		private readonly TimeSpan _value;

		public long Ticks => _value.Ticks;

		public int Milliseconds => _value.Milliseconds;

		public int Seconds => _value.Seconds;

		public int Minutes => _value.Minutes;

		public int Hours => _value.Hours;

		public int Days => _value.Days;

		public double TotalMilliseconds => _value.TotalMilliseconds;

		public double TotalSeconds => _value.TotalSeconds;

		public double TotalMinutes => _value.TotalMinutes;

		public double TotalHours => _value.TotalHours;

		public double TotalDays => _value.TotalDays;

		public override string ToString()
		{
			return _value.ToString();
		}

		public string ToString(string? format)
		{
			return _value.ToString(format);
		}

		public string ToString(string? format, IFormatProvider? formatProvider)
		{
			return _value.ToString(format, formatProvider);
		}

		public static SITimeSpan Parse(string input)
		{
			if (input.Contains('.'))
			{
				return new SITimeSpan(TimeSpan.ParseExact(input, "mm\\:ss\\.fff", null));
			}
			return new SITimeSpan(TimeSpan.Parse(input));
		}

		public static bool TryParse(string s, out SITimeSpan result)
		{
			TimeSpan result3;
			bool result2 = TimeSpan.TryParse(s, out result3);
			result = new SITimeSpan(result3);
			return result2;
		}

		public static int Compare(SITimeSpan t1, SITimeSpan t2)
		{
			return TimeSpan.Compare(t1._value, t2._value);
		}

		public static int Compare(TimeSpan t1, SITimeSpan t2)
		{
			return TimeSpan.Compare(t1, t2._value);
		}

		public static int Compare(SITimeSpan t1, TimeSpan t2)
		{
			return TimeSpan.Compare(t1._value, t2);
		}

		public static int Compare(double t1, SITimeSpan t2)
		{
			if (t1 > t2.TotalSeconds)
			{
				return 1;
			}
			if (!(t1 < t2.TotalSeconds))
			{
				return 0;
			}
			return -1;
		}

		public static int Compare(SITimeSpan t1, double t2)
		{
			if (t1.TotalSeconds > t2)
			{
				return 1;
			}
			if (!(t1.TotalSeconds < t2))
			{
				return 0;
			}
			return -1;
		}

		public static bool Equals(SITimeSpan t1, SITimeSpan t2)
		{
			return TimeSpan.Equals(t1._value, t2._value);
		}

		public static bool Equals(TimeSpan t1, SITimeSpan t2)
		{
			return TimeSpan.Equals(t1, t2._value);
		}

		public static bool Equals(SITimeSpan t1, TimeSpan t2)
		{
			return TimeSpan.Equals(t1._value, t2);
		}

		public static bool Equals(double t1, SITimeSpan t2)
		{
			return object.Equals(t1, (double)t2);
		}

		public static bool Equals(SITimeSpan t1, double t2)
		{
			return object.Equals((double)t1, t2);
		}

		public static SITimeSpan FromTicks(long value)
		{
			return new SITimeSpan(TimeSpan.FromTicks(value));
		}

		public static SITimeSpan FromMilliseconds(double value)
		{
			return new SITimeSpan(TimeSpan.FromMilliseconds(value));
		}

		public static SITimeSpan FromSeconds(double value)
		{
			return new SITimeSpan(TimeSpan.FromSeconds(value));
		}

		public static SITimeSpan FromMinutes(double value)
		{
			return new SITimeSpan(TimeSpan.FromMinutes(value));
		}

		public static SITimeSpan FromHours(double value)
		{
			return new SITimeSpan(TimeSpan.FromHours(value));
		}

		public static SITimeSpan FromDays(double value)
		{
			return new SITimeSpan(TimeSpan.FromDays(value));
		}

		public SITimeSpan Duration()
		{
			return new SITimeSpan(_value.Duration());
		}

		public SITimeSpan Add(SITimeSpan other)
		{
			return new SITimeSpan(_value.Add(other._value));
		}

		public SITimeSpan Subtract(SITimeSpan other)
		{
			return new SITimeSpan(_value.Subtract(other._value));
		}

		public SITimeSpan Negate()
		{
			return new SITimeSpan(_value.Negate());
		}

		private SITimeSpan(TimeSpan value)
		{
			_value = value;
		}

		private SITimeSpan(double value)
		{
			_value = TimeSpan.FromSeconds(value);
		}

		private SITimeSpan(long value)
		{
			_value = TimeSpan.FromSeconds(value);
		}

		public SITimeSpan? NullIfZero()
		{
			if (!(_value == TimeSpan.Zero))
			{
				return this;
			}
			return null;
		}

		public static implicit operator SITimeSpan(double value)
		{
			return new SITimeSpan(value);
		}

		public static implicit operator SITimeSpan?(double? value)
		{
			if (!value.HasValue)
			{
				return null;
			}
			return new SITimeSpan(value.Value);
		}

		public static implicit operator SITimeSpan(TimeSpan value)
		{
			return new SITimeSpan(value);
		}

		public static implicit operator SITimeSpan?(TimeSpan? value)
		{
			if (!value.HasValue)
			{
				return null;
			}
			return new SITimeSpan(value.Value);
		}

		public static implicit operator SITimeSpan(Func<TimeSpan> value)
		{
			return new SITimeSpan(value());
		}

		public static implicit operator SITimeSpan?(Func<TimeSpan>? value)
		{
			if (value == null)
			{
				return null;
			}
			return new SITimeSpan(value());
		}

		public static implicit operator SITimeSpan(Func<SITimeSpan> value)
		{
			return new SITimeSpan(value()._value);
		}

		public static implicit operator SITimeSpan?(Func<SITimeSpan>? value)
		{
			if (value == null)
			{
				return null;
			}
			return new SITimeSpan(value()._value);
		}

		public static explicit operator double(SITimeSpan value)
		{
			return value._value.TotalSeconds;
		}

		public static explicit operator double?(SITimeSpan? value)
		{
			return value?._value.TotalSeconds;
		}

		public static explicit operator float(SITimeSpan value)
		{
			return (float)value._value.TotalSeconds;
		}

		public static explicit operator float?(SITimeSpan? value)
		{
			return (float?)value?._value.TotalSeconds;
		}

		public static explicit operator long(SITimeSpan value)
		{
			return checked((long)value._value.TotalSeconds);
		}

		public static explicit operator long?(SITimeSpan? value)
		{
			return checked((long?)value?._value.TotalSeconds);
		}

		public static explicit operator TimeSpan(SITimeSpan value)
		{
			return value._value;
		}

		public static explicit operator TimeSpan?(SITimeSpan? value)
		{
			return value?._value;
		}

		public static explicit operator Func<TimeSpan>(SITimeSpan value)
		{
			return () => value._value;
		}

		public static explicit operator Func<TimeSpan?>(SITimeSpan? value)
		{
			return () => value?._value;
		}

		public static explicit operator Func<SITimeSpan>(SITimeSpan value)
		{
			return () => value;
		}

		public static explicit operator Func<SITimeSpan?>(SITimeSpan? value)
		{
			return () => value;
		}

		public override bool Equals(object? obj)
		{
			if (obj is SITimeSpan other)
			{
				return Equals(other);
			}
			if (obj is TimeSpan other2)
			{
				return Equals(other2);
			}
			if (obj is double other3)
			{
				return Equals(other3);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return _value.GetHashCode();
		}

		public bool Equals(SITimeSpan other)
		{
			return _value.Equals(other._value);
		}

		public int CompareTo(SITimeSpan other)
		{
			return _value.CompareTo(other._value);
		}

		public static bool operator ==(SITimeSpan a, SITimeSpan b)
		{
			return a._value.Equals(b._value);
		}

		public static bool operator !=(SITimeSpan a, SITimeSpan b)
		{
			return !a._value.Equals(b._value);
		}

		public static bool operator <(SITimeSpan a, SITimeSpan b)
		{
			return a._value < b._value;
		}

		public static bool operator <=(SITimeSpan a, SITimeSpan b)
		{
			return a._value <= b._value;
		}

		public static bool operator >(SITimeSpan a, SITimeSpan b)
		{
			return a._value > b._value;
		}

		public static bool operator >=(SITimeSpan a, SITimeSpan b)
		{
			return a._value >= b._value;
		}

		public bool Equals(TimeSpan other)
		{
			return _value.Equals(other);
		}

		public int CompareTo(TimeSpan other)
		{
			return _value.CompareTo(other);
		}

		public static bool operator ==(SITimeSpan a, TimeSpan b)
		{
			return a.Equals(b);
		}

		public static bool operator ==(TimeSpan a, SITimeSpan b)
		{
			return b.Equals(a);
		}

		public static bool operator !=(SITimeSpan a, TimeSpan b)
		{
			return !a.Equals(b);
		}

		public static bool operator !=(TimeSpan a, SITimeSpan b)
		{
			return !b.Equals(a);
		}

		public static bool operator <(SITimeSpan a, TimeSpan b)
		{
			return a._value < b;
		}

		public static bool operator <(TimeSpan a, SITimeSpan b)
		{
			return a < b._value;
		}

		public static bool operator <=(SITimeSpan a, TimeSpan b)
		{
			return a._value <= b;
		}

		public static bool operator <=(TimeSpan a, SITimeSpan b)
		{
			return a <= b._value;
		}

		public static bool operator >(SITimeSpan a, TimeSpan b)
		{
			return a._value > b;
		}

		public static bool operator >(TimeSpan a, SITimeSpan b)
		{
			return a > b._value;
		}

		public static bool operator >=(SITimeSpan a, TimeSpan b)
		{
			return a._value >= b;
		}

		public static bool operator >=(TimeSpan a, SITimeSpan b)
		{
			return a >= b._value;
		}

		public static SITimeSpan operator -(SITimeSpan a)
		{
			return -a._value;
		}

		public static SITimeSpan operator +(TimeSpan a, SITimeSpan b)
		{
			return a + b._value;
		}

		public static SITimeSpan operator -(TimeSpan a, SITimeSpan b)
		{
			return a - b._value;
		}

		public static SITimeSpan operator +(SITimeSpan a, TimeSpan b)
		{
			return a._value + b;
		}

		public static SITimeSpan operator -(SITimeSpan a, TimeSpan b)
		{
			return a._value - b;
		}

		public static SITimeSpan operator +(SITimeSpan a, SITimeSpan b)
		{
			return a._value + b._value;
		}

		public static SITimeSpan operator -(SITimeSpan a, SITimeSpan b)
		{
			return a._value - b._value;
		}

		public static DateTime operator +(DateTime a, SITimeSpan b)
		{
			return a + b._value;
		}

		public static DateTime operator -(DateTime a, SITimeSpan b)
		{
			return a - b._value;
		}

		public static DateTimeOffset operator +(DateTimeOffset a, SITimeSpan b)
		{
			return a + b._value;
		}

		public static DateTimeOffset operator -(DateTimeOffset a, SITimeSpan b)
		{
			return a - b._value;
		}

		public static SITimeSpan operator +(double a, SITimeSpan b)
		{
			return a + b._value.TotalSeconds;
		}

		public static SITimeSpan operator -(double a, SITimeSpan b)
		{
			return a - b._value.TotalSeconds;
		}

		public static SITimeSpan operator *(double a, SITimeSpan b)
		{
			return a * b._value.TotalSeconds;
		}

		public static SITimeSpan operator +(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds + b;
		}

		public static SITimeSpan operator -(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds - b;
		}

		public static SITimeSpan operator *(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds * b;
		}

		public static SITimeSpan operator /(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds / b;
		}

		public static SITimeSpan operator %(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds % b;
		}

		public bool Equals(double other)
		{
			return _value.TotalSeconds.Equals(other);
		}

		public int CompareTo(double other)
		{
			return _value.TotalSeconds.CompareTo(other);
		}

		public static bool operator ==(SITimeSpan a, double b)
		{
			return a.Equals(b);
		}

		public static bool operator ==(double a, SITimeSpan b)
		{
			return b.Equals(a);
		}

		public static bool operator !=(SITimeSpan a, double b)
		{
			return !a.Equals(b);
		}

		public static bool operator !=(double a, SITimeSpan b)
		{
			return !b.Equals(a);
		}

		public static bool operator <(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds < b;
		}

		public static bool operator <(double a, SITimeSpan b)
		{
			return a < b._value.TotalSeconds;
		}

		public static bool operator <=(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds <= b;
		}

		public static bool operator >=(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds >= b;
		}

		public static bool operator >(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds > b;
		}

		public static bool operator >(double a, SITimeSpan b)
		{
			return a > b._value.TotalSeconds;
		}

		public static bool operator <=(double a, SITimeSpan b)
		{
			return a <= b._value.TotalSeconds;
		}

		public static bool operator >=(double a, SITimeSpan b)
		{
			return a >= b._value.TotalSeconds;
		}
	}
	internal static class SpawnHelper
	{
		private static bool _loggedEnemyTypes;

		public static SpawnableObject? FindEnemy(string enemyCode)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Invalid comparison between Unknown and I4
			SpawnMenu val = FindSpawnMenu();
			if ((Object)(object)val == (Object)null)
			{
				CrowdControlMod.Instance.Logger.LogWarning((object)"SpawnHelper: SpawnMenu not found");
				return null;
			}
			SpawnableObjectsDatabase field = val.GetField<SpawnableObjectsDatabase>("objects");
			if (field?.enemies == null)
			{
				CrowdControlMod.Instance.Logger.LogWarning((object)"SpawnHelper: enemy database is null");
				return null;
			}
			string text = enemyCode.ToLowerInvariant();
			SpawnableObject val2 = null;
			SpawnableObject[] enemies = field.enemies;
			foreach (SpawnableObject val3 in enemies)
			{
				if ((int)val3.spawnableObjectType == 1 && ((object)Unsafe.As<EnemyType, EnemyType>(ref val3.enemyType)/*cast due to .constrained prefix*/).ToString().ToLowerInvariant() == text)
				{
					val2 = val3;
					break;
				}
			}
			if ((Object)(object)val2 == (Object)null && !_loggedEnemyTypes)
			{
				_loggedEnemyTypes = true;
				List<string> values = (from t in (from o in field.enemies
						where (int)o.spawnableObjectType == 1
						select ((object)Unsafe.As<EnemyType, EnemyType>(ref o.enemyType)/*cast due to .constrained prefix*/).ToString()).Distinct()
					orderby t
					select t).ToList();
				CrowdControlMod.Instance.Logger.LogWarning((object)("SpawnHelper: no match for '" + enemyCode + "'. Available: " + string.Join(", ", values)));
			}
			return val2;
		}

		public static List<SpawnableObject> GetAllEnemies()
		{
			SpawnMenu val = FindSpawnMenu();
			if ((Object)(object)val == (Object)null)
			{
				return new List<SpawnableObject>();
			}
			SpawnableObjectsDatabase field = val.GetField<SpawnableObjectsDatabase>("objects");
			if (field?.enemies == null)
			{
				return new List<SpawnableObject>();
			}
			return field.enemies.Where((SpawnableObject o) => (int)o.spawnableObjectType == 1).ToList();
		}

		public static bool SpawnEnemy(SpawnableObject target, NewMovement player, float distance = 10f, Vector3? position = null)
		{
			//IL_0014: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: 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_00d3: 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)
			GoreZone val = SandboxArm.debugZone;
			if ((Object)(object)val == (Object)null)
			{
				val = (SandboxArm.debugZone = new GameObject("Debug Gore Zone").AddComponent<GoreZone>());
			}
			Vector3 val2 = (Vector3)(((??)position) ?? (((Component)player).transform.position + ((Component)player).transform.forward * distance));
			GameObject val3 = Object.Instantiate<GameObject>(target.gameObject, val2, Quaternion.identity, ((Component)val).transform);
			SandboxProp val4 = default(SandboxProp);
			if (val3.TryGetComponent<SandboxProp>(ref val4))
			{
				((SpawnableInstance)val4).sourceObject = target;
			}
			((SpawnableInstance)val3.AddComponent<EnemySpawnableInstance>()).sourceObject = target;
			if (Object.op_Implicit((Object)(object)MonoSingleton<SandboxNavmesh>.Instance))
			{
				MonoSingleton<SandboxNavmesh>.Instance.EnsurePositionWithinBounds(val3.transform.position);
			}
			val3.SetActive(true);
			CrowdControlMod.Instance.Logger.LogInfo((object)$"SpawnHelper: spawned {target.enemyType} at {val2}");
			return true;
		}

		private static SpawnMenu? FindSpawnMenu()
		{
			SpawnMenu val = null;
			try
			{
				val = MonoSingleton<SpawnMenu>.Instance;
			}
			catch
			{
			}
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			CanvasController instance = MonoSingleton<CanvasController>.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				val = ((Component)instance).GetComponentInChildren<SpawnMenu>(true);
			}
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			return Object.FindObjectOfType<SpawnMenu>(true);
		}
	}
	public static class TaskEx
	{
		public static async void Forget(this Task task)
		{
			try
			{
				await task.ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (Exception ex)
			{
				CrowdControlMod.Instance.Logger.LogError((object)ex);
			}
		}

		public static async void Forget(this Task task, bool silent)
		{
			try
			{
				await task.ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (Exception ex)
			{
				if (!silent)
				{
					CrowdControlMod.Instance.Logger.LogError((object)ex);
				}
			}
		}
	}
}
namespace CrowdControl.Harmony
{
	[HarmonyPatch(typeof(CameraController), "ApplyRotations")]
	internal static class CameraController_ApplyRotations
	{
		private static void Prefix(CameraController __instance)
		{
			if (CameraEffectState.InvertActive || CameraEffectState.DrunkActive)
			{
				CameraEffectState.Apply(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(NewMovement), "Update")]
	internal static class NewMovement_Update
	{
		private static void Postfix()
		{
			CrowdControlMod.Instance?.OnGameTick();
		}
	}
	[HarmonyPatch(typeof(Punch), "PunchStart")]
	internal static class Punch_PunchStart
	{
		private static bool Prefix()
		{
			return !CombatFlags.NoPunchActive;
		}
	}
}
namespace CrowdControl.Delegates.Metadata
{
	[AttributeUsage(AttributeTargets.Method)]
	public class MetadataAttribute(params string[] ids) : Attribute()
	{
		public string[] IDs { get; } = ids;

		public MetadataAttribute(string ids)
			: this(new string[1] { ids })
		{
		}

		public MetadataAttribute([ParamCollection] IEnumerable<string> ids)
			: this(ids.ToArray())
		{
		}
	}
	public delegate DataResponse MetadataDelegate(CrowdControlMod mod);
	public static class MetadataDelegates
	{
		public static readonly string[] CommonMetadata = Array.Empty<string>();
	}
	public static class MetadataLoader
	{
		private const BindingFlags BINDING_FLAGS = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public static readonly Dictionary<string, MetadataDelegate> Metadata;

		static MetadataLoader()
		{
			Metadata = new Dictionary<string, MetadataDelegate>();
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			foreach (Type type in types)
			{
				try
				{
					MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					foreach (MethodInfo methodInfo in methods)
					{
						try
						{
							foreach (MetadataAttribute customAttribute in methodInfo.GetCustomAttributes<MetadataAttribute>())
							{
								string[] iDs = customAttribute.IDs;
								foreach (string key in iDs)
								{
									try
									{
										Metadata[key] = (MetadataDelegate)Delegate.CreateDelegate(typeof(MetadataDelegate), methodInfo);
									}
									catch (Exception ex)
									{
										CrowdControlMod.Instance.Logger.LogError((object)ex);
									}
								}
							}
						}
						catch
						{
						}
					}
				}
				catch
				{
				}
			}
		}
	}
}
namespace CrowdControl.Delegates.Effects
{
	public abstract class Effect
	{
		public EffectAttribute EffectAttribute { get; }

		public bool IsTimed => EffectAttribute.DefaultDuration > 0.0;

		public CrowdControlMod Mod { get; }

		public NetworkClient Client { get; }

		protected Effect(CrowdControlMod mod, NetworkClient client)
		{
			Mod = mod;
			Client = client;
			EffectAttribute = GetType().GetCustomAttributes<EffectAttribute>(inherit: false).First();
		}

		public abstract EffectResponse Start(EffectRequest request);

		public virtual EffectResponse? Tick(EffectRequest request)
		{
			return null;
		}

		public virtual EffectResponse? Pause(EffectRequest request)
		{
			return EffectResponse.Paused(((SimpleJSONMessage)request).ID, (string)null);
		}

		public virtual EffectResponse? Resume(EffectRequest request)
		{
			return EffectResponse.Resumed(((SimpleJSONMessage)request).ID, (string)null);
		}

		public virtual EffectResponse? Stop(EffectRequest request)
		{
			return EffectResponse.Finished(((SimpleJSONMessage)request).ID, (string)null);
		}

		protected bool HasConflict(EffectRequest request)
		{
			foreach (string conflict in EffectAttribute.Conflicts)
			{
				if (Mod.Scheduler.IsRunning(conflict, ((SimpleJSONMessage)request).ID))
				{
					return true;
				}
			}
			return false;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class EffectAttribute(string[] ids, SITimeSpan defaultDuration, string[] conflicts) : Attribute()
	{
		public IReadOnlyList<string> IDs { get; } = ids;

		public SITimeSpan DefaultDuration { get; } = defaultDuration;

		public IReadOnlyList<string> Conflicts { get; } = conflicts;

		public EffectAttribute([ParamCollection] IEnumerable<string> ids)
			: this(ids.ToArray(), SITimeSpan.Zero, Array.Empty<string>())
		{
		}

		public EffectAttribute(params string[] ids)
			: this(ids.ToArray(), SITimeSpan.Zero, Array.Empty<string>())
		{
		}

		public EffectAttribute(string[] ids, float defaultDuration, string[] conflicts)
			: this(ids, (SITimeSpan)defaultDuration, conflicts)
		{
		}

		public EffectAttribute(string[] ids, float defaultDuration, string conflict)
			: this(ids, defaultDuration, new string[1] { conflict })
		{
		}

		public EffectAttribute(string id)
			: this(new string[1] { id }, SITimeSpan.Zero, Array.Empty<string>())
		{
		}

		public EffectAttribute(string id, float defaultDuration)
			: this(new string[1] { id }, defaultDuration, (!(SITimeSpan.Zero > 0.0)) ? Array.Empty<string>() : new string[1] { id })
		{
		}

		public EffectAttribute(string id, float defaultDuration, string conflict)
			: this(new string[1] { id }, defaultDuration, new string[1] { conflict })
		{
		}

		public EffectAttribute(string id, float defaultDuration, string[] conflicts)
			: this(new string[1] { id }, defaultDuration, conflicts)
		{
		}

		public EffectAttribute(string id, float defaultDuration, bool selfConflict)
			: this(new string[1] { id }, defaultDuration, (!selfConflict) ? Array.Empty<string>() : new string[1] { id })
		{
		}

		public EffectAttribute(string[] ids, float defaultDuration, bool selfConflict)
			: this(ids, defaultDuration, selfConflict ? ids : Array.Empty<string>())
		{
		}

		public EffectAttribute(string id, bool selfConflict)
			: this(new string[1] { id }, SITimeSpan.Zero, (!selfConflict) ? Array.Empty<string>() : new string[1] { id })
		{
		}

		public EffectAttribute(string[] ids, bool selfConflict)
			: this(ids, SITimeSpan.Zero, selfConflict ? ids : Array.Empty<string>())
		{
		}
	}
	public class EffectLoader
	{
		private const BindingFlags BINDING_FLAGS = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public readonly Dictionary<string, Effect> Effects = new Dictionary<string, Effect>();

		public EffectLoader(CrowdControlMod mod, NetworkClient client)
		{
			foreach (Type item in from type in Assembly.GetExecutingAssembly().GetTypes()
				where type.IsSubclassOf(typeof(Effect))
				select type)
			{
				try
				{
					foreach (EffectAttribute customAttribute in item.GetCustomAttributes<EffectAttribute>())
					{
						foreach (string iD in customAttribute.IDs)
						{
							try
							{
								Effects[iD] = (Effect)Activator.CreateInstance(item, mod, client);
							}
							catch (Exception ex)
							{
								CrowdControlMod.Instance.Logger.LogError((object)ex);
							}
						}
					}
				}
				catch (Exception ex2)
				{
					CrowdControlMod.Instance.Logger.LogError((object)ex2);
				}
			}
		}
	}
	public class TimedEffectState
	{
		public enum EffectState
		{
			NotStarted,
			Running,
			Paused,
			Finished,
			Errored
		}

		public readonly EffectRequest Request;

		public readonly SITimeSpan Duration;

		public readonly Effect Effect;

		public readonly NetworkClient Client;

		public SITimeSpan TimeRemaining;

		private int m_stateLock;

		private int m_notReadyFrames;

		private int m_readyFrames;

		private const int STATE_CHANGE_FRAMES = 3;

		private static readonly IEnumerator EMPTY_ENUMERATOR = Enumerable.Empty<object>().GetEnumerator();

		public EffectState State { get; private set; }

		private bool TryGetLock()
		{
			return Interlocked.CompareExchange(ref m_stateLock, 1, 0) == 0;
		}

		private void ReleaseLock()
		{
			m_stateLock = 0;
		}

		public TimedEffectState(Effect effect, EffectRequest request, SITimeSpan duration)
		{
			Effect = effect;
			Client = effect.Client;
			Request = request;
			Duration = duration;
			TimeRemaining = duration;
		}

		private void FinalizeResponse(EffectResponse? response)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			if (response != null)
			{
				bool flag = response.timeRemaining == 0;
				if (flag)
				{
					EffectStatus status = response.status;
					bool flag2 = (((int)status == 0 || status - 6 <= 1) ? true : false);
					flag = flag2;
				}
				if (flag)
				{
					response.timeRemaining = checked((long)TimeRemaining.TotalMilliseconds);
				}
				Client.AttachMetadata(response);
			}
		}

		public IEnumerator Start()
		{
			EffectResponse response = null;
			bool locked = false;
			try
			{
				while (true)
				{
					bool flag;
					locked = (flag = TryGetLock());
					if (flag)
					{
						break;
					}
					yield return null;
				}
				if (State != EffectState.NotStarted)
				{
					yield break;
				}
				try
				{
					response = Effect.Start(Request);
					if ((int)response.status == 0)
					{
						TimeRemaining = Duration;
						State = EffectState.Running;
					}
					else
					{
						State = EffectState.Errored;
					}
				}
				catch (Exception ex)
				{
					response = EffectResponse.Failure(((SimpleJSONRequest)Request).id, (StandardErrors)1);
					CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
					State = EffectState.Errored;
				}
			}
			finally
			{
				TimedEffectState timedEffectState = this;
				if (locked)
				{
					timedEffectState.ReleaseLock();
					timedEffectState.FinalizeResponse(response);
					timedEffectState.Client.Send((SimpleJSONResponse?)(object)response);
				}
			}
		}

		public IEnumerator Pause()
		{
			EffectResponse response = null;
			bool locked = false;
			checked
			{
				try
				{
					while (true)
					{
						bool flag;
						locked = (flag = TryGetLock());
						if (flag)
						{
							break;
						}
						yield return null;
					}
					if (State == EffectState.Running)
					{
						try
						{
							response = Effect.Pause(Request) ?? EffectResponse.Paused(((SimpleJSONRequest)Request).id, (long)TimeRemaining.TotalMilliseconds, (string)null);
							State = EffectState.Paused;
							m_notReadyFrames = 0;
							m_readyFrames = 0;
							CrowdControlMod.Instance.Logger.LogInfo((object)$"Timed effect {Request.code} paused ({(long)TimeRemaining.TotalMilliseconds}ms remaining)");
							yield break;
						}
						catch (Exception ex)
						{
							response = EffectResponse.Failure(((SimpleJSONRequest)Request).id, (StandardErrors)1);
							CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
							State = EffectState.Errored;
							yield break;
						}
					}
				}
				finally
				{
					TimedEffectState timedEffectState = this;
					if (locked)
					{
						timedEffectState.ReleaseLock();
						timedEffectState.FinalizeResponse(response);
						timedEffectState.Client.Send((SimpleJSONResponse?)(object)response);
					}
				}
			}
		}

		public IEnumerator Resume()
		{
			EffectResponse response = null;
			bool locked = false;
			checked
			{
				try
				{
					while (true)
					{
						bool flag;
						locked = (flag = TryGetLock());
						if (flag)
						{
							break;
						}
						yield return null;
					}
					if (State == EffectState.Paused)
					{
						try
						{
							response = Effect.Resume(Request) ?? EffectResponse.Resumed(((SimpleJSONRequest)Request).id, (long)TimeRemaining.TotalMilliseconds, (string)null);
							State = EffectState.Running;
							m_notReadyFrames = 0;
							m_readyFrames = 0;
							CrowdControlMod.Instance.Logger.LogInfo((object)$"Timed effect {Request.code} resumed ({(long)TimeRemaining.TotalMilliseconds}ms remaining)");
							yield break;
						}
						catch (Exception ex)
						{
							response = EffectResponse.Failure(((SimpleJSONRequest)Request).id, (StandardErrors)1);
							CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
							State = EffectState.Errored;
							yield break;
						}
					}
				}
				finally
				{
					TimedEffectState timedEffectState = this;
					if (locked)
					{
						timedEffectState.ReleaseLock();
						timedEffectState.FinalizeResponse(response);
						timedEffectState.Client.Send((SimpleJSONResponse?)(object)response);
					}
				}
			}
		}

		public IEnumerator Stop()
		{
			EffectResponse response = null;
			bool locked = false;
			try
			{
				while (true)
				{
					bool flag;
					locked = (flag = TryGetLock());
					if (flag)
					{
						break;
					}
					yield return null;
				}
				if (State != EffectState.Finished)
				{
					try
					{
						response = Effect.Stop(Request) ?? EffectResponse.Finished(((SimpleJSONRequest)Request).id, (string)null);
						State = EffectState.Finished;
						yield break;
					}
					catch (Exception ex)
					{
						response = EffectResponse.Failure(((SimpleJSONRequest)Request).id, (StandardErrors)1);
						CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
						State = EffectState.Errored;
						yield break;
					}
				}
			}
			finally
			{
				TimedEffectState timedEffectState = this;
				if (locked)
				{
					timedEffectState.ReleaseLock();
					timedEffectState.FinalizeResponse(response);
					timedEffectState.Client.Send((SimpleJSONResponse?)(object)response);
				}
			}
		}

		public IEnumerator Tick()
		{
			EffectResponse val = null;
			bool flag = false;
			try
			{
				if (!(flag = TryGetLock()))
				{
					return EMPTY_ENUMERATOR;
				}
				bool flag2 = GameHelper.Player?.levelOver ?? false;
				if (flag2)
				{
					EffectState state = State;
					bool flag3 = (uint)(state - 1) <= 1u;
					flag2 = flag3;
				}
				if (flag2)
				{
					return Stop();
				}
				bool flag4 = CrowdControlMod.Instance.GameStateManager.IsEffectTickReady();
				checked
				{
					switch (State)
					{
					case EffectState.Running:
						if (!flag4)
						{
							m_notReadyFrames++;
							m_readyFrames = 0;
							if (m_notReadyFrames >= 3)
							{
								return Pause();
							}
							break;
						}
						m_notReadyFrames = 0;
						try
						{
							if (TimeRemaining > 0.0)
							{
								Effect.Tick(Request);
								TimeRemaining -= (double)CrowdControlMod.UnscaledTickDelta;
								if (TimeRemaining < SITimeSpan.Zero)
								{
									TimeRemaining = SITimeSpan.Zero;
								}
							}
							else
							{
								val = Effect.Stop(Request) ?? EffectResponse.Finished(((SimpleJSONRequest)Request).id, (string)null);
								State = EffectState.Finished;
								TimeRemaining = SITimeSpan.Zero;
							}
						}
						catch (Exception ex)
						{
							val = EffectResponse.Failure(((SimpleJSONRequest)Request).id, (StandardErrors)1);
							CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
							State = EffectState.Errored;
						}
						break;
					case EffectState.Paused:
						if (flag4)
						{
							m_readyFrames++;
							m_notReadyFrames = 0;
							if (m_readyFrames >= 3)
							{
								return Resume();
							}
						}
						else
						{
							m_readyFrames = 0;
						}
						break;
					}
					return EMPTY_ENUMERATOR;
				}
			}
			finally
			{
				if (flag)
				{
					ReleaseLock();
					if (val != null)
					{
						FinalizeResponse(val);
						Client.Send((SimpleJSONResponse?)(object)val);
					}
				}
			}
		}
	}
}
namespace CrowdControl.Delegates.Effects.Implementations
{
	[Effect(new string[] { "widecam", "narrowcam" }, 30f, new string[] { "widecam", "narrowcam" })]
	public class CameraFovEffect : Effect
	{
		public CameraFovEffect(CrowdControlMod mod, NetworkClient client)
			: base(mod, client)
		{
		}

		public override EffectResponse Start(EffectRequest request)
		{
			if (HasConflict(request))
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
			return EffectResponse.Success(((SimpleJSONMessage)request).ID, (string)null);
		}

		public override EffectResponse? Tick(EffectRequest request)
		{
			CameraController val = CameraHelper.Get();
			if ((Object)(object)val?.cam == (Object)null)
			{
				return null;
			}
			val.cam.fieldOfView = ((request.code == "widecam") ? (val.defaultFov * 1.5f) : (val.defaultFov * 0.5f));
			return null;
		}

		public override EffectResponse? Stop(EffectRequest request)
		{
			CameraController val = CameraHelper.Get();
			if ((Object)(object)val?.cam != (Object)null)
			{
				val.cam.fieldOfView = val.defaultFov;
			}
			return EffectResponse.Finished(((SimpleJSONMessage)request).ID, (string)null);
		}
	}
	[Effect("invertcam", 30f, new string[] { "invertcam", "drunkcam" })]
	public class InvertCameraEffect : Effect
	{
		public InvertCameraEffect(CrowdControlMod mod, NetworkClient client)
			: base(mod, client)
		{
		}

		public override EffectResponse Start(EffectRequest request)
		{
			if (HasConflict(request))
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
			CameraController val = CameraHelper.Get();
			if ((Object)(object)val == (Object)null)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, "Camera not found");
			}
			CameraEffectState.DrunkActive = false;
			CameraEffectState.InvertActive = true;
			CameraEffectState.ApplyAndRefresh(val);
			return EffectResponse.Success(((SimpleJSONMessage)request).ID, (string)null);
		}

		public override EffectResponse? Tick(EffectRequest request)
		{
			CameraEffectState.ApplyAndRefresh(CameraHelper.Get());
			return null;
		}

		public override EffectResponse? Stop(EffectRequest request)
		{
			CameraEffectState.InvertActive = false;
			if (!CameraEffectState.DrunkActive)
			{
				CameraEffectState.ResetVisuals(CameraHelper.Get());
			}
			return EffectResponse.Finished(((SimpleJSONMessage)request).ID, (string)null);
		}
	}
	[Effect("drunkcam", 30f, new string[] { "invertcam", "drunkcam" })]
	public class DrunkCameraEffect : Effect
	{
		public DrunkCameraEffect(CrowdControlMod mod, NetworkClient client)
			: base(mod, client)
		{
		}

		public override EffectResponse Start(EffectRequest request)
		{
			if (HasConflict(request))
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
			CameraController val = CameraHelper.Get();
			if ((Object)(object)val == (Object)null)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, "Camera not found");
			}
			CameraEffectState.InvertActive = false;
			CameraEffectState.DrunkActive = true;
			CameraEffectState.DrunkTime = 0f;
			CameraEffectState.ApplyAndRefresh(val);
			return EffectResponse.Success(((SimpleJSONMessage)request).ID, (string)null);
		}

		public override EffectResponse? Tick(EffectRequest request)
		{
			CameraEffectState.ApplyAndRefresh(CameraHelper.Get());
			return null;
		}

		public override EffectResponse? Stop(EffectRequest request)
		{
			CameraEffectState.DrunkActive = false;
			CameraEffectState.DrunkTime = 0f;
			if (!CameraEffectState.InvertActive)
			{
				CameraEffectState.ResetVisuals(CameraHelper.Get());
			}
			return EffectResponse.Finished(((SimpleJSONMessage)request).ID, (string)null);
		}
	}
	[Effect("screenshake", 4f, true)]
	public class ScreenShakeEffect : Effect
	{
		private const float ShakeIntensity = 12f;

		public ScreenShakeEffect(CrowdControlMod mod, NetworkClient client)
			: base(mod, client)
		{
		}

		public override EffectResponse Start(EffectRequest request)
		{
			if (HasConflict(request))
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
			CameraController val = CameraHelper.Get();
			if ((Object)(object)val == (Object)null)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
			ApplyShake(val);
			return EffectResponse.Success(((SimpleJSONMessage)request).ID, (string)null);
		}

		public override EffectResponse? Tick(EffectRequest request)
		{
			CameraController val = CameraHelper.Get();
			if ((Object)(object)val != (Object)null)
			{
				ApplyShake(val);
			}
			return null;
		}

		public override EffectResponse? Stop(EffectRequest request)
		{
			CameraController? obj = CameraHelper.Get();
			if (obj != null)
			{
				obj.StopShake();
			}
			return EffectResponse.Finished(((SimpleJSONMessage)request).ID, (string)null);
		}

		private static void ApplyShake(CameraController camera)
		{
			camera.cameraShaking = 12f;
		}
	}
	[Effect(new string[] { "ohko", "invul" }, 30f, new string[] { "ohko", "invul" })]
	public class HealthModifierEffect : Effect
	{
		private int _frames;

		public HealthModifierEffect(CrowdControlMod mod, NetworkClient client)
			: base(mod, client)
		{
		}

		public override EffectResponse Start(EffectRequest request)
		{
			if (HasConflict(request))
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
			NewMovement player = GameHelper.Player;
			if ((Object)(object)player == (Object)null)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
			_frames = 0;
			if (request.code == "ohko" && player.hp > 1)
			{
				player.hp = 1;
			}
			return EffectResponse.Success(((SimpleJSONMessage)request).ID, (string)null);
		}

		public override EffectResponse? Tick(EffectRequest request)
		{
			NewMovement player = GameHelper.Player;
			if ((Object)(object)player == (Object)null)
			{
				return null;
			}
			if (request.code == "ohko")
			{
				if (player.hp > 1)
				{
					player.hp = 1;
				}
			}
			else
			{
				if (player.dead || player.hp <= 0)
				{
					return null;
				}
				float num = 100f;
				int property = player.GetProperty<int>("difficulty");
				if (property == 0 || (property == 1 && player.sameCheckpointRestarts > 2))
				{
					num = 200f;
				}
				checked
				{
					player.hp = (int)num;
					_frames++;
				}
				if (_frames % 16 == 0 && (Object)(object)player.hpFlash != (Object)null)
				{
					player.hpFlash.Flash(1f);
				}
			}
			return null;
		}

		public override EffectResponse? Stop(EffectRequest request)
		{
			if (request.code != "ohko")
			{
				return EffectResponse.Finished(((SimpleJSONMessage)request).ID, (string)null);
			}
			NewMovement player = GameHelper.Player;
			if ((Object)(object)player != (Object)null)
			{
				float num = 100f;
				int property = player.GetProperty<int>("difficulty");
				if (property == 0 || (property == 1 && player.sameCheckpointRestarts > 2))
				{
					num = 200f;
				}
				player.hp = checked((int)num);
			}
			return EffectResponse.Finished(((SimpleJSONMessage)request).ID, (string)null);
		}
	}
	[Effect("nodash", 30f, true)]
	public class NoDashEffect : Effect
	{
		public NoDashEffect(CrowdControlMod mod, NetworkClient client)
			: base(mod, client)
		{
		}

		public override EffectResponse Start(EffectRequest request)
		{
			if (HasConflict(request))
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
			return EffectResponse.Success(((SimpleJSONMessage)request).ID, (string)null);
		}

		public override EffectResponse? Tick(EffectRequest request)
		{
			NewMovement player = GameHelper.Player;
			if ((Object)(object)player != (Object)null)
			{
				player.modNoDashSlide = true;
			}
			return null;
		}

		public override EffectResponse? Stop(EffectRequest request)
		{
			NewMovement player = GameHelper.Player;
			if ((Object)(object)player != (Object)null)
			{
				player.modNoDashSlide = false;
			}
			return EffectResponse.Finished(((SimpleJSONMessage)request).ID, (string)null);
		}
	}
	[Effect("nojump", 30f, new string[] { "nojump", "lowjump", "highjump", "ultrajump" })]
	public class NoJumpEffect : Effect
	{
		public NoJumpEffect(CrowdControlMod mod, NetworkClient client)
			: base(mod, client)
		{
		}

		public override EffectResponse Start(EffectRequest request)
		{
			if (HasConflict(request))
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
			return EffectResponse.Success(((SimpleJSONMessage)request).ID, (string)null);
		}

		public override EffectResponse? Tick(EffectRequest request)
		{
			NewMovement player = GameHelper.Player;
			if ((Object)(object)player != (Object)null)
			{
				player.modNoJump = true;
			}
			return null;
		}

		public override EffectResponse? Stop(EffectRequest request)
		{
			NewMovement player = GameHelper.Player;
			if ((Object)(object)player != (Object)null)
			{
				player.modNoJump = false;
			}
			return EffectResponse.Finished(((SimpleJSONMessage)request).ID, (string)null);
		}
	}
	[Effect("autoparry", 30f, true)]
	public class AutoParryEffect : Effect
	{
		public AutoParryEffect(CrowdControlMod mod, NetworkClient client)
			: base(mod, client)
		{
		}

		public override EffectResponse Start(EffectRequest request)
		{
			if (HasConflict(request))
			{
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
			return EffectResponse.Success(((SimpleJSONMessage)request).ID, (string)null);
		}

		public override EffectResponse? Tick(EffectRequest request)
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			NewMovement player = GameHelper.Player;
			FistControl instance = MonoSingleton<FistControl>.Instance;
			if ((Object)(object)player == (Object)null || (Object)(object)instance?.currentPunch == (Object)null)
			{
				return null;
			}
			List<Projectile> list = Object.FindObjectsOfType<Projectile>().ToList();
			list.RemoveAll((Projectile x) => (Object)(object)x == (Object)null || x.friendly || x.parried);
			foreach (Projectile item in list)
			{
				Vector3 val = ((Component)item).transform.position - ((Component)player).transform.position;
				if (((Vector3)(ref val)).magnitude < 2f)
				{
					instance.currentPunch.CallMethod("ParryProjectile", item);
				}
			}
			return null;
		}
	}
	[Effect("punch")]
	public class PunchEffect : Effect
	{
		public PunchEffe

BepInEx/plugins/CrowdControl/HypeTrain.dll

Decompiled 10 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
public class HypeTrainTester : MonoBehaviour
{
	[SerializeField]
	private string[] m_names = new string[0];

	[SerializeField]
	private HypeTrain m_hypeTrainPrototype;

	[SerializeField]
	private Transform m_startTransform;

	[SerializeField]
	private Transform m_endTransform;

	[SerializeField]
	private Transform m_playerTransform;

	private HypeTrain m_createdHypeTrain;

	private void Start()
	{
		((MonoBehaviour)this).StartCoroutine(StartTest());
	}

	private IEnumerator StartTest()
	{
		yield return (object)new WaitForSeconds(0.5f);
		m_createdHypeTrain = Object.Instantiate<HypeTrain>(m_hypeTrainPrototype);
		m_createdHypeTrain.OnFinishedEvent.AddListener(new UnityAction(ResetTest));
		HypeTrainBoxData[] array = new HypeTrainBoxData[m_names.Length];
		for (int i = 0; i < m_names.Length; i++)
		{
			array[i] = new HypeTrainBoxData
			{
				name = m_names[i],
				box_color = Color.HSVToRGB(Random.value, 1f, 1f),
				box_color_rate = (((i & 1) != 0) ? ((Random.Range(0, 1) == 0) ? (-0.2f) : 1f) : 0f),
				bit_amount = ((i % 4 == 0) ? Random.Range(1, 1000000) : 0),
				name_color = Color.HSVToRGB(Random.value, 1f, 1f)
			};
		}
		m_createdHypeTrain.StartHypeTrain(m_startTransform.position, m_endTransform.position, array, m_playerTransform);
	}

	private void ResetTest()
	{
		if ((Object)null != (Object)(object)m_createdHypeTrain)
		{
			Object.Destroy((Object)(object)((Component)m_createdHypeTrain).gameObject);
			m_createdHypeTrain = null;
		}
		((MonoBehaviour)this).StartCoroutine(StartTest());
	}
}
public class HypeTrainBit : MonoBehaviour
{
	[SerializeField]
	private Animator m_animator;

	[SerializeField]
	private int m_bitValue;

	[SerializeField]
	private Rigidbody m_rigidbody;

	[SerializeField]
	private Collider m_collider;

	[SerializeField]
	private float m_lifeTime = 20f;

	private IEnumerator m_deathCoroutine;

	private static readonly int s_deathTrigger = Animator.StringToHash("Death");

	public int BitValue => m_bitValue;

	public Rigidbody Rigidbody => m_rigidbody;

	public Collider Collider => m_collider;

	public float LifeTime
	{
		get
		{
			return m_lifeTime;
		}
		set
		{
			m_lifeTime = value;
		}
	}

	private void Awake()
	{
		m_animator.StopPlayback();
	}

	public void StartDeathCountdown()
	{
		if (m_deathCoroutine != null)
		{
			((MonoBehaviour)this).StopCoroutine(m_deathCoroutine);
			m_deathCoroutine = null;
		}
		m_deathCoroutine = Death();
		((MonoBehaviour)this).StartCoroutine(m_deathCoroutine);
	}

	private IEnumerator Death()
	{
		yield return (object)new WaitForSeconds(m_lifeTime);
		m_animator.Play(s_deathTrigger, 0, 0f);
	}

	private void Kill()
	{
		Object.Destroy((Object)(object)((Component)this).gameObject);
	}
}
public class HypeTrain : MonoBehaviour
{
	[SerializeField]
	private Rigidbody m_rigidBody;

	[SerializeField]
	private HypeTrainCarAudio m_carWheelsAudio;

	[SerializeField]
	private HypeTrainLocomotive m_locomotive;

	[SerializeField]
	private HypeTrainBox m_boxPrototype;

	[SerializeField]
	private HypeTrainBitBox m_bitboxPrototype;

	[SerializeField]
	private float m_distancePerSecond = 4f;

	[SerializeField]
	private HypeTrainBit[] m_bitPrototypes = new HypeTrainBit[0];

	[SerializeField]
	private bool m_keepAliveOnFinish;

	[SerializeField]
	private Shader m_builtinShader;

	[SerializeField]
	private Shader m_urpShader;

	[SerializeField]
	private Shader m_hdrpShader;

	private UnityEvent m_onFinishedEvent = new UnityEvent();

	private List<HypeTrainBox> m_activeBoxes = new List<HypeTrainBox>();

	private Queue<HypeTrainBox> m_availableBoxes = new Queue<HypeTrainBox>();

	private Queue<HypeTrainBitBox> m_availableBitBoxes = new Queue<HypeTrainBitBox>();

	private Vector3 m_startPosition = Vector3.zero;

	private Vector3 m_stopPosition = Vector3.zero;

	private Vector3 m_direction = Vector3.zero;

	private float m_trackDistance;

	private Transform m_playerRoot;

	private int m_nextBoxIndexToSpawn;

	private float m_nextBoxOffset;

	private HypeTrainBoxData[] m_boxData;

	private bool m_shadersDistributed;

	public UnityEvent OnFinishedEvent => m_onFinishedEvent;

	private void Awake()
	{
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		m_bitPrototypes = m_bitPrototypes.OrderByDescending((HypeTrainBit bit) => bit.BitValue).ToArray();
		((Component)m_locomotive).transform.localPosition = -m_locomotive.FrontLoc.localPosition;
		((UnityEvent<HypeTrainCar, HypeTrainCar.Visibility>)m_locomotive.OnVisibilityChangedEvent).AddListener((UnityAction<HypeTrainCar, HypeTrainCar.Visibility>)OnLocomotiveFinished);
		StopHypeTrain();
		((Component)m_boxPrototype).gameObject.SetActive(false);
		((Component)m_bitboxPrototype).gameObject.SetActive(false);
	}

	private void FixedUpdate()
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: 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)
		float num = Time.deltaTime * m_distancePerSecond;
		m_rigidBody.MovePosition(m_rigidBody.position + m_direction * num);
		m_locomotive.UpdateCar(Time.deltaTime, num);
		foreach (HypeTrainBox activeBox in m_activeBoxes)
		{
			activeBox.UpdateCar(Time.deltaTime, num);
		}
		m_carWheelsAudio.UpdateAudio(Time.deltaTime, num, m_locomotive, m_activeBoxes, m_playerRoot);
	}

	public void StartHypeTrain(Vector3 startWorldPosition, Vector3 stopWorldPosition, HypeTrainBoxData[] boxData, Transform playerRoot = null, HypeTrainOptions options = null)
	{
		//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_000e: 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_0015: Unknown result type (might be due to invalid IL or missing references)
		//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_0036: 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_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: 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_0175: Unknown result type (might be due to invalid IL or missing references)
		//IL_017c: Unknown result type (might be due to invalid IL or missing references)
		StopHypeTrain();
		m_startPosition = startWorldPosition;
		m_stopPosition = stopWorldPosition;
		Vector3 val = m_stopPosition - m_startPosition;
		m_trackDistance = ((Vector3)(ref val)).magnitude;
		m_direction = ((Vector3)(ref val)).normalized;
		m_boxData = boxData;
		m_playerRoot = playerRoot;
		m_nextBoxIndexToSpawn = 0;
		m_nextBoxOffset = 0f - m_locomotive.CalculateCarLength();
		m_distancePerSecond = ((options != null && options.distance_per_second.HasValue) ? options.distance_per_second.Value : m_distancePerSecond);
		m_keepAliveOnFinish = ((options != null && options.keep_alive_on_finish.HasValue) ? options.keep_alive_on_finish.Value : m_keepAliveOnFinish);
		if (options != null && options.train_layer.HasValue)
		{
			SetLayerRecursive(((Component)this).gameObject, options.train_layer.Value);
			HypeTrainBit[] bitPrototypes = m_bitPrototypes;
			foreach (HypeTrainBit hypeTrainBit in bitPrototypes)
			{
				SetLayerRecursive(((Component)hypeTrainBit).gameObject, options.train_layer.Value);
			}
		}
		if (options != null && options.volume.HasValue)
		{
			SetVolume(options.volume.Value);
		}
		Transform transform = ((Component)this).transform;
		Vector3 position = (m_rigidBody.position = startWorldPosition);
		transform.position = position;
		Transform transform2 = ((Component)this).transform;
		Quaternion rotation = (m_rigidBody.rotation = Quaternion.LookRotation(m_direction));
		transform2.rotation = rotation;
		int num = Mathf.Min(Mathf.CeilToInt((m_trackDistance + m_boxPrototype.CalculateCarLength()) / m_boxPrototype.CalculateCarLength()), boxData.Length);
		for (int j = 0; j < num; j++)
		{
			HypeTrainBox hypeTrainBox = Object.Instantiate<HypeTrainBox>(m_boxPrototype, ((Component)m_boxPrototype).transform.parent, false);
			((UnityEvent<HypeTrainCar, HypeTrainCar.Visibility>)hypeTrainBox.OnVisibilityChangedEvent).AddListener((UnityAction<HypeTrainCar, HypeTrainCar.Visibility>)OnBoxFinished);
			m_availableBoxes.Enqueue(hypeTrainBox);
		}
		num = Mathf.Min(Mathf.CeilToInt((m_trackDistance + m_bitboxPrototype.CalculateCarLength()) / m_bitboxPrototype.CalculateCarLength()), boxData.Length);
		for (int k = 0; k < num; k++)
		{
			HypeTrainBitBox hypeTrainBitBox = Object.Instantiate<HypeTrainBitBox>(m_bitboxPrototype, ((Component)m_bitboxPrototype).transform.parent, false);
			hypeTrainBitBox.Init(m_bitPrototypes, playerRoot, options?.player_collider_radius, options?.max_bits_per_car, options?.bit_lifetime_in_seconds);
			((UnityEvent<HypeTrainCar, HypeTrainCar.Visibility>)hypeTrainBitBox.OnVisibilityChangedEvent).AddListener((UnityAction<HypeTrainCar, HypeTrainCar.Visibility>)OnBoxFinished);
			m_availableBitBoxes.Enqueue(hypeTrainBitBox);
		}
		m_carWheelsAudio.StartPersistentSounds();
		((Component)m_locomotive).gameObject.SetActive(true);
		m_locomotive.Engage(0f, m_trackDistance + m_locomotive.CalculateCarLength(), 0);
		FlushAvailableBoxes();
	}

	public void StopHypeTrain()
	{
		m_carWheelsAudio.StopPersistentSounds();
		foreach (HypeTrainBox availableBox in m_availableBoxes)
		{
			Object.Destroy((Object)(object)((Component)availableBox).gameObject);
		}
		m_availableBoxes.Clear();
		foreach (HypeTrainBitBox availableBitBox in m_availableBitBoxes)
		{
			Object.Destroy((Object)(object)((Component)availableBitBox).gameObject);
		}
		m_availableBitBoxes.Clear();
		foreach (HypeTrainBox activeBox in m_activeBoxes)
		{
			Object.Destroy((Object)(object)((Component)activeBox).gameObject);
		}
		m_activeBoxes.Clear();
		((Component)m_locomotive).gameObject.SetActive(false);
	}

	public void SetDistancePerSecond(float distancePerSecond)
	{
		m_distancePerSecond = distancePerSecond;
	}

	public void SetKeepAliveOnFinish(bool keepAlive)
	{
		m_keepAliveOnFinish = keepAlive;
	}

	public void SetVolume(float volume)
	{
		m_locomotive.SetBaseVolume(volume);
		m_carWheelsAudio.SetBaseVolume(volume);
	}

	private void OnLocomotiveFinished(HypeTrainCar car, HypeTrainCar.Visibility visibility)
	{
		if (visibility == HypeTrainCar.Visibility.Hidden)
		{
			FlushAvailableBoxes();
		}
	}

	private void OnBoxFinished(HypeTrainCar car, HypeTrainCar.Visibility visibility)
	{
		if (visibility == HypeTrainCar.Visibility.Hidden)
		{
			m_activeBoxes.Remove((HypeTrainBox)car);
			if (((object)car).GetType() == typeof(HypeTrainBitBox))
			{
				HypeTrainBitBox item = (HypeTrainBitBox)car;
				m_availableBitBoxes.Enqueue(item);
			}
			else
			{
				m_availableBoxes.Enqueue((HypeTrainBox)car);
			}
			FlushAvailableBoxes();
		}
	}

	private void FlushAvailableBoxes()
	{
		//IL_003e: 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_0054: 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_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		while (m_nextBoxIndexToSpawn < m_boxData.Length && m_availableBoxes.Count != 0)
		{
			HypeTrainBoxData hypeTrainBoxData = m_boxData[m_nextBoxIndexToSpawn];
			HypeTrainBox hypeTrainBox = null;
			hypeTrainBox = ((hypeTrainBoxData.bit_amount <= 0) ? m_availableBoxes.Dequeue() : m_availableBitBoxes.Dequeue());
			((Component)hypeTrainBox).transform.localPosition = Vector3.forward * m_nextBoxOffset - hypeTrainBox.FrontLoc.localPosition;
			float num = hypeTrainBox.CalculateCarLength();
			float num2 = Mathf.Abs(m_nextBoxOffset);
			Vector3 val = ((Component)this).transform.position - m_startPosition;
			float num3 = num2 - ((Vector3)(ref val)).magnitude;
			hypeTrainBox.Engage(hypeTrainBoxData, num3, num3 + m_trackDistance + num, m_nextBoxIndexToSpawn + 1);
			m_activeBoxes.Add(hypeTrainBox);
			m_nextBoxIndexToSpawn++;
			m_nextBoxOffset -= num;
		}
		bool flag = false;
		flag |= ((Component)m_locomotive).gameObject.activeSelf;
		foreach (HypeTrainBox activeBox in m_activeBoxes)
		{
			flag |= ((Component)activeBox).gameObject.activeSelf;
		}
		if (!flag)
		{
			OnFinishedEvent.Invoke();
			StopHypeTrain();
			if (!m_keepAliveOnFinish)
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}
	}

	private void SetLayerRecursive(GameObject go, int layer)
	{
		go.layer = layer;
		for (int i = 0; i < go.transform.childCount; i++)
		{
			SetLayerRecursive(((Component)go.transform.GetChild(i)).gameObject, layer);
		}
	}
}
public class HypeTrainBitBox : HypeTrainBox
{
	[SerializeField]
	private BoxCollider m_bitSpawnZone;

	[SerializeField]
	private int m_maxBitBreaks = 100;

	[SerializeField]
	private TextMeshPro[] m_bitsTexts = (TextMeshPro[])(object)new TextMeshPro[0];

	[SerializeField]
	private HypeTrainBitBoxPlayerCollider m_playerCollider;

	private List<HypeTrainBit> m_createdBits = new List<HypeTrainBit>();

	private HypeTrainBit[] m_bitPrototypes;

	private int? m_maxBitsToSpawn;

	private float? m_bitLifetimeInSeconds;

	public void Init(HypeTrainBit[] bitPrototypes, Transform playerRoot, float? playerColliderRadius = null, int? maxBitsToSpawn = null, float? bitLifetimeInSeconds = null)
	{
		m_bitPrototypes = bitPrototypes;
		m_maxBitsToSpawn = maxBitsToSpawn;
		m_bitLifetimeInSeconds = bitLifetimeInSeconds;
		m_playerCollider.Init(this, playerRoot, playerColliderRadius);
	}

	public override void Engage(HypeTrainBoxData data, float distanceToStart, float distanceToStop, int index)
	{
		base.Engage(data, distanceToStart, distanceToStop, index);
		TextMeshPro[] bitsTexts = m_bitsTexts;
		for (int i = 0; i < bitsTexts.Length; i++)
		{
			((TMP_Text)bitsTexts[i]).SetText($"BITS: {data.bit_amount}", true);
		}
		SpawnBits(data.bit_amount);
	}

	public void SpawnBits(int amount)
	{
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		RelinquishCreatedBits();
		if (m_bitPrototypes == null)
		{
			return;
		}
		int num = (m_maxBitsToSpawn.HasValue ? m_maxBitsToSpawn.Value : amount);
		int num2 = m_maxBitBreaks;
		Vector3 localPosition = default(Vector3);
		while (amount > 0 && num > 0)
		{
			int num3 = amount;
			if (0 < num2)
			{
				num3 = Random.Range(1, amount + 1);
			}
			amount -= num3;
			while (0 < num3 && num > 0)
			{
				HypeTrainBit[] bitPrototypes = m_bitPrototypes;
				foreach (HypeTrainBit hypeTrainBit in bitPrototypes)
				{
					if (hypeTrainBit.BitValue <= num3)
					{
						num3 -= hypeTrainBit.BitValue;
						num--;
						((Vector3)(ref localPosition))..ctor(Random.Range((0f - m_bitSpawnZone.size.x) * 0.5f, m_bitSpawnZone.size.x * 0.5f), 0f, Random.Range((0f - m_bitSpawnZone.size.z) * 0.5f, m_bitSpawnZone.size.z * 0.5f));
						HypeTrainBit hypeTrainBit2 = Object.Instantiate<HypeTrainBit>(hypeTrainBit, ((Component)m_bitSpawnZone).transform, false);
						((Component)hypeTrainBit2).transform.localPosition = localPosition;
						hypeTrainBit2.Rigidbody.isKinematic = true;
						hypeTrainBit2.Collider.enabled = true;
						m_createdBits.Add(hypeTrainBit2);
					}
				}
			}
			num2--;
		}
	}

	protected override void OnShowFinished()
	{
		base.OnShowFinished();
		if (m_createdBits.Count == 0)
		{
			SpawnBits(100);
		}
	}

	protected override void OnHideFinished()
	{
		base.OnHideFinished();
		foreach (HypeTrainBit createdBit in m_createdBits)
		{
			Object.Destroy((Object)(object)((Component)createdBit).gameObject);
		}
		m_createdBits.Clear();
	}

	public void RelinquishCreatedBits()
	{
		foreach (HypeTrainBit createdBit in m_createdBits)
		{
			createdBit.Rigidbody.isKinematic = false;
			createdBit.Collider.enabled = true;
			((Component)createdBit).transform.SetParent((Transform)null, true);
			if (m_bitLifetimeInSeconds.HasValue)
			{
				createdBit.LifeTime = m_bitLifetimeInSeconds.Value;
			}
			createdBit.StartDeathCountdown();
		}
		m_createdBits.Clear();
	}
}
public class HypeTrainBitBoxPlayerCollider : MonoBehaviour
{
	[SerializeField]
	private SphereCollider m_collider;

	private HypeTrainBitBox m_owner;

	private Transform m_playerRoot;

	public void Init(HypeTrainBitBox owner, Transform playerRoot, float? playerColliderRadius = null)
	{
		m_owner = owner;
		m_playerRoot = playerRoot;
		if (playerColliderRadius.HasValue)
		{
			m_collider.radius = playerColliderRadius.Value;
		}
	}

	private void OnCollisionEnter(Collision other)
	{
		if ((Object)null != (Object)(object)m_owner && (Object)(object)other.transform == (Object)(object)m_playerRoot)
		{
			m_owner.RelinquishCreatedBits();
		}
	}

	private void OnTriggerEnter(Collider other)
	{
		if ((Object)null != (Object)(object)m_owner && (Object)(object)((Component)other).transform == (Object)(object)m_playerRoot)
		{
			m_owner.RelinquishCreatedBits();
		}
	}
}
public class HypeTrainBox : HypeTrainCar
{
	[SerializeField]
	private TextMeshPro[] m_nameTexts;

	private Material m_carMaterial;

	private Color m_carColor;

	private float m_carColorRate;

	private static int s_trimColorMaterialPropertyID = Shader.PropertyToID("_TrimColor");

	public virtual void Engage(HypeTrainBoxData data, float distanceToStart, float distanceToStop, int index)
	{
		//IL_0012: 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)
		Engage(distanceToStart, distanceToStop, index);
		SetName(data.name, data.name_color);
		SetBoxColor(data.box_color, data.box_color_rate);
	}

	public override void UpdateCar(float dt, float delta)
	{
		//IL_0016: 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)
		base.UpdateCar(dt, delta);
		if (m_carColorRate != 0f)
		{
			float num2 = default(float);
			float num3 = default(float);
			float num = default(float);
			Color.RGBToHSV(m_carColor, ref num, ref num2, ref num3);
			for (num += m_carColorRate * delta; num > 1f; num -= 1f)
			{
			}
			for (; num < 0f; num += 1f)
			{
			}
			SetBoxColor(Color.HSVToRGB(num, num2, num3), m_carColorRate);
		}
	}

	public void SetName(string name, Color nameColor)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		TextMeshPro[] nameTexts = m_nameTexts;
		foreach (TextMeshPro obj in nameTexts)
		{
			((TMP_Text)obj).SetText(name, true);
			((Graphic)obj).color = nameColor;
		}
	}

	public void SetBoxColor(Color color, float carColorRate)
	{
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Expected O, but got Unknown
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)null == (Object)(object)m_carMaterial)
		{
			m_carMaterial = new Material(((Renderer)base.Meshes[0]).material);
			MeshRenderer[] meshes = base.Meshes;
			for (int i = 0; i < meshes.Length; i++)
			{
				((Renderer)meshes[i]).material = m_carMaterial;
			}
		}
		m_carColor = color;
		if ((Object)null != (Object)(object)m_carMaterial)
		{
			m_carMaterial.SetColor(s_trimColorMaterialPropertyID, color);
		}
		m_carColorRate = carColorRate;
	}
}
[Serializable]
public class HypeTrainBoxData
{
	public string name = "";

	public Color name_color = new Color(1f, 1f, 1f);

	public Color box_color = new Color(0.3803921f, 0.7960785f, 0.545098f);

	public float box_color_rate;

	public int bit_amount;
}
public class HypeTrainCar : MonoBehaviour
{
	public enum Visibility
	{
		Visible,
		Hidden
	}

	public class VisibilityChangedEvent : UnityEvent<HypeTrainCar, Visibility>
	{
	}

	[SerializeField]
	private Animator m_animatorRoot;

	[SerializeField]
	private Animator m_animatorCar;

	[SerializeField]
	private Transform m_frontLoc;

	[SerializeField]
	private Transform m_backLoc;

	[SerializeField]
	private MeshRenderer[] m_meshes = (MeshRenderer[])(object)new MeshRenderer[0];

	private VisibilityChangedEvent m_onVisibilityChangedEvent = new VisibilityChangedEvent();

	private float m_distanceToStart;

	private float m_distanceToStop;

	private static readonly int s_animShowTag = Animator.StringToHash("Show");

	private static readonly int s_animHideTag = Animator.StringToHash("Hide");

	private static readonly int s_animWobbleTag = Animator.StringToHash("Wobble");

	protected MeshRenderer[] Meshes => m_meshes;

	public Transform FrontLoc => m_frontLoc;

	public Transform BackLoc => m_backLoc;

	public VisibilityChangedEvent OnVisibilityChangedEvent => m_onVisibilityChangedEvent;

	public void Engage(float distanceToStart, float distanceToStop, int index)
	{
		m_distanceToStart = distanceToStart;
		m_distanceToStop = distanceToStop;
		if (m_distanceToStart <= 0f)
		{
			Show();
			float num = 5f;
			m_animatorCar.Play(s_animWobbleTag, 0, (float)index % (num + 1f) / num);
		}
		if (m_distanceToStop <= 0f)
		{
			Hide();
		}
	}

	public virtual void UpdateCar(float dt, float delta)
	{
		if (m_distanceToStart > 0f)
		{
			m_distanceToStart -= delta;
			if (m_distanceToStart <= 0f)
			{
				m_distanceToStart = 0f;
				Show();
			}
		}
		if (m_distanceToStop > 0f)
		{
			m_distanceToStop -= delta;
			if (m_distanceToStop <= 0f)
			{
				m_distanceToStop = 0f;
				Hide();
			}
		}
	}

	public virtual void Show()
	{
		((Component)this).gameObject.SetActive(true);
		m_animatorRoot.Play(s_animShowTag, 0, 0f);
	}

	public virtual void Hide()
	{
		m_animatorRoot.Play(s_animHideTag, 0, 0f);
	}

	public float CalculateCarLength()
	{
		//IL_0006: 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_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = m_frontLoc.localPosition - m_backLoc.localPosition;
		return ((Vector3)(ref val)).magnitude;
	}

	protected virtual void OnShowFinished()
	{
		((UnityEvent<HypeTrainCar, Visibility>)m_onVisibilityChangedEvent).Invoke(this, Visibility.Visible);
	}

	protected virtual void OnHideFinished()
	{
		((Component)this).gameObject.SetActive(false);
		((UnityEvent<HypeTrainCar, Visibility>)m_onVisibilityChangedEvent).Invoke(this, Visibility.Hidden);
	}
}
public class HypeTrainCarAudio : MonoBehaviour
{
	[SerializeField]
	private AudioSource m_carWheelsAudio;

	[SerializeField]
	private AudioSource m_carWheelsClankAudio;

	[SerializeField]
	private AudioClip[] m_carWheelsClankAudioClips = (AudioClip[])(object)new AudioClip[0];

	[SerializeField]
	private int m_maxSimultaneousClanks = 3;

	[SerializeField]
	private float m_clankMinInterval = 0.1f;

	[SerializeField]
	private float m_clankMaxInterval = 0.5f;

	private float m_nextClankTimer;

	private float[] m_clankTimers;

	private float m_wheelVolume = 1f;

	private float m_baseVolume = 1f;

	private void Awake()
	{
		m_clankTimers = new float[m_maxSimultaneousClanks];
	}

	public void StartPersistentSounds()
	{
		m_carWheelsAudio.Play();
	}

	public void StopPersistentSounds()
	{
		m_carWheelsAudio.Stop();
	}

	public void UpdateAudio(float dt, float delta, HypeTrainLocomotive locomotive, List<HypeTrainBox> activeBoxes, Transform playerRoot)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: 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_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_00dd: 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_0031: 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)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		Vector3 position = ((Component)locomotive).transform.position;
		float x = ((Component)locomotive).transform.lossyScale.x;
		if ((Object)null != (Object)(object)playerRoot)
		{
			float num = Vector3.SqrMagnitude(playerRoot.position - position);
			foreach (HypeTrainBox activeBox in activeBoxes)
			{
				float num2 = Vector3.SqrMagnitude(playerRoot.position - ((Component)activeBox).transform.position);
				if (num2 < num)
				{
					num = num2;
					position = ((Component)activeBox).transform.position;
					x = ((Component)activeBox).transform.lossyScale.x;
				}
			}
		}
		position.y += 0.75f;
		((Component)this).transform.position = Vector3.MoveTowards(((Component)m_carWheelsAudio).transform.position, position, delta * 4f);
		m_wheelVolume = Mathf.MoveTowards(m_wheelVolume, x, dt * 2f);
		AudioSource carWheelsAudio = m_carWheelsAudio;
		float volume = (m_carWheelsClankAudio.volume = m_baseVolume * m_wheelVolume);
		carWheelsAudio.volume = volume;
		if (m_nextClankTimer > 0f)
		{
			m_nextClankTimer -= dt;
			if (m_nextClankTimer <= 0f)
			{
				for (int i = 0; i < m_maxSimultaneousClanks; i++)
				{
					if (m_clankTimers[i] <= 0f)
					{
						AudioClip val = m_carWheelsClankAudioClips[Random.Range(0, m_carWheelsClankAudioClips.Length)];
						m_clankTimers[i] = val.length;
						m_carWheelsClankAudio.PlayOneShot(val);
						break;
					}
				}
			}
		}
		for (int j = 0; j < m_maxSimultaneousClanks; j++)
		{
			m_clankTimers[j] -= dt;
			if (m_clankTimers[j] <= 0f)
			{
				while (m_nextClankTimer <= 0f)
				{
					m_nextClankTimer += Random.Range(m_clankMinInterval, m_clankMaxInterval);
				}
			}
		}
	}

	public void SetBaseVolume(float volume)
	{
		m_baseVolume = volume;
		AudioSource carWheelsAudio = m_carWheelsAudio;
		float volume2 = (m_carWheelsClankAudio.volume = m_baseVolume * m_wheelVolume);
		carWheelsAudio.volume = volume2;
	}
}
public class HypeTrainLocomotive : HypeTrainCar
{
	[SerializeField]
	private AudioSource m_audioSource;

	private float m_baseVolume = 1f;

	public override void Show()
	{
		base.Show();
		m_audioSource.Play();
	}

	protected override void OnHideFinished()
	{
		base.OnHideFinished();
		m_audioSource.Stop();
	}

	public override void UpdateCar(float dt, float delta)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		base.UpdateCar(dt, delta);
		m_audioSource.volume = m_baseVolume * Mathf.Clamp01(((Component)this).transform.lossyScale.x);
	}

	public void SetBaseVolume(float volume)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		m_baseVolume = volume;
		m_audioSource.volume = m_baseVolume * Mathf.Clamp01(((Component)this).transform.lossyScale.x);
	}
}
[Serializable]
public class HypeTrainOptions
{
	public int? train_layer;

	public float? distance_per_second;

	public float? player_collider_radius;

	public int? max_bits_per_car;

	public float? bit_lifetime_in_seconds;

	public float? volume;

	public bool? keep_alive_on_finish;
}