Decompiled source of ColoredPortals v0.1.0

ColoredPortals.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
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(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("Catosaur")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Recolor Valheim portal swirl particles by typing color=tag in the portal tag box.")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyProduct("ColoredPortals")]
[assembly: AssemblyTitle("ColoredPortals")]
[assembly: AssemblyVersion("0.1.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 ColoredPortals
{
	public enum TagParseKind
	{
		PlainTag,
		Colored,
		Rejected
	}
	public sealed class TagParseResult
	{
		public TagParseKind Kind { get; private set; }

		public string Color { get; private set; }

		public string Tag { get; private set; }

		public string Error { get; private set; }

		public string Warning { get; private set; }

		private TagParseResult()
		{
		}

		internal static TagParseResult Plain(string tag, string warning)
		{
			return new TagParseResult
			{
				Kind = TagParseKind.PlainTag,
				Tag = tag,
				Warning = warning
			};
		}

		internal static TagParseResult Colored(string color, string tag)
		{
			return new TagParseResult
			{
				Kind = TagParseKind.Colored,
				Color = color,
				Tag = tag
			};
		}

		internal static TagParseResult Rejected(string error)
		{
			return new TagParseResult
			{
				Kind = TagParseKind.Rejected,
				Error = error
			};
		}
	}
	public static class ColoredPortalsParser
	{
		public static TagParseResult Parse(string input, IEnumerable<string> paletteNames, int maxTagLength)
		{
			if (paletteNames == null)
			{
				throw new ArgumentNullException("paletteNames");
			}
			if (maxTagLength < 1)
			{
				throw new ArgumentOutOfRangeException("maxTagLength");
			}
			HashSet<string> hashSet = new HashSet<string>(from n in paletteNames
				where !string.IsNullOrEmpty(n)
				select n.ToLowerInvariant(), StringComparer.Ordinal);
			string text = Sanitize(input);
			int num = text.IndexOf('=');
			if (num < 0)
			{
				return CheckLength(TagParseResult.Plain(text, null), maxTagLength);
			}
			string text2 = text.Substring(0, num).Trim();
			string text3 = text.Substring(num + 1).Trim();
			string text4 = text2.ToLowerInvariant();
			if (text4.Length > 0 && hashSet.Contains(text4))
			{
				if (text3.Length == 0)
				{
					return TagParseResult.Rejected("Add a tag after the '=' (for example red=Home).");
				}
				return CheckLength(TagParseResult.Colored(text4, text3), maxTagLength);
			}
			string warning = ((text2.Length == 0) ? "Nothing before '=', so the whole text is used as the tag." : ("'" + text2 + "' is not a color. Valid colors: " + string.Join(", ", hashSet.OrderBy<string, string>((string n) => n, StringComparer.Ordinal)) + ". The whole text is used as the tag."));
			return CheckLength(TagParseResult.Plain(text, warning), maxTagLength);
		}

		private static TagParseResult CheckLength(TagParseResult result, int maxTagLength)
		{
			if (string.IsNullOrEmpty(result.Tag))
			{
				return TagParseResult.Rejected("The portal tag is empty.");
			}
			if (result.Tag.Length > maxTagLength)
			{
				return TagParseResult.Rejected($"The tag is {result.Tag.Length} characters. The limit is {maxTagLength}.");
			}
			return result;
		}

		private static string Sanitize(string input)
		{
			if (string.IsNullOrEmpty(input))
			{
				return string.Empty;
			}
			return new string(input.Where((char c) => !char.IsControl(c)).ToArray()).Trim();
		}
	}
	public static class PaletteParser
	{
		private static readonly Regex HexColor = new Regex("^#?[0-9a-fA-F]{6}$", RegexOptions.CultureInvariant);

		public static Dictionary<string, string> Parse(string raw, List<string> problems)
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
			if (problems == null)
			{
				problems = new List<string>();
			}
			if (string.IsNullOrWhiteSpace(raw))
			{
				return dictionary;
			}
			string[] array = raw.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0)
				{
					continue;
				}
				int num = text.IndexOf('=');
				if (num <= 0)
				{
					problems.Add("Palette entry '" + text + "' has no name before '='.");
					continue;
				}
				string text2 = text.Substring(0, num).Trim().ToLowerInvariant();
				string text3 = text.Substring(num + 1).Trim();
				if (text2.Length == 0 || text2.Any((char c) => char.IsWhiteSpace(c) || c == '='))
				{
					problems.Add("Palette name '" + text2 + "' is not valid.");
				}
				else if (!HexColor.IsMatch(text3))
				{
					problems.Add("Palette entry '" + text2 + "' has an invalid hex color '" + text3 + "'.");
				}
				else if (dictionary.ContainsKey(text2))
				{
					problems.Add("Palette name '" + text2 + "' is listed more than once. The first entry is used.");
				}
				else
				{
					dictionary[text2] = (text3.StartsWith("#", StringComparison.Ordinal) ? text3 : ("#" + text3));
				}
			}
			return dictionary;
		}
	}
	internal static class ModConfig
	{
		internal const string DefaultPalette = "red=#E53935,blue=#1E88E5,green=#43A047,yellow=#FDD835,purple=#8E24AA,orange=#FB8C00,white=#FFFFFF,cyan=#00ACC1,pink=#D81B60";

		private static ConfigEntry<int> _maxTagLength;

		private static ConfigEntry<string> _palette;

		private static ConfigEntry<bool> _enableFeedback;

		private static ConfigEntry<bool> _dumpPortalHierarchy;

		private static ConfigEntry<float> _flameBrightness;

		private static Dictionary<string, Color> _paletteColors = new Dictionary<string, Color>(StringComparer.Ordinal);

		internal static int MaxTagLength => _maxTagLength.Value;

		internal static bool EnableFeedback => _enableFeedback.Value;

		internal static float FlameBrightness => _flameBrightness.Value;

		internal static bool DumpPortalHierarchy => _dumpPortalHierarchy.Value;

		internal static IReadOnlyDictionary<string, Color> PaletteColors => _paletteColors;

		internal static void Bind(ConfigFile config)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			_maxTagLength = config.Bind<int>("Tags", "MaxTagLength", 32, new ConfigDescription("Maximum portal tag length in characters. Vanilla is 10. Applies to the portal tag box.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 128), Array.Empty<object>()));
			_palette = config.Bind<string>("Colors", "Palette", "red=#E53935,blue=#1E88E5,green=#43A047,yellow=#FDD835,purple=#8E24AA,orange=#FB8C00,white=#FFFFFF,cyan=#00ACC1,pink=#D81B60", "Comma-separated name=#RRGGBB entries. Names are typed before '=' in the portal tag box (for example red=Home).");
			_enableFeedback = config.Bind<bool>("Feedback", "EnableFeedback", true, "Show in-game messages when a portal tag is refused or a color is not recognized.");
			_flameBrightness = config.Bind<float>("Tuning", "FlameBrightness", 0.45f, new ConfigDescription("Brightness of the recolored swirling flame, as a multiple of the palette color. Lower is dimmer. 1.0 is the raw palette color, which is too bright for the additive flame.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			_dumpPortalHierarchy = config.Bind<bool>("Debug", "DumpPortalHierarchy", false, "Write each portal's particle systems, renderers, materials, and lights to the BepInEx log when it loads. For diagnosing colors. Takes effect on the next load.");
			RebuildPalette();
			_palette.SettingChanged += delegate
			{
				RebuildPalette();
			};
		}

		private static void RebuildPalette()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = new List<string>();
			Dictionary<string, string> dictionary = PaletteParser.Parse(_palette.Value, list);
			Dictionary<string, Color> dictionary2 = new Dictionary<string, Color>(StringComparer.Ordinal);
			Color value = default(Color);
			foreach (KeyValuePair<string, string> item in dictionary)
			{
				if (ColorUtility.TryParseHtmlString(item.Value, ref value))
				{
					dictionary2[item.Key] = value;
				}
				else
				{
					list.Add("Palette entry '" + item.Key + "' could not be converted to a color.");
				}
			}
			foreach (string item2 in list)
			{
				Plugin.Log.LogWarning((object)("Palette: " + item2));
			}
			_paletteColors = dictionary2;
		}
	}
	[BepInPlugin("catos.coloredportals", "Colored Portals", "0.1.0")]
	[BepInProcess("valheim.exe")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "catos.coloredportals";

		public const string PluginName = "Colored Portals";

		public const string PluginVersion = "0.1.0";

		private Harmony _harmony;

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ModConfig.Bind(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("catos.coloredportals");
			_harmony.PatchAll(typeof(Plugin).Assembly);
			Log.LogInfo((object)"Colored Portals 0.1.0 loaded.");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class PortalColorStore
	{
		internal const string ColorKey = "coloredportals.color";

		internal const string RpcSetColor = "RPC_ColoredPortals_SetColor";

		private const string ForeignManagedKey = "vh_household_portal";

		internal static string Read(ZDO zdo)
		{
			if (zdo != null)
			{
				return zdo.GetString("coloredportals.color", string.Empty);
			}
			return string.Empty;
		}

		internal static bool IsManagedByOtherMod(ZDO zdo)
		{
			if (zdo != null)
			{
				return zdo.GetBool("vh_household_portal", false);
			}
			return false;
		}

		internal static void HandleSetColor(TeleportWorld portal, string colorName)
		{
			ZNetView component = ((Component)portal).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			if (zDO != null)
			{
				if (component.IsOwner())
				{
					string text = ((!string.IsNullOrEmpty(colorName) && ModConfig.PaletteColors.ContainsKey(colorName)) ? colorName : string.Empty);
					zDO.Set("coloredportals.color", text);
				}
				SwirlRecolorer component2 = ((Component)portal).GetComponent<SwirlRecolorer>();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.ForceRefresh();
				}
			}
		}
	}
	internal sealed class SwirlRecolorer : MonoBehaviour
	{
		private const float CheckInterval = 0.5f;

		private static readonly string[] TintProperties = new string[5] { "_Color", "_TintColor", "_BaseColor", "_Tint", "_MainColor" };

		private TeleportWorld _tw;

		private ZNetView _nview;

		private Transform _swirlRoot;

		private ParticleSystem[] _systems = (ParticleSystem[])(object)new ParticleSystem[0];

		private MinMaxGradient[] _originalStart = (MinMaxGradient[])(object)new MinMaxGradient[0];

		private Material[] _originalMats = (Material[])(object)new Material[0];

		private Material[] _swappedMats = (Material[])(object)new Material[0];

		private readonly MaterialPropertyBlock _block = new MaterialPropertyBlock();

		private Color _originalUnconnected;

		private Color _originalTargetFound;

		private string _applied;

		private float _nextCheck;

		private static bool _warnedNoTintSource;

		private void Start()
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			_nview = ((Component)this).GetComponent<ZNetView>();
			_tw = ((Component)this).GetComponent<TeleportWorld>();
			_swirlRoot = (((Object)(object)_tw != (Object)null && (Object)(object)_tw.m_target_found != (Object)null) ? ((Component)_tw.m_target_found).transform : null);
			if ((Object)(object)_tw == (Object)null || (Object)(object)_swirlRoot == (Object)null)
			{
				Plugin.Log.LogWarning((object)(((Object)this).name + ": no m_target_found effect; swirl recolor disabled for this portal."));
				((Behaviour)this).enabled = false;
				return;
			}
			_originalUnconnected = _tw.m_colorUnconnected;
			_originalTargetFound = _tw.m_colorTargetfound;
			_systems = ((Component)_swirlRoot).GetComponentsInChildren<ParticleSystem>(true);
			_originalMats = (Material[])(object)new Material[_systems.Length];
			_swappedMats = (Material[])(object)new Material[_systems.Length];
			_originalStart = (MinMaxGradient[])(object)new MinMaxGradient[_systems.Length];
			for (int i = 0; i < _systems.Length; i++)
			{
				if (!((Object)(object)_systems[i] == (Object)null))
				{
					MinMaxGradient[] originalStart = _originalStart;
					int num = i;
					MainModule main = _systems[i].main;
					originalStart[num] = ((MainModule)(ref main)).startColor;
				}
			}
			if (ModConfig.DumpPortalHierarchy)
			{
				DumpHierarchy();
			}
		}

		private void Update()
		{
			if (Time.time < _nextCheck)
			{
				return;
			}
			_nextCheck = Time.time + 0.5f;
			if ((Object)(object)_nview == (Object)null || !_nview.IsValid())
			{
				return;
			}
			ZDO zDO = _nview.GetZDO();
			if (zDO != null && !PortalColorStore.IsManagedByOtherMod(zDO))
			{
				string text = PortalColorStore.Read(zDO);
				if (!(text == _applied))
				{
					Apply(text);
				}
			}
		}

		internal void ForceRefresh()
		{
			_nextCheck = 0f;
		}

		private void Apply(string colorName)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: 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_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: 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)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			_applied = colorName;
			Color value = Color.white;
			bool flag = !string.IsNullOrEmpty(colorName) && ModConfig.PaletteColors.TryGetValue(colorName, out value);
			Material val = (flag ? FindTintSource() : null);
			for (int i = 0; i < _systems.Length; i++)
			{
				if ((Object)(object)_systems[i] == (Object)null)
				{
					continue;
				}
				MainModule main = _systems[i].main;
				ParticleSystemRenderer component = ((Component)_systems[i]).GetComponent<ParticleSystemRenderer>();
				if (!flag)
				{
					((MainModule)(ref main)).startColor = _originalStart[i];
					if ((Object)(object)component != (Object)null)
					{
						RestoreRenderer(i, component);
					}
					continue;
				}
				Material val2 = (((Object)(object)component != (Object)null) ? ((Renderer)component).sharedMaterial : null);
				if ((Object)(object)component == (Object)null || (Object)(object)val2 == (Object)null)
				{
					((MainModule)(ref main)).startColor = new MinMaxGradient(value);
				}
				else if (HasAnyTint(val2))
				{
					((MainModule)(ref main)).startColor = new MinMaxGradient(Color.white);
					Color val3 = (Color)(IsSwappedMaterial(val2) ? new Color(value.r * ModConfig.FlameBrightness, value.g * ModConfig.FlameBrightness, value.b * ModConfig.FlameBrightness, 1f) : value);
					_block.Clear();
					string[] tintProperties = TintProperties;
					foreach (string text in tintProperties)
					{
						if (val2.HasProperty(text))
						{
							_block.SetColor(text, val3);
						}
					}
					((Renderer)component).SetPropertyBlock(_block);
				}
				else if (IsGradientMapped(val2) && (Object)(object)val != (Object)null)
				{
					((MainModule)(ref main)).startColor = new MinMaxGradient(Color.white);
					SwapToTinted(i, component, val2, value, val);
				}
				else
				{
					((Renderer)component).SetPropertyBlock((MaterialPropertyBlock)null);
					((MainModule)(ref main)).startColor = new MinMaxGradient(value);
				}
			}
			if ((Object)(object)_tw != (Object)null)
			{
				_tw.m_colorUnconnected = (flag ? WithHue(_originalUnconnected, value) : _originalUnconnected);
				_tw.m_colorTargetfound = (flag ? WithHue(_originalTargetFound, value) : _originalTargetFound);
			}
		}

		private static bool HasAnyTint(Material mat)
		{
			string[] tintProperties = TintProperties;
			foreach (string text in tintProperties)
			{
				if (mat.HasProperty(text))
				{
					return true;
				}
			}
			return false;
		}

		private static bool IsGradientMapped(Material mat)
		{
			if ((Object)(object)mat.shader != (Object)null)
			{
				return ((Object)mat.shader).name.Contains("Gradient Mapped");
			}
			return false;
		}

		private Material FindTintSource()
		{
			Material val = null;
			for (int i = 0; i < _systems.Length; i++)
			{
				if ((Object)(object)_systems[i] == (Object)null)
				{
					continue;
				}
				ParticleSystemRenderer component = ((Component)_systems[i]).GetComponent<ParticleSystemRenderer>();
				if ((Object)(object)component == (Object)null)
				{
					continue;
				}
				Material sharedMaterial = ((Renderer)component).sharedMaterial;
				if (!((Object)(object)sharedMaterial == (Object)null) && sharedMaterial.HasProperty("_Color") && !IsSwappedMaterial(sharedMaterial))
				{
					if ((Object)(object)sharedMaterial.shader != (Object)null && ((Object)sharedMaterial.shader).name.Contains("Unlit"))
					{
						return sharedMaterial;
					}
					if ((Object)(object)val == (Object)null)
					{
						val = sharedMaterial;
					}
				}
			}
			if ((Object)(object)val == (Object)null && !_warnedNoTintSource)
			{
				_warnedNoTintSource = true;
				Plugin.Log.LogWarning((object)"No tintable particle material on this portal; gradient-mapped swirl parts keep vanilla color.");
			}
			return val;
		}

		private bool IsSwappedMaterial(Material m)
		{
			for (int i = 0; i < _swappedMats.Length; i++)
			{
				if ((Object)(object)_swappedMats[i] == (Object)(object)m)
				{
					return true;
				}
			}
			return false;
		}

		private void SwapToTinted(int i, ParticleSystemRenderer renderer, Material original, Color palette, Material source)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_005e: 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)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_swappedMats[i] != (Object)null))
			{
				Material val = new Material(source)
				{
					name = ((Object)original).name + " (ColoredPortals)"
				};
				if (original.HasProperty("_MainTex"))
				{
					val.SetTexture("_MainTex", original.GetTexture("_MainTex"));
				}
				float flameBrightness = ModConfig.FlameBrightness;
				val.SetColor("_Color", new Color(palette.r * flameBrightness, palette.g * flameBrightness, palette.b * flameBrightness, 1f));
				if (val.HasProperty("_SrcBlend"))
				{
					val.SetFloat("_SrcBlend", 1f);
				}
				if (val.HasProperty("_DstBlend"))
				{
					val.SetFloat("_DstBlend", 1f);
				}
				_originalMats[i] = original;
				_swappedMats[i] = val;
				((Renderer)renderer).sharedMaterial = val;
			}
		}

		private void RestoreRenderer(int i, ParticleSystemRenderer renderer)
		{
			((Renderer)renderer).SetPropertyBlock((MaterialPropertyBlock)null);
			if ((Object)(object)_swappedMats[i] != (Object)null)
			{
				((Renderer)renderer).sharedMaterial = _originalMats[i];
				Object.Destroy((Object)(object)_swappedMats[i]);
				_swappedMats[i] = null;
				_originalMats[i] = null;
			}
		}

		private void OnDestroy()
		{
			for (int i = 0; i < _swappedMats.Length; i++)
			{
				if ((Object)(object)_swappedMats[i] != (Object)null)
				{
					Object.Destroy((Object)(object)_swappedMats[i]);
					_swappedMats[i] = null;
				}
			}
		}

		private static Color WithHue(Color original, Color palette)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Max(((Color)(ref original)).maxColorComponent, 1f);
			if (((Color)(ref original)).maxColorComponent <= 0f)
			{
				num = 1f;
			}
			return new Color(palette.r * num, palette.g * num, palette.b * num, original.a);
		}

		private void DumpHierarchy()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine($"[dump] portal '{((Object)this).name}' at {((Component)this).transform.position}");
			ParticleSystem[] componentsInChildren = ((Component)this).GetComponentsInChildren<ParticleSystem>(true);
			foreach (ParticleSystem val in componentsInChildren)
			{
				bool flag = ((Component)val).transform.IsChildOf(_swirlRoot);
				ParticleSystemRenderer component = ((Component)val).GetComponent<ParticleSystemRenderer>();
				Material val2 = (((Object)(object)component != (Object)null) ? ((Renderer)component).sharedMaterial : null);
				string text = DescribeMaterial(val2);
				string text2 = (((Object)(object)val2 != (Object)null) ? string.Join(", ", DescribeProperties(val2)) : "");
				stringBuilder.AppendLine($"[dump]  particles '{PathOf(((Component)val).transform)}' inTarget={flag} playing={val.isPlaying} material={text} props=[{text2}]");
			}
			Renderer[] componentsInChildren2 = ((Component)this).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val3 in componentsInChildren2)
			{
				if (val3 is ParticleSystemRenderer)
				{
					continue;
				}
				StringBuilder stringBuilder2 = new StringBuilder();
				Material[] sharedMaterials = val3.sharedMaterials;
				foreach (Material m in sharedMaterials)
				{
					if (stringBuilder2.Length > 0)
					{
						stringBuilder2.Append("; ");
					}
					stringBuilder2.Append(DescribeMaterial(m));
				}
				stringBuilder.AppendLine($"[dump]  renderer '{PathOf(((Component)val3).transform)}' enabled={val3.enabled} materials={stringBuilder2}");
			}
			Light[] componentsInChildren3 = ((Component)this).GetComponentsInChildren<Light>(true);
			foreach (Light val4 in componentsInChildren3)
			{
				stringBuilder.AppendLine($"[dump]  light '{PathOf(((Component)val4).transform)}' color={val4.color} intensity={val4.intensity}");
			}
			Plugin.Log.LogInfo((object)stringBuilder.ToString().TrimEnd(Array.Empty<char>()));
		}

		private static string DescribeMaterial(Material m)
		{
			if ((Object)(object)m == (Object)null)
			{
				return "none";
			}
			return ((Object)m).name + " (shader " + ((Object)m.shader).name + ")";
		}

		private static List<string> DescribeProperties(Material mat)
		{
			//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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Invalid comparison between Unknown and I4
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = new List<string>();
			Shader shader = mat.shader;
			int propertyCount = shader.GetPropertyCount();
			for (int i = 0; i < propertyCount; i++)
			{
				string propertyName = shader.GetPropertyName(i);
				ShaderPropertyType propertyType = shader.GetPropertyType(i);
				string text = $"{propertyName}:{propertyType}";
				if ((int)propertyType == 4)
				{
					Texture texture = mat.GetTexture(propertyName);
					text += (((Object)(object)texture != (Object)null) ? $"({((Object)texture).name} {texture.width}x{texture.height})" : "(none)");
				}
				else if ((int)propertyType == 0)
				{
					text += $"={mat.GetColor(propertyName)}";
				}
				list.Add(text);
			}
			return list;
		}

		private string PathOf(Transform t)
		{
			List<string> list = new List<string>();
			Transform val = t;
			while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)((Component)this).transform)
			{
				list.Add(((Object)val).name);
				val = val.parent;
			}
			list.Reverse();
			return string.Join("/", list);
		}
	}
	[HarmonyPatch(typeof(TextInput), "RequestText")]
	internal static class TextInputRequestTextPatch
	{
		private const string PortalTagTopic = "$piece_portal_tag";

		private static void Prefix(TextReceiver sign, string topic, ref int charLimit)
		{
			if (sign is TeleportWorld && string.Equals(topic, "$piece_portal_tag", StringComparison.Ordinal))
			{
				charLimit = ModConfig.MaxTagLength;
			}
		}
	}
	[HarmonyPatch(typeof(TeleportWorld), "Awake")]
	internal static class TeleportWorldAwakePatch
	{
		private static void Postfix(TeleportWorld __instance)
		{
			try
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.GetZDO() != null)
				{
					component.Register<string>("RPC_ColoredPortals_SetColor", (Action<long, string>)delegate(long sender, string colorName)
					{
						PortalColorStore.HandleSetColor(__instance, colorName);
					});
					if ((Object)(object)((Component)__instance).GetComponent<SwirlRecolorer>() == (Object)null)
					{
						((Component)__instance).gameObject.AddComponent<SwirlRecolorer>();
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("TeleportWorld.Awake postfix failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(TeleportWorld), "GetText")]
	internal static class TeleportWorldGetTextPatch
	{
		private static void Postfix(TeleportWorld __instance, ref string __result)
		{
			try
			{
				if (string.IsNullOrEmpty(__result))
				{
					return;
				}
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.GetZDO() != null && !PortalColorStore.IsManagedByOtherMod(component.GetZDO()))
				{
					string text = PortalColorStore.Read(component.GetZDO());
					if (text.Length != 0)
					{
						__result = text + "=" + __result;
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("TeleportWorld.GetText postfix failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(TeleportWorld), "SetText")]
	internal static class TeleportWorldSetTextPatch
	{
		private static bool Prefix(TeleportWorld __instance, ref string text)
		{
			try
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					return true;
				}
				if (PortalColorStore.IsManagedByOtherMod(component.GetZDO()))
				{
					return true;
				}
				TagParseResult tagParseResult = ColoredPortalsParser.Parse(text, ModConfig.PaletteColors.Keys, ModConfig.MaxTagLength);
				if (tagParseResult.Kind == TagParseKind.Rejected)
				{
					Notify(tagParseResult.Error);
					return false;
				}
				string text2 = ((tagParseResult.Kind == TagParseKind.Colored) ? tagParseResult.Color : string.Empty);
				component.InvokeRPC("RPC_ColoredPortals_SetColor", new object[1] { text2 });
				text = tagParseResult.Tag;
				Notify(tagParseResult.Warning);
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("TeleportWorld.SetText prefix failed; vanilla text used: " + ex));
				return true;
			}
		}

		private static void Notify(string message)
		{
			if (ModConfig.EnableFeedback && !string.IsNullOrEmpty(message))
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null)
				{
					((Character)localPlayer).Message((MessageType)2, message, 0, (Sprite)null, false);
				}
			}
		}
	}
}