Decompiled source of Overdrive v1.1.0
Overdrive.dll
Decompiled 16 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using ExitGames.Client.Photon; using HarmonyLib; using InControl; using Microsoft.CodeAnalysis; using Photon.Pun; using Photon.Realtime; using TMPro; using UnboundLib; using UnboundLib.GameModes; using UnboundLib.Utils; using UnboundLib.Utils.UI; using UnityEngine; using UnityEngine.CrashReportHandler; using UnityEngine.Events; using UnityEngine.Profiling; using UnityEngine.SceneManagement; using UnityEngine.Scripting; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [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 Overdrive { internal class Benchmark : MonoBehaviour { internal static bool Running; internal BenchSpec Spec; private readonly StringBuilder report = new StringBuilder(); private readonly StringBuilder json = new StringBuilder(); private readonly Dictionary<string, int> exceptionSources = new Dictionary<string, int>(); private string progressPath; private float deadline; private bool finished; private bool driving; private float nextBlock; private float loadSeconds; private int allowErrorsLogged; private string selfTest; private object cardsInstance; private MethodInfo addCard; private MethodInfo isAllowed; private MethodInfo removeAll; private void Start() { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown if (Spec == null) { Spec = CommandLine.Bench ?? new BenchSpec(); } Running = true; Directory.CreateDirectory(Plugin.DataDir); progressPath = Path.Combine(Plugin.DataDir, "bench-" + Spec.Tag + ".progress.log"); File.WriteAllText(progressPath, ""); deadline = Time.realtimeSinceStartup + 2400f; Watchdog.Start(progressPath, CommandLine.Bench != null && Application.isBatchMode); Application.logMessageReceived += new LogCallback(OnLog); ((MonoBehaviour)this).StartCoroutine(Guarded(Run())); } private void OnDestroy() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown Application.logMessageReceived -= new LogCallback(OnLog); Running = false; } private void OnLog(string condition, string stackTrace, LogType type) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 if ((int)type != 4) { return; } string text = "(no stack)"; if (!string.IsNullOrEmpty(stackTrace)) { int num = stackTrace.IndexOf('\n'); text = ((num > 0) ? stackTrace.Substring(0, num) : stackTrace); int num2 = text.IndexOf(" (at ", StringComparison.Ordinal); if (num2 > 0) { text = text.Substring(0, num2); } } string text2 = condition ?? ""; int num3 = text2.IndexOf(':'); if (num3 > 0) { text2 = text2.Substring(0, num3); } string key = text2 + " @ " + text; exceptionSources.TryGetValue(key, out var value); exceptionSources[key] = value + 1; } private void Progress(string line) { string text = "[" + Time.realtimeSinceStartup.ToString("F1", CultureInfo.InvariantCulture) + "s] " + line; Plugin.Log.LogInfo((object)("[bench] " + line)); try { File.AppendAllText(progressPath, text + Environment.NewLine); } catch { } } private void Update() { Watchdog.Beat(); if (!finished && Time.realtimeSinceStartup > deadline) { Progress("TIMEOUT - writing partial report"); Finish("timeout"); } if (CommandLine.Bench != null && AudioListener.volume != 0f) { AudioListener.volume = 0f; } if (driving) { Drive(); } } private IEnumerator Guarded(IEnumerator inner) { while (true) { object current; try { if (!inner.MoveNext()) { break; } current = inner.Current; } catch (Exception ex) { Progress("ERROR: " + ex); report.AppendLine("ERROR: " + ex); Finish("error"); break; } if (current is IEnumerator) { yield return ((MonoBehaviour)this).StartCoroutine(Guarded((IEnumerator)current)); } else { yield return current; } } } private IEnumerator Run() { Progress("waiting for main menu"); while (true) { Scene activeScene = SceneManager.GetActiveScene(); if (!(((Scene)(ref activeScene)).name != "Main") && !((Object)(object)MainMenuHandler.instance == (Object)null) && !((Object)(object)CardChoice.instance == (Object)null)) { break; } yield return null; } float stableSince = Time.realtimeSinceStartup; int lastCount = -1; float begin = Time.realtimeSinceStartup; float lastReport = begin; while (true) { float realtimeSinceStartup = Time.realtimeSinceStartup; int count = CardManager.cards.Count; if (count != lastCount || Time.unscaledDeltaTime > 0.5f) { lastCount = count; stableSince = realtimeSinceStartup; } if (realtimeSinceStartup - lastReport > 30f) { lastReport = realtimeSinceStartup; Progress("still loading: " + count + " cards registered"); } if (realtimeSinceStartup - stableSince > 12f && realtimeSinceStartup - begin > Spec.StartDelay) { break; } yield return null; } loadSeconds = stableSince; Progress("card registry stable: " + lastCount + " cards registered, " + ((CardChoice.instance.cards != null) ? CardChoice.instance.cards.Length : 0) + " active"); ResolveModdingUtils(); if (LazyCardMenus.Deferred > 0) { yield return MenuSelfTest(); } Random.InitState(4242); if (!PhotonNetwork.InRoom) { Progress("entering offline mode"); if (!PhotonNetwork.OfflineMode) { PhotonNetwork.OfflineMode = true; } if (!PhotonNetwork.InRoom) { PhotonNetwork.JoinRandomRoom(); } float tRoom = Time.realtimeSinceStartup; while (!PhotonNetwork.InRoom && Time.realtimeSinceStartup - tRoom < 20f) { yield return null; } if (!PhotonNetwork.InRoom) { throw new Exception("could not enter an offline Photon room"); } } if (Spec.Capture > 0) { Time.captureFramerate = Spec.Capture; Progress("fixed simulation rate: " + Spec.Capture + " steps per game second"); } Progress("starting sandbox"); MainMenuHandler.instance.Close(); GameModeManager.SetGameMode("Sandbox"); GameModeManager.CurrentHandler.StartGame(); float t0 = Time.realtimeSinceStartup; while (((Object)(object)MapManager.instance == (Object)null || MapManager.instance.currentMap == null) && Time.realtimeSinceStartup - t0 < 60f) { yield return null; } yield return (object)new WaitForSecondsRealtime(3f); string mapName = "?"; try { mapName = MapManager.instance.levels[MapManager.instance.currentLevelID]; } catch { } Progress("map loaded: " + mapName); int want = Spec.Players; if (PlayerAssigner.instance.maxPlayers < want) { PlayerAssigner.instance.maxPlayers = want; } for (int i = 0; i < want; i++) { int before = PlayerManager.instance.players.Count; ((MonoBehaviour)PlayerAssigner.instance).StartCoroutine(PlayerAssigner.instance.CreatePlayer((InputDevice)null, true)); float tRoom = Time.realtimeSinceStartup; while (PlayerManager.instance.players.Count == before && Time.realtimeSinceStartup - tRoom < 15f) { yield return null; } yield return (object)new WaitForSecondsRealtime(0.5f); } yield return (object)new WaitForSecondsRealtime(2f); Player[] players = PlayerManager.instance.players.ToArray(); Progress("players: " + players.Length); if (players.Length == 0) { throw new Exception("no bot could be created"); } if (Spec.Profile) { Progress("installing profiler"); yield return null; Profiler.Install(); yield return null; } report.AppendLine("Overdrive benchmark " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); report.AppendLine("tag=" + Spec.Tag + " startup fixes=" + (Plugin.StartupOn ? "ON" : "OFF") + " in-game optimizations=" + (Plugin.RuntimeOn ? "ON" : "OFF") + ((CommandLine.Disabled.Count > 0) ? (" disabled=" + string.Join(",", new List<string>(CommandLine.Disabled).ToArray())) : "") + " batchmode=" + Application.isBatchMode + " profiler=" + Spec.Profile); report.AppendLine("players=" + players.Length + " cards/player=" + Spec.Cards + ((Spec.Capture > 0) ? (" fixed-step=" + Spec.Capture + "/s frames/set=" + Spec.Frames + " (wall cap " + Spec.MaxWall + "s)") : (" seconds/set=" + Spec.Seconds)) + " map=" + mapName + " card pool=" + lastCount); report.AppendLine("STARTUP: pack finished loading " + loadSeconds.ToString("F0", CultureInfo.InvariantCulture) + " s after launch; longest single-frame freeze " + Watchdog.LongestStallSeconds + " s; engine memory " + Profiler.GetTotalReservedMemoryLong() / 1048576 + " MB + managed heap " + GC.GetTotalMemory(forceFullCollection: false) / 1048576 + " MB"); report.AppendLine("STARTUP FIXES: " + ((StartupPatches.Active.Count > 0) ? string.Join(", ", StartupPatches.Active.ToArray()) : "none") + " | deferred config writes " + ConfigBatcher.Deferred + " | card previews deferred " + LazyCardMenus.Deferred + ", built on demand " + LazyCardMenus.Built); if (selfTest != null) { report.AppendLine("MENU SELF-TEST: " + selfTest); } report.AppendLine(); json.Append("{\"tag\":\"").Append(Spec.Tag).Append("\",\"optimizations\":") .Append(Plugin.RuntimeOn ? "true" : "false") .Append(",\"players\":") .Append(players.Length) .Append(",\"cards\":") .Append(Spec.Cards) .Append(",\"map\":\"") .Append(mapName.Replace("\\", "/").Replace("\"", "'")) .Append("\",\"sets\":["); new List<float>(); bool firstSet = true; int[] seeds = Spec.Seeds; for (int i = 0; i < seeds.Length; i++) { int before = seeds[i]; Progress("seed " + before + ": clearing cards"); Player[] array = players; foreach (Player val in array) { if ((Object)(object)val != (Object)null && (Object)(object)val.data != (Object)null && val.data.currentCards.Count > 0) { RemoveAllCards(val); } } yield return (object)new WaitForSecondsRealtime(2f); Random rng = new Random(before); List<CardInfo> pool = new List<CardInfo>(); foreach (KeyValuePair<string, Card> card in CardManager.cards) { if (card.Value != null && card.Value.enabled && (Object)(object)card.Value.cardInfo != (Object)null) { pool.Add(card.Value.cardInfo); } } pool.Sort((CardInfo a, CardInfo b) => string.CompareOrdinal(((Object)a).name, ((Object)b).name)); if (pool.Count == 0) { CardInfo[] cards = CardChoice.instance.cards; foreach (CardInfo val2 in cards) { if ((Object)(object)val2 != (Object)null) { pool.Add(val2); } } } List<string> given = new List<string>(); int failedCards = 0; Player[] array2 = players; foreach (Player p in array2) { if ((Object)(object)p == (Object)null || (Object)(object)p.data == (Object)null) { continue; } int got = 0; int attempts = 0; List<string> names = new List<string>(); while (got < Spec.Cards && attempts < Spec.Cards * 40) { attempts++; CardInfo val3 = pool[rng.Next(pool.Count)]; if (Allowed(p, val3)) { bool flag = true; try { AddCard(p, val3); } catch (Exception ex) { flag = false; failedCards++; Progress("card '" + val3.cardName + "' failed to apply: " + (ex.InnerException ?? ex).GetType().Name + ": " + (ex.InnerException ?? ex).Message); } if (flag || p.data.currentCards.Count > got) { got = Math.Max(got + 1, p.data.currentCards.Count); names.Add(val3.cardName); } yield return null; } } given.Add("P" + p.playerID + " (" + got + " cards, " + attempts + " tries, has " + p.data.currentCards.Count + "): " + string.Join(", ", names.ToArray())); } Progress("seed " + before + ": cards applied, settling"); yield return (object)new WaitForSecondsRealtime(3f); Progress("seed " + before + ": measuring " + ((Spec.Capture > 0) ? (Spec.Frames + " frames") : (Spec.Seconds + "s"))); exceptionSources.Clear(); GC.Collect(); yield return null; yield return null; driving = true; if (Spec.Profile) { Profiler.InstrumentPlayerEvents(); GarbageCollector.GCMode = (Mode)0; Profiler.Begin(); } FrameStats.Instance.BeginCapture(); if (Spec.Capture > 0) { int num = Time.frameCount; float tRoom = Time.realtimeSinceStartup; while (Time.frameCount - num < Spec.Frames && Time.realtimeSinceStartup - tRoom < Spec.MaxWall) { yield return null; } } else { yield return (object)new WaitForSecondsRealtime(Spec.Seconds); } FrameSummary s = FrameStats.Instance.EndCapture(); List<Profiler.Stat> prof = null; if (Spec.Profile) { prof = Profiler.End(); GarbageCollector.GCMode = (Mode)1; } driving = false; AppendSet(before, s, given, failedCards, prof); try { report.AppendLine(" --- player events with many subscribers ---"); report.Append(DelegateCensus()); } catch (Exception ex2) { report.AppendLine(" delegate census failed: " + ex2.Message); } try { report.AppendLine(" --- census right after measuring ---"); report.Append(Census()); report.AppendLine(); } catch (Exception ex3) { report.AppendLine(" census failed: " + ex3.Message); } if (!firstSet) { json.Append(","); } firstSet = false; AppendJson(before, s); Progress(string.Format(CultureInfo.InvariantCulture, "seed {0}: avg {1:F2} ms ({2:F0} fps) 1% low {3:F0} fps worst {4:F1} ms bullets peak {5} exceptions {6}", before, s.AvgMs, s.AvgFps, s.Low1Fps, s.MaxMs, s.PeakBullets, s.Exceptions)); yield return (object)new WaitForSecondsRealtime(1f); } Finish("ok"); } internal static string Census() { Dictionary<string, int[]> dictionary = new Dictionary<string, int[]>(); int num = 0; MonoBehaviour[] array = Object.FindObjectsOfType<MonoBehaviour>(); foreach (MonoBehaviour val in array) { if (!((Object)(object)val == (Object)null) && ((Behaviour)val).isActiveAndEnabled) { num++; Transform root = ((Component)val).transform.root; int num2 = 3; if ((Object)(object)((Component)root).GetComponent<CardInfo>() != (Object)null) { num2 = 0; } else if ((Object)(object)((Component)root).GetComponent<ProjectileHit>() != (Object)null) { num2 = 1; } else if ((Object)(object)((Component)root).GetComponent<Player>() != (Object)null) { num2 = 2; } string fullName = ((object)val).GetType().FullName; if (!dictionary.TryGetValue(fullName, out var value)) { value = (dictionary[fullName] = new int[4]); } value[num2]++; } } List<KeyValuePair<string, int[]>> list = new List<KeyValuePair<string, int[]>>(dictionary); list.Sort((KeyValuePair<string, int[]> a, KeyValuePair<string, int[]> b) => (b.Value[0] + b.Value[1] + b.Value[2] + b.Value[3]).CompareTo(a.Value[0] + a.Value[1] + a.Value[2] + a.Value[3])); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(" running scripts: " + num + " (columns: on card templates / bullets / players / other)"); for (int num3 = 0; num3 < Math.Min(40, list.Count); num3++) { int[] value2 = list[num3].Value; stringBuilder.AppendFormat(" {0,6} {1,6} {2,6} {3,6} {4}\n", value2[0], value2[1], value2[2], value2[3], list[num3].Key); } return stringBuilder.ToString(); } internal static string DelegateCensus() { StringBuilder stringBuilder = new StringBuilder(); foreach (Player player in PlayerManager.instance.players) { if ((Object)(object)player == (Object)null) { continue; } try { GunAmmo componentInChildren = ((Component)player.data.weaponHandler.gun).GetComponentInChildren<GunAmmo>(); if ((Object)(object)componentInChildren != (Object)null) { stringBuilder.Append(" P").Append(player.playerID).Append(" ammo: max ") .Append(componentInChildren.maxAmmo) .Append(", bar icons ") .Append(((Component)componentInChildren.populate).transform.childCount - 1) .AppendLine(); } } catch { } List<Component> list = new List<Component>(); Component[] components = ((Component)player).GetComponents<Component>(); foreach (Component item in components) { list.Add(item); } if ((Object)(object)player.data != (Object)null && (Object)(object)player.data.weaponHandler != (Object)null && (Object)(object)player.data.weaponHandler.gun != (Object)null) { list.Add((Component)(object)player.data.weaponHandler.gun); GunAmmo componentInChildren2 = ((Component)player.data.weaponHandler.gun).GetComponentInChildren<GunAmmo>(); if ((Object)(object)componentInChildren2 != (Object)null) { list.Add((Component)(object)componentInChildren2); } } foreach (Component item2 in list) { if ((Object)(object)item2 == (Object)null) { continue; } Type type = ((object)item2).GetType(); while (type != null && type != typeof(MonoBehaviour)) { FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (!typeof(Delegate).IsAssignableFrom(fieldInfo.FieldType) || !(fieldInfo.GetValue(item2) is Delegate obj2)) { continue; } Delegate[] invocationList = obj2.GetInvocationList(); if (invocationList.Length >= 8) { Dictionary<string, int> dictionary = new Dictionary<string, int>(); Delegate[] array = invocationList; foreach (Delegate obj3 in array) { string key = ((obj3.Method.DeclaringType != null) ? obj3.Method.DeclaringType.FullName : "?") + "." + obj3.Method.Name; dictionary.TryGetValue(key, out var value); dictionary[key] = value + 1; } List<KeyValuePair<string, int>> list2 = new List<KeyValuePair<string, int>>(dictionary); list2.Sort((KeyValuePair<string, int> a, KeyValuePair<string, int> b) => b.Value.CompareTo(a.Value)); stringBuilder.Append(" P").Append(player.playerID).Append(" ") .Append(type.Name) .Append(".") .Append(fieldInfo.Name) .Append(": ") .Append(invocationList.Length) .Append(" handlers"); for (int num = 0; num < Math.Min(4, list2.Count); num++) { stringBuilder.Append((num == 0) ? " (" : ", ").Append(list2[num].Value).Append("x ") .Append(list2[num].Key); } stringBuilder.AppendLine((list2.Count > 0) ? ")" : ""); } } type = type.BaseType; } } } return stringBuilder.ToString(); } private IEnumerator MenuSelfTest() { Type type = AccessTools.TypeByName("UnboundLib.Utils.UI.ToggleCardsMenuHandler"); GameObject canvas = (GameObject)((type == null) ? null : /*isinst with value type is only supported in some contexts*/); MethodInfo setActive = ((type == null) ? null : AccessTools.Method(type, "SetActive", new Type[2] { typeof(Transform), typeof(bool) }, (Type[])null)); if ((Object)(object)canvas == (Object)null || setActive == null) { selfTest = "skipped (menu not found)"; yield break; } int builtBefore = LazyCardMenus.Built; int excBefore = FrameStats.ExceptionCount; setActive.Invoke(null, new object[2] { canvas.transform, true }); float t = Time.realtimeSinceStartup; while (Time.realtimeSinceStartup - t < 4f) { yield return null; } int withInfo = 0; int entries = 0; LazyCardVisual[] componentsInChildren = canvas.GetComponentsInChildren<LazyCardVisual>(false); for (int i = 0; i < componentsInChildren.Length; i++) { _ = componentsInChildren[i]; entries++; } CardInfo[] componentsInChildren2 = canvas.GetComponentsInChildren<CardInfo>(false); for (int i = 0; i < componentsInChildren2.Length; i++) { _ = componentsInChildren2[i]; withInfo++; } setActive.Invoke(null, new object[2] { canvas.transform, false }); yield return (object)new WaitForSecondsRealtime(0.5f); selfTest = "opened the toggle-cards menu for 4 s: " + (LazyCardMenus.Built - builtBefore) + " previews built on demand, " + withInfo + " visible card previews, " + entries + " visible entries still waiting, " + (FrameStats.ExceptionCount - excBefore) + " exceptions"; Progress("menu self-test: " + selfTest); } private void Drive() { PlayerManager instance = PlayerManager.instance; if ((Object)(object)instance == (Object)null) { return; } bool flag = Time.unscaledTime > nextBlock; if (flag) { nextBlock = Time.unscaledTime + 2.5f; } List<Player> players = instance.players; for (int i = 0; i < players.Count; i++) { Player val = players[i]; if ((Object)(object)val == (Object)null || (Object)(object)val.data == (Object)null || val.data.dead) { continue; } try { Gun val2 = (((Object)(object)val.data.weaponHandler != (Object)null) ? val.data.weaponHandler.gun : null); if ((Object)(object)val2 != (Object)null && val2.IsReady(0f)) { ((Weapon)val2).Attack(0f, false, 1f, 1f, true); } if (flag && (Object)(object)val.data.block != (Object)null) { val.data.block.TryBlock(); } } catch (Exception ex) { Debug.LogException(ex); } } } private void AppendSet(int seed, FrameSummary s, List<string> given, int failedCards, List<Profiler.Stat> prof) { CultureInfo invariantCulture = CultureInfo.InvariantCulture; report.AppendLine("=== card set (seed) " + seed + " ==="); foreach (string item in given) { report.AppendLine(" " + item); } report.AppendLine(string.Format(invariantCulture, " frames {0} in {1:F1}s | avg {2:F3} ms = {3:F0} fps | 1% low {4:F0} fps | 0.1% low {5:F0} fps", s.Frames, s.Seconds, s.AvgMs, s.AvgFps, s.Low1Fps, s.Low01Fps)); report.AppendLine(string.Format(invariantCulture, " p50 {0:F3} ms | p95 {1:F3} ms | p99 {2:F3} ms | p99.9 {3:F3} ms | worst {4:F2} ms", s.P50Ms, s.P95Ms, s.P99Ms, s.P999Ms, s.MaxMs)); report.AppendLine(string.Format(invariantCulture, " frames slower than 165 fps: {0} ({1:P2}) | slower than 60 fps: {2} | slower than 30 fps: {3}", s.Over6Ms, (s.Frames > 0) ? ((double)s.Over6Ms / (double)s.Frames) : 0.0, s.Over16Ms, s.Over33Ms)); report.AppendLine(string.Format(invariantCulture, " bullets: peak {0}, average {1:F1} | GC collections {2} | heap {3:F0} -> {4:F0} MB | exceptions {5} | cards failed to apply {6}", s.PeakBullets, s.AvgBullets, s.GcCollections, (double)s.HeapStartBytes / 1048576.0, (double)s.HeapEndBytes / 1048576.0, s.Exceptions, failedCards)); if (exceptionSources.Count > 0) { List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>(exceptionSources); list.Sort((KeyValuePair<string, int> a, KeyValuePair<string, int> b) => b.Value.CompareTo(a.Value)); report.AppendLine(" exception sources:"); for (int num = 0; num < Math.Min(12, list.Count); num++) { report.AppendLine(" " + list[num].Value + " x " + list[num].Key); } } if (prof != null) { report.AppendLine(" --- profiler (top 60 by total time; nested calls are counted in their callers too) ---"); report.Append(Profiler.Format(prof, s.Frames, 90)); report.AppendLine(" --- top 30 by allocations ---"); report.Append(Profiler.FormatByAlloc(prof, s.Frames, 30)); } report.AppendLine(); } private void AppendJson(int seed, FrameSummary s) { CultureInfo invariantCulture = CultureInfo.InvariantCulture; json.AppendFormat(invariantCulture, "{{\"seed\":{0},\"frames\":{1},\"seconds\":{2:F2},\"avgMs\":{3:F4},\"p50Ms\":{4:F4},\"p95Ms\":{5:F4},\"p99Ms\":{6:F4},\"p999Ms\":{7:F4},\"maxMs\":{8:F3},\"avgFps\":{9:F1},\"low1Fps\":{10:F1},\"low01Fps\":{11:F1},\"over165\":{12},\"over60\":{13},\"over30\":{14},\"gc\":{15},\"peakBullets\":{16},\"avgBullets\":{17:F1},\"exceptions\":{18}}}", seed, s.Frames, s.Seconds, s.AvgMs, s.P50Ms, s.P95Ms, s.P99Ms, s.P999Ms, s.MaxMs, s.AvgFps, s.Low1Fps, s.Low01Fps, s.Over6Ms, s.Over16Ms, s.Over33Ms, s.GcCollections, s.PeakBullets, s.AvgBullets, s.Exceptions); } private void Finish(string status) { if (!finished) { finished = true; driving = false; json.Append("],\"status\":\"").Append(status).Append("\"}"); report.AppendLine("status: " + status); report.AppendLine("log guard suppressed lines: " + LogGuard.TotalSuppressed + " | firewall wrapped methods: " + ExceptionFirewall.WrappedCount + " | firewall swallowed: " + ExceptionFirewall.TotalSwallowed + " | doomed calls skipped: " + ExceptionFirewall.TotalSkipped); report.AppendLine("ammo-bar rebuilds avoided: " + AmmoBar.RedrawsAvoided + " (icons added " + AmmoBar.IconsCreated + ", removed " + AmmoBar.IconsRemoved + ") | time-scale lookups served from cache: " + PlayerTimeScaleFix.Lookups); report.AppendLine("bot map scans: " + LazyMapScanner.Scans + " (skipped ticks " + LazyMapScanner.TicksSkipped + ") | bullet-object scans deferred " + ProjectileScanCoalescer.Deferred + ", run " + ProjectileScanCoalescer.Runs); report.AppendLine("known-broken calls skipped: " + KnownBrokenBehaviours.Skipped + " | bullet pairs resolved inline: " + BulletRaycast.PairsSkipped + " | card templates asleep: " + TemplateSleep.Templates + " (" + TemplateSleep.Sleeping + " components) | GC mode: " + GcGovernor.StateText + ", forced collections " + GcGovernor.ForcedCollections + ", last collect " + GcGovernor.LastCollectMs.ToString("F0", CultureInfo.InvariantCulture) + " ms"); report.AppendLine("active: [engine] " + string.Join(", ", EnginePatches.Active.ToArray()) + " [mods] " + string.Join(", ", ModPatches.Active.ToArray())); try { File.WriteAllText(Path.Combine(Plugin.DataDir, "bench-" + Spec.Tag + ".txt"), report.ToString()); File.WriteAllText(Path.Combine(Plugin.DataDir, "bench-" + Spec.Tag + ".json"), json.ToString()); } catch (Exception ex) { Plugin.Log.LogError((object)("Could not write benchmark report: " + ex)); } Progress("DONE " + status); Running = false; if (Spec.Quit) { Application.Quit(); } else { Hud.Flash("Benchmark finished - report in BepInEx/Overdrive/bench-" + Spec.Tag + ".txt"); } } } private void ResolveModdingUtils() { Type type = AccessTools.TypeByName("ModdingUtils.Utils.Cards"); if (type == null) { Progress("ModdingUtils not found - using vanilla card application"); return; } cardsInstance = AccessTools.Field(type, "instance").GetValue(null); MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { ParameterInfo[] parameters = methodInfo.GetParameters(); if (methodInfo.Name == "AddCardToPlayer" && parameters.Length == 7) { addCard = methodInfo; } else if (methodInfo.Name == "PlayerIsAllowedCard" && parameters.Length == 2) { isAllowed = methodInfo; } else if (methodInfo.Name == "RemoveAllCardsFromPlayer" && parameters.Length == 2) { removeAll = methodInfo; } } } private bool Allowed(Player p, CardInfo card) { if ((Object)(object)card == (Object)null) { return false; } if (isAllowed == null) { return true; } try { return (bool)isAllowed.Invoke(cardsInstance, new object[2] { p, card }); } catch (Exception ex) { if (allowErrorsLogged++ < 2) { Progress("PlayerIsAllowedCard threw (using basic rules instead): " + (ex.InnerException ?? ex).GetType().Name + " in " + (((ex.InnerException ?? ex).TargetSite != null) ? (ex.InnerException ?? ex).TargetSite.DeclaringType.FullName : "?")); } try { foreach (CardInfo currentCard in p.data.currentCards) { if ((Object)(object)currentCard == (Object)null) { continue; } if (!card.allowMultiple && ((Object)((Component)currentCard).gameObject).name == ((Object)((Component)card).gameObject).name) { return false; } if (card.categories == null || currentCard.blacklistedCategories == null) { continue; } CardCategory[] categories = card.categories; foreach (CardCategory value in categories) { if (Array.IndexOf(currentCard.blacklistedCategories, value) >= 0) { return false; } } } return true; } catch { return false; } } } private void AddCard(Player p, CardInfo card) { //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) if (addCard != null) { bool flag = (Object)(object)CardBarHandler.instance != (Object)null && CardBarHandler.instance.cardBars != null && p.playerID < CardBarHandler.instance.cardBars.Length; addCard.Invoke(cardsInstance, new object[7] { p, card, false, "", 0f, 0f, flag }); } else { Object.Instantiate<GameObject>(((Component)card).gameObject, new Vector3(1000f, 1000f, 0f), Quaternion.identity).GetComponent<ApplyCardStats>().Pick(p.playerID, true, (PickerType)1); } } private void RemoveAllCards(Player p) { if (removeAll == null) { return; } try { removeAll.Invoke(cardsInstance, new object[2] { p, true }); } catch (Exception ex) { Progress("RemoveAllCards failed: " + (ex.InnerException ?? ex).Message); } } } internal static class FloatingNinjaFix { private static readonly HashSet<Player> unarmed = new HashSet<Player>(); internal static void Install() { //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Expected O, but got Unknown if (!Settings.FixFloatingNinja.Value) { return; } Type type = AccessTools.TypeByName("TTGC.Cards.FloatingNinjaCard+TransparentEffect"); if (type == null) { Type type2 = AccessTools.TypeByName("TTGC.Cards.FloatingNinjaCard"); if (type2 != null) { type = type2.GetNestedType("TransparentEffect", BindingFlags.Public | BindingFlags.NonPublic); } } MethodInfo methodInfo = ((type != null) ? AccessTools.Method(type, "OnEnable", (Type[])null, (Type[])null) : null); MethodInfo methodInfo2 = AccessTools.Method(typeof(Gun), "Attack", (Type[])null, (Type[])null); if (!(methodInfo == null) && !(methodInfo2 == null)) { Plugin.Harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(FloatingNinjaFix), "Register", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.Harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(FloatingNinjaFix), "BlockAttack", (Type[])null) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); ModPatches.Active.Add("FloatingNinjaFix"); } } private static void Register(MonoBehaviour __instance) { if ((Object)(object)__instance == (Object)null) { return; } Player component = ((Component)__instance).GetComponent<Player>(); if (!((Object)(object)component == (Object)null)) { unarmed.RemoveWhere((Player x) => (Object)(object)x == (Object)null); unarmed.Add(component); } } private static bool BlockAttack(Gun __instance, ref bool __result) { if (unarmed.Count == 0 || (Object)(object)__instance == (Object)null) { return true; } Player player = __instance.player; if ((Object)(object)player == (Object)null || !unarmed.Contains(player)) { return true; } __result = false; return false; } } internal static class CompatGuards { private static readonly Dictionary<Type, object> dummies = new Dictionary<Type, object>(); private static FieldInfo generalInputData; internal static void Install() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Expected O, but got Unknown //IL_02b7: Unknown result type (might be due to invalid IL or missing references) //IL_02c2: Expected O, but got Unknown //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Expected O, but got Unknown if (!Settings.CompatGuards.Value) { return; } HarmonyMethod val = new HarmonyMethod(typeof(CompatGuards), "NullActionsData", (Type[])null) { priority = 800 }; int num = 0; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { Type type; try { type = assembly.GetType("TabInfo.Extensions.PlayerActionsExtension", throwOnError: false); } catch { continue; } if (!(type == null)) { MethodInfo methodInfo = AccessTools.Method(type, "GetAdditionalData", (Type[])null, (Type[])null); if (!(methodInfo == null) && !methodInfo.ReturnType.IsValueType) { Plugin.Harmony.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); num++; } } } if (num > 0) { ModPatches.Active.Add("TabInfoNullGuard(" + num + ")"); } generalInputData = AccessTools.Field(typeof(GeneralInput), "data"); MethodInfo methodInfo2 = AccessTools.Method(typeof(GeneralInput), "DoUIInput", (Type[])null, (Type[])null); if (generalInputData != null && methodInfo2 != null) { Plugin.Harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(CompatGuards), "UiInputNeedsActions", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); ModPatches.Active.Add("UiInputGuard"); } string[,] array = new string[4, 2] { { "CPCCrafter.Patches.ProjHitPatch", "Prefix" }, { "CPCCore.Patches.UpwardsKnockbackPatch", "Prefix" }, { "AALUND13Cards.Classes.Patches.ProjectileHitPatch", "Prefix" }, { "SeniorProject.MonoBehaviours.ProjectileHitPatchHit", "Prefix" } }; for (int j = 0; j < array.GetLength(0); j++) { Type type2 = AccessTools.TypeByName(array[j, 0]); MethodInfo methodInfo3 = ((type2 != null) ? AccessTools.Method(type2, array[j, 1], (Type[])null, (Type[])null) : null); if (!(methodInfo3 == null)) { string text = ((methodInfo3.ReturnType == typeof(bool)) ? "ContainBoolPrefix" : "Swallow"); Plugin.Harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(CompatGuards), text, (Type[])null), (HarmonyMethod)null); ModPatches.Active.Add("HitPrefixGuard:" + type2.Name); } } MethodInfo methodInfo4 = AccessTools.Method(typeof(PlayerSkinParticle), "OnEnable", (Type[])null, (Type[])null); if (methodInfo4 != null) { Plugin.Harmony.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(CompatGuards), "Swallow", (Type[])null), (HarmonyMethod)null); ModPatches.Active.Add("SkinEnableGuard"); } } private static bool NullActionsData(object __0, MethodBase __originalMethod, ref object __result) { if (__0 != null) { return true; } Type returnType = ((MethodInfo)__originalMethod).ReturnType; if (!dummies.TryGetValue(returnType, out var value)) { try { value = Activator.CreateInstance(returnType, nonPublic: true); } catch { value = null; } dummies[returnType] = value; } if (value == null) { return true; } __result = value; return false; } private static bool UiInputNeedsActions(GeneralInput __instance) { object? value = generalInputData.GetValue(__instance); CharacterData val = (CharacterData)((value is CharacterData) ? value : null); if ((Object)(object)val != (Object)null) { return val.playerActions != null; } return false; } private static Exception Swallow(Exception __exception) { return null; } private static Exception ContainBoolPrefix(Exception __exception, ref bool __result) { if (__exception != null) { __result = true; } return null; } } internal enum DisplayMode { Game, Borderless, Exclusive, Windowed } internal class DisplayModeApplier : MonoBehaviour { private float startedAt; private bool appliedOnce; internal static void Install() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(typeof(Optionshandler), "ApplyOptions", (Type[])null, (Type[])null); if (methodInfo != null) { Plugin.Harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(DisplayModeApplier), "AfterGameApplies", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } private void Start() { startedAt = Time.realtimeSinceStartup; } private void Update() { if (!appliedOnce && !((Object)(object)Optionshandler.instance == (Object)null) && !(Time.realtimeSinceStartup - startedAt < 2f)) { appliedOnce = true; Apply(); ((Behaviour)this).enabled = false; } } private static void AfterGameApplies() { Apply(); } internal static void Apply() { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Invalid comparison between Unknown and I4 //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Invalid comparison between Unknown and I4 if (Application.isBatchMode) { return; } DisplayMode value = Settings.Display.Value; if (value == DisplayMode.Game) { return; } try { switch (value) { case DisplayMode.Borderless: { int systemWidth = Display.main.systemWidth; int systemHeight = Display.main.systemHeight; if (systemWidth > 0 && systemHeight > 0 && ((int)Screen.fullScreenMode != 1 || Screen.width != systemWidth || Screen.height != systemHeight)) { Screen.SetResolution(systemWidth, systemHeight, (FullScreenMode)1); Plugin.Log.LogInfo((object)("Display: borderless fullscreen at native " + systemWidth + "x" + systemHeight)); } break; } case DisplayMode.Exclusive: if ((int)Screen.fullScreenMode != 0) { Screen.SetResolution(((Resolution)(ref Optionshandler.resolution)).width, ((Resolution)(ref Optionshandler.resolution)).height, (FullScreenMode)0); } break; case DisplayMode.Windowed: if ((int)Screen.fullScreenMode != 3) { Screen.SetResolution(((Resolution)(ref Optionshandler.resolution)).width, ((Resolution)(ref Optionshandler.resolution)).height, (FullScreenMode)3); } break; } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Display mode could not be applied: " + ex.Message)); } } } internal static class WideScreenCards { internal static void Install() { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Expected O, but got Unknown if (Settings.CardLayoutAspect.Value <= 0f) { return; } Type type = AccessTools.TypeByName("DrawNCards.WorldToScreenExtensions"); if (!(type == null)) { MethodInfo methodInfo = AccessTools.Method(type, "WorldPoint", new Type[1] { typeof(Vector3) }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(type, "ScreenPoint", new Type[1] { typeof(Vector3) }, (Type[])null); if (methodInfo != null) { Plugin.Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(WideScreenCards), "WorldPoint", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } if (methodInfo2 != null) { Plugin.Harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(WideScreenCards), "ScreenPoint", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } ModPatches.Active.Add("WideScreenCards"); } } private static void SafeArea(out float width, out float left) { float num = Screen.width; float num2 = Screen.height; width = Mathf.Min(num, num2 * Settings.CardLayoutAspect.Value); left = (num - width) * 0.5f; } private static Camera Cam() { if (!((Object)(object)MainCam.instance != (Object)null)) { return null; } return ((Component)((Component)MainCam.instance).transform).GetComponent<Camera>(); } private static bool WorldPoint(Vector3 __0, ref Vector3 __result) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) Camera val = Cam(); if ((Object)(object)val == (Object)null) { return true; } SafeArea(out var width, out var left); Vector3 val2 = __0; val2.x = left + val2.x * width; val2.y *= Screen.height; Vector3 val3 = val.ScreenToWorldPoint(val2); val3.z = -5f; __result = val3; return false; } private static bool ScreenPoint(Vector3 __0, ref Vector3 __result) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) Camera val = Cam(); if ((Object)(object)val == (Object)null) { return true; } SafeArea(out var width, out var left); Vector3 val2 = val.WorldToScreenPoint(__0); val2.x = (val2.x - left) / width; val2.y /= Screen.height; val2.z = 0f; __result = val2; return false; } } internal static class EnginePatches { internal static readonly List<string> Active = new List<string>(); internal static void Install() { if (CommandLine.On(Settings.FastBulletRaycasts)) { Plugin.Safe("FastBulletRaycasts", BulletRaycast.Install); } if (CommandLine.On(Settings.CacheMapColliders)) { Plugin.Safe("CacheMapColliders", MapColliders.Install); } if (CommandLine.On(Settings.MultithreadedPhysics)) { Plugin.Safe("MultithreadedPhysics", EnableMultithreadedPhysics); } } private static void EnableMultithreadedPhysics() { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) if (SystemInfo.processorCount >= 4) { PhysicsJobOptions2D jobOptions = Physics2D.jobOptions; if (!((PhysicsJobOptions2D)(ref jobOptions)).useMultithreading) { ((PhysicsJobOptions2D)(ref jobOptions)).useMultithreading = true; ((PhysicsJobOptions2D)(ref jobOptions)).useConsistencySorting = true; Physics2D.jobOptions = jobOptions; Active.Add("MultithreadedPhysics"); } } } internal static bool HasForeignTranspiler(MethodBase method) { Patches patchInfo = Harmony.GetPatchInfo(method); if (patchInfo == null) { return false; } foreach (Patch transpiler in patchInfo.Transpilers) { if (!transpiler.owner.StartsWith("overdrive.rounds.performance")) { return true; } } return false; } } internal static class BulletRaycast { private struct ColliderInfo { public Transform Root; public Player Player; public bool HasPlayer; public ProjectileHitSurface Surface; public bool HasSurface; public bool InlineBullet; public bool ForwardKnown; public Vector2 RootForward; } private const int ColliderIdOffset = 32; private static RaycastHit2D[] rayBuffer = (RaycastHit2D[])(object)new RaycastHit2D[64]; private static RaycastHit2D[] circleBuffer = (RaycastHit2D[])(object)new RaycastHit2D[64]; private static readonly Dictionary<int, ColliderInfo> infoCache = new Dictionary<int, ColliderInfo>(2048); private static int cacheFrame = -1; private static float timeNow; private static bool layoutOk = true; private static bool busy; private static bool inlinePairs; private static MethodInfo hitSurface; private static float nextPatchCheck; internal static long PairsSkipped; internal static void Install() { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(typeof(RayCastTrail), "Update", (Type[])null, (Type[])null); if (EnginePatches.HasForeignTranspiler(methodInfo)) { Plugin.Log.LogInfo((object)"FastBulletRaycasts skipped: another mod rewrites RayCastTrail.Update."); return; } hitSurface = AccessTools.Method(typeof(ProjectileCollision), "HitSurface", (Type[])null, (Type[])null); Plugin.Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(BulletRaycast), "Prefix", (Type[])null) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); EnginePatches.Active.Add("FastBulletRaycasts"); } private static void RefreshInlineAllowed() { bool flag = hitSurface != null && CommandLine.On(Settings.FastBulletPairs); if (flag) { Patches patchInfo = Harmony.GetPatchInfo((MethodBase)hitSurface); if (patchInfo != null) { if (patchInfo.Transpilers.Count > 0 || patchInfo.Postfixes.Count > 0 || patchInfo.Finalizers.Count > 0) { flag = false; } foreach (Patch prefix in patchInfo.Prefixes) { if (!BulletProofOwners.IsKnownPrefix(prefix.PatchMethod)) { flag = false; } } } } inlinePairs = flag; } private static bool Prefix(RayCastTrail __instance) { if (busy) { return true; } busy = true; try { Run(__instance); } finally { busy = false; } return false; } private static void Run(RayCastTrail self) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) int frameCount = Time.frameCount; if (frameCount != cacheFrame) { cacheFrame = frameCount; infoCache.Clear(); timeNow = Time.time; BulletProofOwners.NewFrame(); if (Time.unscaledTime > nextPatchCheck) { nextPatchCheck = Time.unscaledTime + 5f; RefreshInlineAllowed(); } } Transform transform = ((Component)self).transform; Vector3 position = transform.position; Vector3 lastPos = self.lastPos; Vector2 val = Vector2.op_Implicit(lastPos); Vector2 val2 = Vector2.op_Implicit(position - lastPos); float num = Vector3.Distance(position, lastPos); int num2; for (num2 = Physics2D.RaycastNonAlloc(val, val2, rayBuffer, num, LayerMask.op_Implicit(self.mask)); num2 >= rayBuffer.Length; num2 = Physics2D.RaycastNonAlloc(val, val2, rayBuffer, num, LayerMask.op_Implicit(self.mask))) { rayBuffer = (RaycastHit2D[])(object)new RaycastHit2D[rayBuffer.Length * 2]; } int num3; for (num3 = Physics2D.CircleCastNonAlloc(val, self.size, val2, circleBuffer, num, LayerMask.op_Implicit(self.playerMask)); num3 >= circleBuffer.Length; num3 = Physics2D.CircleCastNonAlloc(val, self.size, val2, circleBuffer, num, LayerMask.op_Implicit(self.playerMask))) { circleBuffer = (RaycastHit2D[])(object)new RaycastHit2D[circleBuffer.Length * 2]; } if (num2 + num3 > 0) { RaycastHit2D best = default(RaycastHit2D); ((RaycastHit2D)(ref best)).distance = float.PositiveInfinity; Transform root = transform.root; GameObject gameObject = ((Component)self).gameObject; Vector2 ownForward = default(Vector2); bool ownForwardKnown = false; Consider(self, rayBuffer, num2, transform, root, gameObject, ref ownForward, ref ownForwardKnown, ref best); Consider(self, circleBuffer, num3, transform, root, gameObject, ref ownForward, ref ownForwardKnown, ref best); if (Object.op_Implicit((Object)(object)((RaycastHit2D)(ref best)).transform)) { self.rayHit.Hit(HitInfo.GetHitInfo(best), false); } } GridVisualizer instance = GridVisualizer.instance; if (Object.op_Implicit((Object)(object)instance)) { instance.BulletCall(Vector2.op_Implicit(transform.position)); } self.lastPos = transform.position; } private static bool Describe(ref RaycastHit2D h, out ColliderInfo info) { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown info = default(ColliderInfo); Collider2D collider = ((RaycastHit2D)(ref h)).collider; if (!Object.op_Implicit((Object)(object)collider)) { return false; } info.HasPlayer = Object.op_Implicit((Object)(object)(info.Player = ((Component)(info.Root = ((RaycastHit2D)(ref h)).transform.root)).GetComponent<Player>())); ProjectileHitSurface val = (info.Surface = ((Component)collider).GetComponent<ProjectileHitSurface>()); info.HasSurface = Object.op_Implicit((Object)(object)val); if (info.HasSurface && inlinePairs && ((object)val).GetType() == typeof(ProjectileCollision)) { info.InlineBullet = !BulletProofOwners.OwnerIsBulletProof((ProjectileCollision)val); } return true; } private unsafe static void Consider(RayCastTrail self, RaycastHit2D[] hits, int count, Transform ownTransform, Transform ownRoot, GameObject ownObject, ref Vector2 ownForward, ref bool ownForwardKnown, ref RaycastHit2D best) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < count; i++) { RaycastHit2D h = hits[i]; int num; if (layoutOk) { num = ((int*)(&h))[8]; if (num == 0) { continue; } } else { Collider2D collider = ((RaycastHit2D)(ref h)).collider; if (!Object.op_Implicit((Object)(object)collider)) { continue; } num = ((Object)collider).GetInstanceID(); } if (!infoCache.TryGetValue(num, out var value)) { if (!Describe(ref h, out value)) { continue; } if (layoutOk && ((Object)((RaycastHit2D)(ref h)).collider).GetInstanceID() != num) { layoutOk = false; num = ((Object)((RaycastHit2D)(ref h)).collider).GetInstanceID(); } infoCache[num] = value; } if (value.Root == ownRoot || (value.HasPlayer && value.Player.playerID == self.teamID && self.timeAtSpawn + 0.2f >= timeNow) || (Object.op_Implicit((Object)(object)self.ignoredRig) && (Object)(object)self.ignoredRig == (Object)(object)((RaycastHit2D)(ref h)).rigidbody)) { continue; } if (value.HasSurface) { if (value.InlineBullet) { if (!value.ForwardKnown) { value.RootForward = Vector2.op_Implicit(value.Root.forward); value.ForwardKnown = true; infoCache[num] = value; } if (!ownForwardKnown) { ownForward = Vector2.op_Implicit(ownTransform.forward); ownForwardKnown = true; } if (Vector2.Angle(value.RootForward, ownForward) < 45f) { PairsSkipped++; continue; } } HasToStop val; try { val = value.Surface.HitSurface(HitInfo.GetHitInfo(h), ownObject); } catch (Exception) { continue; } if ((int)val == 0) { continue; } } if (((RaycastHit2D)(ref h)).distance < ((RaycastHit2D)(ref best)).distance) { best = h; } } } } internal static class BulletProofOwners { private const string CardName = "BulletProof bullets"; private static readonly List<Player> players = new List<Player>(16); private static readonly List<bool> answers = new List<bool>(16); private static MethodInfo bscPrefix; private static int lastFrame = -1; internal static void Install() { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown Type type = AccessTools.TypeByName("BossSlothsCards.Patches.ProjectileCollisionPatch") ?? FindType("ProjectileCollisionPatch", "hitSurface"); if (!(type == null)) { bscPrefix = AccessTools.Method(type, "hitSurface", (Type[])null, (Type[])null); if (!(bscPrefix == null)) { Plugin.Harmony.Patch((MethodBase)bscPrefix, new HarmonyMethod(typeof(BulletProofOwners), "SkipWhenNotOwned", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); ModPatches.Active.Add("BulletProofBulletsCheck"); } } } private static Type FindType(string typeName, string method) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (!assembly.GetName().Name.StartsWith("BossSloth")) { continue; } Type[] types; try { types = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { types = ex.Types; } Type[] array = types; foreach (Type type in array) { if (type != null && type.Name == typeName && AccessTools.Method(type, method, (Type[])null, (Type[])null) != null) { return type; } } } return null; } internal static bool IsKnownPrefix(MethodInfo method) { if (bscPrefix != null) { return method == bscPrefix; } return false; } internal static void NewFrame() { players.Clear(); answers.Clear(); } internal static bool OwnerIsBulletProof(ProjectileCollision pc) { if (bscPrefix == null) { return false; } ProjectileHit componentInParent = ((Component)pc).GetComponentInParent<ProjectileHit>(); if (!Object.op_Implicit((Object)(object)componentInParent)) { return true; } Player ownPlayer = componentInParent.ownPlayer; if (!Object.op_Implicit((Object)(object)ownPlayer) || (Object)(object)ownPlayer.data == (Object)null) { return true; } return HasCard(ownPlayer); } private static bool HasCard(Player owner) { for (int i = 0; i < players.Count; i++) { if (players[i] == owner) { return answers[i]; } } bool flag = false; List<CardInfo> currentCards = owner.data.currentCards; for (int j = 0; j < currentCards.Count; j++) { CardInfo val = currentCards[j]; if ((Object)(object)val != (Object)null && val.cardName == "BulletProof bullets") { flag = true; break; } } players.Add(owner); answers.Add(flag); return flag; } private static bool SkipWhenNotOwned(ProjectileCollision __0, ref bool __result) { if (__0 == null) { return true; } if (Time.frameCount != lastFrame) { lastFrame = Time.frameCount; if (!EnginePatches.Active.Contains("FastBulletRaycasts")) { NewFrame(); } } if (OwnerIsBulletProof(__0)) { return true; } __result = true; return false; } } internal static class MapColliders { private static Collider2D[] cached; private static Component cachedFor; private static int cachedFrame = -1; private static readonly MethodInfo Replacement = AccessTools.Method(typeof(MapColliders), "Get", (Type[])null, (Type[])null); private static int replaced; internal static void Install() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown HarmonyMethod val = new HarmonyMethod(typeof(MapColliders), "Transpile", (Type[])null); Plugin.Harmony.Patch((MethodBase)AccessTools.Method(typeof(ProjectileHit), "Hit", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.Harmony.Patch((MethodBase)AccessTools.Method(typeof(ProjectileHit), "RPCA_DoHit", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null); if (replaced > 0) { EnginePatches.Active.Add("CacheMapColliders(" + replaced + ")"); } } public static Collider2D[] Get(Component map) { int frameCount = Time.frameCount; if (frameCount != cachedFrame || cachedFor != map || cached == null) { cached = map.GetComponentsInChildren<Collider2D>(); cachedFor = map; cachedFrame = frameCount; } return cached; } private static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> instructions) { foreach (CodeInstruction instruction in instructions) { MethodInfo methodInfo = instruction.operand as MethodInfo; if ((instruction.opcode == OpCodes.Callvirt || instruction.opcode == OpCodes.Call) && methodInfo != null && methodInfo.Name == "GetComponentsInChildren" && methodInfo.IsGenericMethod && methodInfo.GetParameters().Length == 0 && methodInfo.GetGenericArguments()[0] == typeof(Collider2D)) { CodeInstruction val = new CodeInstruction(OpCodes.Call, (object)Replacement); val.labels.AddRange(instruction.labels); val.blocks.AddRange(instruction.blocks); replaced++; yield return val; } else { yield return instruction; } } } } internal class TemplateSleep : MonoBehaviour { internal static int Sleeping; internal static int Templates; private static readonly HashSet<int> done = new HashSet<int>(); internal static readonly Dictionary<string, int> Masks = new Dictionary<string, int>(); internal static bool Arming; private int lastCount = -1; private float nextScan; private void Update() { if (StartupPatches.Loading) { return; } float unscaledTime = Time.unscaledTime; if (unscaledTime < nextScan) { return; } nextScan = unscaledTime + 3f; Dictionary<string, Card> cards = CardManager.cards; if (cards == null || cards.Count == lastCount) { return; } lastCount = cards.Count; int sleeping = Sleeping; foreach (KeyValuePair<string, Card> kv in cards) { if (kv.Value != null && !((Object)(object)kv.Value.cardInfo == (Object)null)) { Plugin.Safe("TemplateSleep", delegate { Process(((Component)kv.Value.cardInfo).gameObject); }); } } if (Sleeping != sleeping) { Plugin.Log.LogInfo((object)("Card templates: " + Templates + " live template objects, " + Sleeping + " idle components switched off (" + (Sleeping - sleeping) + " new).")); } } private static void Process(GameObject template) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)template == (Object)null || !done.Add(((Object)template).GetInstanceID())) { return; } Scene scene = template.scene; if (!((Scene)(ref scene)).IsValid() || !template.activeInHierarchy || (Object)(object)template.transform.parent != (Object)null || Masks.ContainsKey(((Object)template).name)) { return; } int num = 0; Gun component = template.GetComponent<Gun>(); Block component2 = template.GetComponent<Block>(); CharacterStatModifiers component3 = template.GetComponent<CharacterStatModifiers>(); ApplyCardStats component4 = template.GetComponent<ApplyCardStats>(); if ((Object)(object)component != (Object)null && ((Behaviour)component).enabled) { num |= 1; } if ((Object)(object)component2 != (Object)null && ((Behaviour)component2).enabled) { num |= 2; } if ((Object)(object)component3 != (Object)null && ((Behaviour)component3).enabled) { num |= 4; } if ((Object)(object)component4 != (Object)null && ((Behaviour)component4).enabled && !component4.shootToPick) { num |= 8; } if (num != 0) { Masks[((Object)template).name] = num; Arming = true; try { template.AddComponent<TemplateCloneWaker>(); } finally { Arming = false; } if ((num & 1) != 0) { ((Behaviour)component).enabled = false; } if ((num & 2) != 0) { ((Behaviour)component2).enabled = false; } if ((num & 4) != 0) { ((Behaviour)component3).enabled = false; } if ((num & 8) != 0) { ((Behaviour)component4).enabled = false; } Templates++; Sleeping += (((num & 1) != 0) ? 1 : 0) + (((num & 2) != 0) ? 1 : 0) + (((num & 4) != 0) ? 1 : 0) + (((num & 8) != 0) ? 1 : 0); } } } internal class TemplateCloneWaker : MonoBehaviour { private void Awake() { if (TemplateSleep.Arming) { return; } string text = ((Object)((Component)this).gameObject).name; if (text.EndsWith("(Clone)")) { text = text.Substring(0, text.Length - 7); } if (!TemplateSleep.Masks.TryGetValue(text, out var value)) { value = 15; } if ((value & 1) != 0) { Gun component = ((Component)this).GetComponent<Gun>(); if ((Object)(object)component != (Object)null) { ((Behaviour)component).enabled = true; } } if ((value & 2) != 0) { Block component2 = ((Component)this).GetComponent<Block>(); if ((Object)(object)component2 != (Object)null) { ((Behaviour)component2).enabled = true; } } if ((value & 4) != 0) { CharacterStatModifiers component3 = ((Component)this).GetComponent<CharacterStatModifiers>(); if ((Object)(object)component3 != (Object)null) { ((Behaviour)component3).enabled = true; } } if ((value & 8) != 0) { ApplyCardStats component4 = ((Component)this).GetComponent<ApplyCardStats>(); if ((Object)(object)component4 != (Object)null) { ((Behaviour)component4).enabled = true; } } Object.Destroy((Object)(object)this); } } internal static class ExceptionFirewall { private class Counter { internal int WindowStart; internal int Count; internal bool Done; internal string LastMessage; } private class Streak { internal int Throws; internal int SkipUntilFrame; } private sealed class ByReference : IEqualityComparer<object> { bool IEqualityComparer<object>.Equals(object a, object b) { return a == b; } int IEqualityComparer<object>.GetHashCode(object o) { return RuntimeHelpers.GetHashCode(o); } } [CompilerGenerated] private static class <>O { public static LogCallback <0>__OnLog; } private static readonly HashSet<string> EntryPoints = new HashSet<string> { "Update", "FixedUpdate", "LateUpdate", "OnGUI", "OnRenderObject", "OnWillRenderObject", "OnTriggerStay2D", "OnCollisionStay2D", "OnTriggerEnter2D", "OnTriggerExit2D", "OnCollisionEnter2D", "OnCollisionExit2D", "OnParticleCollision" }; private static readonly HashSet<string> Throttled = new HashSet<string> { "Update", "FixedUpdate", "LateUpdate", "OnGUI" }; private const int WindowMs = 10000; private static readonly Dictionary<string, Counter> counters = new Dictionary<string, Counter>(64); private static readonly List<KeyValuePair<string, Counter>> pending = new List<KeyValuePair<string, Counter>>(); private static readonly Dictionary<Type, int> swallowedByType = new Dictionary<Type, int>(); private static readonly HashSet<MethodBase> wrapped = new HashSet<MethodBase>(); private static readonly Dictionary<object, Streak> streaks = new Dictionary<object, Streak>(new ByReference()); private static readonly List<object> purge = new List<object>(); private static int threshold = 15; private static int maxSkip = 30; private static float nextSummary; private static float nextPurge; internal static long TotalSwallowed; internal static long TotalSkipped; internal static int WrappedCount => wrapped.Count; internal static void Install() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown if (CommandLine.On(Settings.FirewallEnabled)) { threshold = Settings.FirewallThreshold.Value; maxSkip = Settings.FirewallBackoff.Value; object obj = <>O.<0>__OnLog; if (obj == null) { LogCallback val = OnLog; <>O.<0>__OnLog = val; obj = (object)val; } Application.logMessageReceived += (LogCallback)obj; } } private static void OnLog(string condition, string stackTrace, LogType type) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 if ((int)type != 4 || string.IsNullOrEmpty(stackTrace)) { return; } int num = stackTrace.Length; while (num > 0 && (stackTrace[num - 1] == '\n' || stackTrace[num - 1] == '\r' || stackTrace[num - 1] == ' ')) { num--; } if (num <= 0) { return; } int num2 = stackTrace.LastIndexOf('\n', num - 1) + 1; int num3 = stackTrace.IndexOf('(', num2, num - num2); if (num3 <= num2) { return; } int num4 = num3; while (num4 > num2 && stackTrace[num4 - 1] == ' ') { num4--; } string key = stackTrace.Substring(num2, num4 - num2); if (!counters.TryGetValue(key, out var value)) { if (counters.Count > 2048) { counters.Clear(); } value = new Counter { WindowStart = Environment.TickCount }; counters[key] = value; } if (!value.Done) { int tickCount = Environment.TickCount; if (tickCount - value.WindowStart > 10000) { value.WindowStart = tickCount; value.Count = 0; } value.Count++; if (value.Count >= threshold) { value.Done = true; value.LastMessage = condition; pending.Add(new KeyValuePair<string, Counter>(key, value)); } } } internal static void Tick() { if (pending.Count > 0) { for (int i = 0; i < pending.Count; i++) { string frame = pending[i].Key; string msg = pending[i].Value.LastMessage; Plugin.Safe("Firewall " + frame, delegate { Wrap(frame, msg); }); } pending.Clear(); } float unscaledTime = Time.unscaledTime; if (streaks.Count > 0 && unscaledTime > nextPurge) { nextPurge = unscaledTime + 4f; purge.Clear(); foreach (KeyValuePair<object, Streak> streak in streaks) { object key = streak.Key; Object val = (Object)((key is Object) ? key : null); if (streak.Key == null || (val != null && val == (Object)null)) { purge.Add(streak.Key); } } for (int num = 0; num < purge.Count; num++) { streaks.Remove(purge[num]); } purge.Clear(); } if (TotalSwallowed > 0 && unscaledTime > nextSummary) { nextSummary = unscaledTime + 120f; Plugin.Log.LogInfo((object)Summary()); } } internal static string Summary() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Exception firewall: ").Append(TotalSwallowed).Append(" exceptions caught quietly, ") .Append(TotalSkipped) .Append(" doomed calls not attempted"); int num = 0; foreach (KeyValuePair<Type, int> item in swallowedByType) { if (num++ >= 6) { break; } stringBuilder.Append((num == 1) ? " (" : ", ").Append(item.Key.Name).Append(": ") .Append(item.Value); } if (num > 0) { stringBuilder.Append(")"); } return stringBuilder.ToString(); } private static void Wrap(string frame, string message) { //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Expected O, but got Unknown //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Expected O, but got Unknown //IL_01cb: Expected O, but got Unknown int num = frame.LastIndexOf('.'); if (num <= 0) { return; } string text = frame.Substring(0, num); string text2 = frame.Substring(num + 1); if (!EntryPoints.Contains(text2) || text.IndexOf('[') >= 0 || text.IndexOf('`') >= 0) { return; } Type type = null; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { type = assemblies[i].GetType(text, throwOnError: false); if (type != null) { break; } } if (type == null || !typeof(MonoBehaviour).IsAssignableFrom(type) || type.Assembly == typeof(ExceptionFirewall).Assembly) { return; } MethodInfo methodInfo = null; MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo2 in methods) { if (methodInfo2.Name == text2 && methodInfo2.ReturnType == typeof(void) && !methodInfo2.IsAbstract && !methodInfo2.IsGenericMethod && methodInfo2.GetMethodBody() != null) { methodInfo = methodInfo2; break; } } if (!(methodInfo == null) && !wrapped.Contains(methodInfo)) { bool flag = type.Assembly == typeof(RayCastTrail).Assembly; bool flag2 = maxSkip > 0 && !flag && Throttled.Contains(text2) && methodInfo.GetParameters().Length == 0; if (flag2) { Plugin.Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ExceptionFirewall), "Gate", (Type[])null) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(ExceptionFirewall), "SwallowAndBackOff", (Type[])null), (HarmonyMethod)null); } else { Plugin.Harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(ExceptionFirewall), "Swallow", (Type[])null), (HarmonyMethod)null); } wrapped.Add(methodInfo); string text3 = message ?? ""; int num2 = text3.IndexOf('\n'); if (num2 > 0) { text3 = text3.Substring(0, num2); } Plugin.Log.LogWarning((object)(frame + "() threw " + threshold + "+ exceptions within 10 seconds (" + text3 + "). Overdrive now catches them at the source so they no longer flood the log" + (flag2 ? ", and retries a component that keeps failing only every few frames." : "."))); } } private static void Count(object instance) { TotalSwallowed++; FrameStats.ExceptionCount++; Type key = ((instance != null) ? instance.GetType() : typeof(object)); swallowedByType.TryGetValue(key, out var value); swallowedByType[key] = value + 1; } private static Exception Swallow(Exception __exception, object __instance) { if (__exception != null) { Count(__instance); } return null; } private static bool Gate(object __instance, out bool __state) { __state = false; if (streaks.Count == 0) { return true; } if (__instance == null || !streaks.TryGetValue(__instance, out var value)) { return true; } if (Time.frameCount < value.SkipUntilFrame) { __state = true; TotalSkipped++; return false; } return true; } private static Exception SwallowAndBackOff(Exception __exception, object __instance, bool __state) { if (__exception == null) { if (!__state && streaks.Count != 0 && __instance != null) { streaks.Remove(__instance); } return null; } Count(__instance); if (__instance != null) { if (!streaks.TryGetValue(__instance, out var value)) { value = new Streak(); streaks[__instance] = value; } value.Throws++; int num = ((value.Throws >= 3) ? Math.Min(1 << Math.Min(value.Throws - 3, 10), maxSkip) : 0); value.SkipUntilFrame = Time.frameCount + num + 1; } return null; } } internal struct FrameSummary { internal int Frames; internal double Seconds; internal double AvgMs; internal double P50Ms; internal double P95Ms; internal double P99Ms; internal double P999Ms; internal double MaxMs; internal double AvgFps; internal double Low1Fps; internal double Low01Fps; internal int Over6Ms; internal int Over16Ms; internal int Over33Ms; internal int GcCollections; internal long HeapStartBytes; internal long HeapEndBytes; internal int PeakBullets; internal double AvgBullets; internal int Exceptions; } internal class FrameStats : MonoBehaviour { [CompilerGenerated] private static class <>O { public static Action <0>__Install; public static LogCallback <1>__CountExceptions; } internal static FrameStats Instance; private const int RingSize = 1024; private readonly float[] ring = new float[1024]; private int ringPos; private int ringCount; private long lastTicks; private bool capturing; private readonly List<float> capture = new List<float>(65536); private int gcAtStart; private long heapAtStart; private int excAtStart; private long bulletSamples; private long bulletSum; private int bulletPeak; internal static int ExceptionCount; private void Awake() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown Instance = this; lastTicks = Stopwatch.GetTimestamp(); Plugin.Safe("BulletTracker", BulletTracker.Install); object obj = <>O.<1>__CountExceptions; if (obj == null) { LogCallback val = CountExceptions; <>O.<1>__CountExceptions = val; obj = (object)val; } Application.logMessageReceived += (LogCallback)obj; } private static void CountExceptions(string condition, string stackTrace, LogType type) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 if ((int)type == 4) { ExceptionCount++; } } private void Update() { ExceptionFirewall.Tick(); if ((Object)(object)Hud.Instance != (Object)null) { Hud.Instance.Poll(); } long timestamp = Stopwatch.GetTimestamp(); float num = (float)((double)(timestamp - lastTicks) * 1000.0 / (double)Stopwatch.Frequency); lastTicks = timestamp; ring[ringPos] = num; ringPos = (ringPos + 1) % 1024; if (ringCount < 1024) { ringCount++; } if (capturing) { capture.Add(num); int live = BulletTracker.Live; bulletSum += live; bulletSamples++; if (live > bulletPeak) { bulletPeak = live; } } } internal void BeginCapture() { capture.Clear(); capturing = true; gcAtStart = GC.CollectionCount(0); heapAtStart = GC.GetTotalMemory(forceFullCollection: false); excAtStart = ExceptionCount; bulletSamples = (bulletSum = 0L); bulletPeak = 0; } internal FrameSummary EndCapture() { capturing = false; FrameSummary result = Summarize(capture); result.GcCollections = GC.CollectionCount(0) - gcAtStart; result.HeapStartBytes = heapAtStart; result.HeapEndBytes = GC.GetTotalMemory(forceFullCollection: false); result.Exceptions = ExceptionCount - excAtStart; result.PeakBullets = bulletPeak; result.AvgBullets = ((bulletSamples > 0) ? ((double)bulletSum / (double)bulletSamples) : 0.0); return result; } internal FrameSummary Recent(int frames) { List<float> list = new List<float>(frames); int num = Math.Min(frames, ringCount); for (int i = 0; i < num; i++) { int num2 = (ringPos - 1 - i + 2048) % 1024; list.Add(ring[num2]); } return Summarize(list); } internal static FrameSummary Summarize(List<float> frames) { FrameSummary result = new FrameSummary { Frames = frames.Count }; if (frames.Count == 0) { return result; } float[] array = frames.ToArray(); Array.Sort(array); double num = 0.0; foreach (float num2 in array) { num += (double)num2; if (num2 > 6.0606f) { result.Over6Ms++; } if (num2 > 16.667f) { result.Over16Ms++; } if (num2 > 33.333f) { result.Over33Ms++; } } result.Seconds = num / 1000.0; result.AvgMs = num / (double)array.Length; result.P50Ms = Pct(array, 0.5); result.P95Ms = Pct(array, 0.95); result.P99Ms = Pct(array, 0.99); result.P999Ms = Pct(array, 0.999); result.MaxMs = array[^1]; result.AvgFps = 1000.0 / result.AvgMs; result.Low1Fps = 1000.0 / AvgOfWorst(array, 0.01); result.Low01Fps = 1000.0 / AvgOfWorst(array, 0.001); return result; } private static double Pct(float[] sorted, double p) { int num = (int)Math.Ceiling(p * (double)sorted.Length) - 1; if (num < 0) { num = 0; } if (num >= sorted.Length) { num = sorted.Length - 1; } return sorted[num]; } private static double AvgOfWorst(float[] sorted, double fraction) { int num = Math.Max(1, (int)Math.Round((double)sorted.Length * fraction)); double num2 = 0.0; for (int i = sorted.Length - num; i < sorted.Length; i++) { num2 += (double)sorted[i]; } return num2 / (double)num; } } internal static class BulletTracker { private static readonly List<ProjectileHit> live = new List<ProjectileHit>(1024); private static int lastPruneFrame = -1; internal static int TotalSpawned; internal static int Live { get { int frameCount = Time.frameCount; if (frameCount != lastPruneFrame) { lastPruneFrame = frameCount; for (int num = live.Count - 1; num >= 0; num--) { if ((Object)(object)live[num] == (Object)null) { int index = live.Count - 1; live[num] = live[index]; live.RemoveAt(index); } } } return live.Count; } } internal static void Install() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(typeof(ProjectileHit), "Start", (Type[])null, (Type[])null); Plugin.Harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(BulletTracker), "OnStart", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static void OnStart(ProjectileHit __instance) { live.Add(__instance); if ((++TotalSpawned & 0xFF) == 0) { _ = Live; } } } internal class GcGovernor : MonoBehaviour { internal static string StateText = "vanilla"; internal static double LastCollectMs; internal static int ForcedCollections; private bool deferred; private long heapAtDefer; private long budgetBytes; private int frame; private float battleEndedAt = -1f; private float nextCapCheck; private void Start() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown int num = Settings.GcHeapBudgetMb.Value; int systemMemorySize = SystemInfo.systemMemorySize; if (systemMemorySize > 0) { num = Mathf.Min(num, Mathf.Max(256, systemMemorySize / 6)); } budgetBytes = (long)num * 1024L * 1024; Application.lowMemory += new LowMemoryCallback(OnLowMemory); } private void OnDestroy() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown Application.lowMemory -= new LowMemoryCallback(OnLowMemory); SetDeferred(value: false); } private void OnApplicationQuit() { SetDeferred(value: false); } private void OnLowMemory() { if (deferred) { Collect("low memory"); } } private static void ApplyFrameCap() { int value = Settings.TargetFrameRate.Value; if (value > 0 && QualitySettings.vSyncCount <= 0 && CommandLine.Bench == null && Application.targetFrameRate != value) { Application.targetFrameRate = value; } } private void Update() { if (Time.unscaledTime > nextCapCheck) { nextCapCheck = Time.unscaledTime + 2f; ApplyFrameCap(); } if (Settings.Gc.Value != GcMode.DeferDuringBattle || CommandLine.Disabled.Contains("GarbageCollection")) { if (deferred) { SetDeferred(value: false); } StateText = "vanilla"; return; } GameManager instance = GameManager.instance; if ((Object)(object)instance != (Object)null && instance.battleOngoing && instance.isPlaying) { battleEndedAt = -1f; if (!deferred) { SetDeferred(value: true); } else if ((++frame & 0x3F) == 0 && GC.GetTotalMemory(forceFullCollection: false) - heapAtDefer > budgetBytes) { Collect("heap budget reached"); ForcedCollections++; } } else if (deferred) { Collect("point end"); SetDeferred(value: false); battleEndedAt = Time.unscaledTime; } StateText = (deferred ? "deferred" : "normal"); } private void SetDeferred(bool value) { if (deferred != value) { deferred = value; try { GarbageCollector.GCMode = (Mode)(!value); } catch (Exception ex) { Plugin.Log.LogWarning((object)("GC mode switch failed, leaving the collector alone: " + ex.Message)); Settings.Gc.Value = GcMode.Vanilla; deferred = false; return; } if (value) { heapAtDefer = GC.GetTotalMemory(forceFullCollection: false); } } } private void Collect(string why) { Stopwatch stopwatch = Stopwatch.StartNew(); bool flag = deferred; try { if (flag) { GarbageCollector.GCMode = (Mode)1; } GC.Collect(); if (flag) { GarbageCollector.GCMode = (Mode)0; } } catch { } LastCollectMs = stopwatch.Elapsed.TotalMilliseconds; heapAtDefer = GC.GetTotalMemory(forceFullCollection: false); } } internal class Hud : MonoBehaviour { internal static Hud Instance; private static string flash; private static float flashUntil; private string text = ""; private float nextRefresh; private GUIStyle style; private Texture2D background; private bool show; private void Awake() { Instance = this; show = Settings.HudEnabled.Value; ((Behaviour)this).enabled = show; } internal static void Flash(string message) { flash = message; flashUntil = Time.unscaledTime + 10f; if ((Object)(object)Instance != (Object)null) { ((Behaviour)Instance).enabled = true; } } internal void Poll() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = Settings.HudKey.Value; if (((KeyboardShortcut)(ref value)).IsDown()) { show = !show; Settings.HudEnabled.Value = show; } if (!Benchmark.Running) { value = Settings.BenchKey.Value; if (((KeyboardShortcut)(ref value)).IsDown() && (Object)(object)MainMenuHandler.instance != (Object)null) { BenchSpec benchSpec = new BenchSpec(); benchSpec.Seeds = new int[3] { 1, 2, 3 }; benchSpec.Tag = "manual"; benchSpec.Quit = false; BenchSpec spec = benchSpec; ((Component)this).gameObject.AddComponent<Benchmark>().Spec = spec; Flash("Overdrive benchmark started - hands off for about two minutes..."); } } bool flag = show || Time.unscaledTime < flashUntil; if (((Behaviour)this).enabled != flag) { ((Behaviour)this).enabled = flag; } } private void OnGUI() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Expected O, but got Unknown //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) if ((int)Event.current.type == 7) { if (style == null) { background = new Texture2D(1, 1); background.SetPixel(0, 0, new Color(0f, 0f, 0f, 0.6f)); background.Apply(); style = new GUIStyle(GUI.skin.label) { fontSize = Mathf.Max(13, Screen.height / 80), richText = false }; style.normal.textColor = Color.white; style.normal.background = background; style.padding = new RectOffset(8, 8, 6, 6); } if (Time.unscaledTime > nextRefresh) { nextRefresh = Time.unscaledTime + 0.25f; text = Build(); } Vector2 val = style.CalcSize(new GUIContent(text)); GUI.Label(new Rect(10f, 10f, val.x, val.y), text, style); } } private string Build() { CultureInfo invariantCulture = CultureInfo.InvariantCulture; StringBuilder stringBuilder = new StringBuilder(256); if (Time.unscaledTime < flashUntil && flash != null) { stringBuilder.AppendLine(flash); } if (show && (Object)(object)FrameStats.Instance != (Object)null) { FrameSummary frameSummary = FrameStats.Instance.Recent(120); FrameSummary frameSummary2 = FrameStats.Instance.Recent(1000); stringBuilder.AppendFormat(invariantCulture, "Overdrive {0} {1:F0} fps 1% low {2:F0} worst {3:F1} ms\n", "1.1.0", frameSummary.AvgFps, frameSummary2.Low1Fps, frameSummary2.MaxMs); stringBuilder.AppendFormat(invariantCulture, "bullets {0} GC {1} ({2}) heap {3:F0} MB\n", BulletTracker.Live, GC.CollectionCount(0), GcGovernor.StateText, (double)GC.GetTotalMemory(forceFullCollection: false) / 1048576.0); stringBuilder.AppendFormat(invariantCulture, "log lines suppressed {0} exceptions caught {1} in {2} methods", LogGuard.TotalSuppressed, ExceptionFirewall.TotalSwallowed, ExceptionFirewall.WrappedCount); if (!string.IsNullOrEmpty(NetStats.HudLine)) { stringBuilder.Append("\n").Append(NetStats.HudLine); } } return stringBuilder.ToString().TrimEnd(Array.Empty<char>()); } } internal static class KillCounterFix { private static FieldInfo playerField; private static FieldInfo killsField; internal static void Install() { //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown //IL_00b8: Expected O, but got Unknown //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown if (!Settings.FixKillCounter.Value) { return; } Type type = AccessTools.TypeByName("Simple_Gamemodes.Monos.Timed_Kills"); if (type == null) { return; } playerField = AccessTools.Field(type, "player"); killsField = AccessTools.Field(type, "_kills"); MethodInfo methodInfo = AccessTools.PropertyGetter(type, "Kills"); MethodInfo methodInfo2 = AccessTools.Method(type, "UpdateScore", (Type[])null, (Type[])null); if (!(playerField == null) && !(killsField == null) && !(methodInfo == null)) { Plugin.Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(KillCounterFix), "BeforeKills", (Type[])null), new HarmonyMethod(typeof(KillCounterFix), "AfterKills", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); if (methodInfo2 != null) { Plugin.Harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(KillCounterFix), "BeforeKills", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } ModPatches.Active.Add("KillCounterFix"); } } private static void BeforeKills(MonoBehaviour __instance) { if ((Object)(object)__instance == (Object)null) { return; } object? value = playerField.GetValue(__instance); if ((Object)((value is Player) ? value : null) == (Object)null) { Player componentInParent = ((Component)__instance).GetComponentInParent<Player>(); if ((Object)(object)componentInParent != (Object)null) { playerField.SetValue(__instance, componentInParent); } } object? value2 = killsField.GetValue(__instance); GameObject val = (GameObject)((value2 is GameObject) ? value2 : null); if ((Object)(object)val != (Object)null && (Object)(object)val.transform.parent == (Object)null && playerField.GetValue(__instance) != null) { Object.Destroy((Object)(object)val); killsField.SetValue(__instance, null); } } private static void AfterKills(MonoBehaviour __instance, GameObject __result) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__result == (Object)null) { return; } Canvas component = __result.GetComponent<Canvas>(); if ((Object)(object)component == (Object)null || (int)component.renderMode == 2) { return; } component.renderMode = (RenderMode)2; object? value = playerField.GetValue(__instance); Player val = (Player)((value is Player) ? value : null); Transform val2 = (((Object)(object)val != (Object)null) ? ((Component)val).transform.Find("WobbleObjects/Healthbar/Canvas") : null); Canvas val3 = (((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponent<Canvas>() : null); if ((Object)(object)val3 != (Object)null) { component.sortingLayerID = val3.sortingLayerID; component.sortingOrder = val3.sortingOrder + 1; } else { component.sortingLayerName = "MostFront"; } if ((Object)(object)val != (Object)null) { if ((Object)(object)__result.transform.parent == (Object)null) { __result.transform.SetParent(((Component)val).transform, true); } Transform val4 = ((Component)val).transform.Find("WobbleObjects/Healthbar/Canvas/CrownPos"); if ((Object)(object)val4 != (Object)null) { __result.transform.position = val4.position + Vector3.up; } } } } internal static class LogGuard { private class Entry { internal int WindowStart; internal int Count; internal int Suppressed; } private class Handler : ILogHandler { internal ILogHandler Inner; public void LogFormat(LogType logType, Object context, string format, params object[] args) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (!Admit(logType, format, args, out var suppressedBefore)) { return; } if (suppressedBefore > 0) { string text; try { text = ((args == null || args.Length == 0) ? format : string.Format(format, args)); } catch { text = format; } Inner.LogFormat(logType, context, "{0}", new object[1] { text + "\n[Overdrive] the line above repeated " + suppressedBefore + " more times and was not written." }); } else { Inner.LogFormat(logType, context, format, args); } } public void LogException(Exception exception, Object context) { string format = ((exception == null) ? "null" : (exception.GetType().Name + ((exception.TargetSite != null) ? exception.TargetSite.Name : ""))); if (!Admit((LogType)4, format, null, out var _)) { FrameStats.ExceptionCount++; } else { Inner.LogException(exception, context); } } } private const int WindowMs = 10000; private static readonly Dictionary<int, Entry> seen = new Dictionary<int, Entry>(256); private static readonly object gate = new object(); private static int limit = 3; internal static long TotalSuppressed; internal static void Install() { if (CommandLine.On(Settings.NoCrashReports)) { Plugin.Safe("NoCrashReports", delegate { CrashReportHandler.enableCaptureExceptions = false; }); } if (!CommandLine.On(Settings.LogGuardEnabled)) { return; } limit = Settings.LogRepeatLimit.Value; Settings.LogRepeatLimit.SettingChanged += delegate { limit = Settings.LogRepeatLimit.Value; }; ILogHandler logHandler = Debug.unityLogger.logHandler; if (!(logHandler is Handler)) { Debug.unityLogger.logHandler = (ILogHandler)(object)new Handler { Inner = logHandler }; } if (Settings.StripStackTraces.Value) { Application.SetStackTraceLogType((LogType)3, (StackTraceLogType)0); Application.SetStackTraceLogType((LogType)2, (StackTraceLogType)0); } if (!Settings.SilenceNullSounds.Value) { return; } Plugin.Safe("Sonigon warnings", delegate { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown Type type = AccessTools.TypeByName("Sonigon.Internal.SoundManagerDataSetting"); MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "GetDebugWarnings", (Type[])null, (Type[])null)); if (methodInfo != null) { Plugin.Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(LogGuard), "NoDebugWarnings", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } }); } private static bool NoDebugWarnings(ref bool __result) { __result = false; return false; } private static int Hash(string s, int h) { if (s == null) { return h; } int num = ((s.Length < 200) ? s.Length : 200); for (int i = 0; i < num; i++) { char c = s[i]; if (c < '0' || c > '9') { h = (h ^ c) * 16777619; } } return h; } private st