Decorrelate D3D12 medium froxel samples

This commit is contained in:
Meta Vens 2026-05-10 17:19:07 +01:00
commit 46aa1e3922
6 changed files with 83 additions and 6 deletions

View file

@ -47,6 +47,8 @@ public sealed class D3D12Renderer : IAquariumRenderer
private const string MediumShaderRelativePath = "Render/Shaders/D3D12Medium.hlsl";
private const string SceneShaderRelativePath = "Render/Shaders/D3D12Scene.hlsl";
private const string PostShaderRelativePath = "Render/Shaders/D3D12Post.hlsl";
private const string DitherTextureRelativePath = "Assets/Textures/Aetheria-LDR_LLL1_0.r8";
private const int DitherTextureSize = 512;
private static readonly DebugUi.DebugUiOption[] RenderDebugOptions =
[
new(0, "Final"),
@ -129,6 +131,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
new(-0.4f, -3.9f, -1.35f),
];
private D3D12StructuredBuffer froxelPrimitiveBuffer;
private readonly D3D12StructuredBuffer ditherBuffer;
private readonly D3D12StructuredBuffer fieldInstanceBuffer;
private Int4[] froxelPrimitiveIds = [];
private readonly FieldInstanceGpu[] fieldInstances = new FieldInstanceGpu[FieldInstanceCount];
@ -235,12 +238,19 @@ public sealed class D3D12Renderer : IAquariumRenderer
CreateHistoryRenderTargets();
CreateBloomRenderTargets();
froxelPrimitiveBuffer = CreateViewFroxelPrimitiveBuffer();
ditherBuffer = CreateDitherBuffer(Path.Combine(AppContext.BaseDirectory, DitherTextureRelativePath));
fieldInstanceBuffer = new D3D12StructuredBuffer(device, FieldInstanceCount, Marshal.SizeOf<FieldInstanceGpu>(), "Aquarium D3D12 Field Instance Buffer");
resourceRegistry.Add("froxel-primitive-buffer", froxelPrimitiveBuffer);
resourceRegistry.Add("dither-buffer", ditherBuffer);
resourceRegistry.Add("field-instance-buffer", fieldInstanceBuffer);
commandList = device.CreateCommandList<ID3D12GraphicsCommandList>(0, CommandListType.Direct, frames[frameIndex].CommandAllocator, null);
commandList.Name = "Aquarium D3D12 Graphics Command List";
ditherBuffer.Upload(commandList, frames[frameIndex].UploadRing, LoadDitherPixels(Path.Combine(AppContext.BaseDirectory, DitherTextureRelativePath)));
commandList.Close();
fence = device.CreateFence(0);
fence.Name = "Aquarium D3D12 Frame Fence";
commandQueue.ExecuteCommandList(commandList);
WaitForGpu();
ReportStartupProgress(startupProgress, "Creating D3D12 render pipelines");
fullscreenRootSignature = CreateFullscreenRootSignature();
fullscreenRootSignature.Name = "Aquarium D3D12 Fullscreen Root Signature";
@ -248,8 +258,6 @@ public sealed class D3D12Renderer : IAquariumRenderer
StartPipelineBuild("initial");
viewport = new Viewport(0.0f, 0.0f, width, height);
scissorRect = new RawRect(0, 0, width, height);
fence = device.CreateFence(0);
fence.Name = "Aquarium D3D12 Frame Fence";
Console.WriteLine($"D3D12 resource registry: {resourceRegistry.Describe()}");
Console.WriteLine("D3D12 device and swapchain created.");
}
@ -368,6 +376,8 @@ public sealed class D3D12Renderer : IAquariumRenderer
frameResources.FroxelPrimitiveDescriptor = frameResources.TransientShaderDescriptors.Allocate();
froxelPrimitiveBuffer.CreateShaderResourceView(device, frameResources.FroxelPrimitiveDescriptor);
frameResources.DitherDescriptor = frameResources.TransientShaderDescriptors.Allocate();
ditherBuffer.CreateShaderResourceView(device, frameResources.DitherDescriptor);
frameResources.FieldInstanceDescriptor = frameResources.TransientShaderDescriptors.Allocate();
fieldInstanceBuffer.CreateShaderResourceView(device, frameResources.FieldInstanceDescriptor);
frameResources.GridHeightDescriptor = frameResources.TransientShaderDescriptors.Allocate();
@ -534,6 +544,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
DisposePipelineStates();
fullscreenRootSignature.Dispose();
fieldInstanceBuffer.Dispose();
ditherBuffer.Dispose();
froxelPrimitiveBuffer.Dispose();
DisposeBloomRenderTargets();
DisposeHistoryRenderTargets();
@ -662,6 +673,32 @@ public sealed class D3D12Renderer : IAquariumRenderer
"Aquarium D3D12 View-Froxel Primitive Buffer");
}
private D3D12StructuredBuffer CreateDitherBuffer(string path)
{
return new D3D12StructuredBuffer(
device,
DitherTextureSize * DitherTextureSize,
sizeof(uint),
"Aquarium D3D12 Aetheria Blue Noise Buffer");
}
private static uint[] LoadDitherPixels(string path)
{
var pixels = File.ReadAllBytes(path);
if (pixels.Length != DitherTextureSize * DitherTextureSize)
{
throw new InvalidOperationException($"Dither texture {path} must be {DitherTextureSize}x{DitherTextureSize} R8 data.");
}
var values = new uint[pixels.Length];
for (var index = 0; index < pixels.Length; index++)
{
values[index] = pixels[index];
}
return values;
}
private D3D12PipelineSet CreatePipelineSet(D3D12ShaderPaths paths)
{
var gridHeightBase = CreateGridHeightBasePipelineState(paths.Grid);
@ -1269,6 +1306,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
activeCommandList.SetGraphicsRootDescriptorTable(0, frameResources.FrameConstantsDescriptor.Gpu);
activeCommandList.SetGraphicsRootDescriptorTable(4, frameResources.FieldInstanceDescriptor.Gpu);
activeCommandList.SetGraphicsRootDescriptorTable(18, frameResources.GridHeightDescriptor.Gpu);
activeCommandList.SetGraphicsRootDescriptorTable(22, frameResources.DitherDescriptor.Gpu);
activeCommandList.RSSetViewports(mediumViewport);
activeCommandList.RSSetScissorRects(mediumScissorRect);
activeCommandList.OMSetRenderTargets(
@ -2159,6 +2197,12 @@ public sealed class D3D12Renderer : IAquariumRenderer
25,
0,
D3D12.DescriptorRangeOffsetAppend);
var ditherRange = new DescriptorRange(
DescriptorRangeType.ShaderResourceView,
1,
26,
0,
D3D12.DescriptorRangeOffsetAppend);
var rootParameters = new[]
{
new RootParameter(new RootDescriptorTable([constantBufferRange]), ShaderVisibility.All),
@ -2183,6 +2227,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
new RootParameter(new RootDescriptorTable([currentMediumColorRange]), ShaderVisibility.Pixel),
new RootParameter(new RootDescriptorTable([historyMediumColorRange]), ShaderVisibility.Pixel),
new RootParameter(new RootDescriptorTable([mediumLightDirectionRange]), ShaderVisibility.Pixel),
new RootParameter(new RootDescriptorTable([ditherRange]), ShaderVisibility.Pixel),
};
var staticSamplers = new[]
{
@ -2618,6 +2663,8 @@ public sealed class D3D12Renderer : IAquariumRenderer
public D3D12DescriptorSlot FroxelPrimitiveDescriptor { get; set; }
public D3D12DescriptorSlot DitherDescriptor { get; set; }
public D3D12DescriptorSlot FieldInstanceDescriptor { get; set; }
public D3D12DescriptorSlot GridHeightDescriptor { get; set; }

View file

@ -37,6 +37,7 @@ Texture2D<float4> mediumVolumeTexture : register(t13);
Texture2D<float4> mediumLightTexture : register(t15);
Texture2D<float4> gridHeightTexture : register(t22);
Texture2D<float4> mediumLightDirectionTexture : register(t25);
StructuredBuffer<uint> ditherTexture : register(t26);
SamplerState sourceSampler : register(s0);
static const int FIELD_INSTANCE_COUNT = 11;
@ -45,8 +46,11 @@ static const int FIELD_FLAG_EMITTER = 8;
static const int MEDIUM_FROXEL_ATLAS_COLUMNS = 8;
static const int MEDIUM_FROXEL_ATLAS_ROWS = 4;
static const int MEDIUM_FROXEL_SLICE_COUNT = MEDIUM_FROXEL_ATLAS_COLUMNS * MEDIUM_FROXEL_ATLAS_ROWS;
static const int MEDIUM_FROXEL_DOWNSCALE = 8;
static const int DITHER_TEXTURE_SIZE = 512;
static const float PI = 3.14159265359;
static const float INV_FOUR_PI = 0.07957747155;
static const float GOLDEN_RATIO_CONJUGATE = 0.61803398875;
static const float GRID_FOG_EXTINCTION = 0.18;
static const float GRID_FOG_SCATTERING_ALBEDO = 0.82;
@ -97,6 +101,17 @@ float3 rayDirectionForPixel(float2 pixel, float2 jitter, float3 camera, float2 c
return normalize(forward * 1.6 + right * ndc.x + up * ndc.y);
}
float blueNoise(uint2 pixel)
{
uint2 wrapped = pixel & (DITHER_TEXTURE_SIZE - 1);
return ((float)(ditherTexture[wrapped.x + wrapped.y * DITHER_TEXTURE_SIZE] & 255u) + 0.5) / 256.0;
}
float animatedBlueNoise(uint2 pixel, float salt)
{
return frac(blueNoise(pixel) + frameIndex * GOLDEN_RATIO_CONJUGATE + salt);
}
float hash31(float3 p)
{
p = frac(p * 0.1031);
@ -380,12 +395,20 @@ MediumVolumeOut MediumVolumePS(VertexOut input)
int2 tile = clamp((int2)floor(atlasCoord), int2(0, 0), int2(MEDIUM_FROXEL_ATLAS_COLUMNS - 1, MEDIUM_FROXEL_ATLAS_ROWS - 1));
int sliceIndex = tile.x + tile.y * MEDIUM_FROXEL_ATLAS_COLUMNS;
float2 localUv = frac(atlasCoord);
int froxelWidth = max((int)(resolution.x / (float)MEDIUM_FROXEL_DOWNSCALE), 1);
int froxelHeight = max((int)(resolution.y / (float)MEDIUM_FROXEL_DOWNSCALE), 1);
int2 cell = clamp((int2)floor(localUv * float2(froxelWidth, froxelHeight)), int2(0, 0), int2(froxelWidth - 1, froxelHeight - 1));
uint2 ditherPixel = (uint2)(cell * MEDIUM_FROXEL_DOWNSCALE);
float2 xyJitter = float2(
animatedBlueNoise(ditherPixel + uint2(17u, 59u), 0.0),
animatedBlueNoise(ditherPixel + uint2(113u, 211u), 0.37)) - 0.5;
float2 screenUv = float2(localUv.x, 1.0 - localUv.y);
float2 pixel = screenUv * resolution;
float2 pixel = screenUv * resolution + xyJitter * (float)MEDIUM_FROXEL_DOWNSCALE;
float3 rayDirection = rayDirectionForPixel(pixel, jitterPixels, cameraPosition, gridCenter);
float sliceLength = farDistance / (float)MEDIUM_FROXEL_SLICE_COUNT;
float travel = mediumSliceTravel(sliceIndex);
float zJitter = animatedBlueNoise(ditherPixel + uint2(307u, 401u), 0.73);
float travel = (((float)sliceIndex + zJitter) / (float)MEDIUM_FROXEL_SLICE_COUNT) * farDistance;
float3 p = cameraPosition + rayDirection * travel;
float density;
float sigmaT;

View file

@ -138,3 +138,4 @@
{"timestamp":"2026-05-10T16:38:53.8578765+01:00","topic":"D3D12 directional medium lighting","lesson":"Medium lighting needs explicit directional/probe data once phase and glossy surfaces matter. Aquarium now carries a luminance-weighted dominant-light direction moment beside propagated froxel irradiance, uses it for Henyey-Greenstein scattering, and shades solids from the same field instead of private direct emitter loops.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Medium.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs"]}
{"timestamp":"2026-05-10T16:49:14.2607265+01:00","topic":"Dominant-light direction limitation","lesson":"A single froxel light direction is a lossy artistic approximation. Intersecting beams average, and opposed beams can cancel to low confidence and isotropic fallback. Keep the smear for now because it may look good, but future full transport needs multi-lobe, probe, or reservoir direction storage.","files":["state/memory.json","state/map.yaml","state/scratch.md"]}
{"timestamp":"2026-05-10T17:03:06.9352794+01:00","topic":"D3D12 iterative medium light propagation","lesson":"The propagated medium light field now uses explicit scratch/final froxel targets and four ping-ponged propagation iterations for irradiance plus dominant direction, replacing the single one-pass neighbor spread. This remains a compact diffusion approximation, but propagation state and cost are explicit.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json","state/map.yaml","state/scratch.md"]}
{"timestamp":"2026-05-10T17:18:38.9003279+01:00","topic":"D3D12 medium froxel sample decorrelation","lesson":"Aetheria-style raymarch jitter only fights march-step aliasing because it marches per pixel. Aquarium froxel injection also has an 8x8 screen-space lattice, so medium samples must jitter both sub-froxel XY representative ray location and in-slice Z travel. D3D12 now uploads the Aetheria R8 blue-noise texture as a static structured buffer and uses animated blue-noise offsets for both axes before TAA accumulation.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Medium.hlsl","state/memory.json","state/map.yaml","state/scratch.md"]}

View file

@ -63,7 +63,7 @@ renderer_state:
- DirectWrite overlay text after scene rendering.
- Direct2D/DirectWrite debug UI panel with code-first controls bound to renderer state.
- Global GraphicsSettings document feeding render debug, exposure, bloom intensity, bloom veil, and medium composite intensity.
- Field instance structured buffer feeding D3D12 medium density, transport, raw light injection, and four-iteration ping-ponged froxel propagation for irradiance plus dominant-light direction.
- Field instance structured buffer feeding blue-noise-decorrelated D3D12 medium density, transport, raw light injection, and four-iteration ping-ponged froxel propagation for irradiance plus dominant-light direction.
- D3D12 default renderer behind IAquariumRenderer with device/queue/swapchain, per-frame command allocators, fences, static/transient descriptor arenas, upload ring constants, RTV/SRV/UAV render targets, structured field buffers, tracked barriers, command events, resize descriptor-arena rebuild, migrated Grid height brushes, view-froxel solid bins, HDR/bloom/present, temporal history lanes, and DirectWrite overlay bridge.
- D3D12 Grid linework is direct-traced as a non-terminating stochastic event lane before the nearest solid; the failed transparent-froxel Grid bin experiment is dead and must stay out of live code.
- Splash screen with bundled app icon and GameCult typefaces.

View file

@ -52,7 +52,7 @@
"HDR/PBR presentation should follow research/rendering/hdr-pbr-presentation.md: scene-linear lighting, explicit exposure, pre-tonemap bloom/veil, then a display transform. Do not reach for 2000s threshold bloom when the frame needs dynamic range.",
"Aquarium's current HDR presentation pass uses fixed manual exposure plus a three-level half/quarter/eighth pre-tonemap bloom pyramid with firefly-safe downsampling and separable blur. Next HDR work is persisted exposure/display controls, not threshold glow.",
"Future volumetric lighting should be a field sampled consistently by terrain, planets, fog, particles, and diegetic UI. Do not fake only the planet term if the scene is supposed to bounce light.",
"Volumetric density must not self-illuminate through baked color. D3D12 medium lighting now evaluates physical-ish coefficients first: density for inspection, extinction sigma_t, scattering sigma_s, and albedo. Field mediumTerms mean x = extinction per density, y = scattering albedo, z = reserved phase/aniso, w = density scale. Raw irradiance from FieldFlags.Emitter instances is injected using emitter colorIntensity.rgb, finite solid angle, and cheap depth/radial light-path attenuation; propagation ping-pongs four low-resolution froxel iterations through scratch/final irradiance and luminance-weighted dominant-light direction targets. Medium integration uses Beer-Lambert transmittance and Henyey-Greenstein phase from that direction field; solids consume the propagated froxel light/direction for diffuse and cursor GGX specular. A single direction moment is intentionally lossy: crossing beams smear or cancel to low confidence and fall back toward isotropic scattering. Keep it for now if the smear is useful, but do not mistake it for final transport; future richer lighting needs multi-lobe/probe/reservoir direction storage. Do not compute unused direct-scattering color into transport targets or private per-surface emitter loops just because an earlier pass did. Self, cursor, nebulae, and future emissive SDFs must all use this field-emitter path; do not reintroduce point-light constants or ambient fog glow.",
"Volumetric density must not self-illuminate through baked color. D3D12 medium lighting now evaluates physical-ish coefficients first: density for inspection, extinction sigma_t, scattering sigma_s, and albedo. Field mediumTerms mean x = extinction per density, y = scattering albedo, z = reserved phase/aniso, w = density scale. Raw irradiance from FieldFlags.Emitter instances is injected using emitter colorIntensity.rgb, finite solid angle, and cheap depth/radial light-path attenuation; propagation ping-pongs four low-resolution froxel iterations through scratch/final irradiance and luminance-weighted dominant-light direction targets. Medium froxel injection samples one representative ray per froxel/slice, decorrelated by the Aetheria blue-noise buffer in both sub-froxel XY and in-slice travel Z; this fights both 32-slice march aliasing and 8x8 froxel row/column aliasing before TAA accumulation. Medium integration uses Beer-Lambert transmittance and Henyey-Greenstein phase from that direction field; solids consume the propagated froxel light/direction for diffuse and cursor GGX specular. A single direction moment is intentionally lossy: crossing beams smear or cancel to low confidence and fall back toward isotropic scattering. Keep it for now if the smear is useful, but do not mistake it for final transport; future richer lighting needs multi-lobe/probe/reservoir direction storage. Do not compute unused direct-scattering color into transport targets or private per-surface emitter loops just because an earlier pass did. Self, cursor, nebulae, and future emissive SDFs must all use this field-emitter path; do not reintroduce point-light constants or ambient fog glow.",
"Do not blend D3D12 medium color history into final presentation until the renderer owns a proper light-volume/medium reprojection contract. Medium packets can keep opacity/density/travel age for diagnostics, but resolved fog color history smears badly when injected lighting changes with camera/emitter geometry.",
"D3D12 medium radiance has its own temporal lane: scene emits `sceneMediumColor`, resolve keeps surface history surface-only, reprojects medium packet travel into `historyMediumColor`, validates by travel/opacity/density, and composites resolved surface + resolved medium + events. Medium lighting is split into raw emitter injection and a propagated froxel light target; medium integration and solid diffuse shading consume the propagated light field instead of private direct diffuse loops. This is single-step froxel propagation plus reprojection; full multi-bounce GI and directional/probe glossy lighting remain future work.",
"Volumetric design must start from research/volumetrics/synthesis.md. The first pass should follow Wronski/Hillaire production shape: explicit low-resolution frustum volume, injected density/extinction/scattering, Self as first emitter, front-to-back transmittance/in-scattering integration, then consistent composition.",

View file

@ -525,3 +525,9 @@ reusing field identity/travel/control.
still a compact diffusion-style approximation, not full multi-bounce
transport, but the cost and state are explicit and the scene consumes only the
final propagated irradiance/direction targets.
- D3D12 medium sample decorrelation pass: D3D12 now uploads the existing
Aetheria `Aetheria-LDR_LLL1_0.r8` blue-noise texture as a static structured
buffer. Medium froxel injection uses animated blue-noise offsets for both the
representative ray's sub-froxel XY location and the sample's in-slice Z
travel. This is different from Aetheria's per-pixel cloud march: Aquarium must
fight both fixed march-step aliasing and the 8x8 froxel row/column lattice.