Crafter.Graphics/tests/HeapDynamicIndexHit/main.cpp

405 lines
19 KiB
C++
Raw Normal View History

//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Regression test for dynamic descriptor-heap indexing in ray-tracing hit
// shaders. On NVIDIA 610.43.02, selecting a VK_EXT_descriptor_heap descriptor
// with a runtime index inside a hit shader lost the device, for storage
// buffers and sampled images alike (README, "Native RT limitation"), so the
// examples select hit-shader descriptors through spec constants. This renders
// two instances of one triangle whose closest-hit picks a storage buffer and a
// texture by a runtime index: instance 0 the same set everywhere, instance 1 a
// different set in every other pixel column, so neighbouring lanes of a wave
// select different descriptors. It reads the frame back and checks every
// pixel got its own set's buffer red and texture green.
//
// The fault fixed in NVIDIA 615.78.08, so on older NVIDIA drivers the test
// skips instead of aborting the suite. GPU-assisted validation hides the
// fault (examples/Sponza/README.md), so with CRAFTER_GRAPHICS_VALIDATION set
// the scene is also rendered in a child process with validation off; the
// validation check only means something with it set. Needs a live Wayland
// compositor and a Vulkan RT device; without RT it skips.
#include "vulkan/vulkan.h"
#include <cstddef>
#include <cstdio>
#include <cstdlib>
// PNG decode for the read-back frame. The library only compiles the writer
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
// (Window::CaptureNextFrame); STB_IMAGE_STATIC keeps the reader private to this file.
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#define STBI_ONLY_PNG
#include "../../lib/stb_image.h"
import Crafter.Graphics;
import Crafter.Math;
import std;
using namespace Crafter;
namespace fs = std::filesystem;
namespace {
int failures = 0;
void Check(bool ok, std::string_view what) {
std::println("{} {}", ok ? "PASS" : "FAIL", what);
// Flushed per line: a driver with the fault aborts the process from
// inside Render(), and the checks before it should still show.
std::fflush(stdout);
if (!ok) ++failures;
}
// The build places the compiled shaders next to the test binary, and the
// test runner's working directory is not that directory.
fs::path ExeDir() {
return fs::read_symlink("/proc/self/exe").parent_path();
}
int RunCommand(const std::string& cmd) {
int status = std::system(cmd.c_str());
if (status == -1) return -1;
return (status & 0x7f) == 0 ? ((status >> 8) & 0xff) : 128 + (status & 0x7f);
}
struct RGBA8 { std::uint8_t r, g, b, a; };
struct Frame {
int width = 0;
int height = 0;
std::vector<std::uint8_t> rgba;
std::array<std::uint8_t, 3> At(int x, int y) const {
const std::size_t i = (static_cast<std::size_t>(y) * width + x) * 4;
return { rgba[i], rgba[i + 1], rgba[i + 2] };
}
};
Frame LoadFrame(const fs::path& path) {
Frame frame;
int channels = 0;
stbi_uc* pixels = stbi_load(path.string().c_str(), &frame.width, &frame.height, &channels, STBI_rgb_alpha);
if (pixels != nullptr) {
frame.rgba.assign(pixels, pixels + static_cast<std::size_t>(frame.width) * frame.height * 4);
stbi_image_free(pixels);
}
return frame;
}
bool Near(std::array<std::uint8_t, 3> pixel, std::array<std::uint8_t, 3> expected) {
for (std::size_t c = 0; c < 3; ++c) {
if (std::abs(static_cast<int>(pixel[c]) - static_cast<int>(expected[c])) > 8) return false;
}
return true;
}
void CheckPixel(const Frame& frame, int x, int y, std::array<std::uint8_t, 3> expected, std::string_view what) {
const std::array<std::uint8_t, 3> pixel = frame.At(x, y);
Check(Near(pixel, expected), std::format("{} at ({}, {}) is ({}, {}, {}), expected ({}, {}, {})",
what, x, y, pixel[0], pixel[1], pixel[2], expected[0], expected[1], expected[2]));
}
// The pixel column world x on the triangles' plane (z = 100, 400 in front of
// the camera) lands in, for the raygen's 60° vertical field of view.
int FrameX(float worldX, const Frame& frame) {
const float aspect = static_cast<float>(frame.width) / static_cast<float>(frame.height);
const float ndc = worldX / (400.0f * aspect * std::tan(std::numbers::pi_v<float> / 6.0f));
return static_cast<int>((0.5f + ndc * 0.5f) * static_cast<float>(frame.width));
}
// Spec constants of the closest-hit, matching dynidx-closesthit.glsl.
struct HitConstants {
std::uint16_t bufferStart;
std::uint16_t pad;
std::uint32_t textureBase;
std::uint32_t colourBase;
};
// What each descriptor set holds: the red its buffer gives and the green its
// texture gives.
constexpr std::array<float, 2> bufferRed = {1.0f, 0.5f};
constexpr std::array<std::uint8_t, 2> textureGreen = {64, 191};
constexpr std::array<std::array<std::uint8_t, 3>, 2> setColour = {{{255, 64, 0}, {128, 191, 0}}};
// NVIDIA's proprietary driver packs its version into 10.8.8.6 bits.
std::tuple<std::uint32_t, std::uint32_t, std::uint32_t> NvidiaVersion() {
const std::uint32_t v = Device::deviceProperties.driverVersion;
return {(v >> 22) & 0x3ff, (v >> 14) & 0xff, (v >> 6) & 0xff};
}
// Renders the scene into `out` and checks the pixels. Device::Initialize has
// already run. Returns the number of failed checks.
int RenderScene(const fs::path& out) {
const int failuresBefore = failures;
Device::validationErrorCount = 0;
Window window(640, 360, "HeapDynamicIndexHit test");
VkCommandBuffer cmd = window.StartInit();
// Image slots: 0 = the frame's swapchain image, 1-2 = the textures.
// Buffer slots: 0 = the TLAS, 1-2 = the colour buffers. Sampler slot 0.
DescriptorHeapVulkan descriptorHeap;
descriptorHeap.Initialize(3, 3, 1);
VkSpecializationMapEntry raygenEntry = { .constantID = 0, .offset = 0, .size = sizeof(std::uint16_t) };
VkSpecializationInfo raygenSpec = {
.mapEntryCount = 1,
.pMapEntries = &raygenEntry,
.dataSize = sizeof(std::uint16_t),
.pData = &descriptorHeap.bufferStartElement,
};
HitConstants hitConstants = {
.bufferStart = descriptorHeap.bufferStartElement,
.pad = 0,
.textureBase = 1,
.colourBase = 1,
};
std::array<VkSpecializationMapEntry, 3> hitEntries {{
{ .constantID = 0, .offset = offsetof(HitConstants, bufferStart), .size = sizeof(std::uint16_t) },
{ .constantID = 1, .offset = offsetof(HitConstants, textureBase), .size = sizeof(std::uint32_t) },
{ .constantID = 2, .offset = offsetof(HitConstants, colourBase), .size = sizeof(std::uint32_t) },
}};
VkSpecializationInfo hitSpec = {
.mapEntryCount = static_cast<std::uint32_t>(hitEntries.size()),
.pMapEntries = hitEntries.data(),
.dataSize = sizeof(HitConstants),
.pData = &hitConstants,
};
const fs::path dir = ExeDir();
std::array<VulkanShader, 3> shaders{{
{dir / "dynidx-raygen.spv", "main", VK_SHADER_STAGE_RAYGEN_BIT_KHR, &raygenSpec},
{dir / "dynidx-miss.spv", "main", VK_SHADER_STAGE_MISS_BIT_KHR, nullptr},
{dir / "dynidx-closesthit.spv", "main", VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, &hitSpec},
}};
ShaderBindingTableVulkan shaderTable;
shaderTable.Init(shaders);
std::array<VkRayTracingShaderGroupCreateInfoKHR, 1> raygenGroups {{ {
.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR,
.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR,
.generalShader = 0, .closestHitShader = VK_SHADER_UNUSED_KHR,
.anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = VK_SHADER_UNUSED_KHR,
} }};
std::array<VkRayTracingShaderGroupCreateInfoKHR, 1> missGroups {{ {
.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR,
.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR,
.generalShader = 1, .closestHitShader = VK_SHADER_UNUSED_KHR,
.anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = VK_SHADER_UNUSED_KHR,
} }};
std::array<VkRayTracingShaderGroupCreateInfoKHR, 1> hitGroups {{ {
.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR,
.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR,
.generalShader = VK_SHADER_UNUSED_KHR, .closestHitShader = 2,
.anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = VK_SHADER_UNUSED_KHR,
} }};
PipelineRTVulkan pipeline;
pipeline.Init(cmd, raygenGroups, missGroups, hitGroups, shaderTable);
// One triangle, two instances 100 units either side of the centre line.
Mesh triangleMesh;
std::array<Vector<float, 3, 3>, 3> verts {{{-75, -75, 100}, {0, 75, 100}, {75, -75, 100}}};
std::array<std::uint32_t, 3> index {{2, 1, 0}};
triangleMesh.Build(verts, index, cmd);
std::array<RenderingElement3D, 2> renderers{};
for (std::uint32_t i = 0; i < renderers.size(); ++i) {
renderers[i].instance = {
.instanceCustomIndex = i,
.mask = 0xFF,
.instanceShaderBindingTableRecordOffset = 0,
.flags = VK_GEOMETRY_INSTANCE_FORCE_OPAQUE_BIT_KHR,
.accelerationStructureReference = triangleMesh.blasAddr,
};
MatrixRowMajor<float, 4, 3, 1>::Translation(i == 0 ? -100.0f : 100.0f, 0.0f, 0.0f)
.Store(reinterpret_cast<float*>(renderers[i].instance.transform.matrix));
RenderingElement3D::Add(&renderers[i]);
}
for (std::uint32_t f = 0; f < Window::numFrames; ++f) RenderingElement3D::BuildTLAS(cmd, f);
// Per descriptor set: a 2x2 texture whose green the hit shader reads, and
// a one-vec4 buffer whose red it reads.
std::array<Image2D<RGBA8>, 2> textures;
std::array<VulkanBuffer<float, true>, 2> colourBuffers;
for (std::size_t i = 0; i < textures.size(); ++i) {
textures[i].Create(2, 2, 1, cmd, VK_FORMAT_R8G8B8A8_UNORM,
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
for (std::size_t p = 0; p < 4; ++p) textures[i].buffer.value[p] = {0, textureGreen[i], 0, 255};
textures[i].Update(cmd, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
colourBuffers[i].Create(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 4);
colourBuffers[i].value[0] = bufferRed[i];
colourBuffers[i].value[1] = 0.0f;
colourBuffers[i].value[2] = 0.0f;
colourBuffers[i].value[3] = 1.0f;
colourBuffers[i].FlushDevice();
}
window.FinishInit();
auto imgSlots = descriptorHeap.AllocateImageSlots(3);
auto bufSlots = descriptorHeap.AllocateBufferSlots(3);
auto samplerSlots = descriptorHeap.AllocateSamplerSlots(1);
std::array<VkImageViewCreateInfo, 2> textureViews{};
std::array<VkImageDescriptorInfoEXT, 2> textureInfos{};
std::array<VkDeviceAddressRangeKHR, 2> colourRanges{};
for (std::size_t i = 0; i < 2; ++i) {
textureViews[i] = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.image = textures[i].image,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = VK_FORMAT_R8G8B8A8_UNORM,
.subresourceRange = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0,
.levelCount = 1, .baseArrayLayer = 0, .layerCount = 1 },
};
textureInfos[i] = {
.sType = VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT,
.pView = &textureViews[i],
.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
colourRanges[i] = { .address = colourBuffers[i].address, .size = 4 * sizeof(float) };
}
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
// The output image at image slot 0 is the swapchain's, which the window
// writes every frame with the image that frame draws into.
descriptorHeap.AddSwapchainSlot(imgSlots.firstElement, window);
{
std::array<VkDeviceAddressRangeKHR, Window::numFrames> tlasRanges{};
std::vector<VkResourceDescriptorInfoEXT> resources;
std::vector<VkHostAddressRangeEXT> destinations;
auto add = [&](std::uint32_t f, VkResourceDescriptorInfoEXT resource, std::uint32_t offset, std::uint32_t size) {
resources.push_back(resource);
destinations.push_back({ .address = descriptorHeap.resourceHeap[f].value + offset, .size = size });
};
const std::uint32_t imageSize = Device::descriptorHeapProperties.imageDescriptorSize;
const std::uint32_t bufferSize = Device::descriptorHeapProperties.bufferDescriptorSize;
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
tlasRanges[f] = { .address = RenderingElement3D::tlases[f].address };
add(f, { .sType = VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT,
.type = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR,
.data = { .pAddressRange = &tlasRanges[f] } },
descriptorHeap.BufferByteOffset(bufSlots.firstElement), bufferSize);
for (std::uint16_t i = 0; i < 2; ++i) {
add(f, { .sType = VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT,
.type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
.data = { .pImage = &textureInfos[i] } },
descriptorHeap.ImageByteOffset(imgSlots.firstElement + 1 + i), imageSize);
add(f, { .sType = VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT,
.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
.data = { .pAddressRange = &colourRanges[i] } },
descriptorHeap.BufferByteOffset(bufSlots.firstElement + 1 + i), bufferSize);
}
}
Device::vkWriteResourceDescriptorsEXT(Device::device, static_cast<std::uint32_t>(resources.size()),
resources.data(), destinations.data());
for (auto& heap : descriptorHeap.resourceHeap) heap.FlushDevice();
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
}
VkSamplerCreateInfo samplerInfo = {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.magFilter = VK_FILTER_NEAREST,
.minFilter = VK_FILTER_NEAREST,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.maxLod = VK_LOD_CLAMP_NONE,
};
std::array<VkSamplerCreateInfo, Window::numFrames> samplerInfos{};
std::array<VkHostAddressRangeEXT, Window::numFrames> samplerDestinations{};
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
samplerInfos[f] = samplerInfo;
samplerDestinations[f] = {
.address = descriptorHeap.samplerHeap[f].value + descriptorHeap.SamplerByteOffset(samplerSlots.firstElement),
.size = Device::descriptorHeapProperties.samplerDescriptorSize,
};
}
Device::vkWriteSamplerDescriptorsEXT(Device::device, Window::numFrames, samplerInfos.data(), samplerDestinations.data());
for (auto& heap : descriptorHeap.samplerHeap) heap.FlushDevice();
window.descriptorHeap = &descriptorHeap;
RTPass rtPass(&pipeline);
window.passes.push_back(&rtPass);
// More frames than are in flight, so every per-frame heap copy is read at
// least once. A device loss here throws out of Render().
for (int i = 0; i < Window::numFrames * 2; ++i) window.Render();
Device::CheckVkResult(vkQueueWaitIdle(Device::queue));
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
window.CaptureNextFrame(out);
window.Render();
if (std::getenv("CRAFTER_GRAPHICS_VALIDATION") != nullptr) {
Check(Device::validationErrorCount == 0,
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
std::format("no Vulkan validation errors while rendering and capturing ({} seen)", Device::validationErrorCount));
}
Device::CheckVkResult(vkQueueWaitIdle(Device::queue));
const Frame frame = LoadFrame(out);
Check(!frame.rgba.empty(), "the frame was read back");
if (!frame.rgba.empty()) {
const int y = frame.height / 2;
// An even column then the odd one next to it, in each triangle.
const int left = FrameX(-100.0f, frame) & ~1;
const int right = FrameX(100.0f, frame) & ~1;
CheckPixel(frame, left, y, setColour[0], "instance 0, even column (set 0)");
CheckPixel(frame, left + 1, y, setColour[0], "instance 0, odd column (set 0)");
CheckPixel(frame, right, y, setColour[1], "instance 1, even column (set 1)");
CheckPixel(frame, right + 1, y, setColour[0], "instance 1, odd column (set 0)");
CheckPixel(frame, frame.width / 2, y, {0, 0, 255}, "miss between the triangles");
CheckPixel(frame, frame.width / 20, frame.height / 10, {0, 0, 255}, "miss in the corner");
}
for (RenderingElement3D& renderer : renderers) RenderingElement3D::Remove(&renderer);
return failures - failuresBefore;
}
// A fresh directory for the read-back frames, so a frame left by an earlier
// run can't stand in for one this run failed to write.
fs::path OutputDir() {
const fs::path dir = fs::temp_directory_path() / "crafter-heap-dynamic-index-hit";
std::error_code ec;
fs::remove_all(dir, ec);
fs::create_directories(dir);
return dir;
}
} // namespace
int main(int argc, char** argv) {
feat(device): applications ask for the device features their shaders use Device - Device::Initialize(required, optional) takes DeviceFeatures, the five core feature structs vulkan10 to vulkan14. The library enables only what its own shaders and code use. Device::enabledFeatures says what was enabled, supportedFeatures what the GPU has, apiVersion the version in use. - shaderInt16, shaderFloat16, storageBuffer16BitAccess, scalarBlockLayout and the uniform-buffer, storage-buffer and storage-image non-uniform indexing bits are no longer enabled for everyone. An application whose shaders take uint16_t spec constants passes {.vulkan10 = {.shaderInt16 = VK_TRUE}}. scalarBlockLayout stays on with the NVIDIA workaround, whose TLAS address may sit in a struct's tail padding. - Every GPU is weighed before one is chosen: Vulkan 1.3, the swapchain and, below 1.4, maintenance5 extensions, the library's needs, the required features. One that can't run the application is skipped, saying why when it ranks higher. A CPU device runs it only when nothing else is listed, and CRAFTER_GRAPHICS_DEVICE never falls back. A GPU two drivers both list is tried through each. - When no GPU qualifies, Initialize throws naming each GPU's gaps. It destroys the instance it made, before any Wayland connection, so it can be called again asking for less. - maintenance5 is vulkan14's on a 1.4 GPU and VK_KHR_maintenance5's below. CRAFTER_GRAPHICS_NO_VULKAN_1_4 runs as a 1.3 application, to exercise that path on a 1.4 GPU. - VK_KHR_spirv_1_4 and VK_KHR_shader_float_controls, core since 1.2, are no longer enabled, nor VK_EXT_shader_atomic_float, which was enabled without its feature struct. memoryDecompression's feature bit is queried before it is enabled. Shaders - VulkanShader checks a module's capabilities, declared directly or implicitly, against the enabled core features, the GPU's subgroup operations and the optional groups, and throws naming the field to pass, or saying the GPU lacks it. The tables are generated from vk.xml and SPIR-V's grammar. - WorkaroundNvidiaAS::Patch sized a row-major matrix push member by its columns, so the TLAS address could land inside it. Window - The swapchain format is one whose own feature flags allow storage reads and writes without a format, which since Vulkan 1.3 each format says for itself; shaderStorageImageRead/WriteWithoutFormat are no longer required. Tests - DeviceFeatures: ResolveFeatures, ChooseDevice and CheckShaderCapabilities, without a GPU. - FeatureRequests: required and optional features end to end, the 1.3 path, and a retry after a refusal. - PushConstantRewrite: a row-major mat3x4 push member. - HeapASRead, HeapDynamicIndexHit, RTPassPushData and the ray-tracing examples ask for the features their shaders use. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 06:40:02 +01:00
// The shaders take heap slots as uint16_t spec constants, and the
// closest-hit indexes buffers non-uniformly.
Device::Initialize({
.vulkan10 = {.shaderInt16 = VK_TRUE},
.vulkan12 = {.shaderStorageBufferArrayNonUniformIndexing = VK_TRUE},
});
if (!Device::rayTracingSupported) {
std::println("SKIP no Vulkan ray-tracing device");
return 77;
}
if (Device::driverProperties.driverID == VK_DRIVER_ID_NVIDIA_PROPRIETARY
&& NvidiaVersion() < std::tuple(615u, 78u, 8u)) {
const auto [major, minor, patch] = NvidiaVersion();
std::println("SKIP NVIDIA {}.{:02}.{:02} loses the device on this (fixed in 615.78.08)", major, minor, patch);
return 77;
}
// `--render <png>`: the child run, rendering as configured.
if (argc == 3 && std::string_view(argv[1]) == "--render") {
RenderScene(argv[2]);
return failures == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
const fs::path dir = OutputDir();
if (std::getenv("CRAFTER_GRAPHICS_VALIDATION") != nullptr) {
const fs::path exe = fs::read_symlink("/proc/self/exe");
const int exit = RunCommand(std::format("env -u CRAFTER_GRAPHICS_VALIDATION '{}' --render '{}'",
exe.string(), (dir / "unvalidated.png").string()));
Check(exit == 0, std::format("the scene renders with validation off (exit {})", exit));
}
RenderScene(dir / "frame.png");
std::println("{}", failures == 0 ? "all checks passed" : "check(s) failed");
return failures == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}