Decompiled source of UnshelvedHighlight v1.0.0

plugins/UnshelvedHighlight.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HighlightPlus;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("UnshelvedHighlight")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("UnshelvedHighlight")]
[assembly: AssemblyTitle("UnshelvedHighlight")]
[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 UnshelvedHighlight
{
	internal static class BoxHighlighter
	{
		private sealed class Entry
		{
			public HighlightEffect Effect;

			public bool AddedByUs;
		}

		public struct Result
		{
			public int Products;

			public int Boxes;
		}

		private static readonly Dictionary<GameObject, Entry> Active = new Dictionary<GameObject, Entry>();

		public static Result Refresh()
		{
			NPC_Manager instance = NPC_Manager.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.shelvesOBJ == (Object)null || (Object)(object)instance.storageOBJ == (Object)null)
			{
				Clear();
				return default(Result);
			}
			List<Data_Container> list = (from c in Containers(instance.storageOBJ.transform)
				where c.containerClass == 69
				select c).ToList();
			HashSet<int> hashSet = UnshelvedFinder.Find(from c in Containers(instance.shelvesOBJ.transform)
				select c.productInfoArray, list.Select((Data_Container c) => c.productInfoArray));
			HashSet<GameObject> hashSet2 = new HashSet<GameObject>();
			foreach (Data_Container item in list)
			{
				Transform val = ((Component)item).transform.Find("BoxContainer");
				int[] productInfoArray = item.productInfoArray;
				if ((Object)(object)val == (Object)null || productInfoArray == null)
				{
					continue;
				}
				int num = Math.Min(productInfoArray.Length / 2, val.childCount);
				for (int num2 = 0; num2 < num; num2++)
				{
					if (productInfoArray[num2 * 2 + 1] > 0 && hashSet.Contains(productInfoArray[num2 * 2]))
					{
						Transform child = val.GetChild(num2);
						if (child.childCount > 0)
						{
							hashSet2.Add(((Component)child.GetChild(0)).gameObject);
						}
					}
				}
			}
			foreach (GameObject item2 in Active.Keys.ToList())
			{
				if ((Object)(object)item2 == (Object)null || !hashSet2.Contains(item2))
				{
					Remove(item2);
				}
			}
			foreach (GameObject item3 in hashSet2)
			{
				if (!Active.ContainsKey(item3))
				{
					Add(item3);
				}
			}
			return new Result
			{
				Products = hashSet.Count,
				Boxes = hashSet2.Count
			};
		}

		public static void Clear()
		{
			foreach (GameObject item in Active.Keys.ToList())
			{
				Remove(item);
			}
			Active.Clear();
		}

		private static IEnumerable<Data_Container> Containers(Transform root)
		{
			for (int i = 0; i < root.childCount; i++)
			{
				Data_Container component = ((Component)root.GetChild(i)).GetComponent<Data_Container>();
				if ((Object)(object)component != (Object)null)
				{
					yield return component;
				}
			}
		}

		private static void Add(GameObject box)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: 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)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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)
			try
			{
				HighlightEffect val = box.GetComponent<HighlightEffect>();
				bool flag = (Object)(object)val == (Object)null;
				if (flag)
				{
					val = box.AddComponent<HighlightEffect>();
				}
				Color value = Plugin.HighlightColor.Value;
				val.effectGroup = (TargetOptions)0;
				val.outline = 1f;
				val.outlineColor = value;
				val.outlineWidth = 0.8f;
				val.glow = 0.6f;
				val.glowHQColor = value;
				val.outlineVisibility = (Visibility)(Plugin.SeeThroughWalls.Value ? 1 : 0);
				val.glowVisibility = val.outlineVisibility;
				val.Refresh(false);
				val.highlighted = true;
				Active[box] = new Entry
				{
					Effect = val,
					AddedByUs = flag
				};
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not highlight " + ((Object)box).name + ": " + ex.Message));
			}
		}

		private static void Remove(GameObject box)
		{
			if (!Active.TryGetValue(box, out var value))
			{
				return;
			}
			Active.Remove(box);
			if ((Object)(object)box == (Object)null || (Object)(object)value.Effect == (Object)null)
			{
				return;
			}
			try
			{
				value.Effect.highlighted = false;
				if (value.AddedByUs)
				{
					Object.Destroy((Object)(object)value.Effect);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not remove highlight: " + ex.Message));
			}
		}
	}
	internal static class Loc
	{
		public const string Auto = "Auto";

		public const string Fallback = "en";

		private static readonly Dictionary<string, Dictionary<string, string>> Tables = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase)
		{
			["en"] = new Dictionary<string, string>
			{
				["on"] = "Highlight ON: {0} product(s) in storage are not on any shelf ({1} box(es)).",
				["on.none"] = "Highlight ON: every product in storage is on a shelf.",
				["off"] = "Highlight OFF."
			},
			["ja"] = new Dictionary<string, string>
			{
				["on"] = "ハイライト ON: 棚に並んでいない商品が倉庫に {0} 種類あります({1} 箱)。",
				["on.none"] = "ハイライト ON: 倉庫の商品はすべて棚に並んでいます。",
				["off"] = "ハイライト OFF"
			}
		};

		public static IEnumerable<string> Available => Tables.Keys.OrderBy<string, string>((string k) => k, StringComparer.OrdinalIgnoreCase);

		public static string Current
		{
			get
			{
				string text = Plugin.Language?.Value ?? "Auto";
				if (!string.Equals(text, "Auto", StringComparison.OrdinalIgnoreCase) && Tables.ContainsKey(text))
				{
					return text;
				}
				if (!GameIsJapanese())
				{
					return "en";
				}
				return "ja";
			}
		}

		public static void LoadExternal(string pluginDir)
		{
			string path = Path.Combine(pluginDir, "lang");
			if (!Directory.Exists(path))
			{
				return;
			}
			string[] files = Directory.GetFiles(path, "*.txt");
			foreach (string text in files)
			{
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
				if (fileNameWithoutExtension.StartsWith("_") || fileNameWithoutExtension.Length == 0)
				{
					continue;
				}
				try
				{
					if (!Tables.TryGetValue(fileNameWithoutExtension, out var value))
					{
						value = (Tables[fileNameWithoutExtension] = new Dictionary<string, string>());
					}
					int num = 0;
					string[] array = File.ReadAllLines(text, Encoding.UTF8);
					for (int j = 0; j < array.Length; j++)
					{
						string text2 = array[j].Trim();
						if (text2.Length == 0 || text2.StartsWith("#"))
						{
							continue;
						}
						int num2 = text2.IndexOf('=');
						if (num2 > 0)
						{
							string key = text2.Substring(0, num2).Trim();
							string text3 = text2.Substring(num2 + 1).Trim();
							if (text3.Length >= 2 && text3[0] == '"' && text3[text3.Length - 1] == '"')
							{
								text3 = text3.Substring(1, text3.Length - 2);
							}
							value[key] = text3.Replace("\\n", "\n");
							num++;
						}
					}
					Plugin.Log.LogInfo((object)$"Loaded language file '{fileNameWithoutExtension}' ({num} entries).");
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Could not read language file " + text + ": " + ex.Message));
				}
			}
		}

		public static string T(string key, params object[] args)
		{
			string value = null;
			if (Tables.TryGetValue(Current, out var value2))
			{
				value2.TryGetValue(key, out value);
			}
			if (value == null)
			{
				Tables["en"].TryGetValue(key, out value);
			}
			if (value == null)
			{
				return key;
			}
			if (args == null || args.Length == 0)
			{
				return value;
			}
			try
			{
				return string.Format(value, args);
			}
			catch (FormatException)
			{
				return value;
			}
		}

		private static bool GameIsJapanese()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			LocalizationManager instance = LocalizationManager.instance;
			if ((Object)(object)instance == (Object)null || instance.LocalizationDictionary == null || instance.LocalizationDictionary.Count == 0)
			{
				return (int)Application.systemLanguage == 22;
			}
			int num = 0;
			foreach (string value in instance.LocalizationDictionary.Values)
			{
				if (value != null && value.Any((char c) => c >= '\u3040' && c <= 'ヿ'))
				{
					return true;
				}
				if (++num >= 300)
				{
					break;
				}
			}
			return false;
		}
	}
	internal static class Notifier
	{
		private static FieldInfo _cooldownField;

		private static bool _resolved;

		public static void Show(string message)
		{
			Plugin.Log.LogInfo((object)("[Notify] " + message));
			GameCanvas instance = GameCanvas.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			try
			{
				if (!_resolved)
				{
					_resolved = true;
					_cooldownField = typeof(GameCanvas).GetField("inCooldown", BindingFlags.Instance | BindingFlags.NonPublic);
				}
				_cooldownField?.SetValue(instance, false);
				instance.CreateCanvasNotification("`" + message);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Notification failed: " + ex.Message));
			}
		}
	}
	[BepInPlugin("penguin4glte.supermarkettogether.unshelvedhighlight", "UnshelvedHighlight", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "penguin4glte.supermarkettogether.unshelvedhighlight";

		public const string PluginName = "UnshelvedHighlight";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<KeyboardShortcut> ToggleHotkey;

		internal static ConfigEntry<Color> HighlightColor;

		internal static ConfigEntry<bool> SeeThroughWalls;

		internal static ConfigEntry<float> RefreshInterval;

		internal static ConfigEntry<string> Language;

		private bool _on;

		private float _nextRefresh;

		private void Awake()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Expected O, but got Unknown
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Expected O, but got Unknown
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Loc.LoadExternal(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location));
			ToggleHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "ToggleHotkey", new KeyboardShortcut((KeyCode)291, Array.Empty<KeyCode>()), "Key that turns the highlight on/off.\nハイライトの ON/OFF を切り替えるキー。");
			HighlightColor = ((BaseUnityPlugin)this).Config.Bind<Color>("General", "HighlightColor", new Color(0f, 0.9f, 1f, 1f), "Outline/glow color of highlighted boxes (RGBA, hex).\nハイライトした箱の輪郭・発光の色(RGBA の16進数)。");
			SeeThroughWalls = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SeeThroughWalls", false, "Show the highlight through walls and other objects.\n壁や他の物の向こう側でもハイライトを表示します。");
			RefreshInterval = ((BaseUnityPlugin)this).Config.Bind<float>("General", "RefreshInterval", 1f, new ConfigDescription("Seconds between updates while the highlight is on.\nハイライト ON の間、表示を更新する間隔(秒)。", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 10f), Array.Empty<object>()));
			Language = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Language", "Auto", new ConfigDescription("Message language. Auto = Japanese if the game is in Japanese, otherwise English. Add more languages as lang/<code>.txt in the plugin folder.\nメッセージの言語。Auto = ゲームが日本語なら日本語、それ以外は英語。", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[1] { "Auto" }.Concat(Loc.Available).ToArray()), Array.Empty<object>()));
			HighlightColor.SettingChanged += delegate
			{
				Restyle();
			};
			SeeThroughWalls.SettingChanged += delegate
			{
				Restyle();
			};
			Log.LogInfo((object)string.Format("{0} {1} loaded. Hotkey: {2}", "UnshelvedHighlight", "1.0.0", ToggleHotkey.Value));
		}

		private void OnDestroy()
		{
			BoxHighlighter.Clear();
		}

		private void Update()
		{
			//IL_0021: 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)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Invalid comparison between Unknown and I4
			bool flag = (Object)(object)NPC_Manager.Instance != (Object)null && (Object)(object)ProductListing.Instance != (Object)null;
			KeyboardShortcut value = ToggleHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown() && (int)Cursor.lockState == 1 && flag)
			{
				Toggle();
			}
			if (_on)
			{
				if (!flag)
				{
					_on = false;
					BoxHighlighter.Clear();
				}
				else if (Time.unscaledTime >= _nextRefresh)
				{
					SafeRefresh();
				}
			}
		}

		private void Toggle()
		{
			_on = !_on;
			if (!_on)
			{
				BoxHighlighter.Clear();
				Notifier.Show(Loc.T("off"));
				return;
			}
			BoxHighlighter.Result result = SafeRefresh();
			Notifier.Show((result.Products > 0) ? Loc.T("on", result.Products, result.Boxes) : Loc.T("on.none"));
		}

		private void Restyle()
		{
			if (_on)
			{
				BoxHighlighter.Clear();
				SafeRefresh();
			}
		}

		private BoxHighlighter.Result SafeRefresh()
		{
			_nextRefresh = Time.unscaledTime + RefreshInterval.Value;
			try
			{
				return BoxHighlighter.Refresh();
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Highlight refresh failed: " + ex));
				return default(BoxHighlighter.Result);
			}
		}
	}
	internal static class UnshelvedFinder
	{
		public static HashSet<int> Find(IEnumerable<int[]> productShelves, IEnumerable<int[]> storageShelves)
		{
			HashSet<int> hashSet = new HashSet<int>();
			foreach (int[] productShelf in productShelves)
			{
				foreach (var item3 in Slots(productShelf))
				{
					var (item, _) = item3;
					if (item3.count > 0)
					{
						hashSet.Add(item);
					}
				}
			}
			HashSet<int> hashSet2 = new HashSet<int>();
			foreach (int[] storageShelf in storageShelves)
			{
				foreach (var item4 in Slots(storageShelf))
				{
					var (item2, _) = item4;
					if (item4.count > 0 && !hashSet.Contains(item2))
					{
						hashSet2.Add(item2);
					}
				}
			}
			return hashSet2;
		}

		public static IEnumerable<(int pid, int count)> Slots(int[] productInfoArray)
		{
			if (productInfoArray == null)
			{
				yield break;
			}
			for (int i = 0; i + 1 < productInfoArray.Length; i += 2)
			{
				if (productInfoArray[i] >= 0)
				{
					yield return (pid: productInfoArray[i], count: productInfoArray[i + 1]);
				}
			}
		}
	}
}