Add GPU-resident fractal splat receipt

This commit is contained in:
Meta Vens 2026-05-19 21:10:37 +01:00
commit 1d57a62535
15 changed files with 594 additions and 1 deletions

View file

@ -43,6 +43,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.LocalCast", "src\A
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.LocalCast.Tests", "tests\Aquarium.LocalCast.Tests\Aquarium.LocalCast.Tests.csproj", "{E6560D72-B018-4E00-AEBD-C1B9419E0BC7}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{07C2787E-EAC7-C090-1BA3-A61EC2A24D84}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Fractal.Receipt", "tools\Aquarium.Fractal.Receipt\Aquarium.Fractal.Receipt.csproj", "{C0D1BFAC-B1B4-4350-92A7-D537AE382909}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -269,6 +273,18 @@ Global
{E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Release|x64.Build.0 = Release|Any CPU
{E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Release|x86.ActiveCfg = Release|Any CPU
{E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Release|x86.Build.0 = Release|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|x64.ActiveCfg = Debug|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|x64.Build.0 = Debug|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|x86.ActiveCfg = Debug|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|x86.Build.0 = Debug|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|Any CPU.Build.0 = Release|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|x64.ActiveCfg = Release|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|x64.Build.0 = Release|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|x86.ActiveCfg = Release|Any CPU
{C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -285,5 +301,6 @@ Global
{A9D41C48-7E78-4D75-A814-0C1500245EFC} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{E6560D72-B018-4E00-AEBD-C1B9419E0BC7} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{C0D1BFAC-B1B4-4350-92A7-D537AE382909} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
EndGlobalSection
EndGlobal

View file

@ -558,6 +558,14 @@ evidence.
Move hot reservoirs to GPU buffers, add spatial reuse across screen tiles and
domain neighbors, and keep CPU/GPU parity fixtures.
Current state: `tools/Aquarium.Fractal.Receipt` is the first GPU-resident
receipt harness. It allocates a packed D3D12 `RWStructuredBuffer` of fractal SDF
splats, populates the whole buffer with a compute shader, measures GPU timestamp
queries, and reads back only a tiny checksum sample. On the local GTX 1070, the
receipt ran `2,000,000` splats for `120` measured frames at `3.362 ms/frame`,
`297.5 FPS` equivalent, and about `594.9M` splats/sec. This proves compute-side
population throughput, not final shaded visibility.
### Phase J: Learned Priority Gate
Only after telemetry exists, train or calibrate a predictor for update/residency

View file

@ -529,6 +529,40 @@ Cut line:
- If it does not beat the estimator clearly, delete it. No ornamental oracle.
## Phase 11: GPU-Resident Splat Receipt
Goal: prove hot fractal splat population belongs on the GPU, not in managed
object graphs.
Tasks:
- [x] Add packed GPU splat buffer contract with no per-splat strings or object
ownership.
- [x] Add native packed CPU buffer helper for the rare staging/readback paths
that genuinely need C# memory.
- [x] Add D3D12 compute receipt harness that writes millions of splats directly
into a GPU-resident UAV.
- [x] Measure with GPU timestamp queries and read back only a tiny checksum
sample.
Receipt:
- GTX 1070, `2,000,000` splats, `120` measured frames, `80` bytes/splat.
- GPU time: `3.362 ms/frame`.
- Equivalent throughput: `297.5 FPS`, about `594.9M` splats/sec.
- Command: `.\scripts\fractal-splat-receipt.ps1 -Splats 2000000 -Frames 120`.
Exit gate:
- Receipt must show plural-millions of GPU-resident splats populated at hundreds
of FPS equivalent on the target tired GTX 1070.
Cut line:
- This is compute-side population throughput, not final shaded visibility. Do
not sell it as renderer completion until the draw/raster/resolve path consumes
the same packed buffer.
## First Work Packet
Start here:

View file

@ -0,0 +1,16 @@
param(
[int]$Splats = 2000000,
[int]$Warmup = 30,
[int]$Frames = 120,
[int]$Depth = 8,
[int]$ReadbackSplats = 64
)
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
dotnet run --project (Join-Path $repoRoot "tools\Aquarium.Fractal.Receipt\Aquarium.Fractal.Receipt.csproj") -c Release -- `
--splats $Splats `
--warmup $Warmup `
--frames $Frames `
--depth $Depth `
--readback-splats $ReadbackSplats

View file

@ -1,4 +1,5 @@
using System.Numerics;
using System.Runtime.InteropServices;
namespace Aquarium.Engine.Fractal;
@ -160,6 +161,14 @@ public readonly record struct AquariumFractalSdfSplat3D(
float MaterialValue,
float Confidence);
[StructLayout(LayoutKind.Sequential)]
public readonly record struct AquariumPackedFractalSdfSplat3D(
Vector4 CenterRadius,
Vector4 Orientation,
Vector4 RadiiFalloff,
Vector4 MaterialConfidence,
Vector4 Key);
public readonly record struct AquariumBrushClaim(
AquariumFractalKey Key,
AquariumFractalKey DomainKey,

View file

@ -8,6 +8,7 @@
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,95 @@
using System.Runtime.InteropServices;
namespace Aquarium.Engine.Fractal.Lod;
public sealed unsafe class FractalNativeBuffer<T> : IDisposable
where T : unmanaged
{
private readonly nuint byteCount;
private bool disposed;
public FractalNativeBuffer(int length, nuint alignment = 64)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "Native buffer length must not be negative.");
}
if (alignment == 0 || (alignment & (alignment - 1)) != 0)
{
throw new ArgumentOutOfRangeException(nameof(alignment), alignment, "Native buffer alignment must be a power of two.");
}
Length = length;
byteCount = checked((nuint)length * (nuint)sizeof(T));
Pointer = byteCount == 0
? null
: (T*)NativeMemory.AlignedAlloc(byteCount, alignment);
if (Pointer is null && byteCount > 0)
{
throw new OutOfMemoryException($"Could not allocate {byteCount} bytes for native buffer.");
}
if (Pointer is not null)
{
NativeMemory.Clear(Pointer, byteCount);
}
}
public int Length { get; }
public T* Pointer { get; private set; }
public Span<T> Span
{
get
{
ThrowIfDisposed();
return new Span<T>(Pointer, Length);
}
}
public ref T this[int index]
{
get
{
ThrowIfDisposed();
if ((uint)index >= (uint)Length)
{
throw new ArgumentOutOfRangeException(nameof(index), index, "Native buffer index is outside the allocated range.");
}
return ref Pointer[index];
}
}
public void Dispose()
{
if (disposed)
{
return;
}
disposed = true;
if (Pointer is not null)
{
NativeMemory.AlignedFree(Pointer);
Pointer = null;
}
GC.SuppressFinalize(this);
}
~FractalNativeBuffer()
{
Dispose();
}
private void ThrowIfDisposed()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(FractalNativeBuffer<T>));
}
}
}

View file

@ -175,3 +175,4 @@
{"timestamp":"2026-05-19T23:35:00+01:00","topic":"fractal-surface-page-rasterizer","lesson":"Resident surface pages now produce CPU payloads instead of only metadata. `FractalSurfacePageRasterizer` lowers ownership-tree claims into height, 2D signed-distance support, material, and confidence sample arrays using `FractalBrushEnvelope2D`; Zyphos caches resident page payloads by stable page key. This gives Phase E a renderer-agnostic payload producer before D3D12 atlas/upload work begins.","files":["src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePayload.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageRasterizer.cs","tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageRasterizerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase E CPU page payload slice"}
{"timestamp":"2026-05-19T23:55:00+01:00","topic":"fractal-3d-sdf-splat-contract","lesson":"Phase F has its first stable packet shape. `AquariumFractalSdfSplat3DKey` and `AquariumFractalSdfSplat3D` define domain/node/payload-keyed compact 3D SDF splats; `FractalSdfSplat3DCompiler` lowers structural `FractalProbeSample` evidence into splats, and `FractalSdfSplat3DKernel` owns CPU compact-weight/signed-distance parity math. Zyphos exposes a structural splat from its probe reservoir before renderer lowering.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DCompiler.cs","src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DKernel.cs","src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeReservoir.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DCompilerTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeReservoirTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase F compact 3D SDF splat groundwork"}
{"timestamp":"2026-05-19T23:59:00+01:00","topic":"fractal-projected-sdf-splat-compiler","lesson":"Phase G now has a pure 2D-projected-to-3D lowering seam. `FractalProjectedSdfSplatCompiler` takes resident SignedDistance2D page payload samples, an explicit page-to-world mapper, a surface normal, support radii, and a splat budget, then emits compact `AquariumFractalSdfSplat3D` packets ordered by near-surface distance. Zyphos caches a bounded first set of projected surface splats using a flat local mapping until cube-sphere and torus mappings are implemented.","files":["src/Aquarium.Engine.Fractal/Lod/FractalProjectedSdfSplatCompiler.cs","tests/Aquarium.Engine.Fractal.Tests/FractalProjectedSdfSplatCompilerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase G projected SDF splat groundwork"}
{"timestamp":"2026-05-19T21:03:19+00:00","topic":"gpu-resident-fractal-splat-receipt","lesson":"The first honest performance receipt is GPU-resident compute, not CPU object population. `tools/Aquarium.Fractal.Receipt` allocates an 80-byte packed `AquariumPackedFractalSdfSplat3D` UAV, populates it entirely in a D3D12 compute shader, measures GPU timestamp queries, and reads back only 64 splats for checksum. On the local NVIDIA GTX 1070, `2,000,000` splats over `120` measured frames ran at `3.362 ms/frame`, `297.5 FPS` equivalent, and about `594.9M` splats/sec. This proves compute-side population throughput; final shaded rendering still has to consume the packed buffer.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Lod/FractalNativeBuffer.cs","tests/Aquarium.Engine.Fractal.Tests/FractalNativeBufferTests.cs","tools/Aquarium.Fractal.Receipt/Aquarium.Fractal.Receipt.csproj","tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-splat-receipt.ps1","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"user demanded a receipt showing millions of splats at hundreds of FPS and rejected CPU-resident architecture"}

View file

@ -136,6 +136,7 @@ renderer_state:
- Fractal resource planning is explicit: one plan coordinates CPU contribution updates, GPU selected-cut estimated cost, RAM resident payload budget, and SSD request pressure before backend packet compilation. This same budget language should generalize to Mimir-style sensor fusion because both fractal SDF probes and camera/microphone feature detections accumulate confidence-weighted spatial samples into temporal reservoirs.
- Fractal residency uses score-per-cost retention under RAM pressure and emits evicted node keys as planner output; real storage mutation waits for a page/payload store boundary.
- Compact 3D SDF splats now have a stable fractal contract and CPU compiler/kernel: structural FractalProbeSample evidence can lower into AquariumFractalSdfSplat3D packets with compact shaped support before GPU rendering exists.
- Hot fractal splats must be GPU-resident packed buffers. AquariumPackedFractalSdfSplat3D is the 80-byte numeric packet; tools/Aquarium.Fractal.Receipt proves a D3D12 compute shader can populate 2,000,000 such splats on the GTX 1070 at 3.362 ms/frame, 297.5 FPS equivalent, with only tiny checksum readback.
- 2D-projected-to-3D splats have a pure compiler seam: FractalProjectedSdfSplatCompiler maps resident SignedDistance2D page payload samples through an explicit page-to-world function and normal into bounded AquariumFractalSdfSplat3D packets.
- The consolidated fractal brush architecture plan defines the intended pipeline: client intent -> domain roots -> semantic IFS brush grammar -> ownership tree -> node summaries -> contribution cache/residency scheduler -> backend packets -> renderer passes -> debug/evidence, with explicit module boundaries and mockable unit-test seams.
- The Perfect Machine architecture lives in docs/perfect-machine-architecture.md. It is the current waterfall design authority for fast 2D SDF splats, 3D SDF splats, 2D-projected-to-3D surface splats, IFS `.aquageo` structural probes, Mimir-style camera/audio evidence candidates, ReSTIR/GRIS reservoir reuse, heuristic occupancy graph updates, resource-tier residency, and TAA guide-buffer integration.

View file

@ -98,6 +98,8 @@
"FractalStructuralProbeGenerator lowers AquariumFractalSummary rows into FractalProbeSample reservoir candidates with local support, projected target contribution, clamped source PDF, material delta, and payload handle. This is the structural IFS probe producer; renderer-facing temporal validation still needs camera/disocclusion/material/visibility inputs.",
"FractalStructuralProbeReservoir builds a reservoir snapshot from an ownership tree, selected cut, summaries, and projected pixels per world unit. ZyphosFractalRenderPlan now carries this structural probe reservoir, so the planet path exposes reservoir-shaped structural evidence beside brushes/resource plans before GPU reuse exists.",
"AquariumFractalSdfSplat3D is the compact 3D SDF splat packet contract for Phase F. FractalSdfSplat3DCompiler lowers FractalProbeSample evidence into stable domain/node/payload-keyed splats, and FractalSdfSplat3DKernel owns CPU compact-weight/signed-distance parity math. Zyphos exposes a first structural splat from its probe reservoir before D3D12 lowering.",
"Hot fractal splat storage must be GPU-resident packed buffers manipulated by compute shaders. Stable string-keyed splat contracts are metadata/debug boundaries, not million-instance hot buffers. `AquariumPackedFractalSdfSplat3D` is the numeric 80-byte packet shape; C# staging/readback paths use unsafe `FractalNativeBuffer<T>` when CPU memory is genuinely needed.",
"The GPU splat receipt harness lives at tools/Aquarium.Fractal.Receipt and scripts/fractal-splat-receipt.ps1. On the local NVIDIA GTX 1070 it populated 2,000,000 GPU-resident packed fractal splats for 120 measured frames at 3.362 ms/frame, 297.5 FPS equivalent, about 594.9M splats/sec, with only a 64-splat checksum readback. This proves compute-side population throughput, not final shaded visibility.",
"FractalProjectedSdfSplatCompiler is the Phase G 2D-projected-to-3D lowering seam: it converts resident SignedDistance2D page payload samples into compact 3D SDF splats through an explicit page-local Vector2 -> Vector3 mapping, surface normal, support radius, and splat budget. Zyphos caches a bounded first set with a flat local mapping until cube-sphere/torus mappers are added.",
"Zyphos camera distance limits belong to the selected spatial domain, not one global planetary clamp. Leaf/pebble domains must be able to zoom below whole-body distances, and the parent star must be a visible SDF body when it is also the primary light source.",
"The consolidated fractal brush architecture lives in research/rendering/fractal-brush-architecture-plan.md. Its pipeline is client intent -> domain roots -> semantic IFS brush grammar -> ownership tree -> node summaries -> contribution cache/residency scheduler -> backend packets -> renderer passes -> debug/evidence. Its credibility depends on module boundaries and tests: contracts, pure CPU fractal core, D3D12 backend, client adapters, mock payload/probe/random/clock seams, shader parity tests, and deterministic performance fixtures.",

View file

@ -5,6 +5,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
@ -24,4 +25,4 @@
<ProjectReference Include="..\..\src\Aquarium.Zyphos\Aquarium.Zyphos.csproj" />
</ItemGroup>
</Project>
</Project>

View file

@ -0,0 +1,24 @@
using Aquarium.Engine.Fractal;
using Aquarium.Engine.Fractal.Lod;
namespace Aquarium.Engine.Fractal.Tests;
public sealed class FractalNativeBufferTests
{
[Fact]
public unsafe void NativeBufferExposesPointerAndSpanWithoutCopy()
{
using var buffer = new FractalNativeBuffer<AquariumPackedFractalSdfSplat3D>(4);
buffer.Pointer[2] = buffer.Pointer[2] with { CenterRadius = new System.Numerics.Vector4(1.0f, 2.0f, 3.0f, 4.0f) };
Assert.Equal(4, buffer.Length);
Assert.Equal(1.0f, buffer.Span[2].CenterRadius.X);
}
[Fact]
public void NativeBufferRejectsInvalidAlignment()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new FractalNativeBuffer<int>(4, alignment: 48));
}
}

View file

@ -1,4 +1,5 @@
using System.Numerics;
using System.Runtime.InteropServices;
using Aquarium.Engine.Fractal;
namespace Aquarium.Engine.Fractal.Tests;
@ -44,4 +45,10 @@ public sealed class FractalSdfSplat3DContractTests
Assert.Equal(new Vector3(4.0f, 5.0f, 6.0f), splat.Radii);
Assert.Equal(0.8f, splat.Confidence);
}
[Fact]
public void PackedSdfSplat3DIsFixedSizeGpuPacket()
{
Assert.Equal(80, Marshal.SizeOf<AquariumPackedFractalSdfSplat3D>());
}
}

View file

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Aquarium.Engine.Contracts\Aquarium.Engine.Contracts.csproj" />
<PackageReference Include="Vortice.Direct3D12" Version="3.8.3" />
<PackageReference Include="Vortice.D3DCompiler" Version="3.8.3" />
<PackageReference Include="Vortice.DXGI" Version="3.8.3" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,359 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.Json;
using Aquarium.Engine.Fractal;
using Vortice.D3DCompiler;
using Vortice.Direct3D;
using Vortice.Direct3D12;
using Vortice.DXGI;
var options = ReceiptOptions.Parse(args);
using var runner = new GpuFractalSplatReceiptRunner();
var receipt = runner.Run(options);
Directory.CreateDirectory(options.OutputDirectory);
var receiptPath = Path.Combine(
options.OutputDirectory,
$"fractal-gpu-splat-receipt-{DateTimeOffset.Now:yyyyMMdd-HHmmss}.json");
File.WriteAllText(receiptPath, JsonSerializer.Serialize(receipt, new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine("=== Aquarium Perfect Machine GPU Splat Receipt ===");
Console.WriteLine($"adapter: {receipt.Adapter}");
Console.WriteLine($"splats: {receipt.SplatCount:N0}");
Console.WriteLine($"frames: {receipt.MeasuredFrames}");
Console.WriteLine($"shader: D3D12 compute, GPU-resident RWStructuredBuffer");
Console.WriteLine($"packed bytes/splat: {receipt.BytesPerSplat}");
Console.WriteLine($"gpu ms/frame: {receipt.GpuMillisecondsPerFrame:0.000}");
Console.WriteLine($"gpu equivalent fps: {receipt.GpuEquivalentFps:0.0}");
Console.WriteLine($"gpu splats/sec: {receipt.GpuSplatsPerSecond:N0}");
Console.WriteLine($"cpu submit+wait ms/frame: {receipt.CpuSubmitAndWaitMillisecondsPerFrame:0.000}");
Console.WriteLine($"readback checksum: 0x{receipt.ReadbackChecksum:X16}");
Console.WriteLine($"receipt: {receiptPath}");
internal sealed class GpuFractalSplatReceiptRunner : IDisposable
{
private const int ThreadGroupSize = 256;
private readonly ID3D12Device device;
private readonly ID3D12CommandQueue queue;
private readonly ID3D12CommandAllocator allocator;
private readonly ID3D12GraphicsCommandList commandList;
private readonly ID3D12Fence fence;
private readonly AutoResetEvent fenceEvent = new(false);
private readonly ID3D12RootSignature rootSignature;
private readonly ID3D12PipelineState pipelineState;
private readonly string adapterName;
private ulong fenceValue;
public GpuFractalSplatReceiptRunner()
{
device = D3D12.D3D12CreateDevice<ID3D12Device>(IntPtr.Zero, FeatureLevel.Level_11_0);
adapterName = ResolveAdapterName();
queue = device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));
allocator = device.CreateCommandAllocator(CommandListType.Direct);
commandList = device.CreateCommandList<ID3D12GraphicsCommandList>(0, CommandListType.Direct, allocator, null);
commandList.Close();
fence = device.CreateFence(0);
rootSignature = CreateRootSignature(device);
pipelineState = CreatePipelineState(device, rootSignature);
}
public GpuFractalSplatReceipt Run(ReceiptOptions options)
{
var stride = Marshal.SizeOf<AquariumPackedFractalSdfSplat3D>();
var splatBytes = checked((ulong)stride * (ulong)options.SplatCount);
using var splats = device.CreateCommittedResource(
HeapType.Default,
ResourceDescription.Buffer(splatBytes, ResourceFlags.AllowUnorderedAccess),
ResourceStates.UnorderedAccess,
null);
splats.Name = "Aquarium Fractal Receipt GPU Splat Buffer";
var readbackBytes = (ulong)Math.Min(options.ReadbackSplats, options.SplatCount) * (ulong)stride;
using var readback = device.CreateCommittedResource(
HeapType.Readback,
ResourceDescription.Buffer(Math.Max(readbackBytes, 1)),
ResourceStates.CopyDest,
null);
readback.Name = "Aquarium Fractal Receipt Readback";
using var queryHeap = device.CreateQueryHeap<ID3D12QueryHeap>(new QueryHeapDescription(QueryHeapType.Timestamp, 2u));
using var queryReadback = device.CreateCommittedResource(
HeapType.Readback,
ResourceDescription.Buffer(16),
ResourceStates.CopyDest,
null);
queue.GetTimestampFrequency(out var timestampFrequency);
var measuredGpuTicks = 0UL;
var measuredCpuTicks = 0L;
var measuredFrames = 0;
for (var frame = 0; frame < options.WarmupFrames + options.MeasuredFrames; frame++)
{
allocator.Reset();
commandList.Reset(allocator, pipelineState);
commandList.SetComputeRootSignature(rootSignature);
commandList.SetPipelineState(pipelineState);
commandList.SetComputeRoot32BitConstant(0, (uint)options.SplatCount, 0);
commandList.SetComputeRoot32BitConstant(0, (uint)frame, 1);
commandList.SetComputeRoot32BitConstant(0, (uint)options.Depth, 2);
commandList.SetComputeRoot32BitConstant(0, options.Seed, 3);
commandList.SetComputeRootUnorderedAccessView(1, splats.GPUVirtualAddress);
commandList.EndQuery(queryHeap, QueryType.Timestamp, 0);
commandList.Dispatch((uint)((options.SplatCount + ThreadGroupSize - 1) / ThreadGroupSize), 1, 1);
commandList.EndQuery(queryHeap, QueryType.Timestamp, 1);
commandList.ResolveQueryData(queryHeap, QueryType.Timestamp, 0, 2, queryReadback, 0);
if (frame == options.WarmupFrames + options.MeasuredFrames - 1 && readbackBytes > 0)
{
commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(splats, ResourceStates.UnorderedAccess, ResourceStates.CopySource));
commandList.CopyBufferRegion(readback, 0, splats, 0, readbackBytes);
commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(splats, ResourceStates.CopySource, ResourceStates.UnorderedAccess));
}
commandList.Close();
var cpuStart = Stopwatch.GetTimestamp();
queue.ExecuteCommandList(commandList);
WaitForGpu();
var cpuEnd = Stopwatch.GetTimestamp();
if (frame >= options.WarmupFrames)
{
measuredFrames++;
measuredCpuTicks += cpuEnd - cpuStart;
unsafe
{
var timestamps = (ulong*)queryReadback.Map<byte>(0);
measuredGpuTicks += timestamps[1] - timestamps[0];
queryReadback.Unmap(0);
}
}
}
var checksum = readbackBytes == 0 ? 0UL : Checksum(readback, (int)readbackBytes);
var gpuSeconds = measuredGpuTicks / (double)timestampFrequency;
var cpuSeconds = measuredCpuTicks / (double)Stopwatch.Frequency;
var gpuMsPerFrame = gpuSeconds * 1000.0 / Math.Max(measuredFrames, 1);
var cpuMsPerFrame = cpuSeconds * 1000.0 / Math.Max(measuredFrames, 1);
var gpuSplatsPerSecond = (options.SplatCount * (double)measuredFrames) / Math.Max(gpuSeconds, 1.0e-12);
return new GpuFractalSplatReceipt(
adapterName,
options.SplatCount,
measuredFrames,
stride,
gpuMsPerFrame,
1000.0 / Math.Max(gpuMsPerFrame, 1.0e-12),
gpuSplatsPerSecond,
cpuMsPerFrame,
checksum);
}
public void Dispose()
{
WaitForGpu();
pipelineState.Dispose();
rootSignature.Dispose();
fence.Dispose();
commandList.Dispose();
allocator.Dispose();
queue.Dispose();
device.Dispose();
fenceEvent.Dispose();
}
private void WaitForGpu()
{
fenceValue++;
queue.Signal(fence, fenceValue);
if (fence.CompletedValue < fenceValue)
{
fence.SetEventOnCompletion(fenceValue, fenceEvent.SafeWaitHandle.DangerousGetHandle());
fenceEvent.WaitOne();
}
}
private string ResolveAdapterName()
{
using var factory = DXGI.CreateDXGIFactory1<IDXGIFactory6>();
for (var index = 0u; factory.EnumAdapterByGpuPreference(index, GpuPreference.HighPerformance, out IDXGIAdapter1? adapter).Success && adapter is not null; index++)
{
using (adapter)
{
var description = adapter.Description1;
if ((description.Flags & AdapterFlags.Software) == 0)
{
return description.Description;
}
}
}
return "default D3D12 adapter";
}
private static ID3D12RootSignature CreateRootSignature(ID3D12Device device)
{
var rootParameters = new[]
{
new RootParameter(new RootConstants(0, 0, 4), ShaderVisibility.All),
new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(0, 0), ShaderVisibility.All),
};
var description = new RootSignatureDescription(RootSignatureFlags.None, rootParameters, []);
return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1);
}
private static ID3D12PipelineState CreatePipelineState(ID3D12Device device, ID3D12RootSignature rootSignature)
{
var shader = Compiler.Compile(ShaderSource, "D3D12FractalSplatReceiptCS", "receipt.hlsl", "cs_5_0", ShaderFlags.OptimizationLevel3, EffectFlags.None);
return device.CreateComputePipelineState(new ComputePipelineStateDescription
{
RootSignature = rootSignature,
ComputeShader = shader,
});
}
private static unsafe ulong Checksum(ID3D12Resource readback, int byteCount)
{
var data = (byte*)readback.Map<byte>(0);
var hash = 1469598103934665603UL;
for (var index = 0; index < byteCount; index++)
{
hash ^= data[index];
hash *= 1099511628211UL;
}
readback.Unmap(0);
return hash;
}
private const string ShaderSource = """
struct PackedSplat
{
float4 centerRadius;
float4 orientation;
float4 radiiFalloff;
float4 materialConfidence;
float4 key;
};
cbuffer ReceiptConstants : register(b0)
{
uint SplatCount;
uint FrameIndex;
uint Depth;
uint Seed;
};
RWStructuredBuffer<PackedSplat> Splats : register(u0);
uint Hash(uint x)
{
x ^= x >> 16;
x *= 747796405u;
x ^= x >> 16;
x *= 2891336453u;
x ^= x >> 16;
return x;
}
[numthreads(256, 1, 1)]
void D3D12FractalSplatReceiptCS(uint3 dispatchThreadId : SV_DispatchThreadID)
{
uint index = dispatchThreadId.x;
if (index >= SplatCount)
{
return;
}
uint n = index ^ Seed;
float3 p = float3(0.0, 0.0, 0.0);
float scale = 1.0;
[loop]
for (uint depth = 0; depth < Depth; depth++)
{
uint branch = (n >> (depth * 2u)) & 3u;
float2 dir = branch == 0u ? float2(1.0, 0.0)
: branch == 1u ? float2(-0.42, 0.91)
: branch == 2u ? float2(-0.76, -0.65)
: float2(0.72, -0.69);
scale *= 0.535;
p.xy += dir * scale;
p.z += ((float)branch - 1.5) * scale * 0.19;
n = Hash(n + branch + FrameIndex + depth * 17u);
}
float radius = max(scale * 0.75, 0.0001);
uint h = Hash(index + FrameIndex * 1664525u + Seed);
PackedSplat splat;
splat.centerRadius = float4(p, radius);
splat.orientation = float4(0.0, 0.0, 0.0, 1.0);
splat.radiiFalloff = float4(radius, radius * 0.72, radius * 0.45, 4.0);
splat.materialConfidence = float4((float)(h & 1023u) / 1023.0, 1.0, 0.0, 1.0);
splat.key = float4((float)index, (float)FrameIndex, (float)Depth, asfloat(h));
Splats[index] = splat;
}
""";
}
internal sealed record ReceiptOptions(
int SplatCount,
int WarmupFrames,
int MeasuredFrames,
int Depth,
uint Seed,
int ReadbackSplats,
string OutputDirectory)
{
public static ReceiptOptions Parse(string[] args)
{
var options = new ReceiptOptions(
SplatCount: 2_000_000,
WarmupFrames: 30,
MeasuredFrames: 120,
Depth: 8,
Seed: 0xA17EA11u,
ReadbackSplats: 64,
OutputDirectory: Path.Combine("artifacts", "fractal-splat-receipts"));
for (var index = 0; index < args.Length; index++)
{
var arg = args[index];
string Next() => index + 1 < args.Length ? args[++index] : throw new ArgumentException($"Missing value for {arg}.");
options = arg switch
{
"--splats" => options with { SplatCount = int.Parse(Next()) },
"--warmup" => options with { WarmupFrames = int.Parse(Next()) },
"--frames" => options with { MeasuredFrames = int.Parse(Next()) },
"--depth" => options with { Depth = int.Parse(Next()) },
"--seed" => options with { Seed = Convert.ToUInt32(Next(), 0) },
"--readback-splats" => options with { ReadbackSplats = int.Parse(Next()) },
"--out" => options with { OutputDirectory = Next() },
_ => throw new ArgumentException($"Unknown receipt option: {arg}"),
};
}
if (options.SplatCount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(SplatCount), options.SplatCount, "Splat count must be positive.");
}
if (options.WarmupFrames < 0 || options.MeasuredFrames <= 0 || options.Depth <= 0 || options.ReadbackSplats < 0)
{
throw new ArgumentOutOfRangeException(nameof(args), "Warmup must be nonnegative; frames/depth must be positive; readback splats must be nonnegative.");
}
return options;
}
}
internal sealed record GpuFractalSplatReceipt(
string Adapter,
int SplatCount,
int MeasuredFrames,
int BytesPerSplat,
double GpuMillisecondsPerFrame,
double GpuEquivalentFps,
double GpuSplatsPerSecond,
double CpuSubmitAndWaitMillisecondsPerFrame,
ulong ReadbackChecksum);