Decompiled source of CharmGoblet v1.0.0

CharmGoblet.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using CharmCore.Api;
using CharmGoblet.Domain;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("Osmar Briones")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+5f0020dccb23895301d170d69d9fcee593c43aa4")]
[assembly: AssemblyProduct("CharmGoblet")]
[assembly: AssemblyTitle("CharmGoblet")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CharmGoblet
{
	[BepInPlugin("com.osmar.CharmGoblet", "CharmGoblet", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class CharmGobletPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.osmar.CharmGoblet";

		public const string PluginName = "CharmGoblet";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Logger { get; private set; }

		internal static GobletCharm Charm { get; private set; }

		private void Awake()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			Logger = ((BaseUnityPlugin)this).Logger;
			((Component)this).gameObject.transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			Charm = new GobletCharm();
			CharmsApi.Register((Charm)(object)Charm, ((BaseUnityPlugin)this).Config);
			new Harmony("com.osmar.CharmGoblet").PatchAll();
			Logger.LogInfo((object)"CharmGoblet 1.0.0 loaded!");
		}
	}
	internal sealed class GobletCharm : Charm
	{
		internal const string PrefabName = "Valuable Manor Goblet";

		public override string? Description => HealingChaliceText.Describe(HealPercentOfMaxHealth.Value, RadiusMeters.Value);

		internal CharmSetting HealPercentOfMaxHealth { get; }

		internal CharmSetting RadiusMeters { get; }

		internal GobletCharm()
			: base("Goblet", "Goblet - Healing Chalice", 20f, (float?)null, new string[1] { "Valuable Manor Goblet" })
		{
			((Charm)this).EnableCharge(240f);
			HealPercentOfMaxHealth = ((Charm)this).AddSetting("HealPercentOfMaxHealth", 100f, 0f, 100f, "Share of each player's maximum health restored at FULL charge when an extraction point completes (100 = all of it). A partly charged chalice restores that share in proportion to its charge. 0 turns the healing off. The result is rounded to a whole number of health points, never below 1.");
			RadiusMeters = ((Charm)this).AddSetting("RadiusMeters", 10f, 1f, 50f, "Distance in metres around the Goblet carrier within which other players are healed too. The carrier is always healed.");
		}

		protected override void OnLevelEnded()
		{
			HealingChalice.Reset();
		}
	}
	internal static class HealingChalice
	{
		private const float DuplicateWindowSeconds = 2f;

		private const float MinimumCharge = 0.01f;

		private static int lastCount = -1;

		private static float lastTime = -100f;

		internal static void Reset()
		{
			lastCount = -1;
			lastTime = -100f;
		}

		internal static void OnExtractionCompleted(GobletCharm charm, int completedCount)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (ChaliceMath.IsDuplicateCompletion(lastCount, lastTime, completedCount, realtimeSinceStartup, 2f))
			{
				if (((Charm)charm).DebugMode)
				{
					((Charm)charm).LogDebug($"Healing Chalice: repeated completion event ({completedCount}) ignored");
				}
				return;
			}
			lastCount = completedCount;
			lastTime = realtimeSinceStartup;
			float percent = charm.HealPercentOfMaxHealth.Value;
			float radius = charm.RadiusMeters.Value;
			if (percent <= 0f)
			{
				return;
			}
			Dictionary<PlayerAvatar, int> pending = new Dictionary<PlayerAvatar, int>();
			int carriers = 0;
			CharmsApi.ForEachCarrier((Charm)(object)charm, (Action<PlayerAvatar, ValuableObject>)delegate(PlayerAvatar carrier, ValuableObject valuable)
			{
				carriers++;
				float num = CharmsApi.ChargeOf(carrier, (Charm)(object)charm);
				if (num < 0.01f)
				{
					if (((Charm)charm).DebugMode)
					{
						((Charm)charm).LogDebug("Healing Chalice: carrier " + ((Object)carrier).name + " has no charge yet");
					}
				}
				else
				{
					int num2 = HealAround(carrier, percent * num, radius, pending, charm);
					if (num2 > 0)
					{
						((Charm)charm).WearValuable(valuable, ((Charm)charm).WearPercent);
						CharmsApi.ConsumeCharge((Charm)(object)charm, valuable);
					}
					if (((Charm)charm).DebugMode)
					{
						((Charm)charm).LogDebug($"Healing Chalice: carrier {((Object)carrier).name} charge {num * 100f:0}%, healed {num2} player(s)");
					}
				}
			});
			if (((Charm)charm).DebugMode)
			{
				((Charm)charm).LogDebug($"Healing Chalice: extraction {completedCount} completed, {carriers} carrier(s)");
			}
		}

		private static int HealAround(PlayerAvatar carrier, float percent, float radius, Dictionary<PlayerAvatar, int> pending, GobletCharm charm)
		{
			//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_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: 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_007f: 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_008b: 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_0099: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)carrier).transform.position;
			int num = 0;
			PlayerAvatar[] array = GameDirector.instance.PlayerList.ToArray();
			foreach (PlayerAvatar val in array)
			{
				if ((Object)(object)val == (Object)null || val.deadSet || val.isDisabled || (Object)(object)val.playerHealth == (Object)null)
				{
					continue;
				}
				bool num2 = (Object)(object)val == (Object)(object)carrier;
				Vector3 position2 = ((Component)val).transform.position;
				if (!num2 && !ChaliceMath.IsWithinRange(position.x, position.y, position.z, position2.x, position2.y, position2.z, radius))
				{
					continue;
				}
				PlayerHealth playerHealth = val.playerHealth;
				pending.TryGetValue(val, out var value);
				if (!ChaliceMath.NeedsHealing(playerHealth.health, playerHealth.maxHealth, value))
				{
					continue;
				}
				int num3 = ChaliceMath.HealAmount(playerHealth.maxHealth, percent);
				if (num3 > 0)
				{
					playerHealth.HealOther(num3, true);
					pending[val] = value + num3;
					num++;
					if (((Charm)charm).DebugMode)
					{
						((Charm)charm).LogDebug($"Healing Chalice: {((Object)val).name} healed by {num3} (health {playerHealth.health}/{playerHealth.maxHealth} before this heal)");
					}
				}
			}
			return num;
		}
	}
}
namespace CharmGoblet.Patches
{
	[HarmonyPatch(typeof(RoundDirector), "ExtractionCompleted")]
	internal static class RoundDirector_ExtractionCompleted_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(RoundDirector __instance)
		{
			if (SemiFunc.IsMasterClientOrSingleplayer())
			{
				HealingChalice.OnExtractionCompleted(CharmGobletPlugin.Charm, __instance.extractionPointsCompleted);
			}
		}
	}
}
namespace CharmGoblet.Domain
{
	internal static class ChaliceMath
	{
		internal static int HealAmount(int maxHealth, float percent)
		{
			if (maxHealth <= 0 || percent <= 0f)
			{
				return 0;
			}
			int num = (int)Math.Round((double)maxHealth * (double)percent / 100.0, MidpointRounding.AwayFromZero);
			if (num >= 1)
			{
				return num;
			}
			return 1;
		}

		internal static bool IsWithinRange(float ax, float ay, float az, float bx, float by, float bz, float radius)
		{
			if (radius < 0f)
			{
				return false;
			}
			double num = ax - bx;
			double num2 = ay - by;
			double num3 = az - bz;
			return num * num + num2 * num2 + num3 * num3 <= (double)radius * (double)radius;
		}

		internal static bool NeedsHealing(int health, int maxHealth, int pendingHeal)
		{
			if (health > 0 && maxHealth > 0)
			{
				return health + Math.Max(0, pendingHeal) < maxHealth;
			}
			return false;
		}

		internal static bool IsDuplicateCompletion(int lastCount, float lastTime, int count, float now, float windowSeconds)
		{
			if (lastCount == count && now >= lastTime)
			{
				return now - lastTime < windowSeconds;
			}
			return false;
		}
	}
	internal static class HealingChaliceText
	{
		internal static string? Describe(float healPercent, float radiusMetres)
		{
			if (!(healPercent <= 0f))
			{
				return "Charges over time. On extraction, heals you and allies within " + Number(radiusMetres) + " m, up to " + Number(healPercent) + "% health.";
			}
			return null;
		}

		private static string Number(float value)
		{
			return value.ToString("0.##", CultureInfo.InvariantCulture);
		}
	}
}