10#include "graphics/shaders/pt_denoise_spv.inc"
11#include "graphics/shaders/pt_path_rahit_spv.inc"
12#include "graphics/shaders/pt_path_rchit_spv.inc"
13#include "graphics/shaders/pt_path_rgen_spv.inc"
14#include "graphics/shaders/pt_path_rmiss_spv.inc"
15#include "graphics/shaders/pt_temporal_spv.inc"
25#include <glm/gtc/matrix_inverse.hpp>
31VulkanRayTracing::PathPipeline::~PathPipeline() {
34 if (temporalPipeline) (*device)->destroyPipeline(temporalPipeline,
device->allocation_callbacks);
35 if (temporalModule) (*device)->destroyShaderModule(temporalModule,
device->allocation_callbacks);
36 if (denoisePipeline) (*device)->destroyPipeline(denoisePipeline,
device->allocation_callbacks);
37 if (denoiseModule) (*device)->destroyShaderModule(denoiseModule,
device->allocation_callbacks);
38 if (pipeline) (*device)->destroyPipeline(pipeline,
device->allocation_callbacks);
40 if (setLayout) (*device)->destroyDescriptorSetLayout(setLayout,
device->allocation_callbacks);
41 for (
auto module : modules)
42 if (module) (*
device)->destroyShaderModule(module,
device->allocation_callbacks);
45Result<void> VulkanRayTracing::ensurePathPipeline() {
52 if (device_->physical_device.properties.limits.maxPerStageDescriptorStorageImages < 10)
55 "graphics.raytracing"));
59 if (!handleSize || !handleAlignment || !baseAlignment)
65 auto candidate = std::make_unique<PathPipeline>();
66 candidate->device = device_;
68 const std::array<const uint32_t*, 4>
code{pt_path_rgen_spv, pt_path_rmiss_spv, pt_path_rchit_spv,
70 const std::array<size_t, 4> sizes{
sizeof(pt_path_rgen_spv),
sizeof(pt_path_rmiss_spv),
71 sizeof(pt_path_rchit_spv),
sizeof(pt_path_rahit_spv)};
72 for (
size_t i = 0; i <
code.size(); ++i) {
73 vk::ShaderModuleCreateInfo
info{};
74 info.codeSize = sizes[i];
76 candidate->modules[i] = (*device_)->createShaderModule(
info, device_->allocation_callbacks);
79 std::array<vk::DescriptorSetLayoutBinding, 18>
bindings{};
80 for (uint32_t i = 0; i <
bindings.size(); ++i) {
83 bindings[i].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR | vk::ShaderStageFlagBits::eCompute;
84 if ((i >= 3 && i <= 6) || i == 10 || i == 12)
bindings[i].stageFlags |= vk::ShaderStageFlagBits::eAnyHitKHR;
85 bindings[i].descriptorType = i == 0 ? vk::DescriptorType::eAccelerationStructureKHR
86 : ((i >= 3 && i <= 7) || i == 10 || i == 12)
87 ? vk::DescriptorType::eStorageBuffer
88 : vk::DescriptorType::eStorageImage;
90 vk::DescriptorSetLayoutCreateInfo setInfo{};
91 setInfo.bindingCount = uint32_t(
bindings.size());
93 candidate->setLayout = (*device_)->createDescriptorSetLayout(setInfo, device_->allocation_callbacks);
94 vk::PushConstantRange push{vk::ShaderStageFlagBits::eRaygenKHR | vk::ShaderStageFlagBits::eCompute, 0,
95 sizeof(path::Constants)};
96 vk::PipelineLayoutCreateInfo layoutInfo{};
97 layoutInfo.setLayoutCount = 1;
98 layoutInfo.pSetLayouts = &candidate->setLayout;
99 layoutInfo.pushConstantRangeCount = 1;
100 layoutInfo.pPushConstantRanges = &push;
101 candidate->layout = (*device_)->createPipelineLayout(layoutInfo, device_->allocation_callbacks);
102 vk::ShaderModuleCreateInfo denoiseCode{};
103 denoiseCode.codeSize =
sizeof(pt_denoise_spv);
104 denoiseCode.pCode = pt_denoise_spv;
105 candidate->denoiseModule = (*device_)->createShaderModule(denoiseCode, device_->allocation_callbacks);
106 vk::ComputePipelineCreateInfo denoiseInfo{};
108 vk::PipelineShaderStageCreateInfo{{}, vk::ShaderStageFlagBits::eCompute, candidate->denoiseModule,
"main"};
109 denoiseInfo.layout = candidate->layout;
110 auto denoiseCreated = (*device_)->createComputePipeline({}, denoiseInfo, device_->allocation_callbacks);
111 candidate->denoisePipeline = denoiseCreated.value;
112 if (denoiseCreated.result != vk::Result::eSuccess || !candidate->denoisePipeline)
116 vk::ShaderModuleCreateInfo temporalCode{};
117 temporalCode.codeSize =
sizeof(pt_temporal_spv);
118 temporalCode.pCode = pt_temporal_spv;
119 candidate->temporalModule = (*device_)->createShaderModule(temporalCode, device_->allocation_callbacks);
120 denoiseInfo.stage.module = candidate->temporalModule;
121 auto temporalCreated = (*device_)->createComputePipeline({}, denoiseInfo, device_->allocation_callbacks);
122 candidate->temporalPipeline = temporalCreated.value;
123 if (temporalCreated.result != vk::Result::eSuccess || !candidate->temporalPipeline)
127 const std::array<vk::ShaderStageFlagBits, 4> kinds{
128 vk::ShaderStageFlagBits::eRaygenKHR, vk::ShaderStageFlagBits::eMissKHR,
129 vk::ShaderStageFlagBits::eClosestHitKHR, vk::ShaderStageFlagBits::eAnyHitKHR};
130 std::array<vk::PipelineShaderStageCreateInfo, 4> stages{};
131 std::array<vk::RayTracingShaderGroupCreateInfoKHR, 3>
groups{};
132 for (uint32_t i = 0; i < stages.size(); ++i) {
133 stages[i].stage = kinds[i];
134 stages[i].module = candidate->modules[i];
135 stages[i].pName =
"main";
137 for (uint32_t i = 0; i <
groups.size(); ++i) {
138 groups[i].type = i == 2 ? vk::RayTracingShaderGroupTypeKHR::eTrianglesHitGroup
139 : vk::RayTracingShaderGroupTypeKHR::eGeneral;
140 groups[i].generalShader = i == 2 ? VK_SHADER_UNUSED_KHR : i;
141 groups[i].closestHitShader = i == 2 ? i : VK_SHADER_UNUSED_KHR;
142 groups[i].anyHitShader = i == 2 ? 3 : VK_SHADER_UNUSED_KHR;
143 groups[i].intersectionShader = VK_SHADER_UNUSED_KHR;
145 vk::RayTracingPipelineCreateInfoKHR pipelineInfo{};
146 pipelineInfo.stageCount = uint32_t(stages.size());
147 pipelineInfo.pStages = stages.data();
148 pipelineInfo.groupCount = uint32_t(
groups.size());
149 pipelineInfo.pGroups =
groups.data();
151 pipelineInfo.maxPipelineRayRecursionDepth = 1;
152 pipelineInfo.layout = candidate->layout;
153 auto created = (*device_)->createRayTracingPipelinesKHR(vk::DeferredOperationKHR{}, vk::PipelineCache{},
154 pipelineInfo, device_->allocation_callbacks);
155 if (!
created.value.empty()) candidate->pipeline =
created.value.front();
156 if (
created.result != vk::Result::eSuccess || !candidate->pipeline)
161 std::vector<uint8_t> handles(
size_t(handleSize) * 3);
163 (*device_)->getRayTracingShaderGroupHandlesKHR(candidate->pipeline, 0, 3, handles.size(), handles.data());
164 if (
result != vk::Result::eSuccess)
167 const auto align = [](vk::DeviceSize
value, vk::DeviceSize alignment) {
168 return (
value + alignment - 1) / alignment * alignment;
170 const auto stride = align(handleSize, handleAlignment);
171 const auto regionSpacing = align(stride, baseAlignment);
173 const auto allocationSize = regionSpacing * 3 + baseAlignment - 1;
174 if (
auto r = candidate->sbt.allocate(
175 *device_, allocationSize,
176 vk::BufferUsageFlagBits::eShaderBindingTableKHR | vk::BufferUsageFlagBits::eTransferDst);
179 const auto start = align(candidate->sbt.address, baseAlignment) - candidate->sbt.address;
180 std::vector<uint8_t>
bytes(
size_t(allocationSize), 0);
181 for (
size_t i = 0; i < 3; ++i) {
183 std::memcpy(
bytes.data() +
offset, handles.data() + i * handleSize, handleSize);
184 candidate->regions[i] = vk::StridedDeviceAddressRegionKHR{candidate->sbt.address +
offset, stride, stride};
186 if (
auto r = candidate->sbt.upload(uploadPool_, graphicsQueue_,
bytes.data(), allocationSize); !
r.ok())
188 }
catch (
const std::exception&
error) {
192 pathPipeline_ = std::move(candidate);
200 std::array<eve::graphics::vulkan::GpuTexture, 2>
gpu;
204 if (
pool) (*device)->destroyDescriptorPool(
pool,
device->allocation_callbacks);
209VulkanRayTracing::PathFrame::~PathFrame() {
210 if (
device && pool) (*device)->destroyDescriptorPool(pool,
device->allocation_callbacks);
216 "Path-tracing extent must be nonzero",
"graphics.raytracing"));
217 if (
auto r = ensurePathPipeline(); !
r.
ok())
return r;
219 if (pathFrameGeneration_ == UINT64_MAX)
223 auto candidate = std::make_unique<PathFrame>();
224 candidate->device = device_;
225 candidate->width =
width;
226 candidate->height =
height;
228 for (
size_t i = 0; i < candidate->images.size(); ++i) {
229 vk::ImageCreateInfo
info{};
230 info.imageType = vk::ImageType::e2D;
231 info.format = (i == 0 || i == 2 || (i >= 5 && i <= 8)) ? vk::Format::eR32G32B32A32Sfloat
232 : vk::Format::eR16G16B16A16Sfloat;
235 info.arrayLayers = 1;
236 info.samples = vk::SampleCountFlagBits::e1;
237 info.tiling = vk::ImageTiling::eOptimal;
238 info.usage = vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eSampled |
239 vk::ImageUsageFlagBits::eTransferSrc;
240 info.sharingMode = vk::SharingMode::eExclusive;
241 info.initialLayout = vk::ImageLayout::eUndefined;
242 candidate->images[i].create(*device_,
info, vk::ImageViewType::e2D, vk::ImageAspectFlagBits::eColor,
false);
244 candidate->output = std::make_unique<PathFrame::OutputTextures>();
245 auto&
output = *candidate->output;
247 vk::SamplerCreateInfo samplerInfo{};
248 samplerInfo.magFilter = vk::Filter::eNearest;
249 samplerInfo.minFilter = vk::Filter::eNearest;
250 samplerInfo.addressModeU = samplerInfo.addressModeV = samplerInfo.addressModeW =
251 vk::SamplerAddressMode::eClampToEdge;
252 output.sampler = (*device_)->createSampler(samplerInfo, device_->allocation_callbacks);
253 vk::DescriptorPoolSize sampledSize{vk::DescriptorType::eCombinedImageSampler, 10};
254 vk::DescriptorPoolCreateInfo sampledPool{};
255 sampledPool.maxSets = 2;
256 sampledPool.poolSizeCount = 1;
257 sampledPool.pPoolSizes = &sampledSize;
258 output.pool = (*device_)->createDescriptorPool(sampledPool, device_->allocation_callbacks);
259 std::array<vk::DescriptorSetLayout, 2> sampledLayouts{pathGraphics_->
getTexSetLayout(),
261 vk::DescriptorSetAllocateInfo sampledAllocate{
output.pool, 2, sampledLayouts.data()};
262 const auto sampledSets = (*device_)->allocateDescriptorSets(sampledAllocate);
263 for (
size_t i = 0; i < 2; ++i) {
268 gpu.sharedSampler =
true;
269 gpu.viewOverride = candidate->images[i == 0 ? 1 : 4].imageView();
270 vkb::UnboundSet unbound{sampledSets[i]};
271 vkb::DescriptorSetUpdater updater;
272 updater.beginDescriptorSet(unbound);
274 updater.beginImages(
binding, 0, vk::DescriptorType::eCombinedImageSampler)
276 vkb::SampledImage{
output.sampler,
gpu.viewOverride, vk::ImageLayout::eShaderReadOnlyOptimal});
277 updater.update(device_->instance);
278 gpu.descriptorSet = std::move(unbound).publish();
284 const std::array<vk::DescriptorPoolSize, 3> sizes{{{vk::DescriptorType::eAccelerationStructureKHR, 2},
285 {vk::DescriptorType::eStorageBuffer, 14},
286 {vk::DescriptorType::eStorageImage, 20}}};
287 vk::DescriptorPoolCreateInfo poolInfo{};
288 poolInfo.maxSets = 2;
289 poolInfo.poolSizeCount = uint32_t(sizes.size());
290 poolInfo.pPoolSizes = sizes.data();
291 candidate->pool = (*device_)->createDescriptorPool(poolInfo, device_->allocation_callbacks);
292 vk::DescriptorSetAllocateInfo allocateInfo{};
293 allocateInfo.descriptorPool = candidate->pool;
294 const std::array<vk::DescriptorSetLayout, 2> layouts{pathPipeline_->setLayout, pathPipeline_->setLayout};
295 allocateInfo.descriptorSetCount = uint32_t(layouts.size());
296 allocateInfo.pSetLayouts = layouts.data();
297 const auto sets = (*device_)->allocateDescriptorSets(allocateInfo);
298 std::copy(sets.begin(), sets.end(), candidate->sets.begin());
300 if (pathFrame_) graphicsQueue_.waitIdle();
301 }
catch (
const std::exception&
error) {
306 pathFrame_ = std::move(candidate);
307 ++pathFrameGeneration_;
311Result<void> VulkanRayTracing::recordPathDispatch(vk::CommandBuffer command, vk::AccelerationStructureKHR scene,
312 const std::array<vk::DescriptorBufferInfo, 7>& buffers,
313 const path::Constants& constants,
const PathTraceView&
view,
315 if (!command || !scene || !constants.sampling.y)
318 for (
const auto&
buffer : buffers)
322 const bool sameFrame = pathFrame_ && pathFrame_->width ==
width && pathFrame_->height ==
height;
323 const bool sameScene = sameFrame && pathFrame_->scene ==
scene && pathFrame_->buffers == buffers;
324 if (constants.counts.y && (!sameScene || !pathFrame_->initialized))
326 "Path-tracing history must reset after scene or size changes",
327 "graphics.raytracing"));
329 auto&
frame = *pathFrame_;
331 const auto descriptorSet =
frame.sets[
slot];
336 if (
frame.initialized) graphicsQueue_.waitIdle();
337 vk::WriteDescriptorSetAccelerationStructureKHR
acceleration{};
340 std::array<vk::DescriptorImageInfo, 10> images{};
341 for (
size_t i = 0; i < images.size(); ++i) {
342 images[i].imageView =
frame.images[i].imageView();
343 images[i].imageLayout = vk::ImageLayout::eGeneral;
347 constexpr std::array<size_t, 10> reversed{5, 1, 8, 9, 4, 0, 7, 6, 2, 3};
348 for (
size_t setIndex = 0; setIndex <
frame.sets.size(); ++setIndex) {
349 std::array<vk::WriteDescriptorSet, 18> writes{};
350 for (uint32_t i = 0; i < writes.size(); ++i) {
351 writes[i].dstSet =
frame.sets[setIndex];
352 writes[i].dstBinding = i;
353 writes[i].descriptorCount = 1;
355 writes[i].descriptorType = vk::DescriptorType::eAccelerationStructureKHR;
357 }
else if ((i >= 3 && i <= 7) || i == 10 || i == 12) {
358 writes[i].descriptorType = vk::DescriptorType::eStorageBuffer;
359 writes[i].pBufferInfo = &buffers[i == 12 ? 6 : (i == 10 ? 5 : i - 3)];
361 writes[i].descriptorType = vk::DescriptorType::eStorageImage;
362 const size_t imageIndex = i >= 13 ? i - 8 : (i == 11 ? 4 : (i <= 2 ? i - 1 : i - 6));
363 writes[i].pImageInfo = &images[setIndex == 0 ? imageIndex : reversed[imageIndex]];
366 (*device_)->updateDescriptorSets(writes, {});
369 frame.buffers = buffers;
370 }
catch (
const std::exception&
error) {
372 std::string(
"Path-tracing descriptors: ") +
error.what(),
373 "graphics.raytracing"));
377 std::array<vk::ImageMemoryBarrier, 10> barriers{};
378 for (
size_t i = 0; i < barriers.size(); ++i) {
379 auto& barrier = barriers[i];
380 barrier.srcAccessMask =
381 frame.initialized ? vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite : vk::AccessFlags{};
382 barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite;
383 barrier.oldLayout = !
frame.initialized
384 ? vk::ImageLayout::eUndefined
385 : (
frame.sampledOutput && (i == 1 || i == 4) ? vk::ImageLayout::eShaderReadOnlyOptimal
386 : vk::ImageLayout::eGeneral);
387 barrier.newLayout = vk::ImageLayout::eGeneral;
388 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
389 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
390 barrier.image =
frame.images[i].image();
391 barrier.subresourceRange = vk::ImageSubresourceRange{vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
394 vk::MemoryBarrier sceneBarrier{vk::AccessFlagBits::eMemoryWrite,
395 vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite |
396 vk::AccessFlagBits::eAccelerationStructureReadKHR};
397 command.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands,
398 vk::PipelineStageFlagBits::eRayTracingShaderKHR | vk::PipelineStageFlagBits::eComputeShader,
399 {}, sceneBarrier, {}, barriers);
400 command.bindPipeline(vk::PipelineBindPoint::eRayTracingKHR, pathPipeline_->pipeline);
401 command.bindDescriptorSets(vk::PipelineBindPoint::eRayTracingKHR, pathPipeline_->layout, 0, descriptorSet, {});
402 command.pushConstants(pathPipeline_->layout,
403 vk::ShaderStageFlagBits::eRaygenKHR | vk::ShaderStageFlagBits::eCompute, 0,
sizeof(constants),
405 const auto& regions = pathPipeline_->regions;
406 command.traceRaysKHR(regions[0], regions[1], regions[2], regions[3],
width,
height, 1);
407 vk::MemoryBarrier outputBarrier{vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eMemoryRead};
408 command.pipelineBarrier(vk::PipelineStageFlagBits::eRayTracingShaderKHR, vk::PipelineStageFlagBits::eAllCommands,
409 {}, outputBarrier, {}, {});
411 const auto&
previous = pathPreviousView_;
412 const bool valid = sameScene &&
frame.initialized && pathHistorySamples_ != 0 && !
view.resetTemporalHistory &&
417 path::TemporalConstants temporal;
418 if (
valid) temporal.previousViewProj = glm::inverse(
previous.invViewProj);
419 temporal.previousEye = glm::vec4(
previous.eye, 0.f);
420 temporal.currentEye = glm::vec4(
view.eye, 0.f);
421 temporal.parameters = {3.f, .9f, .01f, .99f};
424 32u * std::min(
view.samples, 16u)};
425 command.bindPipeline(vk::PipelineBindPoint::eCompute, pathPipeline_->temporalPipeline);
426 command.bindDescriptorSets(vk::PipelineBindPoint::eCompute, pathPipeline_->layout, 0, descriptorSet, {});
427 command.pushConstants(pathPipeline_->layout,
428 vk::ShaderStageFlagBits::eRaygenKHR | vk::ShaderStageFlagBits::eCompute, 0,
429 sizeof(temporal), &temporal);
430 command.dispatch((
width + 7u) / 8u, (
height + 7u) / 8u, 1);
431 vk::MemoryBarrier historyReady{vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead};
432 command.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eComputeShader,
433 {}, historyReady, {}, {});
435 if (constants.counts.z != 0
u) {
436 command.bindPipeline(vk::PipelineBindPoint::eCompute, pathPipeline_->denoisePipeline);
437 command.bindDescriptorSets(vk::PipelineBindPoint::eCompute, pathPipeline_->layout, 0, descriptorSet, {});
438 command.dispatch((
width + 7u) / 8u, (
height + 7u) / 8u, 1);
439 command.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eAllCommands, {},
440 outputBarrier, {}, {});
443 frame.initialized =
true;
444 frame.sampledOutput =
false;
449bool finiteVector(
const glm::vec3&
value) {
450 return std::isfinite(
value.x) && std::isfinite(
value.y) && std::isfinite(
value.z);
452bool finiteMatrix(
const glm::mat4&
value) {
454 for (
int row = 0;
row < 4; ++
row)
455 if (!std::isfinite(
value[
column][row]))
return false;
461struct NativePathTexture {
468constexpr uint32_t packedTexture = 1, repeatTextureU = 2, repeatTextureV = 4, linearTexture = 8, srgbTexture = 16,
469 premultipliedTexture = 32, mirrorTextureU = 64, mirrorTextureV = 128;
470uint32_t textureSamplerFlags(
const PathColorTexture&
texture, uint32_t
flags) {
472 flags &= ~linearTexture;
477 flags &= ~(repeat | mirror);
481 address(
texture.addressU, repeatTextureU, mirrorTextureU);
482 address(
texture.addressV, repeatTextureV, mirrorTextureV);
497std::vector<uint32_t> instanceWords(std::span<const PathInstance> instances) {
499 key.values.reserve(1 + instances.size() * 17);
500 key.count(instances.size());
501 for (
const auto& instance : instances) {
502 key.values.push_back(instance.geometry);
504 for (
int row = 0;
row < 4; ++
row)
key.scalar(instance.transform[
column][row]);
506 return std::move(
key.values);
509std::vector<uint32_t> sceneWords(
const PathSceneDescription& scene, std::span<const NativePathTexture> native) {
537 key.values.push_back(
material.metallicRoughnessTexture);
543 key.values.push_back(uint32_t(
material.alphaMode));
547 key.values.push_back(uint32_t(
light.kind));
555 key.count(
scene.colorTextures.size());
561 key.values.insert(
key.values.end(), {uint32_t(source.identity), uint32_t(source.identity >> 32),
562 source.width, source.height, source.flags});
569 key.values.insert(
key.values.end(),
570 {uint32_t(texture.filter), uint32_t(texture.addressU), uint32_t(texture.addressV)});
576 for (
float alpha :
texture.alpha)
key.scalar(alpha);
578 return std::move(
key.values);
582Result<void> VulkanRayTracing::buildPathInstances(std::span<const PathInstance>
input,
const PathScene&
source,
583 PathScene& destination) {
589 if (
input.empty() ||
input.size() > 0xffffffu)
return invalid(
"Invalid path instance count");
590 std::vector<path::Instance> instances;
591 std::vector<path::Light>
lights;
594 packed.p0Area = glm::vec4(
598 packed.p1Kind = glm::vec4(glm::normalize(
light.beamDirection), 3.f);
599 packed.p2 = glm::vec4(
light.cosOuter,
light.cosInner, 0.f, 0.f);
601 packed.emission = glm::vec4(
light.strength, 0.f);
604 std::vector<vk::AccelerationStructureInstanceKHR> accelerationInstances;
605 instances.reserve(
input.size());
606 accelerationInstances.reserve(
input.size());
607 for (
const auto& instance :
input) {
608 const auto& transform = instance.transform;
609 const float determinant = glm::determinant(transform);
610 if (instance.geometry >=
source.geometry.size() || !finiteMatrix(transform) || transform[0][3] != 0.f ||
611 transform[1][3] != 0.f || transform[2][3] != 0.f || transform[3][3] != 1.f || !std::isfinite(determinant) ||
612 std::abs(determinant) < 1e-12f)
613 return invalid(
"Path instance needs a valid geometry and invertible affine transform");
615 path::Instance packed;
616 packed.objectToWorld = transform;
617 packed.normalToWorld = glm::transpose(glm::inverse(transform));
618 if (!finiteMatrix(packed.normalToWorld))
return invalid(
"Non-finite path normal transform");
621 for (
int row = 0;
row < 3; ++
row)
624 acceleration.instanceCustomIndex = uint32_t(instances.size());
626 acceleration.flags = uint32_t(vk::GeometryInstanceFlagBitsKHR::eTriangleFacingCullDisable);
627 if (
geometry.alphaCoverage)
acceleration.flags |= uint32_t(vk::GeometryInstanceFlagBitsKHR::eForceNoOpaque);
628 acceleration.accelerationStructureReference =
source.meshes[instance.geometry]->blas.deviceAddress;
630 instances.push_back(packed);
632 if (
lights.size() >= UINT32_MAX - 1u)
return invalid(
"Too many emissive path triangles");
633 const glm::vec3
a = transform * glm::vec4(
emitter.a, 1.f);
634 const glm::vec3
b = transform * glm::vec4(
emitter.b, 1.f);
635 const glm::vec3
c = transform * glm::vec4(
emitter.c, 1.f);
636 const float area = glm::length(glm::cross(
b -
a,
c -
a)) * 0.5f;
637 if (!std::isfinite(
area) ||
area <= 0.f)
return invalid(
"Invalid transformed emissive triangle area");
640 light.p1Kind = glm::vec4(
b, 0.f);
641 light.p2 = glm::vec4(
c, std::bit_cast<float>(
emitter.primitive));
642 light.emission = glm::vec4(
emitter.emission, std::bit_cast<float>(uint32_t(instances.size() - 1)));
646 destination.lightCount = uint32_t(
lights.size());
648 const auto upload = [&](
size_t slot,
const auto&
values) -> Result<void> {
651 return buffer.initializeHostVisible(*device_,
values.data(),
bytes, vk::BufferUsageFlagBits::eStorageBuffer);
653 if (
auto r = upload(2, instances); !
r.ok())
return r;
654 if (
auto r = upload(4,
lights); !
r.ok())
return r;
655 return buildTlas(accelerationInstances, destination.tlas, destination.workspace);
659 std::span<const PathInstance> instances) {
663 if (!pathScene_ || !device_ ||
token.generation != pathScene_->generation || instances.empty() ||
664 instances.size() > 0xffffffu || pathGeneration_ == std::numeric_limits<uint64_t>::max())
668 return updatePathInstancesPrepared(instances, instanceWords(instances));
669 }
catch (
const std::exception&
error) {
675Result<PathSceneToken> VulkanRayTracing::updatePathInstancesPrepared(std::span<const PathInstance> instances,
676 std::vector<uint32_t> newInstanceWords) {
677 auto candidate = pathSpareScene_ ? std::move(pathSpareScene_) :
std::make_unique<PathScene>();
679 if (
auto r = buildPathInstances(instances, *pathScene_, *candidate); !
r.
ok())
681 }
catch (
const std::exception&
error) {
687 candidate->geometry = std::move(pathScene_->geometry);
688 candidate->lights = std::move(pathScene_->lights);
689 candidate->meshes = std::move(pathScene_->meshes);
690 for (
const size_t slot : {size_t(0), size_t(1), size_t(3), size_t(5), size_t(6)})
691 candidate->buffers[
slot] = std::move(pathScene_->buffers[
slot]);
692 candidate->generation = ++pathGeneration_;
693 pathSpareScene_ = std::move(pathScene_);
694 pathScene_ = std::move(candidate);
695 pathInstanceWords_ = std::move(newInstanceWords);
696 pathHistorySamples_ = 0;
699 if (pathFrame_) pathFrame_->scene = vk::AccelerationStructureKHR{};
705 const auto invalid = [](
const char*
message) {
713 if (
graphics->hasOpenPresentFrame())
return invalid(
"Prepare path scenes outside frame recording");
714 reconcilePathRecording();
715 std::vector<NativePathTexture> nativeTextures(
scene.colorTextures.size());
717 if (std::any_of(
scene.colorTextures.begin(),
scene.colorTextures.end(),
719 graphics->ensureFileTexturesReady();
720 for (
size_t i = 0; i <
scene.colorTextures.size(); ++i) {
722 if (!std::isfinite(
texture.offset.x) || !std::isfinite(
texture.offset.y) ||
723 !std::isfinite(
texture.scale.x) || !std::isfinite(
texture.scale.y) || !std::isfinite(
texture.rotation))
724 return invalid(
"Path texture UV transform must be finite");
728 return invalid(
"Invalid path texture sampler override");
729 if (!
texture.sourceTexture)
continue;
731 return invalid(
"Path texture cannot mix engine and pixel-span sources");
735 if (
gpu->width <= 0 ||
gpu->height <= 0 ||
736 gpu->image.currentLayout() != vk::ImageLayout::eShaderReadOnlyOptimal)
737 return invalid(
"Path source texture must have valid dimensions and a sampled layout");
739 const uint32_t
flags =
740 packedTexture | (
sampler.repeatU ? repeatTextureU : 0
u) | (
sampler.repeatV ? repeatTextureV : 0
u) |
742 (
texture.sourceTexture->hasPremultipliedAlpha() ? premultipliedTexture : 0
u);
745 }
catch (
const std::exception&
error) {
749 if (std::any_of(
scene.geometry.begin(),
scene.geometry.end(), [](
const PathGeometry&
g) { return g.sourceMesh; })) {
752 std::vector<glm::vec2>
uv;
753 std::vector<glm::vec3> tangents, bitangents;
758 bool cacheable =
true;
759 std::vector<uint32_t> meshWords;
768 return invalid(
"Path geometry cannot mix mesh and span sources");
772 if (
mesh->hasGpuSkinning() ||
gpu->residentVertexOverride)
775 "Path mesh deformation snapshot is not available",
"graphics.raytracing"));
776 if (!
mesh->geometryGeneration() || !
mesh->tangentFrameRevision()) cacheable =
false;
777 for (uint64_t
revision : {
mesh->geometryGeneration(),
mesh->texcoordRevision(),
778 mesh->tangentFrameRevision(), uint64_t(
gpu->dynamicWriteCount)}) {
779 meshWords.push_back(uint32_t(
revision));
780 meshWords.push_back(uint32_t(
revision >> 32));
782 meshWords.push_back(
gpu->vertexCount);
783 meshWords.push_back(
gpu->indexCount);
784 meshWords.push_back(uint32_t(
gpu->indexType));
788 meshWords.insert(meshWords.end(),
values.begin(),
values.end());
789 if (pathScene_ && pathGraphics_ ==
graphics && meshWords == pathMeshSceneWords_) {
790 auto instanceKey = instanceWords(
scene.instances);
791 if (instanceKey == pathInstanceWords_)
793 if (pathGeneration_ == UINT64_MAX)
return invalid(
"Path scene identity exhausted");
794 return updatePathInstancesPrepared(
scene.instances, std::move(instanceKey));
797 std::vector<Captured>
owned(
scene.geometry.size());
799 graphics->waitForSharedGpuResources();
800 for (
size_t i = 0; i <
resolved.size(); ++i) {
806 return invalid(
"Path geometry cannot mix mesh and span sources");
810 if (
gpu->vertexCount < 3 ||
gpu->indexCount < 3 ||
gpu->indexCount % 3)
811 return invalid(
"Invalid engine mesh geometry for path tracing");
812 if (
mesh->hasGpuSkinning() ||
gpu->residentVertexOverride)
815 "Path mesh deformation snapshot is not available",
"graphics.raytracing"));
816 auto& copy =
owned[i];
817 copy.positions.resize(
gpu->vertexCount);
818 copy.normals.resize(
gpu->vertexCount);
819 copy.uv.resize(
gpu->vertexCount);
820 copy.indices.resize(
gpu->indexCount);
821 auto&
vertices = eve::graphics::vulkan::meshDrawVertices(*
gpu);
823 for (
size_t v = 0;
v < copy.positions.size(); ++
v) {
824 copy.positions[
v] = data[
v].pos;
825 copy.normals[
v] = data[
v].normal;
826 copy.uv[
v] = data[
v].uv;
829 const auto uv0 =
mesh->texcoordSet(0);
831 if (uv0.size() != size_t(
gpu->vertexCount) * 2)
832 return invalid(
"Path UV0 override must match mesh vertices");
833 for (
size_t v = 0;
v < copy.uv.size(); ++
v) copy.uv[
v] = {uv0[
v * 2], uv0[
v * 2 + 1]};
835 if (
mesh->hasImportedTangents()) {
836 const auto&
t =
mesh->importedTangents();
837 const auto&
b =
mesh->importedBitangents();
838 if (
t.size() != size_t(
gpu->vertexCount) * 3 ||
b.size() !=
t.size())
839 return invalid(
"Authored path tangent frame must match mesh vertices");
840 copy.tangents.resize(
gpu->vertexCount);
841 copy.bitangents.resize(
gpu->vertexCount);
842 for (
size_t v = 0;
v < copy.tangents.size(); ++
v) {
843 copy.tangents[
v] = {
t[
v * 3],
t[
v * 3 + 1],
t[
v * 3 + 2]};
844 copy.bitangents[
v] = {
b[
v * 3],
b[
v * 3 + 1],
b[
v * 3 + 2]};
847 if (
gpu->cpuIndices.size() >=
gpu->indexCount) {
848 std::copy_n(
gpu->cpuIndices.begin(),
gpu->indexCount, copy.indices.begin());
850 auto&
indices = eve::graphics::vulkan::meshDrawIndices(*
gpu);
851 const void* dataIndices =
indices.map();
852 for (
size_t v = 0;
v < copy.indices.size(); ++
v)
853 copy.indices[
v] =
gpu->indexType == vk::IndexType::eUint16
854 ?
static_cast<const uint16_t*
>(dataIndices)[
v]
855 :
static_cast<const uint32_t*
>(dataIndices)[
v];
858 geometry.positions = copy.positions;
862 geometry.bitangents = copy.bitangents;
866 auto captured =
scene;
871 pathMeshSceneWords_ = std::move(meshWords);
873 pathMeshSceneWords_.clear();
876 }
catch (
const std::exception&
error) {
881 if (
scene.geometry.empty() ||
scene.instances.empty() ||
scene.materials.empty() ||
882 scene.instances.size() > 0xffffffu ||
scene.materials.size() > UINT32_MAX)
883 return invalid(
"Path scene requires geometry, instances and materials within index limits");
884 uint64_t textureWordCount = 0;
885 for (
size_t i = 0; i <
scene.colorTextures.size(); ++i) {
887 const auto& native = nativeTextures[i];
889 const uint64_t
count = uint64_t(native.width) * native.height;
890 if (
count > UINT32_MAX - textureWordCount)
return invalid(
"Path texture storage exceeds index capacity");
891 textureWordCount +=
count;
897 return invalid(
"Invalid path color texture dimensions");
898 if (!
texture.alpha.empty() &&
texture.alpha.size() !=
count)
return invalid(
"Invalid path texture alpha count");
899 for (
float alpha :
texture.alpha)
900 if (!
std::isfinite(alpha) || alpha < 0.f || alpha > 1.f)
901 return invalid(
"Path texture alpha must be finite in [0,1]");
902 textureWordCount +=
count * 4;
904 if (!finiteVector(pixel) || glm::any(glm::lessThan(pixel, glm::vec3(0.f))) ||
905 glm::any(glm::greaterThan(pixel, glm::vec3(1.f))))
906 return invalid(
"Path color textures require finite linear RGB in [0,1]");
912 return invalid(
"Invalid path material texture index");
913 if (!std::isfinite(
material.normalScale))
return invalid(
"Path normal scale must be finite");
914 if (
material.normalTexture != UINT32_MAX) {
916 if (
texture.sourceTexture &&
texture.srgbDecode)
return invalid(
"Normal textures require linear decoding");
918 if (
material.metallicRoughnessTexture != UINT32_MAX) {
921 return invalid(
"Metallic-roughness textures require linear decoding");
923 if (!finiteVector(
material.baseColor) || !finiteVector(
material.emission) ||
924 glm::any(glm::lessThan(
material.baseColor, glm::vec3(0.f))) ||
925 glm::any(glm::greaterThan(
material.baseColor, glm::vec3(1.f))) ||
926 glm::any(glm::lessThan(
material.emission, glm::vec3(0.f))) || !std::isfinite(
material.roughness) ||
933 return invalid(
"Invalid path material parameters");
935 if (
scene.lights.size() >= UINT32_MAX - 1u)
return invalid(
"Too many analytic path lights");
939 !finiteVector(
light.strength) || glm::any(glm::lessThan(
light.strength, glm::vec3(0.f))) ||
941 return invalid(
"Invalid analytic path light");
944 if (!finiteVector(
light.beamDirection) || !std::isfinite(lengthSquared) || lengthSquared <= 1e-12f ||
945 !std::isfinite(
light.cosOuter) || !std::isfinite(
light.cosInner) ||
light.cosOuter < -1.f ||
947 return invalid(
"Spot light requires a nonzero beam and ordered cone cosines in [-1,1]");
951 if (!finiteVector(
light.directionToLight) || !std::isfinite(lengthSquared) || lengthSquared <= 1e-12f)
952 return invalid(
"Directional path light needs a finite nonzero direction");
958 triangleCount +=
geometry.indices.size() / 3;
960 geometry.indices.size() > UINT32_MAX ||
vertexCount > UINT32_MAX || triangleCount > UINT32_MAX ||
963 return invalid(
"Invalid path geometry dimensions or material index");
965 ((
scene.materials[
geometry.material].baseColorTexture != UINT32_MAX ||
966 scene.materials[
geometry.material].metallicRoughnessTexture != UINT32_MAX ||
967 scene.materials[
geometry.material].emissionTexture != UINT32_MAX ||
968 scene.materials[
geometry.material].normalTexture != UINT32_MAX) &&
970 return invalid(
"Textured path geometry requires one UV per vertex");
976 if (!finiteVector(
normal)) return
invalid(
"Non-finite path normal");
981 return invalid(
"Path tangent frame requires one pair per vertex");
982 for (
size_t i = 0; i <
geometry.tangents.size(); ++i) {
983 const auto t = glm::dvec3(
geometry.tangents[i]),
b = glm::dvec3(
geometry.bitangents[i]);
984 const double tt = glm::dot(
t,
t), bb = glm::dot(
b,
b),
tb = glm::dot(
t,
b);
985 if (!finiteVector(
geometry.tangents[i]) || !finiteVector(
geometry.bitangents[i]) || tt <= 1e-20 ||
986 bb <= 1e-20 || tt * bb -
tb *
tb <= tt * bb * 1e-12)
987 return invalid(
"Path tangent frame requires finite independent directions");
990 for (
size_t i = 0; i <
geometry.indices.size(); i += 3) {
996 if (!std::isfinite(determinant) || std::abs(determinant) <= 1e-12f)
997 return invalid(
"Normal-mapped triangles require nondegenerate UVs or authored tangent frames");
1001 for (
const auto& instance :
scene.instances) {
1002 const auto& transform = instance.transform;
1003 const float determinant = glm::determinant(transform);
1004 if (instance.geometry >=
scene.geometry.size() || !finiteMatrix(transform) || transform[0][3] != 0.f ||
1005 transform[1][3] != 0.f || transform[2][3] != 0.f || transform[3][3] != 1.f || !std::isfinite(determinant) ||
1006 std::abs(determinant) < 1e-12f)
1007 return invalid(
"Path instance needs a valid geometry and invertible affine transform");
1009 if (pathGeneration_ == std::numeric_limits<uint64_t>::max())
return invalid(
"Path scene identity exhausted");
1010 if (pathFrame_ && pathFrameGeneration_ == UINT64_MAX)
return invalid(
"Path frame identity exhausted");
1011 if (device_ != &
graphics->getDevice())
1013 graphics->getDevice().getQueue(vkb::QueueType::graphics));
1015 if (std::max(uint64_t(4), textureWordCount) *
sizeof(uint32_t) >
1016 device_->physical_device.properties.limits.maxStorageBufferRange)
1017 return invalid(
"Path color textures exceed device storage-buffer capacity");
1019 if (std::max(
size_t(1),
scene.colorTextures.size()) >
1020 device_->physical_device.properties.limits.maxStorageBufferRange /
sizeof(path::TextureRecord))
1021 return invalid(
"Path texture records exceed device storage-buffer capacity");
1023 auto candidate = std::make_unique<PathScene>();
1024 std::vector<uint32_t> newSceneWords, newInstanceWords;
1026 newSceneWords = sceneWords(scene, nativeTextures);
1027 newInstanceWords = instanceWords(
scene.instances);
1028 if (pathScene_ && pathGraphics_ == graphics && newSceneWords == pathSceneWords_) {
1029 if (newInstanceWords == pathInstanceWords_)
1031 return updatePathInstancesPrepared(
scene.instances, std::move(newInstanceWords));
1033 candidate->lights.assign(
scene.lights.begin(),
scene.lights.end());
1034 std::vector<path::Vertex>
vertices;
1036 std::vector<path::Material> materials;
1037 std::vector<uint32_t> texels;
1038 std::vector<path::TextureRecord> textureRecords;
1039 for (
size_t i = 0; i <
scene.colorTextures.size(); ++i) {
1041 const auto& native = nativeTextures[i];
1042 path::TextureRecord
record;
1044 record.parameters = glm::vec4(std::cos(
texture.rotation), std::sin(
texture.rotation), 0.f, 0.f);
1046 record.image = {uint32_t(texels.size()), native.width, native.height,
1047 textureSamplerFlags(
texture, native.flags)};
1048 texels.resize(texels.size() +
size_t(native.width) * native.height);
1051 textureSamplerFlags(
texture, repeatTextureU | repeatTextureV | linearTexture)};
1052 for (
size_t pixel = 0; pixel <
texture.pixels.size(); ++pixel) {
1053 const auto rgb =
texture.pixels[pixel];
1056 {std::bit_cast<uint32_t>(rgb.x), std::bit_cast<uint32_t>(rgb.y), std::bit_cast<uint32_t>(rgb.z),
1057 std::bit_cast<uint32_t>(texture.alpha.empty() ? 1.f : texture.alpha[pixel])});
1060 textureRecords.push_back(
record);
1062 if (texels.empty()) texels.resize(4, std::bit_cast<uint32_t>(1.f));
1063 if (textureRecords.empty()) textureRecords.emplace_back();
1065 path::Material packed;
1067 packed.emissionRoughness = glm::vec4(
material.emission,
material.roughness);
1072 materials.push_back(packed);
1075 PathGeometryRecord
record;
1080 for (
size_t i = 0; i <
geometry.positions.size(); ++i) {
1083 path::Vertex vertex;
1084 vertex.position = glm::vec4(
p, 1.f);
1085 if (!
geometry.normals.empty()) vertex.normal = glm::vec4(
geometry.normals[i], 0.f);
1086 if (!
geometry.texcoords.empty()) vertex.texcoord = glm::vec4(
geometry.texcoords[i], 0.f, 0.f);
1088 vertex.tangent = glm::vec4(
geometry.tangents[i], 1.f);
1089 vertex.bitangent = glm::vec4(
geometry.bitangents[i], 0.f);
1093 const bool emissive =
1094 glm::any(glm::greaterThan(
scene.materials[
geometry.material].emission, glm::vec3(0.f)));
1095 for (
size_t i = 0; i <
geometry.indices.size(); i += 3) {
1100 triangle.emitter.x = uint32_t(i / 3);
1104 scene.materials[
geometry.material].emission, uint32_t(i / 3)});
1108 auto mesh = std::make_unique<TriangleMeshRecord>();
1109 mesh->vertexCount = uint32_t(
geometry.positions.size());
1111 const auto uploadGeometry = [&](DeviceAddressBuffer&
target,
const void* data,
1112 size_t bytes) -> Result<void> {
1114 vk::BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR |
1115 vk::BufferUsageFlagBits::eTransferDst);
1118 return target.upload(uploadPool_, graphicsQueue_, data,
bytes);
1123 if (
auto r = uploadGeometry(
mesh->indexBuffer,
geometry.indices.data(),
geometry.indices.size_bytes());
1127 candidate->meshes.push_back(std::move(
mesh));
1128 candidate->geometry.push_back(std::move(
record));
1130 const auto upload = [&](
size_t slot,
const auto&
values) -> Result<void> {
1134 *device_,
bytes, vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst);
1144 if (std::any_of(nativeTextures.begin(), nativeTextures.end(),
1146 graphics->waitForSharedGpuResources();
1147 vkb::executeImmediately(device_->instance, uploadPool_, graphicsQueue_, [&](vk::CommandBuffer command) {
1148 for (size_t i = 0; i < nativeTextures.size(); ++i) {
1149 const auto& texture = nativeTextures[i];
1150 if (!texture.gpu) continue;
1151 vk::ImageMemoryBarrier barrier{};
1152 barrier.srcAccessMask = vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite;
1153 barrier.dstAccessMask = vk::AccessFlagBits::eTransferRead;
1154 barrier.oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
1155 barrier.newLayout = vk::ImageLayout::eTransferSrcOptimal;
1156 barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1157 barrier.image = texture.gpu->image.image();
1158 barrier.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, texture.gpu->mipLevels, 0, 1};
1159 command.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands,
1160 vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 0, nullptr, 1,
1162 vk::BufferImageCopy copy{};
1163 copy.bufferOffset = vk::DeviceSize(textureRecords[i].image.x) * sizeof(uint32_t);
1164 copy.imageSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
1165 copy.imageExtent = vk::Extent3D{texture.width, texture.height, 1};
1166 command.copyImageToBuffer(texture.gpu->image.image(), vk::ImageLayout::eTransferSrcOptimal,
1167 candidate->buffers[5].buffer, copy);
1168 barrier.srcAccessMask = vk::AccessFlagBits::eTransferRead;
1169 barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
1170 std::swap(barrier.oldLayout, barrier.newLayout);
1171 command.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
1172 vk::PipelineStageFlagBits::eAllCommands, {}, 0, nullptr, 0, nullptr, 1,
1175 vk::BufferMemoryBarrier ready{};
1176 ready.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
1177 ready.dstAccessMask = vk::AccessFlagBits::eShaderRead;
1178 ready.srcQueueFamilyIndex = ready.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1179 ready.buffer = candidate->buffers[5].buffer;
1180 ready.size = VK_WHOLE_SIZE;
1181 command.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
1182 vk::PipelineStageFlagBits::eRayTracingShaderKHR, {}, 0,
nullptr, 1, &ready, 0,
1186 if (
auto r = buildPathInstances(
scene.instances, *candidate, *candidate); !
r.ok())
1188 }
catch (
const std::exception&
error) {
1192 candidate->generation = ++pathGeneration_;
1197 pathFrame_->scene = vk::AccelerationStructureKHR{};
1198 ++pathFrameGeneration_;
1200 pathRecordedSequence_ = 0;
1201 pathSpareScene_.reset();
1202 pathScene_ = std::move(candidate);
1203 pathMeshSceneWords_.clear();
1204 pathSceneWords_ = std::move(newSceneWords);
1205 pathInstanceWords_ = std::move(newInstanceWords);
1207 pathHistorySamples_ = 0;
1211void VulkanRayTracing::reconcilePathRecording() {
1212 if (!pathRecordedSequence_ || !pathGraphics_ || pathRecordedSequence_ == pathGraphics_->recordingPresentSequence())
1214 if (pathRecordedSequence_ != pathGraphics_->submittedPresentSequence()) {
1215 pathHistorySamples_ = 0;
1216 if (pathFrame_) pathFrame_->initialized =
false;
1218 pathRecordedSequence_ = 0;
1222 if (!pathScene_ || !pathGraphics_ ||
scene.generation != pathScene_->generation ||
1226 "graphics.raytracing"));
1227 reconcilePathRecording();
1228 if (
auto prepared = ensurePathFrame(
width,
height); !prepared.ok())
1236 const auto invalid = [](
const char*
message) {
1240 if (!pathGraphics_ || !pathScene_ ||
scene.generation != pathScene_->generation || !pathFrame_ ||
1241 output.generation != pathFrameGeneration_ || !pathGraphics_->hasOpenPresentFrame())
1242 return invalid(
"Record paths with prepared output in an open normal frame");
1243 const auto sequence = pathGraphics_->recordingPresentSequence();
1245 return invalid(
"Only one path batch may record per present frame");
1246 reconcilePathRecording();
1248 std::array<vk::DescriptorBufferInfo, 7> buffers{};
1249 for (
size_t i = 0; i < buffers.size(); ++i)
1250 buffers[i] = vk::DescriptorBufferInfo{pathScene_->buffers[i].buffer, 0, pathScene_->buffers[i].size};
1253 constants.
eye = glm::vec4(
view.eye, 0.f);
1256 constants.
counts = {pathScene_->lightCount,
view.historySamples, uint32_t(
view.denoise), 0
u};
1258 pathGraphics_->beginPathSceneOutput();
1259 auto recorded = recordPathDispatch(pathGraphics_->postSceneCommandBuffer(), pathScene_->tlas.handle, buffers,
1260 constants,
view, pathFrame_->width, pathFrame_->height);
1262 std::array<vk::ImageMemoryBarrier, 2> sampled{};
1263 for (
size_t i = 0; i < sampled.size(); ++i) {
1264 auto& barrier = sampled[i];
1265 barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
1266 barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
1267 barrier.oldLayout = vk::ImageLayout::eGeneral;
1268 barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
1269 barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1270 barrier.image = pathFrame_->images[i == 0 ? 1 : 4].image();
1271 barrier.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
1273 pathGraphics_->postSceneCommandBuffer().pipelineBarrier(
1274 vk::PipelineStageFlagBits::eRayTracingShaderKHR | vk::PipelineStageFlagBits::eComputeShader,
1275 vk::PipelineStageFlagBits::eFragmentShader | vk::PipelineStageFlagBits::eComputeShader, {}, {}, {},
1277 pathFrame_->sampledOutput =
true;
1278 }
catch (
const std::exception&
error) {
1279 pathHistorySamples_ = 0;
1280 pathFrame_->initialized =
false;
1285 pathHistorySamples_ =
view.historySamples +
view.samples;
1286 pathPreviousView_ =
view;
1288 pathGraphics_->resolvePathSceneOutput(
texture);
1293 const auto invalid = [](
const char*
message) {
1297 if (!finiteMatrix(
view.invViewProj) || !finiteVector(
view.eye) || !finiteVector(
view.environment) ||
1298 glm::any(glm::lessThan(
view.environment, glm::vec3(0.f))) ||
view.samples == 0 ||
view.samples > 4096 ||
1299 view.maxBounces > 64 ||
view.historySamples > (1u << 24) -
view.samples ||
1300 view.firstSample > UINT32_MAX -
view.samples)
1301 return invalid(
"Invalid path camera or sampling settings");
1304 return invalid(
"Invalid path denoising mode");
1306 (
view.historySamples != 0 || glm::determinant(
view.invViewProj) == 0.f ||
1307 !finiteMatrix(glm::inverse(
view.invViewProj))))
1308 return invalid(
"Temporal paths need an invertible camera and zero explicit historySamples");
1309 const auto&
previous = pathPreviousView_;
1311 return invalid(
"Temporal history cannot be used as exact sample accumulation");
1312 if (
view.historySamples &&
1313 (
view.historySamples != pathHistorySamples_ ||
view.invViewProj !=
previous.invViewProj ||
1316 return invalid(
"Path history does not match the previous completed sample batch");
1321 const auto invalid = [](
const char*
message) {
1326 if (!pathGraphics_ || pathGraphics_->hasOpenPresentFrame())
1327 return invalid(
"Render synchronous path batches outside frame recording");
1328 if (!pathScene_ ||
token.generation != pathScene_->generation || !canvas ||
1329 canvas->owningGraphics() != pathGraphics_ || dest->
getWidth() <= 0 || dest->
getHeight() <= 0)
1330 return invalid(
"Invalid path scene token or destination");
1331 if (canvas->colorImage().format() != vk::Format::eR16G16B16A16Sfloat)
1332 return invalid(
"Path-tracing destination must use RGBA16F");
1333 reconcilePathRecording();
1335 std::array<vk::DescriptorBufferInfo, 7> buffers{};
1336 for (
size_t i = 0; i < buffers.size(); ++i)
1337 buffers[i] = vk::DescriptorBufferInfo{pathScene_->buffers[i].buffer, 0, pathScene_->buffers[i].size};
1340 constants.
eye = glm::vec4(
view.eye, 0.f);
1343 constants.
counts = {pathScene_->lightCount,
view.historySamples, uint32_t(
view.denoise), 0
u};
1346 vkb::executeImmediately(device_->instance, uploadPool_, graphicsQueue_, [&](vk::CommandBuffer command) {
1347 auto recorded = recordPathDispatch(command, pathScene_->tlas.handle, buffers, constants, view,
1348 uint32_t(dest->getWidth()), uint32_t(dest->getHeight()));
1349 if (!recorded.ok()) {
1350 status = recorded.status();
1353 canvas->colorImage().setLayout(command, vk::ImageLayout::eTransferDstOptimal);
1355 region.srcSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
1359 command.copyImage(pathFrame_->images[outputImage].image(), vk::ImageLayout::eGeneral,
1360 canvas->colorImage().image(), vk::ImageLayout::eTransferDstOptimal,
region);
1361 canvas->colorImage().setLayout(command, vk::ImageLayout::eShaderReadOnlyOptimal);
1363 }
catch (
const std::exception&
error) {
1364 pathHistorySamples_ = 0;
1365 if (pathFrame_) pathFrame_->initialized =
false;
1370 pathHistorySamples_ =
view.historySamples +
view.samples;
1371 pathPreviousView_ =
view;
Stable, structured diagnostics shared by engine modules.
ScriptComponentRecord record
ScriptForceVector acceleration
std::uint32_t vertexCount
std::vector< eve::ProcgenProbeDesc > lights
vk::UniqueSampler sampler
wgpu::PopErrorScopeStatus status
std::vector< std::uint32_t > indices
std::vector< float > texcoords
std::vector< float > normals
std::vector< float > positions
std::array< float, 3 > position
std::shared_ptr< OceanGpuSpectrum > gpu
std::shared_ptr< const OceanSprayFrame > previous
std::unique_ptr< gpgpu::GpuBuffer > buffer
std::unique_ptr< gpgpu::Sequence > sequence
eve::action::ActionVfxBinding binding
std::array< uint32_t, 16 > material
std::vector< ParticleBakeMaterial > bindings
std::weak_ptr< PrimitiveScene > scene
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
std::set< std::string > values
std::unique_ptr< TrailEmitter > emitter
std::array< double, 2 > vertices[3]
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.
Structured status and zero or more diagnostics for an operation.
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 int getHeight() const =0
Returns the height.
Result< PathSceneToken > preparePathScene(Graphics *gfx, const PathSceneDescription &scene) override
Prepare and publish a path-tracing scene. @ownership Inputs are borrowed for this call; GPU snapshot ...
Result< PathSceneToken > updatePathInstances(PathSceneToken token, std::span< const PathInstance > instances) override
Replace instances while retaining prepared geometry. @ownership Input is borrowed for the call; the p...
EVENGINE_API_BACKENDS public API.
bool hasOpenPresentFrame() const
True while the present frame command buffer is being recorded, including its render passes.
void retirePathSceneOutput()
Invalidate cached bindings before retiring completed path output; render thread only.
vk::DescriptorSetLayout getTexSetLayout() const
Returns the tex set layout.
OffscreenCanvas public API.
float lengthSquared(Vec3 value)
Length squared.
eve::Diagnostic Diagnostic
Status invalid(const char *message)
Value vector(glm::dvec3 v)
PathTextureAddress
Address override; Source uses the source sampler (repeat for pixel spans).
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
DiagnosticCode
Stable machine-readable diagnostic codes.
Base-level color or material-data texture from linear pixels or an owned engine RGBA8 texture....
Provider-owned frame output identity; invalidated by resize, scene replacement or device detach.
Indexed geometry; spans are borrowed only during scene preparation. @ownership Caller owns all spans ...
Borrowed scene snapshot; preparation copies all inputs into provider-owned resources....
Opaque prepared-scene identity; invalid after replacement or device detachment. @ownership Does not o...
Deterministic path sample batch. Zero history starts a new accumulation.
uint32_t shaderGroupHandleAlignment
bool rayTracingAvailable() const
True when BLAS/TLAS + ray-tracing pipelines can be created.
uint32_t shaderGroupHandleSize
uint32_t shaderGroupBaseAlignment
std::array< eve::graphics::vulkan::GpuTexture, 2 > gpu
std::array< Texture, 2 > textures