载入中...
搜索中...
未找到
GraphicsGpuDriven.cpp
浏览该文件的文档.
1// Vulkan backend implementation — GPU-driven rendering (stages 0-3).
2//
3// Bindless resources, GPU tables, per-frame arena, CPU/GPU indirect draws,
4// HZB + frustum cull chain, visibility-buffer pass, fullscreen resolve and
5// VirtualGeometry hardware-raster integration. Kept in its own TU (matching
6// dev's split-graphics-backend layout) so the feature stays reviewable.
7
8#include "common/Assert.h"
10#include "graphics/Light.h"
11#include "graphics/Material.h"
14#include "graphics/Shadow.h"
18
19#include <SDL2/SDL.h>
20
21#include <algorithm>
22#include <array>
23#include <cmath>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <functional>
28#include <stdexcept>
29#include <string>
30#include <vector>
31
32#include "common/Exception.h"
34#include "zeroerr/assert.h"
35
36#include <glm/gtc/matrix_transform.hpp>
37
38#include "graphics/shaders/gpu_emit_comp_spv.inc"
39#include "graphics/shaders/vg_main_cull_comp_spv.inc"
40#include "graphics/shaders/hzb_build_comp_spv.inc"
41#include "graphics/shaders/gpu_cull_comp_spv.inc"
42#include "graphics/shaders/mesh3d_gpudriven_vert_spv.inc"
43#include "graphics/shaders/mesh3d_gpudriven_frag_spv.inc"
44#include "graphics/shaders/mesh3d_gbuffer_vis_vert_spv.inc"
45#include "graphics/shaders/mesh3d_gbuffer_vis_frag_spv.inc"
46#include "graphics/shaders/mesh3d_gbuffer_vgvis_vert_spv.inc"
47#include "graphics/shaders/mesh3d_gbuffer_vgvis_frag_spv.inc"
48#include "graphics/shaders/resolve_vis_vert_spv.inc"
49#include "graphics/shaders/resolve_vis_frag_spv.inc"
50
51namespace eve::graphics::vulkan {
52
54 return gpuDrivenEnabled_ && gpuDrivenCaps_.gpuDrivenCullAvailable() &&
55 renderControl_ && renderControl_->isEnabled("visResolve") &&
56 sceneColorSamples == vk::SampleCountFlagBits::e1;
57}
58
59vk::DescriptorSet Graphics::bindlessSetForFrame() const {
60 if (bindlessSets_.empty()) return nullptr;
61 return bindlessSets_[currentFrameSlot() % bindlessSets_.size()];
62}
63
64void Graphics::initGpuDrivenResources() {
65 if (!gpuDrivenCaps_.gpuDrivenAvailable()) return;
66 frameArenas_.resize(frameSlotCount());
67 for (auto &arena : frameArenas_) {
68 arena.ensure(device, 8u << 20,
69 vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eStorageBuffer |
70 vk::BufferUsageFlagBits::eIndirectBuffer | vk::BufferUsageFlagBits::eTransferDst);
71 }
72 createBindlessSet();
73 createMesh3DGpuDrivenPipeline();
74}
75
76void Graphics::createGpuDrivenVisResources(int width, int height) {
77 if (!gpuDrivenCaps_.gpuDrivenAvailable()) return;
78 if (gbufferVisRenderPass || gbufferSlots.empty()) return;
79 const uint32_t w = uint32_t(width);
80 const uint32_t h = uint32_t(height);
81 const vk::Format colorFmt = pickGBufferColorFormat(device);
82 const vk::Format depthFmt = vk::Format::eD32Sfloat;
83 const vk::Format visIDFmt = vk::Format::eR32G32Uint;
84 const vk::Format visBaryFmt = vk::Format::eR16G16Sfloat;
85
86 gbufferVisRenderPass =
87 device.createRenderPass()
88 .addSampledColorAttachment(colorFmt)
89 .addSampledColorAttachment(colorFmt)
90 .addSampledColorAttachment(colorFmt)
91 .addSampledColorAttachment(visIDFmt)
92 .addSampledColorAttachment(visBaryFmt)
93 .addSampledDepthAttachment(depthFmt)
94 .addSubpass(vkb::SubpassBuilder()
95 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
96 .addAttachmentRef(1, vk::ImageLayout::eColorAttachmentOptimal)
97 .addAttachmentRef(2, vk::ImageLayout::eColorAttachmentOptimal)
98 .addAttachmentRef(3, vk::ImageLayout::eColorAttachmentOptimal)
99 .addAttachmentRef(4, vk::ImageLayout::eColorAttachmentOptimal)
100 .setDepthStencilAttachment(
101 5, vk::ImageLayout::eDepthStencilAttachmentOptimal))
102 .addExternalShaderReadDependencies()
103 .build();
104 for (auto &slot : gbufferSlots) {
105 slot.visFramebuffer = gbufferVisRenderPass.createFramebuffer(
106 device, w, h,
107 {slot.normal.asAttachment(), slot.depthColor.asAttachment(), slot.albedo.asAttachment(),
108 slot.visID.asAttachment(), slot.visBary.asAttachment(), slot.depth.asAttachment()});
109 }
110
111 if (!mesh3dGpuDrivenPipelineLayout) return;
112 // Instance vis pass: no vertex input (fetches from the pooled buffers via
113 // gl_VertexIndex); draws non-indexed with the cull chain's NI commands.
114 {
115 std::vector<uint32_t> visVert(mesh3d_gbuffer_vis_vert_spv,
116 mesh3d_gbuffer_vis_vert_spv +
117 mesh3d_gbuffer_vis_vert_spv_count);
118 std::vector<uint32_t> visFrag(mesh3d_gbuffer_vis_frag_spv,
119 mesh3d_gbuffer_vis_frag_spv +
120 mesh3d_gbuffer_vis_frag_spv_count);
121 vk::ShaderModule visVertModule =
122 vkb::PipelineBuilder::createShaderModule(device.instance, visVert);
123 vk::ShaderModule visFragModule =
124 vkb::PipelineBuilder::createShaderModule(device.instance, visFrag);
125 gbufferVisPipeline =
126 device.createPipeline()
127 .useClassicPipeline(visVertModule, visFragModule)
128 .setPipelineLayout(mesh3dGpuDrivenPipelineLayout)
129 .setDynamicStatesViewportScissor()
130 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
131 vk::CullModeFlagBits::eNone, vk::FrontFace::eClockwise)
132 .setDepthStencil(true, true, vk::CompareOp::eLess)
133 .setColorAttachmentCount(5)
134 .build(gbufferVisRenderPass);
135 device->destroyShaderModule(visVertModule);
136 device->destroyShaderModule(visFragModule);
137 }
138 // VG variant: same vis attachments, cluster-stream fetch (no vertex input).
139 {
140 std::vector<uint32_t> vgVisVert(mesh3d_gbuffer_vgvis_vert_spv,
141 mesh3d_gbuffer_vgvis_vert_spv +
142 mesh3d_gbuffer_vgvis_vert_spv_count);
143 std::vector<uint32_t> vgVisFrag(mesh3d_gbuffer_vgvis_frag_spv,
144 mesh3d_gbuffer_vgvis_frag_spv +
145 mesh3d_gbuffer_vgvis_frag_spv_count);
146 vk::ShaderModule vgVisVertModule =
147 vkb::PipelineBuilder::createShaderModule(device.instance, vgVisVert);
148 vk::ShaderModule vgVisFragModule =
149 vkb::PipelineBuilder::createShaderModule(device.instance, vgVisFrag);
150 gbufferVgVisPipeline =
151 device.createPipeline()
152 .useClassicPipeline(vgVisVertModule, vgVisFragModule)
153 .setPipelineLayout(mesh3dGpuDrivenPipelineLayout)
154 .setDynamicStatesViewportScissor()
155 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
156 vk::CullModeFlagBits::eNone, vk::FrontFace::eClockwise)
157 .setDepthStencil(true, true, vk::CompareOp::eLess)
158 .setColorAttachmentCount(5)
159 .build(gbufferVisRenderPass);
160 device->destroyShaderModule(vgVisVertModule);
161 device->destroyShaderModule(vgVisFragModule);
162 }
163}
164
165// ---- GPU-driven (stage 0): bindless set + per-frame arena + tables ----
166
168 // Ordinary post-processing records immutable vertices here too, including
169 // devices without bindless/GPU-driven support. Keep that storage in the
170 // Graphics owner and behind the same per-slot fences as every other draw.
171 auto &arena = currentSlot(frameArenas_, frameSlotCount(), currentFrameSlot());
172 if (!arena.ensure(device, 8u << 20,
173 vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eStorageBuffer |
174 vk::BufferUsageFlagBits::eIndirectBuffer | vk::BufferUsageFlagBits::eTransferDst))
175 throw Exception("Frame arena unavailable");
176 return arena;
177}
178
179void Graphics::createBindlessSet() {
180 if (!gpuDrivenCaps_.gpuDrivenAvailable()) return;
181 // Submission also calls initGpuDrivenResources(). Keep the tables and
182 // descriptor sets that already own registered mesh/material/texture slots;
183 // replacing their buffers leaves those CPU registrations pointing at
184 // uninitialized GPU records (and invalidates earlier recorded draws).
185 if (bindlessSetLayout_) return;
186 if (!whiteTexture || !whiteTexture->gpuHandle) return;
187 if (!defaultBindlessCube || !defaultBindlessCube->gpuHandle) return;
188 auto *white = static_cast<GpuTexture *>(whiteTexture->gpuHandle);
189 auto *whiteCube = static_cast<GpuTexture *>(defaultBindlessCube->gpuHandle);
190
191 auto samplerBinding = [](uint32_t binding, uint32_t count, vk::ShaderStageFlags stages) {
192 vk::DescriptorSetLayoutBinding b{};
193 b.binding = binding;
194 b.descriptorType = vk::DescriptorType::eCombinedImageSampler;
195 b.descriptorCount = count;
196 b.stageFlags = stages;
197 return b;
198 };
199 auto storageBinding = [](uint32_t binding, vk::ShaderStageFlags stages) {
200 vk::DescriptorSetLayoutBinding b{};
201 b.binding = binding;
202 b.descriptorType = vk::DescriptorType::eStorageBuffer;
203 b.descriptorCount = 1;
204 b.stageFlags = stages;
205 return b;
206 };
207 auto uniformBinding = [](uint32_t binding, vk::ShaderStageFlags stages) {
208 vk::DescriptorSetLayoutBinding b{};
209 b.binding = binding;
210 b.descriptorType = vk::DescriptorType::eUniformBuffer;
211 b.descriptorCount = 1;
212 b.stageFlags = stages;
213 return b;
214 };
215 const vk::ShaderStageFlags allStages = vk::ShaderStageFlagBits::eVertex |
216 vk::ShaderStageFlagBits::eFragment |
217 vk::ShaderStageFlagBits::eCompute;
218 const vk::ShaderStageFlags computeOnly = vk::ShaderStageFlagBits::eCompute;
219 const vk::ShaderStageFlags vertFrag =
220 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment;
221 std::vector<vk::DescriptorSetLayoutBinding> bindings{
222 samplerBinding(0, kMaxBindlessTextures, allStages),
223 samplerBinding(1, kMaxBindlessCubemaps, allStages),
224 storageBinding(2, allStages),
225 storageBinding(3, allStages),
226 storageBinding(4, allStages),
227 storageBinding(5, allStages), // unused by shaders; kept valid
228 uniformBinding(6, computeOnly),
229 storageBinding(7, computeOnly),
230 storageBinding(8, computeOnly),
231 storageBinding(9, computeOnly),
232 storageBinding(10, computeOnly),
233 samplerBinding(11, 1, computeOnly),
234 storageBinding(12, computeOnly),
235 storageBinding(13, computeOnly),
236 storageBinding(14, computeOnly),
237 samplerBinding(15, 1, vk::ShaderStageFlagBits::eFragment), // visID (resolve)
238 samplerBinding(16, 1, vk::ShaderStageFlagBits::eFragment), // visBary (resolve)
239 storageBinding(17, computeOnly),
240 storageBinding(18, vertFrag), // pooled vertex positions
241 storageBinding(19, vertFrag), // pooled vertex normals
242 storageBinding(20, vertFrag), // pooled vertex uvs
243 storageBinding(21, vertFrag), // pooled indices
244 storageBinding(22, allStages), // VG position stream (float xyz)
245 storageBinding(23, allStages), // VG triangle stream (u32)
246 storageBinding(24, allStages), // VG cluster table (uvec4 x 4)
247 storageBinding(25, allStages), // VG cluster -> asset id
248 storageBinding(26, allStages), // VG visible list (per slot)
249 storageBinding(27, allStages), // VG indirect commands (per slot)
250 storageBinding(28, vk::ShaderStageFlagBits::eFragment), // VG asset -> material
251 storageBinding(29, vk::ShaderStageFlagBits::eVertex |
252 vk::ShaderStageFlagBits::eFragment |
253 vk::ShaderStageFlagBits::eCompute), // VG asset models
254 storageBinding(30, computeOnly), // non-indexed indirect commands (vis pass)
255 };
256
257 vk::DescriptorSetLayoutCreateInfo layoutInfo{};
258 layoutInfo.bindingCount = uint32_t(bindings.size());
259 layoutInfo.pBindings = bindings.data();
260 bindlessSetLayoutUnique_ = device->createDescriptorSetLayoutUnique(layoutInfo);
261 bindlessSetLayout_ = *bindlessSetLayoutUnique_;
262
263 // kAsyncResourceCopies sets: one per frame-in-flight slot, so frame N+1 can
264 // rewrite its own set while frame N's pending command buffers still hold
265 // the previous contents of the other set (no UPDATE_AFTER_BIND required).
266 const uint32_t setCount = kAsyncResourceCopies;
267 std::array<vk::DescriptorPoolSize, 3> poolSizes{
268 vk::DescriptorPoolSize{vk::DescriptorType::eCombinedImageSampler,
269 (kMaxBindlessTextures + kMaxBindlessCubemaps + 3) * setCount},
270 vk::DescriptorPoolSize{vk::DescriptorType::eStorageBuffer, 25 * setCount},
271 vk::DescriptorPoolSize{vk::DescriptorType::eUniformBuffer, 1 * setCount},
272 };
273 vk::DescriptorPoolCreateInfo poolInfo{};
274 poolInfo.maxSets = setCount;
275 poolInfo.poolSizeCount = uint32_t(poolSizes.size());
276 poolInfo.pPoolSizes = poolSizes.data();
277 bindlessPool_ = device->createDescriptorPool(poolInfo);
278
279 {
280 std::vector<vk::DescriptorSetLayout> layouts(setCount, bindlessSetLayout_);
281 vk::DescriptorSetAllocateInfo alloc{};
282 alloc.descriptorPool = bindlessPool_;
283 alloc.descriptorSetCount = setCount;
284 alloc.pSetLayouts = layouts.data();
285 bindlessSets_ = device->allocateDescriptorSets(alloc);
286 }
287
288 bindlessTextures2D_.assign(kMaxBindlessTextures, white);
289 bindlessCubemaps_.assign(kMaxBindlessCubemaps, whiteCube);
290 bindlessFree2D_.clear();
291 bindlessFreeCube_.clear();
292 bindlessFree2D_.reserve(kMaxBindlessTextures);
293 bindlessFreeCube_.reserve(kMaxBindlessCubemaps);
294 for (uint32_t i = 0; i < kMaxBindlessTextures; ++i) bindlessFree2D_.push_back(i);
295 for (uint32_t i = 0; i < kMaxBindlessCubemaps; ++i) bindlessFreeCube_.push_back(i);
296
297 vk::DescriptorImageInfo white2D{white->sampler, white->imageView(),
298 vk::ImageLayout::eShaderReadOnlyOptimal};
299 vk::DescriptorImageInfo whiteCubeInfo{whiteCube->sampler, whiteCube->cubeImage.imageView(),
300 vk::ImageLayout::eShaderReadOnlyOptimal};
301 // Placeholder fill: single-element writes keep the per-call update tiny;
302 // ~1.1k single-element calls per set at init cost ~6 ms, which is fine.
303 constexpr uint32_t kDescriptorChunk = 1;
304 auto chunkFill = [&](vk::DescriptorSet set, uint32_t binding, uint32_t total,
305 const vk::DescriptorImageInfo &info) {
306 for (uint32_t base = 0; base < total; base += kDescriptorChunk) {
307 vk::WriteDescriptorSet w{};
308 w.dstSet = set;
309 w.dstBinding = binding;
310 w.dstArrayElement = base;
311 w.descriptorCount = std::min(kDescriptorChunk, total - base);
312 w.descriptorType = vk::DescriptorType::eCombinedImageSampler;
313 w.pImageInfo = &info;
314 device->updateDescriptorSets(1, &w, 0, nullptr);
315 }
316 };
317 for (vk::DescriptorSet set : bindlessSets_) {
318 chunkFill(set, 0, kMaxBindlessTextures, white2D);
319 chunkFill(set, 1, kMaxBindlessCubemaps, whiteCubeInfo);
320 }
321
322 // GPU resource tables (fixed capacity at startup; entries registered lazily).
323 constexpr uint32_t kMaxMeshRecords = 4096;
324 constexpr uint32_t kMaxMaterialRecords = 1024;
325 meshTableBuffer_ = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
326 kMaxMeshRecords * sizeof(GpuMeshRecord),
327 kHostVisibleCoherent);
328 meshTableCapacity_ = kMaxMeshRecords;
329 meshTableRecords_.reserve(kMaxMeshRecords);
330 materialTableBuffer_ = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
331 kMaxMaterialRecords * sizeof(GpuMaterialRecord),
332 kHostVisibleCoherent);
333 materialTableCapacity_ = kMaxMaterialRecords;
334 materialTableRecords_.reserve(kMaxMaterialRecords);
335
336 // Bind the resource tables into the bindless set (bindings 2-5). Binding 4
337 // (per-frame instances) is rewritten before each frame; these writes make
338 // every binding valid so the set is safe to bind at any time.
339 auto tableWrite = [&](vk::DescriptorSet set, uint32_t binding, vk::Buffer buffer) {
340 vk::DescriptorBufferInfo info{buffer, 0, VK_WHOLE_SIZE};
341 vk::WriteDescriptorSet w{};
342 w.dstSet = set;
343 w.dstBinding = binding;
344 w.descriptorCount = 1;
345 w.descriptorType = vk::DescriptorType::eStorageBuffer;
346 w.pBufferInfo = &info;
347 device->updateDescriptorSets(1, &w, 0, nullptr);
348 };
349 for (vk::DescriptorSet set : bindlessSets_) {
350 tableWrite(set, 2, meshTableBuffer_.buffer);
351 tableWrite(set, 3, materialTableBuffer_.buffer);
352 tableWrite(set, 4, meshTableBuffer_.buffer); // placeholder; rewritten per frame
353 tableWrite(set, 5, meshTableBuffer_.buffer); // unused by shaders
354 }
355 // Stage 2 placeholders: every binding must be valid before the set binds.
356 gpuDrivenCullParamsPlaceholder_ =
357 vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eUniformBuffer, 256,
358 kHostVisibleCoherent);
359 {
360 vk::DescriptorBufferInfo ubo{gpuDrivenCullParamsPlaceholder_.buffer, 0, 256};
361 for (vk::DescriptorSet set : bindlessSets_) {
362 vk::WriteDescriptorSet w{};
363 w.dstSet = set;
364 w.dstBinding = 6;
365 w.descriptorCount = 1;
366 w.descriptorType = vk::DescriptorType::eUniformBuffer;
367 w.pBufferInfo = &ubo;
368 device->updateDescriptorSets(1, &w, 0, nullptr);
369 }
370 }
371 for (uint32_t b : {7u, 8u, 9u, 10u, 12u, 13u, 14u, 17u})
372 for (vk::DescriptorSet set : bindlessSets_) tableWrite(set, b, meshTableBuffer_.buffer);
373 {
374 vk::DescriptorImageInfo depthInfo{white->sampler, white->imageView(),
375 vk::ImageLayout::eShaderReadOnlyOptimal};
376 for (vk::DescriptorSet set : bindlessSets_) {
377 vk::WriteDescriptorSet w{};
378 w.dstSet = set;
379 w.dstBinding = 11;
380 w.descriptorCount = 1;
381 w.descriptorType = vk::DescriptorType::eCombinedImageSampler;
382 w.pImageInfo = &depthInfo;
383 device->updateDescriptorSets(1, &w, 0, nullptr);
384 }
385 }
386 // Stage 3 placeholders: visID/visBary are rewritten per frame by the
387 // resolve; keep them valid so the set is safe to bind anywhere.
388 for (vk::DescriptorSet set : bindlessSets_) {
389 vk::DescriptorImageInfo visInfo{white->sampler, white->imageView(),
390 vk::ImageLayout::eShaderReadOnlyOptimal};
391 vk::WriteDescriptorSet w{};
392 w.dstSet = set;
393 w.dstBinding = 15;
394 w.descriptorCount = 1;
395 w.descriptorType = vk::DescriptorType::eCombinedImageSampler;
396 w.pImageInfo = &visInfo;
397 device->updateDescriptorSets(1, &w, 0, nullptr);
398 w.dstBinding = 16;
399 device->updateDescriptorSets(1, &w, 0, nullptr);
400 }
401 // Pooled vertex/index buffers for the vis resolve (grows lazily).
402 ensureGpuVertexPool();
403 bindGpuVertexPoolBindless();
404 // Shared virtual-geometry cluster pool (grows lazily on upload).
405 ensureVgBuffers();
406 bindVgPoolBindless();
407}
408
409uint32_t Graphics::registerBindlessTexture2D(GpuTexture *tex) {
410 if (!tex || bindlessSets_.empty()) return kInvalidBindlessSlot;
411 if (tex->bindlessIndex2D != kInvalidBindlessSlot) return tex->bindlessIndex2D;
412 if (bindlessFree2D_.empty()) return kInvalidBindlessSlot;
413 const uint32_t slot = bindlessFree2D_.front();
414 bindlessFree2D_.erase(bindlessFree2D_.begin());
415 bindlessTextures2D_[slot] = tex;
416 tex->bindlessIndex2D = slot;
417 vk::DescriptorImageInfo img{tex->sampler, tex->imageView(),
418 vk::ImageLayout::eShaderReadOnlyOptimal};
419 for (vk::DescriptorSet set : bindlessSets_) {
420 vk::WriteDescriptorSet write{};
421 write.dstSet = set;
422 write.dstBinding = 0;
423 write.dstArrayElement = slot;
424 write.descriptorCount = 1;
425 write.descriptorType = vk::DescriptorType::eCombinedImageSampler;
426 write.pImageInfo = &img;
427 device->updateDescriptorSets(1, &write, 0, nullptr);
428 }
429 return slot;
430}
431
432uint32_t Graphics::registerBindlessTextureCube(GpuTexture *tex) {
433 if (!tex || bindlessSets_.empty()) return kInvalidBindlessSlot;
434 if (tex->bindlessIndexCube != kInvalidBindlessSlot) return tex->bindlessIndexCube;
435 if (bindlessFreeCube_.empty()) return kInvalidBindlessSlot;
436 const uint32_t slot = bindlessFreeCube_.front();
437 bindlessFreeCube_.erase(bindlessFreeCube_.begin());
438 bindlessCubemaps_[slot] = tex;
439 tex->bindlessIndexCube = slot;
440 vk::DescriptorImageInfo img{tex->sampler, tex->imageView(),
441 vk::ImageLayout::eShaderReadOnlyOptimal};
442 for (vk::DescriptorSet set : bindlessSets_) {
443 vk::WriteDescriptorSet write{};
444 write.dstSet = set;
445 write.dstBinding = 1;
446 write.dstArrayElement = slot;
447 write.descriptorCount = 1;
448 write.descriptorType = vk::DescriptorType::eCombinedImageSampler;
449 write.pImageInfo = &img;
450 device->updateDescriptorSets(1, &write, 0, nullptr);
451 }
452 return slot;
453}
454
456 if (!cubemap || !cubemap->gpuHandle) return kInvalidGpuDrivenSlot;
457 auto *gpu = static_cast<GpuTexture *>(cubemap->gpuHandle);
458 if (!gpu->isCube) return kInvalidGpuDrivenSlot;
459 return registerBindlessTextureCube(gpu);
460}
461
462void Graphics::unregisterBindlessTexture(GpuTexture *tex) {
463 if (!tex || bindlessSets_.empty()) return;
464 auto *white = static_cast<GpuTexture *>(whiteTexture->gpuHandle);
465 GpuTexture *whiteCube = white;
466 if (defaultBindlessCube && defaultBindlessCube->gpuHandle)
467 whiteCube = static_cast<GpuTexture *>(defaultBindlessCube->gpuHandle);
468
469 auto restore = [&](uint32_t binding, uint32_t slot, GpuTexture *placeholder,
470 bool cube) {
471 vk::DescriptorImageInfo img{
472 placeholder->sampler,
473 cube ? placeholder->cubeImage.imageView() : placeholder->imageView(),
474 vk::ImageLayout::eShaderReadOnlyOptimal};
475 for (vk::DescriptorSet set : bindlessSets_) {
476 vk::WriteDescriptorSet write{};
477 write.dstSet = set;
478 write.dstBinding = binding;
479 write.dstArrayElement = slot;
480 write.descriptorCount = 1;
481 write.descriptorType = vk::DescriptorType::eCombinedImageSampler;
482 write.pImageInfo = &img;
483 device->updateDescriptorSets(1, &write, 0, nullptr);
484 }
485 };
486
488 const uint32_t slot = tex->bindlessIndex2D;
489 bindlessTextures2D_[slot] = white;
490 bindlessFree2D_.push_back(slot);
491 restore(0, slot, white, false);
493 }
495 const uint32_t slot = tex->bindlessIndexCube;
496 bindlessCubemaps_[slot] = whiteCube;
497 bindlessFreeCube_.push_back(slot);
498 restore(1, slot, whiteCube, true);
500 }
501}
502
503void Graphics::ensureVgBuffers() {
504 if (vgGpu_.positions.buffer) return;
505 const auto hostMem = kHostVisibleCoherent;
506 constexpr uint32_t kInitClusters = 16384;
507 constexpr uint32_t kInitVertFloats = 1u << 20; // ~1M floats (~4MB)
508 constexpr uint32_t kInitTriangles = 2u << 20; // ~2M u32 indices
509 vgGpu_.positions = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
510 kInitVertFloats * sizeof(float), hostMem);
511 vgGpu_.triangles = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
512 kInitTriangles * sizeof(uint32_t), hostMem);
513 vgGpu_.clusters = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
514 kInitClusters * sizeof(GpuVgCluster), hostMem);
515 vgGpu_.clusterAssets =
516 vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
517 kInitClusters * sizeof(uint32_t), hostMem);
518 constexpr uint32_t kVisBytes = (kMaxVgClusters + 1) * sizeof(uint32_t);
519 constexpr uint32_t kIndBytes = kMaxVgClusters * sizeof(glm::uvec4);
520 vgGpu_.visible = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer |
521 vk::BufferUsageFlagBits::eIndirectBuffer,
522 kVisBytes * kAsyncResourceCopies, hostMem);
523 vgGpu_.indirect = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer |
524 vk::BufferUsageFlagBits::eIndirectBuffer,
525 kIndBytes * kAsyncResourceCopies, hostMem);
526 vgGpu_.assetMaterials =
527 vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
528 kMaxVgAssets * sizeof(uint32_t) * kAsyncResourceCopies, hostMem);
529 vgGpu_.assetModels =
530 vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
531 kMaxVgAssets * sizeof(glm::mat4) * kAsyncResourceCopies, hostMem);
532 {
533 void *m = vgGpu_.visible.map();
534 std::memset(m, 0, kVisBytes * kAsyncResourceCopies);
535 vgGpu_.visible.unmap();
536 m = vgGpu_.assetMaterials.map();
537 std::memset(m, 0, kMaxVgAssets * sizeof(uint32_t) * kAsyncResourceCopies);
538 vgGpu_.assetMaterials.unmap();
539 m = vgGpu_.assetModels.map();
540 for (size_t s = 0; s < kAsyncResourceCopies; ++s)
541 for (uint32_t a = 0; a < kMaxVgAssets; ++a)
542 static_cast<glm::mat4 *>(m)[s * kMaxVgAssets + a] = glm::mat4(1.f);
543 vgGpu_.assetModels.unmap();
544 }
545 bindVgPoolBindless();
546}
547
548void Graphics::growVgBuffers(uint32_t needClusters, uint32_t needVertices,
549 uint32_t needTriangles) {
550 device->waitIdle();
551 const auto hostMem = kHostVisibleCoherent;
552 auto growBuffer = [&](vkb::GenericBuffer &dst, uint32_t elementSize, uint32_t oldElems,
553 uint32_t newElems) {
554 if (newElems <= oldElems) return;
555 vkb::GenericBuffer grown(device, vk::BufferUsageFlagBits::eStorageBuffer,
556 vk::DeviceSize(newElems) * elementSize, hostMem);
557 if (oldElems > 0) {
558 void *srcMap = dst.map();
559 void *dstMap = grown.map();
560 std::memcpy(dstMap, srcMap, vk::DeviceSize(oldElems) * elementSize);
561 grown.unmap();
562 dst.unmap();
563 }
564 dst.release();
565 dst = std::move(grown);
566 };
567 const uint32_t curClusters = uint32_t(vgGpu_.clusters.size / sizeof(GpuVgCluster));
568 const uint32_t curVertFloats = uint32_t(vgGpu_.positions.size / sizeof(float));
569 const uint32_t curTriangles = uint32_t(vgGpu_.triangles.size / sizeof(uint32_t));
570 growBuffer(vgGpu_.clusters, uint32_t(sizeof(GpuVgCluster)), curClusters,
571 std::max(needClusters, curClusters * 2u));
572 growBuffer(vgGpu_.clusterAssets, uint32_t(sizeof(uint32_t)), curClusters,
573 std::max(needClusters, curClusters * 2u));
574 growBuffer(vgGpu_.positions, uint32_t(sizeof(float)), curVertFloats,
575 std::max(needVertices, curVertFloats * 2u));
576 growBuffer(vgGpu_.triangles, uint32_t(sizeof(uint32_t)), curTriangles,
577 std::max(needTriangles, curTriangles * 2u));
578 bindVgPoolBindless();
579}
580
581void Graphics::bindVgPoolBindless() {
582 if (bindlessSets_.empty() || !vgGpu_.positions.buffer) return;
583 auto bufWrite = [&](vk::DescriptorSet set, uint32_t binding, vk::Buffer buffer,
584 vk::DeviceSize offset, vk::DeviceSize size) {
585 vk::DescriptorBufferInfo info{buffer, offset, size};
586 vk::WriteDescriptorSet w{};
587 w.dstSet = set;
588 w.dstBinding = binding;
589 w.descriptorCount = 1;
590 w.descriptorType = vk::DescriptorType::eStorageBuffer;
591 w.pBufferInfo = &info;
592 device->updateDescriptorSets(1, &w, 0, nullptr);
593 };
594 const vk::DeviceSize posBytes = vgGpu_.positions.size;
595 const vk::DeviceSize triBytes = vgGpu_.triangles.size;
596 const vk::DeviceSize clBytes = vgGpu_.clusters.size;
597 const vk::DeviceSize claBytes = vgGpu_.clusterAssets.size;
598 for (vk::DescriptorSet set : bindlessSets_) {
599 bufWrite(set, 22, vgGpu_.positions.buffer, 0, posBytes);
600 bufWrite(set, 23, vgGpu_.triangles.buffer, 0, triBytes);
601 bufWrite(set, 24, vgGpu_.clusters.buffer, 0, clBytes);
602 bufWrite(set, 25, vgGpu_.clusterAssets.buffer, 0, claBytes);
603 bufWrite(set, 28, vgGpu_.assetMaterials.buffer, 0, vgGpu_.assetMaterials.size);
604 bufWrite(set, 29, vgGpu_.assetModels.buffer, 0, vgGpu_.assetModels.size);
605 bufWrite(set, 26, vgGpu_.visible.buffer, 0, vgGpu_.visible.size);
606 bufWrite(set, 27, vgGpu_.indirect.buffer, 0, vgGpu_.indirect.size);
607 }
608}
609
610void Graphics::bindVgFrameBindless(vk::DescriptorSet bindless, size_t slot) {
611 if (!bindless || !vgGpu_.visible.buffer) return;
612 const vk::DeviceSize slotVis = (vk::DeviceSize(kMaxVgClusters) + 1) * sizeof(uint32_t);
613 const vk::DeviceSize slotInd = vk::DeviceSize(kMaxVgClusters) * sizeof(glm::uvec4);
614 const vk::DeviceSize slotMat = vk::DeviceSize(kMaxVgAssets) * sizeof(uint32_t);
615 const vk::DeviceSize slotModel = vk::DeviceSize(kMaxVgAssets) * sizeof(glm::mat4);
616 const vk::DeviceSize visOff = slotVis * slot;
617 const vk::DeviceSize indOff = slotInd * slot;
618 const vk::DeviceSize matOff = slotMat * slot;
619 const vk::DeviceSize modelOff = slotModel * slot;
620 vk::DescriptorBufferInfo infos[4]{
621 {vgGpu_.visible.buffer, visOff, slotVis},
622 {vgGpu_.indirect.buffer, indOff, slotInd},
623 {vgGpu_.assetMaterials.buffer, matOff, slotMat},
624 {vgGpu_.assetModels.buffer, modelOff, slotModel},
625 };
626 vk::WriteDescriptorSet w[4]{};
627 const uint32_t bindings[4] = {26, 27, 28, 29};
628 for (int i = 0; i < 4; ++i) {
629 w[i].dstSet = bindless;
630 w[i].dstBinding = bindings[i];
631 w[i].descriptorCount = 1;
632 w[i].descriptorType = vk::DescriptorType::eStorageBuffer;
633 w[i].pBufferInfo = &infos[i];
634 }
635 device->updateDescriptorSets(4, w, 0, nullptr);
636}
637
639 // The compacted cluster command stream needs an indirect-count draw. Keep
640 // ordinary GPU-driven meshes available on devices without that optional
641 // Vulkan 1.2 feature, but reject VG explicitly instead of accepting an
642 // asset that can never be rasterized.
643 if (!gpuDrivenCaps_.drawIndirectCount) return kInvalidBindlessSlot;
644 if (!asset.positions || asset.vertexCount <= 0 || !asset.triangles ||
645 asset.triangleCount <= 0 || !asset.clusters || asset.clusterCount <= 0)
647 if (vgAssetCount_ >= kMaxVgAssets) return kInvalidBindlessSlot;
648 ensureVgBuffers();
649
650 const uint32_t assetId = vgAssetCount_;
651 const uint32_t vertBase = vgVertexCount_; // global vertex index base
652 const uint32_t triBase = vgTriangleCount_; // global index-stream base
653 const uint32_t clusterBase = vgClusterCount_;
654 const uint32_t needClusters = clusterBase + uint32_t(asset.clusterCount);
655 const uint32_t needVerts = uint32_t(vertBase + uint32_t(asset.vertexCount)) * 3;
656 const uint32_t needTris = triBase + uint32_t(asset.triangleCount);
657 const uint32_t curClusters = uint32_t(vgGpu_.clusters.size / sizeof(GpuVgCluster));
658 const uint32_t curVerts = uint32_t(vgGpu_.positions.size / sizeof(float));
659 const uint32_t curTris = uint32_t(vgGpu_.triangles.size / sizeof(uint32_t));
660 if (needClusters > curClusters || needVerts > curVerts || needTris > curTris)
661 growVgBuffers(needClusters, needVerts, needTris);
662
663 void *posMap = vgGpu_.positions.map();
664 void *triMap = vgGpu_.triangles.map();
665 void *clMap = vgGpu_.clusters.map();
666 void *claMap = vgGpu_.clusterAssets.map();
667 if (!posMap || !triMap || !clMap || !claMap) {
668 if (posMap) vgGpu_.positions.unmap();
669 if (triMap) vgGpu_.triangles.unmap();
670 if (clMap) vgGpu_.clusters.unmap();
671 if (claMap) vgGpu_.clusterAssets.unmap();
673 }
674 std::memcpy(static_cast<char *>(posMap) + size_t(vertBase) * 3 * sizeof(float), asset.positions,
675 size_t(asset.vertexCount) * 3 * sizeof(float));
676 {
677 auto *dst = static_cast<uint32_t *>(triMap) + triBase;
678 for (int i = 0; i < asset.triangleCount; ++i) dst[i] = asset.triangles[i] + vertBase;
679 }
680 std::memcpy(static_cast<char *>(clMap) + vgClusterCount_ * sizeof(GpuVgCluster),
681 asset.clusters, size_t(asset.clusterCount) * sizeof(GpuVgCluster));
682 {
683 auto *dst = static_cast<GpuVgCluster *>(clMap) + vgClusterCount_;
684 for (int i = 0; i < asset.clusterCount; ++i) {
685 // Cluster triStart is a triangle ordinal; vgTriangleCount_ tracks
686 // uint32 indices. The vertex/resolve shaders multiply triStart by
687 // three, so convert the index offset before rebasing the cluster.
688 dst[i].u1[0] += triBase / 3u;
689 }
690 }
691 auto *cla = static_cast<uint32_t *>(claMap);
692 for (int i = 0; i < asset.clusterCount; ++i) cla[vgClusterCount_ + uint32_t(i)] = assetId;
693 vgGpu_.positions.unmap();
694 vgGpu_.triangles.unmap();
695 vgGpu_.clusters.unmap();
696 vgGpu_.clusterAssets.unmap();
697
698 vgClusterCount_ = needClusters;
699 vgVertexCount_ = vertBase + uint32_t(asset.vertexCount);
700 vgTriangleCount_ = needTris;
701 vgAssetCount_ = assetId + 1;
702 // Default identity model per slot; vgSetInstance overwrites the current slot.
703 {
704 void *m = vgGpu_.assetModels.map();
705 auto *models = static_cast<glm::mat4 *>(m);
706 for (size_t s = 0; s < kAsyncResourceCopies; ++s)
707 models[s * kMaxVgAssets + assetId] = glm::mat4(1.f);
708 vgGpu_.assetModels.unmap();
709 }
710 return assetId;
711}
712
714 if (!mesh || !mesh->gpuHandle) return kInvalidBindlessSlot;
715 const auto *gpu = static_cast<const GpuMesh *>(mesh->gpuHandle);
716 return gpu->record.vgAssetId;
717}
718
719bool Graphics::gpuDrivenVgAttachToMesh(Mesh *mesh, uint32_t vgAssetId) {
720 if (!mesh || !mesh->gpuHandle) return false;
721 if (vgAssetId >= vgAssetCount_ || vgAssetId >= kMaxVgAssets) return false;
722 auto *gpu = static_cast<GpuMesh *>(mesh->gpuHandle);
723 gpu->record.vgAssetId = vgAssetId;
724 if (gpu->gpuRecordIndex != kInvalidBindlessSlot &&
725 gpu->gpuRecordIndex < meshTableRecords_.size()) {
726 meshTableRecords_[gpu->gpuRecordIndex].vgAssetId = vgAssetId;
727 syncMeshTable();
728 }
729 return true;
730}
731
732bool Graphics::gpuDrivenVgSetInstance(uint32_t vgAssetId, const glm::mat4 &model,
733 uint32_t materialId) {
734 if (vgAssetId >= vgAssetCount_ || vgAssetId >= kMaxVgAssets) return false;
735 if (vgGpu_.assetModels.buffer) {
736 const size_t slot = currentFrameSlot() % kAsyncResourceCopies;
737 void *m = vgGpu_.assetModels.map();
738 static_cast<glm::mat4 *>(m)[slot * kMaxVgAssets + vgAssetId] = model;
739 vgGpu_.assetModels.unmap();
740 void *am = vgGpu_.assetMaterials.map();
741 static_cast<uint32_t *>(am)[slot * kMaxVgAssets + vgAssetId] = materialId;
742 vgGpu_.assetMaterials.unmap();
743 }
744 vgAnyThisFrame_ = true;
745 return true;
746}
747
749 if (!vgGpu_.visible.buffer || vgAssetCount_ == 0) return 0;
750 void *map = vgGpu_.visible.map();
751 if (!map) return 0;
752 const size_t slot = vgLastVisible_ % kAsyncResourceCopies;
753 const uint32_t count = static_cast<const uint32_t *>(map)[slot * (kMaxVgClusters + 1)];
754 vgGpu_.visible.unmap();
755 return count;
756}
757
758void Graphics::syncMeshTable() {
759 if (!meshTableBuffer_.buffer || meshTableRecords_.empty()) return;
760 meshTableBuffer_.updateLocal(vkb::FrameSlot::gpuIdle(), meshTableRecords_.data(),
761 meshTableRecords_.size() * sizeof(GpuMeshRecord));
762}
763
764GpuMaterialRecord Graphics::buildMaterialRecord(Material *material) {
765 GpuMaterialRecord rec{};
766 if (!material) return rec;
767 rec.tint = glm::vec4(material->getTintR(), material->getTintG(), material->getTintB(),
768 material->getTintA());
769 rec.pbr = glm::vec4(material->getMetallic(), material->getRoughness(),
770 material->getReceiveShadow() ? 1.f : 0.f,
771 material->getReceiveLight() ? 1.f : 0.f);
772 rec.texBomb = glm::vec4(material->getTexCellBombScale(), material->getTexCellBombStrength(),
773 material->getTexCellBombRotation(), 0.f);
774 rec.parallax = glm::vec4(material->getParallaxScale(), material->getParallaxMinLayers(),
775 material->getParallaxMaxLayers(), 0.f);
776 rec.surface =
777 glm::vec4(material->getAlphaCutoff(), material->surfaceMode() == SurfaceMode::Masked ? 1.f : 0.f, 0.f, 0.f);
778 auto slotOf = [](Texture *t) {
779 if (!t || !t->gpuHandle) return kInvalidBindlessSlot;
780 return static_cast<GpuTexture *>(t->gpuHandle)->bindlessIndex2D;
781 };
782 rec.textureSlots[0] = slotOf(material->getAlbedoTexture());
783 rec.textureSlots[1] = slotOf(material->getNormalTexture());
784 rec.textureSlots[2] = slotOf(material->getHeightTexture());
785 rec.textureSlots[3] = kInvalidBindlessSlot; // env is camera state, not material state
786 const std::string model = material->getShadingModel();
787 rec.shadingModel = (model == "unlit") ? 1u : (model == "hair") ? 2u
788 : (model == "custom") ? 3u
789 : 0u;
790 if (material->getCastShadow()) rec.flags |= 1u;
791 if (material->getCastOcclusion()) rec.flags |= 2u;
792 if (material->getCameraFacing()) rec.flags |= 4u;
793 return rec;
794}
795
797 if (!material) return kInvalidBindlessSlot;
798 auto it = materialTableIndex_.find(material);
799 if (it != materialTableIndex_.end()) {
800 const GpuMaterialRecord updated = buildMaterialRecord(material);
801 GpuMaterialRecord& stored = materialTableRecords_[it->second];
802 if (std::memcmp(&stored, &updated, sizeof(updated)) != 0) {
803 stored = updated;
805 }
806 return it->second;
807 }
808 if (!materialTableFree_.empty()) {
809 const uint32_t idx = materialTableFree_.back();
810 materialTableFree_.pop_back();
811 materialTableIndex_.emplace(material, idx);
812 materialTableRecords_[idx] = buildMaterialRecord(material);
814 return idx;
815 }
816 if (materialTableRecords_.size() >= materialTableCapacity_) return kInvalidBindlessSlot;
817 const uint32_t idx = uint32_t(materialTableRecords_.size());
818 materialTableIndex_.emplace(material, idx);
819 materialTableRecords_.push_back(buildMaterialRecord(material));
821 return idx;
822}
823
825 if (!materialTableBuffer_.buffer || materialTableRecords_.empty()) return;
826 materialTableBuffer_.updateLocal(vkb::FrameSlot::gpuIdle(), materialTableRecords_.data(),
827 materialTableRecords_.size() *
828 sizeof(GpuMaterialRecord));
829}
830
832 if (!mesh || !mesh->gpuHandle) return kInvalidBindlessSlot;
833 auto *gpu = static_cast<GpuMesh *>(mesh->gpuHandle);
834 if (gpu->gpuRecordIndex == kInvalidBindlessSlot) registerMeshRecord(gpu);
835 return gpu->gpuRecordIndex;
836}
837
839 if (!material || material->virtualTextureMode() == MaterialVirtualTextureMode::AtlasPageTable ||
840 material->surfaceMode() == SurfaceMode::Transparent || material->hasPbrSurface())
841 return false;
842 return materialTableIndex_.contains(material) || !materialTableFree_.empty() ||
843 materialTableRecords_.size() < materialTableCapacity_;
844}
845
847 if (!material)
849 "cannot release a null GPU-driven material"));
850 const auto found = materialTableIndex_.find(material);
851 if (found == materialTableIndex_.end()) return Result<void>::success();
852 const uint32_t slot = found->second;
853 materialTableIndex_.erase(found);
854 materialTableRecords_[slot] = {};
855 materialTableFree_.push_back(slot);
857 return Result<void>::success();
858}
859
861 if (!gpuDrivenEnabled() || !gpuDrivenCaps_.gpuDrivenAvailable()) return false;
862 initGpuDrivenResources();
863 if (!mesh3dGpuDrivenPipeline || bindlessSets_.empty() || !meshTableBuffer_.buffer) return false;
864 if (!instances || instanceCount == 0) return false;
865
866 // Sort by (material, mesh) and merge buckets using the GPU mesh table.
868 for (uint32_t i = 0; i < instanceCount; ++i) {
869 builder.add(i, instances[i].meshId, instances[i].materialId, 0);
870 }
871 const uint32_t drawCount = builder.build(meshTableRecords_);
872 if (drawCount == 0) return false;
873 lastGpuDrivenDrawCount_ = drawCount;
874 const auto &cmds = builder.commands();
875 const auto &order = builder.sortedInstanceOrder();
876
877 // Upload instances in the sorted order so each bucket is a contiguous range.
878 std::vector<GpuInstance> sorted(instanceCount);
879 for (uint32_t i = 0; i < instanceCount; ++i) sorted[i] = instances[order[i]];
880
881 auto &arena = currentFrameArena();
882 FrameArena::Alloc instAlloc = arena.alloc(instanceCount * sizeof(GpuInstance), 16);
883 FrameArena::Alloc cmdAlloc = arena.alloc(drawCount * sizeof(GpuIndirectCommand), 16);
884 if (!instAlloc.mapped || !cmdAlloc.mapped) return false; // arena overflow: caller falls back
885 std::memcpy(instAlloc.mapped, sorted.data(), instanceCount * sizeof(GpuInstance));
886 std::memcpy(cmdAlloc.mapped, cmds.data(), drawCount * sizeof(GpuIndirectCommand));
887
888 // Bind the arena instance buffer as bindless binding 4 (update before bind,
889 // on the current frame slot's set only; the other slot's pending command
890 // buffers keep pointing at their own frame's arena).
891 const vk::DescriptorSet bindless = bindlessSetForFrame();
892 if (!bindless) return false;
893 vk::DescriptorBufferInfo instInfo{arena.buffer(), instAlloc.offset, instAlloc.size};
894 vk::WriteDescriptorSet instWrite{};
895 instWrite.dstSet = bindless;
896 instWrite.dstBinding = 4;
897 instWrite.descriptorCount = 1;
898 instWrite.descriptorType = vk::DescriptorType::eStorageBuffer;
899 instWrite.pBufferInfo = &instInfo;
900 device->updateDescriptorSets(1, &instWrite, 0, nullptr);
901
902 // Per-frame set0 through the shared ring (dynamic UBO offsets).
903 const Graphics::GpuDrivenFrameSet0 s0 = gpuDrivenFrameSet0();
904 if (!s0.set) return false;
905 const uint32_t dynOffsets[2] = {s0.uboOffset, s0.shadowOffset};
906
907 auto &cb = currentPresentCb();
908 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipeline);
909 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 0, 1,
910 &s0.set, 2, dynOffsets);
911 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 1, 1,
912 &bindless, 0, nullptr);
913 const vk::DeviceSize stride = sizeof(GpuIndirectCommand);
914 // Stage 1 keeps one host buffer pair per mesh (no pool yet), so each draw
915 // group must bind the owning mesh's vertex/index buffers. The builder sorts
916 // by (pipeline, material, mesh), so commands sharing a mesh are contiguous;
917 // bind only when the mesh changes.
918 GpuMesh *boundMesh = nullptr;
919 for (uint32_t i = 0; i < drawCount;) {
920 const GpuInstance &first = sorted[cmds[i].firstInstance];
921 if (first.meshId >= meshRecordOwners_.size()) {
922 EV_ASSERT(false, "indirect draw references an unregistered mesh record");
923 ++i;
924 continue;
925 }
926 GpuMesh *mesh = meshRecordOwners_[first.meshId];
927 if (mesh != boundMesh) {
928 const vk::DeviceSize vbOffset = 0;
929 cb.bindVertexBuffers(0, 1, mesh->vertices, &vbOffset);
930 cb.bindIndexBuffer(mesh->indices.buffer, 0, mesh->indexType);
931 boundMesh = mesh;
932 }
933 uint32_t batchEnd = i + 1;
934 if (gpuDrivenCaps_.multiDrawIndirect) {
935 const uint32_t limit = device.physical_device.properties.limits.maxDrawIndirectCount;
936 while (batchEnd < drawCount && batchEnd - i < limit &&
937 sorted[cmds[batchEnd].firstInstance].meshId == first.meshId)
938 ++batchEnd;
939 }
940 cb.drawIndexedIndirect(arena.buffer(), cmdAlloc.offset + vk::DeviceSize(i) * stride, batchEnd - i, stride);
941 i = batchEnd;
942 }
943 return true;
944}
945
947 if (!gpuDrivenEnabled() || !gpuDrivenCaps_.gpuDrivenAvailable())
949 initGpuDrivenResources();
950 if (!mesh3dGpuDrivenPipeline || bindlessSets_.empty() || !meshTableBuffer_.buffer)
954 batch.buffer.strideBytes != sizeof(GpuInstance) || !batch.buckets || batch.bucketCount == 0 ||
955 batch.instanceCount == 0)
959 const uint64_t required = batch.buffer.offsetBytes + uint64_t(batch.instanceCount) * sizeof(GpuInstance);
960 if (required < batch.buffer.offsetBytes || required > batch.buffer.sizeBytes)
962
963 std::vector<GpuIndirectCommand> commands(batch.bucketCount);
964 uint64_t coveredInstances = 0;
965 for (uint32_t i = 0; i < batch.bucketCount; ++i) {
966 const GpuResidentInstanceBucket &bucket = batch.buckets[i];
967 const uint64_t end = uint64_t(bucket.firstInstance) + bucket.instanceCount;
968 if (bucket.instanceCount == 0 || bucket.firstInstance != coveredInstances || end > batch.instanceCount ||
969 bucket.meshId >= meshTableRecords_.size() || bucket.meshId >= meshRecordOwners_.size() ||
970 bucket.materialId >= materialTableRecords_.size() || !meshRecordOwners_[bucket.meshId])
972 const GpuMeshRecord &mesh = meshTableRecords_[bucket.meshId];
973 commands[i] = {mesh.indexCount, bucket.instanceCount, mesh.firstIndex, mesh.vertexBase, bucket.firstInstance};
974 coveredInstances = end;
975 }
976 if (coveredInstances != batch.instanceCount) return GpuResidentSubmitStatus::InvalidArgument;
977
978 auto &arena = currentFrameArena();
979 FrameArena::Alloc commandAlloc = arena.alloc(batch.bucketCount * sizeof(GpuIndirectCommand), 16);
980 if (!commandAlloc.mapped) return GpuResidentSubmitStatus::CapacityExceeded;
981 std::memcpy(commandAlloc.mapped, commands.data(), batch.bucketCount * sizeof(GpuIndirectCommand));
982
983 VkBuffer rawBuffer{};
984 static_assert(sizeof(rawBuffer) <= sizeof(batch.buffer.nativeHandle));
985 std::memcpy(&rawBuffer, &batch.buffer.nativeHandle, sizeof(rawBuffer));
986 vk::Buffer residentBuffer(rawBuffer);
987 const vk::DescriptorSet bindless = bindlessSetForFrame();
988 if (!bindless || !residentBuffer) return GpuResidentSubmitStatus::ResourceUnavailable;
989 vk::DescriptorBufferInfo instanceInfo{residentBuffer, batch.buffer.offsetBytes,
990 uint64_t(batch.instanceCount) * sizeof(GpuInstance)};
991 vk::WriteDescriptorSet instanceWrite{};
992 instanceWrite.dstSet = bindless;
993 instanceWrite.dstBinding = 4;
994 instanceWrite.descriptorCount = 1;
995 instanceWrite.descriptorType = vk::DescriptorType::eStorageBuffer;
996 instanceWrite.pBufferInfo = &instanceInfo;
997 device->updateDescriptorSets(1, &instanceWrite, 0, nullptr);
998
999 const Graphics::GpuDrivenFrameSet0 frame = gpuDrivenFrameSet0();
1002 const uint32_t dynamicOffsets[2] = {frame.uboOffset, frame.shadowOffset};
1003 auto &cb = currentPresentCb();
1004 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipeline);
1005 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 0, 1, &frame.set, 2,
1006 dynamicOffsets);
1007 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 1, 1, &bindless, 0, nullptr);
1008
1009 GpuMesh *boundMesh = nullptr;
1010 for (uint32_t i = 0; i < batch.bucketCount; ++i) {
1011 GpuMesh *mesh = meshRecordOwners_[batch.buckets[i].meshId];
1012 if (mesh != boundMesh) {
1013 const vk::DeviceSize vertexOffset = 0;
1014 cb.bindVertexBuffers(0, 1, mesh->vertices, &vertexOffset);
1015 cb.bindIndexBuffer(mesh->indices.buffer, 0, mesh->indexType);
1016 boundMesh = mesh;
1017 }
1018 cb.drawIndexedIndirect(arena.buffer(), commandAlloc.offset + uint64_t(i) * sizeof(GpuIndirectCommand), 1,
1019 sizeof(GpuIndirectCommand));
1020 }
1021 lastGpuDrivenDrawCount_ = batch.bucketCount;
1023}
1024
1025// --- Stage 2: HZB + GPU cull ------------------------------------------------
1026
1027namespace {
1028
1030void gpuDrivenFrustumPlanes(const glm::mat4 &m, glm::vec4 planes[6]) {
1031 // glm is column-major: row i is (m[0][i], m[1][i], m[2][i], m[3][i]).
1032 const glm::vec4 row0(m[0][0], m[1][0], m[2][0], m[3][0]);
1033 const glm::vec4 row1(m[0][1], m[1][1], m[2][1], m[3][1]);
1034 const glm::vec4 row2(m[0][2], m[1][2], m[2][2], m[3][2]);
1035 const glm::vec4 row3(m[0][3], m[1][3], m[2][3], m[3][3]);
1036 planes[0] = row3 + row0; // left
1037 planes[1] = row3 - row0; // right
1038 planes[2] = row3 + row1; // bottom
1039 planes[3] = row3 - row1; // top
1040 planes[4] = row3 + row2; // near
1041 planes[5] = row3 - row2; // far
1042 for (int i = 0; i < 6; ++i) {
1043 const float len = glm::length(glm::vec3(planes[i]));
1044 if (len > 1e-8f) planes[i] /= len;
1045 }
1046}
1047
1048} // namespace
1049
1050Graphics::GpuDrivenCullSlot &Graphics::gpuDrivenCullSlot(uint32_t frameSlot) {
1051 // Callers guard with gpuDrivenCullReady_; this is a debug-only invariant.
1052 EV_ASSERT(!gpuDrivenCullSlots_.empty(), "gpuDriven cull slot accessed before resources");
1053 return gpuDrivenCullSlots_[frameSlot % gpuDrivenCullSlots_.size()];
1054}
1055
1056Graphics::GpuDrivenCullSlot &Graphics::currentGpuDrivenCullSlot() {
1057 return gpuDrivenCullSlot(static_cast<uint32_t>(currentFrameSlot()));
1058}
1059
1060void Graphics::ensureGpuDrivenCullResources(int width, int height) {
1061 if (!gpuDrivenCaps_.gpuDrivenCullAvailable() || width <= 0 || height <= 0) return;
1062 if (!bindlessSetLayout_) return;
1063 if (gpuDrivenCullReady_ && gpuDrivenCullWidth == width && gpuDrivenCullHeight == height)
1064 return;
1065 destroyGpuDrivenCullResources();
1066
1067 gpuDrivenCullWidth = width;
1068 gpuDrivenCullHeight = height;
1069
1070 // HZB word layout per slot: [16 header uints][mip0][mip1]...
1071 uint32_t mipOffsets[kMaxHzbMips] = {};
1072 uint32_t totalWords = kHZBHeaderWords;
1073 uint32_t maxMip = 0;
1074 {
1075 uint32_t w = uint32_t(width);
1076 uint32_t h = uint32_t(height);
1077 for (uint32_t m = 0; m < kMaxHzbMips; ++m) {
1078 mipOffsets[m] = totalWords;
1079 const uint32_t mw = std::max(w >> m, 1u);
1080 const uint32_t mh = std::max(h >> m, 1u);
1081 totalWords += mw * mh;
1082 maxMip = m;
1083 if (mw == 1 && mh == 1) break;
1084 }
1085 }
1086 gpuDrivenCullMaxMip = maxMip;
1087
1088 const vk::DeviceSize flagBytes = kMaxGpuDrivenInstances * sizeof(uint32_t);
1089 const vk::DeviceSize compactBytes = kMaxGpuDrivenInstances * sizeof(GpuInstance);
1090 const vk::DeviceSize indirectBytes = kMaxGpuDrivenBuckets * sizeof(GpuIndirectCommand);
1091 const vk::DeviceSize indirectNIBytes = kMaxGpuDrivenBuckets * sizeof(glm::uvec4);
1092 const vk::DeviceSize counterBytes = kMaxGpuDrivenBuckets * sizeof(uint32_t);
1093 const vk::DeviceSize hzbBytes = totalWords * sizeof(uint32_t);
1094
1095 gpuDrivenCullSlots_.resize(frameSlotCount());
1096 for (auto &slot : gpuDrivenCullSlots_) {
1097 slot.visibleFlags =
1098 vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer, flagBytes,
1099 kHostVisibleCoherent);
1100 slot.compacted = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
1101 compactBytes, kHostVisibleCoherent);
1102 slot.indirect = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer |
1103 vk::BufferUsageFlagBits::eIndirectBuffer,
1104 indirectBytes, kHostVisibleCoherent);
1105 slot.indirectNI = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer |
1106 vk::BufferUsageFlagBits::eIndirectBuffer,
1107 indirectNIBytes, kHostVisibleCoherent);
1108 slot.bucketCounters =
1109 vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer, counterBytes,
1110 kHostVisibleCoherent);
1111 slot.hzb = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer, hzbBytes,
1112 kHostVisibleCoherent);
1113 slot.cullParams =
1114 vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eUniformBuffer,
1115 sizeof(GpuCullParams), kHostVisibleCoherent);
1116 // Header offsets + zero depth (0 = near plane -> everything visible).
1117 void *hzbMap = slot.hzb.map();
1118 auto *u32 = static_cast<uint32_t *>(hzbMap);
1119 for (uint32_t m = 0; m <= maxMip; ++m) u32[m] = mipOffsets[m];
1120 for (uint32_t m = maxMip + 1; m < kHZBHeaderWords; ++m) u32[m] = 0;
1121 std::memset(static_cast<char *>(hzbMap) + kHZBHeaderWords * sizeof(uint32_t), 0,
1122 (totalWords - kHZBHeaderWords) * sizeof(uint32_t));
1123 slot.hzb.unmap();
1124 }
1125
1126 // Compute pipeline layout: set 1 = bindless (set 0 = empty placeholder so
1127 // the shaders' `layout(set = 1, ...)` bindings resolve to index 1).
1128 vk::DescriptorSetLayoutCreateInfo emptyInfo{};
1129 gpuDrivenComputeEmptyLayout_ = device->createDescriptorSetLayout(emptyInfo);
1130 vk::PushConstantRange pcr{vk::ShaderStageFlagBits::eCompute, 0, 20};
1131 vk::PipelineLayoutCreateInfo pli{};
1132 std::array<vk::DescriptorSetLayout, 2> computeLayouts{gpuDrivenComputeEmptyLayout_,
1133 bindlessSetLayout_};
1134 pli.setLayoutCount = uint32_t(computeLayouts.size());
1135 pli.pSetLayouts = computeLayouts.data();
1136 pli.pushConstantRangeCount = 1;
1137 pli.pPushConstantRanges = &pcr;
1138 gpuDrivenComputeLayout = device->createPipelineLayout(pli);
1139
1140 const auto spvOf = [](const uint32_t *p, size_t n) {
1141 return std::vector<uint32_t>(p, p + n);
1142 };
1143 hzbBuildPass_.create(device, gpuDrivenComputeLayout,
1144 spvOf(hzb_build_comp_spv, hzb_build_comp_spv_count));
1145 cullPass_.create(device, gpuDrivenComputeLayout,
1146 spvOf(gpu_cull_comp_spv, gpu_cull_comp_spv_count));
1147 emitPass_.create(device, gpuDrivenComputeLayout,
1148 spvOf(gpu_emit_comp_spv, gpu_emit_comp_spv_count));
1149 vgCullPass_.create(device, gpuDrivenComputeLayout,
1150 spvOf(vg_main_cull_comp_spv, vg_main_cull_comp_spv_count));
1151 gpuDrivenCullReady_ =
1152 hzbBuildPass_.pipeline() && cullPass_.pipeline() && emitPass_.pipeline();
1153}
1154
1155void Graphics::destroyGpuDrivenCullResources() {
1156 hzbBuildPass_ = ComputePass{};
1157 cullPass_ = ComputePass{};
1158 emitPass_ = ComputePass{};
1159 vgCullPass_ = ComputePass{};
1160 if (gpuDrivenComputeLayout) {
1161 device->destroyPipelineLayout(gpuDrivenComputeLayout);
1162 gpuDrivenComputeLayout = nullptr;
1163 }
1164 if (gpuDrivenComputeEmptyLayout_) {
1165 device->destroyDescriptorSetLayout(gpuDrivenComputeEmptyLayout_);
1166 gpuDrivenComputeEmptyLayout_ = nullptr;
1167 }
1168 for (auto &slot : gpuDrivenCullSlots_) {
1169 slot.visibleFlags.release();
1170 slot.compacted.release();
1171 slot.indirect.release();
1172 slot.indirectNI.release();
1173 slot.bucketCounters.release();
1174 slot.hzb.release();
1175 slot.cullParams.release();
1176 }
1177 gpuDrivenCullSlots_.clear();
1178 gpuDrivenCullReady_ = false;
1179 gpuDrivenCullWidth = 0;
1180 gpuDrivenCullHeight = 0;
1181}
1182
1183void Graphics::recordGpuDrivenHzbBuild() {
1184 if (!gpuDrivenCullReady_) return;
1185 auto *slot = currentGBufferSlot();
1186 if (!slot || !slot->depthGpu.sampler || !slot->depthGpu.imageView()) return;
1187 auto &cull = currentGpuDrivenCullSlot();
1188 auto &cb = currentPresentCb();
1189
1190 // Depth attachment write -> compute shader read.
1191 vk::ImageMemoryBarrier imb{};
1192 imb.image = slot->depth.image();
1193 imb.oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
1194 imb.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
1195 imb.srcAccessMask = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
1196 imb.dstAccessMask = vk::AccessFlagBits::eShaderRead;
1197 imb.subresourceRange = {vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1};
1198 cb.pipelineBarrier(vk::PipelineStageFlagBits::eEarlyFragmentTests |
1199 vk::PipelineStageFlagBits::eLateFragmentTests,
1200 vk::PipelineStageFlagBits::eComputeShader, {}, 0, nullptr, 0, nullptr, 1,
1201 &imb);
1202
1203 uint32_t mipOffsets[kMaxHzbMips] = {};
1204 uint32_t totalWords = kHZBHeaderWords;
1205 {
1206 uint32_t w = uint32_t(gpuDrivenCullWidth);
1207 uint32_t h = uint32_t(gpuDrivenCullHeight);
1208 for (uint32_t m = 0; m <= gpuDrivenCullMaxMip; ++m) {
1209 mipOffsets[m] = totalWords;
1210 const uint32_t mw = std::max(w >> m, 1u);
1211 const uint32_t mh = std::max(h >> m, 1u);
1212 totalWords += mw * mh;
1213 }
1214 }
1215 for (uint32_t m = 0; m <= gpuDrivenCullMaxMip; ++m) {
1216 if (m > 0) {
1217 // Previous mip write -> this mip read.
1218 vk::BufferMemoryBarrier bmb{};
1219 bmb.buffer = cull.hzb.buffer;
1220 bmb.size = VK_WHOLE_SIZE;
1221 bmb.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
1222 bmb.dstAccessMask = vk::AccessFlagBits::eShaderRead;
1223 cb.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader,
1224 vk::PipelineStageFlagBits::eComputeShader, {}, 0, nullptr, 1, &bmb,
1225 0, nullptr);
1226 }
1227 const uint32_t mw = std::max(uint32_t(gpuDrivenCullWidth) >> m, 1u);
1228 const uint32_t mh = std::max(uint32_t(gpuDrivenCullHeight) >> m, 1u);
1229 struct HzbPush {
1230 uint32_t mip;
1231 uint32_t width;
1232 uint32_t height;
1233 uint32_t slotBase;
1234 uint32_t prevOffset;
1235 } push{m, mw, mh, 0u, mipOffsets[m > 0 ? m - 1 : 0]};
1236 cb.pushConstants(gpuDrivenComputeLayout, vk::ShaderStageFlagBits::eCompute, 0,
1237 sizeof(push), &push);
1238 hzbBuildPass_.record(cb, (mw + 7) / 8, (mh + 7) / 8, 1);
1239 }
1240}
1241
1243 if (!gpuDrivenCullEnabled() || !gpuDrivenCullReady_) return false;
1244 if (!instances || instanceCount == 0) return false;
1246
1248 for (uint32_t i = 0; i < instanceCount; ++i) {
1249 builder.add(i, instances[i].meshId, instances[i].materialId, 0);
1250 }
1251 const uint32_t bucketCount = builder.build(meshTableRecords_);
1252 if (bucketCount == 0 || bucketCount > kMaxGpuDrivenBuckets) return false;
1253 const auto &cmds = builder.commands();
1254 const auto &order = builder.sortedInstanceOrder();
1255
1256 std::vector<GpuInstance> sorted(instanceCount);
1257 for (uint32_t i = 0; i < instanceCount; ++i) sorted[i] = instances[order[i]];
1258
1259 gpuDrivenBucketIds_.assign(instanceCount, 0);
1260 gpuDrivenBucketOffsets_.resize(bucketCount);
1261 gpuDrivenBucketMeshIds_.resize(bucketCount);
1262 for (uint32_t b = 0; b < bucketCount; ++b) {
1263 gpuDrivenBucketOffsets_[b] = cmds[b].firstInstance;
1264 gpuDrivenBucketMeshIds_[b] = sorted[cmds[b].firstInstance].meshId;
1265 }
1266 {
1267 uint32_t b = 0;
1268 for (uint32_t j = 0; j < instanceCount; ++j) {
1269 while (b + 1 < bucketCount && cmds[b + 1].firstInstance <= j) ++b;
1270 gpuDrivenBucketIds_[j] = b;
1271 }
1272 }
1273
1274 auto &arena = currentFrameArena();
1275 // Storage-buffer descriptor offsets must honor minStorageBufferOffsetAlignment
1276 // (64 on this Intel driver); align conservatively to 64.
1277 gpuDrivenInstAlloc_ = arena.alloc(instanceCount * sizeof(GpuInstance), 64);
1278 gpuDrivenBucketIdAlloc_ = arena.alloc(instanceCount * sizeof(uint32_t), 64);
1279 gpuDrivenBucketOffAlloc_ = arena.alloc(bucketCount * sizeof(uint32_t), 64);
1280 if (!gpuDrivenInstAlloc_.mapped || !gpuDrivenBucketIdAlloc_.mapped ||
1281 !gpuDrivenBucketOffAlloc_.mapped) {
1282 gpuDrivenCullInstanceCount_ = 0;
1283 return false;
1284 }
1285 std::memcpy(gpuDrivenInstAlloc_.mapped, sorted.data(),
1286 instanceCount * sizeof(GpuInstance));
1287 std::memcpy(gpuDrivenBucketIdAlloc_.mapped, gpuDrivenBucketIds_.data(),
1288 instanceCount * sizeof(uint32_t));
1289 std::memcpy(gpuDrivenBucketOffAlloc_.mapped, gpuDrivenBucketOffsets_.data(),
1290 bucketCount * sizeof(uint32_t));
1291
1292 gpuDrivenBucketCount_ = bucketCount;
1293 gpuDrivenCullInstanceCount_ = instanceCount;
1294 lastGpuDrivenDrawCount_ = bucketCount; // debug counter: bucket draws the cull path emits
1295
1296 // Cull source buffers: sorted instances (17), bucket ids (12), offsets (13).
1297 const vk::DescriptorSet bindless = bindlessSetForFrame();
1298 if (!bindless) {
1299 gpuDrivenCullInstanceCount_ = 0;
1300 return false;
1301 }
1302 auto bufWrite = [&](uint32_t binding, vk::Buffer buffer, vk::DeviceSize offset,
1303 vk::DeviceSize size) {
1304 vk::DescriptorBufferInfo info{buffer, offset, size};
1305 vk::WriteDescriptorSet w{};
1306 w.dstSet = bindless;
1307 w.dstBinding = binding;
1308 w.descriptorCount = 1;
1309 w.descriptorType = vk::DescriptorType::eStorageBuffer;
1310 w.pBufferInfo = &info;
1311 device->updateDescriptorSets(1, &w, 0, nullptr);
1312 };
1313 bufWrite(17, arena.buffer(), gpuDrivenInstAlloc_.offset, gpuDrivenInstAlloc_.size);
1314 bufWrite(12, arena.buffer(), gpuDrivenBucketIdAlloc_.offset, gpuDrivenBucketIdAlloc_.size);
1315 bufWrite(13, arena.buffer(), gpuDrivenBucketOffAlloc_.offset, gpuDrivenBucketOffAlloc_.size);
1316 return true;
1317}
1318
1319void Graphics::gpuDrivenRecordComputeSection(const glm::mat4 &viewProj, const glm::vec3 &eye,
1320 float fovYDeg, float nearZ, float farZ) {
1321 if (!gpuDrivenCullReady_) return;
1322 auto &slot = currentGpuDrivenCullSlot();
1323 auto &cb = currentPresentCb();
1324 const vk::DescriptorSet bindless = bindlessSetForFrame();
1325 if (!bindless) return;
1326 // Lazily-created defaults register into the bindless set (bindings 0/1);
1327 // do it BEFORE the set is bound to the recording command buffer.
1328 ensureFlatNormalTexture3D();
1329 ensureFlatHeightTexture3D();
1330 ensureDefaultEnvCubemap();
1331 // Per-frame bindless updates must happen BEFORE the set is bound to the
1332 // recording command buffer (no UPDATE_AFTER_BIND): updating it afterwards
1333 // invalidates the command buffer (VUID-vkCmdBindPipeline-commandBuffer-recording).
1334 createGBufferResources(gbufferWidth > 0 ? gbufferWidth : int(swapchain.extent.width),
1335 gbufferHeight > 0 ? gbufferHeight : int(swapchain.extent.height));
1336 {
1337 auto *gbSlot = currentGBufferSlot();
1338 if (gbSlot && gbSlot->visIDGpu.sampler && gbSlot->visBaryGpu.sampler) {
1339 vk::DescriptorImageInfo visIDInfo{gbSlot->visIDGpu.sampler, gbSlot->visIDGpu.imageView(),
1340 vk::ImageLayout::eShaderReadOnlyOptimal};
1341 vk::DescriptorImageInfo visBaryInfo{gbSlot->visBaryGpu.sampler,
1342 gbSlot->visBaryGpu.imageView(),
1343 vk::ImageLayout::eShaderReadOnlyOptimal};
1344 vk::WriteDescriptorSet w[2]{};
1345 w[0].dstSet = bindless;
1346 w[0].dstBinding = 15;
1347 w[0].descriptorCount = 1;
1348 w[0].descriptorType = vk::DescriptorType::eCombinedImageSampler;
1349 w[0].pImageInfo = &visIDInfo;
1350 w[1].dstSet = bindless;
1351 w[1].dstBinding = 16;
1352 w[1].descriptorCount = 1;
1353 w[1].descriptorType = vk::DescriptorType::eCombinedImageSampler;
1354 w[1].pImageInfo = &visBaryInfo;
1355 device->updateDescriptorSets(2, w, 0, nullptr);
1356 }
1357 }
1358 bindVgFrameBindless(bindless, currentFrameSlot() % kAsyncResourceCopies);
1359
1360 GpuCullParams params{};
1361 params.viewProj = viewProj;
1362 gpuDrivenFrustumPlanes(viewProj, params.frustumPlanes);
1363 params.cameraPos = glm::vec4(eye, 0.f);
1364 const int w = gpuDrivenCullWidth;
1365 const int h = gpuDrivenCullHeight;
1366 params.screen = glm::vec4(float(w), float(h), 1.f / float(w), 1.f / float(h));
1367 const float fovRad = fovYDeg * 0.017453292519943295f;
1368 params.clipNearFar =
1369 glm::vec4(nearZ, farZ, float(h) * 0.5f / std::tan(fovRad * 0.5f), 1.f);
1370 params.hzbInfo =
1371 glm::vec4(float(gpuDrivenCullMaxMip), 0.f, float(w), float(h));
1372 params.counts = glm::uvec4(gpuDrivenCullInstanceCount_, gpuDrivenBucketCount_,
1374 {
1375 void *pMap = slot.cullParams.map();
1376 std::memcpy(pMap, &params, sizeof(params));
1377 slot.cullParams.unmap();
1378 }
1379
1380 auto bufWrite = [&](uint32_t binding, vk::Buffer buffer, vk::DeviceSize offset,
1381 vk::DeviceSize size, vk::DescriptorType type) {
1382 vk::DescriptorBufferInfo info{buffer, offset, size};
1383 vk::WriteDescriptorSet w{};
1384 w.dstSet = bindless;
1385 w.dstBinding = binding;
1386 w.descriptorCount = 1;
1387 w.descriptorType = type;
1388 w.pBufferInfo = &info;
1389 device->updateDescriptorSets(1, &w, 0, nullptr);
1390 };
1391 bufWrite(6, slot.cullParams.buffer, 0, sizeof(GpuCullParams),
1392 vk::DescriptorType::eUniformBuffer);
1393 bufWrite(7, slot.visibleFlags.buffer, 0, VK_WHOLE_SIZE,
1394 vk::DescriptorType::eStorageBuffer);
1395 bufWrite(8, slot.compacted.buffer, 0, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
1396 bufWrite(9, slot.indirect.buffer, 0, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
1397 bufWrite(30, slot.indirectNI.buffer, 0, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
1398 bufWrite(14, slot.bucketCounters.buffer, 0, VK_WHOLE_SIZE,
1399 vk::DescriptorType::eStorageBuffer);
1400 // The draw consumes the compacted buffer as its instance source (binding 4).
1401 bufWrite(4, slot.compacted.buffer, 0, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
1402 // HZB buffer + GBuffer depth sampler for the build pass.
1403 bufWrite(10, slot.hzb.buffer, 0, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
1404 {
1405 auto *gbSlot = currentGBufferSlot();
1406 if (gbSlot && gbSlot->depthGpu.sampler && gbSlot->depthGpu.imageView()) {
1407 vk::DescriptorImageInfo depthInfo{gbSlot->depthGpu.sampler, gbSlot->depthGpu.imageView(),
1408 vk::ImageLayout::eShaderReadOnlyOptimal};
1409 vk::WriteDescriptorSet wd{};
1410 wd.dstSet = bindless;
1411 wd.dstBinding = 11;
1412 wd.descriptorCount = 1;
1413 wd.descriptorType = vk::DescriptorType::eCombinedImageSampler;
1414 wd.pImageInfo = &depthInfo;
1415 device->updateDescriptorSets(1, &wd, 0, nullptr);
1416 }
1417 }
1418
1419 // All descriptor updates are done; bind the bindless set ONCE for the
1420 // whole compute section (the set is not UPDATE_AFTER_BIND, so updating it
1421 // while bound to a recording command buffer would invalidate the buffer).
1422 cb.bindDescriptorSets(vk::PipelineBindPoint::eCompute, gpuDrivenComputeLayout, 1, 1,
1423 &bindless, 0, nullptr);
1424
1425 recordGpuDrivenHzbBuild();
1426
1427 // HZB build writes (storage buffer) -> cull reads.
1428 {
1429 vk::BufferMemoryBarrier bmb{};
1430 bmb.buffer = slot.hzb.buffer;
1431 bmb.size = VK_WHOLE_SIZE;
1432 bmb.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
1433 bmb.dstAccessMask = vk::AccessFlagBits::eShaderRead;
1434 cb.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader,
1435 vk::PipelineStageFlagBits::eComputeShader, {}, 0, nullptr, 1, &bmb, 0,
1436 nullptr);
1437 }
1438}
1439
1440void Graphics::gpuDrivenVgComputeSection(const glm::mat4 &viewProj, const glm::vec3 &eye,
1441 float fovYDeg, float nearZ, float farZ) {
1442 gpuDrivenRecordComputeSection(viewProj, eye, fovYDeg, nearZ, farZ);
1443}
1444
1445void Graphics::gpuDrivenCullEmit(const glm::mat4 &viewProj, const glm::vec3 &eye, float fovYDeg,
1446 float nearZ, float farZ) {
1447 if (!gpuDrivenCullReady_ || gpuDrivenCullInstanceCount_ == 0) return;
1448 gpuDrivenLastCullSlot_ = uint32_t(currentFrameSlot());
1449 auto &slot = currentGpuDrivenCullSlot();
1450 auto &cb = currentPresentCb();
1451 // This frame's own bindless set: the previous frame that owned this slot
1452 // completed at acquireForFrame()'s fence wait, so rewriting it is safe.
1453 const vk::DescriptorSet bindless = bindlessSetForFrame();
1454 if (!bindless) return;
1455
1456 // CPU reset of GPU-owned per-slot state (slot's previous frame is complete).
1457 {
1458 void *flagsMap = slot.visibleFlags.map();
1459 std::memset(flagsMap, 0, kMaxGpuDrivenInstances * sizeof(uint32_t));
1460 slot.visibleFlags.unmap();
1461 void *counterMap = slot.bucketCounters.map();
1462 std::memset(counterMap, 0, kMaxGpuDrivenBuckets * sizeof(uint32_t));
1463 slot.bucketCounters.unmap();
1464 // The emit pass only writes buckets that survived culling; clear the
1465 // commands so a stale instanceCount from an earlier frame cannot make
1466 // a culled bucket draw again (readbacks / validation read this too).
1467 void *cmdMap = slot.indirect.map();
1468 std::memset(cmdMap, 0, kMaxGpuDrivenBuckets * sizeof(GpuIndirectCommand));
1469 slot.indirect.unmap();
1470 }
1471
1472 gpuDrivenRecordComputeSection(viewProj, eye, fovYDeg, nearZ, farZ);
1473
1474 const uint32_t groups = (gpuDrivenCullInstanceCount_ + 63u) / 64u;
1475 // Arena host writes + previous-frame HZB shader writes visible to cull.
1476 {
1477 vk::BufferMemoryBarrier bmb{};
1478 bmb.buffer = currentFrameArena().buffer();
1479 bmb.size = VK_WHOLE_SIZE;
1480 bmb.srcAccessMask = vk::AccessFlagBits::eHostWrite | vk::AccessFlagBits::eShaderWrite;
1481 bmb.dstAccessMask = vk::AccessFlagBits::eShaderRead;
1482 cb.pipelineBarrier(vk::PipelineStageFlagBits::eHost |
1483 vk::PipelineStageFlagBits::eComputeShader,
1484 vk::PipelineStageFlagBits::eComputeShader, {}, 0, nullptr, 1, &bmb, 0,
1485 nullptr);
1486 }
1487 cullPass_.record(cb, groups, 1, 1);
1488
1489 // Cull flags write -> emit read.
1490 {
1491 vk::BufferMemoryBarrier bmb{};
1492 bmb.buffer = slot.visibleFlags.buffer;
1493 bmb.size = VK_WHOLE_SIZE;
1494 bmb.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
1495 bmb.dstAccessMask = vk::AccessFlagBits::eShaderRead;
1496 cb.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader,
1497 vk::PipelineStageFlagBits::eComputeShader, {}, 0, nullptr, 1, &bmb, 0,
1498 nullptr);
1499 }
1500 emitPass_.record(cb, groups, 1, 1);
1501
1502 // Emit writes (compacted + commands) -> vertex read + indirect read.
1503 {
1504 vk::BufferMemoryBarrier bmb[2]{};
1505 bmb[0].buffer = slot.compacted.buffer;
1506 bmb[0].size = VK_WHOLE_SIZE;
1507 bmb[0].srcAccessMask = vk::AccessFlagBits::eShaderWrite;
1508 bmb[0].dstAccessMask = vk::AccessFlagBits::eShaderRead;
1509 bmb[1].buffer = slot.indirect.buffer;
1510 bmb[1].size = VK_WHOLE_SIZE;
1511 bmb[1].srcAccessMask = vk::AccessFlagBits::eShaderWrite;
1512 bmb[1].dstAccessMask = vk::AccessFlagBits::eIndirectCommandRead;
1513 cb.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader,
1514 vk::PipelineStageFlagBits::eVertexShader |
1515 vk::PipelineStageFlagBits::eDrawIndirect,
1516 {}, 0, nullptr, 2, bmb, 0, nullptr);
1517 }
1518}
1519
1521 if (!gpuDrivenScenePassPending_) return;
1522 gpuDrivenScenePassPending_ = false;
1523 if (beginSceneColorRenderPass()) {
1524 ensureScenePassPipelines(activeScenePass(), activeSceneSamples());
1525 } else {
1526 ensureScenePassPipelines(renderpass, vk::SampleCountFlagBits::e1);
1527 beginSwapchainColorPass();
1528 }
1529 swapchainPassOpen = true;
1530}
1531
1532Graphics::GpuDrivenFrameSet0 Graphics::gpuDrivenFrameSet0() {
1533 // Per-frame set0 + UBO (same shading state as the stage-1 path).
1534 ensureFlatNormalTexture3D();
1535 ensureFlatHeightTexture3D();
1536 ensureDefaultEnvCubemap();
1537 Texture *tex = whiteTexture;
1538 auto *gpuTex = static_cast<GpuTexture *>(tex->gpuHandle);
1539 auto *gpuNormal = static_cast<GpuTexture *>(mesh3dNormalTexture ? mesh3dNormalTexture->gpuHandle
1540 : flatNormalTexture3D->gpuHandle);
1541 auto *gpuHeight = static_cast<GpuTexture *>(mesh3dHeightTexture ? mesh3dHeightTexture->gpuHandle
1542 : flatHeightTexture3D->gpuHandle);
1543 Texture *envTex = mesh3dEnvTexture ? mesh3dEnvTexture : defaultEnvCubemap;
1544 auto *gpuEnv = static_cast<GpuTexture *>(envTex->gpuHandle);
1545 auto *gpuDepth = static_cast<GpuTexture *>(whiteTexture->gpuHandle);
1546 ensureDecalPlaceholders();
1547 auto *gpuDecalAlb = static_cast<GpuTexture *>(decalFlatAlbedo->gpuHandle);
1548 auto *gpuDecalNrm = static_cast<GpuTexture *>(decalFlatNormal->gpuHandle);
1549 auto *gpuDecalPrm = static_cast<GpuTexture *>(decalFlatParams->gpuHandle);
1550 if (decalLayerFresh) {
1551 if (auto *dslot = currentDecalSlot()) {
1552 gpuDecalAlb = &dslot->albedoGpu;
1553 gpuDecalNrm = &dslot->normalGpu;
1554 gpuDecalPrm = &dslot->paramsGpu;
1555 }
1556 }
1557
1558 Mesh3DUBO ubo = mesh3dFrameUbo;
1559 ubo.model = glm::mat4(1.f);
1560 ubo.tint = glm::vec4(1.f);
1561 const int lightCount = std::max(0, std::min(mesh3dLighting.count, Lighting3DPack::kMaxLights));
1562 ubo.lightDir.w = float(lightCount);
1563 ubo.cameraPos.w = mesh3dRoughness;
1564 ubo.lightColor.w = mesh3dEnvIntensity;
1565 const uint32_t envSlot = gpuEnv->bindlessIndexCube;
1568 for (int i = 0; i < ReflectionProbeUpload::kMaxProbes; ++i) {
1569 if (i >= mesh3dReflectionProbes.count) continue;
1570 const auto &probe = mesh3dReflectionProbes.probes[i];
1571 if (!probe.cubemap || !probe.cubemap->gpuHandle) continue;
1572 auto *gpuProbe = static_cast<GpuTexture *>(probe.cubemap->gpuHandle);
1573 if (!gpuProbe->isCube || gpuProbe->bindlessIndexCube == kInvalidBindlessSlot) continue;
1574 probeSlots[i] = gpuProbe->bindlessIndexCube;
1575 ubo.reflectionProbeCenter[i] = glm::vec4(probe.center, probe.intensity);
1576 ubo.reflectionProbeExtent[i] = glm::vec4(probe.extent, probe.blendDistance);
1577 }
1578 ubo.bindlessEnv = glm::vec4(float(envSlot), mesh3dEnvIntensity,
1579 float(probeSlots[0]), float(probeSlots[1]));
1580 ubo.ambient = glm::vec4(glm::vec3(mesh3dLighting.ambient), mesh3dMetallic);
1581 for (int i = 0; i < lightCount; ++i) ubo.lights[i] = mesh3dLighting.lights[i];
1582 int dirI = -1;
1583 for (int i = 0; i < lightCount; ++i) {
1584 if (mesh3dLighting.lights[i].posRadius.w <= 0.f) {
1585 dirI = i;
1586 break;
1587 }
1588 }
1589 if (dirI >= 0) {
1590 glm::vec3 d(mesh3dLighting.lights[dirI].posRadius);
1591 if (glm::length(d) < 1e-6f) d = glm::vec3(0.f, 1.f, 0.f);
1592 else d = glm::normalize(d);
1593 ubo.lightDir = glm::vec4(d, float(lightCount));
1594 ubo.lightColor =
1595 glm::vec4(glm::vec3(mesh3dLighting.lights[dirI].color), mesh3dEnvIntensity);
1596 } else {
1597 ubo.lightDir = glm::vec4(0.f, 1.f, 0.f, float(lightCount));
1598 ubo.lightColor = glm::vec4(0.f, 0.f, 0.f, mesh3dEnvIntensity);
1599 }
1600 auto &fslots = currentMesh3dFrameSlots();
1601 if (fslots.drawIndex >= fslots.capacity) {
1602 std::fprintf(stderr, "[vulkan] mesh3d UBO ring exhausted; gpu-driven draw skipped\n");
1603 return {};
1604 }
1605 const size_t slot = fslots.drawIndex++;
1606 ensureMesh3dStrides();
1607 const uint32_t uboOffset = uint32_t(slot) * mesh3dUboStride;
1608 const uint32_t shadowOffset = uint32_t(slot) * shadowUboStride;
1609 updateRingLocal(fslots.uboRing, uboOffset, &ubo, sizeof(ubo));
1610 ShadowUBO shadowUbo = mesh3dShadows.ubo;
1611 if (!mesh3dShadows.active) {
1612 shadowUbo.bias.y = 0.f;
1613 shadowUbo.splits.w = 0.f;
1614 }
1615 shadowUbo.bias.z = mesh3dShadowReceive ? 1.f : 0.f;
1616 updateRingLocal(fslots.shadowRing, shadowOffset, &shadowUbo, sizeof(shadowUbo));
1617 auto *gpuSceneColor = mesh3dSceneColorTexture && mesh3dSceneColorTexture->gpuHandle
1618 ? static_cast<GpuTexture *>(mesh3dSceneColorTexture->gpuHandle)
1619 : sceneColorHistoryValid && completedSceneColorSlot < sceneColorSlots.size()
1620 ? &sceneColorSlots[completedSceneColorSlot].colorGpu
1621 : static_cast<GpuTexture *>(whiteTexture->gpuHandle);
1622 uploadSkinPalette(nullptr, fslots);
1623 vk::DescriptorSet set = mesh3dSetFor(gpuTex, gpuNormal, gpuEnv, gpuHeight, gpuDepth, gpuSceneColor, gpuDecalAlb,
1624 gpuDecalNrm, gpuDecalPrm, fslots, {});
1625 return {set, uboOffset, shadowOffset};
1626}
1627
1629 if (!gpuDrivenCullReady_ || gpuDrivenBucketCount_ == 0) return;
1630 if (!swapchainPassOpen && !sceneColorPassOpen) return;
1631 auto &slot = currentGpuDrivenCullSlot();
1632
1633 const Graphics::GpuDrivenFrameSet0 s0 = gpuDrivenFrameSet0();
1634 if (!s0.set) return;
1635 const uint32_t dynOffsets[2] = {s0.uboOffset, s0.shadowOffset};
1636
1637 auto &cb = currentPresentCb();
1638 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipeline);
1639 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 0, 1,
1640 &s0.set, 2, dynOffsets);
1641 const vk::DescriptorSet bindless = bindlessSetForFrame();
1642 if (!bindless) return;
1643 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 1, 1,
1644 &bindless, 0, nullptr);
1645
1646 const vk::DeviceSize stride = sizeof(GpuIndirectCommand);
1647 GpuMesh *boundMesh = nullptr;
1648 for (uint32_t b = 0; b < gpuDrivenBucketCount_; ++b) {
1649 const uint32_t meshId = gpuDrivenBucketMeshIds_[b];
1650 if (meshId >= meshRecordOwners_.size()) continue;
1651 GpuMesh *mesh = meshRecordOwners_[meshId];
1652 if (mesh != boundMesh) {
1653 const vk::DeviceSize vbOffset = 0;
1654 cb.bindVertexBuffers(0, 1, mesh->vertices, &vbOffset);
1655 cb.bindIndexBuffer(mesh->indices.buffer, 0, mesh->indexType);
1656 boundMesh = mesh;
1657 }
1658 cb.drawIndexedIndirect(slot.indirect.buffer, vk::DeviceSize(b) * stride, 1, stride);
1659 }
1660}
1661
1663 if (!gpuDrivenCullReady_) return;
1664 if (gpuDrivenBucketCount_ == 0 && !vgAnyThisFrame_) return;
1665 // The vis attachments live in the GBuffer slot set; make sure it exists
1666 // even when the AO/gbuffer feature is off (resolve needs it anyway).
1667 createGBufferResources(gbufferWidth > 0 ? gbufferWidth : int(swapchain.extent.width),
1668 gbufferHeight > 0 ? gbufferHeight : int(swapchain.extent.height));
1669 auto *slot = currentGBufferSlot();
1670 if (!slot || !gbufferVisPipeline || !gbufferVisRenderPass || !slot->visFramebuffer) return;
1671 auto &cull = currentGpuDrivenCullSlot();
1672 auto &cb = currentPresentCb();
1673 // Stage 3 VG: cluster cull (frustum + HZB) runs right before the vis pass.
1674 recordVgCull();
1675
1676 const uint32_t w = uint32_t(gbufferWidth);
1677 const uint32_t h = uint32_t(gbufferHeight);
1678 std::array<vk::ClearValue, 6> clears{};
1679 clears[0].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
1680 clears[1].color = vk::ClearColorValue(std::array<float, 4>{1, 1, 1, 1});
1681 clears[2].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
1682 clears[3].color = vk::ClearColorValue(std::array<uint32_t, 4>{0xFFFFFFFFu, 0u, 0u, 0u});
1683 clears[4].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
1684 clears[5].depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
1685 vk::RenderPassBeginInfo rpBegin{};
1686 rpBegin.renderPass = gbufferVisRenderPass;
1687 rpBegin.framebuffer = slot->visFramebuffer;
1688 rpBegin.renderArea = vk::Rect2D{{0, 0}, {w, h}};
1689 rpBegin.clearValueCount = uint32_t(clears.size());
1690 rpBegin.pClearValues = clears.data();
1691 slot->normal.beginColorAttachment();
1692 slot->depthColor.beginColorAttachment();
1693 slot->albedo.beginColorAttachment();
1694 slot->visID.beginColorAttachment();
1695 slot->visBary.beginColorAttachment();
1696 slot->depth.beginDepthAttachment();
1697 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
1698 setViewportAndScissor(cb, w, h);
1699
1700 const Graphics::GpuDrivenFrameSet0 s0 = gpuDrivenFrameSet0();
1701 const vk::DescriptorSet bindless = bindlessSetForFrame();
1702 if (s0.set && bindless) {
1703 const uint32_t dynOffsets[2] = {s0.uboOffset, s0.shadowOffset};
1704 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, gbufferVisPipeline);
1705 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 0,
1706 1, &s0.set, 2, dynOffsets);
1707 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 1,
1708 1, &bindless, 0, nullptr);
1709 const vk::DeviceSize stride = sizeof(glm::uvec4);
1710 for (uint32_t b = 0; b < gpuDrivenBucketCount_; ++b) {
1711 cb.drawIndirect(cull.indirectNI.buffer, vk::DeviceSize(b) * stride, 1, stride);
1712 }
1713 if (vgAnyThisFrame_) drawVgClusters(cb);
1714 }
1715 cb.endRenderPass();
1716 slot->normal.endSampledLayout();
1717 slot->depthColor.endSampledLayout();
1718 slot->albedo.endSampledLayout();
1719 slot->visID.endSampledLayout();
1720 slot->visBary.endSampledLayout();
1721 slot->depth.endSampledLayout();
1722}
1723
1725 if (!gpuDrivenCullReady_) return;
1726 if (gpuDrivenBucketCount_ == 0 && !vgAnyThisFrame_) return;
1727 if (!swapchainPassOpen && !sceneColorPassOpen) return;
1728 if (!resolveVisPipeline || !mesh3dGpuDrivenPipelineLayout) return;
1729 auto *slot = currentGBufferSlot();
1730 if (!slot || !slot->visIDGpu.sampler || !slot->visBaryGpu.sampler) return;
1731 auto &cb = currentPresentCb();
1732 const vk::DescriptorSet bindless = bindlessSetForFrame();
1733 if (!bindless) return;
1734
1735 const Graphics::GpuDrivenFrameSet0 s0 = gpuDrivenFrameSet0();
1736 if (!s0.set) return;
1737 const uint32_t dynOffsets[2] = {s0.uboOffset, s0.shadowOffset};
1738 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, resolveVisPipeline);
1739 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 0, 1,
1740 &s0.set, 2, dynOffsets);
1741 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 1, 1,
1742 &bindless, 0, nullptr);
1743 const uint32_t w =
1744 uint32_t(sceneColorPassOpen ? sceneColorWidth : int(swapchain.extent.width));
1745 const uint32_t h =
1746 uint32_t(sceneColorPassOpen ? sceneColorHeight : int(swapchain.extent.height));
1747 setViewportAndScissor(cb, w, h);
1748 cb.draw(3, 1, 0, 0);
1749}
1750
1751void Graphics::createResolveVisPipeline(const vkb::BuiltRenderPass &rp,
1752 vk::SampleCountFlagBits samples) {
1753 destroyPipeline(device, resolveVisPipeline);
1754 if (!mesh3dGpuDrivenPipelineLayout) return;
1755 std::vector<uint32_t> vert(resolve_vis_vert_spv, resolve_vis_vert_spv +
1756 resolve_vis_vert_spv_count);
1757 std::vector<uint32_t> frag(resolve_vis_frag_spv, resolve_vis_frag_spv +
1758 resolve_vis_frag_spv_count);
1759 vk::ShaderModule vertModule = vkb::PipelineBuilder::createShaderModule(device.instance, vert);
1760 vk::ShaderModule fragModule = vkb::PipelineBuilder::createShaderModule(device.instance, frag);
1761 resolveVisPipeline =
1762 device.createPipeline()
1763 .useClassicPipeline(vertModule, fragModule)
1764 .setPipelineLayout(mesh3dGpuDrivenPipelineLayout)
1765 .setDynamicStatesViewportScissor()
1766 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
1767 vk::CullModeFlagBits::eNone, vk::FrontFace::eClockwise)
1768 .setMultisampler(false, samples)
1769 .setDepthStencil(true, true, vk::CompareOp::eLessOrEqual)
1770 .setColorAttachmentCount(1)
1771 .build(rp);
1772 device->destroyShaderModule(vertModule);
1773 device->destroyShaderModule(fragModule);
1774}
1775
1776void Graphics::recordVgCull() {
1777 if (!gpuDrivenCullReady_ || vgAssetCount_ == 0 || vgClusterCount_ == 0) return;
1778 if (!vgCullPass_.pipeline() || !vgGpu_.visible.buffer) return;
1779 auto &cb = currentPresentCb();
1780 const vk::DescriptorSet bindless = bindlessSetForFrame();
1781 if (!bindless) return;
1782
1783 const size_t slot = currentFrameSlot() % kAsyncResourceCopies;
1784 vgLastVisible_ = uint32_t(slot);
1785
1786 // Uploads and per-frame instance/material projections are written through
1787 // host-visible mappings. Make those writes available before the compute
1788 // cull and the following vertex/fragment fetches; validation layers can
1789 // otherwise hide this race by perturbing submission timing.
1790 {
1791 std::array<vk::BufferMemoryBarrier, 6> barriers{};
1792 const vk::Buffer buffers[] = {
1793 vgGpu_.positions.buffer, vgGpu_.triangles.buffer, vgGpu_.clusters.buffer,
1794 vgGpu_.clusterAssets.buffer, vgGpu_.assetMaterials.buffer, vgGpu_.assetModels.buffer,
1795 };
1796 for (size_t i = 0; i < barriers.size(); ++i) {
1797 barriers[i].buffer = buffers[i];
1798 barriers[i].size = VK_WHOLE_SIZE;
1799 barriers[i].srcAccessMask = vk::AccessFlagBits::eHostWrite;
1800 barriers[i].dstAccessMask = vk::AccessFlagBits::eShaderRead;
1801 }
1802 cb.pipelineBarrier(vk::PipelineStageFlagBits::eHost,
1803 vk::PipelineStageFlagBits::eComputeShader |
1804 vk::PipelineStageFlagBits::eVertexShader |
1805 vk::PipelineStageFlagBits::eFragmentShader,
1806 {}, 0, nullptr, uint32_t(barriers.size()), barriers.data(), 0, nullptr);
1807 }
1808
1809 // Reset this slot's visible counter (the slot's fence was waited at frame
1810 // begin, so the previous use of this slot's buffers has completed).
1811 {
1812 const vk::DeviceSize slotVis = (vk::DeviceSize(kMaxVgClusters) + 1) * sizeof(uint32_t);
1813 void *map = vgGpu_.visible.map();
1814 if (!map) return;
1815 std::memset(static_cast<char *>(map) + slotVis * slot, 0, sizeof(uint32_t));
1816 vgGpu_.visible.unmap();
1817 }
1818
1819 cb.bindDescriptorSets(vk::PipelineBindPoint::eCompute, gpuDrivenComputeLayout, 1, 1,
1820 &bindless, 0, nullptr);
1821 const uint32_t push[4]{vgClusterCount_, 0u, 0u, 0u};
1822 cb.pushConstants(gpuDrivenComputeLayout, vk::ShaderStageFlagBits::eCompute, 0, sizeof(push),
1823 push);
1824 vgCullPass_.record(cb, (vgClusterCount_ + 63u) / 64u);
1825
1826 // VG cull writes (visible + indirect) -> vertex read + indirect read.
1827 {
1828 vk::BufferMemoryBarrier bmb[2]{};
1829 bmb[0].buffer = vgGpu_.visible.buffer;
1830 bmb[0].size = VK_WHOLE_SIZE;
1831 bmb[0].srcAccessMask = vk::AccessFlagBits::eShaderWrite;
1832 bmb[0].dstAccessMask = vk::AccessFlagBits::eShaderRead;
1833 bmb[1].buffer = vgGpu_.indirect.buffer;
1834 bmb[1].size = VK_WHOLE_SIZE;
1835 bmb[1].srcAccessMask = vk::AccessFlagBits::eShaderWrite;
1836 bmb[1].dstAccessMask = vk::AccessFlagBits::eIndirectCommandRead;
1837 cb.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader,
1838 vk::PipelineStageFlagBits::eVertexShader |
1839 vk::PipelineStageFlagBits::eDrawIndirect,
1840 {}, 0, nullptr, 2, bmb, 0, nullptr);
1841 }
1842}
1843
1844void Graphics::drawVgClusters(vk::CommandBuffer cb) {
1845 if (!gbufferVgVisPipeline || vgAssetCount_ == 0 || vgClusterCount_ == 0) return;
1846 const vk::DescriptorSet bindless = bindlessSetForFrame();
1847 if (!bindless || !mesh3dGpuDrivenPipelineLayout) return;
1848 const size_t slot = currentFrameSlot() % kAsyncResourceCopies;
1849 const vk::DeviceSize slotInd = vk::DeviceSize(kMaxVgClusters) * sizeof(glm::uvec4);
1850 const vk::DeviceSize slotVis = (vk::DeviceSize(kMaxVgClusters) + 1) * sizeof(uint32_t);
1851 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, gbufferVgVisPipeline);
1852 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dGpuDrivenPipelineLayout, 1, 1,
1853 &bindless, 0, nullptr);
1854 cb.drawIndirectCount(vgGpu_.indirect.buffer, slotInd * slot, vgGpu_.visible.buffer,
1855 slotVis * slot, kMaxVgClusters, sizeof(glm::uvec4));
1856}
1857
1859 if (!gpuDrivenCullReady_ || gpuDrivenCullSlots_.empty()) return 0;
1860 auto &slot = gpuDrivenCullSlots_[gpuDrivenLastCullSlot_ % gpuDrivenCullSlots_.size()];
1861 uint32_t count = 0;
1862 void *map = slot.visibleFlags.map();
1863 if (!map) return 0;
1864 const uint32_t n = std::min(gpuDrivenCullInstanceCount_, kMaxGpuDrivenInstances);
1865 const auto *flags = static_cast<const uint32_t *>(map);
1866 for (uint32_t i = 0; i < n; ++i) count += flags[i] != 0 ? 1u : 0u;
1867 slot.visibleFlags.unmap();
1868 return count;
1869}
1870
1872 if (!gpuDrivenCullReady_ || gpuDrivenCullSlots_.empty()) return 0;
1873 auto &slot = gpuDrivenCullSlots_[gpuDrivenLastCullSlot_ % gpuDrivenCullSlots_.size()];
1874 uint32_t count = 0;
1875 void *map = slot.indirect.map();
1876 if (!map) return 0;
1877 const auto *cmds = static_cast<const GpuIndirectCommand *>(map);
1878 const uint32_t n = std::min(gpuDrivenBucketCount_, kMaxGpuDrivenBuckets);
1879 for (uint32_t b = 0; b < n; ++b) count += cmds[b].instanceCount > 0 ? 1u : 0u;
1880 slot.indirect.unmap();
1881 return count;
1882}
1883
1885 if (!tex || !tex->gpuHandle) return kInvalidBindlessSlot;
1886 return static_cast<GpuTexture *>(tex->gpuHandle)->bindlessIndex2D;
1887}
1888
1890 if (!mesh || !mesh->gpuHandle) return kInvalidBindlessSlot;
1891 return static_cast<GpuMesh *>(mesh->gpuHandle)->gpuRecordIndex;
1892}
1893
1894void Graphics::createMesh3DGpuDrivenPipeline() {
1895 if (mesh3dGpuDrivenPipeline) return;
1896 if (!mesh3dSetLayout || !bindlessSetLayout_ || !gpuDrivenCaps_.gpuDrivenAvailable()) return;
1897
1898 // Pipeline layout: set0 = per-frame (legacy mesh3d layout), set1 = bindless.
1899 // No push constants: instance indexing relies on gl_InstanceIndex, which
1900 // already includes the command's firstInstance per the Vulkan spec.
1901 std::array<vk::DescriptorSetLayout, 2> setLayouts{mesh3dSetLayout, bindlessSetLayout_};
1902 vk::PipelineLayoutCreateInfo pli{};
1903 pli.setLayoutCount = uint32_t(setLayouts.size());
1904 pli.pSetLayouts = setLayouts.data();
1905 mesh3dGpuDrivenPipelineLayout = device->createPipelineLayout(pli);
1906 mesh3dGpuDrivenPipeline =
1907 createMesh3DStylePipeline(embeddedSpirv(mesh3d_gpudriven_vert_spv),
1908 embeddedSpirv(mesh3d_gpudriven_frag_spv),
1909 mesh3dGpuDrivenPipelineLayout, renderpass,
1910 vk::SampleCountFlagBits::e1);
1911}
1912} // namespace eve::graphics::vulkan
double m[16]
float w
Definition AnimClip.cpp:738
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
const std::string & s
float planes[6][4]
glm::vec4 p[6]
std::vector< std::uint8_t > stored
Definition Evpack.cpp:171
vk::ShaderModule vert
vk::ShaderModule frag
std::uint32_t firstInstance
std::uint32_t instanceCount
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::int32_t first
int h
std::uint32_t height
std::uint32_t width
std::function< void(b3JointId, const Numbers &)> write
size_t offset
bool required
std::vector< RecipeParam > params
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< std::int32_t > order
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
ssq::Object frame
uint32_t groups
Definition OnnxGpgpu.cpp:39
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
eve::action::ActionVfxBinding binding
std::array< uint32_t, 16 > material
int idx
std::vector< ParticleBakeMaterial > bindings
std::array< std::uint64_t, kPixelChunkSize *kPixelChunkSize > updated
float d
float t
std::string slot
Local-probe upload record kept off the high-fanout IGraphics3D header.
glm::vec3 eye
float fovRad
glm::mat4 viewProj
glm::mat4 model
bool found
size_t end
int count
int limit
Definition TreeMesh.cpp:166
float size
Definition TreeMesh.cpp:158
std::vector< VegetationPresetCommand > commands
uint32_t flags
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
void push(bool all)
Pushes .
std::unique_ptr< RenderControl > renderControl_
Definition Graphics.h:2340
CPU-side builder for GPU-driven indirect draws (stage 1).
uint32_t build(const std::vector< GpuMeshRecord > &meshTable)
Sort + merge. meshTable supplies indexCount/firstIndex/vertexBase.
void add(uint32_t seq, uint32_t meshId, uint32_t materialId, uint32_t pipelineId)
seq = monotonic instance sequence (stable order tiebreak).
const std::vector< GpuIndirectCommand > & commands() const
Commands.
const std::vector< uint32_t > & sortedInstanceOrder() const
Instance indices in the sorted order the caller must upload.
Packages shading method + surface parameters into one attachable asset.
Definition Material.h:38
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
bool create(vkb::Device &device, vk::PipelineLayout layout, const std::vector< uint32_t > &spv)
Create from embedded SPIR-V words; layout must outlive the pass.
vk::Pipeline pipeline() const
Pipeline.
Definition ComputePass.h:42
void record(vk::CommandBuffer cb, uint32_t groupsX, uint32_t groupsY=1, uint32_t groupsZ=1) const
Record one dispatch (local size baked into the shader).
bool gpuDrivenCullEnabled() const
Stage 2 cull is live for this frame (GPU-written commands).
Definition Graphics.h:528
Result< void > gpuDrivenReleaseMaterialRecord(Material *material) override
Gpu driven release material record.
uint32_t gpuDrivenMeshRecord(Mesh *mesh) override
Gpu driven mesh record.
uint32_t gpuDrivenVgAssetId(Mesh *mesh) const override
Gpu driven vg asset id.
uint32_t debugMeshRecordIndex(Mesh *mesh) const
Debug mesh record index.
bool gpuDrivenVgSetInstance(uint32_t vgAssetId, const glm::mat4 &model, uint32_t materialId) override
Gpu driven vg set instance.
void gpuDrivenVgComputeSection(const glm::mat4 &viewProj, const glm::vec3 &eye, float fovYDeg, float nearZ, float farZ) override
Gpu driven vg compute section.
bool gpuDrivenMaterialUsable(Material *material) override
Gpu driven material usable.
GpuResidentSubmitStatus gpuDrivenSubmitResident(const GpuResidentInstanceBatch &batch) override
Gpu driven submit resident.
void syncMaterialTable()
Upload all registered material records to the GPU table.
uint32_t debugGpuDrivenCulledDrawCount() const
Debug gpu driven culled draw count.
uint32_t debugGpuDrivenVgVisibleCount() const
Debug readback: visible VG clusters from the last cull.
uint32_t materialTableGetOrCreate(eve::graphics::Material *material)
Get (or lazily create) the GPU material-table slot for a material.
bool gpuDrivenCullBegin(const GpuInstance *instances, uint32_t instanceCount)
Gpu driven cull begin.
void gpuDrivenResolve() override
Gpu driven resolve.
bool gpuDrivenResolveWanted() const override
Stage 3: vis+resolve live for this frame (opt-in, 1x scene pass).
void gpuDrivenDrawOpaque()
Gpu driven draw opaque.
bool gpuDrivenEnabled() const override
Gpu driven enabled.
Definition Graphics.h:468
uint32_t gpuDrivenVgUpload(const GpuVgAssetUpload &asset) override
Gpu driven vg upload.
void gpuDrivenOpenScenePass()
Gpu driven open scene pass.
bool gpuDrivenScenePassPending() const
Scene color pass is deferred until after the compute cull section.
Definition Graphics.h:532
uint32_t debugBindlessIndex(Texture *tex) const
Test/debug helpers (valid when the GPU-driven path is live).
uint32_t debugGpuDrivenVisibleCount() const
Debug readback: visible instances / non-empty buckets from the last cull.
void gpuDrivenRecordVisPass() override
Gpu driven record vis pass.
bool gpuDrivenVgAttachToMesh(Mesh *mesh, uint32_t vgAssetId) override
Gpu driven vg attach to mesh.
bool gpuDrivenSubmitOpaque(const GpuInstance *instances, uint32_t instanceCount) override
Gpu driven submit opaque.
void gpuDrivenCullEmit(const glm::mat4 &viewProj, const glm::vec3 &eye, float fovYDeg, float nearZ, float farZ)
Gpu driven cull emit.
uint32_t gpuDrivenReflectionProbeSlot(Texture *cubemap) override
Gpu driven reflection probe slot.
FrameArena & currentFrameArena()
Per-frame arena for the current swapchain frame slot.
constexpr uint32_t kMaxGpuDrivenBuckets
Definition GpuDriven.h:24
vkb::FrameArena FrameArena
Engine alias for the VKBuilder per-frame bump allocator.
Definition FrameArena.h:8
eve::graphics::GpuIndirectCommand GpuIndirectCommand
Definition GpuDriven.h:18
constexpr uint32_t kMaxHzbMips
Definition GpuDriven.h:25
constexpr uint32_t kMaxBindlessCubemaps
Definition GpuDriven.h:20
constexpr uint32_t kMaxGpuDrivenInstances
Definition GpuDriven.h:23
constexpr uint32_t kInvalidBindlessSlot
Definition GpuDriven.h:22
constexpr uint32_t kHZBHeaderWords
Definition GpuDriven.h:26
constexpr uint32_t kMaxBindlessTextures
Definition GpuDriven.h:19
eve::graphics::GpuMeshRecord GpuMeshRecord
GPU-driven rendering shared constants + std430 GPU layouts.
Definition GpuDriven.h:15
eve::graphics::GpuMaterialRecord GpuMaterialRecord
Definition GpuDriven.h:16
eve::graphics::GpuInstance GpuInstance
Definition GpuDriven.h:17
constexpr uint32_t kInvalidGpuDrivenSlot
GPU-driven API surface without GLM layout records.
GpuResidentSubmitStatus
Structured result for direct resident-instance submission.
size_t elementSize(OnnxElement e)
Element size.
constexpr uint64_t kGpuResidentStorageOffsetAlignment
Portable alignment required for resident storage-buffer slice offsets.
Indirect draw command; layout identical to VkDrawIndexedIndirectCommand.
Per-instance GPU record (std430). Mirrors GLSL GpuInstance.
GPU material table record (std430). Mirrors GLSL GpuMaterialRecord.
GPU-driven rendering std430 GPU layouts.
Direct-render description for a GPU-authored array of GpuInstance records. @ownership buckets and buf...
const GpuResidentInstanceBucket * buckets
One contiguous mesh/material bucket in a sorted resident instance buffer.
Neutral GPU upload for one virtual-geometry asset. Raw arrays so the graphics module does not depend ...
const std::uint32_t * triangles
GPU-packed cluster node (std430, 4 x uvec4). Mirrors the virtualgeometry module's VgGpuCluster layout...
static constexpr int kMaxLights
Definition Light.h:172
Light3DGpu lights[kMaxLights]
Definition Light.h:174
bool gpuDrivenAvailable() const
Gpu driven available.
Definition GpuDriven.h:41
bool gpuDrivenCullAvailable() const
Stage 2: GPU frustum/HZB cull + GPU-written indirect commands.
Definition GpuDriven.h:56
GpuMesh public API.
Definition Graphics.h:298
GpuMeshRecord record
CPU-side record for this mesh (bounds/ranges); uploaded by registerMeshRecord.
Definition Graphics.h:324
GpuTexture public API.
Definition Graphics.h:264
uint32_t bindlessIndex2D
Bindless texture-array slot (stage 0 GPU-driven path).
Definition Graphics.h:285
uint32_t bucket
glm::uvec4 info