Decompiled source of TerraMeshAsync v1.0.0

TerraMeshAsync.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TerraMesh;
using TerraMesh.Utils;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("TerraMeshAsync")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("TerraMeshAsync")]
[assembly: AssemblyTitle("TerraMeshAsync")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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;
		}
	}
}
[BepInPlugin("local.TerraMeshAsync", "TerraMeshAsync", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class TerraMeshAsync : BaseUnityPlugin
{
	private class Job
	{
		public Task Task;

		public MeshifyTerrainData Data;

		public Mesh Mesh;

		public MeshCollider Collider;

		public string Name;

		public Stopwatch Clock;
	}

	private class Finisher : MonoBehaviour
	{
		private void Update()
		{
			for (int num = jobs.Count - 1; num >= 0; num--)
			{
				Job job = jobs[num];
				if (job.Task.IsCompleted)
				{
					jobs.RemoveAt(num);
					if (job.Task.IsFaulted)
					{
						log.LogWarning((object)(job.Name + ": full-detail mesh failed, keeping the low-detail one (" + job.Task.Exception?.GetBaseException().Message + ")"));
					}
					else if (!((Object)(object)job.Mesh == (Object)null))
					{
						Stopwatch stopwatch = Stopwatch.StartNew();
						Apply(job.Mesh, (MeshifyData)(object)job.Data);
						if ((Object)(object)job.Collider != (Object)null)
						{
							job.Collider.sharedMesh = job.Mesh;
						}
						log.LogInfo((object)$"{job.Name}: full-detail mesh in place after {job.Clock.Elapsed.TotalSeconds:F1} s ({stopwatch.ElapsedMilliseconds} ms on the main thread)");
					}
				}
			}
		}
	}

	private const int PlaceholderStep = 8;

	private static ManualLogSource log;

	private static Action<TerraMeshConfig, MeshifyTerrainData> generateMeshData;

	private static Func<Terrain, TerraMeshConfig, MeshifyTerrainData, GameObject> buildMeshObject;

	private static readonly List<Job> jobs = new List<Job>();

	private void Awake()
	{
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_0145: Expected O, but got Unknown
		//IL_014b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_015e: Expected O, but got Unknown
		log = ((BaseUnityPlugin)this).Logger;
		try
		{
			BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
			generateMeshData = (Action<TerraMeshConfig, MeshifyTerrainData>)Delegate.CreateDelegate(typeof(Action<TerraMeshConfig, MeshifyTerrainData>), typeof(TerraMeshExtensions).GetMethod("GenerateMeshData", bindingAttr, null, new Type[2]
			{
				typeof(TerraMeshConfig),
				typeof(MeshifyTerrainData)
			}, null));
			buildMeshObject = (Func<Terrain, TerraMeshConfig, MeshifyTerrainData, GameObject>)Delegate.CreateDelegate(typeof(Func<Terrain, TerraMeshConfig, MeshifyTerrainData, GameObject>), typeof(TerraMeshExtensions).GetMethod("Meshify", bindingAttr, null, new Type[3]
			{
				typeof(Terrain),
				typeof(TerraMeshConfig),
				typeof(MeshifyTerrainData)
			}, null));
		}
		catch (Exception ex)
		{
			log.LogWarning((object)("TerraMesh internals changed, leaving conversion as is: " + ex.Message));
			return;
		}
		new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID).Patch((MethodBase)AccessTools.Method(typeof(TerraMeshExtensions), "Meshify", new Type[2]
		{
			typeof(Terrain),
			typeof(TerraMeshConfig)
		}, (Type[])null), new HarmonyMethod(typeof(TerraMeshAsync), "MeshifyPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		GameObject val = new GameObject("TerraMeshAsync")
		{
			hideFlags = (HideFlags)61
		};
		Object.DontDestroyOnLoad((Object)val);
		val.AddComponent<Finisher>();
	}

	private static bool MeshifyPrefix(Terrain terrain, TerraMeshConfig config, ref GameObject __result)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Expected O, but got Unknown
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: 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_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Expected O, but got Unknown
		if ((Object)(object)terrain == (Object)null || (Object)(object)terrain.terrainData == (Object)null)
		{
			return true;
		}
		Stopwatch stopwatch = Stopwatch.StartNew();
		GameObject val = null;
		try
		{
			MeshifyTerrainData val2 = new MeshifyTerrainData(terrain);
			TerraMeshConfig val3 = config;
			val3.minMeshStep = Math.Max(config.minMeshStep, 8);
			val3.maxMeshStep = Math.Max(config.maxMeshStep, val3.minMeshStep);
			val3.refineMesh = false;
			val3.smoothMesh = false;
			generateMeshData(val3, val2);
			val = buildMeshObject(terrain, config, val2);
			MeshifyTerrainData full = new MeshifyTerrainData(terrain);
			jobs.Add(new Job
			{
				Task = Task.Run(delegate
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					generateMeshData(config, full);
				}),
				Data = full,
				Mesh = val.GetComponent<MeshFilter>().sharedMesh,
				Collider = val.GetComponent<MeshCollider>(),
				Name = ((Object)terrain).name,
				Clock = stopwatch
			});
			log.LogInfo((object)$"{((Object)terrain).name}: low-detail mesh in {stopwatch.ElapsedMilliseconds} ms, full detail building in the background");
			__result = val;
			return false;
		}
		catch (Exception ex)
		{
			log.LogWarning((object)(((Object)terrain).name + ": falling back to TerraMesh's normal conversion (" + ex.Message + ")"));
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
			return true;
		}
	}

	private static void Apply(Mesh mesh, MeshifyData data)
	{
		Vector3[] array = data.vertices.ToArray();
		mesh.Clear();
		mesh.indexFormat = (IndexFormat)(array.Length > 65535);
		mesh.vertices = array;
		mesh.uv = data.uvs.ToArray();
		mesh.triangles = data.triangles.ToArray();
		mesh.RecalculateBounds();
		mesh.RecalculateNormals();
		mesh.RecalculateTangents();
	}
}