Decompiled source of Tamed Wolf Balance v1.7.0

BepInEx/plugins/TamedWolfBalance/TamedWolfBalance.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: AssemblyFileVersion("1.7.0.0")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("1.7.0.0")]
namespace Fai.WolfBalance;

[BepInPlugin("fai.tamedwolfbalance", "TamedWolfBalance", "1.7.0")]
public sealed class Plugin : BaseUnityPlugin
{
	internal struct TameSnapshot
	{
		internal bool Eligible;

		internal float Maximum;
	}

	[HarmonyPatch(typeof(Tameable), "Tame", new Type[] { })]
	internal static class TamePatch
	{
		[HarmonyPriority(800)]
		internal static void Prefix(Tameable __instance, out TameSnapshot __state)
		{
			__state = default(TameSnapshot);
			Character component = ((Component)__instance).GetComponent<Character>();
			if (!((Object)(object)component == (Object)null) && !component.IsPlayer() && !component.IsTamed() && component.IsOwner() && !component.IsDead() && Data(component) != null)
			{
				float maxHealth = component.GetMaxHealth();
				if (Positive(maxHealth))
				{
					__state = new TameSnapshot
					{
						Eligible = true,
						Maximum = maxHealth
					};
				}
			}
		}

		[HarmonyPriority(0)]
		internal static void Postfix(Tameable __instance, TameSnapshot __state)
		{
			if (__state.Eligible)
			{
				Apply(((Component)__instance).GetComponent<Character>(), __state.Maximum);
			}
		}
	}

	[HarmonyPatch(typeof(Character), "SetMaxHealth", new Type[] { typeof(float) })]
	internal static class WriteMaxPatch
	{
		[HarmonyPriority(0)]
		internal static void Prefix(Character __instance, ref float __0)
		{
			if (Target(__instance, out var maximum))
			{
				__0 = maximum;
			}
		}
	}

	[HarmonyPatch(typeof(Character), "GetMaxHealth", new Type[] { })]
	internal static class ReadMaxPatch
	{
		[HarmonyPriority(0)]
		internal static void Postfix(Character __instance, ref float __result)
		{
			if (Target(__instance, out var maximum))
			{
				__result = maximum;
			}
		}
	}

	[HarmonyPatch(typeof(Attack), "ModifyDamage", new Type[]
	{
		typeof(HitData),
		typeof(float)
	})]
	internal static class DamagePatch
	{
		private static readonly ConditionalWeakTable<HitData, object> adjusted = new ConditionalWeakTable<HitData, object>();

		[HarmonyPriority(0)]
		internal static void Postfix(Humanoid ___m_character, HitData __0)
		{
			if (__0 != null && IsTamedCreature((Character)(object)___m_character) && !adjusted.TryGetValue(__0, out var _))
			{
				adjusted.Add(__0, new object());
				((DamageTypes)(ref __0.m_damage)).Modify(0.35f);
			}
		}
	}

	[HarmonyPatch(typeof(BaseAI), "UpdateRegeneration", new Type[] { typeof(float) })]
	internal static class RegenerationPatch
	{
		internal static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo method = typeof(Character).GetMethod("Heal", new Type[2]
			{
				typeof(float),
				typeof(bool)
			});
			MethodInfo method2 = typeof(Plugin).GetMethod("HealRegeneration", BindingFlags.Static | BindingFlags.NonPublic);
			int num = 0;
			foreach (CodeInstruction item in list)
			{
				if ((item.opcode == OpCodes.Callvirt || item.opcode == OpCodes.Call) && object.Equals(item.operand, method))
				{
					item.opcode = OpCodes.Call;
					item.operand = method2;
					num++;
				}
			}
			if (num != 1)
			{
				throw new InvalidOperationException("TWB: unrecognized BaseAI.UpdateRegeneration layout (Heal calls: " + num + ").");
			}
			return list;
		}
	}

	public const string Id = "fai.tamedwolfbalance";

	public const string Version = "1.7.0";

	internal const float HealthFactor = 3f;

	internal const float DamageFactor = 0.35f;

	internal const float RegenerationFactor = 0.01f;

	internal const string Marker = "fai_twb_alltamed_v170";

	internal const string BaseKey = "fai_twb_alltamed_basehp_v170";

	internal const string MaxKey = "fai_twb_alltamed_maxhp_v170";

	internal const string PreviousMarker = "fai_twb_alltamed_v160";

	internal const string PreviousBaseKey = "fai_twb_alltamed_basehp_v160";

	internal const string PreviousMaxKey = "fai_twb_alltamed_maxhp_v160";

	internal const string LegacyMarker = "fai_twb_newtame_v150";

	internal const string LegacyMaxKey = "fai_twb_newtame_maxhp_v150";

	internal static ManualLogSource Log;

	private Harmony harmony;

	private bool ready;

	private float scanTimer;

	private void Awake()
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		((BaseUnityPlugin)this).Logger.LogInfo((object)("TWB 1.7.0 LOADING: " + typeof(Plugin).Assembly.Location));
		harmony = new Harmony("fai.tamedwolfbalance");
		try
		{
			harmony.PatchAll(typeof(Plugin).Assembly);
			ready = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"TWB 1.7.0 READY | all tamed creatures | HP x3 | damage x0.35 | fed regeneration 1% per tick");
		}
		catch (Exception ex)
		{
			harmony.UnpatchSelf();
			((BaseUnityPlugin)this).Logger.LogError((object)("TWB 1.7.0 PATCH FAILED; no balance patches active: " + ex));
		}
	}

	private void Update()
	{
		if (!ready)
		{
			return;
		}
		scanTimer -= Time.unscaledDeltaTime;
		if (!(scanTimer > 0f))
		{
			scanTimer = 1f;
			List<Character> allCharacters = Character.GetAllCharacters();
			for (int i = 0; i < allCharacters.Count; i++)
			{
				Apply(allCharacters[i], 0f);
			}
		}
	}

	private void OnDestroy()
	{
		ready = false;
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		Log = null;
	}

	internal static bool Positive(float value)
	{
		return value > 0f && !float.IsNaN(value) && !float.IsInfinity(value);
	}

	internal static bool IsTamedCreature(Character c)
	{
		return (Object)(object)c != (Object)null && !c.IsPlayer() && c.IsTamed();
	}

	internal static ZDO Data(Character c)
	{
		if ((Object)(object)c == (Object)null)
		{
			return null;
		}
		ZNetView component = ((Component)c).GetComponent<ZNetView>();
		return (!((Object)(object)component != (Object)null) || !component.IsValid()) ? null : component.GetZDO();
	}

	internal static bool SavedMaximum(ZDO zdo, out float maximum)
	{
		maximum = 0f;
		if (zdo == null)
		{
			return false;
		}
		if (zdo.GetBool("fai_twb_alltamed_v170", false))
		{
			maximum = zdo.GetFloat("fai_twb_alltamed_maxhp_v170", 0f);
		}
		else if (zdo.GetBool("fai_twb_alltamed_v160", false))
		{
			maximum = zdo.GetFloat("fai_twb_alltamed_maxhp_v160", 0f);
		}
		else if (zdo.GetBool("fai_twb_newtame_v150", false))
		{
			maximum = zdo.GetFloat("fai_twb_newtame_maxhp_v150", 0f);
		}
		return Positive(maximum);
	}

	internal static bool Target(Character c, out float maximum)
	{
		maximum = 0f;
		return IsTamedCreature(c) && SavedMaximum(Data(c), out maximum);
	}

	internal static bool Plan(float currentMaximum, float currentHealth, float normalMaximum, out float targetMaximum, out float targetHealth)
	{
		targetMaximum = (targetHealth = 0f);
		if (!Positive(currentMaximum) || !Positive(currentHealth) || !Positive(normalMaximum))
		{
			return false;
		}
		float num = normalMaximum * 3f;
		if (!Positive(num))
		{
			return false;
		}
		targetMaximum = num;
		targetHealth = Math.Min(1f, currentHealth / currentMaximum) * num;
		return Positive(targetHealth);
	}

	internal static void Apply(Character c, float normalOverride)
	{
		//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
		if (!IsTamedCreature(c) || !c.IsOwner() || c.IsDead())
		{
			return;
		}
		ZDO val = Data(c);
		if (val == null || (val.GetBool("fai_twb_alltamed_v170", false) && SavedMaximum(val, out var _)))
		{
			return;
		}
		float num = c.GetMaxHealth();
		float health = c.GetHealth();
		float num2 = ((!Positive(normalOverride)) ? num : normalOverride);
		bool flag = false;
		if (val.GetBool("fai_twb_alltamed_v160", false) && Positive(val.GetFloat("fai_twb_alltamed_maxhp_v160", 0f)))
		{
			num = val.GetFloat("fai_twb_alltamed_maxhp_v160", 0f);
			num2 = val.GetFloat("fai_twb_alltamed_basehp_v160", 0f);
			if (!Positive(num2))
			{
				num2 = num / 5f;
			}
			flag = true;
		}
		else if (val.GetBool("fai_twb_newtame_v150", false) && Positive(val.GetFloat("fai_twb_newtame_maxhp_v150", 0f)))
		{
			num = val.GetFloat("fai_twb_newtame_maxhp_v150", 0f);
			num2 = num / 3f;
			flag = true;
		}
		if (Plan(num, health, num2, out var targetMaximum, out var targetHealth))
		{
			val.Set("fai_twb_alltamed_basehp_v170", num2);
			val.Set("fai_twb_alltamed_maxhp_v170", targetMaximum);
			val.Set("fai_twb_alltamed_v170", true);
			c.SetMaxHealth(targetMaximum);
			c.SetHealth(targetHealth);
			if (Log != null)
			{
				Log.LogInfo((object)string.Concat("TWB ", (!flag) ? "APPLIED" : "MIGRATED", " | ZDO=", c.GetZDOID(), " | normalMax=", num2.ToString("0.##"), " | HP=", c.GetHealth().ToString("0.##"), "/", targetMaximum.ToString("0.##"), " | damage=x0.35"));
			}
		}
	}

	internal static void HealRegeneration(Character c, float amount, bool showText)
	{
		if ((Object)(object)c == (Object)null)
		{
			return;
		}
		if (IsTamedCreature(c))
		{
			Tameable component = ((Component)c).GetComponent<Tameable>();
			if ((Object)(object)component != (Object)null)
			{
				if (component.IsHungry() || !c.IsOwner() || c.IsDead() || !Positive(c.GetHealth()))
				{
					return;
				}
				float maxHealth = c.GetMaxHealth();
				if (!Positive(maxHealth))
				{
					return;
				}
				amount = maxHealth * 0.01f;
			}
		}
		c.Heal(amount, showText);
	}
}