Decompiled source of CustomPaintings Fix v1.0.0

CustomPaintingsV050Fix.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using CustomPaintings;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[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("CustomPaintingsV050Fix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CustomPaintingsV050Fix")]
[assembly: AssemblyTitle("CustomPaintingsV050Fix")]
[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 CustomPaintingsV050Fix
{
	[BepInPlugin("vanif.custompaintings.v050fix", "CustomPaintings v0.5.0 Fix", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		internal static Plugin Instance;

		private static readonly FieldInfo SwapperField = AccessTools.Field(typeof(CustomPaintings), "swapper");

		private static readonly FieldInfo LoaderField = AccessTools.Field(typeof(CP_Swapper), "loader");

		private static int extraSwappedCount;

		private void Awake()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Harmony val = new Harmony("vanif.custompaintings.v050fix");
			val.PatchAll();
			Type type = AccessTools.TypeByName("LevelGenerator");
			if (type != null)
			{
				MethodInfo methodInfo = AccessTools.Method(type, "GenerateDone", (Type[])null, (Type[])null) ?? AccessTools.Method(type, "Start", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "OnLevelGenerated", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			Log.LogInfo((object)"CustomPaintings v0.5.0 Fix 1.0.0 loaded!");
		}

		private static void OnLevelGenerated()
		{
			if ((Object)(object)Instance != (Object)null)
			{
				((MonoBehaviour)Instance).StartCoroutine(Instance.DelayedSwapRoutine("LevelGenerator"));
			}
		}

		private IEnumerator DelayedSwapRoutine(string source)
		{
			yield return (object)new WaitForSeconds(0.5f);
			RunSwap(source + "_0.5s");
			yield return (object)new WaitForSeconds(2.5f);
			RunSwap(source + "_3.0s");
		}

		private static string CleanMaterialName(string rawName)
		{
			string text = rawName.Trim();
			if (text.EndsWith(" (Instance)", StringComparison.OrdinalIgnoreCase))
			{
				text = text.Substring(0, text.Length - " (Instance)".Length).Trim();
			}
			return text;
		}

		private static bool ContainsAny(string text, params string[] words)
		{
			foreach (string value in words)
			{
				if (text.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return true;
				}
			}
			return false;
		}

		private static string DetectShapeFromBounds(MeshRenderer mr, string hintName)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: 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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			if (ContainsAny(hintName, "_H_", " H ", "Horizontal", "Landscape"))
			{
				return "Landscape";
			}
			if (ContainsAny(hintName, "_V_", " V ", "Vertical", "Portrait"))
			{
				return "Portrait";
			}
			Bounds bounds = ((Renderer)mr).bounds;
			Vector3 size = ((Bounds)(ref bounds)).size;
			float num = Mathf.Max(size.x, size.z);
			float y = size.y;
			if (y > 0.01f && num > 0.01f)
			{
				float num2 = num / y;
				if (num2 > 1.15f)
				{
					return "Landscape";
				}
				if (num2 < 0.85f)
				{
					return "Portrait";
				}
			}
			return "Square";
		}

		private static bool TryResolveGroups(MeshRenderer mr, string cleanMatName, out List<string> groups)
		{
			if (CP_GroupList.MaterialNameToGroup.TryGetValue(cleanMatName, out groups))
			{
				return true;
			}
			string name = ((Object)((Component)mr).gameObject).name;
			string text = (((Object)(object)((Component)mr).transform.parent != (Object)null) ? ((Object)((Component)mr).transform.parent).name : "");
			bool flag = ContainsAny(cleanMatName, "Painting", "Picture", "Portrait", "Artwork", "Poster") && !ContainsAny(cleanMatName, "Frame", "Grunge");
			bool flag2 = !ContainsAny(name, "Frame", "Collider", "Debris", "Broken") && !ContainsAny(cleanMatName, "Frame", "Grunge", "Wall", "Brick", "Wood", "Gold", "Metal", "Default-Material", "Debris") && (name.Equals("painting", StringComparison.OrdinalIgnoreCase) || name.Equals("canvas", StringComparison.OrdinalIgnoreCase) || (ContainsAny(text, "Painting", "Picture", "Portrait") && !ContainsAny(text, "Broken", "Debris")));
			if (flag || flag2)
			{
				string item = DetectShapeFromBounds(mr, cleanMatName + " " + text);
				groups = new List<string> { item, "Normal", "RugsAndBanners", "Chaos" };
				return true;
			}
			groups = null;
			return false;
		}

		[HarmonyPatch(typeof(CP_Swapper), "ReplacePaintings")]
		[HarmonyPostfix]
		private static void PostfixReplacePaintings(CP_Swapper __instance)
		{
			SwapWithSwapper(__instance, "Postfix");
			if ((Object)(object)Instance != (Object)null)
			{
				((MonoBehaviour)Instance).StartCoroutine(Instance.DelayedSwapRoutine("ReplacePaintings"));
			}
		}

		private static void RunSwap(string source)
		{
			CustomPaintings[] array = Resources.FindObjectsOfTypeAll<CustomPaintings>();
			if (array != null && array.Length != 0)
			{
				object? obj = SwapperField?.GetValue(array);
				CP_Swapper val = (CP_Swapper)((obj is CP_Swapper) ? obj : null);
				if (val != null)
				{
					SwapWithSwapper(val, source);
				}
			}
		}

		private static void SwapWithSwapper(CP_Swapper swapper, string source)
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			if (swapper == null)
			{
				return;
			}
			object? obj = LoaderField?.GetValue(swapper);
			CP_Loader val = (CP_Loader)((obj is CP_Loader) ? obj : null);
			if (val == null)
			{
				return;
			}
			bool flag = (CP_Config.SeperateImages.Value && CP_Swapper.SeperateState == "Singleplayer") || (CP_Swapper.SeperateState == "on" && CP_Config.HostControl.Value) || (!CP_Config.HostControl.Value && CP_Config.SeperateImages.Value);
			int num = ((CP_Swapper.Seed != 0) ? CP_Swapper.Seed : Random.Range(1, int.MaxValue));
			int num2 = 0;
			MeshRenderer[] array = Resources.FindObjectsOfTypeAll<MeshRenderer>();
			foreach (MeshRenderer val2 in array)
			{
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				Scene scene = ((Component)val2).gameObject.scene;
				if (!((Scene)(ref scene)).IsValid())
				{
					continue;
				}
				Material[] sharedMaterials = ((Renderer)val2).sharedMaterials;
				bool flag2 = false;
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					if ((Object)(object)sharedMaterials[j] == (Object)null)
					{
						continue;
					}
					string text = CleanMaterialName(((Object)sharedMaterials[j]).name);
					if (text.Contains("Painting Frame Vertical Gold") || text.Contains("Painting Frame Horizontal Gold") || !TryResolveGroups(val2, text, out var groups) || !groups.Contains(CP_Swapper.ImageMode))
					{
						continue;
					}
					if (!flag && val.LoadedMaterials.Count > 0)
					{
						int index = Mathf.Abs((num + 10000 + extraSwappedCount) % val.LoadedMaterials.Count);
						sharedMaterials[j] = val.LoadedMaterials[index];
						extraSwappedCount++;
						num2++;
						flag2 = true;
					}
					else if (flag)
					{
						string key = (groups.Contains("Landscape") ? "Landscape" : (groups.Contains("Portrait") ? "Portrait" : "Square"));
						if (val.MaterialGroups.TryGetValue(key, out var value) && value.Count > 0)
						{
							int index2 = Mathf.Abs((num + 10000 + extraSwappedCount) % value.Count);
							sharedMaterials[j] = value[index2];
							extraSwappedCount++;
							num2++;
							flag2 = true;
						}
					}
				}
				if (flag2)
				{
					((Renderer)val2).sharedMaterials = sharedMaterials;
				}
			}
			if (num2 > 0)
			{
				Log.LogInfo((object)$"[v0.5.0 Fix] Pass '{source}' finished — swapped {num2} paintings.");
			}
		}
	}
}