Decompiled source of GetOffMyLawn v1.10.0

GetOffMyLawn.dll

Decompiled 13 hours 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.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ComfyLib;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("GetOffMyLawn")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GetOffMyLawn")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("514d9344-a1b0-4edf-93a8-17c7ae859946")]
[assembly: AssemblyFileVersion("1.10.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.10.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 GetOffMyLawn
{
	public static class PieceUtils
	{
		private static readonly List<Piece> _pieceCache = new List<Piece>();

		private static int _pieceCount = 0;

		public static bool CanRemovePiece(Piece piece)
		{
			Vagon component2;
			if (!((Component)(object)piece).TryGetComponentInChildren<Ship>(out Ship _))
			{
				return ((Component)(object)piece).TryGetComponentInChildren<Vagon>(out component2);
			}
			return true;
		}

		public static bool RepairPiece(this Player player, ItemData toolItem, Piece piece)
		{
			//IL_003d: 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_00a5: Unknown result type (might be due to invalid IL or missing references)
			Plant val = default(Plant);
			if (!Object.op_Implicit((Object)(object)piece) || !Object.op_Implicit((Object)(object)piece.m_nview) || !piece.m_nview.IsValid() || ((Component)piece).TryGetComponent<Plant>(ref val))
			{
				return false;
			}
			if (!player.CheckCanRemovePiece(piece) || !PrivateArea.CheckAccess(((Component)piece).transform.position, 0f, true, false))
			{
				return false;
			}
			RepairPiece(piece, PluginConfig.TargetPieceHealth.Value, Time.time);
			player.FaceLookDirection();
			((Character)player).m_zanim.SetTrigger(toolItem.m_shared.m_attack.m_attackAnimation);
			EffectList placeEffect = piece.m_placeEffect;
			if (placeEffect != null)
			{
				placeEffect.Create(((Component)piece).transform.position, ((Component)piece).transform.rotation, (Transform)null, 1f, -1);
			}
			if (PluginConfig.ShowTopLeftMessageOnPieceRepair.Value)
			{
				((Character)player).Message((MessageType)1, Localization.instance.Localize("$msg_repaired", new string[1] { piece.m_name }), 0, (Sprite)null);
			}
			return true;
		}

		public static void RepairPiece(Piece piece, float targetHealth, float repairTime)
		{
			piece.m_nview.ClaimOwnership();
			piece.m_nview.m_zdo.Set(ZDOVars.s_health, targetHealth);
			WearNTear val = default(WearNTear);
			if (((Component)piece).TryGetComponent<WearNTear>(ref val))
			{
				val.m_lastRepair = repairTime;
				val.m_healthPercentage = Mathf.Clamp01(targetHealth / val.m_health);
				val.SetHealthVisual(val.m_healthPercentage, true);
			}
		}

		public static void RepairPiecesInRadius(Vector3 origin, float radius)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			_pieceCache.Clear();
			_pieceCount = 0;
			GetAllPiecesInRadius(origin, radius, _pieceCache);
			float value = PluginConfig.TargetPieceHealth.Value;
			float time = Time.time;
			Plant val = default(Plant);
			foreach (Piece item in _pieceCache)
			{
				if (!Object.op_Implicit((Object)(object)item) || !Object.op_Implicit((Object)(object)item.m_nview) || !item.m_nview.IsValid() || ((Component)item).TryGetComponent<Plant>(ref val))
				{
					continue;
				}
				RepairPiece(item, value, time);
				if (PluginConfig.ShowRepairEffectOnWardActivation.Value)
				{
					EffectList placeEffect = item.m_placeEffect;
					if (placeEffect != null)
					{
						placeEffect.Create(((Component)item).transform.position, ((Component)item).transform.rotation, (Transform)null, 1f, -1);
					}
				}
				_pieceCount++;
			}
			GetOffMyLawn.LogInfo($"Repaired {_pieceCount} pieces to health: {PluginConfig.TargetPieceHealth.Value}");
			if (PluginConfig.ShowTopLeftMessageOnPieceRepair.Value)
			{
				((Character)Player.m_localPlayer).Message((MessageType)1, $"Repaired {_pieceCount} pieces to health: {PluginConfig.TargetPieceHealth.Value}", 0, (Sprite)null);
			}
			_pieceCache.Clear();
		}

		private static void GetAllPiecesInRadius(Vector3 origin, float radius, List<Piece> pieces)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			foreach (Piece s_allPiece in Piece.s_allPieces)
			{
				if (((Component)s_allPiece).gameObject.layer != Piece.s_ghostLayer && !(Vector3.Distance(origin, ((Component)s_allPiece).transform.position) >= radius))
				{
					pieces.Add(s_allPiece);
				}
			}
		}
	}
	[BepInPlugin("redseiko.valheim.getoffmylawn", "GetOffMyLawn", "1.10.0")]
	public sealed class GetOffMyLawn : BaseUnityPlugin
	{
		public const string PluginGUID = "redseiko.valheim.getoffmylawn";

		public const string PluginName = "GetOffMyLawn";

		public const string PluginVersion = "1.10.0";

		private static ManualLogSource _logger;

		private void Awake()
		{
			_logger = ((BaseUnityPlugin)this).Logger;
			PluginConfig.BindConfig(((BaseUnityPlugin)this).Config);
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "redseiko.valheim.getoffmylawn");
		}

		public static void LogInfo(object obj)
		{
			_logger.LogInfo((object)$"[{DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo)}] {obj}");
		}

		public static void LogWarning(object obj)
		{
			_logger.LogWarning((object)$"[{DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo)}] {obj}");
		}
	}
	[HarmonyPatch(typeof(BaseAI))]
	internal static class BaseAIPatch
	{
		public static int TargetRayMask;

		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		private static void AwakePostfix()
		{
			if (PluginConfig.IsModEnabled.Value && TargetRayMask == 0)
			{
				TargetRayMask = LayerMask.GetMask(new string[4] { "Default", "static_solid", "Default_small", "vehicle" });
				BaseAI.m_monsterTargetRayMask = TargetRayMask;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("FindRandomStaticTarget")]
		private static bool FindRandomStaticTargetPrefix(ref StaticTarget __result)
		{
			if (PluginConfig.IsModEnabled.Value)
			{
				__result = null;
				return false;
			}
			return true;
		}

		[HarmonyPrefix]
		[HarmonyPatch("FindClosestStaticPriorityTarget")]
		private static bool FindClosestStaticPriorityTargetPrefix(ref StaticTarget __result)
		{
			if (PluginConfig.IsModEnabled.Value)
			{
				__result = null;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(MonsterAI))]
	internal static class MonsterAIPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		private static void AwakePostfix(ref MonsterAI __instance)
		{
			if (PluginConfig.IsModEnabled.Value)
			{
				__instance.m_attackPlayerObjects = false;
			}
		}
	}
	[HarmonyPatch(typeof(Piece))]
	internal static class PiecePatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("SetCreator")]
		private static void SetCreatorPostfix(Piece __instance)
		{
			Plant val = default(Plant);
			if (PluginConfig.IsModEnabled.Value && Object.op_Implicit((Object)(object)__instance) && Object.op_Implicit((Object)(object)__instance.m_nview) && __instance.m_nview.IsValid() && !((Component)__instance).TryGetComponent<Plant>(ref val))
			{
				__instance.m_nview.m_zdo.Set(ZDOVars.s_health, PluginConfig.TargetPieceHealth.Value);
			}
		}
	}
	[HarmonyPatch(typeof(Player))]
	internal static class PlayerPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("Repair")]
		private static bool RepairPrefix(Player __instance, ItemData toolItem)
		{
			if (PluginConfig.IsModEnabled.Value)
			{
				__instance.RepairPiece(toolItem, __instance.m_hoveringPiece);
				return false;
			}
			return true;
		}

		[HarmonyTranspiler]
		[HarmonyPatch("RemovePiece")]
		private static IEnumerable<CodeInstruction> RemovePieceTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).Start().MatchStartForward((CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Ldfld, (object)typeof(Piece).GetField("m_canBeRemoved"), (string)null)
			}).ThrowIfInvalid("Could not patch Player.RemovePiece()! (m_canBeRemoved)")
				.Advance(1)
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[2]
				{
					new CodeInstruction(OpCodes.Ldloc_1, (object)null),
					Transpilers.EmitDelegate<Func<bool, Piece, bool>>((Func<bool, Piece, bool>)CanBeRemovedDelegate)
				})
				.InstructionEnumeration();
		}

		private static bool CanBeRemovedDelegate(bool canBeRemoved, Piece piece)
		{
			if (!canBeRemoved)
			{
				if (PluginConfig.IsModEnabled.Value)
				{
					return PieceUtils.CanRemovePiece(piece);
				}
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PrivateArea))]
	internal static class PrivateAreaPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Interact")]
		private static void InteractPostfix(PrivateArea __instance)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if (PluginConfig.IsModEnabled.Value && PluginConfig.RepairPiecesOnWardActivation.Value && Object.op_Implicit((Object)(object)__instance) && __instance.IsEnabled() && __instance.m_piece.IsCreator())
			{
				PieceUtils.RepairPiecesInRadius(((Component)__instance).transform.position, __instance.m_radius);
			}
		}
	}
	[HarmonyPatch(typeof(WearNTear))]
	internal static class WearNTearPatch
	{
		public static readonly long PieceHealthDamageThreshold = 100000L;

		[HarmonyPrefix]
		[HarmonyPatch("ApplyDamage", new Type[]
		{
			typeof(float),
			typeof(HitData)
		})]
		private static bool ApplyDamagePrefix(WearNTear __instance, float damage, HitData hitData, ref bool __result)
		{
			if (PluginConfig.IsModEnabled.Value && PluginConfig.EnablePieceHealthDamageThreshold.Value)
			{
				__result = ApplyDamageDelegate(__instance, damage, hitData);
				return false;
			}
			return true;
		}

		public static bool ApplyDamageDelegate(WearNTear wearNTear, float damage, HitData hitData)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			float @float = wearNTear.m_nview.m_zdo.GetFloat(ZDOVars.s_health, wearNTear.m_health);
			if (@float <= 0f || @float >= (float)PieceHealthDamageThreshold)
			{
				return false;
			}
			@float -= damage;
			wearNTear.m_nview.m_zdo.Set(ZDOVars.s_health, @float);
			if (@float <= 0f)
			{
				wearNTear.Destroy(hitData, false);
			}
			else
			{
				ZRoutedRpc.s_instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "RPC_HealthChanged", new object[2]
				{
					wearNTear.m_nview.m_zdo.m_uid,
					@float
				});
			}
			return true;
		}
	}
	public static class PluginConfig
	{
		public static ConfigEntry<bool> IsModEnabled { get; private set; }

		public static ConfigEntry<float> TargetPieceHealth { get; private set; }

		public static ConfigEntry<bool> RepairPiecesOnWardActivation { get; private set; }

		public static ConfigEntry<bool> EnablePieceHealthDamageThreshold { get; private set; }

		public static ConfigEntry<bool> ShowTopLeftMessageOnPieceRepair { get; private set; }

		public static ConfigEntry<bool> ShowRepairEffectOnWardActivation { get; private set; }

		public static void BindConfig(ConfigFile config)
		{
			IsModEnabled = config.BindInOrder("_Global", "isModEnabled", defaultValue: true, "Globally enable or disable this mod.");
			TargetPieceHealth = config.BindInOrder("PieceValue", "targetPieceHealth", 1E+17f, "Target value to set piece health to when creating and repairing.");
			RepairPiecesOnWardActivation = config.BindInOrder("Behaviour", "repairPiecesOnWardActivation", defaultValue: true, "IF set, will repair all Pieces in Ward range when a Ward is activated.");
			EnablePieceHealthDamageThreshold = config.BindInOrder("Optimization", "enablePieceHealthDamageThreshold", defaultValue: true, "If piece health exceeds 100K, DO NOT execute ApplyDamage() or send WNTHealthChanged messages.");
			ShowTopLeftMessageOnPieceRepair = config.BindInOrder("Indicators", "showTopLeftMessageOnPieceRepair", defaultValue: false, "Shows a message in the top-left message area on piece repair.");
			ShowRepairEffectOnWardActivation = config.BindInOrder("Indicators", "showRepairEffectOnWardActivation", defaultValue: false, "Shows the repair effect on affected pieces when activating a ward.");
		}
	}
}
namespace ComfyLib
{
	public static class ConfigFileExtensions
	{
		internal sealed class ConfigurationManagerAttributes
		{
			public Action<ConfigEntryBase> CustomDrawer;

			public bool? Browsable;

			public bool? HideDefaultButton;

			public bool? HideSettingName;

			public bool? IsAdvanced;

			public int? Order;

			public bool? ReadOnly;
		}

		private static readonly Dictionary<string, int> _sectionToSettingOrder = new Dictionary<string, int>();

		private static int GetSettingOrder(string section)
		{
			if (!_sectionToSettingOrder.TryGetValue(section, out var value))
			{
				value = 0;
			}
			_sectionToSettingOrder[section] = value - 1;
			return value;
		}

		public static ConfigEntry<T> BindInOrder<T>(this ConfigFile config, string section, string key, T defaultValue, string description, AcceptableValueBase acceptableValues)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, acceptableValues, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = GetSettingOrder(section)
				}
			}));
		}

		public static ConfigEntry<T> BindInOrder<T>(this ConfigFile config, string section, string key, T defaultValue, string description, Action<ConfigEntryBase> customDrawer = null, bool browsable = true, bool hideDefaultButton = false, bool hideSettingName = false, bool isAdvanced = false, bool readOnly = false)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = browsable,
					CustomDrawer = customDrawer,
					HideDefaultButton = hideDefaultButton,
					HideSettingName = hideSettingName,
					IsAdvanced = isAdvanced,
					Order = GetSettingOrder(section),
					ReadOnly = readOnly
				}
			}));
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action settingChangedHandler)
		{
			configEntry.SettingChanged += delegate
			{
				settingChangedHandler();
			};
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action<T> settingChangedHandler)
		{
			configEntry.SettingChanged += delegate(object _, EventArgs eventArgs)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				settingChangedHandler((T)((SettingChangedEventArgs)eventArgs).ChangedSetting.BoxedValue);
			};
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action<ConfigEntry<T>> settingChangedHandler)
		{
			configEntry.SettingChanged += delegate(object _, EventArgs eventArgs)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				settingChangedHandler((ConfigEntry<T>)((SettingChangedEventArgs)eventArgs).ChangedSetting.BoxedValue);
			};
		}
	}
	public static class ComponentExtensions
	{
		public static bool TryGetComponentInChildren<T>(this Component rootComponent, out T component) where T : Component
		{
			component = rootComponent.GetComponentInChildren<T>(true);
			return Object.op_Implicit((Object)(object)component);
		}
	}
	public static class ObjectExtensions
	{
		public static T FirstByNameOrThrow<T>(this T[] unityObjects, string name) where T : Object
		{
			foreach (T val in unityObjects)
			{
				if (((Object)val).name == name)
				{
					return val;
				}
			}
			throw new InvalidOperationException($"Could not find Unity object of type {typeof(T)} with name: {name}");
		}

		public static T Ref<T>(this T unityObject) where T : Object
		{
			if (!Object.op_Implicit((Object)(object)unityObject))
			{
				return default(T);
			}
			return unityObject;
		}
	}
}