Decompiled source of MoonforgedBells v1.0.0

MoonforgedBells.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Playables;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("MoonforgedBells")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MoonforgedBells")]
[assembly: AssemblyTitle("MoonforgedBells")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Moonforged.Bells;

internal sealed class ControllerBell : MonoBehaviour
{
	internal static readonly HashSet<ControllerBell> Instances = new HashSet<ControllerBell>();

	[SerializeField]
	private GameObject rope;

	[SerializeField]
	private BellStrikePreview playback;

	[SerializeField]
	private int order;

	private ZNetView view;

	private BellController controller;

	private long lastRound;

	private BellController lastConductor;

	internal int Order => order;

	internal float Duration => playback.Duration;

	internal string Id => ((object)Unsafe.As<ZDOID, ZDOID>(ref view.GetZDO().m_uid)/*cast due to .constrained prefix*/).ToString();

	internal bool Ready => Object.op_Implicit((Object)(object)view) && view.IsValid();

	internal bool Linked => Object.op_Implicit((Object)(object)controller);

	internal void Configure(GameObject ropeObject, BellStrikePreview preview, int size)
	{
		rope = ropeObject;
		playback = preview;
		order = size;
	}

	private void OnEnable()
	{
		view = ((Component)this).GetComponent<ZNetView>();
		Instances.Add(this);
	}

	private void OnDisable()
	{
		Instances.Remove(this);
	}

	internal void SetController(BellController next)
	{
		controller = next;
		if (rope.activeSelf == Linked)
		{
			rope.SetActive(!Linked);
		}
	}

	internal bool Scheduled(BellController conductor, long start, double elapsed)
	{
		if ((Object)(object)lastConductor == (Object)(object)conductor && lastRound == start)
		{
			return true;
		}
		if (!playback.TryStrikeAfter(elapsed))
		{
			return false;
		}
		lastConductor = conductor;
		lastRound = start;
		return true;
	}
}
internal sealed class BellController : MonoBehaviour
{
	private const float ButtonUseRange = 6f;

	private const double StaggerSeconds = 1.5;

	private const double NetworkLead = 0.35;

	private const string ToggleRpc = "MoonforgedBellController.Toggle";

	private const string ClickRpc = "MoonforgedBellController.Click";

	private const string LoopKey = "mf_bell_loop";

	private const string ToggleTimeKey = "mf_bell_toggle_time";

	private const string RoundKey = "mf_bell_round";

	private const string PendingKey = "mf_bell_pending";

	private static readonly HashSet<BellController> Instances = new HashSet<BellController>();

	private static readonly int Emission = Shader.PropertyToID("_EmissionColor");

	[SerializeField]
	private Renderer[] buttonRenderers;

	[SerializeField]
	private AudioSource click;

	[SerializeField]
	private bool detectPlayers;

	[SerializeField]
	private bool linkControllers;

	[SerializeField]
	private float linkRange;

	[SerializeField]
	private float detectionRange;

	[SerializeField]
	private float controllerLinkRange;

	private HashSet<long> inside = new HashSet<long>();

	private HashSet<long> observed = new HashSet<long>();

	private MaterialPropertyBlock emissionBlock;

	private ZNetView view;

	private bool lit;

	private bool glowInitialized;

	private static float nextRefresh;

	private bool Ready => Object.op_Implicit((Object)(object)view) && view.IsValid();

	private string Id => ((object)Unsafe.As<ZDOID, ZDOID>(ref view.GetZDO().m_uid)/*cast due to .constrained prefix*/).ToString();

	internal void Configure(Renderer[] renderers, AudioSource clickSource, bool detection, bool link, float range, float playerRange, float buttonRange)
	{
		buttonRenderers = renderers;
		click = clickSource;
		detectPlayers = detection;
		linkControllers = link;
		linkRange = range;
		detectionRange = playerRange;
		controllerLinkRange = buttonRange;
	}

	private void Awake()
	{
		view = ((Component)this).GetComponent<ZNetView>();
	}

	private void Start()
	{
		if (Ready)
		{
			view.Register<ZDOID>("MoonforgedBellController.Toggle", (Action<long, ZDOID>)OnToggle);
			view.Register<ZDOID>("MoonforgedBellController.Click", (Action<long, ZDOID>)OnClick);
		}
	}

	private void OnEnable()
	{
		Instances.Add(this);
	}

	private void OnDisable()
	{
		Instances.Remove(this);
		if (Instances.Any((BellController controller) => controller.Ready))
		{
			return;
		}
		foreach (ControllerBell instance in ControllerBell.Instances)
		{
			if (instance.Ready)
			{
				instance.SetController(null);
			}
		}
	}

	private void Update()
	{
		if (Ready && Object.op_Implicit((Object)(object)ZNet.instance) && !(Time.unscaledTime < nextRefresh))
		{
			nextRefresh = Time.unscaledTime + 0.1f;
			Refresh();
		}
	}

	private static void Refresh()
	{
		//IL_012f: Unknown result type (might be due to invalid IL or missing references)
		BellController[] array = Instances.Where((BellController controller) => controller.Ready).OrderBy<BellController, string>((BellController controller) => controller.Id, StringComparer.Ordinal).ToArray();
		Dictionary<BellController, BellController> dictionary = new Dictionary<BellController, BellController>();
		Dictionary<BellController, List<ControllerBell>> dictionary2 = new Dictionary<BellController, List<ControllerBell>>();
		Dictionary<BellController, List<BellController>> dictionary3 = new Dictionary<BellController, List<BellController>>();
		BellController[] array2 = array;
		foreach (BellController bellController in array2)
		{
			if (dictionary.ContainsKey(bellController))
			{
				continue;
			}
			dictionary2.Add(bellController, new List<ControllerBell>());
			dictionary3.Add(bellController, bellController.GetGroup(array));
			foreach (BellController item in dictionary3[bellController])
			{
				dictionary.Add(item, bellController);
			}
		}
		foreach (ControllerBell instance in ControllerBell.Instances)
		{
			if (instance.Ready)
			{
				BellController bellController2 = ClosestButton(((Component)instance).transform.position, array);
				instance.SetController(bellController2);
				if (Object.op_Implicit((Object)(object)bellController2))
				{
					dictionary2[dictionary[bellController2]].Add(instance);
				}
			}
		}
		double timeSeconds = ZNet.instance.GetTimeSeconds();
		foreach (KeyValuePair<BellController, List<ControllerBell>> item2 in dictionary2)
		{
			List<BellController> list = dictionary3[item2.Key];
			bool flag = IsLooping(list);
			item2.Key.UpdateGroup(item2.Value, list, timeSeconds, flag);
			foreach (BellController item3 in list)
			{
				item3.SetGlow(flag);
			}
		}
	}

	private static BellController ClosestButton(Vector3 position, BellController[] controllers)
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: 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)
		BellController result = null;
		float num = float.PositiveInfinity;
		foreach (BellController bellController in controllers)
		{
			Vector3 val = ((Component)bellController).transform.position - position;
			float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
			if (!(sqrMagnitude > bellController.linkRange * bellController.linkRange) && !(sqrMagnitude >= num))
			{
				result = bellController;
				num = sqrMagnitude;
			}
		}
		return result;
	}

	private List<BellController> GetGroup(BellController[] controllers)
	{
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		List<BellController> list = new List<BellController> { this };
		if (!linkControllers)
		{
			return list;
		}
		for (int i = 0; i < list.Count; i++)
		{
			BellController bellController = list[i];
			foreach (BellController bellController2 in controllers)
			{
				float num = Mathf.Min(bellController.controllerLinkRange, bellController2.controllerLinkRange);
				if (bellController2.linkControllers && !list.Contains(bellController2))
				{
					Vector3 val = ((Component)bellController2).transform.position - ((Component)bellController).transform.position;
					if (((Vector3)(ref val)).sqrMagnitude <= num * num)
					{
						list.Add(bellController2);
					}
				}
			}
		}
		return list;
	}

	private static bool IsLooping(List<BellController> group)
	{
		return group.OrderByDescending((BellController button) => button.view.GetZDO().GetLong("mf_bell_toggle_time", 0L)).ThenBy<BellController, string>((BellController button) => button.Id, StringComparer.Ordinal).First()
			.view.GetZDO().GetBool("mf_bell_loop", false);
	}

	internal bool Toggle()
	{
		//IL_000f: 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)
		if (!Ready || !PrivateArea.CheckAccess(((Component)this).transform.position, 0f, true, false))
		{
			return false;
		}
		List<BellController> source = GetGroup(Instances.Where((BellController controller) => controller.Ready).ToArray());
		BellController bellController = source.OrderBy<BellController, string>((BellController controller) => controller.Id, StringComparer.Ordinal).First();
		bellController.view.InvokeRPC("MoonforgedBellController.Toggle", new object[1] { view.GetZDO().m_uid });
		return true;
	}

	private void OnToggle(long sender, ZDOID buttonId)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
		if (!Ready || !view.IsOwner() || !Object.op_Implicit((Object)(object)ZNet.instance))
		{
			return;
		}
		List<BellController> list = GetGroup(Instances.Where((BellController controller) => controller.Ready).ToArray());
		BellController button = list.Find((BellController controller) => controller.view.GetZDO().m_uid == buttonId);
		if (!Object.op_Implicit((Object)(object)button) || list.Any((BellController controller) => string.CompareOrdinal(controller.Id, Id) < 0) || !Player.GetAllPlayers().Any(delegate(Player player)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			ZNetView component = ((Component)player).GetComponent<ZNetView>();
			int result;
			if (Object.op_Implicit((Object)(object)component) && component.IsValid() && component.GetZDO().GetOwner() == sender)
			{
				Vector3 val = ((Component)player).transform.position - ((Component)button).transform.position;
				result = ((((Vector3)(ref val)).sqrMagnitude <= 36f) ? 1 : 0);
			}
			else
			{
				result = 0;
			}
			return (byte)result != 0;
		}))
		{
			return;
		}
		ZDO zDO = view.GetZDO();
		bool flag = !IsLooping(list);
		long num = ToMilliseconds(ZNet.instance.GetTimeSeconds());
		foreach (BellController item in list)
		{
			num = Math.Max(num, item.view.GetZDO().GetLong("mf_bell_toggle_time", 0L) + 1);
		}
		zDO.Set("mf_bell_loop", flag);
		zDO.Set("mf_bell_toggle_time", num);
		zDO.Set("mf_bell_pending", 0);
		zDO.Set("mf_bell_round", flag ? ToMilliseconds(ZNet.instance.GetTimeSeconds() + 0.35) : 0);
		if (Object.op_Implicit((Object)(object)button.click))
		{
			view.InvokeRPC(0L, "MoonforgedBellController.Click", new object[1] { buttonId });
		}
	}

	private void OnClick(long sender, ZDOID buttonId)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		if (Ready && view.GetZDO().GetOwner() == sender)
		{
			BellController bellController = GetGroup(Instances.Where((BellController controller) => controller.Ready).ToArray()).Find((BellController controller) => controller.view.GetZDO().m_uid == buttonId);
			if (Object.op_Implicit((Object)(object)bellController) && Object.op_Implicit((Object)(object)bellController.click))
			{
				bellController.click.PlayOneShot(bellController.click.clip);
			}
		}
	}

	private void UpdateGroup(List<ControllerBell> bells, List<BellController> buttons, double now, bool loop)
	{
		ZDO zDO = view.GetZDO();
		long num = zDO.GetLong("mf_bell_round", 0L);
		ControllerBell[] array = bells.OrderBy((ControllerBell bell) => bell.Order).ThenBy<ControllerBell, string>((ControllerBell bell) => bell.Id, StringComparer.Ordinal).ToArray();
		double num2 = 0.0;
		for (int num3 = 0; num3 < array.Length; num3++)
		{
			num2 = Math.Max(num2, (double)num3 * 1.5 + (double)array[num3].Duration);
		}
		if (view.IsOwner())
		{
			int num4 = zDO.GetInt("mf_bell_pending", 0) + ObserveArrivals(buttons, bells.Count > 0, loop);
			if (num == 0L || now >= (double)num / 1000.0 + num2)
			{
				num = ((array.Length != 0 && (loop || num4 > 0)) ? ToMilliseconds(now + 0.35) : 0);
				if (num != 0L && !loop)
				{
					num4--;
				}
				if (zDO.GetLong("mf_bell_round", 0L) != num)
				{
					zDO.Set("mf_bell_round", num);
				}
			}
			if (zDO.GetInt("mf_bell_pending", 0) != num4)
			{
				zDO.Set("mf_bell_pending", num4);
			}
		}
		if (num == 0)
		{
			return;
		}
		for (int num5 = 0; num5 < array.Length; num5++)
		{
			double num6 = now - (double)num / 1000.0 - (double)num5 * 1.5;
			if (num6 >= 0.0 && num6 < (double)array[num5].Duration)
			{
				array[num5].Scheduled(this, num, num6);
			}
		}
	}

	private int ObserveArrivals(List<BellController> buttons, bool hasBells, bool loop)
	{
		if (!hasBells || !buttons.Any((BellController button) => button.detectPlayers))
		{
			inside.Clear();
			observed.Clear();
			return 0;
		}
		int num = 0;
		HashSet<long> hashSet = new HashSet<long>();
		foreach (Player player in Player.GetAllPlayers())
		{
			long playerID = player.GetPlayerID();
			hashSet.Add(playerID);
			bool flag = !observed.Add(playerID);
			if (buttons.Any(delegate(BellController button)
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: 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)
				int result;
				if (button.detectPlayers)
				{
					Vector3 val = ((Component)player).transform.position - ((Component)button).transform.position;
					result = ((((Vector3)(ref val)).sqrMagnitude <= button.detectionRange * button.detectionRange) ? 1 : 0);
				}
				else
				{
					result = 0;
				}
				return (byte)result != 0;
			}))
			{
				if (inside.Add(playerID) && flag && !loop)
				{
					num++;
				}
			}
			else
			{
				inside.Remove(playerID);
			}
		}
		observed.IntersectWith(hashSet);
		inside.IntersectWith(hashSet);
		return num;
	}

	private static long ToMilliseconds(double time)
	{
		return (long)(time * 1000.0);
	}

	private void SetGlow(bool value)
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		if (glowInitialized && lit == value)
		{
			return;
		}
		glowInitialized = true;
		lit = value;
		if (emissionBlock == null)
		{
			emissionBlock = new MaterialPropertyBlock();
		}
		Renderer[] array = buttonRenderers;
		foreach (Renderer val in array)
		{
			if (Object.op_Implicit((Object)(object)val))
			{
				val.GetPropertyBlock(emissionBlock);
				emissionBlock.SetColor(Emission, value ? (new Color(0.1f, 0.38f, 1f) * 2f) : Color.black);
				val.SetPropertyBlock(emissionBlock);
			}
		}
	}
}
internal sealed class ControllerInteraction : MonoBehaviour, Interactable, Hoverable
{
	[SerializeField]
	private BellController controller;

	internal void Configure(BellController value)
	{
		controller = value;
	}

	public float GetHoverOffset()
	{
		return 0f;
	}

	public string GetHoverName()
	{
		return "Bell Controller";
	}

	public string GetHoverText()
	{
		return "Bell Controller\n[<color=yellow><b>E</b></color>] Toggle chime";
	}

	public bool Interact(Humanoid user, bool hold, bool alt)
	{
		return !hold && user is Player && Object.op_Implicit((Object)(object)controller) && controller.Toggle();
	}

	public bool UseItem(Humanoid user, ItemData item)
	{
		return false;
	}
}
internal sealed class BellRopeLength : MonoBehaviour
{
	private const float MaximumDrop = 30f;

	private const float FloorClearance = 0.15f;

	private const float MinimumLength = 0.05f;

	[SerializeField]
	private MeshFilter ropeMesh;

	[SerializeField]
	private SkinnedMeshRenderer skinnedRope;

	[SerializeField]
	private Transform ropeRoot;

	[SerializeField]
	private bool preserveBend;

	private Transform[] ropeBones;

	private Vector3[] sampledBonePositions;

	private Vector3[] jointPositions;

	private bool bendApplied;

	private Transform rope;

	private BoxCollider ropeCollider;

	private Vector3 sampledScale;

	private float extension = 1f;

	private bool extensionApplied;

	private bool ringing;

	private Vector3 originalScale;

	private Vector3 topInMesh;

	private Vector3 bottomInMesh;

	private int lengthAxis;

	private RaycastHit[] hits = (RaycastHit[])(object)new RaycastHit[16];

	private ZNetView view;

	private bool ready;

	public void Configure(MeshFilter mesh)
	{
		ropeMesh = mesh;
	}

	public void Configure(SkinnedMeshRenderer mesh, Transform root, bool keepBend)
	{
		skinnedRope = mesh;
		ropeRoot = root;
		preserveBend = keepBend;
	}

	private void Start()
	{
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: 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_0073: 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_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: 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_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: 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_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_012f: 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_0130: 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)
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_015a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0173: 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)
		view = ((Component)this).GetComponent<ZNetView>();
		if (!Object.op_Implicit((Object)(object)view) || !view.IsValid() || !TryGetRopeBounds(out var bounds))
		{
			return;
		}
		originalScale = rope.localScale;
		lengthAxis = 0;
		Vector3 val;
		for (int i = 1; i < 3; i++)
		{
			val = ((Bounds)(ref bounds)).size;
			float num = ((Vector3)(ref val))[i];
			val = ((Bounds)(ref bounds)).size;
			if (num > ((Vector3)(ref val))[lengthAxis])
			{
				lengthAxis = i;
			}
		}
		Vector3 center = ((Bounds)(ref bounds)).center;
		Vector3 center2 = ((Bounds)(ref bounds)).center;
		int num2 = lengthAxis;
		val = ((Bounds)(ref bounds)).min;
		((Vector3)(ref center))[num2] = ((Vector3)(ref val))[lengthAxis];
		int num3 = lengthAxis;
		val = ((Bounds)(ref bounds)).max;
		((Vector3)(ref center2))[num3] = ((Vector3)(ref val))[lengthAxis];
		bool flag = rope.TransformPoint(center).y > rope.TransformPoint(center2).y;
		topInMesh = (flag ? center : center2);
		bottomInMesh = (flag ? center2 : center);
		if (Object.op_Implicit((Object)(object)skinnedRope))
		{
			topInMesh = Vector3.zero;
			float num4 = ((Vector3)(ref bottomInMesh))[lengthAxis];
			bottomInMesh = Vector3.zero;
			((Vector3)(ref bottomInMesh))[lengthAxis] = num4;
		}
		ready = true;
		((MonoBehaviour)this).InvokeRepeating("AdjustLength", 0f, 0.5f);
	}

	private bool TryGetRopeBounds(out Bounds bounds)
	{
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0114: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		//IL_0121: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_012f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: 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_0142: 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_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_0157: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)ropeMesh) && Object.op_Implicit((Object)(object)ropeMesh.sharedMesh))
		{
			rope = ((Component)ropeMesh).transform;
			bounds = ropeMesh.sharedMesh.bounds;
			return true;
		}
		bounds = default(Bounds);
		if (!Object.op_Implicit((Object)(object)skinnedRope) || !Object.op_Implicit((Object)(object)skinnedRope.sharedMesh))
		{
			return false;
		}
		Transform rootBone = skinnedRope.rootBone;
		Transform[] bones = skinnedRope.bones;
		rope = (Object.op_Implicit((Object)(object)rootBone) ? rootBone.parent : null);
		if (!Object.op_Implicit((Object)(object)rope) || ((Object)rope).name != "RopeRig" || bones.Length < 2 || Array.Exists(bones, (Transform bone) => !Object.op_Implicit((Object)(object)bone) || !bone.IsChildOf(rope)))
		{
			return false;
		}
		Vector3 position = bones[^1].position;
		Vector3 position2 = bones[^2].position;
		Vector3 val = rope.InverseTransformPoint(position + (position - position2));
		bounds = new Bounds(Vector3.zero, Vector3.zero);
		((Bounds)(ref bounds)).Encapsulate(val);
		ropeCollider = ((Component)ropeRoot).GetComponent<BoxCollider>();
		if (preserveBend)
		{
			ropeBones = bones;
			sampledBonePositions = (Vector3[])(object)new Vector3[bones.Length];
			jointPositions = (Vector3[])(object)new Vector3[bones.Length];
		}
		skinnedRope.updateWhenOffscreen = true;
		return true;
	}

	public void SetRinging(bool value)
	{
		ringing = value;
	}

	public void RemoveExtension()
	{
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		if (bendApplied)
		{
			for (int i = 1; i < ropeBones.Length; i++)
			{
				ropeBones[i].localPosition = sampledBonePositions[i];
			}
			bendApplied = false;
		}
		if (extensionApplied)
		{
			rope.localScale = sampledScale;
			extensionApplied = false;
		}
	}

	public void ApplyExtension(bool animatedPose = false)
	{
		//IL_00c2: 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_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_012b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: 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_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: 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)
		//IL_0154: 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)
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_016e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0173: Unknown result type (might be due to invalid IL or missing references)
		//IL_0194: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Unknown result type (might be due to invalid IL or missing references)
		//IL_0198: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		if (!ready || !Object.op_Implicit((Object)(object)skinnedRope) || extensionApplied || extension == 1f)
		{
			return;
		}
		bool flag = animatedPose && ropeBones != null && extension > 1f;
		if (flag)
		{
			for (int i = 1; i < ropeBones.Length; i++)
			{
				sampledBonePositions[i] = ropeBones[i].localPosition;
				jointPositions[i] = rope.InverseTransformPoint(ropeBones[i].position);
			}
		}
		sampledScale = rope.localScale;
		Vector3 localScale = sampledScale;
		int num = lengthAxis;
		((Vector3)(ref localScale))[num] = ((Vector3)(ref localScale))[num] * extension;
		rope.localScale = localScale;
		extensionApplied = true;
		if (flag)
		{
			Vector3 val = rope.InverseTransformPoint(ropeBones[0].position);
			float num2 = Mathf.Sqrt(extension);
			for (int j = 1; j < ropeBones.Length; j++)
			{
				Vector3 val2 = jointPositions[j] - val;
				float num3 = ((Vector3)(ref val2))[lengthAxis];
				val2 *= num2;
				((Vector3)(ref val2))[lengthAxis] = num3;
				ropeBones[j].position = rope.TransformPoint(val + val2);
			}
			bendApplied = true;
		}
	}

	private void ResizeRopeCollider()
	{
		//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_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0065: 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_0082: 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_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_009f: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)ropeCollider))
		{
			Transform transform = ((Component)ropeCollider).transform;
			Vector3 val = transform.InverseTransformPoint(rope.TransformPoint(topInMesh));
			Vector3 val2 = transform.InverseTransformPoint(rope.TransformPoint(bottomInMesh));
			Vector3 size = ropeCollider.size;
			size.z = Mathf.Abs(val.z - val2.z);
			ropeCollider.center = (val + val2) * 0.5f;
			ropeCollider.size = size;
		}
	}

	private void AdjustLength()
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: 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_0058: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_018f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0194: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0220: 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_0234: Unknown result type (might be due to invalid IL or missing references)
		//IL_023c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0241: Unknown result type (might be due to invalid IL or missing references)
		//IL_0246: Unknown result type (might be due to invalid IL or missing references)
		//IL_024b: Unknown result type (might be due to invalid IL or missing references)
		if (ringing)
		{
			return;
		}
		Vector3 val = rope.TransformPoint(topInMesh);
		float num = val.y - rope.TransformPoint(bottomInMesh).y;
		if (num < 0.001f)
		{
			return;
		}
		int num2;
		while (true)
		{
			num2 = Physics.RaycastNonAlloc(val, Vector3.down, hits, 30f, -5, (QueryTriggerInteraction)1);
			if (num2 == hits.Length)
			{
				Array.Resize(ref hits, hits.Length * 2);
				bool flag = true;
				continue;
			}
			break;
		}
		float num3 = float.PositiveInfinity;
		for (int i = 0; i < num2; i++)
		{
			RaycastHit val2 = hits[i];
			if (!((RaycastHit)(ref val2)).transform.IsChildOf(((Component)this).transform) && !Object.op_Implicit((Object)(object)((Component)((RaycastHit)(ref val2)).collider).GetComponentInParent<Character>()) && ((RaycastHit)(ref val2)).distance < num3)
			{
				num3 = ((RaycastHit)(ref val2)).distance;
			}
		}
		if (Object.op_Implicit((Object)(object)skinnedRope))
		{
			float num4 = num / extension;
			extension = (float.IsPositiveInfinity(num3) ? 1f : (Mathf.Max(0.05f, num3 - 0.15f) / num4));
			RemoveExtension();
			ApplyExtension();
			ResizeRopeCollider();
			return;
		}
		float num5 = ((Vector3)(ref originalScale))[lengthAxis];
		Vector3 localScale = rope.localScale;
		float num6 = num * Mathf.Abs(num5 / ((Vector3)(ref localScale))[lengthAxis]);
		if (!float.IsPositiveInfinity(num3))
		{
			num6 = Mathf.Max(0.05f, num3 - 0.15f);
		}
		if (!(Mathf.Abs(num6 - num) < 0.005f))
		{
			Vector3 localScale2 = rope.localScale;
			int num7 = lengthAxis;
			((Vector3)(ref localScale2))[num7] = ((Vector3)(ref localScale2))[num7] * (num6 / num);
			rope.localScale = localScale2;
			Transform obj = rope;
			obj.position += val - rope.TransformPoint(topInMesh);
		}
	}
}
internal sealed class BellStrikePreview : MonoBehaviour
{
	[SerializeField]
	private AnimationClip swing;

	[SerializeField]
	private AudioSource strike;

	[SerializeField]
	private int audioStartFrame;

	private PlayableGraph graph;

	private AnimationClipPlayable motion;

	private Animation legacyAnimation;

	private AnimationState legacyState;

	private bool playing;

	private BellRopeLength rope;

	internal float Duration => Mathf.Max(swing.length, (float)(audioStartFrame - 1) / swing.frameRate + strike.clip.length);

	public void Configure(AnimationClip animationClip, AudioSource audioSource, int soundStartFrame)
	{
		swing = animationClip;
		strike = audioSource;
		audioStartFrame = soundStartFrame;
	}

	public bool TryStrike()
	{
		return TryStrikeAfter(-0.1);
	}

	internal bool TryStrikeAfter(double elapsed)
	{
		ZNetView component = ((Component)this).GetComponent<ZNetView>();
		if (playing || !Object.op_Implicit((Object)(object)swing) || !Object.op_Implicit((Object)(object)strike) || !Object.op_Implicit((Object)(object)strike.clip) || !Object.op_Implicit((Object)(object)component) || !component.IsValid())
		{
			return false;
		}
		((MonoBehaviour)this).StartCoroutine(PlayRingSequence(AudioSettings.dspTime - elapsed));
		return true;
	}

	private IEnumerator PlayRingSequence(double started)
	{
		if (swing.legacy)
		{
			legacyAnimation = ((Component)this).GetComponent<Animation>();
			if (!Object.op_Implicit((Object)(object)legacyAnimation))
			{
				yield break;
			}
			((Behaviour)legacyAnimation).enabled = true;
			legacyAnimation.playAutomatically = false;
			if (!Object.op_Implicit((Object)(object)legacyAnimation.GetClip(((Object)swing).name)))
			{
				legacyAnimation.AddClip(swing, ((Object)swing).name);
			}
			legacyState = legacyAnimation[((Object)swing).name];
			legacyState.speed = 0f;
			legacyState.wrapMode = (WrapMode)8;
			legacyAnimation.Play(((Object)swing).name);
		}
		else
		{
			Animator animator = ((Component)this).GetComponent<Animator>() ?? ((Component)this).gameObject.AddComponent<Animator>();
			animator.cullingMode = (AnimatorCullingMode)0;
			graph = PlayableGraph.Create("Moonforged Bells");
			((PlayableGraph)(ref graph)).SetTimeUpdateMode((DirectorUpdateMode)3);
			motion = AnimationClipPlayable.Create(graph, swing);
			PlayableExtensions.SetSpeed<AnimationClipPlayable>(motion, 0.0);
			PlayableOutputExtensions.SetSourcePlayable<AnimationPlayableOutput, AnimationClipPlayable>(AnimationPlayableOutput.Create(graph, "Bell", animator), motion);
			((PlayableGraph)(ref graph)).Play();
		}
		playing = true;
		rope = ((Component)this).GetComponent<BellRopeLength>();
		if (Object.op_Implicit((Object)(object)rope))
		{
			rope.SetRinging(value: true);
		}
		yield return PlayTimedStrike(started);
		SetPose(swing.length, extendRope: false);
		if (swing.legacy)
		{
			legacyAnimation.Stop();
			((Behaviour)legacyAnimation).enabled = false;
		}
		else
		{
			((PlayableGraph)(ref graph)).Destroy();
		}
		if (Object.op_Implicit((Object)(object)rope))
		{
			rope.ApplyExtension();
			rope.SetRinging(value: false);
		}
		playing = false;
	}

	private IEnumerator PlayTimedStrike(double started)
	{
		double audioOffset = (double)(audioStartFrame - 1) / (double)swing.frameRate;
		double audioStart = started + audioOffset;
		double scheduled = Math.Max(AudioSettings.dspTime + 0.02, audioStart);
		double seek = scheduled - audioStart;
		if (seek < (double)strike.clip.length)
		{
			strike.time = (float)seek;
			strike.PlayScheduled(scheduled);
		}
		double duration = Duration;
		while (true)
		{
			double elapsed = AudioSettings.dspTime - started;
			SetPose(Mathf.Clamp((float)elapsed, 0f, swing.length));
			if (elapsed >= duration)
			{
				break;
			}
			yield return null;
		}
	}

	private void SetPose(float time, bool extendRope = true)
	{
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)rope))
		{
			rope.RemoveExtension();
		}
		if (swing.legacy)
		{
			legacyState.time = Mathf.Min(time, swing.length);
			legacyAnimation.Sample();
		}
		else
		{
			PlayableExtensions.SetTime<AnimationClipPlayable>(motion, (double)Mathf.Min(time, swing.length));
			((PlayableGraph)(ref graph)).Evaluate(0f);
		}
		if (extendRope && Object.op_Implicit((Object)(object)rope))
		{
			rope.ApplyExtension(animatedPose: true);
		}
	}

	private void OnDisable()
	{
		if (playing)
		{
			((MonoBehaviour)this).StopAllCoroutines();
			strike.Stop();
			if (swing.legacy)
			{
				SetPose(0f, extendRope: false);
				legacyAnimation.Stop();
				((Behaviour)legacyAnimation).enabled = false;
			}
			else if (((PlayableGraph)(ref graph)).IsValid())
			{
				SetPose(0f, extendRope: false);
				((PlayableGraph)(ref graph)).Destroy();
			}
			if (Object.op_Implicit((Object)(object)rope))
			{
				rope.ApplyExtension();
				rope.SetRinging(value: false);
			}
			playing = false;
		}
	}
}
internal sealed class BellPreviewInteraction : MonoBehaviour, Interactable, Hoverable
{
	[SerializeField]
	private BellStrikePreview bell;

	[SerializeField]
	private string displayName;

	[SerializeField]
	private string interactionLabel;

	[SerializeField]
	private ControllerBell linkedBell;

	private bool RemoteOnly => Object.op_Implicit((Object)(object)linkedBell) && linkedBell.Linked;

	public void Configure(BellStrikePreview preview, string name, string label)
	{
		bell = preview;
		displayName = name;
		interactionLabel = label;
		linkedBell = ((Component)preview).GetComponent<ControllerBell>();
	}

	public float GetHoverOffset()
	{
		return 0f;
	}

	public string GetHoverName()
	{
		return displayName;
	}

	public string GetHoverText()
	{
		return RemoteOnly ? (displayName + "\nControlled by a nearby wall button") : (displayName + "\n[<color=yellow><b>E</b></color>] " + interactionLabel);
	}

	public bool Interact(Humanoid user, bool hold, bool alt)
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		return !hold && !RemoteOnly && user is Player && Object.op_Implicit((Object)(object)bell) && PrivateArea.CheckAccess(((Component)bell).transform.position, 0f, true, false) && bell.TryStrike();
	}

	public bool UseItem(Humanoid user, ItemData item)
	{
		return false;
	}
}
[BepInPlugin("Moonforged.Bells", "Moonforged Bells", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class MoonforgedBellsPlugin : BaseUnityPlugin
{
	public const string PluginGuid = "Moonforged.Bells";

	public const string PluginName = "Moonforged Bells";

	public const string PluginVersion = "1.0.0";

	private const string SmallChurchBellPrefabName = "M_Church_Bell_2m";

	private const string SmallChurchBellClipAssetName = "Assets/Moonforged Bells/Models/Ding Dong bell/Churchbell4_Three_Strikes_Extended_Decay.ogg";

	private const string SwingBellPrefabName = "M_Church_Bell_4m";

	private const string SwingBellClipAssetName = "Hells_Bell_4m_Three_Strikes.ogg";

	private const string LargeChurchBellPrefabName = "M_Church_Bell_6m";

	private const string LargeChurchBellClipAssetName = "Assets/Moonforged Bells/Models/Church Bell/model2/Churchbell3_Three_Strikes.ogg";

	private const string GreatBellPrefabName = "M_Great_Bell";

	private const string DoorBellPrefabName = "M_Door_Bell";

	private const string ControllerPrefabName = "M_Controler";

	private const string ControllerClickAssetName = "Assets/Moonforged Bells/Sound/button.ogg";

	private const string ChurchBellSoundPrefabName = "sfx_Hells_Bell";

	private const string GreatBellSoundPrefabName = "sfx_Great_Bell";

	private const int GreatBellImpactFrame = 48;

	private const int DoorBellAudioStartFrame = 1;

	private AssetBundle bundle;

	private ConfigEntry<bool> smallChurchBellEnabledInHammer;

	private ConfigEntry<bool> swingBellEnabledInHammer;

	private ConfigEntry<bool> largeChurchBellEnabledInHammer;

	private ConfigEntry<bool> greatBellEnabledInHammer;

	private ConfigEntry<bool> doorBellEnabledInHammer;

	private string hammerTab;

	private ConfigEntry<bool> playerDetection;

	private ConfigEntry<bool> linkControllers;

	private ConfigEntry<float> linkRange;

	private ConfigEntry<float> detectionRange;

	private ConfigEntry<float> controllerLinkRange;

	private bool registrationStarted;

	private void Awake()
	{
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b1: Expected O, but got Unknown
		//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Expected O, but got Unknown
		//IL_0229: Unknown result type (might be due to invalid IL or missing references)
		//IL_0233: Expected O, but got Unknown
		bundle = LoadEmbeddedBundle();
		if (!Object.op_Implicit((Object)(object)bundle))
		{
			((BaseUnityPlugin)this).Logger.LogError((object)"Could not load the embedded bells bundle.");
			return;
		}
		smallChurchBellEnabledInHammer = ((BaseUnityPlugin)this).Config.Bind<bool>("Pieces", "M_Church_Bell_2m", true, "Show the 2 m Church Bell in the hammer menu. Restart Valheim to apply. Existing bells stay registered. Local setting.");
		swingBellEnabledInHammer = ((BaseUnityPlugin)this).Config.Bind<bool>("Pieces", "M_Church_Bell_4m", true, "Show the church bell in the hammer menu. Restart Valheim to apply. Existing bells stay registered. Local setting.");
		largeChurchBellEnabledInHammer = ((BaseUnityPlugin)this).Config.Bind<bool>("Pieces", "M_Church_Bell_6m", true, "Show the 6 m Church Bell in the hammer menu. Restart Valheim to apply. Existing bells stay registered. Local setting.");
		greatBellEnabledInHammer = ((BaseUnityPlugin)this).Config.Bind<bool>("Pieces", "M_Great_Bell", true, "Show the Great Bell in the hammer menu. Restart Valheim to apply. Existing bells stay registered. Local setting.");
		doorBellEnabledInHammer = ((BaseUnityPlugin)this).Config.Bind<bool>("Pieces", "M_Door_Bell", true, "Show the Door Bell in the hammer menu. Restart Valheim to apply. Existing bells stay registered. Local setting.");
		hammerTab = ((BaseUnityPlugin)this).Config.Bind<string>("Categories", "CustomHammerTab", "Moonforged Bells", "Hammer tab for Moonforged Bells pieces. Restart Valheim to apply.").Value.Trim();
		if (string.IsNullOrWhiteSpace(hammerTab))
		{
			hammerTab = "Moonforged Bells";
		}
		PieceManager.Instance.AddPieceCategory(hammerTab);
		playerDetection = ((BaseUnityPlugin)this).Config.Bind<bool>("Controller", "PlayerDetection", true, "Ring a linked bell group once when a player enters the detection range of a controller.");
		linkControllers = ((BaseUnityPlugin)this).Config.Bind<bool>("Controller", "LinkNearbyControllers", false, "Let nearby controllers operate one shared group of bells.");
		linkRange = ((BaseUnityPlugin)this).Config.Bind<float>("Controller", "LinkRange", 15f, new ConfigDescription("Maximum distance in metres between a bell and a controller.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
		detectionRange = ((BaseUnityPlugin)this).Config.Bind<float>("Controller", "PlayerDetectionRange", 25f, new ConfigDescription("Player detection radius in metres around each controller.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 150f), Array.Empty<object>()));
		controllerLinkRange = ((BaseUnityPlugin)this).Config.Bind<float>("Controller", "ControllerLinkRange", linkRange.Value, new ConfigDescription("Maximum distance in metres between controllers when linking is enabled.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 150f), Array.Empty<object>()));
		PrefabManager.OnPrefabsRegistered += OnPrefabsRegistered;
	}

	private void OnPrefabsRegistered()
	{
		if (!registrationStarted)
		{
			registrationStarted = true;
			((MonoBehaviour)this).StartCoroutine(RegisterWhenSceneIsReady());
		}
	}

	private IEnumerator RegisterWhenSceneIsReady()
	{
		while (!Object.op_Implicit((Object)(object)ZNetScene.instance))
		{
			yield return null;
		}
		RegisterBell("M_Church_Bell_6m", "6 m Church Bell", "sfx_Hells_Bell", largeChurchBellEnabledInHammer.Value, 1, "Assets/Moonforged Bells/Models/Church Bell/model2/Churchbell3_Three_Strikes.ogg", true, ("Bronze", 15), ("Tin", 10));
		RegisterBell("M_Church_Bell_4m", "4 m Church Bell", "sfx_Hells_Bell", swingBellEnabledInHammer.Value, 1, "Hells_Bell_4m_Three_Strikes.ogg", true, ("Iron", 10), ("Copper", 5));
		RegisterBell("M_Church_Bell_2m", "2 m Church Bell", "sfx_Hells_Bell", smallChurchBellEnabledInHammer.Value, 1, "Assets/Moonforged Bells/Models/Ding Dong bell/Churchbell4_Three_Strikes_Extended_Decay.ogg", true, ("Silver", 10), ("Iron", 5));
		RegisterBell("M_Door_Bell", "Door Bell", "sfx_Hells_Bell", doorBellEnabledInHammer.Value, 1, "M_Door_Bell.ogg", false, ("Tin", 2));
		RegisterBell("M_Great_Bell", "Great Bell", "sfx_Great_Bell", greatBellEnabledInHammer.Value, 48, "Assets/Moonforged Bells/Models/Great Bell/sounffx/Great_Bell.ogg", false, ("RoundLog", 10), ("Copper", 20), ("Wood", 10));
		RegisterController();
	}

	private void OnDestroy()
	{
		PrefabManager.OnPrefabsRegistered -= OnPrefabsRegistered;
		ReleaseBundle();
	}

	private void ReleaseBundle()
	{
		if (Object.op_Implicit((Object)(object)bundle))
		{
			bundle.Unload(false);
			bundle = null;
		}
	}

	private static AssetBundle LoadEmbeddedBundle()
	{
		Assembly assembly = typeof(MoonforgedBellsPlugin).Assembly;
		using Stream stream = assembly.GetManifestResourceStream("Moonforged.Bells.bells");
		if (stream == null)
		{
			return null;
		}
		using MemoryStream memoryStream = new MemoryStream();
		stream.CopyTo(memoryStream);
		return AssetBundle.LoadFromMemory(memoryStream.ToArray());
	}

	private void RegisterBell(string prefabName, string displayName, string soundPrefabName, bool enabled, int audioStartFrame, string clipAssetName, bool useRope, params (string Item, int Amount)[] requirements)
	{
		GameObject val = bundle.LoadAsset<GameObject>(prefabName);
		Animation val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<Animation>() : null);
		AudioClip val3 = bundle.LoadAsset<AudioClip>(clipAssetName);
		if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val2) || !Object.op_Implicit((Object)(object)val2.clip) || !Object.op_Implicit((Object)(object)val3))
		{
			((BaseUnityPlugin)this).Logger.LogError((object)$"Could not register {prefabName}. Prefab found: {Object.op_Implicit((Object)(object)val)}. Root animation clip found: {Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val2.clip)}. Audio clip {clipAssetName} found: {Object.op_Implicit((Object)(object)val3)}.");
			return;
		}
		AudioSource val4 = FindAudioTemplate(soundPrefabName);
		if (!Object.op_Implicit((Object)(object)val4) && soundPrefabName != "sfx_Great_Bell")
		{
			val4 = FindAudioTemplate("sfx_Great_Bell");
		}
		AnimationClip clip = val2.clip;
		val2.playAutomatically = false;
		((Behaviour)val2).enabled = false;
		AudioSource audioSource = AddStrikeSource(val, val4, val3);
		int num = LayerMask.NameToLayer("piece");
		if (num >= 0)
		{
			Transform[] componentsInChildren = val.GetComponentsInChildren<Transform>(true);
			foreach (Transform val5 in componentsInChildren)
			{
				((Component)val5).gameObject.layer = num;
			}
		}
		val3.LoadAudioData();
		ZNetView val6 = val.GetComponent<ZNetView>() ?? val.AddComponent<ZNetView>();
		val6.m_persistent = true;
		val6.m_syncInitialScale = true;
		ZSyncTransform val7 = val.GetComponent<ZSyncTransform>() ?? val.AddComponent<ZSyncTransform>();
		val7.m_syncPosition = false;
		val7.m_syncRotation = false;
		val7.m_syncScale = true;
		val7.m_syncBodyVelocity = false;
		val7.m_characterParentSync = false;
		GameObject val8 = ZNetScene.instance.GetPrefab("iron_grate") ?? PrefabManager.Instance.GetPrefab("iron_grate");
		Piece val9 = (Object.op_Implicit((Object)(object)val8) ? val8.GetComponent<Piece>() : null);
		WearNTear val10 = (Object.op_Implicit((Object)(object)val8) ? val8.GetComponent<WearNTear>() : null);
		Piece val11 = val.GetComponent<Piece>() ?? val.AddComponent<Piece>();
		val11.m_name = displayName;
		val11.m_description = (useRope ? "Pull the rope to ring the bell three times." : "Interact with the bell to strike it.");
		val11.m_groundOnly = false;
		val11.m_icon = bundle.LoadAsset<Sprite>("Assets/Moonforged Bells Icons/" + prefabName + ".png");
		EffectList placeEffect2;
		if (Object.op_Implicit((Object)(object)val9))
		{
			EffectList placeEffect = val9.m_placeEffect;
			if (placeEffect != null && placeEffect.m_effectPrefabs?.Length > 0)
			{
				placeEffect2 = val9.m_placeEffect;
				goto IL_02d6;
			}
		}
		placeEffect2 = BuildSoundEffect("sfx_build_hammer_metal");
		goto IL_02d6;
		IL_02d6:
		val11.m_placeEffect = placeEffect2;
		WearNTear val12 = val.GetComponent<WearNTear>() ?? val.AddComponent<WearNTear>();
		val12.m_health = 1000f;
		val12.m_noRoofWear = true;
		EffectList destroyedEffect2;
		if (Object.op_Implicit((Object)(object)val10))
		{
			EffectList destroyedEffect = val10.m_destroyedEffect;
			if (destroyedEffect != null && destroyedEffect.m_effectPrefabs?.Length > 0)
			{
				destroyedEffect2 = val10.m_destroyedEffect;
				goto IL_0364;
			}
		}
		destroyedEffect2 = BuildSoundEffect("sfx_metal_blocked");
		goto IL_0364;
		IL_0364:
		val12.m_destroyedEffect = destroyedEffect2;
		if (useRope)
		{
			ConfigureChurchBellRope(val);
		}
		BellStrikePreview bellStrikePreview = val.AddComponent<BellStrikePreview>();
		bellStrikePreview.Configure(clip, audioSource, audioStartFrame);
		if (useRope)
		{
			Transform val13 = Array.Find(val.GetComponentsInChildren<Transform>(true), (Transform child) => ((Object)child).name == "Rope");
			if (Object.op_Implicit((Object)(object)val13))
			{
				int size = ((prefabName == "M_Church_Bell_2m") ? 2 : ((prefabName == "M_Church_Bell_4m") ? 4 : 6));
				val.AddComponent<ControllerBell>().Configure(((Component)val13).gameObject, bellStrikePreview, size);
			}
		}
		Collider[] componentsInChildren2 = val.GetComponentsInChildren<Collider>(true);
		BellPreviewInteraction bellPreviewInteraction = default(BellPreviewInteraction);
		foreach (Collider val14 in componentsInChildren2)
		{
			if (!((Component)val14).TryGetComponent<BellPreviewInteraction>(ref bellPreviewInteraction))
			{
				bellPreviewInteraction = ((Component)val14).gameObject.AddComponent<BellPreviewInteraction>();
			}
			bellPreviewInteraction.Configure(bellStrikePreview, displayName, useRope ? "Pull rope" : "Strike bell");
		}
		AddBuildPiece(val, prefabName, enabled, requirements);
	}

	private void AddBuildPiece(GameObject prefab, string prefabName, bool enabled, (string Item, int Amount)[] defaults)
	{
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01af: Expected O, but got Unknown
		//IL_0248: Unknown result type (might be due to invalid IL or missing references)
		//IL_0252: Expected O, but got Unknown
		string text = ((BaseUnityPlugin)this).Config.Bind<string>("Bell Hammer Tabs", prefabName, "", "Hammer tab override. Leave blank to use CustomHammerTab. Restart Valheim to apply.").Value.Trim();
		if (string.IsNullOrEmpty(text))
		{
			text = hammerTab;
		}
		else if (text != hammerTab)
		{
			PieceManager.Instance.AddPieceCategory(text);
		}
		string text2 = string.Join(", ", Array.ConvertAll(defaults, ((string Item, int Amount) item) => $"{item.Item}:{item.Amount}"));
		string value = ((BaseUnityPlugin)this).Config.Bind<string>("Bell Recipes", prefabName, text2, "Comma-separated item prefab IDs and quantities, e.g. Iron:10, Copper:5. Restart Valheim to apply.").Value;
		List<(string, int)> list = new List<(string, int)>();
		ObjectDB instance = ObjectDB.instance;
		HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
		string[] array = value.Split(new char[1] { ',' });
		foreach (string text3 in array)
		{
			string[] array2 = text3.Split(new char[1] { ':' });
			string text4 = array2[0].Trim();
			if (array2.Length != 2 || string.IsNullOrEmpty(text4) || !int.TryParse(array2[1], out var result) || result < 1 || !hashSet.Add(text4) || (Object.op_Implicit((Object)(object)instance) && !Object.op_Implicit((Object)(object)instance.GetItemPrefab(text4))))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Invalid recipe for " + prefabName + "; using its default recipe."));
				list.Clear();
				list.AddRange(defaults);
				break;
			}
			list.Add((text4, result));
		}
		PieceConfig val = new PieceConfig();
		val.Enabled = enabled;
		val.PieceTable = PieceTables.Hammer;
		val.Category = text;
		val.CraftingStation = CraftingStations.Forge;
		val.Usage = new string[1] { PieceUsages.Decor };
		PieceConfig val2 = val;
		foreach (var (text5, num2) in list)
		{
			val2.AddRequirement(text5, num2, true);
		}
		if (!PieceManager.Instance.AddPiece(new CustomPiece(prefab, false, val2)))
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Could not register " + prefabName + "."));
		}
	}

	private void RegisterController()
	{
		GameObject val = bundle.LoadAsset<GameObject>("M_Controler");
		if (!Object.op_Implicit((Object)(object)val))
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"The bells bundle does not yet contain M_Controler. Rope operation is available.");
			return;
		}
		ZNetView val2 = val.GetComponent<ZNetView>() ?? val.AddComponent<ZNetView>();
		val2.m_persistent = true;
		GameObject val3 = ZNetScene.instance.GetPrefab("iron_grate") ?? PrefabManager.Instance.GetPrefab("iron_grate");
		Piece val4 = (Object.op_Implicit((Object)(object)val3) ? val3.GetComponent<Piece>() : null);
		WearNTear val5 = (Object.op_Implicit((Object)(object)val3) ? val3.GetComponent<WearNTear>() : null);
		Piece val6 = val.GetComponent<Piece>() ?? val.AddComponent<Piece>();
		val6.m_name = "Bell Controller";
		val6.m_description = (playerDetection.Value ? "Hides the ropes on nearby church bells and enables player detection. Press to toggle a repeating chime." : "Hides the ropes on nearby church bells. Press to toggle a repeating chime.");
		val6.m_groundOnly = false;
		Sprite val7 = bundle.LoadAsset<Sprite>("Assets/Moonforged Bells Icons/M_Controler.png");
		if (Object.op_Implicit((Object)(object)val7))
		{
			val6.m_icon = val7;
		}
		EffectList placeEffect2;
		if (Object.op_Implicit((Object)(object)val4))
		{
			EffectList placeEffect = val4.m_placeEffect;
			if (placeEffect != null && placeEffect.m_effectPrefabs?.Length > 0)
			{
				placeEffect2 = val4.m_placeEffect;
				goto IL_0166;
			}
		}
		placeEffect2 = BuildSoundEffect("sfx_build_hammer_metal");
		goto IL_0166;
		IL_0166:
		val6.m_placeEffect = placeEffect2;
		WearNTear val8 = val.GetComponent<WearNTear>() ?? val.AddComponent<WearNTear>();
		val8.m_noRoofWear = true;
		EffectList destroyedEffect2;
		if (Object.op_Implicit((Object)(object)val5))
		{
			EffectList destroyedEffect = val5.m_destroyedEffect;
			if (destroyedEffect != null && destroyedEffect.m_effectPrefabs?.Length > 0)
			{
				destroyedEffect2 = val5.m_destroyedEffect;
				goto IL_01e8;
			}
		}
		destroyedEffect2 = BuildSoundEffect("sfx_metal_blocked");
		goto IL_01e8;
		IL_01e8:
		val8.m_destroyedEffect = destroyedEffect2;
		Transform val9 = Array.Find(val.GetComponentsInChildren<Transform>(true), (Transform child) => ((Object)child).name == "Button");
		Renderer[] renderers = (Object.op_Implicit((Object)(object)val9) ? ((Component)val9).GetComponentsInChildren<Renderer>(true) : Array.Empty<Renderer>());
		AudioClip val10 = bundle.LoadAsset<AudioClip>("Assets/Moonforged Bells/Sound/button.ogg");
		AudioSource val11 = null;
		if (Object.op_Implicit((Object)(object)val10))
		{
			val10.LoadAudioData();
			val11 = AddStrikeSource(Object.op_Implicit((Object)(object)val9) ? ((Component)val9).gameObject : val, null, val10);
			val11.maxDistance = 10f;
		}
		else
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"The bells bundle does not contain Assets/Moonforged Bells/Sound/button.ogg. The controller will toggle silently.");
		}
		BellController bellController = val.AddComponent<BellController>();
		bellController.Configure(renderers, val11, playerDetection.Value, linkControllers.Value, linkRange.Value, detectionRange.Value, controllerLinkRange.Value);
		int num = LayerMask.NameToLayer("piece");
		Transform[] componentsInChildren = val.GetComponentsInChildren<Transform>(true);
		foreach (Transform val12 in componentsInChildren)
		{
			if (num >= 0)
			{
				((Component)val12).gameObject.layer = num;
			}
		}
		Collider[] componentsInChildren2 = val.GetComponentsInChildren<Collider>(true);
		if (componentsInChildren2.Length == 0)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"M_Controler has no interaction collider.");
		}
		Collider[] array = componentsInChildren2;
		foreach (Collider val13 in array)
		{
			if (!Object.op_Implicit((Object)(object)((Component)val13).GetComponent<ControllerInteraction>()))
			{
				((Component)val13).gameObject.AddComponent<ControllerInteraction>().Configure(bellController);
			}
		}
		bool value = ((BaseUnityPlugin)this).Config.Bind<bool>("Pieces", "M_Controler", true, "Show the controller in the hammer menu. Restart Valheim to apply.").Value;
		AddBuildPiece(val, "M_Controler", value, new(string, int)[2]
		{
			("Bronze", 2),
			("Wood", 1)
		});
	}

	private AudioSource FindAudioTemplate(string prefabName)
	{
		GameObject val = bundle.LoadAsset<GameObject>(prefabName);
		return Object.op_Implicit((Object)(object)val) ? val.GetComponent<AudioSource>() : null;
	}

	private static AudioSource AddStrikeSource(GameObject bell, AudioSource template, AudioClip clip)
	{
		//IL_00a1: 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_00bb: Invalid comparison between Unknown and I4
		AudioSource val = bell.AddComponent<AudioSource>();
		val.clip = clip;
		val.outputAudioMixerGroup = (Object.op_Implicit((Object)(object)template) ? template.outputAudioMixerGroup : null);
		val.volume = (Object.op_Implicit((Object)(object)template) ? template.volume : 1f);
		val.pitch = 1f;
		val.dopplerLevel = 0f;
		val.minDistance = (Object.op_Implicit((Object)(object)template) ? template.minDistance : 1f);
		val.maxDistance = (Object.op_Implicit((Object)(object)template) ? template.maxDistance : 40f);
		val.rolloffMode = (AudioRolloffMode)(Object.op_Implicit((Object)(object)template) ? ((int)template.rolloffMode) : 0);
		if (Object.op_Implicit((Object)(object)template) && (int)template.rolloffMode == 2)
		{
			val.SetCustomCurve((AudioSourceCurveType)0, template.GetCustomCurve((AudioSourceCurveType)0));
		}
		val.playOnAwake = false;
		val.loop = false;
		val.spatialBlend = 1f;
		return val;
	}

	private void ConfigureChurchBellRope(GameObject bell)
	{
		Transform val = Array.Find(bell.GetComponentsInChildren<Transform>(true), (Transform child) => ((Object)child).name == "Rope");
		MeshFilter val2 = (Object.op_Implicit((Object)(object)val) ? ((Component)val).GetComponent<MeshFilter>() : null);
		SkinnedMeshRenderer val3 = (Object.op_Implicit((Object)(object)val) ? (((Component)val).GetComponent<SkinnedMeshRenderer>() ?? ((Component)val).GetComponentInChildren<SkinnedMeshRenderer>(true)) : null);
		if (Object.op_Implicit((Object)(object)val3) && Object.op_Implicit((Object)(object)val3.sharedMesh))
		{
			bell.AddComponent<BellRopeLength>().Configure(val3, val, ((Object)bell).name == "M_Church_Bell_2m");
		}
		else if (Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val2.sharedMesh))
		{
			bell.AddComponent<BellRopeLength>().Configure(val2);
		}
		else
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"The church bell Rope child has no mesh for automatic length.");
		}
	}

	private EffectList BuildSoundEffect(string soundName)
	{
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Expected O, but got Unknown
		//IL_0065: 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_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Expected O, but got Unknown
		GameObject val = ZNetScene.instance.GetPrefab(soundName) ?? PrefabManager.Instance.GetPrefab(soundName);
		if (!Object.op_Implicit((Object)(object)val))
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not find the bell build sound " + soundName + "."));
		}
		EffectList val2 = new EffectList();
		val2.m_effectPrefabs = (EffectData[])((!Object.op_Implicit((Object)(object)val)) ? ((Array)Array.Empty<EffectData>()) : ((Array)new EffectData[1]
		{
			new EffectData
			{
				m_prefab = val,
				m_enabled = true
			}
		}));
		return val2;
	}
}
internal sealed class PlayerEntryTracker
{
	public const float RadiusMeters = 50f;

	public const int StrikesPerEntry = 3;

	private readonly Dictionary<long, bool> wasInside = new Dictionary<long, bool>();

	public bool Observe(long playerId, float squaredDistance)
	{
		bool flag = squaredDistance <= 2500f;
		bool value;
		bool result = wasInside.TryGetValue(playerId, out value) && !value && flag;
		wasInside[playerId] = flag;
		return result;
	}

	public void Forget(long playerId)
	{
		wasInside.Remove(playerId);
	}
}