Decompiled source of TranslucentCart v1.0.0

TranslucentCart.dll

Decompiled 21 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
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;
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: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("Tolga")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("TranslucentCart")]
[assembly: AssemblyTitle("TranslucentCart")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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.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;
		}
	}
	[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 TranslucentCart
{
	[HarmonyPatch(typeof(PhysGrabCart))]
	internal static class PhysGrabCartPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void Start_Postfix(PhysGrabCart __instance)
		{
			TranslucentCart.ApplyCartTransparency(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("StateSwitchRPC")]
		private static void StateSwitchRPC_Postfix(PhysGrabCart __instance)
		{
			TranslucentCart.ApplyCartTransparency(__instance);
		}
	}
	[HarmonyPatch(typeof(PhysGrabObject))]
	internal static class PhysGrabObjectCartGrabPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("GrabStarted")]
		private static void GrabStarted_Postfix(PhysGrabObject __instance)
		{
			PhysGrabCart component = ((Component)__instance).GetComponent<PhysGrabCart>();
			if (Object.op_Implicit((Object)(object)component))
			{
				TranslucentCart.ApplyCartTransparency(component);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("GrabEnded")]
		private static void GrabEnded_Postfix(PhysGrabObject __instance)
		{
			PhysGrabCart component = ((Component)__instance).GetComponent<PhysGrabCart>();
			if (Object.op_Implicit((Object)(object)component))
			{
				TranslucentCart.ApplyCartTransparency(component);
			}
		}
	}
	[BepInPlugin("Tolga.TranslucentCart", "TranslucentCart", "1.0")]
	public class TranslucentCart : BaseUnityPlugin
	{
		private struct MaterialSnapshot
		{
			public bool Initialized;

			public int RenderQueue;

			public string RenderTypeTag;

			public bool HasSurface;

			public float Surface;

			public bool HasMode;

			public float Mode;

			public bool HasSrcBlend;

			public int SrcBlend;

			public bool HasDstBlend;

			public int DstBlend;

			public bool HasZWrite;

			public int ZWrite;

			public bool AlphaTestKeyword;

			public bool AlphaBlendKeyword;

			public bool AlphaPremultiplyKeyword;

			public bool HasColor;

			public Color Color;

			public bool HasBaseColor;

			public Color BaseColor;

			public bool HasTintColor;

			public Color TintColor;
		}

		private struct RendererSnapshot
		{
			public bool Initialized;

			public bool Enabled;

			public ShadowCastingMode ShadowCastingMode;

			public bool ReceiveShadows;
		}

		private static readonly Dictionary<int, MaterialSnapshot> MaterialSnapshots = new Dictionary<int, MaterialSnapshot>();

		private static readonly Dictionary<int, RendererSnapshot> RendererSnapshots = new Dictionary<int, RendererSnapshot>();

		private static bool _refreshAllCartsRequested;

		internal static TranslucentCart Instance { get; private set; } = null;


		internal static ManualLogSource Logger => Instance._logger;

		private ManualLogSource _logger => ((BaseUnityPlugin)this).Logger;

		internal Harmony? Harmony { get; set; }

		internal static ConfigEntry<float> CartTransparencyPercent { get; private set; } = null;


		internal static ConfigEntry<bool> OnlyWhenGrabbing { get; private set; } = null;


		internal static float CartAlpha
		{
			get
			{
				float num = Mathf.Clamp(CartTransparencyPercent.Value, 0f, 100f) / 100f;
				return Mathf.Clamp01(1f - num);
			}
		}

		private void Awake()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			Instance = this;
			CartTransparencyPercent = ((BaseUnityPlugin)this).Config.Bind<float>("General", "CartTransparencyPercent", 40f, new ConfigDescription("How transparent the cart should be as a percent. 0 = opaque, 100 = invisible.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			OnlyWhenGrabbing = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "OnlyWhenGrabbing", false, "If true, only apply transparency while you are grabbing the cart (local player). If false, always apply.");
			CartTransparencyPercent.SettingChanged += OnAnySettingChanged;
			OnlyWhenGrabbing.SettingChanged += OnAnySettingChanged;
			((BaseUnityPlugin)this).Config.ConfigReloaded += OnConfigReloaded;
			((Component)this).gameObject.transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			Patch();
			Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} has loaded!");
		}

		private void OnDestroy()
		{
			try
			{
				CartTransparencyPercent.SettingChanged -= OnAnySettingChanged;
				OnlyWhenGrabbing.SettingChanged -= OnAnySettingChanged;
				((BaseUnityPlugin)this).Config.ConfigReloaded -= OnConfigReloaded;
			}
			catch
			{
			}
		}

		private static void OnAnySettingChanged(object sender, EventArgs e)
		{
			RequestRefreshAllCarts();
		}

		private static void OnConfigReloaded(object sender, EventArgs e)
		{
			RequestRefreshAllCarts();
		}

		private static void RequestRefreshAllCarts()
		{
			_refreshAllCartsRequested = true;
		}

		internal void Patch()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_0025: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
				Harmony val2 = val;
				Harmony = val;
			}
			Harmony.PatchAll();
		}

		internal void Unpatch()
		{
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void Update()
		{
			if (_refreshAllCartsRequested)
			{
				_refreshAllCartsRequested = false;
				RefreshAllCarts();
			}
		}

		internal static void RefreshAllCarts()
		{
			PhysGrabCart[] array;
			try
			{
				array = Object.FindObjectsOfType<PhysGrabCart>();
			}
			catch
			{
				return;
			}
			PhysGrabCart[] array2 = array;
			foreach (PhysGrabCart cart in array2)
			{
				ApplyCartTransparency(cart);
			}
		}

		internal static void ApplyCartTransparency(PhysGrabCart cart)
		{
			if (!Object.op_Implicit((Object)(object)cart))
			{
				return;
			}
			float effectiveAlpha = GetEffectiveAlpha(cart);
			Renderer[] componentsInChildren = ((Component)cart).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if ((val is MeshRenderer || val is SkinnedMeshRenderer) && !((Object)(object)((Component)val).GetComponent("TMPro.TMP_Text") != (Object)null) && !((Object)(object)((Component)val).GetComponent("TMPro.TextMeshPro") != (Object)null))
				{
					Material[] materials;
					try
					{
						materials = val.materials;
					}
					catch
					{
						continue;
					}
					Material[] array = materials;
					foreach (Material material in array)
					{
						ApplyMaterialFade(material, effectiveAlpha);
					}
					ApplyRendererShadowRules(val, effectiveAlpha);
				}
			}
		}

		private static float GetEffectiveAlpha(PhysGrabCart cart)
		{
			if (!OnlyWhenGrabbing.Value)
			{
				return CartAlpha;
			}
			PhysGrabObject val;
			try
			{
				val = ((Component)cart).GetComponent<PhysGrabObject>();
			}
			catch
			{
				val = null;
			}
			if (!((Object)(object)val != (Object)null) || !val.grabbedLocal)
			{
				return 1f;
			}
			return CartAlpha;
		}

		private static void ApplyRendererShadowRules(Renderer renderer, float alphaMultiplier)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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)
			alphaMultiplier = Mathf.Clamp01(alphaMultiplier);
			int instanceID = ((Object)renderer).GetInstanceID();
			if (!RendererSnapshots.TryGetValue(instanceID, out var value) || !value.Initialized)
			{
				RendererSnapshot rendererSnapshot = default(RendererSnapshot);
				rendererSnapshot.Initialized = true;
				rendererSnapshot.Enabled = renderer.enabled;
				rendererSnapshot.ShadowCastingMode = renderer.shadowCastingMode;
				rendererSnapshot.ReceiveShadows = renderer.receiveShadows;
				value = rendererSnapshot;
				RendererSnapshots[instanceID] = value;
			}
			if (alphaMultiplier <= 0.001f)
			{
				renderer.enabled = false;
				renderer.shadowCastingMode = (ShadowCastingMode)0;
			}
			else
			{
				renderer.enabled = value.Enabled;
				renderer.shadowCastingMode = value.ShadowCastingMode;
			}
			renderer.receiveShadows = value.ReceiveShadows;
		}

		private static void ApplyMaterialFade(Material material, float alphaMultiplier)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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_00b3: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)material))
			{
				return;
			}
			alphaMultiplier = Mathf.Clamp01(alphaMultiplier);
			int instanceID = ((Object)material).GetInstanceID();
			if (!MaterialSnapshots.TryGetValue(instanceID, out var value) || !value.Initialized)
			{
				value = CaptureSnapshot(material);
				MaterialSnapshots[instanceID] = value;
			}
			if (alphaMultiplier >= 0.999f)
			{
				RestoreSnapshot(material, value);
				return;
			}
			SetMaterialTransparent(material);
			if (value.HasColor && material.HasProperty("_Color"))
			{
				Color color = value.Color;
				color.a = Mathf.Clamp01(value.Color.a * alphaMultiplier);
				material.color = color;
			}
			if (value.HasBaseColor && material.HasProperty("_BaseColor"))
			{
				Color baseColor = value.BaseColor;
				baseColor.a = Mathf.Clamp01(value.BaseColor.a * alphaMultiplier);
				material.SetColor("_BaseColor", baseColor);
			}
			if (value.HasTintColor && material.HasProperty("_TintColor"))
			{
				Color tintColor = value.TintColor;
				tintColor.a = Mathf.Clamp01(value.TintColor.a * alphaMultiplier);
				material.SetColor("_TintColor", tintColor);
			}
		}

		private static MaterialSnapshot CaptureSnapshot(Material material)
		{
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			MaterialSnapshot materialSnapshot = default(MaterialSnapshot);
			materialSnapshot.Initialized = true;
			materialSnapshot.RenderQueue = material.renderQueue;
			materialSnapshot.RenderTypeTag = material.GetTag("RenderType", false, "");
			MaterialSnapshot result = materialSnapshot;
			if (material.HasProperty("_Surface"))
			{
				result.HasSurface = true;
				result.Surface = material.GetFloat("_Surface");
			}
			if (material.HasProperty("_Mode"))
			{
				result.HasMode = true;
				result.Mode = material.GetFloat("_Mode");
			}
			if (material.HasProperty("_SrcBlend"))
			{
				result.HasSrcBlend = true;
				result.SrcBlend = material.GetInt("_SrcBlend");
			}
			if (material.HasProperty("_DstBlend"))
			{
				result.HasDstBlend = true;
				result.DstBlend = material.GetInt("_DstBlend");
			}
			if (material.HasProperty("_ZWrite"))
			{
				result.HasZWrite = true;
				result.ZWrite = material.GetInt("_ZWrite");
			}
			result.AlphaTestKeyword = material.IsKeywordEnabled("_ALPHATEST_ON");
			result.AlphaBlendKeyword = material.IsKeywordEnabled("_ALPHABLEND_ON");
			result.AlphaPremultiplyKeyword = material.IsKeywordEnabled("_ALPHAPREMULTIPLY_ON");
			if (material.HasProperty("_Color"))
			{
				result.HasColor = true;
				result.Color = material.color;
			}
			if (material.HasProperty("_BaseColor"))
			{
				result.HasBaseColor = true;
				result.BaseColor = material.GetColor("_BaseColor");
			}
			if (material.HasProperty("_TintColor"))
			{
				result.HasTintColor = true;
				result.TintColor = material.GetColor("_TintColor");
			}
			return result;
		}

		private static void RestoreSnapshot(Material material, MaterialSnapshot snap)
		{
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			material.renderQueue = snap.RenderQueue;
			material.SetOverrideTag("RenderType", snap.RenderTypeTag);
			if (snap.HasSurface && material.HasProperty("_Surface"))
			{
				material.SetFloat("_Surface", snap.Surface);
			}
			if (snap.HasMode && material.HasProperty("_Mode"))
			{
				material.SetFloat("_Mode", snap.Mode);
			}
			if (snap.HasSrcBlend && material.HasProperty("_SrcBlend"))
			{
				material.SetInt("_SrcBlend", snap.SrcBlend);
			}
			if (snap.HasDstBlend && material.HasProperty("_DstBlend"))
			{
				material.SetInt("_DstBlend", snap.DstBlend);
			}
			if (snap.HasZWrite && material.HasProperty("_ZWrite"))
			{
				material.SetInt("_ZWrite", snap.ZWrite);
			}
			if (snap.AlphaTestKeyword)
			{
				material.EnableKeyword("_ALPHATEST_ON");
			}
			else
			{
				material.DisableKeyword("_ALPHATEST_ON");
			}
			if (snap.AlphaBlendKeyword)
			{
				material.EnableKeyword("_ALPHABLEND_ON");
			}
			else
			{
				material.DisableKeyword("_ALPHABLEND_ON");
			}
			if (snap.AlphaPremultiplyKeyword)
			{
				material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
			}
			else
			{
				material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
			}
			if (snap.HasColor && material.HasProperty("_Color"))
			{
				material.color = snap.Color;
			}
			if (snap.HasBaseColor && material.HasProperty("_BaseColor"))
			{
				material.SetColor("_BaseColor", snap.BaseColor);
			}
			if (snap.HasTintColor && material.HasProperty("_TintColor"))
			{
				material.SetColor("_TintColor", snap.TintColor);
			}
		}

		private static void SetMaterialTransparent(Material material)
		{
			material.SetOverrideTag("RenderType", "Transparent");
			if (material.HasProperty("_Surface"))
			{
				material.SetFloat("_Surface", 1f);
			}
			if (material.HasProperty("_Mode"))
			{
				material.SetFloat("_Mode", 3f);
			}
			if (material.HasProperty("_SrcBlend"))
			{
				material.SetInt("_SrcBlend", 5);
			}
			if (material.HasProperty("_DstBlend"))
			{
				material.SetInt("_DstBlend", 10);
			}
			if (material.HasProperty("_ZWrite"))
			{
				material.SetInt("_ZWrite", 0);
			}
			material.DisableKeyword("_ALPHATEST_ON");
			material.EnableKeyword("_ALPHABLEND_ON");
			material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
			material.renderQueue = 3000;
		}

		private static void SetMaterialOpaque(Material material)
		{
			material.SetOverrideTag("RenderType", "Opaque");
			if (material.HasProperty("_Surface"))
			{
				material.SetFloat("_Surface", 0f);
			}
			if (material.HasProperty("_Mode"))
			{
				material.SetFloat("_Mode", 0f);
			}
			if (material.HasProperty("_SrcBlend"))
			{
				material.SetInt("_SrcBlend", 1);
			}
			if (material.HasProperty("_DstBlend"))
			{
				material.SetInt("_DstBlend", 0);
			}
			if (material.HasProperty("_ZWrite"))
			{
				material.SetInt("_ZWrite", 1);
			}
			material.DisableKeyword("_ALPHATEST_ON");
			material.DisableKeyword("_ALPHABLEND_ON");
			material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
			material.renderQueue = 2000;
		}
	}
}