Decompiled source of Venture Terrain Reset v0.1.1

Plugins/VentureValheim.TerrainReset.dll

Decompiled 6 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
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 HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("VentureValheim.TerrainReset")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("VentureValheim.TerrainReset")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("085C895B-3942-4A02-9B4A-932E71FF473E")]
[assembly: AssemblyFileVersion("0.1.1")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.1.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace VentureValheim.TerrainReset
{
	[BepInPlugin("com.orianaventure.mod.TerrainReset", "TerrainReset", "0.1.1")]
	public class TerrainResetPlugin : BaseUnityPlugin
	{
		private const string ModName = "TerrainReset";

		private const string ModVersion = "0.1.1";

		private const string Author = "com.orianaventure.mod";

		private const string ModGUID = "com.orianaventure.mod.TerrainReset";

		private static string ConfigFileName = "com.orianaventure.mod.TerrainReset.cfg";

		private static string ConfigFileFullPath;

		private readonly Harmony HarmonyInstance = new Harmony("com.orianaventure.mod.TerrainReset");

		public static readonly ManualLogSource TerrainResetLogger;

		private static readonly TerrainResetPlugin _instance;

		private static ConfigEntry<bool> CE_ModEnabled;

		private static ConfigEntry<KeyCode> CE_HotKey;

		private static ConfigEntry<float> CE_HotKeyRadius;

		private static ConfigEntry<KeyCode> CE_ToolModKey;

		private static ConfigEntry<float> CE_ToolRadius;

		public static TerrainResetPlugin Instance => _instance;

		private TerrainResetPlugin()
		{
		}//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown


		public static bool GetModEnabled()
		{
			return CE_ModEnabled.Value;
		}

		public static KeyCode GetHotKey()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return CE_HotKey.Value;
		}

		public static float GetHotKeyRadius()
		{
			return CE_HotKeyRadius.Value;
		}

		public static KeyCode GetToolModKey()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return CE_ToolModKey.Value;
		}

		public static float GetToolRadius()
		{
			return CE_ToolRadius.Value;
		}

		private void AddConfig<T>(string key, string section, string description, bool synced, T value, ref ConfigEntry<T> configEntry)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			string extendedDescription = GetExtendedDescription(description, synced);
			configEntry = ((BaseUnityPlugin)this).Config.Bind<T>(section, key, value, new ConfigDescription(extendedDescription, (AcceptableValueBase)null, Array.Empty<object>()));
		}

		public string GetExtendedDescription(string description, bool synchronizedSetting)
		{
			return description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]");
		}

		public void Awake()
		{
			AddConfig("Enabled", "General", "Enable this mod (boolean).", synced: false, value: true, ref CE_ModEnabled);
			AddConfig("HotKey", "General", "Hotkey to reset terrain (KeyCode).", synced: false, (KeyCode)0, ref CE_HotKey);
			AddConfig("HotKeyRadius", "General", "Reset radius for hotkey (float).", synced: false, 50f, ref CE_HotKeyRadius);
			AddConfig("ToolModKey", "General", "Modifier key to reset terrain when using tools (KeyCode).", synced: false, (KeyCode)308, ref CE_ToolModKey);
			AddConfig("ToolRadius", "General", "Reset radius for tools. Set to 0 to use the tool's original radius (float).", synced: false, 0f, ref CE_ToolRadius);
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			HarmonyInstance.PatchAll(executingAssembly);
			SetupWatcher();
		}

		private void Update()
		{
			//IL_000e: 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)
			if (GetModEnabled() && !TerrainReset.IgnoreKeyPresses() && TerrainReset.CheckKeyDown(GetHotKey()))
			{
				int num = TerrainReset.ResetTerrain(((Component)Player.m_localPlayer).transform.position, GetHotKeyRadius());
				((Character)Player.m_localPlayer).Message((MessageType)2, $"{num} edits reset.", 0, (Sprite)null);
			}
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}

		private void SetupWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			fileSystemWatcher.Changed += ReadConfigValues;
			fileSystemWatcher.Created += ReadConfigValues;
			fileSystemWatcher.Renamed += ReadConfigValues;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			if (!File.Exists(ConfigFileFullPath))
			{
				return;
			}
			try
			{
				TerrainResetLogger.LogInfo((object)"Attempting to reload configuration...");
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch
			{
				TerrainResetLogger.LogError((object)("There was an issue loading " + ConfigFileName));
			}
		}

		static TerrainResetPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			TerrainResetLogger = Logger.CreateLogSource("TerrainReset");
			_instance = new TerrainResetPlugin();
			CE_ModEnabled = null;
			CE_HotKey = null;
			CE_HotKeyRadius = null;
			CE_ToolModKey = null;
			CE_ToolRadius = null;
		}
	}
	public class TerrainReset
	{
		[HarmonyPatch(typeof(TerrainComp), "ApplyOperation")]
		private static class Patch_TerrainComp_ApplyOperation
		{
			private static bool Prefix(TerrainOp modifier)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				if (TerrainResetPlugin.GetModEnabled() && CheckKeyHeld(TerrainResetPlugin.GetToolModKey()))
				{
					ResetTerrain(((Component)modifier).transform.position, (TerrainResetPlugin.GetToolRadius() > 0f) ? TerrainResetPlugin.GetToolRadius() : modifier.GetRadius());
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(TerrainOp), "OnPlaced")]
		private static class Patch_TerrainOp_OnPlaced
		{
			private static bool Prefix()
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				if (TerrainResetPlugin.GetModEnabled() && CheckKeyHeld(TerrainResetPlugin.GetToolModKey()))
				{
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Terminal), "InitTerminal")]
		private static class Patch_Terminal_InitTerminal
		{
			[Serializable]
			[CompilerGenerated]
			private sealed class <>c
			{
				public static readonly <>c <>9 = new <>c();

				public static ConsoleEvent <>9__1_0;

				internal void <Postfix>b__1_0(ConsoleEventArgs args)
				{
					//IL_0034: Unknown result type (might be due to invalid IL or missing references)
					float result;
					if (args.Length < 2)
					{
						args.Context.AddString("Syntax: resetterrain [radius]");
					}
					else if (float.TryParse(args[1], out result))
					{
						int num = ResetTerrain(((Component)Player.m_localPlayer).transform.position, result);
						args.Context.AddString($"{num} edits reset.");
					}
					else
					{
						args.Context.AddString("Invalid command, syntax: resetterrain [radius as a float]");
					}
				}
			}

			[HarmonyPriority(800)]
			private static void Prefix(out bool __state)
			{
				__state = Terminal.m_terminalInitialized;
			}

			private static void Postfix(bool __state)
			{
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Expected O, but got Unknown
				if (__state || !TerrainResetPlugin.GetModEnabled())
				{
					return;
				}
				TerrainResetPlugin.TerrainResetLogger.LogInfo((object)"Adding Terminal Command \"resetterrain\".");
				try
				{
					object obj = <>c.<>9__1_0;
					if (obj == null)
					{
						ConsoleEvent val = delegate(ConsoleEventArgs args)
						{
							//IL_0034: Unknown result type (might be due to invalid IL or missing references)
							float result;
							if (args.Length < 2)
							{
								args.Context.AddString("Syntax: resetterrain [radius]");
							}
							else if (float.TryParse(args[1], out result))
							{
								int num = ResetTerrain(((Component)Player.m_localPlayer).transform.position, result);
								args.Context.AddString($"{num} edits reset.");
							}
							else
							{
								args.Context.AddString("Invalid command, syntax: resetterrain [radius as a float]");
							}
						};
						<>c.<>9__1_0 = val;
						obj = (object)val;
					}
					new ConsoleCommand("resetterrain", "[name] [radius]", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
				}
				catch (Exception ex)
				{
					TerrainResetPlugin.TerrainResetLogger.LogWarning((object)"Error, could not add terminal command. This can happen when two mods add the same command. The rest of this mod should work as expected.");
					TerrainResetPlugin.TerrainResetLogger.LogWarning((object)ex);
				}
			}
		}

		private static readonly TerrainReset _instance = new TerrainReset();

		public static TerrainReset Instance => _instance;

		private TerrainReset()
		{
		}

		public static bool IgnoreKeyPresses()
		{
			if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !Minimap.IsOpen() && !Console.IsVisible() && !TextInput.IsVisible() && !ZNet.instance.InPasswordDialog() && (!((Object)(object)Chat.instance != (Object)null) || !Chat.instance.HasFocus()) && !StoreGui.IsVisible() && !InventoryGui.IsVisible() && !Menu.IsVisible())
			{
				if ((Object)(object)TextViewer.instance != (Object)null)
				{
					return TextViewer.instance.IsVisible();
				}
				return false;
			}
			return true;
		}

		public static bool CheckKeyDown(KeyCode value)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return ZInput.GetKeyDown(value, true);
		}

		public static bool CheckKeyHeld(KeyCode value)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return ZInput.GetKey(value, true);
		}

		public static int ResetTerrain(Vector3 center, float radius)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			List<Heightmap> list = new List<Heightmap>();
			Heightmap.FindHeightmap(center, radius + 100f, list);
			foreach (TerrainModifier allInstance in TerrainModifier.GetAllInstances())
			{
				Vector3 position = ((Component)allInstance).transform.position;
				ZNetView component = ((Component)allInstance).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid() || !(Utils.DistanceXZ(position, center) <= radius))
				{
					continue;
				}
				if (!component.IsOwner())
				{
					component.ClaimOwnership();
				}
				num++;
				foreach (Heightmap item in list)
				{
					if (item.TerrainVSModifier(allInstance))
					{
						item.Poke(true);
					}
				}
				component.Destroy();
			}
			using (List<Heightmap>.Enumerator enumerator3 = list.GetEnumerator())
			{
				int num2 = default(int);
				int num3 = default(int);
				int num4 = default(int);
				int num5 = default(int);
				while (enumerator3.MoveNext())
				{
					TerrainComp val = TerrainComp.FindTerrainCompiler(((Component)enumerator3.Current).transform.position);
					if (!Object.op_Implicit((Object)(object)val))
					{
						continue;
					}
					if (!val.m_nview.IsOwner())
					{
						val.m_nview.ClaimOwnership();
					}
					if (!val.m_initialized)
					{
						continue;
					}
					enumerator3.Current.WorldToVertex(center, ref num2, ref num3);
					enumerator3.Current.WorldToVertexMask(center, ref num4, ref num5);
					bool flag = false;
					int num6 = val.m_width + 1;
					for (int i = 0; i < num6; i++)
					{
						for (int j = 0; j < num6; j++)
						{
							int num7 = i * num6 + j;
							if (CoordDistance(num2, num3, j, i) <= radius && val.m_modifiedHeight[num7])
							{
								num++;
								flag = true;
								val.m_modifiedHeight[num7] = false;
								val.m_levelDelta[num7] = 0f;
								val.m_smoothDelta[num7] = 0f;
							}
							if (CoordDistance(num4, num5, j, i) <= radius && val.m_modifiedPaint[num7])
							{
								flag = true;
								val.m_modifiedPaint[num7] = false;
								val.m_paintMask[num7] = Color.clear;
							}
						}
					}
					if (flag)
					{
						val.Save();
						enumerator3.Current.Poke(true);
					}
				}
			}
			if ((Object)(object)ClutterSystem.instance != (Object)null)
			{
				ClutterSystem.instance.ResetGrass(center, radius);
			}
			return num;
		}

		private static float CoordDistance(float x, float y, float rx, float ry)
		{
			float num = x - rx;
			float num2 = y - ry;
			return Mathf.Sqrt(num * num + num2 * num2);
		}
	}
}