Decompiled source of ControllerSupport v1.0.2

ControllerSupport.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.Win32.SafeHandles;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: AssemblyMetadata("Notice", "Copyright (c) casualexpie. All rights reserved. Do NOT decompile, disassemble, or reverse-engineer this assembly. Report bug symptoms on the Nexus Bugs page; do not post decompiled or reconstructed source. Reverse-engineering this DLL is not authorized.")]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ControllerSupport;

public enum Btn
{
	A,
	B,
	X,
	Y,
	LB,
	RB,
	LT,
	RT,
	Back,
	Start,
	L3,
	R3,
	DUp,
	DDown,
	DLeft,
	DRight,
	Touch,
	Touch2,
	PS,
	Mute,
	Count
}
public enum PadKind
{
	None,
	Xbox,
	DualSense,
	DualShock4
}
[BepInPlugin("controllersupport", "Controller Support", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	public const string Version = "1.0.0";

	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> Enabled;

	internal static ConfigEntry<bool> ShowMessages;

	internal static ConfigEntry<bool> PauseOnDisconnect;

	internal static ConfigEntry<bool> BlockUINavigation;

	internal static ConfigEntry<float> CursorSpeed;

	internal static ConfigEntry<float> CursorCurve;

	internal static ConfigEntry<float> PreciseSpeed;

	internal static ConfigEntry<bool> InvertLookY;

	internal static ConfigEntry<float> Deadzone;

	internal static ConfigEntry<float> MoveThreshold;

	internal static ConfigEntry<float> TriggerThreshold;

	internal static ConfigEntry<bool> MenuSelect;

	internal static ConfigEntry<bool> TouchpadMouse;

	internal static ConfigEntry<float> TouchpadSpeed;

	internal static ConfigEntry<bool> TapToClick;

	internal static ConfigEntry<bool> TwoFingerScroll;

	internal static ConfigEntry<bool> InvertScroll;

	internal static ConfigEntry<bool> AdaptiveTriggers;

	internal static ConfigEntry<float> TriggerStrength;

	internal static ConfigEntry<bool> GunTriggers;

	internal static ConfigEntry<bool> HealthLightbar;

	internal static ConfigEntry<bool> CharacterLightbar;

	internal static ConfigEntry<bool> EnergyLights;

	internal static ConfigEntry<bool> Rumble;

	internal static ConfigEntry<float> RumbleStrength;

	internal static ConfigEntry<bool> Heartbeat;

	internal static ConfigEntry<bool> SpeakerAlert;

	internal static ConfigEntry<float> SpeakerVolume;

	internal static ConfigEntry<float> SpeakerDelay;

	internal static ConfigEntry<string>[] Map = new ConfigEntry<string>[20];

	internal static readonly string[] ActionList = new string[27]
	{
		"jump", "throw", "iteminteract", "attack", "switchhands", "toggleinventory", "craft", "woundview", "pause", "ragdoll",
		"bark", "expanddesc", "altview", "favourite", "customizeitem", "speed1", "speed2", "speed3", "speedcycle", "marksmanrack",
		"marksmanunload", "console", "leftclick", "rightclick", "middleclick", "precise", "none"
	};

	private void Awake()
	{
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Expected O, but got Unknown
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Expected O, but got Unknown
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Expected O, but got Unknown
		//IL_0194: Unknown result type (might be due to invalid IL or missing references)
		//IL_019e: Expected O, but got Unknown
		//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dc: Expected O, but got Unknown
		//IL_0210: Unknown result type (might be due to invalid IL or missing references)
		//IL_021a: Expected O, but got Unknown
		//IL_028e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0298: Expected O, but got Unknown
		//IL_036c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0376: Expected O, but got Unknown
		//IL_042a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0434: Expected O, but got Unknown
		//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b2: Expected O, but got Unknown
		//IL_04e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_04f0: Expected O, but got Unknown
		//IL_06da: Unknown result type (might be due to invalid IL or missing references)
		//IL_06e1: Expected O, but got Unknown
		//IL_06fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0708: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Turn controller support on or off.");
		ShowMessages = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShowMessages", true, "Show a banner with the connected controller on the title screen, and when a controller connects or disconnects.");
		PauseOnDisconnect = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "PauseOnDisconnect", true, "Pause the game if your controller disconnects or its battery dies during a run.");
		BlockUINavigation = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "BlockUINavigation", true, "Stop Unity's built-in menu navigation from also reacting to the controller (prevents a face button re-pressing the last clicked menu button).");
		CursorSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Cursor", "Speed", 1.3f, new ConfigDescription("How fast the right stick moves the cursor, in screen heights per second at full tilt.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 5f), new object[0]));
		CursorCurve = ((BaseUnityPlugin)this).Config.Bind<float>("Cursor", "Curve", 2f, new ConfigDescription("Response curve of the right stick. 1 = linear, higher = finer control near the center.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 4f), new object[0]));
		PreciseSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Cursor", "PreciseMultiplier", 0.3f, new ConfigDescription("Cursor speed multiplier (stick and touchpad) while the 'precise' button is held.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1f), new object[0]));
		InvertLookY = ((BaseUnityPlugin)this).Config.Bind<bool>("Cursor", "InvertY", false, "Invert the right stick's up/down.");
		Deadzone = ((BaseUnityPlugin)this).Config.Bind<float>("Sticks", "Deadzone", 0.2f, new ConfigDescription("Stick deadzone (0-1).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.6f), new object[0]));
		MoveThreshold = ((BaseUnityPlugin)this).Config.Bind<float>("Sticks", "MoveThreshold", 0.45f, new ConfigDescription("How far the left stick must be pushed to walk, climb or crouch (0-1).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 0.95f), new object[0]));
		TriggerThreshold = ((BaseUnityPlugin)this).Config.Bind<float>("Sticks", "TriggerThreshold", 0.35f, new ConfigDescription("How far a trigger must be pulled to count as pressed (0-1).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 0.95f), new object[0]));
		MenuSelect = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "MenuSelect", true, "A / Cross clicks where the cursor is on the title screen, menus (pause, settings, character select), tutorial course select and text boxes, crafting, trading and item customizing. Otherwise it does its normal action.");
		TouchpadMouse = ((BaseUnityPlugin)this).Config.Bind<bool>("Touchpad", "Enabled", true, "DualSense / DualShock 4 touchpad works like a laptop trackpad: slide one finger to move the cursor, press the pad to click.");
		TouchpadSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Touchpad", "Speed", 1.2f, new ConfigDescription("Touchpad cursor speed. 1 = sliding across the whole pad moves the cursor across the whole screen.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 5f), new object[0]));
		TapToClick = ((BaseUnityPlugin)this).Config.Bind<bool>("Touchpad", "TapToClick", true, "A quick one-finger tap on the touchpad clicks.");
		TwoFingerScroll = ((BaseUnityPlugin)this).Config.Bind<bool>("Touchpad", "TwoFingerScroll", true, "Slide two fingers up or down on the touchpad to scroll.");
		InvertScroll = ((BaseUnityPlugin)this).Config.Bind<bool>("Touchpad", "InvertScroll", false, "Flip the two-finger scroll direction.");
		AdaptiveTriggers = ((BaseUnityPlugin)this).Config.Bind<bool>("DualSense", "AdaptiveTriggers", true, "Adaptive trigger effects. The triggers stay loose for normal play (mining, menus, keypads); they only react to guns and power tools, and lock up while you're knocked out or asleep.");
		GunTriggers = ((BaseUnityPlugin)this).Config.Bind<bool>("DualSense", "GunTriggers", true, "Guns change R2: each gun has its own trigger break (pistol light, rifle heavier, shotgun heavy), the trigger kicks back on every shot, automatics buzz at their fire rate, empty guns feel dead and the safety locks the trigger. The heavy drill, plasma cutter and mini laser drill make R2 vibrate while they run.");
		TriggerStrength = ((BaseUnityPlugin)this).Config.Bind<float>("DualSense", "TriggerStrength", 1f, new ConfigDescription("Adaptive trigger strength multiplier.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 2f), new object[0]));
		HealthLightbar = ((BaseUnityPlugin)this).Config.Bind<bool>("Lightbar", "HealthLightbar", true, "In a run, the lightbar shows your condition: green healthy, yellow hurt, red badly hurt, dim blue asleep. It flashes red fast while dying (in sync with the health panel alert), fades bright yellow while bleeding, flashes green slowly when badly poisoned, does a rainbow with two or more problems at once, and fades to dark red when you die.");
		CharacterLightbar = ((BaseUnityPlugin)this).Config.Bind<bool>("Lightbar", "CharacterLightbar", true, "On the menus, the lightbar takes the color of the character you hover or pick: orange SAW-01, white SAW-03, pale plum Dune.");
		EnergyLights = ((BaseUnityPlugin)this).Config.Bind<bool>("DualSense", "EnergyLights", true, "The five little player lights under the touchpad show your energy (tiredness).");
		Rumble = ((BaseUnityPlugin)this).Config.Bind<bool>("Rumble", "Enabled", true, "Rumble when you get hurt.");
		RumbleStrength = ((BaseUnityPlugin)this).Config.Bind<float>("Rumble", "Strength", 1f, new ConfigDescription("Rumble strength multiplier.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), new object[0]));
		Heartbeat = ((BaseUnityPlugin)this).Config.Bind<bool>("Rumble", "HeartbeatWhenDying", true, "Feel a heartbeat in the controller while you're dying.");
		SpeakerAlert = ((BaseUnityPlugin)this).Config.Bind<bool>("Speaker", "HealthPanelSounds", true, "DualSense over USB: the health panel sounds also play from the controller speaker, in sync with the game: the open sound, the heartbeat while it's open, and the critical alert.");
		SpeakerVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Speaker", "Volume", 1f, new ConfigDescription("Controller speaker volume.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
		SpeakerDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Speaker", "Delay", 0f, new ConfigDescription("Seconds to hold back the controller speaker so it lines up with your main audio. Raise it if the controller plays before the game (common with Bluetooth speakers or headphones).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), new object[0]));
		string text = "Action for this button. One of: " + string.Join(", ", ActionList) + ". Game actions press whatever key you set for them in the game's controls settings.";
		string[] array = new string[20]
		{
			"jump", "throw", "switchhands", "toggleinventory", "expanddesc", "precise", "iteminteract", "leftclick", "craft", "pause",
			"bark", "rightclick", "woundview", "ragdoll", "speed1", "speedcycle", "leftclick", "rightclick", "none", "none"
		};
		string[] array2 = new string[20]
		{
			"A_Cross", "B_Circle", "X_Square", "Y_Triangle", "LB_L1", "RB_R1", "LT_L2", "RT_R2", "View_Create", "Menu_Options",
			"L3", "R3", "DpadUp", "DpadDown", "DpadLeft", "DpadRight", "TouchpadPress", "TouchpadPressTwoFingers", "PSButton", "MuteButton"
		};
		for (int i = 0; i < 20; i++)
		{
			Map[i] = ((BaseUnityPlugin)this).Config.Bind<string>("Buttons", array2[i], array[i], text);
		}
		GameObject val = new GameObject("ControllerSupportRunner");
		((Object)val).hideFlags = (HideFlags)61;
		Object.DontDestroyOnLoad((Object)(object)val);
		val.AddComponent<Runner>();
		int num = ControllerTab.Patch(new Harmony("controllersupport"));
		Log.LogInfo((object)("Controller Support 1.0.0 loaded (" + num + "/4 hooks). XInput: " + XInput.Describe() + ". Game version " + Application.version + "."));
	}
}
internal class PadState
{
	public bool[] Down = new bool[20];

	public float LX;

	public float LY;

	public float RX;

	public float RY;

	public float LT;

	public float RT;

	public bool HasTouch;

	public bool T0;

	public bool T1;

	public int T0X;

	public int T0Y;

	public int T1X;

	public int T1Y;

	public int TouchH = 1080;

	public int Battery = -1;

	public void Clear()
	{
		for (int i = 0; i < Down.Length; i++)
		{
			Down[i] = false;
		}
		LX = (LY = (RX = (RY = (LT = (RT = 0f)))));
		HasTouch = (T0 = (T1 = false));
	}
}
internal class Feedback
{
	public float Low;

	public float High;

	public byte R;

	public byte G;

	public byte B;

	public byte Leds;

	public bool Speaker;

	public byte[] RightTrig = new byte[11];

	public byte[] LeftTrig = new byte[11];

	public void Clear()
	{
		Low = (High = 0f);
		R = (G = (B = 0));
		Leds = 0;
		Trig.Off(RightTrig);
		Trig.Off(LeftTrig);
	}

	public byte[] Signature()
	{
		byte[] array = new byte[29];
		array[28] = (byte)(Speaker ? 1u : 0u);
		array[0] = (byte)(Mathf.Clamp01(Low) * 255f);
		array[1] = (byte)(Mathf.Clamp01(High) * 255f);
		array[2] = R;
		array[3] = G;
		array[4] = B;
		array[5] = Leds;
		Buffer.BlockCopy(RightTrig, 0, array, 6, 11);
		Buffer.BlockCopy(LeftTrig, 0, array, 17, 11);
		return array;
	}
}
internal static class Trig
{
	public static void Off(byte[] t)
	{
		Array.Clear(t, 0, t.Length);
		t[0] = 5;
	}

	public static void Resist(byte[] t, int start, int strength)
	{
		Array.Clear(t, 0, t.Length);
		t[0] = 1;
		t[1] = (byte)Mathf.Clamp(start, 0, 255);
		t[2] = (byte)Mathf.Clamp(strength, 0, 255);
	}

	public static void Vibrate(byte[] t, int frequency, int amplitude, int start)
	{
		Array.Clear(t, 0, t.Length);
		t[0] = 6;
		t[1] = (byte)Mathf.Clamp(frequency, 1, 255);
		t[2] = (byte)Mathf.Clamp(amplitude, 0, 255);
		t[3] = (byte)Mathf.Clamp(start, 0, 255);
	}

	public static void Weapon(byte[] t, int start, int end, int strength)
	{
		Array.Clear(t, 0, t.Length);
		t[0] = 2;
		t[1] = (byte)Mathf.Clamp(start, 0, 255);
		t[2] = (byte)Mathf.Clamp(end, 0, 255);
		t[3] = (byte)Mathf.Clamp(strength, 0, 255);
	}
}
internal interface IPad
{
	string Name { get; }

	PadKind Kind { get; }

	bool Poll(PadState s);

	void Apply(Feedback f);

	void Close();
}
internal static class XInput
{
	public struct Gamepad
	{
		public ushort Buttons;

		public byte LeftTrigger;

		public byte RightTrigger;

		public short LX;

		public short LY;

		public short RX;

		public short RY;
	}

	public struct State
	{
		public uint Packet;

		public Gamepad Pad;
	}

	public struct Vibration
	{
		public ushort Left;

		public ushort Right;
	}

	private static class X14
	{
		[DllImport("xinput1_4.dll", EntryPoint = "XInputGetState")]
		public static extern uint Get(uint i, out State s);

		[DllImport("xinput1_4.dll", EntryPoint = "XInputSetState")]
		public static extern uint Set(uint i, ref Vibration v);
	}

	private static class X910
	{
		[DllImport("xinput9_1_0.dll", EntryPoint = "XInputGetState")]
		public static extern uint Get(uint i, out State s);

		[DllImport("xinput9_1_0.dll", EntryPoint = "XInputSetState")]
		public static extern uint Set(uint i, ref Vibration v);
	}

	private static int which = -1;

	private static void Pick()
	{
		if (which < 0)
		{
			State s;
			try
			{
				X14.Get(0u, out s);
				which = 1;
				return;
			}
			catch (Exception)
			{
			}
			try
			{
				X910.Get(0u, out s);
				which = 2;
				return;
			}
			catch (Exception)
			{
			}
			which = 0;
		}
	}

	public static string Describe()
	{
		Pick();
		if (which != 1)
		{
			if (which != 2)
			{
				return "not available";
			}
			return "xinput9_1_0";
		}
		return "xinput1_4";
	}

	public static bool Get(int i, out State s)
	{
		Pick();
		s = default(State);
		try
		{
			if (which == 1)
			{
				return X14.Get((uint)i, out s) == 0;
			}
			if (which == 2)
			{
				return X910.Get((uint)i, out s) == 0;
			}
		}
		catch (Exception)
		{
			which = 0;
		}
		return false;
	}

	public static void Set(int i, float low, float high)
	{
		Vibration v = new Vibration
		{
			Left = (ushort)(Mathf.Clamp01(low) * 65535f),
			Right = (ushort)(Mathf.Clamp01(high) * 65535f)
		};
		try
		{
			if (which == 1)
			{
				X14.Set((uint)i, ref v);
			}
			else if (which == 2)
			{
				X910.Set((uint)i, ref v);
			}
		}
		catch (Exception)
		{
		}
	}
}
internal class XboxPad : IPad
{
	private readonly int index;

	private int lastLow = -1;

	private int lastHigh = -1;

	public string Name => "Xbox controller";

	public PadKind Kind => PadKind.Xbox;

	public XboxPad(int i)
	{
		index = i;
	}

	public bool Poll(PadState s)
	{
		if (!XInput.Get(index, out var s2))
		{
			return false;
		}
		ushort buttons = s2.Pad.Buttons;
		s.Down[12] = (buttons & 1) != 0;
		s.Down[13] = (buttons & 2) != 0;
		s.Down[14] = (buttons & 4) != 0;
		s.Down[15] = (buttons & 8) != 0;
		s.Down[9] = (buttons & 0x10) != 0;
		s.Down[8] = (buttons & 0x20) != 0;
		s.Down[10] = (buttons & 0x40) != 0;
		s.Down[11] = (buttons & 0x80) != 0;
		s.Down[4] = (buttons & 0x100) != 0;
		s.Down[5] = (buttons & 0x200) != 0;
		s.Down[0] = (buttons & 0x1000) != 0;
		s.Down[1] = (buttons & 0x2000) != 0;
		s.Down[2] = (buttons & 0x4000) != 0;
		s.Down[3] = (buttons & 0x8000) != 0;
		s.LX = (float)s2.Pad.LX / 32767f;
		s.LY = (float)s2.Pad.LY / 32767f;
		s.RX = (float)s2.Pad.RX / 32767f;
		s.RY = (float)s2.Pad.RY / 32767f;
		s.LT = (float)(int)s2.Pad.LeftTrigger / 255f;
		s.RT = (float)(int)s2.Pad.RightTrigger / 255f;
		return true;
	}

	public void Apply(Feedback f)
	{
		int num = (int)(Mathf.Clamp01(f.Low) * 255f);
		int num2 = (int)(Mathf.Clamp01(f.High) * 255f);
		if (num != lastLow || num2 != lastHigh)
		{
			lastLow = num;
			lastHigh = num2;
			XInput.Set(index, (float)num / 255f, (float)num2 / 255f);
		}
	}

	public void Close()
	{
		XInput.Set(index, 0f, 0f);
	}
}
internal static class Hid
{
	public struct Attributes
	{
		public int Size;

		public ushort VendorID;

		public ushort ProductID;

		public ushort Version;
	}

	public struct Caps
	{
		public ushort Usage;

		public ushort UsagePage;

		public ushort InputReportByteLength;

		public ushort OutputReportByteLength;

		public ushort FeatureReportByteLength;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 27)]
		public ushort[] Rest;
	}

	public struct InterfaceData
	{
		public int Size;

		public Guid Class;

		public int Flags;

		public IntPtr Reserved;
	}

	public const uint Read = 2147483648u;

	public const uint Write = 1073741824u;

	public const uint Share = 3u;

	public const uint OpenExisting = 3u;

	private static uint[] table;

	[DllImport("hid.dll")]
	public static extern void HidD_GetHidGuid(out Guid g);

	[DllImport("hid.dll")]
	public static extern bool HidD_GetAttributes(SafeFileHandle h, ref Attributes a);

	[DllImport("hid.dll")]
	public static extern bool HidD_GetPreparsedData(SafeFileHandle h, out IntPtr p);

	[DllImport("hid.dll")]
	public static extern bool HidD_FreePreparsedData(IntPtr p);

	[DllImport("hid.dll")]
	public static extern int HidP_GetCaps(IntPtr p, out Caps c);

	[DllImport("hid.dll")]
	public static extern bool HidD_GetFeature(SafeFileHandle h, byte[] buf, int len);

	[DllImport("setupapi.dll", SetLastError = true)]
	public static extern IntPtr SetupDiGetClassDevs(ref Guid g, IntPtr enumerator, IntPtr hwnd, uint flags);

	[DllImport("setupapi.dll", SetLastError = true)]
	public static extern bool SetupDiEnumDeviceInterfaces(IntPtr set, IntPtr info, ref Guid g, uint index, ref InterfaceData d);

	[DllImport("setupapi.dll", EntryPoint = "SetupDiGetDeviceInterfaceDetailW", SetLastError = true)]
	public static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr set, ref InterfaceData d, IntPtr detail, int size, out int required, IntPtr info);

	[DllImport("setupapi.dll")]
	public static extern bool SetupDiDestroyDeviceInfoList(IntPtr set);

	[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", SetLastError = true)]
	public static extern SafeFileHandle CreateFile(string path, uint access, uint share, IntPtr sec, uint disp, uint flags, IntPtr template);

	[DllImport("kernel32.dll", SetLastError = true)]
	public static extern bool ReadFile(SafeFileHandle h, byte[] buf, int len, out int read, IntPtr ov);

	[DllImport("kernel32.dll", SetLastError = true)]
	public static extern bool WriteFile(SafeFileHandle h, byte[] buf, int len, out int written, IntPtr ov);

	[DllImport("kernel32.dll")]
	public static extern bool CancelIoEx(SafeFileHandle h, IntPtr ov);

	public static List<string> Paths()
	{
		List<string> list = new List<string>();
		HidD_GetHidGuid(out var g);
		IntPtr intPtr = SetupDiGetClassDevs(ref g, IntPtr.Zero, IntPtr.Zero, 18u);
		if (intPtr == IntPtr.Zero || intPtr == new IntPtr(-1))
		{
			return list;
		}
		try
		{
			for (uint num = 0u; num < 256; num++)
			{
				InterfaceData d = new InterfaceData
				{
					Size = Marshal.SizeOf(typeof(InterfaceData))
				};
				if (!SetupDiEnumDeviceInterfaces(intPtr, IntPtr.Zero, ref g, num, ref d))
				{
					break;
				}
				SetupDiGetDeviceInterfaceDetail(intPtr, ref d, IntPtr.Zero, 0, out var required, IntPtr.Zero);
				if (required <= 0)
				{
					continue;
				}
				IntPtr intPtr2 = Marshal.AllocHGlobal(required);
				try
				{
					Marshal.WriteInt32(intPtr2, (IntPtr.Size == 8) ? 8 : 6);
					if (SetupDiGetDeviceInterfaceDetail(intPtr, ref d, intPtr2, required, out required, IntPtr.Zero))
					{
						list.Add(Marshal.PtrToStringUni(new IntPtr(intPtr2.ToInt64() + 4)));
					}
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr2);
				}
			}
		}
		finally
		{
			SetupDiDestroyDeviceInfoList(intPtr);
		}
		return list;
	}

	public static bool Identify(string path, out ushort vid, out ushort pid)
	{
		vid = (pid = 0);
		using SafeFileHandle safeFileHandle = CreateFile(path, 0u, 3u, IntPtr.Zero, 3u, 0u, IntPtr.Zero);
		if (safeFileHandle.IsInvalid)
		{
			return false;
		}
		Attributes a = new Attributes
		{
			Size = Marshal.SizeOf(typeof(Attributes))
		};
		if (!HidD_GetAttributes(safeFileHandle, ref a))
		{
			return false;
		}
		vid = a.VendorID;
		pid = a.ProductID;
		return true;
	}

	public static bool GetCaps(SafeFileHandle h, out Caps c)
	{
		c = default(Caps);
		if (!HidD_GetPreparsedData(h, out var p))
		{
			return false;
		}
		try
		{
			return HidP_GetCaps(p, out c) == 1114112;
		}
		finally
		{
			HidD_FreePreparsedData(p);
		}
	}

	public static uint Crc(byte seed, byte[] data, int len)
	{
		if (table == null)
		{
			uint[] array = new uint[256];
			for (uint num = 0u; num < 256; num++)
			{
				uint num2 = num;
				for (int i = 0; i < 8; i++)
				{
					num2 = (((num2 & 1) != 0) ? (0xEDB88320u ^ (num2 >> 1)) : (num2 >> 1));
				}
				array[num] = num2;
			}
			table = array;
		}
		uint num3 = uint.MaxValue;
		num3 = table[(num3 ^ seed) & 0xFF] ^ (num3 >> 8);
		for (int j = 0; j < len; j++)
		{
			num3 = table[(num3 ^ data[j]) & 0xFF] ^ (num3 >> 8);
		}
		return ~num3;
	}

	public static void PutCrc(byte[] b)
	{
		uint num = Crc(162, b, 74);
		b[74] = (byte)num;
		b[75] = (byte)(num >> 8);
		b[76] = (byte)(num >> 16);
		b[77] = (byte)(num >> 24);
	}
}
internal abstract class HidPad : IPad
{
	protected SafeFileHandle rh;

	protected SafeFileHandle wh;

	protected bool bt;

	protected int inLen;

	protected int outLen;

	protected int featLen;

	protected volatile bool alive = true;

	private Thread thread;

	private readonly object gate = new object();

	private byte[] latest;

	private int latestLen;

	private byte[] work;

	private byte[] lastSig;

	private float lastSend = -10f;

	private volatile int lastTick;

	public abstract string Name { get; }

	public abstract PadKind Kind { get; }

	protected abstract void Parse(PadState s, byte[] d, int n);

	protected abstract void Send(Feedback f, bool release);

	protected abstract void Prepare();

	public static IPad Open()
	{
		List<string> list;
		try
		{
			list = Hid.Paths();
		}
		catch (Exception)
		{
			return null;
		}
		foreach (string item in list)
		{
			ushort vid;
			ushort pid;
			try
			{
				if (!Hid.Identify(item, out vid, out pid))
				{
					continue;
				}
			}
			catch (Exception)
			{
				continue;
			}
			if (vid != 1356)
			{
				continue;
			}
			HidPad hidPad = null;
			switch (pid)
			{
			case 3302:
			case 3570:
				hidPad = new DualSensePad(pid == 3570);
				break;
			case 1476:
			case 2508:
			case 2976:
				hidPad = new Ds4Pad();
				break;
			}
			if (hidPad == null)
			{
				continue;
			}
			try
			{
				if (hidPad.Init(item))
				{
					return hidPad;
				}
			}
			catch (Exception)
			{
			}
		}
		return null;
	}

	private bool Init(string path)
	{
		rh = Hid.CreateFile(path, 3221225472u, 3u, IntPtr.Zero, 3u, 0u, IntPtr.Zero);
		if (rh.IsInvalid)
		{
			return false;
		}
		wh = Hid.CreateFile(path, 3221225472u, 3u, IntPtr.Zero, 3u, 0u, IntPtr.Zero);
		if (wh.IsInvalid || !Hid.GetCaps(rh, out var c) || c.InputReportByteLength == 0)
		{
			rh.Dispose();
			wh.Dispose();
			return false;
		}
		inLen = c.InputReportByteLength;
		outLen = c.OutputReportByteLength;
		featLen = c.FeatureReportByteLength;
		bt = inLen > 64;
		Prepare();
		latest = new byte[Math.Max(inLen, 80)];
		work = new byte[latest.Length];
		thread = new Thread(ReadLoop);
		thread.IsBackground = true;
		thread.Name = "Controller Support reader";
		thread.Start();
		return true;
	}

	protected void Feature(byte id)
	{
		if (featLen <= 0)
		{
			return;
		}
		try
		{
			byte[] array = new byte[featLen];
			array[0] = id;
			Hid.HidD_GetFeature(wh, array, array.Length);
		}
		catch (Exception)
		{
		}
	}

	private void ReadLoop()
	{
		byte[] array = new byte[Math.Max(inLen, 80)];
		while (alive)
		{
			bool flag;
			int read;
			try
			{
				flag = Hid.ReadFile(rh, array, inLen, out read, IntPtr.Zero);
			}
			catch (Exception)
			{
				flag = false;
				read = 0;
			}
			if (!flag || read <= 0)
			{
				alive = false;
				break;
			}
			lastTick = Environment.TickCount;
			lock (gate)
			{
				int count = Math.Min(read, latest.Length);
				Buffer.BlockCopy(array, 0, latest, 0, count);
				latestLen = count;
			}
		}
	}

	public bool Poll(PadState s)
	{
		if (!alive)
		{
			return false;
		}
		int num;
		lock (gate)
		{
			num = latestLen;
			Buffer.BlockCopy(latest, 0, work, 0, latest.Length);
		}
		if (num > 0 && Environment.TickCount - lastTick > 1500)
		{
			alive = false;
			return false;
		}
		if (num > 0)
		{
			Parse(s, work, num);
		}
		return true;
	}

	public void Apply(Feedback f)
	{
		if (alive)
		{
			byte[] a = f.Signature();
			float unscaledTime = Time.unscaledTime;
			bool flag = lastSig != null && Same(a, lastSig);
			if ((!flag || !(unscaledTime - lastSend < 2f)) && (flag || !(unscaledTime - lastSend < 1f / 60f)))
			{
				lastSig = a;
				lastSend = unscaledTime;
				Send(f, release: false);
			}
		}
	}

	private static bool Same(byte[] a, byte[] b)
	{
		for (int i = 0; i < a.Length; i++)
		{
			if (a[i] != b[i])
			{
				return false;
			}
		}
		return true;
	}

	protected void Write(byte[] b)
	{
		try
		{
			if (!Hid.WriteFile(wh, b, b.Length, out var _, IntPtr.Zero))
			{
				alive = false;
			}
		}
		catch (Exception)
		{
			alive = false;
		}
	}

	protected static float Axis(byte v)
	{
		return Mathf.Clamp(((float)(int)v - 128f) / 127f, -1f, 1f);
	}

	protected static void Hat(PadState s, int hat)
	{
		s.Down[12] = hat == 0 || hat == 1 || hat == 7;
		s.Down[15] = hat == 1 || hat == 2 || hat == 3;
		s.Down[13] = hat == 3 || hat == 4 || hat == 5;
		s.Down[14] = hat == 5 || hat == 6 || hat == 7;
	}

	protected static void Buttons(PadState s, byte b0, byte b1, byte b2)
	{
		Hat(s, b0 & 0xF);
		s.Down[2] = (b0 & 0x10) != 0;
		s.Down[0] = (b0 & 0x20) != 0;
		s.Down[1] = (b0 & 0x40) != 0;
		s.Down[3] = (b0 & 0x80) != 0;
		s.Down[4] = (b1 & 1) != 0;
		s.Down[5] = (b1 & 2) != 0;
		s.Down[8] = (b1 & 0x10) != 0;
		s.Down[9] = (b1 & 0x20) != 0;
		s.Down[10] = (b1 & 0x40) != 0;
		s.Down[11] = (b1 & 0x80) != 0;
		s.Down[18] = (b2 & 1) != 0;
		s.Down[16] = (b2 & 2) != 0;
		s.Down[19] = (b2 & 4) != 0;
	}

	protected static void Touch(PadState s, byte[] d, int p, int h)
	{
		s.HasTouch = true;
		s.TouchH = h;
		s.T0 = (d[p] & 0x80) == 0;
		s.T0X = d[p + 1] | ((d[p + 2] & 0xF) << 8);
		s.T0Y = (d[p + 2] >> 4) | (d[p + 3] << 4);
		p += 4;
		s.T1 = (d[p] & 0x80) == 0;
		s.T1X = d[p + 1] | ((d[p + 2] & 0xF) << 8);
		s.T1Y = (d[p + 2] >> 4) | (d[p + 3] << 4);
	}

	public void Close()
	{
		if (alive)
		{
			Feedback feedback = new Feedback();
			feedback.Clear();
			try
			{
				Send(feedback, release: true);
			}
			catch (Exception)
			{
			}
		}
		alive = false;
		try
		{
			Hid.CancelIoEx(rh, IntPtr.Zero);
		}
		catch (Exception)
		{
		}
		try
		{
			rh.Dispose();
		}
		catch (Exception)
		{
		}
		try
		{
			wh.Dispose();
		}
		catch (Exception)
		{
		}
	}
}
internal class DualSensePad : HidPad
{
	private readonly bool edge;

	private int seq;

	private bool reset = true;

	private bool speakerOn;

	public override string Name => (edge ? "DualSense Edge" : "DualSense") + (bt ? " (Bluetooth)" : " (USB)");

	public override PadKind Kind => PadKind.DualSense;

	public DualSensePad(bool isEdge)
	{
		edge = isEdge;
	}

	protected override void Prepare()
	{
		outLen = (bt ? Math.Max(outLen, 78) : Math.Max(outLen, 48));
		Feature(5);
	}

	protected override void Parse(PadState s, byte[] d, int n)
	{
		if (d[0] == 49 && n >= 64)
		{
			Full(s, d, 2);
		}
		else if (d[0] == 1 && !bt && n >= 64)
		{
			Full(s, d, 1);
		}
		else if (d[0] == 1 && n >= 10)
		{
			s.LX = HidPad.Axis(d[1]);
			s.LY = 0f - HidPad.Axis(d[2]);
			s.RX = HidPad.Axis(d[3]);
			s.RY = 0f - HidPad.Axis(d[4]);
			HidPad.Buttons(s, d[5], d[6], d[7]);
			s.LT = (float)(int)d[8] / 255f;
			s.RT = (float)(int)d[9] / 255f;
		}
	}

	private static void Full(PadState s, byte[] d, int o)
	{
		s.LX = HidPad.Axis(d[o]);
		s.LY = 0f - HidPad.Axis(d[o + 1]);
		s.RX = HidPad.Axis(d[o + 2]);
		s.RY = 0f - HidPad.Axis(d[o + 3]);
		s.LT = (float)(int)d[o + 4] / 255f;
		s.RT = (float)(int)d[o + 5] / 255f;
		HidPad.Buttons(s, d[o + 7], d[o + 8], d[o + 9]);
		HidPad.Touch(s, d, o + 32, 1080);
		s.Battery = Mathf.Min(100, (d[o + 52] & 0xF) * 10 + 5);
	}

	protected override void Send(Feedback f, bool release)
	{
		byte[] array = new byte[outLen];
		int num;
		if (bt)
		{
			array[0] = 49;
			array[1] = (byte)(seq << 4);
			seq = (seq + 1) & 0xF;
			array[2] = 16;
			num = 3;
		}
		else
		{
			array[0] = 2;
			num = 1;
		}
		array[num] = 15;
		array[num + 1] = (byte)(release ? 8u : 21u);
		array[num + 2] = (byte)(Mathf.Clamp01(f.High) * 255f);
		array[num + 3] = (byte)(Mathf.Clamp01(f.Low) * 255f);
		if (f.Speaker && !release)
		{
			array[num] |= 160;
			array[num + 5] = 100;
			array[num + 7] = 48;
			speakerOn = true;
		}
		else if (speakerOn)
		{
			array[num] |= 128;
			array[num + 7] = 0;
			speakerOn = false;
		}
		Buffer.BlockCopy(f.RightTrig, 0, array, num + 10, 11);
		Buffer.BlockCopy(f.LeftTrig, 0, array, num + 21, 11);
		if (reset && !release)
		{
			array[num + 38] = 2;
			array[num + 41] = 2;
			reset = false;
		}
		array[num + 43] = f.Leds;
		array[num + 44] = f.R;
		array[num + 45] = f.G;
		array[num + 46] = f.B;
		if (bt)
		{
			Hid.PutCrc(array);
		}
		Write(array);
	}
}
internal class Ds4Pad : HidPad
{
	public override string Name => "DualShock 4" + (bt ? " (Bluetooth)" : " (USB)");

	public override PadKind Kind => PadKind.DualShock4;

	protected override void Prepare()
	{
		outLen = (bt ? Math.Max(outLen, 78) : Math.Max(outLen, 32));
		Feature(2);
		if (bt)
		{
			Feature(5);
		}
	}

	protected override void Parse(PadState s, byte[] d, int n)
	{
		int num;
		if (d[0] == 17 && n >= 78)
		{
			num = 3;
		}
		else
		{
			if (d[0] != 1 || n < 64 || bt)
			{
				if (d[0] == 1 && n >= 10)
				{
					Basic(s, d, 1);
				}
				return;
			}
			num = 1;
		}
		Basic(s, d, num);
		byte b = d[num + 29];
		int num2 = b & 0xF;
		bool flag = (b & 0x10) != 0;
		s.Battery = Mathf.Clamp(flag ? (num2 * 100 / 11) : (num2 * 10), 0, 100);
		HidPad.Touch(s, d, num + 34, 942);
	}

	private static void Basic(PadState s, byte[] d, int o)
	{
		s.LX = HidPad.Axis(d[o]);
		s.LY = 0f - HidPad.Axis(d[o + 1]);
		s.RX = HidPad.Axis(d[o + 2]);
		s.RY = 0f - HidPad.Axis(d[o + 3]);
		HidPad.Buttons(s, d[o + 4], d[o + 5], (byte)(d[o + 6] & 3));
		s.LT = (float)(int)d[o + 7] / 255f;
		s.RT = (float)(int)d[o + 8] / 255f;
	}

	protected override void Send(Feedback f, bool release)
	{
		byte[] array = new byte[outLen];
		int num;
		if (bt)
		{
			array[0] = 17;
			array[1] = 196;
			array[2] = 0;
			num = 3;
		}
		else
		{
			array[0] = 5;
			num = 1;
		}
		array[num] = 7;
		array[num + 3] = (byte)(Mathf.Clamp01(f.High) * 255f);
		array[num + 4] = (byte)(Mathf.Clamp01(f.Low) * 255f);
		if (release)
		{
			array[num + 5] = 0;
			array[num + 6] = 0;
			array[num + 7] = 64;
		}
		else
		{
			array[num + 5] = f.R;
			array[num + 6] = f.G;
			array[num + 7] = f.B;
		}
		if (bt)
		{
			Hid.PutCrc(array);
		}
		Write(array);
	}
}
internal static class Win
{
	public struct POINT
	{
		public int X;

		public int Y;
	}

	public struct RECT
	{
		public int L;

		public int T;

		public int R;

		public int B;
	}

	[DllImport("user32.dll")]
	public static extern bool GetCursorPos(out POINT p);

	[DllImport("user32.dll")]
	public static extern bool SetCursorPos(int x, int y);

	[DllImport("user32.dll")]
	public static extern IntPtr GetActiveWindow();

	[DllImport("user32.dll")]
	public static extern bool GetClientRect(IntPtr h, out RECT r);

	[DllImport("user32.dll")]
	public static extern bool ClientToScreen(IntPtr h, ref POINT p);

	[DllImport("user32.dll")]
	public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);

	[DllImport("user32.dll")]
	public static extern void mouse_event(uint flags, int dx, int dy, int data, UIntPtr extra);

	[DllImport("user32.dll")]
	public static extern uint MapVirtualKey(uint code, uint type);

	public static void Key(KeyCode k, bool down)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Invalid comparison between Unknown and I4
		//IL_001e: 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_000e: Invalid comparison between Unknown and I4
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Expected I4, but got Unknown
		if ((int)k >= 323 && (int)k <= 329)
		{
			Mouse(k - 323, down);
			return;
		}
		bool ext;
		int num = Vk(k, out ext);
		if (num <= 0)
		{
			return;
		}
		uint flags = (uint)(((!down) ? 2 : 0) | (ext ? 1 : 0));
		try
		{
			keybd_event((byte)num, (byte)MapVirtualKey((uint)num, 0u), flags, UIntPtr.Zero);
		}
		catch (Exception)
		{
		}
	}

	public static void Wheel(int notches)
	{
		try
		{
			mouse_event(2048u, 0, 0, notches * 120, UIntPtr.Zero);
		}
		catch (Exception)
		{
		}
	}

	private static void Mouse(int button, bool down)
	{
		int data = 0;
		uint flags;
		switch (button)
		{
		default:
			return;
		case 0:
			flags = (down ? 2u : 4u);
			break;
		case 1:
			flags = (down ? 8u : 16u);
			break;
		case 2:
			flags = (down ? 32u : 64u);
			break;
		case 3:
			flags = (down ? 128u : 256u);
			data = 1;
			break;
		case 4:
			flags = (down ? 128u : 256u);
			data = 2;
			break;
		}
		try
		{
			mouse_event(flags, 0, 0, data, UIntPtr.Zero);
		}
		catch (Exception)
		{
		}
	}

	private static int Vk(KeyCode k, out bool ext)
	{
		//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Expected I4, but got Unknown
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Invalid comparison between Unknown and I4
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Invalid comparison between Unknown and I4
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Invalid comparison between Unknown and I4
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Invalid comparison between Unknown and I4
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Invalid comparison between Unknown and I4
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Invalid comparison between Unknown and I4
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Invalid comparison between Unknown and I4
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Invalid comparison between Unknown and I4
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Invalid comparison between Unknown and I4
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Invalid comparison between Unknown and I4
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: Expected I4, but got Unknown
		//IL_00aa: 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_00d7: Expected I4, but got Unknown
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Invalid comparison between Unknown and I4
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Expected I4, but got Unknown
		//IL_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Invalid comparison between Unknown and I4
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Expected I4, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Invalid comparison between Unknown and I4
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Invalid comparison between Unknown and I4
		//IL_011a: 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_01d2: Expected I4, but got Unknown
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Invalid comparison between Unknown and I4
		ext = false;
		int num = (int)k;
		if ((int)k >= 97 && (int)k <= 122)
		{
			return 65 + (num - 97);
		}
		if ((int)k >= 48 && (int)k <= 57)
		{
			return 48 + (num - 48);
		}
		if ((int)k >= 282 && (int)k <= 296)
		{
			return 112 + (num - 282);
		}
		if ((int)k >= 256 && (int)k <= 265)
		{
			return 96 + (num - 256);
		}
		if ((int)k <= 32)
		{
			if ((int)k <= 13)
			{
				switch (k - 8)
				{
				case 0:
					return 8;
				case 1:
					return 9;
				}
				if ((int)k == 13)
				{
					return 13;
				}
			}
			else
			{
				if ((int)k == 19)
				{
					return 19;
				}
				if ((int)k == 27)
				{
					return 27;
				}
				if ((int)k == 32)
				{
					return 32;
				}
			}
		}
		else if ((int)k <= 61)
		{
			switch (k - 39)
			{
			default:
				switch (k - 59)
				{
				case 0:
					return 186;
				case 2:
					return 187;
				}
				break;
			case 5:
				return 188;
			case 6:
				return 189;
			case 7:
				return 190;
			case 8:
				return 191;
			case 0:
				return 222;
			case 1:
			case 2:
			case 3:
			case 4:
				break;
			}
		}
		else
		{
			switch (k - 91)
			{
			default:
				if ((int)k != 127)
				{
					switch (k - 266)
					{
					case 5:
						ext = true;
						return 13;
					case 35:
						return 20;
					case 14:
						ext = true;
						return 33;
					case 15:
						ext = true;
						return 34;
					case 13:
						ext = true;
						return 35;
					case 12:
						ext = true;
						return 36;
					case 10:
						ext = true;
						return 37;
					case 7:
						ext = true;
						return 38;
					case 9:
						ext = true;
						return 39;
					case 8:
						ext = true;
						return 40;
					case 11:
						ext = true;
						return 45;
					case 2:
						return 106;
					case 4:
						return 107;
					case 3:
						return 109;
					case 0:
						return 110;
					case 1:
						ext = true;
						return 111;
					case 38:
						return 160;
					case 37:
						return 161;
					case 40:
						return 162;
					case 39:
						ext = true;
						return 163;
					case 42:
						return 164;
					case 41:
						ext = true;
						return 165;
					}
					break;
				}
				ext = true;
				return 46;
			case 5:
				return 192;
			case 0:
				return 219;
			case 1:
				return 220;
			case 2:
				return 221;
			case 3:
			case 4:
				break;
			}
		}
		return 0;
	}
}
public class PadSafeInput : BaseInput
{
	public override bool GetButtonDown(string buttonName)
	{
		if (Runner.PadActive)
		{
			return false;
		}
		return ((BaseInput)this).GetButtonDown(buttonName);
	}

	public override float GetAxisRaw(string axisName)
	{
		if (Runner.PadActive)
		{
			return 0f;
		}
		return ((BaseInput)this).GetAxisRaw(axisName);
	}
}
internal static class PadSpeaker
{
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
	private struct Caps
	{
		public ushort Mid;

		public ushort Pid;

		public uint Ver;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
		public string Name;

		public uint Formats;

		public ushort Channels;

		public ushort Reserved;

		public uint Support;
	}

	private struct Wfx
	{
		public ushort Tag;

		public ushort Ch;

		public uint Rate;

		public uint Bytes;

		public ushort Align;

		public ushort Bits;

		public ushort Size;
	}

	private struct Hdr
	{
		public IntPtr Data;

		public uint Len;

		public uint Rec;

		public IntPtr User;

		public uint Flags;

		public uint Loops;

		public IntPtr Next;

		public IntPtr Res;
	}

	private class Voice
	{
		public float[] S;

		public int Pos;

		public float Vol;

		public bool Loop;

		public int Wait;

		public int EndIn = -1;
	}

	private const int Rate = 48000;

	private const int Block = 768;

	private const int Blocks = 4;

	public static float Delay;

	private static readonly Dictionary<AudioClip, float[]> cache = new Dictionary<AudioClip, float[]>();

	private static readonly List<Voice> voices = new List<Voice>();

	private static readonly object gate = new object();

	private static Voice loop;

	private static Thread thread;

	private static volatile bool running;

	private static float retryAt;

	private static IntPtr dev = IntPtr.Zero;

	private static IntPtr data = IntPtr.Zero;

	private static IntPtr[] hdrs;

	private static int DelayFrames => (int)(Mathf.Clamp(Delay, 0f, 3f) * 48000f);

	public static bool Open => running;

	public static bool LoopPlaying => loop != null;

	private static int HdrSize => Marshal.SizeOf(typeof(Hdr));

	[DllImport("winmm.dll", CharSet = CharSet.Unicode)]
	private static extern int waveOutGetDevCapsW(IntPtr id, ref Caps c, int size);

	[DllImport("winmm.dll")]
	private static extern int waveOutGetNumDevs();

	[DllImport("winmm.dll")]
	private static extern int waveOutOpen(out IntPtr h, IntPtr id, ref Wfx f, IntPtr cb, IntPtr inst, uint flags);

	[DllImport("winmm.dll")]
	private static extern int waveOutPrepareHeader(IntPtr h, IntPtr hdr, int size);

	[DllImport("winmm.dll")]
	private static extern int waveOutUnprepareHeader(IntPtr h, IntPtr hdr, int size);

	[DllImport("winmm.dll")]
	private static extern int waveOutWrite(IntPtr h, IntPtr hdr, int size);

	[DllImport("winmm.dll")]
	private static extern int waveOutReset(IntPtr h);

	[DllImport("winmm.dll")]
	private static extern int waveOutClose(IntPtr h);

	private static int FindDevice()
	{
		int num = -1;
		try
		{
			int num2 = waveOutGetNumDevs();
			for (int i = 0; i < num2; i++)
			{
				Caps c = default(Caps);
				if (waveOutGetDevCapsW((IntPtr)i, ref c, Marshal.SizeOf(typeof(Caps))) == 0 && c.Name != null)
				{
					if (c.Name.IndexOf("DualSense", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						return i;
					}
					if (num < 0 && c.Name.IndexOf("Wireless Controller", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						num = i;
					}
				}
			}
		}
		catch (Exception)
		{
		}
		return num;
	}

	private static float[] Get(AudioClip clip)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Invalid comparison between Unknown and I4
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Invalid comparison between Unknown and I4
		if (cache.TryGetValue(clip, out var value))
		{
			return value;
		}
		value = null;
		try
		{
			if ((int)clip.loadState != 2)
			{
				clip.LoadAudioData();
			}
			int channels = clip.channels;
			int samples = clip.samples;
			int frequency = clip.frequency;
			if ((int)clip.loadState == 2 && channels >= 1 && samples > 0 && frequency > 0)
			{
				float[] array = new float[samples * channels];
				if (clip.GetData(array, 0))
				{
					int num = (int)((long)samples * 48000L / frequency);
					value = new float[num * 2];
					double num2 = (double)frequency / 48000.0;
					for (int i = 0; i < num; i++)
					{
						double num3 = (double)i * num2;
						int num4 = (int)num3;
						int num5 = Math.Min(num4 + 1, samples - 1);
						float num6 = (float)(num3 - (double)num4);
						int num7 = ((channels > 1) ? 1 : 0);
						value[i * 2] = array[num4 * channels] + (array[num5 * channels] - array[num4 * channels]) * num6;
						value[i * 2 + 1] = array[num4 * channels + num7] + (array[num5 * channels + num7] - array[num4 * channels + num7]) * num6;
					}
				}
			}
		}
		catch (Exception)
		{
			value = null;
		}
		cache[clip] = value;
		return value;
	}

	public static void Ensure()
	{
		if (running || Time.unscaledTime < retryAt)
		{
			return;
		}
		int num = FindDevice();
		if (num < 0)
		{
			retryAt = Time.unscaledTime + 3f;
			return;
		}
		Wfx f = new Wfx
		{
			Tag = 1,
			Ch = 2,
			Rate = 48000u,
			Bits = 16,
			Align = 4,
			Bytes = 192000u
		};
		if (waveOutOpen(out var h, (IntPtr)num, ref f, IntPtr.Zero, IntPtr.Zero, 0u) != 0)
		{
			retryAt = Time.unscaledTime + 3f;
			return;
		}
		dev = h;
		int num2 = 3072;
		data = Marshal.AllocHGlobal(num2 * 4);
		Marshal.Copy(new byte[num2 * 4], 0, data, num2 * 4);
		hdrs = new IntPtr[4];
		for (int i = 0; i < 4; i++)
		{
			Hdr structure = new Hdr
			{
				Data = new IntPtr(data.ToInt64() + (long)i * (long)num2),
				Len = (uint)num2
			};
			ref IntPtr reference = ref hdrs[i];
			reference = Marshal.AllocHGlobal(HdrSize);
			Marshal.StructureToPtr(structure, hdrs[i], fDeleteOld: false);
			waveOutPrepareHeader(dev, hdrs[i], HdrSize);
			waveOutWrite(dev, hdrs[i], HdrSize);
		}
		running = true;
		thread = new Thread(Pump);
		thread.IsBackground = true;
		thread.Start();
	}

	private static void Pump()
	{
		float[] array = new float[1536];
		short[] array2 = new short[1536];
		int ofs = Marshal.OffsetOf(typeof(Hdr), "Flags").ToInt32();
		int num = 0;
		try
		{
			while (running)
			{
				if ((Marshal.ReadInt32(hdrs[num], ofs) & 1) == 0)
				{
					Thread.Sleep(2);
					continue;
				}
				Fill(array);
				for (int i = 0; i < array2.Length; i++)
				{
					array2[i] = (short)(Mathf.Clamp(array[i], -1f, 1f) * 32767f);
				}
				Marshal.Copy(array2, 0, Marshal.ReadIntPtr(hdrs[num], 0), array2.Length);
				waveOutWrite(dev, hdrs[num], HdrSize);
				num = (num + 1) % 4;
			}
		}
		catch (Exception)
		{
		}
	}

	private static void Fill(float[] mix)
	{
		Array.Clear(mix, 0, mix.Length);
		lock (gate)
		{
			for (int num = voices.Count - 1; num >= 0; num--)
			{
				Voice voice = voices[num];
				int num2 = voice.S.Length / 2;
				bool flag = false;
				for (int i = 0; i < 768; i++)
				{
					if (voice.EndIn >= 0)
					{
						if (voice.EndIn == 0)
						{
							flag = true;
							break;
						}
						voice.EndIn--;
					}
					if (voice.Wait > 0)
					{
						voice.Wait--;
						continue;
					}
					if (voice.Pos >= num2)
					{
						if (!voice.Loop)
						{
							flag = true;
							break;
						}
						voice.Pos = 0;
					}
					mix[i * 2] += voice.S[voice.Pos * 2] * voice.Vol;
					mix[i * 2 + 1] += voice.S[voice.Pos * 2 + 1] * voice.Vol;
					voice.Pos++;
				}
				if (flag || (!voice.Loop && voice.Pos >= num2))
				{
					voices.RemoveAt(num);
				}
			}
		}
	}

	public static void StartLoop(AudioClip clip, int offset, float vol)
	{
		StopLoop();
		if (!running || (Object)(object)clip == (Object)null)
		{
			return;
		}
		float[] array = Get(clip);
		if (array != null && array.Length >= 2)
		{
			Voice voice = new Voice();
			voice.S = array;
			voice.Vol = vol;
			voice.Loop = true;
			voice.Wait = DelayFrames;
			voice.Pos = ((clip.frequency > 0) ? ((int)((long)offset * 48000L / clip.frequency) % (array.Length / 2)) : 0);
			lock (gate)
			{
				voices.Add(voice);
			}
			loop = voice;
		}
	}

	public static void LoopVolume(float vol)
	{
		if (loop != null)
		{
			loop.Vol = vol;
		}
	}

	public static void StopLoop()
	{
		if (loop == null)
		{
			return;
		}
		int delayFrames = DelayFrames;
		lock (gate)
		{
			if (delayFrames <= 0 || loop.Wait >= delayFrames)
			{
				voices.Remove(loop);
			}
			else
			{
				loop.EndIn = delayFrames;
			}
		}
		loop = null;
	}

	public static void Shot(AudioClip clip, float vol)
	{
		if (!running || (Object)(object)clip == (Object)null || vol <= 0.01f)
		{
			return;
		}
		float[] array = Get(clip);
		if (array == null || array.Length < 2)
		{
			return;
		}
		Voice voice = new Voice();
		voice.S = array;
		voice.Vol = vol;
		voice.Wait = DelayFrames;
		lock (gate)
		{
			if (voices.Count < 12)
			{
				voices.Add(voice);
			}
		}
	}

	public static void StopAll()
	{
		lock (gate)
		{
			voices.Clear();
		}
		loop = null;
		if (!running && dev == IntPtr.Zero)
		{
			return;
		}
		running = false;
		try
		{
			if (thread != null)
			{
				thread.Join(300);
			}
		}
		catch (Exception)
		{
		}
		thread = null;
		try
		{
			waveOutReset(dev);
			for (int i = 0; i < hdrs.Length; i++)
			{
				waveOutUnprepareHeader(dev, hdrs[i], HdrSize);
				Marshal.FreeHGlobal(hdrs[i]);
			}
			waveOutClose(dev);
		}
		catch (Exception)
		{
		}
		if (data != IntPtr.Zero)
		{
			Marshal.FreeHGlobal(data);
		}
		data = IntPtr.Zero;
		dev = IntPtr.Zero;
	}
}
public class Runner : MonoBehaviour
{
	private const int MoveL = 20;

	private const int MoveR = 21;

	private const int MoveU = 22;

	private const int MoveD = 23;

	private const int Tap = 24;

	private const int Wrap = 25;

	internal static bool PadActive;

	internal static PadKind Kind = PadKind.None;

	internal static PadKind LastKind = PadKind.DualSense;

	internal static string PadName = "";

	internal static PadState Live = new PadState();

	internal static Feedback LiveFb = new Feedback();

	internal static float TestRumbleUntil;

	internal static float TestTriggersUntil;

	internal static Color ShownLight = new Color(1f, 0.5f, 0.12f);

	private readonly PadState state = new PadState();

	private readonly Feedback fb = new Feedback();

	private readonly bool[] prev = new bool[26];

	private readonly KeyCode[] heldWith = (KeyCode[])(object)new KeyCode[26];

	private readonly Dictionary<KeyCode, int> holds = new Dictionary<KeyCode, int>();

	private readonly float[] probeAt = new float[4];

	private float hidProbeAt;

	private IPad pad;

	private int padIndex = -1;

	private float accX;

	private float accY;

	private IntPtr hwnd = IntPtr.Zero;

	private string bannerText = "";

	private string bannerSub = "";

	private PadKind bannerKind;

	private bool bannerBad;

	private float bannerAt = -100f;

	private float bannerHold;

	private PreRunScript lastTitle;

	private float titleLookAt;

	private GUIStyle bannerStyle;

	private GUIStyle bannerSubStyle;

	private float uiCheckAt;

	private int cycleStep;

	private bool touchRawPrev;

	private int touchChosen = 16;

	private bool touching;

	private int touchFingers;

	private int touchMaxFingers;

	private float touchStart;

	private float touchMoved;

	private float tapUpAt = -1f;

	private float scrollAcc;

	private int lastTX;

	private int lastTY;

	private bool touchClicked;

	private float limbPrev = -1f;

	private float hitUntil;

	private float hitPower;

	private bool batteryShown;

	private Color light = new Color(1f, 0.5f, 0.12f);

	private PreRunScript preRun;

	private float preRunLookAt;

	private static readonly Color[] CharColors = (Color[])(object)new Color[3]
	{
		new Color(1f, 0.45f, 0.08f),
		new Color(1f, 1f, 1f),
		new Color(0.78f, 0.52f, 0.86f)
	};

	private bool dLeftPrev;

	private bool dRightPrev;

	private AudioSource alertSrc;

	internal static bool SpeakerOk;

	private bool wrapGrab;

	private static bool Wrapping;

	private float lastPadAt = -99f;

	private float lastKbmAt = -99f;

	private float padCursorAt = -99f;

	private Vector3 lastMouse;

	private TextMeshProUGUI warnText;

	private string warnOrig;

	private static GUIStyle hintStyle;

	internal static float ShotAt = -10f;

	internal static GunScript ShotGun;

	private void Update()
	{
		if (!Plugin.Enabled.Value)
		{
			if (pad != null)
			{
				Drop("");
			}
			return;
		}
		FindPad();
		TitleCheck();
		WarningPrompt();
		if (pad == null)
		{
			Kind = PadKind.None;
			return;
		}
		state.Clear();
		if (!pad.Poll(state))
		{
			Drop(pad.Name + " disconnected");
			return;
		}
		PadActive = true;
		Kind = pad.Kind;
		LastKind = Kind;
		PadName = pad.Name;
		Live = state;
		LiveFb = fb;
		TrackInput();
		if (!batteryShown && state.Battery >= 0)
		{
			batteryShown = true;
			Plugin.Log.LogInfo((object)(pad.Name + " battery about " + state.Battery + "%."));
		}
		GameFeedback();
		SpeakerSync();
		pad.Apply(fb);
		if (!Application.isFocused)
		{
			ReleaseAll();
			accX = (accY = 0f);
			touching = false;
			return;
		}
		IntPtr activeWindow = Win.GetActiveWindow();
		if (activeWindow != IntPtr.Zero)
		{
			hwnd = activeWindow;
		}
		else if (hwnd == IntPtr.Zero)
		{
			try
			{
				hwnd = Process.GetCurrentProcess().MainWindowHandle;
			}
			catch (Exception)
			{
			}
		}
		GuardUI();
		CourseNav();
		Sticks();
		Touchpad();
		for (int i = 0; i < 20; i++)
		{
			switch (i)
			{
			case 16:
			{
				bool flag = state.Down[i];
				if (flag != touchRawPrev)
				{
					if (flag)
					{
						touchChosen = ((touchFingers >= 2) ? 17 : 16);
						touchClicked = true;
					}
					Set(touchChosen, flag, Plugin.Map[touchChosen].Value);
					touchRawPrev = flag;
				}
				break;
			}
			default:
			{
				bool down = state.Down[i];
				switch (i)
				{
				case 6:
					down = state.LT >= Plugin.TriggerThreshold.Value;
					break;
				case 7:
					down = state.RT >= Plugin.TriggerThreshold.Value;
					break;
				}
				Set(i, down, ActionFor(i));
				break;
			}
			case 17:
				break;
			}
		}
		if (tapUpAt > 0f && Time.unscaledTime >= tapUpAt)
		{
			tapUpAt = -1f;
			Set(24, down: false, "leftclick");
		}
	}

	private string ActionFor(int i)
	{
		if (i == 0 && Plugin.MenuSelect.Value && InMenu())
		{
			return "leftclick";
		}
		if ((i == 14 || i == 15) && (Object)(object)CourseSelect() != (Object)null)
		{
			return "none";
		}
		return Plugin.Map[i].Value;
	}

	private static TutorialHandler CourseSelect()
	{
		try
		{
			TutorialHandler main = TutorialHandler.main;
			if ((Object)(object)main != (Object)null && (Object)(object)main.courseSelectScreen != (Object)null && main.courseSelectScreen.activeInHierarchy)
			{
				return main;
			}
		}
		catch (Exception)
		{
		}
		return null;
	}

	private void CourseNav()
	{
		bool flag = state.Down[14];
		bool flag2 = state.Down[15];
		TutorialHandler val = (((flag && !dLeftPrev) || (flag2 && !dRightPrev)) ? CourseSelect() : null);
		if ((Object)(object)val != (Object)null)
		{
			try
			{
				val.ChangeSelectedCourse((!flag || dLeftPrev) ? 1 : (-1));
			}
			catch (Exception)
			{
			}
		}
		dLeftPrev = flag;
		dRightPrev = flag2;
	}

	internal static bool InMenu()
	{
		try
		{
			if ((Object)(object)SettingsMenu.instance != (Object)null)
			{
				return true;
			}
			if (PauseHandler.paused)
			{
				return true;
			}
			if ((Object)(object)PlayerCamera.main == (Object)null || (Object)(object)PlayerCamera.main.body == (Object)null)
			{
				return true;
			}
			if (ScrollableText.textExists)
			{
				return true;
			}
			if ((Object)(object)CourseSelect() != (Object)null)
			{
				return true;
			}
			PlayerCamera main = PlayerCamera.main;
			if ((Object)(object)main.craftingPanel != (Object)null && main.craftingPanel.activeInHierarchy)
			{
				return true;
			}
			if ((Object)(object)main.tradeMenu != (Object)null && main.tradeMenu.activeInHierarchy)
			{
				return true;
			}
			if ((Object)(object)main.itemCustomizer != (Object)null && main.itemCustomizer.activeInHierarchy)
			{
				return true;
			}
		}
		catch (Exception)
		{
			return true;
		}
		return false;
	}

	private void FindPad()
	{
		if (this.pad != null)
		{
			return;
		}
		PadActive = false;
		float unscaledTime = Time.unscaledTime;
		if (unscaledTime >= hidProbeAt)
		{
			hidProbeAt = unscaledTime + 2f;
			IPad pad = HidPad.Open();
			if (pad != null)
			{
				Use(pad, -1);
				return;
			}
		}
		for (int i = 0; i < 4; i++)
		{
			if (!(unscaledTime < probeAt[i]))
			{
				if (XInput.Get(i, out var _))
				{
					Use(new XboxPad(i), i);
					break;
				}
				probeAt[i] = unscaledTime + 2f;
			}
		}
	}

	private void Use(IPad p, int index)
	{
		pad = p;
		padIndex = index;
		batteryShown = false;
		limbPrev = -1f;
		Show(p.Name + " connected", "", p.Kind, bad: false, 2.5f);
		Plugin.Log.LogInfo((object)("Using " + p.Name + ((index >= 0) ? (" in slot " + (index + 1)) : "") + "."));
	}

	internal static void GameSound(AudioClip clip, float volume)
	{
		if ((Object)(object)clip == (Object)null || !SpeakerOk)
		{
			return;
		}
		PlayerCamera main = PlayerCamera.main;
		if (!((Object)(object)main == (Object)null) && !((Object)(object)main.woundView == (Object)null))
		{
			bool flag = main.uiSounds != null && main.uiSounds.Length > 3 && (Object)(object)clip == (Object)(object)main.uiSounds[3];
			if (!flag && main.uiSounds != null && main.uiSounds.Length > 2 && (Object)(object)clip == (Object)(object)main.uiSounds[2] && main.woundView.activeInHierarchy)
			{
				flag = true;
			}
			bool flag2 = ((Object)clip).name.StartsWith("heartthump", StringComparison.OrdinalIgnoreCase) && main.woundView.activeInHierarchy;
			if (flag || flag2)
			{
				PadSpeaker.Shot(clip, Mathf.Clamp01(volume * Plugin.SpeakerVolume.Value));
			}
		}
	}

	private void SpeakerSync()
	{
		AudioSource val = null;
		bool flag = false;
		SpeakerOk = false;
		try
		{
			if (Kind == PadKind.DualSense && Plugin.SpeakerAlert.Value && (Object)(object)PlayerCamera.main != (Object)null && (Object)(object)PlayerCamera.main.woundView != (Object)null)
			{
				SpeakerOk = true;
				flag = PlayerCamera.main.woundView.activeInHierarchy;
				if ((Object)(object)alertSrc == (Object)null || (Object)(object)((Component)alertSrc).gameObject != (Object)(object)PlayerCamera.main.woundView)
				{
					alertSrc = PlayerCamera.main.woundView.GetComponent<AudioSource>();
				}
				val = alertSrc;
			}
		}
		catch (Exception)
		{
			val = null;
		}
		bool flag2 = (Object)(object)val != (Object)null && val.isPlaying && (Object)(object)val.clip != (Object)null && !AudioListener.pause;
		float vol = (flag2 ? Mathf.Clamp01(val.volume * Plugin.SpeakerVolume.Value) : 0f);
		PadSpeaker.Delay = Plugin.SpeakerDelay.Value;
		if (SpeakerOk)
		{
			PadSpeaker.Ensure();
		}
		else
		{
			PadSpeaker.StopAll();
		}
		if (flag2 && !PadSpeaker.LoopPlaying)
		{
			PadSpeaker.StartLoop(val.clip, val.timeSamples, vol);
		}
		else if (!flag2 && PadSpeaker.LoopPlaying)
		{
			PadSpeaker.StopLoop();
		}
		else if (flag2)
		{
			PadSpeaker.LoopVolume(vol);
		}
		fb.Speaker = PadSpeaker.Open || (flag && SpeakerOk);
	}

	private void Drop(string why)
	{
		SpeakerOk = false;
		PadSpeaker.StopAll();
		ReleaseAll();
		if (pad != null)
		{
			try
			{
				pad.Close();
			}
			catch (Exception)
			{
			}
			if (why.Length > 0)
			{
				bool flag = ForcePause();
				Show(why, flag ? "Game paused. Reconnect it, or press Esc to keep playing." : "", pad.Kind, bad: true, flag ? 6f : 4f);
				Plugin.Log.LogInfo((object)(why + (flag ? ", paused the game." : ".")));
			}
		}
		if (padIndex >= 0)
		{
			probeAt[padIndex] = Time.unscaledTime + 1f;
		}
		hidProbeAt = Time.unscaledTime + 1f;
		pad = null;
		padIndex = -1;
		PadActive = false;
		Kind = PadKind.None;
		touching = false;
	}

	private void TrackInput()
	{
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		float unscaledTime = Time.unscaledTime;
		bool flag = state.T0 || state.T1;
		for (int i = 0; i < 20; i++)
		{
			if (flag)
			{
				break;
			}
			flag = state.Down[i];
		}
		float value = Plugin.Deadzone.Value;
		if (!flag)
		{
			flag = Mathf.Abs(state.LX) > value || Mathf.Abs(state.LY) > value || Mathf.Abs(state.RX) > value || Mathf.Abs(state.RY) > value || state.LT > 0.2f || state.RT > 0.2f;
		}
		if (flag)
		{
			lastPadAt = unscaledTime;
		}
		Vector3 mousePosition = Input.mousePosition;
		Vector3 val = mousePosition - lastMouse;
		if (((Vector3)(ref val)).sqrMagnitude > 4f && unscaledTime - padCursorAt > 0.2f)
		{
			lastKbmAt = unscaledTime;
		}
		lastMouse = mousePosition;
		if (Input.anyKeyDown && !flag && holds.Count == 0 && unscaledTime - lastPadAt > 0.3f)
		{
			lastKbmAt = unscaledTime;
		}
	}

	private void WarningPrompt()
	{
		try
		{
			PreRunScript instance = PreRunScript.instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.contentWarning == (Object)null || !instance.contentWarning.activeInHierarchy)
			{
				return;
			}
			if ((Object)(object)warnText == (Object)null || (Object)(object)((Component)warnText).gameObject == (Object)null)
			{
				warnText = null;
				warnOrig = null;
				TextMeshProUGUI[] componentsInChildren = instance.contentWarning.GetComponentsInChildren<TextMeshProUGUI>(true);
				foreach (TextMeshProUGUI val in componentsInChildren)
				{
					if (((TMP_Text)val).text != null && ((TMP_Text)val).text.Contains("LMB"))
					{
						warnText = val;
						warnOrig = ((TMP_Text)val).text;
						break;
					}
				}
				if ((Object)(object)warnText == (Object)null)
				{
					return;
				}
			}
			string text = warnOrig;
			if (pad != null && Plugin.MenuSelect.Value)
			{
				text = warnOrig.Replace("LMB", (Kind == PadKind.Xbox) ? "A" : "Cross");
			}
			if (((TMP_Text)warnText).text != text)
			{
				((TMP_Text)warnText).text = text;
			}
		}
		catch (Exception)
		{
		}
	}

	private void DrawWrapHint()
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Expected O, but got Unknown
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Expected O, but got Unknown
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: 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_0104: 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_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_012f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		if (Wrapping && PadActive && !(lastKbmAt > lastPadAt))
		{
			if (hintStyle == null)
			{
				hintStyle = new GUIStyle(GUI.skin.label);
				hintStyle.alignment = (TextAnchor)4;
				hintStyle.fontStyle = (FontStyle)1;
				hintStyle.normal.textColor = Color.white;
			}
			float num = (float)Screen.height / 1080f;
			hintStyle.fontSize = Mathf.Max(12, Mathf.RoundToInt(26f * num));
			string text = (wrapGrab ? "Keep rotating the stick to wrap the bandage" : "Rotate a stick to grab the roll and patch yourself up");
			Vector2 val = hintStyle.CalcSize(new GUIContent(text));
			Rect val2 = default(Rect);
			((Rect)(ref val2))..ctor(((float)Screen.width - val.x) * 0.5f - 24f * num, (float)Screen.height * 0.84f, val.x + 48f * num, val.y + 18f * num);
			Color color = GUI.color;
			GUI.color = new Color(0f, 0f, 0f, 0.65f);
			GUI.DrawTexture(val2, (Texture)(object)Texture2D.whiteTexture);
			GUI.color = color;
			GUI.Label(val2, text, hintStyle);
		}
	}

	private bool BandageStick()
	{
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//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_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0189: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		MinigameBase main = MinigameBase.main;
		BandageMinigame val = null;
		try
		{
			if ((Object)(object)main != (Object)null && (Object)(object)main.minigameScreen != (Object)null)
			{
				Minigame currentMinigame = main.currentMinigame;
				val = (BandageMinigame)(object)((currentMinigame is BandageMinigame) ? currentMinigame : null);
			}
		}
		catch (Exception)
		{
			val = null;
		}
		Wrapping = val != null;
		if (val == null)
		{
			if (wrapGrab)
			{
				wrapGrab = false;
				Set(25, down: false, "attack");
			}
			return false;
		}
		Set(20, down: false, "left");
		Set(21, down: false, "right");
		Set(22, down: false, "up");
		Set(23, down: false, "down");
		Dead(state.LX, state.LY, out var ox, out var oy);
		Dead(state.RX, state.RY, out var ox2, out var oy2);
		Vector2 val2 = ((ox * ox + oy * oy >= ox2 * ox2 + oy2 * oy2) ? new Vector2(ox, oy) : new Vector2(ox2, oy2));
		if (((Vector2)(ref val2)).magnitude < 0.5f)
		{
			wrapGrab = false;
			Set(25, down: false, "attack");
			return true;
		}
		Vector2 normalized = ((Vector2)(ref val2)).normalized;
		float num = 1f;
		try
		{
			num = PlayerCamera.uiScale;
		}
		catch (Exception)
		{
		}
		CursorToScreen(Vector2.op_Implicit(((Transform)main.minigameScreen).position) + normalized * 320f * num);
		if (!wrapGrab)
		{
			try
			{
				wrapGrab = Vector2.Dot(BandageMinigame.GetVectorFromAngle(val.bandageAngle), ((Vector2)(ref main.handPos)).normalized) > 0.93f;
			}
			catch (Exception)
			{
				wrapGrab = false;
			}
		}
		Set(25, wrapGrab, "attack");
		return true;
	}

	private void CursorToScreen(Vector2 p)
	{
		if (!(hwnd == IntPtr.Zero) && Win.GetClientRect(hwnd, out var r) && Screen.width > 0 && Screen.height > 0)
		{
			Win.POINT p2 = default(Win.POINT);
			Win.ClientToScreen(hwnd, ref p2);
			int x = p2.X + Mathf.Clamp(Mathf.RoundToInt(p.x * (float)r.R / (float)Screen.width), 0, r.R - 1);
			int y = p2.Y + Mathf.Clamp(Mathf.RoundToInt(((float)Screen.height - p.y) * (float)r.B / (float)Screen.height), 0, r.B - 1);
			Win.SetCursorPos(x, y);
			accX = (accY = 0f);
			padCursorAt = Time.unscaledTime;
		}
	}

	private void Sticks()
	{
		if (BandageStick())
		{
			return;
		}
		Dead(state.LX, state.LY, out var ox, out var oy);
		float value = Plugin.MoveThreshold.Value;
		Set(20, ox <= 0f - value, "left");
		Set(21, ox >= value, "right");
		Set(22, oy >= value, "up");
		Set(23, oy <= 0f - value, "down");
		Dead(state.RX, state.RY, out var ox2, out var oy2);
		float num = Mathf.Sqrt(ox2 * ox2 + oy2 * oy2);
		if (!(num <= 0f))
		{
			float num2 = Plugin.CursorSpeed.Value * (float)Screen.height * Mathf.Pow(Mathf.Min(num, 1f), Plugin.CursorCurve.Value) / num;
			if (Holding("precise"))
			{
				num2 *= Plugin.PreciseSpeed.Value;
			}
			float unscaledDeltaTime = Time.unscaledDeltaTime;
			MoveCursor(ox2 * num2 * unscaledDeltaTime, (Plugin.InvertLookY.Value ? oy2 : (0f - oy2)) * num2 * unscaledDeltaTime);
		}
	}

	private void Touchpad()
	{
		if (!state.HasTouch || !Plugin.TouchpadMouse.Value)
		{
			touching = false;
			touchFingers = 0;
			return;
		}
		float unscaledTime = Time.unscaledTime;
		int num = (state.T0 ? 1 : 0) + (state.T1 ? 1 : 0);
		if (num == 0)
		{
			if (touching && Plugin.TapToClick.Value && touchMaxFingers == 1 && !touchClicked && unscaledTime - touchStart < 0.2f && touchMoved < 60f && tapUpAt < 0f)
			{
				Set(24, down: true, "leftclick");
				tapUpAt = unscaledTime + 0.06f;
			}
			touching = false;
			touchFingers = 0;
			return;
		}
		int num2 = (state.T0 ? state.T0X : state.T1X);
		int num3 = (state.T0 ? state.T0Y : state.T1Y);
		if (num == 2)
		{
			num3 = (state.T0Y + state.T1Y) / 2;
		}
		if (!touching)
		{
			touching = true;
			touchStart = unscaledTime;
			touchMoved = 0f;
			touchMaxFingers = num;
			touchClicked = state.Down[16];
			touchFingers = num;
			lastTX = num2;
			lastTY = num3;
			scrollAcc = 0f;
			return;
		}
		if (num > touchMaxFingers)
		{
			touchMaxFingers = num;
		}
		if (num != touchFingers)
		{
			touchFingers = num;
			lastTX = num2;
			lastTY = num3;
			scrollAcc = 0f;
			return;
		}
		int num4 = num2 - lastTX;
		int num5 = num3 - lastTY;
		lastTX = num2;
		lastTY = num3;
		touchMoved += Mathf.Abs(num4) + Mathf.Abs(num5);
		if (num == 1)
		{
			float num6 = Plugin.TouchpadSpeed.Value * (float)Screen.width / 1920f;
			if (Holding("precise"))
			{
				num6 *= Plugin.PreciseSpeed.Value;
			}
			MoveCursor((float)num4 * num6, (float)num5 * num6);
		}
		else if (Plugin.TwoFingerScroll.Value)
		{
			scrollAcc += (Plugin.InvertScroll.Value ? (-num5) : num5);
			int num7 = (int)(scrollAcc / 45f);
			if (num7 != 0)
			{
				scrollAcc -= (float)num7 * 45f;
				Win.Wheel(num7);
			}
		}
	}

	private void MoveCursor(float dx, float dy)
	{
		accX += dx;
		accY += dy;
		int num = (int)accX;
		int num2 = (int)accY;
		if (num == 0 && num2 == 0)
		{
			return;
		}
		accX -= num;
		accY -= num2;
		if (Win.GetCursorPos(out var p))
		{
			int num3 = p.X + num;
			int num4 = p.Y + num2;
			if (hwnd != IntPtr.Zero && Win.GetClientRect(hwnd, out var r))
			{
				Win.POINT p2 = default(Win.POINT);
				Win.ClientToScreen(hwnd, ref p2);
				num3 = Mathf.Clamp(num3, p2.X, p2.X + r.R - 1);
				num4 = Mathf.Clamp(num4, p2.Y, p2.Y + r.B - 1);
			}
			Win.SetCursorPos(num3, num4);
			padCursorAt = Time.unscaledTime;
		}
	}

	private void Dead(float x, float y, out float ox, out float oy)
	{
		float num = Mathf.Sqrt(x * x + y * y);
		float value = Plugin.Deadzone.Value;
		if (num <= value || num <= 0f)
		{
			ox = (oy = 0f);
			return;
		}
		float num2 = Mathf.Min((num - value) / (1f - value), 1f) / num;
		ox = x * num2;
		oy = y * num2;
	}

	private int MenuCharacter()
	{
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		int result = Mathf.Clamp(PreRunScript.characterSelected, 0, CharColors.Length - 1);
		if (Time.unscaledTime >= preRunLookAt)
		{
			preRunLookAt = Time.unscaledTime + 1f;
			if ((Object)(object)preRun == (Object)null)
			{
				preRun = Object.FindObjectOfType<PreRunScript>();
			}
		}
		if ((Object)(object)preRun == (Object)null || preRun.charImages == null)
		{
			return result;
		}
		Vector2 val = Vector2.op_Implicit(Input.mousePosition);
		for (int i = 0; i < preRun.charImages.Count && i < CharColors.Length; i++)
		{
			Image val2 = preRun.charImages[i];
			if ((Object)(object)val2 == (Object)null || !((Component)val2).gameObject.activeInHierarchy)
			{
				continue;
			}
			Canvas canvas = ((Graphic)val2).canvas;
			Camera val3 = null;
			if ((Object)(object)canvas != (Object)null)
			{
				canvas = canvas.rootCanvas;
				if ((int)canvas.renderMode != 0)
				{
					val3 = canvas.worldCamera;
				}
			}
			if (RectTransformUtility.RectangleContainsScreenPoint(((Graphic)val2).rectTransform, val, val3))
			{
				return i;
			}
		}
		return result;
	}

	private void GameFeedback()
	{
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0346: Unknown result type (might be due to invalid IL or missing references)
		//IL_034b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_048a: Unknown result type (might be due to invalid IL or missing references)
		//IL_048f: Unknown result type (might be due to invalid IL or missing references)
		//IL_03da: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_03fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0393: Unknown result type (might be due to invalid IL or missing references)
		//IL_037d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0268: Unknown result type (might be due to invalid IL or missing references)
		//IL_027c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0289: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Unknown result type (might be due to invalid IL or missing references)
		//IL_022a: Unknown result type (might be due to invalid IL or missing references)
		//IL_023e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0251: Unknown result type (might be due to invalid IL or missing references)
		//IL_0256: Unknown result type (might be due to invalid IL or missing references)
		//IL_0446: Unknown result type (might be due to invalid IL or missing references)
		//IL_045a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0461: Unknown result type (might be due to invalid IL or missing references)
		//IL_0466: Unknown result type (might be due to invalid IL or missing references)
		//IL_0398: Unknown result type (might be due to invalid IL or missing references)
		//IL_06a7: Unknown result type (might be due to invalid IL or missing references)
		fb.Clear();
		Body val = null;
		try
		{
			if ((Object)(object)PlayerCamera.main != (Object)null)
			{
				val = PlayerCamera.main.body;
			}
		}
		catch (Exception)
		{
		}
		float unscaledTime = Time.unscaledTime;
		float unscaledDeltaTime = Time.unscaledDeltaTime;
		bool snap = false;
		Color target = default(Color);
		if ((Object)(object)val == (Object)null)
		{
			limbPrev = -1f;
			((Color)(ref target))..ctor(1f, 0.45f, 0.08f);
			if (Plugin.CharacterLightbar.Value)
			{
				try
				{
					target = CharColors[MenuCharacter()];
				}
				catch (Exception)
				{
				}
			}
			fb.Leds = 4;
			Tests(unscaledTime);
			Finish(target, unscaledDeltaTime, snap: false);
			return;
		}
		bool flag = true;
		bool flag2 = true;
		bool flag3 = false;
		bool flag4 = false;
		float num = 1f;
		float num2 = 100f;
		float num3 = 0f;
		try
		{
			flag = val.alive;
			flag2 = val.conscious;
			flag3 = val.isDying;
			flag4 = val.sleeping;
			num2 = val.energy;
			float num4 = 1f;
			if (val.limbs != null && val.limbs.Length > 0)
			{
				float num5 = 0f;
				Limb[] limbs = val.limbs;
				foreach (Limb val2 in limbs)
				{
					if (!((Object)(object)val2 == (Object)null))
					{
						num5 += val2.skinHealth + val2.muscleHealth;
					}
				}
				num3 = num5;
				num4 = num5 / ((float)val.limbs.Length * 200f);
			}
			num = Mathf.Min(Mathf.Min(val.bloodVolume / 100f, val.consciousness / 100f), Mathf.Min(val.brainHealth / 100f, num4));
			num = Mathf.Clamp01(num);
		}
		catch (Exception)
		{
		}
		if (!flag)
		{
			limbPrev = -1f;
			Tests(unscaledTime);
			Finish(new Color(0.16f, 0f, 0f), unscaledDeltaTime * 0.25f, snap: false);
			return;
		}
		if (Plugin.HealthLightbar.Value)
		{
			if (!flag4)
			{
				target = ((!(num > 0.5f)) ? Color.Lerp(new Color(1f, 0f, 0f), new Color(1f, 0.85f, 0f), num * 2f) : Color.Lerp(new Color(1f, 0.85f, 0f), new Color(0f, 1f, 0.2f), (num - 0.5f) * 2f));
			}
			else
			{
				((Color)(ref target))..ctor(0f, 0.05f, 0.25f);
			}
			if (!flag4)
			{
				bool flag5 = false;
				bool flag6 = false;
				int num6 = 0;
				try
				{
					flag5 = val.totalBleedSpeed > 0.06f;
					flag6 = val.venomCurrent + val.venomFake > 55f || val.sicknessAmount > 50f;
					if (flag5)
					{
						num6++;
					}
					if (flag6)
					{
						num6++;
					}
					if (val.internalBleeding > 25f)
					{
						num6++;
					}
					if (val.septicShock > 10f)
					{
						num6++;
					}
					if (val.radiationSickness > 30f)
					{
						num6++;
					}
				}
				catch (Exception)
				{
				}
				if (num6 >= 2)
				{
					target = Color.HSVToRGB(Mathf.Repeat(unscaledTime * 0.5f, 1f), 1f, 1f);
					snap = true;
				}
				else if (flag3)
				{
					target = ((Mathf.PingPong(Time.unscaledTime, 0.3f) > 0.15f) ? new Color(1f, 0f, 0f) : new Color(0.07f, 0f, 0f));
					snap = true;
				}
				else if (flag5)
				{
					float num7 = 0.5f - 0.5f * Mathf.Cos(unscaledTime * (float)Math.PI * 2f / 1.4f);
					target = Color.Lerp(new Color(0.12f, 0.09f, 0f), new Color(1f, 0.85f, 0f), num7);
					snap = true;
				}
				else if (flag6)
				{
					float num8 = Mathf.SmoothStep(0f, 1f, Mathf.Clamp01((Mathf.PingPong(unscaledTime, 1.2f) - 0.35f) * 2f));
					target = Color.Lerp(new Color(0f, 0.06f, 0.02f), new Color(0.1f, 1f, 0.2f), num8);
					snap = true;
				}
			}
		}
		else
		{
			target = CharColors[Mathf.Clamp(PreRunScript.characterSelected, 0, CharColors.Length - 1)];
		}
		if (Plugin.EnergyLights.Value)
		{
			int num9 = Mathf.Clamp(Mathf.CeilToInt(num2 / 20f), 0, 5);
			byte[] array = new byte[6] { 0, 1, 3, 7, 15, 31 };
			fb.Leds = array[num9];
			if (num9 <= 1 && Mathf.Repeat(unscaledTime, 1f) < 0.5f)
			{
				fb.Leds = 0;
			}
		}
		else
		{
			fb.Leds = 4;
		}
		if (limbPrev >= 0f && num3 < limbPrev - 0.5f)
		{
			float num10 = limbPrev - num3;
			hitPower = Mathf.Max((unscaledTime < hitUntil) ? hitPower : 0f, Mathf.Clamp(num10 / 25f, 0.3f, 1f));
			hitUntil = unscaledTime + 0.18f + Mathf.Min(num10 / 60f, 0.35f);
		}
		limbPrev = num3;
		if (Plugin.Rumble.Value)
		{
			float value = Plugin.RumbleStrength.Value;
			if (unscaledTime < hitUntil)
			{
				fb.Low = hitPower * value;
				fb.High = hitPower * 0.6f * value;
			}
			if (flag3 && Plugin.Heartbeat.Value && Beat(unscaledTime) > 0.6f)
			{
				fb.Low = Mathf.Max(fb.Low, 0.45f * value);
			}
		}
		if (Plugin.AdaptiveTriggers.Value)
		{
			float value2 = Plugin.TriggerStrength.Value;
			if (!flag2 || flag4)
			{
				Trig.Resist(fb.RightTrig, 0, (int)(255f * Mathf.Min(1f, value2)));
				Trig.Resist(fb.LeftTrig, 0, (int)(255f * Mathf.Min(1f, value2)));
			}
		}
		if (flag2 && !flag4)
		{
			GunFeel(val, unscaledTime);
			ToolFeel(val);
		}
		Tests(unscaledTime);
		Finish(target, unscaledDeltaTime, snap);
	}

	internal static void GunFired(GunScript g)
	{
		ShotAt = Time.unscaledTime;
		ShotGun = g;
	}

	private static GunScript HeldGun(Body b)
	{
		try
		{
			Item item = b.GetItem(b.handSlot);
			return ((Object)(object)item != (Object)null) ? ((Component)item).GetComponent<GunScript>() : null;
		}
		catch (Exception)
		{
			return null;
		}
	}

	private void GunFeel(Body b, float now)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Invalid comparison between Unknown and I4
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Invalid comparison between Unknown and I4
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Invalid comparison between Unknown and I4
		//IL_0240: Unknown result type (might be due to invalid IL or missing references)
		GunScript val = HeldGun(b);
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		bool flag = (int)val.firingMode == 2;
		bool flag2 = (int)val.firingMode == 0 || (int)val.ammoType == 2;
		bool flag3 = (int)val.ammoType == 1;
		float num = Mathf.Max(0.05f, val.desiredGasTime);
		float num2 = (flag2 ? 0.2f : (flag3 ? 0.12f : 0.08f));
		if (flag)
		{
			num2 = Mathf.Min(num2, num * 0.5f);
		}
		float num3 = (((Object)(object)ShotGun == (Object)(object)val) ? (now - ShotAt) : 99f);
		if (Plugin.Rumble.Value && num3 < num2 + 0.04f)
		{
			float value = Plugin.RumbleStrength.Value;
			float num4 = (flag2 ? 1f : (flag3 ? 0.7f : 0.45f));
			fb.Low = Mathf.Max(fb.Low, num4 * value);
			fb.High = Mathf.Max(fb.High, num4 * 0.7f * value);
		}
		if (!Plugin.AdaptiveTriggers.Value || !Plugin.GunTriggers.Value)
		{
			return;
		}
		float value2 = Plugin.TriggerStrength.Value;
		if (val.safe)
		{
			Trig.Resist(fb.RightTrig, 0, (int)(255f * Mathf.Min(1f, value2)));
		}
		else if (num3 < num2)
		{
			int frequency = (flag2 ? 15 : (flag3 ? 30 : 40));
			if (flag)
			{
				frequency = Mathf.RoundToInt(Mathf.Clamp(1f / num, 5f, 40f));
			}
			Trig.Vibrate(fb.RightTrig, frequency, (int)((float)((flag2 || flag3) ? 255 : 210) * Mathf.Min(1f, value2)), 0);
		}
		else if (flag && num3 < num * 2.5f && state.RT > 0.3f)
		{
			Trig.Vibrate(fb.RightTrig, Mathf.RoundToInt(Mathf.Clamp(1f / num, 5f, 40f)), (int)(255f * Mathf.Min(1f, value2)), 0);
		}
		else if ((int)val.roundInChamber != 0 || val.racked)
		{
			Trig.Weapon(fb.RightTrig, 40, 80, (int)(45f * value2));
		}
		else if (flag2)
		{
			Trig.Weapon(fb.RightTrig, 70, 150, (int)(255f * value2));
		}
		else if (flag)
		{
			Trig.Weapon(fb.RightTrig, 40, 90, (int)(120f * value2));
		}
		else if (flag3)
		{
			Trig.Weapon(fb.RightTrig, 60, 130, (int)(210f * value2));
		}
		else
		{
			Trig.Weapon(fb.RightTrig, 50, 105, (int)(150f * value2));
		}
	}

	private void ToolFeel(Body b)
	{
		Item item;
		try
		{
			item = b.GetItem(b.handSlot);
		}
		catch (Exception)
		{
			return;
		}
		if ((Object)(object)item == (Object)null || item.id == null)
		{
			return;
		}
		int num = ((item.id == "heavydrill") ? 1 : ((item.id == "plasmacutter") ? 2 : ((item.id == "minilaserdrill") ? 3 : 0)));
		if (num == 0)
		{
			return;
		}
		bool flag = false;
		try
		{
			flag = ((Object)(object)item.battery == (Object)null || item.battery.hasCharge) && item.condition > 0f && b.attackCooldown > -0.1f && state.RT > Plugin.TriggerThreshold.Value;
		}
		catch (Exception)
		{
			flag = false;
		}
		if (!flag)
		{
			return;
		}
		float unscaledTime = Time.unscaledTime;
		if (Plugin.Rumble.Value)
		{
			float value = Plugin.RumbleStrength.Value;
			if (num == 1)
			{
				fb.Low = Mathf.Max(fb.Low, (0.3f + 0.1f * Mathf.Sin(unscaledTime * 40f)) * value);
				fb.High = Mathf.Max(fb.High, 0.15f * value);
			}
			else
			{
				fb.High = Mathf.Max(fb.High, ((num == 2) ? 0.18f : 0.12f) * value);
			}
		}
		if (Plugin.AdaptiveTriggers.Value && Plugin.GunTriggers.Value)
		{
			float num2 = Mathf.Min(1f, Plugin.TriggerStrength.Value);
			switch (num)
			{
			case 1:
				Trig.Vibrate(fb.RightTrig, 22, (int)(255f * num2), 0);
				break;
			case 2:
				Trig.Vibrate(fb.RightTrig, 40, (int)(150f * num2), 0);
				break;
			default:
				Trig.Vibrate(fb.RightTrig, 32, (int)(190f * num2), 0);
				break;
			}
		}
	}

	private void Tests(float now)
	{
		if (now < TestRumbleUntil)
		{
			fb.Low = 0.8f;
			fb.High = 0.6f;
		}
		if (now < TestTriggersUntil)
		{
			Trig.Weapon(fb.RightTrig, 40, 100, 220);
			Trig.Resist(fb.LeftTrig, 20, 170);
		}
	}

	private void Finish(Color target, float dt, bool snap)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//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)
		light = (snap ? target : Color.Lerp(light, target, Mathf.Clamp01(dt * 6f)));
		ShownLight = light;
		fb.R = (byte)(Mathf.Clamp01(light.r) * 255f);
		fb.G = (byte)(Mathf.Clamp01(light.g) * 255f);
		fb.B = (byte)(Mathf.Clamp01(light.b) * 255f);
	}

	private static float Beat(float now)
	{
		float num = Mathf.Repeat(now, 1.1f);
		if (num < 0.1f)
		{
			return 1f;
		}
		if (num > 0.25f && num < 0.33f)
		{
			return 0.7f;
		}
		return 0f;
	}

	private bool Holding(string action)
	{
		for (int i = 0; i < 20; i++)
		{
			if (prev[i] && string.Equals(Plugin.Map[i].Value.Trim(), action, StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
		}
		return false;
	}

	private void Set(int slot, bool down, string action)
	{
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Expected I4, but got Unknown
		//IL_0029: 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_0033: 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_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		if (down == prev[slot])
		{
			return;
		}
		prev[slot] = down;
		if (down)
		{
			KeyCode val = Resolve(action);
			heldWith[slot] = (KeyCode)(int)val;
			if ((int)val != 0)
			{
				holds.TryGetValue(val, out var value);
				holds[val] = value + 1;
				if (value == 0)
				{
					Win.Key(val, down: true);
				}
			}
			return;
		}
		KeyCode val2 = heldWith[slot];
		heldWith[slot] = (KeyCode)0;
		if ((int)val2 != 0)
		{
			holds.TryGetValue(val2, out var value2);
			if (value2 <= 1)
			{
				holds.Remove(val2);
				Win.Key(val2, down: false);
			}
			else
			{
				holds[val2] = value2 - 1;
			}
		}
	}

	private KeyCode Resolve(string action)
	{
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		string text = (action ?? "").Trim().ToLowerInvariant();
		switch (text)
		{
		case "":
		case "none":
		case "precise":
			return (KeyCode)0;
		case "leftclick":
			return (KeyCode)323;
		case "rightclick":
			return (KeyCode)324;
		case "middleclick":
			return (KeyCode)325;
		case "speedcycle":
			cycleStep = ((Time.timeScale <= 1.01f) ? 1 : ((cycleStep == 1) ? 2 : 0));
			return Bind((cycleStep == 0) ? "speed1" : ((cycleStep == 1) ? "speed2" : "speed3"));
		default:
			return Bind(text);
		}
	}

	private static KeyCode Bind(string action)
	{
		//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_000b: 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)
		try
		{
			return KeyBinds.GetBind(action);
		}
		catch (Exception)
		{
			return (KeyCode)0;
		}
	}

	private void ReleaseAll()
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		foreach (KeyValuePair<KeyCode, int> hold in holds)
		{
			Win.Key(hold.Key, down: false);
		}
		holds.Clear();
		for (int i = 0; i < prev.Length; i++)
		{
			prev[i] = false;
			heldWith[i] = (KeyCode)0;
		}
		touchRawPrev = false;
		tapUpAt = -1f;
	}

	private void GuardUI()
	{
		if (!Plugin.BlockUINavigation.Value || Time.unscaledTime < uiCheckAt)
		{
			return;
		}
		uiCheckAt = Time.unscaledTime + 1f;
		try
		{
			StandaloneInputModule[] array = Object.FindObjectsOfType<StandaloneInputModule>();
			foreach (StandaloneInputModule val in array)
			{
				if (!(((BaseInputModule)val).inputOverride is PadSafeInput))
				{
					PadSafeInput padSafeInput = ((Component)val).GetComponent<PadSafeInput>();
					if ((Object)(object)padSafeInput == (Object)null)
					{
						padSafeInput = ((Component)val).gameObject.AddComponent<PadSafeInput>();
					}
					((BaseInputModule)val).inputOverride = (BaseInput)(object)padSafeInput;
				}
			}
		}
		catch (Exception)
		{
		}
	}

	private static bool ForcePause()
	{
		try
		{
			if (!Plugin.PauseOnDisconnect.Value || InMenu() || PauseHandler.paused)
			{
				return false;
			}
			if ((Object)(object)MinigameBase.main != (Object)null && MinigameBase.main.currentMinigame != null)
			{
				return false;
			}
			PauseHandler.TogglePause();
			return PauseHandler.paused;
		}
		catch (Exception)
		{
			return false;
		}
	}

	private void TitleCheck()
	{
		if (Time.unscaledTime < titleLookAt)
		{
			return;
		}
		titleLookAt = Time.unscaledTime + 0.5f;
		PreRunScript val = Object.FindObjectOfType<PreRunScript>();
		if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)lastTitle))
		{
			lastTitle = val;
			preRun = val;
			if (pad != null)
			{
				Show(pad.Name + " connected", (Live != null && Live.Battery >= 0) ? ("Battery about " + Live.Battery + "%") : "", pad.Kind, bad: false, 3f);
			}
		}
	}

	private void Show(string text, string sub, PadKind kind, bool bad, float hold)
	{
		if (Plugin.ShowMessages.Value)
		{
			bannerText = text;
			bannerSub = sub;
			bannerKind = kind;
			bannerBad = bad;
			bannerHold = hold;
			bannerAt = Time.unscaledTime;
		}
	}

	private void DrawBanner()
	{
		//IL_0129: Unknown result type (might be due to invalid IL or missing references)
		//IL_0133: Expected O, but got Unknown
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Expected O, but got Unknown
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Expected O, but got Unknown
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Expected O, but got Unknown
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_022a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0214: Unknown result type (might be due to invalid IL or missing references)
		//IL_022f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0247: Unknown result type (might be due to invalid IL or missing references)
		//IL_0287: Unknown result type (might be due to invalid IL or missing references)
		//IL_0371: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_038e: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0476: Unknown result type (might be due to invalid IL or missing references)
		//IL_040d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0448: Unknown result type (might be due to invalid IL or missing references)
		//IL_048c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0310: Unknown result type (might be due to invalid IL or missing references)
		//IL_0353: Unknown result type (might be due to invalid IL or missing references)
		float num = Time.unscaledTime - bannerAt;
		float num2 = 0.25f;
		float num3 = 1f;
		if (bannerText.Length != 0 && !(num > bannerHold + num3))
		{
			float num4 = ((num < num2) ? (num / num2) : ((num > bannerHold) ? (1f - (num - bannerHold) / num3) : 1f));
			num4 = Mathf.Clamp01(num4);
			float num5 = Mathf.Max(0.6f, (float)Screen.height / 1080f);
			if (bannerStyle == null)
			{
				GUIStyle val = new GUIStyle(GUI.skin.label);
				val.fontStyle = (FontStyle)1;
				val.alignment = (TextAnchor)3;
				val.wordWrap = false;
				bannerStyle = val;
				GUIStyle val2 = new GUIStyle(GUI.skin.label);
				val2.alignment = (TextAnchor)3;
				val2.wordWrap = false;
				bannerSubStyle = val2;
			}
			bannerStyle.fontSize = (int)(22f * num5);
			bannerSubStyle.fontSize = (int)(15f * num5);
			bool flag = bannerSub.Length > 0;
			float num6 = 120f * num5 + Mathf.Max(bannerStyle.CalcSize(new GUIContent(bannerText)).x, flag ? bannerSubStyle.CalcSize(new GUIContent(bannerSub)).x : 0f);
			float num7 = (flag ? 84f : 64f) * num5;
			float num8 = (1f - Mathf.SmoothStep(0f, 1f, Mathf.Clamp01(num / num2))) * 20f * num5;
			Rect val3 = default(Rect);
			((Rect)(ref val3))..ctor(((float)Screen.width - num6) * 0.5f, 26f * num5 - num8, num6, num7);
			Color color = GUI.color;
			GUI.color = new Color(0.06f, 0.06f, 0.08f, 0.88f * num4);
			GUI.DrawTexture(val3, (Texture)(object)Art.Banner, (ScaleMode)0, true);
			Color val4 = (bannerBad ? new Color(1f, 0.42f, 0.4f) : new Color(0.45f, 0.85f, 1f));
			GUI.color = new Color(val4.r, val4.g, val4.b, num4);
			GUI.DrawTexture(new Rect(((Rect)(ref val3)).x + 10f * num5, ((Rect)(ref val3)).y + num7 - 4f * num5, num6 - 20f * num5, 2f * num5), (Texture)(object)Texture2D.whiteTexture);
			string name = ((bannerKind == PadKind.Xbox) ? "ic_xbox" : ((bannerKind == PadKind.DualShock4) ? "ic_ps4" : "ic_ps5"));
			Texture2D val5 = Art.Img(name);
			if ((Object)(object)val5 != (Object)null)
			{
				GUI.color = new Color(bannerBad ? 1f : 0.92f, bannerBad ? 0.55f : 0.92f, bannerBad ? 0.55f : 0.95f, num4);
				GUI.DrawTexture(new Rect(((Rect)(ref val3)).x + 22f * num5, ((Rect)(ref val3)).y + (num7 - 64f * num5) * 0.5f, 64f * num5, 64f * num5), (Texture)(object)val5, (ScaleMode)2, true);
			}
			GUI.color = new Color(1f, 1f, 1f, num4);
			bannerStyle.normal.textColor = (Color)(bannerBad ? new Color(1f, 0.75f, 0.73f) : Color.white);
			bannerSubStyle.normal.textColor = new Color(0.8f, 0.8f, 0.84f);
			float num9 = ((Rect)(ref val3)).x + 100f * num5;
			if (flag)
			{
				GUI.Label(new Rect(num9, ((Rect)(ref val3)).y + 10f * num5, num6 - 110f * num5, 34f * num5), bannerText, bannerStyle);
				GUI.Label(new Rect(num9, ((Rect)(ref val3)).y + 44f * num5, num6 - 110f * num5, 26f * num5), bannerSub, bannerSubStyle);
			}
			else
			{
				GUI.Label(new Rect(num9, ((Rect)(ref val3)).y, num6 - 110f * num5, num7), bannerText, bannerStyle);
			}
			GUI.color = color;
		}
	}

	private void OnGUI()
	{
		try
		{
			ControllerTab.Draw();
		}
		catch (Exception e)
		{
			ControllerTab.Fail(e);
		}
		GUI.depth = -1000;
		DrawWrapHint();
		DrawBanner();
	}

	private void OnApplicationFocus(bool focus)
	{
		if (!focus)
		{
			ReleaseAll();
		}
	}

	private void OnDisable()
	{
		SpeakerOk = false;
		PadSpeaker.StopAll();
		ReleaseAll();
		if (pad != null)
		{
			try
			{
				pad.Close();
			}
			catch (Exception)
			{
			}
			pad = null;
		}
	}
}
internal static class Art
{
	private delegate float Sdf(float x, float y);

	private static readonly Dictionary<string, Texture2D> cache = new Dictionary<string, Texture2D>();

	private static readonly Dictionary<string, Texture2D> imgs = new Dictionary<string, Texture2D>();

	public static Texture2D Banner => Make("banner", 512, 96, (float x, float y) => Box(x, y, 256f, 48f, 254f, 46f, 30f), Color.white, Color.white, 0f);

	public static Texture2D Disc => Make("disc", 64, 64, (float x, float y) => Len(x - 32f, y - 32f) - 30f, Color.white, Color.white, 0f);

	public static Texture2D Ring => Make("ring", 64, 64, (float x, float y) => Mathf.Abs(Len(x - 32f, y - 32f) - 27f) - 3.5f, Color.white, Color.white, 0f);

	public static Texture2D RoundRect => Make("rrect", 128, 72, (float x, float y) => Box(x, y, 64f, 36f, 62f, 34f, 14f), Color.white, Color.white, 0f);

	public static Texture2D Pill => Make("pill", 96, 32, (float x, float y) => Box(x, y, 48f, 16f, 46f, 14f, 14f), Color.white, Color.white, 0f);

	public static Texture2D GTriangle => Make("gtri", 64, 64, (float x, float y) => Mathf.Min(Seg(x, y, 32f, 12f, 54f, 50f), Mathf.Min(Seg(x, y, 54f, 50f, 10f, 50f), Seg(x, y, 10f, 50f, 32f, 12f))) - 4f, Color.white, Color.white, 0f);

	public static Texture2D GCircle => Make("gcir", 64, 64, (float x, float y) => Mathf.Abs(Len(x - 32f, y - 32f) - 18f) - 4f, Color.white, Color.white, 0f);

	public static Texture2D GCross => Make("gx", 64, 64, (float x, float y) => Mathf.Min(Seg(x, y, 15f, 15f, 49f, 49f), Seg(x, y, 49f, 15f, 15f, 49f)) - 4f, Color.white, Color.white, 0f);

	public static Texture2D GSquare => Make("gsq", 64, 64, (float x, float y) => Mathf.Abs(Box(x, y, 32f, 32f, 17f, 17f, 2f)) - 3.5f, Color.white, Color.white, 0f);

	private static float Len(float x, float y)
	{
		return Mathf.Sqrt(x * x + y * y);
	}

	private static float Box(float x, float y, float cx, float cy, float hx, float hy, float r)
	{
		float num = Mathf.Abs(x - cx) - hx + r;
		float num2 = Mathf.Abs(y - cy) - hy + r;
		return Len(Mathf.Max(num, 0f), Mathf.Max(num2, 0f)) + Mathf.Min(Mathf.Max(num, num2), 0f) - r;
	}

	private static float Seg(float x, float y, float ax, float ay, float bx, float by)
	{
		float num = x - ax;
		float num2 = y - ay;
		float num3 = bx - ax;
		float num4 = by - ay;
		float num5 = Mathf.Clamp01((num * num3 + num2 * num4) / (num3 * num3 + num4 * num4));
		return Len(num - num3 * num5, num2 - num4 * num5);
	}

	private static Texture2D Make(string key, int w, int h, Sdf f, Color fill, Color rim, float rimWidth)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Expected O, but got Unknown
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: 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)
		//IL_009b: Unknown resu