using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using ExitGames.Client.Photon;
using HarmonyLib;
using InControl;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Bugfixes")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1+c9b03c0ff381adab9c0ba8924ab03e2818cd50b0")]
[assembly: AssemblyProduct("Bugfixes")]
[assembly: AssemblyTitle("Bugfixes")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
internal sealed class NullableAttribute : Attribute
{
public readonly byte[] NullableFlags;
public NullableAttribute(byte P_0)
{
NullableFlags = new byte[1] { P_0 };
}
public NullableAttribute(byte[] P_0)
{
NullableFlags = P_0;
}
}
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
internal sealed class NullableContextAttribute : Attribute
{
public readonly byte Flag;
public NullableContextAttribute(byte P_0)
{
Flag = P_0;
}
}
[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;
}
}
}
internal static class PluginVersion
{
internal const string Value = "1.0.1";
}
namespace RoundsBugfixes.Plugin
{
internal sealed class BugfixesSmoke : MonoBehaviour
{
private const string DemonicPact = "Demonic pact";
private const string Spray = "SPRAY";
private static readonly FieldRef<GunAmmo, int> CurrentAmmo = AccessTools.FieldRefAccess<GunAmmo, int>("currentAmmo");
private Plugin _plugin;
private bool _matchEnded;
private bool _rematchRequested;
private bool _finished;
private int _rematchMapLoads;
private float _lastDamage;
private float _started;
private CharacterSelectionInstance[] _selectors = Array.Empty<CharacterSelectionInstance>();
private bool _initialMenuVerified;
private bool _rematchMenuVerified;
private bool _initialScreenshotRequested;
private bool _initialScreenshotComplete;
private readonly FieldInfo _cards = AccessTools.Field(typeof(CardChoice), "spawnedCards");
private readonly FieldInfo _pickingAnimation = AccessTools.Field(typeof(CardChoice), "isPlaying");
internal static void Install(Harmony harmony)
{
//IL_0076: Unknown result type (might be due to invalid IL or missing references)
//IL_0084: Expected O, but got Unknown
//IL_0163: Unknown result type (might be due to invalid IL or missing references)
//IL_0170: Expected O, but got Unknown
//IL_0199: Unknown result type (might be due to invalid IL or missing references)
//IL_01a6: Expected O, but got Unknown
//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
//IL_01dc: Expected O, but got Unknown
//IL_0205: Unknown result type (might be due to invalid IL or missing references)
//IL_0212: Expected O, but got Unknown
//IL_011e: Unknown result type (might be due to invalid IL or missing references)
//IL_012c: Expected O, but got Unknown
Type type = AccessTools.TypeByName("FriendlyFoe.Platform.PlatformManager");
Type type2 = AccessTools.TypeByName("Steamworks.SteamUserStats");
if (type == null || type2 == null)
{
throw new InvalidOperationException("Cannot suppress account writes for the local smoke test.");
}
string[] array = new string[3] { "UnlockAchievement", "ProgressAchievement", "ClearAchievementsProgress" };
foreach (string text in array)
{
harmony.Patch((MethodBase)AccessTools.Method(type, text, (Type[])null, (Type[])null), new HarmonyMethod(typeof(BugfixesSmoke), "SuppressStats", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
MethodInfo[] methods = type2.GetMethods(BindingFlags.Static | BindingFlags.Public);
foreach (MethodInfo methodInfo in methods)
{
if (methodInfo.ReturnType == typeof(bool) && Array.IndexOf(new string[7] { "SetAchievement", "SetStat", "UpdateAvgRateStat", "ClearAchievement", "ResetAllStats", "StoreStats", "IndicateAchievementProgress" }, methodInfo.Name) >= 0)
{
harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(BugfixesSmoke), "SuppressSteamWrite", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
}
harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GameOver", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(BugfixesSmoke), "OnGameOver", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GameOverRematch", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(BugfixesSmoke), "OnRematchPrompt", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(MapManager), "RPCA_LoadLevel", (Type[])null, (Type[])null), new HarmonyMethod(typeof(BugfixesSmoke), "OnMapLoad", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(CardChoice), "GetRandomCard", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(BugfixesSmoke), "OfferTestCardFirst", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
private static void OfferTestCardFirst(CardChoice __instance, List<GameObject> ___spawnedCards, ref GameObject __result)
{
Plugin? instance = Plugin.Instance;
BugfixesSmoke bugfixesSmoke = ((instance != null) ? ((Component)instance).GetComponent<BugfixesSmoke>() : null);
if (!((Object)(object)bugfixesSmoke == (Object)null) && ___spawnedCards.Count == 0)
{
string name = (bugfixesSmoke._rematchRequested ? "SPRAY" : "Demonic pact");
CardInfo val = Array.Find(__instance.cards, (CardInfo candidate) => ((Object)candidate).name == name);
if ((Object)(object)val != (Object)null)
{
__result = ((Component)val).gameObject;
}
}
}
private static bool SuppressStats()
{
return false;
}
private static bool SuppressSteamWrite(ref bool __result)
{
__result = false;
return false;
}
private IEnumerator Start()
{
_plugin = ((Component)this).GetComponent<Plugin>();
_started = Time.realtimeSinceStartup;
AudioListener.volume = 0f;
while ((Object)(object)MainMenuHandler.instance == (Object)null || (Object)(object)ListMenu.instance == (Object)null || !ListMenu.instance.IsInitialized)
{
yield return null;
}
MainMenuHandler.instance.PlayLocalMultiplayer();
yield return (object)new WaitForSecondsRealtime(0.5f);
while ((Object)(object)GM_ArmsRace.instance == (Object)null || !((Behaviour)GM_ArmsRace.instance).isActiveAndEnabled || !PhotonNetwork.OfflineMode)
{
yield return null;
}
PlayerAssigner.instance.CreatePlayer((InputDevice)null, false);
yield return null;
PlayerAssigner.instance.CreatePlayer((InputDevice)null, false);
yield return null;
if (PlayerManager.instance.players.Count != 2)
{
Fail("local_players_not_created");
yield break;
}
_selectors = ((Component)MainMenuHandler.instance.CharacterSelect).GetComponentsInChildren<CharacterSelectionInstance>();
if (_selectors.Length != 2 || Array.Exists(_selectors, (CharacterSelectionInstance selector) => (Object)(object)selector.currentPlayer == (Object)null || !((Component)selector).gameObject.activeInHierarchy))
{
Fail("local_character_select_not_ready_for_both_players;selectors=" + _selectors.Length + ";joined=" + Array.FindAll(_selectors, (CharacterSelectionInstance selector) => (Object)(object)selector.currentPlayer != (Object)null).Length);
yield break;
}
CharacterSelectionInstance[] selectors = _selectors;
for (int num = 0; num < selectors.Length; num++)
{
selectors[num].ReadyUp();
}
yield return null;
if (!CharacterMenuClosed())
{
Fail("character_select_still_visible_after_ready");
}
else
{
_plugin.WriteTrace("bugfixes_local_started", "offline;two_local_players;normal_rules;stat_writes_suppressed");
}
}
private void Update()
{
//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)_plugin == (Object)null || _finished)
{
return;
}
if (Time.realtimeSinceStartup - _started > 300f)
{
Fail("timeout");
return;
}
GM_ArmsRace instance = GM_ArmsRace.instance;
PlayerManager instance2 = PlayerManager.instance;
if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || !((Behaviour)instance).isActiveAndEnabled)
{
return;
}
if (GameManager.instance.isPlaying)
{
if (!CharacterMenuClosed())
{
Fail("join_or_face_selection_visible_during_match");
return;
}
if (!_rematchRequested && !_initialMenuVerified)
{
_initialMenuVerified = true;
_plugin.WriteTrace("bugfixes_local_menu_closed", "stage=initial;normal_ready_path;no_join_or_face_selection");
}
if (_rematchRequested && !_rematchMenuVerified)
{
_rematchMenuVerified = true;
_plugin.WriteTrace("bugfixes_local_menu_closed", "stage=rematch;no_join_or_face_selection");
}
}
CardChoice instance3 = CardChoice.instance;
if ((Object)(object)instance3 != (Object)null && instance3.IsPicking && instance3.pickrID >= 0 && !(bool)_pickingAnimation.GetValue(instance3))
{
if (_rematchRequested && !PromptClosed())
{
Fail("rematch_prompt_visible_during_pick");
return;
}
List<GameObject> list = (List<GameObject>)_cards.GetValue(instance3);
if (list.Count > 0)
{
_plugin.WriteTrace("bugfixes_local_card_picked", "player=" + instance3.pickrID);
instance3.Pick(list[0], false);
instance3.pickrID = -1;
}
}
if ((Object)(object)GameManager.instance == (Object)null || !GameManager.instance.battleOngoing)
{
return;
}
if (!_initialScreenshotRequested)
{
_initialScreenshotRequested = true;
((MonoBehaviour)this).StartCoroutine(CaptureBattle("initial"));
}
else
{
if (!_initialScreenshotComplete)
{
return;
}
if (_rematchRequested)
{
_finished = true;
((MonoBehaviour)this).StartCoroutine(CheckStableRematch(instance));
}
else if (!_matchEnded && !(Time.realtimeSinceStartup - _lastDamage < 2f))
{
Player val = instance2.players.Find((Player player) => player.TeamID == 1);
Player val2 = instance2.players.Find((Player player) => player.TeamID == 0);
if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null) && !val.data.dead && val.data.isPlaying)
{
_lastDamage = Time.realtimeSinceStartup;
((Damagable)val.data.healthHandler).CallTakeDamage(new Vector2(0f, 1E+09f), Vector2.op_Implicit(((Component)val).transform.position), (GameObject)null, val2, true, (DamageSource)1);
}
}
}
}
private static void OnGameOver(GM_ArmsRace __instance, int winningTeamID)
{
Plugin? instance = Plugin.Instance;
BugfixesSmoke bugfixesSmoke = ((instance != null) ? ((Component)instance).GetComponent<BugfixesSmoke>() : null);
if (!((Object)(object)bugfixesSmoke == (Object)null))
{
if (__instance.roundsToWinGame != 5 || winningTeamID != 0 || __instance.p1Rounds != 5)
{
bugfixesSmoke.Fail("unexpected_match_result");
return;
}
bugfixesSmoke._matchEnded = true;
bugfixesSmoke._plugin.WriteTrace("bugfixes_local_match_complete", "winner=0;rounds=5:" + __instance.p2Rounds);
}
}
private static void OnRematchPrompt()
{
Plugin? instance = Plugin.Instance;
BugfixesSmoke bugfixesSmoke = ((instance != null) ? ((Component)instance).GetComponent<BugfixesSmoke>() : null);
if ((Object)(object)bugfixesSmoke != (Object)null && bugfixesSmoke._matchEnded)
{
((MonoBehaviour)bugfixesSmoke).StartCoroutine(bugfixesSmoke.AcceptRematch());
}
}
private IEnumerator AcceptRematch()
{
yield return (object)new WaitForSecondsRealtime(0.75f);
PopUpHandler popUpHandler = UIHandler.instance.popUpHandler;
if (!popUpHandler.isPicking)
{
Fail("rematch_prompt_not_open");
yield break;
}
_rematchRequested = true;
AccessTools.Field(typeof(PopUpHandler), "currentYesNo").SetValue(popUpHandler, (object)(YesNo)0);
AccessTools.Method(typeof(PopUpHandler), "DonePicking", (Type[])null, (Type[])null).Invoke(popUpHandler, null);
if (!PromptClosed())
{
Fail("rematch_prompt_not_closed");
}
}
private static void OnMapLoad()
{
Plugin? instance = Plugin.Instance;
BugfixesSmoke bugfixesSmoke = ((instance != null) ? ((Component)instance).GetComponent<BugfixesSmoke>() : null);
if ((Object)(object)bugfixesSmoke != (Object)null && bugfixesSmoke._matchEnded)
{
bugfixesSmoke._rematchMapLoads++;
}
}
private IEnumerator CheckStableRematch(GM_ArmsRace game)
{
yield return CaptureBattle("rematch");
MapWrapper map = MapManager.instance.currentMap;
float deadline = Time.realtimeSinceStartup + 3f;
while (Time.realtimeSinceStartup < deadline)
{
List<Player> players = PlayerManager.instance.players;
if (GameManager.instance.battleOngoing && MapManager.instance.currentMap == map && map != null)
{
Scene scene = map.Scene;
if (((Scene)(ref scene)).isLoaded && !((Object)(object)map.Map == (Object)null) && map.Map.hasEntered && players.Count == 2 && !players.Exists((Player player) => player.data.dead || !player.data.isPlaying) && PromptClosed() && CharacterMenuClosed() && game.p1Points == 0 && game.p2Points == 0 && game.p1Rounds == 0 && game.p2Rounds == 0 && _rematchMapLoads == 1)
{
yield return null;
continue;
}
}
Fail("rematch_not_stable;map_loads=" + _rematchMapLoads);
yield break;
}
_plugin.WriteTrace("bugfixes_local_smoke_complete", "offline_match;normal_ready_ui;no_join_or_face_selection;card_picks;prompt_closed;one_rematch_map_load;stable_battle");
Application.Quit(0);
}
private static bool PromptClosed()
{
PopUpHandler popUpHandler = UIHandler.instance.popUpHandler;
if (!popUpHandler.isPicking && !popUpHandler.yesPart.loop && !popUpHandler.noPart.loop && !VisibleParticles(popUpHandler.yesPart))
{
return !VisibleParticles(popUpHandler.noPart);
}
return false;
}
private bool CharacterMenuClosed()
{
MainMenuHandler instance = MainMenuHandler.instance;
if ((Object)(object)instance == (Object)null || instance.isOpen || instance.CharacterSelect.IsOpen || _selectors.Length != 2)
{
return false;
}
CharacterSelectionInstance[] selectors = _selectors;
foreach (CharacterSelectionInstance val in selectors)
{
if (((Component)val).gameObject.activeInHierarchy || val.joinObj.activeInHierarchy || val.getReadyObj.activeInHierarchy || ((Component)((Component)val).transform.GetChild(0)).gameObject.activeInHierarchy)
{
return false;
}
}
return true;
}
private IEnumerator CaptureBattle(string stage)
{
float enteredDeadline = Time.realtimeSinceStartup + 10f;
while (true)
{
MapManager instance = MapManager.instance;
int num;
if (instance == null)
{
num = 1;
}
else
{
MapWrapper currentMap = instance.currentMap;
num = ((((currentMap == null) ? ((bool?)null) : currentMap.Map?.hasEntered) != true) ? 1 : 0);
}
if (num == 0 || !(Time.realtimeSinceStartup < enteredDeadline))
{
break;
}
yield return null;
}
MapManager instance2 = MapManager.instance;
int num2;
if (instance2 == null)
{
num2 = 1;
}
else
{
MapWrapper currentMap2 = instance2.currentMap;
num2 = ((((currentMap2 == null) ? ((bool?)null) : currentMap2.Map?.hasEntered) != true) ? 1 : 0);
}
if (num2 != 0)
{
Fail("framebuffer_map_not_entered;stage=" + stage);
yield break;
}
yield return (object)new WaitForSecondsRealtime(1.5f);
MethodInfo methodInfo = Type.GetType("UnityEngine.ScreenCapture, UnityEngine.ScreenCaptureModule")?.GetMethod("CaptureScreenshot", new Type[2]
{
typeof(string),
typeof(int)
});
string text = null;
string[] commandLineArgs = Environment.GetCommandLineArgs();
foreach (string text2 in commandLineArgs)
{
if (text2.StartsWith("--rounds-bugfixes-trace=", StringComparison.Ordinal))
{
text = text2.Substring("--rounds-bugfixes-trace=".Length);
}
}
if (methodInfo == null || text == null)
{
Fail("framebuffer_capture_unavailable");
yield break;
}
string output = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(text)), "local-" + stage + ".png");
methodInfo.Invoke(null, new object[2] { output, 1 });
float deadline = Time.realtimeSinceStartup + 5f;
while ((!File.Exists(output) || new FileInfo(output).Length == 0L) && Time.realtimeSinceStartup < deadline)
{
yield return null;
}
if (!File.Exists(output) || new FileInfo(output).Length == 0L)
{
Fail("framebuffer_capture_missing;stage=" + stage);
yield break;
}
_plugin.WriteTrace("bugfixes_local_screenshot", "stage=" + stage + ";path=" + output);
yield return CheckHeldFire(stage);
}
private IEnumerator CheckHeldFire(string stage)
{
List<Player> players = PlayerManager.instance.players;
Player val = players.Find((Player candidate) => candidate.TeamID == 0);
Player val2 = players.Find((Player candidate) => candidate.TeamID == 1);
bool expectAutofire = stage == "rematch";
string card = (expectAutofire ? "SPRAY" : "Demonic pact");
WeaponHandler weaponHandler = val.data.weaponHandler;
Gun gun = weaponHandler.gun;
GunAmmo ammo = ((Component)gun).GetComponentInChildren<GunAmmo>();
int magazine = CurrentAmmo.Invoke(ammo);
if (!val.data.currentCards.Exists((CardInfo picked) => ((Object)picked).name == card) || magazine != ammo.maxAmmo || magazine < 2 || !gun.IsReady(0f) || gun.isReloading || weaponHandler.isOverHeated)
{
Fail("held_fire_setup_failed;stage=" + stage + ";ammo=" + magazine + "/" + ammo.maxAmmo);
yield break;
}
GeneralInput input = ((Component)val).GetComponent<GeneralInput>();
(bool controlledElseWhere, Vector3 aimDirection, bool shootIsPressed, bool shootWasPressed, bool shootWasReleased) previousInput = (controlledElseWhere: input.controlledElseWhere, aimDirection: input.aimDirection, shootIsPressed: input.shootIsPressed, shootWasPressed: input.shootWasPressed, shootWasReleased: input.shootWasReleased);
int projectiles = 0;
gun.ShootPojectileAction = (Action<GameObject>)Delegate.Combine(gun.ShootPojectileAction, new Action<GameObject>(CountProjectile));
try
{
input.controlledElseWhere = true;
Vector3 val3 = new Vector3(Mathf.Sign(((Component)val).transform.position.x - ((Component)val2).transform.position.x), 1f, 0f);
input.aimDirection = ((Vector3)(ref val3)).normalized;
GeneralInput val4 = input;
GeneralInput val5 = input;
input.shootIsPressed = false;
val4.shootWasPressed = false;
val5.shootWasReleased = false;
yield return null;
float deadline = Time.realtimeSinceStartup + 2f;
val5 = input;
val4 = input;
input.shootIsPressed = true;
val5.shootWasPressed = true;
val4.shootWasReleased = false;
yield return null;
input.shootWasPressed = false;
while (!gun.isReloading && Time.realtimeSinceStartup < deadline)
{
yield return null;
}
}
finally
{
gun.ShootPojectileAction = (Action<GameObject>)Delegate.Remove(gun.ShootPojectileAction, new Action<GameObject>(CountProjectile));
(input.controlledElseWhere, input.aimDirection, input.shootIsPressed, input.shootWasPressed, input.shootWasReleased) = previousInput;
}
int num = CurrentAmmo.Invoke(ammo);
int num2 = ((!expectAutofire) ? 1 : magazine);
string text = "stage=" + stage + ";card=" + card + ";presses=1;magazine=" + magazine + ";projectiles=" + projectiles + ";ammo_remaining=" + num + ";reloading=" + gun.isReloading;
if (projectiles != num2 || num != magazine - num2 || gun.isReloading != expectAutofire)
{
Fail("unexpected_held_fire;" + text);
yield break;
}
_plugin.WriteTrace("bugfixes_local_held_fire_checked", text);
if (!expectAutofire)
{
_initialScreenshotComplete = true;
}
void CountProjectile(GameObject projectile)
{
projectiles++;
}
}
private static bool VisibleParticles(GeneralParticleSystem emitter)
{
//IL_0029: Unknown result type (might be due to invalid IL or missing references)
if (((Component)emitter).transform.childCount == 0)
{
return false;
}
foreach (Transform item in ((Component)emitter).transform.GetChild(0))
{
if (((Component)item).gameObject.activeInHierarchy)
{
return true;
}
}
return false;
}
private void Fail(string detail)
{
_finished = true;
_plugin.WriteTrace("bugfixes_local_smoke_failed", detail);
Application.Quit(2);
}
}
[BepInPlugin("local.rounds.bugfixes", "Bugfixes", "1.0.1")]
public sealed class Plugin : BaseUnityPlugin
{
public const string Id = "local.rounds.bugfixes";
private readonly SandboxInputFont _sandboxInputFont = new SandboxInputFont();
private readonly Stopwatch _clock = Stopwatch.StartNew();
private Harmony? _harmony;
private Harmony? _smokeHarmony;
private StreamWriter? _trace;
private MapWrapper? _mapBeforeRematch;
private object? _rematchSession;
private Room? _rematchRoom;
private bool _offlineRematch;
private readonly RematchProtocol _rematchProtocol = new RematchProtocol();
private bool _rematchArmed;
private bool _rematchPreparing;
internal static Plugin? Instance { get; private set; }
private void Awake()
{
//IL_004f: Unknown result type (might be due to invalid IL or missing references)
//IL_0059: Expected O, but got Unknown
//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
//IL_00cd: Expected O, but got Unknown
//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
//IL_00fc: Expected O, but got Unknown
Instance = this;
string path = CommandLineValue("--rounds-bugfixes-trace=") ?? Path.Combine(Paths.BepInExRootPath, "Bugfixes.trace.log");
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path)));
_trace = new StreamWriter(path, append: false)
{
AutoFlush = true
};
_harmony = new Harmony("local.rounds.bugfixes");
_sandboxInputFont.Install(_harmony);
InstallPlayerVisibilityHooks(_harmony);
InstallRematchHooks(_harmony);
WindowedResolutionFix.Install(_harmony, ((Component)this).gameObject);
_harmony.Patch((MethodBase)AccessTools.Method(typeof(Gun), "ResetStats", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "ResetAutoFireRestriction", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
((Component)this).gameObject.AddComponent<BugfixesRoomCallbacks>();
if (Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-bugfixes-local-smoke") >= 0)
{
_smokeHarmony = new Harmony("local.rounds.bugfixes.smoke");
BugfixesSmoke.Install(_smokeHarmony);
((Component)this).gameObject.AddComponent<BugfixesSmoke>();
}
WriteTrace("plugin_loaded", "unity=" + Application.unityVersion + ";standalone=true");
((BaseUnityPlugin)this).Logger.LogInfo((object)"Bugfixes loaded: sandbox Cyrillic, player visibility and rematches.");
}
private static void ResetAutoFireRestriction(Gun __instance)
{
__instance.dontAllowAutoFire = false;
}
private IEnumerator Start()
{
while ((Object)(object)MainMenuHandler.instance == (Object)null || (Object)(object)LoadingScreen.instance == (Object)null)
{
yield return null;
}
if (Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-bugfixes-window-smoke") >= 0)
{
yield return WindowedResolutionSmoke.Run(this);
}
else if (Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-bugfixes-sandbox-font-smoke") >= 0)
{
int.TryParse(CommandLineValue("--rounds-bugfixes-smoke-hold="), out var result);
yield return SandboxFontSmoke.Run(this, Math.Max(0, Math.Min(120, result)));
}
}
private static string? CommandLineValue(string prefix)
{
string[] commandLineArgs = Environment.GetCommandLineArgs();
foreach (string text in commandLineArgs)
{
if (text.StartsWith(prefix, StringComparison.Ordinal))
{
return text.Substring(prefix.Length);
}
}
return null;
}
internal void WriteTrace(string name, string detail)
{
_trace?.WriteLine(_clock.Elapsed.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture) + "\t" + name + "\t" + detail.Replace('\r', ' ').Replace('\n', ' '));
}
private void OnDestroy()
{
((MonoBehaviour)this).StopAllCoroutines();
_sandboxInputFont.Dispose();
Object.Destroy((Object)(object)((Component)this).GetComponent<BugfixesRoomCallbacks>());
Object.Destroy((Object)(object)((Component)this).GetComponent<WindowedResolutionFix>());
Harmony? harmony = _harmony;
if (harmony != null)
{
harmony.UnpatchSelf();
}
Harmony? smokeHarmony = _smokeHarmony;
if (smokeHarmony != null)
{
smokeHarmony.UnpatchSelf();
}
_trace?.Dispose();
_trace = null;
Instance = null;
}
private void InstallPlayerVisibilityHooks(Harmony harmony)
{
//IL_0027: Unknown result type (might be due to invalid IL or missing references)
//IL_003c: Unknown result type (might be due to invalid IL or missing references)
//IL_0049: Expected O, but got Unknown
//IL_0049: Expected O, but got Unknown
harmony.Patch((MethodBase)AccessTools.Method(typeof(PlayerManager), "SetPlayersVisible", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "AllowOffscreenTeleport", (Type[])null), new HarmonyMethod(typeof(Plugin), "MoveOffscreenWeapons", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
private static void AllowOffscreenTeleport(PlayerManager __instance)
{
foreach (Player player in __instance.players)
{
if ((Object)(object)player != (Object)null)
{
PlayerCollision component = ((Component)player).GetComponent<PlayerCollision>();
if (component != null)
{
component.IgnoreWallForFrames(2);
}
}
}
}
private static void MoveOffscreenWeapons(PlayerManager __instance)
{
//IL_004a: 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_0083: Unknown result type (might be due to invalid IL or missing references)
foreach (Player player in __instance.players)
{
if ((Object)(object)player == (Object)null)
{
continue;
}
Holdable val = ((Component)player).GetComponent<Holding>()?.holdable;
if (!((Object)(object)val == (Object)null))
{
((Component)val).transform.position = ((Component)player).transform.position;
if (!((Object)(object)val.rig == (Object)null))
{
val.rig.position = Vector2.op_Implicit(((Component)player).transform.position);
val.rig.velocity = Vector2.zero;
val.rig.angularVelocity = 0f;
}
}
}
}
private void InstallRematchHooks(Harmony harmony)
{
//IL_0027: Unknown result type (might be due to invalid IL or missing references)
//IL_0035: Expected O, but got Unknown
//IL_005e: Unknown result type (might be due to invalid IL or missing references)
//IL_006b: Expected O, but got Unknown
//IL_0094: Unknown result type (might be due to invalid IL or missing references)
//IL_00a1: Expected O, but got Unknown
//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
//IL_00d7: Expected O, but got Unknown
//IL_0101: Unknown result type (might be due to invalid IL or missing references)
//IL_010d: Expected O, but got Unknown
//IL_0135: Unknown result type (might be due to invalid IL or missing references)
//IL_0143: Expected O, but got Unknown
//IL_016c: Unknown result type (might be due to invalid IL or missing references)
//IL_0179: Expected O, but got Unknown
//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
//IL_01af: Expected O, but got Unknown
harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GameOver", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "CaptureRematch", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "ResetMatch", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "ArmRematch", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "OnDisable", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "CancelRematch", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(GameManager), "GoToMenu", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "ResetRematchBeforeSceneReload", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GameOverRematch", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "ReplacePreviewLoad", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GetRematchYesNo", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "DismissRematchPrompt", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "DoStartGame", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "WrapRematchStart", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "PlayerDied", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "AllowRoundEnding", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
private static bool CanSynchronizeRematch()
{
if (PhotonNetwork.OfflineMode)
{
return true;
}
Room currentRoom = PhotonNetwork.CurrentRoom;
if (!PhotonNetwork.InRoom || currentRoom == null)
{
return false;
}
List<object> list = new List<object>();
foreach (Player value2 in currentRoom.Players.Values)
{
((Dictionary<object, object>)(object)value2.CustomProperties).TryGetValue((object)"bugfixes_rematch_protocol", out object value);
list.Add(value);
}
return RematchProtocol.CanSynchronize(offline: false, list);
}
private static void CaptureRematch()
{
Plugin instance = Instance;
if (!((Object)(object)instance == (Object)null))
{
CancelRematch();
if (CanSynchronizeRematch())
{
instance._rematchSession = new object();
instance._rematchRoom = PhotonNetwork.CurrentRoom;
instance._offlineRematch = PhotonNetwork.OfflineMode;
instance._mapBeforeRematch = MapManager.instance?.currentMap;
}
}
}
private static void ArmRematch()
{
Plugin instance = Instance;
if (instance != null && instance._rematchSession != null)
{
instance._rematchProtocol.NextRematch();
instance._rematchArmed = true;
}
}
internal static void CancelRematch()
{
Plugin instance = Instance;
if (!((Object)(object)instance == (Object)null))
{
instance._rematchSession = null;
instance._rematchRoom = null;
instance._mapBeforeRematch = null;
instance._rematchArmed = false;
instance._rematchPreparing = false;
}
}
internal static void ResetRoomRematch()
{
CancelRematch();
Instance?._rematchProtocol.BeginRoom();
}
public static void EnterRematchLobbyCycle(int cycle)
{
Plugin? instance = Instance;
if (instance != null && instance._rematchProtocol.EnterLobbyCycle(cycle))
{
CancelRematch();
}
}
private static void ResetRematchBeforeSceneReload()
{
//IL_0018: Unknown result type (might be due to invalid IL or missing references)
//IL_001d: Unknown result type (might be due to invalid IL or missing references)
//IL_0029: Expected O, but got Unknown
//IL_0030: Expected O, but got Unknown
if (PhotonNetwork.InRoom && !PhotonNetwork.OfflineMode)
{
CancelRematch();
Player localPlayer = PhotonNetwork.LocalPlayer;
Hashtable val = new Hashtable();
((Dictionary<object, object>)val).Add((object)"bugfixes_rematch_map", (object)null);
localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
}
else
{
ResetRoomRematch();
}
}
private static IEnumerable<CodeInstruction> ReplacePreviewLoad(IEnumerable<CodeInstruction> instructions)
{
MethodInfo load = AccessTools.Method(typeof(MapManager), "LoadNextLevel", (Type[])null, (Type[])null);
MethodInfo operand = AccessTools.Method(typeof(Plugin), "LoadRematchPreview", (Type[])null, (Type[])null);
List<CodeInstruction> list = new List<CodeInstruction>(instructions);
CodeInstruction? obj = list.Find((CodeInstruction code) => CodeInstructionExtensions.Calls(code, load)) ?? throw new InvalidOperationException("Bugfixes could not locate the stock rematch map preload.");
obj.opcode = OpCodes.Call;
obj.operand = operand;
return list;
}
private static void LoadRematchPreview(MapManager manager, bool callInImmediately, bool forceLoad)
{
if (Instance?._rematchSession == null)
{
manager.LoadNextLevel(callInImmediately, forceLoad);
}
else
{
Instance.WriteTrace("rematch_preview_skipped", "map_is_requested_after_both_votes");
}
}
private static void DismissRematchPrompt()
{
PopUpHandler val = UIHandler.instance?.popUpHandler;
if (!((Object)(object)val == (Object)null))
{
val.yesPart.Stop();
val.noPart.Stop();
val.yesAnim.PlayOut();
val.noAnim.PlayOut();
}
}
private static bool AllowRoundEnding()
{
Plugin? instance = Instance;
if (instance == null)
{
return true;
}
return !instance._rematchPreparing;
}
private static void WrapRematchStart(GM_ArmsRace __instance, ref IEnumerator __result)
{
Plugin instance = Instance;
if (instance != null && instance._rematchArmed && instance._rematchSession != null)
{
instance._rematchArmed = false;
__result = instance.RunRematchStart(__instance, __result, instance._rematchSession, instance._mapBeforeRematch, instance._rematchProtocol.Number);
}
}
private IEnumerator RunRematchStart(GM_ArmsRace game, IEnumerator original, object session, MapWrapper? oldMap, int number)
{
_rematchPreparing = true;
bool waitedForLoad = false;
try
{
while (IsRematchActive(game, session, number) && original.MoveNext())
{
if (!waitedForLoad && original.Current is WaitForSecondsRealtime)
{
yield return WaitForBothMaps(game, session, oldMap, number);
waitedForLoad = true;
}
else
{
yield return original.Current;
}
}
if (!IsRematchActive(game, session, number))
{
yield break;
}
GameManager.instance.battleOngoing = false;
double battleDeadline = _clock.Elapsed.TotalSeconds + 30.0;
while (IsRematchActive(game, session, number) && !PlayersAndMapEntered())
{
if (_clock.Elapsed.TotalSeconds >= battleDeadline)
{
FailRematch(session, number, "player_readiness_timeout");
yield break;
}
yield return null;
}
if (IsRematchActive(game, session, number))
{
GameManager.instance.battleOngoing = true;
WriteTrace("rematch_battle_ready", "cards_finished;map_entered;players_spawned");
}
}
finally
{
Plugin plugin = this;
(original as IDisposable)?.Dispose();
if (plugin._rematchSession == session && plugin._rematchProtocol.Number == number)
{
plugin._rematchPreparing = false;
}
}
}
private IEnumerator WaitForBothMaps(GM_ArmsRace game, object session, MapWrapper? oldMap, int number)
{
RematchMapWait wait = new RematchMapWait(_clock.Elapsed.TotalSeconds);
while (IsRematchActive(game, session, number))
{
string text = null;
MapManager instance = MapManager.instance;
MapWrapper val = instance?.currentMap;
if (val != null && val != oldMap)
{
Scene scene;
if (oldMap != null)
{
scene = oldMap.Scene;
if (((Scene)(ref scene)).isLoaded)
{
goto IL_00c7;
}
}
scene = val.Scene;
if (((Scene)(ref scene)).isLoaded && (Object)(object)val.Map != (Object)null && instance.currentLevelID >= 0)
{
text = _rematchProtocol.MapState(instance.currentLevelID);
}
}
goto IL_00c7;
IL_00c7:
List<object> list = new List<object>();
if (!_offlineRematch)
{
foreach (Player value2 in PhotonNetwork.CurrentRoom.Players.Values)
{
((Dictionary<object, object>)(object)value2.CustomProperties).TryGetValue((object)"bugfixes_rematch_map", out object value);
list.Add(value);
}
}
bool publish;
RematchMapStatus rematchMapStatus = wait.Poll(_clock.Elapsed.TotalSeconds, text, _offlineRematch, list, out publish);
if (rematchMapStatus == RematchMapStatus.TimedOut)
{
FailRematch(session, number, "map_readiness_timeout");
yield break;
}
if (publish)
{
Player localPlayer = PhotonNetwork.LocalPlayer;
Hashtable val2 = new Hashtable();
((Dictionary<object, object>)val2).Add((object)"bugfixes_rematch_map", (object)text);
bool flag = localPlayer.SetCustomProperties(val2, (Hashtable)null, (WebFlags)null);
WriteTrace("rematch_ready_publish", $"state={text};queued={flag}");
}
if (rematchMapStatus == RematchMapStatus.Ready)
{
WriteTrace("rematch_map_ready", _offlineRematch ? "local_map_loaded" : "both_clients_loaded_matching_map");
yield break;
}
yield return null;
}
FailRematch(session, number, "map_readiness_cancelled");
}
private bool IsRematchActive(GM_ArmsRace game, object session, int number)
{
if (_rematchSession == session && _rematchProtocol.Number == number && (Object)(object)game != (Object)null && ((Behaviour)game).isActiveAndEnabled && _offlineRematch == PhotonNetwork.OfflineMode && _rematchRoom == PhotonNetwork.CurrentRoom)
{
return CanSynchronizeRematch();
}
return false;
}
private void FailRematch(object session, int number, string reason)
{
if (_rematchSession != session || _rematchProtocol.Number != number)
{
return;
}
WriteTrace("rematch_failed", reason);
((BaseUnityPlugin)this).Logger.LogWarning((object)("Rematch stopped: " + reason + ". Returning to the menu."));
if ((Object)(object)GameManager.instance != (Object)null)
{
GameManager.instance.battleOngoing = false;
}
CancelRematch();
if ((Object)(object)NetworkConnectionHandler.instance != (Object)null)
{
NetworkConnectionHandler.instance.NetworkRestart();
return;
}
GameManager instance = GameManager.instance;
if (instance != null)
{
instance.GoToMenu();
}
}
private static bool PlayersAndMapEntered()
{
MapManager instance = MapManager.instance;
object obj;
if (instance == null)
{
obj = null;
}
else
{
MapWrapper currentMap = instance.currentMap;
obj = ((currentMap != null) ? currentMap.Map : null);
}
Map val = (Map)obj;
List<Player> list = PlayerManager.instance?.players;
if ((Object)(object)val == (Object)null || !val.hasEntered || list == null || list.Count != 2)
{
return false;
}
foreach (Player item in list)
{
if ((Object)(object)item == (Object)null || (Object)(object)item.data == (Object)null || !item.data.isPlaying || item.data.dead)
{
return false;
}
}
return true;
}
}
internal sealed class BugfixesRoomCallbacks : MonoBehaviourPunCallbacks
{
public override void OnJoinedRoom()
{
//IL_000a: Unknown result type (might be due to invalid IL or missing references)
//IL_000f: Unknown result type (might be due to invalid IL or missing references)
//IL_0020: Expected O, but got Unknown
//IL_0020: Unknown result type (might be due to invalid IL or missing references)
//IL_002c: Expected O, but got Unknown
//IL_0033: Expected O, but got Unknown
Plugin.ResetRoomRematch();
Player localPlayer = PhotonNetwork.LocalPlayer;
Hashtable val = new Hashtable();
((Dictionary<object, object>)val).Add((object)"bugfixes_rematch_protocol", (object)2);
((Dictionary<object, object>)val).Add((object)"bugfixes_rematch_map", (object)null);
localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
}
public override void OnLeftRoom()
{
Plugin.ResetRoomRematch();
}
}
internal enum RematchMapStatus
{
Waiting,
Ready,
TimedOut
}
internal sealed class RematchMapWait
{
internal const double TimeoutSeconds = 30.0;
private readonly double _deadline;
private double _nextPublicationAt;
internal RematchMapWait(double startedAt)
{
_deadline = startedAt + 30.0;
_nextPublicationAt = startedAt;
}
internal RematchMapStatus Poll(double now, string? localMap, bool offline, IReadOnlyCollection<object?> peerStates, out bool publish)
{
publish = false;
if (now >= _deadline)
{
return RematchMapStatus.TimedOut;
}
if (localMap == null)
{
return RematchMapStatus.Waiting;
}
if (offline)
{
return RematchMapStatus.Ready;
}
bool flag = peerStates.Count == 2;
foreach (object peerState in peerStates)
{
if (!(peerState is string text) || text != localMap)
{
flag = false;
}
}
if (flag)
{
return RematchMapStatus.Ready;
}
if (now >= _nextPublicationAt)
{
publish = true;
_nextPublicationAt = now + 1.0;
}
return RematchMapStatus.Waiting;
}
}
internal sealed class RematchProtocol
{
internal const string CapabilityKey = "bugfixes_rematch_protocol";
internal const string ReadyKey = "bugfixes_rematch_map";
internal const int Version = 2;
internal int? LobbyCycle { get; private set; }
internal int Number { get; private set; }
internal void BeginRoom()
{
LobbyCycle = null;
Number = 0;
}
internal bool EnterLobbyCycle(int cycle)
{
if (cycle < 0 || (LobbyCycle.HasValue && cycle <= LobbyCycle.Value))
{
return false;
}
LobbyCycle = cycle;
Number = 0;
return true;
}
internal void NextRematch()
{
Number++;
}
internal string MapState(int level)
{
return (LobbyCycle.HasValue ? (LobbyCycle.Value.ToString(CultureInfo.InvariantCulture) + ":") : string.Empty) + Number.ToString(CultureInfo.InvariantCulture) + ":" + level.ToString(CultureInfo.InvariantCulture);
}
internal static bool CanSynchronize(bool offline, IReadOnlyCollection<object?> versions)
{
if (offline)
{
return true;
}
if (versions.Count != 2)
{
return false;
}
foreach (object version in versions)
{
if (!(version is int num) || num != 2)
{
return false;
}
}
return true;
}
}
internal static class SandboxFontSmoke
{
internal static IEnumerator Run(Plugin plugin, int holdSeconds)
{
while ((Object)(object)ListMenu.instance == (Object)null || !ListMenu.instance.IsInitialized)
{
yield return null;
}
MainMenuHandler.instance.PlaySandbox();
DevConsole console = Object.FindObjectOfType<DevConsole>();
if ((Object)(object)console == (Object)null || (Object)(object)GM_Test.instance == (Object)null || !((Component)GM_Test.instance).gameObject.activeSelf)
{
plugin.WriteTrace("sandbox_font_smoke_failed", "sandbox or its input not found");
Application.Quit(2);
yield break;
}
TMP_InputField field = console.inputField;
TMP_FontAsset originalFont = field.textComponent.font;
for (int attempt = 0; attempt < 2; attempt++)
{
console.ToggleConsole();
yield return null;
field.SetTextWithoutNotify("Ёё Фрост Щит Яя ROUNDS 123");
field.ForceLabelUpdate();
field.textComponent.ForceMeshUpdate(false, false);
TMP_TextInfo textInfo = field.textComponent.textInfo;
bool rendered = field.text == "Ёё Фрост Щит Яя ROUNDS 123" && ((Component)field).gameObject.activeInHierarchy && textInfo.characterCount >= "Ёё Фрост Щит Яя ROUNDS 123".Length;
int num = 0;
while (rendered && num < "Ёё Фрост Щит Яя ROUNDS 123".Length)
{
TMP_TextElement textElement = textInfo.characterInfo[num].textElement;
rendered = ((textElement != null) ? new uint?(textElement.unicode) : ((uint?)null)) == "Ёё Фрост Щит Яя ROUNDS 123"[num];
num++;
}
if (rendered && attempt == 0 && holdSeconds > 0)
{
yield return (object)new WaitForSecondsRealtime((float)holdSeconds);
}
field.SetTextWithoutNotify(string.Empty);
if (rendered)
{
CardInfo val = Array.Find(CardChoice.instance.cards, (CardInfo item) => (Object)(object)item != (Object)null && !string.IsNullOrEmpty(item.CardName));
if ((Object)(object)val != (Object)null)
{
field.SetTextWithoutNotify(val.CardName);
}
else
{
rendered = false;
}
}
if (!rendered)
{
plugin.WriteTrace("sandbox_font_smoke_failed", "rendered glyph codes or card catalog mismatch");
Application.Quit(2);
yield break;
}
console.ToggleConsole();
if ((Object)(object)field.textComponent.font != (Object)(object)originalFont)
{
plugin.WriteTrace("sandbox_font_smoke_failed", "original font was not restored");
Application.Quit(2);
yield break;
}
}
plugin.WriteTrace("sandbox_font_smoke_complete", "cyrillic_latin_digits_match_input_on_two_opens");
Application.Quit(0);
}
}
internal sealed class SandboxInputFont : IDisposable
{
private const string Cyrillic = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя";
private static SandboxInputFont? _instance;
private TMP_Text? _label;
private TMP_FontAsset? _original;
private Material? _originalMaterial;
private TMP_FontAsset? _localFont;
private TMP_FontAsset? _generatedFallback;
private Font? _systemFont;
internal void Install(Harmony harmony)
{
//IL_0027: Unknown result type (might be due to invalid IL or missing references)
//IL_0035: Expected O, but got Unknown
harmony.Patch((MethodBase)AccessTools.Method(typeof(DevConsole), "ToggleConsole", (Type[])null, (Type[])null), new HarmonyMethod(typeof(SandboxInputFont), "BeforeToggleConsole", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
_instance = this;
}
private static void BeforeToggleConsole(DevConsole __instance)
{
SandboxInputFont instance = _instance;
if (instance == null)
{
return;
}
TMP_InputField inputField = __instance.inputField;
GM_Test instance2 = GM_Test.instance;
if ((Object)(object)inputField == (Object)null || ((Component)inputField).gameObject.activeSelf || (Object)(object)instance2 == (Object)null || !((Component)instance2).gameObject.activeSelf)
{
instance.RestoreLabel();
return;
}
try
{
instance.Apply(inputField.textComponent);
}
catch (Exception ex)
{
instance.RestoreLabel();
Plugin.Instance?.WriteTrace("sandbox_font_error", ex.Message);
}
}
private void Apply(TMP_Text label)
{
if ((Object)(object)label == (Object)null || (Object)(object)label.font == (Object)null || ((Object)(object)_label == (Object)(object)label && (Object)(object)label.font == (Object)(object)_localFont))
{
return;
}
TMP_FontAsset font = label.font;
uint[] array = default(uint[]);
if (font.HasCharacters("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя", ref array, true, false))
{
return;
}
if ((Object)(object)_label != (Object)(object)label || (Object)(object)_original != (Object)(object)font)
{
ReleaseLocalFont();
TMP_FontAsset val = FindFallback();
if ((Object)(object)val == (Object)null)
{
return;
}
_localFont = Object.Instantiate<TMP_FontAsset>(font);
((Object)_localFont).name = ((Object)font).name + " (Bugfixes sandbox)";
_localFont.fallbackFontAssetTable = ((font.fallbackFontAssetTable == null) ? new List<TMP_FontAsset>() : new List<TMP_FontAsset>(font.fallbackFontAssetTable));
_localFont.fallbackFontAssetTable.Add(val);
_label = label;
_original = font;
_originalMaterial = label.fontSharedMaterial;
Plugin.Instance?.WriteTrace("sandbox_font_ready", ((Object)font).name + " => " + ((Object)val).name);
}
label.font = _localFont;
if ((Object)(object)_originalMaterial != (Object)null)
{
label.fontSharedMaterial = _originalMaterial;
}
}
private TMP_FontAsset? FindFallback()
{
TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
foreach (TMP_FontAsset val in array)
{
if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)_localFont && val.HasCharacters("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя"))
{
return val;
}
}
if ((Object)(object)_generatedFallback != (Object)null)
{
return _generatedFallback;
}
_systemFont = Font.CreateDynamicFontFromOSFont("Arial", 32);
if ((Object)(object)_systemFont == (Object)null)
{
return null;
}
_generatedFallback = TMP_FontAsset.CreateFontAsset(_systemFont);
uint[] array2 = default(uint[]);
if ((Object)(object)_generatedFallback != (Object)null && _generatedFallback.HasCharacters("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя", ref array2, false, true))
{
return _generatedFallback;
}
ReleaseGeneratedFallback();
return null;
}
private void RestoreLabel()
{
if ((Object)(object)_label != (Object)null && (Object)(object)_original != (Object)null && (Object)(object)_label.font == (Object)(object)_localFont)
{
_label.font = _original;
if ((Object)(object)_originalMaterial != (Object)null)
{
_label.fontSharedMaterial = _originalMaterial;
}
}
}
private void ReleaseLocalFont()
{
RestoreLabel();
if ((Object)(object)_localFont != (Object)null)
{
Object.Destroy((Object)(object)_localFont);
}
_localFont = null;
_original = null;
_originalMaterial = null;
_label = null;
}
private void ReleaseGeneratedFallback()
{
if ((Object)(object)_generatedFallback != (Object)null)
{
Texture2D[] atlasTextures = _generatedFallback.atlasTextures;
foreach (Texture2D val in atlasTextures)
{
if ((Object)(object)val != (Object)null)
{
Object.Destroy((Object)(object)val);
}
}
if ((Object)(object)((TMP_Asset)_generatedFallback).material != (Object)null)
{
Object.Destroy((Object)(object)((TMP_Asset)_generatedFallback).material);
}
Object.Destroy((Object)(object)_generatedFallback);
_generatedFallback = null;
}
if ((Object)(object)_systemFont != (Object)null)
{
Object.Destroy((Object)(object)_systemFont);
}
_systemFont = null;
}
public void Dispose()
{
if (_instance == this)
{
_instance = null;
}
ReleaseLocalFont();
ReleaseGeneratedFallback();
}
}
internal sealed class WindowedResolutionFix : MonoBehaviour
{
internal readonly struct WindowGeometry
{
internal readonly IntPtr Handle;
internal readonly RectInt Window;
internal readonly RectInt Client;
internal readonly RectInt WorkArea;
internal bool FitsSize
{
get
{
//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_000f: Unknown result type (might be due to invalid IL or missing references)
//IL_0014: Unknown result type (might be due to invalid IL or missing references)
//IL_001f: 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_002d: Unknown result type (might be due to invalid IL or missing references)
//IL_0032: Unknown result type (might be due to invalid IL or missing references)
RectInt val = Window;
int width = ((RectInt)(ref val)).width;
val = WorkArea;
if (width <= ((RectInt)(ref val)).width)
{
val = Window;
int height = ((RectInt)(ref val)).height;
val = WorkArea;
return height <= ((RectInt)(ref val)).height;
}
return false;
}
}
internal WindowGeometry(IntPtr handle, RectInt window, RectInt client, RectInt workArea)
{
//IL_0008: Unknown result type (might be due to invalid IL or missing references)
//IL_0009: Unknown result type (might be due to invalid IL or missing references)
//IL_000f: Unknown result type (might be due to invalid IL or missing references)
//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_0018: Unknown result type (might be due to invalid IL or missing references)
Handle = handle;
Window = window;
Client = client;
WorkArea = workArea;
}
}
private struct NativeRect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public RectInt ToRect()
{
//IL_0026: Unknown result type (might be due to invalid IL or missing references)
return new RectInt(Left, Top, Right - Left, Bottom - Top);
}
}
private struct NativeWindowInfo
{
public uint Size;
public NativeRect Window;
public NativeRect Client;
public uint Style;
public uint ExtendedStyle;
public uint WindowStatus;
public uint WindowBordersX;
public uint WindowBordersY;
public ushort WindowType;
public ushort CreatorVersion;
}
private struct NativeMonitorInfo
{
public uint Size;
public NativeRect MonitorArea;
public NativeRect WorkArea;
public uint Flags;
}
private const uint MonitorDefaultToNearest = 2u;
private const uint MoveWithoutResize = 21u;
private int _request;
internal static void Install(Harmony harmony, GameObject host)
{
//IL_0000: Unknown result type (might be due to invalid IL or missing references)
//IL_0006: Invalid comparison between Unknown and I4
//IL_003f: Unknown result type (might be due to invalid IL or missing references)
//IL_004c: Expected O, but got Unknown
if ((int)Application.platform == 2 && !Application.isBatchMode)
{
host.AddComponent<WindowedResolutionFix>();
harmony.Patch((MethodBase)AccessTools.Method(typeof(OptionsData), "ApplyScreen", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(WindowedResolutionFix), "AfterApplyScreen", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
}
private void Start()
{
QueueFit();
}
private static void AfterApplyScreen()
{
Plugin? instance = Plugin.Instance;
if (instance != null)
{
((Component)instance).GetComponent<WindowedResolutionFix>()?.QueueFit();
}
}
private void QueueFit()
{
((MonoBehaviour)this).StartCoroutine(FitAfterResolutionChange(++_request));
}
private bool ShouldFit(int request)
{
//IL_0009: Unknown result type (might be due to invalid IL or missing references)
//IL_000f: Invalid comparison between Unknown and I4
if (request == _request)
{
return (int)Screen.fullScreenMode == 3;
}
return false;
}
private IEnumerator FitAfterResolutionChange(int request)
{
yield return (object)new WaitForSecondsRealtime(0.15f);
if (!ShouldFit(request))
{
yield break;
}
float windowDeadline = Time.realtimeSinceStartup + 2f;
WindowGeometry geometry;
while (!TryReadWindow(out geometry))
{
if (!ShouldFit(request) || Time.realtimeSinceStartup >= windowDeadline)
{
yield break;
}
yield return null;
}
if (!ShouldFit(request) || IsIconic(geometry.Handle) || IsZoomed(geometry.Handle) || geometry.FitsSize)
{
yield break;
}
WindowGeometry before = geometry;
RectInt val;
for (int attempt = 0; attempt < 2; attempt++)
{
if (geometry.FitsSize)
{
break;
}
val = geometry.WorkArea;
int width = ((RectInt)(ref val)).width;
val = geometry.Window;
int width2 = ((RectInt)(ref val)).width;
val = geometry.Client;
int num = width - Math.Max(0, width2 - ((RectInt)(ref val)).width);
val = geometry.WorkArea;
int height = ((RectInt)(ref val)).height;
val = geometry.Window;
int height2 = ((RectInt)(ref val)).height;
val = geometry.Client;
int num2 = height - Math.Max(0, height2 - ((RectInt)(ref val)).height);
if (num <= 0 || num2 <= 0)
{
yield break;
}
double num3 = num;
val = geometry.Client;
double val2 = num3 / (double)((RectInt)(ref val)).width;
double num4 = num2;
val = geometry.Client;
double num5 = Math.Min(val2, num4 / (double)((RectInt)(ref val)).height);
int num6 = Math.Max(1, (int)Math.Floor((double)Screen.width * num5));
int num7 = Math.Max(1, (int)Math.Floor((double)Screen.height * num5));
val = geometry.Client;
Vector2Int previousClientSize = ((RectInt)(ref val)).size;
IntPtr handle = geometry.Handle;
Screen.SetResolution(num6, num7, (FullScreenMode)3);
float resizeDeadline = Time.realtimeSinceStartup + 1f;
do
{
yield return null;
if (!ShouldFit(request) || IsIconic(handle) || IsZoomed(handle) || !TryReadWindow(handle, out geometry))
{
yield break;
}
val = geometry.Client;
}
while (((RectInt)(ref val)).size == previousClientSize && Time.realtimeSinceStartup < resizeDeadline);
}
if (geometry.FitsSize)
{
val = geometry.Window;
int xMin = ((RectInt)(ref val)).xMin;
val = geometry.WorkArea;
int xMin2 = ((RectInt)(ref val)).xMin;
val = geometry.WorkArea;
int xMax = ((RectInt)(ref val)).xMax;
val = geometry.Window;
int num8 = Math.Clamp(xMin, xMin2, xMax - ((RectInt)(ref val)).width);
val = geometry.Window;
int yMin = ((RectInt)(ref val)).yMin;
val = geometry.WorkArea;
int yMin2 = ((RectInt)(ref val)).yMin;
val = geometry.WorkArea;
int yMax = ((RectInt)(ref val)).yMax;
val = geometry.Window;
int num9 = Math.Clamp(yMin, yMin2, yMax - ((RectInt)(ref val)).height);
val = geometry.Window;
if (num8 == ((RectInt)(ref val)).xMin)
{
val = geometry.Window;
if (num9 == ((RectInt)(ref val)).yMin)
{
goto IL_0387;
}
}
if (SetWindowPos(geometry.Handle, IntPtr.Zero, num8, num9, 0, 0, 21u) && TryReadWindow(geometry.Handle, out var geometry2))
{
geometry = geometry2;
}
}
goto IL_0387;
IL_0387:
Plugin.Instance?.WriteTrace("windowed_resolution_fit", $"before_window={before.Window};before_client={before.Client};before_work={before.WorkArea};" + $"after_window={geometry.Window};after_client={geometry.Client};after_work={geometry.WorkArea}");
}
internal static bool TryReadWindow(out WindowGeometry geometry)
{
//IL_0007: Unknown result type (might be due to invalid IL or missing references)
//IL_000d: Invalid comparison between Unknown and I4
geometry = default(WindowGeometry);
if ((int)Application.platform != 2)
{
return false;
}
using Process process = Process.GetCurrentProcess();
return TryReadWindow(process.MainWindowHandle, out geometry);
}
private static bool TryReadWindow(IntPtr handle, out WindowGeometry geometry)
{
//IL_0079: 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_0091: Unknown result type (might be due to invalid IL or missing references)
//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
//IL_00a6: 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_00b8: Unknown result type (might be due to invalid IL or missing references)
//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
//IL_0100: Unknown result type (might be due to invalid IL or missing references)
geometry = default(WindowGeometry);
if (handle == IntPtr.Zero)
{
return false;
}
NativeWindowInfo info = new NativeWindowInfo
{
Size = (uint)Marshal.SizeOf<NativeWindowInfo>()
};
if (!GetWindowInfo(handle, ref info))
{
return false;
}
IntPtr intPtr = MonitorFromWindow(handle, 2u);
NativeMonitorInfo info2 = new NativeMonitorInfo
{
Size = (uint)Marshal.SizeOf<NativeMonitorInfo>()
};
if (intPtr == IntPtr.Zero || !GetMonitorInfo(intPtr, ref info2))
{
return false;
}
geometry = new WindowGeometry(handle, info.Window.ToRect(), info.Client.ToRect(), info2.WorkArea.ToRect());
RectInt val = geometry.Window;
if (((RectInt)(ref val)).width > 0)
{
val = geometry.Window;
if (((RectInt)(ref val)).height > 0)
{
val = geometry.Client;
if (((RectInt)(ref val)).width > 0)
{
val = geometry.Client;
if (((RectInt)(ref val)).height > 0)
{
val = geometry.WorkArea;
if (((RectInt)(ref val)).width > 0)
{
val = geometry.WorkArea;
return ((RectInt)(ref val)).height > 0;
}
}
}
}
}
return false;
}
[DllImport("user32.dll")]
private static extern bool GetWindowInfo(IntPtr window, ref NativeWindowInfo info);
[DllImport("user32.dll")]
private static extern IntPtr MonitorFromWindow(IntPtr window, uint flags);
[DllImport("user32.dll", EntryPoint = "GetMonitorInfoW")]
private static extern bool GetMonitorInfo(IntPtr monitor, ref NativeMonitorInfo info);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr window);
[DllImport("user32.dll")]
private static extern bool IsZoomed(IntPtr window);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr window, IntPtr insertAfter, int x, int y, int width, int height, uint flags);
}
internal static class WindowedResolutionSmoke
{
internal static IEnumerator Run(Plugin plugin)
{
using IEnumerator<object?> steps = CheckWindow(plugin).GetEnumerator();
while (true)
{
object current;
try
{
if (!steps.MoveNext())
{
break;
}
current = steps.Current;
goto IL_0079;
}
catch (Exception ex)
{
plugin.WriteTrace("bugfixes_window_smoke_failed", ex.ToString());
Application.Quit(2);
yield break;
}
IL_0079:
yield return current;
}
plugin.WriteTrace("bugfixes_window_smoke_complete", "window_fits_work_area;aspect_ratio_preserved");
Application.Quit(0);
}
private static IEnumerable<object?> CheckWindow(Plugin plugin)
{
float deadline = Time.realtimeSinceStartup + 25f;
while (((Object)(object)ListMenu.instance == (Object)null || !ListMenu.instance.IsInitialized || (Object)(object)Optionshandler.instance == (Object)null) && Time.realtimeSinceStartup < deadline)
{
yield return null;
}
Optionshandler instance = Optionshandler.instance;
OptionsData settings = ((instance != null) ? instance.OptionsData : null) ?? throw new InvalidOperationException("ROUNDS options did not initialize.");
DisplayInfo display = Screen.mainWindowDisplayInfo;
Resolution[] resolutionsWithHighestRefreshRate = settings.GetResolutionsWithHighestRefreshRate();
int num = Array.FindIndex(resolutionsWithHighestRefreshRate, (Resolution item) => ((Resolution)(ref item)).width == display.width && ((Resolution)(ref item)).height == display.height);
if (num < 0)
{
throw new InvalidOperationException("The stock resolution selector does not offer the current monitor size.");
}
SettingsData resolution = settings.GetSettingsData("OPTION_RESOLUTION");
SettingsData mode = settings.GetSettingsData("OPTION_FULLSCREEN");
int originalResolution = resolution.CurrentValueOptions;
int originalMode = mode.CurrentValueOptions;
bool saveResolution = resolution.m_saveInPlayerprefs;
bool saveMode = mode.m_saveInPlayerprefs;
Resolution requested = resolutionsWithHighestRefreshRate[num];
try
{
resolution.m_saveInPlayerprefs = false;
mode.m_saveInPlayerprefs = false;
resolution.CurrentValueOptions = num;
mode.CurrentValueOptions = 3;
settings.ApplyScreen();
for (int frame = 0; frame < 8; frame++)
{
yield return null;
}
deadline = Time.realtimeSinceStartup + 10f;
WindowedResolutionFix.WindowGeometry geometry = default(WindowedResolutionFix.WindowGeometry);
bool fits = false;
while (Time.realtimeSinceStartup < deadline)
{
if ((int)Screen.fullScreenMode == 3 && WindowedResolutionFix.TryReadWindow(out geometry))
{
RectInt val = geometry.Window;
int xMin = ((RectInt)(ref val)).xMin;
val = geometry.WorkArea;
if (xMin >= ((RectInt)(ref val)).xMin)
{
val = geometry.Window;
int xMax = ((RectInt)(ref val)).xMax;
val = geometry.WorkArea;
if (xMax <= ((RectInt)(ref val)).xMax)
{
val = geometry.Window;
int yMin = ((RectInt)(ref val)).yMin;
val = geometry.WorkArea;
if (yMin >= ((RectInt)(ref val)).yMin)
{
val = geometry.Window;
int yMax = ((RectInt)(ref val)).yMax;
val = geometry.WorkArea;
if (yMax <= ((RectInt)(ref val)).yMax)
{
val = geometry.Client;
if (((RectInt)(ref val)).width >= ((Resolution)(ref requested)).width)
{
val = geometry.Client;
if (((RectInt)(ref val)).height >= ((Resolution)(ref requested)).height)
{
goto IL_033f;
}
}
fits = true;
break;
}
}
}
}
}
goto IL_033f;
IL_033f:
yield return null;
}
string text = $"requested={((Resolution)(ref requested)).width}x{((Resolution)(ref requested)).height};client={geometry.Client};" + $"outer={geometry.Window};work_area={geometry.WorkArea};mode={Screen.fullScreenMode}";
if (!fits)
{
throw new InvalidOperationException("The oversized game window did not fit the work area. " + text);
}
float num2 = (float)Screen.width / (float)Screen.height;
float num3 = (float)((Resolution)(ref requested)).width / (float)((Resolution)(ref requested)).height;
if (Mathf.Abs(num2 - num3) > 0.01f)
{
throw new InvalidOperationException("The window resize changed the game aspect ratio. " + text);
}
plugin.WriteTrace("bugfixes_window_geometry", text);
}
finally
{
resolution.CurrentValueOptions = originalResolution;
mode.CurrentValueOptions = originalMode;
settings.ApplyScreen();
resolution.m_saveInPlayerprefs = saveResolution;
mode.m_saveInPlayerprefs = saveMode;
}
}
}
}