14#include "graphics/shaders/rt_reflection_rchit_spv.inc"
15#include "graphics/shaders/rt_reflection_rgen_spv.inc"
16#include "graphics/shaders/rt_reflection_rmiss_spv.inc"
29uint32_t alignedSize(uint32_t
value, uint32_t alignment) {
30 if (alignment == 0)
return value;
31 return (
value + alignment - 1u) & ~(alignment - 1u);
34vk::TransformMatrixKHR toTransformMatrix(
const glm::mat4&
m) {
36 vk::TransformMatrixKHR
out{};
37 const float* src = &
m[0][0];
38 out.matrix[0][0] = src[0];
39 out.matrix[0][1] = src[4];
40 out.matrix[0][2] = src[8];
41 out.matrix[0][3] = src[12];
42 out.matrix[1][0] = src[1];
43 out.matrix[1][1] = src[5];
44 out.matrix[1][2] = src[9];
45 out.matrix[1][3] = src[13];
46 out.matrix[2][0] = src[2];
47 out.matrix[2][1] = src[6];
48 out.matrix[2][2] = src[10];
49 out.matrix[2][3] = src[14];
60 memory = vk::DeviceMemory{};
75 properties_ = o.properties_;
76 o.buffer = vk::Buffer{};
77 o.memory = vk::DeviceMemory{};
84 return allocateWithProperties(dev,
bytes,
usage, vk::MemoryPropertyFlagBits::eDeviceLocal);
88 vk::BufferUsageFlags
usage) {
92 if (
auto r = allocateWithProperties(
93 dev,
bytes,
usage, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
96 void* mapped = (*device)->mapMemory(
memory, 0,
bytes);
97 std::memcpy(mapped, data,
size_t(
bytes));
98 (*device)->unmapMemory(
memory);
102Result<void> DeviceAddressBuffer::allocateWithProperties(vkb::Device& dev, vk::DeviceSize
bytes,
103 vk::BufferUsageFlags
usage,
113 vk::BufferCreateInfo ci{};
115 ci.usage =
usage | vk::BufferUsageFlagBits::eShaderDeviceAddress;
116 ci.sharingMode = vk::SharingMode::eExclusive;
117 buffer = (*device)->createBuffer(ci,
device->allocation_callbacks);
120 const auto memreq = (*device)->getBufferMemoryRequirements(
buffer);
122 vk::MemoryAllocateFlagsInfo flagsInfo{};
123 flagsInfo.flags = vk::MemoryAllocateFlagBits::eDeviceAddress;
125 vk::MemoryAllocateInfo allocInfo{};
126 allocInfo.pNext = &flagsInfo;
127 allocInfo.allocationSize = memreq.size;
128 allocInfo.memoryTypeIndex =
device->physical_device.findMemoryTypeIndex(memreq.memoryTypeBits,
properties);
129 memory = (*device)->allocateMemory(allocInfo,
device->allocation_callbacks);
134 vk::BufferDeviceAddressInfo addrInfo{};
136 address = (*device)->getBufferAddress(addrInfo);
146 vk::DeviceSize
bytes) {
152 using pfb = vk::MemoryPropertyFlagBits;
153 vkb::GenericBuffer staging(*
device, vk::BufferUsageFlagBits::eTransferSrc,
bytes,
154 pfb::eHostVisible | pfb::eHostCoherent);
155 staging.updateLocal(vkb::FrameSlot::gpuIdle(), data,
bytes);
157 auto cmd = (*device)->allocateCommandBuffers({pool, vk::CommandBufferLevel::ePrimary, 1}).front();
158 cmd.begin({vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
159 vk::BufferCopy copy{};
161 cmd.copyBuffer(staging.buffer,
buffer, copy);
163 vk::SubmitInfo submit{};
164 submit.commandBufferCount = 1;
165 submit.pCommandBuffers = &cmd;
166 queue.submit(submit, vk::Fence{});
168 (*device)->freeCommandBuffers(pool, cmd);
174 (*device)->destroyAccelerationStructureKHR(
handle,
device->allocation_callbacks);
175 handle = vk::AccelerationStructureKHR{};
184 storage = std::move(o.storage);
185 deviceAddress = o.deviceAddress;
187 o.handle = vk::AccelerationStructureKHR{};
200 auto* base = eve::ModuleManager::getInstance<eve::graphics::Graphics>(
"Graphics");
201 if (!base) base = eve::graphics::Graphics::create();
203 if (!vg || !vg->supportsRayTracing()) {
204 if (vg) caps_ = vg->rayTracingCaps();
208 vkb::Device*
current = &vg->getDevice();
212 vg->getDevice().getQueue(vkb::QueueType::graphics));
221 auto* base = eve::ModuleManager::getInstance<eve::graphics::Graphics>(
"Graphics");
228 auto* base = eve::ModuleManager::getInstance<eve::graphics::Graphics>(
"Graphics");
234 vk::Queue graphicsQueue) {
238 uploadPool_ = uploadPool;
239 graphicsQueue_ = graphicsQueue;
243 if (pathPipeline_ && graphicsQueue_) graphicsQueue_.waitIdle();
247 pathSceneWords_.clear();
248 pathMeshSceneWords_.clear();
249 pathInstanceWords_.clear();
250 pathGraphics_ =
nullptr;
251 pathRecordedSequence_ = 0;
252 pathSpareScene_.reset();
253 pathHistorySamples_ = 0;
254 pathPipeline_.reset();
257 if (pipeline_) (*device_)->destroyPipeline(pipeline_, device_->allocation_callbacks);
258 if (pipelineLayout_) (*device_)->destroyPipelineLayout(pipelineLayout_, device_->allocation_callbacks);
259 if (setLayout_) (*device_)->destroyDescriptorSetLayout(setLayout_, device_->allocation_callbacks);
260 if (descriptorPool_) (*device_)->destroyDescriptorPool(descriptorPool_, device_->allocation_callbacks);
261 if (sampler_) (*device_)->destroySampler(sampler_, device_->allocation_callbacks);
262 if (raygenModule_) (*device_)->destroyShaderModule(raygenModule_, device_->allocation_callbacks);
263 if (missModule_) (*device_)->destroyShaderModule(missModule_, device_->allocation_callbacks);
264 if (closestHitModule_) (*device_)->destroyShaderModule(closestHitModule_, device_->allocation_callbacks);
266 pipeline_ = vk::Pipeline{};
267 pipelineLayout_ = vk::PipelineLayout{};
268 setLayout_ = vk::DescriptorSetLayout{};
269 descriptorPool_ = vk::DescriptorPool{};
270 descriptorSet_ = vk::DescriptorSet{};
271 sampler_ = vk::Sampler{};
272 raygenModule_ = vk::ShaderModule{};
273 missModule_ = vk::ShaderModule{};
274 closestHitModule_ = vk::ShaderModule{};
275 outputImage_ = StorageColorImage{};
279 raygenRegion_ = vk::StridedDeviceAddressRegionKHR{};
280 missRegion_ = vk::StridedDeviceAddressRegionKHR{};
281 hitRegion_ = vk::StridedDeviceAddressRegionKHR{};
282 callableRegion_ = vk::StridedDeviceAddressRegionKHR{};
284 uploadPool_ = vk::CommandPool{};
285 graphicsQueue_ = vk::Queue{};
291 if (device_ && graphicsQueue_ && (!meshes_.empty() || tlas_.
handle)) graphicsQueue_.waitIdle();
301 "addTriangleMesh: invalid geometry",
"graphics.raytracing"));
303 auto mesh = std::make_unique<TriangleMeshRecord>();
306 mesh->transform = transform;
308 const vk::DeviceSize vBytes = vk::DeviceSize(
vertexCount) * 3u *
sizeof(float);
309 const vk::DeviceSize iBytes = vk::DeviceSize(
indexCount) *
sizeof(uint32_t);
310 const auto usage = vk::BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR |
311 vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst;
313 if (
auto r =
mesh->vertexBuffer.allocate(*device_, vBytes,
usage); !
r.ok())
315 if (
auto r =
mesh->indexBuffer.allocate(*device_, iBytes,
usage); !
r.ok())
317 if (
auto r =
mesh->vertexBuffer.upload(uploadPool_, graphicsQueue_, positionsXYZ, vBytes); !
r.ok())
319 if (
auto r =
mesh->indexBuffer.upload(uploadPool_, graphicsQueue_,
indices, iBytes); !
r.ok())
323 const uint32_t
id = uint32_t(meshes_.size());
324 meshes_.push_back(std::move(
mesh));
334 if (
gpu->vertexCount < 3 ||
gpu->indexCount < 3 || (
gpu->indexCount % 3u) != 0)
338 auto& vb = eve::graphics::vulkan::meshDrawVertices(*
gpu);
343 std::vector<float>
positions(
size_t(
gpu->vertexCount) * 3u);
345 void* mapped = vb.map();
347 for (uint32_t i = 0; i <
gpu->vertexCount; ++i) {
355 std::vector<uint32_t>
indices(
gpu->indexCount);
356 if (!
gpu->cpuIndices.empty() &&
gpu->cpuIndices.size() >=
gpu->indexCount) {
357 std::copy_n(
gpu->cpuIndices.begin(),
gpu->indexCount,
indices.begin());
359 auto& ib = eve::graphics::vulkan::meshDrawIndices(*
gpu);
363 void* mapped = ib.map();
364 if (
gpu->indexType == vk::IndexType::eUint16) {
365 const auto* src =
static_cast<const uint16_t*
>(mapped);
366 for (uint32_t i = 0; i <
gpu->indexCount; ++i)
indices[i] = src[i];
368 std::memcpy(
indices.data(), mapped,
size_t(
gpu->indexCount) *
sizeof(uint32_t));
377 vk::AccelerationStructureGeometryTrianglesDataKHR
triangles{};
378 triangles.vertexFormat = vk::Format::eR32G32B32Sfloat;
379 triangles.vertexData.deviceAddress =
mesh.vertexBuffer.address;
380 triangles.vertexStride =
sizeof(float) * 3;
382 triangles.indexType = vk::IndexType::eUint32;
383 triangles.indexData.deviceAddress =
mesh.indexBuffer.address;
385 vk::AccelerationStructureGeometryKHR
geometry{};
386 geometry.geometryType = vk::GeometryTypeKHR::eTriangles;
387 geometry.flags = vk::GeometryFlagBitsKHR::eOpaque;
390 vk::AccelerationStructureBuildGeometryInfoKHR
buildInfo{};
391 buildInfo.type = vk::AccelerationStructureTypeKHR::eBottomLevel;
392 buildInfo.flags = vk::BuildAccelerationStructureFlagBitsKHR::ePreferFastTrace;
393 buildInfo.mode = vk::BuildAccelerationStructureModeKHR::eBuild;
397 const uint32_t primitiveCount =
mesh.indexCount / 3;
398 const auto sizes = (*device_)->getAccelerationStructureBuildSizesKHR(vk::AccelerationStructureBuildTypeKHR::eDevice,
401 auto storageResult =
mesh.blas.storage.allocate(
402 *device_, sizes.accelerationStructureSize,
403 vk::BufferUsageFlagBits::eAccelerationStructureStorageKHR | vk::BufferUsageFlagBits::eShaderDeviceAddress);
404 if (!storageResult.ok())
return storageResult;
406 vk::AccelerationStructureCreateInfoKHR createInfo{};
407 createInfo.buffer =
mesh.blas.storage.buffer;
408 createInfo.size = sizes.accelerationStructureSize;
409 createInfo.type = vk::AccelerationStructureTypeKHR::eBottomLevel;
410 mesh.blas.handle = (*device_)->createAccelerationStructureKHR(createInfo, device_->allocation_callbacks);
411 mesh.blas.device = device_;
413 vk::AccelerationStructureDeviceAddressInfoKHR addrInfo{};
414 addrInfo.accelerationStructure =
mesh.blas.handle;
415 mesh.blas.deviceAddress = (*device_)->getAccelerationStructureAddressKHR(addrInfo);
417 DeviceAddressBuffer scratch;
419 scratch.allocate(*device_, sizes.buildScratchSize,
420 vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eShaderDeviceAddress);
425 buildInfo.scratchData.deviceAddress = scratch.address;
427 vk::AccelerationStructureBuildRangeInfoKHR
range{};
428 range.primitiveCount = primitiveCount;
429 const vk::AccelerationStructureBuildRangeInfoKHR* ranges = &
range;
431 auto cmd = (*device_)->allocateCommandBuffers({uploadPool_, vk::CommandBufferLevel::ePrimary, 1}).front();
432 cmd.begin({vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
433 cmd.buildAccelerationStructuresKHR(
buildInfo, ranges);
435 vk::SubmitInfo submit{};
436 submit.commandBufferCount = 1;
437 submit.pCommandBuffers = &cmd;
438 graphicsQueue_.submit(submit, vk::Fence{});
439 graphicsQueue_.waitIdle();
440 (*device_)->freeCommandBuffers(uploadPool_, cmd);
444Result<void> VulkanRayTracing::buildTlas() {
445 if (meshes_.empty()) {
446 if (tlas_.
handle) graphicsQueue_.waitIdle();
451 std::vector<vk::AccelerationStructureInstanceKHR> instances;
452 instances.reserve(meshes_.size());
453 for (
const auto&
mesh : meshes_) {
454 vk::AccelerationStructureInstanceKHR inst{};
455 inst.transform = toTransformMatrix(
mesh->transform);
456 inst.instanceCustomIndex = 0;
458 inst.instanceShaderBindingTableRecordOffset = 0;
459 inst.flags = uint32_t(vk::GeometryInstanceFlagBitsKHR::eTriangleFacingCullDisable);
460 inst.accelerationStructureReference =
mesh->blas.deviceAddress;
461 instances.push_back(inst);
464 AccelerationStructure candidate;
465 if (
auto r = buildTlas(instances, candidate); !
r.
ok())
return r;
467 tlas_ = std::move(candidate);
471Result<void> VulkanRayTracing::buildTlas(std::span<const vk::AccelerationStructureInstanceKHR> instances,
472 AccelerationStructure&
target) {
473 TlasWorkspace workspace;
474 return buildTlas(instances,
target, workspace);
477Result<void> VulkanRayTracing::buildTlas(std::span<const vk::AccelerationStructureInstanceKHR> instances,
478 AccelerationStructure&
target, TlasWorkspace& workspace) {
480 if (instances.empty() || instances.size() > UINT32_MAX)
484 auto& instanceBuffer = workspace.instances;
485 const vk::DeviceSize
bytes = vk::DeviceSize(instances.size()) *
sizeof(instances[0]);
486 if (
auto r = instanceBuffer.initializeHostVisible(
487 *device_, instances.data(),
bytes, vk::BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR);
491 vk::AccelerationStructureGeometryInstancesDataKHR instancesData{};
492 instancesData.arrayOfPointers = VK_FALSE;
493 instancesData.data.deviceAddress = instanceBuffer.address;
495 vk::AccelerationStructureGeometryKHR
geometry{};
496 geometry.geometryType = vk::GeometryTypeKHR::eInstances;
497 geometry.geometry.instances = instancesData;
499 vk::AccelerationStructureBuildGeometryInfoKHR
buildInfo{};
500 buildInfo.type = vk::AccelerationStructureTypeKHR::eTopLevel;
501 buildInfo.flags = vk::BuildAccelerationStructureFlagBitsKHR::ePreferFastTrace;
502 buildInfo.mode = vk::BuildAccelerationStructureModeKHR::eBuild;
506 const uint32_t primitiveCount = uint32_t(instances.size());
507 const auto sizes = (*device_)->getAccelerationStructureBuildSizesKHR(vk::AccelerationStructureBuildTypeKHR::eDevice,
510 if (
target.handle &&
target.storage.size < sizes.accelerationStructureSize)
target.release();
512 if (
auto r =
target.storage.allocate(*device_, sizes.accelerationStructureSize,
513 vk::BufferUsageFlagBits::eAccelerationStructureStorageKHR |
514 vk::BufferUsageFlagBits::eShaderDeviceAddress);
518 vk::AccelerationStructureCreateInfoKHR createInfo{};
519 createInfo.buffer =
target.storage.buffer;
520 createInfo.size = sizes.accelerationStructureSize;
521 createInfo.type = vk::AccelerationStructureTypeKHR::eTopLevel;
522 target.handle = (*device_)->createAccelerationStructureKHR(createInfo, device_->allocation_callbacks);
525 vk::AccelerationStructureDeviceAddressInfoKHR addrInfo{};
526 addrInfo.accelerationStructure =
target.handle;
527 target.deviceAddress = (*device_)->getAccelerationStructureAddressKHR(addrInfo);
530 auto& scratch = workspace.scratch;
532 scratch.allocate(*device_, sizes.buildScratchSize,
533 vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eShaderDeviceAddress);
538 buildInfo.scratchData.deviceAddress = scratch.address;
540 vk::AccelerationStructureBuildRangeInfoKHR
range{};
541 range.primitiveCount = primitiveCount;
542 const vk::AccelerationStructureBuildRangeInfoKHR* ranges = &
range;
544 auto cmd = (*device_)->allocateCommandBuffers({uploadPool_, vk::CommandBufferLevel::ePrimary, 1}).front();
545 cmd.begin({vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
546 cmd.buildAccelerationStructuresKHR(
buildInfo, ranges);
548 vk::SubmitInfo submit{};
549 submit.commandBufferCount = 1;
550 submit.pCommandBuffers = &cmd;
551 graphicsQueue_.submit(submit, vk::Fence{});
552 graphicsQueue_.waitIdle();
553 (*device_)->freeCommandBuffers(uploadPool_, cmd);
567 auto makeModule = [&](
const uint32_t* words,
size_t count) -> vk::ShaderModule {
568 vk::ShaderModuleCreateInfo ci{};
569 ci.codeSize =
count *
sizeof(uint32_t);
571 return (*device_)->createShaderModule(ci, device_->allocation_callbacks);
573 raygenModule_ = makeModule(rt_reflection_rgen_spv, rt_reflection_rgen_spv_count);
574 missModule_ = makeModule(rt_reflection_rmiss_spv, rt_reflection_rmiss_spv_count);
575 closestHitModule_ = makeModule(rt_reflection_rchit_spv, rt_reflection_rchit_spv_count);
577 vk::DescriptorSetLayoutBinding
bindings[5]{};
579 bindings[0].descriptorType = vk::DescriptorType::eAccelerationStructureKHR;
581 bindings[0].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
583 bindings[1].descriptorType = vk::DescriptorType::eStorageImage;
585 bindings[1].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
587 bindings[2].descriptorType = vk::DescriptorType::eCombinedImageSampler;
589 bindings[2].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
591 bindings[3].descriptorType = vk::DescriptorType::eCombinedImageSampler;
593 bindings[3].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
595 bindings[4].descriptorType = vk::DescriptorType::eCombinedImageSampler;
597 bindings[4].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
599 vk::DescriptorSetLayoutCreateInfo layoutCi{};
600 layoutCi.bindingCount = 5;
602 setLayout_ = (*device_)->createDescriptorSetLayout(layoutCi, device_->allocation_callbacks);
604 vk::PushConstantRange push{};
605 push.stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
607 push.size =
sizeof(PushConstants);
609 vk::PipelineLayoutCreateInfo plCi{};
610 plCi.setLayoutCount = 1;
611 plCi.pSetLayouts = &setLayout_;
612 plCi.pushConstantRangeCount = 1;
613 plCi.pPushConstantRanges = &push;
614 pipelineLayout_ = (*device_)->createPipelineLayout(plCi, device_->allocation_callbacks);
616 std::array<vk::PipelineShaderStageCreateInfo, 3> stages{};
617 stages[0].stage = vk::ShaderStageFlagBits::eRaygenKHR;
618 stages[0].module = raygenModule_;
619 stages[0].pName =
"main";
620 stages[1].stage = vk::ShaderStageFlagBits::eMissKHR;
621 stages[1].module = missModule_;
622 stages[1].pName =
"main";
623 stages[2].stage = vk::ShaderStageFlagBits::eClosestHitKHR;
624 stages[2].module = closestHitModule_;
625 stages[2].pName =
"main";
627 std::array<vk::RayTracingShaderGroupCreateInfoKHR, 3>
groups{};
628 groups[0].type = vk::RayTracingShaderGroupTypeKHR::eGeneral;
629 groups[0].generalShader = 0;
630 groups[0].closestHitShader = VK_SHADER_UNUSED_KHR;
631 groups[0].anyHitShader = VK_SHADER_UNUSED_KHR;
632 groups[0].intersectionShader = VK_SHADER_UNUSED_KHR;
633 groups[1].type = vk::RayTracingShaderGroupTypeKHR::eGeneral;
634 groups[1].generalShader = 1;
635 groups[1].closestHitShader = VK_SHADER_UNUSED_KHR;
636 groups[1].anyHitShader = VK_SHADER_UNUSED_KHR;
637 groups[1].intersectionShader = VK_SHADER_UNUSED_KHR;
638 groups[2].type = vk::RayTracingShaderGroupTypeKHR::eTrianglesHitGroup;
639 groups[2].generalShader = VK_SHADER_UNUSED_KHR;
640 groups[2].closestHitShader = 2;
641 groups[2].anyHitShader = VK_SHADER_UNUSED_KHR;
642 groups[2].intersectionShader = VK_SHADER_UNUSED_KHR;
644 vk::RayTracingPipelineCreateInfoKHR pipeCi{};
645 pipeCi.stageCount = uint32_t(stages.size());
646 pipeCi.pStages = stages.data();
647 pipeCi.groupCount = uint32_t(
groups.size());
648 pipeCi.pGroups =
groups.data();
649 pipeCi.maxPipelineRayRecursionDepth =
651 pipeCi.layout = pipelineLayout_;
653 auto created = (*device_)->createRayTracingPipelinesKHR(vk::DeferredOperationKHR{}, vk::PipelineCache{}, pipeCi,
654 device_->allocation_callbacks);
655 if (
created.result != vk::Result::eSuccess ||
created.value.empty())
658 pipeline_ =
created.value.front();
660 return createShaderBindingTable();
663Result<void> VulkanRayTracing::createShaderBindingTable() {
667 const uint32_t handleSizeAligned = alignedSize(handleSize, handleAlignment);
668 const uint32_t groupCount = 3;
669 const uint32_t sbtSize = groupCount * handleSizeAligned;
671 std::vector<uint8_t> handles(sbtSize);
672 auto result = (*device_)->getRayTracingShaderGroupHandlesKHR(pipeline_, 0, groupCount, sbtSize, handles.data());
673 if (
result != vk::Result::eSuccess)
678 const uint32_t raygenSize = alignedSize(handleSizeAligned, baseAlignment);
679 const uint32_t missSize = alignedSize(handleSizeAligned, baseAlignment);
680 const uint32_t hitSize = alignedSize(handleSizeAligned, baseAlignment);
681 const uint32_t total = raygenSize + missSize + hitSize;
683 std::vector<uint8_t> sbt(total, 0);
684 std::memcpy(sbt.data(), handles.data(), handleSize);
685 std::memcpy(sbt.data() + raygenSize, handles.data() + handleSizeAligned, handleSize);
686 std::memcpy(sbt.data() + raygenSize + missSize, handles.data() + 2 * handleSizeAligned, handleSize);
688 if (
auto r = sbtBuffer_.
allocate(*device_, total,
689 vk::BufferUsageFlagBits::eShaderBindingTableKHR |
690 vk::BufferUsageFlagBits::eShaderDeviceAddress |
691 vk::BufferUsageFlagBits::eTransferDst);
694 if (
auto r = sbtBuffer_.
upload(uploadPool_, graphicsQueue_, sbt.data(), total); !
r.
ok())
return r;
696 raygenRegion_.deviceAddress = sbtBuffer_.
address;
697 raygenRegion_.stride = raygenSize;
698 raygenRegion_.size = raygenSize;
700 missRegion_.deviceAddress = sbtBuffer_.
address + raygenSize;
701 missRegion_.stride = handleSizeAligned;
702 missRegion_.size = missSize;
704 hitRegion_.deviceAddress = sbtBuffer_.
address + raygenSize + missSize;
705 hitRegion_.stride = handleSizeAligned;
706 hitRegion_.size = hitSize;
708 callableRegion_ = vk::StridedDeviceAddressRegionKHR{};
712Result<void> VulkanRayTracing::ensureDescriptorSets(vk::ImageView outputView, vk::ImageView sceneView,
713 vk::ImageView depthView, vk::ImageView normalView) {
714 if (!descriptorPool_) {
715 std::array<vk::DescriptorPoolSize, 3> sizes{};
716 sizes[0] = {vk::DescriptorType::eAccelerationStructureKHR, 4};
717 sizes[1] = {vk::DescriptorType::eStorageImage, 4};
718 sizes[2] = {vk::DescriptorType::eCombinedImageSampler, 12};
719 vk::DescriptorPoolCreateInfo poolCi{};
721 poolCi.poolSizeCount = uint32_t(sizes.size());
722 poolCi.pPoolSizes = sizes.data();
723 descriptorPool_ = (*device_)->createDescriptorPool(poolCi, device_->allocation_callbacks);
725 if (!descriptorSet_) {
726 vk::DescriptorSetAllocateInfo alloc{};
727 alloc.descriptorPool = descriptorPool_;
728 alloc.descriptorSetCount = 1;
729 alloc.pSetLayouts = &setLayout_;
730 descriptorSet_ = (*device_)->allocateDescriptorSets(alloc).front();
733 vk::WriteDescriptorSetAccelerationStructureKHR asWrite{};
734 asWrite.accelerationStructureCount = 1;
735 asWrite.pAccelerationStructures = &tlas_.
handle;
737 vk::WriteDescriptorSet writes[5]{};
738 writes[0].pNext = &asWrite;
739 writes[0].dstSet = descriptorSet_;
740 writes[0].dstBinding = 0;
741 writes[0].descriptorCount = 1;
742 writes[0].descriptorType = vk::DescriptorType::eAccelerationStructureKHR;
745 vk::DescriptorImageInfo outInfo{};
746 outInfo.imageView = outputView;
747 outInfo.imageLayout = vk::ImageLayout::eGeneral;
748 writes[1].dstSet = descriptorSet_;
749 writes[1].dstBinding = 1;
750 writes[1].descriptorCount = 1;
751 writes[1].descriptorType = vk::DescriptorType::eStorageImage;
752 writes[1].pImageInfo = &outInfo;
754 if (
auto r = ensureSampler(); !
r.
ok())
return r;
756 vk::DescriptorImageInfo sceneInfo{};
757 sceneInfo.sampler = sampler_;
758 sceneInfo.imageView = sceneView;
759 sceneInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
760 writes[2].dstSet = descriptorSet_;
761 writes[2].dstBinding = 2;
762 writes[2].descriptorCount = 1;
763 writes[2].descriptorType = vk::DescriptorType::eCombinedImageSampler;
764 writes[2].pImageInfo = &sceneInfo;
766 vk::DescriptorImageInfo depthInfo{};
767 depthInfo.sampler = sampler_;
768 depthInfo.imageView = depthView;
769 depthInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
770 writes[3].dstSet = descriptorSet_;
771 writes[3].dstBinding = 3;
772 writes[3].descriptorCount = 1;
773 writes[3].descriptorType = vk::DescriptorType::eCombinedImageSampler;
774 writes[3].pImageInfo = &depthInfo;
776 vk::DescriptorImageInfo normalInfo{};
777 normalInfo.sampler = sampler_;
778 normalInfo.imageView = normalView;
779 normalInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
780 writes[4].dstSet = descriptorSet_;
781 writes[4].dstBinding = 4;
782 writes[4].descriptorCount = 1;
783 writes[4].descriptorType = vk::DescriptorType::eCombinedImageSampler;
784 writes[4].pImageInfo = &normalInfo;
786 (*device_)->updateDescriptorSets(writes, {});
790Result<void> VulkanRayTracing::ensureSampler() {
794 vk::SamplerCreateInfo sci{};
795 sci.magFilter = vk::Filter::eNearest;
796 sci.minFilter = vk::Filter::eNearest;
797 sci.mipmapMode = vk::SamplerMipmapMode::eNearest;
798 sci.addressModeU = vk::SamplerAddressMode::eClampToEdge;
799 sci.addressModeV = vk::SamplerAddressMode::eClampToEdge;
800 sci.addressModeW = vk::SamplerAddressMode::eClampToEdge;
801 sampler_ = (*device_)->createSampler(sci, device_->allocation_callbacks);
805Result<void> VulkanRayTracing::ensureOutputImage(uint32_t
width, uint32_t
height) {
811 outputImage_ = StorageColorImage{};
812 outputWidth_ =
width;
820 const glm::mat4&
viewProj,
const glm::vec3& eyeWorld) {
822 if (!gfx || !sceneColor || !hwDepth || !worldNormal || !dest)
825 if (meshes_.empty() || !tlas_.
handle) {
834 if (
auto r = ensurePipeline(); !
r.
ok())
return r;
836 auto textureView = [](
Texture* tex) -> vk::ImageView {
837 if (!tex || !tex->gpuHandle)
return {};
853 const vk::ImageView outView = outputImage_.imageView();
854 const vk::ImageView sceneView = textureView(sceneColor);
855 const vk::ImageView depthView = textureView(hwDepth);
856 const vk::ImageView normalView = textureView(worldNormal);
857 if (!outView || !sceneView || !depthView || !normalView)
862 vkGfx->waitForSharedGpuResources();
863 if (
auto r = ensureDescriptorSets(outView, sceneView, depthView, normalView); !
r.
ok())
return r;
865 PushConstants push{};
868 push.eye = glm::vec4(eyeWorld, 0.f);
870 auto record = [&](vk::CommandBuffer cmd) {
871 outputImage_.setLayout(cmd, vk::ImageLayout::eGeneral);
873 vk::MemoryBarrier memBarrier{};
874 memBarrier.srcAccessMask =
875 vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentWrite;
876 memBarrier.dstAccessMask = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite;
878 vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eLateFragmentTests,
879 vk::PipelineStageFlagBits::eRayTracingShaderKHR, {}, memBarrier, {}, {});
881 cmd.bindPipeline(vk::PipelineBindPoint::eRayTracingKHR, pipeline_);
882 cmd.bindDescriptorSets(vk::PipelineBindPoint::eRayTracingKHR, pipelineLayout_, 0, descriptorSet_, {});
883 cmd.pushConstants(pipelineLayout_, vk::ShaderStageFlagBits::eRaygenKHR, 0,
sizeof(PushConstants), &push);
884 cmd.traceRaysKHR(raygenRegion_, missRegion_, hitRegion_, callableRegion_,
width,
height, 1);
889 vk::MemoryBarrier traceToCopy{};
890 traceToCopy.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
891 traceToCopy.dstAccessMask = vk::AccessFlagBits::eTransferRead;
892 cmd.pipelineBarrier(vk::PipelineStageFlagBits::eRayTracingShaderKHR, vk::PipelineStageFlagBits::eTransfer, {},
893 traceToCopy, {}, {});
894 outputImage_.setLayout(cmd, vk::ImageLayout::eTransferSrcOptimal);
895 destCanvas->colorImage().setLayout(cmd, vk::ImageLayout::eTransferDstOptimal);
897 region.srcSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
898 region.dstSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
900 cmd.copyImage(outputImage_.image(), vk::ImageLayout::eTransferSrcOptimal, destCanvas->colorImage().image(),
901 vk::ImageLayout::eTransferDstOptimal,
region);
902 destCanvas->colorImage().setLayout(cmd, vk::ImageLayout::eShaderReadOnlyOptimal);
905 if (vkGfx->canRecordPostSceneGpuWork()) {
906 record(vkGfx->postSceneCommandBuffer());
908 vkGfx->waitForSharedGpuResources();
909 vkb::executeImmediately(device_->instance, uploadPool_, graphicsQueue_,
record);
916struct RegisterCapability {
917 RegisterCapability() { eve::cap::provide<IRayTracing>(&
vulkanRayTracing()); }
std::vector< std::uint32_t > verts
Stable, structured diagnostics shared by engine modules.
ScriptComponentRecord record
std::uint32_t vertexCount
vk::UniqueDeviceMemory memory
std::vector< std::uint32_t > indices
std::vector< float > positions
std::map< std::string, PropertyRule > properties
std::shared_ptr< OceanGpuSpectrum > gpu
std::unique_ptr< gpgpu::GpuBuffer > buffer
std::vector< ParticleBakeMaterial > bindings
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Structured operation status used by the common Result foundation.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
virtual int getWidth() const =0
Returns the width.
virtual Texture * getTexture()=0
Sampleable color buffer; screen Canvas returns nullptr.
virtual int getHeight() const =0
Returns the height.
GPU mesh handle (+ optional CPU morph targets).
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Vulkan implementation of IRayTracing (KHR ray-tracing pipeline).
Result< void > rebuildScene() override
Rebuild scene.
void clearScene() override
Clears scene.
~VulkanRayTracing() override
Releases VulkanRayTracing resources.
Result< uint32_t > addMesh(Mesh *mesh, const glm::mat4 &transform) override
Adds mesh.
RayTracingCaps caps() const override
Caps.
void attachDevice(vkb::Device *device, const RayTracingCaps &caps, vk::CommandPool uploadPool, vk::Queue graphicsQueue)
Bind to the live Vulkan Graphics device (call after init). @ownership device is borrowed; Graphics re...
Result< void > ensureAttached()
Lazily bind to the process Graphics singleton when RT is available.
bool isAvailable() const override
True when available.
void detachDevice()
Drop GPU resources when Graphics tears down.
Result< uint32_t > addTriangleMesh(const float *positionsXYZ, int vertexCount, const uint32_t *indices, int indexCount, const glm::mat4 &transform) override
Adds triangle mesh.
Result< void > applyReflections(Graphics *gfx, Texture *sceneColor, Texture *hwDepth, Texture *worldNormal, Canvas *dest, const glm::mat4 &invViewProj, const glm::mat4 &viewProj, const glm::vec3 &eyeWorld) override
Applies reflections.
EVENGINE_API_BACKENDS public API.
bool supportsRayTracing() const override
Supports ray tracing.
void retirePathSceneOutput()
Invalidate cached bindings before retiring completed path output; render thread only.
RayTracingCaps rayTracingCaps() const override
Ray tracing caps.
OffscreenCanvas public API.
VulkanRayTracing & vulkanRayTracing()
Process-wide Vulkan RT backend; also registered as IRayTracing.
std::string buildInfo()
One-line build metadata for diagnostics (printed by eve --version).
Hardware ray-tracing capabilities probed once at Vulkan device creation.
uint32_t shaderGroupHandleAlignment
bool rayTracingAvailable() const
True when BLAS/TLAS + ray-tracing pipelines can be created.
uint32_t maxRecursionDepth
uint32_t shaderGroupHandleSize
uint32_t shaderGroupBaseAlignment
Bottom- or top-level acceleration structure handle.
vk::DeviceAddress deviceAddress
void steal(AccelerationStructure &o) noexcept
Steal.
DeviceAddressBuffer storage
vk::AccelerationStructureKHR handle
Device-local buffer with shader device address (for AS builds / SBT). @ownership Owns the Vulkan buff...
vk::DeviceAddress address
Result< void > initializeHostVisible(vkb::Device &dev, const void *data, vk::DeviceSize bytes, vk::BufferUsageFlags usage)
Allocate coherent host-visible storage and initialize it without a transfer submission....
Result< void > allocate(vkb::Device &dev, vk::DeviceSize bytes, vk::BufferUsageFlags usage)
Ensure buffer capacity with usage including SHADER_DEVICE_ADDRESS. @ownership Reuses compatible stora...
Result< void > upload(vk::CommandPool pool, vk::Queue queue, const void *data, vk::DeviceSize bytes)
Upload host bytes via a staging buffer (stalls the queue).
void steal(DeviceAddressBuffer &o) noexcept
Steal.
TriangleMeshRecord public API.
vk::ImageView imageView() const
Image view.