The last of V6's three commits, and the one that makes the backend render. Plan sections: 4.5 (pipelines and the persisted cache), 4.6 (shaders and the committed .spv), 4.7 and 3.3 (clip space, the Y flip and winding), 4.9 and 4.10 (swapchain format and the scissor convention), 4.11 (the probe shader V5 deferred), 5.4 (Target: null means the swapchain image, literally). WHAT RUNS. ACDREAM_RENDER_BACKEND=vulkan now renders a real scene through the whole RHI on the RX 9070 XT: 60,000-plus frames per twelve-second run, 4x MSAA resolving into a B8G8R8A8_UNORM swapchain, GPU timer scopes resolving, a screenshot taken through IGpuDevice.CaptureBackbuffer, and a clean CloseMainWindow exit with the allocator reporting three device-memory objects. WHAT IT DRAWS, AND WHY IT IS NOT THE GAME. V6's milestone is "a full game frame on Vulkan" and on this branch that cannot be the game's own frame. V4c and V4d are parked by 5.5.5 so the world renderers are still raw GL; and the two renderers that DO speak the RHI - TextRenderer and DebugLineRenderer, ported at V4a - both throw for any device that is not a GlGpuDevice, because their loose uniforms and their classic texture-unit sprite binding have no home in the pinned contract yet. Converting them is a V4-class change with its own GL pixel gate, outside this slice's file list. So the backend is exercised through the contract by a scene of our own, and it is not a toy. It uses a device-local mesh arena filled through the staging ring, instance and batch data written straight into mapped ring memory, an offscreen render target whose colour is registered into the global texture table and sampled by a later pass, a BC1 texture with a CPU-built mip chain beside an uncompressed one with a vkCmdBlitImage chain, one multi-draw-indirect covering five quads with gl_DrawID selecting per-draw batch data, a second pipeline with line-list topology bound mid-pass, dynamic cull/front-face/depth-write, push constants, timer scopes, and an MSAA colour attachment resolving into the swapchain image. ORIENTATION, BY INSPECTION. Slice V5's screenshot was a uniform clear and its orientation was right "by construction" - which a uniform clear cannot show. The scene is therefore deliberately asymmetric in both axes: a quadrant card that is red top-left, green top-right, blue bottom-left and white bottom-right, four differently tinted markers at four different corners, and an open L of lines whose short stub rises at its right end. The captured PNG reads correctly in every one of those, including a miniature of the same card in the bottom-right whose own quadrants are also the right way up. The negative viewport height, the front-face inversion and the capture path agree. THE SHADER TOOLCHAIN, AND WHAT IT FOUND. tools/compile-shaders.ps1 drives tools/ShaderCompiler, a small out-of-solution .NET tool over Silk.NET.Shaderc - the same shaderc glslc is built on, through the already-pinned Silk 2.23.0 family. glslc is preferred when a Vulkan SDK is present and reported when it is; neither this machine nor CI has one, and requiring a 500 MB manual install between a contributor and a working checkout is not a reasonable price for a build step. The GLSL sources stay the single source of truth: the Vulkan dialect arrives as a preamble injected after the #version line - ACDREAM_UBO_SET becomes "set = 1,", the texture table becomes a set-2 descriptor array with a required nonuniformEXT accessor, and the shared 96-byte push block is declared with each loose uniform name defined onto its member. The only edits to a shader BODY are mechanical and dialect-level: dropping default-block uniform declarations, which Vulkan GLSL has no such thing as, and assigning explicit varying locations BY NAME across a pair, because ordinal assignment would look identical today and silently swap varyings the first time an author reordered a line. Run over the eight production pairs, exactly one thing happened: none of them compiled, and every failure is a specific source-level fact belonging to a renderer-port slice that has not landed. debug_line needs uView/uProjection converged into one uViewProjection - two matrices are 128 bytes and the shared block is 96. mesh_modern and particle still pass a uvec2 bindless handle as a varying, which is V4t's GpuTextureSlot retype. sky has ten loose uniforms and wants a UBO. ui_text needs uScreenSize/uUseTexture/uTex. particle_mesh needs uTextureIndex to become uTextureIndexA. terrain_modern needs V4d-1's matrix convergence. mesh is the legacy pair with no RHI consumer at all. That inventory is committed as shaders.manifest.json, with each source's SHA-256 and the compiler's own message, and a test re-hashes it so an edited shader that never got recompiled fails a build rather than shipping a stale binary. vk_probe is the pair that does compile, and it is the shader 4.11 already asked for: V5 recorded "build one real pipeline from the committed .spv" as its single deliberate deviation because no toolchain existed. It is Vulkan-dialect only and no GL renderer draws with it, so it forks nothing; it retires when the ported world renderers become the backend's own proof. DESCRIPTORS. Sets 0 and 1 are DYNAMIC buffer descriptors bound per flight slot, so a per-draw range change costs a dynamic offset in vkCmdBindDescriptorSets rather than a vkUpdateDescriptorSets in the hot path - which is what keeps 4.4's zero-writes-per-frame property true for buffers as well as for textures. Ten dynamic storage descriptors is above Vulkan's guaranteed minimum of four, so it is a real requirement rather than a free choice, it fails loudly at layout creation on a device that cannot serve it, and V9's lavapipe row must confirm it. Unused bindings point at a shared dummy range so there is ONE set layout and one pipeline layout; that is why binding a second pipeline mid-pass costs nothing and disturbs neither the descriptors nor the push constants. THE ONE MAPPING FUNCTION. VulkanViewportMapping holds the whole coordinate reconciliation: negative viewport height, the front-face inversion that pairs with it, and - separately - the scissor flip, which the viewport sign does NOT perform. The V3 audit flagged that as a concrete V6 acceptance item and it is the subtle one: vkCmdSetScissor is always top-left-origin, NdcScissorRect emits GL bottom-left rectangles, and getting it wrong clips a doorway aperture from the wrong edge in a scene that has one. Clip space needs nothing, as 4.7 concluded: the cameras already build [0,1]-convention projections. CONTRACT GAP, RECORDED NOT PAPERED OVER. GpuPipelineDescription cannot name its colour-attachment format, and Vulkan bakes that into a pipeline. Offscreen targets therefore adopt the swapchain's B8G8R8A8_UNORM rather than a literal RGBA order - invisible above the API, because an image is sampled through its format's component mapping and the one CPU readback swizzles explicitly. The honest fix is a colour-format field added in a reviewed contract commit, exactly as GpuBlendMode.InverseAlpha and GpuVertexFormat.UByte4UInt were added when V4c and V4d met the same wall. It is documented at VulkanTextureFormatMapping.CanonicalColorAttachmentFormat. The pipeline cache is persisted to the cache directory and validated by its 32-byte header against this device's vendor, device and cache UUID before use. Drivers are required to ignore incompatible blobs, but "required to" is a poor foundation for something that runs before anything else in the process, and the check costs 32 bytes of comparison. Two consecutive launches report "cold" then "reused". Gates: Release build clean; App suite 4056 passed / 3 skipped (4037 at V6b plus 19 new); offline pixel gate PASS at a differing fraction of 5.15e-05 with a same-commit control immediately after it at 2.84e-05 - 29 and 16 pixels of 563,200, the same class of ambient variation the campaign's 15-23 band records, and roughly 19x under the 0.001 threshold on a commit that changes no GL code path. Validation layers could not be run: this machine has no Vulkan SDK, no HKLM\SOFTWARE\Khronos\Vulkan\ExplicitLayers key, no VK_LAYER_PATH and no VkLayer_khronos_validation.json anywhere on disk. Plan 7 already requires one validation-clean run at V7; it needs the SDK installed first and is reported rather than assumed here. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
514 lines
21 KiB
C#
514 lines
21 KiB
C#
using System.Numerics;
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace AcDream.App.Rendering.Gpu.Vk;
|
|
|
|
/// <summary>
|
|
/// Campaign V slice V6c: the scene that proves the Vulkan RHI end to end.
|
|
///
|
|
/// <para><b>Why this exists.</b> V6's milestone is "a full game frame on
|
|
/// Vulkan", and on this branch that cannot be the game's own frame: V4c and V4d
|
|
/// are parked (plan §5.5.5) so the world renderers are still raw GL, and
|
|
/// <c>TextRenderer</c>/<c>DebugLineRenderer</c> — the two renderers that DO
|
|
/// speak the RHI — currently require a <c>GlGpuDevice</c> for their loose
|
|
/// uniforms and their classic texture-unit binding, and refuse any other
|
|
/// backend. So the only honest way to exercise the whole backend now is to drive
|
|
/// it through the pinned contract with a scene of our own.</para>
|
|
///
|
|
/// <para>It is not a toy. Every verb the contract exposes is used the way a
|
|
/// renderer would use it: a device-local mesh arena filled through the staging
|
|
/// ring, per-frame instance and batch data written straight into mapped ring
|
|
/// memory, an offscreen render target whose colour is registered into the global
|
|
/// texture table and sampled by a later pass, block-compressed and uncompressed
|
|
/// textures with CPU-built and blit-built mip chains, multi-draw-indirect with
|
|
/// <c>gl_DrawID</c> selecting per-draw batch data, a second pipeline with
|
|
/// line-list topology bound mid-pass, dynamic cull/front-face/depth-write, push
|
|
/// constants, GPU timer scopes, and an MSAA colour attachment resolving into the
|
|
/// swapchain image.</para>
|
|
///
|
|
/// <para><b>Deliberately asymmetric.</b> The layout has a distinct marker in
|
|
/// each quadrant and nothing is mirror-symmetric in either axis, because the one
|
|
/// thing a uniform clear could never prove is that the negative-viewport Y flip
|
|
/// and the capture path agree. Slice V5's screenshot was uniform and its
|
|
/// orientation was right "by construction"; this one has to be right by
|
|
/// inspection, and a wrong flip is unmissable.</para>
|
|
/// </summary>
|
|
internal sealed class VulkanRhiScene : IDisposable
|
|
{
|
|
/// <summary>The quadrant marker colours, in the order the layout places them.</summary>
|
|
internal static readonly (string Corner, uint Rgba)[] QuadrantMarkers =
|
|
[
|
|
("top-left", 0xE04040FFu),
|
|
("top-right", 0x40E040FFu),
|
|
("bottom-left", 0x4060E0FFu),
|
|
("bottom-right", 0xF0F0F0FFu),
|
|
];
|
|
|
|
private const int OffscreenExtent = 128;
|
|
|
|
private readonly VulkanGpuDevice _device;
|
|
private readonly IGpuBuffer _vertexArena;
|
|
private readonly IGpuBuffer _indexArena;
|
|
private readonly IGpuPipeline _meshPipeline;
|
|
private readonly IGpuPipeline _linePipeline;
|
|
private readonly IGpuRenderTarget _offscreen;
|
|
private readonly IGpuTexture _cardTexture;
|
|
private readonly IGpuTexture _compressedTexture;
|
|
private readonly List<IDisposable> _owned = [];
|
|
|
|
private readonly GpuTextureSlot _cardSlot;
|
|
private readonly GpuTextureSlot _compressedSlot;
|
|
private GpuTextureSlot _offscreenSlot = GpuTextureSlot.Unassigned;
|
|
|
|
private readonly uint _quadIndexCount;
|
|
private readonly uint _lineVertexCount;
|
|
private readonly uint _lineFirstVertex;
|
|
|
|
private bool _disposed;
|
|
|
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
|
private struct Vertex(Vector3 position, Vector3 normal, Vector2 texCoord)
|
|
{
|
|
public Vector3 Position = position;
|
|
public Vector3 Normal = normal;
|
|
public Vector2 TexCoord = texCoord;
|
|
}
|
|
|
|
/// <summary>std430 <c>BatchData</c> at the pinned 16-byte stride.</summary>
|
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
|
private struct BatchData
|
|
{
|
|
public uint TextureIndex;
|
|
public uint TextureLayer;
|
|
public uint Tint;
|
|
public uint Pad;
|
|
}
|
|
|
|
/// <summary>The indirect command layout <c>vkCmdDrawIndexedIndirect</c> reads.</summary>
|
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
|
private struct DrawIndexedIndirectCommand
|
|
{
|
|
public uint IndexCount;
|
|
public uint InstanceCount;
|
|
public uint FirstIndex;
|
|
public int VertexOffset;
|
|
public uint FirstInstance;
|
|
}
|
|
|
|
internal VulkanRhiScene(VulkanGpuDevice device, int sampleCount)
|
|
{
|
|
_device = device ?? throw new ArgumentNullException(nameof(device));
|
|
SampleCount = Math.Max(1, sampleCount);
|
|
|
|
// ── the mesh arena: device-local, filled through the staging ring ──
|
|
Vertex[] vertices = BuildVertices(out ushort[] indices, out _quadIndexCount, out _lineFirstVertex, out _lineVertexCount);
|
|
_vertexArena = device.CreateBuffer(new GpuBufferDescription(
|
|
"vk-scene-vertex-arena",
|
|
vertices.Length * Marshal.SizeOf<Vertex>(),
|
|
GpuBufferUsage.Vertex | GpuBufferUsage.TransferDestination,
|
|
GpuMemoryResidency.DeviceLocal));
|
|
_indexArena = device.CreateBuffer(new GpuBufferDescription(
|
|
"vk-scene-index-arena",
|
|
indices.Length * sizeof(ushort),
|
|
GpuBufferUsage.Index | GpuBufferUsage.TransferDestination,
|
|
GpuMemoryResidency.DeviceLocal));
|
|
_vertexArena.Upload(0, MemoryMarshal.AsBytes<Vertex>(vertices));
|
|
_indexArena.Upload(0, MemoryMarshal.AsBytes<ushort>(indices));
|
|
_owned.Add(_vertexArena);
|
|
_owned.Add(_indexArena);
|
|
|
|
// ── textures: one uncompressed array with a blit chain, one BC1 with a
|
|
// CPU chain. Both paths matter; only one of them can use the GPU.
|
|
_cardTexture = BuildOrientationCard(device);
|
|
_compressedTexture = BuildCompressedCheckerboard(device);
|
|
_owned.Add(_cardTexture);
|
|
_owned.Add(_compressedTexture);
|
|
|
|
IGpuSampler sampler = device.CreateSampler(GpuSamplerDescription.WorldClamp);
|
|
_cardSlot = device.RegisterTexture(_cardTexture, sampler);
|
|
_compressedSlot = device.RegisterTexture(_compressedTexture, sampler);
|
|
|
|
_offscreen = device.CreateRenderTarget(new GpuRenderTargetDescription(
|
|
"vk-scene-offscreen",
|
|
OffscreenExtent,
|
|
OffscreenExtent,
|
|
GpuTextureFormat.Rgba8UnormRenderTarget,
|
|
DepthFormat: null,
|
|
SampleCount: 1));
|
|
_owned.Add(_offscreen);
|
|
|
|
_meshPipeline = device.CreatePipeline(new GpuPipelineDescription
|
|
{
|
|
Name = "vk-scene-mesh",
|
|
Shaders = new GpuShaderSet("vk_probe"),
|
|
VertexLayout = GpuVertexLayout.WorldMesh,
|
|
Topology = GpuPrimitiveTopology.TriangleList,
|
|
Blend = GpuBlendMode.StraightAlpha,
|
|
Depth = GpuDepthState.OpaqueDefault,
|
|
Cull = GpuCullMode.None,
|
|
SampleCount = SampleCount,
|
|
});
|
|
_linePipeline = device.CreatePipeline(new GpuPipelineDescription
|
|
{
|
|
Name = "vk-scene-line",
|
|
Shaders = new GpuShaderSet("vk_probe"),
|
|
VertexLayout = GpuVertexLayout.WorldMesh,
|
|
Topology = GpuPrimitiveTopology.LineList,
|
|
Blend = GpuBlendMode.None,
|
|
Depth = GpuDepthState.Disabled,
|
|
Cull = GpuCullMode.None,
|
|
SampleCount = SampleCount,
|
|
});
|
|
_owned.Add(_meshPipeline);
|
|
_owned.Add(_linePipeline);
|
|
|
|
// The offscreen pass needs its own pipeline: its target is
|
|
// single-sampled, and sample count is baked into a pipeline rather than
|
|
// dynamic.
|
|
OffscreenPipeline = device.CreatePipeline(new GpuPipelineDescription
|
|
{
|
|
Name = "vk-scene-offscreen",
|
|
Shaders = new GpuShaderSet("vk_probe"),
|
|
VertexLayout = GpuVertexLayout.WorldMesh,
|
|
Topology = GpuPrimitiveTopology.TriangleList,
|
|
Blend = GpuBlendMode.None,
|
|
Depth = GpuDepthState.Disabled,
|
|
Cull = GpuCullMode.None,
|
|
SampleCount = 1,
|
|
});
|
|
_owned.Add(OffscreenPipeline);
|
|
}
|
|
|
|
internal int SampleCount { get; }
|
|
|
|
internal IGpuPipeline OffscreenPipeline { get; }
|
|
|
|
/// <summary>Records one complete frame: offscreen pass, then the backbuffer pass.</summary>
|
|
internal void Render(IGpuFrame frame, uint width, uint height, double seconds)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(frame);
|
|
|
|
RenderOffscreen(frame);
|
|
RenderMain(frame, width, height, seconds);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Fills the offscreen target with a flat quad and registers its colour into
|
|
/// the texture table. Registration happens after the first pass has run so
|
|
/// the image is in a defined layout; the slot is then stable for the process.
|
|
/// </summary>
|
|
private void RenderOffscreen(IGpuFrame frame)
|
|
{
|
|
using (IGpuPassEncoder encoder = frame.BeginPass(new GpuPassDescription
|
|
{
|
|
Name = "vk-scene-offscreen",
|
|
Color = new GpuColorAttachment(
|
|
_offscreen,
|
|
GpuLoadOp.Clear,
|
|
GpuStoreOp.Store,
|
|
new Vector4(0.12f, 0.02f, 0.24f, 1f)),
|
|
Depth = null,
|
|
SampleCount = 1,
|
|
}))
|
|
{
|
|
using IDisposable _ = encoder.BeginTimerScope("offscreen");
|
|
encoder.BindPipeline(OffscreenPipeline);
|
|
|
|
GpuPushConstants constants = GpuPushConstants.Default;
|
|
// Straight to NDC: the offscreen pass is a flat 2-D fill, so an
|
|
// identity transform is the whole camera.
|
|
constants.LightingMode = 1;
|
|
encoder.SetPushConstants(constants);
|
|
|
|
WriteInstances(frame, encoder, [Matrix4x4.CreateScale(0.75f)]);
|
|
WriteBatches(frame, encoder, [new BatchData { Tint = 0xFFC020FFu }]);
|
|
BindArena(encoder);
|
|
encoder.DrawIndexed(6, 1, 0, 0, 0);
|
|
}
|
|
|
|
if (!_offscreenSlot.IsAssigned)
|
|
{
|
|
_offscreenSlot = _device.RegisterTexture(
|
|
_offscreen.ColorTexture,
|
|
_device.CreateSampler(GpuSamplerDescription.UiNearest));
|
|
}
|
|
}
|
|
|
|
private void RenderMain(IGpuFrame frame, uint width, uint height, double seconds)
|
|
{
|
|
using IGpuPassEncoder encoder = frame.BeginPass(GpuPassDescription.BackbufferClear(
|
|
"vk-scene-main",
|
|
new Vector4(0.043f, 0.075f, 0.153f, 1f),
|
|
SampleCount));
|
|
using IDisposable scope = encoder.BeginTimerScope("main");
|
|
|
|
float aspect = height == 0 ? 1f : width / (float)height;
|
|
// Matrix4x4.CreatePerspectiveFieldOfView is D3D convention with NDC z in
|
|
// [0,1] — already Vulkan's, which is exactly why plan §4.7 concludes no
|
|
// projection rework is needed anywhere.
|
|
Matrix4x4 projection = Matrix4x4.CreatePerspectiveFieldOfView(
|
|
MathF.PI / 3f,
|
|
aspect,
|
|
0.1f,
|
|
50f);
|
|
Matrix4x4 view = Matrix4x4.CreateLookAt(
|
|
new Vector3(0f, 0f, 3.4f),
|
|
Vector3.Zero,
|
|
Vector3.UnitY);
|
|
|
|
GpuPushConstants constants = GpuPushConstants.Default;
|
|
constants.ViewProjection = view * projection;
|
|
constants.LightingMode = 0;
|
|
|
|
encoder.BindPipeline(_meshPipeline);
|
|
encoder.SetPushConstants(constants);
|
|
encoder.SetCullMode(GpuCullMode.None);
|
|
encoder.SetDepthWrite(true);
|
|
|
|
// Four quadrant markers plus one wide backdrop. Nothing here is
|
|
// mirror-symmetric, on purpose.
|
|
float wobble = (float)Math.Sin(seconds) * 0.05f;
|
|
Matrix4x4[] instances =
|
|
[
|
|
Matrix4x4.CreateScale(2.6f, 1.6f, 1f) * Matrix4x4.CreateTranslation(0f, 0f, -0.4f),
|
|
Matrix4x4.CreateScale(0.5f) * Matrix4x4.CreateTranslation(-1.0f, 0.55f + wobble, 0f),
|
|
Matrix4x4.CreateScale(0.36f) * Matrix4x4.CreateTranslation(0.95f, 0.55f, 0f),
|
|
Matrix4x4.CreateScale(0.28f) * Matrix4x4.CreateTranslation(-1.0f, -0.6f, 0f),
|
|
Matrix4x4.CreateScale(0.44f) * Matrix4x4.CreateTranslation(0.6f, -0.62f, 0f),
|
|
];
|
|
BatchData[] batches =
|
|
[
|
|
new BatchData { TextureIndex = _cardSlot.Index, Tint = 0xFFFFFFFFu },
|
|
new BatchData { TextureIndex = _compressedSlot.Index, Tint = QuadrantMarkers[0].Rgba },
|
|
new BatchData { TextureIndex = _offscreenSlot.Index, Tint = QuadrantMarkers[1].Rgba },
|
|
new BatchData { TextureIndex = _compressedSlot.Index, Tint = QuadrantMarkers[2].Rgba },
|
|
new BatchData { TextureIndex = _cardSlot.Index, Tint = QuadrantMarkers[3].Rgba },
|
|
];
|
|
|
|
WriteInstances(frame, encoder, instances);
|
|
WriteBatches(frame, encoder, batches);
|
|
BindArena(encoder);
|
|
|
|
// One multi-draw covering every quad, with gl_DrawID selecting the batch
|
|
// — the production dispatch shape, not a loop of single draws.
|
|
GpuRingAllocation commands = frame.AllocateRing(
|
|
instances.Length * Marshal.SizeOf<DrawIndexedIndirectCommand>(),
|
|
GpuRingUsage.Indirect);
|
|
Span<DrawIndexedIndirectCommand> span = commands.AsSpan<DrawIndexedIndirectCommand>();
|
|
for (int i = 0; i < instances.Length; i++)
|
|
{
|
|
span[i] = new DrawIndexedIndirectCommand
|
|
{
|
|
IndexCount = _quadIndexCount,
|
|
InstanceCount = 1,
|
|
FirstIndex = 0,
|
|
VertexOffset = 0,
|
|
// The per-group instance base — the reason
|
|
// drawIndirectFirstInstance is a required feature.
|
|
FirstInstance = (uint)i,
|
|
};
|
|
}
|
|
|
|
encoder.MultiDrawIndexedIndirect(
|
|
commands.Buffer,
|
|
commands.OffsetBytes,
|
|
(uint)instances.Length,
|
|
(uint)Marshal.SizeOf<DrawIndexedIndirectCommand>());
|
|
|
|
// A second pipeline bound mid-pass. Because every pipeline shares one
|
|
// layout, the descriptor sets and push constants above survive this.
|
|
constants.LightingMode = 1;
|
|
encoder.BindPipeline(_linePipeline);
|
|
encoder.SetPushConstants(constants);
|
|
encoder.SetDepthWrite(false);
|
|
|
|
WriteInstances(frame, encoder, [Matrix4x4.Identity]);
|
|
WriteBatches(frame, encoder, [new BatchData { Tint = 0xFFE060FFu }]);
|
|
BindArena(encoder);
|
|
encoder.Draw(_lineVertexCount, 1, _lineFirstVertex, 0);
|
|
}
|
|
|
|
private void BindArena(IGpuPassEncoder encoder)
|
|
{
|
|
encoder.BindVertexBuffer(_vertexArena, 0);
|
|
encoder.BindIndexBuffer(_indexArena, 0, GpuIndexType.UInt16);
|
|
}
|
|
|
|
private static void WriteInstances(
|
|
IGpuFrame frame,
|
|
IGpuPassEncoder encoder,
|
|
ReadOnlySpan<Matrix4x4> transforms)
|
|
{
|
|
GpuRingAllocation allocation = frame.AllocateRing(
|
|
transforms.Length * Marshal.SizeOf<Matrix4x4>(),
|
|
GpuRingUsage.Storage);
|
|
transforms.CopyTo(allocation.AsSpan<Matrix4x4>());
|
|
encoder.BindStorageBuffer(
|
|
GpuBindingModel.StorageInstances,
|
|
allocation.Buffer,
|
|
allocation.OffsetBytes,
|
|
(uint)allocation.Data.Length);
|
|
}
|
|
|
|
private static void WriteBatches(
|
|
IGpuFrame frame,
|
|
IGpuPassEncoder encoder,
|
|
ReadOnlySpan<BatchData> batches)
|
|
{
|
|
GpuRingAllocation allocation = frame.AllocateRing(
|
|
batches.Length * GpuBindingModel.GpuBatchDataStrideBytes,
|
|
GpuRingUsage.Storage);
|
|
batches.CopyTo(allocation.AsSpan<BatchData>());
|
|
encoder.BindStorageBuffer(
|
|
GpuBindingModel.StorageBatches,
|
|
allocation.Buffer,
|
|
allocation.OffsetBytes,
|
|
(uint)allocation.Data.Length);
|
|
}
|
|
|
|
/// <summary>
|
|
/// One unit quad (indexed) followed by an asymmetric open line figure. Both
|
|
/// live in the same arena, which is what a real mesh arena does and what the
|
|
/// vertex-offset/first-vertex plumbing has to get right.
|
|
/// </summary>
|
|
private static Vertex[] BuildVertices(
|
|
out ushort[] indices,
|
|
out uint quadIndexCount,
|
|
out uint lineFirstVertex,
|
|
out uint lineVertexCount)
|
|
{
|
|
var vertices = new List<Vertex>
|
|
{
|
|
// Quad, counter-clockwise when viewed from +Z. v = 0 is the TOP
|
|
// edge, so texture row 0 lands at the top and the orientation card
|
|
// reads the same way in memory and on screen.
|
|
new(new Vector3(-0.5f, 0.5f, 0f), Vector3.UnitZ, new Vector2(0f, 0f)),
|
|
new(new Vector3(-0.5f, -0.5f, 0f), Vector3.UnitZ, new Vector2(0f, 1f)),
|
|
new(new Vector3(0.5f, -0.5f, 0f), Vector3.UnitZ, new Vector2(1f, 1f)),
|
|
new(new Vector3(0.5f, 0.5f, 0f), Vector3.UnitZ, new Vector2(1f, 0f)),
|
|
};
|
|
indices = [0, 1, 2, 0, 2, 3];
|
|
quadIndexCount = 6;
|
|
|
|
lineFirstVertex = (uint)vertices.Count;
|
|
// An "L" opening up and to the left, drawn as a line list: three
|
|
// segments, no symmetry in either axis.
|
|
Vector3[] path =
|
|
[
|
|
new(-1.5f, 0.9f, 0.2f),
|
|
new(-1.5f, -0.9f, 0.2f),
|
|
new(-1.5f, -0.9f, 0.2f),
|
|
new(0.2f, -0.9f, 0.2f),
|
|
new(0.2f, -0.9f, 0.2f),
|
|
new(0.2f, -0.4f, 0.2f),
|
|
];
|
|
foreach (Vector3 point in path)
|
|
vertices.Add(new Vertex(point, Vector3.UnitZ, Vector2.Zero));
|
|
lineVertexCount = (uint)path.Length;
|
|
|
|
return [.. vertices];
|
|
}
|
|
|
|
/// <summary>
|
|
/// A 16x16 RGBA orientation card: red top-left, green top-right, blue
|
|
/// bottom-left, white bottom-right, with a one-texel black frame. Its mips
|
|
/// come from <c>vkCmdBlitImage</c>, which is the path only uncompressed
|
|
/// formats can take.
|
|
/// </summary>
|
|
private static IGpuTexture BuildOrientationCard(VulkanGpuDevice device)
|
|
{
|
|
const int extent = 16;
|
|
int levels = VulkanTextureFormatMapping.FullMipLevelCount(extent, extent);
|
|
IGpuTexture texture = device.CreateTexture(new GpuTextureDescription(
|
|
"vk-scene-orientation-card",
|
|
GpuTextureKind.Texture2DArray,
|
|
GpuTextureFormat.Rgba8Unorm,
|
|
extent,
|
|
extent,
|
|
LayerCount: 1,
|
|
MipLevelCount: levels));
|
|
|
|
var pixels = new byte[extent * extent * 4];
|
|
for (int y = 0; y < extent; y++)
|
|
{
|
|
for (int x = 0; x < extent; x++)
|
|
{
|
|
bool top = y < extent / 2;
|
|
bool left = x < extent / 2;
|
|
uint colour = (top, left) switch
|
|
{
|
|
(true, true) => QuadrantMarkers[0].Rgba,
|
|
(true, false) => QuadrantMarkers[1].Rgba,
|
|
(false, true) => QuadrantMarkers[2].Rgba,
|
|
_ => QuadrantMarkers[3].Rgba,
|
|
};
|
|
bool frame = x == 0 || y == 0 || x == extent - 1 || y == extent - 1;
|
|
if (frame)
|
|
colour = 0x101010FFu;
|
|
|
|
int offset = ((y * extent) + x) * 4;
|
|
pixels[offset + 0] = (byte)(colour >> 24);
|
|
pixels[offset + 1] = (byte)(colour >> 16);
|
|
pixels[offset + 2] = (byte)(colour >> 8);
|
|
pixels[offset + 3] = (byte)colour;
|
|
}
|
|
}
|
|
|
|
texture.Upload(0, 0, pixels);
|
|
texture.GenerateMipChain();
|
|
return texture;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A BC1 checkerboard whose mip chain is built on the CPU, because Vulkan
|
|
/// cannot blit into a compressed image. This is the path every DAT surface
|
|
/// in the game will take.
|
|
/// </summary>
|
|
private static IGpuTexture BuildCompressedCheckerboard(VulkanGpuDevice device)
|
|
{
|
|
const int extent = 32;
|
|
int levels = VulkanTextureFormatMapping.FullMipLevelCount(extent, extent);
|
|
IGpuTexture texture = device.CreateTexture(new GpuTextureDescription(
|
|
"vk-scene-checkerboard",
|
|
GpuTextureKind.Texture2DArray,
|
|
GpuTextureFormat.Bc1Unorm,
|
|
extent,
|
|
extent,
|
|
LayerCount: 1,
|
|
MipLevelCount: levels));
|
|
|
|
var rgba = new byte[extent * extent * 4];
|
|
for (int y = 0; y < extent; y++)
|
|
{
|
|
for (int x = 0; x < extent; x++)
|
|
{
|
|
bool light = ((x / 4) + (y / 4)) % 2 == 0;
|
|
byte value = light ? (byte)0xFF : (byte)0x50;
|
|
int offset = ((y * extent) + x) * 4;
|
|
rgba[offset + 0] = value;
|
|
rgba[offset + 1] = value;
|
|
rgba[offset + 2] = value;
|
|
rgba[offset + 3] = 0xFF;
|
|
}
|
|
}
|
|
|
|
texture.Upload(0, 0, BlockCompressionCodec.EncodeLevel(GpuTextureFormat.Bc1Unorm, rgba, extent, extent));
|
|
foreach (BlockCompressionMipChain.Level level in
|
|
BlockCompressionMipChain.BuildFromRgba(GpuTextureFormat.Bc1Unorm, rgba, extent, extent, levels))
|
|
{
|
|
texture.Upload(level.MipLevel, 0, level.Data);
|
|
}
|
|
|
|
return texture;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (_disposed)
|
|
return;
|
|
_disposed = true;
|
|
for (int i = _owned.Count - 1; i >= 0; i--)
|
|
_owned[i].Dispose();
|
|
_owned.Clear();
|
|
}
|
|
}
|