Decompiled source of MapItems v0.1.1

MapItems.dll

Decompiled 2 hours ago
using System;
using System.Collections;
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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using ModShared;
using Photon.Pun;
using Photon.Realtime;
using REPOLib.Modules;
using UnityEngine;

[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("MapItems")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MapItems")]
[assembly: AssemblyTitle("MapItems")]
[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 ModShared
{
	internal static class ConfigSync
	{
		private const float Interval = 2f;

		private static ConfigFile _cfg;

		private static ManualLogSource _log;

		private static string _property;

		private static readonly HashSet<string> LocalKeys = new HashSet<string>();

		private static readonly Dictionary<ConfigDefinition, string> Own = new Dictionary<ConfigDefinition, string>();

		private static string _published;

		private static string _applied;

		internal static bool Overridden => Own.Count > 0;

		internal static float TickInterval => 2f;

		internal static event Action Changed;

		internal static void Init(ConfigFile cfg, string modName, ManualLogSource log, params string[] localKeys)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: 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_005a: Expected O, but got Unknown
			_cfg = cfg;
			_log = log;
			_property = modName + "_config";
			foreach (string item in localKeys)
			{
				LocalKeys.Add(item);
			}
			GameObject val = new GameObject(modName + "_ConfigSync")
			{
				hideFlags = (HideFlags)61
			};
			Object.DontDestroyOnLoad((Object)val);
			val.AddComponent<ConfigSyncRunner>().Tick = Tick;
		}

		private static void Tick()
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0072: Expected O, but got Unknown
			if (_cfg == null)
			{
				return;
			}
			if (!SemiFunc.IsMultiplayer() || !PhotonNetwork.InRoom || PhotonNetwork.CurrentRoom == null)
			{
				Restore();
				_published = null;
			}
			else if (PhotonNetwork.IsMasterClient)
			{
				Restore();
				string text = Serialize();
				if (!(text == _published))
				{
					_published = text;
					Room currentRoom = PhotonNetwork.CurrentRoom;
					Hashtable val = new Hashtable();
					((Dictionary<object, object>)val).Add((object)_property, (object)text);
					currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
					_log.LogInfo((object)"Settings shared with the other players.");
				}
			}
			else
			{
				_published = null;
				if (((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)_property, out object value) && value is string text2 && !(text2 == _applied))
				{
					Apply(text2);
				}
			}
		}

		private static bool IsLocal(ConfigDefinition def)
		{
			return LocalKeys.Contains(def.Section + "|" + def.Key);
		}

		private static string Serialize()
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in _cfg)
			{
				if (!IsLocal(item.Key))
				{
					string text = item.Value.GetSerializedValue() ?? "";
					stringBuilder.Append(item.Key.Section).Append('\t').Append(item.Key.Key)
						.Append('\t')
						.Append(text.Replace("\n", " ").Replace("\t", " "))
						.Append('\n');
				}
			}
			return stringBuilder.ToString();
		}

		private static void Apply(string data)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			int num = 0;
			_cfg.SaveOnConfigSet = false;
			string[] array = data.Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split('\t');
				if (array2.Length < 3)
				{
					continue;
				}
				ConfigDefinition val = new ConfigDefinition(array2[0], array2[1]);
				if (IsLocal(val) || !_cfg.ContainsKey(val))
				{
					continue;
				}
				ConfigEntryBase val2 = _cfg[val];
				try
				{
					string serializedValue = val2.GetSerializedValue();
					if (!(serializedValue == array2[2]))
					{
						if (!Own.ContainsKey(val))
						{
							Own[val] = serializedValue;
						}
						val2.SetSerializedValue(array2[2]);
						num++;
					}
				}
				catch (Exception ex)
				{
					_log.LogDebug((object)("Host setting " + array2[0] + "." + array2[1] + " ignored: " + ex.Message));
				}
			}
			_applied = data;
			if (Own.Count == 0)
			{
				_cfg.SaveOnConfigSet = true;
			}
			_log.LogInfo((object)$"Using the host's settings ({num} value(s) differ from yours).");
			if (num > 0)
			{
				Notify();
			}
		}

		private static void Restore()
		{
			_applied = null;
			if (Own.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<ConfigDefinition, string> item in Own)
			{
				try
				{
					if (_cfg.ContainsKey(item.Key))
					{
						_cfg[item.Key].SetSerializedValue(item.Value);
					}
				}
				catch (Exception ex)
				{
					_log.LogDebug((object)("Could not restore " + item.Key.Section + "." + item.Key.Key + ": " + ex.Message));
				}
			}
			Own.Clear();
			_cfg.SaveOnConfigSet = true;
			_log.LogInfo((object)"Back to your own settings.");
			Notify();
		}

		private static void Notify()
		{
			try
			{
				ConfigSync.Changed?.Invoke();
			}
			catch (Exception arg)
			{
				_log.LogError((object)$"Applying changed settings failed: {arg}");
			}
		}
	}
	public class ConfigSyncRunner : MonoBehaviour
	{
		internal Action Tick;

		private float _timer;

		private void Update()
		{
			_timer -= Time.unscaledDeltaTime;
			if (_timer > 0f)
			{
				return;
			}
			_timer = ConfigSync.TickInterval;
			try
			{
				Tick?.Invoke();
			}
			catch (Exception)
			{
			}
		}
	}
}
namespace MapItems
{
	[BepInPlugin("Ondra.MapItems", "MapItems", "0.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "Ondra.MapItems";

		public const string Name = "MapItems";

		public const string Version = "0.1.1";

		internal static ManualLogSource Log;

		internal static Plugin Instance;

		internal ConfigEntry<int> MinItems;

		internal ConfigEntry<int> MaxItems;

		internal ConfigEntry<bool> Guns;

		internal ConfigEntry<bool> Melee;

		internal ConfigEntry<bool> Grenades;

		internal ConfigEntry<bool> Upgrades;

		internal ConfigEntry<bool> HealthPacks;

		internal ConfigEntry<bool> Other;

		internal ConfigEntry<string> Blacklist;

		internal ConfigEntry<bool> ShowOnMap;

		internal ConfigEntry<Color> MapColor;

		private void Awake()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			MinItems = ((BaseUnityPlugin)this).Config.Bind<int>("Amount", "MinItems", 2, new ConfigDescription("Minimum items spawned per level.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			MaxItems = ((BaseUnityPlugin)this).Config.Bind<int>("Amount", "MaxItems", 5, new ConfigDescription("Maximum items spawned per level.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			Guns = ((BaseUnityPlugin)this).Config.Bind<bool>("Categories", "Guns", true, "Guns (pistol, shotgun, tranq, laser...).");
			Melee = ((BaseUnityPlugin)this).Config.Bind<bool>("Categories", "Melee", true, "Melee weapons.");
			Grenades = ((BaseUnityPlugin)this).Config.Bind<bool>("Categories", "Grenades", true, "Grenades and mines.");
			Upgrades = ((BaseUnityPlugin)this).Config.Bind<bool>("Categories", "Upgrades", true, "Player upgrades (stamina, health, strength...).");
			HealthPacks = ((BaseUnityPlugin)this).Config.Bind<bool>("Categories", "HealthPacks", true, "Health packs.");
			Other = ((BaseUnityPlugin)this).Config.Bind<bool>("Categories", "Other", false, "Drones, orbs, trackers and other tools.");
			Blacklist = ((BaseUnityPlugin)this).Config.Bind<string>("Categories", "Blacklist", "", "Comma separated item names that never spawn (e.g. 'Item Gun Laser, Item Grenade Explosive').");
			ShowOnMap = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "ShowOnMap", true, "Spawned items are highlighted on the map.");
			MapColor = ((BaseUnityPlugin)this).Config.Bind<Color>("Map", "Color", new Color(0.72f, 0.2f, 1f, 1f), "Map marker color of spawned items.");
			ConfigSync.Init(((BaseUnityPlugin)this).Config, "MapItems", Log, "Map|ShowOnMap");
			new Harmony("Ondra.MapItems").PatchAll(typeof(LevelGeneratorPatch));
			Log.LogInfo((object)"MapItems 0.1.1 loaded.");
		}

		internal bool IsAllowed(Item item)
		{
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected I4, but got Unknown
			if ((Object)(object)item == (Object)null || item.disabled || !item.physicalItem)
			{
				return false;
			}
			if (((Object)item).name.StartsWith("Item Star Orb ", StringComparison.Ordinal))
			{
				return false;
			}
			if ((from s in Blacklist.Value.Split(',')
				select s.Trim() into s
				where s.Length > 0
				select s).Any((string b) => string.Equals(b, ((Object)item).name, StringComparison.OrdinalIgnoreCase) || string.Equals(b, item.itemName, StringComparison.OrdinalIgnoreCase)))
			{
				return false;
			}
			itemType itemType = item.itemType;
			switch ((int)itemType)
			{
			case 9:
			case 15:
				return Guns.Value;
			case 7:
				return Melee.Value;
			case 6:
			case 11:
				return Grenades.Value;
			case 4:
				return Upgrades.Value;
			case 8:
				return HealthPacks.Value;
			case 0:
			case 1:
			case 10:
			case 13:
				return Other.Value;
			default:
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(LevelGenerator), "Start")]
	internal static class LevelGeneratorPatch
	{
		[HarmonyPostfix]
		private static void Postfix(LevelGenerator __instance)
		{
			((MonoBehaviour)__instance).StartCoroutine(ItemSpawner.SpawnWhenReady());
		}
	}
	internal static class ItemSpawner
	{
		private static readonly FieldRef<ValuableDirector, bool> SetupComplete = AccessTools.FieldRefAccess<ValuableDirector, bool>("setupComplete");

		private const string RoomKey = "MapItems_ids";

		private static readonly FieldRef<MapCustom, MapCustomEntity> MapEntity = AccessTools.FieldRefAccess<MapCustom, MapCustomEntity>("mapCustomEntity");

		private static Sprite _fallbackSprite;

		internal static IEnumerator SpawnWhenReady()
		{
			float timeout = 180f;
			while (timeout > 0f)
			{
				LevelGenerator instance = LevelGenerator.Instance;
				if ((Object)(object)instance != (Object)null && instance.Generated)
				{
					break;
				}
				timeout -= Time.unscaledDeltaTime;
				yield return null;
			}
			if (timeout <= 0f)
			{
				Plugin.Log.LogWarning((object)"Level was not generated in time, no items spawned.");
			}
			else
			{
				if (!SemiFunc.RunIsLevel())
				{
					yield break;
				}
				if (SemiFunc.IsMasterClientOrSingleplayer())
				{
					float wait = 10f;
					while (wait > 0f)
					{
						ValuableDirector instance2 = ValuableDirector.instance;
						if ((Object)(object)instance2 != (Object)null && SetupComplete.Invoke(instance2))
						{
							break;
						}
						wait -= Time.unscaledDeltaTime;
						yield return null;
					}
					yield return (object)new WaitForSeconds(1f);
					try
					{
						Spawn();
						yield break;
					}
					catch (Exception arg)
					{
						Plugin.Log.LogError((object)$"Spawning items failed: {arg}");
						yield break;
					}
				}
				yield return ClientMarkLoop();
			}
		}

		private static void Spawn()
		{
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Expected O, but got Unknown
			//IL_0263: Expected O, but got Unknown
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: 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_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			Plugin instance = Plugin.Instance;
			if ((Object)(object)StatsManager.instance == (Object)null)
			{
				return;
			}
			List<Item> list = StatsManager.instance.itemDictionary.Values.Where(instance.IsAllowed).ToList();
			if (list.Count == 0)
			{
				Plugin.Log.LogWarning((object)"No allowed items to spawn (check config categories).");
				return;
			}
			int num = Mathf.Min(instance.MinItems.Value, instance.MaxItems.Value);
			int num2 = Mathf.Max(instance.MinItems.Value, instance.MaxItems.Value);
			int num3 = Random.Range(num, num2 + 1);
			List<ValuableVolume> source = (from _ in Object.FindObjectsByType<ValuableVolume>((FindObjectsSortMode)0)
				orderby Random.value
				select _).ToList();
			HashSet<ValuableVolume> used = new HashSet<ValuableVolume>();
			int num4 = 0;
			List<int> list2 = new List<int>();
			for (int num5 = 0; num5 < num3 * 5; num5++)
			{
				if (num4 >= num3)
				{
					break;
				}
				Item item = list[Random.Range(0, list.Count)];
				ValuableVolume val = ((IEnumerable<ValuableVolume>)source).FirstOrDefault((Func<ValuableVolume, bool>)((ValuableVolume v) => !used.Contains(v) && Fits(item, v) && IsFree(v)));
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				used.Add(val);
				Vector3 val2 = ((Component)val).transform.position + Vector3.up * 0.15f;
				Quaternion val3 = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f) * item.spawnRotationOffset;
				GameObject val4 = Items.SpawnItem(item, val2, val3);
				if ((Object)(object)val4 != (Object)null)
				{
					num4++;
					MarkOnMap(val4);
					PhotonView component = val4.GetComponent<PhotonView>();
					if ((Object)(object)component != (Object)null)
					{
						list2.Add(component.ViewID);
					}
					Plugin.Log.LogInfo((object)$"Spawned '{item.itemName}' ({((Object)item).name}) in {val.VolumeType} volume.");
				}
			}
			if (SemiFunc.IsMultiplayer() && PhotonNetwork.CurrentRoom != null)
			{
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Hashtable val5 = new Hashtable();
				((Dictionary<object, object>)val5).Add((object)"MapItems_ids", (object)list2.ToArray());
				currentRoom.SetCustomProperties(val5, (Hashtable)null, (WebFlags)null);
			}
			Plugin.Log.LogInfo((object)$"Spawned {num4}/{num3} items on the map.");
		}

		private static void MarkOnMap(GameObject go)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: 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_00f7: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Instance.ShowOnMap.Value || (Object)(object)go == (Object)null)
			{
				return;
			}
			Color value = Plugin.Instance.MapColor.Value;
			MapCustom val = go.GetComponent<MapCustom>();
			if ((Object)(object)val == (Object)null)
			{
				if ((Object)(object)_fallbackSprite == (Object)null)
				{
					MapCustom[] array = Object.FindObjectsByType<MapCustom>((FindObjectsSortMode)0);
					foreach (MapCustom val2 in array)
					{
						if ((Object)(object)val2.sprite != (Object)null)
						{
							_fallbackSprite = val2.sprite;
							break;
						}
					}
				}
				if ((Object)(object)_fallbackSprite == (Object)null)
				{
					return;
				}
				val = go.AddComponent<MapCustom>();
				val.sprite = _fallbackSprite;
				val.autoAdd = true;
			}
			else if ((Object)(object)val.sprite != (Object)null)
			{
				_fallbackSprite = val.sprite;
			}
			val.color = value;
			MapCustomEntity val3 = MapEntity.Invoke(val);
			if ((Object)(object)val3 != (Object)null && (Object)(object)val3.spriteRenderer != (Object)null)
			{
				val3.spriteRenderer.color = value;
			}
		}

		private static IEnumerator ClientMarkLoop()
		{
			HashSet<int> done = new HashSet<int>();
			float time = 90f;
			WaitForSeconds delay = new WaitForSeconds(1f);
			while (time > 0f)
			{
				time -= 1f;
				yield return delay;
				if (PhotonNetwork.CurrentRoom == null || !((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)"MapItems_ids", out object value) || !(value is int[] array))
				{
					continue;
				}
				int[] array2 = array;
				foreach (int num in array2)
				{
					if (!done.Contains(num))
					{
						PhotonView val = PhotonView.Find(num);
						if (!((Object)(object)val == (Object)null))
						{
							done.Add(num);
							MarkOnMap(((Component)val).gameObject);
						}
					}
				}
			}
		}

		private static bool Fits(Item item, ValuableVolume volume)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected I4, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Invalid comparison between Unknown and I4
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Invalid comparison between Unknown and I4
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Invalid comparison between Unknown and I4
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Invalid comparison between Unknown and I4
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Invalid comparison between Unknown and I4
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Invalid comparison between Unknown and I4
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Invalid comparison between Unknown and I4
			Type volumeType = volume.VolumeType;
			itemVolume itemVolume = item.itemVolume;
			switch ((int)itemVolume)
			{
			case 0:
			case 4:
			case 6:
			case 7:
				if ((int)volumeType != 1)
				{
					return (int)volumeType == 2;
				}
				return true;
			case 1:
				if ((int)volumeType != 2)
				{
					return (int)volumeType == 3;
				}
				return true;
			case 2:
			case 8:
				if ((int)volumeType != 3)
				{
					return (int)volumeType == 4;
				}
				return true;
			case 3:
				return (int)volumeType == 4;
			case 5:
				if ((int)volumeType != 5)
				{
					return (int)volumeType == 6;
				}
				return true;
			default:
				return false;
			}
		}

		private static bool IsFree(ValuableVolume volume)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(((Component)volume).transform.position, 0.35f, -1, (QueryTriggerInteraction)1);
			for (int i = 0; i < array.Length; i++)
			{
				if ((Object)(object)((Component)array[i]).GetComponentInParent<PhysGrabObject>() != (Object)null)
				{
					return false;
				}
			}
			return true;
		}
	}
}