Decompiled source of BonkBook v0.8.6
plugins/BonkBook.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using BonkBook.Patches; using BonkBook.Ui; using Epic.OnlineServices; using Epic.OnlineServices.Connect; using HarmonyLib; using Microsoft.CodeAnalysis; using Mirror; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Steamworks; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.InputSystem.UI; using UnityEngine.InputSystem.Utilities; using UnityEngine.SceneManagement; using UnityEngine.TextCore; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("GameAssembly")] [assembly: IgnoresAccessChecksTo("SharedAssembly")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BonkBook")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.8.6.0")] [assembly: AssemblyInformationalVersion("0.8.6+6dcdfb10769676215f48e11bd5e12bd5314c0991")] [assembly: AssemblyProduct("BonkBook")] [assembly: AssemblyTitle("BonkBook")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.8.6.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BonkBook { internal static class InputGuard { private static bool _gameFlagsBroken; public static string? TypingReason() { if (GUIUtility.keyboardControl != 0) { return "IMGUI keyboard focus"; } if (!_gameFlagsBroken) { try { string text = GameTypingReason(); if (text != null) { return text; } } catch (Exception ex) { _gameFlagsBroken = true; Plugin.Log.LogWarning((object)("Game typing-state check disabled (" + ex.GetType().Name + ": " + ex.Message + "); only the EventSystem/IMGUI checks remain.")); } } EventSystem current = EventSystem.current; GameObject val = (((Object)(object)current != (Object)null) ? current.currentSelectedGameObject : null); if ((Object)(object)val == (Object)null) { return null; } TMP_InputField val2 = default(TMP_InputField); InputField val3 = default(InputField); if ((val.TryGetComponent<TMP_InputField>(ref val2) && ((Behaviour)val2).isActiveAndEnabled && ((Selectable)val2).interactable) || (val.TryGetComponent<InputField>(ref val3) && ((Behaviour)val3).isActiveAndEnabled && ((Selectable)val3).interactable)) { return "text field '" + ((Object)val).name + "' selected"; } return null; } [MethodImpl(MethodImplOptions.NoInlining)] private static string? GameTypingReason() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: 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_0025: Unknown result type (might be due to invalid IL or missing references) if (TextChatUi.IsOpen) { return "text chat open"; } InputMode currentModeMask = InputManager.CurrentModeMask; if ((currentModeMask & 0x80) != 0) { return "text chat input mode"; } if ((currentModeMask & 0x40) != 0 || DevConsoleGui.Active) { return "dev console open"; } ControlsRebind[] array = Object.FindObjectsByType<ControlsRebind>((FindObjectsSortMode)0); foreach (ControlsRebind val in array) { if ((Object)(object)val != (Object)null && val.rebindOperation != null) { return "rebinding a control"; } } return null; } } public class StatTotals { public int KnockoutsDealt { get; set; } public int KnockoutsReceived { get; set; } public int SelfKnockouts { get; set; } public int EliminationsDealt { get; set; } public int EliminationsReceived { get; set; } public int SelfEliminations { get; set; } public int HolesPlayed { get; set; } public int MatchesFinished { get; set; } [JsonIgnore] public bool IsZero { get { if (KnockoutsDealt == 0 && KnockoutsReceived == 0 && SelfKnockouts == 0 && EliminationsDealt == 0 && EliminationsReceived == 0 && SelfEliminations == 0 && HolesPlayed == 0) { return MatchesFinished == 0; } return false; } } public void Add(StatTotals other) { KnockoutsDealt += other.KnockoutsDealt; KnockoutsReceived += other.KnockoutsReceived; SelfKnockouts += other.SelfKnockouts; EliminationsDealt += other.EliminationsDealt; EliminationsReceived += other.EliminationsReceived; SelfEliminations += other.SelfEliminations; HolesPlayed += other.HolesPlayed; MatchesFinished += other.MatchesFinished; } } public class OpponentStats { public string LastKnownName { get; set; } = ""; public int KnockedOutByMe { get; set; } public int KnockedMeOut { get; set; } public int EliminatedByMe { get; set; } public int EliminatedMe { get; set; } public int HolesTogether { get; set; } public int MatchesTogether { get; set; } public DateTime LastSeenUtc { get; set; } [JsonIgnore] public int TotalInteractions => KnockedOutByMe + KnockedMeOut + EliminatedByMe + EliminatedMe; public void Add(OpponentStats other) { KnockedOutByMe += other.KnockedOutByMe; KnockedMeOut += other.KnockedMeOut; EliminatedByMe += other.EliminatedByMe; EliminatedMe += other.EliminatedMe; HolesTogether += other.HolesTogether; MatchesTogether += other.MatchesTogether; if (other.LastSeenUtc > LastSeenUtc) { LastSeenUtc = other.LastSeenUtc; if (!string.IsNullOrEmpty(other.LastKnownName)) { LastKnownName = other.LastKnownName; } } if (string.IsNullOrEmpty(LastKnownName)) { LastKnownName = other.LastKnownName; } } } public class PairStats { public string Attacker { get; set; } = ""; public string Victim { get; set; } = ""; public int Knockouts { get; set; } public int Eliminations { get; set; } public DateTime LastSeenUtc { get; set; } public void Add(PairStats other) { Knockouts += other.Knockouts; Eliminations += other.Eliminations; if (other.LastSeenUtc > LastSeenUtc) { LastSeenUtc = other.LastSeenUtc; } } } public class StatsView { private Dictionary<(string, string), PairStats>? _pairIndex; public StatTotals Totals { get; set; } = new StatTotals(); public Dictionary<string, OpponentStats> Opponents { get; set; } = new Dictionary<string, OpponentStats>(); public List<PairStats> Pairs { get; set; } = new List<PairStats>(); public Dictionary<string, string> Names { get; set; } = new Dictionary<string, string>(); private Dictionary<(string, string), PairStats> PairIndex { get { if (_pairIndex == null) { RebuildPairIndex(); } return _pairIndex; } } [JsonIgnore] public bool IsEmpty { get { if (Totals.IsZero && Opponents.Count == 0) { return Pairs.Count == 0; } return false; } } public PairStats GetPair(in ResolvedPlayer attacker, in ResolvedPlayer victim) { PairStats orAddPair = GetOrAddPair(attacker.Key, victim.Key); orAddPair.LastSeenUtc = DateTime.UtcNow; Names[attacker.Key] = attacker.Name; Names[victim.Key] = victim.Name; return orAddPair; } private PairStats GetOrAddPair(string attacker, string victim) { if (!PairIndex.TryGetValue((attacker, victim), out PairStats value)) { value = new PairStats { Attacker = attacker, Victim = victim }; Pairs.Add(value); PairIndex[(attacker, victim)] = value; } return value; } public bool TryGetPair(string attackerKey, string victimKey, out PairStats? pair) { return PairIndex.TryGetValue((attackerKey, victimKey), out pair); } public string? NameOf(string key) { if (Names.TryGetValue(key, out string value) && !string.IsNullOrEmpty(value)) { return value; } if (Opponents.TryGetValue(key, out OpponentStats value2) && !string.IsNullOrEmpty(value2.LastKnownName)) { return value2.LastKnownName; } return null; } private void RebuildPairIndex() { Dictionary<(string, string), PairStats> dictionary = new Dictionary<(string, string), PairStats>(); List<PairStats> list = new List<PairStats>(Pairs.Count); foreach (PairStats pair in Pairs) { if (pair != null && !string.IsNullOrEmpty(pair.Attacker) && !string.IsNullOrEmpty(pair.Victim) && !(pair.Attacker == pair.Victim)) { (string, string) key = (pair.Attacker, pair.Victim); if (dictionary.TryGetValue(key, out var value)) { value.Add(pair); continue; } dictionary[key] = pair; list.Add(pair); } } Pairs = list; _pairIndex = dictionary; } public OpponentStats GetOpponent(in ResolvedPlayer player) { if (!Opponents.TryGetValue(player.Key, out OpponentStats value)) { value = new OpponentStats(); Opponents[player.Key] = value; } value.LastKnownName = player.Name; value.LastSeenUtc = DateTime.UtcNow; return value; } public bool Merge(string oldKey, string newKey) { if (oldKey == newKey) { return false; } bool flag = false; if (Opponents.TryGetValue(oldKey, out OpponentStats value)) { Opponents.Remove(oldKey); if (Opponents.TryGetValue(newKey, out OpponentStats value2)) { value2.Add(value); } else { Opponents[newKey] = value; } flag = true; } bool flag2 = false; foreach (PairStats pair in Pairs) { if (pair.Attacker == oldKey) { pair.Attacker = newKey; flag2 = true; } if (pair.Victim == oldKey) { pair.Victim = newKey; flag2 = true; } } if (flag2) { RebuildPairIndex(); } if (Names.TryGetValue(oldKey, out string value3)) { Names.Remove(oldKey); if (!Names.ContainsKey(newKey)) { Names[newKey] = value3; } flag = true; } return flag || flag2; } public void AddFrom(StatsView other) { Totals.Add(other.Totals); foreach (KeyValuePair<string, OpponentStats> opponent in other.Opponents) { if (opponent.Value != null) { if (!Opponents.TryGetValue(opponent.Key, out OpponentStats value)) { value = new OpponentStats(); Opponents[opponent.Key] = value; } value.Add(opponent.Value); } } foreach (PairStats pair in other.Pairs) { if (pair != null && !string.IsNullOrEmpty(pair.Attacker) && !string.IsNullOrEmpty(pair.Victim)) { GetOrAddPair(pair.Attacker, pair.Victim).Add(pair); } } foreach (KeyValuePair<string, string> name in other.Names) { if (!string.IsNullOrEmpty(name.Value)) { Names[name.Key] = name.Value; } } } public void Normalize() { if (Totals == null) { StatTotals statTotals = (Totals = new StatTotals()); } if (Opponents == null) { Dictionary<string, OpponentStats> dictionary = (Opponents = new Dictionary<string, OpponentStats>()); } if (Pairs == null) { List<PairStats> list = (Pairs = new List<PairStats>()); } if (Names == null) { Dictionary<string, string> dictionary3 = (Names = new Dictionary<string, string>()); } List<string> list3 = new List<string>(); foreach (KeyValuePair<string, OpponentStats> opponent in Opponents) { if (opponent.Value == null) { list3.Add(opponent.Key); } } foreach (string item in list3) { Opponents.Remove(item); } foreach (string item2 in Names.Keys.ToList()) { Names[item2] = PlayerIdentity.PlainName(Names[item2]); } foreach (OpponentStats value in Opponents.Values) { value.LastKnownName = PlayerIdentity.PlainName(value.LastKnownName); } RebuildPairIndex(); } } public class PersistedStats : StatsView { public const int CurrentSchemaVersion = 3; public int SchemaVersion { get; set; } = 3; public DateTime CreatedUtc { get; set; } = DateTime.UtcNow; public DateTime LastSavedUtc { get; set; } public Dictionary<string, string> SteamIdByPuid { get; set; } = new Dictionary<string, string>(); [JsonProperty(/*Could not decode attribute arguments.*/)] public bool Trimmed { get; set; } } public class KnockoutTracker { private enum EventKind { Knockout, SelfKnockout, Elimination, SelfElimination } private const float DuplicateWindowSeconds = 0.25f; private const float SaveIntervalSeconds = 5f; private const float IdentityPollSeconds = 2f; public static readonly string DataDir = Path.GetFullPath(Path.Combine(Application.persistentDataPath, "BonkBook")); public static readonly string DefaultSavePath = Path.Combine(DataDir, "stats.json"); public static readonly string OldSavePath = Path.Combine(Paths.ConfigPath, "com.matugol.sbg.bonkbook.stats.json"); public static readonly string SyncedMarkerPath = Path.Combine(DataDir, "cloud-synced"); private readonly string _oldSavePath; private bool _dirty; private float _lastSaveTime; private readonly SteamCloud _cloud; private bool _cloudReconciled; private string? _cloudPending; private float _lastCloudWrite = -1000f; private bool _cloudFlushFailLogged; private bool _trimLogged; private int _lastTrimDrop; private DateTime _localSavedUtc = DateTime.MinValue; private bool _localTrimmed; private bool _localFileAtLoad; private float _lastPollTime; private bool _matchCounted; private bool _holePlayed; private readonly List<(ulong Guid, ResolvedPlayer Player, bool IsLocal)> _togetherScratch = new List<(ulong, ResolvedPlayer, bool)>(); private bool _togetherBroken; private bool _startPending; private bool _endedLatch; private bool _wasConnected; private bool _courseStateBroken; private readonly List<(EventKind Kind, string Key, float Time)> _recent = new List<(EventKind, string, float)>(); private const int BackupsKept = 5; public string SavePath { get; } public StatsView Session { get; } = new StatsView(); public PersistedStats AllTime { get; private set; } = new PersistedStats(); public StatsView Match { get; private set; } = new StatsView(); public bool CourseActive { get; private set; } public bool InMatch => CourseActive; public int Version { get; private set; } public KnockoutTracker(string savePath, string oldSavePath, SteamCloud cloud) { SavePath = savePath; _oldSavePath = oldSavePath; _cloud = cloud; PlayerIdentity.KeyUpgraded += OnKeyUpgraded; PlayerIdentity.SteamIdLearned += OnSteamIdLearned; } public void OnKnockout(ulong attacker, ulong victim) { OnVersus(EventKind.Knockout, attacker, victim); } public void OnElimination(ulong attacker, ulong victim) { OnVersus(EventKind.Elimination, attacker, victim); } public void OnSelfKnockout(ulong player) { OnSelf(EventKind.SelfKnockout, player); } public void OnSelfElimination(ulong player) { OnSelf(EventKind.SelfElimination, player); } private void OnVersus(EventKind kind, ulong attacker, ulong victim) { if (CanRecord(kind, out var local)) { if (attacker == victim) { Plugin.Log.LogDebug((object)$"Ignored {kind} with identical attacker and victim ({attacker})."); } else if (kind == EventKind.Knockout && AreTeammates(attacker, victim)) { Plugin.Log.LogDebug((object)$"Ignored knockout {attacker} -> {victim}: teammates."); } else if (attacker == local || victim == local) { bool flag = attacker == local; ResolvedPlayer opponent = PlayerIdentity.Resolve(flag ? victim : attacker); RecordVersus(kind, flag, opponent); } else { ResolvedPlayer attacker2 = PlayerIdentity.Resolve(attacker); ResolvedPlayer victim2 = PlayerIdentity.Resolve(victim); RecordPair(kind, attacker2, victim2); } } } private void OnSelf(EventKind kind, ulong player) { if (CanRecord(kind, out var local)) { if (player != local) { Plugin.Log.LogDebug((object)$"Ignored {kind} of {player}: not you ({local})."); } else { RecordSelf(kind); } } } private void RecordVersus(EventKind kind, bool iAmAttacker, ResolvedPlayer opponent) { string text = ((kind == EventKind.Knockout) ? "KO" : "Elim"); string text2 = (iAmAttacker ? (text + ": You -> " + opponent.Name + " [" + opponent.Key + "]") : (text + ": " + opponent.Name + " -> You [" + opponent.Key + "]")); if (IsDuplicate(kind, (iAmAttacker ? "out>" : "in<") + opponent.Key, text2)) { return; } Apply(delegate(StatsView view) { OpponentStats opponent2 = view.GetOpponent(in opponent); StatTotals totals = view.Totals; if (kind == EventKind.Knockout) { if (iAmAttacker) { totals.KnockoutsDealt++; opponent2.KnockedOutByMe++; } else { totals.KnockoutsReceived++; opponent2.KnockedMeOut++; } } else if (iAmAttacker) { totals.EliminationsDealt++; opponent2.EliminatedByMe++; } else { totals.EliminationsReceived++; opponent2.EliminatedMe++; } }); Plugin.Log.LogDebug((object)text2); } private void RecordSelf(EventKind kind) { string text = ((kind == EventKind.SelfKnockout) ? "Self KO: You" : "Self elim: You"); if (IsDuplicate(kind, "self", text)) { return; } Apply(delegate(StatsView view) { if (kind == EventKind.SelfKnockout) { view.Totals.SelfKnockouts++; } else { view.Totals.SelfEliminations++; } }); Plugin.Log.LogDebug((object)text); } private void RecordPair(EventKind kind, ResolvedPlayer attacker, ResolvedPlayer victim) { string text = ((kind == EventKind.Knockout) ? "KO" : "Elim"); string text2 = "Lobby " + text + ": " + attacker.Name + " -> " + victim.Name + " [" + attacker.Key + " -> " + victim.Key + "]"; if (attacker.Key == victim.Key) { Plugin.Log.LogDebug((object)("Ignored " + text2 + ": both players resolve to the same key.")); } else { if (IsDuplicate(kind, "pair:" + attacker.Key + ">" + victim.Key, text2)) { return; } Apply(delegate(StatsView view) { PairStats pair = view.GetPair(in attacker, in victim); if (kind == EventKind.Knockout) { pair.Knockouts++; } else { pair.Eliminations++; } }); Plugin.Log.LogDebug((object)text2); } } public void OnMatchStateChanged(MatchState previous, MatchState current) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Invalid comparison between Unknown and I4 //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Invalid comparison between Unknown and I4 //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Invalid comparison between Unknown and I4 //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Invalid comparison between Unknown and I4 Plugin.Log.LogDebug((object)$"Match state {previous} -> {current}"); if ((int)current <= 2) { PlayerIdentity.Prewarm(); } if ((int)current <= 1) { _matchCounted = false; _holePlayed = false; return; } bool flag = current - 2 <= 1; if (flag && !_matchCounted) { _matchCounted = true; if (InDrivingRange()) { Plugin.Log.LogDebug((object)"Match start ignored: driving range."); return; } Apply(delegate(StatsView view) { view.Totals.HolesPlayed++; }); _holePlayed = true; Plugin.Log.LogInfo((object)$"Match started (holes played this session: {Session.Totals.HolesPlayed})."); } else if ((int)current == 6) { if (_holePlayed) { CountTogether(hole: true); } _matchCounted = false; _holePlayed = false; if (_dirty) { Save(); } } } private void CountTogether(bool hole) { if (_togetherBroken) { return; } try { PlayerIdentity.GetLobbyPlayers(_togetherScratch); int n = 0; Apply(delegate(StatsView view) { n = 0; foreach (var item in _togetherScratch) { ResolvedPlayer player = item.Player; if (!item.IsLocal && !string.IsNullOrEmpty(player.Key)) { OpponentStats opponent = view.GetOpponent(in player); if (hole) { opponent.HolesTogether++; } else { opponent.MatchesTogether++; } n++; } } }); Plugin.Log.LogInfo((object)string.Format("{0} ended with {1} other player(s): {2} together +1.", hole ? "Hole" : "Course", n, hole ? "holes" : "matches")); } catch (Exception ex) { _togetherBroken = true; Plugin.Log.LogWarning((object)("Holes/matches together counting disabled (" + ex.GetType().Name + ": " + ex.Message + ").")); } } private static bool CanRecord(EventKind kind, out ulong local) { local = 0uL; if (InDrivingRange()) { Plugin.Log.LogDebug((object)$"Ignored {kind}: driving range."); return false; } local = PlayerIdentity.LocalGuid; if (local == 0L) { Plugin.Log.LogDebug((object)$"Ignored {kind}: local player not known yet."); return false; } return true; } private bool IsDuplicate(EventKind kind, string eventKey, string desc) { float now = Time.realtimeSinceStartup; _recent.RemoveAll(((EventKind Kind, string Key, float Time) e) => now - e.Time >= 0.25f); int num = _recent.FindIndex(((EventKind Kind, string Key, float Time) e) => e.Kind == kind && e.Key == eventKey); if (num < 0) { _recent.Add((kind, eventKey, now)); return false; } _recent[num] = (kind, eventKey, now); Plugin.Log.LogDebug((object)$"Ignored duplicate (within {0.25f}s): {desc}."); return true; } private static bool AreTeammates(ulong a, ulong b) { if (PlayerIdentity.TryGetPlayer(a, out PlayerInfo info) && PlayerIdentity.TryGetPlayer(b, out PlayerInfo info2)) { return info.IsTeammateOf(info2, false); } return false; } private void Apply(Action<StatsView> change) { UpdateCourseState(); change(Session); change(AllTime); if (InMatch) { change(Match); } MarkDirty(); } public void OnCourseStarting() { ResetMatch("course starting"); _startPending = true; _endedLatch = false; CourseActive = false; Version++; } public void OnCourseEnding() { if (CourseActive && !_endedLatch) { Apply(delegate(StatsView view) { view.Totals.MatchesFinished++; }); CountTogether(hole: false); } if (CourseActive) { Plugin.Log.LogInfo((object)$"Course ended (this match: {Match.Totals.KnockoutsDealt} KOs dealt / {Match.Totals.KnockoutsReceived} received)."); } CourseActive = false; _endedLatch = true; _startPending = false; Version++; } private void ResetMatch(string reason, bool logIfEmpty = true) { bool num = Match.Opponents.Count > 0 || Match.Pairs.Count > 0 || Match.Totals.HolesPlayed > 0; Match = new StatsView(); if (num || logIfEmpty) { Plugin.Log.LogInfo((object)("Match stats reset (" + reason + ").")); } } public void UpdateCourseState() { if (_courseStateBroken) { return; } try { if (!ClientConnected()) { if (_wasConnected) { _wasConnected = false; CourseActive = false; _startPending = (_endedLatch = false); ResetMatch("left the lobby", logIfEmpty: false); Version++; } return; } _wasConnected = true; if (InDrivingRange()) { _endedLatch = false; if (CourseActive) { CourseActive = false; Plugin.Log.LogInfo((object)"Back in the lobby; match stats kept until the next course starts."); Version++; } } else if (!CourseActive && !_endedLatch && CourseManagerPresent()) { CourseActive = true; if (!_startPending) { ResetMatch("joined a course in progress"); } _startPending = false; Plugin.Log.LogInfo((object)"Course started: counting 'This match'."); Version++; } } catch (Exception ex) { _courseStateBroken = true; Plugin.Log.LogWarning((object)("Course detection disabled (" + ex.GetType().Name + ": " + ex.Message + "); 'This match' only follows the course start/end hooks.")); } } [MethodImpl(MethodImplOptions.NoInlining)] private static bool ClientConnected() { return NetworkClient.active; } [MethodImpl(MethodImplOptions.NoInlining)] private static bool InDrivingRange() { return SingletonBehaviour<DrivingRangeManager>.HasInstance; } [MethodImpl(MethodImplOptions.NoInlining)] private static bool CourseManagerPresent() { return SingletonNetworkBehaviour<CourseManager>.HasInstance; } private void MarkDirty() { _dirty = true; Version++; } private void OnKeyUpgraded(string oldKey, string newKey, string name) { if (!(Session.Merge(oldKey, newKey) | AllTime.Merge(oldKey, newKey) | Match.Merge(oldKey, newKey))) { return; } StatsView[] array = new StatsView[3] { Session, AllTime, Match }; foreach (StatsView statsView in array) { if (statsView.Opponents.TryGetValue(newKey, out OpponentStats value)) { value.LastKnownName = name; } if (statsView.Names.ContainsKey(newKey)) { statsView.Names[newKey] = name; } } Plugin.Log.LogInfo((object)("Merged stats for " + name + ": " + oldKey + " -> " + newKey)); MarkDirty(); } private void OnSteamIdLearned(string puid, string steamId) { MarkDirty(); string text = "eos:" + puid; string name = Session.NameOf(text) ?? AllTime.NameOf(text) ?? steamId; OnKeyUpgraded(text, "steam:" + steamId, name); } public void Tick() { UpdateCourseState(); float realtimeSinceStartup = Time.realtimeSinceStartup; if (realtimeSinceStartup - _lastPollTime >= 2f) { _lastPollTime = realtimeSinceStartup; try { if ((Object)(object)GameManager.LocalPlayerInfo != (Object)null) { PlayerIdentity.Prewarm(); PlayerIdentity.Poll(); } } catch (Exception ex) { Plugin.Log.LogDebug((object)("Identity poll failed: " + ex.Message)); } } if (_cloud.PollReady(realtimeSinceStartup)) { ReconcileCloud(); } if (_dirty && realtimeSinceStartup - _lastSaveTime >= 5f) { Save(); } if (_cloudPending != null) { FlushCloud(force: false); } } public void Load() { try { Directory.CreateDirectory(Path.GetDirectoryName(SavePath)); MoveOldStatsFile(); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not move the stats from '" + _oldSavePath + "' to '" + SavePath + "': " + ex.GetType().Name + ": " + ex.Message)); } try { _localFileAtLoad = File.Exists(SavePath); if (_localFileAtLoad) { string error; bool tooNew; PersistedStats persistedStats = ParseStats(File.ReadAllText(SavePath), out error, out tooNew); if (persistedStats == null) { BackUpAndStartFresh(error ?? "stats file could not be read"); return; } AllTime = persistedStats; _localSavedUtc = persistedStats.LastSavedUtc.ToUniversalTime(); _localTrimmed = persistedStats.Trimmed; Plugin.Log.LogInfo((object)($"Loaded all-time stats: {AllTime.Opponents.Count} opponents, " + $"{AllTime.Totals.KnockoutsDealt} KOs dealt / {AllTime.Totals.KnockoutsReceived} received, " + $"{AllTime.Pairs.Count} lobby pairs.")); } } catch (Exception ex2) { BackUpAndStartFresh("failed to load stats (" + ex2.GetType().Name + ": " + ex2.Message + ")"); } finally { PlayerIdentity.AttachAliasMap(AllTime.SteamIdByPuid); Version++; } } private void MoveOldStatsFile() { if (!File.Exists(_oldSavePath)) { return; } if (File.Exists(SavePath)) { Plugin.Log.LogInfo((object)("Old stats file '" + _oldSavePath + "' left as it is: '" + SavePath + "' already exists and is used.")); return; } File.Move(_oldSavePath, SavePath); int num = 0; foreach (var item in TimestampedBackups(_oldSavePath)) { string text = SavePath + Path.GetFileName(item.Path).Substring(Path.GetFileName(_oldSavePath).Length); if (!File.Exists(text)) { File.Move(item.Path, text); num++; } } Plugin.Log.LogInfo((object)("Moved the stats file" + ((num > 0) ? $" and {num} backups" : "") + " from '" + _oldSavePath + "' to '" + SavePath + "'.")); } public static void MoveOldSyncedFlag(string cfgPath) { try { if (!File.Exists(SyncedMarkerPath) && File.Exists(cfgPath) && File.ReadAllLines(cfgPath).Any((string l) => l.Trim() == "CloudSyncedHere = true")) { Directory.CreateDirectory(DataDir); File.WriteAllText(SyncedMarkerPath, ""); Plugin.Log.LogInfo((object)("[Storage] CloudSyncedHere = true in the .cfg: created '" + SyncedMarkerPath + "' (where it is kept now).")); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not carry over [Storage] CloudSyncedHere: " + ex.GetType().Name + ": " + ex.Message)); } } private static PersistedStats? ParseStats(string text, out string? error, out bool tooNew) { //IL_001b: Expected O, but got Unknown error = null; tooNew = false; JObject val; try { val = JObject.Parse(text.TrimStart('\ufeff')); } catch (JsonException ex) { JsonException ex2 = ex; error = "stats file is not valid JSON (" + ((Exception)(object)ex2).Message + ")"; return null; } int? num = ((JToken)val).Value<int?>((object)"SchemaVersion"); if (!num.HasValue) { error = "stats file has no SchemaVersion (unknown or pre-release format)"; return null; } int value = num.Value; if (value > 3) { tooNew = true; error = $"stats file schema {value} is newer than this plugin supports ({3})"; return null; } PersistedStats persistedStats = ((JToken)val).ToObject<PersistedStats>(); if (persistedStats == null) { error = "stats file deserialized to null"; return null; } persistedStats.Normalize(); PersistedStats persistedStats2 = persistedStats; if (persistedStats2.SteamIdByPuid == null) { Dictionary<string, string> dictionary = (persistedStats2.SteamIdByPuid = new Dictionary<string, string>()); } persistedStats.SchemaVersion = 3; FoldAliases(persistedStats); return persistedStats; } private static void FoldAliases(PersistedStats stats) { foreach (KeyValuePair<string, string> item in stats.SteamIdByPuid) { stats.Merge("eos:" + item.Key, "steam:" + item.Value); } } private void ReconcileCloud() { _cloudReconciled = true; try { string text = _cloud.ReadText(); if (!_cloud.IsReady) { return; } if (text == null) { if (File.Exists(SavePath)) { Plugin.Log.LogInfo((object)"Steam Cloud: no cloud copy yet; uploading the local stats as 'BonkBook.json.gz'."); Save(); } else { Plugin.Log.LogInfo((object)"Steam Cloud: no stats locally or in the cloud yet; starting fresh (the first save creates both)."); } return; } string error; bool tooNew; PersistedStats persistedStats = ParseStats(text, out error, out tooNew); if (persistedStats == null) { if (tooNew) { _cloud.Disable("the cloud copy was written by a newer Bonk Book (" + error + "); leaving it untouched"); return; } Plugin.Log.LogWarning((object)("Steam Cloud: the cloud copy is unusable (" + error + "); it will be replaced by the local stats.")); if (File.Exists(SavePath)) { Save(); } return; } if (!_localFileAtLoad && File.Exists(SyncedMarkerPath)) { string text2 = WriteBackup(text, "the Steam Cloud copy, before replacing it after the stats file was deleted"); Plugin.Log.LogInfo((object)("Steam Cloud: the stats file was deleted on this PC after it had synced before, so all-time stats start fresh and the cloud copy is replaced" + ((text2 != null) ? (" (the old cloud copy is kept as " + text2 + ").") : "."))); Save(); return; } DateTime dateTime = persistedStats.LastSavedUtc.ToUniversalTime(); if (dateTime > _localSavedUtc && persistedStats.Trimmed && _localFileAtLoad && !_localTrimmed) { string text3 = WriteBackup(text, "the trimmed Steam Cloud copy, before replacing it with the complete local stats"); Plugin.Log.LogWarning((object)($"Steam Cloud: the cloud copy is newer (saved {dateTime:yyyy-MM-dd HH:mm:ss} UTC) but trimmed to fit the " + "cloud budget, so the complete local stats are kept and uploaded instead" + ((text3 != null) ? (" (the cloud copy is kept as " + text3 + ").") : "."))); Save(); } else if (dateTime > _localSavedUtc) { BackupLocal("before replacing it with the newer Steam Cloud copy"); bool flag = !Session.IsEmpty; if (flag) { persistedStats.AddFrom(Session); } foreach (KeyValuePair<string, string> item in AllTime.SteamIdByPuid) { if (!persistedStats.SteamIdByPuid.ContainsKey(item.Key)) { persistedStats.SteamIdByPuid[item.Key] = item.Value; } } FoldAliases(persistedStats); AllTime = persistedStats; PlayerIdentity.AttachAliasMap(AllTime.SteamIdByPuid); Version++; Plugin.Log.LogInfo((object)($"Steam Cloud: the cloud copy is newer (saved {dateTime:yyyy-MM-dd HH:mm:ss} UTC vs local " + ((_localSavedUtc == DateTime.MinValue) ? "none" : (_localSavedUtc.ToString("yyyy-MM-dd HH:mm:ss") + " UTC")) + "); " + $"using it: {AllTime.Opponents.Count} opponents, {AllTime.Totals.KnockoutsDealt} KOs dealt / " + $"{AllTime.Totals.KnockoutsReceived} received" + (flag ? ", plus this session's events." : "."))); Save(flag, flag); } else if (dateTime < _localSavedUtc) { Plugin.Log.LogInfo((object)($"Steam Cloud: the local stats are newer (saved {_localSavedUtc:yyyy-MM-dd HH:mm:ss} UTC vs cloud " + $"{dateTime:yyyy-MM-dd HH:mm:ss} UTC); uploading them.")); Save(); } else { Plugin.Log.LogInfo((object)"Steam Cloud: the local and cloud copies match."); if (_dirty) { Save(); } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Steam Cloud: sync failed (" + ex.GetType().Name + ": " + ex.Message + "); carrying on with the local stats.")); } finally { MarkSyncedHere(); } } private void MarkSyncedHere() { try { if (_cloud.IsReady && !File.Exists(SyncedMarkerPath)) { File.WriteAllText(SyncedMarkerPath, ""); } } catch (Exception ex) { Plugin.Log.LogDebug((object)("Could not create '" + SyncedMarkerPath + "': " + ex.Message)); } } private void FlushCloud(bool force) { if (_cloudPending == null) { return; } float realtimeSinceStartup = Time.realtimeSinceStartup; if (!force && realtimeSinceStartup - _lastCloudWrite < 5f) { return; } _lastCloudWrite = realtimeSinceStartup; string cloudPending = _cloudPending; _cloudPending = null; if (!_cloud.IsReady) { return; } try { long num = _cloud.Budget(); byte[] array = SteamCloud.Gzip(cloudPending); if (array.Length > num) { int num2 = array.Length; string summary; byte[] array2 = TrimForCloud(cloudPending, num, out summary); if (array2 == null) { _cloud.ReportNoRoom(num, num2); return; } if (!_trimLogged) { _trimLogged = true; Plugin.Log.LogWarning((object)($"Steam Cloud: the stats ({num2 / 1024} KB compressed) are over the cloud budget ({num / 1024} KB); " + "syncing a trimmed copy without " + summary + ". The local file stays complete.")); } array = array2; } _cloud.Write(array, cloudPending.Length); } catch (Exception ex) { if (!_cloudFlushFailLogged) { _cloudFlushFailLogged = true; Plugin.Log.LogWarning((object)("Steam Cloud: preparing the cloud copy failed (" + ex.GetType().Name + ": " + ex.Message + "); stats are still saved locally.")); } } } private byte[]? TrimForCloud(string json, long budget, out string summary) { summary = ""; PersistedStats stats = JsonConvert.DeserializeObject<PersistedStats>(json); if (stats == null) { return null; } stats.Normalize(); List<PairStats> pairs = (from p in stats.Pairs orderby p.Knockouts + p.Eliminations, p.LastSeenUtc select p).ToList(); List<string> opponents = (from kv in stats.Opponents orderby kv.Value.TotalInteractions, kv.Value.HolesTogether + kv.Value.MatchesTogether, kv.Value.LastSeenUtc select kv.Key).ToList(); int num = pairs.Count + opponents.Count; byte[] array = null; int num2 = -1; int num3 = 1; int num4 = num; if (_lastTrimDrop > 0 && _lastTrimDrop <= num) { byte[] array2 = Build(_lastTrimDrop); if (array2.Length <= budget) { array = array2; num2 = _lastTrimDrop; num4 = _lastTrimDrop - 1; num3 = num4 + 1; } else { num3 = _lastTrimDrop + 1; } } while (num3 <= num4) { int num5 = num3 + (num4 - num3) / 2; byte[] array3 = Build(num5); if (array3.Length <= budget) { array = array3; num2 = num5; num4 = num5 - 1; } else { num3 = num5 + 1; } } if (array == null) { return null; } _lastTrimDrop = num2; int num6 = Math.Min(num2, pairs.Count); summary = $"{num6} of {pairs.Count} lobby pairs" + ((num2 > num6) ? $" and {num2 - num6} of {opponents.Count} opponents" : "") + $" ({array.Length / 1024} KB)"; return array; byte[] Build(int drop) { int num7 = Math.Min(drop, pairs.Count); List<PairStats> list = pairs.Skip(num7).ToList(); HashSet<string> droppedOpponents = new HashSet<string>(opponents.Take(drop - num7)); HashSet<string> pairKeys = new HashSet<string>(); foreach (PairStats item in list) { pairKeys.Add(item.Attacker); pairKeys.Add(item.Victim); } return SteamCloud.Gzip(JsonConvert.SerializeObject((object)new PersistedStats { SchemaVersion = stats.SchemaVersion, CreatedUtc = stats.CreatedUtc, LastSavedUtc = stats.LastSavedUtc, Totals = stats.Totals, SteamIdByPuid = stats.SteamIdByPuid, Trimmed = true, Opponents = stats.Opponents.Where<KeyValuePair<string, OpponentStats>>((KeyValuePair<string, OpponentStats> kv) => !droppedOpponents.Contains(kv.Key)).ToDictionary((KeyValuePair<string, OpponentStats> kv) => kv.Key, (KeyValuePair<string, OpponentStats> kv) => kv.Value), Pairs = list, Names = stats.Names.Where<KeyValuePair<string, string>>((KeyValuePair<string, string> kv) => pairKeys.Contains(kv.Key)).ToDictionary((KeyValuePair<string, string> kv) => kv.Key, (KeyValuePair<string, string> kv) => kv.Value) }, (Formatting)0)); } } private void BackUpAndStartFresh(string reason) { AllTime = new PersistedStats(); PlayerIdentity.AttachAliasMap(AllTime.SteamIdByPuid); string text = BackupLocal("unreadable file, starting fresh", move: true); Plugin.Log.LogWarning((object)((text != null) ? (reason + ". Moved it to '" + text + "' and starting fresh.") : (reason + ". Could not back it up; starting fresh in memory, the file will be overwritten on the next save."))); } private string? BackupLocal(string why, bool move = false) { if (!File.Exists(SavePath)) { return null; } return Backup("the stats file (" + why + ")", delegate(string path) { if (move) { File.Move(SavePath, path); } else { File.Copy(SavePath, path); } }); } private string? WriteBackup(string json, string why) { return Backup(why, delegate(string path) { File.WriteAllText(path, json); }); } private string? Backup(string what, Action<string> write) { try { string text = DateTime.Now.ToString("yyyyMMdd-HHmmss"); string text2 = SavePath + "." + text + ".bak"; int num = 2; while (File.Exists(text2)) { text2 = $"{SavePath}.{text}-{num}.bak"; num++; } write(text2); Plugin.Log.LogInfo((object)("Backed up " + what + ": " + text2)); PruneBackups(); return text2; } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not back up " + what + ": " + ex.GetType().Name + ": " + ex.Message)); return null; } } private void PruneBackups() { try { List<(string, string, int)> list = TimestampedBackups(SavePath); if (list.Count <= 5) { return; } list.Sort(delegate((string Path, string Stamp, int N) a, (string Path, string Stamp, int N) b) { int num2 = string.CompareOrdinal(b.Stamp, a.Stamp); return (num2 == 0) ? b.N.CompareTo(a.N) : num2; }); for (int num = 5; num < list.Count; num++) { try { File.Delete(list[num].Item1); } catch (Exception ex) { Plugin.Log.LogDebug((object)("Could not delete old backup '" + list[num].Item1 + "': " + ex.Message)); } } } catch (Exception ex2) { Plugin.Log.LogDebug((object)("Could not prune old stats backups: " + ex2.Message)); } } private static List<(string Path, string Stamp, int N)> TimestampedBackups(string statsPath) { List<(string, string, int)> list = new List<(string, string, int)>(); string directoryName = Path.GetDirectoryName(statsPath); string fileName = Path.GetFileName(statsPath); if (string.IsNullOrEmpty(directoryName) || !Directory.Exists(directoryName)) { return list; } Regex regex = new Regex("^" + Regex.Escape(fileName) + "\\.(\\d{8}-\\d{6})(?:-(\\d+))?\\.bak$"); string[] files = Directory.GetFiles(directoryName, fileName + ".*.bak"); foreach (string text in files) { Match match = regex.Match(Path.GetFileName(text)); if (match.Success) { list.Add((text, match.Groups[1].Value, (!match.Groups[2].Success) ? 1 : int.Parse(match.Groups[2].Value))); } } return list; } public void Save() { Save(toCloud: true, stamp: true); } private void Save(bool toCloud, bool stamp) { _lastSaveTime = Time.realtimeSinceStartup; _dirty = false; try { if (stamp || AllTime.LastSavedUtc == default(DateTime)) { AllTime.LastSavedUtc = DateTime.UtcNow; } string contents = JsonConvert.SerializeObject((object)AllTime, (Formatting)1); string text = SavePath + ".tmp"; File.WriteAllText(text, contents); if (File.Exists(SavePath)) { try { File.Replace(text, SavePath, null); } catch (Exception ex) when (((ex is PlatformNotSupportedException || ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0) { File.Copy(text, SavePath, overwrite: true); File.Delete(text); } } else { File.Move(text, SavePath); } if (toCloud && _cloudReconciled && _cloud.IsReady) { _cloudPending = JsonConvert.SerializeObject((object)AllTime, (Formatting)0); FlushCloud(force: false); } } catch (Exception arg) { _dirty = true; Plugin.Log.LogError((object)$"Failed to save stats: {arg}"); } } public void SaveIfDirty() { if (_dirty) { Save(); } FlushCloud(force: true); } } public readonly struct ResolvedPlayer { public string Key { get; } public string Name { get; } public bool IsSteam => Key.StartsWith("steam:", StringComparison.Ordinal); public ResolvedPlayer(string key, string name) { Key = key; Name = name; } } internal static class PlayerIdentity { private sealed class CachedPlayer { public ProductUserId? Puid; public string? PuidString; public string Name = ""; } private sealed class PendingPlayer { public PlayerInfo Player; public string Key = ""; } public const string SteamPrefix = "steam:"; public const string EosPrefix = "eos:"; public const string NamePrefix = "name:"; private static readonly Dictionary<ulong, CachedPlayer> ByGuid = new Dictionary<ulong, CachedPlayer>(); private static readonly List<PendingPlayer> Pending = new List<PendingPlayer>(); private static PlayerInfo? _cacheOwner; private static Dictionary<string, string> _steamIdByPuid = new Dictionary<string, string>(); public static ulong LocalGuid { get { PlayerId localPlayerId = GameManager.LocalPlayerId; if (!((Object)(object)localPlayerId != (Object)null)) { return 0uL; } return localPlayerId.Guid; } } public static event Action<string, string, string>? KeyUpgraded; public static event Action<string, string>? SteamIdLearned; public static void AttachAliasMap(Dictionary<string, string> steamIdByPuid) { _steamIdByPuid = steamIdByPuid; } public static bool SteamIdOf(string key, out ulong steamId) { steamId = 0uL; string value = null; if (key.StartsWith("steam:", StringComparison.Ordinal)) { value = key.Substring("steam:".Length); } else if (key.StartsWith("eos:", StringComparison.Ordinal)) { _steamIdByPuid.TryGetValue(key.Substring("eos:".Length), out value); } if (value != null && ulong.TryParse(value, out steamId)) { return steamId != 0; } return false; } public static bool TryGetPlayer(ulong guid, out PlayerInfo? info) { info = null; if (guid != 0L && GameManager.TryFindPlayerByGuid(guid, ref info)) { return (Object)(object)info != (Object)null; } return false; } public static ResolvedPlayer Resolve(ulong guid) { EnsureCacheOwner(); CachedPlayer value; if (TryGetPlayer(guid, out PlayerInfo info)) { value = Observe(guid, info); } else if (!ByGuid.TryGetValue(guid, out value)) { value = new CachedPlayer { Name = GetName(guid, null) }; } ResolvedPlayer result = BuildKey(value); if (!result.IsSteam && (Object)(object)info != (Object)null) { Track(info, result.Key); } return result; } public static void Prewarm() { EnsureCacheOwner(); PlayerInfo localPlayerInfo = GameManager.LocalPlayerInfo; if ((Object)(object)localPlayerInfo != (Object)null && (Object)(object)localPlayerInfo.PlayerId != (Object)null) { Observe(localPlayerInfo.PlayerId.Guid, localPlayerInfo); } List<PlayerInfo> remotePlayers = GameManager.RemotePlayers; if (remotePlayers == null) { return; } foreach (PlayerInfo item in remotePlayers) { if (!((Object)(object)item == (Object)null) && !((Object)(object)item.PlayerId == (Object)null)) { TryGetSteamId(Observe(item.PlayerId.Guid, item)); } } } public static void GetLobbyPlayers(List<(ulong Guid, ResolvedPlayer Player, bool IsLocal)> result) { result.Clear(); PlayerInfo localPlayerInfo = GameManager.LocalPlayerInfo; if ((Object)(object)localPlayerInfo == (Object)null || (Object)(object)localPlayerInfo.PlayerId == (Object)null) { return; } ulong guid = localPlayerInfo.PlayerId.Guid; result.Add((guid, Resolve(guid), true)); List<PlayerInfo> remotePlayers = GameManager.RemotePlayers; if (remotePlayers == null) { return; } foreach (PlayerInfo item in remotePlayers) { if (!((Object)(object)item == (Object)null) && !((Object)(object)item.PlayerId == (Object)null)) { ulong guid2 = item.PlayerId.Guid; if (guid2 != 0L && guid2 != guid) { result.Add((guid2, Resolve(guid2), false)); } } } } public static void Poll() { EnsureCacheOwner(); for (int num = Pending.Count - 1; num >= 0; num--) { PendingPlayer pendingPlayer = Pending[num]; if ((Object)(object)pendingPlayer.Player == (Object)null || (Object)(object)pendingPlayer.Player.PlayerId == (Object)null) { Pending.RemoveAt(num); } else { ResolvedPlayer resolvedPlayer = BuildKey(Observe(pendingPlayer.Player.PlayerId.Guid, pendingPlayer.Player)); if (resolvedPlayer.Key != pendingPlayer.Key && Rank(resolvedPlayer.Key) > Rank(pendingPlayer.Key)) { string key = pendingPlayer.Key; pendingPlayer.Key = resolvedPlayer.Key; Plugin.Log.LogDebug((object)("Identity upgraded: " + key + " -> " + resolvedPlayer.Key + " (" + resolvedPlayer.Name + ")")); PlayerIdentity.KeyUpgraded?.Invoke(key, resolvedPlayer.Key, resolvedPlayer.Name); } if (resolvedPlayer.IsSteam) { Pending.RemoveAt(num); } } } } private static int Rank(string key) { if (!key.StartsWith("steam:", StringComparison.Ordinal)) { if (!key.StartsWith("eos:", StringComparison.Ordinal)) { return 1; } return 2; } return 3; } private static void Track(PlayerInfo info, string key) { foreach (PendingPlayer item in Pending) { if ((Object)(object)item.Player == (Object)(object)info) { item.Key = key; return; } } Pending.Add(new PendingPlayer { Player = info, Key = key }); } private static void EnsureCacheOwner() { PlayerInfo localPlayerInfo = GameManager.LocalPlayerInfo; if (!((Object)(object)localPlayerInfo == (Object)null) && !((Object)(object)localPlayerInfo == (Object)(object)_cacheOwner)) { ByGuid.Clear(); Pending.Clear(); _cacheOwner = localPlayerInfo; } } private static CachedPlayer Observe(ulong guid, PlayerInfo info) { if (!ByGuid.TryGetValue(guid, out CachedPlayer value)) { value = new CachedPlayer(); ByGuid[guid] = value; } try { ProductUserId val = (((Object)(object)info.PlayerId != (Object)null) ? info.PlayerId.EosProductUserId : null); if ((Handle)(object)val != (Handle)null && val.IsValid()) { string text = ((object)val).ToString(); if (!string.IsNullOrEmpty(text)) { value.Puid = val; value.PuidString = text; } } } catch (Exception ex) { Plugin.Log.LogDebug((object)$"Could not read EOS product user id for guid {guid}: {ex.Message}"); } string name = GetName(guid, info); if (!string.IsNullOrEmpty(name)) { value.Name = name; } return value; } private static ResolvedPlayer BuildKey(CachedPlayer entry) { string text = (string.IsNullOrEmpty(entry.Name) ? "Unknown" : entry.Name); string text2 = TryGetSteamId(entry); if (text2 != null) { return new ResolvedPlayer("steam:" + text2, text); } if (entry.PuidString != null) { return new ResolvedPlayer("eos:" + entry.PuidString, text); } return new ResolvedPlayer("name:" + text, text); } private static string? TryGetSteamId(CachedPlayer entry) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Invalid comparison between Unknown and I4 if (entry.PuidString == null) { return null; } if (_steamIdByPuid.TryGetValue(entry.PuidString, out string value)) { return value; } if ((Handle)(object)entry.Puid == (Handle)null) { return null; } try { ExternalAccountInfo val = default(ExternalAccountInfo); if (BEosLobbyManager.TryGetExternalAccountInfoFor(entry.Puid, ref val) && (int)((ExternalAccountInfo)(ref val)).AccountIdType == 1) { string text = Utf8String.op_Implicit(((ExternalAccountInfo)(ref val)).AccountId); if (!string.IsNullOrEmpty(text) && ulong.TryParse(text, out var _)) { _steamIdByPuid[entry.PuidString] = text; PlayerIdentity.SteamIdLearned?.Invoke(entry.PuidString, text); return text; } } } catch (Exception ex) { Plugin.Log.LogDebug((object)("Steam id lookup failed for " + entry.PuidString + ": " + ex.Message)); } return null; } internal static string PlainName(string? s) { return (s ?? "").Replace("<noparse>", "").Replace("</noparse>", ""); } private static string GetName(ulong guid, PlayerInfo? info) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) try { bool flag = default(bool); string text = PlainName(PlayerNameManager.GetPlayerName(guid, ref flag).nameWithNoParsedRichText); if (!flag && text.Length > 0) { return text; } string text2 = PlainName(((Object)(object)info != (Object)null && (Object)(object)info.PlayerId != (Object)null) ? info.PlayerId.PlayerNameNoRichText : null); if (text2.Length > 0) { return text2; } if (text.Length > 0) { return text; } } catch (Exception ex) { Plugin.Log.LogDebug((object)$"Name lookup failed for guid {guid}: {ex.Message}"); } return "Player " + guid; } } [BepInPlugin("com.matugol.sbg.bonkbook", "Bonk Book", "0.8.6")] public class Plugin : BaseUnityPlugin { private static ConfigEntry<Key> _toggleKey = null; private static Harmony? _harmony; private static bool _subscribedMatchState; private static bool _shutDown; private static readonly (Type Patch, string Name)[] Hooks = new(Type, string)[10] { (typeof(KnockoutMessagePatch), "Knockout"), (typeof(SelfKnockoutMessagePatch), "SelfKnockout"), (typeof(EliminationMessagePatch), "Elimination"), (typeof(SelfEliminationMessagePatch), "SelfElimination"), (typeof(ScoreboardEntryPatch), "Scoreboard"), (typeof(CourseStartPatch), "CourseStart"), (typeof(CourseEndPatch), "CourseEnd"), (typeof(PauseMenuPausePatch), "EscPause"), (typeof(MenuExitPatch), "EscMenuBack"), (typeof(ScoreboardShowPatch), "TabScoreboard") }; internal static ManualLogSource Log { get; private set; } = null; internal static KnockoutTracker Tracker { get; private set; } = null; internal static string ToggleKeyName => ((object)_toggleKey.Value/*cast due to .constrained prefix*/).ToString(); private void Awake() { //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; _toggleKey = ((BaseUnityPlugin)this).Config.Bind<Key>("General", "ToggleKey", (Key)25, "Key for the stats window (UnityEngine.InputSystem.Key name, e.g. K, F8, F9): tap to open/close it, hold to peek (shown while held, you can keep playing). None disables it. Ignored while you are typing (chat, dev console, any focused text field)."); ConfigEntry<bool> sbEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Scoreboard", "Enabled", true, "Add two columns to the game's Tab scoreboard: 'Taken' (how often each player was knocked out this match) and 'vs You' (you KO'd them / they KO'd you). Applied at startup."); ConfigEntry<ScoreboardRange> sbRange = ((BaseUnityPlugin)this).Config.Bind<ScoreboardRange>("Scoreboard", "Range", ScoreboardRange.Match, "Which stats the scoreboard's 'vs You' column shows: Match (the current course), Session or AllTime. The 'Taken' column always shows this match, like the game's own knockouts column."); ConfigEntry<bool> gridShading = ((BaseUnityPlugin)this).Config.Bind<bool>("Window", "GridShading", true, "Lobby grid: shade cells by value (heatmap). Also switchable in the menu."); ConfigEntry<CellMode> val = ((BaseUnityPlugin)this).Config.Bind<CellMode>("Window", "CellMode", CellMode.Knockouts, "Lobby grid: what each cell shows: Knockouts, Eliminations or Both (KOs / Elims). Also switchable in the menu."); ConfigEntry<bool> obj = ((BaseUnityPlugin)this).Config.Bind<bool>("Storage", "SteamCloud", true, "Also keep the stats in Steam Cloud (gzip-compressed as BonkBook.json.gz, at most 256 KB and always leaving 256 KB free for the game's own saves; next to the game's own cloud saves), so they follow you to other PCs. On start the newer of the local and cloud copies is used."); ScoreboardColumns.Configure(sbEnabled.Value, sbRange.Value); sbRange.SettingChanged += delegate { ScoreboardColumns.Configure(sbEnabled.Value, sbRange.Value); }; KnockoutTracker.MoveOldSyncedFlag(((BaseUnityPlugin)this).Config.ConfigFilePath); string defaultSavePath = KnockoutTracker.DefaultSavePath; string oldSavePath = KnockoutTracker.OldSavePath; bool value = obj.Value; string disabledReason = "[Storage] SteamCloud = false"; Tracker = new KnockoutTracker(defaultSavePath, oldSavePath, new SteamCloud(value, disabledReason)); Tracker.Load(); _harmony = new Harmony("com.matugol.sbg.bonkbook"); ApplyPatches(_harmony, sbEnabled.Value); try { SubscribeMatchState(); _subscribedMatchState = true; } catch (Exception ex) { Log.LogWarning((object)("Could not hook CourseManager.MatchStateChanged; holes played will not be counted: " + ex.Message)); } StatsModel.Cells = val.Value; Runner.Create(_toggleKey, gridShading, val); Log.LogInfo((object)("Bonk Book 0.8.6 loaded. Stats file: " + defaultSavePath + ". Toggle window with " + ToggleKeyName + ".")); } private static void ApplyPatches(Harmony harmony, bool scoreboard) { List<string> list = new List<string>(); List<string> list2 = new List<string>(); (Type, string)[] hooks = Hooks; for (int i = 0; i < hooks.Length; i++) { var (type, text) = hooks[i]; if (type == typeof(ScoreboardEntryPatch) && !scoreboard) { continue; } try { List<MethodInfo> list3 = harmony.CreateClassProcessor(type).Patch(); if (list3 != null && list3.Count > 0) { list.Add(text); } else { list2.Add(text); } } catch (Exception arg) { list2.Add(text); Log.LogError((object)$"Failed to apply {text} hook: {arg}"); } } Log.LogInfo((object)("Hooks active: " + ((list.Count > 0) ? string.Join(", ", list) : "none") + ((list2.Count > 0) ? ("; inactive: " + string.Join(", ", list2)) : ""))); } [MethodImpl(MethodImplOptions.NoInlining)] private static void SubscribeMatchState() { CourseManager.MatchStateChanged += OnMatchStateChanged; } [MethodImpl(MethodImplOptions.NoInlining)] private static void UnsubscribeMatchState() { CourseManager.MatchStateChanged -= OnMatchStateChanged; } private static void OnMatchStateChanged(MatchState previous, MatchState current) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) try { Tracker.OnMatchStateChanged(previous, current); } catch (Exception arg) { Log.LogError((object)$"MatchStateChanged handler failed: {arg}"); } } internal static void Shutdown() { if (_shutDown) { return; } _shutDown = true; if (_subscribedMatchState) { try { UnsubscribeMatchState(); } catch (Exception) { } } Harmony? harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private void OnDestroy() { Tracker?.SaveIfDirty(); ManualLogSource log = Log; if (log != null) { log.LogDebug((object)"BepInEx plugin component destroyed; the Bonk Book runner keeps running."); } } } internal sealed class Runner : MonoBehaviour { private const float TapSeconds = 0.25f; private ConfigEntry<Key> _toggleKey; private StatsMenu _menu; private bool _cursorForcedByUs; private bool _cursorHandlingBroken; private bool _inputBlockedByUs; private bool _inputBlockingBroken; internal static void Create(ConfigEntry<Key> toggleKey, ConfigEntry<bool> gridShading, ConfigEntry<CellMode> cellMode) { //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_0013: Expected O, but got Unknown GameObject val = new GameObject("BonkBook.Runner") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)(object)val); Runner runner = val.AddComponent<Runner>(); runner._toggleKey = toggleKey; runner._menu = new StatsMenu(val.transform, gridShading, cellMode); } private void Update() { //IL_0013: 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) Keyboard current = Keyboard.current; KeyControl val = ((current != null) ? Control(current, _toggleKey.Value) : null); if (current != null) { if (val != null && ((ButtonControl)val).wasPressedThisFrame) { string text = InputGuard.TypingReason(); if (text != null) { Plugin.Log.LogDebug((object)$"Toggle key {_toggleKey.Value} ignored: {text}."); } else if (_menu.Visible) { _menu.Close(); } else { _menu.Open(peek: true); } } if (_menu.Visible && ((ButtonControl)current.tabKey).wasPressedThisFrame && InputGuard.TypingReason() == null) { _menu.NextTab(); } if (_menu.Visible && ((ButtonControl)current.escapeKey).wasPressedThisFrame) { StatsMenu.ConsumeEscape(); } } bool held = val != null && ((ButtonControl)val).isPressed; UpdatePeek(held); _menu.Tick(); UpdateInputBlock(); UpdateCursor(); Plugin.Tracker.Tick(); ScoreboardColumns.Tick(Plugin.Tracker.Version); } private static KeyControl? Control(Keyboard keyboard, Key key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) if ((int)key == 0) { return null; } try { return keyboard[key]; } catch (ArgumentException) { return null; } } private void UpdatePeek(bool held) { if (!(!_menu.Peeking || held)) { if (_menu.PeekSeconds < 0.25f) { _menu.EndPeek(); } else { _menu.Close(); } } } private void UpdateCursor() { try { if (_cursorHandlingBroken) { return; } if (_menu.Interactive) { if (!CursorManager.isCursorForceUnlocked) { CursorManager.SetCursorForceUnlocked(true); _cursorForcedByUs = true; } } else if (_cursorForcedByUs) { _cursorForcedByUs = false; if (!FullScreenMessage.IsDisplayingAnyMessage) { CursorManager.SetCursorForceUnlocked(false); } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Cursor handling disabled: " + ex.Message)); _cursorHandlingBroken = true; _cursorForcedByUs = false; } } private void UpdateInputBlock() { if (_inputBlockingBroken) { return; } try { if (_menu.Interactive) { if (!InputModeHas((InputMode)32)) { InputManager.EnableMode((InputMode)32); _inputBlockedByUs = true; } } else if (_inputBlockedByUs) { ReleaseInputBlock(); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Game input blocking disabled: " + ex.Message)); _inputBlockingBroken = true; try { ReleaseInputBlock(); } catch { } } } [MethodImpl(MethodImplOptions.NoInlining)] private static bool InputModeHas(InputMode mode) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 return (InputManager.CurrentModeMask & mode) > 0; } [MethodImpl(MethodImplOptions.NoInlining)] private void ReleaseInputBlock() { if (_inputBlockedByUs) { _inputBlockedByUs = false; if (!PauseMenu.IsPaused) { InputManager.DisableMode((InputMode)32); } } } private void LateUpdate() { _menu.LateTick(); } private void OnApplicationQuit() { Plugin.Tracker.SaveIfDirty(); } private void OnDestroy() { try { ReleaseInputBlock(); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not restore game input: " + ex.Message)); } Plugin.Tracker.SaveIfDirty(); Plugin.Shutdown(); } } public enum ScoreboardRange { Match, Session, AllTime } internal static class ScoreboardColumns { private sealed class Row { public ScoreboardEntry Entry; public readonly GameObject[] Cells = (GameObject[])(object)new GameObject[Columns.Length]; public readonly TMP_Text[] Texts = (TMP_Text[])(object)new TMP_Text[Columns.Length]; public RectTransform Source; public ulong Guid; public float ColumnWidth; public float Widened; public LayoutElement? StatsLayout; public RectTransform? InfoBackground; public bool InfoOnLeft; public bool Alive { get { if ((Object)(object)Entry != (Object)null) { return Array.TrueForAll(Cells, (GameObject c) => (Object)(object)c != (Object)null); } return false; } } } private sealed class Header { public RectTransform Group; public RectTransform Original; public readonly GameObject[] Clones = (GameObject[])(object)new GameObject[Columns.Length]; public readonly RectTransform[] Icons = (RectTransform[])(object)new RectTransform[Columns.Length]; public readonly TMP_Text?[] Labels = (TMP_Text?[])(object)new TMP_Text[Columns.Length]; public Row Row; public bool Checked; public TMP_Text? Template; public float Height; } private static readonly (string Cell, string Header, string? Label)[] Columns = new(string, string, string)[2] { ("BonkBook_Taken", "BonkBook_TakenHeader", null), ("BonkBook_VsYou", "BonkBook_VsYouHeader", "vs You") }; private const int TakenColumn = 0; private const int VsYouColumn = 1; private const float HeaderLabelRestY = 0.02f; private const float HeaderLabelLowering = 0.5f; private const string DealtColor = "#2E9E44"; private const string ReceivedColor = "#D64535"; private const string OwnRow = "<alpha=#80>-"; private static ScoreboardRange _range = ScoreboardRange.Match; private static bool _enabled; private static bool _disabled; private static int _shownVersion = -1; private static Transform? _staging; private static Sprite? _takenIcon; private static bool _takenIconLoaded; private static readonly Dictionary<int, Row> Rows = new Dictionary<int, Row>(); private static readonly HashSet<int> HeaderDoneFor = new HashSet<int>(); private static readonly List<Header> Headers = new List<Header>(); private static readonly List<int> DeadRows = new List<int>(); private static Transform Staging { get { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown if ((Object)(object)_staging != (Object)null) { return _staging; } GameObject val = new GameObject("BonkBook.Staging") { hideFlags = (HideFlags)61 }; val.SetActive(false); Object.DontDestroyOnLoad((Object)val); _staging = val.transform; return _staging; } } public static void Configure(bool enabled, ScoreboardRange range) { _enabled = enabled; _range = range; _shownVersion = -1; } public static void OnPopulate(ScoreboardEntry entry, ulong playerGuid) { if (!_enabled || _disabled || (Object)(object)entry == (Object)null) { return; } try { Row orCreateRow = GetOrCreateRow(entry); if (orCreateRow != null) { orCreateRow.Guid = playerGuid; SetCells(orCreateRow); } } catch (Exception arg) { Disable($"row update failed: {arg}"); } } public static void Tick(int statsVersion) { if (!_enabled || _disabled || Rows.Count == 0) { return; } try { if (!ScoreboardVisible()) { return; } bool flag = false; foreach (Row value2 in Rows.Values) { if (value2.Alive && ((Component)value2.Entry).gameObject.activeInHierarchy && !HeaderDoneFor.Contains(ParentId(value2.Entry))) { flag = true; break; } } foreach (Header header in Headers) { if (!header.Checked) { flag = true; break; } } if (flag) { Canvas.ForceUpdateCanvases(); CheckHeaderAlignment(); foreach (KeyValuePair<int, Row> row in Rows) { Row value = row.Value; if (!value.Alive) { DeadRows.Add(row.Key); } else if (((Component)value.Entry).gameObject.activeInHierarchy) { EnsureHeader(value); if (_disabled) { return; } } } foreach (int deadRow in DeadRows) { Rows.Remove(deadRow); } DeadRows.Clear(); } if (statsVersion == _shownVersion) { return; } _shownVersion = statsVersion; foreach (Row value3 in Rows.Values) { if (value3.Alive) { SetCells(value3); } } } catch (Exception arg) { Disable($"deferred update failed: {arg}"); } } [MethodImpl(MethodImplOptions.NoInlining)] private static bool ScoreboardVisible() { return Scoreboard.IsVisible; } private static Row? GetOrCreateRow(ScoreboardEntry entry) { int instanceID = ((Object)entry).GetInstanceID(); if (Rows.TryGetValue(instanceID, out Row value) && value.Alive) { return value; } TMP_Text knockoutsLabel = GetKnockoutsLabel(entry); if ((Object)(object)knockoutsLabel == (Object)null) { Disable("ScoreboardEntry.knockouts is not set on this row; unexpected scoreboard layout"); return null; } Transform? obj = FindLayoutChild(((Component)entry).transform, knockoutsLabel.transform); RectTransform val = (RectTransform)(object)((obj is RectTransform) ? obj : null); if (val == null) { Disable("the knockouts label is not inside a layout group; unexpected scoreboard layout"); return null; } value = new Row { Entry = entry, Source = val }; GameObject knockoutMedal = GetKnockoutMedal(entry); int num = 0; for (int i = 0; i < Columns.Length; i++) { Transform val2 = (((Object)(object)((Transform)val).parent != (Object)null) ? ((Transform)val).parent.Find(Columns[i].Cell) : null); GameObject val3; if ((Object)(object)val2 != (Object)null) { val3 = ((Component)val2).gameObject; } else { val3 = Object.Instantiate<GameObject>(((Component)val).gameObject, Staging, false); UiKit.StripGameComponents(val3); val3.transform.SetParent(((Transform)val).parent, false); ((Object)val3).name = Columns[i].Cell; num++; } if ((Object)(object)knockoutMedal != (Object)null && (Object)(object)knockoutMedal.transform != (Object)(object)val && knockoutMedal.transform.IsChildOf((Transform)(object)val)) { Transform val4 = val3.transform.Find(UiKit.RelativePath((Transform)(object)val, knockoutMedal.transform)); if ((Object)(object)val4 != (Object)null) { ((Component)val4).gameObject.SetActive(false); ((Object)val4).name = ((Object)val4).name + " (Bonk Book hidden)"; } } object obj3; if (!((Object)(object)knockoutsLabel.transform == (Object)(object)val)) { Transform obj2 = val3.transform.Find(UiKit.RelativePath((Transform)(object)val, knockoutsLabel.transform)); obj3 = ((obj2 != null) ? ((Component)obj2).GetComponent<TMP_Text>() : null); } else { obj3 = val3.GetComponent<TMP_Text>(); } TMP_Text val5 = (TMP_Text)obj3; if ((Object)(object)val5 == (Object)null) { if ((Object)(object)val2 == (Object)null) { Object.Destroy((Object)(object)val3); } Disable("could not find the label inside the cloned knockouts cell"); return null; } val5.richText = true; val5.fontStyle = (FontStyles)0; val5.overflowMode = (TextOverflowModes)0; val5.textWrappingMode = (TextWrappingModes)0; val5.fontSizeMax = val5.fontSize; val5.fontSizeMin = Mathf.Max(8f, val5.fontSize * 0.45f); val5.enableAutoSizing = false; val3.transform.SetSiblingIndex(((Transform)val).GetSiblingIndex() + 1 + i); value.Cells[i] = val3; value.Texts[i] = val5; } Widen(value, num); GameObject[] cells = value.Cells; for (int j = 0; j < cells.Length; j++) { cells[j].SetActive(true); } Rows[instanceID] = value; Plugin.Log.LogDebug((object)($"Scoreboard: added {num} of {Columns.Length} columns to row {entry.name} " + $"(after '{((Object)val).name}' in '{((Object)((Transform)val).parent).name}', widened by {value.Widened:0})")); return value; } private static void Widen(Row row, int added) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) Transform parent = ((Transform)row.Source).parent; RectTransform val = (RectTransform)(object)((parent is RectTransform) ? parent : null); if ((Object)(object)val == (Object)null) { return; } Rect rect = row.Source.rect; float num; if (!(((Rect)(ref rect)).width > 1f)) { num = row.Source.sizeDelta.x; } else { rect = row.Source.rect; num = ((Rect)(ref rect)).width; } float num2 = num; HorizontalLayoutGroup val2 = default(HorizontalLayoutGroup); if (((Component)val).TryGetComponent<HorizontalLayoutGroup>(ref val2)) { num2 += ((HorizontalOrVerticalLayoutGroup)val2).spacing; } if (num2 <= 1f) { return; } row.ColumnWidth = num2; row.Widened = num2 * (float)Columns.Length; float num3 = num2 * (float)added; LayoutElement val3 = default(LayoutElement); if (((Component)val).TryGetComponent<LayoutElement>(ref val3) && val3.preferredWidth > 0f) { LayoutElement obj = val3; obj.preferredWidth += num3; if (val3.minWidth > 0f) { LayoutElement obj2 = val3; obj2.minWidth += num3; } row.StatsLayout = val3; } Image infoBackground = GetInfoBackground(row.Entry); if (!((Object)(object)infoBackground != (Object)null) || !((Object)(object)((Component)infoBackground).transform.parent == (Object)(object)((Transform)val).parent)) { return; } RectTransform rectTransform = ((Graphic)infoBackground).rectTransform; LayoutElement val4 = default(LayoutElement); if ((!((Component)infoBackground).TryGetComponent<LayoutElement>(ref val4) || val4.ignoreLayout) && Mathf.Approximately(rectTransform.anchorMin.x, 0f) && Mathf.Approximately(rectTransform.anchorMax.x, 1f)) { row.InfoOnLeft = ((Transform)val).GetSiblingIndex() > IndexOfFirstLayoutChild(((Transform)val).parent); if (row.InfoOnLeft) { rectTransform.offsetMax -= new Vector2(num3, 0f); } else { rectTransform.offsetMin += new Vector2(num3, 0f); } row.InfoBackground = rectTransform; } } private static int IndexOfFirstLayoutChild(Transform? parent) { if ((Object)(object)parent == (Object)null) { return 0; } LayoutElement val = default(LayoutElement); for (int i = 0; i < parent.childCount; i++) { Transform child = parent.GetChild(i); if (((Component)child).gameObject.activeSelf && (!((Component)child).TryGetComponent<LayoutElement>(ref val) || !val.ignoreLayout)) { return i; } } return 0; } private static void Unwiden(Row row) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) if (row.Widened <= 0f) { return; } if ((Object)(object)row.StatsLayout != (Object)null) { LayoutElement? statsLayout = row.StatsLayout; statsLayout.preferredWidth -= row.Widened; if (row.StatsLayout.minWidth > 0f) { LayoutElement? statsLayout2 = row.StatsLayout; statsLayout2.minWidth -= row.Widened; } } if ((Object)(object)row.InfoBackground != (Object)null) { if (row.InfoOnLeft) { RectTransform? infoBackground = row.InfoBackground; infoBackground.offsetMax += new Vector2(row.Widened, 0f); } else { RectTransform? infoBackground2 = row.InfoBackground; infoBackground2.offsetMin -= new Vector2(row.Widened, 0f); } } row.Widened = 0f; } private static Transform? FindLayoutChild(Transform root, Transform label) { Transform result = null; Transform val = label; while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)root && (!((Object)(object)val != (Object)(object)label) || ((Component)val).GetComponentsInChildren<TMP_Text>(true).Length <= 1)) { if ((Object)(object)val.parent != (Object)null && (Object)(object)((Component)val.parent).GetComponent<HorizontalLayoutGroup>() != (Object)null) { result = val; } val = val.parent; } return result; } private static int ParentId(ScoreboardEntry entry) { if (!((Object)(object)((Component)entry).transform.parent != (Object)null)) { return 0; } return ((Object)((Component)entry).transform.parent).GetInstanceID(); } private static void EnsureHeader(Row row) { //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Expected O, but got Unknown //IL_03c1: Unknown result type (might be due to invalid IL or missing references) //IL_03c8: Expected O, but got Unknown //IL_0466: Unknown result type (might be due to invalid IL or missing references) //IL_046b: Unknown result type (might be due to invalid IL or missing references) //IL_048d: Unknown result type (might be due to invalid IL or missing references) //IL_0492: Unknown result type (might be due to invalid IL or missing references) //IL_04b3: Unknown result type (might be due to invalid IL or missing references) //IL_04b8: Unknown result type (might be due to invalid IL or missing references) int item = ParentId(row.Entry); if (!HeaderDoneFor.Add(item)) { return; } Scoreboard componentInParent = ((Component)row.Entry).GetComponentInParent<Scoreboard>(true); if ((Object)(object)componentInParent == (Object)null) { Plugin.Log.LogInfo((object)"Scoreboard: row is not under the Scoreboard object; no header added."); return; } Vector3[] array = (Vector3[])(object)new Vector3[4]; row.Source.GetWorldCorners(array); float num = (array[0].x + array[2].x) * 0.5f; float num2 = array[2].x - array[0].x; float num3 = array[1].y - array[0].y; if (row.InfoOnLeft) { Transform transform = row.Cells[Columns.Length - 1].transform; RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null); if (val != null) { val.GetWorldCorners(array); num = (array[0].x + array[2].x) * 0.5f; } } float num4 = array[1].y; Transform parent = ((Component)row.Entry).transform.parent; if ((Object)(object)parent != (Object)null) { foreach (Transform item2 in parent) { Transform val2 = item2; if (((Component)val2).gameObject.activeInHierarchy) { RectTransform val3 = (RectTransform)(object)((val2 is RectTransform) ? val2 : null); if (val3 != null && !((Object)(object)((Component)val2).GetComponent<ScoreboardEntry>() == (Object)null)) { val3.GetWorldCorners(array); num4 = Mathf.Max(num4, array[1].y); } } } } float num5 = Mathf.Max(num2 * 0.35f, 4f); RectTransform val4 = null; RectTransform val5 = null; float num6 = float.PositiveInfinity; float num7 = float.PositiveInfinity; string name = ((Object)row.Source).name; RectTransform[] componentsInChildren = ((Component)componentInParent).GetComponentsInChildren<RectTransform>(false); foreach (RectTransform val6 in componentsInChildren) { Transform parent2 = ((Transform)val6).parent; if ((Object)(object)parent2 == (Object)null || (Object)(object)((Component)parent2).GetComponent<HorizontalLayoutGroup>() == (Object)null || IsOurs(((Object)val6).name) || (Object)(object)((Component)val6).GetComponentInParent<ScoreboardEntry>(true) != (Object)null || (Object)(object)((Component)val6).GetComponentInParent<ScoreboardStat>(true) != (Object)null || (Object)(object)((Component)val6).GetComponentInChildren<Graphic>(false) == (Object)null) { continue; } val6.GetWorldCorners(array); float num8 = array[2].x - array[0].x; if (num8 <= 0.01f || num8 > num2 * 2.5f) { continue; } float num9 = (array[0].x + array[2].x) * 0.5f; float num10 = (array[0].y + array[1].y) * 0.5f - num4; if (!(num10 <= 0f) && !(num10 > num3 * 2.5f)) { if (name.Length > 0 && ((Object)val6).name.StartsWith(name, StringComparison.OrdinalIgnoreCase) && num10 < num7) { num7 = num10; val5 = val6; } if (!(Mathf.Abs(num9 - num) > num5) && num10 < num6) { num6 = num10; val4 = val6; } } } if ((Object)(object)val5 != (Object)null) { val4 = val5; } if (!((Object)(object)val4 == (Object)null)) { Transform parent3 = ((Transform)val4).parent; RectTransform val7 = (RectTransform)(object)((parent3 is RectTransform) ? parent3 : null); if (val7 != null) { if ((Object)(object)((Transform)val7).Find(Columns[0].Header) != (Object)null) { return; } TMP_Text val8 = null; TMP_Text val10 = default(TMP_Text); foreach (Transform item3 in (Transform)val7) { Transform val9 = item3; if (!IsOurs(((Object)val9).name) && ((Component)val9).TryGetComponent<TMP_Text>(ref val10) && ((Object)(object)val8 == (Object)null || ((Object)val9).name.IndexOf("Ping", StringComparison.OrdinalIgnoreCase) >= 0)) { val8 = val10; } } TMP_Text style = (TMP_Text)(((Object)(object)val8 != (Object)null) ? ((object)val8) : ((object)row.Texts[0])); HorizontalLayoutGroup val11 = default(HorizontalLayoutGroup); float num11 = (((Component)val7).TryGetComponent<HorizontalLayoutGroup>(ref val11) ? ((HorizontalOrVerticalLayoutGroup)val11).spacing : 0f); Rect rect; float num12; if (!(row.ColumnWidth > 0f)) { rect = val4.rect; num12 = ((Rect)(ref rect)).width; } else { num12 = Mathf.Max(40f, row.ColumnWidth - num11); } float width = num12; rect = val4.rect; float height = ((Rect)(ref rect)).height; float num13; if (!((Object)(object)val8 != (Object)null)) { num13 = 0f; } else { rect = val8.rectTransform.rect; num13 = ((Rect)(ref rect)).height; } float num14 = Mathf.Max(height, num13); if (num14 < 30f) { num14 = 60f; } Header header = new Header { Group = val7, Original = val4, Row = row, Template = val8, Height = num14 }; for (int j = 0; j < Columns.Length; j++) { GameObject val12 = AddHeaderCell(val4, Columns[j].Header, Columns[j].Label, (j == 0) ? TakenIcon() : null, style, width, num14, out header.Icons[j], out header.Labels[j]); val12.transform.SetSiblingIndex(((Transform)val4).GetSiblingIndex() + 1 + j); header.Clones[j] = val12; } Headers.Add(header); Plugin.Log.LogDebug((object)($"Scoreboard: {Columns.Length} header cells inserted after '{((Object)val4).name}' in '{((Object)val7).name}' " + "(icon copy + label styled like " + (((Object)(object)val8 != (Object)null) ? ("'" + ((Object)val8).name + "'") : "the row label") + ").")); return; } } Plugin.Log.LogInfo((object)"Scoreboard: no header cell found above the knockouts column; the added columns have no header."); } private static GameObject AddHeaderCell(RectTransform best, string name, string? label, Sprite? sprite, TMP_Text style, float width, float height, out RectTransform iconRt, out TMP_Text? text) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0103: 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_013a: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Expected O, but got Unknown //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018d: 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_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) }) { layer = ((Component)best).gameObject.layer }; val.SetActive(false); RectTransform val2 = (RectTransform)val.transform; ((Transform)val2).SetParent(Staging, false); val2.sizeDelta = new Vector2(width, height); LayoutElement obj = val.AddComponent<LayoutElement>(); obj.preferredWidth = width; obj.preferredHeight = height; GameObject val3 = Object.Instantiate<GameObject>(((Component)best).gameObject, Staging, false); UiKit.StripGameComponents(val3); ((Object)val3).name = "Icon"; iconRt = (RectTransform)val3.transform; ((Transform)iconRt).SetParent((Transform)(object)val2, false); LayoutElement val4 = default(LayoutElement); if (val3.TryGetComponent<LayoutElement>(ref val4)) { val4.ignoreLayout = true; } RectTransform obj2 = iconRt; RectTransform obj3 = iconRt; Vector2 val5 = default(Vector2); ((Vector2)(ref val5))..ctor(0.5f, 1f); obj3.anchorMax = val5; obj2.anchorMin = val5; iconRt.pivot = new Vector2(0.5f, 1f); RectTransform obj4 = iconRt; Rect rect = best.rect; obj4.sizeDelta = ((Rect)(ref rect)).size; ((Transform)iconRt).localScale = new Vector3(0.72f, 0.72f, 1f); iconRt.anchoredPosition = new Vector2(0f, (0f - height) * 0.04f); if ((Object)(object)sprite != (Object)null) { Image componentInChildren = val3.GetComponentInChildren<Image>(true); if (componentInChildren != null) { componentInChildren.sprite = sprite; } } val3.SetActive(true); if (label == null) { RectTransform obj5 = iconRt; RectTransform obj6 = iconRt; RectTransform obj7 = iconRt; Vector2 val6 = default(Vector2); ((Vector2)(ref val6))..ctor(0.5f, 0.5f); obj7.pivot = val6; val5 = (obj5.anchorMin = (obj6.anchorMax = val6)); ((Transform)iconRt).localScale = Vector3.one; iconRt.anchoredPosition = Vector2.zero; text = null; return Place(val, best); } GameObject val9 = new GameObject("Label", new Type[1] { typeof(RectTransform) }) { layer = ((Component)best).gameObject.layer }; val9.SetActive(false); RectTransform val10 = (RectTransform)val9.transform; ((Transform)val10).SetParent((Transform)(object)val2, false); val10.anchorMin = new Vector2(0f, 0f); val10.anchorMax = new Vector2(1f, 0f); val10.pivot = new Vector2(0.5f, 0f); val10.sizeDelta = new Vector2(0f, height * 0.38f); val10.anchoredPosition = Vector2.zero; text = (TMP_Text?)(object)val9.AddComponent<TextMeshProUGUI>(); text.font = style.font; if ((Object)(object)style.fontSharedMaterial != (Object)null) { text.fontSharedMaterial = style.fontSharedMaterial; } ((Graphic)text).color = ((Graphic)style).color; text.fontStyle = (FontStyles)1; text.fontSize = Mathf.Clamp(style.fontSize * 0.7f, 12f, 20f); text.enableAutoSizing = true; text.fontSizeMax = text.fontSize; text.fontSizeMin = 10f; text.alignment = (TextAlignmentOptions)514; text.textWrappingMode = (TextWrappingModes)0; text.overflowMode = (TextOverflowModes)0; ((Graphic)text).raycastTarget = false; text.text = label; val9.SetActive(true); return Place(val, best); } private static GameObject Place(GameObject cell, RectTransform best) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) cell.transform.SetParent(((Transform)best).parent, false); cell.transform.localScale = Vector3.one; cell.SetActive(true); return cell; } private static Sprite? TakenIcon() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) if (_takenIconLoaded) { return _takenIcon; } _takenIconLoaded = true; try { using Stream stream = typeof(ScoreboardColumns).Assembly.GetManifestResourceStream("BonkBook.assets.taken.png"); using MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true) { hideFlags = (HideFlags)61 }; if (!ImageConversion.LoadImage(val, memoryStream.ToArray(), true)) { throw new InvalidDataException("not a PNG"); } ((Texture)val).filterMode = (FilterMode)1; ((Texture)val).wrapMode = (TextureWrapMode)1; _takenIcon = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f)); ((Object)_takenIcon).hideFlags = (HideFlags)61; } catch (Exception ex) { Plugin.Log.LogDebug((object)("Scoreboard: Taken icon not loaded, using the knockouts icon: " + ex.Message)); } return _takenIcon; } private static bool IsOurs(string name) { return Array.Exists(Columns, ((string Cell, string Header, string Label) c) => c.Cell == name || c.Header == name); } private static void CheckHeaderAlignment() { //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Expected O, but got Unknown //IL_026e: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Expected O, but got Unknown //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_02e1: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0313: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) Vector3[] corners = (Vector3[])(object)new Vector3[4]; HorizontalLayoutGroup val = default(HorizontalLayoutGroup); foreach (Header header in Headers) { if (header.Checked) { continue; } header.Checked = true; if ((Object)(object)header.Group == (Object)null || (Object)(object)header.Original == (Object)null || (Object)(object)header.Clones[0] == (Object)null || (Object)(object)header.Row.Source == (Object)null || !header.Row.Alive) { continue; } if (!((Component)header.Row.Entry).gameObject.activeInHierarchy) { header.Checked = false; continue; } header.Row.Source.GetWorldCorners(corners); float num = corners[2].x - corners[0].x; float num2 = Center(header.Original) - Center(header.Row.Source); if (Mathf.Abs(num2) > Mathf.Max(num * 0.1f, 2f) && ((Component)header.Group).TryGetComponent<HorizontalLayoutGroup>(ref val)) { float num3 = (Mathf.Approximately(((Transform)header.Group).lossyScale.x, 0f) ? 1f : ((Transform)header.Group).lossyScale.x); int num4 = Mathf.RoundToInt((0f - num2) / num3); float num5 = (float)(((LayoutGroup)val).childAlignment % 3) * 0.5f; RectOffset padding = ((LayoutGroup)val).padding; if (num5 < 0.25f) { padding.left += num4; } else if (num5 > 0.75f) { padding.right -= num4; } else { padding.left += 2 * num4; } ((LayoutGroup)val).padding = padding; LayoutRebuilder.MarkLayoutForRebuild(header.Group); Plugin.Log.LogInfo((object)($"Scoreboard: header row was {num2:0.#} px off the rows after inserting the columns; " + $"shifted '{((Object)header.Group).name}' by {num4} (alignment {((LayoutGroup)val).childAlignment}).")); } else { float num6 = Center((RectTransform)header.Clones[0].transform) - Center((RectTransform)header.Row.Cells[0].transform); Plugin.Log.LogDebug((object)$"Scoreboard header aligned (knockouts header off by {num2:0.#} px, first added header off by {num6:0.#} px)."); } for (int i = 0; i < Columns.Length; i++) { TMP_Text val2 = header.Labels[i]; if (val2 != null) { AlignHeaderLabel(header, val2, header.Icons[i]); } else if ((Object)(object)header.Icons[i] != (Object)null) { RectTransform obj = header.Icons[i]; ((Transform)obj).position = ((Transform)obj).position + new Vector3(0f, Middle(header.Original) - Middle(header.Icons[i]), 0f); } } } float Center(RectTransform rt) { rt.GetWorldCorners(corners); return (corners[0].x + corners[2].x) * 0.5f; } float Middle(RectTransform rt) { rt.GetWorldCorners(corners); return (corners[0].y + corners[1].y) * 0.5f; } } private static void AlignHeaderLabel(Header h, TMP_Text label, RectTransform icon) { //IL_001d: 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_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0110: 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_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)label == (Object)null || (Object)(object)icon == (Object)null) { return; } float y = ((Transform)label.rectTransform).lossyScale.y; if (Mathf.Abs(y) < 1E-06f) { return; } label.ForceMeshUpdate(false, false); if (label.textInfo == null || label.textInfo.lineCount == 0) { return; } float num = 0f; if ((Object)(object)h.Template != (Object)null && ((Behaviour)h.Template).isActiveAndEnabled) { h.Template.ForceMeshUpdate(false, false); TMP_TextInfo textInfo = h.Template.textInfo; if (textInfo != null && textInfo.lineCount > 0) { num = Baseline(h.Template, textInfo.lineInfo[0].baseline) - Baseline(label, label.textInfo.lineInfo[0].baseline); } } Vector3[] array = (Vector3[])(object)new Vector3[4]; icon.GetWorldCorners(array); float y2 = array[0].y; Transform transform = label.transform; Bounds textBounds = label.textBounds; float y3 = transform.TransformPoint(new Vector3(0f, ((Bounds)(ref textBounds)).max.y, 0f)).y; num = Mathf.Min(num, y2 - 2f * y - y3); floa