Decompiled source of SBG Multiplayer Compatibility v0.1.0

BepInEx/plugins/SbgCompat/SbgCompatBridge.dll

Decompiled 5 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using Eflatun.SceneReference;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mirror;
using Steamworks;
using Steamworks.Data;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SbgCompatBridge")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+bf82a5fe997b7da303e3bd4301f0352040fa3600")]
[assembly: AssemblyProduct("SbgCompatBridge")]
[assembly: AssemblyTitle("SbgCompatBridge")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SbgCompat
{
	public struct StateMessage : NetworkMessage
	{
		public byte Kind;

		public ulong Owner;

		public string Key;

		public string Value;
	}
	[BepInPlugin("local.sbg.compat", "SBG Multiplayer Compatibility", "0.1.0")]
	public sealed class Bridge : BaseUnityPlugin
	{
		private static readonly Dictionary<string, string> Shared = new Dictionary<string, string>();

		private static readonly Dictionary<ulong, Dictionary<string, string>> Members = new Dictionary<ulong, Dictionary<string, string>>();

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

		private static readonly HashSet<int> Peers = new HashSet<int>();

		private static readonly Dictionary<int, ulong> PeerGuids = new Dictionary<int, ulong>();

		private static Bridge instance;

		private static bool serverWasActive;

		private static bool clientWasConnected;

		private static bool welcomed;

		private static NetworkConnectionToServer lastConnection;

		private static ulong session = 1uL;

		private static ulong hostGuid;

		private float nextHello;

		private bool serverRegistered;

		private bool clientRegistered;

		public static bool Ready => LocalGuid != 0L && (NetworkServer.active || welcomed);

		public static ulong LocalGuid => BNetworkManager.LocalPlayerGuidOnServer;

		private void Awake()
		{
			instance = this;
			Writer<StateMessage>.write = delegate(NetworkWriter w, StateMessage m)
			{
				w.WriteByte(m.Kind);
				NetworkWriterExtensions.WriteULong(w, m.Owner);
				NetworkWriterExtensions.WriteString(w, m.Key);
				NetworkWriterExtensions.WriteString(w, m.Value);
			};
			Reader<StateMessage>.read = (NetworkReader r) => new StateMessage
			{
				Kind = r.ReadByte(),
				Owner = NetworkReaderExtensions.ReadULong(r),
				Key = NetworkReaderExtensions.ReadString(r),
				Value = NetworkReaderExtensions.ReadString(r)
			};
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Compatibility bridge 0.1.0 loaded; metadata uses the game's transport.");
		}

		private void Start()
		{
			GameplayAdapters.Install(((BaseUnityPlugin)this).Logger);
		}

		private void Update()
		{
			ObserveSession();
			bool active = NetworkServer.active;
			bool isConnected = NetworkClient.isConnected;
			if (active)
			{
				if (!serverRegistered)
				{
					NetworkServer.RegisterHandler<StateMessage>((Action<NetworkConnectionToClient, StateMessage>)OnServer, true);
					serverRegistered = true;
				}
				hostGuid = BNetworkManager.LocalPlayerGuidOnServer;
				int[] array = Peers.Where((int id) => !NetworkServer.connections.ContainsKey(id)).ToArray();
				foreach (int num2 in array)
				{
					Peers.Remove(num2);
					if (PeerGuids.TryGetValue(num2, out var value))
					{
						Members.Remove(value);
						PeerGuids.Remove(num2);
						Broadcast(new StateMessage
						{
							Kind = 4,
							Owner = value,
							Key = "sbgcompat",
							Value = "1"
						});
					}
				}
			}
			if (!isConnected)
			{
				return;
			}
			if (!clientRegistered)
			{
				NetworkClient.RegisterHandler<StateMessage>((Action<StateMessage>)OnClient, true);
				clientRegistered = true;
			}
			if (!active && !welcomed && Time.unscaledTime >= nextHello && ((NetworkConnection)NetworkClient.connection).isAuthenticated)
			{
				nextHello = Time.unscaledTime + 2f;
				NetworkClient.Send<StateMessage>(new StateMessage
				{
					Kind = 0,
					Key = "sbgcompat",
					Value = "1"
				}, 0);
			}
			if (LocalGuid != 0L && (active || welcomed) && Pending.Count > 0)
			{
				KeyValuePair<string, string>[] array2 = Pending.ToArray();
				Pending.Clear();
				KeyValuePair<string, string>[] array3 = array2;
				for (int num3 = 0; num3 < array3.Length; num3++)
				{
					KeyValuePair<string, string> keyValuePair = array3[num3];
					WriteMember(keyValuePair.Key, keyValuePair.Value);
				}
			}
		}

		private static void ObserveSession()
		{
			bool active = NetworkServer.active;
			bool isConnected = NetworkClient.isConnected;
			if (active != serverWasActive || isConnected != clientWasConnected || lastConnection != NetworkClient.connection)
			{
				if (!active)
				{
					instance.serverRegistered = false;
				}
				if (!isConnected || lastConnection != NetworkClient.connection)
				{
					instance.clientRegistered = false;
				}
				if (!active || !serverWasActive)
				{
					Shared.Clear();
					Members.Clear();
					Pending.Clear();
					Peers.Clear();
					PeerGuids.Clear();
					hostGuid = 0uL;
					welcomed = false;
					session++;
				}
				serverWasActive = active;
				clientWasConnected = isConnected;
				lastConnection = NetworkClient.connection;
				instance.nextHello = 0f;
			}
		}

		private static bool ValidKey(string key)
		{
			return key != null && key.Length <= 64 && (key.StartsWith("holebuffs", StringComparison.Ordinal) || key.StartsWith("hb_", StringComparison.Ordinal) || key.StartsWith("chaosmod", StringComparison.Ordinal));
		}

		private static bool Valid(StateMessage m)
		{
			return ValidKey(m.Key) && m.Value != null && m.Value.Length <= 12000;
		}

		public static CourseData[] GetCourses(CourseCollection courses)
		{
			return courses?.Courses?.ToArray();
		}

		public static float GetCharacterScale(PlayerMovement movement)
		{
			return movement.NetworkcharacterScale;
		}

		public static bool ObjectEquals(object a, object b)
		{
			if (a is Object || b is Object)
			{
				return (Object)((a is Object) ? a : null) == (Object)((b is Object) ? b : null);
			}
			return a == b;
		}

		public static bool ObjectNotEquals(object a, object b)
		{
			return !ObjectEquals(a, b);
		}

		private static void OnServer(NetworkConnectionToClient connection, StateMessage message)
		{
			ulong num = default(ulong);
			if (connection == null || !((NetworkConnection)connection).isAuthenticated || (Object)(object)BNetworkManager.singleton == (Object)null || !BNetworkManager.singleton.ServerTryGetPlayerGuidFromConnection(connection, ref num))
			{
				return;
			}
			if (message.Kind == 0 && message.Key == "sbgcompat" && message.Value == "1")
			{
				if (!Peers.Add(connection.connectionId))
				{
					return;
				}
				PeerGuids[connection.connectionId] = num;
				foreach (KeyValuePair<string, string> item in Shared)
				{
					((NetworkConnection)connection).Send<StateMessage>(new StateMessage
					{
						Kind = 1,
						Key = item.Key,
						Value = item.Value
					}, 0);
				}
				foreach (KeyValuePair<ulong, Dictionary<string, string>> member in Members)
				{
					foreach (KeyValuePair<string, string> item2 in member.Value)
					{
						((NetworkConnection)connection).Send<StateMessage>(new StateMessage
						{
							Kind = 2,
							Owner = member.Key,
							Key = item2.Key,
							Value = item2.Value
						}, 0);
					}
				}
				((NetworkConnection)connection).Send<StateMessage>(new StateMessage
				{
					Kind = 3,
					Owner = hostGuid,
					Key = "sbgcompat",
					Value = "1"
				}, 0);
				((BaseUnityPlugin)instance).Logger.LogInfo((object)("Compatibility client synchronized on connection " + connection.connectionId));
			}
			else if (message.Kind == 2 && Peers.Contains(connection.connectionId) && Valid(message))
			{
				message.Owner = num;
				if (StoreMember(message))
				{
					Broadcast(message);
				}
			}
		}

		private static void OnClient(StateMessage message)
		{
			if (NetworkServer.active)
			{
				return;
			}
			if (message.Kind == 3 && message.Key == "sbgcompat" && message.Value == "1")
			{
				welcomed = true;
				hostGuid = message.Owner;
				((BaseUnityPlugin)instance).Logger.LogInfo((object)"Compatibility host snapshot received.");
			}
			else if (message.Kind == 4 && message.Key == "sbgcompat" && message.Value == "1")
			{
				Members.Remove(message.Owner);
			}
			else if (Valid(message))
			{
				if (message.Kind == 1)
				{
					Shared[message.Key] = message.Value;
				}
				else if (message.Kind == 2)
				{
					StoreMember(message);
				}
			}
		}

		private static bool StoreMember(StateMessage m)
		{
			if (!Members.TryGetValue(m.Owner, out var value))
			{
				value = (Members[m.Owner] = new Dictionary<string, string>());
			}
			if (value.TryGetValue(m.Key, out var value2) && value2 == m.Value)
			{
				return false;
			}
			if (value.Count >= 128 && !value.ContainsKey(m.Key))
			{
				return false;
			}
			value[m.Key] = m.Value;
			return true;
		}

		private static void Broadcast(StateMessage message)
		{
			int[] array = Peers.ToArray();
			foreach (int key in array)
			{
				if (NetworkServer.connections.TryGetValue(key, out var value) && ((NetworkConnection)value).isAuthenticated)
				{
					((NetworkConnection)value).Send<StateMessage>(message, 0);
				}
			}
		}

		public static Lobby? CurrentLobby()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			ObserveSession();
			return (NetworkServer.active || (NetworkClient.isConnected && LocalGuid != 0L)) ? new Lobby?(new Lobby(SteamId.op_Implicit(session))) : ((Lobby?)null);
		}

		public static bool TryGetLobby(out Lobby lobby)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			lobby = new Lobby(SteamId.op_Implicit(session));
			return CurrentLobby().HasValue;
		}

		public static bool IsValid()
		{
			return CurrentLobby().HasValue;
		}

		public static SteamId GetLocalId()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return SteamId.op_Implicit(LocalGuid);
		}

		public static Friend GetOwner(ref Lobby lobby)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			return new Friend(SteamId.op_Implicit((hostGuid == 0L) ? ulong.MaxValue : hostGuid));
		}

		public static IEnumerable<Friend> GetMembers(ref Lobby lobby)
		{
			return (from p in Object.FindObjectsByType<PlayerId>((FindObjectsSortMode)0)
				where p.Guid != 0
				select p).Select((Func<PlayerId, Friend>)((PlayerId p) => new Friend(SteamId.op_Implicit(p.Guid)))).ToArray();
		}

		public static string GetName(ref Friend friend)
		{
			ulong guid = friend.Id.Value;
			PlayerId? obj = ((IEnumerable<PlayerId>)Object.FindObjectsByType<PlayerId>((FindObjectsSortMode)0)).FirstOrDefault((Func<PlayerId, bool>)((PlayerId p) => p.Guid == guid));
			return ((obj != null) ? obj.PlayerNameNoRichText : null) ?? "Player";
		}

		public static string GetData(ref Lobby lobby, string key)
		{
			string value;
			return Shared.TryGetValue(key, out value) ? value : "";
		}

		public static bool SetData(ref Lobby lobby, string key, string value)
		{
			StateMessage stateMessage = new StateMessage
			{
				Kind = 1,
				Key = key,
				Value = (value ?? "")
			};
			if (!NetworkServer.active || !Valid(stateMessage))
			{
				return false;
			}
			if (Shared.TryGetValue(key, out var value2) && value2 == stateMessage.Value)
			{
				return true;
			}
			if (Shared.Count >= 128 && !Shared.ContainsKey(key))
			{
				return false;
			}
			Shared[key] = stateMessage.Value;
			Broadcast(stateMessage);
			return true;
		}

		public static string GetMemberData(ref Lobby lobby, Friend member, string key)
		{
			//IL_0005: 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)
			Dictionary<string, string> value;
			string value2;
			return (Members.TryGetValue(member.Id.Value, out value) && value.TryGetValue(key, out value2)) ? value2 : "";
		}

		public static void SetMemberData(ref Lobby lobby, string key, string value)
		{
			WriteMember(key, value ?? "");
		}

		private static void WriteMember(string key, string value)
		{
			StateMessage stateMessage = new StateMessage
			{
				Kind = 2,
				Owner = LocalGuid,
				Key = key,
				Value = value
			};
			if (!Valid(stateMessage))
			{
				return;
			}
			if (LocalGuid == 0L || (!NetworkServer.active && !welcomed))
			{
				Pending[key] = value;
			}
			else if (StoreMember(stateMessage))
			{
				if (NetworkServer.active)
				{
					Broadcast(stateMessage);
				}
				else if (NetworkClient.isConnected)
				{
					NetworkClient.Send<StateMessage>(stateMessage, 0);
				}
			}
		}
	}
	internal static class GameplayAdapters
	{
		private static MethodInfo oldSwing;

		private static MethodInfo canHit;

		private static MethodInfo buffMultiplier;

		private static long swingSequence;

		private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;

		public static void Install(ManualLogSource log)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Expected O, but got Unknown
			Type type = Type.GetType("HoleBuffs.SwingPowerPatch, HoleBuffs");
			if (!(type == null))
			{
				oldSwing = AccessTools.Method(type, "Prefix", (Type[])null, (Type[])null);
				canHit = AccessTools.Method(typeof(Hittable), "IsHittableBySwing", (Type[])null, (Type[])null);
				buffMultiplier = AccessTools.Method(type.Assembly.GetType("HoleBuffs.BuffSync"), "MultFor", (Type[])null, (Type[])null);
				Harmony val = new Harmony("local.sbg.compat.gameplay");
				val.Patch((MethodBase)AccessTools.Method(typeof(Hittable), "HitWithGolfSwing", (Type[])null, (Type[])null), new HarmonyMethod(typeof(GameplayAdapters), "BeforeSwing", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method(typeof(Hittable), "HitWithGolfSwingInternal", (Type[])null, (Type[])null), new HarmonyMethod(typeof(GameplayAdapters), "ApplyPower", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method(typeof(GolfCartMovement), "ApplySteering", (Type[])null, (Type[])null), new HarmonyMethod(typeof(GameplayAdapters), "ApplyGrip", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				log.LogInfo((object)"HoleBuffs authoritative swing and steering adapters installed.");
			}
		}

		private static bool BeforeSwing(Hittable __instance, PlayerGolfer hitter, SwingType swingType, bool isForcedFumble, ref float sideSpin)
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: 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_00e5: Unknown result type (might be due to invalid IL or missing references)
			if (!Bridge.Ready)
			{
				return false;
			}
			if ((Object)(object)hitter == (Object)null || !((NetworkBehaviour)hitter).isLocalPlayer || !(bool)canHit.Invoke(__instance, new object[1] { hitter }))
			{
				return true;
			}
			float num = hitter.CalculateSwingReleaseNormalizedPower(swingType, isForcedFumble);
			object[] array = new object[5] { __instance, hitter, swingType, num, sideSpin };
			oldSwing.Invoke(null, array);
			float num2 = (float)array[3];
			sideSpin = (float)array[4];
			float num3 = ((num > 1E-05f) ? (num2 / num) : 1f);
			Lobby? val = Bridge.CurrentLobby();
			if (!val.HasValue)
			{
				return false;
			}
			Lobby lobby = val.Value;
			Bridge.SetMemberData(ref lobby, "hb_swing", string.Join("|", (++swingSequence).ToString(Inv), ((NetworkBehaviour)__instance).netId.ToString(Inv), num3.ToString("R", Inv), NetworkTime.time.ToString("R", Inv)));
			return true;
		}

		private static void ApplyPower(Hittable __instance, PlayerGolfer hitter, ref float power)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)hitter == (Object)null || (Object)(object)hitter.PlayerInfo == (Object)null || (Object)(object)hitter.PlayerInfo.PlayerId == (Object)null)
			{
				return;
			}
			Lobby? val = Bridge.CurrentLobby();
			if (val.HasValue)
			{
				Lobby lobby = val.Value;
				Friend member = default(Friend);
				((Friend)(ref member))..ctor(SteamId.op_Implicit(hitter.PlayerInfo.PlayerId.Guid));
				string[] array = Bridge.GetMemberData(ref lobby, member, "hb_swing").Split('|');
				if (array.Length == 4 && uint.TryParse(array[1], out var result) && result == ((NetworkBehaviour)__instance).netId && float.TryParse(array[2], NumberStyles.Float, Inv, out var result2) && !float.IsNaN(result2) && !float.IsInfinity(result2) && double.TryParse(array[3], NumberStyles.Float, Inv, out var result3) && !(Math.Abs(NetworkTime.time - result3) > 3.0))
				{
					power *= Mathf.Clamp(result2, 0f, 100f);
				}
			}
		}

		private static void ApplyGrip(GolfCartMovement __instance, ref float steering)
		{
			PlayerInfo val = default(PlayerInfo);
			if (!((Object)(object)__instance.GolfCartInfo == (Object)null) && __instance.GolfCartInfo.TryGetDriver(ref val))
			{
				float num = (float)buffMultiplier.Invoke(null, new object[2] { val, "g_grip" });
				steering *= num;
			}
		}
	}
	public static class MinigameAdapter
	{
		public static IEnumerable<CodeInstruction> Rewrite(IEnumerable<CodeInstruction> instructions)
		{
			Type minigames = Type.GetType("HoleBuffs.Minigames, HoleBuffs", throwOnError: true);
			MethodInfo getter = AccessTools.PropertyGetter(typeof(SceneReference), "Guid");
			MethodInfo setNext = AccessTools.Method(typeof(ServerPersistentCourseData), "SetNextHoleIndex", (Type[])null, (Type[])null);
			bool scene = false;
			bool index = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.Calls(instruction, setNext))
				{
					instruction.operand = AccessTools.Method(minigames, "SetNextHoleIndex", (Type[])null, (Type[])null);
					index = true;
				}
				yield return instruction;
				if (CodeInstructionExtensions.Calls(instruction, getter))
				{
					yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(MinigameAdapter), "SceneForAddress", (Type[])null, (Type[])null));
					scene = true;
				}
			}
			if (!scene || !index)
			{
				throw new InvalidOperationException("Next-hole adapter no longer matches the game.");
			}
		}

		public static string SceneForAddress(string address)
		{
			List<HoleData> allHoles = GameManager.AllCourses.allHoles;
			HoleData val = ((IEnumerable<HoleData>)allHoles).FirstOrDefault((Func<HoleData, bool>)((HoleData h) => h.Scene.Guid == address));
			if ((Object)(object)val == (Object)null)
			{
				return address;
			}
			string selected = (string)AccessTools.Method(Type.GetType("HoleBuffs.Minigames, HoleBuffs", throwOnError: true), "SceneFor", (Type[])null, (Type[])null).Invoke(null, new object[1] { val.Scene.Name });
			HoleData val2 = ((IEnumerable<HoleData>)allHoles).FirstOrDefault((Func<HoleData, bool>)((HoleData h) => h.Scene.Name == selected));
			if ((Object)(object)val2 == (Object)null)
			{
				throw new InvalidOperationException("Unknown minigame scene: " + selected);
			}
			return val2.Scene.Guid;
		}
	}
}

BepInEx/patchers/SbgCompat/SbgCompatInstaller.dll

Decompiled 5 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using BepInEx;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SbgCompatInstaller")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+3857b65dcd0e8968185cbfd1b8fe857a48fd236b")]
[assembly: AssemblyProduct("SbgCompatInstaller")]
[assembly: AssemblyTitle("SbgCompatInstaller")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SbgCompatInstaller
{
	public static class Installer
	{
		public static IEnumerable<string> TargetDLLs => Array.Empty<string>();

		public static void Patch(AssemblyDefinition unused)
		{
		}

		private static string Hash(string path)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(File.ReadAllBytes(path))).Replace("-", "").ToLowerInvariant();
		}

		public static void Initialize()
		{
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Expected O, but got Unknown
			ManualLogSource val = Logger.CreateLogSource("SBG Compatibility Installer");
			try
			{
				if (Hash(Path.Combine(Paths.ManagedPath, "GameAssembly.dll")) != "ad5ba51a758b86f59c604a48a0124a5bf82b72fa395fa99184227305a612cad9")
				{
					throw new Exception("Unsupported game build; compatibility update required");
				}
				string[] files = Directory.GetFiles(Paths.PluginPath, "SbgCompatBridge.dll", SearchOption.AllDirectories);
				if (files.Length != 1)
				{
					throw new Exception("Install exactly one SbgCompatBridge.dll");
				}
				string[] array = new string[3] { "HoleBuffs.dll", "SuperBattleGolfChaosMod.dll", "com.github.LyricLy.BetterDistanceEstimation.dll" };
				List<(string, string, string)> list = new List<(string, string, string)>();
				string text = Path.Combine(Paths.BepInExRootPath, "sbgcompat-backups");
				Directory.CreateDirectory(text);
				string[] array2 = array;
				foreach (string text2 in array2)
				{
					string[] files2 = Directory.GetFiles(Paths.PluginPath, text2, SearchOption.AllDirectories);
					if (files2.Length != 1)
					{
						throw new Exception("Expected exactly one installed " + text2 + ", found " + files2.Length);
					}
					string text3 = files2[0];
					string text4 = Hash(text3);
					string text5 = Path.Combine(text, text4 + "-" + text2);
					AssemblyDefinition val2 = AssemblyDefinition.ReadAssembly(text3);
					try
					{
						if (((IEnumerable<Resource>)val2.MainModule.Resources).Any((Resource r) => r.Name == "SbgCompat.Applied.0.1.0"))
						{
							val.LogInfo((object)(text2 + " already patched"));
							continue;
						}
					}
					finally
					{
						((IDisposable)val2)?.Dispose();
					}
					if (!File.Exists(text5))
					{
						File.Copy(text3, text5);
					}
					if (Hash(text5) != text4)
					{
						throw new Exception("Backup hash mismatch: " + text2);
					}
					string text6 = Path.Combine(text, Guid.NewGuid().ToString("N") + "-" + text2);
					PatchEngine.Apply(new string[3]
					{
						text5,
						files[0],
						text6
					}, Paths.ManagedPath, Path.GetDirectoryName(typeof(Paths).Assembly.Location));
					AssemblyDefinition val3 = AssemblyDefinition.ReadAssembly(text6);
					try
					{
						val3.MainModule.Resources.Add((Resource)new EmbeddedResource("SbgCompat.Applied.0.1.0", (ManifestResourceAttributes)2, new byte[1] { 1 }));
						val3.Write(text6 + ".ready");
					}
					finally
					{
						((IDisposable)val3)?.Dispose();
					}
					list.Add((text3, text6 + ".ready", text5));
				}
				try
				{
					foreach (var item in list)
					{
						File.Copy(item.Item2, item.Item1, overwrite: true);
						val.LogInfo((object)("Patched " + Path.GetFileName(item.Item1)));
					}
				}
				catch
				{
					foreach (var item2 in list)
					{
						File.Copy(item2.Item3, item2.Item1, overwrite: true);
					}
					throw;
				}
				val.LogInfo((object)("Compatibility installation complete. Original mod backups: " + text));
			}
			catch (Exception ex)
			{
				val.LogError((object)("Compatibility installation failed; do not start a multiplayer match: " + ex));
				throw;
			}
		}
	}
	public static class PatchEngine
	{
		private static IEnumerable<TypeDefinition> AllTypes(IEnumerable<TypeDefinition> types)
		{
			return types.SelectMany((TypeDefinition t) => ((IEnumerable<TypeDefinition>)(object)new TypeDefinition[1] { t }).Concat(AllTypes((IEnumerable<TypeDefinition>)t.NestedTypes)));
		}

		public static void Apply(string[] args, string gameDir, string coreDir)
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_09b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_09be: Unknown result type (might be due to invalid IL or missing references)
			//IL_09cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_09d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d3f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0741: Unknown result type (might be due to invalid IL or missing references)
			//IL_074b: Expected O, but got Unknown
			//IL_075c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0769: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_07bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_088f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0894: Unknown result type (might be due to invalid IL or missing references)
			//IL_0838: Unknown result type (might be due to invalid IL or missing references)
			//IL_0842: Expected O, but got Unknown
			//IL_0853: Unknown result type (might be due to invalid IL or missing references)
			//IL_086c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f08: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f0f: Expected O, but got Unknown
			//IL_0f30: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f6a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0559: Unknown result type (might be due to invalid IL or missing references)
			//IL_055e: Unknown result type (might be due to invalid IL or missing references)
			//IL_059f: Unknown result type (might be due to invalid IL or missing references)
			if (args.Length != 3)
			{
				throw new ArgumentException("usage: patcher original.dll bridge.dll output.dll");
			}
			HashSet<string> hashSet = new HashSet<string> { "f408025c6d372d25d89c1cc16a41bd3fed259f2986b0dae803c1f8359bca0780", "2cf4dff60ae0f07a3567c76f3c9a15817d127006b3d5e1eba3a5d525e66f1ad0", "e8ba53afb501988116c6a76f2c7672037e4f0ef2ccbde823b3a3cf4c15ed16b2" };
			if (!hashSet.Contains(Hash(args[0])))
			{
				throw new Exception("Unsupported or already patched mod; expected a pinned original DLL");
			}
			if (Hash(Path.Combine(gameDir, "GameAssembly.dll")) != "ad5ba51a758b86f59c604a48a0124a5bf82b72fa395fa99184227305a612cad9")
			{
				throw new Exception("Unsupported game assembly; re-audit this repair for the new game build");
			}
			DefaultAssemblyResolver val = new DefaultAssemblyResolver();
			((BaseAssemblyResolver)val).AddSearchDirectory(gameDir);
			((BaseAssemblyResolver)val).AddSearchDirectory(coreDir);
			AssemblyDefinition mod = AssemblyDefinition.ReadAssembly(args[0], new ReaderParameters
			{
				AssemblyResolver = (IAssemblyResolver)(object)val
			});
			TypeDefinition bridgeType;
			try
			{
				if (((AssemblyNameReference)mod.Name).Name == "com.github.LyricLy.BetterDistanceEstimation")
				{
					AssemblyDefinition val2 = AssemblyDefinition.ReadAssembly(Path.Combine(gameDir, "GameAssembly.dll"));
					try
					{
						string name = ((MemberReference)((IEnumerable<MethodDefinition>)val2.MainModule.GetType("PlayerGolfer").Methods).Single((MethodDefinition m) => ((MemberReference)m).Name.StartsWith("<OnBUpdate>g__UpdateHoleDistanceEstimationForOwnBall|"))).Name;
						int num = 0;
						foreach (TypeDefinition item in AllTypes((IEnumerable<TypeDefinition>)mod.MainModule.Types))
						{
							foreach (MethodDefinition item2 in ((IEnumerable<MethodDefinition>)item.Methods).Where((MethodDefinition m) => m.HasBody))
							{
								Enumerator<Instruction> enumerator3 = item2.Body.Instructions.GetEnumerator();
								try
								{
									while (enumerator3.MoveNext())
									{
										Instruction current3 = enumerator3.Current;
										if (current3.OpCode == OpCodes.Ldstr && current3.Operand is string text && text == "<OnBUpdate>g__UpdateHoleDistanceEstimationForOwnBall|184_4")
										{
											current3.Operand = name;
											num++;
										}
									}
								}
								finally
								{
									((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose();
								}
							}
						}
						if (num != 2)
						{
							throw new Exception("Unexpected BetterDistance hook layout");
						}
						mod.Write(args[2]);
						Console.WriteLine("Patched BetterDistanceEstimation: " + num + " hook references -> " + name);
						return;
					}
					finally
					{
						((IDisposable)val2)?.Dispose();
					}
				}
				if (((AssemblyNameReference)mod.Name).Name != "HoleBuffs" && ((AssemblyNameReference)mod.Name).Name != "SuperBattleGolfChaosMod")
				{
					throw new Exception("Unexpected input assembly");
				}
				AssemblyDefinition val3 = AssemblyDefinition.ReadAssembly(args[1]);
				try
				{
					bridgeType = val3.MainModule.GetType("SbgCompat.Bridge");
					int num2 = 0;
					int num3 = 0;
					HashSet<string> hashSet2 = new HashSet<string>();
					foreach (TypeDefinition item3 in All((IEnumerable<TypeDefinition>)mod.MainModule.Types))
					{
						if (((MemberReference)item3).FullName == "HoleBuffs.SwingPowerPatch" || ((MemberReference)item3).FullName == "HoleBuffs.SteeringPatch")
						{
							CustomAttribute[] array = ((IEnumerable<CustomAttribute>)item3.CustomAttributes).Where((CustomAttribute a) => ((MemberReference)a.AttributeType).Name == "HarmonyPatch").ToArray();
							foreach (CustomAttribute val4 in array)
							{
								item3.CustomAttributes.Remove(val4);
							}
						}
						foreach (CustomAttribute item4 in ((IEnumerable<CustomAttribute>)item3.CustomAttributes).Where((CustomAttribute a) => ((MemberReference)a.AttributeType).Name == "HarmonyPatch"))
						{
							TypeReference val5 = ((IEnumerable<CustomAttributeArgument>)item4.ConstructorArguments).Select((CustomAttributeArgument a) => ((CustomAttributeArgument)(ref a)).Value).OfType<TypeReference>().FirstOrDefault();
							string targetName = (from a in (IEnumerable<CustomAttributeArgument>)item4.ConstructorArguments
								where ((MemberReference)((CustomAttributeArgument)(ref a)).Type).FullName == "System.String"
								select ((CustomAttributeArgument)(ref a)).Value as string).FirstOrDefault();
							object obj;
							if (val5 == null)
							{
								obj = null;
							}
							else
							{
								IMetadataScope scope = val5.Scope;
								obj = ((scope != null) ? scope.Name : null);
							}
							if ((string?)obj != "GameAssembly" || targetName == null)
							{
								continue;
							}
							if ((((MemberReference)val5).Name == "WorldspaceIconUi" || ((MemberReference)val5).Name == "NameTagUi") && targetName == "LateUpdate")
							{
								for (int num5 = 0; num5 < item4.ConstructorArguments.Count; num5++)
								{
									CustomAttributeArgument val6 = item4.ConstructorArguments[num5];
									if (((MemberReference)((CustomAttributeArgument)(ref val6)).Type).FullName == "System.String")
									{
										item4.ConstructorArguments[num5] = new CustomAttributeArgument(mod.MainModule.TypeSystem.String, (object)"OnPostPostLateBUpdate");
									}
								}
								targetName = "OnPostPostLateBUpdate";
							}
							TypeDefinition val7 = val5.Resolve();
							if (val7 == null || ((IEnumerable<MethodDefinition>)val7.Methods).Any((MethodDefinition m) => ((MemberReference)m).Name == targetName) || ((IEnumerable<PropertyDefinition>)val7.Properties).Any((PropertyDefinition p) => ((MemberReference)p).Name == targetName))
							{
								continue;
							}
							throw new Exception("MISSING HARMONY TARGET: " + ((MemberReference)item3).FullName + ": " + ((MemberReference)val5).FullName + "." + targetName);
						}
					}
					foreach (TypeDefinition item5 in All((IEnumerable<TypeDefinition>)mod.MainModule.Types))
					{
						foreach (MethodDefinition item6 in ((IEnumerable<MethodDefinition>)item5.Methods).Where((MethodDefinition m) => m.HasBody))
						{
							if (((MemberReference)item5).FullName == "HoleBuffs.MinigameStartNextMatchPatch" && ((MemberReference)item6).Name == "Transpiler")
							{
								item6.Body = new MethodBody(item6);
								ILProcessor iLProcessor = item6.Body.GetILProcessor();
								iLProcessor.Emit(OpCodes.Ldarg_0);
								iLProcessor.Emit(OpCodes.Call, mod.MainModule.ImportReference((MethodReference)(object)((IEnumerable<MethodDefinition>)val3.MainModule.GetType("SbgCompat.MinigameAdapter").Methods).Single((MethodDefinition m) => ((MemberReference)m).Name == "Rewrite")));
								iLProcessor.Emit(OpCodes.Ret);
								continue;
							}
							bool flag = ((IEnumerable<Instruction>)item6.Body.Instructions).Any(delegate(Instruction i)
							{
								object operand3 = i.Operand;
								MemberReference val16 = (MemberReference)((operand3 is MemberReference) ? operand3 : null);
								int result;
								if (val16 != null)
								{
									TypeReference declaringType2 = val16.DeclaringType;
									if (!(((declaringType2 != null) ? ((MemberReference)declaringType2).Name : null) == "CourseCollection"))
									{
										MethodReference val17 = (MethodReference)(object)((val16 is MethodReference) ? val16 : null);
										result = ((val17 != null && ((MemberReference)val17.ReturnType).Name == "CourseCollection") ? 1 : 0);
									}
									else
									{
										result = 1;
									}
								}
								else
								{
									result = 0;
								}
								return (byte)result != 0;
							});
							if (((MemberReference)item6).Name == "CurrentLobby" && ((MemberReference)((MethodReference)item6).ReturnType).FullName.Contains("Steamworks.Data.Lobby"))
							{
								item6.Body = new MethodBody(item6);
								ILProcessor iLProcessor2 = item6.Body.GetILProcessor();
								iLProcessor2.Emit(OpCodes.Call, Import("CurrentLobby"));
								iLProcessor2.Emit(OpCodes.Ret);
								num3++;
								continue;
							}
							Enumerator<Instruction> enumerator8 = item6.Body.Instructions.GetEnumerator();
							try
							{
								while (enumerator8.MoveNext())
								{
									Instruction current8 = enumerator8.Current;
									object operand = current8.Operand;
									MemberReference val8 = (MemberReference)((operand is MemberReference) ? operand : null);
									if (val8 != null)
									{
										TypeReference declaringType = val8.DeclaringType;
										object obj2;
										if (declaringType == null)
										{
											obj2 = null;
										}
										else
										{
											IMetadataScope scope2 = declaringType.Scope;
											obj2 = ((scope2 != null) ? scope2.Name : null);
										}
										if ((string?)obj2 == "GameAssembly" && val8.FullName != "CourseData[] CourseCollection::get_Courses()" && val8.FullName != "System.Single PlayerMovement::get_CharacterScale()")
										{
											try
											{
												if (1 == 0)
												{
												}
												MethodReference val9 = (MethodReference)(object)((val8 is MethodReference) ? val8 : null);
												bool flag2;
												if (val9 == null)
												{
													FieldReference val10 = (FieldReference)(object)((val8 is FieldReference) ? val8 : null);
													flag2 = val10 == null || val10.Resolve() != null;
												}
												else
												{
													flag2 = val9.Resolve() != null;
												}
												if (1 == 0)
												{
												}
												if (!flag2)
												{
													hashSet2.Add(val8.FullName);
												}
											}
											catch (Exception ex)
											{
												hashSet2.Add(val8.FullName + ": " + ex.Message);
											}
										}
									}
									object operand2 = current8.Operand;
									MethodReference val11 = (MethodReference)((operand2 is MethodReference) ? operand2 : null);
									if (val11 == null || (current8.OpCode != OpCodes.Call && current8.OpCode != OpCodes.Callvirt))
									{
										continue;
									}
									string fullName = ((MemberReference)((MemberReference)val11).DeclaringType).FullName;
									string name2 = ((MemberReference)val11).Name;
									if (1 == 0)
									{
									}
									string text2;
									switch (fullName)
									{
									case "Steamworks.Data.Lobby":
										switch (name2)
										{
										case "GetData":
											break;
										case "SetData":
											goto IL_0c12;
										case "GetMemberData":
											goto IL_0c1e;
										case "SetMemberData":
											goto IL_0c27;
										case "get_Members":
											goto IL_0c30;
										case "get_Owner":
											goto IL_0c39;
										default:
											goto IL_0c9f;
										}
										text2 = "GetData";
										break;
									case "Steamworks.Friend":
										if (!(name2 == "get_Name"))
										{
											goto IL_0c9f;
										}
										text2 = "GetName";
										break;
									case "Steamworks.SteamClient":
										if (!(name2 == "get_IsValid"))
										{
											if (!(name2 == "get_SteamId"))
											{
												goto IL_0c9f;
											}
											text2 = "GetLocalId";
											break;
										}
										text2 = "IsValid";
										break;
									case "BNetworkManager":
										if (!(name2 == "TryGetSteamLobby"))
										{
											if (!(name2 == "IsSteamLobbyValid"))
											{
												goto IL_0c9f;
											}
											text2 = "IsValid";
											break;
										}
										text2 = "TryGetLobby";
										break;
									case "CourseCollection":
										if (!(name2 == "get_Courses"))
										{
											goto IL_0c9f;
										}
										text2 = "GetCourses";
										break;
									case "PlayerMovement":
										if (!(name2 == "get_CharacterScale"))
										{
											goto IL_0c9f;
										}
										text2 = "GetCharacterScale";
										break;
									case "UnityEngine.Object":
										if (!(name2 == "op_Equality"))
										{
											if (name2 == "op_Inequality" && flag)
											{
												text2 = "ObjectNotEquals";
												break;
											}
										}
										else if (flag)
										{
											text2 = "ObjectEquals";
											break;
										}
										goto IL_0c9f;
									default:
										goto IL_0c9f;
										IL_0c9f:
										text2 = null;
										break;
										IL_0c30:
										text2 = "GetMembers";
										break;
										IL_0c1e:
										text2 = "GetMemberData";
										break;
										IL_0c27:
										text2 = "SetMemberData";
										break;
										IL_0c12:
										text2 = "SetData";
										break;
										IL_0c39:
										text2 = "GetOwner";
										break;
									}
									if (1 == 0)
									{
									}
									string text3 = text2;
									if (text3 != null)
									{
										MethodReference val12 = Import(text3);
										if (((MemberReference)val12.ReturnType).FullName != ((MemberReference)val11.ReturnType).FullName || val12.Parameters.Count != val11.Parameters.Count + (val11.HasThis ? 1 : 0))
										{
											throw new Exception("Signature mismatch: " + ((MemberReference)val11).FullName + " -> " + ((MemberReference)val12).FullName);
										}
										current8.OpCode = OpCodes.Call;
										current8.Operand = val12;
										num2++;
									}
								}
							}
							finally
							{
								((IDisposable)enumerator8/*cast due to .constrained prefix*/).Dispose();
							}
						}
					}
					foreach (string item7 in hashSet2.OrderBy((string x) => x))
					{
						Console.WriteLine("MISSING GAME MEMBER: " + item7);
					}
					if (hashSet2.Count != 0)
					{
						throw new Exception("Unresolved game references: " + hashSet2.Count);
					}
					if (num2 < 10)
					{
						throw new Exception("Expected metadata calls not found; input version changed");
					}
					AssemblyDefinition val13 = AssemblyDefinition.ReadAssembly(Path.Combine(coreDir, "BepInEx.dll"));
					try
					{
						TypeDefinition type = val13.MainModule.GetType("BepInEx.BepInDependency");
						MethodDefinition val14 = ((IEnumerable<MethodDefinition>)type.Methods).Single((MethodDefinition m) => m.IsConstructor && ((MethodReference)m).Parameters.Count == 2 && ((MemberReference)((ParameterReference)((MethodReference)m).Parameters[1]).ParameterType).Name == "DependencyFlags");
						foreach (TypeDefinition item8 in ((IEnumerable<TypeDefinition>)mod.MainModule.Types).Where((TypeDefinition t) => ((IEnumerable<CustomAttribute>)t.CustomAttributes).Any((CustomAttribute a) => ((MemberReference)a.AttributeType).Name == "BepInPlugin")))
						{
							CustomAttribute val15 = new CustomAttribute(mod.MainModule.ImportReference((MethodReference)(object)val14));
							val15.ConstructorArguments.Add(new CustomAttributeArgument(mod.MainModule.TypeSystem.String, (object)"local.sbg.compat"));
							val15.ConstructorArguments.Add(new CustomAttributeArgument(mod.MainModule.ImportReference(((ParameterReference)((MethodReference)val14).Parameters[1]).ParameterType), (object)1));
							item8.CustomAttributes.Add(val15);
						}
						Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(args[2])));
						mod.Write(args[2]);
						Console.WriteLine($"Patched {((AssemblyNameReference)mod.Name).Name}: {num2} metadata calls, {num3} lobby accessors. Output: {args[2]}");
					}
					finally
					{
						((IDisposable)val13)?.Dispose();
					}
				}
				finally
				{
					((IDisposable)val3)?.Dispose();
				}
			}
			finally
			{
				if (mod != null)
				{
					((IDisposable)mod).Dispose();
				}
			}
			static IEnumerable<TypeDefinition> All(IEnumerable<TypeDefinition> types)
			{
				return types.SelectMany((TypeDefinition t) => ((IEnumerable<TypeDefinition>)(object)new TypeDefinition[1] { t }).Concat(All((IEnumerable<TypeDefinition>)t.NestedTypes)));
			}
			static string Hash(string path)
			{
				return BitConverter.ToString(SHA256.Create().ComputeHash(File.ReadAllBytes(path))).Replace("-", "").ToLowerInvariant();
			}
			MethodReference Import(string text4)
			{
				return mod.MainModule.ImportReference((MethodReference)(object)((IEnumerable<MethodDefinition>)bridgeType.Methods).Single((MethodDefinition m) => ((MemberReference)m).Name == text4));
			}
		}
	}
}