diff --git a/client/HbGpuCanvas.cs b/client/HbGpuCanvas.cs index 5ba193b..0e2f67d 100644 --- a/client/HbGpuCanvas.cs +++ b/client/HbGpuCanvas.cs @@ -14,6 +14,8 @@ public partial class HbGpuCanvas : Control { public const byte DefaultFontId = 0; private const int PushConstantBytes = 80; // mat4 (64) + vec2 viewport (8) + vec2 logicalSize (8) + private const int AtlasTexWidth = 1024; + private const int AtlasTexHeight = 256; // 1024 * 256 = 262,144 == HbGpuAtlasAllocator.TotalTexels [StructLayout(LayoutKind.Sequential, Pack = 4)] private struct PushConstants @@ -34,6 +36,8 @@ public partial class HbGpuCanvas : Control private readonly object _syncLock = new(); private readonly HbGpuQuadInstance[] _stagedQuads = new HbGpuQuadInstance[HbGpuCommandWriter.MaxQuads]; + private readonly byte[] _stagedAtlasMirror = new byte[HbGpuAtlasAllocator.TotalBytes]; + private bool _stagedAtlasDirty; private int _stagedQuadCount; private float _stagedLogicalW = 1280f; private float _stagedLogicalH = 720f; @@ -89,7 +93,7 @@ public partial class HbGpuCanvas : Control AddChild(_outputRect); _outputRect.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); - _backend = new HbGpuVulkanBackend(_outputTexRd, _atlas); + _backend = new HbGpuVulkanBackend(_outputTexRd); _renderCallable = Callable.From(RenderOnRenderThread); _disposeCallable = Callable.From(DisposeOnRenderThread); } @@ -277,6 +281,72 @@ public partial class HbGpuCanvas : Control color.R, color.G, color.B, color.A); } + public void DrawChevron(float cx, float cy, float sizePx, float angleRad, Color color) + { + CachedBlob blob = HbGpuVectorShapes.GetChevronTriangle(_blobCache); + float s = sizePx * 0.001f; + float cos = MathF.Cos(angleRad); + float sin = MathF.Sin(angleRad); + _writer.DrawBlob( + blob, cx, cy, + -sin * s, cos * s, + cos * s, sin * s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void DrawDiamond(float cx, float cy, float radiusPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + CachedBlob blob = HbGpuVectorShapes.GetDiamondBlip(_blobCache); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawRectOutline(float x, float y, float w, float h, float thicknessPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + if (w <= 0f || h <= 0f || thicknessPx <= 0f) + { + return; + } + float t = thicknessPx; + DrawRectFilled(x, y, w, t, color, clipMinPacked, clipMaxPacked); + DrawRectFilled(x, y + h - t, w, t, color, clipMinPacked, clipMaxPacked); + DrawRectFilled(x, y + t, t, MathF.Max(0f, h - 2f * t), color, clipMinPacked, clipMaxPacked); + DrawRectFilled(x + w - t, y + t, t, MathF.Max(0f, h - 2f * t), color, clipMinPacked, clipMaxPacked); + } + + public void DrawPanelFrame(Rect2 rect, Color bgCol, Color borderCol, Color accentCol, + float cornerLen = 12f, float borderPx = 1.5f, bool drawBg = true) + { + float x = rect.Position.X; + float y = rect.Position.Y; + float w = rect.Size.X; + float h = rect.Size.Y; + if (w < 2f || h < 2f) + { + return; + } + if (drawBg) + { + DrawRectFilled(x, y, w, h, bgCol); + } + DrawRectOutline(x, y, w, h, borderPx, borderCol); + + float arm = MathF.Min(cornerLen, MathF.Min(w, h) * 0.4f); + float cThick = MathF.Max(borderPx + 0.5f, 2.0f); + DrawTargetBracketCorner(x, y, arm, cThick, 0, accentCol); + DrawTargetBracketCorner(x + w, y, arm, cThick, 1, accentCol); + DrawTargetBracketCorner(x + w, y + h, arm, cThick, 2, accentCol); + DrawTargetBracketCorner(x, y + h, arm, cThick, 3, accentCol); + } + public void DrawArcStrokeDynamic(float cx, float cy, float radiusPx, float strokePx, float startRadScreen, float endRadScreen, Color color) { if (radiusPx <= 0f || strokePx <= 0f) @@ -314,6 +384,11 @@ public partial class HbGpuCanvas : Control { Array.Copy(_writer.RawBuffer, 0, _stagedQuads, 0, count); } + if (_atlas.PendingChunkCount > 0) + { + _atlas.DrainToMirror(_stagedAtlasMirror); + _stagedAtlasDirty = true; + } _stagedQuadCount = count; _stagedLogicalW = logicalW; _stagedLogicalH = logicalH; @@ -367,9 +442,6 @@ public partial class HbGpuCanvas : Control return; } - int quadCount; - float logicalW, logicalH; - int physW, physH; lock (_syncLock) { if (!_hasStagedFrame) @@ -377,12 +449,17 @@ public partial class HbGpuCanvas : Control return; } _hasStagedFrame = false; - quadCount = _stagedQuadCount; - logicalW = _stagedLogicalW; - logicalH = _stagedLogicalH; - physW = _stagedPhysW; - physH = _stagedPhysH; - _backend.RenderFrame(_stagedQuads, quadCount, logicalW, logicalH, physW, physH); + bool atlasDirty = _stagedAtlasDirty; + _stagedAtlasDirty = false; + _backend.RenderFrame( + _stagedQuads, + _stagedQuadCount, + _stagedAtlasMirror, + atlasDirty, + _stagedLogicalW, + _stagedLogicalH, + _stagedPhysW, + _stagedPhysH); } } @@ -429,6 +506,17 @@ public partial class HbGpuCanvas : Control } public override void _ExitTree() + { + ReleaseResources(disposing: true); + } + + protected override void Dispose(bool disposing) + { + ReleaseResources(disposing); + base.Dispose(disposing); + } + + private void ReleaseResources(bool disposing) { if (_disposed) { @@ -436,15 +524,18 @@ public partial class HbGpuCanvas : Control } _disposed = true; - if (_outputTexRd is not null) + if (disposing) { - _outputTexRd.TextureRdRid = new Rid(); - } + if (_outputTexRd is not null) + { + _outputTexRd.TextureRdRid = new Rid(); + } - if (_backend is not null && RenderingServer.GetRenderingDevice() is not null) - { - RenderingServer.CallOnRenderThread(_disposeCallable); - RenderingServer.ForceSync(); + if (_backend is not null && RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.CallOnRenderThread(_disposeCallable); + RenderingServer.ForceSync(); + } } _fontCache.Dispose(); @@ -453,9 +544,7 @@ public partial class HbGpuCanvas : Control private sealed class HbGpuVulkanBackend { private readonly Texture2Drd _outputTexRd; - private readonly HbGpuAtlasAllocator _atlas; - private readonly byte[] _atlasMirrorBytes = new byte[HbGpuAtlasAllocator.TotalBytes]; private readonly byte[] _quadUploadBytes = new byte[HbGpuCommandWriter.MaxQuads * 80]; private readonly byte[] _pushConstantBytes = new byte[PushConstantBytes]; private static readonly Color[] ClearColors = { new Color(0f, 0f, 0f, 0f) }; @@ -466,7 +555,8 @@ public partial class HbGpuCanvas : Control private Rid _shaderRid; private Rid _pipelineRid; - private Rid _atlasBufRid; + private Rid _nearestSamplerRid; + private Rid _atlasTexRid; private Rid _quadSsboRid; private Rid _uniformSetRid; private Rid _colorTexRid; @@ -481,15 +571,16 @@ public partial class HbGpuCanvas : Control public double LastHbGpuMs { get; private set; } public int LastDrawCallCount { get; private set; } - public HbGpuVulkanBackend(Texture2Drd outputTexRd, HbGpuAtlasAllocator atlas) + public HbGpuVulkanBackend(Texture2Drd outputTexRd) { _outputTexRd = outputTexRd; - _atlas = atlas; } public void RenderFrame( HbGpuQuadInstance[] quads, int quadCount, + byte[] atlasMirrorBytes, + bool atlasDirty, float logicalW, float logicalH, int physW, @@ -506,15 +597,9 @@ public partial class HbGpuCanvas : Control return; } - bool atlasDirty = _atlas.PendingChunkCount > 0; - if (atlasDirty) - { - _atlas.DrainToMirror(_atlasMirrorBytes); - } - if (!_initialized) { - if (!TryInitialize(rd, physW, physH)) + if (!TryInitialize(rd, atlasMirrorBytes, physW, physH)) { _failed = true; return; @@ -524,7 +609,7 @@ public partial class HbGpuCanvas : Control { if (atlasDirty) { - RebuildAtlasBufferAndUniformSet(rd); + rd.TextureUpdate(_atlasTexRid, 0, atlasMirrorBytes); } if (physW != _fbWidth || physH != _fbHeight) { @@ -590,30 +675,43 @@ public partial class HbGpuCanvas : Control } } - private void RebuildAtlasBufferAndUniformSet(RenderingDevice rd) + private void CreateAtlasAndUniformSet(RenderingDevice rd, byte[] initialAtlasBytes) { - if (_uniformSetRid.IsValid) + var nearestState = new RDSamplerState { - rd.FreeRid(_uniformSetRid); - _uniformSetRid = new Rid(); - } - if (_atlasBufRid.IsValid) - { - rd.FreeRid(_atlasBufRid); - _atlasBufRid = new Rid(); - } + MinFilter = RenderingDevice.SamplerFilter.Nearest, + MagFilter = RenderingDevice.SamplerFilter.Nearest, + RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge + }; + _nearestSamplerRid = rd.SamplerCreate(nearestState); - _atlasBufRid = rd.TextureBufferCreate( - HbGpuAtlasAllocator.TotalTexels, - RenderingDevice.DataFormat.R16G16B16A16Sint, - _atlasMirrorBytes); + var atlasFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sint, + Width = AtlasTexWidth, + Height = AtlasTexHeight, + Depth = 1, + ArrayLayers = 1, + Mipmaps = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit + | RenderingDevice.TextureUsageBits.CanUpdateBit + }; + _atlasTexRid = rd.TextureCreate( + atlasFmt, + new RDTextureView(), + new Godot.Collections.Array { initialAtlasBytes }); var u0 = new RDUniform { - UniformType = RenderingDevice.UniformType.TextureBuffer, + UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 0 }; - u0.AddId(_atlasBufRid); + u0.AddId(_nearestSamplerRid); + u0.AddId(_atlasTexRid); var u1 = new RDUniform { @@ -660,7 +758,7 @@ public partial class HbGpuCanvas : Control } } - private bool TryInitialize(RenderingDevice rd, int physW, int physH) + private bool TryInitialize(RenderingDevice rd, byte[] initialAtlasBytes, int physW, int physH) { _rd = rd; @@ -694,7 +792,7 @@ public partial class HbGpuCanvas : Control } _quadSsboRid = rd.StorageBufferCreate((uint)(HbGpuCommandWriter.MaxQuads * 80)); - RebuildAtlasBufferAndUniformSet(rd); + CreateAtlasAndUniformSet(rd, initialAtlasBytes); RecreateRenderTarget(rd, physW, physH); @@ -805,7 +903,8 @@ public partial class HbGpuCanvas : Control if (_colorTexRid.IsValid) { _rd.FreeRid(_colorTexRid); _colorTexRid = new Rid(); } if (_uniformSetRid.IsValid) { _rd.FreeRid(_uniformSetRid); _uniformSetRid = new Rid(); } if (_quadSsboRid.IsValid) { _rd.FreeRid(_quadSsboRid); _quadSsboRid = new Rid(); } - if (_atlasBufRid.IsValid) { _rd.FreeRid(_atlasBufRid); _atlasBufRid = new Rid(); } + if (_atlasTexRid.IsValid) { _rd.FreeRid(_atlasTexRid); _atlasTexRid = new Rid(); } + if (_nearestSamplerRid.IsValid) { _rd.FreeRid(_nearestSamplerRid); _nearestSamplerRid = new Rid(); } if (_pipelineRid.IsValid) { _rd.FreeRid(_pipelineRid); _pipelineRid = new Rid(); } if (_shaderRid.IsValid) { _rd.FreeRid(_shaderRid); _shaderRid = new Rid(); } @@ -886,10 +985,20 @@ void main() {{ { string sharedFrag = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Shared); string drawFrag = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Draw); + const string oldAtlasDecl = "uniform highp isampler2D hb_gpu_atlas;"; + const string oldWidthDecl = "uniform int hb_gpu_atlas_width;"; + if (!sharedFrag.Contains(oldAtlasDecl, StringComparison.Ordinal) || + !sharedFrag.Contains(oldWidthDecl, StringComparison.Ordinal)) + { + throw new InvalidOperationException("Unexpected hb-gpu-fragment.glsl HB_GPU_ATLAS_2D uniform layout."); + } + sharedFrag = sharedFrag + .Replace(oldAtlasDecl, "layout(set = 0, binding = 0) uniform highp isampler2D hb_gpu_atlas;", StringComparison.Ordinal) + .Replace(oldWidthDecl, $"const int hb_gpu_atlas_width = {AtlasTexWidth};", StringComparison.Ordinal); + return $@"#version 450 -#define uniform layout(set = 0, binding = 0) uniform +#define HB_GPU_ATLAS_2D {sharedFrag} -#undef uniform {drawFrag} layout(push_constant, std430) uniform Push {{ diff --git a/client/Hud.cs b/client/Hud.cs index f2a60f0..c34b339 100644 --- a/client/Hud.cs +++ b/client/Hud.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using Godot; using RustToDust.Core; +using RustToDust.HbGpu; namespace RustToDust.Client; @@ -15,16 +16,18 @@ public enum HitMarkerKind } /// -/// Rust to Dust industrial HUD: -/// - Top-Left: Chassis badge (DORSAL/CORONAL), Core HP, Speed, Contenders Alive, Safe Circle status, Pickup prompt. +/// Rust to Dust industrial HUD rendered in a single Vulkan draw call via : +/// - Top-Left: Chassis badge (DORSAL/CORONAL), Core HP bar, Speed/Alt/Alive/Kills, Safe Circle, Detection, Wave, Net, Prompt. /// - Top-Right: Tactical Radar (Safe Circle, RadarSignature-scaled Spectator Wall, lock lines, contenders, salvage). /// - Bottom-Left: Live clickable Aetheria Hardpoint & Heat Schematic + Cargo Salvage Rack (Tab expands Garage details). -/// - Bottom-Center: Imperial Broadcast Chyron (Weksa commentary). +/// - Bottom-Right: Imperial Broadcast Chyron (Weksa commentary). +/// - Center & 3D World: Crosshair + heat arc + incoming/outgoing hit feedback + squad chevrons + target boxes + offscreen arrows. /// public partial class Hud : CanvasLayer { - private static readonly Color BgDark = Color.FromHtml("#131613"); + private static readonly Color BgDark = new(0.075f, 0.086f, 0.075f, 0.88f); private static readonly Color BgInner = Color.FromHtml("#1b1f1b"); + private static readonly Color BgRowHover = new(0.16f, 0.20f, 0.16f, 0.92f); private static readonly Color BorderCol = Color.FromHtml("#3e4638"); private static readonly Color OliveCol = Color.FromHtml("#9bb06a"); private static readonly Color OrangeCol = Color.FromHtml("#e08a4a"); @@ -34,64 +37,128 @@ public partial class Hud : CanvasLayer private static readonly Color AlliedCol = Color.FromHtml("#52e3a8"); private static readonly Color GoldCol = Color.FromHtml("#e6b838"); private static readonly Color RedCol = Color.FromHtml("#d93829"); + private static readonly Color PatronColor = Color.FromHtml("#4ba8a5"); + private static readonly Color ShadowCol = new(0.04f, 0.05f, 0.04f, 0.88f); + + private const float HitArcDuration = 0.65f; + private const float BorderPad = 36f; + private const float PanelAvoidPad = 18f; + private const float OffscreenHostileMaxDistance = 220f; + private const int MaxOffscreenHostileArrows = 6; + private const int MaxCargoHitRects = 16; + + private struct IncomingHitArc + { + public float SourceX; + public float SourceZ; + public WeaponVisualClass WeaponClass; + public float Age; + } + + private readonly struct OffscreenMarker + { + public readonly System.Numerics.Vector3 CamLocal; + public readonly float Distance; + public readonly Color Color; + public readonly bool IsLockedOnLocal; + + public OffscreenMarker(System.Numerics.Vector3 camLocal, float distance, Color color, bool isLockedOnLocal) + { + CamLocal = camLocal; + Distance = distance; + Color = color; + IsLockedOnLocal = isLockedOnLocal; + } + } private readonly Func _getSession; private readonly Action _onEquipCargo; private readonly Func _getCameraYaw; private readonly Func? _projectWorld; - private Label _chassisHeader = null!; - private Label _planeBadge = null!; - private ProgressBar _coreHpBar = null!; - private Label _coreHpLabel = null!; - private Label _statsLabel = null!; - private Label _safeLabel = null!; - private Label _detectionLabel = null!; - private Label _waveLabel = null!; - private Label _netStatusLabel = null!; - private Label _promptLabel = null!; - private Label _controlsHint = null!; - - private RadarWidget _radar = null!; - private Label _radarTitle = null!; - private Label _mapAttribLabel = null!; private ColorRect _vignetteRect = null!; private ShaderMaterial _vignetteMat = null!; - private WorldMarkerOverlay _worldMarkers = null!; - private CrosshairOverlay _crosshair = null!; - private float _damagePulse; - private float _lowCoreRatio; - private float _overheatPulse; - private float _vignetteTime; + private ColorRect _bottomLeftBg = null!; private InventoryGridControl _schematic = null!; - private Label _hoverLabel = null!; - private VBoxContainer _cargoList = null!; - private Label _cargoHeader = null!; - private Label _garageDetails = null!; - private ChromePanel _topLeftPanel = null!; - private ChromePanel _topRightPanel = null!; - private ChromePanel _bottomLeftPanel = null!; - private ChromePanel _chyronPanel = null!; + private HbGpuCanvas _hbCanvas = null!; - private ChromePanel _netPanel = null!; + // Interactive [F9] multiplayer input panel (kept on Godot Controls until Thing 2 Cut 14c) + private PanelContainer _netPanel = null!; private Label _netModeBadge = null!; private Label _netPanelStatus = null!; private LineEdit _callsignEdit = null!; private LineEdit _endpointEdit = null!; private string? _uiNetError; - private VBoxContainer _chyronBox = null!; - private readonly Label[] _chyronLabels = new Label[3]; - private BroadcastFeed? _lastBroadcastFeed; - private long _lastChyronVersion = -1; - private ChromePanel _outcomeBanner = null!; - private Label _outcomeLabel = null!; + // Layout rects (logical pixels) + private Rect2 _topLeftRect; + private Rect2 _topRightRect; + private Rect2 _bottomLeftRect; + private Rect2 _schematicRect; + private Rect2 _chyronRect; + private Rect2 _outcomeRect; + private bool _outcomeVisible; + private Vector2 _lastViewportSize = new(1280f, 720f); + // Cargo click hitboxes (zero Button allocations) + private readonly Rect2[] _cargoRowRects = new Rect2[MaxCargoHitRects]; + private readonly Rect2[] _cargoFitRects = new Rect2[MaxCargoHitRects]; + private int _cargoHitCount; + private ChassisGrid? _lastCargoGrid; private int _selectedCargoIndex = -1; - private int _lastCargoHash = -1; private bool _garageExpanded; private Vector2I? _lastHoveredCell; + // Vignette & combat feedback + private float _damagePulse; + private float _lowCoreRatio; + private float _overheatPulse; + private float _vignetteTime; + private readonly IncomingHitArc[] _incomingArcs = new IncomingHitArc[8]; + private int _incomingArcCount; + private HitMarkerKind _hitMarkerKind; + private float _hitMarkerRemaining; + private float _hitMarkerDuration; + private MatchState? _lastCrosshairState; + + // Zero-GC scratch & change-detected text caches + private readonly char[] _scratch = new char[512]; + private readonly List _offscreenHostiles = new(16); + private static readonly Comparison OffscreenSortComparison = static (a, b) => + { + int lockCmp = b.IsLockedOnLocal.CompareTo(a.IsLockedOnLocal); + return lockCmp != 0 ? lockCmp : a.Distance.CompareTo(b.Distance); + }; + + private readonly List _promptLines = new(3); + private string _cachedPromptText = string.Empty; + private int _lastPromptKey = int.MinValue; + private bool _lastPromptPod; + private int _lastPodAglRounded = int.MinValue; + private int _lastPodHorizRounded = int.MinValue; + private int _lastPodVertRounded = int.MinValue; + private bool _lastPodBurn; + + private readonly List _hoverLines = new(3); + private string _cachedHoverText = "HOVER CELL FOR TELEMETRY"; + private Color _cachedHoverColor = TextMuted; + + private readonly List _garageLines = new(24); + private string _cachedGarageDetails = string.Empty; + private int _lastGarageHash = int.MinValue; + + private BroadcastFeed? _lastBroadcastFeed; + private long _lastChyronVersion = -1; + private readonly string[] _chyronDisplayLines = new string[3]; + private readonly bool[] _chyronIsLatest = new bool[3]; + private int _chyronLineCount; + + private IClientArenaSession? _latestSession; + private string? _cachedChassisName; + private string _cachedChassisUpper = "CHASSIS"; + private bool _dirtyEmit; + private bool _emittedThisFrame; + public event Action? JoinRequested; public event Action? HostRequested; public event Action? SoloRequested; @@ -110,43 +177,107 @@ public partial class Hud : CanvasLayer Layer = 10; } + public HbGpuCanvas HbCanvas => _hbCanvas; public bool GarageExpanded => _garageExpanded; public bool NetworkPanelOpen => _netPanel.Visible; public bool IsUiTextInputFocused => _netPanel.Visible && (_callsignEdit.HasFocus() || _endpointEdit.HasFocus()); public InventoryGridControl Schematic => _schematic; - internal int ActiveHitArcCount => _crosshair.ActiveHitArcCount; - internal bool HasActiveHitMarker => _crosshair.HasActiveHitMarker; - internal HitMarkerKind ActiveHitMarkerKind => _crosshair.ActiveHitMarkerKind; + internal int ActiveHitArcCount => _incomingArcCount; + internal bool HasActiveHitMarker => _hitMarkerRemaining > 0f && _hitMarkerKind != HitMarkerKind.None; + internal HitMarkerKind ActiveHitMarkerKind => HasActiveHitMarker ? _hitMarkerKind : HitMarkerKind.None; internal bool IsVignetteVisible => _vignetteRect is not null && _vignetteRect.Visible; - internal void PushTestHitArc(float sourceX, float sourceZ, WeaponVisualClass weaponClass) => - _crosshair.PushTestHitArc(sourceX, sourceZ, weaponClass); + internal Rect2 BottomLeftPanelRect => _bottomLeftRect; + internal Rect2 ChyronPanelRect => _chyronRect; + internal string HoverLabelText => _cachedHoverText; + internal string PromptLabelText => _cachedPromptText; + internal string GarageDetailsText => _cachedGarageDetails; + + internal void PushTestHitArc(float sourceX, float sourceZ, WeaponVisualClass weaponClass) + { + if (_incomingArcCount >= _incomingArcs.Length) + { + for (int i = 1; i < _incomingArcs.Length; i++) + { + _incomingArcs[i - 1] = _incomingArcs[i]; + } + _incomingArcCount = _incomingArcs.Length - 1; + } + _incomingArcs[_incomingArcCount++] = new IncomingHitArc + { + SourceX = sourceX, + SourceZ = sourceZ, + WeaponClass = weaponClass, + Age = 0f + }; + _dirtyEmit = true; + } + internal void ResetFeedback() { _damagePulse = 0f; _lowCoreRatio = 0f; _overheatPulse = 0f; _vignetteTime = 0f; + _incomingArcCount = 0; + _hitMarkerKind = HitMarkerKind.None; + _hitMarkerRemaining = 0f; + _hitMarkerDuration = 0f; if (_vignetteRect is not null) { _vignetteRect.Visible = false; } - _crosshair?.ResetFeedback(); + _dirtyEmit = true; } - internal Rect2 BottomLeftPanelRect => _bottomLeftPanel.GetGlobalRect(); - internal Rect2 ChyronPanelRect => _chyronPanel.GetGlobalRect(); - internal string HoverLabelText => _hoverLabel.Text; - internal string PromptLabelText => _promptLabel.Text; - internal string GarageDetailsText => _garageDetails.Text; + internal void SimulateCellHover(Vector2I? cell, HardpointSpec? hp) => OnSchematicHoverChanged(cell, hp); - public IEnumerable GetChromeMaterials() + public override void _Ready() { - yield return _topLeftPanel.ChromeMaterial; - yield return _topRightPanel.ChromeMaterial; - yield return _bottomLeftPanel.ChromeMaterial; - yield return _chyronPanel.ChromeMaterial; - yield return _outcomeBanner.ChromeMaterial; - yield return _netPanel.ChromeMaterial; + Shader vigShader = GD.Load("res://hud_vignette.gdshader") + ?? throw new InvalidOperationException("Failed to load res://hud_vignette.gdshader"); + _vignetteMat = new ShaderMaterial { Shader = vigShader }; + _vignetteRect = new ColorRect + { + Name = "HudVignette", + Material = _vignetteMat, + MouseFilter = Control.MouseFilterEnum.Ignore, + Visible = false + }; + _vignetteRect.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_vignetteRect); + + // Dark backdrop under _schematic so inactive holes (e.g. Raptor) show panel BgDark instead of 3D world + _bottomLeftBg = new ColorRect + { + Name = "BottomLeftBackdrop", + Color = BgDark, + MouseFilter = Control.MouseFilterEnum.Ignore + }; + AddChild(_bottomLeftBg); + + _schematic = new InventoryGridControl + { + Name = "SchematicGrid", + ExternalHbGpuOwner = true, + CustomMinimumSize = new Vector2(180f, 188f) + }; + _schematic.HardpointClicked += OnHardpointClicked; + _schematic.HoverChanged += OnSchematicHoverChanged; + AddChild(_schematic); + + // Single-draw-call HarfBuzz hb-gpu overlay sits strictly ABOVE _schematic's bilinear thermal backdrop + _hbCanvas = new HbGpuCanvas + { + Name = "HbGpuCanvas", + MouseFilter = Control.MouseFilterEnum.Ignore + }; + _hbCanvas.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.FullRect); + AddChild(_hbCanvas); + + BuildNetworkPanel(); + + _lastViewportSize = GetViewportSizeSafe(); + RecomputeLayoutRects(_lastViewportSize, _latestSession); } public void ToggleNetworkPanel() => SetNetworkPanelOpen(!_netPanel.Visible); @@ -183,9 +314,10 @@ public partial class Hud : CanvasLayer public void ToggleGarage() { _garageExpanded = !_garageExpanded; - _garageDetails.Visible = _garageExpanded; + _lastGarageHash = int.MinValue; _schematic.CustomMinimumSize = _garageExpanded ? new Vector2(198f, 208f) : new Vector2(180f, 188f); - _schematic.QueueRedraw(); + RecomputeLayoutRects(GetViewportSizeSafe(), _latestSession); + _dirtyEmit = true; } public void SetMatchHudActive(bool active) @@ -207,14 +339,54 @@ public partial class Hud : CanvasLayer } } + public override void _Input(InputEvent @event) + { + if (!Visible || _netPanel.Visible) + { + return; + } + + if (@event is InputEventMouseButton mb && mb.Pressed && mb.ButtonIndex == MouseButton.Left) + { + if (_lastCargoGrid is not null && + _bottomLeftRect.HasPoint(mb.Position) && + !_schematic.GetGlobalRect().HasPoint(mb.Position)) + { + for (int i = 0; i < _cargoHitCount; i++) + { + if (_cargoFitRects[i].HasPoint(mb.Position)) + { + AutoFitCargo(_lastCargoGrid, i); + GetViewport().SetInputAsHandled(); + _dirtyEmit = true; + return; + } + if (_cargoRowRects[i].HasPoint(mb.Position)) + { + _selectedCargoIndex = (_selectedCargoIndex == i) ? -1 : i; + if (_lastHoveredCell is null) + { + UpdateCargoSelectionTooltip(_lastCargoGrid); + } + GetViewport().SetInputAsHandled(); + _dirtyEmit = true; + return; + } + } + } + } + } + public override void _Process(double delta) { if (!Visible) { + _emittedThisFrame = false; return; } + float dt = (float)delta; - _crosshair?.Advance(dt); + bool timerAdvanced = AdvanceTimers(dt); if (_vignetteRect is not null) { @@ -234,6 +406,50 @@ public partial class Hud : CanvasLayer _vignetteMat.SetShaderParameter("time_sec", _vignetteTime); } } + else if (dt > 0f) + { + _vignetteTime += dt; + } + + if ((_dirtyEmit || timerAdvanced) && !_emittedThisFrame && _latestSession is not null) + { + EmitHudFrame(_latestSession); + } + + _emittedThisFrame = false; + _dirtyEmit = false; + } + + private bool AdvanceTimers(float dt) + { + bool dirty = false; + if (_incomingArcCount > 0 && dt > 0f) + { + int write = 0; + for (int i = 0; i < _incomingArcCount; i++) + { + _incomingArcs[i].Age += dt; + if (_incomingArcs[i].Age < HitArcDuration) + { + _incomingArcs[write++] = _incomingArcs[i]; + } + } + _incomingArcCount = write; + dirty = true; + } + + if (_hitMarkerRemaining > 0f && dt > 0f) + { + _hitMarkerRemaining = MathF.Max(0f, _hitMarkerRemaining - dt); + if (_hitMarkerRemaining <= 0.001f) + { + _hitMarkerRemaining = 0f; + _hitMarkerKind = HitMarkerKind.None; + } + dirty = true; + } + + return dirty; } public void ConsumeEvents( @@ -254,7 +470,7 @@ public partial class Hud : CanvasLayer if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId == localContenderId) { var wc = (WeaponVisualClass)hit.WeaponClass; - _crosshair?.PushTestHitArc(hit.SourceX, hit.SourceZ, wc); + PushTestHitArc(hit.SourceX, hit.SourceZ, wc); float pulse = wc is WeaponVisualClass.Explosive or WeaponVisualClass.RocketSalvo or WeaponVisualClass.GaussRail ? 0.95f : 0.62f; @@ -264,7 +480,7 @@ public partial class Hud : CanvasLayer || hit.TargetKind == (byte)HitTargetKind.Spectator; if (targetIsVehicle && hit.IsContenderShooter && hit.ShooterId == localContenderId) { - _crosshair?.TriggerHitMarker(hit.CoreDamage > 0.001f, hit.Killed); + TriggerHitMarker(hit.CoreDamage > 0.001f, hit.Killed); } break; } @@ -291,45 +507,60 @@ public partial class Hud : CanvasLayer } } - public override void _Ready() + private void TriggerHitMarker(bool coreHit, bool killed) { - BuildCrosshair(); - BuildTopLeft(); - BuildTopRightRadar(); - BuildBottomLeftSchematic(); - BuildBottomCenterChyron(); - BuildOutcomeBanner(); - BuildNetworkPanel(); - _worldMarkers.SetAvoidPanels(_topLeftPanel, _topRightPanel, _bottomLeftPanel, _chyronPanel); + HitMarkerKind nextKind = killed + ? HitMarkerKind.Kill + : (coreHit ? HitMarkerKind.Core : HitMarkerKind.Armor); + if (_hitMarkerRemaining > 0f && (int)nextKind < (int)_hitMarkerKind) + { + nextKind = _hitMarkerKind; + } + _hitMarkerKind = nextKind; + _hitMarkerDuration = nextKind switch + { + HitMarkerKind.Kill => 0.38f, + HitMarkerKind.Core => 0.26f, + _ => 0.18f + }; + _hitMarkerRemaining = _hitMarkerDuration; + _dirtyEmit = true; } public bool IsPointerOverInteractiveHud(Vector2 screenPos) { - return (_topLeftPanel.Visible && _topLeftPanel.GetGlobalRect().HasPoint(screenPos)) - || (_topRightPanel.Visible && _topRightPanel.GetGlobalRect().HasPoint(screenPos)) - || (_bottomLeftPanel.Visible && _bottomLeftPanel.GetGlobalRect().HasPoint(screenPos)) - || (_chyronPanel.Visible && _chyronPanel.GetGlobalRect().HasPoint(screenPos)) - || (_chyronBox.Visible && _chyronBox.GetGlobalRect().HasPoint(screenPos)) - || (_outcomeBanner.Visible && _outcomeBanner.GetGlobalRect().HasPoint(screenPos)) + return (Visible && _topLeftRect.HasPoint(screenPos)) + || (Visible && _topRightRect.HasPoint(screenPos)) + || (Visible && _bottomLeftRect.HasPoint(screenPos)) + || (Visible && _chyronRect.HasPoint(screenPos)) + || (Visible && _outcomeVisible && _outcomeRect.HasPoint(screenPos)) || (_netPanel.Visible && _netPanel.GetGlobalRect().HasPoint(screenPos)); } public bool HasPanelOverlapOrClip(Vector2 viewportSize) { - var panels = new[] { _topLeftPanel, _topRightPanel, _bottomLeftPanel, _chyronPanel, _netPanel }; - var bounds = new Rect2(Vector2.Zero, viewportSize + new Vector2(1f, 1f)); - for (int i = 0; i < panels.Length; i++) + RecomputeLayoutRects(viewportSize, _latestSession); + Span rects = stackalloc Rect2[5]; + int count = 0; + rects[count++] = _topLeftRect; + rects[count++] = _topRightRect; + rects[count++] = _bottomLeftRect; + rects[count++] = _chyronRect; + if (_netPanel.Visible) { - if (!panels[i].Visible) continue; - var ri = panels[i].GetGlobalRect(); - if (!bounds.Encloses(ri)) + rects[count++] = _netPanel.GetGlobalRect(); + } + + var bounds = new Rect2(Vector2.Zero, viewportSize + new Vector2(1f, 1f)); + for (int i = 0; i < count; i++) + { + if (!bounds.Encloses(rects[i])) { return true; } - for (int j = i + 1; j < panels.Length; j++) + for (int j = i + 1; j < count; j++) { - if (!panels[j].Visible) continue; - if (ri.Intersects(panels[j].GetGlobalRect())) + if (rects[i].Intersects(rects[j])) { return true; } @@ -340,187 +571,31 @@ public partial class Hud : CanvasLayer public void Sync(IClientArenaSession session) { + _latestSession = session; var state = session.ViewState; + if (!ReferenceEquals(_lastCrosshairState, state)) + { + _lastCrosshairState = state; + _incomingArcCount = 0; + _hitMarkerKind = HitMarkerKind.None; + _hitMarkerRemaining = 0f; + _hitMarkerDuration = 0f; + } + var player = session.LocalContender; var net = session.ConnectionStatus; - // Top-Left Status - OrbitalPod? localPod = null; - if (player.IsInDropPod) - { - var pods = session.ActivePods; - for (int i = 0; i < pods.Count; i++) - { - if (pods[i].PodKind == OrbitalPodKind.Contender && pods[i].ContenderId == player.Id) - { - localPod = pods[i]; - break; - } - } - } - - int aliveCount = 0; - for (int i = 0; i < state.Contenders.Count; i++) - { - if (state.Contenders[i].Alive) aliveCount++; - } - - if (player.IsInDropPod) - { - float agl = localPod is not null - ? MathF.Max(0f, localPod.LastAgl) - : MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z)); - float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY); - float horizSpeed = localPod is not null - ? MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ) - : player.Speed; - bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; - _chassisHeader.Text = "ORBITAL DROP POD"; - _planeBadge.Text = burning ? "RETRO BURN" : "FREEFALL"; - _planeBadge.Modulate = burning ? OrangeCol : CyanCol; - _statsLabel.Text = $"ALT {agl:F0}m | HORIZ {horizSpeed:F0} m/s | VERT {velDown:F0} m/s | ALIVE {aliveCount} / {state.Contenders.Count}"; - _controlsHint.Text = "WASD Steer Pod | Mouse Look | Retro-Burn Auto | Wheel Zoom"; - } - else - { - _chassisHeader.Text = player.Grid.Spec.Name.ToUpperInvariant(); - bool isCoronal = player.Grid.Spec.Plane == GridPlane.Coronal; - _planeBadge.Text = isCoronal ? "CORONAL" : "DORSAL"; - _planeBadge.Modulate = isCoronal ? CyanCol : OliveCol; - - if (player.Grid.Spec.IsVtol) - { - float agl = MathF.Max(0f, player.Y - player.Grid.Spec.HalfHeight - state.Terrain.SampleHeight(player.X, player.Z)); - _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALT {agl:F1}m | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; - _controlsHint.Text = "WASD Fly | Space/C Alt | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net"; - } - else - { - _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; - _controlsHint.Text = "WASD Drive | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net | Wheel Zoom"; - } - } - - _coreHpBar.MaxValue = Math.Max(1f, player.Grid.MaxCoreHp); - _coreHpBar.Value = Math.Max(0f, player.Grid.CoreHp); - _coreHpLabel.Text = $"CORE {player.Grid.CoreHp:F0} / {player.Grid.MaxCoreHp:F0}"; - - _radarTitle.Text = state.MapKind == ArenaMapKind.Sion - ? "SION 3KM • RADAR" - : "DESERT RING • RADAR"; - _mapAttribLabel.Text = state.MapKind == ArenaMapKind.Sion - ? "Data: swisstopo | [M] Switch Map" - : "[M] Switch to Sion 3 km"; - - float distCenter = MathF.Sqrt(player.X * player.X + player.Z * player.Z); - float outside = distCenter - state.Spectators.SafeRadius; - int cleared = state.Spectators.CountClearedFor(player.Id); - int provoked = state.Spectators.CountProvokedFor(player.Id); - - if (outside <= 0f) - { - _safeLabel.Text = $"RING SAFE ({-outside:F0}m margin)" + (provoked > 0 ? $" • {provoked} PROVOKED!" : ""); - _safeLabel.Modulate = provoked > 0 ? OrangeCol : OliveCol; - } - else - { - _safeLabel.Text = $"OUTSIDE +{outside:F0}m — {cleared} CLEARED" + (provoked > 0 ? $" / {provoked} PROVOKED!" : "!"); - _safeLabel.Modulate = RedCol; - } - - int detectedBy = session.LocalDetectedByCount; - if (detectedBy > 0) - { - _detectionLabel.Text = $"DETECTED BY {detectedBy}"; - _detectionLabel.Modulate = RedCol; - } - else - { - _detectionLabel.Text = "CONCEALED (TERRAIN)"; - _detectionLabel.Modulate = OliveCol; - } - - var wave = session.DropWaveState; - if (wave.RespawnCutoffReached) - { - _waveLabel.Text = "FINAL RING — RESPAWNS CLOSED"; - _waveLabel.Modulate = RedCol; - } - else if (wave.NextWaveAtSec is float nextWaveAt) - { - float eta = MathF.Max(0f, nextWaveAt - state.Time); - _waveLabel.Text = $"PATRON WAVE {wave.NextWaveIndex} IN {eta:F0}s • RESP {player.RespawnsRemaining}"; - _waveLabel.Modulate = eta <= 10f ? GoldCol : CyanCol; - } - else - { - _waveLabel.Text = $"WAVE {wave.CurrentWaveIndex} ACTIVE • RESP {player.RespawnsRemaining}"; - _waveLabel.Modulate = OliveCol; - } - - if (net.Mode == NetworkMode.Solo) - { - _netStatusLabel.Visible = false; - } - else - { - _netStatusLabel.Visible = true; - if (net.Mode == NetworkMode.ListenHost) - { - _netStatusLabel.Text = $"{net.StateLabel} • HUMANS {net.ConnectedHumans}/{net.MaxHumans} • [F9] NET"; - _netStatusLabel.Modulate = CyanCol; - } - else if (net.Connected) - { - _netStatusLabel.Text = $"PING {net.PingMs} ms • HUMANS {net.ConnectedHumans}/{net.MaxHumans} • [F9] NET"; - _netStatusLabel.Modulate = net.PingMs > 120 ? OrangeCol : CyanCol; - } - else - { - _netStatusLabel.Text = $"{net.StateLabel} • [F9] NET"; - _netStatusLabel.Modulate = net.LastError is not null ? RedCol : OrangeCol; - } - } + OrbitalPod? localPod = FindLocalContenderPod(session, player); if (_netPanel.Visible) { SyncNetworkPanel(net); } - if (player.IsInDropPod) - { - float agl = localPod is not null - ? MathF.Max(0f, localPod.LastAgl) - : MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z)); - float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY); - float horizSpeed = localPod is not null - ? MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ) - : player.Speed; - _promptLabel.Text = $"ORBITAL INSERTION — ALT {agl:F0}m | HORIZ {horizSpeed:F0} m/s | VERT {velDown:F0} m/s | [WASD] STEER" - + (localPod?.Phase == OrbitalPodPhase.RetroBurn ? " [RETRO BURN]" : ""); - _promptLabel.Visible = true; - } - else - { - _promptLabel.Text = BuildInteractionPrompt(state, player); - _promptLabel.Visible = !string.IsNullOrEmpty(_promptLabel.Text); - } + UpdatePromptCache(state, player, localPod); - // 3D projected world markers (ally chevrons, visible enemy target boxes, offscreen arrows) - _worldMarkers.SetState(session, _projectWorld); - _worldMarkers.QueueRedraw(); - - // Crosshair + Heat Arc / Orbital Altimeter + Directional Incoming Hit Arcs - _crosshair.SetState(state, player, _getCameraYaw(), localPod); - _crosshair.QueueRedraw(); - - // Radar (heading-up with camera yaw) - _radar.SetState(session, _getCameraYaw()); - _radar.QueueRedraw(); - - // Schematic + Cargo _schematic.SetGrid(player.Grid, _selectedCargoIndex); - SyncCargoButtons(player.Grid); + _lastCargoGrid = player.Grid; if (_lastHoveredCell is null) { @@ -529,336 +604,1824 @@ public partial class Hud : CanvasLayer if (_garageExpanded) { - _garageDetails.Text = BuildGarageDetails(player.Grid, _selectedCargoIndex); + UpdateGarageDetailsCache(player.Grid); } - // Broadcast Chyron SyncBroadcastChyron(state.Broadcast); - // Outcome / WaitingForRespawnWave Banner - var outcome = session.LocalOutcome; - if (outcome == ClientMatchOutcome.Victory) + RecomputeLayoutRects(GetViewportSizeSafe(), session); + EmitHudFrame(session); + _emittedThisFrame = true; + _dirtyEmit = false; + } + + private Vector2 GetViewportSizeSafe() + { + Viewport? vp = GetViewport(); + if (vp is not null) { - _outcomeBanner.Visible = true; - _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", OliveCol); - _outcomeLabel.Text = net.Mode == NetworkMode.RemoteClient - ? "VICTORY — LAST RIG STANDING\nNext round starting soon..." - : "VICTORY — LAST RIG STANDING\n[R] New Drop"; - _outcomeLabel.Modulate = OliveCol; + Vector2 vis = vp.GetVisibleRect().Size; + if (vis.X >= 64f && vis.Y >= 64f) + { + _lastViewportSize = vis; + return vis; + } } - else if (outcome == ClientMatchOutcome.Defeat) + return _lastViewportSize; + } + + private static OrbitalPod? FindLocalContenderPod(IClientArenaSession session, ContenderState player) + { + if (!player.IsInDropPod) return null; + var pods = session.ActivePods; + for (int i = 0; i < pods.Count; i++) { - _outcomeBanner.Visible = true; - _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", RedCol); - string title = !player.Alive ? "CHASSIS DESTROYED" : "MATCH COMPLETED — DEFEAT"; - string sub = net.Mode == NetworkMode.RemoteClient - ? (state.Phase == MatchPhase.Completed ? "Waiting for server next round..." : "Spectating live match...") - : "[R] Redeploy"; - _outcomeLabel.Text = $"{title}\n{sub}"; - _outcomeLabel.Modulate = RedCol; + if (pods[i].PodKind == OrbitalPodKind.Contender && pods[i].ContenderId == player.Id) + { + return pods[i]; + } } - else if (player.WaitingForRespawn) + return null; + } + + private void RecomputeLayoutRects(Vector2 vpSize, IClientArenaSession? session) + { + float vw = MathF.Max(320f, vpSize.X); + float vh = MathF.Max(240f, vpSize.Y); + + // Top-Left panel + float tlW = 368f; + float tlH = 152f; + if (session is not null && session.ConnectionStatus.Mode != NetworkMode.Solo) { - _outcomeBanner.Visible = true; - _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", CyanCol); - float eta = wave.NextWaveAtSec is float nxt ? MathF.Max(0f, nxt - state.Time) : 0f; - _outcomeLabel.Text = $"AWAITING PATRON WAVE {wave.NextWaveIndex}\nRESPAWN IN {eta:F1}s (RESP: {player.RespawnsRemaining} LEFT)"; - _outcomeLabel.Modulate = CyanCol; + tlH += 17f; + } + if (_promptLines.Count > 0) + { + tlH += 4f + _promptLines.Count * 16f; + } + _topLeftRect = new Rect2(14f, 14f, tlW, tlH); + + // Top-Right Radar panel + float trW = 234f; + float trH = 264f; + _topRightRect = new Rect2(vw - 14f - trW, 14f, trW, trH); + + // Bottom-Left Schematic + Cargo + optional Garage panel + float gridW = _garageExpanded ? 198f : 180f; + float gridH = _garageExpanded ? 208f : 188f; + const float cargoW = 156f; + float garageW = _garageExpanded ? 186f : 0f; + float blW = 10f + gridW + 8f + cargoW + (_garageExpanded ? 8f + garageW : 0f) + 10f; + + float hoverH = MathF.Max(28f, _hoverLines.Count * 14f); + float leftColH = 18f + gridH + 4f + hoverH; + + int cargoCount = session?.LocalContender.Grid.Cargo.Count ?? 0; + float cargoColH = 18f + (cargoCount > 0 ? cargoCount * 21f : 34f); + float garageColH = _garageExpanded ? MathF.Max(140f, _garageLines.Count * 13.5f + 8f) : 0f; + float blH = 8f + MathF.Max(leftColH, MathF.Max(cargoColH, garageColH)) + 8f; + + _bottomLeftRect = new Rect2(14f, vh - 14f - blH, blW, blH); + _schematicRect = new Rect2(_bottomLeftRect.Position.X + 10f, _bottomLeftRect.Position.Y + 8f + 18f, gridW, gridH); + + if (_bottomLeftBg is not null) + { + if (_bottomLeftBg.Position != _bottomLeftRect.Position) _bottomLeftBg.Position = _bottomLeftRect.Position; + if (_bottomLeftBg.Size != _bottomLeftRect.Size) _bottomLeftBg.Size = _bottomLeftRect.Size; + } + if (_schematic is not null) + { + if (_schematic.Position != _schematicRect.Position) _schematic.Position = _schematicRect.Position; + if (_schematic.Size != _schematicRect.Size) _schematic.Size = _schematicRect.Size; + } + + // Bottom-Right Chyron panel + const float chW = 570f; + const float chH = 92f; + _chyronRect = new Rect2(vw - 14f - chW, vh - 14f - chH, chW, chH); + + // Outcome banner + _outcomeRect = new Rect2(vw * 0.5f - 210f, vh * 0.28f - 40f, 420f, 80f); + _outcomeVisible = false; + if (session is not null) + { + var outcome = session.LocalOutcome; + _outcomeVisible = outcome == ClientMatchOutcome.Victory + || outcome == ClientMatchOutcome.Defeat + || session.LocalContender.WaitingForRespawn; + } + } + + private void EmitHudFrame(IClientArenaSession session) + { + if (_hbCanvas is null || !Visible) + { + return; + } + + Vector2 vpSize = GetViewportSizeSafe(); + var state = session.ViewState; + var player = session.LocalContender; + var net = session.ConnectionStatus; + OrbitalPod? localPod = FindLocalContenderPod(session, player); + + _hbCanvas.BeginFrame(); + + // 1. 3D Projected World Markers (behind panels, above scene) + EmitWorldMarkers(session, state, player, vpSize); + + // 2. Center Crosshair, Thermal Heat Arc, Incoming Hit Arcs, Hit-Marker X, Pod Altimeter + EmitCrosshairAndCombatFeedback(state, player, localPod, vpSize * 0.5f); + + // 3. Top-Left Telemetry Panel + EmitTopLeftPanel(session, state, player, net, localPod); + + // 4. Top-Right Radar Panel + EmitTopRightRadarPanel(session, state); + + // 5. Bottom-Left Schematic Panel Frame + Hardpoint Overlay + Hover + Cargo Rack + Garage + EmitBottomLeftPanel(player.Grid); + + // 6. Bottom-Right Broadcast Chyron + EmitChyronPanel(); + + // 7. Outcome / Awaiting Wave Banner + if (_outcomeVisible) + { + EmitOutcomeBanner(session, state, player, net); + } + + // 8. Optional [F9] Network panel corner brackets + if (_netPanel.Visible) + { + _hbCanvas.DrawPanelFrame(_netPanel.GetGlobalRect(), new Color(0f, 0f, 0f, 0f), CyanCol, CyanCol, cornerLen: 14f, borderPx: 1.5f, drawBg: false); + } + + _hbCanvas.EndFrameAndSubmit(); + } + + // ------------------------------------------------------------------------- + // 1. Top-Left Panel (0 GC allocs) + // ------------------------------------------------------------------------- + private void EmitTopLeftPanel( + IClientArenaSession session, + MatchState state, + ContenderState player, + NetworkStatusSnapshot net, + OrbitalPod? localPod) + { + _hbCanvas.DrawPanelFrame(_topLeftRect, BgDark, BorderCol, OliveCol, cornerLen: 12f, borderPx: 1.5f); + + float x = _topLeftRect.Position.X + 10f; + float rightX = _topLeftRect.End.X - 10f; + float y = _topLeftRect.Position.Y + 8f; + + int aliveCount = 0; + for (int i = 0; i < state.Contenders.Count; i++) + { + if (state.Contenders[i].Alive) aliveCount++; + } + + // Header + Dorsal/Coronal/Pod badge + if (player.IsInDropPod) + { + bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; + _hbCanvas.DrawText("ORBITAL DROP POD", x, y + 14f, 16f, TextLight, wght: 700f); + ReadOnlySpan badge = burning ? "RETRO BURN" : "FREEFALL"; + Color bCol = burning ? OrangeCol : CyanCol; + float bw = _hbCanvas.MeasureTextWidth(badge, 12.5f, wght: 600f); + _hbCanvas.DrawText(badge, rightX - bw, y + 13f, 12.5f, bCol, wght: 600f); } else { - _outcomeBanner.Visible = false; - } - } - - private void BuildCrosshair() - { - Shader vigShader = GD.Load("res://hud_vignette.gdshader") - ?? throw new InvalidOperationException("Failed to load res://hud_vignette.gdshader"); - _vignetteMat = new ShaderMaterial { Shader = vigShader }; - _vignetteRect = new ColorRect - { - Name = "HudVignette", - Material = _vignetteMat, - MouseFilter = Control.MouseFilterEnum.Ignore, - Visible = false - }; - _vignetteRect.SetAnchorsPreset(Control.LayoutPreset.FullRect); - AddChild(_vignetteRect); - - _worldMarkers = new WorldMarkerOverlay { Name = "WorldMarkers" }; - _worldMarkers.SetAnchorsPreset(Control.LayoutPreset.FullRect); - _worldMarkers.MouseFilter = Control.MouseFilterEnum.Ignore; - AddChild(_worldMarkers); - - _crosshair = new CrosshairOverlay { Name = "Crosshair" }; - _crosshair.SetAnchorsPreset(Control.LayoutPreset.FullRect); - _crosshair.MouseFilter = Control.MouseFilterEnum.Ignore; - AddChild(_crosshair); - } - - private void BuildTopLeft() - { - var panel = CreateStyledPanel(OliveCol); - _topLeftPanel = panel; - panel.AnchorLeft = 0f; - panel.AnchorTop = 0f; - panel.OffsetLeft = 14f; - panel.OffsetTop = 14f; - panel.CustomMinimumSize = new Vector2(360f, 0f); - AddChild(panel); - - var vbox = new VBoxContainer { Theme = null }; - vbox.AddThemeConstantOverride("separation", 5); - panel.AddChild(vbox); - - var headRow = new HBoxContainer(); - headRow.AddThemeConstantOverride("separation", 10); - vbox.AddChild(headRow); - - _chassisHeader = new Label { Text = "DUNE BUGGY", SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; - _chassisHeader.AddThemeColorOverride("font_color", TextLight); - _chassisHeader.AddThemeFontSizeOverride("font_size", 17); - headRow.AddChild(_chassisHeader); - - _planeBadge = new Label { Text = "DORSAL" }; - _planeBadge.AddThemeFontSizeOverride("font_size", 13); - headRow.AddChild(_planeBadge); - - var hpRow = new HBoxContainer(); - hpRow.AddThemeConstantOverride("separation", 8); - vbox.AddChild(hpRow); - - _coreHpBar = new ProgressBar - { - ShowPercentage = false, - SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, - CustomMinimumSize = new Vector2(180f, 16f) - }; - var barBg = new StyleBoxFlat { BgColor = BgInner, BorderColor = BorderCol }; - barBg.SetBorderWidthAll(1); - var barFill = new StyleBoxFlat { BgColor = OliveCol }; - _coreHpBar.AddThemeStyleboxOverride("background", barBg); - _coreHpBar.AddThemeStyleboxOverride("fill", barFill); - hpRow.AddChild(_coreHpBar); - - _coreHpLabel = new Label { Text = "CORE 100 / 100" }; - _coreHpLabel.AddThemeColorOverride("font_color", TextLight); - _coreHpLabel.AddThemeFontSizeOverride("font_size", 13); - hpRow.AddChild(_coreHpLabel); - - _statsLabel = new Label { Text = "SPD 0.0 m/s" }; - _statsLabel.AddThemeColorOverride("font_color", TextMuted); - _statsLabel.AddThemeFontSizeOverride("font_size", 13); - vbox.AddChild(_statsLabel); - - _safeLabel = new Label { Text = "RING SAFE" }; - _safeLabel.AddThemeFontSizeOverride("font_size", 13); - vbox.AddChild(_safeLabel); - - _detectionLabel = new Label { Text = "CONCEALED (TERRAIN)" }; - _detectionLabel.AddThemeFontSizeOverride("font_size", 13); - vbox.AddChild(_detectionLabel); - - _waveLabel = new Label { Text = "WAVE 0" }; - _waveLabel.AddThemeFontSizeOverride("font_size", 12); - _waveLabel.AddThemeColorOverride("font_color", CyanCol); - vbox.AddChild(_waveLabel); - - _netStatusLabel = new Label { Text = "", Visible = false }; - _netStatusLabel.AddThemeFontSizeOverride("font_size", 12); - vbox.AddChild(_netStatusLabel); - - _promptLabel = new Label - { - Text = "", - Visible = false, - AutowrapMode = TextServer.AutowrapMode.Word, - CustomMinimumSize = new Vector2(336f, 0f) - }; - _promptLabel.AddThemeColorOverride("font_color", CyanCol); - _promptLabel.AddThemeFontSizeOverride("font_size", 13); - vbox.AddChild(_promptLabel); - - _controlsHint = new Label { Text = "WASD Drive | Mouse Aim | LMB Fire | E Loot/Swap | Tab Garage | Wheel Zoom" }; - _controlsHint.AddThemeColorOverride("font_color", TextMuted); - _controlsHint.AddThemeFontSizeOverride("font_size", 11); - vbox.AddChild(_controlsHint); - } - - private void BuildTopRightRadar() - { - var panel = CreateStyledPanel(OrangeCol); - _topRightPanel = panel; - panel.AnchorLeft = 1f; - panel.AnchorRight = 1f; - panel.AnchorTop = 0f; - panel.OffsetLeft = -246f; - panel.OffsetRight = -14f; - panel.OffsetTop = 14f; - AddChild(panel); - - var vbox = new VBoxContainer(); - vbox.AddThemeConstantOverride("separation", 4); - panel.AddChild(vbox); - - _radarTitle = new Label { Text = "SION 3KM • RADAR", HorizontalAlignment = HorizontalAlignment.Center }; - _radarTitle.AddThemeColorOverride("font_color", OrangeCol); - _radarTitle.AddThemeFontSizeOverride("font_size", 12); - vbox.AddChild(_radarTitle); - - _radar = new RadarWidget - { - CustomMinimumSize = new Vector2(214f, 214f) - }; - vbox.AddChild(_radar); - - _mapAttribLabel = new Label { Text = "Data: swisstopo | [M] Switch Map", HorizontalAlignment = HorizontalAlignment.Center }; - _mapAttribLabel.AddThemeColorOverride("font_color", TextMuted); - _mapAttribLabel.AddThemeFontSizeOverride("font_size", 10); - vbox.AddChild(_mapAttribLabel); - } - - private void BuildBottomLeftSchematic() - { - _bottomLeftPanel = CreateStyledPanel(OrangeCol); - _bottomLeftPanel.AnchorLeft = 0f; - _bottomLeftPanel.AnchorTop = 1f; - _bottomLeftPanel.AnchorBottom = 1f; - _bottomLeftPanel.GrowVertical = Control.GrowDirection.Begin; - _bottomLeftPanel.OffsetLeft = 14f; - _bottomLeftPanel.OffsetTop = -248f; - _bottomLeftPanel.OffsetBottom = -14f; - AddChild(_bottomLeftPanel); - - var hbox = new HBoxContainer(); - hbox.AddThemeConstantOverride("separation", 8); - _bottomLeftPanel.AddChild(hbox); - - var leftCol = new VBoxContainer(); - leftCol.AddThemeConstantOverride("separation", 4); - hbox.AddChild(leftCol); - - var headRow = new HBoxContainer(); - headRow.AddThemeConstantOverride("separation", 6); - leftCol.AddChild(headRow); - - var title = new Label - { - Text = "HARDPOINTS & HEAT", - SizeFlagsHorizontal = Control.SizeFlags.ExpandFill - }; - title.AddThemeColorOverride("font_color", OrangeCol); - title.AddThemeFontSizeOverride("font_size", 12); - headRow.AddChild(title); - - _schematic = new InventoryGridControl - { - CustomMinimumSize = new Vector2(180f, 188f) - }; - _schematic.HardpointClicked += OnHardpointClicked; - _schematic.HoverChanged += OnSchematicHoverChanged; - leftCol.AddChild(_schematic); - - _hoverLabel = new Label - { - Text = "HOVER CELL FOR TELEMETRY", - AutowrapMode = TextServer.AutowrapMode.Word, - CustomMinimumSize = new Vector2(180f, 28f) - }; - _hoverLabel.AddThemeColorOverride("font_color", TextMuted); - _hoverLabel.AddThemeFontSizeOverride("font_size", 10); - leftCol.AddChild(_hoverLabel); - - var rightCol = new VBoxContainer { CustomMinimumSize = new Vector2(156f, 0f) }; - rightCol.AddThemeConstantOverride("separation", 3); - hbox.AddChild(rightCol); - - _cargoHeader = new Label { Text = "SALVAGE CARGO (0/4)" }; - _cargoHeader.AddThemeColorOverride("font_color", OliveCol); - _cargoHeader.AddThemeFontSizeOverride("font_size", 11); - rightCol.AddChild(_cargoHeader); - - _cargoList = new VBoxContainer(); - _cargoList.AddThemeConstantOverride("separation", 2); - rightCol.AddChild(_cargoList); - - _garageDetails = new Label { Visible = false, AutowrapMode = TextServer.AutowrapMode.Word }; - _garageDetails.AddThemeColorOverride("font_color", TextMuted); - _garageDetails.AddThemeFontSizeOverride("font_size", 10); - _garageDetails.CustomMinimumSize = new Vector2(178f, 0f); - hbox.AddChild(_garageDetails); - } - - private void BuildBottomCenterChyron() - { - _chyronPanel = CreateStyledPanel(GoldCol); - var panel = _chyronPanel; - panel.AnchorLeft = 1f; - panel.AnchorRight = 1f; - panel.AnchorTop = 1f; - panel.AnchorBottom = 1f; - panel.GrowHorizontal = Control.GrowDirection.Begin; - panel.GrowVertical = Control.GrowDirection.Begin; - panel.OffsetLeft = -584f; - panel.OffsetRight = -14f; - panel.OffsetTop = -104f; - panel.OffsetBottom = -14f; - AddChild(panel); - - var vbox = new VBoxContainer(); - vbox.AddThemeConstantOverride("separation", 3); - panel.AddChild(vbox); - - var header = new Label { Text = "IMPERIAL BROADCAST FEED" }; - header.AddThemeColorOverride("font_color", GoldCol); - header.AddThemeFontSizeOverride("font_size", 11); - vbox.AddChild(header); - - _chyronBox = new VBoxContainer(); - _chyronBox.AddThemeConstantOverride("separation", 2); - vbox.AddChild(_chyronBox); - - for (int i = 0; i < _chyronLabels.Length; i++) - { - var lbl = new Label + string rawName = player.Grid.Spec.Name; + if (!ReferenceEquals(_cachedChassisName, rawName)) { - Visible = false, - AutowrapMode = TextServer.AutowrapMode.Word + _cachedChassisName = rawName; + _cachedChassisUpper = rawName.ToUpperInvariant(); + } + _hbCanvas.DrawText(_cachedChassisUpper, x, y + 14f, 16f, TextLight, wght: 700f); + bool isCoronal = player.Grid.Spec.Plane == GridPlane.Coronal; + ReadOnlySpan badge = isCoronal ? "CORONAL" : "DORSAL"; + Color bCol = isCoronal ? CyanCol : OliveCol; + float bw = _hbCanvas.MeasureTextWidth(badge, 12.5f, wght: 600f); + _hbCanvas.DrawText(badge, rightX - bw, y + 13f, 12.5f, bCol, wght: 600f); + } + y += 22f; + + // Core HP vector bar + label + float maxCore = MathF.Max(1f, player.Grid.MaxCoreHp); + float coreHp = MathF.Max(0f, player.Grid.CoreHp); + float hpFrac = Math.Clamp(coreHp / maxCore, 0f, 1f); + + SpanWriter sw = new(_scratch); + sw.Append("CORE "); + sw.AppendFloat(coreHp, "F0"); + sw.Append(" / "); + sw.AppendFloat(maxCore, "F0"); + ReadOnlySpan hpSpan = sw.Span; + float hpLabelW = _hbCanvas.MeasureTextWidth(hpSpan, 12.5f, wght: 550f); + float barW = MathF.Max(80f, rightX - x - hpLabelW - 10f); + + _hbCanvas.DrawRectFilled(x, y, barW, 15f, BgInner); + _hbCanvas.DrawRectOutline(x, y, barW, 15f, 1.0f, BorderCol); + if (hpFrac > 0.001f) + { + Color fillCol = hpFrac < 0.35f ? RedCol : OliveCol; + _hbCanvas.DrawRectFilled(x + 1f, y + 1f, MathF.Max(1f, (barW - 2f) * hpFrac), 13f, fillCol); + } + _hbCanvas.DrawText(hpSpan, x + barW + 8f, y + 12f, 12.5f, TextLight, wght: 550f); + y += 21f; + + // Stats line + sw = new SpanWriter(_scratch); + if (player.IsInDropPod) + { + float agl = localPod is not null + ? MathF.Max(0f, localPod.LastAgl) + : MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z)); + float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY); + float horizSpeed = localPod is not null + ? MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ) + : player.Speed; + sw.Append("ALT "); sw.AppendFloat(agl, "F0"); sw.Append("m | HORIZ "); + sw.AppendFloat(horizSpeed, "F0"); sw.Append(" m/s | VERT "); + sw.AppendFloat(velDown, "F0"); sw.Append(" m/s | ALIVE "); + sw.AppendInt(aliveCount); sw.Append(" / "); sw.AppendInt(state.Contenders.Count); + } + else if (player.Grid.Spec.IsVtol) + { + float agl = MathF.Max(0f, player.Y - player.Grid.Spec.HalfHeight - state.Terrain.SampleHeight(player.X, player.Z)); + sw.Append("SPD "); sw.AppendFloat(player.Speed, "F1"); sw.Append(" m/s | ALT "); + sw.AppendFloat(agl, "F1"); sw.Append("m | ALIVE "); + sw.AppendInt(aliveCount); sw.Append(" / "); sw.AppendInt(state.Contenders.Count); + sw.Append(" | KILLS "); sw.AppendInt(player.Kills); + } + else + { + sw.Append("SPD "); sw.AppendFloat(player.Speed, "F1"); sw.Append(" m/s | ALIVE "); + sw.AppendInt(aliveCount); sw.Append(" / "); sw.AppendInt(state.Contenders.Count); + sw.Append(" | KILLS "); sw.AppendInt(player.Kills); + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 12f, TextMuted, wght: 400f); + y += 18f; + + // Safe ring status + float distCenter = MathF.Sqrt(player.X * player.X + player.Z * player.Z); + float outside = distCenter - state.Spectators.SafeRadius; + int cleared = state.Spectators.CountClearedFor(player.Id); + int provoked = state.Spectators.CountProvokedFor(player.Id); + + sw = new SpanWriter(_scratch); + Color safeCol; + if (outside <= 0f) + { + sw.Append("RING SAFE ("); sw.AppendFloat(-outside, "F0"); sw.Append("m margin)"); + if (provoked > 0) + { + sw.Append(" • "); sw.AppendInt(provoked); sw.Append(" PROVOKED!"); + } + safeCol = provoked > 0 ? OrangeCol : OliveCol; + } + else + { + sw.Append("OUTSIDE +"); sw.AppendFloat(outside, "F0"); sw.Append("m — "); + sw.AppendInt(cleared); sw.Append(" CLEARED"); + if (provoked > 0) + { + sw.Append(" / "); sw.AppendInt(provoked); sw.Append(" PROVOKED!"); + } + else + { + sw.Append("!"); + } + safeCol = RedCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 12.5f, safeCol, wght: 500f); + y += 18f; + + // Detection status + int detectedBy = session.LocalDetectedByCount; + sw = new SpanWriter(_scratch); + Color detCol; + if (detectedBy > 0) + { + sw.Append("DETECTED BY "); sw.AppendInt(detectedBy); + detCol = RedCol; + } + else + { + sw.Append("CONCEALED (TERRAIN)"); + detCol = OliveCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 12.5f, detCol, wght: 500f); + y += 18f; + + // Drop wave / respawn status + var wave = session.DropWaveState; + sw = new SpanWriter(_scratch); + Color waveCol; + if (wave.RespawnCutoffReached) + { + sw.Append("FINAL RING — RESPAWNS CLOSED"); + waveCol = RedCol; + } + else if (wave.NextWaveAtSec is float nextWaveAt) + { + float eta = MathF.Max(0f, nextWaveAt - state.Time); + sw.Append("PATRON WAVE "); sw.AppendInt(wave.NextWaveIndex); + sw.Append(" IN "); sw.AppendFloat(eta, "F0"); + sw.Append("s • RESP "); sw.AppendInt(player.RespawnsRemaining); + waveCol = eta <= 10f ? GoldCol : CyanCol; + } + else + { + sw.Append("WAVE "); sw.AppendInt(wave.CurrentWaveIndex); + sw.Append(" ACTIVE • RESP "); sw.AppendInt(player.RespawnsRemaining); + waveCol = OliveCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 11.8f, waveCol, wght: 450f); + y += 17f; + + // Network status (only non-Solo) + if (net.Mode != NetworkMode.Solo) + { + sw = new SpanWriter(_scratch); + Color netCol; + if (net.Mode == NetworkMode.ListenHost) + { + sw.Append(net.StateLabel); sw.Append(" • HUMANS "); + sw.AppendInt(net.ConnectedHumans); sw.Append("/"); sw.AppendInt(net.MaxHumans); + sw.Append(" • [F9] NET"); + netCol = CyanCol; + } + else if (net.Connected) + { + sw.Append("PING "); sw.AppendInt(net.PingMs); sw.Append(" ms • HUMANS "); + sw.AppendInt(net.ConnectedHumans); sw.Append("/"); sw.AppendInt(net.MaxHumans); + sw.Append(" • [F9] NET"); + netCol = net.PingMs > 120 ? OrangeCol : CyanCol; + } + else + { + sw.Append(net.StateLabel); sw.Append(" • [F9] NET"); + netCol = net.LastError is not null ? RedCol : OrangeCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 11.8f, netCol, wght: 450f); + y += 17f; + } + + // Interaction or orbital prompt + if (_promptLines.Count > 0) + { + y += 4f; + for (int i = 0; i < _promptLines.Count; i++) + { + _hbCanvas.DrawText(_promptLines[i], x, y + 11f, 12f, CyanCol, wght: 550f); + y += 16f; + } + } + + // Controls hint + ReadOnlySpan hint = player.IsInDropPod + ? "WASD Steer Pod | Mouse Look | Retro-Burn Auto | Wheel Zoom" + : (player.Grid.Spec.IsVtol + ? "WASD Fly | Space/C Alt | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net" + : "WASD Drive | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net | Wheel Zoom"); + _hbCanvas.DrawText(hint, x, _topLeftRect.End.Y - 10f, 10.2f, TextMuted, wght: 350f); + } + + // ------------------------------------------------------------------------- + // 2. Top-Right Radar Panel (0 GC allocs) + // ------------------------------------------------------------------------- + private void EmitTopRightRadarPanel(IClientArenaSession session, MatchState state) + { + _hbCanvas.DrawPanelFrame(_topRightRect, BgDark, BorderCol, OrangeCol, cornerLen: 12f, borderPx: 1.5f); + + float panelCenterX = _topRightRect.Position.X + _topRightRect.Size.X * 0.5f; + ReadOnlySpan title = state.MapKind == ArenaMapKind.Sion + ? "SION 3KM • RADAR" + : "DESERT RING • RADAR"; + float titleW = _hbCanvas.MeasureTextWidth(title, 12f, wght: 650f); + _hbCanvas.DrawText(title, panelCenterX - titleW * 0.5f, _topRightRect.Position.Y + 20f, 12f, OrangeCol, wght: 650f); + + Vector2 center = new(panelCenterX, _topRightRect.Position.Y + 26f + 107f); + const float radius = 214f * 0.47f; + float maxBlipRadius = MathF.Max(4f, radius - 3f); + float arenaHalf = MathF.Max(1f, state.Terrain.MapHalfExtent); + float scale = radius / arenaHalf; + float cameraYaw = _getCameraYaw(); + int localId = session.LocalContenderId; + + _hbCanvas.DrawCircleFilled(center.X, center.Y, radius, BgInner); + _hbCanvas.DrawCircleRing(center.X, center.Y, radius, 1.5f, BorderCol); + _hbCanvas.DrawLineSegment(center.X, center.Y - radius, center.X, center.Y - radius + 6f, 2.0f, CyanCol); + + // Safe Circle + float safePx = MathF.Min(state.Spectators.SafeRadius * scale, maxBlipRadius); + _hbCanvas.DrawCircleRing(center.X, center.Y, safePx, 1.6f, OrangeCol); + + // Ground drops + for (int i = 0; i < state.GroundDrops.Count; i++) + { + var d = state.GroundDrops[i]; + if (d.PickedUp) continue; + var p = ClampToRadarDisc(center, MathF.Max(4f, radius - 4f), WorldToRadar(center, scale, d.X, d.Z, cameraYaw)); + if (d.Chassis is not null) + { + _hbCanvas.DrawRectFilled(p.X - 2.5f, p.Y - 2.5f, 5f, 5f, CyanCol); + } + else if (d.Module is { IsImperial: true }) + { + _hbCanvas.DrawCircleFilled(p.X, p.Y, 3.0f, GoldCol); + } + } + + // Active descending Orbital Pods + var pods = session.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + var pod = pods[i]; + if (pod.Phase == OrbitalPodPhase.Popped) continue; + var pp = ClampToRadarDisc(center, MathF.Max(4f, radius - 5f), WorldToRadar(center, scale, pod.X, pod.Z, cameraYaw)); + if (pod.PodKind == OrbitalPodKind.Contender) + { + bool isLocalPod = pod.ContenderId == localId; + bool isAllyPod = !isLocalPod && state.AreAllies(localId, pod.ContenderId); + if (isAllyPod) + { + _hbCanvas.DrawDiamond(pp.X, pp.Y, 4.6f, AlliedCol); + } + else + { + Color pCol = isLocalPod ? OliveCol : OrangeCol; + float sz = isLocalPod ? 10.5f : 7.0f; + _hbCanvas.DrawChevron(pp.X, pp.Y, sz, -MathF.PI * 0.5f, pCol); + } + } + else + { + bool isImp = pod.WaveIndex > 0 || pod.Module?.IsImperial == true; + _hbCanvas.DrawDiamond(pp.X, pp.Y, 3.2f, isImp ? GoldCol : CyanCol); + } + } + + // Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory) + var contenderContacts = session.LocalContenderContacts; + var spectatorContacts = session.LocalSpectatorContacts; + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive) continue; + + spectatorContacts.TryGetValue(s.Id, out var mem); + if (!MatchState.IsContactOnRadar(mem)) continue; + + bool live = mem!.VisibleToPlayer; + bool hasLivePos = session.IsSpectatorVisible(s.Id) && (live || mem.FaintHorizonPing); + if (!hasLivePos && !mem.HasEverBeenSeen) continue; + + float drawX = hasLivePos ? s.X : mem.LastSeenX; + float drawZ = hasLivePos ? s.Z : mem.LastSeenZ; + float blipR = 1.6f + s.RadarSignature * 3.1f; + float specClampR = MathF.Max(4f, radius - blipR - 1f); + var p = ClampToRadarDisc(center, specClampR, WorldToRadar(center, scale, drawX, drawZ, cameraYaw)); + + Color col = s.Tier switch + { + SpectatorTier.Tourist => GoldCol, + SpectatorTier.Patron => PatronColor, + _ => RedCol }; - lbl.AddThemeFontSizeOverride("font_size", 11); - lbl.AddThemeColorOverride("font_color", TextMuted); - _chyronBox.AddChild(lbl); - _chyronLabels[i] = lbl; + + if (live && s.Stance != SpectatorStance.Neutral && s.HasTargetLos && s.TargetContenderId.HasValue) + { + int tid = s.TargetContenderId.Value; + if (tid >= 0 && tid < state.Contenders.Count && state.Contenders[tid].Alive) + { + var tgt = state.Contenders[tid]; + bool targetVisible = tgt.Id == localId || + (session.IsContenderVisible(tgt.Id) && contenderContacts.TryGetValue(tgt.Id, out var tgtMem) && tgtMem.VisibleToPlayer); + if (targetVisible) + { + float tgtClampR = MathF.Max(4f, radius - (tgt.Id == localId ? 7.5f : 4.3f)); + var tp = ClampToRadarDisc(center, tgtClampR, WorldToRadar(center, scale, tgt.X, tgt.Z, cameraYaw)); + _hbCanvas.DrawLineSegment(p.X, p.Y, tp.X, tp.Y, 1.3f, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f)); + } + } + col = RedCol; + } + + if (!live) + { + float alpha = mem.FaintHorizonPing + ? 0.42f + : Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); + Color ghostCol = mem.FaintHorizonPing ? GoldCol : col; + _hbCanvas.DrawCircleFilled(p.X, p.Y, blipR, new Color(ghostCol.R, ghostCol.G, ghostCol.B, alpha)); + } + else + { + _hbCanvas.DrawCircleFilled(p.X, p.Y, blipR, col); + } + } + + // Contenders (player live chevron; allies diamond; rivals LOS + 5s ghost memory) + float sinY = MathF.Sin(cameraYaw); + float cosY = MathF.Cos(cameraYaw); + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) continue; + + if (c.Id == localId) + { + float playerClampR = MathF.Max(4f, radius - 6.5f - 1f); + var (lPos, _, _) = session.GetInterpolatedContenderPose(localId, 1f); + var p = ClampToRadarDisc(center, playerClampR, WorldToRadar(center, scale, lPos.X, lPos.Z, cameraYaw)); + var dir = new Vector2( + -MathF.Sin(c.Yaw) * cosY + MathF.Cos(c.Yaw) * sinY, + -(MathF.Sin(c.Yaw) * sinY + MathF.Cos(c.Yaw) * cosY)); + float ang = MathF.Atan2(dir.Y, dir.X); + _hbCanvas.DrawChevron(p.X, p.Y, 12.5f, ang, OliveCol); + continue; + } + + if (state.AreAllies(localId, c.Id)) + { + float allyClampR = MathF.Max(4f, radius - 4.6f - 1f); + var (aPos, _, _) = session.GetInterpolatedContenderPose(c.Id, 1f); + var p = ClampToRadarDisc(center, allyClampR, WorldToRadar(center, scale, aPos.X, aPos.Z, cameraYaw)); + _hbCanvas.DrawDiamond(p.X, p.Y, 4.6f, AlliedCol); + continue; + } + + contenderContacts.TryGetValue(c.Id, out var mem); + if (!MatchState.IsContactOnRadar(mem)) continue; + + if (mem!.VisibleToPlayer) + { + float rivalClampR = MathF.Max(4f, radius - 3.3f - 1f); + float rx = session.IsContenderVisible(c.Id) ? c.X : mem.LastSeenX; + float rz = session.IsContenderVisible(c.Id) ? c.Z : mem.LastSeenZ; + var p = ClampToRadarDisc(center, rivalClampR, WorldToRadar(center, scale, rx, rz, cameraYaw)); + _hbCanvas.DrawCircleFilled(p.X, p.Y, 3.3f, OrangeCol); + } + else + { + float ghostClampR = MathF.Max(4f, radius - 2.8f - 1f); + var p = ClampToRadarDisc(center, ghostClampR, WorldToRadar(center, scale, mem.LastSeenX, mem.LastSeenZ, cameraYaw)); + float alpha = Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); + _hbCanvas.DrawCircleFilled(p.X, p.Y, 2.8f, new Color(OrangeCol.R, OrangeCol.G, OrangeCol.B, alpha)); + } + } + + ReadOnlySpan attrib = state.MapKind == ArenaMapKind.Sion + ? "Data: swisstopo | [M] Switch Map" + : "[M] Switch to Sion 3 km"; + float attribW = _hbCanvas.MeasureTextWidth(attrib, 10f, wght: 350f); + _hbCanvas.DrawText(attrib, panelCenterX - attribW * 0.5f, _topRightRect.End.Y - 9f, 10f, TextMuted, wght: 350f); + } + + private static Vector2 WorldToRadar(Vector2 center, float scale, float wx, float wz, float camYaw) + { + float sinY = MathF.Sin(camYaw); + float cosY = MathF.Cos(camYaw); + float rx = -wx * cosY + wz * sinY; + float fy = wx * sinY + wz * cosY; + return center + new Vector2(rx, -fy) * scale; + } + + private static Vector2 ClampToRadarDisc(Vector2 center, float maxRadius, Vector2 pt) + { + Vector2 delta = pt - center; + float dist = delta.Length(); + if (dist > maxRadius && dist > 1e-4f) + { + return center + delta * (maxRadius / dist); + } + return pt; + } + + // ------------------------------------------------------------------------- + // 3. Crosshair, Heat Arc, Incoming Hit Arcs, Hit-Marker X, Pod Altimeter + // ------------------------------------------------------------------------- + private void EmitCrosshairAndCombatFeedback( + MatchState state, + ContenderState player, + OrbitalPod? localPod, + Vector2 center) + { + const float gap = 6f; + const float tick = 10f; + bool allDisabled = player.Alive && + player.InArcWeaponCount == 0 && player.OutOfArcWeaponCount == 0 && player.DisabledWeaponCount > 0; + bool outOfArc = player.Alive && player.AllWeaponsOutOfArc; + Color retCol = (outOfArc || allDisabled) + ? new Color(RedCol.R, RedCol.G, RedCol.B, 0.95f) + : new Color(TextLight.R, TextLight.G, TextLight.B, 0.88f); + + _hbCanvas.DrawCircleFilled(center.X, center.Y, 1.8f, retCol); + _hbCanvas.DrawLineSegment(center.X - gap - tick, center.Y, center.X - gap, center.Y, 1.6f, retCol); + _hbCanvas.DrawLineSegment(center.X + gap, center.Y, center.X + gap + tick, center.Y, 1.6f, retCol); + _hbCanvas.DrawLineSegment(center.X, center.Y - gap - tick, center.X, center.Y - gap, 1.6f, retCol); + _hbCanvas.DrawLineSegment(center.X, center.Y + gap, center.X, center.Y + gap + tick, 1.6f, retCol); + + // Outgoing hit-marker X-flash + if (_hitMarkerRemaining > 0f && _hitMarkerDuration > 0.001f && _hitMarkerKind != HitMarkerKind.None) + { + float frac = Math.Clamp(_hitMarkerRemaining / _hitMarkerDuration, 0f, 1f); + float pop = 1.0f + (1.0f - frac) * 0.25f; + Color xCol = _hitMarkerKind switch + { + HitMarkerKind.Kill => new Color(RedCol.R, RedCol.G, RedCol.B, frac * 0.98f), + HitMarkerKind.Core => new Color(1.0f, 0.28f, 0.16f, frac * 0.95f), + _ => new Color(1.0f, 0.95f, 0.78f, frac * 0.92f) + }; + float xWidth = _hitMarkerKind == HitMarkerKind.Armor ? 2.0f : 2.8f; + float rIn = 6.5f * pop; + float rOut = (_hitMarkerKind == HitMarkerKind.Armor ? 13.5f : 15.5f) * pop; + const float diag = 0.70710678f; + for (int q = 0; q < 4; q++) + { + float sx = (q & 1) == 0 ? 1f : -1f; + float sy = (q & 2) == 0 ? 1f : -1f; + Vector2 dir = new(sx * diag, sy * diag); + _hbCanvas.DrawLineSegment( + center.X + dir.X * rIn, center.Y + dir.Y * rIn, + center.X + dir.X * rOut, center.Y + dir.Y * rOut, + xWidth, xCol); + if (_hitMarkerKind == HitMarkerKind.Kill) + { + _hbCanvas.DrawLineSegment( + center.X + dir.X * (rOut + 4f), center.Y + dir.Y * (rOut + 4f), + center.X + dir.X * (rOut + 10.5f), center.Y + dir.Y * (rOut + 10.5f), + 2.2f, new Color(GoldCol.R, GoldCol.G, GoldCol.B, frac * 0.95f)); + } + } + } + + if (allDisabled) + { + ReadOnlySpan msg = "WEAPONS STRIPPED"; + float mw = _hbCanvas.MeasureTextWidth(msg, 11.5f, wght: 600f); + _hbCanvas.DrawText(msg, center.X - mw * 0.5f, center.Y + 38f, 11.5f, RedCol, wght: 600f); + } + else if (outOfArc) + { + ReadOnlySpan msg = "OUT OF ARC"; + float mw = _hbCanvas.MeasureTextWidth(msg, 11.5f, wght: 600f); + _hbCanvas.DrawText(msg, center.X - mw * 0.5f, center.Y + 38f, 11.5f, RedCol, wght: 600f); + } + + if (!player.Alive) + { + return; + } + + if (player.IsInDropPod) + { + float agl = localPod is not null ? MathF.Max(0f, localPod.LastAgl) : 0f; + float vel = localPod is not null ? MathF.Max(0f, -localPod.VelY) : 0f; + float horizSpeed = localPod is not null + ? MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ) + : player.Speed; + bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; + Color bracketCol = burning ? OrangeCol : CyanCol; + + float startAlt = OrbitalPodPreset.GetStartAltAgl(OrbitalPodKind.Contender, state.MapKind); + float altFrac = Math.Clamp(agl / MathF.Max(1f, startAlt), 0f, 1f); + const float barX = 72f; + const float barH = 76f; + float topY = center.Y - barH * 0.5f; + Color trackCol = new(BorderCol.R, BorderCol.G, BorderCol.B, 0.55f); + _hbCanvas.DrawLineSegment(center.X - barX, topY, center.X - barX, topY + barH, 2.0f, trackCol); + _hbCanvas.DrawLineSegment(center.X + barX, topY, center.X + barX, topY + barH, 2.0f, trackCol); + + float fillH = barH * altFrac; + if (fillH > 0.5f) + { + _hbCanvas.DrawLineSegment(center.X - barX, topY + barH - fillH, center.X - barX, topY + barH, 3.0f, bracketCol); + _hbCanvas.DrawLineSegment(center.X + barX, topY + barH - fillH, center.X + barX, topY + barH, 3.0f, bracketCol); + } + + SpanWriter sw = new(_scratch); + sw.Append("ALT "); sw.AppendFloat(agl, "F0"); sw.Append("m | HORIZ "); + sw.AppendFloat(horizSpeed, "F0"); sw.Append(" m/s | VERT "); + sw.AppendFloat(vel, "F0"); sw.Append(" m/s"); + float tw = _hbCanvas.MeasureTextWidth(sw.Span, 11.5f, wght: 500f); + _hbCanvas.DrawText(sw.Span, center.X - tw * 0.5f, center.Y + 56f, 11.5f, bracketCol, wght: 500f); + + if (burning) + { + ReadOnlySpan burnTxt = "RETRO BURN ACTIVE"; + float bw = _hbCanvas.MeasureTextWidth(burnTxt, 11.5f, wght: 650f); + _hbCanvas.DrawText(burnTxt, center.X - bw * 0.5f, center.Y - 50f, 11.5f, OrangeCol, wght: 650f); + } + return; + } + + // Thermal heat-arc indicator around crosshair + float heatRatio = 0f; + bool overPlateau = false; + var mounted = player.Grid.Mounted; + for (int i = 0; i < mounted.Count; i++) + { + var m = mounted[i]; + if (m.Spec.Kind == HardpointKind.Weapon) + { + float r = Math.Clamp( + (m.CurrentTemp - ChassisGrid.AmbientTemp) / MathF.Max(1f, m.Spec.MaxTemp - ChassisGrid.AmbientTemp), + 0f, 1f); + if (r > heatRatio) heatRatio = r; + if (m.CurrentTemp > m.Spec.OptimalTemp + m.Spec.PlateauWidth * 0.5f) + { + overPlateau = true; + } + } + } + + const float arcRadius = 21f; + const float startAngle = -MathF.PI * 0.75f; + const float maxSweep = MathF.PI * 1.5f; + _hbCanvas.DrawArcStrokeDynamic( + center.X, center.Y, arcRadius, 2.0f, + startAngle, startAngle + maxSweep, + new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.40f)); + + if (heatRatio > 0.01f) + { + Color heatCol = overPlateau ? RedCol : (heatRatio > 0.65f ? OrangeCol : OliveCol); + _hbCanvas.DrawArcStrokeDynamic( + center.X, center.Y, arcRadius, 2.5f, + startAngle, startAngle + maxSweep * heatRatio, + heatCol); + } + + // Directional incoming-hit indicator arcs + if (_incomingArcCount > 0) + { + float cameraYaw = _getCameraYaw(); + float sinY = MathF.Sin(cameraYaw); + float cosY = MathF.Cos(cameraYaw); + for (int i = 0; i < _incomingArcCount; i++) + { + var arc = _incomingArcs[i]; + float alpha = Math.Clamp(1f - arc.Age / HitArcDuration, 0f, 1f); + if (alpha <= 0.01f) continue; + + float dx = arc.SourceX - player.X; + float dz = arc.SourceZ - player.Z; + float rx = -dx * cosY + dz * sinY; + float fy = dx * sinY + dz * cosY; + float angle = (rx * rx + fy * fy) > 1e-4f ? MathF.Atan2(-fy, rx) : 0f; + + Color arcCol = arc.WeaponClass switch + { + WeaponVisualClass.Explosive => new Color(1.0f, 0.36f, 0.12f, alpha * 0.96f), + WeaponVisualClass.RocketSalvo => new Color(1.0f, 0.56f, 0.14f, alpha * 0.96f), + WeaponVisualClass.ThermalBeam => new Color(0.30f, 0.90f, 1.0f, alpha * 0.96f), + WeaponVisualClass.GaussRail => new Color(0.24f, 0.78f, 1.0f, alpha * 0.98f), + WeaponVisualClass.PlasmaPpc => new Color(0.18f, 0.92f, 0.96f, alpha * 0.96f), + WeaponVisualClass.SwarmSmart => new Color(0.56f, 0.96f, 0.28f, alpha * 0.96f), + _ => new Color(0.96f, 0.72f, 0.22f, alpha * 0.94f) + }; + + const float hitR = 39f; + const float halfSpan = 0.34f; + _hbCanvas.DrawArcStrokeDynamic(center.X, center.Y, hitR, 4.2f, angle - halfSpan, angle + halfSpan, arcCol); + if (arc.WeaponClass is WeaponVisualClass.ThermalBeam or WeaponVisualClass.GaussRail or WeaponVisualClass.PlasmaPpc) + { + _hbCanvas.DrawArcStrokeDynamic( + center.X, center.Y, hitR - 3.5f, 2.0f, + angle - halfSpan * 0.75f, angle + halfSpan * 0.75f, + new Color(GoldCol.R, GoldCol.G, GoldCol.B, alpha * 0.90f)); + } + + float cosA = MathF.Cos(angle); + float sinA = MathF.Sin(angle); + _hbCanvas.DrawDirectionalArrow(center.X + cosA * (hitR + 4.5f), center.Y + sinA * (hitR + 4.5f), 11f, angle, arcCol); + } + + var latest = _incomingArcs[_incomingArcCount - 1]; + float tagAlpha = Math.Clamp(1f - latest.Age / HitArcDuration, 0f, 1f); + (string tagText, Color tagCol) = latest.WeaponClass switch + { + WeaponVisualClass.Autocannon => ("20MM IMPACT", new Color(0.98f, 0.70f, 0.20f, tagAlpha)), + WeaponVisualClass.Explosive => ("BLAST IMPACT", new Color(1.0f, 0.38f, 0.14f, tagAlpha)), + WeaponVisualClass.RocketSalvo => ("ROCKET HIT", new Color(1.0f, 0.58f, 0.18f, tagAlpha)), + WeaponVisualClass.ThermalBeam => ("THERMAL HIT", new Color(0.36f, 0.92f, 1.0f, tagAlpha)), + WeaponVisualClass.GaussRail => ("GAUSS RAIL", new Color(0.28f, 0.84f, 1.0f, tagAlpha)), + WeaponVisualClass.PlasmaPpc => ("PLASMA BURN", new Color(0.24f, 0.94f, 0.98f, tagAlpha)), + WeaponVisualClass.SwarmSmart => ("SWARM HIT", new Color(0.58f, 0.96f, 0.30f, tagAlpha)), + _ => ("KINETIC HIT", new Color(0.96f, 0.78f, 0.28f, tagAlpha)) + }; + float tagW = _hbCanvas.MeasureTextWidth(tagText, 10.5f, wght: 600f); + _hbCanvas.DrawText(tagText, center.X - tagW * 0.5f, center.Y + 56f, 10.5f, tagCol, wght: 600f); } } - private void BuildOutcomeBanner() + // ------------------------------------------------------------------------- + // 4. Bottom-Left Panel: Schematic + Hover + Cargo + Garage + // ------------------------------------------------------------------------- + private void EmitBottomLeftPanel(ChassisGrid grid) { - _outcomeBanner = CreateStyledPanel(OliveCol, cornerLen: 16f, borderPx: 2f); - _outcomeBanner.AnchorLeft = 0.5f; - _outcomeBanner.AnchorRight = 0.5f; - _outcomeBanner.AnchorTop = 0.28f; - _outcomeBanner.AnchorBottom = 0.28f; - _outcomeBanner.OffsetLeft = -210f; - _outcomeBanner.OffsetRight = 210f; - _outcomeBanner.OffsetTop = -40f; - _outcomeBanner.OffsetBottom = 40f; - _outcomeBanner.Visible = false; - AddChild(_outcomeBanner); + // Draw frame & borders ONLY (backdrop is _bottomLeftBg behind _schematic so inactive holes stay BgDark) + _hbCanvas.DrawPanelFrame(_bottomLeftRect, BgDark, BorderCol, OrangeCol, cornerLen: 12f, borderPx: 1.5f, drawBg: false); - _outcomeLabel = new Label + float leftX = _bottomLeftRect.Position.X + 10f; + float topY = _bottomLeftRect.Position.Y + 8f; + float gridW = _schematicRect.Size.X; + + _hbCanvas.DrawText("HARDPOINTS & HEAT", leftX, topY + 12f, 12f, OrangeCol, wght: 650f); + + // Hardpoint L-brackets, hull outlines, stripped X-marks, compatibility pulses, Krypton labels + _schematic.EmitHbGpuOverlay(_hbCanvas, _schematicRect.Position, _vignetteTime); + + // Hover telemetry beneath schematic + float hoverY = _schematicRect.End.Y + 4f; + for (int i = 0; i < _hoverLines.Count; i++) { - HorizontalAlignment = HorizontalAlignment.Center, - VerticalAlignment = VerticalAlignment.Center - }; - _outcomeLabel.AddThemeFontSizeOverride("font_size", 22); - _outcomeBanner.AddChild(_outcomeLabel); + _hbCanvas.DrawText(_hoverLines[i], leftX, hoverY + 11f, 10f, _cachedHoverColor, wght: 400f); + hoverY += 13.5f; + } + + // Middle column: Salvage Cargo Rack (0 dynamic Button nodes) + float cargoX = _schematicRect.End.X + 8f; + const float cargoW = 156f; + SpanWriter sw = new(_scratch); + sw.Append("SALVAGE CARGO ("); + sw.AppendInt(grid.Cargo.Count); + sw.Append("/"); + sw.AppendInt(grid.Spec.CargoCapacity); + sw.Append(")"); + _hbCanvas.DrawText(sw.Span, cargoX, topY + 11f, 11f, OliveCol, wght: 600f); + + float rowY = topY + 18f; + _cargoHitCount = 0; + if (grid.Cargo.Count == 0) + { + _hbCanvas.DrawText("No modules in rack.", cargoX, rowY + 11f, 10.5f, TextMuted, wght: 350f); + _hbCanvas.DrawText("Press [E] near crates.", cargoX, rowY + 24f, 10.5f, TextMuted, wght: 350f); + } + else + { + Viewport? vp = GetViewport(); + Vector2 mousePos = (vp is not null && Input.MouseMode == Input.MouseModeEnum.Visible) + ? vp.GetMousePosition() + : new Vector2(-9999f, -9999f); + + int count = Math.Min(grid.Cargo.Count, MaxCargoHitRects); + for (int i = 0; i < count; i++) + { + var mod = grid.Cargo[i]; + const float rowH = 19f; + const float fitW = 32f; + Rect2 rowRect = new(cargoX, rowY, cargoW - fitW - 3f, rowH); + Rect2 fitRect = new(cargoX + cargoW - fitW, rowY, fitW, rowH); + _cargoRowRects[i] = rowRect; + _cargoFitRects[i] = fitRect; + _cargoHitCount = i + 1; + + bool rowHovered = rowRect.HasPoint(mousePos); + bool fitHovered = fitRect.HasPoint(mousePos); + bool selected = _selectedCargoIndex == i; + + Color rowBg = selected ? new Color(0.24f, 0.18f, 0.10f, 0.92f) : (rowHovered ? BgRowHover : BgInner); + Color rowBorder = selected ? OrangeCol : (mod.IsImperial ? GoldCol : BorderCol); + _hbCanvas.DrawRectFilled(rowRect.Position.X, rowRect.Position.Y, rowRect.Size.X, rowRect.Size.Y, rowBg); + _hbCanvas.DrawRectOutline(rowRect.Position.X, rowRect.Position.Y, rowRect.Size.X, rowRect.Size.Y, 1.0f, rowBorder); + + Color txtCol = selected ? OrangeCol : (mod.IsImperial ? GoldCol : TextLight); + HbGpuCommandWriter.PackClipRect(rowRect.Position.X + 3f, rowRect.Position.Y, rowRect.Size.X - 6f, rowRect.Size.Y, out uint cMin, out uint cMax); + float nameX = rowRect.Position.X + 5f; + if (mod.IsImperial) + { + nameX += _hbCanvas.DrawText("* ", nameX, rowRect.Position.Y + 13f, 10f, GoldCol, wght: 700f, clipMinPacked: cMin, clipMaxPacked: cMax); + } + _hbCanvas.DrawText(mod.Name, nameX, rowRect.Position.Y + 13f, 10f, txtCol, wght: 450f, clipMinPacked: cMin, clipMaxPacked: cMax); + + Color fitBg = fitHovered ? new Color(0.22f, 0.28f, 0.20f, 0.96f) : BgInner; + _hbCanvas.DrawRectFilled(fitRect.Position.X, fitRect.Position.Y, fitRect.Size.X, fitRect.Size.Y, fitBg); + _hbCanvas.DrawRectOutline(fitRect.Position.X, fitRect.Position.Y, fitRect.Size.X, fitRect.Size.Y, 1.0f, fitHovered ? OliveCol : BorderCol); + float fw = _hbCanvas.MeasureTextWidth("FIT", 9.5f, wght: 650f); + _hbCanvas.DrawText("FIT", fitRect.Position.X + (fitW - fw) * 0.5f, fitRect.Position.Y + 13f, 9.5f, fitHovered ? Colors.White : TextLight, wght: 650f); + + rowY += 21f; + } + } + + // Optional Garage Details column when Tab is expanded + if (_garageExpanded) + { + float garageX = cargoX + cargoW + 8f; + float gy = topY + 11f; + for (int i = 0; i < _garageLines.Count; i++) + { + _hbCanvas.DrawText(_garageLines[i], garageX, gy, 10f, i <= 1 ? OliveCol : TextMuted, wght: i <= 1 ? 550f : 380f); + gy += 13.5f; + } + } } + // ------------------------------------------------------------------------- + // 5. Broadcast Chyron & Outcome Banner + // ------------------------------------------------------------------------- + private void EmitChyronPanel() + { + _hbCanvas.DrawPanelFrame(_chyronRect, BgDark, BorderCol, GoldCol, cornerLen: 12f, borderPx: 1.5f); + + float x = _chyronRect.Position.X + 10f; + float y = _chyronRect.Position.Y + 8f; + _hbCanvas.DrawText("IMPERIAL BROADCAST FEED", x, y + 11f, 11f, GoldCol, wght: 650f); + y += 17f; + + HbGpuCommandWriter.PackClipRect( + _chyronRect.Position.X + 8f, _chyronRect.Position.Y + 6f, + _chyronRect.Size.X - 16f, _chyronRect.Size.Y - 12f, + out uint cMin, out uint cMax); + + for (int i = 0; i < _chyronLineCount; i++) + { + bool latest = _chyronIsLatest[i]; + _hbCanvas.DrawText( + _chyronDisplayLines[i], + x, y + 12f, + latest ? 11.5f : 10.8f, + latest ? TextLight : TextMuted, + wght: latest ? 500f : 380f, + clipMinPacked: cMin, + clipMaxPacked: cMax); + y += 19f; + } + } + + private void EmitOutcomeBanner( + IClientArenaSession session, + MatchState state, + ContenderState player, + NetworkStatusSnapshot net) + { + var outcome = session.LocalOutcome; + Color accent; + ReadOnlySpan title; + ReadOnlySpan sub; + + if (outcome == ClientMatchOutcome.Victory) + { + accent = OliveCol; + title = "VICTORY — LAST RIG STANDING"; + sub = net.Mode == NetworkMode.RemoteClient ? "Next round starting soon..." : "[R] New Drop"; + } + else if (outcome == ClientMatchOutcome.Defeat) + { + accent = RedCol; + title = !player.Alive ? "CHASSIS DESTROYED" : "MATCH COMPLETED — DEFEAT"; + sub = net.Mode == NetworkMode.RemoteClient + ? (state.Phase == MatchPhase.Completed ? "Waiting for server next round..." : "Spectating live match...") + : "[R] Redeploy"; + } + else + { + accent = CyanCol; + var wave = session.DropWaveState; + float eta = wave.NextWaveAtSec is float nxt ? MathF.Max(0f, nxt - state.Time) : 0f; + SpanWriter sw = new(_scratch); + sw.Append("AWAITING PATRON WAVE "); + sw.AppendInt(wave.NextWaveIndex); + _hbCanvas.DrawPanelFrame(_outcomeRect, BgDark, BorderCol, accent, cornerLen: 16f, borderPx: 2.0f); + float cx = _outcomeRect.Position.X + _outcomeRect.Size.X * 0.5f; + float w1 = _hbCanvas.MeasureTextWidth(sw.Span, 20f, wght: 700f); + _hbCanvas.DrawText(sw.Span, cx - w1 * 0.5f, _outcomeRect.Position.Y + 36f, 20f, accent, wght: 700f); + + sw = new SpanWriter(_scratch); + sw.Append("RESPAWN IN "); + sw.AppendFloat(eta, "F1"); + sw.Append("s (RESP: "); + sw.AppendInt(player.RespawnsRemaining); + sw.Append(" LEFT)"); + float w2 = _hbCanvas.MeasureTextWidth(sw.Span, 14f, wght: 500f); + _hbCanvas.DrawText(sw.Span, cx - w2 * 0.5f, _outcomeRect.Position.Y + 60f, 14f, accent, wght: 500f); + return; + } + + _hbCanvas.DrawPanelFrame(_outcomeRect, BgDark, BorderCol, accent, cornerLen: 16f, borderPx: 2.0f); + float centerX = _outcomeRect.Position.X + _outcomeRect.Size.X * 0.5f; + float tw1 = _hbCanvas.MeasureTextWidth(title, 20f, wght: 700f); + float tw2 = _hbCanvas.MeasureTextWidth(sub, 14f, wght: 500f); + _hbCanvas.DrawText(title, centerX - tw1 * 0.5f, _outcomeRect.Position.Y + 36f, 20f, accent, wght: 700f); + _hbCanvas.DrawText(sub, centerX - tw2 * 0.5f, _outcomeRect.Position.Y + 60f, 14f, accent, wght: 500f); + } + + // ------------------------------------------------------------------------- + // 6. 3D World Markers: Squad Chevrons + Target Boxes + Offscreen Arrows + // Preserves ALL Soul-verified invariants from 8310246 (0 GC allocs on hot path) + // ------------------------------------------------------------------------- + private void EmitWorldMarkers( + IClientArenaSession session, + MatchState state, + ContenderState localPlayer, + Vector2 viewSize) + { + if (_projectWorld is null || viewSize.X < 64f || viewSize.Y < 64f) + { + return; + } + + int localId = session.LocalContenderId; + if (localId < 0 || localId >= state.Contenders.Count || !localPlayer.Alive) + { + return; + } + + var (localPos, _, _) = session.GetInterpolatedContenderPose(localId, 1f); + Vector2 center = viewSize * 0.5f; + float halfW = MathF.Max(16f, center.X - BorderPad); + float halfH = MathF.Max(16f, center.Y - BorderPad); + + // 1. Allied squad chevrons (only when SquadSize > 1: Solo vs Trio mutual exclusion) + if (state.SquadSize > 1) + { + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (c.Id == localId || !c.Alive || !state.AreAllies(localId, c.Id)) continue; + + var (allyPos, _, _) = session.GetInterpolatedContenderPose(c.Id, 1f); + float dist = (allyPos - localPos).Length(); + float headOffset = c.IsInDropPod ? 3.4f : (c.Grid.Spec.HalfHeight + 1.9f); + var worldHead = new System.Numerics.Vector3(allyPos.X, allyPos.Y + headOffset, allyPos.Z); + var (valid, inFront, sp, camLocal) = _projectWorld(worldHead); + if (!valid) continue; + + bool inFrame = inFront && + sp.X >= BorderPad && sp.X <= viewSize.X - BorderPad && + sp.Y >= BorderPad && sp.Y <= viewSize.Y - BorderPad; + + SpanWriter sw = new(_scratch); + sw.Append(c.Name); + sw.Append(" "); + sw.AppendFloat(dist, "F0"); + sw.Append("m"); + ReadOnlySpan label = sw.Span; + + if (inFrame) + { + // Pointing down chevron above ally head (+PI/2 in screen coords) + _hbCanvas.DrawChevron(sp.X, sp.Y, 12f, MathF.PI * 0.5f, AlliedCol); + float lw = _hbCanvas.MeasureTextWidth(label, 10.5f, wght: 550f); + _hbCanvas.DrawText(label, sp.X - lw * 0.5f, sp.Y - 10f, 10.5f, AlliedCol, wght: 550f); + } + else + { + Vector2 dir = ComputeOffscreenDirection(camLocal); + Vector2 edge = ComputeSafeEdgePos(center, halfW, halfH, dir); + float angle = MathF.Atan2(dir.Y, dir.X); + _hbCanvas.DrawDirectionalArrow(edge.X, edge.Y, 13f, angle, new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.88f)); + Vector2 textPos = ComputeInwardLabelPos(edge, dir, viewSize, label); + _hbCanvas.DrawText(label, textPos.X, textPos.Y, 10.5f, new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.90f), wght: 550f); + } + } + } + + // 2. Visible enemy contenders (strictly obeying fog-of-war / LOS) + var contenderContacts = session.LocalContenderContacts; + var spectatorContacts = session.LocalSpectatorContacts; + _offscreenHostiles.Clear(); + + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (c.Id == localId || !c.Alive || state.AreAllies(localId, c.Id)) continue; + if (!session.IsContenderVisible(c.Id)) continue; + if (!contenderContacts.TryGetValue(c.Id, out var mem) || !mem.VisibleToPlayer) continue; + + var (pos, rot, _) = session.GetInterpolatedContenderPose(c.Id, 1f); + float dist = (pos - localPos).Length(); + bool targetingLocal = c.AiTargetContenderId == localId; + Color col = targetingLocal ? RedCol : OrangeCol; + float hpRatio = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f; + + float halfBoundW = c.IsInDropPod ? 1.4f : c.Grid.Spec.HalfWidth; + float halfBoundH = c.IsInDropPod ? 1.8f : c.Grid.Spec.HalfHeight; + float halfBoundL = c.IsInDropPod ? 1.4f : c.Grid.Spec.HalfLength; + + ProcessHostileTarget( + pos, rot, halfBoundW, halfBoundH, halfBoundL, + dist, hpRatio, col, targetingLocal, viewSize); + } + + // 3. Visible hostile/provoked spectators (neutral tourists do NOT get hostile target boxes) + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral) continue; + if (!session.IsSpectatorVisible(s.Id)) continue; + if (!spectatorContacts.TryGetValue(s.Id, out var mem) || !mem.VisibleToPlayer) continue; + + var (pos, rot, _) = session.GetInterpolatedSpectatorPose(s.Id, 1f); + float dist = (pos - localPos).Length(); + bool lockedOnLocal = s.TargetContenderId == localId; + float hpRatio = s.Grid.MaxCoreHp > 0f ? s.Grid.CoreHp / s.Grid.MaxCoreHp : 1f; + + ProcessHostileTarget( + pos, rot, s.Grid.Spec.HalfWidth, s.Grid.Spec.HalfHeight, s.Grid.Spec.HalfLength, + dist, hpRatio, RedCol, lockedOnLocal, viewSize); + } + + // 4. Off-screen hostile arrows (locked-on threats first, then nearest visible hostiles) + if (_offscreenHostiles.Count > 0) + { + _offscreenHostiles.Sort(OffscreenSortComparison); + int count = Math.Min(_offscreenHostiles.Count, MaxOffscreenHostileArrows); + for (int i = 0; i < count; i++) + { + EmitOffscreenArrow(_offscreenHostiles[i], viewSize, center, halfW, halfH); + } + } + } + + private void ProcessHostileTarget( + System.Numerics.Vector3 worldCenter, + System.Numerics.Quaternion rot, + float halfBoundW, + float halfBoundH, + float halfBoundL, + float dist, + float hpRatio, + Color col, + bool isLockedOnLocal, + Vector2 viewSize) + { + var (cValid, cInFront, cSp, cCamLocal) = _projectWorld!(worldCenter); + if (!cValid) return; + + bool inFrame = cInFront && + cSp.X >= BorderPad && cSp.X <= viewSize.X - BorderPad && + cSp.Y >= BorderPad && cSp.Y <= viewSize.Y - BorderPad; + + if (!inFrame) + { + if (isLockedOnLocal || dist <= OffscreenHostileMaxDistance) + { + _offscreenHostiles.Add(new OffscreenMarker(cCamLocal, dist, col, isLockedOnLocal)); + } + return; + } + + float minX = float.PositiveInfinity, minY = float.PositiveInfinity; + float maxX = float.NegativeInfinity, maxY = float.NegativeInfinity; + bool allCornersInFront = true; + + for (int sx = -1; sx <= 1; sx += 2) + { + for (int sy = -1; sy <= 1; sy += 2) + { + for (int sz = -1; sz <= 1; sz += 2) + { + var localCorner = new System.Numerics.Vector3(sx * halfBoundW, sy * halfBoundH, sz * halfBoundL); + var worldCorner = worldCenter + System.Numerics.Vector3.Transform(localCorner, rot); + var (valid, inFront, sp, _) = _projectWorld(worldCorner); + if (!valid || !inFront) + { + allCornersInFront = false; + break; + } + if (sp.X < minX) minX = sp.X; + if (sp.X > maxX) maxX = sp.X; + if (sp.Y < minY) minY = sp.Y; + if (sp.Y > maxY) maxY = sp.Y; + } + if (!allCornersInFront) break; + } + if (!allCornersInFront) break; + } + + if (!allCornersInFront) + { + var (topValid, topFront, topSp, _) = _projectWorld(worldCenter + new System.Numerics.Vector3(0f, halfBoundH, 0f)); + var (botValid, botFront, botSp, _) = _projectWorld(worldCenter - new System.Numerics.Vector3(0f, halfBoundH, 0f)); + float rawH = (topValid && topFront && botValid && botFront) + ? MathF.Abs(botSp.Y - topSp.Y) + 8f + : 44f; + float horizRadius = MathF.Max(halfBoundW, halfBoundL); + float rawW = rawH * (horizRadius / MathF.Max(0.4f, halfBoundH)); + minX = cSp.X - rawW * 0.5f; + maxX = cSp.X + rawW * 0.5f; + minY = cSp.Y - rawH * 0.5f; + maxY = cSp.Y + rawH * 0.5f; + } + else + { + minX -= 3f; + maxX += 3f; + minY -= 3f; + maxY += 3f; + } + + float boxW = Math.Clamp(maxX - minX, 22f, 220f); + float boxH = Math.Clamp(maxY - minY, 22f, 220f); + Vector2 boxCenter = new((minX + maxX) * 0.5f, (minY + maxY) * 0.5f); + var rect = new Rect2(boxCenter.X - boxW * 0.5f, boxCenter.Y - boxH * 0.5f, boxW, boxH); + + EmitTargetBox(rect, col, dist, hpRatio, isLockedOnLocal); + } + + private void EmitTargetBox(Rect2 rect, Color col, float dist, float hpRatio, bool isLockedOnLocal) + { + float x0 = rect.Position.X; + float y0 = rect.Position.Y; + float x1 = x0 + rect.Size.X; + float y1 = y0 + rect.Size.Y; + float arm = Math.Clamp(MathF.Min(rect.Size.X, rect.Size.Y) * 0.22f, 5f, 26f); + + Color shadowCol = new(0.04f, 0.05f, 0.04f, 0.78f); + Color strokeCol = new(col.R, col.G, col.B, 0.95f); + + // Dark shadow pass then crisp target brackets across all 4 quadrants + _hbCanvas.DrawTargetBracketCorner(x0 - 0.8f, y0 - 0.8f, arm + 1.5f, 3.6f, 0, shadowCol); + _hbCanvas.DrawTargetBracketCorner(x1 + 0.8f, y0 - 0.8f, arm + 1.5f, 3.6f, 1, shadowCol); + _hbCanvas.DrawTargetBracketCorner(x1 + 0.8f, y1 + 0.8f, arm + 1.5f, 3.6f, 2, shadowCol); + _hbCanvas.DrawTargetBracketCorner(x0 - 0.8f, y1 + 0.8f, arm + 1.5f, 3.6f, 3, shadowCol); + + _hbCanvas.DrawTargetBracketCorner(x0, y0, arm, 2.0f, 0, strokeCol); + _hbCanvas.DrawTargetBracketCorner(x1, y0, arm, 2.0f, 1, strokeCol); + _hbCanvas.DrawTargetBracketCorner(x1, y1, arm, 2.0f, 2, strokeCol); + _hbCanvas.DrawTargetBracketCorner(x0, y1, arm, 2.0f, 3, strokeCol); + + // Thin HP bar right above top bracket + float barW = Math.Clamp(rect.Size.X, 22f, 64f); + float barX = (x0 + x1) * 0.5f - barW * 0.5f; + float barY = y0 - 7f; + _hbCanvas.DrawRectFilled(barX - 1f, barY - 1f, barW + 2f, 4f, shadowCol); + _hbCanvas.DrawRectFilled(barX, barY, barW * Math.Clamp(hpRatio, 0f, 1f), 2f, strokeCol); + + // Distance + LOCK tag above HP bar + SpanWriter sw = new(_scratch); + sw.AppendFloat(dist, "F0"); + sw.Append("m"); + if (isLockedOnLocal) + { + sw.Append(" LOCK"); + } + ReadOnlySpan label = sw.Span; + float textW = _hbCanvas.MeasureTextWidth(label, 10.5f, wght: 600f); + float tx = (x0 + x1) * 0.5f - textW * 0.5f; + float ty = barY - 3f; + _hbCanvas.DrawText(label, tx + 1f, ty + 1f, 10.5f, ShadowCol, wght: 600f); + _hbCanvas.DrawText(label, tx, ty, 10.5f, strokeCol, wght: 600f); + } + + private void EmitOffscreenArrow(OffscreenMarker m, Vector2 viewSize, Vector2 center, float halfW, float halfH) + { + Vector2 dir = ComputeOffscreenDirection(m.CamLocal); + Vector2 edge = ComputeSafeEdgePos(center, halfW, halfH, dir); + float angle = MathF.Atan2(dir.Y, dir.X); + + _hbCanvas.DrawDirectionalArrow(edge.X, edge.Y, 18f, angle, new Color(0.04f, 0.05f, 0.04f, 0.74f)); + Color arrowCol = new(m.Color.R, m.Color.G, m.Color.B, 0.94f); + _hbCanvas.DrawDirectionalArrow(edge.X, edge.Y, 14.5f, angle, arrowCol); + + SpanWriter sw = new(_scratch); + sw.AppendFloat(m.Distance, "F0"); + sw.Append("m"); + if (m.IsLockedOnLocal) + { + sw.Append(" !"); + } + ReadOnlySpan label = sw.Span; + Vector2 textPos = ComputeInwardLabelPos(edge, dir, viewSize, label); + _hbCanvas.DrawText(label, textPos.X + 1f, textPos.Y + 1f, 10.5f, ShadowCol, wght: 600f); + _hbCanvas.DrawText(label, textPos.X, textPos.Y, 10.5f, arrowCol, wght: 600f); + } + + private static Vector2 ComputeOffscreenDirection(System.Numerics.Vector3 camLocal) + { + if (!float.IsFinite(camLocal.X) || !float.IsFinite(camLocal.Y) || !float.IsFinite(camLocal.Z)) + { + return Vector2.Down; + } + + Vector2 dir; + if (camLocal.Z >= 0f) + { + dir = new Vector2(camLocal.X, -camLocal.Y); + } + else + { + float horiz = MathF.Sqrt(camLocal.X * camLocal.X + camLocal.Z * camLocal.Z); + float t = Math.Clamp(-camLocal.Z / MathF.Max(1e-4f, horiz * 0.35f), 0f, 1f); + Vector2 sideDir = new(camLocal.X, -camLocal.Y); + Vector2 behindArcDir = new(camLocal.X, MathF.Max(-camLocal.Z, 0.35f * horiz)); + dir = sideDir.Lerp(behindArcDir, t); + if (MathF.Abs(camLocal.X) < 0.35f * horiz) + { + float minDown = 0.25f * dir.Length(); + if (dir.Y < minDown) + { + dir.Y = MathF.Max(minDown, 0.25f); + } + } + } + + float lenSq = dir.LengthSquared(); + if (!float.IsFinite(lenSq) || lenSq < 1e-6f) + { + return camLocal.Z < 0f ? Vector2.Down : Vector2.Up; + } + return dir / MathF.Sqrt(lenSq); + } + + private Vector2 ComputeSafeEdgePos(Vector2 center, float halfW, float halfH, Vector2 dir) + { + float tx = MathF.Abs(dir.X) > 1e-4f ? halfW / MathF.Abs(dir.X) : float.PositiveInfinity; + float ty = MathF.Abs(dir.Y) > 1e-4f ? halfH / MathF.Abs(dir.Y) : float.PositiveInfinity; + float tBest = MathF.Min(tx, ty); + + Span avoid = stackalloc Rect2[4] + { + _topLeftRect, + _topRightRect, + _bottomLeftRect, + _chyronRect + }; + for (int i = 0; i < avoid.Length; i++) + { + Rect2 r = avoid[i].Grow(PanelAvoidPad); + if (r.HasPoint(center)) continue; + if (TryRayEnterRect(center, dir, r, out float tEnter) && tEnter > 24f && tEnter < tBest) + { + tBest = tEnter; + } + } + + tBest = MathF.Max(24f, tBest); + return center + dir * tBest; + } + + private static bool TryRayEnterRect(Vector2 origin, Vector2 dir, Rect2 r, out float tEnter) + { + float tMin = 0f; + float tMax = float.PositiveInfinity; + + if (MathF.Abs(dir.X) < 1e-5f) + { + if (origin.X < r.Position.X || origin.X > r.End.X) + { + tEnter = 0f; + return false; + } + } + else + { + float invX = 1f / dir.X; + float t1 = (r.Position.X - origin.X) * invX; + float t2 = (r.End.X - origin.X) * invX; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + if (tMin > tMax) + { + tEnter = 0f; + return false; + } + } + + if (MathF.Abs(dir.Y) < 1e-5f) + { + if (origin.Y < r.Position.Y || origin.Y > r.End.Y) + { + tEnter = 0f; + return false; + } + } + else + { + float invY = 1f / dir.Y; + float t1 = (r.Position.Y - origin.Y) * invY; + float t2 = (r.End.Y - origin.Y) * invY; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + if (tMin > tMax) + { + tEnter = 0f; + return false; + } + } + + tEnter = tMin; + return true; + } + + private Vector2 ComputeInwardLabelPos(Vector2 edge, Vector2 dir, Vector2 viewSize, ReadOnlySpan label) + { + float w = _hbCanvas.MeasureTextWidth(label, 10.5f, wght: 600f); + const float h = 11f; + Vector2 inward = edge - dir * 14f; + float textX; + float textY; + + if (MathF.Abs(dir.X) >= MathF.Abs(dir.Y)) + { + textX = dir.X > 0f ? (inward.X - w - 4f) : (inward.X + 6f); + textY = inward.Y + h * 0.3f; + } + else + { + textX = inward.X - w * 0.5f; + textY = dir.Y > 0f ? (inward.Y - 4f) : (inward.Y + h + 4f); + } + + return new Vector2( + Math.Clamp(textX, 10f, MathF.Max(10f, viewSize.X - w - 10f)), + Math.Clamp(textY, 16f, MathF.Max(16f, viewSize.Y - 10f))); + } + + // ------------------------------------------------------------------------- + // Cached Text Helpers (Rebuild ONLY on state delta -> 0 B/frame steady state) + // ------------------------------------------------------------------------- + private void UpdatePromptCache(MatchState state, ContenderState player, OrbitalPod? localPod) + { + if (player.IsInDropPod) + { + int aglR = localPod is not null + ? Mathf.RoundToInt(MathF.Max(0f, localPod.LastAgl)) + : Mathf.RoundToInt(MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z))); + int velR = localPod is not null + ? Mathf.RoundToInt(MathF.Max(0f, -localPod.VelY)) + : Mathf.RoundToInt(MathF.Max(0f, -player.VelY)); + int horR = localPod is not null + ? Mathf.RoundToInt(MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ)) + : Mathf.RoundToInt(player.Speed); + bool burn = localPod?.Phase == OrbitalPodPhase.RetroBurn; + + if (_lastPromptPod && aglR == _lastPodAglRounded && horR == _lastPodHorizRounded && velR == _lastPodVertRounded && burn == _lastPodBurn) + { + return; + } + _lastPromptPod = true; + _lastPodAglRounded = aglR; + _lastPodHorizRounded = horR; + _lastPodVertRounded = velR; + _lastPodBurn = burn; + + _cachedPromptText = $"ORBITAL INSERTION — ALT {aglR}m | HORIZ {horR} m/s | VERT {velR} m/s | [WASD] STEER" + + (burn ? " [RETRO BURN]" : ""); + WrapTextInto(_cachedPromptText, 344f, 12f, 550f, _promptLines); + return; + } + + _lastPromptPod = false; + GroundDrop? nearest = state.FindNearestInteractableDrop(player.Id); + int promptKey = nearest is null + ? -1 + : HashCode.Combine( + nearest.Id, + nearest.Module?.Id ?? string.Empty, + nearest.Chassis?.Id ?? string.Empty, + nearest.Module is { } m ? (player.Grid.FindFirstEmptyCompatibleHardpoint(m)?.Id ?? string.Empty) : string.Empty); + + if (promptKey == _lastPromptKey) + { + return; + } + _lastPromptKey = promptKey; + + _cachedPromptText = BuildInteractionPrompt(player, nearest); + if (string.IsNullOrEmpty(_cachedPromptText)) + { + _promptLines.Clear(); + } + else + { + WrapTextInto(_cachedPromptText, 344f, 12f, 550f, _promptLines); + } + } + + private static string BuildInteractionPrompt(ContenderState player, GroundDrop? nearest) + { + if (nearest is null) return string.Empty; + if (nearest.Module is { } mod) + { + var freeHp = player.Grid.FindFirstEmptyCompatibleHardpoint(mod); + if (mod.Procedural is { } proc) + { + string action = freeHp is not null + ? $"[E] Bolt [{proc.ManufacturerLabel}] {mod.Name} -> {freeHp.Id}" + : $"[E] Loot [{proc.ManufacturerLabel}] {mod.Name}"; + return $"{action}\n{proc.SummaryLine1} | {proc.SummaryLine2}"; + } + return freeHp is not null + ? $"[E] Bolt {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name} -> {freeHp.Id}" + : $"[E] Loot {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name}"; + } + if (nearest.Chassis is { } ch) + { + return $"[E] Swap to {ch.Name} ({ch.Plane})"; + } + return string.Empty; + } + + private void SyncBroadcastChyron(BroadcastFeed broadcast) + { + var lines = broadcast.Lines; + if (ReferenceEquals(_lastBroadcastFeed, broadcast) && broadcast.Version == _lastChyronVersion) + { + return; + } + + _lastBroadcastFeed = broadcast; + _lastChyronVersion = broadcast.Version; + + int start = Math.Max(0, lines.Count - _chyronDisplayLines.Length); + int visibleCount = lines.Count - start; + _chyronLineCount = visibleCount; + for (int slot = 0; slot < visibleCount; slot++) + { + int lineIdx = start + slot; + var line = lines[lineIdx]; + _chyronIsLatest[slot] = lineIdx == lines.Count - 1; + _chyronDisplayLines[slot] = $"[{line.Timestamp:00.0}s] {line.Text}"; + } + } + + private void OnHardpointClicked(string hardpointId) + { + var session = _getSession(); + if (session is null) return; + var cargo = session.LocalContender.Grid.Cargo; + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < cargo.Count) + { + _onEquipCargo(_selectedCargoIndex, hardpointId); + _selectedCargoIndex = -1; + _lastGarageHash = int.MinValue; + _dirtyEmit = true; + } + } + + private void AutoFitCargo(ChassisGrid grid, int cargoIndex) + { + if (cargoIndex < 0 || cargoIndex >= grid.Cargo.Count) return; + var mod = grid.Cargo[cargoIndex]; + for (int i = 0; i < grid.Spec.Hardpoints.Length; i++) + { + var hp = grid.Spec.Hardpoints[i]; + if (ChassisGrid.CanFit(hp, mod)) + { + _onEquipCargo(cargoIndex, hp.Id); + _selectedCargoIndex = -1; + _lastGarageHash = int.MinValue; + _dirtyEmit = true; + return; + } + } + } + + private void OnSchematicHoverChanged(Vector2I? cell, HardpointSpec? hp) + { + _lastHoveredCell = cell; + var grid = _schematic.Grid; + if (cell is null || grid is null) + { + if (!UpdateCargoSelectionTooltip(grid)) + { + SetHoverText("HOVER CELL FOR TELEMETRY", TextMuted); + } + return; + } + + var c = cell.Value; + float arm = grid.Armor[c.X, c.Y]; + float maxArm = grid.MaxArmor[c.X, c.Y]; + float temp = grid.Temperature[c.X, c.Y]; + if (hp is not null) + { + var mounted = grid.GetMountedOn(hp.Id); + bool strippedHp = !grid.IsHardpointOperational(hp); + string hpStatus = strippedHp ? " [STRIPPED]" : ""; + if (mounted is not null && mounted.Spec.Procedural is { } proc) + { + SetHoverText( + $"[{proc.ManufacturerLabel}] {proc.SummaryLine1}{hpStatus}\n{proc.SummaryLine2}", + (arm <= 0.01f || strippedHp) ? RedCol : ResolveManufacturerHudColor(proc.Manufacturer)); + } + else + { + string txt = mounted is not null + ? $"{hp.Kind.ToString().ToUpperInvariant()}: {mounted.Spec.Name} {mounted.CurrentTemp:F0}°C ({mounted.CurrentPerformance * 100f:F0}%){hpStatus}" + : $"{hp.Kind.ToString().ToUpperInvariant()} SLOT [{hp.Width}x{hp.Height}] EMPTY{hpStatus}"; + SetHoverText(txt, (arm <= 0.01f || strippedHp) ? RedCol : TextLight); + } + } + else + { + string txt = arm <= 0.01f + ? $"CELL ({c.X},{c.Y}) STRIPPED! {temp:F0}°C" + : $"HULL ({c.X},{c.Y}) ARM {arm:F0}/{maxArm:F0} {temp:F0}°C"; + SetHoverText(txt, arm <= 0.01f ? RedCol : TextMuted); + } + } + + private bool UpdateCargoSelectionTooltip(ChassisGrid? grid) + { + if (grid is null || _selectedCargoIndex < 0 || _selectedCargoIndex >= grid.Cargo.Count) + { + return false; + } + var mod = grid.Cargo[_selectedCargoIndex]; + if (mod.Procedural is { } proc) + { + SetHoverText($"[{proc.ManufacturerLabel}] {proc.SummaryLine1}\n{proc.SummaryLine2}", ResolveManufacturerHudColor(proc.Manufacturer)); + } + else + { + SetHoverText($"CARGO: {mod.Name} [{mod.Width}x{mod.Height}]", mod.IsImperial ? GoldCol : TextLight); + } + return true; + } + + private void SetHoverText(string text, Color color) + { + if (string.Equals(_cachedHoverText, text, StringComparison.Ordinal) && _cachedHoverColor == color) + { + return; + } + _cachedHoverText = text; + _cachedHoverColor = color; + float maxW = _garageExpanded ? 198f : 180f; + WrapTextInto(text, maxW, 10f, 400f, _hoverLines); + _dirtyEmit = true; + } + + private void UpdateGarageDetailsCache(ChassisGrid grid) + { + var hc = new HashCode(); + hc.Add(grid.Spec.Id); + hc.Add(grid.Mounted.Count); + hc.Add(_selectedCargoIndex); + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count) + { + hc.Add(grid.Cargo[_selectedCargoIndex].Id); + } + for (int i = 0; i < grid.Mounted.Count; i++) + { + var m = grid.Mounted[i]; + hc.Add(m.HardpointId); + hc.Add(m.Spec.Id); + hc.Add(Mathf.RoundToInt(m.CurrentTemp)); + hc.Add(grid.IsHardpointOperational(m.HardpointId)); + } + int sig = hc.ToHashCode(); + if (sig == _lastGarageHash) + { + return; + } + _lastGarageHash = sig; + + _garageLines.Clear(); + var rawLines = new List(16) + { + $"COND {grid.Spec.HullConductivity:F1} | THRUST {grid.ComputeDriveThrust():F0} N", + "MOUNTED:" + }; + _garageLines.Add(rawLines[0]); + _garageLines.Add(rawLines[1]); + for (int i = 0; i < grid.Mounted.Count; i++) + { + var m = grid.Mounted[i]; + string stateTag = grid.IsHardpointOperational(m.HardpointId) ? "" : " [STRIPPED]"; + if (m.Spec.Procedural is { } proc) + { + string l0 = $"• [{proc.ManufacturerLabel}] {m.Spec.Name} {m.CurrentTemp:F0}°C{stateTag}"; + rawLines.Add(l0); + rawLines.Add($" {proc.SummaryLine1}"); + rawLines.Add($" {proc.SummaryLine2}"); + WrapTextInto(l0, 184f, 10f, 400f, _garageLines, clearDest: false); + WrapTextInto($" {proc.SummaryLine1}", 184f, 10f, 400f, _garageLines, clearDest: false); + WrapTextInto($" {proc.SummaryLine2}", 184f, 10f, 400f, _garageLines, clearDest: false); + } + else + { + string l0 = $"• {m.HardpointId}: {m.Spec.Name} {m.CurrentTemp:F0}°C ({m.CurrentPerformance * 100f:F0}%){stateTag}"; + rawLines.Add(l0); + WrapTextInto(l0, 184f, 10f, 400f, _garageLines, clearDest: false); + } + } + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count && + grid.Cargo[_selectedCargoIndex].Procedural is { } cargoProc) + { + string l0 = $"SEL [{cargoProc.ManufacturerLabel}]:"; + rawLines.Add(l0); + rawLines.Add($" {cargoProc.SummaryLine1}"); + rawLines.Add($" {cargoProc.SummaryLine2}"); + _garageLines.Add(l0); + WrapTextInto($" {cargoProc.SummaryLine1}", 184f, 10f, 400f, _garageLines, clearDest: false); + WrapTextInto($" {cargoProc.SummaryLine2}", 184f, 10f, 400f, _garageLines, clearDest: false); + } + _cachedGarageDetails = string.Join("\n", rawLines); + } + + private void WrapTextInto(string text, float maxWidthPx, float fontSizePx, float wght, List dest, bool clearDest = true) + { + if (clearDest) + { + dest.Clear(); + } + if (string.IsNullOrEmpty(text)) + { + return; + } + + int lineStart = 0; + for (int idx = 0; idx <= text.Length; idx++) + { + if (idx == text.Length || text[idx] == '\n') + { + WrapParagraph(text.AsSpan(lineStart, idx - lineStart), maxWidthPx, fontSizePx, wght, dest); + lineStart = idx + 1; + } + } + } + + private void WrapParagraph(ReadOnlySpan para, float maxWidthPx, float fontSizePx, float wght, List dest) + { + if (para.IsEmpty) + { + dest.Add(string.Empty); + return; + } + + if (_hbCanvas is null || _hbCanvas.MeasureTextWidth(para, fontSizePx, wght: wght) <= maxWidthPx) + { + dest.Add(new string(para)); + return; + } + + int pos = 0; + while (pos < para.Length) + { + int bestEnd = pos + 1; + int lastSpace = -1; + for (int end = pos + 1; end <= para.Length; end++) + { + if (end < para.Length && para[end] == ' ') + { + lastSpace = end; + } + float w = _hbCanvas.MeasureTextWidth(para.Slice(pos, end - pos), fontSizePx, wght: wght); + if (w > maxWidthPx) + { + break; + } + bestEnd = end; + } + + int cut = (bestEnd < para.Length && lastSpace > pos) ? lastSpace : bestEnd; + dest.Add(new string(para.Slice(pos, cut - pos))); + pos = cut; + while (pos < para.Length && para[pos] == ' ') + { + pos++; + } + } + } + + private static Color ResolveManufacturerHudColor(ManufacturerId mfg) => mfg switch + { + ManufacturerId.ScrapFrontier => Color.FromHtml("#ffaa33"), + ManufacturerId.KorrathiIronworks => Color.FromHtml("#f2c422"), + ManufacturerId.AuralianOptics => Color.FromHtml("#38e8ff"), + ManufacturerId.VexNineCollective => Color.FromHtml("#7cf230"), + ManufacturerId.ThalassanForge => Color.FromHtml("#2cb8ff"), + _ => GoldCol + }; + + // ------------------------------------------------------------------------- + // [F9] Interactive Multiplayer Link Panel (Godot Controls kept until Cut 14c) + // ------------------------------------------------------------------------- private void BuildNetworkPanel() { - _netPanel = CreateStyledPanel(CyanCol, cornerLen: 14f, borderPx: 1.5f); + var panelStyle = new StyleBoxFlat + { + BgColor = BgDark, + BorderColor = BorderCol, + ContentMarginLeft = 10, + ContentMarginRight = 10, + ContentMarginTop = 8, + ContentMarginBottom = 8 + }; + panelStyle.SetBorderWidthAll(1); + + _netPanel = new PanelContainer + { + Name = "NetworkLinkPanel", + Visible = false + }; + _netPanel.AddThemeStyleboxOverride("panel", panelStyle); _netPanel.AnchorLeft = 0.5f; _netPanel.AnchorRight = 0.5f; _netPanel.AnchorTop = 0.32f; @@ -867,7 +2430,6 @@ public partial class Hud : CanvasLayer _netPanel.OffsetRight = 188f; _netPanel.OffsetTop = 0f; _netPanel.OffsetBottom = 0f; - _netPanel.Visible = false; AddChild(_netPanel); var vbox = new VBoxContainer(); @@ -1035,1413 +2597,43 @@ public partial class Hud : CanvasLayer return fallback; } - private void OnHardpointClicked(string hardpointId) + private ref struct SpanWriter { - var session = _getSession(); - if (session is null) return; - var cargo = session.LocalContender.Grid.Cargo; - if (_selectedCargoIndex >= 0 && _selectedCargoIndex < cargo.Count) - { - _onEquipCargo(_selectedCargoIndex, hardpointId); - _selectedCargoIndex = -1; - _lastCargoHash = -1; - } - } + private readonly char[] _buf; + private int _pos; - private void OnSchematicHoverChanged(Vector2I? cell, HardpointSpec? hp) - { - _lastHoveredCell = cell; - var grid = _schematic.Grid; - if (cell is null || grid is null) + public SpanWriter(char[] buf) { - if (!UpdateCargoSelectionTooltip(grid)) + _buf = buf; + _pos = 0; + } + + public readonly ReadOnlySpan Span => _buf.AsSpan(0, _pos); + + public void Append(ReadOnlySpan s) + { + int copy = Math.Min(s.Length, _buf.Length - _pos); + if (copy > 0) { - _hoverLabel.Text = "HOVER CELL FOR TELEMETRY"; - _hoverLabel.AddThemeColorOverride("font_color", TextMuted); - } - return; - } - - var c = cell.Value; - float arm = grid.Armor[c.X, c.Y]; - float maxArm = grid.MaxArmor[c.X, c.Y]; - float temp = grid.Temperature[c.X, c.Y]; - if (hp is not null) - { - var mounted = grid.GetMountedOn(hp.Id); - bool strippedHp = !grid.IsHardpointOperational(hp); - string hpStatus = strippedHp ? " [STRIPPED]" : ""; - if (mounted is not null && mounted.Spec.Procedural is { } proc) - { - _hoverLabel.Text = $"[{proc.ManufacturerLabel}] {proc.SummaryLine1}{hpStatus}\n{proc.SummaryLine2}"; - _hoverLabel.AddThemeColorOverride("font_color", - (arm <= 0.01f || strippedHp) ? RedCol : ResolveManufacturerHudColor(proc.Manufacturer)); - } - else - { - _hoverLabel.Text = mounted is not null - ? $"{hp.Kind.ToString().ToUpperInvariant()}: {mounted.Spec.Name} {mounted.CurrentTemp:F0}°C ({mounted.CurrentPerformance * 100f:F0}%){hpStatus}" - : $"{hp.Kind.ToString().ToUpperInvariant()} SLOT [{hp.Width}x{hp.Height}] EMPTY{hpStatus}"; - _hoverLabel.AddThemeColorOverride("font_color", (arm <= 0.01f || strippedHp) ? RedCol : TextLight); - } - } - else - { - _hoverLabel.Text = arm <= 0.01f - ? $"CELL ({c.X},{c.Y}) STRIPPED! {temp:F0}°C" - : $"HULL ({c.X},{c.Y}) ARM {arm:F0}/{maxArm:F0} {temp:F0}°C"; - _hoverLabel.AddThemeColorOverride("font_color", arm <= 0.01f ? RedCol : TextMuted); - } - } - - private bool UpdateCargoSelectionTooltip(ChassisGrid? grid) - { - if (grid is null || _selectedCargoIndex < 0 || _selectedCargoIndex >= grid.Cargo.Count) - { - return false; - } - var mod = grid.Cargo[_selectedCargoIndex]; - if (mod.Procedural is { } proc) - { - _hoverLabel.Text = $"[{proc.ManufacturerLabel}] {proc.SummaryLine1}\n{proc.SummaryLine2}"; - _hoverLabel.AddThemeColorOverride("font_color", ResolveManufacturerHudColor(proc.Manufacturer)); - } - else - { - _hoverLabel.Text = $"CARGO: {mod.Name} [{mod.Width}x{mod.Height}]"; - _hoverLabel.AddThemeColorOverride("font_color", mod.IsImperial ? GoldCol : TextLight); - } - return true; - } - - private static Color ResolveManufacturerHudColor(ManufacturerId mfg) => mfg switch - { - ManufacturerId.ScrapFrontier => Color.FromHtml("#ffaa33"), - ManufacturerId.KorrathiIronworks => Color.FromHtml("#f2c422"), - ManufacturerId.AuralianOptics => Color.FromHtml("#38e8ff"), - ManufacturerId.VexNineCollective => Color.FromHtml("#7cf230"), - ManufacturerId.ThalassanForge => Color.FromHtml("#2cb8ff"), - _ => GoldCol - }; - - private void SyncCargoButtons(ChassisGrid grid) - { - int hash = HashCode.Combine(grid.Cargo.Count, grid.Spec.CargoCapacity, _selectedCargoIndex); - for (int i = 0; i < grid.Cargo.Count; i++) - { - hash = HashCode.Combine(hash, grid.Cargo[i].Id); - } - if (hash == _lastCargoHash) return; - _lastCargoHash = hash; - - _cargoHeader.Text = $"SALVAGE CARGO ({grid.Cargo.Count}/{grid.Spec.CargoCapacity})"; - for (int i = _cargoList.GetChildCount() - 1; i >= 0; i--) - { - var c = _cargoList.GetChild(i); - _cargoList.RemoveChild(c); - c.QueueFree(); - } - - if (grid.Cargo.Count == 0) - { - var empty = new Label { Text = "No modules in rack.\nPress [E] near crates." }; - empty.AddThemeColorOverride("font_color", TextMuted); - empty.AddThemeFontSizeOverride("font_size", 11); - _cargoList.AddChild(empty); - return; - } - - for (int i = 0; i < grid.Cargo.Count; i++) - { - int idx = i; - var mod = grid.Cargo[i]; - var row = new HBoxContainer(); - row.AddThemeConstantOverride("separation", 4); - - var selectBtn = new Button - { - Text = $"{(mod.IsImperial ? "★ " : "")}{mod.Name}", - SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, - Alignment = HorizontalAlignment.Left, - FocusMode = Control.FocusModeEnum.None, - ClipText = true, - CustomMinimumSize = new Vector2(114f, 0f) - }; - selectBtn.AddThemeFontSizeOverride("font_size", 10); - if (_selectedCargoIndex == idx) - { - selectBtn.Modulate = OrangeCol; - } - else if (mod.IsImperial) - { - selectBtn.Modulate = GoldCol; - } - selectBtn.Pressed += () => - { - _selectedCargoIndex = (_selectedCargoIndex == idx) ? -1 : idx; - _lastCargoHash = -1; - }; - row.AddChild(selectBtn); - - var fitBtn = new Button { Text = "FIT", FocusMode = Control.FocusModeEnum.None }; - fitBtn.AddThemeFontSizeOverride("font_size", 10); - fitBtn.Pressed += () => AutoFitCargo(grid, idx); - row.AddChild(fitBtn); - - _cargoList.AddChild(row); - } - } - - private void AutoFitCargo(ChassisGrid grid, int cargoIndex) - { - if (cargoIndex < 0 || cargoIndex >= grid.Cargo.Count) return; - var mod = grid.Cargo[cargoIndex]; - for (int i = 0; i < grid.Spec.Hardpoints.Length; i++) - { - var hp = grid.Spec.Hardpoints[i]; - if (ChassisGrid.CanFit(hp, mod)) - { - _onEquipCargo(cargoIndex, hp.Id); - _selectedCargoIndex = -1; - _lastCargoHash = -1; - return; - } - } - } - - private void SyncBroadcastChyron(BroadcastFeed broadcast) - { - var lines = broadcast.Lines; - if (ReferenceEquals(_lastBroadcastFeed, broadcast) && broadcast.Version == _lastChyronVersion) - { - return; - } - - _lastBroadcastFeed = broadcast; - _lastChyronVersion = broadcast.Version; - - int start = Math.Max(0, lines.Count - _chyronLabels.Length); - int visibleCount = lines.Count - start; - for (int slot = 0; slot < _chyronLabels.Length; slot++) - { - var lbl = _chyronLabels[slot]; - if (slot < visibleCount) - { - int lineIdx = start + slot; - var line = lines[lineIdx]; - bool isLatest = lineIdx == lines.Count - 1; - lbl.Visible = true; - lbl.Text = $"[{line.Timestamp:00.0}s] {line.Text}"; - lbl.AddThemeFontSizeOverride("font_size", isLatest ? 12 : 11); - lbl.AddThemeColorOverride("font_color", isLatest ? TextLight : TextMuted); - } - else - { - lbl.Visible = false; - lbl.Text = ""; - } - } - } - - private static string BuildInteractionPrompt(MatchState state, ContenderState player) - { - GroundDrop? nearest = state.FindNearestInteractableDrop(player.Id); - if (nearest is null) return ""; - if (nearest.Module is { } mod) - { - var freeHp = player.Grid.FindFirstEmptyCompatibleHardpoint(mod); - if (mod.Procedural is { } proc) - { - string action = freeHp is not null - ? $"[E] Bolt [{proc.ManufacturerLabel}] {mod.Name} -> {freeHp.Id}" - : $"[E] Loot [{proc.ManufacturerLabel}] {mod.Name}"; - return $"{action}\n{proc.SummaryLine1} | {proc.SummaryLine2}"; - } - return freeHp is not null - ? $"[E] Bolt {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name} -> {freeHp.Id}" - : $"[E] Loot {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name}"; - } - if (nearest.Chassis is { } ch) - { - return $"[E] Swap to {ch.Name} ({ch.Plane})"; - } - return ""; - } - - private static string BuildGarageDetails(ChassisGrid grid, int selectedCargoIndex = -1) - { - var lines = new List - { - $"COND {grid.Spec.HullConductivity:F1} | THRUST {grid.ComputeDriveThrust():F0} N", - "MOUNTED:" - }; - for (int i = 0; i < grid.Mounted.Count; i++) - { - var m = grid.Mounted[i]; - string stateTag = grid.IsHardpointOperational(m.HardpointId) ? "" : " [STRIPPED]"; - if (m.Spec.Procedural is { } proc) - { - lines.Add($"• [{proc.ManufacturerLabel}] {m.Spec.Name} {m.CurrentTemp:F0}°C{stateTag}"); - lines.Add($" {proc.SummaryLine1}"); - lines.Add($" {proc.SummaryLine2}"); - } - else - { - lines.Add($"• {m.HardpointId}: {m.Spec.Name} {m.CurrentTemp:F0}°C ({(m.CurrentPerformance * 100f):F0}%){stateTag}"); - } - } - if (selectedCargoIndex >= 0 && selectedCargoIndex < grid.Cargo.Count && - grid.Cargo[selectedCargoIndex].Procedural is { } cargoProc) - { - lines.Add($"SEL [{cargoProc.ManufacturerLabel}]:"); - lines.Add($" {cargoProc.SummaryLine1}"); - lines.Add($" {cargoProc.SummaryLine2}"); - } - return string.Join("\n", lines); - } - - private static ChromePanel CreateStyledPanel(Color accentColor, float cornerLen = 12f, float borderPx = 1.5f) - { - return new ChromePanel(accentColor, cornerLen, borderPx); - } - - private sealed partial class ChromePanel : PanelContainer - { - private static Shader? _sharedChromeShader; - private static ImageTexture? _sharedWhiteTex; - private readonly ShaderMaterial _material; - - public ChromePanel(Color accentColor, float cornerLen, float borderPx) - { - _sharedChromeShader ??= GD.Load("res://panel_chrome.gdshader"); - if (_sharedWhiteTex is null) - { - var img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); - img.SetPixel(0, 0, Colors.White); - _sharedWhiteTex = ImageTexture.CreateFromImage(img); - } - - _material = new ShaderMaterial { Shader = _sharedChromeShader }; - _material.SetShaderParameter("bg_color", new Color(BgDark.R, BgDark.G, BgDark.B, 0.88f)); - _material.SetShaderParameter("border_color", BorderCol); - _material.SetShaderParameter("accent_color", accentColor); - _material.SetShaderParameter("corner_len", cornerLen); - _material.SetShaderParameter("border_px", borderPx); - Material = _material; - - var empty = new StyleBoxEmpty - { - ContentMarginLeft = 10, - ContentMarginRight = 10, - ContentMarginTop = 8, - ContentMarginBottom = 8 - }; - AddThemeStyleboxOverride("panel", empty); - } - - public ShaderMaterial ChromeMaterial => _material; - - public override void _Notification(int what) - { - if (what == NotificationResized) - { - _material.SetShaderParameter("rect_size", Size); - QueueRedraw(); + s[..copy].CopyTo(_buf.AsSpan(_pos)); + _pos += copy; } } - public override void _Draw() + public void AppendInt(int val) { - if (Size.X < 2f || Size.Y < 2f || _sharedWhiteTex is null) return; - _material.SetShaderParameter("rect_size", Size); - DrawTextureRect(_sharedWhiteTex, new Rect2(Vector2.Zero, Size), false, Colors.White); - } - } - - private sealed partial class CrosshairOverlay : Control - { - private const float HitArcDuration = 0.65f; - - private sealed class IncomingHitArc - { - public float SourceX; - public float SourceZ; - public WeaponVisualClass WeaponClass; - public float Age; - } - - private ContenderState? _player; - private OrbitalPod? _localPod; - private float _cameraYaw; - private MatchState? _lastState; - private readonly List _incomingArcs = new(); - private HitMarkerKind _hitMarkerKind; - private float _hitMarkerRemaining; - private float _hitMarkerDuration; - - public void SetState(MatchState state, ContenderState player, float cameraYaw, OrbitalPod? localPod = null) - { - if (!ReferenceEquals(_lastState, state)) + if (val.TryFormat(_buf.AsSpan(_pos), out int written, default, CultureInfo.InvariantCulture)) { - _lastState = state; - ResetFeedback(); - } - - _player = player; - _localPod = localPod; - _cameraYaw = cameraYaw; - } - - public void ResetFeedback() - { - _incomingArcs.Clear(); - _hitMarkerKind = HitMarkerKind.None; - _hitMarkerRemaining = 0f; - _hitMarkerDuration = 0f; - QueueRedraw(); - } - - public void TriggerHitMarker(bool coreHit, bool killed) - { - HitMarkerKind nextKind = killed - ? HitMarkerKind.Kill - : (coreHit ? HitMarkerKind.Core : HitMarkerKind.Armor); - // Preserve stronger hit-marker kind while active (Kill > Core > Armor) - if (_hitMarkerRemaining > 0f && (int)nextKind < (int)_hitMarkerKind) - { - nextKind = _hitMarkerKind; - } - _hitMarkerKind = nextKind; - _hitMarkerDuration = nextKind switch - { - HitMarkerKind.Kill => 0.38f, - HitMarkerKind.Core => 0.26f, - _ => 0.18f - }; - _hitMarkerRemaining = _hitMarkerDuration; - QueueRedraw(); - } - - public void Advance(float dt) - { - bool dirty = false; - if (_incomingArcs.Count > 0 && dt > 0f) - { - for (int i = _incomingArcs.Count - 1; i >= 0; i--) - { - _incomingArcs[i].Age += dt; - if (_incomingArcs[i].Age >= HitArcDuration) - { - _incomingArcs.RemoveAt(i); - } - } - dirty = true; - } - - if (_hitMarkerRemaining > 0f && dt > 0f) - { - _hitMarkerRemaining = MathF.Max(0f, _hitMarkerRemaining - dt); - if (_hitMarkerRemaining <= 0.001f) - { - _hitMarkerRemaining = 0f; - _hitMarkerKind = HitMarkerKind.None; - } - dirty = true; - } - - if (dirty) - { - QueueRedraw(); + _pos += written; } } - public void PushTestHitArc(float sourceX, float sourceZ, WeaponVisualClass weaponClass) + public void AppendFloat(float val, ReadOnlySpan fmt) { - if (_incomingArcs.Count >= 8) _incomingArcs.RemoveAt(0); - _incomingArcs.Add(new IncomingHitArc + if (val.TryFormat(_buf.AsSpan(_pos), out int written, fmt, CultureInfo.InvariantCulture)) { - SourceX = sourceX, - SourceZ = sourceZ, - WeaponClass = weaponClass, - Age = 0f - }); - QueueRedraw(); - } - - public int ActiveHitArcCount => _incomingArcs.Count; - public bool HasActiveHitMarker => _hitMarkerRemaining > 0f && _hitMarkerKind != HitMarkerKind.None; - public HitMarkerKind ActiveHitMarkerKind => HasActiveHitMarker ? _hitMarkerKind : HitMarkerKind.None; - - public override void _Draw() - { - Vector2 center = Size * 0.5f; - float gap = 6f; - float tick = 10f; - bool allDisabled = _player is not null && _player.Alive && - _player.InArcWeaponCount == 0 && _player.OutOfArcWeaponCount == 0 && _player.DisabledWeaponCount > 0; - bool outOfArc = _player is not null && _player.Alive && _player.AllWeaponsOutOfArc; - Color retCol = (outOfArc || allDisabled) - ? new Color(RedCol.R, RedCol.G, RedCol.B, 0.95f) - : new Color(TextLight.R, TextLight.G, TextLight.B, 0.88f); - - // Clean 4-tick center crosshair + center pip - DrawCircle(center, 1.8f, retCol); - DrawLine(center + new Vector2(-gap - tick, 0f), center + new Vector2(-gap, 0f), retCol, 1.6f); - DrawLine(center + new Vector2(gap, 0f), center + new Vector2(gap + tick, 0f), retCol, 1.6f); - DrawLine(center + new Vector2(0f, -gap - tick), center + new Vector2(0f, -gap), retCol, 1.6f); - DrawLine(center + new Vector2(0f, gap), center + new Vector2(0f, gap + tick), retCol, 1.6f); - - // Outgoing reticle hit-marker X-flash (white/gold armor, crimson core, crimson double-X kill) - if (_hitMarkerRemaining > 0f && _hitMarkerDuration > 0.001f && _hitMarkerKind != HitMarkerKind.None) - { - float frac = Math.Clamp(_hitMarkerRemaining / _hitMarkerDuration, 0f, 1f); - float pop = 1.0f + (1.0f - frac) * 0.25f; - Color xCol = _hitMarkerKind switch - { - HitMarkerKind.Kill => new Color(RedCol.R, RedCol.G, RedCol.B, frac * 0.98f), - HitMarkerKind.Core => new Color(1.0f, 0.28f, 0.16f, frac * 0.95f), - _ => new Color(1.0f, 0.95f, 0.78f, frac * 0.92f) - }; - float xWidth = _hitMarkerKind == HitMarkerKind.Armor ? 2.0f : 2.8f; - float rIn = 6.5f * pop; - float rOut = (_hitMarkerKind == HitMarkerKind.Armor ? 13.5f : 15.5f) * pop; - const float diag = 0.70710678f; - for (int q = 0; q < 4; q++) - { - float sx = (q & 1) == 0 ? 1f : -1f; - float sy = (q & 2) == 0 ? 1f : -1f; - Vector2 dir = new(sx * diag, sy * diag); - DrawLine(center + dir * rIn, center + dir * rOut, xCol, xWidth); - if (_hitMarkerKind == HitMarkerKind.Kill) - { - DrawLine(center + dir * (rOut + 4f), center + dir * (rOut + 10.5f), new Color(GoldCol.R, GoldCol.G, GoldCol.B, frac * 0.95f), 2.2f); - } - } + _pos += written; } - - if (allDisabled) - { - DrawString( - UiFonts.Regular, - center + new Vector2(-52f, 36f), - "WEAPONS STRIPPED", - HorizontalAlignment.Left, - -1, - 11, - RedCol); - } - else if (outOfArc) - { - DrawString( - UiFonts.Regular, - center + new Vector2(-34f, 36f), - "OUT OF ARC", - HorizontalAlignment.Left, - -1, - 11, - RedCol); - } - - if (_player is null || !_player.Alive) - { - return; - } - - if (_player.IsInDropPod) - { - float agl = _localPod is not null ? MathF.Max(0f, _localPod.LastAgl) : 0f; - float vel = _localPod is not null ? MathF.Max(0f, -_localPod.VelY) : 0f; - float horizSpeed = _localPod is not null - ? MathF.Sqrt(_localPod.VelX * _localPod.VelX + _localPod.VelZ * _localPod.VelZ) - : _player.Speed; - bool burning = _localPod?.Phase == OrbitalPodPhase.RetroBurn; - Color bracketCol = burning ? OrangeCol : CyanCol; - - float startAlt = OrbitalPodPreset.GetStartAltAgl(OrbitalPodKind.Contender, _lastState?.MapKind ?? ArenaMapKind.Desert); - float altFrac = Math.Clamp(agl / MathF.Max(1f, startAlt), 0f, 1f); - const float barX = 72f; - const float barH = 76f; - Vector2 topL = center + new Vector2(-barX, -barH * 0.5f); - Vector2 topR = center + new Vector2(barX, -barH * 0.5f); - DrawLine(topL, topL + new Vector2(0f, barH), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.55f), 2.0f); - DrawLine(topR, topR + new Vector2(0f, barH), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.55f), 2.0f); - - float fillH = barH * altFrac; - DrawLine(topL + new Vector2(0f, barH - fillH), topL + new Vector2(0f, barH), bracketCol, 3.0f); - DrawLine(topR + new Vector2(0f, barH - fillH), topR + new Vector2(0f, barH), bracketCol, 3.0f); - - DrawString( - UiFonts.Regular, - center + new Vector2(-88f, 54f), - $"ALT {agl:F0}m | HORIZ {horizSpeed:F0} m/s | VERT {vel:F0} m/s", - HorizontalAlignment.Left, - -1, - 11, - bracketCol); - if (burning) - { - DrawString( - UiFonts.Regular, - center + new Vector2(-46f, -52f), - "RETRO BURN ACTIVE", - HorizontalAlignment.Left, - -1, - 11, - OrangeCol); - } - return; - } - - // Thermal heat-arc indicator around crosshair - float heatRatio = 0f; - bool overPlateau = false; - var mounted = _player.Grid.Mounted; - for (int i = 0; i < mounted.Count; i++) - { - var m = mounted[i]; - if (m.Spec.Kind == HardpointKind.Weapon) - { - float r = Math.Clamp( - (m.CurrentTemp - ChassisGrid.AmbientTemp) / MathF.Max(1f, m.Spec.MaxTemp - ChassisGrid.AmbientTemp), - 0f, 1f); - if (r > heatRatio) heatRatio = r; - if (m.CurrentTemp > m.Spec.OptimalTemp + m.Spec.PlateauWidth * 0.5f) - { - overPlateau = true; - } - } - } - - float arcRadius = 21f; - float startAngle = -MathF.PI * 0.75f; - float maxSweep = MathF.PI * 1.5f; - DrawArc(center, arcRadius, startAngle, startAngle + maxSweep, 24, new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.4f), 2.0f); - - if (heatRatio > 0.01f) - { - Color heatCol = overPlateau - ? RedCol - : (heatRatio > 0.65f ? OrangeCol : OliveCol); - DrawArc(center, arcRadius, startAngle, startAngle + maxSweep * heatRatio, 24, heatCol, 2.4f); - } - - // Directional incoming-hit indicator arcs (fade over 0.65s) - if (_incomingArcs.Count > 0) - { - float sinY = MathF.Sin(_cameraYaw); - float cosY = MathF.Cos(_cameraYaw); - for (int i = 0; i < _incomingArcs.Count; i++) - { - var arc = _incomingArcs[i]; - float alpha = Math.Clamp(1f - arc.Age / HitArcDuration, 0f, 1f); - if (alpha <= 0.01f) - { - continue; - } - - float dx = arc.SourceX - _player.X; - float dz = arc.SourceZ - _player.Z; - float rx = -dx * cosY + dz * sinY; - float fy = dx * sinY + dz * cosY; - float angle = (rx * rx + fy * fy) > 1e-4f ? MathF.Atan2(-fy, rx) : 0f; - - Color arcCol = arc.WeaponClass switch - { - WeaponVisualClass.Explosive => new Color(1.0f, 0.36f, 0.12f, alpha * 0.96f), - WeaponVisualClass.RocketSalvo => new Color(1.0f, 0.56f, 0.14f, alpha * 0.96f), - WeaponVisualClass.ThermalBeam => new Color(0.30f, 0.90f, 1.0f, alpha * 0.96f), - WeaponVisualClass.GaussRail => new Color(0.24f, 0.78f, 1.0f, alpha * 0.98f), - WeaponVisualClass.PlasmaPpc => new Color(0.18f, 0.92f, 0.96f, alpha * 0.96f), - WeaponVisualClass.SwarmSmart => new Color(0.56f, 0.96f, 0.28f, alpha * 0.96f), - _ => new Color(0.96f, 0.72f, 0.22f, alpha * 0.94f) - }; - - const float hitR = 39f; - const float halfSpan = 0.34f; - DrawArc(center, hitR, angle - halfSpan, angle + halfSpan, 14, arcCol, 4.2f); - if (arc.WeaponClass is WeaponVisualClass.ThermalBeam or WeaponVisualClass.GaussRail or WeaponVisualClass.PlasmaPpc) - { - DrawArc(center, hitR - 3.5f, angle - halfSpan * 0.75f, angle + halfSpan * 0.75f, 10, - new Color(GoldCol.R, GoldCol.G, GoldCol.B, alpha * 0.90f), 2.0f); - } - - Vector2 dirVec = new(MathF.Cos(angle), MathF.Sin(angle)); - Vector2 perp = new(-dirVec.Y, dirVec.X); - Vector2 tip = center + dirVec * (hitR + 9f); - Vector2 baseL = center + dirVec * (hitR + 1.5f) - perp * 4.5f; - Vector2 baseR = center + dirVec * (hitR + 1.5f) + perp * 4.5f; - DrawColoredPolygon(new[] { tip, baseL, baseR }, arcCol); - } - - var latest = _incomingArcs[^1]; - float tagAlpha = Math.Clamp(1f - latest.Age / HitArcDuration, 0f, 1f); - (string tagText, Color tagCol) = latest.WeaponClass switch - { - WeaponVisualClass.Autocannon => ("20MM IMPACT", new Color(0.98f, 0.70f, 0.20f, tagAlpha)), - WeaponVisualClass.Explosive => ("BLAST IMPACT", new Color(1.0f, 0.38f, 0.14f, tagAlpha)), - WeaponVisualClass.RocketSalvo => ("ROCKET HIT", new Color(1.0f, 0.58f, 0.18f, tagAlpha)), - WeaponVisualClass.ThermalBeam => ("THERMAL HIT", new Color(0.36f, 0.92f, 1.0f, tagAlpha)), - WeaponVisualClass.GaussRail => ("GAUSS RAIL", new Color(0.28f, 0.84f, 1.0f, tagAlpha)), - WeaponVisualClass.PlasmaPpc => ("PLASMA BURN", new Color(0.24f, 0.94f, 0.98f, tagAlpha)), - WeaponVisualClass.SwarmSmart => ("SWARM HIT", new Color(0.58f, 0.96f, 0.30f, tagAlpha)), - _ => ("KINETIC HIT", new Color(0.96f, 0.78f, 0.28f, tagAlpha)) - }; - DrawString( - UiFonts.Regular, - center + new Vector2(-36f, 54f), - tagText, - HorizontalAlignment.Left, - -1, - 10, - tagCol); - } - } - } - - private sealed partial class RadarWidget : Control - { - private IClientArenaSession? _session; - private float _cameraYaw; - - public void SetState(IClientArenaSession session, float cameraYaw) - { - _session = session; - _cameraYaw = cameraYaw; - } - - private static Vector2 WorldToRadar(Vector2 center, float scale, float wx, float wz, float camYaw) - { - // Heading-up 3P radar: camera forward (sinY, cosY) is always UP (-screenY), camera right (-cosY, sinY) is RIGHT (+screenX). - float sinY = MathF.Sin(camYaw); - float cosY = MathF.Cos(camYaw); - float rx = -wx * cosY + wz * sinY; - float fy = wx * sinY + wz * cosY; - return center + new Vector2(rx, -fy) * scale; - } - - private static Vector2 ClampToRadarDisc(Vector2 center, float maxRadius, Vector2 pt) - { - Vector2 delta = pt - center; - float dist = delta.Length(); - if (dist > maxRadius && dist > 1e-4f) - { - return center + delta * (maxRadius / dist); - } - return pt; - } - - public override void _Draw() - { - Vector2 center = Size * 0.5f; - float radius = MathF.Min(Size.X, Size.Y) * 0.47f; - float maxBlipRadius = MathF.Max(4f, radius - 3f); - var state = _session?.ViewState; - float arenaHalf = MathF.Max(1f, state?.Terrain.MapHalfExtent ?? MatchState.ArenaHalfExtent); - float scale = radius / arenaHalf; - - DrawCircle(center, radius, BgInner); - DrawArc(center, radius, 0f, MathF.Tau, 48, BorderCol, 1.5f); - // Forward-up indicator tick at top of radar - DrawLine(center + new Vector2(0f, -radius), center + new Vector2(0f, -radius + 6f), CyanCol, 2.0f); - - if (_session is null || state is null) return; - - int localId = _session.LocalContenderId; - - // Safe Circle - float safePx = MathF.Min(state.Spectators.SafeRadius * scale, maxBlipRadius); - DrawArc(center, safePx, 0f, MathF.Tau, 64, OrangeCol, 1.6f); - - // Ground drops - for (int i = 0; i < state.GroundDrops.Count; i++) - { - var d = state.GroundDrops[i]; - if (d.PickedUp) continue; - var p = ClampToRadarDisc(center, MathF.Max(4f, radius - 4f), WorldToRadar(center, scale, d.X, d.Z, _cameraYaw)); - if (d.Chassis is not null) - { - DrawRect(new Rect2(p - new Vector2(2.5f, 2.5f), new Vector2(5f, 5f)), CyanCol); - } - else if (d.Module is { IsImperial: true }) - { - DrawCircle(p, 3.0f, GoldCol); - } - } - - // Active descending Orbital Pods (cyan/gold diamonds for gear, chevrons for contenders) - var pods = _session.ActivePods; - for (int i = 0; i < pods.Count; i++) - { - var pod = pods[i]; - if (pod.Phase == OrbitalPodPhase.Popped) continue; - var pp = ClampToRadarDisc(center, MathF.Max(4f, radius - 5f), WorldToRadar(center, scale, pod.X, pod.Z, _cameraYaw)); - if (pod.PodKind == OrbitalPodKind.Contender) - { - bool isLocalPod = pod.ContenderId == localId; - bool isAllyPod = !isLocalPod && state.AreAllies(localId, pod.ContenderId); - if (isAllyPod) - { - const float d = 4.6f; - var pts = new[] - { - pp + new Vector2(0f, -d), - pp + new Vector2(d, 0f), - pp + new Vector2(0f, d), - pp + new Vector2(-d, 0f) - }; - DrawColoredPolygon(pts, AlliedCol); - } - else - { - Color pCol = isLocalPod ? OliveCol : OrangeCol; - float sz = isLocalPod ? 5.5f : 3.6f; - var pts = new[] - { - pp + new Vector2(0f, -sz), - pp + new Vector2(-sz * 0.8f, sz * 0.7f), - pp + new Vector2(sz * 0.8f, sz * 0.7f) - }; - DrawColoredPolygon(pts, pCol); - } - } - else - { - bool isImp = pod.WaveIndex > 0 || pod.Module?.IsImperial == true; - Color gCol = isImp ? GoldCol : CyanCol; - const float d = 3.2f; - var pts = new[] - { - pp + new Vector2(0f, -d), - pp + new Vector2(d, 0f), - pp + new Vector2(0f, d), - pp + new Vector2(-d, 0f) - }; - DrawColoredPolygon(pts, gCol); - } - } - - // Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory; hidden Exemplars vanish!) - var contenderContacts = _session.LocalContenderContacts; - var spectatorContacts = _session.LocalSpectatorContacts; - var specs = state.Spectators.Spectators; - for (int i = 0; i < specs.Count; i++) - { - var s = specs[i]; - if (!s.Alive) continue; - - spectatorContacts.TryGetValue(s.Id, out var mem); - if (!MatchState.IsContactOnRadar(mem)) - { - continue; - } - - bool live = mem!.VisibleToPlayer; - bool hasLivePos = _session.IsSpectatorVisible(s.Id) && (live || mem.FaintHorizonPing); - if (!hasLivePos && !mem.HasEverBeenSeen) - { - continue; - } - float drawX = hasLivePos ? s.X : mem.LastSeenX; - float drawZ = hasLivePos ? s.Z : mem.LastSeenZ; - float blipR = 1.6f + s.RadarSignature * 3.1f; - float specClampR = MathF.Max(4f, radius - blipR - 1f); - var p = ClampToRadarDisc(center, specClampR, WorldToRadar(center, scale, drawX, drawZ, _cameraYaw)); - - Color col = s.Tier switch - { - SpectatorTier.Tourist => GoldCol, - SpectatorTier.Patron => PatronColor, - _ => RedCol - }; - - if (live && s.Stance != SpectatorStance.Neutral && s.HasTargetLos && s.TargetContenderId.HasValue) - { - int tid = s.TargetContenderId.Value; - if (tid >= 0 && tid < state.Contenders.Count && state.Contenders[tid].Alive) - { - var tgt = state.Contenders[tid]; - bool targetVisible = tgt.Id == localId || - (_session.IsContenderVisible(tgt.Id) && contenderContacts.TryGetValue(tgt.Id, out var tgtMem) && tgtMem.VisibleToPlayer); - if (targetVisible) - { - float tgtClampR = MathF.Max(4f, radius - (tgt.Id == localId ? 7.5f : 4.3f)); - var tp = ClampToRadarDisc(center, tgtClampR, WorldToRadar(center, scale, tgt.X, tgt.Z, _cameraYaw)); - DrawLine(p, tp, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f), 1.3f); - } - } - col = RedCol; - } - - if (!live) - { - float alpha = mem.FaintHorizonPing - ? 0.42f - : Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); - Color ghostCol = mem.FaintHorizonPing ? GoldCol : col; - DrawCircle(p, blipR, new Color(ghostCol.R, ghostCol.G, ghostCol.B, alpha)); - } - else - { - DrawCircle(p, blipR, col); - } - } - - // Contenders (player always live; rivals obey LOS + 5s ghost memory) - float sinY = MathF.Sin(_cameraYaw); - float cosY = MathF.Cos(_cameraYaw); - for (int i = 0; i < state.Contenders.Count; i++) - { - var c = state.Contenders[i]; - if (!c.IsGroundedActive) continue; - - if (c.Id == localId) - { - float playerClampR = MathF.Max(4f, radius - 6.5f - 1f); - var (lPos, _, _) = _session.GetInterpolatedContenderPose(localId, 1f); - var p = ClampToRadarDisc(center, playerClampR, WorldToRadar(center, scale, lPos.X, lPos.Z, _cameraYaw)); - var dir = new Vector2( - -MathF.Sin(c.Yaw) * cosY + MathF.Cos(c.Yaw) * sinY, - -(MathF.Sin(c.Yaw) * sinY + MathF.Cos(c.Yaw) * cosY)); - var perp = new Vector2(-dir.Y, dir.X); - var pts = new[] - { - p + dir * 6.5f, - p - dir * 4.5f + perp * 4.2f, - p - dir * 4.5f - perp * 4.2f - }; - DrawColoredPolygon(pts, OliveCol); - continue; - } - - if (state.AreAllies(localId, c.Id)) - { - float allyClampR = MathF.Max(4f, radius - 4.6f - 1f); - var (aPos, _, _) = _session.GetInterpolatedContenderPose(c.Id, 1f); - var p = ClampToRadarDisc(center, allyClampR, WorldToRadar(center, scale, aPos.X, aPos.Z, _cameraYaw)); - const float d = 4.6f; - var pts = new[] - { - p + new Vector2(0f, -d), - p + new Vector2(d, 0f), - p + new Vector2(0f, d), - p + new Vector2(-d, 0f) - }; - DrawColoredPolygon(pts, AlliedCol); - continue; - } - - contenderContacts.TryGetValue(c.Id, out var mem); - if (!MatchState.IsContactOnRadar(mem)) - { - continue; - } - - if (mem!.VisibleToPlayer) - { - float rivalClampR = MathF.Max(4f, radius - 3.3f - 1f); - float rx = _session.IsContenderVisible(c.Id) ? c.X : mem.LastSeenX; - float rz = _session.IsContenderVisible(c.Id) ? c.Z : mem.LastSeenZ; - var p = ClampToRadarDisc(center, rivalClampR, WorldToRadar(center, scale, rx, rz, _cameraYaw)); - DrawCircle(p, 3.3f, OrangeCol); - } - else - { - float ghostClampR = MathF.Max(4f, radius - 2.8f - 1f); - var p = ClampToRadarDisc(center, ghostClampR, WorldToRadar(center, scale, mem.LastSeenX, mem.LastSeenZ, _cameraYaw)); - float alpha = Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); - DrawCircle(p, 2.8f, new Color(OrangeCol.R, OrangeCol.G, OrangeCol.B, alpha)); - } - } - } - - private static readonly Color PatronColor = Color.FromHtml("#4ba8a5"); - } - - private sealed partial class WorldMarkerOverlay : Control - { - private const float BorderPad = 36f; - private const float PanelAvoidPad = 18f; - private const float OffscreenHostileMaxDistance = 220f; - private const int MaxOffscreenHostileArrows = 6; - - private readonly struct OffscreenMarker - { - public readonly System.Numerics.Vector3 CamLocal; - public readonly float Distance; - public readonly Color Color; - public readonly bool IsLockedOnLocal; - - public OffscreenMarker(System.Numerics.Vector3 camLocal, float distance, Color color, bool isLockedOnLocal) - { - CamLocal = camLocal; - Distance = distance; - Color = color; - IsLockedOnLocal = isLockedOnLocal; - } - } - - private IClientArenaSession? _session; - private Func? _projectWorld; - private Control?[] _avoidPanels = Array.Empty(); - private readonly List _offscreenHostiles = new(16); - private readonly Vector2[] _cornerBuf = new Vector2[3]; - private readonly Vector2[] _triBuf = new Vector2[3]; - private readonly Vector2[] _shadowTriBuf = new Vector2[3]; - - public void SetAvoidPanels(params Control?[] panels) - { - _avoidPanels = panels ?? Array.Empty(); - } - - public void SetState( - IClientArenaSession session, - Func? projectWorld) - { - _session = session; - _projectWorld = projectWorld; - } - - public override void _Draw() - { - if (_session is null || _projectWorld is null) return; - var state = _session.ViewState; - - int localId = _session.LocalContenderId; - if (localId < 0 || localId >= state.Contenders.Count) return; - if (!state.Contenders[localId].Alive) return; - - Vector2 viewSize = Size; - if (viewSize.X < 64f || viewSize.Y < 64f) return; - - var (localPos, _, _) = _session.GetInterpolatedContenderPose(localId, 1f); - Vector2 center = viewSize * 0.5f; - float halfW = MathF.Max(16f, center.X - BorderPad); - float halfH = MathF.Max(16f, center.Y - BorderPad); - Font font = UiFonts.Regular; - - // 1. Allied squad chevrons (only when SquadSize > 1) - if (state.SquadSize > 1) - { - for (int i = 0; i < state.Contenders.Count; i++) - { - var c = state.Contenders[i]; - if (c.Id == localId || !c.Alive || !state.AreAllies(localId, c.Id)) continue; - - var (allyPos, _, _) = _session.GetInterpolatedContenderPose(c.Id, 1f); - float dist = (allyPos - localPos).Length(); - float headOffset = c.IsInDropPod ? 3.4f : (c.Grid.Spec.HalfHeight + 1.9f); - var worldHead = new System.Numerics.Vector3(allyPos.X, allyPos.Y + headOffset, allyPos.Z); - var (valid, inFront, sp, camLocal) = _projectWorld(worldHead); - if (!valid) continue; - - bool inFrame = inFront && - sp.X >= BorderPad && sp.X <= viewSize.X - BorderPad && - sp.Y >= BorderPad && sp.Y <= viewSize.Y - BorderPad; - - string label = $"{c.Name} {dist:F0}m"; - if (inFrame) - { - _triBuf[0] = sp + new Vector2(0f, 5f); - _triBuf[1] = sp + new Vector2(-6f, -5f); - _triBuf[2] = sp + new Vector2(6f, -5f); - DrawColoredPolygon(_triBuf, AlliedCol); - DrawString( - font, - sp + new Vector2(-28f, -11f), - label, - HorizontalAlignment.Left, - -1, - 10, - AlliedCol); - } - else - { - Vector2 dir = ComputeOffscreenDirection(camLocal); - Vector2 edge = ComputeSafeEdgePos(center, halfW, halfH, dir); - Vector2 perp = new(-dir.Y, dir.X); - - _triBuf[0] = edge + dir * 7f; - _triBuf[1] = edge - dir * 5f + perp * 5f; - _triBuf[2] = edge - dir * 5f - perp * 5f; - DrawColoredPolygon(_triBuf, new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.88f)); - Vector2 textPos = ComputeInwardLabelPos(edge, dir, viewSize, font, label); - DrawString( - font, - textPos, - label, - HorizontalAlignment.Left, - -1, - 10, - new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.90f)); - } - } - } - - // 2. Visible enemy contenders (strictly obeying fog-of-war / LOS) - var contenderContacts = _session.LocalContenderContacts; - var spectatorContacts = _session.LocalSpectatorContacts; - _offscreenHostiles.Clear(); - - for (int i = 0; i < state.Contenders.Count; i++) - { - var c = state.Contenders[i]; - if (c.Id == localId || !c.Alive || state.AreAllies(localId, c.Id)) continue; - if (!_session.IsContenderVisible(c.Id)) continue; - if (!contenderContacts.TryGetValue(c.Id, out var mem) || !mem.VisibleToPlayer) continue; - - var (pos, rot, _) = _session.GetInterpolatedContenderPose(c.Id, 1f); - float dist = (pos - localPos).Length(); - bool targetingLocal = c.AiTargetContenderId == localId; - Color col = targetingLocal ? RedCol : OrangeCol; - float hpRatio = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f; - - float halfBoundW = c.IsInDropPod ? 1.4f : c.Grid.Spec.HalfWidth; - float halfBoundH = c.IsInDropPod ? 1.8f : c.Grid.Spec.HalfHeight; - float halfBoundL = c.IsInDropPod ? 1.4f : c.Grid.Spec.HalfLength; - - ProcessHostileTarget( - pos, rot, halfBoundW, halfBoundH, halfBoundL, - dist, hpRatio, col, targetingLocal, - viewSize, font); - } - - // 3. Visible hostile/provoked spectators (neutral tourists do NOT get hostile target boxes) - var specs = state.Spectators.Spectators; - for (int i = 0; i < specs.Count; i++) - { - var s = specs[i]; - if (!s.Alive || s.Stance == SpectatorStance.Neutral) continue; - if (!_session.IsSpectatorVisible(s.Id)) continue; - if (!spectatorContacts.TryGetValue(s.Id, out var mem) || !mem.VisibleToPlayer) continue; - - var (pos, rot, _) = _session.GetInterpolatedSpectatorPose(s.Id, 1f); - float dist = (pos - localPos).Length(); - bool lockedOnLocal = s.TargetContenderId == localId; - float hpRatio = s.Grid.MaxCoreHp > 0f ? s.Grid.CoreHp / s.Grid.MaxCoreHp : 1f; - - ProcessHostileTarget( - pos, rot, s.Grid.Spec.HalfWidth, s.Grid.Spec.HalfHeight, s.Grid.Spec.HalfLength, - dist, hpRatio, RedCol, lockedOnLocal, - viewSize, font); - } - - // 4. Off-screen hostile arrows (locked-on threats first, then nearest visible hostiles) - if (_offscreenHostiles.Count > 0) - { - _offscreenHostiles.Sort(static (a, b) => - { - int lockCmp = b.IsLockedOnLocal.CompareTo(a.IsLockedOnLocal); - return lockCmp != 0 ? lockCmp : a.Distance.CompareTo(b.Distance); - }); - - int count = Math.Min(_offscreenHostiles.Count, MaxOffscreenHostileArrows); - for (int i = 0; i < count; i++) - { - DrawOffscreenArrow(_offscreenHostiles[i], viewSize, center, halfW, halfH, font); - } - } - } - - private void ProcessHostileTarget( - System.Numerics.Vector3 worldCenter, - System.Numerics.Quaternion rot, - float halfBoundW, - float halfBoundH, - float halfBoundL, - float dist, - float hpRatio, - Color col, - bool isLockedOnLocal, - Vector2 viewSize, - Font font) - { - var (cValid, cInFront, cSp, cCamLocal) = _projectWorld!(worldCenter); - if (!cValid) return; - - bool inFrame = cInFront && - cSp.X >= BorderPad && cSp.X <= viewSize.X - BorderPad && - cSp.Y >= BorderPad && cSp.Y <= viewSize.Y - BorderPad; - - if (!inFrame) - { - if (isLockedOnLocal || dist <= OffscreenHostileMaxDistance) - { - _offscreenHostiles.Add(new OffscreenMarker(cCamLocal, dist, col, isLockedOnLocal)); - } - return; - } - - float minX = float.PositiveInfinity, minY = float.PositiveInfinity; - float maxX = float.NegativeInfinity, maxY = float.NegativeInfinity; - bool allCornersInFront = true; - - for (int sx = -1; sx <= 1; sx += 2) - { - for (int sy = -1; sy <= 1; sy += 2) - { - for (int sz = -1; sz <= 1; sz += 2) - { - var localCorner = new System.Numerics.Vector3(sx * halfBoundW, sy * halfBoundH, sz * halfBoundL); - var worldCorner = worldCenter + System.Numerics.Vector3.Transform(localCorner, rot); - var (valid, inFront, sp, _) = _projectWorld(worldCorner); - if (!valid || !inFront) - { - allCornersInFront = false; - break; - } - if (sp.X < minX) minX = sp.X; - if (sp.X > maxX) maxX = sp.X; - if (sp.Y < minY) minY = sp.Y; - if (sp.Y > maxY) maxY = sp.Y; - } - if (!allCornersInFront) break; - } - if (!allCornersInFront) break; - } - - if (!allCornersInFront) - { - var (topValid, topFront, topSp, _) = _projectWorld(worldCenter + new System.Numerics.Vector3(0f, halfBoundH, 0f)); - var (botValid, botFront, botSp, _) = _projectWorld(worldCenter - new System.Numerics.Vector3(0f, halfBoundH, 0f)); - float rawH = (topValid && topFront && botValid && botFront) - ? MathF.Abs(botSp.Y - topSp.Y) + 8f - : 44f; - float horizRadius = MathF.Max(halfBoundW, halfBoundL); - float rawW = rawH * (horizRadius / MathF.Max(0.4f, halfBoundH)); - minX = cSp.X - rawW * 0.5f; - maxX = cSp.X + rawW * 0.5f; - minY = cSp.Y - rawH * 0.5f; - maxY = cSp.Y + rawH * 0.5f; - } - else - { - minX -= 3f; - maxX += 3f; - minY -= 3f; - maxY += 3f; - } - - float boxW = Math.Clamp(maxX - minX, 22f, 220f); - float boxH = Math.Clamp(maxY - minY, 22f, 220f); - Vector2 boxCenter = new((minX + maxX) * 0.5f, (minY + maxY) * 0.5f); - var rect = new Rect2(boxCenter.X - boxW * 0.5f, boxCenter.Y - boxH * 0.5f, boxW, boxH); - - DrawTargetBox(rect, col, dist, hpRatio, isLockedOnLocal, font); - } - - private void DrawTargetBox(Rect2 rect, Color col, float dist, float hpRatio, bool isLockedOnLocal, Font font) - { - float x0 = rect.Position.X; - float y0 = rect.Position.Y; - float x1 = x0 + rect.Size.X; - float y1 = y0 + rect.Size.Y; - float legX = Math.Clamp(rect.Size.X * 0.22f, 5f, 26f); - float legY = Math.Clamp(rect.Size.Y * 0.22f, 5f, 26f); - - Color shadowCol = new(0.04f, 0.05f, 0.04f, 0.78f); - Color strokeCol = new(col.R, col.G, col.B, 0.95f); - - // Top-left - _cornerBuf[0] = new Vector2(x0, y0 + legY); - _cornerBuf[1] = new Vector2(x0, y0); - _cornerBuf[2] = new Vector2(x0 + legX, y0); - DrawPolyline(_cornerBuf, shadowCol, 3.6f); - DrawPolyline(_cornerBuf, strokeCol, 2.0f); - - // Top-right - _cornerBuf[0] = new Vector2(x1 - legX, y0); - _cornerBuf[1] = new Vector2(x1, y0); - _cornerBuf[2] = new Vector2(x1, y0 + legY); - DrawPolyline(_cornerBuf, shadowCol, 3.6f); - DrawPolyline(_cornerBuf, strokeCol, 2.0f); - - // Bottom-right - _cornerBuf[0] = new Vector2(x1, y1 - legY); - _cornerBuf[1] = new Vector2(x1, y1); - _cornerBuf[2] = new Vector2(x1 - legX, y1); - DrawPolyline(_cornerBuf, shadowCol, 3.6f); - DrawPolyline(_cornerBuf, strokeCol, 2.0f); - - // Bottom-left - _cornerBuf[0] = new Vector2(x0 + legX, y1); - _cornerBuf[1] = new Vector2(x0, y1); - _cornerBuf[2] = new Vector2(x0, y1 - legY); - DrawPolyline(_cornerBuf, shadowCol, 3.6f); - DrawPolyline(_cornerBuf, strokeCol, 2.0f); - - // Thin HP bar right above top bracket - float barW = Math.Clamp(rect.Size.X, 22f, 64f); - float barX = (x0 + x1) * 0.5f - barW * 0.5f; - float barY = y0 - 7f; - DrawRect(new Rect2(barX - 1f, barY - 1f, barW + 2f, 4f), new Color(0.04f, 0.05f, 0.04f, 0.78f)); - DrawRect(new Rect2(barX, barY, barW * Math.Clamp(hpRatio, 0f, 1f), 2f), strokeCol); - - // Distance + LOCK tag above HP bar - string label = isLockedOnLocal ? $"{dist:F0}m LOCK" : $"{dist:F0}m"; - Vector2 textSize = font.GetStringSize(label, HorizontalAlignment.Left, -1, 10); - Vector2 textPos = new((x0 + x1) * 0.5f - textSize.X * 0.5f, barY - 3f); - DrawString(font, textPos + new Vector2(1f, 1f), label, HorizontalAlignment.Left, -1, 10, new Color(0.04f, 0.05f, 0.04f, 0.90f)); - DrawString(font, textPos, label, HorizontalAlignment.Left, -1, 10, strokeCol); - } - - private void DrawOffscreenArrow(OffscreenMarker m, Vector2 viewSize, Vector2 center, float halfW, float halfH, Font font) - { - Vector2 dir = ComputeOffscreenDirection(m.CamLocal); - Vector2 edge = ComputeSafeEdgePos(center, halfW, halfH, dir); - Vector2 perp = new(-dir.Y, dir.X); - - _shadowTriBuf[0] = edge + dir * 10f; - _shadowTriBuf[1] = edge - dir * 6.5f + perp * 7f; - _shadowTriBuf[2] = edge - dir * 6.5f - perp * 7f; - DrawColoredPolygon(_shadowTriBuf, new Color(0.04f, 0.05f, 0.04f, 0.74f)); - - _triBuf[0] = edge + dir * 8f; - _triBuf[1] = edge - dir * 5f + perp * 5.2f; - _triBuf[2] = edge - dir * 5f - perp * 5.2f; - Color arrowCol = new(m.Color.R, m.Color.G, m.Color.B, 0.94f); - DrawColoredPolygon(_triBuf, arrowCol); - - string label = m.IsLockedOnLocal ? $"{m.Distance:F0}m !" : $"{m.Distance:F0}m"; - Vector2 textPos = ComputeInwardLabelPos(edge, dir, viewSize, font, label); - DrawString(font, textPos + new Vector2(1f, 1f), label, HorizontalAlignment.Left, -1, 10, new Color(0.04f, 0.05f, 0.04f, 0.90f)); - DrawString(font, textPos, label, HorizontalAlignment.Left, -1, 10, arrowCol); - } - - private static Vector2 ComputeOffscreenDirection(System.Numerics.Vector3 camLocal) - { - if (!float.IsFinite(camLocal.X) || !float.IsFinite(camLocal.Y) || !float.IsFinite(camLocal.Z)) - { - return Vector2.Down; - } - - Vector2 dir; - if (camLocal.Z >= 0f) - { - dir = new Vector2(camLocal.X, -camLocal.Y); - } - else - { - float horiz = MathF.Sqrt(camLocal.X * camLocal.X + camLocal.Z * camLocal.Z); - float t = Math.Clamp(-camLocal.Z / MathF.Max(1e-4f, horiz * 0.35f), 0f, 1f); - Vector2 sideDir = new(camLocal.X, -camLocal.Y); - Vector2 behindArcDir = new(camLocal.X, MathF.Max(-camLocal.Z, 0.35f * horiz)); - dir = sideDir.Lerp(behindArcDir, t); - if (MathF.Abs(camLocal.X) < 0.35f * horiz) - { - float minDown = 0.25f * dir.Length(); - if (dir.Y < minDown) - { - dir.Y = MathF.Max(minDown, 0.25f); - } - } - } - - float lenSq = dir.LengthSquared(); - if (!float.IsFinite(lenSq) || lenSq < 1e-6f) - { - return camLocal.Z < 0f ? Vector2.Down : Vector2.Up; - } - return dir / MathF.Sqrt(lenSq); - } - - private Vector2 ComputeSafeEdgePos(Vector2 center, float halfW, float halfH, Vector2 dir) - { - float tx = MathF.Abs(dir.X) > 1e-4f ? halfW / MathF.Abs(dir.X) : float.PositiveInfinity; - float ty = MathF.Abs(dir.Y) > 1e-4f ? halfH / MathF.Abs(dir.Y) : float.PositiveInfinity; - float tBest = MathF.Min(tx, ty); - - for (int i = 0; i < _avoidPanels.Length; i++) - { - var panel = _avoidPanels[i]; - if (panel is null || !panel.Visible) continue; - Rect2 r = panel.GetGlobalRect().Grow(PanelAvoidPad); - if (r.HasPoint(center)) continue; - if (TryRayEnterRect(center, dir, r, out float tEnter) && tEnter > 24f && tEnter < tBest) - { - tBest = tEnter; - } - } - - tBest = MathF.Max(24f, tBest); - return center + dir * tBest; - } - - private static bool TryRayEnterRect(Vector2 origin, Vector2 dir, Rect2 r, out float tEnter) - { - float tMin = 0f; - float tMax = float.PositiveInfinity; - - if (MathF.Abs(dir.X) < 1e-5f) - { - if (origin.X < r.Position.X || origin.X > r.End.X) - { - tEnter = 0f; - return false; - } - } - else - { - float invX = 1f / dir.X; - float t1 = (r.Position.X - origin.X) * invX; - float t2 = (r.End.X - origin.X) * invX; - if (t1 > t2) (t1, t2) = (t2, t1); - tMin = MathF.Max(tMin, t1); - tMax = MathF.Min(tMax, t2); - if (tMin > tMax) - { - tEnter = 0f; - return false; - } - } - - if (MathF.Abs(dir.Y) < 1e-5f) - { - if (origin.Y < r.Position.Y || origin.Y > r.End.Y) - { - tEnter = 0f; - return false; - } - } - else - { - float invY = 1f / dir.Y; - float t1 = (r.Position.Y - origin.Y) * invY; - float t2 = (r.End.Y - origin.Y) * invY; - if (t1 > t2) (t1, t2) = (t2, t1); - tMin = MathF.Max(tMin, t1); - tMax = MathF.Min(tMax, t2); - if (tMin > tMax) - { - tEnter = 0f; - return false; - } - } - - tEnter = tMin; - return true; - } - - private static Vector2 ComputeInwardLabelPos(Vector2 edge, Vector2 dir, Vector2 viewSize, Font font, string label) - { - Vector2 sz = font.GetStringSize(label, HorizontalAlignment.Left, -1, 10); - Vector2 inward = edge - dir * 14f; - float textX; - float textY; - - if (MathF.Abs(dir.X) >= MathF.Abs(dir.Y)) - { - textX = dir.X > 0f ? (inward.X - sz.X - 4f) : (inward.X + 6f); - textY = inward.Y + sz.Y * 0.3f; - } - else - { - textX = inward.X - sz.X * 0.5f; - textY = dir.Y > 0f ? (inward.Y - 4f) : (inward.Y + sz.Y + 4f); - } - - return new Vector2( - Math.Clamp(textX, 10f, MathF.Max(10f, viewSize.X - sz.X - 10f)), - Math.Clamp(textY, 16f, MathF.Max(16f, viewSize.Y - 10f))); } } } diff --git a/client/InventoryGridControl.cs b/client/InventoryGridControl.cs index 98f64ef..1c5fafd 100644 --- a/client/InventoryGridControl.cs +++ b/client/InventoryGridControl.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Godot; using RustToDust.Core; +using RustToDust.HbGpu; namespace RustToDust.Client; @@ -38,8 +39,14 @@ public partial class InventoryGridControl : Control private static Shader? _sharedShader; private readonly TextureRect _gridSurface; - private readonly LabelsOverlay _labelsOverlay; private readonly ShaderMaterial _material; + private HbGpuCanvas? _standaloneCanvas; + + private readonly Dictionary _lastEmittedTags = new(StringComparer.Ordinal); + private readonly char[] _tagScratch = new char[32]; + private int _overlayEmitCount; + private float _standaloneTime; + private bool _standaloneDirty = true; private Image? _dataImage; private ImageTexture? _dataTex; @@ -83,17 +90,10 @@ public partial class InventoryGridControl : Control _gridSurface.SetAnchorsPreset(LayoutPreset.FullRect); AddChild(_gridSurface); - _labelsOverlay = new LabelsOverlay(this) - { - Name = "GridLabelsOverlay", - MouseFilter = MouseFilterEnum.Ignore - }; - _labelsOverlay.SetAnchorsPreset(LayoutPreset.FullRect); - AddChild(_labelsOverlay); - MouseExited += OnMouseExited; } + public bool ExternalHbGpuOwner { get; set; } public ShaderMaterial ShaderMaterial => _material; public Control ShaderSurface => _gridSurface; public ChassisGrid? Grid => _grid; @@ -103,9 +103,24 @@ public partial class InventoryGridControl : Control ? _hardpointLookup[c.X, c.Y] : null; - internal int LabelsDrawCount => _labelsOverlay.DrawCount; - internal string? GetLastDrawnLabel(string hardpointId) => - _labelsOverlay.LastDrawnTags.TryGetValue(hardpointId, out string? tag) ? tag : null; + internal int OverlayEmitCount => _overlayEmitCount; + internal HbGpuCanvas? StandaloneCanvas => _standaloneCanvas; + internal string? GetLastEmittedLabel(string hardpointId) => + _lastEmittedTags.TryGetValue(hardpointId, out string? tag) ? tag : null; + + public override void _Ready() + { + if (!ExternalHbGpuOwner && _standaloneCanvas is null) + { + _standaloneCanvas = new HbGpuCanvas + { + Name = "StandaloneHbGpuCanvas", + MouseFilter = MouseFilterEnum.Ignore + }; + _standaloneCanvas.SetAnchorsPreset(LayoutPreset.FullRect); + AddChild(_standaloneCanvas); + } + } public event Action? CellClicked; public event Action? HardpointClicked; @@ -116,13 +131,14 @@ public partial class InventoryGridControl : Control if (what == NotificationResized) { SyncRectUniform(); - _labelsOverlay.QueueRedraw(); + _standaloneDirty = true; } } public override void _Process(double delta) { float dt = (float)delta; + _standaloneTime += MathF.Max(0f, dt); bool anyPulse = false; for (int y = 0; y < _gridHeight; y++) @@ -141,6 +157,19 @@ public partial class InventoryGridControl : Control { PackDataTexture(_grid); FlushTextures(); + _standaloneDirty = true; + } + + if (!ExternalHbGpuOwner && _standaloneCanvas is not null && _grid is not null) + { + bool hasCompatiblePulse = _selectedCargoIndex >= 0 && _selectedCargoIndex < _grid.Cargo.Count; + if (_standaloneDirty || hasCompatiblePulse) + { + _standaloneDirty = false; + _standaloneCanvas.BeginFrame(); + EmitHbGpuOverlay(_standaloneCanvas, Vector2.Zero, _standaloneTime); + _standaloneCanvas.EndFrameAndSubmit(); + } } } @@ -195,7 +224,7 @@ public partial class InventoryGridControl : Control PackTempTexture(grid); FlushTextures(); SyncRectUniform(); - _labelsOverlay.QueueRedraw(); + _standaloneDirty = true; return; } @@ -224,7 +253,7 @@ public partial class InventoryGridControl : Control } if (dataChanged || tempChanged) { - _labelsOverlay.QueueRedraw(); + _standaloneDirty = true; FlushTextures(); } } @@ -236,6 +265,7 @@ public partial class InventoryGridControl : Control _hitPulse[x, y] = Math.Clamp(intensity, 0f, 1f); PackDataTexture(_grid); FlushTextures(); + _standaloneDirty = true; } public bool TryGetCellAt(Vector2 localPos, out Vector2I cell) @@ -282,6 +312,7 @@ public partial class InventoryGridControl : Control { PackDataTexture(_grid); FlushTextures(); + _standaloneDirty = true; } } } @@ -301,6 +332,7 @@ public partial class InventoryGridControl : Control { PackDataTexture(_grid); FlushTextures(); + _standaloneDirty = true; } } @@ -685,62 +717,218 @@ public partial class InventoryGridControl : Control _ => ColTextLight }; - private sealed partial class LabelsOverlay : Control + /// + /// Emits crisp analytic vector cell borders, hardpoint L-brackets, compatibility pulses, + /// stripped X-marks, and Monaspace Krypton hardpoint labels into . + /// Zero GC allocations on steady-state calls. + /// + public void EmitHbGpuOverlay(HbGpuCanvas canvas, Vector2 originOffset, float timeSec) { - private readonly InventoryGridControl _owner; - public int DrawCount { get; private set; } - public readonly Dictionary LastDrawnTags = new(StringComparer.Ordinal); - - public LabelsOverlay(InventoryGridControl owner) => _owner = owner; - - public override void _Draw() + _overlayEmitCount++; + var grid = _grid; + if (grid is null) { - DrawCount++; - LastDrawnTags.Clear(); - var grid = _owner._grid; - if (grid is null) return; + return; + } - _owner.ComputeCellLayout(out float cellSize, out Vector2 origin); - if (cellSize < 14f) return; + ComputeCellLayout(out float cellSize, out Vector2 origin); + if (cellSize < 8f) + { + return; + } - var spec = grid.Spec; - int fontSize = cellSize >= 38f ? 10 : 9; - float alpha = 0.95f; + Vector2 basePos = originOffset + origin; + var spec = grid.Spec; + ModuleSpec? selectedCargo = _selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count + ? grid.Cargo[_selectedCargoIndex] + : null; + HardpointSpec? hoveredHp = HoveredHardpoint; + Color flashCol = new(1.0f, 0.76f, 0.38f, 1.0f); + Color redAccent = new(0.92f, 0.26f, 0.18f, 1.0f); - for (int i = 0; i < spec.Hardpoints.Length; i++) + // 1. Hull cell outlines, internal subdivisions, and stripped-cell X marks + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) { - var hp = spec.Hardpoints[i]; - var mounted = grid.GetMountedOn(hp.Id); - var pos = origin + new Vector2(hp.X * cellSize, hp.Y * cellSize); - float maxW = MathF.Max(12f, hp.Width * cellSize - 6f); + if (!spec.IsActive(x, y)) + { + continue; + } - string tag = mounted is not null - ? $"{mounted.Spec.Kind.ToString()[..1]}:{mounted.CurrentTemp:F0}°" - : hp.Kind.ToString()[..3].ToUpperInvariant(); - LastDrawnTags[hp.Id] = tag; + float cx = basePos.X + x * cellSize; + float cy = basePos.Y + y * cellSize; + bool stripped = grid.Armor[x, y] <= 0.01f; + var hp = _hardpointLookup[x, y]; + + if (hp is null) + { + Color edgeCol = grid.BorderCells[x, y] + ? ColBorderHull.Lerp(ColBorderRadiatorCell, 0.30f) + : ColBorderHull; + float pulse = Math.Clamp(_hitPulse[x, y], 0f, 1f); + bool isCellHovered = _hoveredCell is { } hc && hc.X == x && hc.Y == y; + if (stripped) edgeCol = edgeCol.Lerp(redAccent, 0.65f); + if (isCellHovered) edgeCol = edgeCol.Lerp(Colors.White, 0.35f); + if (pulse > 0.01f) edgeCol = edgeCol.Lerp(flashCol, pulse * 0.90f); + + float inset = 1.5f; + float x0 = cx + inset; + float y0 = cy + inset; + float x1 = cx + cellSize - inset; + float y1 = cy + cellSize - inset; + + // Outer hull perimeter edges get crisp medium lines; internal matched hull edges get faint hairlines + bool nMatch = spec.IsActive(x, y - 1) && _hardpointLookup[x, y - 1] is null; + bool sMatch = spec.IsActive(x, y + 1) && _hardpointLookup[x, y + 1] is null; + bool wMatch = spec.IsActive(x - 1, y) && _hardpointLookup[x - 1, y] is null; + bool eMatch = spec.IsActive(x + 1, y) && _hardpointLookup[x + 1, y] is null; + + Color outerCol = new(edgeCol.R, edgeCol.G, edgeCol.B, isCellHovered ? 0.85f : 0.42f); + Color innerCol = new(edgeCol.R, edgeCol.G, edgeCol.B, 0.14f); + + if (!nMatch) canvas.DrawLineSegment(x0, y0, x1, y0, 1.2f, outerCol); + if (!sMatch) canvas.DrawLineSegment(x0, y1, x1, y1, 1.2f, outerCol); + else canvas.DrawLineSegment(cx + 2f, cy + cellSize, cx + cellSize - 2f, cy + cellSize, 0.9f, innerCol); + if (!wMatch) canvas.DrawLineSegment(x0, y0, x0, y1, 1.2f, outerCol); + if (!eMatch) canvas.DrawLineSegment(x1, y0, x1, y1, 1.2f, outerCol); + else canvas.DrawLineSegment(cx + cellSize, cy + 2f, cx + cellSize, cy + cellSize - 2f, 0.9f, innerCol); + } + + if (stripped) + { + float pad = MathF.Max(4.5f, cellSize * 0.18f); + Color xCol = new(0.95f, 0.28f, 0.20f, 0.78f); + canvas.DrawLineSegment(cx + pad, cy + pad, cx + cellSize - pad, cy + cellSize - pad, 1.5f, xCol); + canvas.DrawLineSegment(cx + cellSize - pad, cy + pad, cx + pad, cy + cellSize - pad, 1.5f, xCol); + } + } + } + + // 2. Contiguous hardpoint borders, L-brackets, and Krypton tags + float fontSize = cellSize >= 38f ? 10.5f : 9.2f; + float compatPulse = 0.72f + 0.28f * MathF.Sin(timeSec * 6.5f); + + for (int i = 0; i < spec.Hardpoints.Length; i++) + { + var hp = spec.Hardpoints[i]; + var mounted = grid.GetMountedOn(hp.Id); + float hx = basePos.X + hp.X * cellSize; + float hy = basePos.Y + hp.Y * cellSize; + float hw = hp.Width * cellSize; + float hh = hp.Height * cellSize; + + bool strippedHp = !grid.IsHardpointOperational(hp); + bool isCompatible = selectedCargo is not null && ChassisGrid.CanFit(hp, selectedCargo); + bool isHovered = hoveredHp is not null && ReferenceEquals(hp, hoveredHp); + + float maxPulse = 0f; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int cx = hp.X + dx; + int cy = hp.Y + dy; + if (cx >= 0 && cy >= 0 && cx < _gridWidth && cy < _gridHeight) + { + maxPulse = MathF.Max(maxPulse, _hitPulse[cx, cy]); + } + } + } + + Color accent; + if (isCompatible) + { + accent = ColGold; + } + else if (mounted is { Spec.IsImperial: true }) + { + accent = ColGold; + } + else + { + accent = KindColor(hp.Kind); + if (mounted is null) + { + accent = accent.Lerp(ColBorderHull, 0.45f); + } + } + + if (strippedHp) accent = accent.Lerp(redAccent, 0.70f); + if (isCompatible) accent = accent.Lerp(new Color(0.96f, 0.82f, 0.30f, 1f), compatPulse); + if (isHovered) accent = accent.Lerp(Colors.White, 0.35f); + if (maxPulse > 0.01f) accent = accent.Lerp(flashCol, maxPulse * 0.90f); + + const float inset = 1.8f; + float rx = hx + inset; + float ry = hy + inset; + float rw = MathF.Max(2f, hw - inset * 2f); + float rh = MathF.Max(2f, hh - inset * 2f); + + float ruleAlpha = isCompatible ? 0.68f : (isHovered ? 0.60f : 0.34f); + canvas.DrawRectOutline(rx, ry, rw, rh, isCompatible ? 1.5f : 1.0f, new Color(accent.R, accent.G, accent.B, ruleAlpha)); + + float arm = Math.Clamp(MathF.Min(rw, rh) * 0.28f, 4.5f, 12f); + float bracketThick = (isCompatible || isHovered) ? 2.4f : 1.8f; + Color bracketCol = new(accent.R, accent.G, accent.B, 0.96f); + canvas.DrawTargetBracketCorner(rx, ry, arm, bracketThick, 0, bracketCol); + canvas.DrawTargetBracketCorner(rx + rw, ry, arm, bracketThick, 1, bracketCol); + canvas.DrawTargetBracketCorner(rx + rw, ry + rh, arm, bracketThick, 2, bracketCol); + canvas.DrawTargetBracketCorner(rx, ry + rh, arm, bracketThick, 3, bracketCol); + + if (cellSize >= 14f) + { + ReadOnlySpan tagSpan = FormatHardpointTag(hp, mounted, _tagScratch); + if (!_lastEmittedTags.TryGetValue(hp.Id, out string? existingTag) || !tagSpan.SequenceEqual(existingTag)) + { + _lastEmittedTags[hp.Id] = new string(tagSpan); + } Color col = mounted is { Spec.IsImperial: true } ? ColGold : ColTextLight; - col.A = alpha; + col.A = 0.95f; + HbGpuCommandWriter.PackClipRect(hx + 2f, hy + 2f, hw - 4f, hh - 4f, out uint clipMin, out uint clipMax); - // Dark shadow for crisp legibility over bright thermal glow - DrawString( - UiFonts.Regular, - pos + new Vector2(7f, fontSize + 6f), - tag, - HorizontalAlignment.Left, - maxW - 2f, - fontSize, - new Color(0.04f, 0.05f, 0.04f, alpha * 0.9f)); - - DrawString( - UiFonts.Regular, - pos + new Vector2(6f, fontSize + 5f), - tag, - HorizontalAlignment.Left, - maxW - 2f, - fontSize, - col); + float tx = hx + 5f; + float ty = hy + fontSize + 4.5f; + canvas.DrawText(tagSpan, tx + 1f, ty + 1f, fontSize, new Color(0.04f, 0.05f, 0.04f, 0.90f), + wght: 550f, stemDarken: true, clipMinPacked: clipMin, clipMaxPacked: clipMax); + canvas.DrawText(tagSpan, tx, ty, fontSize, col, + wght: 550f, stemDarken: true, clipMinPacked: clipMin, clipMaxPacked: clipMax); } } } + + private static ReadOnlySpan FormatHardpointTag(HardpointSpec hp, MountedModule? mounted, char[] buf) + { + if (mounted is null) + { + return hp.Kind switch + { + HardpointKind.Weapon => "WPN", + HardpointKind.Engine => "ENG", + HardpointKind.Radiator => "RAD", + HardpointKind.Armor => "ARM", + HardpointKind.Utility => "UTL", + _ => "MOD" + }; + } + + buf[0] = mounted.Spec.Kind switch + { + HardpointKind.Weapon => 'W', + HardpointKind.Engine => 'E', + HardpointKind.Radiator => 'R', + HardpointKind.Armor => 'A', + HardpointKind.Utility => 'U', + _ => 'M' + }; + buf[1] = ':'; + int pos = 2; + if (mounted.CurrentTemp.TryFormat(buf.AsSpan(pos), out int written, "F0", System.Globalization.CultureInfo.InvariantCulture)) + { + pos += written; + } + buf[pos++] = '°'; + return buf.AsSpan(0, pos); + } } diff --git a/client/Main.cs b/client/Main.cs index 107cfe7..61a4cab 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -311,6 +311,10 @@ public partial class Main : Node3D { _atmosphere.VolumetricEffect.ProfilingEnabled = true; } + if (_hud?.HbCanvas is not null) + { + _hud.HbCanvas.ProfilingEnabled = true; + } } else if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES"), out int autoExitFrames) && autoExitFrames > 0) { @@ -1600,6 +1604,10 @@ public partial class Main : Node3D double vpCpuMs = RenderingServer.ViewportGetMeasuredRenderTimeCpu(vpRid); GD.Print($"Cut10bGpuMs: total={volFx.LastTotalGpuMs:F3} flow={volFx.LastFlowGpuMs:F3} cull={volFx.LastCullGpuMs:F3} march={volFx.LastMarchGpuMs:F3} comp={volFx.LastCompGpuMs:F3} viewportGpuMs={vpGpuMs:F2} viewportCpuMs={vpCpuMs:F2}"); } + if (_hud?.HbCanvas is { } hb) + { + GD.Print($"HbGpuHud: drawCalls={hb.LastDrawCallCount} quads={hb.LastQuadCount} gpuMs={hb.LastHbGpuMs:F4}"); + } if (_session is not null) { var net = _session.ConnectionStatus; diff --git a/client/inventory_grid.gdshader b/client/inventory_grid.gdshader index fce4ae7..c77eb2d 100644 --- a/client/inventory_grid.gdshader +++ b/client/inventory_grid.gdshader @@ -2,12 +2,13 @@ shader_type canvas_item; render_mode blend_premul_alpha; // Port of Aetheria's UI/Inventory Grid shader to Godot 4 Forward+ Vulkan. -// Evaluates analytical corner-folded texel boxes for hull/hardpoint silhouettes, L-brackets, -// hairline rules, direct bilinear heat glow, hit-pulse flash, and 45-degree fracture hatching. +// Evaluates stateless interior cell fill: corner-folded texel masks, bilinear heat glow, +// hit-pulse flash, and 45-degree fracture hatching. Crisp vector frames, L-brackets, +// stripped X-marks, and Krypton labels are rendered by HbGpuCanvas on top. // // data_tex (3W x H, filter_nearest): // 3x + 0 : cell/item fill & armor tint (RGBA) -// 3x + 1 : border/bracket accent color (RGBA) +// 3x + 1 : reserved / accent tint // 3x + 2 : R = 8-bit neighbor mismatch mask (N,E,S,W,NE,SE,SW,NW) // G = flags (bit0=present, bit1=item, bit2=hover, bit3=damaged/stripped, bit4=compatible, bit5=border_radiator) // B = reserved (0) @@ -23,17 +24,9 @@ uniform sampler2D temp_tex : filter_linear, repeat_disable; uniform vec2 grid_size = vec2(4.0, 5.0); uniform vec2 rect_size = vec2(180.0, 225.0); -// Look parameters in Aetheria texel units -uniform float icon_texel = 1.51515; uniform float bg_texel = 1.0; -uniform float rule_inset = 1.5; -uniform float rule_width = 1.0; -uniform float arm_texels = 1.25; uniform float fill_inset = 2.6; uniform float softness = 1.0; -uniform float rule_alpha = 0.34; -uniform float bracket_alpha = 1.0; -uniform float fill_alpha = 0.14; const float FAR = 1000.0; @@ -45,7 +38,7 @@ float box_profile(float x, float lo, float hi, float soft) { return clamp(1.0 - outside / soft, 0.0, 1.0); } -float eval_layer(vec2 p, float cell_px, float texel, uint mask, bool is_item, bool is_icon, float aa_px) { +float eval_bg_mask(vec2 p, float cell_px, float texel, uint mask, float aa_px) { float t = min(texel, cell_px / 8.0); bool left = p.x < cell_px * 0.5; bool top = p.y >= cell_px * 0.5; @@ -69,36 +62,7 @@ float eval_layer(vec2 p, float cell_px, float texel, uint mask, bool is_item, bo if (concave) { f -= box_profile(x, -FAR, fill_inset - 0.5, soft) * box_profile(y, -FAR, fill_inset - 0.5, soft); } - f = clamp(f, 0.0, 1.0); - if (!is_icon) { - return f; - } - - float a = is_item ? fill_alpha * f : 0.0; - float ri = rule_inset; - float rlo = ri - (rule_width - 1.0) * 0.5; - float rhi = ri + (rule_width - 1.0) * 0.5; - float rx = box_profile(x, rlo, rhi, soft); - float ry = box_profile(y, rlo, rhi, soft); - float arms = arm_texels >= 1.0 ? 1.0 : 0.0; - - if (v) { - a += rule_alpha * ry * (h ? box_profile(x, ri, FAR, soft) : 1.0); - } - if (h) { - a += rule_alpha * rx * (v ? box_profile(y, ri + 1.0, FAR, soft) : 1.0); - } - if (v && h) { - a += (bracket_alpha - rule_alpha) * (ry * box_profile(x, ri, ri + arm_texels, soft) + arms * rx * box_profile(y, ri + 1.0, ri + arm_texels, soft)); - } else if (concave) { - a += bracket_alpha * (ry * box_profile(x, ri - arm_texels, ri, soft) + arms * rx * box_profile(y, ri - arm_texels, ri - 1.0, soft)); - } else if (!v && !h) { - // Faint cell subdivision hairline across matched internal cell boundaries - float sub_x = box_profile(x, 0.0, 0.65, soft); - float sub_y = box_profile(y, 0.0, 0.65, soft); - a += 0.14 * max(sub_x, sub_y); - } - return clamp(a, 0.0, 1.0); + return clamp(f, 0.0, 1.0); } vec3 thermal_ramp(float t) { @@ -136,7 +100,6 @@ void fragment() { float tex_w = safe_grid.x * 3.0; float ty = (cellf.y + 0.5) / safe_grid.y; vec4 cell_fill = textureLod(data_tex, vec2((cellf.x * 3.0 + 0.5) / tex_w, ty), 0.0); - vec4 border_accent = textureLod(data_tex, vec2((cellf.x * 3.0 + 1.5) / tex_w, ty), 0.0); vec4 meta = textureLod(data_tex, vec2((cellf.x * 3.0 + 2.5) / tex_w, ty), 0.0); uint mask = uint(round(meta.r * 255.0)); @@ -146,7 +109,6 @@ void fragment() { if ((flags & 1u) == 0u) { COLOR = vec4(0.0); } else { - bool is_item = (flags & 2u) != 0u; bool is_hover = (flags & 4u) != 0u; bool is_damaged = (flags & 8u) != 0u; bool is_compatible = (flags & 16u) != 0u; @@ -155,8 +117,7 @@ void fragment() { float plateau_stress = temp_sample.g; vec3 heat_col = thermal_ramp(norm_temp); - float a_bg = eval_layer(p, S, bg_texel, mask, false, false, aa_px) * cell_fill.a; - float a_rules = eval_layer(p, S, icon_texel, mask, is_item, true, aa_px); + float a_bg = eval_bg_mask(p, S, bg_texel, mask, aa_px) * cell_fill.a; // Intact vs stripped (Armor == 0) interior fill with always-active subtle bilinear heat glow on hot cells float hot_blend = smoothstep(0.05, 0.65, norm_temp) * 0.56; @@ -174,6 +135,10 @@ void fragment() { base_rgb += heat_col * (0.20 * norm_temp + 0.30 * overheat_glow); base_rgb = clamp(base_rgb, vec3(0.0), vec3(1.0)); + if (is_compatible) { + float pulse = 0.72 + 0.28 * sin(TIME * 6.5); + base_rgb = mix(base_rgb, vec3(0.96, 0.82, 0.30), 0.16 * pulse); + } if (is_hover) { base_rgb = mix(base_rgb, vec3(0.95, 0.94, 0.88), 0.16); } @@ -182,27 +147,8 @@ void fragment() { vec3 flash_col = vec3(1.0, 0.76, 0.38); base_rgb = clamp(mix(base_rgb, flash_col, hit_pulse * 0.85), vec3(0.0), vec3(1.0)); - vec3 accent_rgb = border_accent.rgb; - if (is_damaged) { - accent_rgb = mix(accent_rgb, vec3(0.92, 0.26, 0.18), 0.70); - } - if (is_compatible) { - float pulse = 0.72 + 0.28 * sin(TIME * 6.5); - accent_rgb = mix(accent_rgb, vec3(0.96, 0.82, 0.30), pulse); - a_rules = clamp(a_rules * 1.35, 0.0, 1.0); - } - if (is_hover) { - accent_rgb = mix(accent_rgb, vec3(1.0), 0.35); - a_rules = clamp(a_rules * 1.25, 0.0, 1.0); - } - accent_rgb = clamp(mix(accent_rgb, flash_col, hit_pulse * 0.90), vec3(0.0), vec3(1.0)); - - float icon_alpha = clamp(a_rules * border_accent.a, 0.0, 1.0); - vec3 icon_rgb = clamp(accent_rgb, vec3(0.0), vec3(1.0)); - - float out_a = clamp(icon_alpha + a_bg * (1.0 - icon_alpha), 0.0, 1.0); - vec3 out_rgb = min(icon_rgb * icon_alpha + base_rgb * a_bg * (1.0 - icon_alpha), vec3(out_a)); - out_rgb = max(out_rgb, vec3(0.0)); + float out_a = clamp(a_bg, 0.0, 1.0); + vec3 out_rgb = clamp(base_rgb, vec3(0.0), vec3(1.0)) * out_a; COLOR = vec4(out_rgb, out_a); } } diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index 5247dc6..d9f7c3a 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -287,15 +287,23 @@ public partial class Smoke : Node var invShader = _main.Hud.Schematic.ShaderMaterial.Shader; Check(invShader is not null && !string.IsNullOrWhiteSpace(invShader.Code), "inventory_grid.gdshader failed to load"); + Check(_main.Hud.HbCanvas is not null, "Expected Hud.HbCanvas to be initialized"); - int chromeCount = 0; - foreach (var mat in _main.Hud.GetChromeMaterials()) + // Warm up HUD HbGpuCanvas and verify steady-state Sync allocates zero managed bytes + _main.Hud.Sync(_main.Session); + _main.Hud.Sync(_main.Session); + _main.Hud.Sync(_main.Session); + Check(_main.Hud.HbCanvas!.LastQuadCount > 50, + $"Expected Hud.HbCanvas.LastQuadCount > 50 after Sync, got {_main.Hud.HbCanvas.LastQuadCount}"); + long gcBefore = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < 16; i++) { - chromeCount++; - Check(mat.Shader is not null && !string.IsNullOrWhiteSpace(mat.Shader.Code), - $"panel_chrome.gdshader failed to load on HUD panel #{chromeCount}"); + _main.Hud.Sync(_main.Session); } - Check(chromeCount == 6, $"Expected 6 ChromePanel materials on HUD, got {chromeCount}"); + long gcAfter = GC.GetAllocatedBytesForCurrentThread(); + long gcDelta = gcAfter - gcBefore; + GD.Print($"SMOKE INFO: Steady-state Hud.Sync x16 managed allocs={gcDelta} B"); + Check(gcDelta == 0, $"Expected 0 B managed allocations across steady-state Hud.Sync x16, got {gcDelta} B"); // Pack a real Ironclad chassis with mounted modules, thermal gradient, stripped cell, and active hit-pulse var testGrid = new ChassisGrid(Catalog.Ironclad); @@ -488,7 +496,7 @@ public partial class Smoke : Node Check(raptorHoleScanned > 1000, $"Expected > 1000 inactive hole pixels scanned on Raptor, got {raptorHoleScanned}"); Check(raptorHoleLit == 0, $"Expected 0 lit/opaque pixels in inactive Raptor cell holes, got {raptorHoleLit}"); - // Finding 5 GPU check: LabelsOverlay redraws on temp-only change & compatibility highlights update when Cargo[0] swaps at unchanged index 0 + // Cut 14b GPU check: HbGpuCanvas overlay re-emits on temp-only change & compatibility highlights update when Cargo[0] swaps at unchanged index 0 { raptorGrid.Cargo.Clear(); Check(raptorGrid.TryAddCargo(Catalog.Autocannon), "Expected Autocannon in Raptor Cargo[0]"); @@ -496,8 +504,8 @@ public partial class Smoke : Node await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - int drawCountBeforeTemp = vpGrid.LabelsDrawCount; - string? tagBeforeTemp = vpGrid.GetLastDrawnLabel("hp.engine.chest"); + int emitCountBeforeTemp = vpGrid.OverlayEmitCount; + string? tagBeforeTemp = vpGrid.GetLastEmittedLabel("hp.engine.chest"); var cargoImgWeapon = gridVp.GetTexture().GetImage(); // Temp-only change (no armor hit, no mount change) @@ -507,10 +515,10 @@ public partial class Smoke : Node await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - int drawCountAfterTemp = vpGrid.LabelsDrawCount; - string? tagAfterTemp = vpGrid.GetLastDrawnLabel("hp.engine.chest"); - Check(drawCountAfterTemp > drawCountBeforeTemp, - $"Expected LabelsOverlay to redraw on temp-only change ({drawCountBeforeTemp} -> {drawCountAfterTemp})"); + int emitCountAfterTemp = vpGrid.OverlayEmitCount; + string? tagAfterTemp = vpGrid.GetLastEmittedLabel("hp.engine.chest"); + Check(emitCountAfterTemp > emitCountBeforeTemp, + $"Expected InventoryGridControl HbGpu overlay to re-emit on temp-only change ({emitCountBeforeTemp} -> {emitCountAfterTemp})"); Check(!string.Equals(tagBeforeTemp, tagAfterTemp, StringComparison.Ordinal), $"Expected engine temp label text to update on temp-only change ('{tagBeforeTemp}' -> '{tagAfterTemp}')"); @@ -525,47 +533,31 @@ public partial class Smoke : Node GD.Print($"SMOKE INFO: InventoryGrid Cargo[0] swap diff pixels={cargoDiff}, label '{tagBeforeTemp}'->'{tagAfterTemp}'"); Check(cargoDiff > 50, $"Expected Cargo[0] replacement at unchanged index 0 to update compatibility highlight pixels (>50), got {cargoDiff}"); + Check(vpGrid.StandaloneCanvas is { LastDrawCallCount: 1 }, + $"Expected standalone InventoryGridControl HbGpuCanvas to render in 1 draw call, got {vpGrid.StandaloneCanvas?.LastDrawCallCount ?? -1}"); } gridVp.QueueFree(); - // GPU verification for panel_chrome.gdshader - var chromeVp = new SubViewport - { - Size = new Vector2I(240, 120), - TransparentBg = true, - RenderTargetUpdateMode = SubViewport.UpdateMode.Always - }; - var chromeShader = GD.Load("res://panel_chrome.gdshader"); - var chromeMat = new ShaderMaterial { Shader = chromeShader }; - chromeMat.SetShaderParameter("rect_size", new Vector2(240f, 120f)); - chromeMat.SetShaderParameter("accent_color", Color.FromHtml("#e08a4a")); - var chromeImgTex = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); - chromeImgTex.SetPixel(0, 0, Colors.White); - var chromeRect = new TextureRect - { - Texture = ImageTexture.CreateFromImage(chromeImgTex), - Size = new Vector2(240f, 120f), - ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize, - StretchMode = TextureRect.StretchModeEnum.Scale, - Material = chromeMat - }; - chromeVp.AddChild(chromeRect); - AddChild(chromeVp); - + // Cut 14b Vulkan single-draw-call verification on live Hud.HbCanvas + _main.Hud.Sync(_main.Session); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - - var chromeImg = chromeVp.GetTexture().GetImage(); - int chromeOpaque = CountNonZeroAlphaPixels(chromeImg, 0.08f); - Color cornerPx = chromeImg.GetPixel(2, 2); - Color centerPx = chromeImg.GetPixel(120, 60); - GD.Print($"SMOKE INFO: panel_chrome GPU opaque={chromeOpaque}, corner={cornerPx}, center={centerPx}"); - Check(chromeOpaque > 10000, $"Expected > 10000 rendered pixels from panel_chrome.gdshader, got {chromeOpaque}"); - Check(cornerPx.R > centerPx.R + 0.25f, - $"Expected L-bracket corner pixel ({cornerPx}) to be accented brighter than panel center ({centerPx})"); - - chromeVp.QueueFree(); + var hudHb = _main.Hud.HbCanvas; + Check(hudHb.LastDrawCallCount == 1, $"Expected Hud.HbCanvas LastDrawCallCount == 1, got {hudHb.LastDrawCallCount}"); + Check(hudHb.TryReadbackRgba8(out byte[] hudRgba, out int hudW, out int hudH), + "Expected Hud.HbCanvas.TryReadbackRgba8 to succeed on Vulkan"); + int hudNonZero = 0; + int hudPremulViol = 0; + for (int i = 0; i + 3 < hudRgba.Length; i += 4) + { + byte r = hudRgba[i], g = hudRgba[i + 1], b = hudRgba[i + 2], a = hudRgba[i + 3]; + if (a > 0) hudNonZero++; + if (r > a || g > a || b > a) hudPremulViol++; + } + GD.Print($"SMOKE INFO: Hud.HbCanvas Vulkan {hudW}x{hudH} quads={hudHb.LastQuadCount}, drawCalls={hudHb.LastDrawCallCount}, nonZeroPx={hudNonZero}, premulViol={hudPremulViol}"); + Check(hudNonZero > 4000, $"Expected > 4000 rendered pixels in Hud.HbCanvas, got {hudNonZero}"); + Check(hudPremulViol == 0, $"Expected 0 premul violations in Hud.HbCanvas, got {hudPremulViol}"); } private async Task MaybeCapturePreviewAsync(bool isHeadless) @@ -2216,9 +2208,8 @@ public partial class Smoke : Node _main.Hud.SimulateCellHover(new Vector2I(pWeaponHpSpec.X, pWeaponHpSpec.Y), pWeaponHpSpec); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - int chromeCount = 0; - foreach (var _ in _main.Hud.GetChromeMaterials()) chromeCount++; - Check(chromeCount == 6, $"Expected 6 HUD chrome panels, got {chromeCount}"); + Check(_main.Hud.HbCanvas.LastQuadCount > 50, + $"Expected Hud.HbCanvas.LastQuadCount > 50 in Garage mode, got {_main.Hud.HbCanvas.LastQuadCount}"); Check(_main.Hud.HoverLabelText.Contains(sabotDream.ManufacturerLabel) && _main.Hud.HoverLabelText.Contains('\n'), $"Expected 2-line Borderlands hover tooltip with manufacturer badge, got: {_main.Hud.HoverLabelText}"); Check(_main.Hud.GarageDetailsText.Contains(sabotDream.SummaryLine1) && _main.Hud.GarageDetailsText.Contains(sabotDream.SummaryLine2), diff --git a/src/RustToDust.HbGpu/HbGpuBlobCache.cs b/src/RustToDust.HbGpu/HbGpuBlobCache.cs index e560788..368c07a 100644 --- a/src/RustToDust.HbGpu/HbGpuBlobCache.cs +++ b/src/RustToDust.HbGpu/HbGpuBlobCache.cs @@ -16,6 +16,7 @@ public sealed unsafe class HbGpuBlobCache private readonly Dictionary _glyphBlobs = new(512); private readonly Dictionary _vectorBlobs = new(64); private readonly short[] _scratchShorts = new short[ScratchShortsCapacity]; + private bool _persistentOverflowPending; public HbGpuBlobCache(HbGpuAtlasAllocator atlas) { @@ -28,9 +29,11 @@ public sealed unsafe class HbGpuBlobCache public int CachedVectorCount => _vectorBlobs.Count; + public bool IsPersistentOverflowPending => _persistentOverflowPending; + public bool EnsureBudgetOrReset() { - if (!_atlas.NeedsPersistentReset) + if (!_atlas.NeedsPersistentReset && !_persistentOverflowPending) { return false; } @@ -38,6 +41,7 @@ public sealed unsafe class HbGpuBlobCache _atlas.ResetPersistent(); _glyphBlobs.Clear(); _vectorBlobs.Clear(); + _persistentOverflowPending = false; return true; } @@ -77,9 +81,10 @@ public sealed unsafe class HbGpuBlobCache { if (_atlas.PersistentCursor + (uint)texelCount > HbGpuAtlasAllocator.PersistentCapacity) { - _atlas.ResetPersistent(); - _glyphBlobs.Clear(); - _vectorBlobs.Clear(); + // Never wipe persistent atlas mid-frame while earlier quads reference pre-reset offsets. + // Flag for reset at next BeginFrame() and skip overflow glyphs cleanly for this frame. + _persistentOverflowPending = true; + return new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); } uint offset = _atlas.AllocatePersistent(_scratchShorts.AsSpan(0, texelCount * 4)); @@ -97,6 +102,9 @@ public sealed unsafe class HbGpuBlobCache return blob; } + public bool TryGetStaticPath(VectorBlobKey key, out CachedBlob cached) => + _vectorBlobs.TryGetValue(key, out cached); + public CachedBlob GetOrEncodeStaticPath( VectorBlobKey key, uint designUpem, @@ -118,9 +126,9 @@ public sealed unsafe class HbGpuBlobCache { if (_atlas.PersistentCursor + (uint)texelCount > HbGpuAtlasAllocator.PersistentCapacity) { - _atlas.ResetPersistent(); - _glyphBlobs.Clear(); - _vectorBlobs.Clear(); + // Never wipe persistent atlas mid-frame while earlier quads reference pre-reset offsets. + _persistentOverflowPending = true; + return new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); } uint offset = _atlas.AllocatePersistent(_scratchShorts.AsSpan(0, texelCount * 4)); diff --git a/src/RustToDust.HbGpu/HbGpuVectorShapes.cs b/src/RustToDust.HbGpu/HbGpuVectorShapes.cs index e79dfff..e04115f 100644 --- a/src/RustToDust.HbGpu/HbGpuVectorShapes.cs +++ b/src/RustToDust.HbGpu/HbGpuVectorShapes.cs @@ -80,31 +80,37 @@ public static class HbGpuVectorShapes public static CachedBlob GetUnitRingStroke(HbGpuBlobCache cache, ushort strokeUnits = 24) { - Span args = stackalloc float[] { 0f, 0f, 500f, strokeUnits }; - return cache.GetOrEncodeStaticPath( - new VectorBlobKey(VectorShapeKind.UnitRingStroke, strokeUnits, 0), - DesignUpem, - CircleVerbs, - args); + var key = new VectorBlobKey(VectorShapeKind.UnitRingStroke, strokeUnits, 0); + if (cache.TryGetStaticPath(key, out CachedBlob cached)) + { + return cached; + } + + Span args = stackalloc float[4]; + args[0] = 0f; + args[1] = 0f; + args[2] = 500f; + args[3] = strokeUnits; + return cache.GetOrEncodeStaticPath(key, DesignUpem, CircleVerbs, args); } public static CachedBlob GetTargetBracketCorner(HbGpuBlobCache cache, ushort thicknessUnits = 120) { - float t = Math.Clamp((float)thicknessUnits, 10f, 450f); - Span args = stackalloc float[] + var key = new VectorBlobKey(VectorShapeKind.TargetBracketCorner, thicknessUnits, 0); + if (cache.TryGetStaticPath(key, out CachedBlob cached)) { - 0f, 0f, - 1000f, 0f, - 1000f, -t, - t, -t, - t, -1000f, - 0f, -1000f - }; - return cache.GetOrEncodeStaticPath( - new VectorBlobKey(VectorShapeKind.TargetBracketCorner, thicknessUnits, 0), - DesignUpem, - CornerBracketVerbs, - args); + return cached; + } + + float t = Math.Clamp((float)thicknessUnits, 10f, 450f); + Span args = stackalloc float[12]; + args[0] = 0f; args[1] = 0f; + args[2] = 1000f; args[3] = 0f; + args[4] = 1000f; args[5] = -t; + args[6] = t; args[7] = -t; + args[8] = t; args[9] = -1000f; + args[10] = 0f; args[11] = -1000f; + return cache.GetOrEncodeStaticPath(key, DesignUpem, CornerBracketVerbs, args); } public static CachedBlob GetChevronTriangle(HbGpuBlobCache cache) => diff --git a/tests/RustToDust.Tests/HbGpuNativeTests.cs b/tests/RustToDust.Tests/HbGpuNativeTests.cs index efd33b4..915b1a2 100644 --- a/tests/RustToDust.Tests/HbGpuNativeTests.cs +++ b/tests/RustToDust.Tests/HbGpuNativeTests.cs @@ -175,4 +175,73 @@ public sealed class HbGpuNativeTests atlas.ClearPending(); } } + + [Fact] + public void PersistentAtlasOverflowDoesNotResetMidFrame() + { + var atlas = new HbGpuAtlasAllocator(); + var blobs = new HbGpuBlobCache(atlas); + + // Fill persistent zone right up near PersistentCapacity without crossing it + short[] chunk = new short[4096 * 4]; // 4096 texels + chunk[0] = 1; + while (atlas.PersistentCursor + 4096 <= HbGpuAtlasAllocator.PersistentCapacity) + { + atlas.AllocatePersistent(chunk); + atlas.ClearPending(); + } + + uint epochBefore = atlas.Epoch; + uint cursorBefore = atlas.PersistentCursor; + Assert.True(cursorBefore > HbGpuAtlasAllocator.PersistentResetWatermark); + + // Encode a static vector that exceeds remaining PersistentCapacity: must NOT reset mid-frame! + Span bigVerbs = stackalloc byte[64]; + Span bigArgs = stackalloc float[128]; + int v = 0, a = 0; + bigVerbs[v++] = (byte)HbGpuPathVerb.Move; + bigArgs[a++] = 0f; + bigArgs[a++] = 0f; + for (int i = 1; i <= 30; i++) + { + float ang = i * 0.2f; + bigVerbs[v++] = (byte)HbGpuPathVerb.LineTo; + bigArgs[a++] = MathF.Cos(ang) * 400f; + bigArgs[a++] = MathF.Sin(ang) * 400f; + } + bigVerbs[v++] = (byte)HbGpuPathVerb.Close; + + // First force a large remaining fill so the encoded vector overflows remaining space + uint rem = HbGpuAtlasAllocator.PersistentCapacity - atlas.PersistentCursor; + if (rem > 2) + { + atlas.AllocatePersistent(new short[(rem - 1) * 4]); + atlas.ClearPending(); + } + cursorBefore = atlas.PersistentCursor; + + CachedBlob overflowed = blobs.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.Custom, 999, 1), + 1000u, + bigVerbs[..v], + bigArgs[..a]); + + Assert.False(overflowed.IsValid); + Assert.Equal(epochBefore, atlas.Epoch); + Assert.Equal(cursorBefore, atlas.PersistentCursor); + Assert.True(blobs.IsPersistentOverflowPending); + + // Next BeginFrame resets cleanly and allows encoding + Assert.True(blobs.EnsureBudgetOrReset()); + Assert.Equal(epochBefore + 1, atlas.Epoch); + Assert.Equal(0u, atlas.PersistentCursor); + Assert.False(blobs.IsPersistentOverflowPending); + + CachedBlob recovered = blobs.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.Custom, 999, 1), + 1000u, + bigVerbs[..v], + bigArgs[..a]); + Assert.True(recovered.IsValid); + } } diff --git a/tools/build_release.ps1 b/tools/build_release.ps1 index 0bf7e72..0c8e7c7 100644 --- a/tools/build_release.ps1 +++ b/tools/build_release.ps1 @@ -23,6 +23,8 @@ catch { $MinReleaseYmirDllBytes = 400000L $MaxReleaseYmirDllBytes = 2000000L # Release is ~750-900 KB; Debug (with BOX3D_VALIDATE) is > 4 MB +$MinReleaseHbGpuDllBytes = 100000L +$MaxReleaseHbGpuDllBytes = 2621440L # < 2.5 MiB HarfBuzz 15.2.0 hb-gpu DLL budget function Resolve-RepoPath { param([string]$PathValue, [string]$BaseDir) @@ -259,6 +261,23 @@ if ($ymirDllLen -lt $MinReleaseYmirDllBytes -or $ymirDllLen -gt $MaxReleaseYmirD } Write-Host "Verified Release ymir_box3d.dll ($ymirDllLen B)." +Write-Host "`n[1b/5] Building Release rtd_hbgpu.dll..." +$hbGpuProj = Join-Path $RepoRoot "src\RustToDust.HbGpu\RustToDust.HbGpu.csproj" +& dotnet build $hbGpuProj -c Release -p:HbGpuNativeConfiguration=Release --disable-build-servers -p:UseSharedCompilation=false -nr:false +if ($LASTEXITCODE -ne 0) { + throw "dotnet build RustToDust.HbGpu failed with exit code $LASTEXITCODE." +} + +$hbGpuDllPath = Join-Path $RepoRoot "artifacts\hbgpu-native\Release\bin\Release\rtd_hbgpu.dll" +if (-not (Test-Path $hbGpuDllPath)) { + throw "Release rtd_hbgpu.dll not found at '$hbGpuDllPath'." +} +$hbGpuDllLen = (Get-Item $hbGpuDllPath).Length +if ($hbGpuDllLen -lt $MinReleaseHbGpuDllBytes -or $hbGpuDllLen -gt $MaxReleaseHbGpuDllBytes) { + throw "rtd_hbgpu.dll size outside Release range ($MinReleaseHbGpuDllBytes..$MaxReleaseHbGpuDllBytes B): got $hbGpuDllLen bytes at '$hbGpuDllPath'." +} +Write-Host "Verified Release rtd_hbgpu.dll ($hbGpuDllLen B)." + # Step 2: Export Windows Desktop Release via Godot Write-Host "`n[2/5] Exporting Windows Desktop Release..." if (Test-Path $StageDir) { @@ -318,10 +337,12 @@ if (-not $stagedDataDir) { # Remove PDBs if any slipped through Get-ChildItem -Path $StageDir -Recurse -Filter "*.pdb" -File | Remove-Item -Force -# Step 3: Stage Release ymir_box3d.dll & runtime assets/ -Write-Host "`n[3/5] Staging Release ymir_box3d.dll and runtime assets/..." +# Step 3: Stage Release ymir_box3d.dll, rtd_hbgpu.dll, licenses & runtime assets/ +Write-Host "`n[3/5] Staging Release native DLLs, licenses, and runtime assets/..." Copy-Item -Path $ymirDllPath -Destination (Join-Path $StageDir "ymir_box3d.dll") -Force Copy-Item -Path $ymirDllPath -Destination (Join-Path $stagedDataDir "ymir_box3d.dll") -Force +Copy-Item -Path $hbGpuDllPath -Destination (Join-Path $StageDir "rtd_hbgpu.dll") -Force +Copy-Item -Path $hbGpuDllPath -Destination (Join-Path $stagedDataDir "rtd_hbgpu.dll") -Force $fontLicenseSrc = Join-Path $ClientDir "fonts\MONASPACE_LICENSE.txt" if (-not (Test-Path $fontLicenseSrc)) { @@ -329,13 +350,26 @@ if (-not (Test-Path $fontLicenseSrc)) { } Copy-Item -Path $fontLicenseSrc -Destination (Join-Path $StageDir "MONASPACE_LICENSE.txt") -Force +$thirdPartySrc = Join-Path $RepoRoot "THIRD_PARTY_NOTICES.txt" +if (-not (Test-Path $thirdPartySrc)) { + throw "Required third-party notices missing: '$thirdPartySrc'." +} +Copy-Item -Path $thirdPartySrc -Destination (Join-Path $StageDir "THIRD_PARTY_NOTICES.txt") -Force + $stagedAssetsDir = Join-Path $StageDir "assets" $vCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "vehicles") -DestDir (Join-Path $stagedAssetsDir "vehicles") -IncludeExtensions @(".glb", ".cc", ".json") $gCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "gear") -DestDir (Join-Path $stagedAssetsDir "gear") -IncludeExtensions @(".glb") $dCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "decals") -DestDir (Join-Path $stagedAssetsDir "decals") -IncludeExtensions @(".png") $aCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "audio") -DestDir (Join-Path $stagedAssetsDir "audio") -IncludeExtensions @(".wav", ".md") +$fCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "fonts") -DestDir (Join-Path $stagedAssetsDir "fonts") -IncludeExtensions @(".ttf", ".txt", ".md") $mCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "maps\sion") -DestDir (Join-Path $stagedAssetsDir "maps\sion") -IncludeExtensions @(".json", ".f32", ".png", ".bin", ".glb") -Write-Host "Staged runtime assets: vehicles=$vCount gear=$gCount decals=$dCount audio=$aCount sion=$mCount" +foreach ($reqFontFile in @("Krypton.ttf", "OFL-1.1.txt", "HARFBUZZ-COPYING.txt")) { + $reqPath = Join-Path (Join-Path $stagedAssetsDir "fonts") $reqFontFile + if (-not (Test-Path $reqPath)) { + throw "Required staged font/license file missing: '$reqPath'." + } +} +Write-Host "Staged runtime assets: vehicles=$vCount gear=$gCount decals=$dCount audio=$aCount fonts=$fCount sion=$mCount" # Step 4: Create ZIP and SHA256SUMS.txt Write-Host "`n[4/5] Packaging $ZipName..."