diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 568a2bd..1267c14 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -73,6 +73,8 @@ jobs: arch: x64 - name: Native fixture and managed/AOT ownership qualification shell: pwsh + env: + DXSHARP_FLEET_EVIDENCE: artifacts/sample-results/fleet-system.ppm run: ./build/VerifyInterop.ps1 -Configuration Release -PublishAot - name: WARP sample qualification if: runner.os == 'Windows' diff --git a/doc/FleetBattler.md b/doc/FleetBattler.md index 79ba561..11c3c0a 100644 --- a/doc/FleetBattler.md +++ b/doc/FleetBattler.md @@ -2,7 +2,7 @@ The flagship sample starts with one star system, two factions, and a playable fleet skirmish. Scout a resource site, claim it, spend its output on reinforcements, then send ships to intercept a rival fleet. Use a fixed tick and seeded scenario so the same command stream can drive a replay, a headless test, or the visual sample. -The [Fleet Battler sample](../samples/FleetBattler) implements the first steering and rendering slice. The default scenario packs 1,024 ships into a single instance stream and draws the patrol mesh in three indexed instanced calls. It supports fleet selection, movement orders, camera zoom, a CPU benchmark, and a bounded WARP resize run. +The [Fleet Battler sample](../samples/FleetBattler) starts 72 ships in twelve independently steered squadrons. Send cyan squadrons to the mining beacon, keep a majority against the Amber patrol, and spend ore on two reinforcement wings. The tactical scene has a star, two planets, a moon, elliptical orbit guides, and a HUD for the objective. The renderer uses three indexed instanced ship draws, a sky pass, and an instanced HUD. The stress mode accepts 10,000 starting ships. | Slice | Implementation | Acceptance | | --- | --- | --- | diff --git a/samples/FleetBattler/FleetHud.cs b/samples/FleetBattler/FleetHud.cs new file mode 100644 index 0000000..bc81869 --- /dev/null +++ b/samples/FleetBattler/FleetHud.cs @@ -0,0 +1,140 @@ +using System.Numerics; +using System.Runtime.InteropServices; +using DXSharp.Graphics; +using DXSharp.Shaders; + +namespace FleetBattler; + +internal sealed class FleetHud { + private const uint Stride = 48; + internal const uint BufferBytes = 384 * Stride; + private static readonly Vector4 Panel = new( 0.029f, 0.052f, 0.091f, 1 ); + private static readonly Vector4 Label = new( 0.65f, 0.76f, 0.87f, 1 ); + private static readonly Vector4 White = new( 0.94f, 0.97f, 1.0f, 1 ); + private readonly Glyph[] _glyphs = new Glyph[BufferBytes / Stride]; + private int _count; + + [StructLayout( LayoutKind.Sequential )] + private readonly record struct Glyph( Vector4 Rectangle, Vector4 Tint, uint Low, uint High, uint Panel, uint Padding ); + + private const string Shader = """ + cbuffer Hud : register(b0) { float4 Viewport; }; + struct Input { float4 rect : POSITION; float4 tint : COLOR; uint4 bits : TEXCOORD; }; + struct Output { + float4 position : SV_Position; + float2 uv : TEXCOORD0; + nointerpolation uint2 bits : TEXCOORD1; + nointerpolation float4 tint : COLOR; + }; + Output VS(Input input, uint id : SV_VertexID) { + const float2 corners[6] = { + float2(0,0), float2(1,0), float2(0,1), + float2(0,1), float2(1,0), float2(1,1) + }; + Output output; + output.uv = corners[id]; + float2 pixel = input.rect.xy + output.uv * input.rect.zw; + output.position = float4(pixel/Viewport.xy*float2(2,-2)+float2(-1,1), input.bits.z == 1 ? 0.04 : input.bits.z == 2 ? 0.025 : 0.01, 1); + output.bits = input.bits.xy; + output.tint = input.tint; + return output; + } + float4 PS(Output input) : SV_Target { + uint2 cell = min(uint2(input.uv*float2(5,7)), uint2(4,6)); + uint index = cell.x + cell.y*5; + uint bits = index < 32 ? input.bits.x : input.bits.y; + clip((float)((bits >> (index & 31)) & 1) - 0.5); + return input.tint; + } + """; + + internal static PipelineState CreatePipeline( GraphicsDevice device, RootSignature root, ShaderCompiler compiler ) => + device.CreateGraphicsPipeline( root, compiler.Compile( Shader, "VS", "vs_6_0" ), + compiler.Compile( Shader, "PS", "ps_6_0" ), [ + new( "POSITION", VertexFormat.Float4, 0, InstanceStepRate: 1 ), + new( "COLOR", VertexFormat.Float4, 16, InstanceStepRate: 1 ), + new( "TEXCOORD", VertexFormat.UInt4, 32, InstanceStepRate: 1 ) + ], depthEnabled: true ); + + internal void Record( GraphicsCommandList commands, PipelineState pipeline, GpuResource upload, FleetSimulation fleet, + int selected, int width, int height, bool oreShort ) { + if ( width < 350 || height < 240 ) return; + _count = 0; + Span text = stackalloc char[72]; + float right = width - 165; + var siteTint = fleet.Contested ? SpaceDraw.Amber : fleet.Owner == 0 ? SpaceDraw.Cyan : fleet.Owner == 1 ? SpaceDraw.Amber : SpaceDraw.Neutral; + Rect( 14, 14, 145, 55, Panel, 1 ); + Rect( 14, 14, 2, 55, SpaceDraw.Cyan ); + Text( "FLEET COMMAND", 23, 23, 1.6f, White ); + text.TryWrite( $"SQUAD {selected + 1:D2} {fleet.ShipCount( selected )} SHIPS", out int length ); + Text( text[..length], 23, 49, 1, SpaceDraw.Cyan ); + + Rect( right, 14, 151, 80, Panel, 1 ); + Rect( right, 14, 2, 80, siteTint ); + Text( "MINING BEACON", right + 9, 23, 1.35f, White ); + var site = fleet.Contested ? "CONTESTED" : fleet.Capturing == 0 ? "CYAN CAPTURING" + : fleet.Capturing == 1 ? "AMBER CAPTURING" : fleet.Owner == 0 ? "CYAN CONTROL" + : fleet.Owner == 1 ? "AMBER CONTROL" : "NEUTRAL"; + Text( site, right + 9, 42, 1, siteTint ); + text.TryWrite( $"ORE {fleet.Ore:D3} WINGS {fleet.WingsBuilt}/{FleetSimulation.WingGoal}", out length ); + Text( text[..length], right + 9, 62, 1, Label ); + float fraction = fleet.CaptureTicks > 0 ? (float)fleet.CaptureTicks / FleetSimulation.CaptureDuration + : Math.Clamp( (float)fleet.Ore / FleetSimulation.WingCost, 0, 1 ); + if ( fraction > 0 ) Rect( right + 9, 78, 130 * fraction, 2, siteTint ); + + float bottom = height - 60; + Rect( 14, bottom, width - 28, 46, Panel, 1 ); + Rect( 14, bottom, 2, 46, SpaceDraw.Cyan ); + string instruction = fleet.WingsBuilt == FleetSimulation.WingGoal ? "OBJECTIVE COMPLETE" + : oreShort && fleet.Ore < FleetSimulation.WingCost ? "NEED 60 ORE TO BUILD" + : fleet.Ore >= FleetSimulation.WingCost ? "PRESS B TO LAUNCH A WING" + : fleet.Owner == 0 ? "HOLD THE BEACON TO MINE ORE" : "SEND CYAN SQUADS TO THE BEACON"; + Text( instruction, 23, bottom + 8, 1.25f, fleet.WingsBuilt == FleetSimulation.WingGoal ? SpaceDraw.Cyan : White ); + Text( width >= 470 ? "L CLICK SELECT R CLICK MOVE B BUILD WHEEL ZOOM MID DRAG PAN" + : "L CLICK SELECT R CLICK MOVE B BUILD WHEEL ZOOM", 23, bottom + 29, 1, Label ); + + upload.Write( _glyphs.AsSpan( 0, _count ) ); + commands.SetGraphicsPipeline( pipeline ); + commands.SetGraphicsConstants( [BitConverter.SingleToUInt32Bits( width ), BitConverter.SingleToUInt32Bits( height ), 0, 0] ); + commands.SetVertexBuffer( 0, upload, Stride ); + commands.Draw( 6, (uint)_count ); + } + + private void Rect( float x, float y, float width, float height, Vector4 color, uint layer = 2 ) => + _glyphs[_count++] = new( new( x, y, width, height ), color, uint.MaxValue, 7, layer, 0 ); + + private void Text( ReadOnlySpan text, float x, float y, float scale, Vector4 tint ) { + foreach ( char c in text ) { + uint[]? rows = null; + int index = c switch { + >= 'A' and <= 'Z' => c - 'A', + >= '0' and <= '9' => c - '0' + 26, + '/' => 36, '-' => 37, _ => -1 + }; + if ( index >= 0 ) rows = Font[index]; + if ( rows is not null ) { + ulong bits = 0; + for ( int row = 0; row < 7; ++row ) bits |= (ulong)rows[row] << (row * 5); + _glyphs[_count++] = new( new( x, y, 5 * scale, 7 * scale ), tint, (uint)bits, (uint)(bits >> 32), 0, 0 ); + } + x += 6 * scale; + } + } + + // Rows are stored with the leftmost pixel in the low bit. + private static readonly uint[][] Font = [ + [14,17,17,31,17,17,17], [15,17,17,15,17,17,15], [30,1,1,1,1,1,30], + [15,17,17,17,17,17,15], [31,1,1,15,1,1,31], [31,1,1,15,1,1,1], + [30,1,1,29,17,17,30], [17,17,17,31,17,17,17], [31,4,4,4,4,4,31], + [28,8,8,8,9,9,6], [17,9,5,3,5,9,17], [1,1,1,1,1,1,31], + [17,27,21,21,17,17,17], [17,19,21,25,17,17,17], [14,17,17,17,17,17,14], + [15,17,17,15,1,1,1], [14,17,17,17,21,9,22], [15,17,17,15,5,9,17], + [30,1,1,14,16,16,15], [31,4,4,4,4,4,4], [17,17,17,17,17,17,14], + [17,17,17,17,17,10,4], [17,17,17,21,21,27,17], [17,17,10,4,10,17,17], + [17,17,10,4,4,4,4], [31,16,8,4,2,1,31], + [14,17,25,21,19,17,14], [4,6,4,4,4,4,14], [14,17,16,8,4,2,31], + [31,16,8,12,16,17,14], [8,12,10,9,31,8,8], [31,1,1,15,16,16,15], + [12,2,1,15,17,17,14], [31,16,8,4,2,2,2], [14,17,17,14,17,17,14], + [14,17,17,30,16,8,6], [16,16,8,4,2,1,1], [0,0,0,31,0,0,0] + ]; +} diff --git a/samples/FleetBattler/FleetSimulation.cs b/samples/FleetBattler/FleetSimulation.cs index 817a93d..8540f41 100644 --- a/samples/FleetBattler/FleetSimulation.cs +++ b/samples/FleetBattler/FleetSimulation.cs @@ -8,105 +8,186 @@ namespace FleetBattler; internal sealed class FleetSimulation { internal const int MaxShips = 10_000; + internal const int DefaultShips = 72; + internal const int WingSize = 6, WingCost = 60, WingGoal = 2; + internal const int CaptureDuration = 90, IncomeInterval = 60, IncomeAmount = 15; internal const double StepSeconds = 1.0 / 60; - private const float Pitch = 3.6f; - private const float MaxSpeed = 36; - private const float ApproachGain = 1.8f; - private const float Response = 0.09f; - private readonly Vector2[] _positions; - private readonly Vector2[] _velocities; - private readonly Vector2[] _headings; - private readonly Vector2[] _offsets; - private readonly Vector2[] _targets = new Vector2[2]; - private readonly int _split; + private const int SquadsPerFaction = 6; + private const float Pitch = 3.9f, MaxSpeed = 36, ApproachGain = 1.8f, Response = 0.09f; + private readonly Vector2[] _positions, _velocities, _headings, _offsets; + private readonly Squad[] _squads = new Squad[2 * SquadsPerFaction + WingGoal]; + private readonly bool _rivalPatrol; private readonly float _targetLimit; + private int _amberFirst, _incomeTicks; + private uint _seed; - internal FleetSimulation( int ships, uint seed ) { + private struct Squad { + internal int First, Count, Faction; + internal Vector2 Home, Target, Center; + } + + internal FleetSimulation( int ships, uint seed, bool rivalPatrol = false ) { if ( ships is < 2 or > MaxShips ) throw new ArgumentOutOfRangeException( nameof(ships) ); - _positions = new Vector2[ships]; - _velocities = new Vector2[ships]; - _headings = new Vector2[ships]; - _offsets = new Vector2[ships]; - _split = (ships + 1) / 2; - int side = (int)MathF.Ceiling( MathF.Sqrt( _split ) ); - BoardRadius = side * Pitch + 14; - _targetLimit = BoardRadius - side * Pitch * 0.5f - 3; - _targets[0] = new( -0.51f * BoardRadius, 0.24f * BoardRadius ); - _targets[1] = -_targets[0]; - for ( int i = 0; i < ships; ++i ) { - int fleet = i < _split ? 0 : 1; - int slot = fleet == 0 ? i : i - _split; - var cell = new Vector2( slot % side, slot / side ) - new Vector2( (side - 1) * 0.5f ); - var jitter = new Vector2( NextUnit( ref seed ), NextUnit( ref seed ) ) - new Vector2( 0.5f ); - _offsets[i] = cell * Pitch + jitter * 0.42f; - _positions[i] = _targets[fleet] + _offsets[i]; - _headings[i] = fleet == 0 ? Vector2.UnitX : -Vector2.UnitX; - } + _seed = seed; + _rivalPatrol = rivalPatrol; + int capacity = ships + WingGoal * WingSize; + _positions = new Vector2[capacity]; + _velocities = new Vector2[capacity]; + _headings = new Vector2[capacity]; + _offsets = new Vector2[capacity]; + int cyan = (ships + 1) / 2; + int largestSquad = (cyan + SquadsPerFaction - 1) / SquadsPerFaction; + float formationRadius = MathF.Ceiling( MathF.Sqrt( largestSquad * 1.6f ) ) * Pitch; + BoardRadius = MathF.Max( 78, formationRadius * 2.85f + 22 ); + _targetLimit = BoardRadius - formationRadius * 0.6f; + Site = new( BoardRadius * 0.14f, -BoardRadius * 0.07f ); + SiteRadius = MathF.Max( 8, BoardRadius * 0.093f ); + AddFleet( cyan, 0 ); + _amberFirst = SquadCount; + AddFleet( ships - cyan, 1 ); } internal float BoardRadius { get; } - internal int Count => _positions.Length; + internal Vector2 Site { get; } + internal float SiteRadius { get; } + internal Vector2 Shipyard => new( -0.59f * BoardRadius, 0.62f * BoardRadius ); + internal int Count { get; private set; } + internal int Capacity => _positions.Length; + internal int SquadCount { get; private set; } internal int Tick { get; private set; } - internal ReadOnlySpan Positions => _positions; + internal int Owner { get; private set; } = -1; + internal int Capturing { get; private set; } = -1; + internal int CaptureTicks { get; private set; } + internal bool Contested { get; private set; } + internal int Ore { get; private set; } + internal int WingsBuilt { get; private set; } + internal ReadOnlySpan Positions => _positions.AsSpan( 0, Count ); + + internal Vector2 Center( int squad ) => _squads[squad].Center; + internal Vector2 Target( int squad ) => _squads[squad].Target; + internal int ShipCount( int squad ) => _squads[squad].Count; - internal int FindFleet( Vector2 point ) { + internal int FindSquad( Vector2 point ) { int closest = 0; float best = float.PositiveInfinity; - for ( int i = 0; i < _positions.Length; ++i ) { - float distance = Vector2.DistanceSquared( point, _positions[i] ); + for ( int i = 0; i < SquadCount; ++i ) { + if ( _squads[i].Faction != 0 ) continue; + float distance = Vector2.DistanceSquared( point, _squads[i].Center ); if ( distance >= best ) continue; best = distance; closest = i; } - return closest < _split ? 0 : 1; + return closest; } - internal void Move( int fleet, Vector2 destination ) { - if ( fleet is < 0 or > 1 ) throw new ArgumentOutOfRangeException( nameof(fleet) ); + internal void Move( int squad, Vector2 destination ) { + if ( (uint)squad >= (uint)SquadCount ) throw new ArgumentOutOfRangeException( nameof(squad) ); if ( !float.IsFinite( destination.X ) || !float.IsFinite( destination.Y ) ) throw new ArgumentOutOfRangeException( nameof(destination) ); - _targets[fleet] = Vector2.Clamp( destination, new( -_targetLimit ), new( _targetLimit ) ); + _squads[squad].Target = Vector2.Clamp( destination, new( -_targetLimit ), new( _targetLimit ) ); + } + + internal int BuildWing( ) { + if ( Ore < WingCost || WingsBuilt == WingGoal ) return -1; + int index = SquadCount; + var arrival = Shipyard + new Vector2( WingsBuilt * 13, 0 ); + AddSquad( WingSize, 0, arrival ); + Ore -= WingCost; + ++WingsBuilt; + return index; } internal void Step( ) { - for ( int i = 0; i < _positions.Length; ++i ) { - var error = _targets[i < _split ? 0 : 1] + _offsets[i] - _positions[i]; - var desired = error * ApproachGain; - float speedSquared = desired.LengthSquared( ); - if ( speedSquared > MaxSpeed * MaxSpeed ) - desired *= MaxSpeed / MathF.Sqrt( speedSquared ); - var velocity = Vector2.Lerp( _velocities[i], desired, Response ); - if ( error.LengthSquared( ) < 0.0001f && velocity.LengthSquared( ) < 0.0001f ) { - _positions[i] += error; - _velocities[i] = Vector2.Zero; - continue; + if ( _rivalPatrol && Tick >= 480 && (Tick - 480) % 600 == 0 ) { + bool incoming = ((Tick - 480) / 600 & 1) == 0; + Move( _amberFirst, incoming ? Site : _squads[_amberFirst].Home ); + } + + int cyan = 0, amber = 0; + for ( int i = 0; i < SquadCount; ++i ) { + ref var squad = ref _squads[i]; + var sum = Vector2.Zero; + int end = squad.First + squad.Count; + for ( int ship = squad.First; ship < end; ++ship ) { + var error = squad.Target + _offsets[ship] - _positions[ship]; + var desired = error * ApproachGain; + float speedSquared = desired.LengthSquared( ); + if ( speedSquared > MaxSpeed * MaxSpeed ) desired *= MaxSpeed / MathF.Sqrt( speedSquared ); + var velocity = Vector2.Lerp( _velocities[ship], desired, Response ); + if ( error.LengthSquared( ) < 0.0001f && velocity.LengthSquared( ) < 0.0001f ) { + _positions[ship] += error; + _velocities[ship] = Vector2.Zero; + } else { + _velocities[ship] = velocity; + _positions[ship] += velocity * (float)StepSeconds; + if ( velocity.LengthSquared( ) > 0.25f ) _headings[ship] = Vector2.Normalize( velocity ); + } + sum += _positions[ship]; + } + squad.Center = sum / squad.Count; + if ( Vector2.DistanceSquared( squad.Center, Site ) <= SiteRadius * SiteRadius ) { + if ( squad.Faction == 0 ) ++cyan; + else ++amber; } - _velocities[i] = velocity; - _positions[i] += velocity * (float)StepSeconds; - if ( velocity.LengthSquared( ) > 0.25f ) - _headings[i] = Vector2.Normalize( velocity ); } + AdvanceSite( cyan, amber ); ++Tick; } + private void AdvanceSite( int cyan, int amber ) { + Contested = cyan != 0 && amber != 0; + int dominant = cyan == amber ? -1 : cyan > amber ? 0 : 1; + if ( dominant != -1 && dominant != Owner ) { + if ( Capturing != dominant ) { + CaptureTicks = 0; + Capturing = dominant; + } + if ( ++CaptureTicks == CaptureDuration ) { + Owner = dominant; + Capturing = -1; + CaptureTicks = 0; + _incomeTicks = 0; + } + } else { + Capturing = -1; + CaptureTicks = 0; + } + + if ( Owner != 0 || dominant != 0 || WingsBuilt == WingGoal ) { + _incomeTicks = 0; + return; + } + if ( ++_incomeTicks == IncomeInterval ) { + Ore = Math.Min( Ore + IncomeAmount, WingCost * WingGoal ); + _incomeTicks = 0; + } + } + internal void FillInstances( Span destination, int selected ) { - if ( destination.Length != _positions.Length ) throw new ArgumentException( "Instance span must match the fleet size.", nameof(destination) ); - var cyan = new Vector4( 0.62f, 1.45f, 2.15f, selected == 0 ? 1.2f : 0.87f ); - var orange = new Vector4( 2.55f, 0.79f, 0.32f, selected == 1 ? 1.2f : 0.87f ); - for ( int i = 0; i < destination.Length; ++i ) - destination[i] = new( _positions[i], _headings[i], i < _split ? cyan : orange ); + if ( destination.Length != Count ) throw new ArgumentException( "Instance span must match the active ship count.", nameof(destination) ); + for ( int i = 0; i < SquadCount; ++i ) { + ref readonly var squad = ref _squads[i]; + var tint = squad.Faction == 0 ? new Vector4( 0.66f, 1.55f, 2.25f, i == selected ? 1.55f : 1.04f ) + : new Vector4( 2.9f, 0.89f, 0.37f, 1.11f ); + int end = squad.First + squad.Count; + for ( int ship = squad.First; ship < end; ++ship ) + destination[ship] = new( _positions[ship], _headings[ship], tint ); + } } internal ulong StateHash( ) { ulong hash = 14695981039346656037; - Append( (uint)Tick ); - Append( (uint)Count ); - foreach ( var target in _targets ) AppendVector( target ); - for ( int i = 0; i < _positions.Length; ++i ) { - AppendVector( _offsets[i] ); - AppendVector( _positions[i] ); - AppendVector( _velocities[i] ); - AppendVector( _headings[i] ); + Append( (uint)Tick ); Append( (uint)Count ); Append( (uint)SquadCount ); Append( _seed ); + Append( (uint)Owner ); Append( (uint)Capturing ); Append( (uint)CaptureTicks ); Append( Contested ? 1u : 0u ); + Append( (uint)Ore ); Append( (uint)WingsBuilt ); Append( (uint)_incomeTicks ); Append( _rivalPatrol ? 1u : 0u ); + for ( int i = 0; i < SquadCount; ++i ) { + ref readonly var squad = ref _squads[i]; + Append( (uint)squad.Count ); Append( (uint)squad.Faction ); + AppendVector( squad.Home ); AppendVector( squad.Target ); AppendVector( squad.Center ); + } + for ( int i = 0; i < Count; ++i ) { + AppendVector( _offsets[i] ); AppendVector( _positions[i] ); + AppendVector( _velocities[i] ); AppendVector( _headings[i] ); } return hash; @@ -121,10 +202,42 @@ void Append( uint bits ) { } } - private static float NextUnit( ref uint state ) { - // Integer mixing keeps seeded placement independent of System.Random. - state = unchecked(state + 0x9E3779B9u); - uint bits = state; + private void AddFleet( int ships, int faction ) { + int squads = Math.Min( ships, SquadsPerFaction ); + for ( int i = 0; i < squads; ++i ) { + float angle = -0.93f + 1.86f * (i + 0.5f) / squads; + float radius = BoardRadius * (i % 2 == 0 ? 0.56f : 0.77f); + var home = new Vector2( MathF.Cos( angle ) * (faction == 0 ? -1 : 1), MathF.Sin( angle ) ) * radius; + AddSquad( ships / squads + (i < ships % squads ? 1 : 0), faction, home ); + } + } + + private void AddSquad( int count, int faction, Vector2 center ) { + var heading = faction == 0 ? Vector2.UnitX : -Vector2.UnitX; + var right = new Vector2( -heading.Y, heading.X ); + int columns = (int)MathF.Ceiling( MathF.Sqrt( count * 1.6f ) ); + var mean = Vector2.Zero; + for ( int i = 0; i < count; ++i ) { + int row = count <= 10 ? (int)((MathF.Sqrt( 8 * i + 1 ) - 1) * 0.5f) : i / columns; + float column = count <= 10 ? i - row * (row + 2) * 0.5f : i % columns + (row & 1) * 0.5f; + var jitter = (new Vector2( NextUnit( ), NextUnit( ) ) - new Vector2( 0.5f )) * 0.28f; + var local = new Vector2( column, row * 0.91f ) * Pitch + jitter; + _offsets[Count + i] = right * local.X - heading * local.Y; + mean += _offsets[Count + i]; + } + mean /= count; + for ( int i = Count; i < Count + count; ++i ) { + _offsets[i] -= mean; + _positions[i] = center + _offsets[i]; + _headings[i] = heading; + } + _squads[SquadCount++] = new( ) { First = Count, Count = count, Faction = faction, Home = center, Target = center, Center = center }; + Count += count; + } + + private float NextUnit( ) { + _seed = unchecked(_seed + 0x9E3779B9u); + uint bits = _seed; bits = unchecked((bits ^ (bits >> 16)) * 0x85EBCA6Bu); bits = unchecked((bits ^ (bits >> 13)) * 0xC2B2AE35u); return ((bits ^ (bits >> 16)) >> 8) * (1f / 16_777_216); diff --git a/samples/FleetBattler/Program.cs b/samples/FleetBattler/Program.cs index 78bb122..4d8291f 100644 --- a/samples/FleetBattler/Program.cs +++ b/samples/FleetBattler/Program.cs @@ -19,9 +19,10 @@ public static int Main( string[] args ) { } private static int Run( string[] args ) { - var fleet = new FleetSimulation( int.Parse( Option( args, "--ships=", "1024" ) ), uint.Parse( Option( args, "--seed=", "37" ) ) ); int ticks = int.Parse( Option( args, "--benchmark-ticks=", "0" ) ); ArgumentOutOfRangeException.ThrowIfNegative( ticks ); + var fleet = new FleetSimulation( int.Parse( Option( args, "--ships=", FleetSimulation.DefaultShips.ToString( ) ) ), + uint.Parse( Option( args, "--seed=", "37" ) ), rivalPatrol: ticks == 0 ); if ( ticks > 0 ) { Benchmark( fleet, ticks ); return 0; @@ -49,17 +50,23 @@ private static int Run( string[] args ) { var model = GltfModel.Load( Path.Combine( AppContext.BaseDirectory, "Models", "Patrol.gltf" ) ); Console.WriteLine( device.AdapterName ); Console.WriteLine( $"{fleet.Count:N0} ships, {model.Primitives.Length} shared primitives, {fleet.Count * FleetDraw.InstanceStride:N0} instance bytes per frame." ); - Console.WriteLine( "Left-click a fleet to select it. Right-click to move it. Scroll to zoom." ); + Console.WriteLine( "Left-click to select a cyan squadron, right-click to move, B to build, wheel to zoom." ); using var compiler = new ShaderCompiler( ); using var root = device.CreateGraphicsConstantsRootSignature( 16 ); using var pipeline = FleetDraw.CreatePipeline( device, root, compiler, depthEnabled: true ); - using var first = device.CreateBuffer( (ulong)fleet.Count * FleetDraw.InstanceStride, BufferMemory.Upload ); - using var second = device.CreateBuffer( (ulong)fleet.Count * FleetDraw.InstanceStride, BufferMemory.Upload ); + using var spaceRoot = device.CreateGraphicsConstantsRootSignature( SpaceDraw.Constants ); + using var space = SpaceDraw.CreatePipeline( device, spaceRoot, compiler ); + using var hudRoot = device.CreateGraphicsConstantsRootSignature( 4 ); + using var hud = FleetHud.CreatePipeline( device, hudRoot, compiler ); + using var first = device.CreateBuffer( (ulong)fleet.Capacity * FleetDraw.InstanceStride, BufferMemory.Upload ); + using var second = device.CreateBuffer( (ulong)fleet.Capacity * FleetDraw.InstanceStride, BufferMemory.Upload ); + using var firstHud = device.CreateBuffer( FleetHud.BufferBytes, BufferMemory.Upload ); + using var secondHud = device.CreateBuffer( FleetHud.BufferBytes, BufferMemory.Upload ); var meshes = new Mesh[model.Primitives.Length]; try { UploadMeshes( device, model, meshes ); - var result = Present( device, pipeline, fleet, meshes, [first, second], frameLimit, resizeTest ); + var result = Present( device, pipeline, space, hud, fleet, meshes, [first, second], [firstHud, secondHud], frameLimit, resizeTest ); var diagnostics = device.GetDiagnostics( ); foreach ( string message in diagnostics.Messages ) Console.WriteLine( message ); if ( diagnostics.DeviceRemovedReason < 0 || diagnostics.Messages.Any( @@ -72,17 +79,19 @@ private static int Run( string[] args ) { } } - private static DesktopRunResult Present( GraphicsDevice device, PipelineState pipeline, FleetSimulation fleet, Mesh[] meshes, - GpuResource[] uploads, int frameLimit, bool resizeTest ) { - var instances = new ShipInstance[fleet.Count]; + private static DesktopRunResult Present( GraphicsDevice device, PipelineState pipeline, PipelineState space, PipelineState hudPipeline, + FleetSimulation fleet, Mesh[] meshes, GpuResource[] uploads, GpuResource[] hudUploads, int frameLimit, bool resizeTest ) { + var instances = new ShipInstance[fleet.Capacity]; + var hud = new FleetHud( ); + bool oreShort = false; int selected = 0, slotsUsed = 0; - float zoom = 1; + float zoom = 0.94f; + Vector2 cameraFocus = default; + Point? panStart = null; double lag = 0; Matrix4x4 inverseViewProjection = default; Size viewport = default; float radius = fleet.BoardRadius; - fleet.Move( 0, new( -radius * 0.39f, -radius * 0.23f ) ); - fleet.Move( 1, new( radius * 0.39f, radius * 0.23f ) ); var run = DesktopGame.Run( device, new( ) { Title = "DXSharp · Fleet Battler", EnableDepth = true, FramesInFlight = uploads.Length, FrameLimit = frameLimit, ClearColor = new( 0.017f, 0.025f, 0.048f, 1 ) @@ -96,28 +105,52 @@ private static DesktopRunResult Present( GraphicsDevice device, PipelineState pi viewport = frame.Size; float aspect = (float)viewport.Width / viewport.Height; float halfHeight = radius * zoom / MathF.Min( aspect, 1 ); - var view = Matrix4x4.CreateLookAt( new( 0, radius * 1.6f, radius * 0.88f ), Vector3.Zero, Vector3.UnitY ); + var focus = new Vector3( cameraFocus.X, 0, cameraFocus.Y ); + var view = Matrix4x4.CreateLookAt( focus + new Vector3( 0, radius * 1.6f, radius * 0.88f ), focus, Vector3.UnitY ); var projection = Matrix4x4.CreateOrthographic( 2 * halfHeight * aspect, 2 * halfHeight, 0.1f, 4 * radius ); var viewProjection = view * projection; Matrix4x4.Invert( viewProjection, out inverseViewProjection ); - fleet.FillInstances( instances, selected ); + SpaceDraw.Record( frame.Commands, space, fleet, selected, viewProjection, inverseViewProjection, viewport.Width, viewport.Height, halfHeight ); + var active = instances.AsSpan( 0, fleet.Count ); + fleet.FillInstances( active, selected ); // DesktopGame waits for this slot's fence before invoking the callback. slotsUsed |= 1 << frame.FrameSlotIndex; var upload = uploads[frame.FrameSlotIndex]; - upload.Write( instances ); - FleetDraw.Record( frame.Commands, pipeline, meshes, upload, (uint)instances.Length, viewProjection ); + upload.Write( active ); + FleetDraw.Record( frame.Commands, pipeline, meshes, upload, (uint)active.Length, viewProjection ); + hud.Record( frame.Commands, hudPipeline, hudUploads[frame.FrameSlotIndex], fleet, selected, viewport.Width, viewport.Height, oreShort ); }, ( window, result ) => { if ( result.Frames == 1 ) { - UpdateTitle( window ); + window.KeyPreview = true; + window.KeyDown += ( _, e ) => { + if ( e.KeyCode != Keys.B ) return; + int wing = fleet.BuildWing( ); + oreShort = wing < 0; + if ( wing >= 0 ) selected = wing; + e.SuppressKeyPress = true; + }; window.MouseDown += ( _, e ) => { + if ( e.Button == MouseButtons.Middle ) { panStart = e.Location; return; } if ( !TryPick( e.Location, viewport, inverseViewProjection, out var target ) ) return; - if ( e.Button == MouseButtons.Left ) { - selected = fleet.FindFleet( target ); - UpdateTitle( window ); - } else if ( e.Button == MouseButtons.Right ) fleet.Move( selected, target ); + if ( e.Button == MouseButtons.Left ) selected = fleet.FindSquad( target ); + else if ( e.Button == MouseButtons.Right ) fleet.Move( selected, target ); + }; + window.MouseMove += ( _, e ) => { + if ( panStart is not { } previous ) return; + if ( e.Button != MouseButtons.Middle ) { panStart = null; return; } + if ( TryPick( previous, viewport, inverseViewProjection, out var from ) && + TryPick( e.Location, viewport, inverseViewProjection, out var to ) ) + cameraFocus = ClampCamera( cameraFocus + from - to ); + panStart = e.Location; + }; + window.MouseUp += ( _, e ) => { if ( e.Button == MouseButtons.Middle ) panStart = null; }; + window.MouseWheel += ( _, e ) => { + float nextZoom = Math.Clamp( zoom * MathF.Pow( 0.85f, e.Delta / 120f ), 0.18f, 2.2f ); + if ( TryPick( e.Location, viewport, inverseViewProjection, out var anchor ) ) + cameraFocus = ClampCamera( cameraFocus + (anchor - cameraFocus) * (1 - nextZoom / zoom) ); + zoom = nextZoom; }; - window.MouseWheel += ( _, e ) => zoom = Math.Clamp( zoom * MathF.Pow( 0.85f, e.Delta / 120f ), 0.24f, 2.2f ); } if ( resizeTest && result.Frames == 2 ) window.ClientSize = new( 800, 520 ); if ( resizeTest && result.Frames == 4 ) window.ClientSize = new( 710, 575 ); @@ -126,8 +159,8 @@ private static DesktopRunResult Present( GraphicsDevice device, PipelineState pi throw new InvalidOperationException( "Resize qualification did not exercise both frame slots." ); return run; - void UpdateTitle( Form window ) => - window.Text = $"DXSharp · Fleet Battler · {fleet.Count:N0} ships · {(selected == 0 ? "Cyan" : "Amber")} selected"; + Vector2 ClampCamera( Vector2 center ) => Vector2.Clamp( center, new( -radius ), new( radius ) ); + } private static bool TryPick( Point pixel, Size viewport, Matrix4x4 inverse, out Vector2 point ) { @@ -158,7 +191,7 @@ private static void UploadMeshes( GraphicsDevice device, StaticModel model, Mesh private static void Benchmark( FleetSimulation fleet, int ticks ) { var instances = new ShipInstance[fleet.Count]; fleet.Move( 0, Vector2.Zero ); - fleet.Move( 1, Vector2.Zero ); + for ( int squad = 1; squad < fleet.SquadCount; ++squad ) fleet.Move( squad, Vector2.Zero ); for ( int i = 0; i < 128; ++i ) { fleet.Step( ); fleet.FillInstances( instances, 0 ); @@ -170,8 +203,10 @@ private static void Benchmark( FleetSimulation fleet, int ticks ) { // Reverse the target periodically so long runs keep exercising movement. if ( i % 60 == 0 ) { float offset = (i / 60 & 1) == 0 ? fleet.BoardRadius * 0.4f : -fleet.BoardRadius * 0.4f; - fleet.Move( 0, new( offset, offset ) ); - fleet.Move( 1, new( -offset, -offset ) ); + for ( int squad = 0; squad < fleet.SquadCount; ++squad ) { + float target = (squad & 1) == 0 ? offset : -offset; + fleet.Move( squad, new( target, target ) ); + } } long start = Stopwatch.GetTimestamp( ); fleet.Step( ); diff --git a/samples/FleetBattler/README.md b/samples/FleetBattler/README.md index 07e6cb8..98a43d3 100644 --- a/samples/FleetBattler/README.md +++ b/samples/FleetBattler/README.md @@ -1,6 +1,11 @@ # Fleet Battler -Command two patrol formations from a tactical camera. Left-click a ship to select its fleet, right-click to move the formation, and scroll to zoom. The formations begin with opposing movement orders. The current scenario covers steering and presentation. The [fleet roadmap](../../doc/FleetBattler.md) covers resource sites, reinforcements, combat, and GPU effects. +Command cyan squadrons in a small orbital system. Secure the mining beacon and launch two reinforcement wings from the shipyard. Amber patrols the beacon and can take it from you. + +- **Left-click** near a cyan squadron to select it. **Right-click** to set a destination. The cyan bracket marks the selected squadron and the dashed line shows its order. +- **Scroll** to zoom toward the pointer. **Middle-drag** to pan across the system. +- Move squadrons inside the beacon's circle. The side with more squadrons inside takes control after 1.5 seconds. Equal presence contests the site. +- Hold a cyan majority to earn 15 ore per second. Press **B** to spend 60 ore on a six-ship wing. The new wing spawns at the cyan shipyard and becomes selected. ```powershell dotnet run --project samples/FleetBattler -c Release @@ -9,9 +14,12 @@ dotnet run --project samples/FleetBattler -c Debug -- --warp --ships=129 --frame dotnet run --project samples/FleetBattler -c Release -- --ships=10000 --benchmark-ticks=600 ``` -- The CPU steps position and velocity arrays at 60 Hz. Formation slot offsets and entity order are seeded. Replaying the same commands at the same ticks reproduces the state hash on a given build and architecture. -- The renderer uploads the three patrol mesh primitives once. It writes 32 bytes per ship into the current frame slot and submits three indexed instanced draws for the entire fleet. `DesktopFrame.FrameSlotIndex` identifies the slot after its previous fence completes. -- The benchmark runs without creating a graphics device. It measures CPU simulation, instance packing, and thread allocations for the measured ticks. The displayed instance bytes are the size of one packed stream. GPU timing requires a rendered run. -- Qualification compares replay checkpoints, checks formation spacing and instance layout, and verifies cyan and amber geometry in separate regions of an offscreen WARP render. The windowed test exercises both frame slots through two resizes. +The default scenario has 72 ships in twelve six-ship wedges. The 60 Hz simulation uses seeded formation offsets and stable squad order. It preallocates space for two reinforcement wings. Replaying commands at the same ticks reproduces the state hash within a build and runtime. + +The tactical view uses procedural stars and nebulae, a sun, a terrestrial world and its moon, and a ringed gas giant. The bodies follow fixed-tick elliptical orbits. The rendered bodies are shaded billboards below the tactical plane. The camera projects the orbital tracks, the beacon, and move orders in world space. A HUD reports ownership, ore, and the reinforcement objective. + +The renderer uploads three patrol mesh primitives once and issues three indexed instanced ship draws. It writes 32 bytes per active ship into a fence-retired frame slot. The sky and HUD each add one draw. The headless benchmark measures CPU stepping, instance packing, and allocation without creating a graphics device. + +Qualification checks same-runtime replay, independent orders, contested capture, recapture, the complete reinforcement objective, and orbital positions. The Windows gate verifies both ship colors, reads back a complete tactical frame, and presents through two resizes. The `interop-windows-2025` CI artifact contains `fleet-system.ppm`. -The ships use the original [patrol asset](../StaticModelViewer/Models/Patrol.gltf) under the repository's [MIT license](../../LICENSE.md). +The ships use the original [patrol asset](../StaticModelViewer/Models/Patrol.gltf) under the repository's [MIT license](../../LICENSE.md). See the [fleet roadmap](../../doc/FleetBattler.md) for combat, authored star systems, and shared GPU effects. diff --git a/samples/FleetBattler/SpaceDraw.cs b/samples/FleetBattler/SpaceDraw.cs new file mode 100644 index 0000000..6aaac06 --- /dev/null +++ b/samples/FleetBattler/SpaceDraw.cs @@ -0,0 +1,215 @@ +using System.Numerics; +using System.Runtime.InteropServices; +using DXSharp.Graphics; +using DXSharp.Shaders; + +namespace FleetBattler; + +internal static class SpaceDraw { + internal const uint Constants = 60; + internal const float RockyAxis = 0.45f, GiantAxis = 0.91f, MoonAxis = 0.145f; + internal const float RockyEccentricity = 0.16f, GiantEccentricity = 0.12f, MoonEccentricity = 0.08f; + internal static readonly Vector4 Cyan = new( 0.20f, 0.83f, 1.0f, 1 ); + internal static readonly Vector4 Amber = new( 1.0f, 0.58f, 0.24f, 1 ); + internal static readonly Vector4 Neutral = new( 0.81f, 0.88f, 0.66f, 1 ); + + private const string Shader = """ + cbuffer Scene : register(b0) { + row_major float4x4 InverseViewProjection; + float4 Viewport; + float4 Star; + float4 Rocky; + float4 Giant; + float4 Moon; + float4 Orbits; + float4 MoonOrbit; + float4 Site; + float4 SiteTint; + float4 Selected; + float4 Order; + }; + + float4 VS(uint id : SV_VertexID) : SV_Position { + return float4(float2((id << 1) & 2, id & 2) * float2(2,-2) + float2(-1,1), 0.9999, 1); + } + + float Hash(float2 p) { + float3 q = frac(p.xyx * 0.1031); + q += dot(q, q.yzx + 33.33); + return frac((q.x + q.y) * q.z); + } + + float Noise(float2 p) { + float2 i = floor(p), f = frac(p); + f = f * f * (3 - 2*f); + return lerp(lerp(Hash(i), Hash(i + float2(1,0)), f.x), + lerp(Hash(i + float2(0,1)), Hash(i + 1), f.x), f.y); + } + + float3 Stars(float2 p, float cells, float threshold) { + float2 q = p * cells, id = floor(q); + float seed = Hash(id); + float2 center = 0.2 + 0.6 * float2(Hash(id+17.7), Hash(id+69.1)); + float radius = lerp(0.034, 0.12, seed); + float core = 1 - smoothstep(radius * 0.22, radius, length(frac(q) - center)); + return step(threshold, seed) * core * lerp(float3(0.41,0.58,0.93), float3(1,0.8,0.52), Hash(id+11.1)); + } + + float Line(float distance, float thickness) { + return 1 - smoothstep(thickness, thickness + Viewport.w * 1.4, abs(distance)); + } + + float Orbit(float2 worldPosition, float2 focus, float axis, float eccentricity) { + float2 delta = worldPosition - focus + float2(axis * eccentricity, 0); + delta.y *= rsqrt(1 - eccentricity * eccentricity); + return Line(length(delta) - axis, Viewport.w * 0.45); + } + + float3 Body(float3 sky, float2 pixel, float4 body, uint kind) { + float2 p = (pixel - body.xy) / body.z; + [branch] if (any(abs(p) > 2.5)) return sky; + float d = length(p); + if (kind == 0) { + float a = atan2(p.y, p.x); + float corona = exp(-max(d - 0.94, 0) * 6.5) * + (0.77 + 0.23 * sin(a * 23 + Noise(p*7)*4 + Viewport.z*0.35)); + sky += float3(1,0.35,0.065) * corona * 0.49; + float granules = Noise(p*21 + Viewport.z*0.08); + return lerp(sky, lerp(float3(0.98,0.38,0.08),float3(1,0.94,0.64),0.58 + granules*0.42), + 1 - smoothstep(0.95, 1.01, d)); + } + + float2 ringPlane = float2(p.x * 0.947 - p.y * 0.321, p.x * 0.321 + p.y * 0.947); + float ringDistance = length(ringPlane * float2(1, 3.4)); + float rings = smoothstep(1.19, 1.25, ringDistance) * (1 - smoothstep(1.93, 2.04, ringDistance)); + rings *= 0.38 + 0.57 * smoothstep(-0.3,0.7,sin(ringDistance*59.0)); + float3 ringTint = float3(0.76,0.66,0.48); + if (kind == 2 && ringPlane.y < 0) sky = lerp(sky, ringTint, rings*0.65); + + float3 n = float3(p.x, -p.y, sqrt(saturate(1 - d*d))); + float2 towardSun = Star.xy - body.xy; + float3 light = normalize(float3(towardSun.x, -towardSun.y, max(length(towardSun)*0.60, 1))); + float diffuse = 0.14 + 0.86 * saturate(dot(n, light)); + float3 albedo; + if (kind == 1) { + float land = Noise(n.xy*6.5 + n.z*2.7) * 0.72 + Noise(n.xy*16.0)*0.28; + albedo = lerp(float3(0.12,0.38,0.76), float3(0.30,0.62,0.38), smoothstep(0.49,0.60,land)); + float cloud = smoothstep(0.62,0.83,Noise(n.xy*float2(7,19) + n.z*3)); + albedo = lerp(albedo,float3(0.86,0.94,0.99),cloud*0.58); + sky += float3(0.16,0.42,0.83) * exp(-abs(d-1.0)*16.0) * 0.24; + } else if (kind == 2) { + float bands = 0.5 + 0.5*sin(n.y*27 + Noise(n.xy*5)*2.4 + n.x*0.8); + albedo = lerp(float3(0.58,0.34,0.28),float3(0.97,0.78,0.56),bands); + } else { + albedo = float3(0.69,0.73,0.79) * (0.47 + 0.48*Noise(p*11)); + } + sky = lerp(sky, albedo * diffuse, 1 - smoothstep(0.97,1.015,d)); + if (kind == 2 && ringPlane.y >= 0) sky = lerp(sky,ringTint,rings*0.65); + return sky; + } + + float4 PS(float4 position : SV_Position) : SV_Target { + float2 pixel = position.xy; + float2 p = (pixel - 0.5*Viewport.xy) / Viewport.y; + float2 dust = p * float2(3.2,5.8) + float2(1.2,-1.8); + float nebula = saturate(Noise(dust)*0.66 + Noise(dust*2.5)*0.34 - 0.30); + float band = exp(-abs(p.y - p.x*0.34 + 0.12)*4.1); + float3 sky = float3(0.018,0.026,0.055) + float3(0.12,0.092,0.22)*nebula*band + + float3(0.016,0.058,0.081)*saturate(1-length(p+float2(0.36,-0.23))); + sky += Stars(p, 68, 0.69)*0.39 + Stars(p+0.19, 29, 0.88)*0.74; + + float2 ndc = pixel / Viewport.xy * float2(2,-2) + float2(-1,1); + float3 nearPoint = mul(float4(ndc,0,1), InverseViewProjection).xyz; + float3 ray = mul(float4(0,0,1,0), InverseViewProjection).xyz; + float2 world = (nearPoint - ray*(nearPoint.y/ray.y)).xz; + float2 orbitWorld = world - ray.xz * (0.11*MoonOrbit.w/ray.y); + float tracks = Orbit(orbitWorld,Orbits.xy,Orbits.z,0.16) + Orbit(orbitWorld,Orbits.xy,Orbits.w,0.12) + + Orbit(orbitWorld,MoonOrbit.xy,MoonOrbit.z,0.08); + sky += float3(0.066,0.108,0.172) * saturate(tracks); + + sky = Body(sky,pixel,Star,0); + sky = Body(sky,pixel,Giant,2); + sky = Body(sky,pixel,Rocky,1); + sky = Body(sky,pixel,Moon,3); + + float2 marker = world - Site.xy; + float distanceToSite = length(marker); + float arc = frac(atan2(marker.x,-marker.y) / 6.2831853 + 1); + float ring = Line(distanceToSite-Site.z, Viewport.w*0.7); + float crossMark = Line(abs(marker.x)+abs(marker.y) - Viewport.w*7, Viewport.w*0.85); + float pulse = 0.65 + 0.35*sin(Viewport.z*3.4); + float segment = step(0.18, frac(arc*12)); + float progress = step(arc, Site.w) * step(0.001,Site.w); + sky = lerp(sky, SiteTint.rgb, saturate(ring*(segment*0.45 + progress*0.60) + crossMark*pulse)); + sky += SiteTint.rgb * (1 - saturate(distanceToSite/Site.z)) * 0.085; + + float2 home = abs(world - MoonOrbit.ww * float2(-0.59,-0.62)); + float homeLine = Line(max(home.x,home.y)-Viewport.w*8, Viewport.w*0.7); + sky = lerp(sky, float3(0.18,0.64,0.80), homeLine*0.55); + + float2 selectionDelta = world - Selected.xy; + float selectionRadius = max(Selected.z, Viewport.w*11); + float selectionRing = Line(length(selectionDelta)-selectionRadius, Viewport.w*0.65); + float bracket = step(0.7, max(abs(normalize(selectionDelta + 0.0001).x),abs(normalize(selectionDelta + 0.0001).y))); + sky = lerp(sky,float3(0.28,0.92,1),selectionRing*bracket*0.8); + float2 orderVector = Order.xy - Selected.xy; + float orderT = dot(selectionDelta,orderVector) / max(dot(orderVector,orderVector),0.0001); + float commandDash = step(0.35,frac(orderT*length(orderVector)/(Viewport.w*12))); + float route = Line(length(selectionDelta - orderVector*saturate(orderT)), Viewport.w*0.38) * + step(selectionRadius,length(selectionDelta))*step(0,orderT)*step(orderT,1)*commandDash; + float destination = Line(length(world-Order.xy)-Viewport.w*7, Viewport.w*0.8); + sky = lerp(sky,float3(0.30,0.87,0.96),saturate((route*0.5+destination*0.85)*Order.z)); + return float4(saturate(sky),1); + } + """; + + internal static PipelineState CreatePipeline( GraphicsDevice device, RootSignature root, ShaderCompiler compiler ) => + device.CreateGraphicsPipeline( root, compiler.Compile( Shader, "VS", "vs_6_0" ), + compiler.Compile( Shader, "PS", "ps_6_0" ), PixelFormat.Rgba8Unorm, depthEnabled: true ); + + internal static void Record( GraphicsCommandList commands, PipelineState pipeline, FleetSimulation fleet, int selected, + Matrix4x4 viewProjection, Matrix4x4 inverse, int width, int height, float halfHeight ) { + float r = fleet.BoardRadius; + double seconds = fleet.Tick * FleetSimulation.StepSeconds; + var sun = new Vector2( -0.31f, -0.33f ) * r; + var rocky = sun + OrbitPoint( RockyAxis * r, RockyEccentricity, 0.24 + seconds / 115 ); + var giant = sun + OrbitPoint( GiantAxis * r, GiantEccentricity, 0.98 + seconds / 310 ); + var moon = rocky + OrbitPoint( MoonAxis * r, MoonEccentricity, 0.21 + seconds / 39 ); + float worldPerPixel = halfHeight * 2 / height; + var center = fleet.Center( selected ); + var target = fleet.Target( selected ); + int side = fleet.Capturing >= 0 ? fleet.Capturing : fleet.Owner; + var tint = side switch { 0 => Cyan, 1 => Amber, _ => Neutral }; + float progress = fleet.CaptureTicks > 0 ? (float)fleet.CaptureTicks / FleetSimulation.CaptureDuration : fleet.Owner >= 0 ? 1 : 0; + Span values = stackalloc Vector4[15]; + MemoryMarshal.CreateReadOnlySpan( ref inverse, 1 ).CopyTo( MemoryMarshal.Cast( values[..4] ) ); + values[4] = new( width, height, (float)seconds, worldPerPixel ); + values[5] = Project( sun, 0.117f * r ); + values[6] = Project( rocky, 0.064f * r ); + values[7] = Project( giant, 0.103f * r ); + values[8] = Project( moon, 0.026f * r ); + values[9] = new( sun.X, sun.Y, RockyAxis * r, GiantAxis * r ); + values[10] = new( rocky.X, rocky.Y, MoonAxis * r, r ); + values[11] = new( fleet.Site.X, fleet.Site.Y, fleet.SiteRadius, progress ); + values[12] = tint; + values[13] = new( center.X, center.Y, 3.5f + MathF.Sqrt( fleet.ShipCount( selected ) ) * 2.3f, 0 ); + values[14] = new( target.X, target.Y, Vector2.DistanceSquared( center, target ) > 1 ? 1 : 0, 0 ); + commands.SetGraphicsPipeline( pipeline ); + commands.SetGraphicsConstants( MemoryMarshal.Cast( values ) ); + commands.Draw( 3 ); + + Vector4 Project( Vector2 point, float radius ) { + var clip = Vector4.Transform( new Vector4( point.X, -r * 0.11f, point.Y, 1 ), viewProjection ); + return new( (clip.X / clip.W + 1) * width * 0.5f, (1 - clip.Y / clip.W) * height * 0.5f, radius / worldPerPixel, 0 ); + } + } + + internal static Vector2 OrbitPoint( float axis, float eccentricity, double phase ) { + double mean = (phase - Math.Floor( phase )) * Math.Tau; + double anomaly = mean; + for ( int i = 0; i < 5; ++i ) + anomaly -= (anomaly - eccentricity * Math.Sin( anomaly ) - mean) / (1 - eccentricity * Math.Cos( anomaly )); + return new( (float)(axis * (Math.Cos( anomaly ) - eccentricity)), + (float)(axis * Math.Sqrt( 1 - eccentricity * eccentricity ) * Math.Sin( anomaly )) ); + } +} diff --git a/samples/README.md b/samples/README.md index b93f176..1609d49 100644 --- a/samples/README.md +++ b/samples/README.md @@ -9,7 +9,7 @@ Open `DXSharp.sln` or run a project with `dotnet run --project samples/ -c | [InstancedGrid](InstancedGrid) | 256 animated quads in one instanced draw | | [LitCube](LitCube) | Indexed mesh upload, vertex input layouts, lighting and D32 depth | | [StaticModelViewer](StaticModelViewer) | glTF and GLB import, shared geometry, node transforms, and directional lighting | -| [FleetBattler](FleetBattler) | Selectable formations, fixed-tick steering, and indexed instancing with frame-local uploads | +| [FleetBattler](FleetBattler) | Squadron orders, orbital scenery, contested mining, and reinforcement wings | | [PlanarShadows](PlanarShadows) | Orbiting camera, multiple pipelines and projected shadows | | [ModernCompute](ModernCompute) | DXC compute readback, DirectML Add, and matrix inference with fused ReLU | | [NBodyGravity](NBodyGravity) | Ping-pong GPU simulation, instanced drawing, and a seeded CPU reference | diff --git a/tests/InteropQualification/FleetQualification.cs b/tests/InteropQualification/FleetQualification.cs index 15c1cf3..a0f2d28 100644 --- a/tests/InteropQualification/FleetQualification.cs +++ b/tests/InteropQualification/FleetQualification.cs @@ -7,35 +7,40 @@ namespace InteropQualification; internal static class FleetQualification { internal static void Run( ) { var first = Replay( 37, 0 ); - var second = Replay( 37, 0 ); - Require( first == second, "the same seed and orders reproduce all checkpoints" ); + Require( first == Replay( 37, 0 ), "the same seed and orders reproduce all checkpoints" ); Require( first != Replay( 38, 0 ), "a different seed changes the state" ); var changed = Replay( 37, 1 ); Require( first.BeforeOrder == changed.BeforeOrder && first.AfterOrder != changed.AfterOrder, "a changed order first diverges after its tick" ); + VerifyFormations( ); + VerifyEconomy( ); + VerifyOrbits( ); + Console.WriteLine( $"PASS: fleet replay, independent squads, capture and reinforcement, orbit math, and zero-allocation updates ({first.AfterOrder:X16})." ); + } + + private static void VerifyFormations( ) { var fleet = new FleetSimulation( 129, 37 ); var previous = fleet.Positions.ToArray( ); var instances = new ShipInstance[fleet.Count]; - int split = (fleet.Count + 1) / 2; - Require( Marshal.SizeOf( ) == FleetDraw.InstanceStride, "instance stream ABI" ); - Require( fleet.FindFleet( previous[0] ) == 0 && fleet.FindFleet( previous[^1] ) == 1, "fleet selection" ); + int movedCount = fleet.ShipCount( 0 ); + Require( fleet.SquadCount == 12 && Marshal.SizeOf( ) == FleetDraw.InstanceStride, "squad count and instance ABI" ); + Require( fleet.FindSquad( fleet.Center( 0 ) ) == 0 && fleet.FindSquad( fleet.Center( 3 ) ) == 3, "independent cyan selection" ); fleet.Move( 0, new( 8, -20 ) ); - for ( int i = 0; i < 360; ++i ) fleet.Step( ); + for ( int i = 0; i < 420; ++i ) fleet.Step( ); fleet.FillInstances( instances, 0 ); var moved = fleet.Positions[0] - previous[0]; - Require( moved.X > 20 && moved.Y < -15, "move order reaches the other side of the board" ); + Require( moved.X > 35, "move order advances only the selected squad" ); for ( int i = 0; i < fleet.Count; ++i ) { var instance = instances[i]; Require( instance.Center == fleet.Positions[i] && MathF.Abs( instance.Heading.LengthSquared( ) - 1 ) < 1e-5f, "instance data preserves position and a normalized heading" ); - if ( i < split ) { + if ( i < movedCount ) { Require( Vector2.DistanceSquared( fleet.Positions[i] - previous[i], moved ) < 1e-5f, - "the ordered fleet preserves formation spacing" ); - Require( instance.Tint.Z > instance.Tint.X && instance.Tint.W > 1, "selected fleet tint" ); + "the ordered squad preserves formation spacing" ); + Require( instance.Tint.Z > instance.Tint.X && instance.Tint.W > 1.4f, "selected squad tint" ); } else { - Require( fleet.Positions[i] == previous[i] && instance.Tint.X > instance.Tint.Z && instance.Tint.W < 1, - "the other fleet stays in place with its own tint" ); + Require( fleet.Positions[i] == previous[i] && instance.Tint.W < 1.4f, "other squads stay in place" ); } } @@ -45,7 +50,53 @@ internal static void Run( ) { fleet.FillInstances( instances, 1 ); } Require( GC.GetAllocatedBytesForCurrentThread( ) == start, "steady-state stepping and packing allocate zero bytes" ); - Console.WriteLine( $"PASS: fleet replay, orders, formation spacing, instance ABI, and zero-allocation updates ({first.AfterOrder:X16})." ); + } + + private static void VerifyEconomy( ) { + var fleet = new FleetSimulation( 12, 37 ); + Require( fleet.BuildWing( ) < 0 && fleet.Count == 12 && fleet.Owner == -1, "neutral start and insufficient ore" ); + fleet.Move( 0, fleet.Site ); + AdvanceUntil( fleet, () => fleet.Capturing == 0, "cyan enters the beacon" ); + Require( fleet.CaptureTicks == 1 && fleet.Owner == -1, "capture requires sustained presence" ); + AdvanceUntil( fleet, () => fleet.Owner == 0, "cyan captures the beacon" ); + AdvanceUntil( fleet, () => fleet.Ore >= FleetSimulation.WingCost, "owned beacon generates ore" ); + int before = fleet.Ore; + int firstWing = fleet.BuildWing( ); + Require( firstWing == 12 && fleet.Count == 18 && fleet.ShipCount( firstWing ) == FleetSimulation.WingSize && + fleet.Center( firstWing ) == fleet.Shipyard && fleet.Ore == before - FleetSimulation.WingCost, "wing purchase and shipyard spawn" ); + + fleet.Move( 6, fleet.Site ); + AdvanceUntil( fleet, () => fleet.Contested, "amber contests the beacon" ); + int bank = fleet.Ore; + for ( int i = 0; i < 120; ++i ) fleet.Step( ); + Require( fleet.Contested && fleet.Ore == bank && fleet.Owner == 0 && fleet.Capturing == -1, "equal presence stalls control and income" ); + fleet.Move( 0, fleet.Shipyard ); + AdvanceUntil( fleet, () => fleet.Owner == 1, "amber captures the abandoned beacon" ); + fleet.Move( 0, fleet.Site ); + fleet.Move( firstWing, fleet.Site ); + AdvanceUntil( fleet, () => fleet.Owner == 0, "cyan retakes the beacon with the new squad" ); + AdvanceUntil( fleet, () => fleet.Ore >= FleetSimulation.WingCost, "income resumes after recapture" ); + Require( fleet.BuildWing( ) == 13 && fleet.Count == fleet.Capacity && fleet.WingsBuilt == FleetSimulation.WingGoal && + fleet.BuildWing( ) < 0, "two-wing objective and spawn capacity" ); + + var rival = new FleetSimulation( 2, 37, rivalPatrol: true ); + AdvanceUntil( rival, () => rival.Owner == 1, "rival patrol claims an undefended site", 1200 ); + } + + private static void AdvanceUntil( FleetSimulation fleet, Func condition, string name, int limit = 900 ) { + for ( int i = 0; i < limit && !condition( ); ++i ) fleet.Step( ); + Require( condition( ), name ); + } + + private static void VerifyOrbits( ) { + const float axis = 40, e = SpaceDraw.RockyEccentricity; + var near = SpaceDraw.OrbitPoint( axis, e, 0 ); + var far = SpaceDraw.OrbitPoint( axis, e, 0.5 ); + Require( Vector2.Distance( near, new( axis * (1 - e), 0 ) ) < 0.00001f && + Vector2.Distance( far, new( -axis * (1 + e), 0 ) ) < 0.00001f, "ellipse apsides" ); + var point = SpaceDraw.OrbitPoint( axis, e, 0.25 ); + Require( Vector2.Distance( point, SpaceDraw.OrbitPoint( axis, e, -1.75 ) ) < 0.00001f && point.Y > 0, + "normalized orbital phase wraps across negative and positive cycles" ); } private static (ulong BeforeOrder, ulong AfterOrder) Replay( uint seed, float orderDelta ) { diff --git a/tests/InteropQualification/InteropQualification.csproj b/tests/InteropQualification/InteropQualification.csproj index 7c81e37..04e4674 100644 --- a/tests/InteropQualification/InteropQualification.csproj +++ b/tests/InteropQualification/InteropQualification.csproj @@ -12,6 +12,8 @@ + + diff --git a/tests/InteropQualification/MeshQualification.cs b/tests/InteropQualification/MeshQualification.cs index 6749c41..98a0f47 100644 --- a/tests/InteropQualification/MeshQualification.cs +++ b/tests/InteropQualification/MeshQualification.cs @@ -47,6 +47,7 @@ internal static void Run( ) { Render( device, vertex, pixel, instanceStepRate: 1, splitIndexFormats: false ); Render( device, vertex, pixel, instanceStepRate: 2, splitIndexFormats: false ); RenderFleet( device, compiler ); + RenderSystem( device, compiler ); var diagnostics = device.GetDiagnostics( ); if ( diagnostics.DeviceRemovedReason < 0 || diagnostics.Messages.Any( message => message.Contains( "SEVERITY_ERROR" ) || message.Contains( "SEVERITY_CORRUPTION" ) ) ) @@ -178,10 +179,85 @@ private static void RenderFleet( GraphicsDevice device, ShaderCompiler compiler } } - private static GpuResource CreateTarget( GraphicsDevice device ) { + private static void RenderSystem( GraphicsDevice device, ShaderCompiler compiler ) { + const uint width = 640, height = 400; + var model = GltfModel.Load( Path.Combine( AppContext.BaseDirectory, "Models", "Patrol.gltf" ) ); + var fleet = new FleetSimulation( FleetSimulation.DefaultShips, 37 ); + using var queue = device.CreateCommandQueue( ); + using var allocator = device.CreateCommandAllocator( ); + using var commands = device.CreateCommandList( allocator ); + var meshes = new Mesh[model.Primitives.Length]; + try { + FleetDraw.RecordUploads( device, commands, model, meshes ); + using var fleetRoot = device.CreateGraphicsConstantsRootSignature( 16 ); + using var spaceRoot = device.CreateGraphicsConstantsRootSignature( SpaceDraw.Constants ); + using var hudRoot = device.CreateGraphicsConstantsRootSignature( 4 ); + using var fleetPipeline = FleetDraw.CreatePipeline( device, fleetRoot, compiler, depthEnabled: true ); + using var skyPipeline = SpaceDraw.CreatePipeline( device, spaceRoot, compiler ); + using var hudPipeline = FleetHud.CreatePipeline( device, hudRoot, compiler ); + using var glyphs = device.CreateBuffer( FleetHud.BufferBytes, BufferMemory.Upload ); + using var instances = device.CreateBuffer( (uint)fleet.Count * FleetDraw.InstanceStride, BufferMemory.Upload ); + var ships = new ShipInstance[fleet.Count]; + fleet.FillInstances( ships, 0 ); + instances.Write( ships ); + using var target = CreateTarget( device, width, height ); + using var heap = device.CreateRenderTargetHeap( 1 ); + var view = device.CreateRenderTargetView( target, heap, 0 ); + using var depth = device.CreateDepthTarget( width, height ); + var description = target.Native.Interface.GetDesc( ); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint; + ulong readbackBytes; + device.Native.Interface.GetCopyableFootprints( &description, 0, 1, 0, &footprint, null, null, &readbackBytes ); + using var readback = device.CreateBuffer( readbackBytes, BufferMemory.Readback ); + commands.SetViewport( width, height ); + commands.Clear( view, 0, 0, 0 ); + commands.SetRenderTarget( view, depth, clearDepth: true ); + float radius = fleet.BoardRadius, halfHeight = radius * 0.94f; + var camera = Matrix4x4.CreateLookAt( new( 0, radius * 1.6f, radius * 0.88f ), Vector3.Zero, Vector3.UnitY ); + var projection = Matrix4x4.CreateOrthographic( 2 * halfHeight * width / height, 2 * halfHeight, 0.1f, 4 * radius ); + var matrix = camera * projection; + Matrix4x4.Invert( matrix, out var inverse ); + SpaceDraw.Record( commands, skyPipeline, fleet, 0, matrix, inverse, (int)width, (int)height, halfHeight ); + FleetDraw.Record( commands, fleetPipeline, meshes, instances, (uint)ships.Length, matrix ); + new FleetHud( ).Record( commands, hudPipeline, glyphs, fleet, 0, (int)width, (int)height, false ); + commands.Transition( target, ResourceState.RenderTarget, ResourceState.CopySource ); + CopyPixels( commands, target, readback, footprint ); + commands.Close( ); + queue.Wait( queue.Submit( commands ) ); + var bytes = new byte[checked((int)readbackBytes)]; + readback.Read( bytes ); + var rgb = new byte[width * height * 3]; + int sun = 0, title = 0, sky = 0; + for ( uint y = 0; y < height; ++y ) { + for ( uint x = 0; x < width; ++x ) { + int source = checked((int)(footprint.Offset + y * footprint.Footprint.RowPitch + x * 4)); + int destination = checked((int)((y * width + x) * 3)); + bytes.AsSpan( source, 3 ).CopyTo( rgb.AsSpan( destination, 3 ) ); + byte r = bytes[source], g = bytes[source + 1], b = bytes[source + 2]; + if ( x > 160 && x < width - 165 && y > 80 && y < height - 65 && r > 220 && g > 130 && b < r - 40 ) ++sun; + if ( x is >= 23 and < 152 && y is >= 23 and < 36 && r > 225 && g > 235 && b > 245 ) ++title; + if ( y > 100 && y < 320 && b > r + 5 && r is > 0 and < 50 ) ++sky; + } + } + if ( sun < 500 || title < 100 || sky < 10_000 ) + throw new InvalidOperationException( $"Missing fleet scene pixels: {sun} stellar, {title} HUD, {sky} sky." ); + if ( Environment.GetEnvironmentVariable( "DXSHARP_FLEET_EVIDENCE" ) is { Length: > 0 } evidence ) { + string path = Path.GetFullPath( evidence ); + Directory.CreateDirectory( Path.GetDirectoryName( path )! ); + using var file = File.Create( path ); + file.Write( "P6\n640 400\n255\n"u8 ); + file.Write( rgb ); + } + Console.WriteLine( $"PASS: rendered fleet system and HUD ({sun} stellar, {title} title, {sky} sky pixels)." ); + } finally { + foreach ( var mesh in meshes ) mesh?.Dispose( ); + } + } + + private static GpuResource CreateTarget( GraphicsDevice device, uint width = Width, uint height = Height ) { D3D12_RESOURCE_DESC description = new( ) { Dimension = D3D12_RESOURCE_DIMENSION.D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width = Width, Height = Height, DepthOrArraySize = 1, MipLevels = 1, + Width = width, Height = height, DepthOrArraySize = 1, MipLevels = 1, Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc = new( ) { Count = 1 }, Flags = D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET };