Decompiled source of Type05 v1.0.0

Y4NGZType05.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Dawn;
using Dissonance;
using DunGen;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Animations;
using UnityEngine.Audio;
using UnityEngine.Events;
using UnityEngine.Experimental.Animations;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Playables;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;
using UnityEngine.Video;
using Y4NGZCompany.Facility.Interior.Placement;
using Y4NGZMonsters.Shared;
using Y4NGZType05;
using Y4NGZType05.NetcodePatcher;
using Y4NGZType05.Patches;
using Y4NGZType05.World;

[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("Y4NGZType05")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+597d0743e3d9fad0ef076615b4f8bdf577fcfd15")]
[assembly: AssemblyProduct("Y4NGZType05")]
[assembly: AssemblyTitle("Y4NGZType05")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Y4NGZType05
{
	internal static class Type05AudioAssets
	{
		private const string CuesTablePath = "Assets/Y4NGZ/Type05/Tables/cues.json";

		private const string EventsTablePath = "Assets/Y4NGZ/Type05/Tables/events.json";

		private const int ListedMissingFiles = 10;

		internal static Type05CueCatalogue Catalogue { get; private set; }

		internal static AudioClip[] Clips { get; private set; }

		internal static bool Load(AssetBundle bundle)
		{
			TextAsset val = bundle.LoadAsset<TextAsset>("Assets/Y4NGZ/Type05/Tables/cues.json");
			TextAsset val2 = bundle.LoadAsset<TextAsset>("Assets/Y4NGZ/Type05/Tables/events.json");
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
			{
				return Fail("the bundle has no " + (((Object)(object)val != (Object)null) ? "Assets/Y4NGZ/Type05/Tables/events.json" : (((Object)(object)val2 != (Object)null) ? "Assets/Y4NGZ/Type05/Tables/cues.json" : "Assets/Y4NGZ/Type05/Tables/cues.json or Assets/Y4NGZ/Type05/Tables/events.json")));
			}
			Type05CueCatalogue type05CueCatalogue;
			try
			{
				type05CueCatalogue = Type05CueCatalogue.Compile(val.text, val2.text);
			}
			catch (Type05CueDataException ex)
			{
				return Fail(ex.Message);
			}
			string error;
			Type05CatchTimeline[] array = Type05CatchTimeline.Compile(Type05CueTables.Read(val.text, val2.text), out error);
			if (array == null)
			{
				Plugin.Log.LogError((object)("[Type05] catch timelines not compiled, the robot cannot catch: " + error));
			}
			Plugin.CatchTimelines = array;
			for (int i = 0; i < type05CueCatalogue.CueCount; i++)
			{
				if (type05CueCatalogue.MaxLeaves(i) > 255)
				{
					return Fail($"cue '{type05CueCatalogue.CueName(i)}' can play {type05CueCatalogue.MaxLeaves(i)} sounds at once, more than the {byte.MaxValue} one cue message carries");
				}
			}
			AudioClip[] array2 = (AudioClip[])(object)new AudioClip[type05CueCatalogue.FileCount];
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			for (int j = 0; j < array2.Length; j++)
			{
				array2[j] = bundle.LoadAsset<AudioClip>(type05CueCatalogue.FileAssetPath(j));
				if ((Object)(object)array2[j] == (Object)null && num++ < 10)
				{
					stringBuilder.Append((num == 1) ? string.Empty : ", ").Append(type05CueCatalogue.FileAssetPath(j));
				}
			}
			if (num > 0)
			{
				Plugin.Log.LogWarning((object)string.Format("[Type05] audio catalogue: {0} of {1} sound files are missing from the bundle, those sounds stay silent: {2}{3}", num, array2.Length, stringBuilder, (num > 10) ? ", ..." : string.Empty));
			}
			Catalogue = type05CueCatalogue;
			Clips = array2;
			Plugin.Log.LogInfo((object)FormattableString.Invariant($"[Type05] audio catalogue: {type05CueCatalogue.CueCount} cues, {array2.Length - num} of {type05CueCatalogue.FileCount} files resolved, {type05CueCatalogue.SoundEventCount} sound events in {type05CueCatalogue.ClipsWithSoundEvents} clips, checksum 0x{type05CueCatalogue.Checksum:X8}"));
			return true;
		}

		private static bool Fail(string reason)
		{
			Plugin.Log.LogError((object)("[Type05] audio catalogue not loaded, the robot stays silent: " + reason));
			return false;
		}
	}
	internal sealed class Type05AudioPlayer
	{
		private struct ProofSample
		{
			public ulong EventId;

			public int Cue;

			public double Start;

			public double SampleAt;

			public float MaxRms;
		}

		private const float MinPitch = 0.05f;

		private const float MaxPitch = 4f;

		private const int PooledSourcePriority = 192;

		private const double ProofSampleDelay = 0.25;

		private const int ProofSampleLength = 1024;

		private static readonly AnimationCurve FlatRolloff = new AnimationCurve((Keyframe[])(object)new Keyframe[2]
		{
			new Keyframe(0f, 1f),
			new Keyframe(1f, 1f)
		});

		private static readonly bool ProofEnabled = Environment.GetEnvironmentVariable("Y4NGZ_PILOT") == "1";

		private readonly Transform _anchor;

		private readonly Type05CueCatalogue _catalogue;

		private readonly AudioClip[] _clips;

		private readonly float _maxDistance;

		private readonly Type05CueSchedule _schedule;

		private readonly List<AudioSource> _sources;

		private readonly List<int> _sourceLeaf;

		private readonly List<int> _stops = new List<int>();

		private readonly List<int> _starts = new List<int>();

		private readonly List<ProofSample> _proof;

		private readonly float[] _proofBuffer;

		private readonly StringBuilder _proofLine;

		public bool Routed { get; private set; }

		public bool Idle
		{
			get
			{
				for (int i = 0; i < _schedule.Capacity; i++)
				{
					if (_schedule.Record(i).State != Type05LeafState.Free)
					{
						return false;
					}
				}
				return true;
			}
		}

		public Type05AudioPlayer(Transform anchor, Type05CueCatalogue catalogue, AudioClip[] clips, int poolSize, float maxDistance)
		{
			_anchor = anchor;
			_catalogue = catalogue;
			_clips = clips;
			_maxDistance = maxDistance;
			_schedule = new Type05CueSchedule(catalogue, poolSize);
			_sources = new List<AudioSource>(poolSize);
			_sourceLeaf = new List<int>(poolSize);
			for (int i = 0; i < poolSize; i++)
			{
				AddSource();
			}
			if (ProofEnabled)
			{
				_proof = new List<ProofSample>();
				_proofBuffer = new float[1024];
				_proofLine = new StringBuilder();
			}
		}

		public static Vector3 ListenerPosition()
		{
			//IL_000f: 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_0053: 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)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return Vector3.positiveInfinity;
			}
			if ((Object)(object)instance.audioListener != (Object)null)
			{
				return ((Component)instance.audioListener).transform.position;
			}
			if (!((Object)(object)instance.activeCamera != (Object)null))
			{
				return Vector3.positiveInfinity;
			}
			return ((Component)instance.activeCamera).transform.position;
		}

		public float ListenerDistance()
		{
			//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)
			return Vector3.Distance(_anchor.position, ListenerPosition());
		}

		public bool Route(AudioSource extraA, AudioSource extraB)
		{
			bool flag = CreatureAudioSetup.ConfigureSpatial(extraA) & CreatureAudioSetup.ConfigureSpatial(extraB);
			for (int i = 0; i < _sources.Count; i++)
			{
				flag &= CreatureAudioSetup.ConfigureSpatial(_sources[i]);
			}
			Routed = flag;
			return flag;
		}

		public bool Accept(ulong eventId, int cue, double cueStart, float volume, float pitch, Type05CueGroup group, Type05CueLeafChoice[] leaves, int count, out string reject)
		{
			_stops.Clear();
			bool num = _schedule.Accept(eventId, cue, cueStart, volume, pitch, group, leaves, count, _stops, out reject);
			StopReported();
			if (num && _proof != null)
			{
				_proof.Add(new ProofSample
				{
					EventId = eventId,
					Cue = cue,
					Start = cueStart,
					SampleAt = cueStart + 0.25
				});
			}
			return num;
		}

		public void StopGroup(ulong eventId, Type05CueGroup group)
		{
			_stops.Clear();
			_schedule.StopGroup(eventId, group, _stops, out var _);
			StopReported();
		}

		public void Tick(double now, Vector3 listener)
		{
			//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)
			float distance = Vector3.Distance(_anchor.position, listener);
			for (int i = 0; i < _sources.Count; i++)
			{
				int num = _sourceLeaf[i];
				if (num >= 0)
				{
					if (_sources[i].isPlaying)
					{
						Apply(_sources[i], num, now, distance);
						continue;
					}
					_schedule.Release(num);
					_sourceLeaf[i] = -1;
				}
			}
			_starts.Clear();
			_schedule.Due(now, _starts, out var _);
			for (int j = 0; j < _starts.Count; j++)
			{
				int num2 = _starts[j];
				AudioClip val = _clips[_schedule.Record(num2).File];
				if ((Object)(object)val == (Object)null)
				{
					_schedule.Release(num2);
					continue;
				}
				int num3 = FreeSource();
				AudioSource val2 = _sources[num3];
				val2.clip = val;
				float num4 = _schedule.Seek(num2, now);
				if (num4 > 0f)
				{
					val2.time = num4;
				}
				Apply(val2, num2, now, distance);
				val2.Play();
				_schedule.MarkPlaying(num2, num3);
				_sourceLeaf[num3] = num2;
			}
			if (_proof != null && _proof.Count > 0)
			{
				SampleProof(now, distance);
			}
		}

		public void StopAll(out int stopped, out int cancelled)
		{
			_stops.Clear();
			_schedule.Reset(_stops, out cancelled);
			stopped = _stops.Count;
			StopReported();
			if (_proof != null)
			{
				_proof.Clear();
			}
		}

		private void Apply(AudioSource source, int leaf, double now, float distance)
		{
			ref readonly Type05LeafRecord reference = ref _schedule.Record(leaf);
			_catalogue.Envelope(reference.Cue, reference.Path, (float)(now - reference.CueStart), out var volume, out var pitch);
			source.volume = Mathf.Clamp01(reference.Volume * reference.CallerVolume * _catalogue.LayerGain(reference.Cue, reference.Path, distance) * volume);
			source.pitch = Mathf.Clamp(reference.Pitch * reference.CallerPitch * pitch, 0.05f, 4f);
		}

		private void StopReported()
		{
			for (int i = 0; i < _stops.Count; i++)
			{
				AudioSource val = _sources[_stops[i]];
				if ((Object)(object)val != (Object)null)
				{
					val.Stop();
				}
				_sourceLeaf[_stops[i]] = -1;
			}
		}

		private int FreeSource()
		{
			for (int i = 0; i < _sourceLeaf.Count; i++)
			{
				if (_sourceLeaf[i] < 0)
				{
					return i;
				}
			}
			int result = AddSource();
			Plugin.Log.LogInfo((object)$"[Type05] audio sources grown to {_sources.Count}");
			return result;
		}

		private int AddSource()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Type05Voice" + _sources.Count);
			val.transform.SetParent(_anchor, false);
			AudioSource val2 = val.AddComponent<AudioSource>();
			val2.playOnAwake = false;
			val2.loop = false;
			val2.priority = 192;
			val2.spatialBlend = 1f;
			val2.rolloffMode = (AudioRolloffMode)2;
			val2.SetCustomCurve((AudioSourceCurveType)0, FlatRolloff);
			val2.maxDistance = _maxDistance;
			if (Routed)
			{
				CreatureAudioSetup.ConfigureSpatial(val2);
			}
			_sources.Add(val2);
			_sourceLeaf.Add(-1);
			return _sources.Count - 1;
		}

		private void SampleProof(double now, float distance)
		{
			AudioListener.GetOutputData(_proofBuffer, 0);
			float num = 0f;
			for (int i = 0; i < _proofBuffer.Length; i++)
			{
				num += _proofBuffer[i] * _proofBuffer[i];
			}
			float num2 = Mathf.Sqrt(num / (float)_proofBuffer.Length);
			for (int num3 = _proof.Count - 1; num3 >= 0; num3--)
			{
				ProofSample sample = _proof[num3];
				if (now >= sample.Start && num2 > sample.MaxRms)
				{
					sample.MaxRms = num2;
					_proof[num3] = sample;
				}
				if (!(now < sample.SampleAt))
				{
					LogProof(in sample, distance);
					_proof[num3] = _proof[_proof.Count - 1];
					_proof.RemoveAt(_proof.Count - 1);
				}
			}
		}

		private void LogProof(in ProofSample sample, float distance)
		{
			StringBuilder stringBuilder = _proofLine.Clear().Append(FormattableString.Invariant($"[Type05] cue-listener event={sample.EventId} cue={_catalogue.CueName(sample.Cue)} dist={distance:F1} rms={sample.MaxRms:F4} leaves:"));
			string value = " ";
			for (int i = 0; i < _sources.Count; i++)
			{
				int num = _sourceLeaf[i];
				if (num >= 0 && _schedule.Record(num).EventId == sample.EventId)
				{
					ref readonly Type05LeafRecord reference = ref _schedule.Record(num);
					AudioSource val = _sources[i];
					AudioLowPassFilter component = ((Component)val).GetComponent<AudioLowPassFilter>();
					string text = (((Object)(object)component != (Object)null) ? FormattableString.Invariant($"{component.cutoffFrequency:F0}") : "none");
					string text2 = (((Object)(object)val.outputAudioMixerGroup != (Object)null) ? ((Object)val.outputAudioMixerGroup).name : "none");
					stringBuilder.Append(value).Append(FormattableString.Invariant($"{_catalogue.FileName(reference.File)} vol={val.volume:F3} layer={_catalogue.LayerGain(reference.Cue, reference.Path, distance):F3} lowpass={text} occlude={(Object)(object)((Component)val).GetComponent<OccludeAudio>() != (Object)null} mixer={text2}"));
					value = "; ";
				}
			}
			Plugin.Log.LogInfo((object)stringBuilder.ToString());
		}
	}
	internal enum Type05CueGroup : byte
	{
		None,
		Personality,
		Scanner,
		Weld,
		PowerState,
		Choke
	}
	internal enum Type05FootSide : byte
	{
		None,
		Left,
		Right
	}
	internal enum Type05CurveMode : byte
	{
		Linear,
		Cubic,
		Constant
	}
	internal readonly struct Type05CurveKey
	{
		public readonly float Time;

		public readonly float Value;

		public readonly float Arrive;

		public readonly float Leave;

		public readonly Type05CurveMode Mode;

		public Type05CurveKey(float time, float value, float arrive, float leave, Type05CurveMode mode)
		{
			Time = time;
			Value = value;
			Arrive = arrive;
			Leave = leave;
			Mode = mode;
		}
	}
	internal sealed class Type05Curve
	{
		private readonly Type05CurveKey[] _keys;

		public Type05Curve(Type05CurveKey[] keys)
		{
			_keys = keys;
		}

		public float Evaluate(float t, float fallback)
		{
			if (_keys.Length == 0)
			{
				return fallback;
			}
			if (t <= _keys[0].Time)
			{
				return _keys[0].Value;
			}
			for (int i = 1; i < _keys.Length; i++)
			{
				Type05CurveKey type05CurveKey = _keys[i];
				if (!(t > type05CurveKey.Time))
				{
					Type05CurveKey type05CurveKey2 = _keys[i - 1];
					if (type05CurveKey2.Mode == Type05CurveMode.Constant)
					{
						return type05CurveKey2.Value;
					}
					float num = type05CurveKey.Time - type05CurveKey2.Time;
					float num2 = Type05AudioRules.Saturate((t - type05CurveKey2.Time) / Math.Max(1E-05f, num));
					if (type05CurveKey2.Mode == Type05CurveMode.Cubic)
					{
						float num3 = num2 * num2;
						float num4 = num3 * num2;
						return (2f * num4 - 3f * num3 + 1f) * type05CurveKey2.Value + (num4 - 2f * num3 + num2) * num * type05CurveKey2.Leave + (-2f * num4 + 3f * num3) * type05CurveKey.Value + (num4 - num3) * num * type05CurveKey.Arrive;
					}
					return type05CurveKey2.Value + (type05CurveKey.Value - type05CurveKey2.Value) * num2;
				}
			}
			return _keys[_keys.Length - 1].Value;
		}
	}
	internal readonly struct Type05CrossFade
	{
		public readonly float FadeInStart;

		public readonly float FadeInEnd;

		public readonly float FadeOutStart;

		public readonly float FadeOutEnd;

		public readonly float Volume;

		public Type05CrossFade(float fadeInStart, float fadeInEnd, float fadeOutStart, float fadeOutEnd, float volume)
		{
			FadeInStart = fadeInStart;
			FadeInEnd = fadeInEnd;
			FadeOutStart = fadeOutStart;
			FadeOutEnd = fadeOutEnd;
			Volume = volume;
		}

		public float Gain(float metres)
		{
			float num = Volume;
			if (FadeInEnd > FadeInStart)
			{
				num *= Type05AudioRules.Saturate((metres - FadeInStart) / (FadeInEnd - FadeInStart));
			}
			if (FadeOutEnd > FadeOutStart)
			{
				num *= 1f - Type05AudioRules.Saturate((metres - FadeOutStart) / (FadeOutEnd - FadeOutStart));
			}
			return num;
		}
	}
	internal struct Type05Lehmer
	{
		private const long Multiplier = 48271L;

		private const long Modulus = 2147483647L;

		private long _state;

		public Type05Lehmer(ushort seed)
		{
			_state = seed;
		}

		public double Next(double a, double b)
		{
			_state = _state * 48271 % int.MaxValue;
			return a + (b - a) * (double)_state / 2147483647.0;
		}
	}
	internal static class Type05AudioRules
	{
		private static readonly string[] VictimVoicePrefixes = new string[3] { "type5_throw_vo_", "sfx_helmethit_voice_", "type5_choke_vo_" };

		public const double SourceUnitMetres = 0.0254;

		public const string GappedCueName = "RT_sfx_t5_ChatterRandom";

		public const double GapSeconds = 3.0;

		public static float UnitsToMetres(double units)
		{
			return (float)(units * 0.0254);
		}

		public static float CentimetresToMetres(double centimetres)
		{
			return (float)(centimetres / 100.0);
		}

		public static float Saturate(float value)
		{
			if (!(value < 0f))
			{
				if (!(value > 1f))
				{
					return value;
				}
				return 1f;
			}
			return 0f;
		}

		public static bool VictimVoice(string fileName)
		{
			for (int i = 0; i < VictimVoicePrefixes.Length; i++)
			{
				if (fileName.StartsWith(VictimVoicePrefixes[i], StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		public static float DistanceGain(float[] stopsMetres, float[] row, float metres, float maxMetres, bool layered)
		{
			if (row == null)
			{
				if (layered)
				{
					return 1f;
				}
				float num = UnitsToMetres(70.0);
				return 1f - Saturate((metres - num) / Math.Max(UnitsToMetres(1.0), maxMetres - num));
			}
			int num2 = row.Length - 1;
			float num3;
			if (metres <= stopsMetres[0])
			{
				num3 = row[0];
			}
			else if (metres >= stopsMetres[num2])
			{
				num3 = row[num2];
			}
			else
			{
				int i;
				for (i = 1; metres > stopsMetres[i]; i++)
				{
				}
				float num4 = stopsMetres[i] - stopsMetres[i - 1];
				float num5 = ((num4 > 0f) ? ((metres - stopsMetres[i - 1]) / num4) : 1f);
				num3 = row[i - 1] + (row[i] - row[i - 1]) * num5;
			}
			return num3 * (1f - Saturate((metres - 0.85f * maxMetres) / (0.15f * maxMetres)));
		}
	}
	internal readonly struct Type05ClipSoundEvent
	{
		public readonly float Time;

		public readonly int Cue;

		public readonly float Volume;

		public readonly float Pitch;

		public readonly Type05FootSide Side;

		public Type05ClipSoundEvent(float time, int cue, float volume, float pitch, Type05FootSide side)
		{
			Time = time;
			Cue = cue;
			Volume = volume;
			Pitch = pitch;
			Side = side;
		}
	}
	internal readonly struct Type05ClipCrossing
	{
		public readonly int Event;

		public readonly int Cycle;

		public readonly double Progress;

		public Type05ClipCrossing(int eventIndex, int cycle, double progress)
		{
			Event = eventIndex;
			Cycle = cycle;
			Progress = progress;
		}
	}
	internal readonly struct Type05ClipKey : IEquatable<Type05ClipKey>
	{
		public readonly Type05Phase Phase;

		public readonly Type05Clip Clip;

		public readonly double Start;

		public bool IsNone => Phase == Type05Phase.Dormant;

		public Type05ClipKey(Type05Phase phase, Type05Clip clip, double start)
		{
			Phase = phase;
			Clip = clip;
			Start = start;
		}

		public static Type05ClipKey Of(in Type05State state)
		{
			switch (state.Phase)
			{
			case Type05Phase.Waking:
				return new Type05ClipKey(state.Phase, Type05Clip.Wake, state.ClipStartTime);
			case Type05Phase.Idle:
				return new Type05ClipKey(state.Phase, Type05Clip.Idle, state.ClipStartTime);
			case Type05Phase.Walking:
			case Type05Phase.Turning:
			case Type05Phase.Working:
			case Type05Phase.Hurt:
			case Type05Phase.Shutdown:
			case Type05Phase.Dying:
			case Type05Phase.Attacking:
			case Type05Phase.Inspecting:
				return new Type05ClipKey(state.Phase, (Type05Clip)state.Clip, state.ClipStartTime);
			default:
				return default(Type05ClipKey);
			}
		}

		public bool Equals(Type05ClipKey other)
		{
			if (Phase == other.Phase && Clip == other.Clip)
			{
				return Start.Equals(other.Start);
			}
			return false;
		}

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

		public override int GetHashCode()
		{
			return (int)(((uint)((int)Phase * 397) ^ (uint)Clip) * 397) ^ Start.GetHashCode();
		}

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

		public static bool operator !=(Type05ClipKey a, Type05ClipKey b)
		{
			return !a.Equals(b);
		}
	}
	internal static class Type05ClipAudio
	{
		public static bool Loops(Type05Phase phase)
		{
			if (phase != Type05Phase.Idle)
			{
				return phase == Type05Phase.Walking;
			}
			return true;
		}
	}
	internal sealed class Type05ClipAudioCursor
	{
		private Type05ClipSoundEvent[] _events;

		private float _length;

		private bool _loops;

		private bool _fresh;

		private double _progress;

		public bool Active { get; private set; }

		public Type05ClipKey Key { get; private set; }

		public double Progress => _progress;

		public void Begin(Type05ClipKey key, Type05ClipSoundEvent[] events, float length, bool loops, double startProgress)
		{
			if (key.IsNone)
			{
				Clear();
				return;
			}
			Key = key;
			_events = events;
			_length = length;
			_loops = loops;
			_progress = startProgress;
			_fresh = true;
			Active = true;
		}

		public void Clear()
		{
			Active = false;
			Key = default(Type05ClipKey);
			_events = null;
		}

		public Type05ClipSoundEvent Event(int index)
		{
			return _events[index];
		}

		public void Advance(double to, List<Type05ClipCrossing> crossings)
		{
			if (!Active || _length <= 0f)
			{
				return;
			}
			if (!_loops && to > (double)_length)
			{
				to = _length;
			}
			if (!(to >= _progress))
			{
				return;
			}
			long num = (_loops ? ((long)Math.Floor(_progress / (double)_length)) : 0);
			long num2 = (_loops ? ((long)Math.Floor(to / (double)_length)) : 0);
			for (long num3 = num; num3 <= num2; num3++)
			{
				for (int i = 0; i < _events.Length; i++)
				{
					double num4 = (double)num3 * (double)_length + (double)_events[i].Time;
					if ((_fresh ? (num4 >= _progress) : (num4 > _progress)) && num4 <= to)
					{
						crossings.Add(new Type05ClipCrossing(i, (int)num3, num4));
					}
				}
			}
			_progress = to;
			_fresh = false;
		}
	}
	internal sealed class Type05CueDataException : Exception
	{
		public Type05CueDataException(string message)
			: base(message)
		{
		}
	}
	internal sealed class Type05JsonReader
	{
		private const int MaxNesting = 64;

		private readonly string _text;

		private int _pos;

		private Type05JsonReader(string text)
		{
			_text = text;
		}

		public static object Parse(string text)
		{
			if (text == null)
			{
				throw new Type05CueDataException("JSON error: no text.");
			}
			Type05JsonReader type05JsonReader = new Type05JsonReader(text);
			if (text.Length > 0 && text[0] == '\ufeff')
			{
				type05JsonReader._pos = 1;
			}
			object result = type05JsonReader.ReadValue(0);
			type05JsonReader.SkipSpace();
			if (type05JsonReader._pos != text.Length)
			{
				throw type05JsonReader.Error("unexpected text after the value");
			}
			return result;
		}

		private Type05CueDataException Error(string what)
		{
			return new Type05CueDataException($"JSON error at character {_pos}: {what}.");
		}

		private void SkipSpace()
		{
			while (_pos < _text.Length)
			{
				char c = _text[_pos];
				if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
				{
					break;
				}
				_pos++;
			}
		}

		private object ReadValue(int depth)
		{
			SkipSpace();
			if (_pos >= _text.Length)
			{
				throw Error("the text ends where a value is expected");
			}
			if (depth > 64)
			{
				throw Error("nesting is too deep");
			}
			char c = _text[_pos];
			switch (c)
			{
			case '{':
				return ReadObject(depth);
			case '[':
				return ReadArray(depth);
			case '"':
				return ReadString();
			case 't':
				ReadWord("true");
				return true;
			case 'f':
				ReadWord("false");
				return false;
			case 'n':
				ReadWord("null");
				return null;
			default:
				switch (c)
				{
				case '-':
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
					return ReadNumber();
				default:
					throw Error($"unexpected character '{c}'");
				}
			}
		}

		private void ReadWord(string word)
		{
			if (string.CompareOrdinal(_text, _pos, word, 0, word.Length) != 0)
			{
				throw Error("expected '" + word + "'");
			}
			_pos += word.Length;
		}

		private Dictionary<string, object> ReadObject(int depth)
		{
			Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.Ordinal);
			_pos++;
			SkipSpace();
			if (_pos < _text.Length && _text[_pos] == '}')
			{
				_pos++;
				return dictionary;
			}
			while (true)
			{
				SkipSpace();
				if (_pos >= _text.Length || _text[_pos] != '"')
				{
					throw Error("expected a quoted key");
				}
				int pos = _pos;
				string text = ReadString();
				SkipSpace();
				if (_pos >= _text.Length || _text[_pos] != ':')
				{
					throw Error("expected ':' after the key");
				}
				_pos++;
				object value = ReadValue(depth + 1);
				if (dictionary.ContainsKey(text))
				{
					_pos = pos;
					throw Error("duplicate key '" + text + "'");
				}
				dictionary.Add(text, value);
				SkipSpace();
				if (_pos >= _text.Length)
				{
					throw Error("the text ends inside an object");
				}
				if (_text[_pos] != ',')
				{
					break;
				}
				_pos++;
			}
			if (_text[_pos] == '}')
			{
				_pos++;
				return dictionary;
			}
			throw Error("expected ',' or '}'");
		}

		private List<object> ReadArray(int depth)
		{
			List<object> list = new List<object>();
			_pos++;
			SkipSpace();
			if (_pos < _text.Length && _text[_pos] == ']')
			{
				_pos++;
				return list;
			}
			while (true)
			{
				list.Add(ReadValue(depth + 1));
				SkipSpace();
				if (_pos >= _text.Length)
				{
					throw Error("the text ends inside an array");
				}
				if (_text[_pos] != ',')
				{
					break;
				}
				_pos++;
			}
			if (_text[_pos] == ']')
			{
				_pos++;
				return list;
			}
			throw Error("expected ',' or ']'");
		}

		private string ReadString()
		{
			_pos++;
			int pos = _pos;
			StringBuilder stringBuilder = null;
			while (true)
			{
				if (_pos >= _text.Length)
				{
					throw Error("the text ends inside a string");
				}
				char c = _text[_pos];
				if (c == '"')
				{
					string text = _text.Substring(pos, _pos - pos);
					_pos++;
					if (stringBuilder != null)
					{
						return stringBuilder.Append(text).ToString();
					}
					return text;
				}
				if (c < ' ')
				{
					throw Error("a control character in a string");
				}
				if (c != '\\')
				{
					_pos++;
					continue;
				}
				stringBuilder = (stringBuilder ?? new StringBuilder()).Append(_text, pos, _pos - pos);
				_pos++;
				if (_pos >= _text.Length)
				{
					break;
				}
				char c2 = _text[_pos++];
				switch (c2)
				{
				case '"':
				case '/':
				case '\\':
					stringBuilder.Append(c2);
					break;
				case 'b':
					stringBuilder.Append('\b');
					break;
				case 'f':
					stringBuilder.Append('\f');
					break;
				case 'n':
					stringBuilder.Append('\n');
					break;
				case 'r':
					stringBuilder.Append('\r');
					break;
				case 't':
					stringBuilder.Append('\t');
					break;
				case 'u':
					stringBuilder.Append(ReadHex4());
					break;
				default:
					_pos--;
					throw Error($"unknown escape '\\{c2}'");
				}
				pos = _pos;
			}
			throw Error("the text ends inside an escape");
		}

		private char ReadHex4()
		{
			if (_pos + 4 > _text.Length)
			{
				throw Error("the text ends inside a \\u escape");
			}
			int num = 0;
			for (int i = 0; i < 4; i++)
			{
				char c = _text[_pos + i];
				int num2 = ((c >= '0' && c <= '9') ? (c - 48) : ((c >= 'a' && c <= 'f') ? (c - 97 + 10) : ((c >= 'A' && c <= 'F') ? (c - 65 + 10) : (-1))));
				if (num2 < 0)
				{
					_pos += i;
					throw Error("a \\u escape needs four hex digits");
				}
				num = num * 16 + num2;
			}
			_pos += 4;
			return (char)num;
		}

		private double ReadNumber()
		{
			int pos = _pos;
			if (_text[_pos] == '-')
			{
				_pos++;
			}
			if (_pos >= _text.Length || _text[_pos] < '0' || _text[_pos] > '9')
			{
				throw Error("a number needs a digit");
			}
			if (_text[_pos] == '0')
			{
				_pos++;
			}
			else
			{
				SkipDigits();
			}
			if (_pos < _text.Length && _text[_pos] == '.')
			{
				_pos++;
				if (_pos >= _text.Length || _text[_pos] < '0' || _text[_pos] > '9')
				{
					throw Error("a fraction needs a digit");
				}
				SkipDigits();
			}
			if (_pos < _text.Length && (_text[_pos] == 'e' || _text[_pos] == 'E'))
			{
				_pos++;
				if (_pos < _text.Length && (_text[_pos] == '+' || _text[_pos] == '-'))
				{
					_pos++;
				}
				if (_pos >= _text.Length || _text[_pos] < '0' || _text[_pos] > '9')
				{
					throw Error("an exponent needs a digit");
				}
				SkipDigits();
			}
			if (!double.TryParse(_text.Substring(pos, _pos - pos), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || double.IsInfinity(result))
			{
				_pos = pos;
				throw Error("the number is out of range");
			}
			return result;
		}

		private void SkipDigits()
		{
			while (_pos < _text.Length && _text[_pos] >= '0' && _text[_pos] <= '9')
			{
				_pos++;
			}
		}
	}
	internal enum Type05NodeKind : byte
	{
		Mixer,
		Random,
		WavePlayer,
		Delay,
		Modulator,
		Enveloper,
		DistanceCrossFade
	}
	internal sealed class Type05RawNode
	{
		public int Id;

		public Type05NodeKind Kind;

		public int[] Children;

		public double[] Values;

		public double Min;

		public double Max;

		public double PitchMin;

		public double PitchMax;

		public Type05CrossFade[] Fades;

		public Type05Curve VolumeCurve;

		public Type05Curve PitchCurve;

		public string File;

		public float Duration;
	}
	internal sealed class Type05RawCue
	{
		public string Name;

		public double Volume;

		public double MaxDistance;

		public int Root;

		public float[] DistanceGains;

		public SortedList<int, Type05RawNode> Nodes;
	}
	internal readonly struct Type05RawSoundEvent
	{
		public readonly float Time;

		public readonly string Cue;

		public readonly float Volume;

		public readonly float Pitch;

		public readonly Type05FootSide Side;

		public Type05RawSoundEvent(float time, string cue, float volume, float pitch, Type05FootSide side)
		{
			Time = time;
			Cue = cue;
			Volume = volume;
			Pitch = pitch;
			Side = side;
		}
	}
	internal readonly struct Type05RawGameplayEvent
	{
		public readonly float Time;

		public readonly Type05CatchEffect Effect;

		public Type05RawGameplayEvent(float time, Type05CatchEffect effect)
		{
			Time = time;
			Effect = effect;
		}
	}
	internal sealed class Type05RawTables
	{
		public double[] DistanceStops;

		public List<Type05RawCue> Cues;

		public Dictionary<string, List<Type05RawSoundEvent>> Clips;

		public Dictionary<string, List<Type05RawGameplayEvent>> Gameplay;
	}
	internal static class Type05CueTables
	{
		public static Type05RawTables Read(string cuesJson, string eventsJson)
		{
			Dictionary<string, object> o = Obj(Type05JsonReader.Parse(cuesJson), "cues table");
			Type05RawTables type05RawTables = new Type05RawTables
			{
				DistanceStops = Numbers(Get(o, "distance_stops", "cues table"), "cues table distance_stops"),
				Cues = new List<Type05RawCue>(),
				Clips = new Dictionary<string, List<Type05RawSoundEvent>>(StringComparer.Ordinal),
				Gameplay = new Dictionary<string, List<Type05RawGameplayEvent>>(StringComparer.Ordinal)
			};
			for (int i = 1; i < type05RawTables.DistanceStops.Length; i++)
			{
				if (type05RawTables.DistanceStops[i] < type05RawTables.DistanceStops[i - 1])
				{
					throw new Type05CueDataException("cues table distance_stops must not decrease.");
				}
			}
			foreach (KeyValuePair<string, object> item in Obj(Get(o, "cues", "cues table"), "cues table cues"))
			{
				if (item.Key.Length == 0)
				{
					throw new Type05CueDataException("cues table has a cue with an empty name.");
				}
				type05RawTables.Cues.Add(ReadCue(item.Key, item.Value, type05RawTables.DistanceStops));
			}
			bool flag = default(bool);
			foreach (KeyValuePair<string, object> item2 in Obj(Get(Obj(Type05JsonReader.Parse(eventsJson), "events table"), "clips", "events table"), "events table clips"))
			{
				List<Type05RawSoundEvent> list = new List<Type05RawSoundEvent>();
				List<Type05RawGameplayEvent> list2 = null;
				string text = "events table clip '" + item2.Key + "'";
				foreach (object item3 in Arr(item2.Value, text))
				{
					Dictionary<string, object> dictionary = Obj(item3, text + " event");
					if (!dictionary.TryGetValue("kind", out var value) || !(value is string text2))
					{
						continue;
					}
					Type05CatchEffect type05CatchEffect = GameplayEffect(text2);
					if (text2 != "sound" && type05CatchEffect == Type05CatchEffect.None)
					{
						continue;
					}
					int num;
					if (dictionary.TryGetValue("used_by_addon", out var value2))
					{
						if (value2 is bool)
						{
							flag = (bool)value2;
							num = 1;
						}
						else
						{
							num = 0;
						}
					}
					else
					{
						num = 0;
					}
					if (((uint)num & (flag ? 1u : 0u)) == 0)
					{
						continue;
					}
					if (type05CatchEffect != Type05CatchEffect.None)
					{
						float num2 = (float)Num(Get(dictionary, "time", text), text + " time");
						if (!(num2 >= 0f) || float.IsInfinity(num2))
						{
							throw new Type05CueDataException(text + ", " + text2 + " event: the event time must be a number of seconds from 0.");
						}
						(list2 ?? (list2 = new List<Type05RawGameplayEvent>())).Add(new Type05RawGameplayEvent(num2, type05CatchEffect));
						continue;
					}
					string text3 = Str(Get(dictionary, "cue", text), text + " cue");
					float num3 = (float)Num(Get(dictionary, "time", text), text + " time");
					if (!(num3 >= 0f) || float.IsInfinity(num3))
					{
						throw new Type05CueDataException(text + ", cue '" + text3 + "': the event time must be a number of seconds from 0.");
					}
					Type05FootSide side = Type05FootSide.None;
					if (dictionary.TryGetValue("side", out var value3) && value3 != null)
					{
						string text4 = Str(value3, text + " side");
						int num4;
						if (!(text4 == "l"))
						{
							if (!(text4 == "r"))
							{
								throw new Type05CueDataException(text + ", cue '" + text3 + "': the side must be \"l\" or \"r\".");
							}
							num4 = 2;
						}
						else
						{
							num4 = 1;
						}
						side = (Type05FootSide)num4;
					}
					list.Add(new Type05RawSoundEvent(num3, text3, (float)Num(Get(dictionary, "volume", text), text + " volume"), (float)Num(Get(dictionary, "pitch", text), text + " pitch"), side));
				}
				type05RawTables.Clips.Add(item2.Key, list);
				if (list2 != null)
				{
					type05RawTables.Gameplay.Add(item2.Key, list2);
				}
			}
			return type05RawTables;
		}

		private static Type05CatchEffect GameplayEffect(string kind)
		{
			return kind switch
			{
				"grab_pickup" => Type05CatchEffect.Pickup, 
				"grab_throw" => Type05CatchEffect.Launch, 
				"damage" => Type05CatchEffect.Damage, 
				"release_victim" => Type05CatchEffect.Release, 
				_ => Type05CatchEffect.None, 
			};
		}

		private static Type05RawCue ReadCue(string name, object value, double[] stops)
		{
			string text = "cue '" + name + "'";
			Dictionary<string, object> dictionary = Obj(value, text);
			Type05RawCue type05RawCue = new Type05RawCue
			{
				Name = name,
				Volume = Num(Get(dictionary, "volume", text), text + " volume"),
				MaxDistance = Num(Get(dictionary, "max_distance", text), text + " max_distance"),
				Root = Int(Num(Get(dictionary, "root", text), text + " root"), text + " root"),
				Nodes = new SortedList<int, Type05RawNode>()
			};
			if (!(type05RawCue.MaxDistance > 0.0))
			{
				throw new Type05CueDataException(text + ": max_distance must be above 0.");
			}
			if (dictionary.TryGetValue("distance_gains", out var value2) && value2 != null)
			{
				double[] array = Numbers(value2, text + " distance_gains");
				if (array.Length != stops.Length)
				{
					throw new Type05CueDataException($"{text}: distance_gains has {array.Length} entries for {stops.Length} distance stops.");
				}
				type05RawCue.DistanceGains = new float[array.Length];
				for (int i = 0; i < array.Length; i++)
				{
					type05RawCue.DistanceGains[i] = (float)array[i];
				}
			}
			foreach (KeyValuePair<string, object> item in Obj(Get(dictionary, "nodes", text), text + " nodes"))
			{
				if (!int.TryParse(item.Key, NumberStyles.None, CultureInfo.InvariantCulture, out var result))
				{
					throw new Type05CueDataException(text + ": node id '" + item.Key + "' is not a non-negative number.");
				}
				type05RawCue.Nodes.Add(result, ReadNode(name, result, item.Value));
			}
			return type05RawCue;
		}

		private static Type05RawNode ReadNode(string cue, int id, object value)
		{
			string text = $"cue '{cue}' node {id}";
			Dictionary<string, object> dictionary = Obj(value, text);
			string text2 = Str(Get(dictionary, "type", text), text + " type");
			Type05RawNode type05RawNode = new Type05RawNode
			{
				Id = id
			};
			switch (text2)
			{
			case "Mixer":
				type05RawNode.Kind = Type05NodeKind.Mixer;
				break;
			case "Random":
				type05RawNode.Kind = Type05NodeKind.Random;
				break;
			case "WavePlayer":
				type05RawNode.Kind = Type05NodeKind.WavePlayer;
				break;
			case "Delay":
				type05RawNode.Kind = Type05NodeKind.Delay;
				break;
			case "Modulator":
				type05RawNode.Kind = Type05NodeKind.Modulator;
				break;
			case "Enveloper":
				type05RawNode.Kind = Type05NodeKind.Enveloper;
				break;
			case "DistanceCrossFade":
				type05RawNode.Kind = Type05NodeKind.DistanceCrossFade;
				break;
			default:
				throw new Type05CueDataException(text + ": unknown node type '" + text2 + "'.");
			}
			double[] array = Numbers(Get(dictionary, "children", text), text + " children");
			type05RawNode.Children = new int[array.Length];
			for (int i = 0; i < array.Length; i++)
			{
				type05RawNode.Children[i] = Int(array[i], text + " children");
			}
			object value2;
			Dictionary<string, object> dictionary2 = ((dictionary.TryGetValue("props", out value2) && value2 != null) ? Obj(value2, text + " props") : new Dictionary<string, object>());
			switch (type05RawNode.Kind)
			{
			case Type05NodeKind.Mixer:
				type05RawNode.Values = Fill(dictionary2, "InputVolume", type05RawNode.Children.Length, text);
				break;
			case Type05NodeKind.Random:
				type05RawNode.Values = Fill(dictionary2, "Weights", type05RawNode.Children.Length, text);
				break;
			case Type05NodeKind.WavePlayer:
			{
				Dictionary<string, object> o2 = Obj(Get(dictionary, "wave", text), text + " wave");
				type05RawNode.File = Str(Get(o2, "file", text + " wave"), text + " wave.file");
				if (type05RawNode.File.Length == 0)
				{
					throw new Type05CueDataException(text + ": wave.file is empty.");
				}
				type05RawNode.Duration = (float)Num(Get(o2, "duration", text + " wave"), text + " wave.duration");
				if (!(type05RawNode.Duration >= 0f))
				{
					throw new Type05CueDataException(text + ": wave.duration must be seconds from 0.");
				}
				break;
			}
			case Type05NodeKind.Delay:
				type05RawNode.Min = Num(Get(dictionary2, "DelayMin", text + " props"), text + " DelayMin");
				type05RawNode.Max = Num(Get(dictionary2, "DelayMax", text + " props"), text + " DelayMax");
				break;
			case Type05NodeKind.Modulator:
			{
				type05RawNode.Min = Num(Get(dictionary2, "VolumeMin", text + " props"), text + " VolumeMin");
				type05RawNode.Max = Num(Get(dictionary2, "VolumeMax", text + " props"), text + " VolumeMax");
				type05RawNode.PitchMin = (dictionary2.TryGetValue("PitchMin", out var value3) ? Num(value3, text + " PitchMin") : 0.95);
				type05RawNode.PitchMax = (dictionary2.TryGetValue("PitchMax", out var value4) ? Num(value4, text + " PitchMax") : 1.05);
				break;
			}
			case Type05NodeKind.Enveloper:
				type05RawNode.VolumeCurve = ReadCurve(dictionary2, "VolumeCurve", text);
				type05RawNode.PitchCurve = ReadCurve(dictionary2, "PitchCurve", text);
				break;
			case Type05NodeKind.DistanceCrossFade:
			{
				List<object> list = Arr(Get(dictionary2, "CrossFadeInput", text + " props"), text + " CrossFadeInput");
				if (list.Count != type05RawNode.Children.Length)
				{
					throw new Type05CueDataException($"{text}: CrossFadeInput has {list.Count} entries for {type05RawNode.Children.Length} children.");
				}
				type05RawNode.Fades = new Type05CrossFade[list.Count];
				for (int j = 0; j < list.Count; j++)
				{
					string text3 = $"{text} CrossFadeInput[{j}]";
					Dictionary<string, object> o = Obj(list[j], text3);
					type05RawNode.Fades[j] = new Type05CrossFade(Type05AudioRules.CentimetresToMetres(Num(Get(o, "FadeInDistanceStart", text3), text3 + " FadeInDistanceStart")), Type05AudioRules.CentimetresToMetres(Num(Get(o, "FadeInDistanceEnd", text3), text3 + " FadeInDistanceEnd")), Type05AudioRules.CentimetresToMetres(Num(Get(o, "FadeOutDistanceStart", text3), text3 + " FadeOutDistanceStart")), Type05AudioRules.CentimetresToMetres(Num(Get(o, "FadeOutDistanceEnd", text3), text3 + " FadeOutDistanceEnd")), (float)Num(Get(o, "Volume", text3), text3 + " Volume"));
				}
				break;
			}
			}
			return type05RawNode;
		}

		private static double[] Fill(Dictionary<string, object> props, string key, int count, string where)
		{
			double[] array = new double[count];
			for (int i = 0; i < count; i++)
			{
				array[i] = 1.0;
			}
			if (props.TryGetValue(key, out var value) && value != null)
			{
				double[] array2 = Numbers(value, where + " " + key);
				Array.Copy(array2, array, Math.Min(array2.Length, count));
			}
			return array;
		}

		private static Type05Curve ReadCurve(Dictionary<string, object> props, string key, string where)
		{
			if (!props.TryGetValue(key, out var value) || value == null)
			{
				return new Type05Curve(Array.Empty<Type05CurveKey>());
			}
			string text = where + " " + key;
			List<object> list = Arr(Get(Obj(Get(Obj(value, text), "EditorCurveData", text), text), "Keys", text + " EditorCurveData"), text + " Keys");
			Type05CurveKey[] array = new Type05CurveKey[list.Count];
			for (int i = 0; i < list.Count; i++)
			{
				string text2 = $"{text} key {i}";
				Dictionary<string, object> o = Obj(list[i], text2);
				string text3 = Str(Get(o, "InterpMode", text2), text2 + " InterpMode");
				Type05CurveMode mode = text3 switch
				{
					"RCIM_Constant" => Type05CurveMode.Constant, 
					"RCIM_Cubic" => Type05CurveMode.Cubic, 
					"RCIM_Linear" => Type05CurveMode.Linear, 
					_ => throw new Type05CueDataException(text2 + ": unknown InterpMode '" + text3 + "'."), 
				};
				array[i] = new Type05CurveKey((float)Num(Get(o, "Time", text2), text2 + " Time"), (float)Num(Get(o, "Value", text2), text2 + " Value"), (float)Num(Get(o, "ArriveTangent", text2), text2 + " ArriveTangent"), (float)Num(Get(o, "LeaveTangent", text2), text2 + " LeaveTangent"), mode);
				if (i > 0 && array[i].Time < array[i - 1].Time)
				{
					throw new Type05CueDataException(text2 + ": key times must not decrease.");
				}
			}
			return new Type05Curve(array);
		}

		private static object Get(Dictionary<string, object> o, string key, string where)
		{
			if (!o.TryGetValue(key, out var value))
			{
				throw new Type05CueDataException(where + ": '" + key + "' is missing.");
			}
			return value;
		}

		private static Dictionary<string, object> Obj(object value, string what)
		{
			return (value as Dictionary<string, object>) ?? throw new Type05CueDataException(what + " must be an object.");
		}

		private static List<object> Arr(object value, string what)
		{
			return (value as List<object>) ?? throw new Type05CueDataException(what + " must be an array.");
		}

		private static string Str(object value, string what)
		{
			return (value as string) ?? throw new Type05CueDataException(what + " must be a string.");
		}

		private static double Num(object value, string what)
		{
			if (value is double)
			{
				return (double)value;
			}
			throw new Type05CueDataException(what + " must be a number.");
		}

		private static int Int(double d, string what)
		{
			if (d != Math.Floor(d) || d < -1.0 || d > 2147483647.0)
			{
				throw new Type05CueDataException(what + " must be a whole number, got " + d.ToString(CultureInfo.InvariantCulture) + ".");
			}
			return (int)d;
		}

		private static double[] Numbers(object value, string what)
		{
			List<object> list = Arr(value, what);
			double[] array = new double[list.Count];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = Num(list[i], $"{what}[{i}]");
			}
			return array;
		}
	}
	internal struct Type05CueLeafChoice
	{
		public ushort Path;

		public ushort File;

		public float Delay;

		public float Volume;

		public float Pitch;
	}
	internal sealed class Type05CueCatalogue
	{
		private struct EnvelopeStage
		{
			public float Start;

			public Type05Curve Volume;

			public Type05Curve Pitch;
		}

		private sealed class Occurrence
		{
			public Type05RawNode Node;

			public Occurrence[] Children;

			public int Path = -1;

			public int RandomIndex = -1;

			public int MaxLeaves;
		}

		private sealed class PathModel
		{
			public ushort File;

			public Type05CrossFade[] Filters;

			public EnvelopeStage[] Stages;
		}

		private sealed class CueModel
		{
			public string Name;

			public double Volume;

			public float MaxMetres;

			public float[] Row;

			public double Gap;

			public Occurrence Root;

			public Type05RawNode[] RandomNodes;

			public PathModel[] Paths;
		}

		private sealed class CueBuild
		{
			public Type05RawCue Raw;

			public Dictionary<int, int> RandomIndexById;

			public HashSet<int> OnStack = new HashSet<int>();

			public List<Type05CrossFade> Filters = new List<Type05CrossFade>();

			public List<EnvelopeStage> Stages = new List<EnvelopeStage>();

			public List<PathModel> Paths = new List<PathModel>();
		}

		public const string FootstepCueName = "Type5_TestFootstep";

		private const string AudioFolder = "Assets/Y4NGZ/Type05/Source/Audio/";

		private const int MaxDepth = 32;

		private static readonly Type05ClipSoundEvent[] NoEvents = new Type05ClipSoundEvent[0];

		private readonly CueModel[] _cues;

		private readonly Dictionary<string, int> _cueIndex = new Dictionary<string, int>(StringComparer.Ordinal);

		private readonly float[] _stopsMetres;

		private readonly List<string> _fileNames = new List<string>();

		private readonly List<string> _fileAssets = new List<string>();

		private readonly List<float> _fileDurations = new List<float>();

		private readonly List<bool> _fileVictimVoice = new List<bool>();

		private readonly Dictionary<string, int> _fileIndex = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

		private readonly Dictionary<string, Type05ClipSoundEvent[]> _eventsByName = new Dictionary<string, Type05ClipSoundEvent[]>(StringComparer.Ordinal);

		private readonly Type05ClipSoundEvent[][] _eventsByClip = new Type05ClipSoundEvent[39][];

		public int CueCount => _cues.Length;

		public int FootstepCue { get; }

		public int FileCount => _fileNames.Count;

		public int SoundEventCount { get; }

		public int ClipsWithSoundEvents { get; }

		public uint Checksum { get; }

		private Type05CueCatalogue(Type05RawTables raw, uint checksum)
		{
			Checksum = checksum;
			_stopsMetres = new float[raw.DistanceStops.Length];
			for (int i = 0; i < _stopsMetres.Length; i++)
			{
				_stopsMetres[i] = Type05AudioRules.UnitsToMetres(raw.DistanceStops[i]);
			}
			_cues = new CueModel[raw.Cues.Count];
			for (int j = 0; j < _cues.Length; j++)
			{
				if (_cueIndex.ContainsKey(raw.Cues[j].Name))
				{
					throw new Type05CueDataException("cue '" + raw.Cues[j].Name + "' appears twice.");
				}
				_cueIndex.Add(raw.Cues[j].Name, j);
				_cues[j] = BuildCue(raw.Cues[j]);
			}
			FootstepCue = (_cueIndex.TryGetValue("Type5_TestFootstep", out var value) ? value : (-1));
			foreach (KeyValuePair<string, List<Type05RawSoundEvent>> clip in raw.Clips)
			{
				Type05ClipSoundEvent[] array = BuildEvents(clip.Key, clip.Value);
				_eventsByName.Add(clip.Key, array);
				SoundEventCount += array.Length;
				if (array.Length != 0)
				{
					int clipsWithSoundEvents = ClipsWithSoundEvents;
					ClipsWithSoundEvents = clipsWithSoundEvents + 1;
				}
			}
			for (int k = 0; k < _eventsByClip.Length; k++)
			{
				_eventsByClip[k] = EventsFor(Type05ClipPlan.StateName((Type05Clip)k));
			}
		}

		public static Type05CueCatalogue Compile(string cuesJson, string eventsJson)
		{
			return new Type05CueCatalogue(Type05CueTables.Read(cuesJson, eventsJson), Fnv1a(eventsJson, Fnv1a(cuesJson, 2166136261u)));
		}

		public string CueName(int cue)
		{
			return _cues[cue].Name;
		}

		public bool TryFindCue(string name, out int cue)
		{
			return _cueIndex.TryGetValue(name, out cue);
		}

		public string FileName(int file)
		{
			return _fileNames[file];
		}

		public string FileAssetPath(int file)
		{
			return _fileAssets[file];
		}

		public float FileDuration(int file)
		{
			return _fileDurations[file];
		}

		public bool VictimVoice(int file)
		{
			return _fileVictimVoice[file];
		}

		public Type05ClipSoundEvent[] EventsFor(Type05Clip clip)
		{
			return _eventsByClip[(int)clip];
		}

		public Type05ClipSoundEvent[] EventsFor(string clipName)
		{
			if (!_eventsByName.TryGetValue(clipName, out var value))
			{
				return NoEvents;
			}
			return value;
		}

		public int MaxLeaves(int cue)
		{
			return _cues[cue].Root.MaxLeaves;
		}

		public float MaxDistance(int cue)
		{
			return _cues[cue].MaxMetres;
		}

		public bool IsLeafOf(int cue, in Type05CueLeafChoice leaf)
		{
			if (cue < 0 || cue >= _cues.Length)
			{
				return false;
			}
			PathModel[] paths = _cues[cue].Paths;
			if (leaf.Path < paths.Length)
			{
				return paths[leaf.Path].File == leaf.File;
			}
			return false;
		}

		public float LayerGain(int cue, int path, float metres)
		{
			CueModel cueModel = _cues[cue];
			if (metres > cueModel.MaxMetres)
			{
				return 0f;
			}
			Type05CrossFade[] filters = cueModel.Paths[path].Filters;
			float num = 1f;
			for (int i = 0; i < filters.Length; i++)
			{
				num *= filters[i].Gain(metres);
			}
			return num * Type05AudioRules.DistanceGain(_stopsMetres, cueModel.Row, metres, cueModel.MaxMetres, filters.Length != 0);
		}

		public void Envelope(int cue, int path, float cueElapsed, out float volume, out float pitch)
		{
			EnvelopeStage[] stages = _cues[cue].Paths[path].Stages;
			volume = 1f;
			pitch = 1f;
			for (int i = 0; i < stages.Length; i++)
			{
				float t = cueElapsed - stages[i].Start;
				volume *= stages[i].Volume.Evaluate(t, 1f);
				pitch *= stages[i].Pitch.Evaluate(t, 1f);
			}
		}

		internal double GapSeconds(int cue)
		{
			return _cues[cue].Gap;
		}

		internal int RandomCount(int cue)
		{
			return _cues[cue].RandomNodes.Length;
		}

		internal int RandomChildCount(int cue, int random)
		{
			return _cues[cue].RandomNodes[random].Children.Length;
		}

		internal double RandomWeight(int cue, int random, int child)
		{
			Type05RawNode type05RawNode = _cues[cue].RandomNodes[random];
			if (type05RawNode.Children[child] < 0 || !(type05RawNode.Values[child] > 0.0))
			{
				return 0.0;
			}
			return type05RawNode.Values[child];
		}

		internal void Decode(int cue, int[] picks, ushort seed, List<Type05CueLeafChoice> leaves)
		{
			CueModel cueModel = _cues[cue];
			Type05Lehmer stream = new Type05Lehmer(seed);
			DecodeNode(cueModel, cueModel.Root, 0.0, cueModel.Volume, 1.0, picks, ref stream, leaves);
		}

		private static void DecodeNode(CueModel model, Occurrence occurrence, double delay, double volume, double pitch, int[] picks, ref Type05Lehmer stream, List<Type05CueLeafChoice> leaves)
		{
			Type05RawNode node = occurrence.Node;
			switch (node.Kind)
			{
			case Type05NodeKind.WavePlayer:
				leaves.Add(new Type05CueLeafChoice
				{
					Path = (ushort)occurrence.Path,
					File = model.Paths[occurrence.Path].File,
					Delay = (float)delay,
					Volume = (float)volume,
					Pitch = (float)pitch
				});
				return;
			case Type05NodeKind.Delay:
				delay += stream.Next(node.Min, node.Max);
				break;
			case Type05NodeKind.Modulator:
				volume *= stream.Next(node.Min, node.Max);
				pitch *= stream.Next(node.PitchMin, node.PitchMax);
				break;
			case Type05NodeKind.Enveloper:
				volume *= stream.Next(1.0, 1.0);
				pitch *= stream.Next(1.0, 1.0);
				break;
			case Type05NodeKind.Random:
			{
				int num = picks[occurrence.RandomIndex];
				if (num >= 0 && occurrence.Children[num] != null)
				{
					DecodeNode(model, occurrence.Children[num], delay, volume, pitch, picks, ref stream, leaves);
				}
				return;
			}
			}
			for (int i = 0; i < occurrence.Children.Length; i++)
			{
				if (occurrence.Children[i] != null)
				{
					double volume2 = ((node.Kind == Type05NodeKind.Mixer) ? (volume * node.Values[i]) : volume);
					DecodeNode(model, occurrence.Children[i], delay, volume2, pitch, picks, ref stream, leaves);
				}
			}
		}

		private CueModel BuildCue(Type05RawCue raw)
		{
			string arg = "cue '" + raw.Name + "'";
			List<Type05RawNode> list = new List<Type05RawNode>();
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			foreach (Type05RawNode value in raw.Nodes.Values)
			{
				int[] children = value.Children;
				foreach (int num in children)
				{
					if (num >= 0 && !raw.Nodes.ContainsKey(num))
					{
						throw new Type05CueDataException($"{arg} node {value.Id}: child {num} is not a node of the cue.");
					}
				}
				if (value.Kind == Type05NodeKind.Random)
				{
					dictionary.Add(value.Id, list.Count);
					list.Add(value);
				}
			}
			if (!raw.Nodes.ContainsKey(raw.Root))
			{
				throw new Type05CueDataException($"{arg}: the root {raw.Root} is not a node of the cue.");
			}
			CueBuild cueBuild = new CueBuild
			{
				Raw = raw,
				RandomIndexById = dictionary
			};
			return new CueModel
			{
				Name = raw.Name,
				Volume = raw.Volume,
				MaxMetres = Type05AudioRules.UnitsToMetres(raw.MaxDistance),
				Row = raw.DistanceGains,
				Gap = ((raw.Name == "RT_sfx_t5_ChatterRandom") ? 3.0 : 0.0),
				RandomNodes = list.ToArray(),
				Root = Expand(cueBuild, raw.Root, 0, 0.0, ranged: false),
				Paths = cueBuild.Paths.ToArray()
			};
		}

		private Occurrence Expand(CueBuild build, int id, int depth, double delay, bool ranged)
		{
			if (depth > 32)
			{
				throw new Type05CueDataException($"cue '{build.Raw.Name}' node {id}: the graph is deeper than {32} nodes.");
			}
			if (!build.OnStack.Add(id))
			{
				throw new Type05CueDataException($"cue '{build.Raw.Name}' node {id}: the graph loops back to this node.");
			}
			Type05RawNode type05RawNode = build.Raw.Nodes[id];
			Occurrence occurrence = new Occurrence
			{
				Node = type05RawNode,
				Children = new Occurrence[type05RawNode.Children.Length]
			};
			switch (type05RawNode.Kind)
			{
			case Type05NodeKind.WavePlayer:
				if (build.Paths.Count > 65535)
				{
					throw new Type05CueDataException($"cue '{build.Raw.Name}' has more than {ushort.MaxValue} leaf paths.");
				}
				occurrence.Path = build.Paths.Count;
				occurrence.MaxLeaves = 1;
				build.Paths.Add(new PathModel
				{
					File = RegisterFile(type05RawNode),
					Filters = build.Filters.ToArray(),
					Stages = build.Stages.ToArray()
				});
				build.OnStack.Remove(id);
				return occurrence;
			case Type05NodeKind.Delay:
				delay += type05RawNode.Min;
				ranged |= type05RawNode.Min != type05RawNode.Max;
				break;
			case Type05NodeKind.Enveloper:
				if (ranged)
				{
					throw new Type05CueDataException($"cue '{build.Raw.Name}' node {id}: an Enveloper below a Delay with DelayMin != DelayMax has no fixed start.");
				}
				build.Stages.Add(new EnvelopeStage
				{
					Start = (float)delay,
					Volume = type05RawNode.VolumeCurve,
					Pitch = type05RawNode.PitchCurve
				});
				break;
			case Type05NodeKind.Random:
				occurrence.RandomIndex = build.RandomIndexById[id];
				break;
			}
			for (int i = 0; i < type05RawNode.Children.Length; i++)
			{
				if (type05RawNode.Children[i] >= 0)
				{
					bool num = type05RawNode.Kind == Type05NodeKind.DistanceCrossFade;
					if (num)
					{
						build.Filters.Add(type05RawNode.Fades[i]);
					}
					occurrence.Children[i] = Expand(build, type05RawNode.Children[i], depth + 1, delay, ranged);
					if (num)
					{
						build.Filters.RemoveAt(build.Filters.Count - 1);
					}
					int maxLeaves = occurrence.Children[i].MaxLeaves;
					occurrence.MaxLeaves = ((type05RawNode.Kind == Type05NodeKind.Random) ? Math.Max(occurrence.MaxLeaves, maxLeaves) : (occurrence.MaxLeaves + maxLeaves));
				}
			}
			if (type05RawNode.Kind == Type05NodeKind.Enveloper)
			{
				build.Stages.RemoveAt(build.Stages.Count - 1);
			}
			build.OnStack.Remove(id);
			return occurrence;
		}

		private ushort RegisterFile(Type05RawNode node)
		{
			int num = Math.Max(node.File.LastIndexOf('/'), node.File.LastIndexOf('\\'));
			string text = node.File.Substring(num + 1);
			if (_fileIndex.TryGetValue(text, out var value))
			{
				return (ushort)value;
			}
			if (_fileNames.Count > 65535)
			{
				throw new Type05CueDataException($"the cues name more than {ushort.MaxValue} sound files.");
			}
			int num2 = text.LastIndexOf('.');
			string text2 = ((num2 > 0) ? text.Substring(0, num2) : text);
			_fileIndex.Add(text, _fileNames.Count);
			_fileNames.Add(text2);
			_fileAssets.Add("Assets/Y4NGZ/Type05/Source/Audio/" + text);
			_fileDurations.Add(node.Duration);
			_fileVictimVoice.Add(Type05AudioRules.VictimVoice(text2));
			return (ushort)(_fileNames.Count - 1);
		}

		private Type05ClipSoundEvent[] BuildEvents(string clip, List<Type05RawSoundEvent> sounds)
		{
			if (sounds.Count == 0)
			{
				return NoEvents;
			}
			Type05ClipSoundEvent[] array = new Type05ClipSoundEvent[sounds.Count];
			for (int i = 0; i < array.Length; i++)
			{
				Type05RawSoundEvent type05RawSoundEvent = sounds[i];
				if (!_cueIndex.TryGetValue(type05RawSoundEvent.Cue, out var value))
				{
					throw new Type05CueDataException("events table clip '" + clip + "': unknown cue '" + type05RawSoundEvent.Cue + "'.");
				}
				Type05ClipSoundEvent type05ClipSoundEvent = new Type05ClipSoundEvent(type05RawSoundEvent.Time, value, type05RawSoundEvent.Volume, type05RawSoundEvent.Pitch, type05RawSoundEvent.Side);
				int num = i;
				while (num > 0 && array[num - 1].Time > type05ClipSoundEvent.Time)
				{
					array[num] = array[num - 1];
					num--;
				}
				array[num] = type05ClipSoundEvent;
			}
			return array;
		}

		private static uint Fnv1a(string text, uint hash)
		{
			for (int i = 0; i < text.Length; i++)
			{
				hash = (hash ^ (byte)text[i]) * 16777619;
				hash = (hash ^ (byte)((int)text[i] >> 8)) * 16777619;
			}
			return hash;
		}
	}
	internal sealed class Type05CueHost
	{
		private readonly Type05CueCatalogue _catalogue;

		private readonly Random _random;

		private readonly bool[][][] _used;

		private readonly double[] _nextAllowed;

		private readonly int[] _picks;

		private ulong _eventId;

		public Type05CueHost(Type05CueCatalogue catalogue, Random random)
		{
			_catalogue = catalogue;
			_random = random;
			_used = new bool[catalogue.CueCount][][];
			_nextAllowed = new double[catalogue.CueCount];
			int num = 0;
			for (int i = 0; i < _used.Length; i++)
			{
				int num2 = catalogue.RandomCount(i);
				num = Math.Max(num, num2);
				_used[i] = new bool[num2][];
				for (int j = 0; j < num2; j++)
				{
					_used[i][j] = new bool[catalogue.RandomChildCount(i, j)];
				}
			}
			_picks = new int[num];
			Reset();
		}

		public bool TryResolve(int cue, double now, List<Type05CueLeafChoice> leaves, out ushort seed)
		{
			leaves.Clear();
			seed = 0;
			double num = _catalogue.GapSeconds(cue);
			if (num > 0.0)
			{
				if (now < _nextAllowed[cue])
				{
					return false;
				}
				_nextAllowed[cue] = now + num;
			}
			int num2 = _catalogue.RandomCount(cue);
			for (int i = 0; i < num2; i++)
			{
				_picks[i] = Pick(cue, i);
			}
			seed = (ushort)_random.Next(1, 65536);
			_catalogue.Decode(cue, _picks, seed, leaves);
			int num3 = 0;
			for (int j = 0; j < leaves.Count; j++)
			{
				if (!_catalogue.VictimVoice(leaves[j].File))
				{
					leaves[num3++] = leaves[j];
				}
			}
			leaves.RemoveRange(num3, leaves.Count - num3);
			return true;
		}

		public ulong NextEventId()
		{
			return ++_eventId;
		}

		public void Reset()
		{
			for (int i = 0; i < _used.Length; i++)
			{
				bool[][] array = _used[i];
				foreach (bool[] array2 in array)
				{
					Array.Clear(array2, 0, array2.Length);
				}
			}
			for (int k = 0; k < _nextAllowed.Length; k++)
			{
				_nextAllowed[k] = double.NegativeInfinity;
			}
			_eventId = 0uL;
		}

		private int Pick(int cue, int node)
		{
			bool[] array = _used[cue][node];
			double num = Remaining(cue, node, array);
			if (num <= 0.0)
			{
				Array.Clear(array, 0, array.Length);
				num = Remaining(cue, node, array);
				if (num <= 0.0)
				{
					return -1;
				}
			}
			double num2 = _random.NextDouble() * num;
			int num3 = -1;
			double num4 = 0.0;
			for (int i = 0; i < array.Length; i++)
			{
				double num5 = (array[i] ? 0.0 : _catalogue.RandomWeight(cue, node, i));
				if (!(num5 <= 0.0))
				{
					num3 = i;
					num4 += num5;
					if (num4 >= num2)
					{
						break;
					}
				}
			}
			array[num3] = true;
			return num3;
		}

		private double Remaining(int cue, int node, bool[] used)
		{
			double num = 0.0;
			for (int i = 0; i < used.Length; i++)
			{
				if (!used[i])
				{
					num += _catalogue.RandomWeight(cue, node, i);
				}
			}
			return num;
		}
	}
	internal enum Type05LeafState : byte
	{
		Free,
		Pending,
		Playing
	}
	internal struct Type05LeafRecord
	{
		public ulong EventId;

		public int Cue;

		public Type05CueGroup Group;

		public ushort Path;

		public ushort File;

		public double CueStart;

		public double Due;

		public float Volume;

		public float Pitch;

		public float CallerVolume;

		public float CallerPitch;

		public Type05LeafState State;

		public int Source;
	}
	internal sealed class Type05CueSchedule
	{
		private readonly Type05CueCatalogue _catalogue;

		private Type05LeafRecord[] _records;

		public ulong LastEventId { get; private set; }

		public int Capacity => _records.Length;

		public Type05CueSchedule(Type05CueCatalogue catalogue, int initialCapacity)
		{
			_catalogue = catalogue;
			_records = new Type05LeafRecord[Math.Max(1, initialCapacity)];
		}

		public ref readonly Type05LeafRecord Record(int index)
		{
			return ref _records[index];
		}

		public bool Accept(ulong eventId, int cue, double cueStart, float callerVolume, float callerPitch, Type05CueGroup group, Type05CueLeafChoice[] leaves, int count, List<int> stopSources, out string reject)
		{
			reject = null;
			if (eventId <= LastEventId)
			{
				reject = $"event id {eventId} is not above the last accepted {LastEventId}";
				return false;
			}
			if (cue < 0 || cue >= _catalogue.CueCount)
			{
				reject = $"cue {cue} does not exist";
				return false;
			}
			if (leaves == null || count < 0 || count > leaves.Length || count > _catalogue.MaxLeaves(cue))
			{
				reject = $"{count} leaves do not fit cue '{_catalogue.CueName(cue)}'";
				return false;
			}
			if (!IsFinite(cueStart) || !IsFinite(callerVolume) || !IsFinite(callerPitch))
			{
				reject = "the cue start, volume or pitch is not a finite number";
				return false;
			}
			for (int i = 0; i < count; i++)
			{
				Type05CueLeafChoice leaf = leaves[i];
				if (!_catalogue.IsLeafOf(cue, in leaf))
				{
					reject = $"leaf {i} (path {leaf.Path}, file {leaf.File}) is not a leaf of cue '{_catalogue.CueName(cue)}'";
					return false;
				}
				if (!IsFinite(leaf.Delay) || leaf.Delay < 0f || !IsFinite(leaf.Volume) || !IsFinite(leaf.Pitch))
				{
					reject = $"leaf {i} of cue '{_catalogue.CueName(cue)}' has a delay, volume or pitch that is not valid";
					return false;
				}
			}
			LastEventId = eventId;
			FreeGroup(eventId, group, stopSources, out var _);
			int j = 0;
			for (int k = 0; k < count; k++)
			{
				for (; j < _records.Length && _records[j].State != Type05LeafState.Free; j++)
				{
				}
				if (j == _records.Length)
				{
					Array.Resize(ref _records, _records.Length * 2);
				}
				_records[j] = new Type05LeafRecord
				{
					EventId = eventId,
					Cue = cue,
					Group = group,
					Path = leaves[k].Path,
					File = leaves[k].File,
					CueStart = cueStart,
					Due = cueStart + (double)leaves[k].Delay,
					Volume = leaves[k].Volume,
					Pitch = leaves[k].Pitch,
					CallerVolume = callerVolume,
					CallerPitch = callerPitch,
					State = Type05LeafState.Pending,
					Source = -1
				};
			}
			return true;
		}

		public bool StopGroup(ulong eventId, Type05CueGroup group, List<int> stopSources, out int stopped)
		{
			stopped = 0;
			if (eventId <= LastEventId)
			{
				return false;
			}
			LastEventId = eventId;
			FreeGroup(eventId, group, stopSources, out stopped);
			return true;
		}

		public void Due(double now, List<int> starts, out int dropped)
		{
			dropped = 0;
			for (int i = 0; i < _records.Length; i++)
			{
				if (_records[i].State == Type05LeafState.Pending && !(now < _records[i].Due))
				{
					if (FilePosition(i, now) >= (double)_catalogue.FileDuration(_records[i].File))
					{
						_records[i].State = Type05LeafState.Free;
						dropped++;
					}
					else
					{
						starts.Add(i);
					}
				}
			}
		}

		public float Seek(int index, double now)
		{
			double num = FilePosition(index, now);
			if (!(num > 0.0) || !(num < (double)_catalogue.FileDuration(_records[index].File)))
			{
				return 0f;
			}
			return (float)num;
		}

		public void MarkPlaying(int index, int source)
		{
			_records[index].State = Type05LeafState.Playing;
			_records[index].Source = source;
		}

		public void Release(int index)
		{
			_records[index].State = Type05LeafState.Free;
			_records[index].Source = -1;
		}

		public void Reset(List<int> stopSources, out int cancelled)
		{
			cancelled = 0;
			for (int i = 0; i < _records.Length; i++)
			{
				if (_records[i].State == Type05LeafState.Playing)
				{
					stopSources.Add(_records[i].Source);
				}
				else if (_records[i].State == Type05LeafState.Pending)
				{
					cancelled++;
				}
				_records[i].State = Type05LeafState.Free;
				_records[i].Source = -1;
			}
			LastEventId = 0uL;
		}

		private void FreeGroup(ulong eventId, Type05CueGroup group, List<int> stopSources, out int freed)
		{
			freed = 0;
			if (group == Type05CueGroup.None)
			{
				return;
			}
			for (int i = 0; i < _records.Length; i++)
			{
				if (_records[i].State != Type05LeafState.Free && _records[i].Group == group && _records[i].EventId < eventId)
				{
					if (_records[i].State == Type05LeafState.Playing)
					{
						stopSources.Add(_records[i].Source);
					}
					_records[i].State = Type05LeafState.Free;
					_records[i].Source = -1;
					freed++;
				}
			}
		}

		private double FilePosition(int index, double now)
		{
			return (now - _records[index].Due) * (double)Math.Max(0.1f, _records[index].Pitch * _records[index].CallerPitch);
		}

		private static bool IsFinite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}
	}
	internal static class Type05BloodAssets
	{
		private sealed class Composite
		{
			public Texture BaseMap;

			public Type05BloodPart Part;

			public int Level;

			public RenderTexture Target;

			public int References;
		}

		private const string PrintFramePrefix = "Assets/Y4NGZ/Type05/Source/Blood/mechanical_blood_footprint_";

		private const string PrintMaterialPath = "Assets/Y4NGZ/Type05/Blood/Type05_BloodFootprint.mat";

		private const string DropMaterialPath = "Assets/Y4NGZ/Type05/Blood/Type05_BloodDrop.mat";

		private const string BlitShaderName = "UI/Default";

		private const float ColorMaskRgb = 14f;

		private const float LiveCheckSeconds = 1f;

		private const int PartCount = 6;

		private static readonly int ColorId = Shader.PropertyToID("_Color");

		private static readonly int ColorMaskId = Shader.PropertyToID("_ColorMask");

		private static readonly int TextureSampleAddId = Shader.PropertyToID("_TextureSampleAdd");

		private static readonly int UnlitColorMapId = Shader.PropertyToID("_UnlitColorMap");

		private static readonly int UnlitColorId = Shader.PropertyToID("_UnlitColor");

		private static readonly int BaseColorMapId = Shader.PropertyToID("_BaseColorMap");

		private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor");

		private static readonly Texture2D[] Sheets = (Texture2D[])(object)new Texture2D[18];

		private static readonly Texture2D[] PrintFrames = (Texture2D[])(object)new Texture2D[4];

		private static readonly List<Composite> Composites = new List<Composite>(18);

		private static readonly Action<ScriptableRenderContext, List<Camera>> LiveCheck = CheckLive;

		private static Shader _blitShader;

		private static bool _blitSearched;

		private static Material _blit;

		private static int _targets;

		private static float _liveAt;

		internal static bool PrintsReady { get; private set; }

		internal static bool DripReady { get; private set; }

		internal static Material PrintMaterial { get; private set; }

		internal static Material DropMaterial { get; private set; }

		internal static int PrintMapId { get; private set; } = BaseColorMapId;

		internal static int PrintColorId { get; private set; } = BaseColorId;

		internal static Color PrintTint { get; private set; } = Color.white;

		internal static int CompositeCount => Composites.Count;

		internal static void Load(AssetBundle bundle)
		{
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			for (int i = 1; i <= 6; i++)
			{
				for (int j = 1; j <= 3; j++)
				{
					string text = Type05BloodRules.SheetPath((Type05BloodPart)i, j);
					Texture2D val = bundle.LoadAsset<Texture2D>(text);
					Sheets[SheetIndex((Type05BloodPart)i, j)] = val;
					if ((Object)(object)val == (Object)null)
					{
						stringBuilder.Append((num++ == 0) ? string.Empty : ", ").Append(text);
					}
				}
			}
			if (num > 0)
			{
				Plugin.Log.LogWarning((object)$"[Type05] blood coat: {num} of {Sheets.Length} sheets missing from the bundle, those coats stay off: {stringBuilder}");
			}
			stringBuilder.Clear();
			for (int k = 0; k < PrintFrames.Length; k++)
			{
				string text2 = "Assets/Y4NGZ/Type05/Source/Blood/mechanical_blood_footprint_" + k + ".png";
				PrintFrames[k] = bundle.LoadAsset<Texture2D>(text2);
				if ((Object)(object)PrintFrames[k] == (Object)null)
				{
					stringBuilder.Append((stringBuilder.Length == 0) ? string.Empty : ", ").Append(text2);
				}
			}
			PrintMaterial = bundle.LoadAsset<Material>("Assets/Y4NGZ/Type05/Blood/Type05_BloodFootprint.mat");
			if ((Object)(object)PrintMaterial == (Object)null)
			{
				stringBuilder.Append((stringBuilder.Length == 0) ? string.Empty : ", ").Append("Assets/Y4NGZ/Type05/Blood/Type05_BloodFootprint.mat");
			}
			PrintsReady = stringBuilder.Length == 0;
			if (PrintsReady)
			{
				bool num2 = PrintMaterial.HasProperty(UnlitColorMapId);
				PrintMapId = (num2 ? UnlitColorMapId : BaseColorMapId);
				PrintColorId = (num2 ? UnlitColorId : BaseColorId);
				if (PrintMaterial.HasProperty(PrintColorId))
				{
					PrintTint = PrintMaterial.GetColor(PrintColorId);
				}
			}
			else
			{
				Plugin.Log.LogInfo((object)$"[Type05] blood prints off: {stringBuilder}");
			}
			DropMaterial = bundle.LoadAsset<Material>("Assets/Y4NGZ/Type05/Blood/Type05_BloodDrop.mat");
			DripReady = (Object)(object)DropMaterial != (Object)null;
			if (!DripReady)
			{
				Plugin.Log.LogInfo((object)"[Type05] blood drip off: Assets/Y4NGZ/Type05/Blood/Type05_BloodDrop.mat");
			}
			Plugin.Log.LogInfo((object)string.Format("[Type05] blood assets: {0} of {1} sheets, prints {2}, drip {3}", Sheets.Length - num, Sheets.Length, PrintsReady ? "on" : "off", DripReady ? "on" : "off"));
		}

		internal static Texture2D Sheet(Type05BloodPart part, int level)
		{
			if ((int)part <= 0 || (int)part > 6 || level < 1 || level > 3)
			{
				return null;
			}
			return Sheets[SheetIndex(part, level)];
		}

		internal static Texture2D PrintFrame(int frame)
		{
			return PrintFrames[frame];
		}

		internal static RenderTexture Acquire(Texture baseMap, Type05BloodPart part, int level)
		{
			Texture2D val = Sheet(part, level);
			if ((Object)(object)baseMap == (Object)null || (Object)(object)val == (Object)null)
			{
				return null;
			}
			for (int i = 0; i < Composites.Count; i++)
			{
				Composite composite = Composites[i];
				if (composite.BaseMap == baseMap && composite.Part == part && composite.Level == level)
				{
					composite.References++;
					return composite.Target;
				}
			}
			RenderTexture val2 = CreateTarget(baseMap, $"Type05BloodCoat_{((Object)baseMap).name}_{part}_{level}");
			if ((Object)(object)val2 == (Object)null)
			{
				return null;
			}
			Compose(val2, baseMap, null, 0f, (Texture)(object)val, 1f);
			Composites.Add(new Composite
			{
				BaseMap = baseMap,
				Part = part,
				Level = level,
				Target = val2,
				References = 1
			});
			return val2;
		}

		internal static void Release(RenderTexture target)
		{
			for (int i = 0; i < Composites.Count; i++)
			{
				Composite composite = Composites[i];
				if (composite.Target == target)
				{
					if (--composite.References <= 0)
					{
						int index = Composites.Count - 1;
						Composites[i] = Composites[index];
						Composites.RemoveAt(index);
						DestroyTarget(target);
					}
					break;
				}
			}
		}

		internal static RenderTexture CreateTarget(Texture baseMap, string name)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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_004c: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			if (!EnsureBlit())
			{
				return null;
			}
			RenderTexture val = new RenderTexture(baseMap.width, baseMap.height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2)
			{
				name = name,
				useMipMap = true,
				autoGenerateMips = true,
				wrapModeU = baseMap.wrapModeU,
				wrapModeV = baseMap.wrapModeV,
				filterMode = baseMap.filterMode,
				anisoLevel = baseMap.anisoLevel
			};
			val.Create();
			if (++_targets == 1)
			{
				RenderPipelineManager.beginContextRendering += LiveCheck;
			}
			return val;
		}

		internal static void DestroyTarget(RenderTexture target)
		{
			if ((Object)(object)target != (Object)null)
			{
				target.Release();
				Object.Destroy((Object)(object)target);
			}
			if (--_targets <= 0)
			{
				_targets = 0;
				RenderPipelineManager.beginContextRendering -= LiveCheck;
				if ((Object)(object)_blit != (Object)null)
				{
					Object.Destroy((Object)(object)_blit);
				}
				_blit = null;
			}
		}

		internal static void Compose(RenderTexture target, Texture baseMap, Texture under, float underAlpha, Texture over, float overAlpha)
		{
			RenderTexture active = RenderTexture.active;
			bool sRGBWrite = GL.sRGBWrite;
			GL.sRGBWrite = true;
			try
			{
				Graphics.Blit(baseMap, target);
				Overlay(target, under, underAlpha);
				Overlay(target, over, overAlpha);
			}
			finally
			{
				GL.sRGBWrite = sRGBWrite;
				RenderTexture.active = active;
			}
		}

		private static void CheckLive(ScriptableRenderContext context, List<Camera> cameras)
		{
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime < _liveAt)
			{
				return;
			}
			_liveAt = unscaledTime + 1f;
			for (int i = 0; i < Composites.Count; i++)
			{
				Composite composite = Composites[i];
				if (!composite.Target.IsCreated() && !((Object)(object)composite.BaseMap == (Object)null))
				{
					composite.Target.Create();
					Compose(composite.Target, composite.BaseMap, null, 0f, (Texture)(object)Sheet(composite.Part, composite.Level), 1f);
				}
			}
		}

		private static int SheetIndex(Type05BloodPart part, int level)
		{
			return (int)(part - 1) * 3 + level - 1;
		}

		private static void Overlay(RenderTexture target, Texture sheet, float alpha)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)sheet == (Object)null) && !(alpha <= 0f) && !((Object)(object)_blit == (Object)null))
			{
				_blit.SetColor(ColorId, new Color(1f, 1f, 1f, alpha));
				Graphics.Blit(sheet, target, _blit);
			}
		}

		private static bool EnsureBlit()
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_blit != (Object)null)
			{
				return true;
			}
			if (!_blitSearched)
			{
				_blitSearched = true;
				_blitShader = Shader.Find("UI/Default");
				if ((Object)(object)_blitShader == (Object)null)
				{
					Plugin.Log.LogWarning((object)"[Type05] blood coat off: no UI/Default shader to draw the composites with");
				}
			}
			if ((Object)(object)_blitShader == (Object)null)
			{
				return false;
			}
			_blit = new Material(_blitShader)
			{
				name = "Type05BloodBlit"
			};
			_blit.SetFloat(ColorMaskId, 14f);
			_blit.SetVector(TextureSampleAddId, Vector4.zero);
			return true;
		}
	}
	internal sealed class Type05BloodCoat
	{
		private struct Slot
		{
			public Renderer Renderer;

			public int Index;

			public Type05BloodPart Part;

			public Texture BaseMap;

			public int Group;

			public RenderTexture Composite;

			public bool Coated;
		}

		private static readonly int BaseColorMapId = Shader.PropertyToID("_BaseColorMap");

		private static MaterialPropertyBlock _scratch;

		private readonly Slot[] _slots;

		private readonly Texture[] _groupMaps;

		private readonly Type05BloodPart[] _groupParts;

		private readonly RenderTexture[] _fadeTargets;

		private readonly int _plateSlot = -1;

		private double _fadeStart;

		private bool _applied;

		public byte Shown { get; private set; }

		public bool Fading { get; private set; }

		public Type05BloodCoat(Renderer[] renderers)
		{
			List<Slot> list = new List<Slot>();
			List<Texture> list2 = new List<Texture>();
			List<Type05BloodPart> list3 = new List<Type05BloodPart>();
			foreach (Renderer val in renderers)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				bool flag = ((Object)val).name == "Type05Plate";
				Material[] sharedMaterials = val.sharedMaterials;
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					Material val2 = sharedMaterials[j];
					Type05BloodPart type05BloodPart = (((Object)(object)val2 != (Object)null) ? Type05BloodRules.PartFor(((Object)val2).name) : Type05BloodPart.None);
					Texture val3 = ((type05BloodPart != Type05BloodPart.None && val2.HasProperty(BaseColorMapId)) ? val2.GetTexture(BaseColorMapId) : null);
					if (!((Object)(object)val3 == (Object)null))
					{
						int k;
						for (k = 0; k < list2.Count && (list2[k] != val3 || list3[k] != type05BloodPart); k++)
						{
						}
						if (k == list2.Count)
						{
							list2.Add(val3);
							list3.Add(type05BloodPart);
						}
						if (flag && j == 0)
						{
							_plateSlot = list.Count;
						}
						list.Add(new Slot
						{
							Renderer = val,
							Index = j,
							Part = type05BloodPart,
							BaseMap = val3,
							Group = k
						});
					}
				}
			}
			_slots = list.ToArray();
			_groupMaps = list2.ToArray();
			_groupParts = list3.ToArray();
			_fadeTargets = (RenderTexture[])(object)new RenderTexture[_groupMaps.Length];
			if (_slots.Length == 0)
			{
				Plugin.Log.LogWarning((object)$"[Type05] blood coat: none of {renderers.Length} renderers shows a blood material; no coat");
			}
		}

		internal static void SetBaseMap(Renderer renderer, int index, Texture map)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			if (_scratch == null)
			{
				_scratch = new MaterialPropertyBlock();
			}
			renderer.GetPropertyBlock(_scratch, index);
			_scratch.SetTexture(BaseColorMapId, map);
			renderer.SetPropertyBlock(_scratch, index);
		}

		public void Show(byte level)
		{
			if (!_applied && level == 0)
			{
				_applied = true;
				Shown = 0;
				return;
			}
			_applied = true;
			for (int i = 0; i < _slots.Length; i++)
			{
				ref Slot reference = ref _slots[i];
				RenderTexture val = ((level > 0) ? Type05BloodAssets.Acquire(reference.BaseMap, reference.Part, level) : null);
				RenderTexture composite = reference.Composite;
				reference.Composite = val;
				if ((Object)(object)val != (Object)null)
				{
					Write(ref reference, (Texture)(object)val);
				}
				else if (reference.Coated)
				{
					Write(ref reference, reference.BaseMap);
				}
				if (composite != null)
				{
					Type05BloodAssets.Release(composite);
				}
			}
			DropFade();
			Shown = level;
		}

		public void FadeTo(byte level, double start)
		{
			if (Fading)
			{
				Show(Shown);
			}
			if (level == 0 || _slots.Length == 0)
			{
				Show(level);
				return;
			}
			for (int i = 0; i < _fadeTargets.Length; i++)
			{
				_fadeTargets[i] = Type05BloodAssets.CreateTarget(_groupMaps[i], $"Type05BloodFade_{_groupParts[i]}");
				if ((Object)(object)_fadeTargets[i] == (Object)null)
				{
					DropFade();
					Show(level);
					return;
				}
			}
			_applied = true;
			Fading = true;
			Shown = level;
			_fadeStart = start;
			ComposeFade(0f);
			for (int j = 0; j < _slots.Length; j++)
			{
				ref Slot reference = ref _slots[j];
				RenderTexture composite = reference.Composite;
				reference.Composite = null;
				Write(ref reference, (Texture)(object)_fadeTargets[reference.Group]);
				if (composite != null)
				{
					Type05BloodAssets.Release(composite);
				}
			}
		}

		public void Tick(double now)
		{
			if (Fading)
			{
				float num = Type05BloodRules.CoatFade(_fadeStart, now);
				if (num >= 1f)
				{
					Show(Shown);
				}
				else
				{
					ComposeFade(num);
				}
			}
		}

		public RenderTexture AcquirePlate(byte level, out Texture baseMap)
		{
			baseMap = ((_plateSlot >= 0) ? _slots[_plateSlot].BaseMap : null);
			if (level <= 0 || !((Object)(object)baseMap != (Object)null))
			{
				return null;
			}
			return Type05BloodAssets.Acquire(baseMap, _slots[_plateSlot].Part, level);
		}

		public void Release()
		{
			for (int i = 0; i < _slots.Length; i++)
			{
				ref Slot reference = ref _slots[i];
				if (reference.Coated)
				{
					Write(ref reference, reference.BaseMap);
				}
				if (reference.Composite != null)
				{
					Type05BloodAssets.Release(reference.Composite);
				}
				reference.Composite = null;
			}
			DropFade();
			Shown = 0;
			_applied = false;
		}

		private void ComposeFade(float fade)
		{
			for (int i = 0; i < _fadeTargets.Length; i++)
			{
				Type05BloodPart part = _groupParts[i];
				Type05BloodAssets.Compose(_fadeTargets[i], _groupMaps[i], (Texture)(object)Type05BloodAssets.Sheet(part, Shown - 1), 1f - fade, (Texture)(object)Type05BloodAssets.Sheet(part, Shown), fade);
			}
		}

		private void DropFade()
		{
			for (int i = 0; i < _fadeTargets.Length; i++)
			{
				if (_fadeTargets[i] != null)
				{
					Type05BloodAssets.DestroyTarget(_fadeTargets[i]);
					_fadeTargets[i] = null;
				}
			}
			Fading = false;
		}

		private static void Write(ref Slot slot, Texture map)
		{
			slot.Coated = map != slot.BaseMap;
			if ((Object)(object)slot.Renderer != (Object)null)
			{
				SetBaseMap(slot.Renderer, slot.Index, map);
			}
		}
	}
	internal sealed class Type05BloodDrip
	{
		private const int MaxDrops = 64;

		private static readonly Color32 DropColor = new Color32((byte)120, (byte)7, (byte)5, (byte)245);

		private readonly ulong _robot;

		private GameObject _object;

		private ParticleSystem _system;

		private EmitParams _emit;

		private double _next;

		private bool _live;

		private bool _second;

		public int ActiveDrops
		{
			get
			{
				if (!((Object)(object)_system != (Object)null))
				{
					return 0;
				}
				return _system.particleCount;
			}
		}

		public Type05BloodDrip(ulong robot)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			_robot = robot;
			_object = new GameObject("Type05BloodDrops");
			_object.SetActive(false);
			_system = _object.AddComponent<ParticleSystem>();
			MainModule main = _system.main;
			((MainModule)(ref main)).playOnAwake = false;
			((MainModule)(ref main)).loop = false;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			((MainModule)(ref main)).maxParticles = 64;
			((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(1.45f);
			float num = 0f - Physics.gravity.y;
			((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit((num > 0f) ? (15.24f / num) : 0f);
			EmissionModule emission = _system.emission;
			((EmissionModule)(ref emission)).enabled = false;
			SizeOverLifetimeModule sizeOverLifetime = _system.sizeOverLifetime;
			((SizeOverLifetimeModule)(ref sizeOverLifetime)).enabled = true;
			((SizeOverLifetimeModule)(ref sizeOverLifetime)).size = new MinMaxCurve(1f, AnimationCurve.Linear(0f, 1f, 1f, 28f / 55f));
			CollisionModule collision = _system.collision;
			((CollisionModule)(ref collision)).enabled = true;
			((CollisionModule)(ref collision)).type = (ParticleSystemCollisionType)1;
			((CollisionModule)(ref collision)).mode = (ParticleSystemCollisionMode)0;
			((CollisionModule)(ref collision)).quality = (ParticleSystemCollisionQuality)2;
			((CollisionModule)(ref collision)).lifetimeLoss = MinMaxCurve.op_Implicit(1f);
			((CollisionModule)(ref collision)).bounce = MinMaxCurve.op_Implicit(0f);
			if ((Object)(object)StartOfRound.Instance != (Object)null)
			{
				((CollisionModule)(ref collision)).collidesWith = LayerMask.op_Implicit(StartOfRound.Instance.collidersAndRoomMaskAndDefault);
			}
			ParticleSystemRenderer component = _object.GetComponent<ParticleSystemRenderer>();
			component.renderMode = (ParticleSystemRenderMode)0;
			((Renderer)component).sharedMaterial = Type05BloodAssets.DropMaterial;
			((Renderer)component).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)component).receiveShadows = false;
			_object.SetActive(true);
		}

		public void Tick(double now, double killAt, bool awake, Vector3 velocity, Transform a, Transform b)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: 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)
			if ((Object)(object)_system == (Object)null)
			{
				return;
			}
			bool flag = Type05BloodRules.DripLive(killAt, now, awake);
			if (flag != _live)
			{
				_live = flag;
				_next = now;
				Plugin.Log.LogInfo((object)string.Format("[Type05] blood-drip robot={0} {1}", _robot, flag ? "start" : "stop"));
			}
			if (flag && !(now < _next))
			{
				((EmitParams)(ref _emit)).position = (_second ? b : a).position;
				((EmitParams)(ref _emit)).velocity = velocity * 0.65f + Vector3.down * 0.4064f;
				((EmitParams)(ref _emit)).startSize = 0.01397f;
				((EmitParams)(ref _emit)).startColor = DropColor;
				_second = !_second;
				if (!_system.isPlaying)
				{
					_system.Play(false);
				}
				_system.Emit(_emit, 1);
				_next = now + (double)Type05BloodRules.DripInterval(now - killAt);
			}
		}

		public void Release()
		{
			if ((Object)(object)_object != (Object)null)
			{
				Object.Destroy((Object)(object)_object);
			}
			_object = null;
			_system = null;
		}
	}
	internal enum Type05BloodPart : byte
	{
		None,
		Armour,
		Head,
		GripHand,
		RightLegArmour,
		Innards,
		RightLegInnards
	}
	internal static class Type05BloodRules
	{
		private const string SheetFolder = "Assets/Y4NGZ/Type05/Source/Blood/";

		private static readonly string[] PartNames = new string[7] { null, "armour", "head", "griphand", "rightlegarmour", "innards", "rightleginnards" };

		private static readonly string[] Sheets = BuildSheets();

		public static bool TryCredit(byte level, int serial, int lastCreditedSerial, out byte next)
		{
			if (serial <= lastCreditedSerial)
			{
				next = level;
				return false;
			}
			next = (byte)Math.Min(level + 1, 3);
			return true;
		}

		public static Type05State WithCredit(Type05State state, byte level, double now)
		{
			state.BloodLevel = level;
			state.BloodKillAt = now;
			return state;
		}

		public static Type05State WithBody(Type05State state, byte level)
		{
			state.BloodLevel = level;
			state.BloodKillAt = 0.0;
			return state;
		}

		public static bool IsNewCredit(in Type05State previous, in Type05State current, bool spawn)
		{
			if (!spawn && previous.BodyIndex == current.BodyIndex && current.BloodKillAt > 0.0)
			{
				return !current.BloodKillAt.Equals(previous.BloodKillAt);
			}
			return false;
		}

		public static bool CoatRose(in Type05State previous, in Type05State current, bool spawn)
		{
			if (IsNewCredit(in previous, in current, spawn))
			{
				return current.BloodLevel > previous.BloodLevel;
			}
			return false;
		}

		public static bool IsAwakePhase(Type05Phase phase)
		{
			if (phase != Type05Phase.Dormant && phase != Type05Phase.Shutdown && phase != Type05Phase.Dying)
			{
				return phase != Type05Phase.Dead;
			}
			return false;
		}

		public static bool DripLive(double killAt, double now, bool awake)
		{
			double num = now - killAt;
			if (awake && killAt > 0.0 && num >= 0.0)
			{
				return num < 12.0;
			}
			return false;
		}

		public static float DripInterval(double age)
		{
			float num = (float)Math.Clamp(age / 12.0, 0.0, 1.0);
			return 0.14f * (1f - num) + 0.58f * num;
		}

		public static float CoatFade(double start, double now)
		{
			return (float)Math.Clamp((now - start) / 2.0, 0.0, 1.0);
		}

		public static bool FloorAccepts(bool hit, float normalY, bool water)
		{
			if (hit && normalY >= 0.65f)
			{
				return !water;
			}
			return false;
		}

		public static bool TooClose(bool hasLast, Type05Point last, float lastAge, Type05Point next)
		{
			if (!hasLast || lastAge >= 45f)
			{
				return false;
			}
			float num = next.X - last.X;
			float num2 = next.Y - last.Y;
			float num3 = next.Z - last.Z;
			return num * num + num2 * num2 + num3 * num3 < 0.02322576f;
		}

		public static int NextFrame(int last, int roll)
		{
			if (roll < last || last < 0)
			{
				return roll;
			}
			return roll + 1;
		}

		public static float PrintAlpha(int budgetBefore, float pressure, float age)
		{
			if (age >= 45f)
			{
				return 0f;
			}
			float num = MathF.Pow(Math.Clamp((float)budgetBefore / 8f, 0f, 1f), 0.7f);
			float num2 = Math.Clamp((45f - age) / 10f, 0f, 1f);
			return num * pressure * num2;
		}

		public static int NextSlot(int slot)
		{
			return (slot + 1) % 32;
		}

		public static Type05BloodPart PartFor(string materialName)
		{
			if (materialName == null)
			{
				return Type05BloodPart.None;
			}
			if (Has(materialName, "Head_Default"))
			{
				return Type05BloodPart.Head;
			}
			if (Has(materialName, "RightForearm_Default"))
			{
				return Type05BloodPart.Armour;
			}
			if (Has(materialName, "GripHand_Default"))
			{
				return Type05BloodPart.GripHand;
			}
			if (Has(materialName, "RightLegArmour_Default"))
			{
				return Type05BloodPart.RightLegArmour;
			}
			if (Has(materialName, "RightLegInnards_Default"))
			{
				return Type05BloodPart.RightLegInnards;
			}
			if (Has(materialName, "Innards_Default"))
			{
				return Type05BloodPart.Innards;
			}
			if (!Has(materialName, "Armour_Default"))
			{
				return Type05BloodPart.None;
			}
			return Type05BloodPart.Armour;
		}

		public static string SheetPath(Type05BloodPart part, int level)
		{
			if (part == Type05BloodPart.None || (int)part >= PartNames.Length || level < 1 || level > 3)
			{
				return null;
			}
			return Sheets[(int)(part - 1) * 3 + level - 1];
		}

		private static bool Has(string name, string part)
		{
			return name.IndexOf(part, StringComparison.Ordinal) >= 0;
		}

		private static string[] BuildSheets()
		{
			string[] array = new string[(PartNames.Length - 1) * 3];
			for (int i = 1; i < PartNames.Length; i++)
			{
				for (int j = 1; j <= 3; j++)
				{
					array[(i - 1) * 3 + j - 1] = string.Format("{0}blood_{1}_{2}.png", "Assets/Y4NGZ/Type05/Source/Blood/", PartNames[i], j);
				}
			}
			return array;
		}
	}
	internal static class Type05BloodTuning
	{
		public const byte MaxLevel = 3;

		public const int PrintsPerKill = 8;

		public const double CoatFadeSeconds = 2.0;

		public const double DripSeconds = 12.0;

		public const float DripIntervalStart = 0.14f;

		public const float DripIntervalEnd = 0.58f;

		public const float PrintLifetime = 45f;

		public const float PrintFadeSeconds = 10f;

		public const float PrintSpacing = 0.1524f;

		public const float PrintWidth = 0.304292f;

		public const float PrintLift = 0.003048f;

		public const float FloorMinNormalY = 0.65f;

		public const int PrintPoolSize = 32;

		public const int PrintFrames = 4;

		public const float PrintStrengthExponent = 0.7f;

		public const float PressureMin = 0.75f;

		public const float PressureMax = 1f;

		public const float PrintFadeInterval = 0.125f;

		public const float FootForward = 0.0938276f;

		public const float FootLateral = 0.009652f;

		public const float ProbeAboveFoot = 0.254f;

		public const float ProbeAboveRoot = 0.508f;

		public const float ProbeBelowRoot = 0.6096f;

		public const float DropLifetime = 1.45f;

		public const float DropStartSize = 0.01397f;

		public const float DropEndSize = 0.007112f;

		public const float DropGravity = 15.24f;

		public const float DropFallSpeed = 0.4064f;

		public const float DropInheritVelocity = 0.65f;
	}
	internal sealed class Type05FootprintPool
	{
		private sealed class Mark
		{
			public Transform Transform;

			public MeshRenderer Renderer;

			public MaterialPropertyBlock Block;

			public float PlacedAt;

			public int BudgetBefore;

			public float Pressure;

			public float Alpha;

			public bool Live;
		}

		private readonly Mark[] _marks = new Mark[32];

		private GameObject _container;

		private Mesh _mesh;

		private int _slot = 31;

		private float _nextFade;

		public int Active { get; private set; }

		public Type05FootprintPool()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			_container = new GameObject("Type05BloodFootprints");
			_mesh = BuildQuad();
			for (int i = 0; i < _marks.Length; i++)
			{
				GameObject val = new GameObject($"Footprint_{i:00}");
				val.transform.SetParent(_container.transform, false);
				val.AddComponent<MeshFilter>().sharedMesh = _mesh;
				MeshRenderer val2 = val.AddComponent<MeshRenderer>();
				((Renderer)val2).sharedMaterial = Type05BloodAssets.PrintMaterial;
				((Renderer)val2).shadowCastingMode = (ShadowCastingMode)0;
				((Renderer)val2).receiveShadows = false;
				((Renderer)val2).enabled = false;
				_marks[i] = new Mark
				{
					Transform = val.transform,
					Renderer = val2,
					Block = new MaterialPropertyBlock()
				};
			}
		}

		public void Place(Vector3 point, Vector3 normal, Vector3 forward, int frame, int budgetBefore, float pressure, float now)
		{
			//IL_002e: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: 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_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to