Decompiled source of Totally Accurate Quality of Life v1.5.0

BepInEx/plugins/TotallyAccurateQualityOfLife.dll

Decompiled 3 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using Landfall.TABS;
using Landfall.TABS.AI;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("TotallyAccurateQualityOfLife")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: AssemblyInformationalVersion("1.5.0")]
[assembly: AssemblyProduct("TotallyAccurateQualityOfLife")]
[assembly: AssemblyTitle("TotallyAccurateQualityOfLife")]
[assembly: AssemblyVersion("1.5.0.0")]
[BepInPlugin("cringe2137.totallyaccurateqol", "Totally Accurate Quality of Life", "1.5.0")]
public sealed class TotallyAccurateQualityOfLifePlugin : BaseUnityPlugin
{
	public const string PluginGuid = "cringe2137.totallyaccurateqol";

	public const string PluginName = "Totally Accurate Quality of Life";

	public const string PluginVersion = "1.5.0";

	private Harmony _harmony;

	private void Awake()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		_harmony = new Harmony("cringe2137.totallyaccurateqol");
		_harmony.PatchAll(typeof(TotallyAccurateQualityOfLifePlugin).Assembly);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Totally Accurate Quality of Life by Cringe2137 loaded.");
	}

	private void OnDestroy()
	{
		if (_harmony != null)
		{
			_harmony.UnpatchSelf();
			_harmony = null;
		}
	}
}
[HarmonyPatch]
internal static class AddTargetableExplosionTeamPatch
{
	private static readonly FieldInfo SourceUnitField = AccessTools.Field(typeof(AddTargetableEffect), "unit");

	private static readonly FieldInfo SourceTeamHolderField = AccessTools.Field(typeof(AddTargetableEffect), "rootTeamHolder");

	private static MethodBase TargetMethod()
	{
		return AccessTools.Method(typeof(AddTargetableEffect), "DoEffect", new Type[2]
		{
			typeof(Transform),
			typeof(Transform)
		}, (Type[])null);
	}

	private static bool Prefix(AddTargetableEffect __instance, Transform startPoint, Transform target)
	{
		//IL_00a8: 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)
		if ((Object)(object)__instance == (Object)null || (Object)(object)__instance.EffectPrefab == (Object)null || (Object)(object)target == (Object)null || (Object)(object)((Component)__instance.EffectPrefab).GetComponentInChildren<Explosion>(true) == (Object)null)
		{
			return true;
		}
		Unit val = (Unit)((SourceUnitField != null) ? /*isinst with value type is only supported in some contexts*/: null);
		TeamHolder val2 = (TeamHolder)((SourceTeamHolderField != null) ? /*isinst with value type is only supported in some contexts*/: null);
		if ((Object)(object)val == (Object)null && (Object)(object)startPoint != (Object)null)
		{
			TeamHolder.GetTeamRelevantComponents(startPoint.root, ref val, ref val2);
		}
		if ((Object)(object)val == (Object)null || val.Entity.GUID.m_ID != 1760500345)
		{
			return true;
		}
		DataHandler componentInChildren = ((Component)target.root).GetComponentInChildren<DataHandler>();
		if ((Object)(object)componentInChildren == (Object)null || componentInChildren.Dead)
		{
			return false;
		}
		UnitEffectBase val3 = UnitEffectBase.AddEffectToTarget(((Component)target).gameObject, __instance.EffectPrefab);
		if ((Object)(object)val3 != (Object)null)
		{
			val3.Ping();
			return false;
		}
		UnitEffectBase obj = Object.Instantiate<UnitEffectBase>(__instance.EffectPrefab, target.root);
		((Component)obj).transform.position = target.root.position;
		obj.damageMultiplier = ((TargetableEffect)__instance).damageMultiplier;
		TeamHolder.AddTeamHolder(((Component)obj).gameObject, val, val2);
		obj.DoEffect();
		return false;
	}
}
internal static class WizardSpellExplosionPatchLogic
{
	internal const int WizardEntityId = 1760500345;

	private static readonly FieldInfo ExplosionTeamHolderField = AccessTools.Field(typeof(Explosion), "teamHolder");

	private static readonly FieldInfo ExplosionTeamField = AccessTools.Field(typeof(Explosion), "team");

	private static readonly FieldInfo ExplosionOwnUnitField = AccessTools.Field(typeof(Explosion), "ownUnit");

	private static bool _loggedWizardExplosion;

	internal static void FixWizardExplosion(Explosion explosion)
	{
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: 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)
		if ((Object)(object)explosion == (Object)null)
		{
			return;
		}
		TeamHolder componentInParent = ((Component)explosion).GetComponentInParent<TeamHolder>();
		if ((Object)(object)componentInParent == (Object)null)
		{
			return;
		}
		Unit val = (((Object)(object)componentInParent.spawner != (Object)null) ? componentInParent.spawner.GetComponentInParent<Unit>() : null);
		if (!((Object)(object)val == (Object)null) && val.Entity.GUID.m_ID == 1760500345)
		{
			componentInParent.team = val.Team;
			if (ExplosionTeamHolderField != null)
			{
				ExplosionTeamHolderField.SetValue(explosion, componentInParent);
			}
			if (ExplosionTeamField != null)
			{
				ExplosionTeamField.SetValue(explosion, val.Team);
			}
			if (ExplosionOwnUnitField != null)
			{
				ExplosionOwnUnitField.SetValue(explosion, val);
			}
			explosion.ignoreTeamMates = false;
			explosion.onlyTeamMates = false;
			if (!_loggedWizardExplosion)
			{
				Debug.Log((object)"[Totally Accurate Quality of Life] Applied the Wizard explosion team fix.");
				_loggedWizardExplosion = true;
			}
		}
	}
}
[HarmonyPatch(typeof(Explosion), "Start")]
internal static class WizardSpellExplosionStartPatch
{
	private static void Prefix(Explosion __instance)
	{
		WizardSpellExplosionPatchLogic.FixWizardExplosion(__instance);
	}
}
[HarmonyPatch(typeof(Explosion), "Explode")]
internal static class WizardSpellExplosionPatch
{
	private static void Prefix(Explosion __instance)
	{
		WizardSpellExplosionPatchLogic.FixWizardExplosion(__instance);
	}
}
[HarmonyPatch(typeof(Unit), "Start")]
internal static class ChariotTurnSpeedPatch
{
	private const int ChariotEntityId = 115557157;

	private const int ChariotRiderEntityId = 2091056717;

	private const int ChariotHorseEntityId = 1619128563;

	private const float ChariotTurnSpeed = 10.8f;

	private static bool _loggedAdjustment;

	private static void Postfix(Unit __instance)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)__instance == (Object)null || (Object)(object)__instance.unitBlueprint == (Object)null)
		{
			return;
		}
		int iD = __instance.Entity.GUID.m_ID;
		string text = ((__instance.unitBlueprint.Entity != null) ? __instance.unitBlueprint.Entity.Name : string.Empty);
		if (IsChariotPart(iD, text))
		{
			__instance.turnSpeed = 10.8f;
			if (!_loggedAdjustment)
			{
				Debug.Log((object)("[Totally Accurate Quality of Life] Matched Chariot component '" + text + "' (ID " + iD + "); turn speed set to " + __instance.turnSpeed.ToString("0.##") + " (fixed value)."));
				_loggedAdjustment = true;
			}
		}
	}

	private static bool IsChariotPart(int entityId, string entityName)
	{
		if (entityId == 115557157 || entityId == 2091056717 || entityId == 1619128563)
		{
			return true;
		}
		if (!string.IsNullOrEmpty(entityName))
		{
			return entityName.IndexOf("Chariot", StringComparison.OrdinalIgnoreCase) >= 0;
		}
		return false;
	}
}
internal sealed class CactusDamageContext
{
	internal readonly Unit Target;

	internal readonly float Damage;

	internal CactusDamageContext(Unit target, float damage)
	{
		Target = target;
		Damage = damage;
	}
}
internal static class CactusDamageContextTracker
{
	[ThreadStatic]
	private static CactusDamageContext _current;

	private static readonly FieldInfo HealthHandlerUnitField = AccessTools.Field(typeof(HealthHandler), "unit");

	internal static CactusDamageContext Current
	{
		get
		{
			return _current;
		}
		set
		{
			_current = value;
		}
	}

	internal static Unit GetTarget(HealthHandler handler)
	{
		if ((Object)(object)handler == (Object)null || HealthHandlerUnitField == null)
		{
			return null;
		}
		object? value = HealthHandlerUnitField.GetValue(handler);
		return (Unit)((value is Unit) ? value : null);
	}

	internal static bool IsCactus(Unit unit)
	{
		if ((Object)(object)unit == (Object)null || (Object)(object)unit.unitBlueprint == (Object)null || unit.unitBlueprint.Entity == null)
		{
			return false;
		}
		string name = unit.unitBlueprint.Entity.Name;
		if (!string.IsNullOrEmpty(name))
		{
			return name.IndexOf("Cactus", StringComparison.OrdinalIgnoreCase) >= 0;
		}
		return false;
	}
}
[HarmonyPatch(typeof(HealthHandler), "TakeDamage")]
internal static class CactusHealingContextPatch
{
	private static bool _loggedNegativeDamage;

	private static bool _loggedZeroDamage;

	private static bool _loggedPositiveDamage;

	private static void Prefix(HealthHandler __instance, float __0, out CactusDamageContext __state)
	{
		__state = CactusDamageContextTracker.Current;
		Unit target = CactusDamageContextTracker.GetTarget(__instance);
		CactusDamageContextTracker.Current = new CactusDamageContext(target, __0);
		if (CactusDamageContextTracker.IsCactus(target) && ShouldLogDamage(__0))
		{
			Debug.Log((object)("[Totally Accurate Quality of Life] Cactus TakeDamage: value=" + __0.ToString("0.####") + ", target=" + target.unitBlueprint.Entity.Name + "."));
		}
	}

	private static bool ShouldLogDamage(float damage)
	{
		if (damage < 0f && !_loggedNegativeDamage)
		{
			_loggedNegativeDamage = true;
			return true;
		}
		if (damage == 0f && !_loggedZeroDamage)
		{
			_loggedZeroDamage = true;
			return true;
		}
		if (damage > 0f && !_loggedPositiveDamage)
		{
			_loggedPositiveDamage = true;
			return true;
		}
		return false;
	}

	private static Exception Finalizer(Exception __exception, CactusDamageContext __state)
	{
		CactusDamageContextTracker.Current = __state;
		return __exception;
	}
}
[HarmonyPatch(typeof(ConditionalEvent), "OnUnitDamaged")]
internal static class CactusHealingThornPatch
{
	private static bool _loggedNegativeCallback;

	private static bool _loggedZeroCallback;

	private static bool _loggedPositiveCallback;

	private static bool Prefix(ConditionalEvent __instance)
	{
		if ((Object)(object)__instance == (Object)null)
		{
			return true;
		}
		Unit componentInChildren = ((Component)((Component)__instance).transform.root).GetComponentInChildren<Unit>();
		if (!CactusDamageContextTracker.IsCactus(componentInChildren))
		{
			return true;
		}
		CactusDamageContext current = CactusDamageContextTracker.Current;
		bool flag = current != null && (Object)(object)current.Target == (Object)(object)componentInChildren;
		bool flag2 = string.Equals(((Object)((Component)__instance).gameObject).name, "Move_cactus(Clone)", StringComparison.OrdinalIgnoreCase) || string.Equals(((Object)((Component)__instance).gameObject).name, "Move_cactus", StringComparison.OrdinalIgnoreCase);
		bool flag3 = current != null && current.Damage < 0f && flag && flag2;
		object obj;
		if (current != null)
		{
			float damage = current.Damage;
			obj = damage.ToString("0.####");
		}
		else
		{
			obj = "none";
		}
		string text = (string)obj;
		if (ShouldLogCallback(current))
		{
			Debug.Log((object)("[Totally Accurate Quality of Life] Cactus thorn callback: component='" + ((Object)((Component)__instance).gameObject).name + "', damageContext=" + text + ", sameTarget=" + flag + ", target=" + componentInChildren.unitBlueprint.Entity.Name + ", filtered=" + flag3 + "."));
		}
		return !flag3;
	}

	private static bool ShouldLogCallback(CactusDamageContext context)
	{
		if (context == null)
		{
			return false;
		}
		if (context.Damage < 0f && !_loggedNegativeCallback)
		{
			_loggedNegativeCallback = true;
			return true;
		}
		if (context.Damage == 0f && !_loggedZeroCallback)
		{
			_loggedZeroCallback = true;
			return true;
		}
		if (context.Damage > 0f && !_loggedPositiveCallback)
		{
			_loggedPositiveCallback = true;
			return true;
		}
		return false;
	}
}
[HarmonyPatch(typeof(RaycastTrail), "Check")]
internal static class RaycastTrailCommandDirectionPatch
{
	private static readonly FieldInfo DeltaPositionField = AccessTools.Field(typeof(RaycastTrail), "deltaPos");

	private static readonly MethodInfo NormalizeDirectionMethod = AccessTools.Method(typeof(RaycastTrailCommandDirectionPatch), "NormalizeDirection", (Type[])null, (Type[])null);

	private static Vector3 NormalizeDirection(Vector3 direction)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		return ((Vector3)(ref direction)).normalized;
	}

	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Expected O, but got Unknown
		List<CodeInstruction> list = new List<CodeInstruction>(instructions);
		int num = -1;
		for (int i = 0; i < list.Count; i++)
		{
			ConstructorInfo constructorInfo = list[i].operand as ConstructorInfo;
			if (list[i].opcode == OpCodes.Newobj && constructorInfo != null && constructorInfo.DeclaringType == typeof(RaycastCommand))
			{
				num = i;
				break;
			}
		}
		if (num < 0 || DeltaPositionField == null || NormalizeDirectionMethod == null)
		{
			Debug.LogError((object)"[Totally Accurate Quality of Life] Could not locate RaycastTrail's RaycastCommand direction; the slow-motion projectile fix was not applied.");
			return list;
		}
		int num2 = -1;
		for (int num3 = num - 1; num3 >= 0; num3--)
		{
			FieldInfo fieldInfo = list[num3].operand as FieldInfo;
			if (list[num3].opcode == OpCodes.Ldfld && fieldInfo == DeltaPositionField)
			{
				num2 = num3;
				break;
			}
		}
		if (num2 < 0)
		{
			Debug.LogError((object)"[Totally Accurate Quality of Life] Could not locate RaycastTrail.deltaPos for the RaycastCommand; the slow-motion projectile fix was not applied.");
			return list;
		}
		list.Insert(num2 + 1, new CodeInstruction(OpCodes.Call, (object)NormalizeDirectionMethod));
		Debug.Log((object)"[Totally Accurate Quality of Life] Normalized the RaycastTrail batched ray direction.");
		return list;
	}
}
[HarmonyPatch(typeof(MovementHandler), "BatchedFixedUpdate")]
internal static class BankRobbersStayBannerForcePatch
{
	private const string BankRobbersUnitBaseName = "Safe_1 Prefabs_VB";

	private static readonly FieldInfo DontMoveForField = AccessTools.Field(typeof(DataHandler), "dontMoveFor");

	private static readonly HashSet<int> LoggedMatches = new HashSet<int>();

	private static readonly HashSet<int> LoggedSuppressions = new HashSet<int>();

	private static bool Prefix(MovementHandler __instance)
	{
		if ((Object)(object)__instance == (Object)null)
		{
			return true;
		}
		Unit componentInParent = ((Component)__instance).GetComponentInParent<Unit>();
		if ((Object)(object)componentInParent == (Object)null || (Object)(object)componentInParent.unitBlueprint == (Object)null || (Object)(object)componentInParent.unitBlueprint.UnitBase == (Object)null)
		{
			return true;
		}
		string name = ((Object)componentInParent.unitBlueprint.UnitBase).name;
		string text = ((componentInParent.unitBlueprint.Entity != null) ? componentInParent.unitBlueprint.Entity.Name : string.Empty);
		bool flag = string.Equals(name, "Safe_1 Prefabs_VB", StringComparison.Ordinal) || (!string.IsNullOrEmpty(text) && text.IndexOf("Bank Robbers", StringComparison.OrdinalIgnoreCase) >= 0);
		if (!flag && BannerBearerMovementStopLogic.IsStopped(__instance.data, __instance))
		{
			BannerBearerMovementStopLogic.ClearInput(__instance.data);
			BannerBearerMovementStopLogic.ClearForce(__instance);
			return false;
		}
		if (!flag)
		{
			return true;
		}
		Unit[] componentsInChildren = ((Component)componentInParent).GetComponentsInChildren<Unit>(true);
		RiderHolder component = ((Component)componentInParent).GetComponent<RiderHolder>();
		int num = (((Object)(object)component != (Object)null && component.riders != null) ? component.riders.Count : 0);
		float noWalkTime = GetNoWalkTime(componentInParent.data);
		int num2 = ((__instance.otherHolders != null) ? __instance.otherHolders.Count : 0);
		string text2 = string.Empty;
		if ((Object)(object)component != (Object)null && component.riders != null)
		{
			for (int i = 0; i < component.riders.Count; i++)
			{
				GameObject val = component.riders[i];
				Unit val2 = (((Object)(object)val != (Object)null) ? val.GetComponentInChildren<Unit>(true) : null);
				if (!((Object)(object)val2 == (Object)null))
				{
					string text3 = (((Object)(object)val2.unitBlueprint != (Object)null && val2.unitBlueprint.Entity != null) ? val2.unitBlueprint.Entity.Name : ((Object)val2).name);
					if (text2.Length > 0)
					{
						text2 += "; ";
					}
					text2 = text2 + text3 + " dontMoveFor=" + GetNoWalkTime(val2.data).ToString("0.###");
				}
			}
		}
		if (__instance.otherHolders != null)
		{
			for (int j = 0; j < __instance.otherHolders.Count; j++)
			{
				RigidbodyHolder val3 = __instance.otherHolders[j];
				if (!((Object)(object)val3 == (Object)null))
				{
					Unit val4 = (((Object)(object)val3.data != (Object)null) ? val3.data.unit : null);
					string text4 = (((Object)(object)val4 != (Object)null && (Object)(object)val4.unitBlueprint != (Object)null && val4.unitBlueprint.Entity != null) ? val4.unitBlueprint.Entity.Name : ((Object)val3).name);
					if (text2.Length > 0)
					{
						text2 += "; ";
					}
					text2 = text2 + text4 + " dontMoveFor=" + GetNoWalkTime(val3.data).ToString("0.###");
				}
			}
		}
		foreach (Unit val5 in componentsInChildren)
		{
			if ((Object)(object)val5 != (Object)null && (Object)(object)val5 != (Object)(object)componentInParent)
			{
				float noWalkTime2 = GetNoWalkTime(val5.data);
				string text5 = (((Object)(object)val5.unitBlueprint != (Object)null && val5.unitBlueprint.Entity != null) ? val5.unitBlueprint.Entity.Name : ((Object)val5).name);
				if (text2.Length > 0)
				{
					text2 += "; ";
				}
				text2 = text2 + text5 + " dontMoveFor=" + noWalkTime2.ToString("0.###");
			}
		}
		int instanceID = ((Object)componentInParent).GetInstanceID();
		if (LoggedMatches.Add(instanceID))
		{
			Debug.Log((object)("[Totally Accurate Quality of Life] Bank Robbers force check matched: base='" + name + "', entity='" + text + "', noWalkFor=" + noWalkTime.ToString("0.###") + ", riders=" + num + ", otherHolders=" + num2 + ", descendantUnits=" + componentsInChildren.Length + ", carriers=[" + text2 + "]."));
		}
		if (DontMoveForField == null)
		{
			return true;
		}
		if (noWalkTime > 0f)
		{
			if (LoggedSuppressions.Add(instanceID))
			{
				Debug.Log((object)"[Totally Accurate Quality of Life] Suppressed Bank Robbers safe force because the combined unit has an active no-walk timer.");
			}
			return false;
		}
		if (__instance.otherHolders != null)
		{
			for (int l = 0; l < __instance.otherHolders.Count; l++)
			{
				RigidbodyHolder val6 = __instance.otherHolders[l];
				if ((Object)(object)val6 != (Object)null && GetNoWalkTime(val6.data) > 0f)
				{
					LogSuppression(instanceID, "a linked carrier has an active no-walk timer");
					return false;
				}
			}
		}
		if ((Object)(object)component != (Object)null && component.riders != null)
		{
			for (int m = 0; m < component.riders.Count; m++)
			{
				GameObject val7 = component.riders[m];
				Unit val8 = (((Object)(object)val7 != (Object)null) ? val7.GetComponentInChildren<Unit>(true) : null);
				if ((Object)(object)val8 != (Object)null && GetNoWalkTime(val8.data) > 0f)
				{
					LogSuppression(instanceID, "a Bank Robber rider has an active no-walk timer");
					return false;
				}
			}
		}
		foreach (Unit val9 in componentsInChildren)
		{
			if (!((Object)(object)val9 == (Object)null) && !((Object)(object)val9 == (Object)(object)componentInParent) && GetNoWalkTime(val9.data) > 0f)
			{
				LogSuppression(instanceID, "a child carrier has an active no-walk timer");
				return false;
			}
		}
		return true;
	}

	private static float GetNoWalkTime(DataHandler data)
	{
		if ((Object)(object)data == (Object)null || DontMoveForField == null)
		{
			return -1f;
		}
		return (float)DontMoveForField.GetValue(data);
	}

	private static void LogSuppression(int safeUnitId, string reason)
	{
		if (LoggedSuppressions.Add(safeUnitId))
		{
			Debug.Log((object)("[Totally Accurate Quality of Life] Suppressed Bank Robbers safe force because " + reason + "."));
		}
	}
}
[HarmonyPatch(typeof(RemoveOnMountedUnit), "Start")]
internal static class BankRobbersFlagBearerBuffPatch
{
	private const string BankRobbersSafeBaseName = "Safe_1 Prefabs_VB";

	private const string BankRobbersSafeEntityName = "UNIT_SECRET_SAFE_THROWER";

	private const string BankRobberRiderEntityPrefix = "UNIT_SUBUNITS_SAFERIDER";

	private static bool Prefix(RemoveOnMountedUnit __instance)
	{
		if ((Object)(object)__instance == (Object)null)
		{
			return true;
		}
		Unit componentInParent = ((Component)__instance).GetComponentInParent<Unit>();
		if ((Object)(object)componentInParent == (Object)null || (Object)(object)componentInParent.unitBlueprint == (Object)null)
		{
			return true;
		}
		string a = (((Object)(object)componentInParent.unitBlueprint.UnitBase != (Object)null) ? ((Object)componentInParent.unitBlueprint.UnitBase).name : string.Empty);
		string text = ((componentInParent.unitBlueprint.Entity != null) ? componentInParent.unitBlueprint.Entity.Name : string.Empty);
		return !string.Equals(a, "Safe_1 Prefabs_VB", StringComparison.Ordinal) && !string.Equals(text, "UNIT_SECRET_SAFE_THROWER", StringComparison.Ordinal) && (string.IsNullOrEmpty(text) || !text.StartsWith("UNIT_SUBUNITS_SAFERIDER", StringComparison.Ordinal));
	}
}
internal static class BannerBearerMovementStopLogic
{
	private static readonly FieldInfo DontMoveForField = AccessTools.Field(typeof(DataHandler), "dontMoveFor");

	private static readonly FieldInfo MovementForceField = AccessTools.Field(typeof(MovementHandler), "force");

	internal static bool IsStopped(DataHandler data, MovementHandler movementHandler)
	{
		if (HasActiveTimer(data))
		{
			return true;
		}
		if ((Object)(object)movementHandler != (Object)null && movementHandler.otherHolders != null)
		{
			for (int i = 0; i < movementHandler.otherHolders.Count; i++)
			{
				RigidbodyHolder val = movementHandler.otherHolders[i];
				if ((Object)(object)val != (Object)null && HasActiveTimer(val.data))
				{
					return true;
				}
			}
		}
		Unit val2 = (((Object)(object)data != (Object)null) ? data.unit : null);
		if ((Object)(object)val2 == (Object)null && (Object)(object)movementHandler != (Object)null)
		{
			val2 = ((Component)movementHandler).GetComponentInParent<Unit>();
		}
		if ((Object)(object)val2 == (Object)null)
		{
			return false;
		}
		RiderHolder component = ((Component)val2).GetComponent<RiderHolder>();
		if ((Object)(object)component != (Object)null && component.riders != null)
		{
			for (int j = 0; j < component.riders.Count; j++)
			{
				GameObject val3 = component.riders[j];
				Unit val4 = (((Object)(object)val3 != (Object)null) ? val3.GetComponentInChildren<Unit>(true) : null);
				if ((Object)(object)val4 != (Object)null && HasActiveTimer(val4.data))
				{
					return true;
				}
			}
		}
		Unit[] componentsInChildren = ((Component)val2).GetComponentsInChildren<Unit>(true);
		for (int k = 0; k < componentsInChildren.Length; k++)
		{
			if ((Object)(object)componentsInChildren[k] != (Object)null && HasActiveTimer(componentsInChildren[k].data))
			{
				return true;
			}
		}
		return false;
	}

	internal static bool HasActiveTimer(DataHandler data)
	{
		if ((Object)(object)data != (Object)null && DontMoveForField != null)
		{
			return (float)DontMoveForField.GetValue(data) > 0f;
		}
		return false;
	}

	internal static void ClearInput(DataHandler data)
	{
		//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)
		if ((Object)(object)data != (Object)null && (Object)(object)data.input != (Object)null)
		{
			data.input.inputDirection = Vector3.zero;
			data.input.shift = false;
		}
	}

	internal static void ClearForce(MovementHandler movementHandler)
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)movementHandler != (Object)null && MovementForceField != null)
		{
			MovementForceField.SetValue(movementHandler, Vector3.zero);
		}
	}
}
[HarmonyPatch(typeof(UnitAPI), "SetMovementSpeed")]
internal static class BannerBearerStopMovementInputPatch
{
	private static void Postfix(UnitAPI __instance)
	{
		if (!((Object)(object)__instance == (Object)null))
		{
			Unit componentInParent = ((Component)__instance).GetComponentInParent<Unit>();
			if ((Object)(object)componentInParent != (Object)null && (Object)(object)componentInParent.data != (Object)null && BannerBearerMovementStopLogic.HasActiveTimer(componentInParent.data))
			{
				BannerBearerMovementStopLogic.ClearInput(componentInParent.data);
			}
		}
	}
}
[HarmonyPatch(typeof(WheelMovementHandler), "Update")]
internal static class BannerBearerStopWheelForcePatch
{
	private static bool Prefix(WheelMovementHandler __instance)
	{
		if ((Object)(object)__instance == (Object)null)
		{
			return true;
		}
		Unit componentInParent = ((Component)__instance).GetComponentInParent<Unit>();
		if ((Object)(object)componentInParent == (Object)null || (Object)(object)componentInParent.data == (Object)null)
		{
			return true;
		}
		MovementHandler componentInChildren = ((Component)componentInParent).GetComponentInChildren<MovementHandler>(true);
		if (!BannerBearerMovementStopLogic.IsStopped(componentInParent.data, componentInChildren))
		{
			return true;
		}
		BannerBearerMovementStopLogic.ClearInput(componentInParent.data);
		return false;
	}
}
[HarmonyPatch(typeof(RangeWeapon), "Reload")]
internal static class PossessedMagazineReloadStartPatch
{
	private static void Prefix(RangeWeapon __instance)
	{
		PossessedMagazineHud.RecordReloadStart(__instance);
	}
}
[HarmonyPatch(typeof(CameraAbilityPossess), "UpdateUnitUI")]
internal static class PossessedMagazineHudPatch
{
	private static readonly FieldInfo PossessUIField = AccessTools.Field(typeof(CameraAbilityPossess), "possessUI");

	private static void Postfix(CameraAbilityPossess __instance)
	{
		if (!((Object)(object)__instance == (Object)null) && !(PossessUIField == null))
		{
			object? value = PossessUIField.GetValue(__instance);
			CameraAbilityPossessUI val = (CameraAbilityPossessUI)((value is CameraAbilityPossessUI) ? value : null);
			if (!((Object)(object)val == (Object)null))
			{
				PossessedUnitHealthbar.Hide(__instance);
				WeaponHandler val2 = (((Object)(object)__instance.currentUnit != (Object)null) ? ((Component)__instance.currentUnit).GetComponentInChildren<WeaponHandler>() : null);
				PossessedMagazineHud.Update(val, (RangeWeapon)(((Object)(object)val2 != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null), (RangeWeapon)(((Object)(object)val2 != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null));
			}
		}
	}
}
[HarmonyPatch(typeof(CameraAbilityPossess), "EnterUnit")]
internal static class PossessedUnitHealthbarEnterPatch
{
	private static void Postfix(CameraAbilityPossess __instance)
	{
		PossessedUnitHealthbar.Hide(__instance);
	}
}
[HarmonyPatch(typeof(CameraAbilityPossess), "ExitUnit")]
internal static class PossessedUnitHealthbarExitPatch
{
	private static void Prefix(CameraAbilityPossess __instance)
	{
		PossessedUnitHealthbar.Restore(__instance);
	}
}
[HarmonyPatch(typeof(CameraAbilityPossess), "OnDisable")]
internal static class PossessedUnitHealthbarDisablePatch
{
	private static void Prefix(CameraAbilityPossess __instance)
	{
		PossessedUnitHealthbar.Restore(__instance);
	}
}
internal static class PossessedUnitHealthbar
{
	private sealed class VisibilityState
	{
		internal Unit Unit;

		internal bool WasActive;
	}

	private static readonly FieldInfo HealthbarField = AccessTools.Field(typeof(Unit), "m_unitUI");

	private static readonly ConditionalWeakTable<CameraAbilityPossess, VisibilityState> States = new ConditionalWeakTable<CameraAbilityPossess, VisibilityState>();

	internal static void Hide(CameraAbilityPossess controller)
	{
		if ((Object)(object)controller == (Object)null || !controller.IsPossessing || (Object)(object)controller.currentUnit == (Object)null)
		{
			return;
		}
		Unit currentUnit = controller.currentUnit;
		if (States.TryGetValue(controller, out var value) && (Object)(object)value.Unit == (Object)(object)currentUnit)
		{
			currentUnit.SetHealthBarActive(false);
			return;
		}
		Restore(controller);
		Component val = (Component)((HealthbarField != null) ? /*isinst with value type is only supported in some contexts*/: null);
		if (!((Object)(object)val == (Object)null))
		{
			States.Add(controller, new VisibilityState
			{
				Unit = currentUnit,
				WasActive = val.gameObject.activeSelf
			});
			currentUnit.SetHealthBarActive(false);
		}
	}

	internal static void Restore(CameraAbilityPossess controller)
	{
		if (!((Object)(object)controller == (Object)null) && States.TryGetValue(controller, out var value))
		{
			States.Remove(controller);
			if ((Object)(object)value.Unit != (Object)null)
			{
				value.Unit.SetHealthBarActive(value.WasActive);
			}
		}
	}
}
[HarmonyPatch(typeof(CameraAbilityPossessUI), "EndPossess")]
internal static class PossessedMagazineHudEndPatch
{
	private static void Postfix(CameraAbilityPossessUI __instance)
	{
		PossessedMagazineHud.Hide(__instance);
	}
}
internal static class PossessedMagazineHud
{
	private sealed class HudLabels
	{
		internal TextMeshProUGUI Left;

		internal TextMeshProUGUI Right;
	}

	private sealed class ReloadStart
	{
		internal readonly float Time;

		internal ReloadStart(float time)
		{
			Time = time;
		}
	}

	private const float LabelWidth = 156f;

	private const float LabelHeight = 38f;

	private const float IconGap = 8f;

	private static readonly ConditionalWeakTable<CameraAbilityPossessUI, HudLabels> Labels = new ConditionalWeakTable<CameraAbilityPossessUI, HudLabels>();

	private static readonly ConditionalWeakTable<RangeWeapon, ReloadStart> ReloadStarts = new ConditionalWeakTable<RangeWeapon, ReloadStart>();

	internal static void RecordReloadStart(RangeWeapon weapon)
	{
		if (!((Object)(object)weapon == (Object)null) && !(weapon.reloadTime <= 0f))
		{
			ReloadStarts.Remove(weapon);
			ReloadStarts.Add(weapon, new ReloadStart(Time.time));
		}
	}

	internal static void Update(CameraAbilityPossessUI ui, RangeWeapon leftWeapon, RangeWeapon rightWeapon)
	{
		if ((Object)(object)ui == (Object)null || (Object)(object)ui.UI == (Object)null)
		{
			return;
		}
		Transform transform = ui.UI.transform;
		RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
		if ((Object)(object)val == (Object)null)
		{
			Transform transform2 = ((Component)ui).transform;
			val = (RectTransform)(object)((transform2 is RectTransform) ? transform2 : null);
		}
		if (!((Object)(object)val == (Object)null))
		{
			HudLabels orCreateLabels = GetOrCreateLabels(ui, val);
			if (orCreateLabels != null)
			{
				UpdateSlot(ui.leftW, orCreateLabels.Left, leftWeapon, isLeft: true, val);
				UpdateSlot(ui.rightW, orCreateLabels.Right, rightWeapon, isLeft: false, val);
			}
		}
	}

	internal static void Hide(CameraAbilityPossessUI ui)
	{
		if ((Object)(object)ui != (Object)null && Labels.TryGetValue(ui, out var value))
		{
			SetVisible(value.Left, visible: false);
			SetVisible(value.Right, visible: false);
		}
	}

	private static HudLabels GetOrCreateLabels(CameraAbilityPossessUI ui, RectTransform rootRect)
	{
		if (Labels.TryGetValue(ui, out var value))
		{
			return value;
		}
		HudLabels hudLabels = new HudLabels
		{
			Left = CreateLabel("TAQoL_LeftMagazineText", rootRect, ui.leftT ?? ui.rightT, alignRight: true),
			Right = CreateLabel("TAQoL_RightMagazineText", rootRect, ui.rightT ?? ui.leftT, alignRight: false)
		};
		if ((Object)(object)hudLabels.Left == (Object)null || (Object)(object)hudLabels.Right == (Object)null)
		{
			if ((Object)(object)hudLabels.Left != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)hudLabels.Left).gameObject);
			}
			if ((Object)(object)hudLabels.Right != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)hudLabels.Right).gameObject);
			}
			return null;
		}
		Labels.Add(ui, hudLabels);
		return hudLabels;
	}

	private static TextMeshProUGUI CreateLabel(string objectName, RectTransform parent, TextMeshProUGUI styleSource, bool alignRight)
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: 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_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: Unknown result type (might be due to invalid IL or missing references)
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)parent == (Object)null)
		{
			return null;
		}
		GameObject val = new GameObject(objectName, new Type[3]
		{
			typeof(RectTransform),
			typeof(CanvasRenderer),
			typeof(TextMeshProUGUI)
		});
		val.transform.SetParent((Transform)(object)parent, false);
		TextMeshProUGUI component = val.GetComponent<TextMeshProUGUI>();
		RectTransform rectTransform = ((TMP_Text)component).rectTransform;
		rectTransform.anchorMin = parent.pivot;
		rectTransform.anchorMax = parent.pivot;
		rectTransform.pivot = (alignRight ? new Vector2(1f, 0.5f) : new Vector2(0f, 0.5f));
		rectTransform.sizeDelta = new Vector2(156f, 38f);
		((Transform)rectTransform).localScale = Vector3.one;
		((Graphic)component).raycastTarget = false;
		((TMP_Text)component).alignment = (TextAlignmentOptions)(alignRight ? 4100 : 4097);
		((TMP_Text)component).fontSize = (((Object)(object)styleSource != (Object)null) ? Mathf.Clamp(((TMP_Text)styleSource).fontSize * 0.72f, 10f, 14f) : 12f);
		((Graphic)component).color = (((Object)(object)styleSource != (Object)null) ? ((Graphic)styleSource).color : Color.white);
		if ((Object)(object)styleSource != (Object)null && (Object)(object)((TMP_Text)styleSource).font != (Object)null)
		{
			((TMP_Text)component).font = ((TMP_Text)styleSource).font;
			((TMP_Text)component).fontSharedMaterial = ((TMP_Text)styleSource).fontSharedMaterial;
		}
		((TMP_Text)component).text = string.Empty;
		val.SetActive(false);
		return component;
	}

	private static void UpdateSlot(GameObject slotObject, TextMeshProUGUI label, RangeWeapon weapon, bool isLeft, RectTransform rootRect)
	{
		//IL_007b: 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_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: 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_0068: 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_0096: 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)
		//IL_009a: 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)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)label == (Object)null || (Object)(object)slotObject == (Object)null || (Object)(object)weapon == (Object)null || weapon.magSize <= 1)
		{
			SetVisible(label, visible: false);
			return;
		}
		Transform transform = slotObject.transform;
		RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
		if ((Object)(object)val == (Object)null)
		{
			SetVisible(label, visible: false);
			return;
		}
		Vector3[] array = (Vector3[])(object)new Vector3[4];
		val.GetWorldCorners(array);
		Vector3 val2 = (isLeft ? ((array[0] + array[1]) * 0.5f) : ((array[2] + array[3]) * 0.5f));
		Vector3 val3 = ((Transform)rootRect).InverseTransformPoint(val2);
		float num = (isLeft ? (-8f) : 8f);
		((TMP_Text)label).rectTransform.anchoredPosition = new Vector2(val3.x + num, val3.y);
		string text = "Magazine: " + weapon.GetAmmo().ToString(CultureInfo.InvariantCulture) + "/" + weapon.magSize.ToString(CultureInfo.InvariantCulture);
		if (TryGetReloadRemaining(weapon, out var remaining))
		{
			text = text + "\nReload: " + remaining.ToString("F3", CultureInfo.InvariantCulture) + "s";
		}
		((TMP_Text)label).text = text;
		SetVisible(label, visible: true);
	}

	private static bool TryGetReloadRemaining(RangeWeapon weapon, out float remaining)
	{
		remaining = 0f;
		if ((Object)(object)weapon == (Object)null || weapon.reloadTime <= 0f || weapon.GetAmmo() >= weapon.magSize || !ReloadStarts.TryGetValue(weapon, out var value))
		{
			return false;
		}
		remaining = Mathf.Max(0f, weapon.reloadTime - (Time.time - value.Time));
		return true;
	}

	private static void SetVisible(TextMeshProUGUI label, bool visible)
	{
		if ((Object)(object)label != (Object)null && ((Component)label).gameObject.activeSelf != visible)
		{
			((Component)label).gameObject.SetActive(visible);
		}
	}
}