Decompiled source of CrystalFloorWeather v1.0.0

CrystalFloorWeather.dll

Decompiled 5 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("CrystalFloorWeather")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CrystalFloorWeather")]
[assembly: AssemblyTitle("CrystalFloorWeather")]
[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;
		}
	}
}
namespace CrystalFloorWeather
{
	[BepInPlugin("groshyr.crystalfloorweather", "CrystalFloorWeather", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class WeatherBox
		{
			private static readonly Vector3[] Corners = (Vector3[])(object)new Vector3[8]
			{
				new Vector3(-0.5f, -0.5f, -0.5f),
				new Vector3(0.5f, -0.5f, -0.5f),
				new Vector3(0.5f, -0.5f, 0.5f),
				new Vector3(-0.5f, -0.5f, 0.5f),
				new Vector3(-0.5f, 0.5f, -0.5f),
				new Vector3(0.5f, 0.5f, -0.5f),
				new Vector3(0.5f, 0.5f, 0.5f),
				new Vector3(-0.5f, 0.5f, 0.5f)
			};

			private static readonly Vector3[] Vertices = (Vector3[])(object)new Vector3[Corners.Length];

			private static readonly int[] Triangles = new int[36]
			{
				0, 1, 2, 0, 2, 3, 4, 7, 6, 4,
				6, 5, 0, 4, 5, 0, 5, 1, 1, 5,
				6, 1, 6, 2, 2, 6, 7, 2, 7, 3,
				3, 7, 4, 3, 4, 0
			};

			private static readonly int[] MirroredTriangles = ReversedTriangles();

			private readonly BoxCollider _collider;

			private Matrix4x4 _localToWorld;

			private Vector3 _center;

			private Vector3 _size;

			private Matrix4x4 _boxToWorld;

			private Bounds _bounds;

			private Mesh _mesh;

			private MeshRenderer _renderer;

			private bool _dirty;

			private int _layer;

			public WeatherBox(BoxCollider collider)
			{
				_collider = collider;
			}

			public bool IsVisible(int mask)
			{
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0074: Unknown result type (might be due to invalid IL or missing references)
				//IL_0079: Unknown result type (might be due to invalid IL or missing references)
				//IL_0085: Unknown result type (might be due to invalid IL or missing references)
				//IL_008a: 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_00b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ba: 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_00c1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00db: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
				//IL_0184: Unknown result type (might be due to invalid IL or missing references)
				//IL_0189: Unknown result type (might be due to invalid IL or missing references)
				//IL_018e: 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_01a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				if (!Object.op_Implicit((Object)(object)_collider) || !((Collider)_collider).enabled || !((Component)_collider).gameObject.activeInHierarchy)
				{
					return false;
				}
				_layer = ((Component)_collider).gameObject.layer;
				if (_layer == _ghostLayer || (mask & (1 << _layer)) == 0)
				{
					return false;
				}
				Vector3 center = _collider.center;
				Vector3 size = _collider.size;
				Matrix4x4 localToWorldMatrix = ((Component)_collider).transform.localToWorldMatrix;
				if (!((Matrix4x4)(ref _localToWorld)).Equals(localToWorldMatrix) || !((Vector3)(ref _center)).Equals(center) || !((Vector3)(ref _size)).Equals(size))
				{
					_center = center;
					_size = size;
					_localToWorld = localToWorldMatrix;
					_boxToWorld = localToWorldMatrix * Matrix4x4.TRS(center, Quaternion.identity, size);
					_bounds = new Bounds(((Matrix4x4)(ref localToWorldMatrix)).MultiplyPoint3x4(center), new Vector3(Mathf.Abs(_boxToWorld.m00) + Mathf.Abs(_boxToWorld.m01) + Mathf.Abs(_boxToWorld.m02), Mathf.Abs(_boxToWorld.m10) + Mathf.Abs(_boxToWorld.m11) + Mathf.Abs(_boxToWorld.m12), Mathf.Abs(_boxToWorld.m20) + Mathf.Abs(_boxToWorld.m21) + Mathf.Abs(_boxToWorld.m22)));
					_dirty = true;
				}
				return GeometryUtility.TestPlanesAABB(Frustum, _bounds);
			}

			public MeshRenderer GetRenderer(Material material)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: 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)
				//IL_002f: Expected O, but got Unknown
				//IL_008b: 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_009b: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Expected O, but got Unknown
				//IL_0128: Unknown result type (might be due to invalid IL or missing references)
				//IL_012d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0132: Unknown result type (might be due to invalid IL or missing references)
				//IL_0156: Unknown result type (might be due to invalid IL or missing references)
				//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
				if (!Object.op_Implicit((Object)(object)_renderer))
				{
					GameObject val = new GameObject("CrystalFloorWeather box")
					{
						hideFlags = (HideFlags)61,
						layer = _layer
					};
					MeshFilter obj = val.AddComponent<MeshFilter>();
					_renderer = val.AddComponent<MeshRenderer>();
					((Renderer)_renderer).enabled = false;
					((Renderer)_renderer).shadowCastingMode = (ShadowCastingMode)0;
					((Renderer)_renderer).receiveShadows = false;
					((Renderer)_renderer).lightProbeUsage = (LightProbeUsage)0;
					((Renderer)_renderer).reflectionProbeUsage = (ReflectionProbeUsage)0;
					if (!Object.op_Implicit((Object)(object)_mesh))
					{
						_mesh = new Mesh
						{
							name = "CrystalFloorWeather box",
							hideFlags = (HideFlags)61
						};
					}
					obj.sharedMesh = _mesh;
					_dirty = true;
				}
				if ((Object)(object)((Renderer)_renderer).sharedMaterial != (Object)(object)material)
				{
					((Renderer)_renderer).sharedMaterial = material;
				}
				if (((Component)_renderer).gameObject.layer != _layer)
				{
					((Component)_renderer).gameObject.layer = _layer;
				}
				if (_dirty)
				{
					for (int i = 0; i < Corners.Length; i++)
					{
						Vertices[i] = ((Matrix4x4)(ref _boxToWorld)).MultiplyVector(Corners[i]);
					}
					((Component)_renderer).transform.position = ((Bounds)(ref _bounds)).center;
					_mesh.SetVertices(Vertices, 0, Vertices.Length, (MeshUpdateFlags)8);
					_mesh.SetTriangles((((Matrix4x4)(ref _boxToWorld)).determinant < 0f) ? MirroredTriangles : Triangles, 0, false);
					_mesh.bounds = new Bounds(Vector3.zero, ((Bounds)(ref _bounds)).size);
					_dirty = false;
				}
				return _renderer;
			}

			public void Destroy()
			{
				if (Object.op_Implicit((Object)(object)_renderer))
				{
					((Renderer)_renderer).enabled = false;
					Object.Destroy((Object)(object)((Component)_renderer).gameObject);
				}
				if (Object.op_Implicit((Object)(object)_mesh))
				{
					Object.Destroy((Object)(object)_mesh);
				}
			}

			private static int[] ReversedTriangles()
			{
				int[] array = new int[Triangles.Length];
				for (int i = 0; i < array.Length; i += 3)
				{
					array[i] = Triangles[i];
					array[i + 1] = Triangles[i + 2];
					array[i + 2] = Triangles[i + 1];
				}
				return array;
			}
		}

		private const string Guid = "groshyr.crystalfloorweather";

		private const string VpoGuid = "dev.ontrigger.vpo";

		private const string VpoSkyDepth = "ValheimPerformanceOptimizations.Patches.IndirectRendering.SkyDepthPatches";

		private static readonly int SlabPrefab = StringExtensionMethods.GetStableHashCode("rae_crystal_floorslab");

		private static readonly int RoofFlag = StringExtensionMethods.GetStableHashCode("PT_FloorRoof");

		private static readonly Dictionary<ZNetView, WeatherBox> Boxes = new Dictionary<ZNetView, WeatherBox>();

		private static readonly List<MeshRenderer> EnabledRenderers = new List<MeshRenderer>();

		private static readonly Plane[] Frustum = (Plane[])(object)new Plane[6];

		private static Material _material;

		private static int _ghostLayer;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Expected O, but got Unknown
			if ((int)SystemInfo.graphicsDeviceType == 4)
			{
				return;
			}
			_ghostLayer = LayerMask.NameToLayer("ghost");
			_harmony = new Harmony("groshyr.crystalfloorweather");
			HarmonyMethod val = new HarmonyMethod(typeof(Plugin), "ReplaceDepthRender", (Type[])null);
			try
			{
				_harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(DepthCamera), "RenderDepth", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "AddInstance", new Type[2]
				{
					typeof(ZDO),
					typeof(ZNetView)
				}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "InstanceAdded", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetView), "OnDestroy", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "InstanceDestroyed", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch
			{
				_harmony.UnpatchSelf();
				_harmony = null;
				throw;
			}
			if (!Chainloader.PluginInfos.TryGetValue("dev.ontrigger.vpo", out var value) || !Object.op_Implicit((Object)(object)value.Instance))
			{
				return;
			}
			Type type = ((object)value.Instance).GetType().Assembly.GetType("ValheimPerformanceOptimizations.Patches.IndirectRendering.SkyDepthPatches");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "Render", new Type[2]
			{
				typeof(DepthCamera),
				typeof(int)
			}, (Type[])null));
			if (methodInfo == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"VPO's deferred weather render was not found; only vanilla weather rendering is patched.");
				return;
			}
			try
			{
				_harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception arg)
			{
				_harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)3, "groshyr.crystalfloorweather");
				((BaseUnityPlugin)this).Logger.LogWarning((object)$"Could not patch VPO's deferred weather render: {arg}");
			}
		}

		private void OnDestroy()
		{
			if (_harmony == null)
			{
				return;
			}
			_harmony.UnpatchSelf();
			DisableRenderers();
			foreach (WeatherBox value in Boxes.Values)
			{
				value.Destroy();
			}
			Boxes.Clear();
			if (Object.op_Implicit((Object)(object)_material))
			{
				Object.Destroy((Object)(object)_material);
			}
			_material = null;
		}

		private static void InstanceAdded(ZNetView __1)
		{
			Track(__1);
		}

		private static void Track(ZNetView view)
		{
			Piece val = default(Piece);
			BoxCollider collider = default(BoxCollider);
			if (Object.op_Implicit((Object)(object)view) && view.IsValid() && view.GetZDO().GetPrefab() == SlabPrefab && !Boxes.ContainsKey(view) && ((Component)view).TryGetComponent<Piece>(ref val) && ((Component)view).TryGetComponent<BoxCollider>(ref collider))
			{
				Boxes.Add(view, new WeatherBox(collider));
			}
		}

		private static void InstanceDestroyed(ZNetView __instance)
		{
			if (Boxes.TryGetValue(__instance, out var value))
			{
				Boxes.Remove(__instance);
				value.Destroy();
			}
		}

		private static IEnumerable<CodeInstruction> ReplaceDepthRender(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			MethodInfo objB = AccessTools.DeclaredMethod(typeof(Camera), "RenderWithShader", new Type[2]
			{
				typeof(Shader),
				typeof(string)
			}, (Type[])null);
			MethodInfo operand = AccessTools.DeclaredMethod(typeof(Plugin), "RenderWithWeatherBoxes", (Type[])null, (Type[])null);
			CodeInstruction val = null;
			foreach (CodeInstruction item in list)
			{
				if ((!(item.opcode != OpCodes.Callvirt) || !(item.opcode != OpCodes.Call)) && object.Equals(item.operand, objB))
				{
					if (val != null)
					{
						throw new InvalidOperationException("Expected a single Camera.RenderWithShader call in the weather render.");
					}
					val = item;
				}
			}
			if (val == null)
			{
				throw new InvalidOperationException("No Camera.RenderWithShader call found in the weather render.");
			}
			val.opcode = OpCodes.Call;
			val.operand = operand;
			return list;
		}

		private static void RenderWithWeatherBoxes(Camera camera, Shader shader, string replacementTag)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (Boxes.Count == 0 || !Object.op_Implicit((Object)(object)camera) || !Object.op_Implicit((Object)(object)shader) || !Object.op_Implicit((Object)(object)camera.targetTexture) || EnabledRenderers.Count != 0)
			{
				camera.RenderWithShader(shader, replacementTag);
				return;
			}
			GeometryUtility.CalculateFrustumPlanes(camera.cullingMatrix, Frustum);
			int cullingMask = camera.cullingMask;
			try
			{
				foreach (KeyValuePair<ZNetView, WeatherBox> box in Boxes)
				{
					ZNetView key = box.Key;
					WeatherBox value = box.Value;
					if (Object.op_Implicit((Object)(object)key) && key.IsValid() && key.GetZDO().GetBool(RoofFlag, false) && value.IsVisible(cullingMask))
					{
						MeshRenderer renderer = value.GetRenderer(DepthMaterial(shader));
						EnabledRenderers.Add(renderer);
						((Renderer)renderer).enabled = true;
					}
				}
				camera.RenderWithShader(shader, replacementTag);
			}
			finally
			{
				DisableRenderers();
			}
		}

		private static Material DepthMaterial(Shader shader)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)_material) || (Object)(object)_material.shader != (Object)(object)shader)
			{
				if (Object.op_Implicit((Object)(object)_material))
				{
					Object.Destroy((Object)(object)_material);
				}
				_material = new Material(shader)
				{
					name = "CrystalFloorWeather depth",
					hideFlags = (HideFlags)61
				};
			}
			return _material;
		}

		private static void DisableRenderers()
		{
			foreach (MeshRenderer enabledRenderer in EnabledRenderers)
			{
				if (Object.op_Implicit((Object)(object)enabledRenderer))
				{
					((Renderer)enabledRenderer).enabled = false;
				}
			}
			EnabledRenderers.Clear();
		}
	}
}