feat(render): Campaign V slice V6b - Vulkan textures, mips, samplers and the descriptor table

The second of V6's three commits: everything the fragment stage samples. Plan
sections 4.3 (textures and mip generation) and 4.4 (descriptors).

The descriptor table is the piece that retires GL_ARB_bindless_texture. One
update-after-bind, partially-bound, variable-count combined-image-sampler array
of 16384; registration appends exactly one vkUpdateDescriptorSets and nothing is
written at draw time, so steady state is zero descriptor writes per frame. A
slot is a (view, sampler) pair, exactly like a bindless handle, which is why the
CPU data model needs no change at all - GpuTextureSlot already carries the index
and V2 already moved every batch onto it.

Eviction is retirement-gated and the slot is scrubbed on the way out. Returning
a slot the moment a texture is deleted would let the LRU alias a live draw onto
a new texture, so the release is filed through the ledger; and when it runs the
slot is first overwritten with the default 1x1 white. A stale view descriptor
sitting in a partially-bound array is legal right up until something reads it,
at which point it is a use-after-free with no error attached. Writing the dummy
makes that impossible rather than unlikely.

The CPU block-compression codec is the slice's other substantial piece, and it
exists because Vulkan cannot blit into a compressed image. DAT surfaces arrive
as DXT1/3/5 with no mips, so the chain has to be decoded, box filtered and
re-encoded here. That is not merely a substitute for the missing blit: the GL
path calls glGenerateMipmap on compressed array textures, whose result is
explicitly implementation-defined, so this is the first time that part of the
pipeline has had a defined answer.

Two properties matter more than quality, and both are tested. It is
deterministic - integer arithmetic end to end, endpoints from the block's
bounding box, nearest-palette selection, no dithering and no iterative fit -
because the offline pixel gate compares captures from separate processes and a
chain that varied run to run would make every textured surface look like a
regression. And it preserves BC1's one-bit cut-out: a block containing any texel
below the alpha threshold is encoded in three-colour mode, because retail's
foliage and grates ARE that mode and quantising those texels to an opaque colour
would fill in every leaf. Plan 4.3's escape hatch stands if quality ever trips a
gate: store the affected textures as RGBA8 and blit their mips.

Uncompressed images do take the blit chain, added to the upload queue. Each
source level moves to TRANSFER_SRC for its blit and back to TRANSFER_DST
afterwards; leaving the chain in mixed layouts would be one barrier cheaper and
would then force the batch's final shader-read transition to name a different
old layout per level, so ending every level the same way is what keeps that
transition one barrier per image.

The upload queue now records the layout each image is in on ENTRY to a batch
rather than always naming UNDEFINED. UNDEFINED lets the driver discard existing
contents, which is right for a fresh image and wrong for the incremental
array-layer fills that mirror ManagedGLTextureArray - discarding there would
erase every layer uploaded earlier.

Render targets are single-sampled per the contract and carry SAMPLED usage
alongside COLOR_ATTACHMENT, so a paperdoll or appraisal view can be registered
into the table and drawn by the retained UI the moment its pass ends.
VulkanBackbufferAttachments owns the two attachments the swapchain does not: the
multisampled colour scratch that resolves into the swapchain image, and the
transient depth/stencil. Both are TRANSIENT_ATTACHMENT because nothing reads
either after the frame. Stencil is not optional - issue #117's portal punch
needs the aspect, which is why the V5 gate prefers D32_SFLOAT_S8_UINT over a
depth-only format.

Every format stays UNORM, and that is the V3 audit's finding rather than a
default. The plan previously specified an sRGB swapchain "matching the GL
FramebufferSrgb contract"; that contract does not exist, the renderer is plain
UNORM end to end, and shipping _SRGB would have brightened every frame and
passed silently until V7.

VulkanPipelineLayouts is extracted from V5's capability probe rather than
written beside it, and the probe now calls it. The probe's whole value is
proving the layouts the live backend builds can be built on this device; two
similar-looking definitions would have quietly ended that the first time one of
them changed.

Gates: Release build clean, App suite 4037 passed / 3 skipped (4014 at V6a plus
23 new), offline pixel gate PASS against the parent baseline at a differing
fraction of 4.26e-05 - 24 pixels of 563,200, one above the campaign's recorded
15-23 same-commit noise band and about 23x under the 0.001 threshold, on a
commit that changes no GL code path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-07-28 07:49:40 +02:00
parent 37f3ed0498
commit 9eae496301
11 changed files with 2614 additions and 220 deletions

View file

@ -7,19 +7,69 @@ namespace AcDream.App.Rendering.Gpu.Vk;
/// pipelines and passes.
///
/// <para>Split into its own file because the three V6 commits divide along
/// exactly this line: V6a lands memory, buffers, rings and the frame timeline —
/// everything in <c>VulkanGpuDevice.cs</c> — while textures, the descriptor
/// table and render targets arrive at V6b and pipelines, passes and readback at
/// V6c. Until each lands, the corresponding contract member throws with the
/// slice named, rather than returning something that would fail later and
/// further away.</para>
/// exactly this line: V6a landed memory, buffers, rings and the frame timeline —
/// everything in <c>VulkanGpuDevice.cs</c> — V6b lands textures, samplers, the
/// descriptor table and render targets here, and pipelines, passes and readback
/// arrive at V6c. Until each lands, the corresponding contract member throws
/// with the slice named, rather than returning something that would fail later
/// and further away.</para>
/// </summary>
internal sealed unsafe partial class VulkanGpuDevice
{
private VulkanPipelineLayouts.Created? _layouts;
private VulkanTextureTable? _textureTable;
private VulkanBackbufferAttachments? _backbufferAttachments;
private VulkanGpuTexture? _defaultTexture;
private readonly Dictionary<GpuSamplerDescription, VulkanGpuSampler> _samplers = [];
private float _maxSamplerAnisotropy = 1f;
private void InitialiseResources(string? shaderSpirvDirectory, string? pipelineCacheDirectory)
{
_ = shaderSpirvDirectory;
_ = pipelineCacheDirectory;
_vk.GetPhysicalDeviceProperties(_physicalDevice, out PhysicalDeviceProperties properties);
_maxSamplerAnisotropy = properties.Limits.MaxSamplerAnisotropy;
_layouts = VulkanPipelineLayouts.Create(_vk, _device);
_textureTable = new VulkanTextureTable(
_vk,
_device,
_layouts.TextureTable,
Math.Min(GpuBindingModel.TextureTableCapacity, Capabilities.MaxTextureTableSlots));
_backbufferAttachments = new VulkanBackbufferAttachments(
_vk,
_device,
_allocator,
_debugNames,
DepthStencilFormat);
// The default slot is registered first so it is slot 0 and so the table
// has something defined to scrub evicted slots with. GpuTextureSlot
// documents Unassigned as a loud sentinel precisely so nothing silently
// resolves to slot 0 — this texture exists for the renderers that
// legitimately need a fallback and ask for it by name.
_defaultTexture = new VulkanGpuTexture(
_vk,
_device,
_allocator,
_uploads,
_flights,
_debugNames,
new GpuTextureDescription(
"vk-default-white",
GpuTextureKind.Texture2D,
GpuTextureFormat.Rgba8Unorm,
Width: 1,
Height: 1,
LayerCount: 1,
MipLevelCount: 1));
_defaultTexture.Upload(0, 0, [255, 255, 255, 255]);
var defaultSampler = (VulkanGpuSampler)CreateSampler(GpuSamplerDescription.UiNearest);
_textureTable.SetScrubTarget(_defaultTexture.View, defaultSampler.Handle);
DefaultTextureSlot = _textureTable.Register(_defaultTexture.View, defaultSampler.Handle);
}
private void BeginFrameResources(int slotIndex) => _ = slotIndex;
@ -32,27 +82,118 @@ internal sealed unsafe partial class VulkanGpuDevice
private void DisposeResources()
{
foreach (VulkanGpuSampler sampler in _samplers.Values)
sampler.Dispose();
_samplers.Clear();
_defaultTexture?.Dispose();
_defaultTexture = null;
_flights.DrainAll();
_backbufferAttachments?.Dispose();
_backbufferAttachments = null;
_textureTable?.Dispose();
_textureTable = null;
_layouts?.Destroy(_vk, _device);
_layouts = null;
}
/// <summary>The three shared descriptor set layouts and the one pipeline layout.</summary>
internal VulkanPipelineLayouts.Created Layouts =>
_layouts ?? throw new InvalidOperationException("The device's pipeline layouts have not been created.");
/// <summary>The global sampled-texture table (plan §4.4).</summary>
internal VulkanTextureTable TextureTable =>
_textureTable ?? throw new InvalidOperationException("The device's texture table has not been created.");
/// <summary>MSAA colour scratch and transient depth for the backbuffer pass.</summary>
internal VulkanBackbufferAttachments BackbufferAttachments =>
_backbufferAttachments ?? throw new InvalidOperationException("The backbuffer attachments have not been created.");
public GpuTextureSlot DefaultTextureSlot { get; private set; } = GpuTextureSlot.Unassigned;
/// <summary>
/// Matches the backbuffer pass's attachments to the swapchain's current
/// extent and the requested sample count. Called by the host after a
/// swapchain create or recreate, behind a device-idle wait.
/// </summary>
internal void ConfigureBackbufferAttachments(uint width, uint height, Format colorFormat, int sampleCount) =>
BackbufferAttachments.Configure(width, height, colorFormat, sampleCount);
public IGpuTexture CreateTexture(in GpuTextureDescription description)
{
ThrowIfDisposed();
return new VulkanGpuTexture(
_vk,
_device,
_allocator,
_uploads,
_flights,
_debugNames,
description,
sampleCount: 1,
renderTarget: VulkanTextureFormatMapping.IsRenderTarget(description.Format));
}
public IGpuSampler CreateSampler(in GpuSamplerDescription description)
{
ThrowIfDisposed();
if (_samplers.TryGetValue(description, out VulkanGpuSampler? existing))
return existing;
var created = new VulkanGpuSampler(
_vk,
_device,
_flights,
_debugNames,
description,
_maxSamplerAnisotropy);
_samplers.Add(description, created);
return created;
}
public IGpuRenderTarget CreateRenderTarget(in GpuRenderTargetDescription description)
{
ThrowIfDisposed();
return new VulkanGpuRenderTarget(
_vk,
_device,
_allocator,
_uploads,
_flights,
_debugNames,
description);
}
public GpuTextureSlot RegisterTexture(IGpuTexture texture, IGpuSampler sampler)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(texture);
ArgumentNullException.ThrowIfNull(sampler);
if (texture is not VulkanGpuTexture vulkanTexture)
throw new ArgumentException("The Vulkan backend can only register a Vulkan texture.", nameof(texture));
if (sampler is not VulkanGpuSampler vulkanSampler)
throw new ArgumentException("The Vulkan backend can only register a Vulkan sampler.", nameof(sampler));
return TextureTable.Register(vulkanTexture.View, vulkanSampler.Handle);
}
public void ReleaseTextureSlot(GpuTextureSlot slot)
{
ThrowIfDisposed();
if (!slot.IsAssigned)
throw new ArgumentException("Cannot release an unassigned texture slot.", nameof(slot));
// Deferred, and scrubbed to the default texture on the way out: a
// submitted-but-unretired frame may still sample this slot, so reusing
// it now would alias a live draw onto whatever texture claims it next.
VulkanTextureTable table = TextureTable;
_flights.Retire(() => table.ReleaseNow(slot));
}
public IGpuTimerPool Timers => throw NotYet("GPU timer scopes", "V6c");
public GpuTextureSlot DefaultTextureSlot => throw NotYet("the default 1x1 white table slot", "V6b");
public IGpuTexture CreateTexture(in GpuTextureDescription description) =>
throw NotYet($"texture creation ('{description.Name}')", "V6b");
public IGpuSampler CreateSampler(in GpuSamplerDescription description) =>
throw NotYet("sampler creation", "V6b");
public IGpuRenderTarget CreateRenderTarget(in GpuRenderTargetDescription description) =>
throw NotYet($"render targets ('{description.Name}')", "V6b");
public GpuTextureSlot RegisterTexture(IGpuTexture texture, IGpuSampler sampler) =>
throw NotYet("the global texture table", "V6b");
public void ReleaseTextureSlot(GpuTextureSlot slot) =>
throw NotYet("the global texture table", "V6b");
public IGpuPipeline CreatePipeline(GpuPipelineDescription description) =>
throw NotYet($"pipelines ('{description?.Name}')", "V6c");