Decompiled source of ChineseMemePaintings v1.0.0

plugins\ChineseMemePaintings\ChineseMemePaintings.dll

Decompiled 3 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
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("ChineseMemePaintings")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ChineseMemePaintings")]
[assembly: AssemblyTitle("ChineseMemePaintings")]
[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.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]
	[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]
	[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 ChineseMemePaintings
{
	[BepInPlugin("com.chinesememe.paintings", "Chinese Meme Paintings", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(PlayerAvatar), "LoadingLevelAnimationCompletedRPC")]
		private static class PaintingPatch
		{
			private static void Postfix()
			{
				ReplacePaintingsInScene();
			}
		}

		public const string PluginGuid = "com.chinesememe.paintings";

		public const string PluginName = "Chinese Meme Paintings";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log = null;

		internal static string PaintingsRoot = string.Empty;

		internal static ConfigEntry<float> ReplaceChance = null;

		internal static ConfigEntry<bool> PointFiltering = null;

		internal static ConfigEntry<bool> EnablePaintings = null;

		private static readonly List<Texture2D> SquareTextures = new List<Texture2D>();

		private static readonly List<Texture2D> PortraitTextures = new List<Texture2D>();

		private static readonly List<Texture2D> LandscapeTextures = new List<Texture2D>();

		private static readonly HashSet<string> KnownLandscapeMaterials = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Painting_H_Landscape", "Painting_H_crow", "Painting_H_crow_0", "PaintingMedium", "Painting_Danish_Flag", "Painting_Board", "Painting Danish Flag", "Painting Board" };

		private static readonly HashSet<string> KnownSquareMaterials = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Painting_S_Creep", "Painting_S_Creep 2_0", "Painting_S_Creep 2", "Painting Wizard Class", "Picture Frame - Picture 01", "Painting_Aurora", "Painting_McJannek", "Painting Aurora", "Painting McJannek" };

		private static readonly HashSet<string> KnownPortraitMaterials = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
		{
			"Painting_V_jannk", "Painting_V_Furman", "Painting_V_surrealistic", "Painting_V_surrealistic_0", "painting teacher01", "painting teacher02", "painting teacher03", "painting teacher04", "Painting_S_Tree", "Painting Calendar",
			"Magazine01", "Magazine02"
		};

		private Harmony? _harmony;

		private void Awake()
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			PaintingsRoot = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty, "Paintings");
			EnablePaintings = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "是否启用中文梗图随机替换挂画");
			ReplaceChance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ReplaceChance", 0.25f, new ConfigDescription("每幅原版挂画被梗图替换的概率 (0.0 ~ 1.0,默认 0.25 即 25%)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			PointFiltering = ((BaseUnityPlugin)this).Config.Bind<bool>("Graphics", "PointFiltering", false, "是否开启像素点过滤(关闭则正常清晰显示高清梗图,开启则偏像素风)");
			LoadAllFolders();
			_harmony = new Harmony("com.chinesememe.paintings");
			_harmony.PatchAll(typeof(PaintingPatch));
			Log.LogInfo((object)string.Format("{0} v{1} loaded! Square={2}, Portrait={3}, Landscape={4}", "Chinese Meme Paintings", "1.0.0", SquareTextures.Count, PortraitTextures.Count, LandscapeTextures.Count));
		}

		private static void LoadAllFolders()
		{
			LoadFolder("1_1_正方形", SquareTextures);
			LoadFolder("2_3_竖版", PortraitTextures);
			LoadFolder("3_2_横版", LandscapeTextures);
		}

		private static void LoadFolder(string folderName, List<Texture2D> target)
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			string path = Path.Combine(PaintingsRoot, folderName);
			Directory.CreateDirectory(path);
			string[] files = Directory.GetFiles(path);
			Array.Sort(files, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
			string[] array = files;
			foreach (string text in array)
			{
				string fileName = Path.GetFileName(text);
				if (fileName.StartsWith("_"))
				{
					continue;
				}
				string text2 = Path.GetExtension(text).ToLowerInvariant();
				if (text2 != ".png" && text2 != ".jpg" && text2 != ".jpeg")
				{
					continue;
				}
				try
				{
					byte[] array2 = File.ReadAllBytes(text);
					Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true);
					if (ImageConversion.LoadImage(val, array2))
					{
						((Object)val).name = fileName;
						((Texture)val).filterMode = (FilterMode)(!PointFiltering.Value);
						((Texture)val).wrapMode = (TextureWrapMode)1;
						target.Add(val);
					}
					else
					{
						Object.Destroy((Object)(object)val);
					}
				}
				catch (Exception ex)
				{
					Log.LogWarning((object)("Failed to load image " + text + ": " + ex.Message));
				}
			}
		}

		internal static void ReplacePaintingsInScene()
		{
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			if (!EnablePaintings.Value || (SquareTextures.Count == 0 && PortraitTextures.Count == 0 && LandscapeTextures.Count == 0))
			{
				return;
			}
			float num = Mathf.Clamp01(ReplaceChance.Value);
			int num2 = 0;
			MeshRenderer[] array = Object.FindObjectsByType<MeshRenderer>((FindObjectsSortMode)0);
			foreach (MeshRenderer val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Material[] sharedMaterials = ((Renderer)val).sharedMaterials;
				bool flag = false;
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					Material val2 = sharedMaterials[j];
					if ((Object)(object)val2 == (Object)null)
					{
						continue;
					}
					string matName = ((Object)val2).name.Replace(" (Instance)", string.Empty).Trim();
					List<Texture2D> matchingPool = GetMatchingPool(matName, val2.mainTexture);
					if (matchingPool == null || matchingPool.Count == 0)
					{
						continue;
					}
					Random random = new Random(ComputeStableSeed(((Component)val).transform.position, j, matName));
					if (!(random.NextDouble() > (double)num))
					{
						Texture2D val3 = matchingPool[random.Next(matchingPool.Count)];
						((Texture)val3).filterMode = (FilterMode)(!PointFiltering.Value);
						Material val4 = new Material(val2);
						val4.mainTexture = (Texture)(object)val3;
						if (val4.HasProperty("_BaseMap"))
						{
							val4.SetTexture("_BaseMap", (Texture)(object)val3);
						}
						sharedMaterials[j] = val4;
						flag = true;
						num2++;
					}
				}
				if (flag)
				{
					((Renderer)val).sharedMaterials = sharedMaterials;
				}
			}
			if (num2 > 0)
			{
				Log.LogInfo((object)$"Replaced {num2} paintings with Chinese memes (chance={num:P0}).");
			}
		}

		private static List<Texture2D>? GetMatchingPool(string matName, Texture? vanillaTex)
		{
			if (KnownSquareMaterials.Contains(matName) || matName.StartsWith("Museum Painting S", StringComparison.OrdinalIgnoreCase))
			{
				return SquareTextures;
			}
			if (KnownPortraitMaterials.Contains(matName) || matName.StartsWith("Museum Painting V", StringComparison.OrdinalIgnoreCase))
			{
				return PortraitTextures;
			}
			if (KnownLandscapeMaterials.Contains(matName) || matName.StartsWith("Museum Painting H", StringComparison.OrdinalIgnoreCase))
			{
				return LandscapeTextures;
			}
			if (matName.IndexOf("Painting", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Picture Frame", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				if ((Object)(object)vanillaTex != (Object)null && vanillaTex.height > 0)
				{
					float num = (float)vanillaTex.width / (float)vanillaTex.height;
					if (num < 0.85f)
					{
						return PortraitTextures;
					}
					if (num > 1.18f)
					{
						return LandscapeTextures;
					}
				}
				return SquareTextures;
			}
			return null;
		}

		private static int ComputeStableSeed(Vector3 pos, int matIndex, string matName)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: 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_0030: 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)
			int num = 17 * 31;
			Scene activeScene = SceneManager.GetActiveScene();
			return (((((num + ((Scene)(ref activeScene)).name.GetHashCode()) * 31 + Mathf.RoundToInt(pos.x * 10f)) * 31 + Mathf.RoundToInt(pos.y * 10f)) * 31 + Mathf.RoundToInt(pos.z * 10f)) * 31 + matIndex) * 31 + matName.GetHashCode();
		}
	}
}