Decompiled source of CombatPanel v1.19.71
BepInEx/plugins/GTFOCombatPanel/GTFOCombatPanel.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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Threading; using Agents; using BepInEx; using BepInEx.Configuration; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using CellMenu; using Enemies; using GameData; using Gear; using HarmonyLib; using Il2CppInterop.Runtime.Attributes; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections; using Il2CppSystem.Collections.Generic; using LevelGeneration; using Microsoft.CodeAnalysis; using Player; using SNetwork; using TMPro; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyFileVersion("1.19.71.0")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.19.71.0")] [module: UnverifiableCode] 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; } } } namespace HawChow.GTFOCombatPanel { [HarmonyPatch] internal static class WeaponFirePatch { internal static IEnumerable<MethodBase> TargetMethods() { Type[] array = new Type[4] { typeof(BulletWeapon), typeof(Shotgun), typeof(BulletWeaponSynced), typeof(ShotgunSynced) }; foreach (Type type in array) { yield return AccessTools.DeclaredMethod(type, "Fire", new Type[1] { typeof(bool) }, (Type[])null); } } [HarmonyPrefix] private static void Prefix(BulletWeapon __instance, out FireCapture __state) { __state = CombatTracker.BeginFire(__instance); } [HarmonyPostfix] private static void Postfix(FireCapture __state) { CombatTracker.EndFire(__state, succeeded: true); } [HarmonyFinalizer] private static void Finalizer(Exception __exception, FireCapture __state) { if (__exception != null) { CombatTracker.EndFire(__state, succeeded: false); } } } [HarmonyPatch] internal static class ProjectileRayPatch { internal static MethodBase TargetMethod() { return AccessTools.Method(typeof(Weapon), "CastWeaponRay", new Type[4] { typeof(Transform), typeof(WeaponHitData).MakeByRefType(), typeof(Vector3), typeof(int) }, (Type[])null); } [HarmonyPostfix] private static void Postfix(WeaponHitData weaponRayData) { CombatTracker.OnWeaponRay(weaponRayData); } } [HarmonyPatch(typeof(Dam_EnemyDamageLimb), "BulletDamage")] internal static class EnemyPelletContactPatch { [HarmonyPostfix] private static void Postfix(Dam_EnemyDamageLimb __instance, Agent sourceAgent) { CombatTracker.OnEnemyLimbHit(__instance, sourceAgent); } } [HarmonyPatch(typeof(PlayerInventorySynced), "GetSync")] internal static class RemoteShotsPatch { [HarmonyPrefix] private static void Prefix(PlayerInventorySynced __instance) { CombatTracker.OnRemoteSync(__instance); } } [HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "UpdateFireMaster")] internal static class SentryDamageSourcePatch { [HarmonyPrefix] private static void Prefix(SentryGunInstance_Firing_Bullets __instance, out SentryScope __state) { __state = ToolStatsTracker.BeginSentry(__instance); } [HarmonyFinalizer] private static void Finalizer(SentryScope __state) { ToolStatsTracker.EndSentry(__state); } } public enum AnchorCanvasMode { Unknown, Overlay, ScreenSpaceCamera, WorldSpace } public enum AnchorCameraSource { None, HudWorldCamera, CanvasWorldCamera, PageCamera, MainCamera, AllCameras, ElementCanvas, CellUiCamera } public enum AnchorProjection { None, Camera, CameraLessOverlay, Rect } public readonly struct AnchorCameraCandidate { public readonly AnchorCameraSource Source; public readonly bool Alive; public readonly int CullingMask; public readonly int Depth; public readonly bool TargetTexture; public static AnchorCameraCandidate None => new AnchorCameraCandidate(AnchorCameraSource.None, alive: false, 0, 0); public AnchorCameraCandidate(AnchorCameraSource source, bool alive, int cullingMask, int depth, bool targetTexture = false) { Source = source; Alive = alive; CullingMask = cullingMask; Depth = depth; TargetTexture = targetTexture; } } public readonly struct AnchorCameraChoice { public readonly AnchorProjection Projection; public readonly AnchorCameraSource Source; public readonly int Index; public readonly string Reason; public bool Usable => Projection != AnchorProjection.None; public AnchorCameraChoice(AnchorProjection projection, AnchorCameraSource source, int index, string reason) { Projection = projection; Source = source; Index = index; Reason = reason ?? string.Empty; } public static AnchorCameraChoice Unusable(string reason) { return new AnchorCameraChoice(AnchorProjection.None, AnchorCameraSource.None, -1, reason); } public static string Describe(AnchorCameraChoice choice) { return choice.Projection switch { AnchorProjection.Camera => "projected through " + Name(choice.Source), AnchorProjection.CameraLessOverlay => "projected without a camera (screen-space overlay canvas)", AnchorProjection.Rect => "the element's own RectTransform layout rectangle, projected by the camera that draws its canvas (or without one, inside a real screen-space overlay canvas)", _ => "no projection: " + ((choice.Reason.Length > 0) ? choice.Reason : "no candidate camera"), }; } public static string Provenance(AnchorProjection projection) { return projection switch { AnchorProjection.Camera => "camera", AnchorProjection.CameraLessOverlay => "canvas-overlay", AnchorProjection.Rect => "canvas-geometry", _ => "config", }; } public static string Provenance(AnchorProjection projection, bool measured) { if (!measured) { return Provenance(AnchorProjection.None); } return Provenance(projection); } public static string Authorization(AnchorProjection projection, bool measured) { if (projection == AnchorProjection.None) { return "none"; } if (!measured) { return Provenance(projection) + "(refused)"; } return Provenance(projection); } public static string Describe(AnchorCameraChoice choice, bool measured) { if (choice.Projection == AnchorProjection.None || measured) { return Describe(choice); } return choice.Projection switch { AnchorProjection.Camera => "authorized by " + Name(choice.Source) + ", but that projection answered no usable rectangle", AnchorProjection.CameraLessOverlay => "authorized by the screen-space overlay canvas, but that projection answered no usable rectangle", _ => "the canvas-geometry authorization (the element's own RectTransform, projected by the camera that draws its canvas or without one inside a real screen-space overlay canvas) was granted, but there was no camera to project it with, so it refused", }; } public static AnchorCameraChoice ManualCanvas() { return new AnchorCameraChoice(AnchorProjection.Rect, AnchorCameraSource.None, -1, "the element has no ancestor Canvas, so the ladder's refusal rests on the layer's own mode; this HUD's manual canvas is verified for this window and is the object that composites the element"); } public static string Token(AnchorCameraSource source) { return source switch { AnchorCameraSource.HudWorldCamera => "hud", AnchorCameraSource.CanvasWorldCamera => "canvas", AnchorCameraSource.CellUiCamera => "cellui", AnchorCameraSource.ElementCanvas => "element-canvas", AnchorCameraSource.PageCamera => "page", AnchorCameraSource.MainCamera => "main", AnchorCameraSource.AllCameras => "all", _ => "none", }; } public static string Name(AnchorCameraSource source) { return source switch { AnchorCameraSource.HudWorldCamera => "the HUD's own world camera", AnchorCameraSource.CanvasWorldCamera => "the icon canvas' worldCamera", AnchorCameraSource.PageCamera => "the game's GUI camera", AnchorCameraSource.MainCamera => "Camera.main", AnchorCameraSource.AllCameras => "the deepest camera that draws the icon's layer", AnchorCameraSource.ElementCanvas => "the element's own ancestor canvas worldCamera", AnchorCameraSource.CellUiCamera => "the CellUI canvas' own camera (GuiLayerBase.m_cellUICanvas.m_UICamera)", _ => "no camera", }; } } public static class AnchorCameraLadder { public static bool Renders(int cullingMask, int layer) { if (layer >= 0 && layer < 32) { return (cullingMask & (1 << layer)) != 0; } return false; } public static int Rank(AnchorCameraSource source) { return source switch { AnchorCameraSource.ElementCanvas => 1, AnchorCameraSource.HudWorldCamera => 2, AnchorCameraSource.CanvasWorldCamera => 3, AnchorCameraSource.CellUiCamera => 4, AnchorCameraSource.PageCamera => 5, AnchorCameraSource.MainCamera => 6, AnchorCameraSource.AllCameras => 7, _ => 8, }; } public static List<int> Order(IReadOnlyList<AnchorCameraCandidate> candidates) { List<int> list = new List<int>(); if (candidates == null) { return list; } for (int i = 0; i < candidates.Count; i++) { list.Add(i); } list.Sort(delegate(int left, int right) { AnchorCameraCandidate anchorCameraCandidate = candidates[left]; AnchorCameraCandidate anchorCameraCandidate2 = candidates[right]; int num = Rank(anchorCameraCandidate.Source).CompareTo(Rank(anchorCameraCandidate2.Source)); if (num != 0) { return num; } int num2 = (anchorCameraCandidate.TargetTexture ? 1 : 0).CompareTo(anchorCameraCandidate2.TargetTexture ? 1 : 0); if (num2 != 0) { return num2; } int num3 = anchorCameraCandidate2.Depth.CompareTo(anchorCameraCandidate.Depth); return (num3 != 0) ? num3 : left.CompareTo(right); }); return list; } public static AnchorCameraChoice Select(IReadOnlyList<AnchorCameraCandidate> candidates, int elementLayer, AnchorCanvasMode mode, bool canvasDrawn, out int inspected) { return Select(candidates, elementLayer, mode, canvasDrawn, hasRectTransform: false, out inspected); } public static AnchorCameraChoice Select(IReadOnlyList<AnchorCameraCandidate> candidates, int elementLayer, AnchorCanvasMode mode, bool canvasDrawn, bool hasRectTransform, out int inspected) { inspected = 0; List<int> list = Order(candidates); inspected = list.Count; if (canvasDrawn && mode == AnchorCanvasMode.ScreenSpaceCamera) { for (int i = 0; i < list.Count; i++) { int index = list[i]; AnchorCameraCandidate anchorCameraCandidate = candidates[index]; if ((anchorCameraCandidate.Source == AnchorCameraSource.CanvasWorldCamera || anchorCameraCandidate.Source == AnchorCameraSource.ElementCanvas) && anchorCameraCandidate.Alive && !anchorCameraCandidate.TargetTexture) { return new AnchorCameraChoice(AnchorProjection.Camera, anchorCameraCandidate.Source, index, "the element is drawn by Unity's canvas, which a screen-space-camera canvas projects through its own worldCamera; a canvas draw is not culled through the camera's culling mask"); } } } for (int j = 0; j < list.Count; j++) { int index2 = list[j]; AnchorCameraCandidate anchorCameraCandidate2 = candidates[index2]; if (anchorCameraCandidate2.Alive && Renders(anchorCameraCandidate2.CullingMask, elementLayer) && !anchorCameraCandidate2.TargetTexture) { return new AnchorCameraChoice(AnchorProjection.Camera, anchorCameraCandidate2.Source, index2, "the camera's culling mask contains the element's layer"); } } if (canvasDrawn && mode == AnchorCanvasMode.Overlay) { return new AnchorCameraChoice(AnchorProjection.CameraLessOverlay, AnchorCameraSource.None, -1, "the element is drawn by Unity's canvas inside a screen-space overlay canvas"); } if (AnchorCanvasProjection.Authorized(hasRectTransform, mode)) { return new AnchorCameraChoice(AnchorProjection.Rect, AnchorCameraSource.None, -1, "the element carries a RectTransform inside a screen-space canvas, so Unity's own canvas layout is the drawn rectangle and no camera has to prove anything"); } if (canvasDrawn && mode == AnchorCanvasMode.ScreenSpaceCamera && CanvasCameraOffered(candidates, out var textureOnly)) { return AnchorCameraChoice.Unusable(textureOnly ? "the element's canvas is screen-space-camera and its own worldCamera renders into a RenderTexture, whose pixels are not window pixels, and no other live camera could be shown to draw the element" : "the element's canvas is screen-space-camera but its own worldCamera is not a live window camera, and no other live camera could be shown to draw the element"); } if (elementLayer < 0 || elementLayer >= 32) { return AnchorCameraChoice.Unusable("the element's layer could not be read, so no camera can be shown to draw it"); } if (mode == AnchorCanvasMode.Overlay) { return AnchorCameraChoice.Unusable(OnlyRenderTextures(candidates, elementLayer) ? "the element's canvas is screen-space overlay, which draws no world geometry, and the only cameras that could draw its layer render into a RenderTexture, whose pixels are not window pixels" : "the element's canvas is screen-space overlay - which draws no camera - while the element is world geometry; nothing can be shown to draw it"); } return AnchorCameraChoice.Unusable(OnlyRenderTextures(candidates, elementLayer) ? "the only live cameras whose culling mask contains the element's layer render into a RenderTexture, whose pixels are not window pixels" : "no live camera in the read chain has the element's layer in its culling mask"); } private static bool CanvasCameraOffered(IReadOnlyList<AnchorCameraCandidate> candidates, out bool textureOnly) { textureOnly = false; if (candidates == null) { return false; } bool flag = false; for (int i = 0; i < candidates.Count; i++) { AnchorCameraCandidate anchorCameraCandidate = candidates[i]; if (anchorCameraCandidate.Source == AnchorCameraSource.CanvasWorldCamera || anchorCameraCandidate.Source == AnchorCameraSource.ElementCanvas) { flag = true; if (!anchorCameraCandidate.TargetTexture) { return true; } } } if (flag) { textureOnly = true; } return flag; } private static bool OnlyRenderTextures(IReadOnlyList<AnchorCameraCandidate> candidates, int layer) { if (candidates == null) { return false; } bool result = false; for (int i = 0; i < candidates.Count; i++) { AnchorCameraCandidate anchorCameraCandidate = candidates[i]; if (anchorCameraCandidate.Alive && Renders(anchorCameraCandidate.CullingMask, layer)) { result = true; if (!anchorCameraCandidate.TargetTexture) { return false; } } } return result; } public static string Inspect(IReadOnlyList<AnchorCameraCandidate> candidates) { if (candidates == null || candidates.Count == 0) { return "candidates=0"; } int num = 0; for (int i = 0; i < candidates.Count; i++) { if (candidates[i].Alive) { num++; } } return "candidates=" + candidates.Count + ",alive=" + num; } public static string Detail(IReadOnlyList<AnchorCameraCandidate> candidates, int elementLayer) { if (candidates == null || candidates.Count == 0) { return "each=none"; } List<int> list = Order(candidates); StringBuilder stringBuilder = new StringBuilder("each="); for (int i = 0; i < list.Count; i++) { AnchorCameraCandidate anchorCameraCandidate = candidates[list[i]]; if (i > 0) { stringBuilder.Append(';'); } stringBuilder.Append('#').Append(list[i]).Append(':') .Append(AnchorCameraChoice.Token(anchorCameraCandidate.Source)) .Append(",alive=") .Append(anchorCameraCandidate.Alive ? "yes" : "no") .Append(",mask=0x") .Append(anchorCameraCandidate.CullingMask.ToString("X8")) .Append(",rendersLayer=") .Append(Renders(anchorCameraCandidate.CullingMask, elementLayer) ? "yes" : "no") .Append(",depth=") .Append(anchorCameraCandidate.Depth) .Append(",texture=") .Append(anchorCameraCandidate.TargetTexture ? "yes" : "no"); } return stringBuilder.ToString(); } } public static class AnchorCanvasProjection { public static bool Authorized(bool hasRectTransform, AnchorCanvasMode mode) { if (hasRectTransform) { if (mode != AnchorCanvasMode.Overlay) { return mode == AnchorCanvasMode.ScreenSpaceCamera; } return true; } return false; } public static bool CameraLegitimate(bool hasCamera, AnchorCanvasMode mode) { if (!hasCamera) { return mode == AnchorCanvasMode.Overlay; } return true; } } public readonly struct AnchorManualCanvasFacts { public readonly bool CanvasPresent; public readonly bool CameraPresent; public readonly bool ElementInsideCanvas; public readonly int ElementLayer; public readonly int CameraMask; public readonly bool CameraDrawsLayer; public readonly int CameraPixelWidth; public readonly int CameraPixelHeight; public readonly int WindowWidth; public readonly int WindowHeight; public readonly float CanvasPixelWidth; public readonly float CanvasPixelHeight; public readonly float ViewportX; public readonly float ViewportY; public readonly float ViewportWidth; public readonly float ViewportHeight; public readonly bool CameraEnabled; public readonly bool CameraActive; public readonly bool CameraOrthographic; public readonly float CameraOrthographicSize; public static AnchorManualCanvasFacts None => default(AnchorManualCanvasFacts); public bool FullViewport { get { if (About(ViewportX, 0f) && About(ViewportY, 0f) && About(ViewportWidth, 1f)) { return About(ViewportHeight, 1f); } return false; } } public bool RenderTargetMatchesWindow { get { if (CameraPresent && CameraPixelWidth > 0 && CameraPixelHeight > 0 && CameraPixelWidth == WindowWidth) { return CameraPixelHeight == WindowHeight; } return false; } } public bool CanvasPixelsMatchWindow { get { if (CanvasPresent && WindowWidth > 0 && WindowHeight > 0 && Near(CanvasPixelWidth, WindowWidth)) { return Near(CanvasPixelHeight, WindowHeight); } return false; } } public bool Verified { get { if (CanvasPresent && CameraPresent && ElementInsideCanvas && CameraDrawsLayer && FullViewport && RenderTargetMatchesWindow) { return CanvasPixelsMatchWindow; } return false; } } public AnchorManualCanvasFacts(bool canvasPresent, bool cameraPresent, bool elementInsideCanvas, int elementLayer, bool cameraDrawsLayer, int cameraMask, int cameraPixelWidth, int cameraPixelHeight, float canvasPixelWidth, float canvasPixelHeight, int windowWidth, int windowHeight, float viewportX, float viewportY, float viewportWidth, float viewportHeight, bool cameraEnabled = false, bool cameraActive = false, bool cameraOrthographic = false, float cameraOrthographicSize = 0f) { CanvasPresent = canvasPresent; CameraPresent = cameraPresent; ElementInsideCanvas = elementInsideCanvas; ElementLayer = elementLayer; CameraDrawsLayer = cameraDrawsLayer; CameraMask = cameraMask; CameraPixelWidth = cameraPixelWidth; CameraPixelHeight = cameraPixelHeight; CanvasPixelWidth = canvasPixelWidth; CanvasPixelHeight = canvasPixelHeight; WindowWidth = windowWidth; WindowHeight = windowHeight; ViewportX = viewportX; ViewportY = viewportY; ViewportWidth = viewportWidth; ViewportHeight = viewportHeight; CameraEnabled = cameraEnabled; CameraActive = cameraActive; CameraOrthographic = cameraOrthographic; CameraOrthographicSize = cameraOrthographicSize; } private static bool About(float value, float expected) { if (float.IsFinite(value)) { return Math.Abs(value - expected) <= 0.0001f; } return false; } private static bool Near(float value, float expected) { if (float.IsFinite(value)) { return Math.Abs(value - expected) < 0.5f; } return false; } } public static class AnchorManualCanvasPolicy { public static string Refusal(AnchorManualCanvasFacts facts) { if (!facts.CanvasPresent) { return "GuiLayerBase.m_cellUICanvas is absent, so this HUD names no manual canvas at all"; } if (!facts.CameraPresent) { return "GuiLayerBase.m_cellUICanvas names no m_UICamera, so the manual canvas has no camera"; } if (!facts.ElementInsideCanvas) { return "the element is not a descendant of GuiLayerBase.m_cellUICanvas.m_rectTransform, so that canvas' camera cannot be shown to draw it"; } if (!facts.CameraDrawsLayer) { return "the manual canvas' camera does not draw the element's layer " + facts.ElementLayer + " (culling mask 0x" + facts.CameraMask.ToString("X8") + ")"; } if (!facts.FullViewport) { return "the manual canvas' camera renders into part of its texture (viewport (" + Number(facts.ViewportX) + "," + Number(facts.ViewportY) + "," + Number(facts.ViewportWidth) + "," + Number(facts.ViewportHeight) + ")), so its pixels are not this window's"; } if (!facts.RenderTargetMatchesWindow) { return "the manual canvas' camera renders into a " + facts.CameraPixelWidth + "x" + facts.CameraPixelHeight + " texture while the window is " + facts.WindowWidth + "x" + facts.WindowHeight + ", and no conversion from that texture's pixels has been verified"; } if (!facts.CanvasPixelsMatchWindow) { return "the manual canvas is laid out for " + Number(facts.CanvasPixelWidth) + "x" + Number(facts.CanvasPixelHeight) + " pixels while the window is " + facts.WindowWidth + "x" + facts.WindowHeight; } return "none"; } public static string Describe(AnchorManualCanvasFacts facts) { string text = "(" + Number(facts.ViewportX) + "," + Number(facts.ViewportY) + "," + Number(facts.ViewportWidth) + "," + Number(facts.ViewportHeight) + ")"; return "verified=" + (facts.Verified ? "yes" : "no") + ",canvas=" + (facts.CanvasPresent ? "present" : "missing") + ",camera=" + (facts.CameraPresent ? "present" : "missing") + ",inside=" + (facts.ElementInsideCanvas ? "yes" : "no") + ",layer=" + facts.ElementLayer + ",mask=0x" + facts.CameraMask.ToString("X8") + ",drawsLayer=" + (facts.CameraDrawsLayer ? "yes" : "no") + ",viewport=" + text + ",target=" + facts.CameraPixelWidth + "x" + facts.CameraPixelHeight + ",canvasPixels=" + Number(facts.CanvasPixelWidth) + "x" + Number(facts.CanvasPixelHeight) + ",window=" + facts.WindowWidth + "x" + facts.WindowHeight + ",targetMatchesWindow=" + (facts.RenderTargetMatchesWindow ? "yes" : "no") + ",canvasPixelsMatchWindow=" + (facts.CanvasPixelsMatchWindow ? "yes" : "no") + ",enabled=" + (facts.CameraEnabled ? "yes" : "no") + ",activeInHierarchy=" + (facts.CameraActive ? "yes" : "no") + ",orthographic=" + (facts.CameraOrthographic ? "yes" : "no") + ",orthographicSize=" + Number(facts.CameraOrthographicSize) + (facts.Verified ? ",origin=manual-canvas" : (",origin=refused(" + Refusal(facts) + ")")); } public static string Field(bool observed, AnchorManualCanvasFacts facts) { if (observed) { if (!facts.CanvasPresent) { return "absent"; } return Describe(facts); } return "not-observed"; } private static string Number(float value) { if (!float.IsFinite(value)) { if (!float.IsNaN(value)) { if (!(value > 0f)) { return "-inf"; } return "+inf"; } return "NaN"; } return value.ToString("0.##"); } } public static class AnchorCameraIdentity { public static bool Same(long left, long right) { if (left != 0L) { return left == right; } return false; } public static int IndexOf(IReadOnlyList<AnchorCameraCandidate> candidates, IReadOnlyList<long> pointers, AnchorCameraSource source, long pointer) { if (candidates == null) { return -1; } if (pointer != 0L) { if (pointers == null) { return -1; } int num = Math.Min(candidates.Count, pointers.Count); for (int i = 0; i < num; i++) { if (Same(pointers[i], pointer)) { return i; } } return -1; } if (source == AnchorCameraSource.None) { return -1; } for (int j = 0; j < candidates.Count; j++) { if (candidates[j].Source == source) { return j; } } return -1; } } public readonly struct AnchorScreenRect { public readonly float Left; public readonly float Top; public readonly float Width; public readonly float Height; public readonly bool Finite; public AnchorScreenRect(float left, float top, float width, float height, bool finite) { Left = left; Top = top; Width = width; Height = height; Finite = finite; } public string Describe() { if (Finite || Left != 0f || Top != 0f || Width != 0f || Height != 0f) { return "(" + Number(Left) + "," + Number(Top) + "," + Number(Width) + "," + Number(Height) + ")"; } return "none"; } private static string Number(float value) { if (!float.IsFinite(value)) { if (!float.IsNaN(value)) { if (!(value > 0f)) { return "-inf"; } return "+inf"; } return "NaN"; } return value.ToString("0.##"); } } public static class AnchorRectProjection { public static bool TryRectFromPivot(float pivotX, float pivotY, float width, float height, out float minX, out float maxX, out float minY, out float maxY) { minX = (maxX = (minY = (maxY = 0f))); if (!float.IsFinite(pivotX) || !float.IsFinite(pivotY) || !float.IsFinite(width) || !float.IsFinite(height)) { return false; } float num = Math.Abs(width); float num2 = Math.Abs(height); if (!(num > 0f) || !(num2 > 0f)) { return false; } minX = (0f - pivotX) * num; maxX = (1f - pivotX) * num; minY = (0f - pivotY) * num2; maxY = (1f - pivotY) * num2; return true; } public static AnchorScreenRect Raw(IReadOnlyList<float> xs, IReadOnlyList<float> ys) { if (xs == null || ys == null || xs.Count == 0 || xs.Count != ys.Count) { return new AnchorScreenRect(float.NaN, float.NaN, float.NaN, float.NaN, finite: false); } float num = float.MaxValue; float num2 = float.MaxValue; float num3 = float.MinValue; float num4 = float.MinValue; bool flag = true; for (int i = 0; i < xs.Count; i++) { float num5 = xs[i]; float num6 = ys[i]; if (!float.IsFinite(num5) || !float.IsFinite(num6)) { flag = false; continue; } num = Math.Min(num, num5); num3 = Math.Max(num3, num5); num2 = Math.Min(num2, num6); num4 = Math.Max(num4, num6); } if (!flag) { return new AnchorScreenRect(float.NaN, float.NaN, float.NaN, float.NaN, finite: false); } return new AnchorScreenRect(num, num2, num3 - num, num4 - num2, finite: true); } public static bool TryFromCorners(IReadOnlyList<float> xs, IReadOnlyList<float> ys, float screenWidth, float screenHeight, out LayoutRect rect, out AnchorScreenRect raw) { raw = Raw(xs, ys); return ScreenBounds.TryFromCorners(xs, ys, screenWidth, screenHeight, out rect); } } public enum AnchorElementSource { None, Flashlight, BackgroundFade } public static class AnchorElementNames { public const string Flashlight = "flashlight"; public const string BackgroundFade = "background-fade"; public const string BackgroundFadeObject = "Background Fade"; public const string FlashlightEnabledObject = "FlashLightIcon_:Enabled"; public const string FlashlightDisabledObject = "FlashLightIcon_Disabled"; } public static class AnchorSourceLadder { public static AnchorElementSource First(bool flashlightMeasured, bool backgroundMeasured) { if (!flashlightMeasured) { if (!backgroundMeasured) { return AnchorElementSource.None; } return AnchorElementSource.BackgroundFade; } return AnchorElementSource.Flashlight; } public static bool RestartsSettle(AnchorElementSource previous, AnchorElementSource current) { if (previous != current && previous != AnchorElementSource.None) { return current != AnchorElementSource.None; } return false; } public static string Name(AnchorElementSource source) { return source switch { AnchorElementSource.Flashlight => "flashlight", AnchorElementSource.BackgroundFade => "background-fade", _ => "config", }; } public static string GeometryName(AnchorElementSource source) { return source switch { AnchorElementSource.Flashlight => "the icon row's PUI_InventoryIconDisplay layout rectangle", AnchorElementSource.BackgroundFade => "the row's Background Fade SpriteRenderer geometry", _ => "the configured PositionX/PositionY", }; } } public static class AnchorElementMatch { public static bool IsBackgroundFade(string objectName) { return string.Equals(objectName, "Background Fade", StringComparison.Ordinal); } } public enum AnchorIconSprite { Enabled = 1, Disabled } public static class AnchorFlashlightIcon { public static AnchorIconSprite Drawn(bool enabledRendererOn, bool disabledRendererOn) { if (!enabledRendererOn && disabledRendererOn) { return AnchorIconSprite.Disabled; } return AnchorIconSprite.Enabled; } public static bool FallbackReachable(bool enabledRendererPresent) { return !enabledRendererPresent; } public static string Name(AnchorIconSprite sprite) { if (sprite != AnchorIconSprite.Disabled) { return "FlashLightIcon_:Enabled"; } return "FlashLightIcon_Disabled"; } } public readonly struct AnchorQuad { public readonly float MinX; public readonly float MinY; public readonly float MaxX; public readonly float MaxY; public bool Valid { get { if (float.IsFinite(MinX) && float.IsFinite(MinY) && float.IsFinite(MaxX) && float.IsFinite(MaxY) && MaxX > MinX) { return MaxY > MinY; } return false; } } public float Width => MaxX - MinX; public float Height => MaxY - MinY; public AnchorQuad(float minX, float minY, float maxX, float maxY) { MinX = minX; MinY = minY; MaxX = maxX; MaxY = maxY; } } public static class AnchorSpriteQuad { public static AnchorQuad FromSprite(float width, float height, float pivotX, float pivotY, bool flipX = false, bool flipY = false) { float num = Math.Abs(width); float num2 = Math.Abs(height); if (!float.IsFinite(num) || !float.IsFinite(num2) || num <= 0f || num2 <= 0f) { return default(AnchorQuad); } if (!float.IsFinite(pivotX)) { pivotX = 0.5f; } if (!float.IsFinite(pivotY)) { pivotY = 0.5f; } float num3 = (0f - pivotX) * num; float num4 = (1f - pivotX) * num; float num5 = (0f - pivotY) * num2; float num6 = (1f - pivotY) * num2; if (flipX) { float num7 = num3; num3 = 0f - num4; num4 = 0f - num7; } if (flipY) { float num8 = num5; num5 = 0f - num6; num6 = 0f - num8; } return new AnchorQuad(num3, num5, num4, num6); } } public static class AnchorElementCanvasPolicy { public enum CameraOrigin { None, Overlay, ElementCanvas, ElementCanvasRefused, ManualCanvas, ManualCanvasRefused } public static AnchorCanvasMode Mode(bool ancestorCanvasPresent, AnchorCanvasMode ancestorMode, AnchorCanvasMode fallbackMode) { if (!ancestorCanvasPresent) { return fallbackMode; } return ancestorMode; } public static CameraOrigin Project(bool elementCanvasPresent, AnchorCanvasMode elementMode, bool canvasCameraPresent, bool canvasCameraAlive, bool canvasCameraWindow) { return Project(elementCanvasPresent, elementMode, canvasCameraPresent, canvasCameraAlive, canvasCameraWindow, AnchorManualCanvasFacts.None); } public static CameraOrigin Project(bool elementCanvasPresent, AnchorCanvasMode elementMode, bool canvasCameraPresent, bool canvasCameraAlive, bool canvasCameraWindow, AnchorManualCanvasFacts manual) { if (elementCanvasPresent) { switch (elementMode) { case AnchorCanvasMode.Overlay: return CameraOrigin.Overlay; case AnchorCanvasMode.ScreenSpaceCamera: if (!canvasCameraPresent) { return CameraOrigin.None; } if (!(canvasCameraAlive && canvasCameraWindow)) { return CameraOrigin.ElementCanvasRefused; } return CameraOrigin.ElementCanvas; default: return CameraOrigin.None; } } if (manual.CanvasPresent) { if (!manual.Verified) { return CameraOrigin.ManualCanvasRefused; } return CameraOrigin.ManualCanvas; } return CameraOrigin.None; } public static bool PassesCamera(CameraOrigin origin) { if (origin != CameraOrigin.ElementCanvas) { return origin == CameraOrigin.ManualCanvas; } return true; } public static string Name(CameraOrigin origin) { return origin switch { CameraOrigin.Overlay => "the element's canvas is a screen-space overlay canvas, which is composited without a camera", CameraOrigin.ElementCanvas => "the element's own canvas worldCamera", CameraOrigin.ElementCanvasRefused => "the element's own canvas worldCamera (not a live window camera)", CameraOrigin.ManualCanvas => "the HUD's own manual canvas (GuiLayerBase.m_cellUICanvas.m_UICamera, rendering into a render texture of the window's size)", CameraOrigin.ManualCanvasRefused => "the HUD's own manual canvas, whose camera could not be shown to answer in window pixels", CameraOrigin.None => "none", _ => "none", }; } public static string SourceName(bool ancestorCanvasPresent) { if (!ancestorCanvasPresent) { return "layer-property"; } return "element-canvas"; } public static bool CanProject(CameraOrigin origin) { if (origin != CameraOrigin.Overlay && origin != CameraOrigin.ElementCanvas) { return origin == CameraOrigin.ManualCanvas; } return true; } public static bool ManualAuthorized(bool elementCanvasPresent, AnchorManualCanvasFacts manual) { if (!elementCanvasPresent) { return manual.Verified; } return false; } } public static class BandCameraLiveness { public static bool Alive(bool proved, bool manualCanvasProved, bool enabledAndActive, bool activeInHierarchy, bool readable) { if (!readable) { return false; } if (enabledAndActive) { return true; } return proved && manualCanvasProved && activeInHierarchy; } } public enum AnchorSampleFailure { None, NoCamera, NoIcon, Unmeasurable, NoProjection } public readonly struct AnchorSample { public readonly LayoutRect Rect; public readonly AnchorSampleFailure Failure; public readonly string Error; public readonly AnchorElementSource Source; public bool Measured { get { if (Failure == AnchorSampleFailure.None && Rect.Width > 0f) { return Rect.Height > 0f; } return false; } } public AnchorSample(LayoutRect rect, AnchorSampleFailure failure, string error = null, AnchorElementSource source = AnchorElementSource.None) { Rect = rect; Failure = failure; Error = error; Source = source; } public static AnchorSample Of(LayoutRect rect, AnchorElementSource source = AnchorElementSource.None) { return new AnchorSample(rect, AnchorSampleFailure.None, null, source); } public static AnchorSample Missing(AnchorSampleFailure failure) { return new AnchorSample(default(LayoutRect), failure); } public static AnchorSample Thrown(string error) { return new AnchorSample(default(LayoutRect), AnchorSampleFailure.Unmeasurable, error); } } public sealed class AnchorSamplePolicy { public const int Budget = 12; public const float SettleInterval = 0.25f; public const float FirstRetryDelay = 0.5f; public const float MaximumRetryDelay = 4f; public const float WatchInterval = 2f; private float _nextWatch; private const int MaximumDoublings = 8; private float _nextAttempt; private bool _attempted; private AnchorSampleFailure _lastPrintedFailure; public int Watches { get; private set; } public int Attempts { get; private set; } public int Failures { get; private set; } public bool Abandoned { get; private set; } public AnchorSampleFailure LastFailure { get; private set; } public float Waited { get; private set; } public int Lines { get; private set; } public bool DueToReport { get { if (!Abandoned) { return Attempts > Lines; } return false; } } public bool FreshWarning { get { if (!Abandoned && Attempts > 0) { return LastFailure != _lastPrintedFailure; } return false; } } public static float DelayAfter(int failures) { if (failures <= 0) { return 0.25f; } int num = failures - 1; if (num > 8) { num = 8; } float num2 = 0.5f * (float)Math.Pow(2.0, num); if (!float.IsFinite(num2)) { return 4f; } if (!(num2 < 4f)) { return 4f; } return num2; } public bool Due(float now) { if (Abandoned) { return WatchDue(now); } if (!_attempted) { return true; } if (!float.IsFinite(now)) { return false; } return now >= _nextAttempt; } public bool WatchDue(float now) { if (!Abandoned) { return false; } if (!float.IsFinite(now)) { return false; } if (now < _nextWatch) { return false; } _nextWatch = now + 2f; return true; } public void Reported() { if (!Abandoned) { if (Attempts > Lines) { Lines = Attempts; } _lastPrintedFailure = LastFailure; } } public void Began(float now) { if (!Abandoned) { Attempts++; _attempted = true; if (float.IsFinite(now) && float.IsFinite(_nextAttempt) && now > _nextAttempt) { _nextAttempt = now; } } } public AnchorSample Attempt(float now, Func<AnchorSample> sample, out bool gaveUp) { gaveUp = false; bool abandoned = Abandoned; if (abandoned) { Started(now); } else { Began(now); } AnchorSample result; try { result = sample?.Invoke() ?? AnchorSample.Missing(AnchorSampleFailure.Unmeasurable); } catch (Exception ex) { result = AnchorSample.Thrown(ex?.Message); } if (result.Measured) { if (abandoned) { Restart(); } Measured(now); return result; } if (abandoned) { Watches++; return result; } AnchorSampleFailure anchorSampleFailure = ((result.Failure == AnchorSampleFailure.None) ? AnchorSampleFailure.Unmeasurable : result.Failure); gaveUp = Failed(now, anchorSampleFailure); return new AnchorSample(result.Rect, anchorSampleFailure, result.Error, result.Source); } private void Started(float now) { _nextWatch = (float.IsFinite(now) ? (now + 2f) : float.PositiveInfinity); } public void Measured(float now) { Failures = 0; LastFailure = AnchorSampleFailure.None; _nextAttempt = (float.IsFinite(now) ? (now + 0.25f) : float.PositiveInfinity); } public bool Failed(float now, AnchorSampleFailure reason) { if (Abandoned) { return true; } Failures++; LastFailure = ((reason == AnchorSampleFailure.None) ? AnchorSampleFailure.Unmeasurable : reason); float num = DelayAfter(Failures); if (Failures < 12) { Waited += num; } _nextAttempt = (float.IsFinite(now) ? (now + num) : float.PositiveInfinity); if (Failures < 12) { return false; } Abandoned = true; _nextWatch = (float.IsFinite(now) ? (now + 2f) : float.PositiveInfinity); return true; } public void Restart() { Attempts = 0; Failures = 0; Abandoned = false; LastFailure = AnchorSampleFailure.None; Waited = 0f; Lines = 0; _lastPrintedFailure = AnchorSampleFailure.None; _nextAttempt = 0f; _attempted = false; _nextWatch = 0f; } public static string Describe(AnchorSampleFailure reason) { return reason switch { AnchorSampleFailure.NoCamera => "the HUD's own camera answered null", AnchorSampleFailure.NoProjection => "no camera that draws the icon could be shown to exist, and the element carries no RectTransform on a screen-space canvas from which its own rectangle could be computed either (its layer, its RectTransform, the canvas render mode and every candidate camera's culling mask were all read)", AnchorSampleFailure.NoIcon => "the flashlight icon had no renderer", AnchorSampleFailure.Unmeasurable => "the icon's bounds projected off screen (or could not be read), and the rectangle its own canvas laid out could not be projected into a usable window rectangle either - no camera to project it with, a projection that answered no usable rectangle, or a rectangle the window does not cover", _ => "no attempt was made", }; } } public sealed class AnchorSourceTracker { public AnchorElementSource Source { get; private set; } public bool Observe(AnchorElementSource source) { bool result = AnchorSourceLadder.RestartsSettle(Source, source); Source = source; return result; } public void Restart() { Source = AnchorElementSource.None; } } public enum AnchorLookupOutcome { None, Found, Missing, Unreadable } public sealed class AnchorElementLookup { public const int MissWalks = 12; public const int RetryFrames = 30; public const int WatchFrames = 60; private object _owner; private int _walks; private int _lastWalkFrame = int.MinValue; public AnchorLookupOutcome Outcome { get; private set; } public bool Hit => Outcome == AnchorLookupOutcome.Found; public bool Missing => Outcome == AnchorLookupOutcome.Missing; public bool Unreadable => Outcome == AnchorLookupOutcome.Unreadable; public int Walks => _walks; public bool MissRetired { get { if (Outcome == AnchorLookupOutcome.Missing) { return _walks >= 12; } return false; } } public bool Due(object owner) { return Due(owner, int.MinValue); } public bool Due(object owner, int frame) { if (owner != _owner) { return Started(owner, frame, newOwner: true); } switch (Outcome) { case AnchorLookupOutcome.Found: return false; case AnchorLookupOutcome.Missing: if (frame == int.MinValue) { if (_walks >= 12) { return false; } return Started(owner, frame, newOwner: false); } if (_lastWalkFrame != int.MinValue) { if (frame < _lastWalkFrame) { return Started(owner, frame, newOwner: false); } int num = ((_walks < 12) ? 30 : 60); if (frame - _lastWalkFrame < num) { return false; } } return Started(owner, frame, newOwner: false); default: return Started(owner, frame, newOwner: false); } } private bool Started(object owner, int frame, bool newOwner) { if (newOwner) { _walks = 0; _lastWalkFrame = int.MinValue; } _owner = owner; if (_walks < int.MaxValue) { _walks++; } if (frame != int.MinValue) { _lastWalkFrame = frame; } return true; } public void Record(object owner, bool found, bool walked) { if (owner != _owner) { _owner = owner; _walks = 0; } _owner = owner; if (!walked) { Outcome = AnchorLookupOutcome.Unreadable; } else if (found) { Outcome = AnchorLookupOutcome.Found; _walks = 0; } else { Outcome = AnchorLookupOutcome.Missing; } } public void Forget() { _owner = null; Outcome = AnchorLookupOutcome.None; _walks = 0; _lastWalkFrame = int.MinValue; } public string Describe() { switch (Outcome) { case AnchorLookupOutcome.Found: return "yes(found)"; case AnchorLookupOutcome.Missing: if (!MissRetired) { return "yes(missing,still-looking)"; } return "yes(missing,slow-watch)"; case AnchorLookupOutcome.Unreadable: return "yes(unreadable)"; default: return "no(not-looked-for)"; } } } public sealed class BlinkCompletionLedger { private sealed class Entry { public bool Name; public bool Done; public bool Scheduled; public bool Ended; public bool Excluded; public long Routine; } private readonly Dictionary<long, Entry> _targets = new Dictionary<long, Entry>(); private bool _missing; public int Names => _targets.Values.Count((Entry e) => e.Name && Counted(e)); public int Artwork => _targets.Values.Count((Entry e) => !e.Name && Counted(e)); public int Completed => _targets.Values.Count((Entry e) => e.Done && Counted(e)); public int Count => _targets.Values.Count(Counted); public int Required => _targets.Count; public int Unscheduled => _targets.Values.Count((Entry e) => e.Excluded); public int Aborted => _targets.Values.Count((Entry e) => e.Ended && !e.Done); public bool NamesReady { get { if (!RevealImpossible) { return All(name: true); } return false; } } public bool ArtworkReady { get { if (!RevealImpossible && Artwork > 0) { return All(name: false); } return false; } } public bool Ready { get { if (NamesReady) { return ArtworkReady; } return false; } } public bool RevealImpossible { get { if (!_missing) { return Aborted > 0; } return true; } } public bool MayStillComplete => !RevealImpossible; public int InFlight => _targets.Values.Count((Entry e) => Counted(e) && e.Scheduled && !e.Done && !e.Ended); public bool Settled => InFlight == 0; private static bool Counted(Entry entry) { return !entry.Excluded; } private bool All(bool name) { return _targets.Values.Where((Entry e) => e.Name == name && Counted(e)).All((Entry e) => e.Done); } public void Require(long target, bool name) { if (target == 0L || (_targets.Count >= 64 && !_targets.ContainsKey(target))) { _missing = true; return; } if (!_targets.TryGetValue(target, out var value)) { value = (_targets[target] = new Entry()); } value.Name |= name; } public int CloseSchedule(IEnumerable<long> required) { if (required == null) { return 0; } int num = 0; foreach (long item in required) { if (_targets.TryGetValue(item, out var value) && !value.Scheduled && !value.Excluded) { value.Excluded = true; num++; } } return num; } public bool IsScheduled(long target) { if (target == 0L) { return false; } if (_missing) { return true; } return _targets.ContainsKey(target); } public void Start(long target, long routine) { if (routine != 0L && _targets.TryGetValue(target, out var value)) { value.Routine = routine; value.Done = false; value.Ended = false; value.Scheduled = true; value.Excluded = false; } } public void Finish(long target, long routine, bool naturallyRevealed) { if (routine != 0L && _targets.TryGetValue(target, out var value) && value.Routine == routine) { value.Done = naturallyRevealed; value.Ended = !naturallyRevealed; } } public bool FinishRoutine(long routine, bool naturallyRevealed) { if (routine == 0L) { return false; } foreach (Entry value in _targets.Values) { if (value.Routine == routine) { value.Done = naturallyRevealed; value.Ended = !naturallyRevealed; return true; } } return false; } public void Clear() { _targets.Clear(); _missing = false; } } public static class CombatMerge { private static bool LocalExact(bool observed, bool estimated) { if (observed) { return !estimated; } return false; } public static bool HostSuppliesDamage(bool hostObserved) { return hostObserved; } public static bool HostSuppliesAccuracy(bool localObserved, bool localEstimated, bool hostObserved, bool hostEstimated) { if (LocalExact(localObserved, localEstimated)) { return false; } return hostObserved || hostEstimated; } public static long MergeCount(long local, long host) { if (host == 0L) { return local; } return host; } public static bool KillGroupReported(in SyncSnapshot snap) { return AnyFigure(snap.KillMinor, snap.KillElite, snap.KillBoss, snap.SleepingMinorKills, snap.SleepingEliteKills, snap.SleepingBossKills, snap.UnknownStateMinorKills, snap.UnknownStateEliteKills, snap.UnknownStateBossKills); } public static bool AnyFigure(params long[] figures) { if (figures == null) { return false; } for (int i = 0; i < figures.Length; i++) { if (figures[i] != 0L) { return true; } } return false; } public static double MergeAmount(double local, bool localObserved, double host, bool hostObserved) { if (hostObserved && double.IsFinite(host)) { return host; } if (!double.IsFinite(local)) { return 0.0; } return local; } public static CombatPlayer Project(CombatPlayer local) { return local?.Clone(); } public static void ApplyRemote(CombatPlayer display, in SyncSnapshot snap, int primarySlot, int specialSlot, int classSlot, int meleeSlot, ulong localLookup) { if (display == null) { return; } bool flag = snap.Owner == localLookup; PlayerCombatStats total = display.Total; if (AcceptsDamage(total.EnemyDamageObserved, total.EnemyDamageEstimated, snap.Has(SyncFlags.EnemyDamageObserved), snap.Has(SyncFlags.EnemyDamageEstimated))) { total.RestoreEnemyDamage(snap.EnemyDamage, snap.Has(SyncFlags.EnemyDamageObserved), snap.Has(SyncFlags.EnemyDamageEstimated)); } if (AcceptsDamage(total.FriendlyFireObserved, total.FriendlyFireEstimated, snap.Has(SyncFlags.FriendlyFireObserved), snap.Has(SyncFlags.FriendlyFireEstimated))) { total.RestoreFriendlyFireDamage(snap.FriendlyFire, snap.Has(SyncFlags.FriendlyFireObserved), snap.Has(SyncFlags.FriendlyFireEstimated)); } if (!flag) { MergeAccuracy(total, snap.Shots, snap.Hits, snap.WeakHits, snap.Has(SyncFlags.AccuracyObserved), snap.Has(SyncFlags.AccuracyEstimated)); } display.StatisticsAvailable = display.StatisticsAvailable || snap.Has(SyncFlags.StatisticsAvailable); if (!flag) { display.SupportRole = display.SupportRole || snap.Has(SyncFlags.SupportRole); } ImpactCounters impact = display.Impact; if (KillGroupReported(in snap)) { impact.MinorKills = snap.KillMinor; impact.EliteKills = snap.KillElite; impact.BossKills = snap.KillBoss; impact.SleepingMinorKills = snap.SleepingMinorKills; impact.SleepingEliteKills = snap.SleepingEliteKills; impact.SleepingBossKills = snap.SleepingBossKills; impact.UnknownStateMinorKills = snap.UnknownStateMinorKills; impact.UnknownStateEliteKills = snap.UnknownStateEliteKills; impact.UnknownStateBossKills = snap.UnknownStateBossKills; } if (snap.Has(SyncFlags.MeleeKillsObserved) || AnyFigure(snap.KillMelee, snap.SleepingMeleeKills, snap.UnknownStateMeleeKills)) { impact.MeleeKills = snap.KillMelee; impact.MeleeKillsObserved = impact.MeleeKillsObserved || snap.Has(SyncFlags.MeleeKillsObserved); impact.SleepingMeleeKills = snap.SleepingMeleeKills; impact.UnknownStateMeleeKills = snap.UnknownStateMeleeKills; } if (snap.Has(SyncFlags.ScoutKillsObserved) || AnyFigure(snap.KillScout, snap.SleepingScoutKills, snap.UnknownStateScoutKills)) { impact.ScoutKills = snap.KillScout; impact.ScoutKillsObserved = impact.ScoutKillsObserved || snap.Has(SyncFlags.ScoutKillsObserved); impact.SleepingScoutKills = snap.SleepingScoutKills; impact.UnknownStateScoutKills = snap.UnknownStateScoutKills; } if (snap.Has2(SyncFlags2.ScoutDamageObserved)) { impact.ScoutDamage = ((double.IsFinite(snap.ScoutEnemyDamage) && snap.ScoutEnemyDamage > 0f) ? snap.ScoutEnemyDamage : 0f); impact.ScoutDamageObserved = true; impact.ScoutDamageEstimated = snap.Has2(SyncFlags2.ScoutDamageEstimated); } impact.Stagger = MergeCount(impact.Stagger, snap.Stagger); impact.Revives = MergeCount(impact.Revives, snap.Revives); long num = MergeCount(impact.Downs, snap.Downs); impact.Downs = (int)((num > int.MaxValue) ? int.MaxValue : num); long num2 = MergeCount(impact.LoneSurvivor, snap.LoneSurvivor); impact.LoneSurvivor = (int)((num2 > int.MaxValue) ? int.MaxValue : num2); long num3 = MergeCount(impact.FriendlyFireDeaths, snap.FriendlyFireDeaths); impact.FriendlyFireDeaths = (int)((num3 > int.MaxValue) ? int.MaxValue : num3); impact.SentryShots = MergeCount(impact.SentryShots, snap.SentryShots); impact.SentryHits = MergeCount(impact.SentryHits, snap.SentryHits); impact.SentryDamage = ((float.IsFinite(snap.SentryDamage) && snap.SentryDamage > 0f) ? ((double)snap.SentryDamage) : impact.SentryDamage); impact.MineDeployments = MergeCount(impact.MineDeployments, snap.MineDeployments); impact.MinePickups = MergeCount(impact.MinePickups, snap.MinePickups); impact.MineTriggers = MergeCount(impact.MineTriggers, snap.MineTriggers); impact.MineDamage = ((float.IsFinite(snap.MineDamage) && snap.MineDamage > 0f) ? ((double)snap.MineDamage) : impact.MineDamage); if (!flag && snap.GlueShots != 0) { impact.GlueShots = snap.GlueShots; impact.GlueHits = snap.GlueHits; impact.GluedEnemies = snap.GluedEnemies; } if (!flag && !impact.ScanUsesKnown) { impact.ScanUses = MergeCount(impact.ScanUses, snap.ScanUses); impact.ScanFirstMarks = MergeCount(impact.ScanFirstMarks, snap.ScanFirstMarks); impact.ScanMarks = MergeCount(impact.ScanMarks, snap.ScanMarks); } if (!flag && snap.SupplyUses != 0) { impact.SupplyUses = snap.SupplyUses; impact.SupplyEfficiencySum = snap.SupplyEfficiencySum; } impact.ScanEstimated |= snap.Has(SyncFlags.ScanEstimated); if (!flag && snap.SelfSupplyUses != 0) { if (impact.SelfSupplyKindsKnown && (snap.SelfSupplyUses != impact.SelfSupplyUses || snap.SelfAmmoUses != impact.SelfAmmoUses)) { impact.SelfToolUses = 0L; impact.SelfMedicalUses = 0L; impact.SelfSupplyKindsKnown = false; impact.SelfMedicalKnown = false; } impact.SelfSupplyUses = snap.SelfSupplyUses; impact.SelfAmmoUses = snap.SelfAmmoUses; } if (flag) { if (impact.HealthLost <= 0.0 && snap.HealthLost > 0f && float.IsFinite(snap.HealthLost)) { impact.HealthLost = snap.HealthLost; } } else if (snap.HealthLost > 0f && float.IsFinite(snap.HealthLost)) { impact.HealthLost = snap.HealthLost; } MergeWeapon(display, in snap, flag, primarySlot, SyncFlags.PrimaryPresent, SyncFlags.PrimaryAccuracyObserved, SyncFlags.PrimaryAccuracyEstimated, SyncFlags.PrimaryDamageObserved, SyncFlags.PrimaryDamageEstimated, SyncFlags.PrimaryFriendlyFireObserved, SyncFlags.PrimaryFriendlyFireEstimated, snap.PrimaryArchetypeId, snap.PrimaryGearCategory, snap.GetPrimaryName(), snap.PrimaryShots, snap.PrimaryHits, snap.PrimaryWeakHits, snap.PrimaryEnemyDamage, snap.PrimaryFriendlyFire); MergeWeapon(display, in snap, flag, specialSlot, SyncFlags.SpecialPresent, SyncFlags.SpecialAccuracyObserved, SyncFlags.SpecialAccuracyEstimated, SyncFlags.SpecialDamageObserved, SyncFlags.SpecialDamageEstimated, SyncFlags.SpecialFriendlyFireObserved, SyncFlags.SpecialFriendlyFireEstimated, snap.SpecialArchetypeId, snap.SpecialGearCategory, snap.GetSpecialName(), snap.SpecialShots, snap.SpecialHits, snap.SpecialWeakHits, snap.SpecialEnemyDamage, snap.SpecialFriendlyFire); if (snap.Has(SyncFlags.ClassPresent)) { display.Weapon(classSlot, snap.ClassArchetypeId, snap.GetClassName(), 0u, authoritative: true); } if (snap.Has(SyncFlags.MeleePresent)) { WeaponCombatStats weaponCombatStats = display.Weapon(meleeSlot, snap.MeleeArchetypeId, snap.GetMeleeName(), 0u, authoritative: true); if (AcceptsDamage(weaponCombatStats.Counters.EnemyDamageObserved, weaponCombatStats.Counters.EnemyDamageEstimated, snap.Has(SyncFlags.MeleeDamageObserved), snap.Has(SyncFlags.MeleeDamageEstimated))) { weaponCombatStats.Counters.RestoreEnemyDamage(snap.MeleeEnemyDamage, snap.Has(SyncFlags.MeleeDamageObserved), snap.Has(SyncFlags.MeleeDamageEstimated)); } } } private static void MergeAccuracy(PlayerCombatStats target, long hostShots, long hostHits, long hostWeak, bool hostObserved, bool hostEstimated) { if (target != null && HostSuppliesAccuracy(target.AccuracyObserved, target.AccuracyEstimated, hostObserved, hostEstimated)) { target.RestoreAccuracy(hostShots, hostHits, hostWeak, hostObserved, hostEstimated); } } private static void MergeWeapon(CombatPlayer display, in SyncSnapshot snap, bool own, int slot, SyncFlags present, SyncFlags accuracyObserved, SyncFlags accuracyEstimated, SyncFlags damageObserved, SyncFlags damageEstimated, SyncFlags friendlyObserved, SyncFlags friendlyEstimated, uint archetypeId, uint gearCategoryId, string name, long shots, long hits, long weak, double damage, double friendly) { if (!snap.Has(present)) { return; } WeaponCombatStats weaponCombatStats = display.Weapon(slot, archetypeId, name, gearCategoryId, authoritative: true); if (weaponCombatStats != null) { PlayerCombatStats counters = weaponCombatStats.Counters; if (AcceptsDamage(counters.EnemyDamageObserved, counters.EnemyDamageEstimated, snap.Has(damageObserved), snap.Has(damageEstimated))) { counters.RestoreEnemyDamage(damage, snap.Has(damageObserved), snap.Has(damageEstimated)); } if (AcceptsDamage(counters.FriendlyFireObserved, counters.FriendlyFireEstimated, snap.Has(friendlyObserved), snap.Has(friendlyEstimated))) { counters.RestoreFriendlyFireDamage(friendly, snap.Has(friendlyObserved), snap.Has(friendlyEstimated)); } if (!own) { MergeAccuracy(counters, shots, hits, weak, snap.Has(accuracyObserved), snap.Has(accuracyEstimated)); } } } private static bool AcceptsDamage(bool localPresent, bool localEstimated, bool incomingPresent, bool incomingEstimated) { return Exactness(incomingPresent, incomingEstimated) > Exactness(localPresent, localEstimated); } public static int Exactness(bool present, bool estimated) { if (present) { if (!estimated) { return 2; } return 1; } return 0; } public static SyncSnapshot PreferClientOwned(in SyncSnapshot hostRow, in SyncSnapshot clientRow) { SyncSnapshot result = hostRow; if (clientRow.Has(SyncFlags.AccuracyObserved)) { result.Shots = clientRow.Shots; result.Hits = clientRow.Hits; result.WeakHits = clientRow.WeakHits; result.Set(SyncFlags.AccuracyObserved, on: true); result.Set(SyncFlags.AccuracyEstimated, clientRow.Has(SyncFlags.AccuracyEstimated)); } if (clientRow.ScanUses != 0 || clientRow.ScanFirstMarks != 0 || clientRow.ScanMarks != 0) { result.ScanUses = clientRow.ScanUses; result.ScanFirstMarks = clientRow.ScanFirstMarks; result.ScanMarks = clientRow.ScanMarks; result.Set(SyncFlags.ScanEstimated, clientRow.Has(SyncFlags.ScanEstimated)); } if (clientRow.SupplyUses != 0) { result.SupplyUses = clientRow.SupplyUses; result.SupplyEfficiencySum = clientRow.SupplyEfficiencySum; } if (clientRow.SelfSupplyUses != 0) { result.SelfSupplyUses = clientRow.SelfSupplyUses; result.SelfAmmoUses = clientRow.SelfAmmoUses; } return result; } } public sealed class SnapshotCache { private struct Row { public SyncSnapshot HostSnapshot; public SyncSnapshot PeerSnapshot; public SyncSnapshot Snapshot; public uint HostGeneration; public uint PeerGeneration; public bool HasHost; public bool HasPeer; } private struct SupplyKindsRow { public SyncProtocol.SupplyKinds Block; public uint Generation; public bool Has; public bool FromOwner; public bool HostSlot; } private readonly Dictionary<ulong, Row> _rows = new Dictionary<ulong, Row>(); private double _squadTotal; private uint _squadGeneration; private bool _squadPartial; private bool _hasSquadTotal; private readonly Dictionary<ulong, SupplyKindsRow> _kinds = new Dictionary<ulong, SupplyKindsRow>(); public int Count => _rows.Count; public IEnumerable<ulong> Owners { get { foreach (ulong key in _rows.Keys) { yield return key; } } } public bool Has(ulong owner) { if (owner != 0L) { return _rows.ContainsKey(owner); } return false; } public bool Store(ulong owner, uint generation, in SyncSnapshot snapshot, bool fromHost, bool recovered) { if (owner == 0L) { return false; } SyncSnapshot snapshot2 = snapshot; if (_rows.TryGetValue(owner, out var value)) { uint current = (fromHost ? value.HostGeneration : value.PeerGeneration); bool flag = (fromHost ? value.HasHost : value.HasPeer); if (flag && !recovered && !SyncProtocol.IsNewerOrSame(generation, current)) { return false; } if (flag && recovered) { value = default(Row); } if (fromHost) { value.HostSnapshot = snapshot2; value.HostGeneration = generation; value.HasHost = true; } else { value.PeerSnapshot = snapshot2; value.PeerGeneration = generation; value.HasPeer = true; } value.Snapshot = Compose(in value); _rows[owner] = value; ObserveSquadTotal(in snapshot2, generation, fromHost, recovered); return true; } Row row = default(Row); if (fromHost) { row.HostSnapshot = snapshot2; row.HostGeneration = generation; row.HasHost = true; } else { row.PeerSnapshot = snapshot2; row.PeerGeneration = generation; row.HasPeer = true; } row.Snapshot = Compose(in row); _rows[owner] = row; ObserveSquadTotal(in snapshot2, generation, fromHost, recovered); return true; } private static SyncSnapshot Compose(in Row row) { if (row.HasHost && row.HasPeer) { return SyncProtocol.Combine(in row.HostSnapshot, existingIsHost: true, in row.PeerSnapshot, incomingIsHost: false); } if (!row.HasHost) { return row.PeerSnapshot; } return row.HostSnapshot; } public bool TryGet(ulong owner, out SyncSnapshot snapshot) { if (_rows.TryGetValue(owner, out var value)) { snapshot = value.Snapshot; return true; } snapshot = default(SyncSnapshot); return false; } public bool TryGetSquadTotal(out double total) { bool partial; return TryGetSquadTotal(out total, out partial); } public bool TryGetSquadTotal(out double total, out bool partial) { total = _squadTotal; partial = _squadPartial; return _hasSquadTotal; } private void ObserveSquadTotal(in SyncSnapshot snapshot, uint generation, bool fromHost, bool recovered) { if (fromHost && snapshot.Has(SyncFlags.SquadDamageKnown) && (!_hasSquadTotal || recovered || SyncProtocol.IsNewerOrSame(generation, _squadGeneration))) { _squadTotal = snapshot.SquadEnemyDamage; _squadPartial = snapshot.Has(SyncFlags.SquadDamagePartial); _squadGeneration = generation; _hasSquadTotal = true; } } public bool StoreSupplyKinds(ulong owner, uint generation, in SyncProtocol.SupplyKinds kinds, bool recovered, bool fromOwner = true, bool senderIsHost = false) { if (owner == 0L || !kinds.IsUsable) { return false; } if (_kinds.TryGetValue(owner, out var value) && value.Has) { if (fromOwner && !value.FromOwner) { _kinds[owner] = new SupplyKindsRow { Block = kinds, Generation = generation, Has = true, FromOwner = true, HostSlot = senderIsHost }; return true; } if (value.FromOwner && !fromOwner) { return false; } if (!recovered && !SyncProtocol.IsNewerOrSame(generation, value.Generation)) { return false; } } _kinds[owner] = new SupplyKindsRow { Block = kinds, Generation = generation, Has = true, FromOwner = fromOwner, HostSlot = senderIsHost }; return true; } public bool TryGetSupplyKinds(ulong owner, out SyncProtocol.SupplyKinds kinds) { if (owner != 0L && _kinds.TryGetValue(owner, out var value)) { kinds = value.Block; return true; } kinds = default(SyncProtocol.SupplyKinds); return false; } public bool TryApplySupplyKinds(ulong owner, ImpactCounters impact, bool own) { if (owner == 0L || impact == null) { return false; } if (!_kinds.TryGetValue(owner, out var value) || !value.Has) { return false; } if (!_rows.TryGetValue(owner, out var value2)) { return false; } if (TryApplyToSlot(in value2, in value, value.HostSlot, impact, own)) { return true; } return TryApplyToSlot(in value2, in value, !value.HostSlot, impact, own); } private static bool TryApplyToSlot(in Row row, in SupplyKindsRow kinds, bool hostSlot, ImpactCounters impact, bool own) { uint num = (hostSlot ? row.HostGeneration : row.PeerGeneration); if (!(hostSlot ? row.HasHost : row.HasPeer) || num != kinds.Generation) { return false; } return SyncProtocol.ApplySupplyKinds(impact, in kinds.Block, own); } public void Remove(ulong owner) { if (owner != 0L) { _rows.Remove(owner); _kinds.Remove(owner); } } public void Clear() { _rows.Clear(); _kinds.Clear(); _hasSquadTotal = false; _squadTotal = 0.0; _squadPartial = false; _squadGeneration = 0u; } } public enum PanelColumn { PlayerName, DamageAndShare, FriendlyFire, Accuracy, WeakspotAccuracy, Projectiles, ImpactLabel, ImpactValue } public enum PanelTextRole { Neutral, PlayerName } public sealed class ShotSample { private readonly Dictionary<int, bool> _hits = new Dictionary<int, bool>(); private int _pellet = -1; public bool Blind; public int Fired { get; private set; } public int Hits => _hits.Count; public int WeakspotHits { get { int num = 0; foreach (bool value in _hits.Values) { if (value) { num++; } } return num; } } public void BeginPellet() { _pellet = Fired++; } public void Contact(bool weakspot) { if (_pellet >= 0) { _hits.TryGetValue(_pellet, out var value); _hits[_pellet] = value || weakspot; } } } public sealed class PlayerCombatStats { public long ShotsFired { get; private set; } public long Hits { get; private set; } public long WeakspotHits { get; private set; } public double EnemyDamage { get; private set; } public double FriendlyFireDamage { get; private set; } public bool AccuracyObserved { get; private set; } public bool AccuracyEstimated { get; private set; } public bool EnemyDamageObserved { get; private set; } public bool FriendlyFireObserved { get; private set; } public bool EnemyDamageEstimated { get; private set; } public bool SquadDamageEstimated { get; set; } public bool FriendlyFireEstimated { get; private set; } public void AddAccuracy(long fired, long hits, long weak, bool estimated = false) { if (fired < 0 || hits < 0 || weak < 0 || weak > hits) { throw new ArgumentOutOfRangeException("fired"); } if (!estimated && hits > fired) { throw new ArgumentOutOfRangeException("hits"); } ShotsFired = Add(ShotsFired, fired); Hits = Add(Hits, hits); WeakspotHits = Add(WeakspotHits, weak); AccuracyObserved = true; AccuracyEstimated |= estimated; } public void AdjustAccuracy(long fired, long hits, long weak, bool estimated = false) { ShotsFired = Adjust(ShotsFired, fired); Hits = Adjust(Hits, hits); WeakspotHits = Math.Min(Adjust(WeakspotHits, weak), Hits); AccuracyObserved = true; AccuracyEstimated |= estimated; } public void RestoreAccuracy(long fired, long hits, long weak, bool observed, bool estimated) { ShotsFired = ((fired < 0) ? 0 : fired); Hits = ((hits < 0) ? 0 : ((hits > ShotsFired) ? ShotsFired : hits)); WeakspotHits = ((weak < 0) ? 0 : ((weak > Hits) ? Hits : weak)); AccuracyObserved = observed; AccuracyEstimated = estimated; } public void RestoreEnemyDamage(double amount, bool observed, bool estimated) { EnemyDamage = ((double.IsFinite(amount) && amount > 0.0) ? amount : 0.0); EnemyDamageObserved = observed; EnemyDamageEstimated = estimated; } public void RestoreFriendlyFireDamage(double amount, bool observed, bool estimated) { FriendlyFireDamage = ((double.IsFinite(amount) && amount > 0.0) ? amount : 0.0); FriendlyFireObserved = observed; FriendlyFireEstimated = estimated; } public void AddEnemyDamage(double amount, bool estimated = false) { if (double.IsFinite(amount) && !(amount < 0.0)) { EnemyDamageObserved = true; EnemyDamageEstimated |= estimated; EnemyDamage = AddDamage(EnemyDamage, amount); } } public void WithdrawEnemyDamage(double amount) { if (double.IsFinite(amount) && !(amount <= 0.0) && EnemyDamage > 0.0) { EnemyDamage = Math.Max(0.0, EnemyDamage - amount); } } public void AddFriendlyFireDamage(double amount, bool estimated = false) { if (double.IsFinite(amount) && !(amount < 0.0)) { FriendlyFireObserved = true; FriendlyFireEstimated |= estimated; FriendlyFireDamage = AddDamage(FriendlyFireDamage, amount); } } private static long Add(long value, long increment) { if (value <= long.MaxValue - increment) { return value + increment; } return long.MaxValue; } private static long Adjust(long value, long delta) { if (delta >= 0) { return Add(value, delta); } if (delta == long.MinValue) { return 0L; } return Math.Max(0L, value + delta); } private static double AddDamage(double value, double amount) { return Math.Min(double.MaxValue, value + amount); } public void CopyFrom(PlayerCombatStats other) { if (other != null) { RestoreAccuracy(other.ShotsFired, other.Hits, other.WeakspotHits, other.AccuracyObserved, other.AccuracyEstimated); RestoreEnemyDamage(other.EnemyDamage, other.EnemyDamageObserved, other.EnemyDamageEstimated); RestoreFriendlyFireDamage(other.FriendlyFireDamage, other.FriendlyFireObserved, other.FriendlyFireEstimated); SquadDamageEstimated = other.SquadDamageEstimated; } } } public sealed class WeaponCombatStats { public int Slot { get; } public uint ArchetypeId { get; } public uint GearCategoryId { get; internal set; } public bool EwcManaged { get { if (ArchetypeId == 0) { return GearCategoryId != 0; } return false; } } public string Name { get; private set; } public bool NameAuthoritative { get; private set; } public PlayerCombatStats Counters { get; } = new PlayerCombatStats(); internal WeaponCombatStats(int slot, uint id, uint gearCategoryId, string name) { Slot = slot; ArchetypeId = id; GearCategoryId = gearCategoryId; Name = name; } internal void SetName(string name, bool authoritative) { if (!string.IsNullOrEmpty(name) && (authoritative || !NameAuthoritative)) { Name = name; NameAuthoritative |= authoritative; } } public void CopyInto(WeaponCombatStats target) { if (target != null) { target.SetName(Name, NameAuthoritative); target.Counters.CopyFrom(Counters); } } } public static class WeaponRows { public static WeaponCombatStats For(IEnumerable<WeaponCombatStats> rows, int slot) { WeaponCombatStats weaponCombatStats = null; int num = int.MinValue; if (rows == null) { return null; } foreach (WeaponCombatStats row in rows) { if (row != null && row.Slot == slot) { int num2 = Rank(row); if (weaponCombatStats == null || num2 > num) { weaponCombatStats = row; num = num2; } } } return weaponCombatStats; } public static int Rank(WeaponCombatStats row) { if (row == null) { return int.MinValue; } int num = 0; if (row.ArchetypeId != 0) { num += 4; } if (row.NameAuthoritative) { num += 2; } if (Counted(row)) { num++; } return num; } private static bool Counted(WeaponCombatStats row) { if (row.Counters != null) { if (row.Counters.ShotsFired <= 0 && row.Counters.Hits <= 0 && !(row.Counters.EnemyDamage > 0.0)) { return row.Counters.FriendlyFireDamage > 0.0; } return true; } return false; } public static List<WeaponCombatStats> Others(IEnumerable<WeaponCombatStats> rows, int slot, WeaponCombatStats drawn) { List<WeaponCombatStats> list = new List<WeaponCombatStats>(); if (rows == null) { return list; } string b = NameOf(drawn); foreach (WeaponCombatStats row in rows) { if (row == null || row == drawn || row.Slot != slot || row.ArchetypeId == 0 || !Counted(row)) { continue; } string text = NameOf(row); if (text.Length == 0 || (drawn != null && string.Equals(text, b, StringComparison.OrdinalIgnoreCase))) { continue; } bool flag = false; for (int i = 0; i < list.Count; i++) { if (string.Equals(NameOf(list[i]), text, StringComparison.OrdinalIgnoreCase)) { flag = true; break; } } if (!flag) { list.Add(row); } } list.Sort(delegate(WeaponCombatStats left, WeaponCombatStats right) { int num = right.Counters.EnemyDamage.CompareTo(left.Counters.EnemyDamage); return (num == 0) ? string.CompareOrdinal(NameOf(left), NameOf(right)) : num; }); return list; } private static string NameOf(WeaponCombatStats row) { if (row != null && !string.IsNullOrEmpty(row.Name)) { return row.Name.Trim(); } return string.Empty; } } public sealed class CombatPlayer { private readonly Dictionary<(int, uint), WeaponCombatStats> _weapons = new Dictionary<(int, uint), WeaponCombatStats>(); public ulong Lookup { get; } public int DisplaySlot { get; set; } public string Name { get; set; } public bool StatisticsAvailable { get; set; } public PlayerCombatStats Total { get; } = new PlayerCombatStats(); public ImpactCounters Impact { get; } = new ImpactCounters(); public bool SupportRole { get; set; } public IEnumerable<WeaponCombatStats> Weapons => _weapons.Values; public CombatPlayer(ulong lookup) { Lookup = lookup; } public WeaponCombatStats Weapon(int slot, uint id, string name, uint gearCategoryId = 0u, bool authoritative = false) { if (!_weapons.TryGetValue((slot, id), out var value)) { value = new WeaponCombatStats(slot, id, gearCategoryId, name); _weapons.Add((slot, id), value); value.SetName(name, authoritative); } else { value.SetName(name, authoritative); if (gearCategoryId != 0) { value.GearCategoryId = gearCategoryId; } } return value; } public WeaponCombatStats FindWeapon(int slot, uint id) { _weapons.TryGetValue((slot, id), out var value); return value; } public WeaponCombatStats FindWeaponByGearCategory(uint gearCategoryId) { if (gearCategoryId == 0) { return null; } WeaponCombatStats weaponCombatStats = null; foreach (WeaponCombatStats value in _weapons.Values) { if (value.GearCategoryId == gearCategoryId) { if (weaponCombatStats != null && weaponCombatStats != value) { return null; } weaponCombatStats = value; } } return weaponCombatStats; } public CombatPlayer Clone() { CombatPlayer combatPlayer = new CombatPlayer(Lookup) { DisplaySlot = DisplaySlot, Name = Name, StatisticsAvailable = StatisticsAvailable, SupportRole = SupportRole }; combatPlayer.Total.CopyFrom(Total); combatPlayer.Impact.CopyFrom(Impact); foreach (WeaponCombatStats value in _weapons.Values) { WeaponCombatStats target = combatPlayer.Weapon(value.Slot, value.ArchetypeId, value.Name, value.GearCategoryId, value.NameAuthoritative); value.CopyInto(target); } return combatPlayer; } public void ReconcileDamageLowerBound() { double num = 0.0; double num2 = 0.0; foreach (WeaponCombatStats value in _weapons.Values) { if (value.Counters.EnemyDamageObserved) { num += value.Counters.EnemyDamage; } if (value.Counters.FriendlyFireObserved) { num2 += value.Counters.FriendlyFireDamage; } } if (double.IsFinite(num) && num > Total.EnemyDamage + Math.Max(0.01, num * 1E-05)) { Total.RestoreEnemyDamage(num, observed: true, estimated: true); } if (double.IsFinite(num2) && num2 > Total.FriendlyFireDamage + Math.Max(0.01, num2 * 1E-05)) { Total.RestoreFriendlyFireDamage(num2, observed: true, estimated: true); } } public static WeaponCombatStats MatchDamage(CombatPlayer player, WeaponCombatStats held, uint gearCategoryId) { if (player == null || gearCategoryId == 0) { return held; } return player.FindWeaponByGearCategory(gearCategoryId) ?? held; } public void RecordAccuracy(WeaponCombatStats weapon, long fired, long hits, long weak, bool estimated = false) { Total.AddAccuracy(fired, hits, weak, estimated); weapon?.Counters.AddAccuracy(fired, hits, weak, estimated); } public void AdjustAccuracy(WeaponCombatStats weapon, long fired, long hits, long weak, bool estimated = false) { Total.AdjustAccuracy(fired, hits, weak, estimated); weapon?.Counters.AdjustAccuracy(fired, hits, weak, estimated); } public void RecordDamage(WeaponCombatStats weapon, double amount, bool friendly, bool estimated = false) { if (friendly) { Total.AddFriendlyFireDamage(amount, estimated); weapon?.Counters.AddFriendlyFireDamage(amount, estimated); } else { Total.AddEnemyDamage(amount, estimated); weapon?.Counters.AddEnemyDamage(amount, estimated); } } } public sealed class CombatStatsStore { private readonly Dictionary<ulong, CombatPlayer> _players = new Dictionary<ulong, CombatPlayer>(); public IEnumerable<CombatPlayer> Players => _players.Values; public CombatPlayer GetOrCreate(ulong lookup) { if (!_players.TryGetValue(lookup, out var value)) { value = new CombatPlayer(lookup); _players.Add(lookup, value); } return value; } public bool TryGet(ulong lookup, out CombatPlayer player) { return _players.TryGetValue(lookup, out player); } public List<CombatPlayer> Snapshot() { return new List<CombatPlayer>(_players.Values); } public int PruneExcept(ISet<ulong> retainedLookups) { if (retainedLookups == null) { return 0; } List<ulong> list = new List<ulong>(); foreach (ulong key in _players.Keys) { if (!retainedLookups.Contains(key)) { list.Add(key); } } for (int i = 0; i < list.Count; i++) { _players.Remove(list[i]); } return list.Count; } public void Reset() { _players.Clear(); } } public sealed class ExpeditionLifecycle { private bool _armed; private bool _started; public bool ShouldReset(string state) { switch (state) { case "Generating": if (_armed && !_started) { return false; } _armed = true; _started = false; return true; case "InLevel": if (_started) { return false; } _started = true; if (_armed) { return false; } _armed = true; return true; case "Lobby": case "NoLobby": _armed = false; _started = false; break; } return false; } } public static class CombatStatsFormatter { public const string Separator = " "; public static readonly PanelColumn[] Columns = new PanelColumn[6] { PanelColumn.PlayerName, PanelColumn.DamageAndShare, PanelColumn.FriendlyFire, PanelColumn.Accuracy, PanelColumn.WeakspotAccuracy, PanelColumn.Projectiles }; private static readonly string[] RichTextTags = new string[28] { "color", "b", "i", "u", "s", "smallcaps", "uppercase", "lowercase", "size", "sprite", "align", "indent", "line", "margin", "mark", "mspace", "pos", "space", "voffset", "cspace", "font", "gradient", "link", "material", "page", "br", "nobr", "style" }; public const int NameCapacityBytes = 24; public static PanelTextRole TextRoleFor(PanelColumn column) { if (column != PanelColumn.PlayerName) { return PanelTextRole.Neutral; } return PanelTextRole.PlayerName; } public static bool IsRightAligned(PanelColumn column) { return true; } private static bool IsRichTextTag(string content) { string text = ((content[0] == '/') ? content.Substring(1) : content); if (text.Length > 0 && text[0] == '#') { return true; } int i; for (i = 0; i < text.Length && (char.IsLetterOrDigit(text[i]) || text[i] == '-'); i++) { } if (i == 0) { return false; } string text2 = text.Substring(0, i).ToLowerInvariant(); string[] richTextTags = RichTextTags; foreach (string text3 in richTextTags) { if (text2 == text3) { return true; } } return false; } private static bool LooksLikeRichTextTag(string text, int start, out int end) { end = start; int num = text.IndexOf('>', start + 1); if (num < 0 || num - start > 64) { return false; } string text2 = text.Substring(start + 1, num - start - 1); if (text2.Length == 0 || text2.IndexOf('<') >= 0) { return false; } if (!IsRichTextTag(text2)) { return false; } end = num; return true; } public static string FullPlayerName(string name) { if (string.IsNullOrEmpty(name)) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(name.Length); for (int i = 0; i < name.Length; i++) { if (name[i] == '<' && LooksLikeRichTextTag(name, i, out var end)) { i = end; } else if (!char.IsControl(name[i])) { stringBuilder.Append(name[i]); } } return stringBuilder.ToString(); } public static string VisibleName(string name) { string text = FullPlayerName(name); if (string.IsNullOrEmpty(text)) { return text; } bool atCapacity = false; try { atCapacity = Encoding.UTF8.GetByteCount(name) >= 24; } catch { } bool hadOpenTag = HasOpenTag(name); for (int i = 0; i < text.Length; i++) { if (text[i] == '<' && IsDanglingTagFragment(text, i, atCapacity, hadOpenTag)) { return text.Substring(0, i).TrimEnd(); } } return text; } private static bool HasOpenTag(string name) { if (string.IsNullOrEmpty(name)) { return false; } for (int i = 0; i + 2 < name.Length; i++) { if (name[i] == '<' && name[i + 1] != '/' && LooksLikeRichTextTag(name, i, out var _) && IsRichTextTag(name.Substring(i + 1, name.IndexOf('>', i + 1) - i - 1))) { return true; } } return false; } private static bool IsDanglingTagFragment(string text, int start, bool atCapacity, bool hadOpenTag) { if (text.IndexOf('>', start + 1) >= 0) { return false; } string text2 = text.Substring(start + 1); if (text2.Length > 24 || text2.IndexOf('<') >= 0 || text2.IndexOf(' ') >= 0) { return false; } bool flag = text2.Length > 0 && text2[0] == '/'; if (flag) { text2 = text2.Substring(1); } if (flag && !atCapacity && !hadOpenTag) { return false; } if (text2.Length == 0) { return atCapacity || flag; } if (text2[0] == '#') { return IsColourPrefix(text2.Substring(1)); } int num = text2.IndexOf('='); string text3 = ((num >= 0) ? text2.Substring(0, num) : text2); if (text3.Length < (flag ? 1 : 2)) { return false; } string[] richTextTags = RichTextTags; for (int i = 0; i < richTextTags.Length; i++) { if (richTextTags[i].StartsWith(text3, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } private static bool IsColourPrefix(string body) { if (body.Length == 0) { return true; } foreach (char value in body) { if ("0123456789abcdefABCDEF".IndexOf(value) < 0) { return false; } } return true; } public static string TruncatePlayerName(string name, int maximumTextElements = 6) { if (maximumTextElements <= 0) { return string.Empty; } string text = FullPlayerName(name); if (text.Length == 0) { return string.Empty; } StringInfo stringInfo = new StringInfo(text); return stringInfo.SubstringByTextElements(0, Math.Min(stringInfo.LengthInTextElements, maximumTextElements)); } public static string FormatDamage(double amount) { return ((double.IsFinite(amount) && amount >= 0.0) ? amount : 0.0).ToString("#,0.0", CultureInfo.InvariantCulture); } public static string DamageText(PlayerCombatStats stats, bool friendlyFire = false) { if (stats == null) { return "—"; } if (!(friendlyFire ? stats.FriendlyFireObserved : stats.EnemyDamageObserved)) { return "—"; } bool num = (friendlyFire ? stats.FriendlyFireEstimated : stats.EnemyDamageEstimated); return string.Concat(str1: FormatDamage(friendlyFire ? stats.FriendlyFireDamage : stats.EnemyDamage), str0: num ? "~" : string.Empty); } public static string FormatPercent(long numerator, long denominator) { if (denominator <= 0 || numerator < 0) { return "—"; } double d = (double)numerator * 100.0 / (double)denominator; if (!double.IsFinite(d)) { return "—"; } return d.ToString("0.0", CultureInfo.InvariantCulture) + "%"; } public static string FormatShare(PlayerCombatStats stats, double? squadDamage) { if (stats == null || !stats.EnemyDamageObserved) { return "—"; } if (!squadDamage.HasValue || !double.IsFinite(squadDamage.Value) || squadDamage.Value <= 0.0) { return "—"; } double num = stats.EnemyDamage / squadDamage.Value * 100.0; if (!double.IsFinite(num) || num < 0.0) { return "—"; } return ((stats.EnemyDamageEstimated || stats.SquadDamageEstimated) ? "~" : string.Empty) + num.ToString("0.0", CultureInfo.InvariantCulture) + "%"; } private static string EstimateMark(PlayerCombatStats stats) { if (stats == null || !stats.AccuracyEstimated) { return string.Empty; } return "~"; } public static string AccuracyText(PlayerCombatStats stats) { if (stats == null || !stats.AccuracyObserved) { return "—"; } return EstimateMark(stats) + FormatPercent(stats.Hits, stats.ShotsFired); } public static string WeakspotText(PlayerCombatStats stats) { if (stats == null || !stats.AccuracyObserved) { return "—"; } return EstimateMark(stats) + FormatPercent(stats.WeakspotHits, stats.Hits); } public static string[] Fields(PlayerCombatStats stats, PanelColumn column, double? squadDamage = null) { return column switch { PanelColumn.DamageAndShare => new string[2] { DamageText(stats), FormatShare(stats, squadDamage) }, PanelColumn.FriendlyFire => new string[1] { FriendlyFireText(stats) }, PanelColumn.Accuracy => new string[1] { AccuracyText(stats) }, PanelColumn.WeakspotAccuracy => new string[1] { WeakspotText(stats) }, PanelColumn.Projectiles => ProjectileFields(stats), _ => new string[1] { string.Empty }, }; } public static string FriendlyFireText(PlayerCombatStats stats) { return DamageText(stats, friendlyFire: true); } public static string[] ProjectileFields(PlayerCombatStats stats) { if (stats != null && stats.AccuracyObserved) { return new string[3] { EstimateMark(stats) + stats.ShotsFired.ToString(CultureInfo.InvariantCulture), stats.Hits.ToString(CultureInfo.InvariantCulture), stats.WeakspotHits.ToString(CultureInfo.InvariantCulture) }; } return new string[1] { "—" }; } public static string ProjectilesText(PlayerCombatStats stats) { return string.Join(" ", ProjectileFields(stats)); } public static string Value(PlayerCombatStats stats, PanelColumn column, double? squadDamage = null) { if (column != PanelColumn.PlayerName) { return string.Join(" ", Fields(stats, column, squadDamage)); } return string.Empty; } public static string Summary(PlayerCombatStats stats, double? squadDamage = null, bool includeShare = false) { return CombatStrings.Damage + " " + DamageText(stats) + (includeShare ? (" " + CombatStrings.Share + " " + FormatShare(stats, squadDamage)) : string.Empty) + "\n" + CombatStrings.FriendlyFire + " " + DamageText(stats, friendlyFire: true) + "\n" + CombatStrings.Accuracy + " " + AccuracyText(stats) + " " + CombatStrings.Weakspot + " " + WeakspotText(stats) + "\n" + CombatStrings.Pellets + " " + ProjectilesText(stats); } } internal static class CombatSync { private static readonly SquadExchange Exchange = new SquadExchange(); private static bool _armed; private static bool _wasMaster; private static bool _loggedUnarmed; private static bool _loggedSendError; private static bool _loggedOutbound; private static readonly HashSet<ulong> Mismatched = new HashSet<ulong>(); private static readonly HashSet<string> ReportedSync = new HashSet<string>(); private static readonly SyncLogPolicy Packets = new SyncLogPolicy(); private static eGameStateName _lastState = (eGameStateName)5; private static readonly LevelDiagnosticClock LevelClock = new LevelDiagnosticClock(); private static readonly Dictionary<ulong, int> Heard = new Dictionary<ulong, int>(); private static readonly HashSet<ulong> SentTo = new HashSet<ulong>(); private static readonly HashSet<ulong> Confirmed = new HashSet<ulong>(); private static ConfigEntry<string> _allowlistEntry; private static string _allowlistText; private static readonly List<ulong> Allowlist = new List<ulong>(); private static ConfigEntry<bool> _shareEntry; private static bool _share = true; private static bool _shareApplied; private static bool _binding; private static int PrimarySlot => 1; private static int SpecialSlot => 2; private static int ClassSlot => 3; private static int MeleeSlot => 10; private static float Now { get { try { return Time.realtimeSinceStartup; } catch { return 0f; } } } internal static uint Generation => Exchange.Generation; internal static bool HostRunsMod { get { if (!SNet.IsMaster) { return Exchange.HostAnswered; } return true; } } internal static double? SquadTotal { get { if (SNet.IsMaster) { return null; } double? squadFromHost = Exchange.SquadFromHost; if (!squadFromHost.HasValue && !Exchange.AnyPeerAnswered) { return null; } double num = 0.0; foreach (CombatPlayer item in DisplayRows()) { num += Math.Max(0.0, item.Total.EnemyDamage); } return squadFromHost.HasValue ? Math.Max(squadFromHost.Value, num) : num; } } internal static bool ShareMode { get { if (_shareApplied) { return _share; } return false; } } internal static bool HasSnapshot(ulong lookup) { return Exchange.HasSnapshot(lookup); } internal static uint GenerationOf(ulong lookup) { return Exchange.GenerationOf(lookup); } internal static void Register() { if (_armed) { return; } _armed = true; try { Exchange.Report = delegate(string text) { Line(text); }; SquadNet.OnHello = OnHello; SquadNet.OnSnapshot = OnSnapshot; SquadNet.OnProtocolMismatch = OnProtocolMismatch; SquadNet.OnSupplyKinds = OnSupplyKinds; SquadNet.MaySend = MayBeSpokenTo; BindDiscoveryConfig(); bool flag = SquadNet.TryBindApi(); Plugin.Logger.LogInfo((object)("[DIAG] squad sync armed: sharing with " + (ShareMode ? ("every unproven player in the slot list through a bounded probe of " + 3 + " greeting(s) per expedition, and with named and proven players in full") : "named and proven players only") + "; transport=" + (flag ? "GTFO-API free-sized event" : "SNet.Core.SendBytes with a key+magic gate") + ". The greeting runs at its usual cadence (2s burst, 10s keep-alive) for a peer that may be greeted, the host sends its squad rows each second and a client sends only its own measurements. Received rows are queued for main-thread authority checks and display projection; snapshot Owner identifies the player described, not the sender.")); } catch (Exception ex) { _armed = false; if (!_loggedUnarmed) { _loggedUnarmed = true; Plugin.Logger.LogWarning((object)("squad sync could not be armed on this build and the panel keeps working from locally observed data only: " + ex.GetType().Name + ": " + ex.Message)); } } } private static void BindDiscoveryConfig() { try { ConfigFile val = ((Plugin.Instance != null) ? ((BasePlugin)Plugin.Instance).Config : null); if (val == null) { Plugin.Logger.LogWarning((object)("[DIAG] squad sync discovery: the configuration file is not reachable yet, so this machine shares with every player in its slot list through the bounded probe (" + 3 + " greeting(s) per expedition, no rows until a peer answers) and keeps no allowlist. A configuration failure must never be able to silence sharing, so the default is applied here rather than waited for.")); _share = true; _shareApplied = true; Exchange.Capability.SetBroadcast(broadcast: true); } else { _shareEntry = val.Bind<bool>("Squad Sync", "ShareWithEveryPlayer", true, "默认对本队每一名未证明身份的玩家做一次有上限的探测:每局最多 3 个问候包,之后在对方主动开口、换局或换座位之前一个包都不再发。 数据包走 GTFO-API 自己的网络事件;实测表明没装本模组的机器并不会静默丢弃它,GTFO-API 每收到一个未注册事件就在对方机器的日志里打一行 Error(一次实测中同一事件累积 10225 行),所以探测必须有上限,且行数据只发给已证明或 AllowlistedPeers 点名的玩家。 设为 false 则完全不探测:只分享给 AllowlistedPeers 中点名的玩家,或主动向本机发过本模组协议数据包的玩家。"); ApplyShareMode(force: true); _allowlistEntry = val.Bind<string>("Squad Sync", "AllowlistedPeers", string.Empty, "已知运行 CombatPanel 的玩家的 SteamID64,逗号分隔。这里点名的玩家始终会被直接发送行数据,无论 ShareWithEveryPlayer 是什么: 未点名的玩家只有在 ShareWithEveryPlayer 为 true 时才会收到那几个有上限的问候包(每局最多 3 个), 或者它自己主动向本机发过本模组协议数据包(一次问候也算一个)。 数字必须是游戏大厅自己与该玩家关联的那个;不是纯十进制数的值会被忽略,而不是被乱猜。"); ApplyAllowlist(force: true); } } catch (Exception ex) { Plugin.Logger.LogWarning((object)("squad sync discovery: the share configuration could not be read, so this machine keeps the previous values and the panel continues: " + ex.GetType().Name + ": " + ex.Message)); } } private static void ApplyAllowlist(bool force) { if (_allowlistEntry == null) { if (!_binding) { _binding = true; try { BindDiscoveryConfig(); } finally { _binding = false; } } if (_allowlistEntry == null) { return; } } string text = _allowlistEntry.Value ?? string.Empty; if (force || !(text == _allowlistText)) { _allowlistText = text; int num = SquadCapability.ParseAllowlist(text, Allowlist); Exchange.SetAllowlist(Allowlist); Plugin.Logger.LogInfo((object)("[DIAG] squad sync discovery: " + num + " peer lookup(s) named in this machine's configuration. A named peer is always sent this machine's rows. Every other peer is sent nothing until it has itself sent this machine a packet of this build's protocol - except that ShareWithEveryPlayer buys an unproven peer a bounded probe of " + 3 + " greeting(s) per expedition, never a row. Nothing here proves who is online.")); } } private static void ApplyShareMode(bool force) { if (_shareEntry == null) { if (!_binding) { _binding = true; try { BindDiscoveryConfig(); } finally { _binding = false; } } if (_shareEntry == null) { return; } } bool value = _shareEntry.Value; if (force || value != _share || !_shareApplied) { _share = value; _shareApplied = true; Exchange.Capability.SetBroadcast(value); Plugin.Logger.LogInfo((object)(value ? ("[DIAG] squad sync discovery: sharing with every player in this machine's slot list through a bounded probe of " + 3 + " greeting(s) per expedition. An unproven peer receives no row, and after those greetings it receives nothing at all until it answers, a new expedition starts or its seat changes hands. Named and proven players are always sent the rows. The probe is bounded because a machine that runs no mod is not silent about these packets: GTFO-API writes one error line into its log for each one.") : "[DIAG] squad sync discovery: sharing is restricted to players named in AllowlistedPeers, and to those that have themselves sent this machine a packet of this build's protocol. Nothing at all - not a greeting and not a row - is sent to an unproven peer, so no machine is handed a packet it has no handler for.")); } } private static SquadEvidence MayBeSpokenTo(ulong lookup, SquadPacketKind kind) { try { return Exchange.Capability.MayPutOnWire(lookup, kind); } catch (Exception) { return SquadEvidence.Nothing; } } internal static void ResetExpedition() { FlushPacketSummary("expedition reset"); Heard.Clear(); SentTo.Clear(); Confirmed.Clear(); Mismatched.Clear(); ReportedSync.Clear(); LevelClock.Forget(); SquadNet.ResetRoutes(); Exchange.Configure(OwnLookup(), PrimarySlot, SpecialSlot, ClassSlot, MeleeSlot); Exchange.ResetForExpedition(); } internal static void Tick(eGameStateName state, float now) { //IL_0048: 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_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_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: Invalid comparison between Unknown and I4 //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Invalid comparison between Unknown and I4 //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0346: Expected O, but got Unknown //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Expected O, but got Unknown SquadNet.Drain(); if (!SquadNet.ApiBound) { SquadNet.TryBindApi(); } if (!_armed) { return; } try { bool isMaster = SNet.IsMaster; if (isMaster != _wasMaster) { _wasMaster = isMaster; Plugin.Logger.LogInfo((object)(isMaster ? "[DIAG] squad sync: this machine is the host now, so every row is measured here and a received row is only ever merged into a projection." : "[DIAG] squad sync: authority moved to another player; the row