Decompiled source of CoinClipFix v0.9.0

CoinClipFix.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
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: AssemblyVersion("0.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 CoinClipFix
{
	internal class AlphaMask
	{
		private const int MaxSize = 64;

		private static readonly Dictionary<Sprite, AlphaMask> Cache = new Dictionary<Sprite, AlphaMask>();

		private readonly byte[] alpha;

		private readonly int width;

		private readonly int height;

		private readonly float rectWidth;

		private readonly float rectHeight;

		private readonly float pixelsPerUnit;

		private readonly Vector2 pivot;

		private readonly Vector2 offset;

		private AlphaMask(byte[] alpha, int width, int height, float rectWidth, float rectHeight, float pixelsPerUnit, Vector2 pivot, Vector2 offset)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			this.alpha = alpha;
			this.width = width;
			this.height = height;
			this.rectWidth = rectWidth;
			this.rectHeight = rectHeight;
			this.pixelsPerUnit = pixelsPerUnit;
			this.pivot = pivot;
			this.offset = offset;
		}

		internal static AlphaMask Get(Sprite sprite, ManualLogSource log)
		{
			if (Cache.TryGetValue(sprite, out var value))
			{
				return value;
			}
			AlphaMask alphaMask = null;
			try
			{
				alphaMask = Build(sprite);
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("Reading sprite \"" + ((Object)sprite).name + "\" failed: " + ex.Message));
			}
			Cache[sprite] = alphaMask;
			if (alphaMask == null)
			{
				log.LogWarning((object)("Could not read the shape of sprite \"" + ((Object)sprite).name + "\", using its bounding box instead."));
			}
			return alphaMask;
		}

		internal float Sample(Vector2 local)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			float num = local.x * pixelsPerUnit + pivot.x - offset.x;
			float num2 = local.y * pixelsPerUnit + pivot.y - offset.y;
			if (num < 0f || num2 < 0f || num >= rectWidth || num2 >= rectHeight)
			{
				return 0f;
			}
			int num3 = Mathf.Min((int)(num / rectWidth * (float)width), width - 1);
			int num4 = Mathf.Min((int)(num2 / rectHeight * (float)height), height - 1);
			return (float)(int)alpha[num4 * width + num3] / 255f;
		}

		private static AlphaMask Build(Sprite sprite)
		{
			//IL_0014: 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)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: 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_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			Texture2D texture = sprite.texture;
			if ((Object)(object)texture == (Object)null)
			{
				return null;
			}
			Rect textureRect;
			Vector2 textureRectOffset;
			try
			{
				textureRect = sprite.textureRect;
				textureRectOffset = sprite.textureRectOffset;
			}
			catch (Exception)
			{
				return null;
			}
			if (((Rect)(ref textureRect)).width < 1f || ((Rect)(ref textureRect)).height < 1f)
			{
				return null;
			}
			int num = Mathf.Clamp(Mathf.RoundToInt(((Rect)(ref textureRect)).width), 1, 64);
			int num2 = Mathf.Clamp(Mathf.RoundToInt(((Rect)(ref textureRect)).height), 1, 64);
			RenderTexture temporary = RenderTexture.GetTemporary(num, num2, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)1);
			RenderTexture active = RenderTexture.active;
			Texture2D val = null;
			try
			{
				Vector2 val2 = default(Vector2);
				((Vector2)(ref val2))..ctor(((Rect)(ref textureRect)).width / (float)((Texture)texture).width, ((Rect)(ref textureRect)).height / (float)((Texture)texture).height);
				Vector2 val3 = default(Vector2);
				((Vector2)(ref val3))..ctor(((Rect)(ref textureRect)).x / (float)((Texture)texture).width, ((Rect)(ref textureRect)).y / (float)((Texture)texture).height);
				Graphics.Blit((Texture)(object)texture, temporary, val2, val3);
				RenderTexture.active = temporary;
				val = new Texture2D(num, num2, (TextureFormat)4, false);
				val.ReadPixels(new Rect(0f, 0f, (float)num, (float)num2), 0, 0);
				Color32[] pixels = val.GetPixels32();
				byte[] array = new byte[pixels.Length];
				for (int i = 0; i < pixels.Length; i++)
				{
					array[i] = pixels[i].a;
				}
				return new AlphaMask(array, num, num2, ((Rect)(ref textureRect)).width, ((Rect)(ref textureRect)).height, sprite.pixelsPerUnit, sprite.pivot, textureRectOffset);
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Coin), "OnEnable")]
	internal static class CoinEnablePatch
	{
		private static void Postfix(Coin __instance)
		{
			CoinFader.Register(__instance);
		}
	}
	internal class CoinFader : MonoBehaviour
	{
		private struct UiRect
		{
			internal Bounds Bounds;

			internal float Weight;

			internal Transform Transform;

			internal Sprite Sprite;

			internal Matrix4x4 WorldToLocal;

			internal float PlaneZ;

			internal bool FlipX;

			internal bool FlipY;
		}

		private struct Candidate
		{
			internal UiRect Rect;

			internal AlphaMask Mask;
		}

		private class CoinState
		{
			internal Coin Coin;

			internal MeshRenderer[] Renderers;

			internal Material[][] Originals;

			internal ShadowCastingMode[] OriginalShadows;

			internal MaterialPropertyBlock Block = new MaterialPropertyBlock();

			internal float Alpha = 1f;

			internal bool Faded;

			internal bool Unavailable;
		}

		private const float RefreshInterval = 2f;

		private const float MaxUiSize = 15f;

		private const float MinUiAlpha = 0.05f;

		private const int SampleGrid = 8;

		private static readonly string[] IgnoredRoots = new string[4] { "TABLE ENVIRONMENT", "COIN PAD", "VISUALS", "ENCOUNTER SCENE" };

		private static readonly string[] TexturePreference = new string[2] { "_BaseMap", "_MainTex" };

		private static readonly string[] ColorPreference = new string[2] { "_BaseColor", "_Color" };

		private static readonly int OpacityId = Shader.PropertyToID("_Opacity");

		private static CoinFader instance;

		private static ManualLogSource log;

		private static ConfigEntry<bool> enabledEntry;

		private static ConfigEntry<float> lightOverlap;

		private static ConfigEntry<float> fullOverlap;

		private static ConfigEntry<float> fadeSpeed;

		private static ConfigEntry<bool> ditherShadows;

		private readonly List<CoinState> coins = new List<CoinState>();

		private readonly List<Renderer> uiRenderers = new List<Renderer>();

		private readonly List<UiRect> activeUi = new List<UiRect>();

		private readonly List<Candidate> candidates = new List<Candidate>();

		private readonly Dictionary<Material, Material> fadeMaterials = new Dictionary<Material, Material>();

		private float nextRefresh;

		internal static void Initialize(ManualLogSource logger, ConfigEntry<bool> enabled, ConfigEntry<float> light, ConfigEntry<float> full, ConfigEntry<float> speed, ConfigEntry<bool> shadows)
		{
			log = logger;
			enabledEntry = enabled;
			lightOverlap = light;
			fullOverlap = full;
			fadeSpeed = speed;
			ditherShadows = shadows;
		}

		internal static void Register(Coin coin)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance == (Object)null)
			{
				instance = new GameObject("CoinClipFixFader").AddComponent<CoinFader>();
			}
			instance.Add(coin);
		}

		private static Texture FindTexture(Material source)
		{
			string[] texturePreference = TexturePreference;
			foreach (string text in texturePreference)
			{
				if (source.HasProperty(text) && (Object)(object)source.GetTexture(text) != (Object)null)
				{
					return source.GetTexture(text);
				}
			}
			texturePreference = source.GetTexturePropertyNames();
			foreach (string text2 in texturePreference)
			{
				Texture texture = source.GetTexture(text2);
				if ((Object)(object)texture != (Object)null && !text2.ToLowerInvariant().Contains("normal"))
				{
					return texture;
				}
			}
			return null;
		}

		private static Color FindColor(Material source)
		{
			//IL_0046: 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)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: 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)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			string[] colorPreference = ColorPreference;
			foreach (string text in colorPreference)
			{
				if (source.HasProperty(text))
				{
					Color color = source.GetColor(text);
					return new Color(color.r, color.g, color.b, 1f);
				}
			}
			return Color.white;
		}

		private static bool IsUi(Renderer candidate)
		{
			if (!(candidate is SpriteRenderer) && !(candidate is MeshRenderer))
			{
				return false;
			}
			Transform val = ((Component)candidate).transform;
			while ((Object)(object)val != (Object)null)
			{
				string text = ((Object)val).name.Trim();
				string[] ignoredRoots = IgnoredRoots;
				foreach (string text2 in ignoredRoots)
				{
					if (text == text2)
					{
						return false;
					}
				}
				val = val.parent;
			}
			return (Object)(object)((Component)candidate).GetComponentInParent<Coin>() == (Object)null;
		}

		private void Add(Coin coin)
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected I4, but got Unknown
			foreach (CoinState coin2 in coins)
			{
				if ((Object)(object)coin2.Coin == (Object)(object)coin)
				{
					return;
				}
			}
			MeshRenderer[] componentsInChildren = ((Component)coin).GetComponentsInChildren<MeshRenderer>(true);
			if (componentsInChildren.Length == 0)
			{
				return;
			}
			CoinState coinState = new CoinState
			{
				Coin = coin,
				Renderers = componentsInChildren,
				Originals = new Material[componentsInChildren.Length][],
				OriginalShadows = (ShadowCastingMode[])(object)new ShadowCastingMode[componentsInChildren.Length]
			};
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				coinState.Originals[i] = ((Renderer)componentsInChildren[i]).sharedMaterials;
				coinState.OriginalShadows[i] = (ShadowCastingMode)(int)((Renderer)componentsInChildren[i]).shadowCastingMode;
				Material[] array = coinState.Originals[i];
				foreach (Material source in array)
				{
					GetFadeMaterial(source);
				}
			}
			coins.Add(coinState);
		}

		private void LateUpdate()
		{
			if (coins.Count == 0)
			{
				return;
			}
			bool value = enabledEntry.Value;
			if (value)
			{
				if (Time.unscaledTime >= nextRefresh)
				{
					nextRefresh = Time.unscaledTime + 2f;
					RefreshUi();
				}
				CollectActiveUi();
			}
			float num = fadeSpeed.Value * Time.unscaledDeltaTime;
			for (int num2 = coins.Count - 1; num2 >= 0; num2--)
			{
				CoinState coinState = coins[num2];
				if ((Object)(object)coinState.Coin == (Object)null)
				{
					coins.RemoveAt(num2);
				}
				else
				{
					float num3 = 1f;
					if (value && TryGetOverlap(coinState, out var overlap))
					{
						num3 = Mathf.Lerp(lightOverlap.Value, fullOverlap.Value, overlap);
					}
					coinState.Alpha = Mathf.MoveTowards(coinState.Alpha, num3, num);
					Apply(coinState);
				}
			}
		}

		private void RefreshUi()
		{
			uiRenderers.Clear();
			Renderer[] array = Object.FindObjectsByType<Renderer>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			foreach (Renderer val in array)
			{
				if (IsUi(val))
				{
					uiRenderers.Add(val);
				}
			}
		}

		private void CollectActiveUi()
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: 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)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: 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_00ed: Unknown result type (might be due to invalid IL or missing references)
			activeUi.Clear();
			foreach (Renderer uiRenderer in uiRenderers)
			{
				if ((Object)(object)uiRenderer == (Object)null || !uiRenderer.enabled || !((Component)uiRenderer).gameObject.activeInHierarchy)
				{
					continue;
				}
				UiRect item = new UiRect
				{
					Weight = 1f,
					Transform = ((Component)uiRenderer).transform
				};
				SpriteRenderer val = (SpriteRenderer)(object)((uiRenderer is SpriteRenderer) ? uiRenderer : null);
				if ((Object)(object)val != (Object)null)
				{
					item.Weight = Mathf.Clamp01(val.color.a);
					item.FlipX = val.flipX;
					item.FlipY = val.flipY;
					if ((Object)(object)val.sprite != (Object)null && (int)val.drawMode == 0)
					{
						item.Sprite = val.sprite;
						item.WorldToLocal = item.Transform.worldToLocalMatrix;
						item.PlaneZ = item.Transform.position.z;
					}
				}
				if (!(item.Weight < 0.05f))
				{
					item.Bounds = uiRenderer.bounds;
					if (!(Mathf.Max(((Bounds)(ref item.Bounds)).size.x, ((Bounds)(ref item.Bounds)).size.y) > 15f))
					{
						activeUi.Add(item);
					}
				}
			}
		}

		private bool TryGetOverlap(CoinState state, out float overlap)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			overlap = 0f;
			MeshRenderer[] renderers = state.Renderers;
			Vector2 point = default(Vector2);
			foreach (MeshRenderer val in renderers)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Bounds bounds = ((Renderer)val).bounds;
				candidates.Clear();
				foreach (UiRect item in activeUi)
				{
					if (((Bounds)(ref bounds)).Intersects(item.Bounds))
					{
						candidates.Add(new Candidate
						{
							Rect = item,
							Mask = (((Object)(object)item.Sprite != (Object)null) ? AlphaMask.Get(item.Sprite, log) : null)
						});
					}
				}
				if (candidates.Count == 0)
				{
					continue;
				}
				float num = 0f;
				int num2 = 0;
				for (int j = 0; j < 8; j++)
				{
					for (int k = 0; k < 8; k++)
					{
						float num3 = ((float)j + 0.5f) / 8f * 2f - 1f;
						float num4 = ((float)k + 0.5f) / 8f * 2f - 1f;
						if (num3 * num3 + num4 * num4 > 1f)
						{
							continue;
						}
						num2++;
						((Vector2)(ref point))..ctor(((Bounds)(ref bounds)).center.x + num3 * ((Bounds)(ref bounds)).extents.x, ((Bounds)(ref bounds)).center.y + num4 * ((Bounds)(ref bounds)).extents.y);
						float num5 = 0f;
						foreach (Candidate candidate in candidates)
						{
							num5 = Mathf.Max(num5, SampleCoverage(candidate, point));
						}
						num += num5;
					}
				}
				if (num2 > 0)
				{
					overlap = Mathf.Max(overlap, num / (float)num2);
				}
			}
			return overlap > 0f;
		}

		private static float SampleCoverage(Candidate candidate, Vector2 point)
		{
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			UiRect rect = candidate.Rect;
			if (candidate.Mask == null)
			{
				if (!(point.x >= ((Bounds)(ref rect.Bounds)).min.x) || !(point.x <= ((Bounds)(ref rect.Bounds)).max.x) || !(point.y >= ((Bounds)(ref rect.Bounds)).min.y) || !(point.y <= ((Bounds)(ref rect.Bounds)).max.y))
				{
					return 0f;
				}
				return rect.Weight;
			}
			Vector3 val = ((Matrix4x4)(ref rect.WorldToLocal)).MultiplyPoint3x4(new Vector3(point.x, point.y, rect.PlaneZ));
			if (rect.FlipX)
			{
				val.x = 0f - val.x;
			}
			if (rect.FlipY)
			{
				val.y = 0f - val.y;
			}
			return candidate.Mask.Sample(new Vector2(val.x, val.y)) * rect.Weight;
		}

		private void Apply(CoinState state)
		{
			if (state.Alpha >= 0.999f)
			{
				if (state.Faded)
				{
					Restore(state);
				}
			}
			else
			{
				if (state.Unavailable)
				{
					return;
				}
				if (!state.Faded && !Engage(state))
				{
					state.Unavailable = true;
					return;
				}
				for (int i = 0; i < state.Renderers.Length; i++)
				{
					MeshRenderer val = state.Renderers[i];
					if (!((Object)(object)val == (Object)null))
					{
						((Renderer)val).GetPropertyBlock(state.Block);
						state.Block.SetFloat(OpacityId, state.Alpha);
						((Renderer)val).SetPropertyBlock(state.Block);
						((Renderer)val).shadowCastingMode = (ShadowCastingMode)(ditherShadows.Value ? ((int)state.OriginalShadows[i]) : 0);
					}
				}
			}
		}

		private bool Engage(CoinState state)
		{
			bool flag = false;
			for (int i = 0; i < state.Renderers.Length; i++)
			{
				if (!((Object)(object)state.Renderers[i] == (Object)null))
				{
					Material[] array = state.Originals[i];
					Material[] array2 = (Material[])(object)new Material[array.Length];
					for (int j = 0; j < array.Length; j++)
					{
						Material fadeMaterial = GetFadeMaterial(array[j]);
						array2[j] = (((Object)(object)fadeMaterial != (Object)null) ? fadeMaterial : array[j]);
						flag |= (Object)(object)fadeMaterial != (Object)null;
					}
					((Renderer)state.Renderers[i]).sharedMaterials = array2;
				}
			}
			state.Faded = flag;
			return flag;
		}

		private void Restore(CoinState state)
		{
			for (int i = 0; i < state.Renderers.Length; i++)
			{
				if (!((Object)(object)state.Renderers[i] == (Object)null))
				{
					((Renderer)state.Renderers[i]).sharedMaterials = state.Originals[i];
					((Renderer)state.Renderers[i]).SetPropertyBlock((MaterialPropertyBlock)null);
					((Renderer)state.Renderers[i]).shadowCastingMode = state.OriginalShadows[i];
				}
			}
			state.Faded = false;
		}

		private Material GetFadeMaterial(Material source)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			if (fadeMaterials.TryGetValue(source, out var value))
			{
				return value;
			}
			Shader val = DitherShader.Get(log);
			if ((Object)(object)val == (Object)null)
			{
				fadeMaterials[source] = null;
				return null;
			}
			Material val2 = new Material(val);
			((Object)val2).name = ((Object)source).name + " Dither";
			val2.SetTexture("_BaseMap", FindTexture(source));
			val2.SetColor("_BaseColor", FindColor(source));
			fadeMaterials[source] = val2;
			log.LogInfo((object)("Created dither material for coin material \"" + ((Object)source).name + "\"."));
			return val2;
		}
	}
	internal static class CoinRenderFix
	{
		private const string ZWriteProperty = "_ZWrite";

		private const int CoinRenderQueue = 2999;

		private static readonly HashSet<int> Processed = new HashSet<int>();

		private static ManualLogSource log;

		internal static void Initialize(ManualLogSource logger)
		{
			log = logger;
		}

		internal static void Apply(Coin coin)
		{
			Renderer[] componentsInChildren = ((Component)coin).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if (!(val is MeshRenderer))
				{
					continue;
				}
				Material[] sharedMaterials = val.sharedMaterials;
				foreach (Material val2 in sharedMaterials)
				{
					if (!((Object)(object)val2 == (Object)null) && Processed.Add(((Object)val2).GetInstanceID()))
					{
						Configure(val2);
					}
				}
			}
		}

		private static void Configure(Material material)
		{
			if (!material.HasProperty("_ZWrite"))
			{
				log.LogWarning((object)("Coin material \"" + ((Object)material).name + "\" uses shader \"" + ((Object)material.shader).name + "\" which has no _ZWrite property, coins may still clip into the UI."));
			}
			else
			{
				material.SetInt("_ZWrite", 0);
				material.renderQueue = 2999;
				log.LogInfo((object)("Coin material \"" + ((Object)material).name + "\" (" + ((Object)material.shader).name + ") now draws without writing depth."));
			}
		}
	}
	internal static class DitherShader
	{
		private const string ResourceName = "coinclipfix.bundle";

		private static Shader shader;

		private static bool loaded;

		internal static Shader Get(ManualLogSource log)
		{
			if (loaded)
			{
				return shader;
			}
			loaded = true;
			Shader val = null;
			string text = string.Empty;
			using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("coinclipfix.bundle"))
			{
				if (stream == null)
				{
					log.LogError((object)"The embedded shader bundle coinclipfix.bundle is missing, coins will not fade.");
					return null;
				}
				using MemoryStream memoryStream = new MemoryStream();
				stream.CopyTo(memoryStream);
				AssetBundle val2 = AssetBundle.LoadFromMemory(memoryStream.ToArray());
				if ((Object)(object)val2 == (Object)null)
				{
					log.LogError((object)"The shader bundle could not be loaded, coins will not fade.");
					return null;
				}
				text = string.Join(", ", val2.GetAllAssetNames());
				Shader[] array = val2.LoadAllAssets<Shader>();
				int num = 0;
				if (num < array.Length)
				{
					val = array[num];
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				log.LogError((object)("The shader bundle contains no shader (assets: " + text + "), coins will not fade."));
				return null;
			}
			if (!val.isSupported)
			{
				log.LogError((object)("Shader \"" + ((Object)val).name + "\" is not supported on this graphics setup, coins will not fade. " + Describe(val) + ", bundle assets: " + text + ", bundle size " + ResourceSize() + " bytes"));
				return null;
			}
			shader = val;
			log.LogInfo((object)("Loaded shader \"" + ((Object)shader).name + "\". " + Describe(shader)));
			return shader;
		}

		private static string ResourceSize()
		{
			using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("coinclipfix.bundle");
			return (stream != null) ? stream.Length.ToString() : "unknown";
		}

		private static string Describe(Shader target)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("Graphics ").Append(SystemInfo.graphicsDeviceType).Append(", shader level ")
				.Append(SystemInfo.graphicsShaderLevel);
			Material val = new Material(target);
			stringBuilder.Append(", passes ").Append(val.passCount);
			for (int i = 0; i < val.passCount; i++)
			{
				stringBuilder.Append(' ').Append(val.GetPassName(i));
			}
			Object.Destroy((Object)(object)val);
			return stringBuilder.ToString();
		}
	}
	[BepInPlugin("com.king_tajin.coinclipfix", "Coin Clip Fix", "0.9.0")]
	[BepInProcess("Slots and Daggers.exe")]
	public class Plugin : BaseUnityPlugin
	{
		private void Awake()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			ConfigEntry<bool> enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Fade coins that overlap the UI so they do not clip into it");
			ConfigEntry<float> light = ((BaseUnityPlugin)this).Config.Bind<float>("Opacity", "LightOverlap", 0.75f, new ConfigDescription("Opacity of a coin that only slightly overlaps the UI. 1 is fully visible, 0 is invisible", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			ConfigEntry<float> full = ((BaseUnityPlugin)this).Config.Bind<float>("Opacity", "FullOverlap", 0.2f, new ConfigDescription("Opacity of a coin that is completely covered by the UI. Coins in between blend between the two values", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			ConfigEntry<float> speed = ((BaseUnityPlugin)this).Config.Bind<float>("Opacity", "FadeSpeed", 3f, new ConfigDescription("How quickly coins fade in and out, in opacity per second", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 30f), Array.Empty<object>()));
			ConfigEntry<bool> shadows = ((BaseUnityPlugin)this).Config.Bind<bool>("Opacity", "DitherShadows", true, "Dither the shadows of faded coins to match the coin. When off, faded coins cast no shadow");
			CoinFader.Initialize(((BaseUnityPlugin)this).Logger, enabled, light, full, speed, shadows);
			DitherShader.Get(((BaseUnityPlugin)this).Logger);
			Harmony val = new Harmony("com.king_tajin.coinclipfix");
			Type[] array = new Type[1] { typeof(CoinEnablePatch) };
			foreach (Type type in array)
			{
				try
				{
					val.PatchAll(type);
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)ex);
				}
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Coin Clip Fix loaded");
		}
	}
}