Decompiled source of MAPortableRadio v0.3.0

BepInEx/plugins/MAPortableRadio/MAPortableRadio.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Photon.Pun;
using Photon.Realtime;
using REPOLib.Modules;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace MAPortableRadio;

[BepInPlugin("ma.repo.portableradio", "MA Portable Radio", "0.3.0")]
[BepInDependency("REPOLib", "4.5.1")]
public sealed class Plugin : BaseUnityPlugin
{
	public const string Id = "ma.repo.portableradio";

	public const string Version = "0.3.0";

	private Harmony harmony;

	internal static Plugin Instance { get; private set; }

	internal static ConfigEntry<int> Price { get; private set; }

	internal static ConfigEntry<int> Volume { get; private set; }

	private void Awake()
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		Instance = this;
		Price = ((BaseUnityPlugin)this).Config.Bind<int>("Radio", "Base price", 6000, new ConfigDescription("The shop's usual price modifiers still apply.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1000, 100000), new object[0]));
		Volume = ((BaseUnityPlugin)this).Config.Bind<int>("Radio", "Starting volume", 3, new ConfigDescription("Starting volume for newly spawned radios.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), new object[0]));
		harmony = new Harmony("ma.repo.portableradio");
		harmony.PatchAll(typeof(RadioItem));
		harmony.PatchAll(typeof(RadioInput.ToggleHeldRadio));
		harmony.PatchAll(typeof(RadioInput.SkipVolumeGrab));
		harmony.PatchAll(typeof(RadioPlayback.ChangeTrackOnImpact));
		((MonoBehaviour)this).StartCoroutine(RadioMusic.Load());
	}

	private void Update()
	{
		RadioInput.Update();
	}

	internal void LogInfo(string message)
	{
		((BaseUnityPlugin)this).Logger.LogInfo((object)message);
	}

	internal void LogDebug(string message)
	{
		((BaseUnityPlugin)this).Logger.LogDebug((object)message);
	}

	internal void LogWarning(string message)
	{
		((BaseUnityPlugin)this).Logger.LogWarning((object)message);
	}

	private void OnDestroy()
	{
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
	}
}
internal static class RadioCartSlot
{
	internal static bool TryGet(PhysGrabCart cart, Vector3 radioPosition, float radioHalfWidth, float radioHalfDepth, out Vector3 point, out Quaternion rotation)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: 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_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: 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_00d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: 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)
		//IL_0100: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_017a: Unknown result type (might be due to invalid IL or missing references)
		//IL_017f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0184: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0201: Unknown result type (might be due to invalid IL or missing references)
		//IL_0314: Unknown result type (might be due to invalid IL or missing references)
		//IL_0316: Unknown result type (might be due to invalid IL or missing references)
		//IL_031d: Unknown result type (might be due to invalid IL or missing references)
		//IL_032d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0332: Unknown result type (might be due to invalid IL or missing references)
		//IL_0337: Unknown result type (might be due to invalid IL or missing references)
		//IL_033c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0340: Unknown result type (might be due to invalid IL or missing references)
		//IL_0343: Unknown result type (might be due to invalid IL or missing references)
		//IL_0348: Unknown result type (might be due to invalid IL or missing references)
		//IL_034f: Unknown result type (might be due to invalid IL or missing references)
		//IL_022f: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0240: Unknown result type (might be due to invalid IL or missing references)
		//IL_0245: Unknown result type (might be due to invalid IL or missing references)
		//IL_0249: Unknown result type (might be due to invalid IL or missing references)
		//IL_0253: Unknown result type (might be due to invalid IL or missing references)
		//IL_0258: Unknown result type (might be due to invalid IL or missing references)
		//IL_025c: 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)
		//IL_027e: 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)
		//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_03bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_03de: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_03fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0374: Unknown result type (might be due to invalid IL or missing references)
		//IL_038f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0394: Unknown result type (might be due to invalid IL or missing references)
		point = Vector3.zero;
		rotation = Quaternion.identity;
		Transform transform = ((Component)cart).transform;
		Transform val = transform.Find("In Cart");
		if (!Object.op_Implicit((Object)(object)val))
		{
			return false;
		}
		Vector3 val2 = transform.InverseTransformPoint(val.position);
		Vector3 val3 = val.localScale * 0.5f;
		Vector3 val4 = transform.TransformVector(Vector3.right);
		float magnitude = ((Vector3)(ref val4)).magnitude;
		Vector3 val5 = transform.TransformVector(Vector3.forward);
		float magnitude2 = ((Vector3)(ref val5)).magnitude;
		if (magnitude < 0.001f || magnitude2 < 0.001f)
		{
			return false;
		}
		Transform cartGrabPoint = cart.cartGrabPoint;
		float num = ((Object.op_Implicit((Object)(object)cartGrabPoint) && transform.InverseTransformPoint(cartGrabPoint.position).z > val2.z + 0.15f) ? (-1f) : 1f);
		Vector3 val6 = transform.InverseTransformVector(val.right * val3.x);
		Vector3 val7 = transform.InverseTransformVector(val.up * val3.y);
		Vector3 val8 = transform.InverseTransformVector(val.forward * val3.z);
		float num2 = Mathf.Abs(val6.x) + Mathf.Abs(val7.x) + Mathf.Abs(val8.x);
		float num3 = num * (transform.InverseTransformPoint(radioPosition).x - val2.x);
		if (!(num3 < Mathf.Max(0.05f, num2 * 0.45f)))
		{
			Vector3 val9 = radioPosition - val.position;
			if (!(((Vector3)(ref val9)).sqrMagnitude > 4f))
			{
				float num4 = Mathf.Abs(val6.z) + Mathf.Abs(val7.z) + Mathf.Abs(val8.z);
				float num5 = (radioHalfWidth + 0.05f) / magnitude2;
				float num6 = Mathf.Min(num4 * 0.55f, Mathf.Max(0f, num4 - num5));
				Vector3 val10 = val2 - Vector3.forward * num * num6;
				BoxCollider[] componentsInChildren = ((Component)cart).GetComponentsInChildren<BoxCollider>();
				float num7 = num2;
				BoxCollider[] array = componentsInChildren;
				foreach (BoxCollider val11 in array)
				{
					if (IsWall(val11))
					{
						Matrix4x4 val12 = transform.worldToLocalMatrix * ((Component)val11).transform.localToWorldMatrix;
						Vector3 val13 = val11.size * 0.5f;
						float num8 = Mathf.Abs(((Matrix4x4)(ref val12)).MultiplyVector(Vector3.right * val13.x).x) + Mathf.Abs(((Matrix4x4)(ref val12)).MultiplyVector(Vector3.up * val13.y).x) + Mathf.Abs(((Matrix4x4)(ref val12)).MultiplyVector(Vector3.forward * val13.z).x);
						num7 = Mathf.Max(num7, num * (((Matrix4x4)(ref val12)).MultiplyPoint3x4(val11.center).x - val2.x) + num8);
					}
				}
				float num9 = (num7 - num2) * magnitude + 0.55f;
				Vector3 val14 = transform.TransformPoint(val10 + Vector3.right * num * (num7 + 0.25f / magnitude));
				Ray val15 = default(Ray);
				((Ray)(ref val15))..ctor(val14, -transform.right * num);
				BoxCollider[] array2 = componentsInChildren;
				RaycastHit val17 = default(RaycastHit);
				foreach (BoxCollider val16 in array2)
				{
					if (IsWall(val16) && ((Collider)val16).Raycast(val15, ref val17, num9))
					{
						num9 = ((RaycastHit)(ref val17)).distance;
						num7 = num * (transform.InverseTransformPoint(((RaycastHit)(ref val17)).point).x - val2.x);
					}
				}
				point = val10 + Vector3.right * num * (num7 + (0.008f + radioHalfDepth) / magnitude);
				rotation = Quaternion.Euler(0f, num * 90f, 0f);
				return true;
			}
		}
		return false;
	}

	private static bool IsWall(BoxCollider box)
	{
		Transform parent = ((Component)box).transform.parent;
		if (((Collider)box).enabled && !((Collider)box).isTrigger && Object.op_Implicit((Object)(object)parent))
		{
			return ((Object)parent).name.Contains("Cart Wall Collider");
		}
		return false;
	}
}
[DefaultExecutionOrder(100)]
internal sealed class RadioGlow : MonoBehaviour
{
	private static Sprite haloSprite;

	private SpriteRenderer halo;

	private BoxCollider body;

	private void Awake()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Expected O, but got Unknown
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		body = ((Component)((Component)this).transform.Find("Radio grab bounds")).GetComponent<BoxCollider>();
		GameObject val = new GameObject("Radio gold glow");
		val.transform.SetParent(((Component)this).transform, false);
		Transform transform = val.transform;
		Vector3 one = Vector3.one;
		Vector3 size = body.size;
		transform.localScale = one * Mathf.Max(0.48f, ((Vector3)(ref size)).magnitude * 1.42f);
		halo = val.AddComponent<SpriteRenderer>();
		halo.sprite = GetHaloSprite();
		halo.color = new Color(1f, 0.72f, 0.24f, 0.62f);
		((Renderer)halo).enabled = false;
		((Behaviour)this).enabled = false;
	}

	internal void SetPlaying(bool playing)
	{
		if (((Behaviour)this).enabled != playing)
		{
			((Behaviour)this).enabled = playing;
			if (!playing)
			{
				((Renderer)halo).enabled = false;
			}
			else
			{
				LateUpdate();
			}
		}
	}

	private void LateUpdate()
	{
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: 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_005c: 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_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: 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_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: 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_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		Camera val = (Object.op_Implicit((Object)(object)GameDirector.instance) ? GameDirector.instance.MainCamera : null);
		((Renderer)halo).enabled = (Object)(object)val != (Object)null;
		if (Object.op_Implicit((Object)(object)val))
		{
			Vector3 val2 = ((Component)body).transform.TransformPoint(body.center);
			Vector3 val3 = ((Component)val).transform.position - val2;
			Vector3 normalized = ((Vector3)(ref val3)).normalized;
			Vector3 val4 = ((Component)body).transform.InverseTransformDirection(normalized);
			Vector3 val5 = body.size * 0.5f;
			float num = Mathf.Abs(val4.x) * val5.x * ((Component)body).transform.lossyScale.x + Mathf.Abs(val4.y) * val5.y * ((Component)body).transform.lossyScale.y + Mathf.Abs(val4.z) * val5.z * ((Component)body).transform.lossyScale.z;
			((Component)halo).transform.SetPositionAndRotation(val2 - normalized * (num + 0.015f), ((Component)val).transform.rotation);
		}
	}

	private static Sprite GetHaloSprite()
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Expected O, but got Unknown
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)haloSprite))
		{
			return haloSprite;
		}
		Texture2D val = new Texture2D(64, 64, (TextureFormat)4, false);
		((Object)val).name = "Radio gold glow";
		((Texture)val).wrapMode = (TextureWrapMode)1;
		Color32[] array = (Color32[])(object)new Color32[4096];
		Vector2 val2 = default(Vector2);
		for (int i = 0; i < 64; i++)
		{
			for (int j = 0; j < 64; j++)
			{
				((Vector2)(ref val2))..ctor((2f * (float)j + 1f) / 64f - 1f, (2f * (float)i + 1f) / 64f - 1f);
				float num = 1f - Mathf.SmoothStep(0f, 1f, ((Vector2)(ref val2)).sqrMagnitude);
				ref Color32 reference = ref array[i * 64 + j];
				reference = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, (byte)Mathf.RoundToInt(255f * num));
			}
		}
		val.SetPixels32(array);
		val.Apply(false, true);
		haloSprite = Sprite.Create(val, new Rect(0f, 0f, 64f, 64f), new Vector2(0.5f, 0.5f), 64f, 0u, (SpriteMeshType)0);
		return haloSprite;
	}
}
internal static class RadioInput
{
	[HarmonyPatch(typeof(ItemToggle), "ToggleItem")]
	internal static class ToggleHeldRadio
	{
		private static bool Prefix(ItemToggle __instance, bool __0)
		{
			RadioPlayback component = ((Component)__instance).GetComponent<RadioPlayback>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return true;
			}
			if (!component.Mounted && __instance.toggleState != __0)
			{
				component.Request(0);
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(PhysGrabber), "GrabInputActiveGet")]
	internal static class SkipVolumeGrab
	{
		private static void Prefix(PhysGrabber __instance, ref bool __0, ref bool __1)
		{
			if (!((Object)(object)__instance != (Object)(object)PhysGrabber.instance))
			{
				Mouse current = Mouse.current;
				bool flag = __1 || (current != null && current.leftButton.wasPressedThisFrame);
				bool flag2 = __0 || (current != null && current.leftButton.isPressed);
				if (flag)
				{
					HandleVolumeClick();
				}
				else if (!flag2 && volumeClickFrame != Time.frameCount)
				{
					suppressGrab = false;
				}
				if (suppressGrab)
				{
					__0 = false;
					__1 = false;
				}
			}
		}
	}

	private static readonly RaycastHit[] Hits = (RaycastHit[])(object)new RaycastHit[32];

	private static int lastAimFrame = -1;

	private static RadioPlayback aimedRadio;

	private static RaycastHit aimHit;

	private static Vector3 aimRight;

	private static int volumeClickFrame = -1;

	private static bool suppressGrab;

	internal static void Update()
	{
		if (!CanInteract())
		{
			return;
		}
		Mouse current = Mouse.current;
		if (SemiFunc.InputDown((InputKey)10) || (current != null && current.leftButton.wasPressedThisFrame))
		{
			HandleVolumeClick();
		}
		if (SemiFunc.InputDown((InputKey)2))
		{
			Aim();
			if (Object.op_Implicit((Object)(object)aimedRadio) && !aimedRadio.GrabbedLocally)
			{
				aimedRadio.Request(0);
			}
		}
	}

	private static void HandleVolumeClick()
	{
		//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)
		if (volumeClickFrame == Time.frameCount)
		{
			return;
		}
		volumeClickFrame = Time.frameCount;
		suppressGrab = false;
		if (!CanInteract() || (Object.op_Implicit((Object)(object)PhysGrabber.instance) && PhysGrabber.instance.grabbed))
		{
			return;
		}
		Aim();
		if (Object.op_Implicit((Object)(object)aimedRadio))
		{
			int num = aimedRadio.VolumeEdge(aimHit, aimRight);
			if (num != 0)
			{
				suppressGrab = true;
				aimedRadio.Request(num);
			}
		}
	}

	private static bool CanInteract()
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Invalid comparison between Unknown and I4
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Invalid comparison between Unknown and I4
		if (Object.op_Implicit((Object)(object)GameDirector.instance) && (int)GameDirector.instance.currentState == 2 && Object.op_Implicit((Object)(object)GameDirector.instance.MainCamera))
		{
			return (int)Cursor.lockState == 1;
		}
		return false;
	}

	private static void Aim()
	{
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: 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_010e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		if (lastAimFrame == Time.frameCount)
		{
			return;
		}
		lastAimFrame = Time.frameCount;
		aimedRadio = null;
		PlayerAvatar val = SemiFunc.PlayerAvatarLocal();
		Transform val2 = ((Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val.localCamera)) ? val.localCamera.GetOverrideTransform() : null);
		if (!Object.op_Implicit((Object)(object)val2))
		{
			val2 = ((Component)GameDirector.instance.MainCamera).transform;
		}
		aimRight = val2.right;
		float num = 3.5f;
		int num2 = Physics.RaycastNonAlloc(val2.position, val2.forward, Hits, num, -5, (QueryTriggerInteraction)2);
		for (int i = 0; i < num2; i++)
		{
			RaycastHit val3 = Hits[i];
			if (!(((RaycastHit)(ref val3)).distance >= num) && (!Object.op_Implicit((Object)(object)val) || !((Component)((RaycastHit)(ref val3)).collider).transform.IsChildOf(((Component)val).transform)))
			{
				RadioPlayback componentInParent = ((Component)((RaycastHit)(ref val3)).collider).GetComponentInParent<RadioPlayback>();
				if (!((RaycastHit)(ref val3)).collider.isTrigger || (Object.op_Implicit((Object)(object)componentInParent) && componentInParent.Mounted))
				{
					num = ((RaycastHit)(ref val3)).distance;
					aimedRadio = componentInParent;
					aimHit = val3;
				}
			}
		}
	}
}
[HarmonyPatch(typeof(StatsManager), "RunStartStats")]
internal static class RadioItem
{
	internal const string AssetName = "Item MA Portable Radio";

	private const string DonorItem = "Item Melee Frying Pan";

	private const string RadioModule = "Level/Shop/Modules/Module - Shop - N - Middle Stands";

	private static GameObject holder;

	private static bool registered;

	private static bool reportedMissingAssets;

	[HarmonyBefore(new string[] { "REPOLib" })]
	[HarmonyPriority(600)]
	[HarmonyPostfix]
	private static void Register(StatsManager __instance)
	{
		//IL_00f4: 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)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dd: Expected O, but got Unknown
		if (registered)
		{
			return;
		}
		GameObject val = null;
		Item val2 = null;
		Value val3 = null;
		try
		{
			if (!__instance.itemDictionary.TryGetValue("Item Melee Frying Pan", out var value) || !Object.op_Implicit((Object)(object)value) || value.prefab == null || !Object.op_Implicit((Object)(object)((PrefabRef<GameObject>)(object)value.prefab).Prefab) || !Object.op_Implicit((Object)(object)value.value))
			{
				ReportMissingAssets("The vanilla shop item used for the radio's physical controls is unavailable.");
				return;
			}
			GameObject val4 = Resources.Load<GameObject>("Level/Shop/Modules/Module - Shop - N - Middle Stands");
			ShopRadio val5 = (Object.op_Implicit((Object)(object)val4) ? val4.GetComponentInChildren<ShopRadio>(true) : null);
			if (!Object.op_Implicit((Object)(object)val5))
			{
				ReportMissingAssets("The installed game did not provide the shop radio model.");
				return;
			}
			val2 = Object.Instantiate<Item>(value);
			val3 = Object.Instantiate<Value>(value.value);
			val3.valueMin = (val3.valueMax = Plugin.Price.Value);
			((Object)val2).name = "Item MA Portable Radio";
			val2.itemName = "Radio przenośne";
			val2.itemNameLocalized = null;
			val2.description = "E: włącz, wyłącz lub odepnij. Kliknij skraj radia, aby zmienić głośność.";
			val2.itemType = (itemType)13;
			val2.itemVolume = (itemVolume)0;
			val2.itemSecretShopType = (itemSecretShopType)0;
			val2.maxAmount = 3;
			val2.maxAmountInShop = 1;
			val2.maxPurchase = false;
			val2.minPlayerCount = 1;
			val2.physicalItem = true;
			val2.value = val3;
			val = Object.Instantiate<GameObject>(((PrefabRef<GameObject>)(object)value.prefab).Prefab, InactiveHolder().transform);
			((Object)val).name = "Item MA Portable Radio";
			ItemAttributes component = val.GetComponent<ItemAttributes>();
			PhotonView component2 = val.GetComponent<PhotonView>();
			if (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)component2) || !Object.op_Implicit((Object)(object)val.GetComponent<PhysGrabObject>()))
			{
				throw new InvalidOperationException("The donor has no physical shop item components.");
			}
			int colliderLayer = PrepareDonor(val, component2);
			RadioVisual.Attach(((Component)val5).transform, val.transform, colliderLayer);
			component.item = val2;
			component.icon = null;
			ItemToggle val6 = val.GetComponent<ItemToggle>() ?? val.AddComponent<ItemToggle>();
			val6.onToggle = new UnityEvent();
			val6.playSound = false;
			val6.autoTurnOffWhenEquipped = false;
			val6.toggleState = false;
			AudioSource val7 = val.AddComponent<AudioSource>();
			val7.playOnAwake = false;
			val7.loop = true;
			val7.spatialBlend = 1f;
			val7.dopplerLevel = 0f;
			val7.rolloffMode = (AudioRolloffMode)1;
			val.AddComponent<RadioGlow>();
			val.AddComponent<RadioPlayback>();
			if (Items.RegisterItem(component) == null)
			{
				throw new InvalidOperationException("REPOLib rejected the radio prefab.");
			}
			registered = true;
			Plugin.Instance.LogInfo("Registered Item MA Portable Radio with a base price of " + Plugin.Price.Value + ".");
		}
		catch (Exception ex)
		{
			if (Object.op_Implicit((Object)(object)val))
			{
				Object.DestroyImmediate((Object)(object)val);
			}
			if (Object.op_Implicit((Object)(object)val2))
			{
				Object.DestroyImmediate((Object)(object)val2);
			}
			if (Object.op_Implicit((Object)(object)val3))
			{
				Object.DestroyImmediate((Object)(object)val3);
			}
			ReportMissingAssets("The portable radio could not be registered. " + ex);
		}
	}

	private static int PrepareDonor(GameObject radio, PhotonView view)
	{
		MonoBehaviour[] componentsInChildren = radio.GetComponentsInChildren<MonoBehaviour>(true);
		foreach (MonoBehaviour val in componentsInChildren)
		{
			if (Object.op_Implicit((Object)(object)val) && (val is HurtCollider || ((object)val).GetType().Name.StartsWith("ItemMelee", StringComparison.Ordinal)))
			{
				Object.DestroyImmediate((Object)(object)val);
			}
		}
		if (view.ObservedComponents != null)
		{
			view.ObservedComponents.RemoveAll((Component val8) => !Object.op_Implicit((Object)(object)val8) || !(val8 is IPunObservable));
		}
		Renderer[] componentsInChildren2 = radio.GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val2 in componentsInChildren2)
		{
			val2.enabled = false;
		}
		AudioSource[] componentsInChildren3 = radio.GetComponentsInChildren<AudioSource>(true);
		foreach (AudioSource val3 in componentsInChildren3)
		{
			((Behaviour)val3).enabled = false;
		}
		int layer = radio.layer;
		Collider[] componentsInChildren4 = radio.GetComponentsInChildren<Collider>(true);
		Collider val4 = ((IEnumerable<Collider>)componentsInChildren4).FirstOrDefault((Func<Collider, bool>)((Collider collider) => !collider.isTrigger && Object.op_Implicit((Object)(object)((Component)collider).GetComponent<PhysGrabObjectCollider>())));
		if (Object.op_Implicit((Object)(object)val4))
		{
			layer = ((Component)val4).gameObject.layer;
		}
		Collider[] array = componentsInChildren4;
		foreach (Collider val5 in array)
		{
			val5.enabled = false;
		}
		Transform val6 = radio.transform.Find("Force Grab Point");
		if (Object.op_Implicit((Object)(object)val6))
		{
			Object.DestroyImmediate((Object)(object)((Component)val6).gameObject);
		}
		Transform val7 = radio.transform.Find("Center of Mass");
		if (Object.op_Implicit((Object)(object)val7))
		{
			Object.DestroyImmediate((Object)(object)((Component)val7).gameObject);
		}
		radio.GetComponent<PhysGrabObject>().ignoreGrabPointCentering = false;
		Rigidbody component = radio.GetComponent<Rigidbody>();
		component.maxLinearVelocity = 5f;
		component.maxAngularVelocity = 8f;
		component.linearDamping = Mathf.Max(component.linearDamping, 0.9f);
		component.angularDamping = Mathf.Max(component.angularDamping, 2.5f);
		return layer;
	}

	private static GameObject InactiveHolder()
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Expected O, but got Unknown
		if (!Object.op_Implicit((Object)(object)holder))
		{
			holder = new GameObject("MA Portable Radio Prefabs");
			holder.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)holder);
		}
		return holder;
	}

	private static void ReportMissingAssets(string message)
	{
		if (!reportedMissingAssets)
		{
			reportedMissingAssets = true;
			Plugin.Instance.LogWarning(message);
		}
	}
}
internal static class RadioMusic
{
	private static readonly List<string> Tracks = new List<string>();

	private static readonly Dictionary<string, AudioClip> Clips = new Dictionary<string, AudioClip>(StringComparer.Ordinal);

	internal static string FirstTrack
	{
		get
		{
			if (Tracks.Count <= 0)
			{
				return string.Empty;
			}
			return Tracks[0];
		}
	}

	internal static string NextTrack(string track)
	{
		int num = Tracks.IndexOf(track) + 1;
		if (num >= Tracks.Count)
		{
			return FirstTrack;
		}
		return Tracks[num];
	}

	internal static AudioClip GetTrack(string track)
	{
		if (!Clips.TryGetValue(track, out var value))
		{
			return null;
		}
		return value;
	}

	internal static IEnumerator Load()
	{
		string pluginFolder = Path.GetDirectoryName(((BaseUnityPlugin)Plugin.Instance).Info.Location);
		string folder = Path.Combine(pluginFolder, "Music");
		if (!Directory.Exists(folder))
		{
			yield break;
		}
		string[] files;
		try
		{
			files = Directory.GetFiles(folder).OrderBy<string, string>((string path) => path, StringComparer.OrdinalIgnoreCase).ToArray();
		}
		catch (IOException)
		{
			files = new string[0];
			Plugin.Instance.LogWarning("Could not read radio music from " + folder);
		}
		catch (UnauthorizedAccessException)
		{
			files = new string[0];
			Plugin.Instance.LogWarning("Cannot access radio music in " + folder);
		}
		try
		{
			string[] array = files;
			foreach (string file in array)
			{
				AudioType type = GetAudioType(file);
				if ((int)type != 0)
				{
					yield return LoadClip(new Uri(file), type, Path.GetFileName(file));
				}
			}
		}
		finally
		{
		}
	}

	private static AudioType GetAudioType(string path)
	{
		return (AudioType)(Path.GetExtension(path).ToLowerInvariant() switch
		{
			".ogg" => 14, 
			".mp3" => 13, 
			".wav" => 20, 
			_ => 0, 
		});
	}

	private static IEnumerator LoadClip(Uri uri, AudioType type, string label)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(uri.AbsoluteUri, type);
		try
		{
			request.timeout = 15;
			request.redirectLimit = 0;
			((DownloadHandlerAudioClip)request.downloadHandler).compressed = true;
			yield return request.SendWebRequest();
			AudioClip clip = (((int)request.result == 1) ? DownloadHandlerAudioClip.GetContent(request) : null);
			if (Object.op_Implicit((Object)(object)clip) && clip.samples > 0)
			{
				Tracks.Add(label);
				Clips.Add(label, clip);
				Plugin.Instance.LogDebug("Loaded radio track: " + label);
			}
			else
			{
				Plugin.Instance.LogWarning("Could not load radio track: " + label);
			}
		}
		finally
		{
			((IDisposable)request)?.Dispose();
		}
	}
}
internal sealed class RadioPlayback : MonoBehaviourPunCallbacks
{
	[HarmonyPatch(typeof(PhysGrabObjectImpactDetector), "Break")]
	internal static class ChangeTrackOnImpact
	{
		private static void Postfix(PhysGrabObjectImpactDetector __instance)
		{
			if (SemiFunc.IsMasterClientOrSingleplayer())
			{
				RadioPlayback componentInParent = ((Component)__instance).GetComponentInParent<RadioPlayback>();
				if (Object.op_Implicit((Object)(object)componentInParent) && !componentInParent.Mounted && !(Time.time < componentInParent.nextImpact))
				{
					componentInParent.AdvanceTrack();
				}
			}
		}
	}

	internal const float Reach = 3.5f;

	internal const int Toggle = 0;

	internal const int Quieter = -1;

	internal const int Louder = 1;

	private const float PlayerRangeMultiplier = 1.5f;

	private const string StateRPC = "MAPortableRadioState";

	private const string SyncRPC = "MAPortableRadioRequestState";

	private static readonly FieldInfo BlockExtraction = AccessTools.Field(typeof(ItemAttributes), "blockExtraction");

	private ItemToggle toggle;

	private ItemAttributes attributes;

	private AudioSource speaker;

	private RadioGlow glow;

	private PhysGrabObject grab;

	private BoxCollider radioCollider;

	private PhysGrabCart cart;

	private Vector3 mountPoint;

	private Quaternion mountRotation = Quaternion.identity;

	private int mountView;

	private bool mountApplied;

	private bool previousBlock;

	private float waitForCartUntil;

	private bool wasHeld;

	private float mountRetryUntil;

	private float nextMountSearch;

	private bool playing;

	private int volume;

	private string track = string.Empty;

	private double startedAt;

	private double playedSince = -1.0;

	private int lastInteractFrame = -1;

	private int stateRevision;

	private int stateSender;

	private float nextImpact;

	private float nextNoise;

	internal bool Mounted
	{
		get
		{
			if (!Object.op_Implicit((Object)(object)cart))
			{
				return mountView != 0;
			}
			return true;
		}
	}

	internal bool GrabbedLocally
	{
		get
		{
			if (Object.op_Implicit((Object)(object)grab))
			{
				return grab.grabbedLocal;
			}
			return false;
		}
	}

	private static double Clock
	{
		get
		{
			if (!PhotonNetwork.InRoom)
			{
				return Time.timeAsDouble;
			}
			return PhotonNetwork.Time;
		}
	}

	private void Awake()
	{
		toggle = ((Component)this).GetComponent<ItemToggle>();
		attributes = ((Component)this).GetComponent<ItemAttributes>();
		grab = ((Component)this).GetComponent<PhysGrabObject>();
		radioCollider = ((Component)((Component)this).transform.Find("Radio grab bounds")).GetComponent<BoxCollider>();
		speaker = ((Component)this).GetComponents<AudioSource>().First((AudioSource source) => ((Behaviour)source).enabled);
		glow = ((Component)this).GetComponent<RadioGlow>();
		volume = Plugin.Volume.Value;
	}

	private void Start()
	{
		grab.rb.ResetCenterOfMass();
		grab.rb.ResetInertiaTensor();
		if (PhotonNetwork.InRoom)
		{
			((MonoBehaviourPun)this).photonView.RefreshRpcMonoBehaviourCache();
			if (PhotonNetwork.IsMasterClient)
			{
				Publish();
			}
			else
			{
				RequestState();
			}
		}
	}

	public override void OnMasterClientSwitched(Player newMasterClient)
	{
		if (newMasterClient.IsLocal)
		{
			Publish();
		}
		else
		{
			RequestState();
		}
	}

	internal int VolumeEdge(RaycastHit hit, Vector3 viewRight)
	{
		//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_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		if ((!playing && !Mounted) || (Object)(object)((RaycastHit)(ref hit)).collider != (Object)(object)radioCollider)
		{
			return 0;
		}
		Transform transform = ((Component)radioCollider).transform;
		float num = Vector3.Dot(viewRight, transform.right);
		if (Mathf.Abs(num) < 0.4f)
		{
			return 0;
		}
		float num2 = (transform.InverseTransformPoint(((RaycastHit)(ref hit)).point).x - radioCollider.center.x) * Mathf.Sign(num);
		float num3 = radioCollider.size.x * 0.38f;
		if (num2 < 0f - num3)
		{
			return -1;
		}
		if (num2 > num3)
		{
			return 1;
		}
		return 0;
	}

	internal void Request(int action)
	{
		if (action == 0)
		{
			if (lastInteractFrame == Time.frameCount)
			{
				return;
			}
			lastInteractFrame = Time.frameCount;
		}
		if (!PhotonNetwork.InRoom || PhotonNetwork.IsMasterClient)
		{
			ApplyAction(action, null);
		}
		else if (((MonoBehaviourPun)this).photonView.ViewID != 0)
		{
			((MonoBehaviourPun)this).photonView.RPC("MAPortableRadioAction", (RpcTarget)2, new object[1] { action });
		}
	}

	[PunRPC]
	private void MAPortableRadioAction(int action, PhotonMessageInfo info)
	{
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		if (!PhotonNetwork.IsMasterClient || info.Sender == null || !Object.op_Implicit((Object)(object)GameDirector.instance))
		{
			return;
		}
		foreach (PlayerAvatar player in GameDirector.instance.PlayerList)
		{
			if (Object.op_Implicit((Object)(object)player) && Object.op_Implicit((Object)(object)player.photonView) && player.photonView.OwnerActorNr == info.Sender.ActorNumber)
			{
				Vector3 val = ((Component)player).transform.position - ((Component)this).transform.position;
				if (((Vector3)(ref val)).sqrMagnitude <= 25f)
				{
					ApplyAction(action, info.Sender);
				}
				break;
			}
		}
	}

	private void ApplyAction(int action, Player requester)
	{
		switch (action)
		{
		case 0:
			if (Mounted)
			{
				Detach();
				return;
			}
			playing = !playing;
			if (playing && track.Length == 0)
			{
				track = RadioMusic.FirstTrack;
			}
			startedAt = Clock;
			break;
		case -1:
		case 1:
		{
			if (!playing && !Mounted)
			{
				return;
			}
			int num = Mathf.Clamp(volume + action, 0, 10);
			if (requester == null)
			{
				ShowVolume(num);
			}
			else
			{
				((MonoBehaviourPun)this).photonView.RPC("MAPortableRadioVolume", requester, new object[1] { num });
			}
			if (volume == num)
			{
				return;
			}
			volume = num;
			break;
		}
		default:
			return;
		}
		RefreshAudio();
		Publish();
	}

	[PunRPC]
	private void MAPortableRadioVolume(int level, PhotonMessageInfo info)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		if (FromMaster(info))
		{
			ShowVolume(level);
		}
	}

	private static void ShowVolume(int level)
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		string text = "Głośność radia " + Mathf.Clamp(level, 0, 10) + "/10";
		Plugin.Instance.LogDebug(text);
		if (Object.op_Implicit((Object)(object)MissionUI.instance))
		{
			SemiFunc.UIFocusText(text, new Color(1f, 0.83f, 0.45f), Color.black, 1.2f);
		}
	}

	private void Publish()
	{
		if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient && ((MonoBehaviourPun)this).photonView.ViewID != 0)
		{
			stateRevision++;
			PhotonNetwork.RemoveBufferedRPCs(((MonoBehaviourPun)this).photonView.ViewID, "MAPortableRadioState", (int[])null);
			((MonoBehaviourPun)this).photonView.RPC("MAPortableRadioState", (RpcTarget)4, Snapshot());
		}
	}

	private object[] Snapshot()
	{
		//IL_0059: 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)
		return new object[8] { stateRevision, playing, volume, track, startedAt, mountView, mountPoint, mountRotation };
	}

	private void RequestState()
	{
		if (PhotonNetwork.InRoom && !PhotonNetwork.IsMasterClient && ((MonoBehaviourPun)this).photonView.ViewID != 0)
		{
			((MonoBehaviourPun)this).photonView.RPC("MAPortableRadioRequestState", (RpcTarget)2, new object[0]);
		}
	}

	[PunRPC]
	private void MAPortableRadioRequestState(PhotonMessageInfo info)
	{
		if (PhotonNetwork.IsMasterClient && info.Sender != null && ((MonoBehaviourPun)this).photonView.ViewID != 0)
		{
			((MonoBehaviourPun)this).photonView.RPC("MAPortableRadioState", info.Sender, Snapshot());
		}
	}

	private static bool FromMaster(PhotonMessageInfo info)
	{
		Player masterClient = PhotonNetwork.MasterClient;
		if (info.Sender != null && masterClient != null)
		{
			return info.Sender.ActorNumber == masterClient.ActorNumber;
		}
		return false;
	}

	[PunRPC]
	private void MAPortableRadioState(int revision, bool enabled, int level, string song, double start, int cartView, Vector3 point, Quaternion rotation, PhotonMessageInfo info)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		if (!FromMaster(info))
		{
			return;
		}
		int actorNumber = info.Sender.ActorNumber;
		if (stateSender != actorNumber || revision > stateRevision)
		{
			stateSender = actorNumber;
			stateRevision = revision;
			playing = enabled;
			volume = Mathf.Clamp(level, 0, 10);
			track = song ?? string.Empty;
			startedAt = start;
			if (mountView != cartView)
			{
				cart = null;
			}
			mountView = cartView;
			mountPoint = point;
			mountRotation = rotation;
			if (mountView != 0 && !Object.op_Implicit((Object)(object)cart))
			{
				waitForCartUntil = Time.unscaledTime + 3f;
			}
			SetMounted(Mounted);
			RefreshAudio();
		}
	}

	private void RefreshAudio()
	{
		toggle.toggleState = playing;
		AudioClip val = (playing ? RadioMusic.GetTrack(track) : null);
		glow.SetPlaying((Object)(object)val != (Object)null);
		if (!Object.op_Implicit((Object)(object)val))
		{
			speaker.Stop();
			speaker.clip = null;
			return;
		}
		if (Object.op_Implicit((Object)(object)AudioManager.instance))
		{
			speaker.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
		}
		speaker.volume = Mathf.Pow((float)volume / 10f, 1.55f);
		speaker.minDistance = 2.25f;
		speaker.maxDistance = Mathf.Lerp(3f, 14f, (float)volume / 10f) * 1.5f;
		if ((Object)(object)speaker.clip != (Object)(object)val || !speaker.isPlaying || startedAt != playedSince)
		{
			playedSince = startedAt;
			speaker.clip = val;
			double num = Clock - startedAt;
			if (num < -2147483.0)
			{
				num += 4294967.296;
			}
			speaker.time = (float)(Math.Max(0.0, num) % (double)val.length);
			speaker.Play();
		}
	}

	private void Update()
	{
		//IL_0173: Unknown result type (might be due to invalid IL or missing references)
		bool flag = SemiFunc.IsMasterClientOrSingleplayer();
		if (flag && playing && track.Length == 0 && RadioMusic.FirstTrack.Length != 0)
		{
			track = RadioMusic.FirstTrack;
			Publish();
		}
		if (playing && (Object)(object)speaker.clip != (Object)(object)RadioMusic.GetTrack(track))
		{
			RefreshAudio();
		}
		if (flag)
		{
			bool flag2 = grab.grabbed || grab.grabbedLocal || (grab.playerGrabbing != null && grab.playerGrabbing.Count > 0);
			if (flag2)
			{
				mountRetryUntil = 0f;
			}
			else if (wasHeld && !Mounted)
			{
				mountRetryUntil = Time.time + 0.45f;
				nextMountSearch = Time.time;
			}
			wasHeld = flag2;
			if (!Mounted && Time.time < mountRetryUntil && Time.time >= nextMountSearch)
			{
				nextMountSearch = Time.time + 0.1f;
				TryMount();
			}
			if (playing && speaker.isPlaying && Object.op_Implicit((Object)(object)EnemyDirector.instance) && SemiFunc.RunIsLevel() && Time.time >= nextNoise)
			{
				nextNoise = Time.time + 2f;
				SemiFunc.EnemyInvestigate(((Component)this).transform.position, 1.6f, false);
			}
		}
	}

	private void TryMount()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = Vector3.zero;
		Quaternion val2 = Quaternion.identity;
		PhysGrabCart val3 = null;
		PhotonView val4 = null;
		float num = 0.80999994f;
		float radioHalfWidth = radioCollider.size.x * ((Component)this).transform.lossyScale.x * 0.5f;
		float radioHalfDepth = radioCollider.size.z * ((Component)this).transform.lossyScale.z * 0.5f;
		PhysGrabCart[] array = Object.FindObjectsByType<PhysGrabCart>((FindObjectsSortMode)0);
		foreach (PhysGrabCart val5 in array)
		{
			if (!RadioCartSlot.TryGet(val5, ((Component)this).transform.position, radioHalfWidth, radioHalfDepth, out var point, out var rotation))
			{
				continue;
			}
			Vector3 val6 = ((Component)val5).transform.TransformPoint(point) - ((Component)this).transform.position;
			float sqrMagnitude = ((Vector3)(ref val6)).sqrMagnitude;
			if (!(sqrMagnitude > num) && !IsOccupied(val5))
			{
				PhotonView componentInParent = ((Component)val5).GetComponentInParent<PhotonView>();
				if (!PhotonNetwork.InRoom || (Object.op_Implicit((Object)(object)componentInParent) && componentInParent.ViewID != 0))
				{
					num = sqrMagnitude;
					val3 = val5;
					val4 = componentInParent;
					val = point;
					val2 = rotation;
				}
			}
		}
		if (Object.op_Implicit((Object)(object)val3))
		{
			cart = val3;
			mountView = (PhotonNetwork.InRoom ? val4.ViewID : 0);
			mountPoint = val;
			mountRotation = val2;
			waitForCartUntil = 0f;
			mountRetryUntil = 0f;
			SetMounted(mounted: true);
			FollowCart();
			Publish();
			Plugin.Instance.LogInfo("Mounted portable radio on " + ((Object)cart).name + ".");
		}
	}

	private bool IsOccupied(PhysGrabCart candidate)
	{
		RadioPlayback[] array = Object.FindObjectsByType<RadioPlayback>((FindObjectsSortMode)0);
		foreach (RadioPlayback radioPlayback in array)
		{
			if ((Object)(object)radioPlayback != (Object)(object)this && (Object)(object)radioPlayback.cart == (Object)(object)candidate)
			{
				return true;
			}
		}
		return false;
	}

	private void LateUpdate()
	{
		if (!Mounted && !mountApplied)
		{
			return;
		}
		if (!Object.op_Implicit((Object)(object)cart) && mountView != 0)
		{
			PhotonView val = PhotonView.Find(mountView);
			if (Object.op_Implicit((Object)(object)val))
			{
				cart = ((Component)val).GetComponentInChildren<PhysGrabCart>();
			}
		}
		if (Object.op_Implicit((Object)(object)cart))
		{
			FollowCart();
		}
		else if (Time.unscaledTime >= waitForCartUntil && SemiFunc.IsMasterClientOrSingleplayer())
		{
			Detach();
		}
	}

	private void FollowCart()
	{
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		grab.OverrideGrabDisable(0.2f);
		if (Object.op_Implicit((Object)(object)grab.rb) && SemiFunc.IsMasterClientOrSingleplayer())
		{
			grab.OverrideKinematic(0.2f);
		}
		((Component)this).transform.SetPositionAndRotation(((Component)cart).transform.TransformPoint(mountPoint), ((Component)cart).transform.rotation * mountRotation);
	}

	private void SetMounted(bool mounted)
	{
		if (mountApplied == mounted)
		{
			return;
		}
		mountApplied = mounted;
		((Collider)radioCollider).isTrigger = mounted;
		if (!(BlockExtraction == null))
		{
			if (mounted)
			{
				previousBlock = (bool)BlockExtraction.GetValue(attributes);
				BlockExtraction.SetValue(attributes, true);
			}
			else
			{
				BlockExtraction.SetValue(attributes, previousBlock);
			}
		}
	}

	private void Detach()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: 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_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)cart))
		{
			Transform transform = ((Component)this).transform;
			transform.position += ((Component)cart).transform.rotation * mountRotation * Vector3.forward * 0.14f;
		}
		cart = null;
		mountView = 0;
		waitForCartUntil = 0f;
		mountRetryUntil = 0f;
		SetMounted(mounted: false);
		nextImpact = Time.time + 0.35f;
		Publish();
	}

	private void OnCollisionEnter(Collision collision)
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		if (!Mounted && SemiFunc.IsMasterClientOrSingleplayer() && !(Time.time < nextImpact) && collision.contactCount != 0)
		{
			ContactPoint contact = collision.GetContact(0);
			if (Mathf.Abs(Vector3.Dot(collision.relativeVelocity, ((ContactPoint)(ref contact)).normal)) >= 2.2f)
			{
				AdvanceTrack();
			}
		}
	}

	private void AdvanceTrack()
	{
		string text = RadioMusic.NextTrack(track);
		if (!(text == track))
		{
			nextImpact = Time.time + 0.35f;
			track = text;
			startedAt = Clock;
			RefreshAudio();
			Publish();
		}
	}
}
internal static class RadioVisual
{
	internal static void Attach(Transform source, Transform item, int colliderLayer)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: 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_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: 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_00cc: 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_00e2: Expected O, but got Unknown
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		Transform transform = new GameObject("Radio model").transform;
		transform.SetParent(item, false);
		transform.localRotation = Quaternion.Euler(0f, -90f, 0f);
		CopyMesh(source, transform);
		CopyChildren(source, transform);
		MeshFilter[] componentsInChildren = ((Component)transform).GetComponentsInChildren<MeshFilter>(true);
		if (componentsInChildren.Length == 0)
		{
			throw new InvalidOperationException("The shop radio has no visible mesh.");
		}
		Bounds val = BoundsInItemSpace(componentsInChildren, item);
		float num = Mathf.Max(((Bounds)(ref val)).size.x, Mathf.Max(((Bounds)(ref val)).size.y, ((Bounds)(ref val)).size.z));
		if (num < 0.01f)
		{
			throw new InvalidOperationException("The shop radio mesh has empty bounds.");
		}
		float num2 = 0.46f / num;
		transform.localScale = Vector3.one * num2;
		transform.localPosition = -((Bounds)(ref val)).center * num2;
		GameObject val2 = new GameObject("Radio grab bounds");
		val2.layer = colliderLayer;
		val2.tag = "Phys Grab Object";
		val2.transform.SetParent(item, false);
		BoxCollider val3 = val2.AddComponent<BoxCollider>();
		Vector3 val4 = ((Bounds)(ref val)).size * num2;
		val3.size = new Vector3(Mathf.Max(0.08f, val4.x), Mathf.Max(0.08f, val4.y), Mathf.Max(0.08f, val4.z));
		val2.AddComponent<PhysGrabObjectCollider>();
	}

	private static void CopyChildren(Transform source, Transform destination)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Expected O, but got Unknown
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		foreach (Transform item in source)
		{
			Transform val = item;
			if (((Component)val).gameObject.activeSelf)
			{
				Transform transform = new GameObject(((Object)val).name).transform;
				transform.SetParent(destination, false);
				transform.localPosition = val.localPosition;
				transform.localRotation = val.localRotation;
				transform.localScale = val.localScale;
				CopyMesh(val, transform);
				CopyChildren(val, transform);
			}
		}
	}

	private static void CopyMesh(Transform source, Transform destination)
	{
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		MeshRenderer component = ((Component)source).GetComponent<MeshRenderer>();
		MeshFilter component2 = ((Component)source).GetComponent<MeshFilter>();
		if (Object.op_Implicit((Object)(object)component) && ((Renderer)component).enabled && Object.op_Implicit((Object)(object)component2) && Object.op_Implicit((Object)(object)component2.sharedMesh))
		{
			((Component)destination).gameObject.AddComponent<MeshFilter>().sharedMesh = component2.sharedMesh;
			MeshRenderer val = ((Component)destination).gameObject.AddComponent<MeshRenderer>();
			((Renderer)val).sharedMaterials = ((Renderer)component).sharedMaterials;
			((Renderer)val).shadowCastingMode = ((Renderer)component).shadowCastingMode;
			((Renderer)val).receiveShadows = ((Renderer)component).receiveShadows;
		}
	}

	private static Bounds BoundsInItemSpace(MeshFilter[] filters, Transform item)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: 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_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: 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_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		MeshFilter val = filters[0];
		Transform transform = ((Component)val).transform;
		Bounds bounds = val.sharedMesh.bounds;
		Bounds result = default(Bounds);
		((Bounds)(ref result))..ctor(item.InverseTransformPoint(transform.TransformPoint(((Bounds)(ref bounds)).center)), Vector3.zero);
		Vector3 val4 = default(Vector3);
		foreach (MeshFilter val2 in filters)
		{
			Bounds bounds2 = val2.sharedMesh.bounds;
			Matrix4x4 val3 = item.worldToLocalMatrix * ((Component)val2).transform.localToWorldMatrix;
			for (int j = 0; j < 8; j++)
			{
				((Vector3)(ref val4))..ctor(((j & 1) == 0) ? ((Bounds)(ref bounds2)).min.x : ((Bounds)(ref bounds2)).max.x, ((j & 2) == 0) ? ((Bounds)(ref bounds2)).min.y : ((Bounds)(ref bounds2)).max.y, ((j & 4) == 0) ? ((Bounds)(ref bounds2)).min.z : ((Bounds)(ref bounds2)).max.z);
				((Bounds)(ref result)).Encapsulate(((Matrix4x4)(ref val3)).MultiplyPoint3x4(val4));
			}
		}
		return result;
	}
}