Decompiled source of ParticleOptimizer v0.1.1

BepInEx/plugins/StonewardsParticleOptimizer/Stonewards.ParticleOptimizer.dll

Decompiled a day 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.Configuration;
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("Stonewards.ParticleOptimizer")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.1.0")]
[assembly: AssemblyInformationalVersion("0.1.1+82c8045b94e90149fccc1dfd8b9c23d73d93eaaa")]
[assembly: AssemblyProduct("Stonewards.ParticleOptimizer")]
[assembly: AssemblyTitle("Stonewards.ParticleOptimizer")]
[assembly: AssemblyVersion("0.1.1.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 StonewardsParticleOptimizer
{
	public enum EffectMode
	{
		Vanilla,
		Reduced,
		Disabled
	}
	[BepInPlugin("com.thereisnouser.stonewards.particleoptimizer", "Stonewards Particle Optimizer", "0.1.1")]
	public sealed class ParticleOptimizerPlugin : BaseUnityPlugin
	{
		private enum EffectKind
		{
			DigHit,
			DigBreak,
			PropHit,
			Extra
		}

		public const string PluginId = "com.thereisnouser.stonewards.particleoptimizer";

		public const string PluginName = "Stonewards Particle Optimizer";

		public const string PluginVersion = "0.1.1";

		internal static ParticleOptimizerPlugin Instance;

		private Harmony _harmony;

		private ConfigEntry<EffectMode> _digHitMode;

		private ConfigEntry<EffectMode> _digBreakMode;

		private ConfigEntry<EffectMode> _propHitMode;

		private ConfigEntry<EffectMode> _wallBreakMode;

		private ConfigEntry<string> _extraVfxIds;

		private ConfigEntry<bool> _debugLogging;

		private readonly Dictionary<string, EffectKind> _effectIds = new Dictionary<string, EffectKind>(StringComparer.OrdinalIgnoreCase);

		private readonly Dictionary<string, int> _effectCounters = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

		private readonly HashSet<string> _loggedIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly FieldInfo PropParticleIdField = AccessTools.Field(typeof(DestructibleProp), "particleID");

		private void Awake()
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			Instance = this;
			_digHitMode = ((BaseUnityPlugin)this).Config.Bind<EffectMode>("01 - Mining", "DigHit", EffectMode.Disabled, "Particles from hits that do not yet destroy a terrain block.");
			_digBreakMode = ((BaseUnityPlugin)this).Config.Bind<EffectMode>("01 - Mining", "DigBreak", EffectMode.Disabled, "Particles emitted when terrain/rock is actually broken.");
			_propHitMode = ((BaseUnityPlugin)this).Config.Bind<EffectMode>("02 - Destructible props", "PropHit", EffectMode.Disabled, "Hit particles from DestructibleProp (does not disable loot/sound/damage).");
			_wallBreakMode = ((BaseUnityPlugin)this).Config.Bind<EffectMode>("03 - Walls", "WallBreak", EffectMode.Disabled, "Particles emitted when wall chunks break. Does not change the chunks themselves.");
			_extraVfxIds = ((BaseUnityPlugin)this).Config.Bind<string>("04 - Advanced", "ExtraBlockedVfxIds", "", "Optional additional VFX IDs to suppress, comma/semicolon/newline separated.");
			_debugLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("04 - Advanced", "DebugLogging", false, "Log VFX IDs when first suppressed. Useful for troubleshooting.");
			_harmony = new Harmony("com.thereisnouser.stonewards.particleoptimizer");
			PatchRequired(AccessTools.Method(typeof(PlayerFX), "UserCode_RpcGetParticleAndRelease__String__Vector3__Quaternion__Vector3__Single", (Type[])null, (Type[])null), "FilterReceivedParticlePrefix", null, "client-side PlayerFX VFX receiver");
			PatchOptional(AccessTools.Method(typeof(DiggingManager), "OnStartClient", (Type[])null, (Type[])null), null, "DiggingManagerStartedPostfix", "DiggingManager.OnStartClient");
			PatchOptional(AccessTools.Method(typeof(WallPartAnimator), "PlayDestroyFx", (Type[])null, (Type[])null), "WallDestroyFxPrefix", null, "WallPartAnimator.PlayDestroyFx");
			SceneManager.sceneLoaded += OnSceneLoaded;
			RefreshKnownEffects();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Stonewards Particle Optimizer v0.1.1 initialized (client-side VFX filtering).");
		}

		private void PatchRequired(MethodInfo original, string prefix, string postfix, string description)
		{
			if (original == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Required game method not found: " + description + ". VFX filtering will not be active; this game version may be incompatible."));
			}
			else
			{
				PatchMethod(original, prefix, postfix, description);
			}
		}

		private void PatchOptional(MethodInfo original, string prefix, string postfix, string description)
		{
			if (original == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Optional game method not found: " + description));
			}
			else
			{
				PatchMethod(original, prefix, postfix, description);
			}
		}

		private void PatchMethod(MethodInfo original, string prefix, string postfix, string description)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Type typeFromHandle = typeof(ParticleOptimizerPlugin);
				_harmony.Patch((MethodBase)original, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(AccessTools.Method(typeFromHandle, prefix, (Type[])null, (Type[])null)), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(AccessTools.Method(typeFromHandle, postfix, (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Patched " + description));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Failed to patch " + description + ": " + ex));
			}
		}

		private static bool FilterReceivedParticlePrefix(string __0)
		{
			if (!((Object)(object)Instance == (Object)null))
			{
				return Instance.ShouldShowParticle(__0);
			}
			return true;
		}

		private static void DiggingManagerStartedPostfix(DiggingManager __instance)
		{
			if ((Object)(object)Instance != (Object)null)
			{
				Instance.AddDigMatterIds(__instance);
			}
		}

		private static bool WallDestroyFxPrefix()
		{
			if (!((Object)(object)Instance == (Object)null))
			{
				return Instance.Permit("#wall-fx", Instance._wallBreakMode.Value);
			}
			return true;
		}

		private bool ShouldShowParticle(string id)
		{
			if (string.IsNullOrEmpty(id))
			{
				return true;
			}
			if (!_effectIds.TryGetValue(id, out var value))
			{
				return true;
			}
			EffectMode mode = value switch
			{
				EffectKind.DigHit => _digHitMode.Value, 
				EffectKind.DigBreak => _digBreakMode.Value, 
				EffectKind.PropHit => _propHitMode.Value, 
				_ => EffectMode.Disabled, 
			};
			bool flag = Permit(id, mode);
			if (!flag && _debugLogging.Value && _loggedIds.Add(id))
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Suppressed VFX: " + id + " (" + value.ToString() + ", " + mode.ToString() + ")"));
			}
			return flag;
		}

		private bool Permit(string id, EffectMode mode)
		{
			switch (mode)
			{
			case EffectMode.Vanilla:
				return true;
			case EffectMode.Disabled:
				return false;
			default:
			{
				_effectCounters.TryGetValue(id, out var value);
				_effectCounters[id] = value + 1;
				return (value & 3) == 0;
			}
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			RefreshKnownEffects();
			((MonoBehaviour)this).StartCoroutine(RefreshAfterLoad());
		}

		private IEnumerator RefreshAfterLoad()
		{
			yield return (object)new WaitForSecondsRealtime(1.5f);
			RefreshKnownEffects();
			yield return (object)new WaitForSecondsRealtime(4f);
			RefreshKnownEffects();
		}

		private void RefreshKnownEffects()
		{
			_effectIds.Clear();
			_effectCounters.Clear();
			_loggedIds.Clear();
			if (!string.IsNullOrEmpty(_extraVfxIds.Value))
			{
				string[] array = _extraVfxIds.Value.Split(new char[4] { ',', ';', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string text in array)
				{
					Register(text.Trim(), EffectKind.Extra);
				}
			}
			try
			{
				AddDigMatterIds(DiggingManager.Instance);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not load mining VFX IDs: " + ex.Message));
			}
			try
			{
				DestructibleProp[] array2 = Resources.FindObjectsOfTypeAll<DestructibleProp>();
				if (PropParticleIdField != null)
				{
					DestructibleProp[] array3 = array2;
					foreach (DestructibleProp val in array3)
					{
						if (!((Object)(object)val == (Object)null))
						{
							Register(PropParticleIdField.GetValue(val) as string, EffectKind.PropHit);
						}
					}
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"DestructibleProp.particleID field not found.");
				}
			}
			catch (Exception ex2)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not load destructible prop VFX IDs: " + ex2.Message));
			}
			((BaseUnityPlugin)this).Logger.LogDebug((object)("Registered " + _effectIds.Count + " local VFX IDs for filtering."));
		}

		private void AddDigMatterIds(DiggingManager manager)
		{
			if ((Object)(object)manager == (Object)null || (Object)(object)manager.DiggingSettingsSO == (Object)null || manager.DiggingSettingsSO.digMatterProfiles == null)
			{
				return;
			}
			DigMatterProfileSO[] digMatterProfiles = manager.DiggingSettingsSO.digMatterProfiles;
			foreach (DigMatterProfileSO val in digMatterProfiles)
			{
				if (!((Object)(object)val == (Object)null))
				{
					Register(val.nonDestructionParticleID, EffectKind.DigHit);
					Register(val.rockImpactParticleID, EffectKind.DigBreak);
				}
			}
		}

		private void Register(string id, EffectKind kind)
		{
			if (!string.IsNullOrEmpty(id) && !_effectIds.ContainsKey(id))
			{
				_effectIds.Add(id, kind);
			}
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}
	}
}