载入中...
搜索中...
未找到
VulkanPathTracing.cpp
浏览该文件的文档.
1#include "common/Profile.h"
2// eve-hot-path
4
5#include "common/Diagnostic.h"
6#include "graphics/Canvas.h"
7#include "graphics/Mesh.h"
8#include "graphics/Texture.h"
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"
19
20#include <algorithm>
21#include <bit>
22#include <cmath>
23#include <cstring>
24#include <exception>
25#include <glm/gtc/matrix_inverse.hpp>
26#include <limits>
27#include <string>
28
30
31VulkanRayTracing::PathPipeline::~PathPipeline() {
32 if (!device) return;
33 sbt.release();
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);
39 if (layout) (*device)->destroyPipelineLayout(layout, 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);
43}
44
45Result<void> VulkanRayTracing::ensurePathPipeline() {
46 if (pathPipeline_) return Result<void>::success();
47 // Device binding belongs to the caller; no singleton lookup on this path.
48 if (!device_ || !caps_.rayTracingAvailable())
50 DiagnosticCode::Unsupported, "Path tracing requires an attached RT device", "graphics.raytracing"));
51
52 if (device_->physical_device.properties.limits.maxPerStageDescriptorStorageImages < 10)
54 DiagnosticCode::Unsupported, "Path reconstruction requires ten storage images per shader stage",
55 "graphics.raytracing"));
56 const auto handleSize = caps_.shaderGroupHandleSize;
57 const auto handleAlignment = caps_.shaderGroupHandleAlignment;
58 const auto baseAlignment = caps_.shaderGroupBaseAlignment;
59 if (!handleSize || !handleAlignment || !baseAlignment)
61 DiagnosticCode::Failed, "Invalid ray-tracing shader group properties", "graphics.raytracing"));
62
63 // All intermediate handles belong to this candidate. A failed creation or
64 // upload leaves the live backend unchanged and permits a subsequent retry.
65 auto candidate = std::make_unique<PathPipeline>();
66 candidate->device = device_;
67 try {
68 const std::array<const uint32_t*, 4> code{pt_path_rgen_spv, pt_path_rmiss_spv, pt_path_rchit_spv,
69 pt_path_rahit_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];
75 info.pCode = code[i];
76 candidate->modules[i] = (*device_)->createShaderModule(info, device_->allocation_callbacks);
77 }
78
79 std::array<vk::DescriptorSetLayoutBinding, 18> bindings{};
80 for (uint32_t i = 0; i < bindings.size(); ++i) {
81 bindings[i].binding = i;
82 bindings[i].descriptorCount = 1;
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;
89 }
90 vk::DescriptorSetLayoutCreateInfo setInfo{};
91 setInfo.bindingCount = uint32_t(bindings.size());
92 setInfo.pBindings = bindings.data();
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{};
107 denoiseInfo.stage =
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)
114 DiagnosticCode::Failed, "Path denoise pipeline creation failed", "graphics.raytracing"));
115
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)
125 DiagnosticCode::Failed, "Path temporal pipeline creation failed", "graphics.raytracing"));
126
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";
136 }
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;
144 }
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();
150 // Bounces are iterative in raygen; neither hit nor miss traces recursively.
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)
158 DiagnosticCode::Failed, "Path-tracing pipeline creation failed", "graphics.raytracing"));
159
160 // Vulkan returns tightly packed handles, independent of SBT stride.
161 std::vector<uint8_t> handles(size_t(handleSize) * 3);
162 auto result =
163 (*device_)->getRayTracingShaderGroupHandlesKHR(candidate->pipeline, 0, 3, handles.size(), handles.data());
164 if (result != vk::Result::eSuccess)
166 DiagnosticCode::Failed, "Path-tracing shader group retrieval failed", "graphics.raytracing"));
167 const auto align = [](vk::DeviceSize value, vk::DeviceSize alignment) {
168 return (value + alignment - 1) / alignment * alignment;
169 };
170 const auto stride = align(handleSize, handleAlignment);
171 const auto regionSpacing = align(stride, baseAlignment);
172 // The allocation's device address is not assumed to have SBT base alignment.
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);
177 !r.ok())
178 return r;
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) {
182 const auto offset = start + i * regionSpacing;
183 std::memcpy(bytes.data() + offset, handles.data() + i * handleSize, handleSize);
184 candidate->regions[i] = vk::StridedDeviceAddressRegionKHR{candidate->sbt.address + offset, stride, stride};
185 }
186 if (auto r = candidate->sbt.upload(uploadPool_, graphicsQueue_, bytes.data(), allocationSize); !r.ok())
187 return r;
188 } catch (const std::exception& error) {
190 DiagnosticCode::Failed, std::string("Path-tracing pipeline: ") + error.what(), "graphics.raytracing"));
191 }
192 pathPipeline_ = std::move(candidate);
193 return Result<void>::success();
194}
195
197 vkb::Device* device = nullptr;
198 vk::DescriptorPool pool{};
199 vk::Sampler sampler{};
200 std::array<eve::graphics::vulkan::GpuTexture, 2> gpu;
201 std::array<Texture, 2> textures;
203 if (!device) return;
204 if (pool) (*device)->destroyDescriptorPool(pool, device->allocation_callbacks);
205 if (sampler) (*device)->destroySampler(sampler, device->allocation_callbacks);
206 }
207};
208
209VulkanRayTracing::PathFrame::~PathFrame() {
210 if (device && pool) (*device)->destroyDescriptorPool(pool, device->allocation_callbacks);
211}
212
213Result<void> VulkanRayTracing::ensurePathFrame(uint32_t width, uint32_t height) {
214 if (!width || !height)
216 "Path-tracing extent must be nonzero", "graphics.raytracing"));
217 if (auto r = ensurePathPipeline(); !r.ok()) return r;
218 if (pathFrame_ && pathFrame_->width == width && pathFrame_->height == height) return Result<void>::success();
219 if (pathFrameGeneration_ == UINT64_MAX)
221 Diagnostic::error(DiagnosticCode::Failed, "Path frame identity exhausted", "graphics.raytracing"));
222
223 auto candidate = std::make_unique<PathFrame>();
224 candidate->device = device_;
225 candidate->width = width;
226 candidate->height = height;
227 try {
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;
233 info.extent = vk::Extent3D{width, height, 1};
234 info.mipLevels = 1;
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);
243 }
244 candidate->output = std::make_unique<PathFrame::OutputTextures>();
245 auto& output = *candidate->output;
246 output.device = device_;
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(),
260 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) {
264 auto& gpu = output.gpu[i];
265 gpu.width = int(width);
266 gpu.height = int(height);
267 gpu.sampler = output.sampler;
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);
273 for (uint32_t binding = 0; binding < 5; ++binding)
274 updater.beginImages(binding, 0, vk::DescriptorType::eCombinedImageSampler)
275 .image(
276 vkb::SampledImage{output.sampler, gpu.viewOverride, vk::ImageLayout::eShaderReadOnlyOptimal});
277 updater.update(device_->instance);
278 gpu.descriptorSet = std::move(unbound).publish();
279 auto& texture = output.textures[i];
280 texture.width = texture.pixelWidth = int(width);
281 texture.height = texture.pixelHeight = int(height);
282 texture.gpuHandle = &gpu;
283 }
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());
299 // Size changes retire all history/guide images as one allocation set.
300 if (pathFrame_) graphicsQueue_.waitIdle();
301 } catch (const std::exception& error) {
303 DiagnosticCode::Failed, std::string("Path-tracing frame: ") + error.what(), "graphics.raytracing"));
304 }
305 if (pathFrame_) pathGraphics_->retirePathSceneOutput();
306 pathFrame_ = std::move(candidate);
307 ++pathFrameGeneration_;
308 return Result<void>::success();
309}
310
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,
314 uint32_t width, uint32_t height) {
315 if (!command || !scene || !constants.sampling.y)
317 DiagnosticCode::InvalidArgument, "Path tracing needs a command, scene and samples", "graphics.raytracing"));
318 for (const auto& buffer : buffers)
319 if (!buffer.buffer || !buffer.range)
320 return Result<void>::failure(Diagnostic::error(
321 DiagnosticCode::InvalidArgument, "Path-tracing scene buffer is empty", "graphics.raytracing"));
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"));
328 if (auto r = ensurePathFrame(width, height); !r.ok()) return r;
329 auto& frame = *pathFrame_;
330 const uint32_t slot = view.denoise == PathDenoise::Temporal ? frame.nextTemporalSlot : 0u;
331 const auto descriptorSet = frame.sets[slot];
332 if (!sameScene) {
333 try {
334 // Stable scene descriptors are reused without per-frame queue waits.
335 // The caller must submit the previous recording before replacing a scene.
336 if (frame.initialized) graphicsQueue_.waitIdle();
337 vk::WriteDescriptorSetAccelerationStructureKHR acceleration{};
338 acceleration.accelerationStructureCount = 1;
339 acceleration.pAccelerationStructures = &scene;
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;
344 }
345 // Both sets are immutable while frames are in flight. Set 1 reverses
346 // current/history roles for radiance, normal, albedo and position.
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;
354 if (i == 0) {
355 writes[i].descriptorType = vk::DescriptorType::eAccelerationStructureKHR;
356 writes[i].pNext = &acceleration;
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)];
360 } else {
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]];
364 }
365 }
366 (*device_)->updateDescriptorSets(writes, {});
367 }
368 frame.scene = scene;
369 frame.buffers = buffers;
370 } catch (const std::exception& error) {
372 std::string("Path-tracing descriptors: ") + error.what(),
373 "graphics.raytracing"));
374 }
375 }
376
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};
392 }
393 // This also orders scene upload/build writes before shader and AS reads.
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),
404 &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, {}, {});
410 if (view.denoise == PathDenoise::Temporal) {
411 const auto& previous = pathPreviousView_;
412 const bool valid = sameScene && frame.initialized && pathHistorySamples_ != 0 && !view.resetTemporalHistory &&
413 previous.denoise == PathDenoise::Temporal &&
414 view.firstSample == previous.firstSample + previous.samples &&
415 view.environment == previous.environment && view.seed == previous.seed &&
416 view.maxBounces == previous.maxBounces;
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};
422 const bool identicalCamera = valid && view.invViewProj == previous.invViewProj && view.eye == previous.eye;
423 temporal.counts = {uint32_t(valid) | (identicalCamera ? 2u : 0u), view.samples, uint32_t(PathDenoise::Temporal),
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, {}, {});
434 }
435 if (constants.counts.z != 0u) {
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, {}, {});
441 }
442 if (view.denoise == PathDenoise::Temporal) frame.nextTemporalSlot = slot ^ 1u;
443 frame.initialized = true;
444 frame.sampledOutput = false;
445 return Result<void>::success();
446}
447
448namespace {
449bool finiteVector(const glm::vec3& value) {
450 return std::isfinite(value.x) && std::isfinite(value.y) && std::isfinite(value.z);
451}
452bool finiteMatrix(const glm::mat4& value) {
453 for (int column = 0; column < 4; ++column)
454 for (int row = 0; row < 4; ++row)
455 if (!std::isfinite(value[column][row])) return false;
456 return true;
457}
458
459// Ephemeral, padding-free value encoding for exact cache comparison. No digest
460// collision can hide a geometry/material/light change; signed zero is canonical.
461struct NativePathTexture {
462 eve::graphics::vulkan::GpuTexture* gpu = nullptr; // Borrowed only during preparation.
463 uint64_t identity = 0;
464 uint32_t width = 0, height = 0, flags = 0;
465};
466// Private texture flags shared with pt_surface.glsl: packed RGBA8, repeat U/V,
467// linear magnification, sRGB decode, premultiplied input.
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) {
471 if (texture.filter != PathTextureFilter::Source) {
472 flags &= ~linearTexture;
473 if (texture.filter == PathTextureFilter::Linear) flags |= linearTexture;
474 }
475 const auto address = [&](PathTextureAddress mode, uint32_t repeat, uint32_t mirror) {
476 if (mode == PathTextureAddress::Source) return;
477 flags &= ~(repeat | mirror);
478 if (mode == PathTextureAddress::Repeat) flags |= repeat;
479 if (mode == PathTextureAddress::Mirror) flags |= mirror;
480 };
481 address(texture.addressU, repeatTextureU, mirrorTextureU);
482 address(texture.addressV, repeatTextureV, mirrorTextureV);
483 return flags;
484}
485
486struct SceneWords {
487 std::vector<uint32_t> values;
488 void scalar(float value) { values.push_back(std::bit_cast<uint32_t>(value == 0.f ? 0.f : value)); }
489 void vector(const glm::vec3& value) {
490 scalar(value.x);
491 scalar(value.y);
492 scalar(value.z);
493 }
494 void count(size_t size) { values.push_back(uint32_t(size)); }
495};
496
497std::vector<uint32_t> instanceWords(std::span<const PathInstance> instances) {
498 SceneWords key;
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);
503 for (int column = 0; column < 4; ++column)
504 for (int row = 0; row < 4; ++row) key.scalar(instance.transform[column][row]);
505 }
506 return std::move(key.values);
507}
508
509std::vector<uint32_t> sceneWords(const PathSceneDescription& scene, std::span<const NativePathTexture> native) {
510 SceneWords key;
511 key.count(scene.geometry.size());
512 for (const auto& geometry : scene.geometry) {
513 key.values.push_back(geometry.material);
514 key.count(geometry.positions.size());
515 for (const auto& value : geometry.positions) key.vector(value);
516 key.count(geometry.normals.size());
517 for (const auto& value : geometry.normals) key.vector(value);
518 key.count(geometry.texcoords.size());
519 for (const auto& value : geometry.texcoords) {
520 key.scalar(value.x);
521 key.scalar(value.y);
522 }
523 key.count(geometry.tangents.size());
524 for (const auto& tangent : geometry.tangents) key.vector(tangent);
525 key.count(geometry.bitangents.size());
526 for (const auto& bitangent : geometry.bitangents) key.vector(bitangent);
527 key.count(geometry.indices.size());
528 key.values.insert(key.values.end(), geometry.indices.begin(), geometry.indices.end());
529 }
530 key.count(scene.materials.size());
531 for (const auto& material : scene.materials) {
532 key.vector(material.baseColor);
533 key.vector(material.emission);
534 key.scalar(material.roughness);
535 key.scalar(material.metallic);
536 key.values.push_back(material.baseColorTexture);
537 key.values.push_back(material.metallicRoughnessTexture);
538 key.values.push_back(material.emissionTexture);
539 key.values.push_back(material.normalTexture);
540 key.scalar(material.normalScale);
541 key.scalar(material.opacity);
542 key.scalar(material.alphaCutoff);
543 key.values.push_back(uint32_t(material.alphaMode));
544 }
545 key.count(scene.lights.size());
546 for (const auto& light : scene.lights) {
547 key.values.push_back(uint32_t(light.kind));
548 key.vector(light.position);
549 key.vector(light.directionToLight);
550 key.vector(light.strength);
551 key.vector(light.beamDirection);
552 key.scalar(light.cosOuter);
553 key.scalar(light.cosInner);
554 }
555 key.count(scene.colorTextures.size());
556 for (size_t index = 0; index < scene.colorTextures.size(); ++index) {
557 const auto& texture = scene.colorTextures[index];
558 const auto& source = native[index];
559 key.values.push_back(source.gpu ? 1u : 0u);
560 if (source.gpu) {
561 key.values.insert(key.values.end(), {uint32_t(source.identity), uint32_t(source.identity >> 32),
562 source.width, source.height, source.flags});
563 }
564 key.scalar(texture.offset.x);
565 key.scalar(texture.offset.y);
566 key.scalar(texture.scale.x);
567 key.scalar(texture.scale.y);
568 key.scalar(texture.rotation);
569 key.values.insert(key.values.end(),
570 {uint32_t(texture.filter), uint32_t(texture.addressU), uint32_t(texture.addressV)});
571 key.values.push_back(texture.width);
572 key.values.push_back(texture.height);
573 key.count(texture.pixels.size());
574 for (const auto& pixel : texture.pixels) key.vector(pixel);
575 key.count(texture.alpha.size());
576 for (float alpha : texture.alpha) key.scalar(alpha);
577 }
578 return std::move(key.values);
579}
580} // namespace
581
582Result<void> VulkanRayTracing::buildPathInstances(std::span<const PathInstance> input, const PathScene& source,
583 PathScene& destination) {
584 EV_PROFILE_MODULE("graphics", "Path.BuildInstances");
585 const auto invalid = [](const char* message) {
588 };
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;
592 for (const auto& light : source.lights) {
593 path::Light packed;
594 packed.p0Area = glm::vec4(
595 light.kind == PathLightKind::Directional ? glm::normalize(light.directionToLight) : light.position, 0.f);
596 packed.p1Kind.w = light.kind == PathLightKind::Directional ? 2.f : 1.f;
597 if (light.kind == PathLightKind::Spot) {
598 packed.p1Kind = glm::vec4(glm::normalize(light.beamDirection), 3.f);
599 packed.p2 = glm::vec4(light.cosOuter, light.cosInner, 0.f, 0.f);
600 }
601 packed.emission = glm::vec4(light.strength, 0.f);
602 lights.push_back(packed);
603 }
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");
614 const auto& geometry = source.geometry[instance.geometry];
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");
619 packed.offsets = {geometry.firstTriangle, geometry.firstVertex, uint32_t(lights.size()), 0u};
620 vk::AccelerationStructureInstanceKHR acceleration{};
621 for (int row = 0; row < 3; ++row)
622 for (int column = 0; column < 4; ++column)
623 acceleration.transform.matrix[row][column] = transform[column][row];
624 acceleration.instanceCustomIndex = uint32_t(instances.size());
625 acceleration.mask = 0xff;
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;
629 accelerationInstances.push_back(acceleration);
630 instances.push_back(packed);
631 for (const auto& emitter : geometry.emitters) {
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");
638 path::Light light;
639 light.p0Area = glm::vec4(a, 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)));
643 lights.push_back(light);
644 }
645 }
646 destination.lightCount = uint32_t(lights.size());
647 if (lights.empty()) lights.emplace_back();
648 const auto upload = [&](size_t slot, const auto& values) -> Result<void> {
649 const auto bytes = values.size() * sizeof(values[0]);
650 auto& buffer = destination.buffers[slot];
651 return buffer.initializeHostVisible(*device_, values.data(), bytes, vk::BufferUsageFlagBits::eStorageBuffer);
652 };
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);
656}
657
659 std::span<const PathInstance> instances) {
660 if (!pathGraphics_ || pathGraphics_->hasOpenPresentFrame())
662 DiagnosticCode::InvalidArgument, "Update path instances outside frame recording", "graphics.raytracing"));
663 if (!pathScene_ || !device_ || token.generation != pathScene_->generation || instances.empty() ||
664 instances.size() > 0xffffffu || pathGeneration_ == std::numeric_limits<uint64_t>::max())
666 DiagnosticCode::InvalidArgument, "Invalid path scene identity for instance update", "graphics.raytracing"));
667 try {
668 return updatePathInstancesPrepared(instances, instanceWords(instances));
669 } catch (const std::exception& error) {
671 DiagnosticCode::Failed, std::string("Path instance key: ") + error.what(), "graphics.raytracing"));
672 }
673}
674
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>();
678 try {
679 if (auto r = buildPathInstances(instances, *pathScene_, *candidate); !r.ok())
680 return Result<PathSceneToken>::failure(r.status());
681 } catch (const std::exception& error) {
683 DiagnosticCode::Failed, std::string("Path instance update: ") + error.what(), "graphics.raytracing"));
684 }
685 // Transfer immutable geometry only after every new GPU resource is ready.
686 // The TLAS build has completed, retiring all prior uses on this queue.
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;
697 // Keep image allocations, but force descriptor refresh even if driver handles
698 // are recycled through several updates without intervening draws.
699 if (pathFrame_) pathFrame_->scene = vk::AccelerationStructureKHR{};
700 return Result<PathSceneToken>::success(PathSceneToken{pathGeneration_});
701}
702
704 EV_PROFILE_MODULE("graphics", "Path.PrepareScene");
705 const auto invalid = [](const char* message) {
708 };
709 auto* graphics = dynamic_cast<eve::graphics::vulkan::Graphics*>(gfx);
710 if (!graphics || !graphics->supportsRayTracing())
712 DiagnosticCode::Unsupported, "Path scene requires Vulkan hardware ray tracing", "graphics.raytracing"));
713 if (graphics->hasOpenPresentFrame()) return invalid("Prepare path scenes outside frame recording");
714 reconcilePathRecording();
715 std::vector<NativePathTexture> nativeTextures(scene.colorTextures.size());
716 try {
717 if (std::any_of(scene.colorTextures.begin(), scene.colorTextures.end(),
718 [](const PathColorTexture& texture) { return texture.sourceTexture != nullptr; }))
719 graphics->ensureFileTexturesReady();
720 for (size_t i = 0; i < scene.colorTextures.size(); ++i) {
721 const auto& texture = scene.colorTextures[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");
725 if (uint32_t(texture.filter) > uint32_t(PathTextureFilter::Linear) ||
726 uint32_t(texture.addressU) > uint32_t(PathTextureAddress::Mirror) ||
727 uint32_t(texture.addressV) > uint32_t(PathTextureAddress::Mirror))
728 return invalid("Invalid path texture sampler override");
729 if (!texture.sourceTexture) continue;
730 if (texture.width || texture.height || !texture.pixels.empty() || !texture.alpha.empty())
731 return invalid("Path texture cannot mix engine and pixel-span sources");
732 auto identity = graphics->textureContentIdentity(texture.sourceTexture);
733 if (!identity.ok()) return Result<PathSceneToken>::failure(identity.status());
734 auto* gpu = static_cast<eve::graphics::vulkan::GpuTexture*>(texture.sourceTexture->gpuHandle);
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");
738 const auto& sampler = gpu->samplerState;
739 const uint32_t flags =
740 packedTexture | (sampler.repeatU ? repeatTextureU : 0u) | (sampler.repeatV ? repeatTextureV : 0u) |
741 (sampler.mag == FilterMode::Linear ? linearTexture : 0u) | (texture.srgbDecode ? srgbTexture : 0u) |
742 (texture.sourceTexture->hasPremultipliedAlpha() ? premultipliedTexture : 0u);
743 nativeTextures[i] = {gpu, identity.value(), uint32_t(gpu->width), uint32_t(gpu->height), flags};
744 }
745 } catch (const std::exception& error) {
747 DiagnosticCode::Failed, std::string("Path source texture: ") + error.what(), "graphics.raytracing"));
748 }
749 if (std::any_of(scene.geometry.begin(), scene.geometry.end(), [](const PathGeometry& g) { return g.sourceMesh; })) {
750 struct Captured {
751 std::vector<glm::vec3> positions, normals;
752 std::vector<glm::vec2> uv;
753 std::vector<glm::vec3> tangents, bitangents;
754 std::vector<uint32_t> indices;
755 };
756 try {
757 // Generation identities are globally unique; never retain borrowed mesh pointers.
758 bool cacheable = true;
759 std::vector<uint32_t> meshWords;
760 for (const auto& geometry : scene.geometry) {
761 auto* mesh = geometry.sourceMesh;
762 if (!mesh) {
763 cacheable = false;
764 continue;
765 }
766 if (!geometry.positions.empty() || !geometry.normals.empty() || !geometry.indices.empty() ||
767 !geometry.texcoords.empty() || !geometry.tangents.empty() || !geometry.bitangents.empty())
768 return invalid("Path geometry cannot mix mesh and span sources");
769 auto description = graphics->describeMesh(mesh);
770 if (!description.ok()) return Result<PathSceneToken>::failure(description.status());
771 auto* gpu = static_cast<eve::graphics::vulkan::GpuMesh*>(mesh->gpuHandle);
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));
781 }
782 meshWords.push_back(gpu->vertexCount);
783 meshWords.push_back(gpu->indexCount);
784 meshWords.push_back(uint32_t(gpu->indexType));
785 }
786 if (cacheable) {
787 auto values = sceneWords(scene, nativeTextures);
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_)
792 return Result<PathSceneToken>::success(PathSceneToken{pathGeneration_});
793 if (pathGeneration_ == UINT64_MAX) return invalid("Path scene identity exhausted");
794 return updatePathInstancesPrepared(scene.instances, std::move(instanceKey));
795 }
796 }
797 std::vector<Captured> owned(scene.geometry.size());
798 std::vector<PathGeometry> resolved(scene.geometry.begin(), scene.geometry.end());
799 graphics->waitForSharedGpuResources();
800 for (size_t i = 0; i < resolved.size(); ++i) {
801 auto& geometry = resolved[i];
802 auto* mesh = geometry.sourceMesh;
803 if (!mesh) continue;
804 if (!geometry.positions.empty() || !geometry.normals.empty() || !geometry.indices.empty() ||
805 !geometry.texcoords.empty() || !geometry.tangents.empty() || !geometry.bitangents.empty())
806 return invalid("Path geometry cannot mix mesh and span sources");
807 auto description = graphics->describeMesh(mesh);
808 if (!description.ok()) return Result<PathSceneToken>::failure(description.status());
809 auto* gpu = static_cast<eve::graphics::vulkan::GpuMesh*>(mesh->gpuHandle);
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);
822 const auto* data = static_cast<const eve::graphics::vulkan::MeshVertex*>(vertices.map());
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;
827 }
828 vertices.unmap();
829 const auto uv0 = mesh->texcoordSet(0);
830 if (!uv0.empty()) {
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]};
834 }
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]};
845 }
846 }
847 if (gpu->cpuIndices.size() >= gpu->indexCount) {
848 std::copy_n(gpu->cpuIndices.begin(), gpu->indexCount, copy.indices.begin());
849 } else {
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];
856 indices.unmap();
857 }
858 geometry.positions = copy.positions;
859 geometry.normals = copy.normals;
860 geometry.texcoords = copy.uv;
861 geometry.tangents = copy.tangents;
862 geometry.bitangents = copy.bitangents;
863 geometry.indices = copy.indices;
864 geometry.sourceMesh = nullptr;
865 }
866 auto captured = scene;
867 captured.geometry = resolved;
868 auto prepared = preparePathScene(gfx, captured);
869 if (prepared.ok()) {
870 if (cacheable)
871 pathMeshSceneWords_ = std::move(meshWords);
872 else
873 pathMeshSceneWords_.clear();
874 }
875 return prepared;
876 } catch (const std::exception& error) {
878 DiagnosticCode::Failed, std::string("Path mesh capture: ") + error.what(), "graphics.raytracing"));
879 }
880 }
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) {
886 const auto& texture = scene.colorTextures[i];
887 const auto& native = nativeTextures[i];
888 if (native.gpu) {
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;
892 continue;
893 }
894 const uint64_t count = uint64_t(texture.width) * texture.height;
895 if (!texture.width || !texture.height || texture.width > INT32_MAX / 2 || texture.height > INT32_MAX / 2 ||
896 count != texture.pixels.size() || count * 4 > UINT32_MAX - textureWordCount)
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;
903 for (const auto& pixel : texture.pixels)
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]");
907 }
908 for (const auto& material : scene.materials) {
909 for (uint32_t texture : {material.baseColorTexture, material.metallicRoughnessTexture, material.emissionTexture,
910 material.normalTexture})
911 if (texture != UINT32_MAX && texture >= scene.colorTextures.size())
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) {
915 const auto& texture = scene.colorTextures[material.normalTexture];
916 if (texture.sourceTexture && texture.srgbDecode) return invalid("Normal textures require linear decoding");
917 }
918 if (material.metallicRoughnessTexture != UINT32_MAX) {
919 const auto& texture = scene.colorTextures[material.metallicRoughnessTexture];
920 if (texture.sourceTexture && texture.srgbDecode)
921 return invalid("Metallic-roughness textures require linear decoding");
922 }
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) ||
927 material.roughness < 0.f || material.roughness > 1.f || !std::isfinite(material.metallic) ||
928 material.metallic < 0.f || material.metallic > 1.f || !std::isfinite(material.opacity) ||
929 material.opacity < 0.f || material.opacity > 1.f || !std::isfinite(material.alphaCutoff) ||
930 material.alphaCutoff < 0.f || material.alphaCutoff > 1.f ||
931 (material.alphaMode != PathAlphaMode::Opaque && material.alphaMode != PathAlphaMode::Masked &&
932 material.alphaMode != PathAlphaMode::Blend))
933 return invalid("Invalid path material parameters");
934 }
935 if (scene.lights.size() >= UINT32_MAX - 1u) return invalid("Too many analytic path lights");
936 for (const auto& light : scene.lights) {
938 light.kind != PathLightKind::Spot) ||
939 !finiteVector(light.strength) || glm::any(glm::lessThan(light.strength, glm::vec3(0.f))) ||
940 (light.kind != PathLightKind::Directional && !finiteVector(light.position)))
941 return invalid("Invalid analytic path light");
942 if (light.kind == PathLightKind::Spot) {
943 const float lengthSquared = glm::dot(light.beamDirection, light.beamDirection);
944 if (!finiteVector(light.beamDirection) || !std::isfinite(lengthSquared) || lengthSquared <= 1e-12f ||
945 !std::isfinite(light.cosOuter) || !std::isfinite(light.cosInner) || light.cosOuter < -1.f ||
946 light.cosInner > 1.f || light.cosOuter > light.cosInner)
947 return invalid("Spot light requires a nonzero beam and ordered cone cosines in [-1,1]");
948 }
949 if (light.kind == PathLightKind::Directional) {
950 const float lengthSquared = glm::dot(light.directionToLight, light.directionToLight);
951 if (!finiteVector(light.directionToLight) || !std::isfinite(lengthSquared) || lengthSquared <= 1e-12f)
952 return invalid("Directional path light needs a finite nonzero direction");
953 }
954 }
955 uint64_t vertexCount = 0, triangleCount = 0;
956 for (const auto& geometry : scene.geometry) {
957 vertexCount += geometry.positions.size();
958 triangleCount += geometry.indices.size() / 3;
959 if (geometry.positions.size() < 3 || geometry.indices.empty() || geometry.indices.size() % 3 ||
960 geometry.indices.size() > UINT32_MAX || vertexCount > UINT32_MAX || triangleCount > UINT32_MAX ||
961 geometry.material >= scene.materials.size() ||
962 (!geometry.normals.empty() && geometry.normals.size() != geometry.positions.size()))
963 return invalid("Invalid path geometry dimensions or material index");
964 if ((!geometry.texcoords.empty() && geometry.texcoords.size() != geometry.positions.size()) ||
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) &&
969 geometry.texcoords.empty()))
970 return invalid("Textured path geometry requires one UV per vertex");
971 for (const auto& uv : geometry.texcoords)
972 if (!std::isfinite(uv.x) || !std::isfinite(uv.y)) return invalid("Non-finite path UV");
973 for (const auto& position : geometry.positions)
974 if (!finiteVector(position)) return invalid("Non-finite path vertex");
975 for (const auto& normal : geometry.normals)
976 if (!finiteVector(normal)) return invalid("Non-finite path normal");
977 for (auto index : geometry.indices)
978 if (index >= geometry.positions.size()) return invalid("Path index exceeds vertex count");
979 if (geometry.tangents.size() != geometry.bitangents.size() ||
980 (!geometry.tangents.empty() && geometry.tangents.size() != geometry.positions.size()))
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");
988 }
989 if (scene.materials[geometry.material].normalTexture != UINT32_MAX && geometry.tangents.empty()) {
990 for (size_t i = 0; i < geometry.indices.size(); i += 3) {
991 auto a = geometry.texcoords[geometry.indices[i]];
992 auto b = geometry.texcoords[geometry.indices[i + 1]] - a;
993 auto c = geometry.texcoords[geometry.indices[i + 2]] - a;
994 const auto& texture = scene.colorTextures[scene.materials[geometry.material].normalTexture];
995 float determinant = (b.x * c.y - b.y * c.x) * texture.scale.x * texture.scale.y;
996 if (!std::isfinite(determinant) || std::abs(determinant) <= 1e-12f)
997 return invalid("Normal-mapped triangles require nondegenerate UVs or authored tangent frames");
998 }
999 }
1000 }
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");
1008 }
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())
1012 attachDevice(&graphics->getDevice(), graphics->rayTracingCaps(), graphics->getUploadPool(),
1013 graphics->getDevice().getQueue(vkb::QueueType::graphics));
1014 if (auto r = ensurePathPipeline(); !r.ok()) return Result<PathSceneToken>::failure(r.status());
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");
1018
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");
1022
1023 auto candidate = std::make_unique<PathScene>();
1024 std::vector<uint32_t> newSceneWords, newInstanceWords;
1025 try {
1026 newSceneWords = sceneWords(scene, nativeTextures);
1027 newInstanceWords = instanceWords(scene.instances);
1028 if (pathScene_ && pathGraphics_ == graphics && newSceneWords == pathSceneWords_) {
1029 if (newInstanceWords == pathInstanceWords_)
1030 return Result<PathSceneToken>::success(PathSceneToken{pathScene_->generation});
1031 return updatePathInstancesPrepared(scene.instances, std::move(newInstanceWords));
1032 }
1033 candidate->lights.assign(scene.lights.begin(), scene.lights.end());
1034 std::vector<path::Vertex> vertices;
1035 std::vector<path::Triangle> triangles;
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) {
1040 const auto& texture = scene.colorTextures[i];
1041 const auto& native = nativeTextures[i];
1042 path::TextureRecord record;
1043 record.scaleOffset = glm::vec4(texture.scale, texture.offset);
1044 record.parameters = glm::vec4(std::cos(texture.rotation), std::sin(texture.rotation), 0.f, 0.f);
1045 if (native.gpu) {
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);
1049 } else {
1050 record.image = {uint32_t(texels.size()), texture.width, texture.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];
1054 texels.insert(
1055 texels.end(),
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])});
1058 }
1059 }
1060 textureRecords.push_back(record);
1061 }
1062 if (texels.empty()) texels.resize(4, std::bit_cast<uint32_t>(1.f));
1063 if (textureRecords.empty()) textureRecords.emplace_back();
1064 for (const auto& material : scene.materials) {
1065 path::Material packed;
1066 packed.baseColor = glm::vec4(material.baseColor, material.opacity);
1067 packed.emissionRoughness = glm::vec4(material.emission, material.roughness);
1068 packed.parameters =
1069 glm::vec4(material.metallic, material.alphaCutoff, float(material.alphaMode), material.normalScale);
1070 packed.textures = {material.baseColorTexture, material.metallicRoughnessTexture, material.emissionTexture,
1071 material.normalTexture};
1072 materials.push_back(packed);
1073 }
1074 for (const auto& geometry : scene.geometry) {
1075 PathGeometryRecord record;
1076 record.firstTriangle = uint32_t(triangles.size());
1077 record.firstVertex = uint32_t(vertices.size());
1078 record.alphaCoverage = scene.materials[geometry.material].alphaMode != PathAlphaMode::Opaque;
1079 std::vector<float> positions;
1080 for (size_t i = 0; i < geometry.positions.size(); ++i) {
1081 const auto p = geometry.positions[i];
1082 positions.insert(positions.end(), {p.x, p.y, p.z});
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);
1087 if (!geometry.tangents.empty()) {
1088 vertex.tangent = glm::vec4(geometry.tangents[i], 1.f);
1089 vertex.bitangent = glm::vec4(geometry.bitangents[i], 0.f);
1090 }
1091 vertices.push_back(vertex);
1092 }
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) {
1096 path::Triangle triangle;
1097 triangle.indicesMaterial = {geometry.indices[i], geometry.indices[i + 1], geometry.indices[i + 2],
1098 geometry.material};
1099 if (emissive) {
1100 triangle.emitter.x = uint32_t(i / 3);
1101 record.emitters.push_back({geometry.positions[geometry.indices[i]],
1102 geometry.positions[geometry.indices[i + 1]],
1103 geometry.positions[geometry.indices[i + 2]],
1104 scene.materials[geometry.material].emission, uint32_t(i / 3)});
1105 }
1106 triangles.push_back(triangle);
1107 }
1108 auto mesh = std::make_unique<TriangleMeshRecord>();
1109 mesh->vertexCount = uint32_t(geometry.positions.size());
1110 mesh->indexCount = uint32_t(geometry.indices.size());
1111 const auto uploadGeometry = [&](DeviceAddressBuffer& target, const void* data,
1112 size_t bytes) -> Result<void> {
1113 if (auto r = target.allocate(*device_, bytes,
1114 vk::BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR |
1115 vk::BufferUsageFlagBits::eTransferDst);
1116 !r.ok())
1117 return r;
1118 return target.upload(uploadPool_, graphicsQueue_, data, bytes);
1119 };
1120 if (auto r = uploadGeometry(mesh->vertexBuffer, positions.data(), positions.size() * sizeof(float));
1121 !r.ok())
1122 return Result<PathSceneToken>::failure(r.status());
1123 if (auto r = uploadGeometry(mesh->indexBuffer, geometry.indices.data(), geometry.indices.size_bytes());
1124 !r.ok())
1125 return Result<PathSceneToken>::failure(r.status());
1126 if (auto r = buildBlas(*mesh); !r.ok()) return Result<PathSceneToken>::failure(r.status());
1127 candidate->meshes.push_back(std::move(mesh));
1128 candidate->geometry.push_back(std::move(record));
1129 }
1130 const auto upload = [&](size_t slot, const auto& values) -> Result<void> {
1131 const auto bytes = values.size() * sizeof(values[0]);
1132 auto& buffer = candidate->buffers[slot];
1133 if (auto r = buffer.allocate(
1134 *device_, bytes, vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst);
1135 !r.ok())
1136 return r;
1137 return buffer.upload(uploadPool_, graphicsQueue_, values.data(), bytes);
1138 };
1139 if (auto r = upload(0, vertices); !r.ok()) return Result<PathSceneToken>::failure(r.status());
1140 if (auto r = upload(1, triangles); !r.ok()) return Result<PathSceneToken>::failure(r.status());
1141 if (auto r = upload(3, materials); !r.ok()) return Result<PathSceneToken>::failure(r.status());
1142 if (auto r = upload(5, texels); !r.ok()) return Result<PathSceneToken>::failure(r.status());
1143 if (auto r = upload(6, textureRecords); !r.ok()) return Result<PathSceneToken>::failure(r.status());
1144 if (std::any_of(nativeTextures.begin(), nativeTextures.end(),
1145 [](const auto& texture) { return texture.gpu; })) {
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,
1161 &barrier);
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,
1173 &barrier);
1174 }
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,
1183 nullptr);
1184 });
1185 }
1186 if (auto r = buildPathInstances(scene.instances, *candidate, *candidate); !r.ok())
1187 return Result<PathSceneToken>::failure(r.status());
1188 } catch (const std::exception& error) {
1190 DiagnosticCode::Failed, std::string("Path scene: ") + error.what(), "graphics.raytracing"));
1191 }
1192 candidate->generation = ++pathGeneration_;
1193 // Scene uploads/builds completed before publication. Keep same-device output
1194 // images and sampled identities alive so HDR binding caches can reuse them.
1195 // The public output token still expires on full scene replacement.
1196 if (pathFrame_) {
1197 pathFrame_->scene = vk::AccelerationStructureKHR{};
1198 ++pathFrameGeneration_;
1199 }
1200 pathRecordedSequence_ = 0;
1201 pathSpareScene_.reset();
1202 pathScene_ = std::move(candidate);
1203 pathMeshSceneWords_.clear();
1204 pathSceneWords_ = std::move(newSceneWords);
1205 pathInstanceWords_ = std::move(newInstanceWords);
1206 pathGraphics_ = graphics;
1207 pathHistorySamples_ = 0;
1208 return Result<PathSceneToken>::success(PathSceneToken{pathGeneration_});
1209}
1210
1211void VulkanRayTracing::reconcilePathRecording() {
1212 if (!pathRecordedSequence_ || !pathGraphics_ || pathRecordedSequence_ == pathGraphics_->recordingPresentSequence())
1213 return;
1214 if (pathRecordedSequence_ != pathGraphics_->submittedPresentSequence()) {
1215 pathHistorySamples_ = 0;
1216 if (pathFrame_) pathFrame_->initialized = false;
1217 }
1218 pathRecordedSequence_ = 0;
1219}
1220
1221Result<PathFrameToken> VulkanRayTracing::preparePathFrame(PathSceneToken scene, uint32_t width, uint32_t height) {
1222 if (!pathScene_ || !pathGraphics_ || scene.generation != pathScene_->generation ||
1223 pathGraphics_->hasOpenPresentFrame() || !width || !height || width > INT32_MAX || height > INT32_MAX)
1225 DiagnosticCode::InvalidArgument, "Prepare path output outside a frame with a valid scene and extent",
1226 "graphics.raytracing"));
1227 reconcilePathRecording();
1228 if (auto prepared = ensurePathFrame(width, height); !prepared.ok())
1229 return Result<PathFrameToken>::failure(prepared.status());
1230 return Result<PathFrameToken>::success(PathFrameToken{pathFrameGeneration_});
1231}
1232
1233Result<Texture*> VulkanRayTracing::recordPathFrame(PathSceneToken scene, PathFrameToken output,
1234 const PathTraceView& view) {
1235 EV_PROFILE_MODULE("graphics", "Path.RecordFrame");
1236 const auto invalid = [](const char* message) {
1239 };
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();
1244 if (!sequence || sequence == pathRecordedSequence_)
1245 return invalid("Only one path batch may record per present frame");
1246 reconcilePathRecording();
1247 if (auto valid = validatePathView(view); !valid.ok()) return Result<Texture*>::failure(valid.status());
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};
1251 path::Constants constants;
1252 constants.invViewProj = view.invViewProj;
1253 constants.eye = glm::vec4(view.eye, 0.f);
1254 constants.environment = glm::vec4(view.environment, 0.f);
1255 constants.sampling = {view.firstSample, view.samples, view.maxBounces, view.seed};
1256 constants.counts = {pathScene_->lightCount, view.historySamples, uint32_t(view.denoise), 0u};
1257 try {
1258 pathGraphics_->beginPathSceneOutput();
1259 auto recorded = recordPathDispatch(pathGraphics_->postSceneCommandBuffer(), pathScene_->tlas.handle, buffers,
1260 constants, view, pathFrame_->width, pathFrame_->height);
1261 if (!recorded.ok()) return Result<Texture*>::failure(recorded.status());
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};
1272 }
1273 pathGraphics_->postSceneCommandBuffer().pipelineBarrier(
1274 vk::PipelineStageFlagBits::eRayTracingShaderKHR | vk::PipelineStageFlagBits::eComputeShader,
1275 vk::PipelineStageFlagBits::eFragmentShader | vk::PipelineStageFlagBits::eComputeShader, {}, {}, {},
1276 sampled);
1277 pathFrame_->sampledOutput = true;
1278 } catch (const std::exception& error) {
1279 pathHistorySamples_ = 0;
1280 pathFrame_->initialized = false;
1282 DiagnosticCode::Failed, std::string("Record path frame: ") + error.what(), "graphics.raytracing"));
1283 }
1284 pathRecordedSequence_ = sequence;
1285 pathHistorySamples_ = view.historySamples + view.samples;
1286 pathPreviousView_ = view;
1287 auto* texture = &pathFrame_->output->textures[view.denoise != PathDenoise::None ? 1 : 0];
1288 pathGraphics_->resolvePathSceneOutput(texture);
1290}
1291
1292Result<void> VulkanRayTracing::validatePathView(const PathTraceView& view) const {
1293 const auto invalid = [](const char* message) {
1294 return Result<void>::failure(
1296 };
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");
1302 if (view.denoise != PathDenoise::None && view.denoise != PathDenoise::Spatial &&
1303 view.denoise != PathDenoise::Temporal)
1304 return invalid("Invalid path denoising mode");
1305 if (view.denoise == PathDenoise::Temporal &&
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_;
1310 if (view.historySamples && previous.denoise == PathDenoise::Temporal)
1311 return invalid("Temporal history cannot be used as exact sample accumulation");
1312 if (view.historySamples &&
1313 (view.historySamples != pathHistorySamples_ || view.invViewProj != previous.invViewProj ||
1314 view.eye != previous.eye || view.environment != previous.environment || view.seed != previous.seed ||
1315 view.maxBounces != previous.maxBounces || view.firstSample != previous.firstSample + previous.samples))
1316 return invalid("Path history does not match the previous completed sample batch");
1317 return Result<void>::success();
1318}
1319
1320Result<void> VulkanRayTracing::renderPaths(PathSceneToken token, Canvas* dest, const PathTraceView& view) {
1321 const auto invalid = [](const char* message) {
1322 return Result<void>::failure(
1324 };
1325 auto* canvas = dynamic_cast<eve::graphics::vulkan::OffscreenCanvas*>(dest);
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();
1334 if (auto valid = validatePathView(view); !valid.ok()) return valid;
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};
1338 path::Constants constants;
1339 constants.invViewProj = view.invViewProj;
1340 constants.eye = glm::vec4(view.eye, 0.f);
1341 constants.environment = glm::vec4(view.environment, 0.f);
1342 constants.sampling = {view.firstSample, view.samples, view.maxBounces, view.seed};
1343 constants.counts = {pathScene_->lightCount, view.historySamples, uint32_t(view.denoise), 0u};
1345 try {
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();
1351 return;
1352 }
1353 canvas->colorImage().setLayout(command, vk::ImageLayout::eTransferDstOptimal);
1354 vk::ImageCopy region{};
1355 region.srcSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
1356 region.dstSubresource = region.srcSubresource;
1357 region.extent = vk::Extent3D{uint32_t(dest->getWidth()), uint32_t(dest->getHeight()), 1};
1358 const size_t outputImage = view.denoise != PathDenoise::None ? 4 : 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);
1362 });
1363 } catch (const std::exception& error) {
1364 pathHistorySamples_ = 0;
1365 if (pathFrame_) pathFrame_->initialized = false;
1367 DiagnosticCode::Failed, std::string("Path dispatch: ") + error.what(), "graphics.raytracing"));
1368 }
1369 if (!status.isSuccess()) return Result<void>::failure(status);
1370 pathHistorySamples_ = view.historySamples + view.samples;
1371 pathPreviousView_ = view;
1372 return Result<void>::success();
1373}
1374
1375} // namespace eve::graphics::raytracing
double y
double x
LogicalId target
Duration start
std::string output
ActiveSource owned
std::uint64_t revision
float uv
glm::vec4 p[6]
Stable, structured diagnostics shared by engine modules.
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
EvpackChunkInput input
Definition Evpack.cpp:170
std::string layout
int triangle
Definition FluidSdf.cpp:554
ScriptForceVector acceleration
ScriptFieldRegion region
std::string message
DiagnosticCode code
std::uint32_t vertexCount
tensor::Graph g
Definition GpuGraph.cpp:7
std::vector< eve::ProcgenProbeDesc > lights
vkb::Device & device
vk::UniqueSampler sampler
wgpu::PopErrorScopeStatus status
float u
Definition Grass.cpp:233
float area
Definition Grass.cpp:62
double r
std::vector< std::uint32_t > indices
std::vector< float > texcoords
std::vector< float > normals
std::vector< float > positions
float v
std::int32_t c
std::uint32_t height
std::uint32_t width
size_t offset
Range range
std::array< float, 3 > position
Poco::JSON::Object::Ptr result
const char * description
std::uint64_t bytes
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< TriangleRef > triangles
float tb
Texture * normal
OceanGpuFrameToken token
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
ssq::Object frame
OceanSprayView view
std::shared_ptr< const OceanSprayFrame > previous
uint32_t groups
Definition OnnxGpgpu.cpp:39
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
std::string error
Definition Package.cpp:174
eve::action::ActionVfxBinding binding
std::array< uint32_t, 16 > material
Texture * texture
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.
Definition Profile.h:158
std::set< std::string > values
Object::Ptr value
float t
uint8_t * pixels
std::string slot
RoadNetwork resolved
int created
std::string geometry
Graphics * graphics
std::string_view source
unsigned column
Light3D::Data * light
Definition Shadow.cpp:147
int count
std::unique_ptr< TrailEmitter > emitter
std::array< double, 2 > vertices[3]
float size
Definition TreeMesh.cpp:158
uint32_t index
uint64_t identity
uint32_t flags
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.
Definition Result.h:514
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
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
Canvas public API.
Definition Canvas.h:17
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.
Definition Graphics.h:360
bool hasOpenPresentFrame() const
True while the present frame command buffer is being recorded, including its render passes.
Definition Graphics.h:1067
void retirePathSceneOutput()
Invalidate cached bindings before retiring completed path output; render thread only.
vk::DescriptorSetLayout getTexSetLayout() const
Returns the tex set layout.
Definition Graphics.h:1092
OffscreenCanvas public API.
Definition Canvas.h:15
float lengthSquared(Vec3 value)
Length squared.
eve::Diagnostic Diagnostic
eve::Result< T > Result
Status invalid(const char *message)
PathTextureAddress
Address override; Source uses the source sampler (repeat for pixel spans).
Definition PathTracing.h:42
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
Definition Widget.cpp:870
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Base-level color or material-data texture from linear pixels or an owned engine RGBA8 texture....
Definition PathTracing.h:55
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 ...
Definition PathTracing.h:75
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.
bool rayTracingAvailable() const
True when BLAS/TLAS + ray-tracing pipelines can be created.
GpuMesh public API.
Definition Graphics.h:298
GpuTexture public API.
Definition Graphics.h:264
MeshVertex public API.
Definition Graphics.h:148
glm::uvec4 info