Decompiled source of TocoronScaling v1.0.0

plugins/TocoronScaling.dll

Decompiled a day ago
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

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

public enum ScalingMode
{
	Online,
	Nearby,
	Mix
}
[BepInPlugin("tocoron.scaling", "TocoronScaling", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Game), "GetPlayerDifficulty")]
	private static class Patch_GetPlayerDifficulty
	{
		private static readonly FieldInfo forcePlayers = AccessTools.Field(typeof(Game), "m_forcePlayers");

		[HarmonyPriority(0)]
		private static void Postfix(Game __instance, Vector3 pos, ref int __result)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (Enabled && (!(forcePlayers != null) || (int)forcePlayers.GetValue(__instance) <= 0))
			{
				__result = CountPlayers(pos);
			}
		}
	}

	[HarmonyPatch(typeof(Game), "GetDifficultyDamageScaleEnemy")]
	private static class Patch_HealthScale
	{
		private static void Prefix(Game __instance, out float __state)
		{
			__state = __instance.m_healthScalePerPlayer;
			if (Enabled && HealthPerPlayer >= 0f)
			{
				__instance.m_healthScalePerPlayer = HealthPerPlayer;
			}
		}

		private static void Postfix(Game __instance, float __state)
		{
			__instance.m_healthScalePerPlayer = __state;
		}
	}

	[HarmonyPatch(typeof(Game), "GetDifficultyDamageScalePlayer")]
	private static class Patch_DamageScale
	{
		private static void Prefix(Game __instance, out float __state)
		{
			__state = __instance.m_damageScalePerPlayer;
			if (Enabled && DamagePerPlayer >= 0f)
			{
				__instance.m_damageScalePerPlayer = DamagePerPlayer;
			}
		}

		private static void Postfix(Game __instance, float __state)
		{
			__instance.m_damageScalePerPlayer = __state;
		}
	}

	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	private static class Patch_OnNewConnection
	{
		private static void Postfix(ZNet __instance, ZNetPeer peer)
		{
			if (!__instance.IsServer() && peer != null && peer.m_rpc != null)
			{
				peer.m_rpc.Register<ZPackage>("TocoronScaling_Config", (Action<ZRpc, ZPackage>)ReceiveConfig);
			}
		}
	}

	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	private static class Patch_PeerInfo
	{
		private static void Postfix(ZNet __instance, ZRpc rpc)
		{
			if (__instance.IsServer() && rpc != null)
			{
				SendConfig(rpc);
				Log.LogInfo((object)("Config enviada a un jugador que acaba de entrar. Conectados: " + __instance.GetNrOfPlayers() + ". " + Describe()));
			}
		}
	}

	[HarmonyPatch(typeof(ZNet), "OnDestroy")]
	private static class Patch_ZNetDestroy
	{
		private static void Postfix()
		{
			if (FromServer)
			{
				ApplyLocal();
				Log.LogInfo((object)"Desconectado: vuelve la config local.");
			}
		}
	}

	public const string Guid = "tocoron.scaling";

	public const string Version = "1.0.0";

	private const string RpcName = "TocoronScaling_Config";

	private static ConfigEntry<bool> cEnabled;

	private static ConfigEntry<ScalingMode> cMode;

	private static ConfigEntry<float> cOnlineWeight;

	private static ConfigEntry<int> cMaxPlayers;

	private static ConfigEntry<float> cNearbyRange;

	private static ConfigEntry<float> cHealthPerPlayer;

	private static ConfigEntry<float> cDamagePerPlayer;

	private static ConfigEntry<bool> cDebugLog;

	private static ConfigEntry<int> cTestExtraOnline;

	internal static bool Enabled;

	internal static ScalingMode Mode;

	internal static float OnlineWeight;

	internal static int MaxPlayers;

	internal static float NearbyRange;

	internal static float HealthPerPlayer;

	internal static float DamagePerPlayer;

	internal static bool FromServer;

	internal static ManualLogSource Log;

	private static float lastDebug;

	private void Awake()
	{
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Expected O, but got Unknown
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Expected O, but got Unknown
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Expected O, but got Unknown
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0134: Expected O, but got Unknown
		//IL_0168: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Expected O, but got Unknown
		//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c5: Expected O, but got Unknown
		//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		cEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "Enabled", true, "Activa el escalado. Lo decide el server y se aplica a todos los jugadores.");
		cMode = ((BaseUnityPlugin)this).Config.Bind<ScalingMode>("1 - General", "Mode", ScalingMode.Mix, "Cómo se cuentan los jugadores.\nOnline: todos los conectados al server.\nNearby: solo los que están cerca del enemigo (como el juego normal, pero sin su tope).\nMix: el mayor entre los de cerca y los conectados x OnlineWeight.");
		cOnlineWeight = ((BaseUnityPlugin)this).Config.Bind<float>("1 - General", "OnlineWeight", 0.5f, new ConfigDescription("Solo en Mix: cuánto cuenta cada conectado que no está cerca (0,5 = la mitad). Se redondea hacia arriba.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
		cMaxPlayers = ((BaseUnityPlugin)this).Config.Bind<int>("1 - General", "MaxPlayers", 10, new ConfigDescription("Máximo de jugadores que cuentan para la dificultad.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 64), new object[0]));
		cNearbyRange = ((BaseUnityPlugin)this).Config.Bind<float>("1 - General", "NearbyRange", 200f, new ConfigDescription("Metros alrededor del enemigo en los que un jugador cuenta como cercano.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 2000f), new object[0]));
		cHealthPerPlayer = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Escalado", "HealthPerPlayer", 0.3f, new ConfigDescription("Vida extra de los enemigos por cada jugador después del primero (0,3 = +30 %). El juego lo aplica reduciendo el daño que reciben. -1 = usar el valor del juego.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-1f, 5f), new object[0]));
		cDamagePerPlayer = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Escalado", "DamagePerPlayer", 0.04f, new ConfigDescription("Daño extra de los enemigos por cada jugador después del primero (0,04 = +4 %). -1 = usar el valor del juego.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-1f, 5f), new object[0]));
		cDebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("3 - Debug", "DebugLog", false, "Escribe en el log, cada 30 s como mucho, cuántos jugadores se han contado. Es local, no se sincroniza.");
		cTestExtraOnline = ((BaseUnityPlugin)this).Config.Bind<int>("3 - Debug", "TestExtraOnline", 0, new ConfigDescription("SOLO PARA PROBAR: suma jugadores conectados falsos para ver el efecto jugando solo. Es local, no se sincroniza. Déjalo en 0 para jugar.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 63), new object[0]));
		ApplyLocal();
		((BaseUnityPlugin)this).Config.SettingChanged += OnSettingChanged;
		new Harmony("tocoron.scaling").PatchAll(typeof(Plugin).Assembly);
		Log.LogInfo((object)("TocoronScaling 1.0.0 cargado. " + Describe()));
	}

	private static void ApplyLocal()
	{
		Enabled = cEnabled.Value;
		Mode = cMode.Value;
		OnlineWeight = cOnlineWeight.Value;
		MaxPlayers = cMaxPlayers.Value;
		NearbyRange = cNearbyRange.Value;
		HealthPerPlayer = cHealthPerPlayer.Value;
		DamagePerPlayer = cDamagePerPlayer.Value;
		FromServer = false;
	}

	private static string Describe()
	{
		return string.Concat("Enabled=", Enabled, " Mode=", Mode, " OnlineWeight=", OnlineWeight, " MaxPlayers=", MaxPlayers, " NearbyRange=", NearbyRange, " HealthPerPlayer=", HealthPerPlayer, " DamagePerPlayer=", DamagePerPlayer, FromServer ? " (del server)" : " (local)");
	}

	private void OnSettingChanged(object sender, SettingChangedEventArgs e)
	{
		if (FromServer)
		{
			return;
		}
		ApplyLocal();
		if (!((Object)(object)ZNet.instance != (Object)null) || !ZNet.instance.IsServer())
		{
			return;
		}
		foreach (ZNetPeer peer in ZNet.instance.GetPeers())
		{
			if (peer != null && peer.m_rpc != null)
			{
				SendConfig(peer.m_rpc);
			}
		}
		Log.LogInfo((object)("Config cambiada, enviada a los jugadores. " + Describe()));
	}

	internal static void SendConfig(ZRpc rpc)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		ZPackage val = new ZPackage();
		val.Write(1);
		val.Write(Enabled);
		val.Write((int)Mode);
		val.Write(OnlineWeight);
		val.Write(MaxPlayers);
		val.Write(NearbyRange);
		val.Write(HealthPerPlayer);
		val.Write(DamagePerPlayer);
		rpc.Invoke("TocoronScaling_Config", new object[1] { val });
	}

	private static void ReceiveConfig(ZRpc rpc, ZPackage pkg)
	{
		try
		{
			int num = pkg.ReadInt();
			if (num != 1)
			{
				Log.LogWarning((object)("Config del server con formato desconocido (" + num + "). Actualiza TocoronScaling."));
				return;
			}
			Enabled = pkg.ReadBool();
			Mode = (ScalingMode)pkg.ReadInt();
			OnlineWeight = pkg.ReadSingle();
			MaxPlayers = pkg.ReadInt();
			NearbyRange = pkg.ReadSingle();
			HealthPerPlayer = pkg.ReadSingle();
			DamagePerPlayer = pkg.ReadSingle();
			FromServer = true;
			Log.LogInfo((object)("Config recibida del server. " + Describe()));
		}
		catch (Exception ex)
		{
			Log.LogError((object)("No se pudo leer la config del server: " + ex));
		}
	}

	internal static int CountPlayers(Vector3 pos)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		int playersInRangeXZ = Player.GetPlayersInRangeXZ(pos, NearbyRange);
		int num = ((!((Object)(object)ZNet.instance != (Object)null)) ? 1 : ZNet.instance.GetNrOfPlayers());
		if (num < 1)
		{
			num = 1;
		}
		num += cTestExtraOnline.Value;
		int num2 = ((Mode == ScalingMode.Online) ? num : ((Mode != ScalingMode.Nearby) ? Math.Max(playersInRangeXZ, Mathf.CeilToInt((float)num * OnlineWeight)) : playersInRangeXZ));
		if (num2 < 1)
		{
			num2 = 1;
		}
		if (num2 > MaxPlayers)
		{
			num2 = MaxPlayers;
		}
		if (cDebugLog.Value && Time.time - lastDebug > 30f)
		{
			lastDebug = Time.time;
			float num3 = ((HealthPerPlayer >= 0f) ? HealthPerPlayer : (((Object)(object)Game.instance != (Object)null) ? Game.instance.m_healthScalePerPlayer : 0f));
			float num4 = ((DamagePerPlayer >= 0f) ? DamagePerPlayer : (((Object)(object)Game.instance != (Object)null) ? Game.instance.m_damageScalePerPlayer : 0f));
			Log.LogInfo((object)string.Concat("Jugadores contados: ", num2, " (cerca ", playersInRangeXZ, ", conectados ", num, (cTestExtraOnline.Value > 0) ? (" con " + cTestExtraOnline.Value + " de prueba") : "", ", modo ", Mode, ") -> el enemigo recibe x", (1f / (1f + (float)(num2 - 1) * num3)).ToString("0.00"), " de daño y pega x", (1f + (float)(num2 - 1) * num4).ToString("0.00")));
		}
		return num2;
	}
}