Decompiled source of YawOnMouse v2.1.0

YawOnMouse.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Rewired;
using Rewired.Data;
using Rewired.Utils.Libraries.TinyJson;
using UnityEngine;
using YawOnMouse.Blacklist;
using YawOnMouse.Helpers;

[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("YawOnMouse")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+40e90b669fbd0d69d7af571261dd1f8347f812c5")]
[assembly: AssemblyProduct("YawOnMouse")]
[assembly: AssemblyTitle("YawOnMouse")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 YawOnMouse
{
	public enum AxisPatchType
	{
		Roll = 0,
		Yaw = 2
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "YawOnMouse";

		public const string PLUGIN_NAME = "YawOnMouse";

		public const string PLUGIN_VERSION = "2.1.0";
	}
	[BepInPlugin("YawOnMouse", "YawOnMouse", "2.1.0")]
	public class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Logger;

		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<AxisPatchType> AxisPatchType;

		public static ConfigEntry<bool> UseCraftWhitelist;

		public WhitelistConfigManager WhitelistConfigManager;

		public static Plugin Instance;

		public const string ACTION_TOGGLE = "YawOnMouse::Toggle";

		public static bool RewiredReady;

		private bool _scanComplete;

		private void Awake()
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			WhitelistConfigManager = new WhitelistConfigManager();
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Config", "PlayerAxisControls_Patch", true, "Enable/Disable controller roll input patch");
			AxisPatchType = ((BaseUnityPlugin)this).Config.Bind<AxisPatchType>("Config", "AxisPatchType", YawOnMouse.AxisPatchType.Yaw, "What you want the patch to do on the x-axis (can only be changed before startup not at runtime.)");
			UseCraftWhitelist = ((BaseUnityPlugin)this).Config.Bind<bool>("Config", "UseCraftWhitelist", false, "When enabled the mod will only work on the aircraft specified in the whitelist");
			Logger.LogInfo((object)"Plugin YawOnMouse is loaded!");
			new Harmony("YawOnMouse").PatchAll();
		}

		private void Update()
		{
			if (RewiredReady)
			{
				PlayerHelper players = ReInput.players;
				Player val = ((players != null) ? players.GetPlayer(0) : null);
				if (val != null && val.GetButtonDown("YawOnMouse::Toggle"))
				{
					Enabled.Value = !Enabled.Value;
					((BaseUnityPlugin)this).Config.Save();
				}
			}
			if (!_scanComplete)
			{
				_scanComplete = WhitelistConfigManager.TryScanForAircraft();
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "YawOnMouse";

		public const string PLUGIN_NAME = "YawOnMouse";

		public const string PLUGIN_VERSION = "1.1.0";
	}
}
namespace YawOnMouse.Blacklist
{
	public class WhitelistConfig
	{
		public Dictionary<string, bool> Whitelist = new Dictionary<string, bool>();

		public bool Enabled(string name)
		{
			foreach (KeyValuePair<string, bool> item in Whitelist)
			{
				if (name.Contains(item.Key) && item.Value)
				{
					return true;
				}
			}
			return false;
		}

		public void Add(string name, bool enabled)
		{
			Whitelist.Add(name, enabled);
		}

		public void Remove(string name)
		{
			Whitelist.Remove(name);
		}
	}
	public class WhitelistConfigManager
	{
		private readonly string _whitelistConfigPath;

		public WhitelistConfig Config { get; private set; }

		public WhitelistConfigManager()
		{
			_whitelistConfigPath = Path.Combine(Paths.ConfigPath, "AircraftWhitelistConfig.json");
			LoadOrCreateConfig();
		}

		public bool TryScanForAircraft()
		{
			Aircraft[] array = Resources.FindObjectsOfTypeAll<Aircraft>();
			Plugin.Logger.LogInfo((object)$"Aircraft scan: found {((array != null) ? array.Length : 0)}");
			if (array == null || array.Length == 0)
			{
				return false;
			}
			bool flag = false;
			Aircraft[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				string text = ((Object)((Component)array2[i]).gameObject).name.Replace("(Clone)", "").Trim();
				if (!Config.Whitelist.ContainsKey(text))
				{
					Config.Whitelist.Add(text, value: false);
					Plugin.Logger.LogInfo((object)("Discovered " + text));
					flag = true;
				}
			}
			if (flag)
			{
				SaveConfig();
			}
			return true;
		}

		private void LoadOrCreateConfig()
		{
			if (!File.Exists(_whitelistConfigPath))
			{
				Config = GenerateDefaultConfig();
				SaveConfig();
				Plugin.Logger.LogInfo((object)("Config file " + _whitelistConfigPath + " has been created!"));
				return;
			}
			try
			{
				string text = File.ReadAllText(_whitelistConfigPath);
				Config = JsonParser.FromJson<WhitelistConfig>(text);
				Plugin.Logger.LogInfo((object)"permission config loaded.");
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)("failed to load permission config: " + ex.Message));
				Config = GenerateDefaultConfig();
				SaveConfig();
			}
		}

		private void SaveConfig()
		{
			try
			{
				string contents = JsonWriter.ToJson((object)Config);
				File.WriteAllText(_whitelistConfigPath, contents);
				Plugin.Logger.LogInfo((object)"permission config saved.");
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)("failed to save permission config: " + ex.Message));
			}
		}

		private WhitelistConfig GenerateDefaultConfig()
		{
			return new WhitelistConfig
			{
				Whitelist = new Dictionary<string, bool>()
			};
		}
	}
}
namespace YawOnMouse.Patches
{
	public class PilotPlayerStatePatches
	{
		[HarmonyPatch(typeof(PilotPlayerState), "PlayerAxisControls")]
		private static class PlayerAxisControls
		{
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator il)
			{
				List<CodeInstruction> list = new List<CodeInstruction>(instructions);
				if (Plugin.AxisPatchType.Value == AxisPatchType.Roll)
				{
					return instructions;
				}
				if (Plugin.AxisPatchType.Value == AxisPatchType.Yaw)
				{
					return Yaw(list, il);
				}
				return list;
			}

			private static IEnumerable<CodeInstruction> Yaw(List<CodeInstruction> codes, ILGenerator il)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Expected O, but got Unknown
				//IL_0128: Unknown result type (might be due to invalid IL or missing references)
				//IL_012f: Expected O, but got Unknown
				//IL_015e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0168: Expected O, but got Unknown
				//IL_0175: Unknown result type (might be due to invalid IL or missing references)
				//IL_017f: Expected O, but got Unknown
				//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b5: Expected O, but got Unknown
				//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Expected O, but got Unknown
				CodeMatcher val = new CodeMatcher((IEnumerable<CodeInstruction>)codes, (ILGenerator)null);
				MatchRollInputInstruction(val, useEnd: false);
				if (val.IsInvalid)
				{
					Plugin.Logger.LogError((object)"Could not find instructions for Yaw");
					return codes;
				}
				int pos = val.Pos;
				List<Label> collection = new List<Label>(codes[pos].labels);
				MatchRollInputInstruction(val, useEnd: true);
				int pos2 = val.Pos;
				List<CodeInstruction> range = codes.GetRange(pos, pos2 - pos + 1);
				List<CodeInstruction> list = new List<CodeInstruction>();
				foreach (CodeInstruction item in range)
				{
					if (item.opcode == OpCodes.Stfld && item.operand is FieldInfo fieldInfo && fieldInfo.Name == "rollInput")
					{
						list.Add(new CodeInstruction(OpCodes.Stfld, (object)AccessTools.Field(typeof(PilotPlayerState), "yawInput")));
					}
					else
					{
						list.Add(item.Clone());
					}
				}
				Label label = il.DefineLabel();
				Label label2 = il.DefineLabel();
				list[0].labels.Add(label);
				CodeInstruction val2 = new CodeInstruction(OpCodes.Nop, (object)null);
				val2.labels.Add(label2);
				List<CodeInstruction> list2 = new List<CodeInstruction>
				{
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(PatchHelper), "ShouldUseYaw", (Type[])null, (Type[])null)),
					new CodeInstruction(OpCodes.Brtrue_S, (object)label)
				};
				list2[0].labels.AddRange(collection);
				list2.AddRange(range);
				list2.Add(new CodeInstruction(OpCodes.Br_S, (object)label2));
				list2.AddRange(list);
				list2.Add(val2);
				codes.RemoveRange(pos, pos2 - pos + 1);
				codes.InsertRange(pos, list2);
				return codes;
			}

			private static void MatchRollInputInstruction(CodeMatcher codeMatcher, bool useEnd)
			{
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Expected O, but got Unknown
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Expected O, but got Unknown
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Expected O, but got Unknown
				//IL_0053: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Expected O, but got Unknown
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Expected O, but got Unknown
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0081: Expected O, but got Unknown
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0095: Expected O, but got Unknown
				//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a9: Expected O, but got Unknown
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d0: Expected O, but got Unknown
				codeMatcher.MatchForward(useEnd, (CodeMatch[])(object)new CodeMatch[9]
				{
					new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldsfld, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldfld, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldfld, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldc_R4, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Div, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Stfld, (object)AccessTools.Field(typeof(PilotPlayerState), "rollInput"), (string)null)
				});
			}
		}
	}
	[HarmonyPatch(typeof(InputManager_Base), "Awake")]
	internal static class RewiredAwakePatches
	{
		private const string TargetCategory = "flight";

		private const int ActionID = 850;

		[HarmonyPrefix]
		private static void Prefix(InputManager_Base __instance)
		{
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			try
			{
				UserData userData = __instance.userData;
				if (userData == null)
				{
					return;
				}
				IList field = GetField<IList>(userData, "actionCategories");
				IList field2 = GetField<IList>(userData, "actions");
				if (field == null || field2 == null)
				{
					return;
				}
				object obj = null;
				foreach (object item in field)
				{
					if (string.Equals(GetProp<string>(item, "name"), "flight", StringComparison.OrdinalIgnoreCase))
					{
						obj = item;
						break;
					}
				}
				if (obj == null)
				{
					Plugin.Logger.LogWarning((object)"[YawOnMouse] Flight category not found — toggle action will not be registered");
					return;
				}
				bool flag = false;
				int num = 850;
				foreach (object item2 in field2)
				{
					if (GetProp<string>(item2, "name") == "YawOnMouse::Toggle")
					{
						flag = true;
					}
					int prop = GetProp<int>(item2, "id");
					if (prop >= num)
					{
						num = prop + 1;
					}
				}
				if (!flag)
				{
					Type typeFromHandle = typeof(InputAction);
					InputAction val = (InputAction)Activator.CreateInstance(typeFromHandle, nonPublic: true);
					SetProp(typeFromHandle, val, "id", num);
					SetProp(typeFromHandle, val, "name", "YawOnMouse::Toggle");
					SetProp<InputActionType>(typeFromHandle, val, "type", (InputActionType)1);
					SetProp(typeFromHandle, val, "descriptiveName", "Yaw On Mouse Toggle");
					int prop2 = GetProp<int>(obj, "id");
					SetProp(typeFromHandle, val, "categoryId", prop2);
					SetField(typeFromHandle, val, "_userAssignable", value: true);
					field2.Add(val);
					object field3 = GetField<object>(userData, "actionCategoryMap");
					if (field3 != null)
					{
						AccessTools.Method(field3.GetType(), "AddAction", new Type[2]
						{
							typeof(int),
							typeof(int)
						}, (Type[])null)?.Invoke(field3, new object[2] { prop2, num });
					}
					Plugin.RewiredReady = true;
					Plugin.Logger.LogInfo((object)"[YawOnMouse] Registered toggle action in Flight category");
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[YawOnMouse] Action registration: {arg}");
			}
		}

		private static T GetProp<T>(object instance, string name)
		{
			return (T)(AccessTools.Property(instance.GetType(), name)?.GetValue(instance) ?? ((object)default(T)));
		}

		private static void SetProp<T>(Type type, object instance, string name, T value)
		{
			AccessTools.Property(type, name)?.SetValue(instance, value, null);
		}

		private static T GetField<T>(object instance, string name)
		{
			return (T)(AccessTools.Field(instance.GetType(), name)?.GetValue(instance) ?? ((object)default(T)));
		}

		private static void SetField<T>(Type type, object instance, string name, T value)
		{
			AccessTools.Field(type, name)?.SetValue(instance, value);
		}
	}
}
namespace YawOnMouse.Helpers
{
	public static class PatchHelper
	{
		public static bool ShouldUseYaw()
		{
			if (Plugin.Enabled.Value && Plugin.AxisPatchType.Value == AxisPatchType.Yaw)
			{
				return WhitelistHelper.IsWhitelisted();
			}
			return false;
		}
	}
	public static class WhitelistHelper
	{
		public static bool IsWhitelisted()
		{
			if (!Plugin.UseCraftWhitelist.Value)
			{
				return true;
			}
			Aircraft val = default(Aircraft);
			if (!GameManager.GetLocalAircraft(ref val))
			{
				return false;
			}
			string name = ((Object)((Component)val).gameObject).name;
			return Plugin.Instance.WhitelistConfigManager.Config.Enabled(name);
		}
	}
}