Decompiled source of ArcherArrowDrops v1.0.4

ArcherArrowDrops.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ConditionalConfigSync;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[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("ArcherArrowDrops")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.3.0")]
[assembly: AssemblyInformationalVersion("1.0.3")]
[assembly: AssemblyProduct("ArcherArrowDrops")]
[assembly: AssemblyTitle("ArcherArrowDrops")]
[assembly: AssemblyVersion("1.0.3.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 ArcherArrowDrops
{
	[BepInPlugin("com.dreich.archerarrowdrops", "ArcherArrowDrops", "1.0.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class ArcherArrowDropsPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.dreich.archerarrowdrops";

		public const string PluginName = "ArcherArrowDrops";

		public const string PluginVersion = "1.0.4";

		internal const string ConfigSyncGuid = "_shudnal.ConditionalConfigSync";

		private const int ReloadDelayMilliseconds = 500;

		private const int ReloadCooldownSeconds = 2;

		private const long ReloadDelayTicks = 5000000L;

		private const long ReloadCooldownTicks = 20000000L;

		private static readonly (string enemyName, string defaultDrops)[] defaultEnemyDrops = new(string, string)[4]
		{
			("Skeleton", "ArrowFlint,1,3,0.5"),
			("Draugr_Ranged", "ArrowIron,1,3,0.5"),
			("GoblinArcher", "ArrowNeedle,1,3,0.5"),
			("Charred_Archer", "ArrowCharred,1,3,0.5")
		};

		internal static readonly Dictionary<string, ConfigEntry<string>> dropSettingsByEnemy = new Dictionary<string, ConfigEntry<string>>();

		internal static ConfigEntry<string> customEnemyDropsSetting;

		internal static ManualLogSource logger;

		internal static bool configSyncAvailable;

		private FileSystemWatcher configWatcher;

		private volatile bool reloadPending;

		private long lastChangeTicks;

		private long ignoreChangesUntilTicks;

		private void Awake()
		{
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			logger = ((BaseUnityPlugin)this).Logger;
			configSyncAvailable = Chainloader.PluginInfos.ContainsKey("_shudnal.ConditionalConfigSync");
			if (configSyncAvailable)
			{
				ConfigSyncCompat.Initialize("com.dreich.archerarrowdrops", "ArcherArrowDrops", "1.0.4");
			}
			ConfigEntry<bool> entry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Lock Configuration", true, "If on, the configuration is locked and can be changed by server admins only. Requires ConditionalConfigSync.");
			if (configSyncAvailable)
			{
				ConfigSyncCompat.AddLockingConfigEntry(entry);
			}
			(string, string)[] array = defaultEnemyDrops;
			for (int i = 0; i < array.Length; i++)
			{
				(string, string) tuple = array[i];
				string item = tuple.Item1;
				string item2 = tuple.Item2;
				ConfigEntry<string> val = ((BaseUnityPlugin)this).Config.Bind<string>(item, "Drops", item2, "Format: ItemPrefab,Min amount dropped,Max amount dropped, Chance to drop. Separate multiple drops with a semicolon, leave empty for no drops.");
				if (configSyncAvailable)
				{
					ConfigSyncCompat.AddServerControlledEntry(val);
				}
				dropSettingsByEnemy[item] = val;
			}
			customEnemyDropsSetting = ((BaseUnityPlugin)this).Config.Bind<string>("Custom Enemies", "Drops", "", "Add drops for any other enemy. Format: EnemyPrefab:ItemPrefab,Min amount dropped,Max amount dropped,Chance to drop. Separate multiple drops with a semicolon and multiple enemies with a vertical bar. Example: Fenring:ArrowWood,1,2,0.25|Troll:ArrowFlint,2,4,1.0");
			if (configSyncAvailable)
			{
				ConfigSyncCompat.AddServerControlledEntry(customEnemyDropsSetting);
			}
			WatchConfigFile();
			new Harmony("com.dreich.archerarrowdrops").PatchAll();
		}

		private void WatchConfigFile()
		{
			string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath);
			string fileName = Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath);
			configWatcher = new FileSystemWatcher(directoryName, fileName)
			{
				NotifyFilter = (NotifyFilters.Size | NotifyFilters.LastWrite)
			};
			configWatcher.Changed += OnConfigFileChanged;
			configWatcher.EnableRaisingEvents = true;
		}

		private void OnConfigFileChanged(object sender, FileSystemEventArgs args)
		{
			long ticks = DateTime.UtcNow.Ticks;
			if (ticks >= Interlocked.Read(in ignoreChangesUntilTicks))
			{
				Interlocked.Exchange(ref lastChangeTicks, ticks);
				reloadPending = true;
			}
		}

		private void Update()
		{
			if (!reloadPending)
			{
				return;
			}
			long ticks = DateTime.UtcNow.Ticks;
			if (ticks - Interlocked.Read(in lastChangeTicks) <= 5000000)
			{
				return;
			}
			reloadPending = false;
			Interlocked.Exchange(ref ignoreChangesUntilTicks, ticks + 20000000);
			try
			{
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Config reload failed: " + ex.Message));
			}
		}
	}
	internal static class ConfigSyncCompat
	{
		private static object configSync;

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static void Initialize(string guid, string name, string version)
		{
			//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_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: 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_0027: Expected O, but got Unknown
			configSync = (object)new ConfigSync(guid)
			{
				DisplayName = name,
				CurrentVersion = version,
				MinimumRequiredVersion = version,
				ModRequired = true
			};
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static void AddLockingConfigEntry(ConfigEntry<bool> entry)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			((ConditionalConfigSync)(ConfigSync)configSync).AddLockingConfigEntry<bool>(entry);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static void AddServerControlledEntry(ConfigEntry<string> entry)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			((ConditionalConfigSync)(ConfigSync)configSync).AddConfigEntry<string>(entry, (ConfigSyncMode)0);
		}
	}
	[HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")]
	internal static class AddArrowDropsPatch
	{
		private const char DropSeparator = ';';

		private const char EnemySeparator = '|';

		private const char EnemyNameSeparator = ':';

		private const char FieldSeparator = ',';

		private const int ItemField = 0;

		private const int MinAmountField = 1;

		private const int MaxAmountField = 2;

		private const int ChanceField = 3;

		private const int FieldCount = 4;

		private static readonly ConditionalWeakTable<CharacterDrop, List<Drop>> arrowDropsByEnemy = new ConditionalWeakTable<CharacterDrop, List<Drop>>();

		private static void Prefix(CharacterDrop __instance)
		{
			string prefabName = Utils.GetPrefabName(((Component)__instance).gameObject);
			List<Drop> orCreateValue = arrowDropsByEnemy.GetOrCreateValue(__instance);
			foreach (Drop item in orCreateValue)
			{
				__instance.m_drops.Remove(item);
			}
			orCreateValue.Clear();
			if (IsUnarmedArcher(__instance))
			{
				return;
			}
			foreach (string dropEntry in GetDropEntries(prefabName))
			{
				Drop val = ParseDrop(prefabName, dropEntry);
				if (val != null)
				{
					__instance.m_drops.Add(val);
					orCreateValue.Add(val);
				}
			}
		}

		private static bool IsUnarmedArcher(CharacterDrop characterDrop)
		{
			Humanoid component = ((Component)characterDrop).GetComponent<Humanoid>();
			if ((Object)(object)component == (Object)null || !CanSpawnWithBow(component))
			{
				return false;
			}
			foreach (ItemData allItem in component.GetInventory().GetAllItems())
			{
				if (IsBow(allItem))
				{
					return false;
				}
			}
			return true;
		}

		private static bool CanSpawnWithBow(Humanoid humanoid)
		{
			if (ContainsBow(humanoid.m_defaultItems) || ContainsBow(humanoid.m_randomWeapon))
			{
				return true;
			}
			if (humanoid.m_randomSets != null)
			{
				ItemSet[] randomSets = humanoid.m_randomSets;
				for (int i = 0; i < randomSets.Length; i++)
				{
					if (ContainsBow(randomSets[i].m_items))
					{
						return true;
					}
				}
			}
			return false;
		}

		private static bool ContainsBow(GameObject[] itemPrefabs)
		{
			if (itemPrefabs == null)
			{
				return false;
			}
			foreach (GameObject val in itemPrefabs)
			{
				ItemDrop val2 = (((Object)(object)val == (Object)null) ? null : val.GetComponent<ItemDrop>());
				if ((Object)(object)val2 != (Object)null && IsBow(val2.m_itemData))
				{
					return true;
				}
			}
			return false;
		}

		private static bool IsBow(ItemData item)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Invalid comparison between Unknown and I4
			return (int)item.m_shared.m_itemType == 4;
		}

		private static Drop ParseDrop(string enemyName, string entry)
		{
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			string[] array = entry.Split(new char[1] { ',' });
			if (array.Length != 4 || !int.TryParse(array[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || !int.TryParse(array[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2) || !float.TryParse(array[3], NumberStyles.Float, CultureInfo.InvariantCulture, out var result3))
			{
				ArcherArrowDropsPlugin.logger.LogWarning((object)("Invalid drop for " + enemyName + ": " + entry));
				return null;
			}
			string text = array[0].Trim();
			GameObject prefab = ZNetScene.instance.GetPrefab(text);
			if ((Object)(object)prefab == (Object)null)
			{
				ArcherArrowDropsPlugin.logger.LogWarning((object)("Unknown item for " + enemyName + ": " + text));
				return null;
			}
			return new Drop
			{
				m_prefab = prefab,
				m_amountMin = result,
				m_amountMax = Mathf.Max(result, result2),
				m_chance = Mathf.Clamp01(result3)
			};
		}

		private static IEnumerable<string> GetDropEntries(string enemyName)
		{
			string[] array;
			if (ArcherArrowDropsPlugin.dropSettingsByEnemy.TryGetValue(enemyName, out var value))
			{
				array = SplitDrops(value.Value);
				for (int i = 0; i < array.Length; i++)
				{
					yield return array[i];
				}
			}
			string value2 = ArcherArrowDropsPlugin.customEnemyDropsSetting.Value;
			array = value2.Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string text in array)
			{
				int num = text.IndexOf(':');
				if (num >= 0 && !(text.Substring(0, num).Trim() != enemyName))
				{
					string[] array2 = SplitDrops(text.Substring(num + 1));
					for (int j = 0; j < array2.Length; j++)
					{
						yield return array2[j];
					}
				}
			}
		}

		private static string[] SplitDrops(string value)
		{
			return value.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
		}
	}
}