Decompiled source of DownedRevive v1.0.0

DownedRevive.dll

Decompiled an hour ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DownedRevive")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DownedRevive")]
[assembly: AssemblyTitle("DownedRevive")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 DownedRevive
{
	internal static class Downed
	{
		private const string KeyDown = "BR_Downed";

		private const string KeyEnd = "BR_DownedEnd";

		internal const string RpcRevive = "BR_Revive";

		internal const string RpcAnnounce = "BR_Announce";

		private static readonly FieldRef<Character, ZNetView> NViewRef = AccessTools.FieldRefAccess<Character, ZNetView>("m_nview");

		private static readonly MethodInfo CheckDeathMI = AccessTools.Method(typeof(Character), "CheckDeath", (Type[])null, (Type[])null);

		internal static bool AllowDeath;

		internal static float GraceUntil;

		internal static Player Target;

		internal static float ReviveProgress;

		internal static float GiveUpProgress;

		private static GameObject _pose;

		private static float _reviveHold;

		private static float _reviveCooldown;

		private static float _giveUpHold;

		private static float _noAllyTimer;

		internal static ZNetView NView(Character c)
		{
			if ((Object)(object)c == (Object)null)
			{
				return null;
			}
			ZNetView val = NViewRef.Invoke(c);
			if (!((Object)(object)val != (Object)null) || !val.IsValid())
			{
				return null;
			}
			return val;
		}

		internal static bool IsDowned(Character c)
		{
			ZNetView val = NView(c);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			ZDO zDO = val.GetZDO();
			if (zDO != null)
			{
				return zDO.GetBool("BR_Downed", false);
			}
			return false;
		}

		internal static double Now()
		{
			ZNet instance = ZNet.instance;
			if (!((Object)(object)instance != (Object)null))
			{
				return Time.timeAsDouble;
			}
			return instance.GetTimeSeconds();
		}

		internal static double Remaining(Player p)
		{
			ZNetView val = NView((Character)(object)p);
			if ((Object)(object)val == (Object)null)
			{
				return 0.0;
			}
			return (double)val.GetZDO().GetLong("BR_DownedEnd", 0L) / 1000.0 - Now();
		}

		internal static bool IsProtected(Character c)
		{
			Player val = (Player)(object)((c is Player) ? c : null);
			if (val != null && (Object)(object)val == (Object)(object)Player.m_localPlayer)
			{
				if (!IsDowned((Character)(object)val))
				{
					return Time.time < GraceUntil;
				}
				return true;
			}
			return false;
		}

		internal static bool ShouldDown(Player p)
		{
			if (!Plugin.Enabled.Value)
			{
				return false;
			}
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			if (!Plugin.TestMode.Value && instance.GetNrOfPlayers() <= 1)
			{
				return false;
			}
			if (!Plugin.TestMode.Value && AllLoadedAlliesOut(p, instance))
			{
				return false;
			}
			return true;
		}

		private static bool AllLoadedAlliesOut(Player p, ZNet znet)
		{
			int num = 0;
			int num2 = 0;
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (!((Object)(object)allPlayer == (Object)null) && !((Object)(object)allPlayer == (Object)(object)p))
				{
					num++;
					if (!((Character)allPlayer).IsDead() && !IsDowned((Character)(object)allPlayer))
					{
						num2++;
					}
				}
			}
			if (num > 0 && num == znet.GetNrOfPlayers() - 1)
			{
				return num2 == 0;
			}
			return false;
		}

		internal static bool TryBeginDown(Player p)
		{
			try
			{
				ZNetView val = NView((Character)(object)p);
				if ((Object)(object)val == (Object)null)
				{
					return false;
				}
				ZDO zDO = val.GetZDO();
				zDO.Set("BR_Downed", true);
				zDO.Set("BR_DownedEnd", (long)((Now() + (double)Plugin.DownedSeconds.Value) * 1000.0));
				((Character)p).SetHealth(Mathf.Max(1f, ((Character)p).GetMaxHealth() * 0.05f));
				EnterPose(p);
				_reviveHold = (_giveUpHold = (_noAllyTimer = 0f));
				Target = null;
				ReviveProgress = (GiveUpProgress = 0f);
				Announce(Fmt(Plugin.TextFell.Value, p.GetPlayerName()));
				Plugin.Log.LogInfo((object)$"{p.GetPlayerName()} ha caido ({Plugin.DownedSeconds.Value}s para ser revivido).");
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("No se pudo iniciar el estado de caido, muere normal: " + ex));
				try
				{
					SetFlag(p, value: false);
				}
				catch
				{
				}
				ExitPose(p);
				return false;
			}
		}

		private static void EnterPose(Player p)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			//IL_0044: 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_0072: 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_0087: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			if (((Character)p).IsAttached())
			{
				((Character)p).AttachStop();
			}
			if ((Object)(object)_pose != (Object)null)
			{
				Object.Destroy((Object)(object)_pose);
			}
			_pose = new GameObject("BR_DownedPose");
			_pose.transform.position = ((Component)p).transform.position;
			_pose.transform.rotation = Quaternion.Euler(0f, ((Component)p).transform.eulerAngles.y, 0f);
			GameObject val = new GameObject("BR_NoColliders");
			val.transform.SetParent(_pose.transform, false);
			((Character)p).AttachStart(_pose.transform, val, true, false, false, "attach_bed", new Vector3(0f, 0.3f, 0f), (Transform)null);
		}

		private static void ExitPose(Player p)
		{
			try
			{
				if ((Object)(object)p != (Object)null && ((Character)p).IsAttached())
				{
					((Character)p).AttachStop();
				}
			}
			catch
			{
			}
			if ((Object)(object)_pose != (Object)null)
			{
				Object.Destroy((Object)(object)_pose);
			}
			_pose = null;
		}

		private static void SetFlag(Player p, bool value)
		{
			ZNetView val = NView((Character)(object)p);
			if ((Object)(object)val != (Object)null)
			{
				val.GetZDO().Set("BR_Downed", value);
			}
		}

		internal static void Revive(Player p, string byName, bool lowHealth = false)
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			ExitPose(p);
			SetFlag(p, value: false);
			float num = (lowHealth ? 10f : Plugin.ReviveHealthPercent.Value);
			((Character)p).SetHealth(Mathf.Max(1f, ((Character)p).GetMaxHealth() * num / 100f));
			GraceUntil = Time.time + Plugin.GraceSeconds.Value;
			_reviveHold = (_giveUpHold = 0f);
			GiveUpProgress = 0f;
			if (!string.IsNullOrEmpty(byName))
			{
				Toast(Fmt(Plugin.TextRevivedBy.Value, byName));
			}
			Fx("vfx_HealthUpgrade", ((Component)p).transform.position);
			Plugin.Log.LogInfo((object)(p.GetPlayerName() + " se ha levantado."));
		}

		private static void Die(Player p)
		{
			ExitPose(p);
			SetFlag(p, value: false);
			AllowDeath = true;
			try
			{
				((Character)p).SetHealth(0f);
				CheckDeathMI.Invoke(p, null);
				if (!((Character)p).IsDead())
				{
					((Character)p).OnDeath();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Error al morir tras el tiempo de espera: " + ex));
			}
			finally
			{
				AllowDeath = false;
			}
		}

		private static void Expire(Player p, bool forceDie)
		{
			if (!forceDie && Plugin.OnTimeout.Value == TimeoutMode.StandUp)
			{
				Revive(p, null, lowHealth: true);
			}
			else
			{
				Die(p);
			}
		}

		internal static void Tick()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				if ((Object)(object)_pose != (Object)null)
				{
					Object.Destroy((Object)(object)_pose);
					_pose = null;
				}
				Target = null;
				return;
			}
			float deltaTime = Time.deltaTime;
			if (_reviveCooldown > 0f)
			{
				_reviveCooldown -= deltaTime;
			}
			if (((Character)localPlayer).IsDead())
			{
				ExitPose(localPlayer);
				Target = null;
			}
			else if (IsDowned((Character)(object)localPlayer))
			{
				TickDowned(localPlayer, deltaTime);
			}
			else
			{
				TickRescuer(localPlayer, deltaTime);
			}
		}

		private static void TickDowned(Player me, float dt)
		{
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			Target = null;
			ReviveProgress = 0f;
			if (!((Character)me).IsAttached() && (Object)(object)_pose != (Object)null)
			{
				try
				{
					EnterPose(me);
				}
				catch
				{
				}
			}
			if ((Object)(object)_pose == (Object)null)
			{
				try
				{
					EnterPose(me);
				}
				catch
				{
				}
			}
			if (((Character)me).GetHealth() <= 0f)
			{
				((Character)me).SetHealth(1f);
			}
			if (Remaining(me) <= 0.0)
			{
				Expire(me, forceDie: false);
				return;
			}
			if (!Plugin.TestMode.Value && (Object)(object)ZNet.instance != (Object)null && AllLoadedAlliesOut(me, ZNet.instance))
			{
				_noAllyTimer += dt;
				if (_noAllyTimer >= 2.5f)
				{
					Toast("Nadie puede ayudarte...");
					Expire(me, forceDie: true);
					return;
				}
			}
			else
			{
				_noAllyTimer = 0f;
			}
			if (TypingOrMenu())
			{
				_giveUpHold = 0f;
				GiveUpProgress = 0f;
				return;
			}
			if (Input.GetKey(Plugin.GiveUpKey.Value))
			{
				_giveUpHold += dt;
				GiveUpProgress = Mathf.Clamp01(_giveUpHold / Plugin.GiveUpHoldSeconds.Value);
				if (_giveUpHold >= Plugin.GiveUpHoldSeconds.Value)
				{
					Expire(me, forceDie: true);
					return;
				}
			}
			else
			{
				_giveUpHold = 0f;
				GiveUpProgress = 0f;
			}
			if (Plugin.TestMode.Value && Input.GetKey(Plugin.ReviveKey.Value))
			{
				_reviveHold += dt;
				if (_reviveHold >= Plugin.ReviveHoldSeconds.Value)
				{
					Revive(me, me.GetPlayerName());
				}
			}
			else
			{
				_reviveHold = 0f;
			}
		}

		private static void TickRescuer(Player me, float dt)
		{
			//IL_00dc: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			Target = null;
			ReviveProgress = 0f;
			GiveUpProgress = 0f;
			if (TypingOrMenu())
			{
				_reviveHold = 0f;
				return;
			}
			Player val = null;
			float num = Plugin.ReviveRange.Value;
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (!((Object)(object)allPlayer == (Object)null) && !((Object)(object)allPlayer == (Object)(object)me) && !((Character)allPlayer).IsDead() && IsDowned((Character)(object)allPlayer))
				{
					float num2 = Vector3.Distance(((Component)me).transform.position, ((Component)allPlayer).transform.position);
					if (num2 <= num)
					{
						num = num2;
						val = allPlayer;
					}
				}
			}
			Target = val;
			if ((Object)(object)val == (Object)null)
			{
				_reviveHold = 0f;
			}
			else
			{
				if (_reviveCooldown > 0f)
				{
					return;
				}
				if (Input.GetKey(Plugin.ReviveKey.Value))
				{
					_reviveHold += dt;
					float value = Plugin.ReviveHoldSeconds.Value;
					ReviveProgress = ((value <= 0f) ? 1f : Mathf.Clamp01(_reviveHold / value));
					if (_reviveHold >= value)
					{
						SendRevive(val, me);
						_reviveHold = 0f;
						_reviveCooldown = 2.5f;
						ReviveProgress = 0f;
					}
				}
				else
				{
					_reviveHold = 0f;
				}
			}
		}

		private static void SendRevive(Player target, Player me)
		{
			ZNetView val = NView((Character)(object)target);
			if (!((Object)(object)val == (Object)null))
			{
				val.InvokeRPC("BR_Revive", new object[1] { me.GetPlayerName() });
				Toast(Fmt(Plugin.TextReviving.Value, target.GetPlayerName()));
			}
		}

		internal static bool TypingOrMenu()
		{
			try
			{
				return ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus()) || Console.IsVisible() || Menu.IsVisible() || TextInput.IsVisible() || InventoryGui.IsVisible();
			}
			catch
			{
				return false;
			}
		}

		internal static void Announce(string text)
		{
			try
			{
				if (ZRoutedRpc.instance != null)
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(0L, "BR_Announce", new object[1] { text });
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("No se pudo avisar a los demas: " + ex.Message));
			}
		}

		internal static void Toast(string text)
		{
			try
			{
				if ((Object)(object)MessageHud.instance != (Object)null)
				{
					MessageHud.instance.ShowMessage((MessageType)2, text, 0, (Sprite)null, false, true);
				}
			}
			catch
			{
			}
		}

		private static void Fx(string prefab, Vector3 pos)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(prefab) : null);
				if ((Object)(object)val != (Object)null)
				{
					Object.Instantiate<GameObject>(val, pos, Quaternion.identity);
				}
			}
			catch
			{
			}
		}

		internal static string Fmt(string fmt, params object[] args)
		{
			if (string.IsNullOrEmpty(fmt))
			{
				return string.Empty;
			}
			try
			{
				return string.Format(fmt, args);
			}
			catch (FormatException)
			{
				return fmt;
			}
		}
	}
	[HarmonyPatch(typeof(Character), "CheckDeath")]
	internal static class CheckDeathPatch
	{
		private static bool Prefix(Character __instance)
		{
			try
			{
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val == null || (Object)(object)val != (Object)(object)Player.m_localPlayer)
				{
					return true;
				}
				if (Downed.IsDowned((Character)(object)val))
				{
					if (((Character)val).GetHealth() <= 0f)
					{
						((Character)val).SetHealth(1f);
					}
					return false;
				}
				if (Downed.AllowDeath)
				{
					return true;
				}
				if (((Character)val).GetHealth() > 0f || ((Character)val).IsDead())
				{
					return true;
				}
				if (!Downed.ShouldDown(val))
				{
					return true;
				}
				return !Downed.TryBeginDown(val);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("CheckDeath: " + ex));
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(Character), "RPC_Damage")]
	internal static class RpcDamagePatch
	{
		private static bool Prefix(Character __instance)
		{
			return !Downed.IsProtected(__instance);
		}
	}
	[HarmonyPatch(typeof(Character), "ApplyDamage")]
	internal static class ApplyDamagePatch
	{
		private static bool Prefix(Character __instance)
		{
			return !Downed.IsProtected(__instance);
		}
	}
	[HarmonyPatch(typeof(Player), "TakeInput")]
	internal static class TakeInputPatch
	{
		private static void Postfix(Player __instance, ref bool __result)
		{
			if (__result && Downed.IsDowned((Character)(object)__instance))
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(BaseAI), "IsEnemy", new Type[]
	{
		typeof(Character),
		typeof(Character)
	})]
	internal static class IsEnemyPatch
	{
		private static void Postfix(Character a, Character b, ref bool __result)
		{
			if (__result && (Downed.IsDowned(a) || Downed.IsDowned(b)))
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "Awake")]
	internal static class PlayerAwakePatch
	{
		private static void Postfix(Player __instance)
		{
			try
			{
				ZNetView val = Downed.NView((Character)(object)__instance);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				val.Register<string>("BR_Revive", (Action<long, string>)delegate(long sender, string who)
				{
					if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && Downed.IsDowned((Character)(object)__instance))
					{
						Downed.Revive(__instance, who);
					}
				});
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("No se pudo registrar el RPC de revivir: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	internal static class ZNetSceneAwakePatch
	{
		private static void Postfix()
		{
			try
			{
				if (ZRoutedRpc.instance == null)
				{
					return;
				}
				ZRoutedRpc.instance.Register<string>("BR_Announce", (Action<long, string>)delegate(long sender, string text)
				{
					if ((Object)(object)MessageHud.instance != (Object)null)
					{
						MessageHud.instance.ShowMessage((MessageType)1, text, 0, (Sprite)null, false, true);
					}
				});
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("No se pudo registrar el aviso global: " + ex.Message));
			}
		}
	}
	public enum TimeoutMode
	{
		Die,
		StandUp
	}
	[BepInPlugin("piero.valheim.downedrevive", "Caidos y Revividos", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "piero.valheim.downedrevive";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> DownedSeconds;

		internal static ConfigEntry<TimeoutMode> OnTimeout;

		internal static ConfigEntry<bool> TestMode;

		internal static ConfigEntry<KeyCode> ReviveKey;

		internal static ConfigEntry<float> ReviveHoldSeconds;

		internal static ConfigEntry<float> ReviveRange;

		internal static ConfigEntry<float> ReviveHealthPercent;

		internal static ConfigEntry<float> GraceSeconds;

		internal static ConfigEntry<KeyCode> GiveUpKey;

		internal static ConfigEntry<float> GiveUpHoldSeconds;

		internal static ConfigEntry<bool> ShowMarkers;

		internal static ConfigEntry<string> TextDowned;

		internal static ConfigEntry<string> TextRevivePrompt;

		internal static ConfigEntry<string> TextGiveUp;

		internal static ConfigEntry<string> TextMarker;

		internal static ConfigEntry<string> TextFell;

		internal static ConfigEntry<string> TextRevivedBy;

		internal static ConfigEntry<string> TextReviving;

		private bool _tickErrorLogged;

		private bool _guiErrorLogged;

		private void Awake()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Expected O, but got Unknown
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Expected O, but got Unknown
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Expected O, but got Unknown
			//IL_033c: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "Activado", true, "Activa o desactiva todo el mod.");
			DownedSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("1 - General", "SegundosCaido", 45f, new ConfigDescription("Segundos que dura el estado de caído (con invulnerabilidad) esperando a que lo revivan.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 300f), Array.Empty<object>()));
			OnTimeout = ((BaseUnityPlugin)this).Config.Bind<TimeoutMode>("1 - General", "AlAcabarseElTiempo", TimeoutMode.Die, "Die = muere de verdad (lápida y respawn normal). StandUp = se levanta solo con poca vida.");
			TestMode = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "ModoPrueba", false, "SOLO PARA PROBAR EN SOLITARIO: permite caer aunque estés solo en el servidor y te puedes revivir a ti mismo con la tecla de revivir. Desactívalo para jugar de verdad.");
			ReviveKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("2 - Revivir", "TeclaRevivir", (KeyCode)116, "Tecla que mantiene pulsada el compañero para revivir.");
			ReviveHoldSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Revivir", "SegundosMantenerTecla", 2.5f, new ConfigDescription("Cuánto hay que mantener la tecla para completar la reanimación (0 = instantáneo).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>()));
			ReviveRange = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Revivir", "DistanciaMaxima", 3.5f, new ConfigDescription("Distancia máxima (metros) para poder revivir a un compañero.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 15f), Array.Empty<object>()));
			ReviveHealthPercent = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Revivir", "VidaAlRevivirPorcentaje", 35f, new ConfigDescription("Porcentaje de vida máxima con el que te levantas.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), Array.Empty<object>()));
			GraceSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Revivir", "SegundosProteccionTrasRevivir", 6f, new ConfigDescription("Segundos de invulnerabilidad extra al levantarte, para que puedas huir.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), Array.Empty<object>()));
			GiveUpKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("3 - Rendirse", "TeclaRendirse", (KeyCode)120, "Mantén esta tecla estando caído para morir ya y reaparecer sin esperar.");
			GiveUpHoldSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("3 - Rendirse", "SegundosMantenerTecla", 2f, new ConfigDescription("Cuánto hay que mantener la tecla de rendirse.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>()));
			ShowMarkers = ((BaseUnityPlugin)this).Config.Bind<bool>("4 - Interfaz y textos", "MostrarMarcadorSobreCaidos", true, "Muestra nombre, tiempo y distancia sobre los compañeros caídos (se ven a distancia).");
			TextDowned = ((BaseUnityPlugin)this).Config.Bind<string>("4 - Interfaz y textos", "TextoCaido", "EN ESPERA DE SER REVIVIDO", "Título grande que ve el jugador caído.");
			TextRevivePrompt = ((BaseUnityPlugin)this).Config.Bind<string>("4 - Interfaz y textos", "TextoRevivir", "Mantén [{0}] para revivir a {1}", "{0} = tecla, {1} = nombre del compañero.");
			TextGiveUp = ((BaseUnityPlugin)this).Config.Bind<string>("4 - Interfaz y textos", "TextoRendirse", "Mantén [{0}] para rendirte", "{0} = tecla de rendirse.");
			TextMarker = ((BaseUnityPlugin)this).Config.Bind<string>("4 - Interfaz y textos", "TextoMarcador", "{0}  {1}s  ({2} m)", "{0} = nombre, {1} = segundos restantes, {2} = distancia.");
			TextFell = ((BaseUnityPlugin)this).Config.Bind<string>("4 - Interfaz y textos", "TextoHaCaido", "{0} ha caído, ¡corre a revivirlo!", "Aviso a todos. {0} = nombre.");
			TextRevivedBy = ((BaseUnityPlugin)this).Config.Bind<string>("4 - Interfaz y textos", "TextoRevividoPor", "{0} te ha revivido", "{0} = nombre de quien te revivió.");
			TextReviving = ((BaseUnityPlugin)this).Config.Bind<string>("4 - Interfaz y textos", "TextoReviviendo", "Reviviendo a {0}...", "{0} = nombre del compañero.");
			new Harmony("piero.valheim.downedrevive").PatchAll(Assembly.GetExecutingAssembly());
			Log.LogInfo((object)"Caidos y Revividos cargado.");
		}

		private void Update()
		{
			try
			{
				Downed.Tick();
			}
			catch (Exception ex)
			{
				if (!_tickErrorLogged)
				{
					_tickErrorLogged = true;
					Log.LogError((object)("Error en Tick: " + ex));
				}
			}
		}

		private void OnGUI()
		{
			try
			{
				Ui.Draw();
			}
			catch (Exception ex)
			{
				if (!_guiErrorLogged)
				{
					_guiErrorLogged = true;
					Log.LogError((object)("Error en Ui: " + ex));
				}
			}
		}
	}
	internal static class Ui
	{
		private static GUIStyle _label;

		private static void Init()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_0025: 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_0038: Expected O, but got Unknown
			if (_label == null)
			{
				_label = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)4,
					fontStyle = (FontStyle)1,
					wordWrap = false,
					clipping = (TextClipping)0
				};
			}
		}

		internal static void Draw()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			if (Event.current == null || (int)Event.current.type != 7)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && !((Character)localPlayer).IsDead())
			{
				Init();
				float s = (float)Screen.height / 1080f;
				if (Downed.IsDowned((Character)(object)localPlayer))
				{
					DrawDowned(localPlayer, s);
				}
				else
				{
					DrawRescuePrompt(s);
				}
				if (Plugin.ShowMarkers.Value)
				{
					DrawMarkers(localPlayer, s);
				}
			}
		}

		private static void DrawDowned(Player me, float s)
		{
			//IL_0041: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: 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_0121: 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_0172: 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_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: 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_0275: Unknown result type (might be due to invalid IL or missing references)
			float num = Screen.width;
			float num2 = Screen.height;
			float num3 = Mathf.Max(0f, (float)Downed.Remaining(me));
			float num4 = Mathf.Max(1f, Plugin.DownedSeconds.Value);
			Fill(new Rect(0f, 0f, num, num2), new Color(0.55f, 0f, 0f, 0.18f));
			float num5 = 0.8f + 0.2f * Mathf.Sin(Time.unscaledTime * 4f);
			Text(new Rect(0f, num2 * 0.16f, num, 80f * s), Plugin.TextDowned.Value, 54f * s, new Color(1f, 0.28f, 0.22f, num5));
			Color c = ((num3 <= 10f) ? new Color(1f, 0.25f, 0.2f, 1f) : new Color(1f, 0.92f, 0.75f, 1f));
			Text(new Rect(0f, num2 * 0.16f + 78f * s, num, 140f * s), Mathf.CeilToInt(num3).ToString(), 120f * s, c);
			float num6 = 520f * s;
			float num7 = 14f * s;
			Bar(new Rect((num - num6) / 2f, num2 * 0.16f + 225f * s, num6, num7), num3 / num4, (num3 <= 10f) ? new Color(1f, 0.25f, 0.2f) : new Color(1f, 0.75f, 0.3f));
			string t = SafeFormat(Plugin.TextGiveUp.Value, Plugin.GiveUpKey.Value);
			Text(new Rect(0f, num2 * 0.16f + 250f * s, num, 40f * s), t, 24f * s, new Color(1f, 1f, 1f, 0.7f));
			if (Downed.GiveUpProgress > 0f)
			{
				Bar(new Rect((num - num6 * 0.5f) / 2f, num2 * 0.16f + 292f * s, num6 * 0.5f, 8f * s), Downed.GiveUpProgress, new Color(0.8f, 0.8f, 0.8f));
			}
		}

		private static void DrawRescuePrompt(float s)
		{
			//IL_0035: 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_0084: 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_00de: Unknown result type (might be due to invalid IL or missing references)
			Player target = Downed.Target;
			if (!((Object)(object)target == (Object)null))
			{
				float num = Screen.width;
				float num2 = Screen.height;
				string t = SafeFormat(Plugin.TextRevivePrompt.Value, Plugin.ReviveKey.Value, target.GetPlayerName());
				Text(new Rect(0f, num2 * 0.68f, num, 50f * s), t, 34f * s, new Color(1f, 0.95f, 0.7f, 1f));
				if (Downed.ReviveProgress > 0f)
				{
					float num3 = 360f * s;
					Bar(new Rect((num - num3) / 2f, num2 * 0.68f + 52f * s, num3, 14f * s), Downed.ReviveProgress, new Color(0.35f, 0.9f, 0.45f));
				}
			}
		}

		private static void DrawMarkers(Player me, float s)
		{
			//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_006c: 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_007b: 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)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: 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_011f: 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_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			Camera main = Camera.main;
			if ((Object)(object)main == (Object)null)
			{
				return;
			}
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (!((Object)(object)allPlayer == (Object)null) && !((Object)(object)allPlayer == (Object)(object)me) && !((Character)allPlayer).IsDead() && Downed.IsDowned((Character)(object)allPlayer))
				{
					Vector3 val = main.WorldToScreenPoint(((Component)allPlayer).transform.position + Vector3.up * 1.8f);
					if (!(val.z <= 0f))
					{
						int num = Mathf.Max(0, Mathf.CeilToInt((float)Downed.Remaining(allPlayer)));
						int num2 = Mathf.RoundToInt(Vector3.Distance(((Component)me).transform.position, ((Component)allPlayer).transform.position));
						string t = SafeFormat(Plugin.TextMarker.Value, allPlayer.GetPlayerName(), num, num2);
						float num3 = (float)Screen.height - val.y;
						Color c = ((num <= 10) ? new Color(1f, 0.3f, 0.25f, 1f) : new Color(1f, 0.85f, 0.4f, 1f));
						Text(new Rect(val.x - 250f * s, num3 - 20f * s, 500f * s, 40f * s), t, 24f * s, c);
					}
				}
			}
		}

		private static void Text(Rect r, string t, float size, Color c)
		{
			//IL_0016: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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_0088: Unknown result type (might be due to invalid IL or missing references)
			_label.fontSize = Mathf.Max(8, Mathf.RoundToInt(size));
			Color color = GUI.color;
			float num = Mathf.Max(1f, size * 0.04f);
			GUI.color = new Color(0f, 0f, 0f, 0.85f * c.a);
			GUI.Label(new Rect(((Rect)(ref r)).x + num, ((Rect)(ref r)).y + num, ((Rect)(ref r)).width, ((Rect)(ref r)).height), t, _label);
			GUI.color = c;
			GUI.Label(r, t, _label);
			GUI.color = color;
		}

		private static void Fill(Rect r, Color c)
		{
			//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_000b: Unknown result type (might be due to invalid IL or missing references)
			Color color = GUI.color;
			GUI.color = c;
			GUI.DrawTexture(r, (Texture)(object)Texture2D.whiteTexture);
			GUI.color = color;
		}

		private static void Bar(Rect r, float frac, Color fill)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			Fill(r, new Color(0f, 0f, 0f, 0.6f));
			Fill(new Rect(((Rect)(ref r)).x + 2f, ((Rect)(ref r)).y + 2f, (((Rect)(ref r)).width - 4f) * Mathf.Clamp01(frac), ((Rect)(ref r)).height - 4f), fill);
		}

		private static string SafeFormat(string fmt, params object[] args)
		{
			return Downed.Fmt(fmt, args);
		}
	}
}