Decompiled source of JajamaruBand v0.5.1

BepInEx/plugins/JajamaruBand.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using EmotesAPI;
using GameNetcodeStuff;
using LethalEmotesAPI.ImportV2;
using ModelReplacement;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Video;

[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("JajamaruBand")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.5.1.0")]
[assembly: AssemblyInformationalVersion("0.5.1")]
[assembly: AssemblyProduct("JajamaruBand")]
[assembly: AssemblyTitle("JajamaruBand")]
[assembly: AssemblyVersion("0.5.1.0")]
namespace JajamaruBand;

public enum BandRole
{
	Singer,
	Guitar,
	Bass,
	Drums
}
public sealed class BandSession
{
	private readonly Dictionary<BandRole, ulong> performers = new Dictionary<BandRole, ulong>();

	public Guid Id { get; } = Guid.NewGuid();

	public double StartTime { get; }

	public double Duration { get; }

	public bool Ended { get; private set; }

	public int Revision { get; private set; }

	public IReadOnlyDictionary<BandRole, ulong> Performers => new ReadOnlyDictionary<BandRole, ulong>(performers);

	public BandSession(ulong starter, BandRole role, double serverNow, double duration)
	{
		if (!ValidTime(serverNow) || !ValidTime(duration) || duration <= 0.0 || !Enum.IsDefined(typeof(BandRole), role))
		{
			throw new ArgumentOutOfRangeException();
		}
		StartTime = serverNow;
		Duration = duration;
		performers.Add(role, starter);
		Revision = 1;
	}

	private static bool ValidTime(double value)
	{
		if (!double.IsNaN(value) && !double.IsInfinity(value))
		{
			return value >= 0.0;
		}
		return false;
	}

	public double Position(double serverNow)
	{
		if (!ValidTime(serverNow))
		{
			throw new ArgumentOutOfRangeException("serverNow");
		}
		return Math.Max(0.0, Math.Min(Duration, serverNow - StartTime));
	}

	public bool TryJoin(ulong player, BandRole role, double serverNow, int expectedRevision)
	{
		Tick(serverNow);
		if (Ended || Revision != expectedRevision || !Enum.IsDefined(typeof(BandRole), role) || performers.ContainsKey(role) || performers.ContainsValue(player))
		{
			return false;
		}
		performers.Add(role, player);
		Revision++;
		return true;
	}

	public bool Leave(ulong player)
	{
		BandRole? bandRole = null;
		foreach (KeyValuePair<BandRole, ulong> performer in performers)
		{
			if (performer.Value == player)
			{
				bandRole = performer.Key;
				break;
			}
		}
		if (!bandRole.HasValue)
		{
			return false;
		}
		performers.Remove(bandRole.Value);
		Revision++;
		if (performers.Count == 0)
		{
			Ended = true;
		}
		return true;
	}

	public void Tick(double serverNow)
	{
		if (!Ended && Position(serverNow) >= Duration)
		{
			End();
		}
	}

	public void End()
	{
		if (!Ended)
		{
			performers.Clear();
			Ended = true;
			Revision++;
		}
	}
}
internal sealed class LocalBandPreview
{
	private sealed class Actor
	{
		public GameObject model;

		public Vector3 scale;
	}

	private readonly Dictionary<int, Actor> actors = new Dictionary<int, Actor>();

	private GameObject[] characters;

	private AnimationClip[] clips;

	public bool Enabled { get; private set; }

	public void Initialize(GameObject[] models, AnimationClip[] animations)
	{
		characters = models;
		clips = animations;
	}

	public void Toggle()
	{
		if (Enabled)
		{
			Stop();
		}
		else
		{
			Enabled = true;
		}
	}

	private void Remove(int role)
	{
		if (actors.TryGetValue(role, out var value))
		{
			if ((Object)(object)value.model != (Object)null)
			{
				Object.Destroy((Object)(object)value.model);
			}
			actors.Remove(role);
		}
	}

	public void Stop()
	{
		Enabled = false;
		foreach (int item in new List<int>(actors.Keys))
		{
			Remove(item);
		}
	}

	public void Tick(Transform leader, float songTime, IEnumerable<int> occupiedRoles, Vector3 scale)
	{
		//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
		if (!Enabled)
		{
			return;
		}
		HashSet<int> hashSet = new HashSet<int>(occupiedRoles);
		for (int i = 0; i < 4; i++)
		{
			if (hashSet.Contains(i))
			{
				Remove(i);
				continue;
			}
			if (!actors.TryGetValue(i, out var value))
			{
				value = new Actor();
				actors.Add(i, value);
				value.model = Object.Instantiate<GameObject>(characters[i]);
				((Object)value.model).name = "Jajamaru Local Test - " + i;
				value.scale = Vector3.Scale(characters[i].transform.localScale, scale);
				value.model.transform.localScale = value.scale;
				value.model.transform.SetPositionAndRotation(leader.position + leader.right * (((float)i - 1.5f) * 1.7f) + leader.forward * 3f, leader.rotation);
				Collider[] componentsInChildren = value.model.GetComponentsInChildren<Collider>();
				for (int j = 0; j < componentsInChildren.Length; j++)
				{
					componentsInChildren[j].enabled = false;
				}
				SkinnedMeshRenderer[] componentsInChildren2 = value.model.GetComponentsInChildren<SkinnedMeshRenderer>(true);
				foreach (SkinnedMeshRenderer val in componentsInChildren2)
				{
					val.updateWhenOffscreen = true;
					if (((Object)val).name.StartsWith("PerformanceStick"))
					{
						((Component)val).gameObject.SetActive(i == 3);
					}
				}
				DirectPerformance.Prepare(value.model);
			}
			DirectPerformance.Sample(value.model, clips[i], songTime);
			value.model.transform.localScale = value.scale;
		}
	}
}
public sealed class LocalRolePreview
{
	private int selected = -1;

	public int Resolve(int networkRole, bool local)
	{
		if (!local || selected < 0)
		{
			return networkRole;
		}
		return selected;
	}

	public void Select(int role)
	{
		if (role < 0 || role > 3)
		{
			throw new ArgumentOutOfRangeException("role");
		}
		selected = role;
	}

	public void Reset()
	{
		selected = -1;
	}
}
[BepInPlugin("matthias.lethalcompany.jajamaruband", "Jajamaru Band", "0.5.1")]
[BepInDependency("meow.ModelReplacementAPI", "2.4.20")]
[BepInDependency("com.weliveinasociety.CustomEmotesAPI", "1.18.0")]
public sealed class Plugin : BaseUnityPlugin
{
	public const string Id = "matthias.lethalcompany.jajamaruband";

	private const string EmoteName = "rig_preview";

	private const string BandName = "band_performance";

	private static readonly string[] Roles = new string[4] { "singer", "guitar", "bass", "drums" };

	private readonly Dictionary<PlayerControllerB, BoneMapper> performers = new Dictionary<PlayerControllerB, BoneMapper>();

	private GameObject[] roleProps;

	private GameObject[] roleModels;

	private AnimationClip[] directClips;

	private GameObject drumstick;

	private float songLength;

	internal static GameObject Character;

	private AssetBundle bundle;

	private readonly Dictionary<PlayerControllerB, Type> previous = new Dictionary<PlayerControllerB, Type>();

	private bool subscribed;

	private LocalBandPreview preview;

	private BandStemMixer stemMixer;

	private AudioClip silentClock;

	private BandVideoScreen videoScreen;

	private readonly LocalRolePreview testRole = new LocalRolePreview();

	private float testYaw;

	private readonly Dictionary<Material, Material> runtimeMaterials = new Dictionary<Material, Material>();

	private bool materialsReady;

	private int EffectiveRole(BoneMapper mapper)
	{
		return testRole.Resolve(mapper.uniqueSpot, IsLocal(mapper));
	}

	private void CycleTestRole()
	{
		BoneMapper val = ((IEnumerable<BoneMapper>)performers.Values).FirstOrDefault((Func<BoneMapper, bool>)IsLocal);
		BodyReplacementBase val2 = default(BodyReplacementBase);
		if (!((Object)(object)val == (Object)null) && val.currentClip != null && ModelReplacementAPI.GetPlayerModelReplacement(val.playerController, ref val2) && val2 is JajamaruBody jajamaruBody)
		{
			int num = (EffectiveRole(val) + 1) % Roles.Length;
			jajamaruBody.SetDirectPerformance(roleModels[num], directClips[num], val.currentClip.syncPos);
			testRole.Select(num);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Local test role: " + Roles[num] + " (network role unchanged)"));
		}
	}

	private bool IsLocal(BoneMapper mapper)
	{
		if ((Object)(object)mapper != (Object)null && (Object)(object)StartOfRound.Instance != (Object)null)
		{
			return (Object)(object)mapper.playerController == (Object)(object)StartOfRound.Instance.localPlayerController;
		}
		return false;
	}

	private void PrepareMaterials(PlayerControllerB player)
	{
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Expected O, but got Unknown
		//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		if (materialsReady)
		{
			return;
		}
		Material sharedMaterial = ((Renderer)player.thisPlayerModel).sharedMaterial;
		if ((Object)(object)sharedMaterial == (Object)null || (Object)(object)sharedMaterial.shader == (Object)null)
		{
			throw new InvalidDataException("Player material is unavailable.");
		}
		foreach (GameObject item in ((IEnumerable<GameObject>)(object)new GameObject[1] { Character }).Concat(roleProps).Concat(roleModels))
		{
			Renderer[] componentsInChildren = item.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				Material[] sharedMaterials = val.sharedMaterials;
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					Material val2 = sharedMaterials[j];
					if ((Object)(object)val2 == (Object)null)
					{
						continue;
					}
					if (!runtimeMaterials.TryGetValue(val2, out var value))
					{
						value = new Material(sharedMaterial)
						{
							name = "Jajamaru runtime - " + ((Object)val2).name
						};
						string[] array = new string[4] { "_BaseColorMap", "_BaseColor", "_Metallic", "_Smoothness" };
						foreach (string text in array)
						{
							if (val2.HasProperty(text) && value.HasProperty(text))
							{
								if (text == "_BaseColorMap")
								{
									value.SetTexture(text, val2.GetTexture(text));
								}
								else if (text == "_BaseColor")
								{
									value.SetColor(text, val2.GetColor(text));
								}
								else
								{
									value.SetFloat(text, val2.GetFloat(text));
								}
							}
						}
						array = new string[3] { "_NormalMap", "_MaskMap", "_EmissiveColorMap" };
						foreach (string text2 in array)
						{
							if (value.HasProperty(text2))
							{
								value.SetTexture(text2, (Texture)null);
							}
						}
						if (value.HasProperty("_EmissiveColor"))
						{
							value.SetColor("_EmissiveColor", Color.black);
						}
						runtimeMaterials.Add(val2, value);
					}
					sharedMaterials[j] = value;
				}
				val.sharedMaterials = sharedMaterials;
			}
		}
		materialsReady = true;
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Runtime materials: " + runtimeMaterials.Count + " mapped to game shader " + ((Object)sharedMaterial.shader).name));
	}

	private void Awake()
	{
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Expected O, but got Unknown
		//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_03cd: Expected O, but got Unknown
		//IL_0468: Unknown result type (might be due to invalid IL or missing references)
		//IL_0472: Expected O, but got Unknown
		try
		{
			string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "jajamaru_assets");
			bundle = AssetBundle.LoadFromFile(text);
			if ((Object)(object)bundle == (Object)null)
			{
				throw new InvalidDataException("Missing or invalid asset bundle: " + text);
			}
			Character = bundle.LoadAsset<GameObject>("assets/jajamaru/generated/jajamarucharacter.prefab");
			AnimationClip val = ((IEnumerable<AnimationClip>)bundle.LoadAssetWithSubAssets<AnimationClip>("assets/jajamaru/source/idle.fbx")).FirstOrDefault((Func<AnimationClip, bool>)((AnimationClip c) => !((Object)c).name.StartsWith("__")));
			AudioClip val2 = bundle.LoadAsset<AudioClip>("assets/jajamaru/source/sync-test.wav");
			if ((Object)(object)Character == (Object)null || (Object)(object)val == (Object)null || !((Motion)val).isHumanMotion || (Object)(object)val2 == (Object)null)
			{
				throw new InvalidDataException("Bundle lacks humanoid prefab, idle clip or test audio.");
			}
			ModelReplacementAPI.RegisterModelReplacementException(typeof(JajamaruBody));
			CustomEmoteParams val3 = new CustomEmoteParams();
			val3.internalName = "rig_preview";
			val3.displayName = "Jajamaru - Rig Preview";
			val3.primaryAnimationClips = (AnimationClip[])(object)new AnimationClip[1] { val };
			val3.primaryAudioClips = (AudioClip[])(object)new AudioClip[1] { val2 };
			val3.primaryDMCAFreeAudioClips = (AudioClip[])(object)new AudioClip[1] { val2 };
			val3.audioLoops = true;
			val3.syncAnim = true;
			val3.syncAudio = true;
			val3.allowJoining = true;
			val3.stopWhenMove = true;
			val3.thirdPerson = true;
			EmoteImporter.ImportEmote(val3);
			if ((Object)(object)bundle.LoadAsset<AudioClip>("assets/jajamaru/source/band-song.ogg") == (Object)null)
			{
				throw new InvalidDataException("Band song missing");
			}
			AudioClip[] array = Roles.Select((string role) => bundle.LoadAsset<AudioClip>("assets/jajamaru/source/band-stem-" + role + ".wav")).ToArray();
			if (array.Any((AudioClip s) => (Object)(object)s == (Object)null))
			{
				throw new InvalidDataException("Four separated band stems missing; install the matching bundle.");
			}
			stemMixer = new BandStemMixer(array);
			songLength = array[0].length;
			silentClock = AudioClip.Create("Jajamaru silent API clock", array[0].samples, 1, array[0].frequency, false);
			AnimationClip[] primaryAnimationClips = Roles.Select((string role) => bundle.LoadAssetWithSubAssets<AnimationClip>("assets/jajamaru/source/band-" + role + ".fbx").First((AnimationClip c) => !((Object)c).name.StartsWith("__"))).ToArray();
			preview = new LocalBandPreview();
			roleProps = Roles.Select((string role) => bundle.LoadAsset<GameObject>("assets/jajamaru/generated/" + role + "-props.prefab")).ToArray();
			drumstick = bundle.LoadAsset<GameObject>("assets/jajamaru/generated/drumstick.prefab");
			if (roleProps.Any((GameObject p) => (Object)(object)p == (Object)null) || (Object)(object)drumstick == (Object)null)
			{
				throw new InvalidDataException("Band props missing");
			}
			roleModels = Roles.Select((string role) => bundle.LoadAsset<GameObject>("assets/jajamaru/generated/" + role + "-performance.prefab")).ToArray();
			directClips = Roles.Select((string role) => bundle.LoadAssetWithSubAssets<AnimationClip>("assets/jajamaru/source/direct-" + role + ".fbx").First((AnimationClip c) => !((Object)c).name.StartsWith("__"))).ToArray();
			if (roleModels.Any((GameObject m) => (Object)(object)m == (Object)null) || directClips.Any((AnimationClip c) => !c.legacy))
			{
				throw new InvalidDataException("Direct role models or sampleable legacy clips missing; install matching bundle.");
			}
			preview.Initialize(roleModels, directClips);
			GameObject val4 = bundle.LoadAsset<GameObject>("assets/jajamaru/generated/band-screen.prefab");
			if ((Object)(object)val4 == (Object)null)
			{
				throw new InvalidDataException("Screen prefab missing; install matching bundle.");
			}
			videoScreen = new BandVideoScreen(val4, Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "band-video.mp4"));
			val3 = new CustomEmoteParams();
			val3.internalName = "band_performance";
			val3.displayName = "Jajamaru - Band (4 roles)";
			val3.primaryAnimationClips = primaryAnimationClips;
			val3.primaryAudioClips = (AudioClip[])(object)new AudioClip[1] { silentClock };
			val3.audioLoops = false;
			val3.syncAnim = true;
			val3.syncAudio = true;
			val3.allowJoining = true;
			val3.startPref = -2;
			val3.joinPref = -2;
			val3.stopWhenMove = true;
			val3.thirdPerson = true;
			val3.audioLevel = 0f;
			val3.willGetClaimedByDMCA = true;
			EmoteImporter.ImportEmote(val3);
			CustomEmotesAPI.animChanged += new AnimationChanged(OnAnimationChanged);
			subscribed = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Band registered: Singer, Guitar, Bass, Drums in join order. Song + authored performance loops. Multiplayer acceptance pending.");
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Jajamaru preview disabled: " + ex));
			((Behaviour)this).enabled = false;
		}
	}

	private void OnAnimationChanged(string animation, BoneMapper mapper)
	{
		if ((Object)(object)mapper == (Object)null || (Object)(object)mapper.playerController == (Object)null)
		{
			return;
		}
		PlayerControllerB playerController = mapper.playerController;
		try
		{
			if ((animation == "matthias.lethalcompany.jajamaruband__rig_preview" || animation == "matthias.lethalcompany.jajamaruband__band_performance") && !playerController.isPlayerDead)
			{
				if (!previous.ContainsKey(playerController))
				{
					BodyReplacementBase val = default(BodyReplacementBase);
					ModelReplacementAPI.GetPlayerModelReplacement(playerController, ref val);
					previous.Add(playerController, ((Object)(object)val == (Object)null) ? null : ((object)val).GetType());
				}
				PrepareMaterials(playerController);
				ModelReplacementAPI.SetPlayerModelReplacement(playerController, typeof(JajamaruBody));
				BodyReplacementBase val2 = default(BodyReplacementBase);
				ModelReplacementAPI.GetPlayerModelReplacement(playerController, ref val2);
				if (animation == "matthias.lethalcompany.jajamaruband__band_performance")
				{
					if (IsLocal(mapper))
					{
						testRole.Reset();
						testYaw = 0f;
					}
					performers[playerController] = mapper;
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Band performer tracked: localPlayer=" + IsLocal(mapper) + ", apiLocal=" + mapper.local + ", role=" + mapper.uniqueSpot));
					if (mapper.uniqueSpot >= 0 && mapper.uniqueSpot < 4)
					{
						((JajamaruBody)(object)val2).SetDirectPerformance(roleModels[mapper.uniqueSpot], directClips[mapper.uniqueSpot], mapper.currentClip.syncPos);
					}
					else
					{
						((JajamaruBody)(object)val2).SetPerformance(null, null);
					}
				}
				else
				{
					performers.Remove(playerController);
					((JajamaruBody)(object)val2).SetPerformance(null, null);
				}
			}
			else
			{
				if (performers.ContainsKey(playerController))
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Band ended by API event: " + animation));
				}
				Restore(playerController);
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Costume switch failed: " + ex));
			Restore(playerController);
		}
	}

	private void Update()
	{
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Invalid comparison between Unknown and I4
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		Keyboard current = Keyboard.current;
		BoneMapper val = ((IEnumerable<BoneMapper>)performers.Values).FirstOrDefault((Func<BoneMapper, bool>)IsLocal);
		if ((Object)(object)val != (Object)null && !val.playerController.isTypingChat && !val.playerController.inTerminalMenu && (int)Cursor.lockState == 1)
		{
			if (current != null && ((ButtonControl)current.f10Key).wasPressedThisFrame)
			{
				CycleTestRole();
			}
			if (current != null && (((ButtonControl)current.leftAltKey).isPressed || ((ButtonControl)current.rightAltKey).isPressed))
			{
				Mouse current2 = Mouse.current;
				if (current2 != null)
				{
					testYaw = Mathf.Repeat(testYaw + ((InputControl<Vector2>)(object)((Pointer)current2).delta).ReadValue().x * 0.2f, 360f);
				}
			}
		}
		BodyReplacementBase val2 = default(BodyReplacementBase);
		if ((Object)(object)val != (Object)null && ModelReplacementAPI.GetPlayerModelReplacement(val.playerController, ref val2) && val2 is JajamaruBody jajamaruBody)
		{
			jajamaruBody.TestYaw = testYaw;
		}
		if (preview != null)
		{
			Keyboard current3 = Keyboard.current;
			if (current3 != null && ((ButtonControl)current3.f9Key).wasPressedThisFrame)
			{
				if (performers.Values.Any(IsLocal))
				{
					preview.Toggle();
					((BaseUnityPlugin)this).Logger.LogInfo((object)("F9 local test band enabled=" + preview.Enabled));
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)"F9 received: start the Jajamaru band emote first.");
				}
			}
		}
		BoneMapper[] array = performers.Values.ToArray();
		foreach (BoneMapper val3 in array)
		{
			if (IsLocal(val3) && (val3.uniqueSpot < 0 || val3.currentClip == null || CustomAnimationClip.syncTimer[val3.currentClip.syncPos] >= songLength))
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Band stop requested by plugin: role=" + val3.uniqueSpot + ", clip=" + (val3.currentClip != null) + ", time=" + ((val3.currentClip == null) ? (-1f) : CustomAnimationClip.syncTimer[val3.currentClip.syncPos]) + ", songLength=" + songLength));
				CustomEmotesAPI.PlayAnimation("none", -2);
			}
		}
		PlayerControllerB[] array2 = previous.Keys.ToArray();
		foreach (PlayerControllerB val4 in array2)
		{
			if ((Object)(object)val4 == (Object)null || val4.isPlayerDead || !val4.isPlayerControlled)
			{
				Restore(val4);
			}
		}
		UpdateBandAudio();
	}

	private void UpdateBandAudio()
	{
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
		if (stemMixer == null)
		{
			return;
		}
		BoneMapper[] array = performers.Values.Where((BoneMapper m) => (Object)(object)m != (Object)null && (Object)(object)m.playerController != (Object)null && m.currentClip != null && m.uniqueSpot >= 0 && m.uniqueSpot < 4).ToArray();
		if (array.Length == 0)
		{
			stemMixer.Stop();
			videoScreen?.Stop();
			return;
		}
		BoneMapper val = array[0];
		int sync = val.currentClip.syncPos;
		BoneMapper val2 = ((IEnumerable<BoneMapper>)array).FirstOrDefault((Func<BoneMapper, bool>)((BoneMapper m) => m.uniqueSpot == 0)) ?? val;
		try
		{
			videoScreen?.Tick(sync, CustomAnimationClip.syncTimer[sync], ((Component)val2.playerController).transform, ((Renderer)val2.playerController.thisPlayerModel).sharedMaterial);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Screen disabled; band continues: " + ex));
			videoScreen?.Dispose();
			videoScreen = null;
		}
		int mask = BandAudioPlan.RoleMask(array.Where((BoneMapper m) => m.currentClip.syncPos == sync).Select(EffectiveRole), preview != null && preview.Enabled && array.Any(IsLocal));
		float volume = (((int)Settings.DMCAFree.Value == 0) ? (Settings.EmotesVolume.Value / 100f) : 0f);
		stemMixer.Tick(sync, CustomAnimationClip.syncTimer[sync], mask, ((Component)val.playerController).transform.position, volume, Time.unscaledDeltaTime);
	}

	private void LateUpdate()
	{
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		if (preview == null)
		{
			return;
		}
		BoneMapper val = ((IEnumerable<BoneMapper>)performers.Values).FirstOrDefault((Func<BoneMapper, bool>)IsLocal);
		if ((Object)(object)val == (Object)null || val.currentClip == null)
		{
			preview.Stop();
			return;
		}
		try
		{
			BodyReplacementBase val2 = default(BodyReplacementBase);
			ModelReplacementAPI.GetPlayerModelReplacement(val.playerController, ref val2);
			preview.Tick(((Component)val.playerController).transform, CustomAnimationClip.syncTimer[val.currentClip.syncPos], performers.Values.Where((BoneMapper m) => (Object)(object)m != (Object)null).Select(EffectiveRole), ((Object)(object)val2 != (Object)null && (Object)(object)val2.replacementModel != (Object)null) ? val2.replacementModel.transform.lossyScale : Vector3.one);
		}
		catch (Exception ex)
		{
			preview.Stop();
			((BaseUnityPlugin)this).Logger.LogError((object)("Local band preview stopped: " + ex));
		}
	}

	private void OnGUI()
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
		if (preview == null || !performers.Values.Any(IsLocal))
		{
			return;
		}
		GUI.Box(new Rect(12f, 12f, 370f, 155f), "Local test: F9 band | F10 next instrument");
		GUI.Label(new Rect(24f, 124f, 346f, 30f), "Hold Alt + move mouse: rotate model");
		BoneMapper mapper = ((IEnumerable<BoneMapper>)performers.Values).FirstOrDefault((Func<BoneMapper, bool>)IsLocal);
		if (EffectiveRole(mapper) >= 0 && EffectiveRole(mapper) < Roles.Length)
		{
			if (GUI.Button(new Rect(24f, 86f, 346f, 34f), "F10: Next role (" + Roles[EffectiveRole(mapper)] + ")"))
			{
				CycleTestRole();
			}
			if (GUI.Button(new Rect(24f, 43f, 306f, 40f), preview.Enabled ? "Remove test band" : "Fill empty roles with test band"))
			{
				preview.Toggle();
			}
		}
	}

	private void Restore(PlayerControllerB player)
	{
		if (!previous.TryGetValue(player, out var value))
		{
			return;
		}
		if (performers.TryGetValue(player, out var value2) && IsLocal(value2))
		{
			testRole.Reset();
			testYaw = 0f;
			preview?.Stop();
		}
		performers.Remove(player);
		previous.Remove(player);
		if ((Object)(object)player == (Object)null)
		{
			return;
		}
		try
		{
			BodyReplacementBase val = default(BodyReplacementBase);
			if (ModelReplacementAPI.GetPlayerModelReplacement(player, ref val) && val is JajamaruBody)
			{
				if (value == null)
				{
					ModelReplacementAPI.RemovePlayerModelReplacement(player);
				}
				else
				{
					ModelReplacementAPI.SetPlayerModelReplacement(player, value);
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Costume restore failed: " + ex));
		}
	}

	private void OnDisable()
	{
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Expected O, but got Unknown
		preview?.Stop();
		stemMixer?.Stop();
		videoScreen?.Stop();
		if (performers.Values.Any(IsLocal))
		{
			CustomEmotesAPI.PlayAnimation("none", -2);
		}
		if (subscribed)
		{
			CustomEmotesAPI.animChanged -= new AnimationChanged(OnAnimationChanged);
		}
		subscribed = false;
		PlayerControllerB[] array = previous.Keys.ToArray();
		foreach (PlayerControllerB player in array)
		{
			Restore(player);
		}
	}

	private void OnDestroy()
	{
		OnDisable();
		stemMixer?.Dispose();
		videoScreen?.Dispose();
		if ((Object)(object)silentClock != (Object)null)
		{
			Object.Destroy((Object)(object)silentClock);
		}
		if ((Object)(object)bundle != (Object)null)
		{
			bundle.Unload(false);
		}
	}
}
public sealed class JajamaruBody : BodyReplacementBase
{
	private sealed class FingerTip
	{
		public Transform middle;

		public Transform tip;

		public Quaternion middleBind;

		public Quaternion tipBind;
	}

	private GameObject directModel;

	private AnimationClip directClip;

	private int directSync;

	private Vector3 directScale;

	private int visibilityFrames;

	internal float TestYaw;

	private GameObject props;

	private bool performing;

	private readonly List<FingerTip> tips = new List<FingerTip>();

	public void SetDirectPerformance(GameObject prefab, AnimationClip clip, int sync)
	{
		//IL_003c: 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_0078: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)directModel != (Object)null)
		{
			Object.Destroy((Object)(object)directModel);
		}
		directModel = Object.Instantiate<GameObject>(prefab, base.replacementModel.transform, false);
		directModel.transform.localScale = Vector3.one;
		directClip = clip;
		directSync = sync;
		visibilityFrames = 0;
		directScale = prefab.transform.localScale;
		directModel.transform.localScale = directScale;
		DirectPerformance.PlaceAtPlayer(directModel, ((Component)((BodyReplacementBase)this).controller).transform);
		DirectPerformance.Prepare(directModel);
	}

	protected override GameObject LoadAssetsAndReturnModel()
	{
		return Plugin.Character;
	}

	public void SetPerformance(GameObject prefab, GameObject stick)
	{
		//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_030b: Unknown result type (might be due to invalid IL or missing references)
		//IL_01da: Unknown result type (might be due to invalid IL or missing references)
		//IL_01df: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0203: Unknown result type (might be due to invalid IL or missing references)
		//IL_0207: Unknown result type (might be due to invalid IL or missing references)
		//IL_0212: Unknown result type (might be due to invalid IL or missing references)
		//IL_024d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0254: Unknown result type (might be due to invalid IL or missing references)
		//IL_0259: Unknown result type (might be due to invalid IL or missing references)
		//IL_0261: Unknown result type (might be due to invalid IL or missing references)
		//IL_0268: Unknown result type (might be due to invalid IL or missing references)
		//IL_026d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)directModel != (Object)null)
		{
			Object.Destroy((Object)(object)directModel);
			directModel = null;
		}
		if ((Object)(object)base.replacementModel != (Object)null)
		{
			SkinnedMeshRenderer[] componentsInChildren = base.replacementModel.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				((Renderer)componentsInChildren[i]).forceRenderingOff = false;
			}
		}
		if ((Object)(object)props != (Object)null)
		{
			Object.Destroy((Object)(object)props);
		}
		performing = (Object)(object)prefab != (Object)null;
		GameObject[] array = (GameObject[])(object)new GameObject[2] { base.replacementModel, base.replacementModelShadow };
		foreach (GameObject val in array)
		{
			if (!((Object)(object)val != (Object)null))
			{
				continue;
			}
			SkinnedMeshRenderer[] componentsInChildren = val.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			foreach (SkinnedMeshRenderer val2 in componentsInChildren)
			{
				if (((Object)val2).name.StartsWith("PerformanceStick"))
				{
					((Component)val2).gameObject.SetActive((Object)(object)stick != (Object)null && performing);
				}
			}
		}
		if (tips.Count == 0 && performing)
		{
			Animator componentInChildren = Plugin.Character.GetComponentInChildren<Animator>();
			array = (GameObject[])(object)new GameObject[2] { base.replacementModel, base.replacementModelShadow };
			foreach (GameObject val3 in array)
			{
				if ((Object)(object)val3 == (Object)null)
				{
					continue;
				}
				Animator componentInChildren2 = val3.GetComponentInChildren<Animator>();
				string[] array2 = new string[2] { "Left", "Right" };
				foreach (string text in array2)
				{
					string[] array3 = new string[4] { "Index", "Middle", "Ring", "Little" };
					foreach (string text2 in array3)
					{
						HumanBodyBones val4 = (HumanBodyBones)Enum.Parse(typeof(HumanBodyBones), text + text2 + "Intermediate");
						HumanBodyBones val5 = (HumanBodyBones)Enum.Parse(typeof(HumanBodyBones), text + text2 + "Distal");
						Transform boneTransform = componentInChildren2.GetBoneTransform(val4);
						Transform boneTransform2 = componentInChildren2.GetBoneTransform(val5);
						if ((Object)(object)boneTransform != (Object)null && (Object)(object)boneTransform2 != (Object)null)
						{
							tips.Add(new FingerTip
							{
								middle = boneTransform,
								tip = boneTransform2,
								middleBind = componentInChildren.GetBoneTransform(val4).localRotation,
								tipBind = componentInChildren.GetBoneTransform(val5).localRotation
							});
						}
					}
				}
			}
		}
		if (!((Object)(object)prefab == (Object)null) && !((Object)(object)base.replacementModel == (Object)null))
		{
			props = Object.Instantiate<GameObject>(prefab, base.replacementModel.transform, false);
			props.transform.localPosition = Vector3.zero;
			props.transform.localRotation = Quaternion.identity;
			props.transform.localScale = Vector3.one;
			MatchPropVisibility();
		}
	}

	private void MatchPropVisibility()
	{
		if ((Object)(object)props == (Object)null || (Object)(object)base.replacementModel == (Object)null)
		{
			return;
		}
		SkinnedMeshRenderer componentInChildren = base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>();
		if (!((Object)(object)componentInChildren == (Object)null))
		{
			Renderer[] componentsInChildren = props.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer obj in componentsInChildren)
			{
				((Component)obj).gameObject.layer = ((Component)componentInChildren).gameObject.layer;
				obj.renderingLayerMask = ((Renderer)componentInChildren).renderingLayerMask;
				obj.enabled = ((Renderer)componentInChildren).enabled;
			}
		}
	}

	public override void LateUpdate()
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0304: Unknown result type (might be due to invalid IL or missing references)
		//IL_0309: Unknown result type (might be due to invalid IL or missing references)
		//IL_0315: Unknown result type (might be due to invalid IL or missing references)
		//IL_031a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0324: Unknown result type (might be due to invalid IL or missing references)
		//IL_0329: Unknown result type (might be due to invalid IL or missing references)
		//IL_0232: Unknown result type (might be due to invalid IL or missing references)
		//IL_0237: Unknown result type (might be due to invalid IL or missing references)
		//IL_025e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0263: Unknown result type (might be due to invalid IL or missing references)
		//IL_028a: Unknown result type (might be due to invalid IL or missing references)
		//IL_028f: Unknown result type (might be due to invalid IL or missing references)
		((BodyReplacementBase)this).LateUpdate();
		if ((Object)(object)directModel != (Object)null)
		{
			DirectPerformance.Sample(directModel, directClip, CustomAnimationClip.syncTimer[directSync]);
			directModel.transform.localScale = directScale;
			DirectPerformance.PlaceAtPlayer(directModel, ((Component)((BodyReplacementBase)this).controller).transform);
			Transform transform = directModel.transform;
			transform.rotation *= Quaternion.Euler(0f, TestYaw, 0f);
			SkinnedMeshRenderer val = base.replacementModel.GetComponentsInChildren<SkinnedMeshRenderer>().First((SkinnedMeshRenderer r) => !((Component)r).transform.IsChildOf(directModel.transform));
			Renderer[] componentsInChildren = directModel.GetComponentsInChildren<Renderer>();
			foreach (Renderer obj in componentsInChildren)
			{
				obj.enabled = true;
				obj.forceRenderingOff = false;
				((Component)obj).gameObject.layer = ((Component)val).gameObject.layer;
				obj.renderingLayerMask = ((Renderer)val).renderingLayerMask;
				obj.shadowCastingMode = ((Renderer)val).shadowCastingMode;
				SkinnedMeshRenderer val2 = (SkinnedMeshRenderer)(object)((obj is SkinnedMeshRenderer) ? obj : null);
				if (val2 != null)
				{
					val2.updateWhenOffscreen = true;
				}
			}
			SkinnedMeshRenderer[] componentsInChildren2 = base.replacementModel.GetComponentsInChildren<SkinnedMeshRenderer>();
			foreach (SkinnedMeshRenderer val3 in componentsInChildren2)
			{
				if (!((Component)val3).transform.IsChildOf(directModel.transform))
				{
					((Renderer)val3).forceRenderingOff = true;
				}
			}
			if (++visibilityFrames == 60)
			{
				Camera gameplayCamera = ((BodyReplacementBase)this).controller.gameplayCamera;
				Debug.Log((object)("Jajamaru visibility: sourceEnabled=" + ((Renderer)val).enabled + ", layer=" + ((Component)val).gameObject.layer + ", cameraIncludesLayer=" + ((Object)(object)gameplayCamera != (Object)null && (gameplayCamera.cullingMask & (1 << ((Component)val).gameObject.layer)) != 0) + ", active=" + directModel.activeInHierarchy + ", worldScale=" + ((object)directModel.transform.lossyScale/*cast due to .constrained prefix*/).ToString() + ", position=" + ((object)directModel.transform.position/*cast due to .constrained prefix*/).ToString() + ", player=" + ((object)((Component)((BodyReplacementBase)this).controller).transform.position/*cast due to .constrained prefix*/).ToString()));
			}
			return;
		}
		MatchPropVisibility();
		if (!performing)
		{
			return;
		}
		foreach (FingerTip tip in tips)
		{
			if ((Object)(object)tip.middle != (Object)null && (Object)(object)tip.tip != (Object)null)
			{
				tip.tip.localRotation = tip.tipBind * Quaternion.Slerp(Quaternion.identity, Quaternion.Inverse(tip.middleBind) * tip.middle.localRotation, 58f / 95f);
			}
		}
	}
}
public sealed class BandVideoScreen : IDisposable
{
	private readonly GameObject prefab;

	private readonly string path;

	private GameObject root;

	private VideoPlayer player;

	private RenderTexture texture;

	private Material frame;

	private Material display;

	private int session = -1;

	private double seekStarted;

	private double prepareStarted;

	private double nextSeek;

	private bool seeking;

	private bool failed;

	private bool warned;

	public BandVideoScreen(GameObject prefab, string path)
	{
		this.prefab = prefab;
		this.path = path;
	}

	public void Tick(int sync, double time, Transform singer, Material native)
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Expected O, but got Unknown
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Expected O, but got Unknown
		//IL_015a: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0202: Expected O, but got Unknown
		//IL_0129: Unknown result type (might be due to invalid IL or missing references)
		//IL_037d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0387: Expected O, but got Unknown
		//IL_0394: Unknown result type (might be due to invalid IL or missing references)
		//IL_039e: Expected O, but got Unknown
		//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
		if (session != sync || (Object)(object)root == (Object)null)
		{
			Stop();
			session = sync;
			root = Object.Instantiate<GameObject>(prefab);
			root.transform.SetPositionAndRotation(singer.position - singer.forward * 2.5f, singer.rotation);
			frame = new Material(native);
			display = new Material(native);
			Material[] array = (Material[])(object)new Material[2] { frame, display };
			foreach (Material val in array)
			{
				string[] array2 = new string[4] { "_BaseColorMap", "_NormalMap", "_MaskMap", "_EmissiveColorMap" };
				foreach (string text in array2)
				{
					if (val.HasProperty(text))
					{
						val.SetTexture(text, (Texture)null);
					}
				}
				if (val.HasProperty("_Smoothness"))
				{
					val.SetFloat("_Smoothness", 0.15f);
				}
				if (val.HasProperty("_EmissiveColor"))
				{
					val.SetColor("_EmissiveColor", Color.black);
				}
			}
			frame.SetColor("_BaseColor", new Color(0.045f, 0.055f, 0.06f));
			display.SetColor("_BaseColor", Color.white);
			Renderer[] componentsInChildren = root.GetComponentsInChildren<Renderer>();
			foreach (Renderer obj in componentsInChildren)
			{
				obj.sharedMaterial = ((((Object)obj).name == "Video Surface") ? display : frame);
			}
			if (!File.Exists(path))
			{
				if (!warned)
				{
					Debug.LogWarning((object)"Jajamaru screen: band-video.mp4 missing; screen has no video.");
					warned = true;
				}
				failed = true;
				return;
			}
			texture = new RenderTexture(1280, 720, 0);
			texture.Create();
			display.SetTexture("_BaseColorMap", (Texture)(object)texture);
			if (display.HasProperty("_EmissiveExposureWeight"))
			{
				display.SetFloat("_EmissiveExposureWeight", 0f);
			}
			if (display.HasProperty("_CullMode"))
			{
				display.SetFloat("_CullMode", 0f);
			}
			if (display.HasProperty("_CullModeForward"))
			{
				display.SetFloat("_CullModeForward", 0f);
			}
			if (display.HasProperty("_EmissiveColorMap"))
			{
				display.SetTexture("_EmissiveColorMap", (Texture)(object)texture);
				display.SetColor("_EmissiveColor", Color.white);
				display.EnableKeyword("_EMISSIVE_COLOR_MAP");
			}
			player = root.AddComponent<VideoPlayer>();
			player.playOnAwake = false;
			player.source = (VideoSource)1;
			player.url = new Uri(Path.GetFullPath(path)).AbsoluteUri;
			player.renderMode = (VideoRenderMode)2;
			player.targetTexture = texture;
			player.audioOutputMode = (VideoAudioOutputMode)0;
			player.isLooping = false;
			player.waitForFirstFrame = true;
			player.errorReceived += new ErrorEventHandler(OnError);
			player.seekCompleted += new EventHandler(OnSeek);
			prepareStarted = Time.realtimeSinceStartupAsDouble;
			player.Prepare();
		}
		if (failed || (Object)(object)player == (Object)null)
		{
			return;
		}
		if (!player.isPrepared)
		{
			if (Time.realtimeSinceStartupAsDouble - prepareStarted > 20.0)
			{
				OnError(player, "Preparation timeout");
			}
			return;
		}
		if (time >= player.length)
		{
			player.Pause();
			return;
		}
		if (seeking)
		{
			if (Time.realtimeSinceStartupAsDouble - seekStarted > 5.0)
			{
				OnError(player, "Seek timeout");
			}
			return;
		}
		if (player.canSetTime && Time.realtimeSinceStartupAsDouble >= nextSeek && Math.Abs(player.time - time) > 0.25)
		{
			seeking = true;
			seekStarted = Time.realtimeSinceStartupAsDouble;
			nextSeek = seekStarted + 1.0;
			player.time = Math.Max(0.0, time);
		}
		if (!player.isPlaying)
		{
			player.Play();
		}
	}

	private void OnSeek(VideoPlayer source)
	{
		seeking = false;
	}

	private void OnError(VideoPlayer source, string message)
	{
		if (!failed)
		{
			Debug.LogWarning((object)("Jajamaru screen video stopped: " + message));
		}
		failed = true;
		source.Stop();
	}

	public void Stop()
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Expected O, but got Unknown
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Expected O, but got Unknown
		if ((Object)(object)player != (Object)null)
		{
			player.errorReceived -= new ErrorEventHandler(OnError);
			player.seekCompleted -= new EventHandler(OnSeek);
			player.Stop();
		}
		if ((Object)(object)root != (Object)null)
		{
			Object.Destroy((Object)(object)root);
		}
		if ((Object)(object)texture != (Object)null)
		{
			texture.Release();
			Object.Destroy((Object)(object)texture);
		}
		if ((Object)(object)frame != (Object)null)
		{
			Object.Destroy((Object)(object)frame);
		}
		if ((Object)(object)display != (Object)null)
		{
			Object.Destroy((Object)(object)display);
		}
		root = null;
		player = null;
		texture = null;
		frame = null;
		display = null;
		session = -1;
		seeking = false;
		failed = false;
		nextSeek = 0.0;
	}

	public void Dispose()
	{
		Stop();
	}
}
public static class DirectPerformance
{
	public static void PlaceAtPlayer(GameObject model, Transform player)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		model.transform.SetPositionAndRotation(player.position, player.rotation);
	}

	public static void Prepare(GameObject model)
	{
		Animator[] componentsInChildren = model.GetComponentsInChildren<Animator>(true);
		for (int i = 0; i < componentsInChildren.Length; i++)
		{
			((Behaviour)componentsInChildren[i]).enabled = false;
		}
		Animation[] componentsInChildren2 = model.GetComponentsInChildren<Animation>(true);
		for (int i = 0; i < componentsInChildren2.Length; i++)
		{
			((Behaviour)componentsInChildren2[i]).enabled = false;
		}
	}

	public static void Sample(GameObject model, AnimationClip clip, float time)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		Transform transform = model.transform;
		Vector3 localPosition = transform.localPosition;
		Quaternion localRotation = transform.localRotation;
		Vector3 localScale = transform.localScale;
		clip.SampleAnimation(model, Mathf.Repeat(time, clip.length));
		transform.localPosition = localPosition;
		transform.localRotation = localRotation;
		transform.localScale = localScale;
	}
}
public static class BandAudioPlan
{
	public static int RoleMask(IEnumerable<int> roles, bool preview)
	{
		int num = 0;
		foreach (int role in roles)
		{
			if (role >= 0 && role < 4)
			{
				num |= 1 << role;
			}
		}
		if (!preview || num == 0)
		{
			return num;
		}
		return 15;
	}

	public static int Sample(double seconds, int rate, int samples)
	{
		if (double.IsNaN(seconds) || double.IsInfinity(seconds) || seconds < 0.0 || seconds >= (double)samples / (double)rate)
		{
			return -1;
		}
		return Math.Min(samples - 1, (int)(seconds * (double)rate));
	}
}
public sealed class BandStemMixer : IDisposable
{
	private GameObject root;

	private readonly AudioClip[] clips;

	private bool disposed;

	private readonly AudioSource[] sources = (AudioSource[])(object)new AudioSource[4];

	private readonly int rate;

	private readonly int samples;

	private int session = -1;

	private double scheduledAt;

	private double nextCheck;

	private float lastTime;

	public BandStemMixer(AudioClip[] clips)
	{
		if (clips.Length != 4)
		{
			throw new ArgumentException("Four role stems required");
		}
		rate = clips[0].frequency;
		samples = clips[0].samples;
		foreach (AudioClip val in clips)
		{
			if (val.frequency != rate || val.samples != samples)
			{
				throw new ArgumentException("Stem sample counts must match");
			}
		}
		this.clips = (AudioClip[])clips.Clone();
	}

	private void EnsureSources()
	{
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Expected O, but got Unknown
		bool flag = (Object)(object)root != (Object)null;
		AudioSource[] array = sources;
		foreach (AudioSource val in array)
		{
			flag &= (Object)(object)val != (Object)null;
		}
		if (!flag)
		{
			Debug.Log((object)("Jajamaru audio: creating four live sources (root missing=" + ((Object)(object)root == (Object)null) + ")."));
			Stop();
			if ((Object)(object)root != (Object)null)
			{
				Object.Destroy((Object)(object)root);
			}
			root = new GameObject("Jajamaru synchronized stems");
			Object.DontDestroyOnLoad((Object)(object)root);
			for (int j = 0; j < 4; j++)
			{
				AudioSource val2 = root.AddComponent<AudioSource>();
				sources[j] = val2;
				val2.playOnAwake = false;
				val2.clip = clips[j];
				val2.loop = false;
				val2.volume = 0f;
				val2.spatialBlend = 1f;
				val2.dopplerLevel = 0f;
				val2.minDistance = 5f;
				val2.maxDistance = 30f;
				val2.rolloffMode = (AudioRolloffMode)1;
				val2.priority = 64;
			}
		}
	}

	public void Tick(int sync, float time, int mask, Vector3 position, float volume, float delta)
	{
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		if (disposed)
		{
			return;
		}
		int num = BandAudioPlan.Sample(time, rate, samples);
		if (mask == 0 || num < 0)
		{
			Stop();
			return;
		}
		EnsureSources();
		root.transform.position = position;
		double dspTime = AudioSettings.dspTime;
		if (session != sync || time < lastTime - 0.25f)
		{
			Stop();
			session = sync;
			scheduledAt = dspTime + 0.08;
			nextCheck = scheduledAt + 0.05;
			int timeSamples = Math.Min(samples - 1, num + (int)(0.08 * (double)rate));
			AudioSource[] array = sources;
			foreach (AudioSource obj in array)
			{
				obj.timeSamples = timeSamples;
				obj.PlayScheduled(scheduledAt);
			}
			Debug.Log((object)("Jajamaru audio: scheduled at song=" + time + ", roles=" + mask + ", volume=" + volume));
		}
		lastTime = time;
		if (dspTime >= nextCheck)
		{
			if ((double)Math.Abs(sources[0].timeSamples - num) > (double)rate * 0.075)
			{
				AudioSource[] array = sources;
				for (int i = 0; i < array.Length; i++)
				{
					array[i].timeSamples = num;
				}
			}
			nextCheck = dspTime + 0.25;
		}
		for (int j = 0; j < 4; j++)
		{
			sources[j].volume = Mathf.MoveTowards(sources[j].volume, ((mask & (1 << j)) != 0) ? Mathf.Clamp01(volume) : 0f, Mathf.Max(0f, delta) * 6f);
		}
	}

	public void Stop()
	{
		AudioSource[] array = sources;
		foreach (AudioSource val in array)
		{
			if ((Object)(object)val != (Object)null)
			{
				val.Stop();
				val.volume = 0f;
			}
		}
		session = -1;
		lastTime = 0f;
	}

	public void Dispose()
	{
		if (!disposed)
		{
			disposed = true;
			Stop();
			if ((Object)(object)root != (Object)null)
			{
				Object.Destroy((Object)(object)root);
			}
		}
	}
}