feat(render): Campaign V slice V6j commit 2 - Dereth draws on Vulkan
The three world renderers' submission arms, both pass executors, and the
composition that reaches them. This is the unit three predecessors stopped at.
What it produces. ACDREAM_RENDER_BACKEND=vulkan on the offline scene renders
terrain with blended textures and road overlays, the water edge, static world
meshes, procedural scenery, and the complete retained UI - the same frame the GL
pixel gate captures, from the same camera, minus the sky. artifacts/v6j-vk2.
The shape, and why it is not V4c's. Section 5.5.6 chose option (B) after NVIDIA
rendered the V4c binary 10/10 where AMD's GL stack did not: GL keeps its raw
world path through to V10 as a documented fork confined to the submission seam,
and the RHI world path ships on Vulkan. So V4c's and V4d-2's content returns as a
SECOND arm rather than a replacement. The GL arm issues the same GL statements in
the same order against the same objects; the encoder arm lives in three .Rhi.cs
partials and is entered by one branch per submission site.
Three differences from V4c, each because the tree moved under it. There is no
binding-9 texture table - V4t put the slot on the device and Vulkan binds set 2,
so the arm that used to intern bindless handles simply has nothing to do. The
pipelines carry the device's sample count rather than 1, because Vulkan requires
rasterizationSamples to match the pass and alpha-to-coverage is a no-op at one
sample. And no renderer opens a pass.
That last one is structural, not tidiness. Under MSAA the frame's one backbuffer
pass resolves into the swapchain image and stores DONT_CARE into the multisampled
scratch, so a second pass declaring Load would load undefined contents; the
backend also permits one open pass per frame. VulkanWorldScenePhase therefore
opens the pass, publishes the encoder on VulkanWorldPassScope for exactly the
span of the inner WorldSceneRenderer, and every renderer borrows it.
Three sections are frame-global on GL and cannot be on Vulkan: the SceneLighting
UBO, the per-cell clip regions, and the terrain clip block. GL binds each to a
global binding point and every consumer inherits it. Vulkan binds a descriptor
set per draw, and a renderer's own binds are what select the scope those sections
must land in - so their writers PUBLISH into WorldFrameSections and each renderer
binds them inside the pass, after its own binds. SceneLightingUboBinding's
per-flight-slot buffer pool disappears with it: a ring allocation is already
distinct memory that lives until the frame retires, which is the property the
pool existed to provide.
Both pass executors became backend-neutral rather than gaining twins. Everything
they do is delegation to a renderer except four concerns - the clip-frame
publication, the doorway scissor, gl_ClipDistance enablement, and retail's
interior depth clear - so those four move behind IWorldPassSurface and retail's
ordering, which is what these classes are actually for, is written once. The GL
implementation issues the statements the executors used to issue inline.
Clip distances are no-ops on the Vulkan arm, and that is safe rather than a
divergence: Vulkan activates every element the shader declares, and all three
world vertex shaders already write 1.0 into every slot past the active count.
The interior depth clear becomes vkCmdClearAttachments, reached through the scope
so the pinned contract stays frozen and the backend-only verb stays in the
backend. The hook for it was already committed at V6i-3 with a cref to a type
that did not exist yet; it exists now.
The collision-wireframe DebugLineRenderer is composed as null on the Vulkan arm.
DrawAndPublish flushes it INSIDE the world phase and it opens its own pass, which
the one-pass rule forbids. The toggle is DevTools-only and DevTools is not
composed there, so nothing is lost - composing it would throw on the first
wireframe frame rather than silently misdraw.
Two seams widened rather than invented. GameWindowGraphics answers whether the
backend has a world-pass seam, because the three composition phases that need it
already borrow that handle and "does this backend work that way" is what the type
exists to answer. And MeshSourceReady replaces the anyVao != 0 gate with the same
question in backend-neutral form - V6i-3 published HasStores for exactly this -
so the predicate evaluates identically on GL.
What is NOT here, and is expected. Sky and weather are still raw GL (V4f), so the
Vulkan frame's sky is the atmosphere fog clear. Particles (V4e), the paperdoll and
appraisal viewports and the portal depth mask (V4g) likewise. The executors
already accepted all of them as absent.
Gates. Release build green. App tests 4,112 passed / 3 skipped, the unchanged
baseline; complete Release suite 9,175 / 5. Strict GL offline pixel gate against
847f14ae: 5.50e-05, 31 differing pixels of 563,200, inside the documented 9-31
band and 18x under the threshold. Characterised rather than accepted, because 31
is the band's top: cross-commit pairs measured 21, 29 and 31 while same-commit
controls measured 12 and 20, and maximumChannelDelta is 46-52 in every comparison
INCLUDING the pure controls - so the few large-delta pixels are a property of the
capture, and a cross-commit pair at 21 against a same-commit pair at 20 is not
what a systematic shift looks like. GL connected repeat gate at 3 runs: 3/3
RENDERED on the desktop witness and 3/3 on the client capture. One offline Vulkan
run with VK_LAYER_KHRONOS_validation proven inserted by the loader: zero
validation errors, zero warnings, a captured world frame, and a graceful close.
Coverage gap, stated rather than assumed. The offline scene is a fixed outdoor
view, so EnvCellRenderer's Vulkan arm draws nothing in it - dungeon interiors are
half of this slice and are unproven by anything automated, exactly as they were
for V4c. The deferred-alpha path and the doorway scissor are likewise untouched
by this scene. They join the accumulated user-gate debt in plan section 5.1.
No divergence-register row: no retail-facing behaviour changes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
81fe5e1b63
commit
f84eef3256
22 changed files with 2566 additions and 264 deletions
332
src/AcDream.App/Rendering/TerrainModernRenderer.Rhi.cs
Normal file
332
src/AcDream.App/Rendering/TerrainModernRenderer.Rhi.cs
Normal file
|
|
@ -0,0 +1,332 @@
|
|||
using System.Collections.Immutable;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using AcDream.App.Rendering.Gpu;
|
||||
using AcDream.App.Rendering.Wb;
|
||||
using AcDream.Core.Terrain;
|
||||
|
||||
namespace AcDream.App.Rendering;
|
||||
|
||||
/// <summary>
|
||||
/// Campaign V slice V6j: terrain's RHI submission arm.
|
||||
///
|
||||
/// <para>This is V4d-2's content, re-landed as a SECOND arm rather than as a
|
||||
/// replacement. §5.5.6 selected option (B) after NVIDIA rendered the V4c binary
|
||||
/// 10/10 and AMD's GL stack did not: GL keeps its raw world path through to V10
|
||||
/// as a documented, scoped fork confined to the submission seam, and the RHI
|
||||
/// world path ships on Vulkan. So every GL statement in the sibling file is
|
||||
/// untouched, and everything here runs only when there is no GL context.</para>
|
||||
///
|
||||
/// <para>Three things differ from V4d-2, each because the tree moved under it.
|
||||
/// The texture slots come from <c>TerrainAtlas</c>'s device table (V4t) rather
|
||||
/// than a per-renderer bindless table, so there is no binding-9 table to bind at
|
||||
/// all — the Vulkan texture table is set 2 and the encoder binds it. The tiling
|
||||
/// block is the shared <c>TerrainTextureTilingTable</c> constants (V6f-2) rather
|
||||
/// than locals. And the pass is BORROWED from <see cref="IWorldPassScope"/>
|
||||
/// rather than opened, because the frame's one backbuffer pass resolves and a
|
||||
/// second pass could not load what it left.</para>
|
||||
/// </summary>
|
||||
public sealed unsafe partial class TerrainModernRenderer
|
||||
{
|
||||
/// <summary>
|
||||
/// Terrain's vertex layout: the same 40-byte record <c>ConfigureVao</c>
|
||||
/// describes with <c>glVertexAttribPointer</c>/<c>glVertexAttribIPointer</c>.
|
||||
///
|
||||
/// <para>Locations 2–5 are <see cref="GpuVertexFormat.UByte4UInt"/>, not
|
||||
/// <c>UByte4Normalized</c>. They are <c>uvec4</c> in the shader and carry
|
||||
/// terrain-type, road and split-direction codes; normalising them would not
|
||||
/// be an approximation, it would be garbage.</para>
|
||||
/// </summary>
|
||||
private static readonly GpuVertexLayout TerrainVertexLayout = new(
|
||||
StrideBytes: VertexSize,
|
||||
ImmutableArray.Create(
|
||||
new GpuVertexAttribute(0, GpuVertexFormat.Float3, 0),
|
||||
new GpuVertexAttribute(1, GpuVertexFormat.Float3, 12),
|
||||
new GpuVertexAttribute(2, GpuVertexFormat.UByte4UInt, 24),
|
||||
new GpuVertexAttribute(3, GpuVertexFormat.UByte4UInt, 28),
|
||||
new GpuVertexAttribute(4, GpuVertexFormat.UByte4UInt, 32),
|
||||
new GpuVertexAttribute(5, GpuVertexFormat.UByte4UInt, 36)));
|
||||
|
||||
private readonly IGpuDevice? _device;
|
||||
private readonly ICurrentGpuFrameSource? _frames;
|
||||
private readonly IWorldPassScope? _scope;
|
||||
private IGpuPipeline? _pipeline;
|
||||
private IGpuBuffer? _vertexStore;
|
||||
private IGpuBuffer? _indexStore;
|
||||
private IGpuBuffer? _tilingBuffer;
|
||||
|
||||
/// <summary>
|
||||
/// The RHI arm's constructor. No GL context, no <c>Shader</c>, no
|
||||
/// <c>BindlessSupport</c>: the pipeline compiles <c>terrain_modern</c> from
|
||||
/// the committed SPIR-V and the atlas's slots index the device's one table.
|
||||
/// </summary>
|
||||
internal TerrainModernRenderer(
|
||||
IGpuDevice device,
|
||||
ICurrentGpuFrameSource frames,
|
||||
IWorldPassScope scope,
|
||||
TerrainAtlas atlas,
|
||||
IGpuResourceRetirementQueue resourceRetirement,
|
||||
int initialSlotCapacity = 64)
|
||||
{
|
||||
_device = device ?? throw new ArgumentNullException(nameof(device));
|
||||
_frames = frames ?? throw new ArgumentNullException(nameof(frames));
|
||||
_scope = scope ?? throw new ArgumentNullException(nameof(scope));
|
||||
_atlas = atlas ?? throw new ArgumentNullException(nameof(atlas));
|
||||
ArgumentNullException.ThrowIfNull(resourceRetirement);
|
||||
_retirementLedger = new GpuRetirementLedger(resourceRetirement);
|
||||
_alloc = new GpuRetiredTerrainSlotAllocator(initialSlotCapacity, resourceRetirement);
|
||||
_slots = new SlotData?[initialSlotCapacity];
|
||||
|
||||
_pipeline = device.CreatePipeline(new GpuPipelineDescription
|
||||
{
|
||||
Name = "terrain",
|
||||
Shaders = new GpuShaderSet("terrain_modern"),
|
||||
VertexLayout = TerrainVertexLayout,
|
||||
Topology = GpuPrimitiveTopology.TriangleList,
|
||||
Blend = GpuBlendMode.None,
|
||||
// GL_LESS, not the contract's LessOrEqual default: the world frame
|
||||
// runs under GL_LESS and terrain never called glDepthFunc, so it
|
||||
// inherited it. LessOrEqual would change which of two coplanar retail
|
||||
// surfaces wins — visible exactly where terrain meets roads and
|
||||
// building footings, which is what zFightTerrainAdjust is about.
|
||||
Depth = new GpuDepthState(Test: true, Write: true, GpuCompareOp.Less),
|
||||
// #108-residual: retail terrain is SINGLE-SIDED. See the GL arm's
|
||||
// Draw for the full reasoning; this bakes the same triple.
|
||||
Cull = GpuCullMode.Back,
|
||||
FrontFace = GpuFrontFace.CounterClockwise,
|
||||
AlphaToCoverage = false,
|
||||
ColorWrite = true,
|
||||
SampleCount = scope.SampleCount,
|
||||
});
|
||||
AllocateRhiBuffers(initialSlotCapacity);
|
||||
}
|
||||
|
||||
private void AllocateRhiBuffers(int capacitySlots)
|
||||
{
|
||||
long vertexBytes = checked((long)capacitySlots * VertsPerLandblock * VertexSize);
|
||||
long indexBytes = checked((long)capacitySlots * IndicesPerLandblock * IndexSize);
|
||||
IGpuDevice device = RequireDevice();
|
||||
_vertexStore = device.CreateBuffer(new GpuBufferDescription(
|
||||
"terrain-vertices",
|
||||
vertexBytes,
|
||||
GpuBufferUsage.Vertex
|
||||
| GpuBufferUsage.TransferSource
|
||||
| GpuBufferUsage.TransferDestination,
|
||||
GpuMemoryResidency.DeviceLocal));
|
||||
_globalVboCapacityBytes = vertexBytes;
|
||||
_indexStore = device.CreateBuffer(new GpuBufferDescription(
|
||||
"terrain-indices",
|
||||
indexBytes,
|
||||
GpuBufferUsage.Index
|
||||
| GpuBufferUsage.TransferSource
|
||||
| GpuBufferUsage.TransferDestination,
|
||||
GpuMemoryResidency.DeviceLocal));
|
||||
_globalEboCapacityBytes = indexBytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Grow-and-copy, device-side. <see cref="IGpuBuffer.CopyTo"/> keeps resident
|
||||
/// landblock meshes from round-tripping through system memory, exactly as the
|
||||
/// GL arm's <c>glCopyBufferSubData</c> does.
|
||||
/// </summary>
|
||||
private void EnsureRhiCapacity(int newCapacitySlots)
|
||||
{
|
||||
if (newCapacitySlots <= _alloc.Capacity)
|
||||
return;
|
||||
|
||||
long vertexBytes = checked((long)newCapacitySlots * VertsPerLandblock * VertexSize);
|
||||
long indexBytes = checked((long)newCapacitySlots * IndicesPerLandblock * IndexSize);
|
||||
IGpuDevice device = RequireDevice();
|
||||
IGpuBuffer oldVertices = RequireVertexStore();
|
||||
IGpuBuffer oldIndices = RequireIndexStore();
|
||||
|
||||
IGpuBuffer newVertices = device.CreateBuffer(new GpuBufferDescription(
|
||||
"terrain-vertices",
|
||||
vertexBytes,
|
||||
GpuBufferUsage.Vertex
|
||||
| GpuBufferUsage.TransferSource
|
||||
| GpuBufferUsage.TransferDestination,
|
||||
GpuMemoryResidency.DeviceLocal));
|
||||
IGpuBuffer newIndices;
|
||||
try
|
||||
{
|
||||
newIndices = device.CreateBuffer(new GpuBufferDescription(
|
||||
"terrain-indices",
|
||||
indexBytes,
|
||||
GpuBufferUsage.Index
|
||||
| GpuBufferUsage.TransferSource
|
||||
| GpuBufferUsage.TransferDestination,
|
||||
GpuMemoryResidency.DeviceLocal));
|
||||
}
|
||||
catch
|
||||
{
|
||||
newVertices.Dispose();
|
||||
throw;
|
||||
}
|
||||
|
||||
oldVertices.CopyTo(newVertices, 0, 0, _globalVboCapacityBytes);
|
||||
oldIndices.CopyTo(newIndices, 0, 0, _globalEboCapacityBytes);
|
||||
|
||||
_vertexStore = newVertices;
|
||||
_indexStore = newIndices;
|
||||
_globalVboCapacityBytes = vertexBytes;
|
||||
_globalEboCapacityBytes = indexBytes;
|
||||
|
||||
// Dispose routes the physical free through the device's retirement queue,
|
||||
// so the old arena outlives every frame that can still reference it.
|
||||
oldVertices.Dispose();
|
||||
oldIndices.Dispose();
|
||||
|
||||
var grownSlots = new SlotData?[newCapacitySlots];
|
||||
Array.Copy(_slots, grownSlots, _slots.Length);
|
||||
_slots = grownSlots;
|
||||
_alloc.GrowTo(newCapacitySlots);
|
||||
}
|
||||
|
||||
private void UploadRhiLandblock(
|
||||
int slot,
|
||||
TerrainVertex[] bakedVerts,
|
||||
uint[] bakedIndices)
|
||||
{
|
||||
RequireVertexStore().Upload(
|
||||
(long)slot * VertsPerLandblock * VertexSize,
|
||||
MemoryMarshal.AsBytes<TerrainVertex>(bakedVerts));
|
||||
RequireIndexStore().Upload(
|
||||
(long)slot * IndicesPerLandblock * IndexSize,
|
||||
MemoryMarshal.AsBytes<uint>(bakedIndices));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records terrain's multi-draw into the borrowed world pass.
|
||||
///
|
||||
/// <para>Order matters twice. <c>BindPipeline</c> re-issues the pipeline's own
|
||||
/// cull/front-face/depth-write defaults, so anything dynamic has to come
|
||||
/// after it. And the frame-global sections — SceneLighting and the terrain
|
||||
/// clip block — are bound HERE, after this renderer's own binds, because its
|
||||
/// own binds are what select the descriptor scope those sections must land in
|
||||
/// (plan §5.5.14 item 2).</para>
|
||||
/// </summary>
|
||||
private void DrawRhi(Matrix4x4 viewProjection, int drawCount)
|
||||
{
|
||||
IWorldPassScope scope = _scope!;
|
||||
IGpuPassEncoder encoder = scope.RequireEncoder();
|
||||
IGpuFrame frame = _frames!.CurrentFrame
|
||||
?? throw new InvalidOperationException(
|
||||
"TerrainModernRenderer requires an open IGpuFrame (see GpuDeviceFrameLifetime).");
|
||||
|
||||
// V6i-2's backend-neutral atlas registers both slots at construction, so
|
||||
// there is no per-draw acquire-and-reregister step and no binding-9 table
|
||||
// to flush — the Vulkan texture table is set 2 and the encoder binds it.
|
||||
(GpuTextureSlot terrainSlot, GpuTextureSlot alphaSlot) = _atlas.TextureSlots;
|
||||
|
||||
var pushConstants = new GpuPushConstants
|
||||
{
|
||||
ViewProjection = viewProjection,
|
||||
DrawIdOffset = 0,
|
||||
LightingMode = 0,
|
||||
RenderPass = 0,
|
||||
LightDebug = 0,
|
||||
TextureIndexA = terrainSlot.Index,
|
||||
TextureIndexB = alphaSlot.Index,
|
||||
ParamA = 0f,
|
||||
ParamB = 0f,
|
||||
};
|
||||
|
||||
encoder.BindPipeline(_pipeline!);
|
||||
encoder.SetPushConstants(in pushConstants);
|
||||
encoder.BindVertexBuffer(RequireVertexStore(), 0);
|
||||
encoder.BindIndexBuffer(RequireIndexStore(), 0, GpuIndexType.UInt32);
|
||||
BindTilingTable(encoder);
|
||||
WorldFrameSectionBinding.BindSceneLighting(encoder, scope.Sections, frame);
|
||||
WorldFrameSectionBinding.BindTerrainClip(encoder, scope.Sections, frame);
|
||||
|
||||
GpuRingAllocation commands = frame.AllocateRing(
|
||||
drawCount * sizeof(DrawElementsIndirectCommand),
|
||||
GpuRingUsage.Indirect);
|
||||
MemoryMarshal.AsBytes(_deicScratch.AsSpan(0, drawCount))
|
||||
.CopyTo(commands.Data);
|
||||
encoder.MultiDrawIndexedIndirect(
|
||||
commands.Buffer,
|
||||
commands.OffsetBytes,
|
||||
(uint)drawCount,
|
||||
(uint)sizeof(DrawElementsIndirectCommand));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binds the immutable 36-entry tiling table. Long-lived and written once, so
|
||||
/// its range never moves — which also keeps it out of the descriptor-scope
|
||||
/// key's moving parts.
|
||||
/// </summary>
|
||||
private void BindTilingTable(IGpuPassEncoder encoder)
|
||||
{
|
||||
if (_tilingBuffer is null)
|
||||
{
|
||||
if (_atlas.TilingByLayer.Count != TerrainTextureTilingTable.LayerCapacity)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Terrain tiling table has {_atlas.TilingByLayer.Count} entries; " +
|
||||
$"expected {TerrainTextureTilingTable.LayerCapacity}.");
|
||||
}
|
||||
|
||||
Span<byte> block = stackalloc byte[TerrainTextureTilingTable.UniformBufferBytes];
|
||||
block.Clear();
|
||||
for (int i = 0; i < TerrainTextureTilingTable.LayerCapacity; i++)
|
||||
{
|
||||
BitConverter.TryWriteBytes(
|
||||
block[(i * TerrainTextureTilingTable.UniformElementStrideBytes)..],
|
||||
_atlas.TilingByLayer[i]);
|
||||
}
|
||||
|
||||
IGpuBuffer buffer = RequireDevice().CreateBuffer(new GpuBufferDescription(
|
||||
"terrain-tiling",
|
||||
TerrainTextureTilingTable.UniformBufferBytes,
|
||||
GpuBufferUsage.Uniform | GpuBufferUsage.TransferDestination,
|
||||
GpuMemoryResidency.DeviceLocal));
|
||||
try
|
||||
{
|
||||
buffer.Upload(0, block);
|
||||
}
|
||||
catch
|
||||
{
|
||||
buffer.Dispose();
|
||||
throw;
|
||||
}
|
||||
_tilingBuffer = buffer;
|
||||
_textureTilingUploaded = true;
|
||||
}
|
||||
|
||||
encoder.BindUniformBuffer(
|
||||
GpuBindingModel.UniformTerrainTiling,
|
||||
_tilingBuffer,
|
||||
0,
|
||||
TerrainTextureTilingTable.UniformBufferBytes);
|
||||
}
|
||||
|
||||
private IGpuDevice RequireDevice() =>
|
||||
_device ?? throw new InvalidOperationException(
|
||||
"TerrainModernRenderer's RHI arm was reached without an IGpuDevice.");
|
||||
|
||||
private IGpuBuffer RequireVertexStore() =>
|
||||
_vertexStore ?? throw new InvalidOperationException(
|
||||
"The terrain vertex arena has not been created.");
|
||||
|
||||
private IGpuBuffer RequireIndexStore() =>
|
||||
_indexStore ?? throw new InvalidOperationException(
|
||||
"The terrain index arena has not been created.");
|
||||
|
||||
private void DisposeRhi()
|
||||
{
|
||||
_pipeline?.Dispose();
|
||||
_pipeline = null;
|
||||
_tilingBuffer?.Dispose();
|
||||
_tilingBuffer = null;
|
||||
_vertexStore?.Dispose();
|
||||
_vertexStore = null;
|
||||
_indexStore?.Dispose();
|
||||
_indexStore = null;
|
||||
_globalVboCapacityBytes = 0;
|
||||
_globalEboCapacityBytes = 0;
|
||||
_dynamicFrameStarted = false;
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue