载入中...
搜索中...
未找到
VulkanRayTracing.cpp
浏览该文件的文档.
1#include "common/Profile.h"
2// eve-hot-path
4
5#include "common/Capability.h"
6#include "common/Diagnostic.h"
7#include "common/Exception.h"
8#include "common/Module.h"
9#include "common/Status.h"
10#include "graphics/Canvas.h"
11#include "graphics/Graphics.h"
12#include "graphics/Mesh.h"
13#include "graphics/Texture.h"
14#include "graphics/shaders/rt_reflection_rchit_spv.inc"
15#include "graphics/shaders/rt_reflection_rgen_spv.inc"
16#include "graphics/shaders/rt_reflection_rmiss_spv.inc"
20
21#include <algorithm>
22#include <cstring>
23#include <string>
24#include <vector>
25
27namespace {
28
29uint32_t alignedSize(uint32_t value, uint32_t alignment) {
30 if (alignment == 0) return value;
31 return (value + alignment - 1u) & ~(alignment - 1u);
32}
33
34vk::TransformMatrixKHR toTransformMatrix(const glm::mat4& m) {
35 // Vulkan expects a 3x4 row-major affine matrix.
36 vk::TransformMatrixKHR out{};
37 const float* src = &m[0][0];
38 out.matrix[0][0] = src[0];
39 out.matrix[0][1] = src[4];
40 out.matrix[0][2] = src[8];
41 out.matrix[0][3] = src[12];
42 out.matrix[1][0] = src[1];
43 out.matrix[1][1] = src[5];
44 out.matrix[1][2] = src[9];
45 out.matrix[1][3] = src[13];
46 out.matrix[2][0] = src[2];
47 out.matrix[2][1] = src[6];
48 out.matrix[2][2] = src[10];
49 out.matrix[2][3] = src[14];
50 return out;
51}
52
53} // namespace
54
56 if (!device) return;
57 if (buffer) (*device)->destroyBuffer(buffer, device->allocation_callbacks);
58 if (memory) (*device)->freeMemory(memory, device->allocation_callbacks);
59 buffer = vk::Buffer{};
60 memory = vk::DeviceMemory{};
61 size = 0;
62 address = 0;
63 device = nullptr;
64 usage_ = {};
65 properties_ = {};
66}
67
69 buffer = o.buffer;
70 memory = o.memory;
71 size = o.size;
72 address = o.address;
73 device = o.device;
74 usage_ = o.usage_;
75 properties_ = o.properties_;
76 o.buffer = vk::Buffer{};
77 o.memory = vk::DeviceMemory{};
78 o.size = 0;
79 o.address = 0;
80 o.device = nullptr;
81}
82
83Result<void> DeviceAddressBuffer::allocate(vkb::Device& dev, vk::DeviceSize bytes, vk::BufferUsageFlags usage) {
84 return allocateWithProperties(dev, bytes, usage, vk::MemoryPropertyFlagBits::eDeviceLocal);
85}
86
87Result<void> DeviceAddressBuffer::initializeHostVisible(vkb::Device& dev, const void* data, vk::DeviceSize bytes,
88 vk::BufferUsageFlags usage) {
89 if (!data)
91 DiagnosticCode::InvalidArgument, "Host-visible buffer needs initial data", "graphics.raytracing"));
92 if (auto r = allocateWithProperties(
93 dev, bytes, usage, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
94 !r.ok())
95 return r;
96 void* mapped = (*device)->mapMemory(memory, 0, bytes);
97 std::memcpy(mapped, data, size_t(bytes));
98 (*device)->unmapMemory(memory);
99 return Result<void>::success();
100}
101
102Result<void> DeviceAddressBuffer::allocateWithProperties(vkb::Device& dev, vk::DeviceSize bytes,
103 vk::BufferUsageFlags usage,
104 vk::MemoryPropertyFlags properties) {
105 if (bytes == 0) return Result<void>::failure(
106 Diagnostic::error(DiagnosticCode::InvalidArgument, std::string("DeviceAddressBuffer.allocate") + ": " + "size is zero", "graphics.raytracing"));
107 if (device == &dev && buffer && memory && address && size >= bytes && (usage_ & usage) == usage &&
108 (properties_ & properties) == properties)
109 return Result<void>::success();
110 release();
111 device = &dev;
112
113 vk::BufferCreateInfo ci{};
114 ci.size = bytes;
115 ci.usage = usage | vk::BufferUsageFlagBits::eShaderDeviceAddress;
116 ci.sharingMode = vk::SharingMode::eExclusive;
117 buffer = (*device)->createBuffer(ci, device->allocation_callbacks);
118 size = bytes;
119
120 const auto memreq = (*device)->getBufferMemoryRequirements(buffer);
121
122 vk::MemoryAllocateFlagsInfo flagsInfo{};
123 flagsInfo.flags = vk::MemoryAllocateFlagBits::eDeviceAddress;
124
125 vk::MemoryAllocateInfo allocInfo{};
126 allocInfo.pNext = &flagsInfo;
127 allocInfo.allocationSize = memreq.size;
128 allocInfo.memoryTypeIndex = device->physical_device.findMemoryTypeIndex(memreq.memoryTypeBits, properties);
129 memory = (*device)->allocateMemory(allocInfo, device->allocation_callbacks);
130 (*device)->bindBufferMemory(buffer, memory, 0);
131 usage_ = usage;
132 properties_ = properties;
133
134 vk::BufferDeviceAddressInfo addrInfo{};
135 addrInfo.buffer = buffer;
136 address = (*device)->getBufferAddress(addrInfo);
137 if (address == 0) {
138 release();
140 Diagnostic::error(DiagnosticCode::Failed, std::string("DeviceAddressBuffer.allocate") + ": " + "getBufferAddress returned 0", "graphics.raytracing"));
141 }
142 return Result<void>::success();
143}
144
145Result<void> DeviceAddressBuffer::upload(vk::CommandPool pool, vk::Queue queue, const void* data,
146 vk::DeviceSize bytes) {
147 if (!device || !buffer) return Result<void>::failure(
148 Diagnostic::error(DiagnosticCode::Failed, std::string("DeviceAddressBuffer.upload") + ": " + "buffer not allocated", "graphics.raytracing"));
149 if (!data || bytes == 0 || bytes > size) return Result<void>::failure(
150 Diagnostic::error(DiagnosticCode::InvalidArgument, std::string("DeviceAddressBuffer.upload") + ": " + "invalid host data", "graphics.raytracing"));
151
152 using pfb = vk::MemoryPropertyFlagBits;
153 vkb::GenericBuffer staging(*device, vk::BufferUsageFlagBits::eTransferSrc, bytes,
154 pfb::eHostVisible | pfb::eHostCoherent);
155 staging.updateLocal(vkb::FrameSlot::gpuIdle(), data, bytes);
156
157 auto cmd = (*device)->allocateCommandBuffers({pool, vk::CommandBufferLevel::ePrimary, 1}).front();
158 cmd.begin({vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
159 vk::BufferCopy copy{};
160 copy.size = bytes;
161 cmd.copyBuffer(staging.buffer, buffer, copy);
162 cmd.end();
163 vk::SubmitInfo submit{};
164 submit.commandBufferCount = 1;
165 submit.pCommandBuffers = &cmd;
166 queue.submit(submit, vk::Fence{});
167 queue.waitIdle();
168 (*device)->freeCommandBuffers(pool, cmd);
169 return Result<void>::success();
170}
171
173 if (device && handle) {
174 (*device)->destroyAccelerationStructureKHR(handle, device->allocation_callbacks);
175 handle = vk::AccelerationStructureKHR{};
176 }
178 deviceAddress = 0;
179 device = nullptr;
180}
181
183 handle = o.handle;
184 storage = std::move(o.storage);
185 deviceAddress = o.deviceAddress;
186 device = o.device;
187 o.handle = vk::AccelerationStructureKHR{};
188 o.deviceAddress = 0;
189 o.device = nullptr;
190}
191
193 static VulkanRayTracing instance;
194 return instance;
195}
196
198
200 auto* base = eve::ModuleManager::getInstance<eve::graphics::Graphics>("Graphics");
201 if (!base) base = eve::graphics::Graphics::create();
202 auto* vg = dynamic_cast<eve::graphics::vulkan::Graphics*>(base);
203 if (!vg || !vg->supportsRayTracing()) {
204 if (vg) caps_ = vg->rayTracingCaps();
206 DiagnosticCode::Unsupported, std::string("ensureAttached") + ": hardware ray tracing unavailable", "graphics.raytracing"));
207 }
208 vkb::Device* current = &vg->getDevice();
209 // Rebind whenever Graphics rebuilt the logical device (pointer identity).
210 if (device_ == current && caps_.rayTracingAvailable()) return Result<void>::success();
211 attachDevice(current, vg->rayTracingCaps(), vg->getUploadPool(),
212 vg->getDevice().getQueue(vkb::QueueType::graphics));
214 DiagnosticCode::Unsupported, std::string("ensureAttached") + ": hardware ray tracing unavailable", "graphics.raytracing"));
215 return Result<void>::success();
216}
217
219 if (device_ && caps_.rayTracingAvailable()) return true;
220 // Const path: probe Graphics without mutating. Non-const callers use ensureAttached.
221 auto* base = eve::ModuleManager::getInstance<eve::graphics::Graphics>("Graphics");
222 auto* vg = dynamic_cast<eve::graphics::vulkan::Graphics*>(base);
223 return vg && vg->supportsRayTracing();
224}
225
227 if (caps_.rayTracingAvailable()) return caps_;
228 auto* base = eve::ModuleManager::getInstance<eve::graphics::Graphics>("Graphics");
229 auto* vg = dynamic_cast<eve::graphics::vulkan::Graphics*>(base);
230 return vg ? vg->rayTracingCaps() : RayTracingCaps{};
231}
232
233void VulkanRayTracing::attachDevice(vkb::Device* device, const RayTracingCaps& caps, vk::CommandPool uploadPool,
234 vk::Queue graphicsQueue) {
235 detachDevice();
236 device_ = device;
237 caps_ = caps;
238 uploadPool_ = uploadPool;
239 graphicsQueue_ = graphicsQueue;
240}
241
243 if (pathPipeline_ && graphicsQueue_) graphicsQueue_.waitIdle();
244 if (pathFrame_ && pathGraphics_) pathGraphics_->retirePathSceneOutput();
245 pathFrame_.reset();
246 pathScene_.reset();
247 pathSceneWords_.clear();
248 pathMeshSceneWords_.clear();
249 pathInstanceWords_.clear();
250 pathGraphics_ = nullptr;
251 pathRecordedSequence_ = 0;
252 pathSpareScene_.reset();
253 pathHistorySamples_ = 0;
254 pathPipeline_.reset();
255 clearScene();
256 if (device_) {
257 if (pipeline_) (*device_)->destroyPipeline(pipeline_, device_->allocation_callbacks);
258 if (pipelineLayout_) (*device_)->destroyPipelineLayout(pipelineLayout_, device_->allocation_callbacks);
259 if (setLayout_) (*device_)->destroyDescriptorSetLayout(setLayout_, device_->allocation_callbacks);
260 if (descriptorPool_) (*device_)->destroyDescriptorPool(descriptorPool_, device_->allocation_callbacks);
261 if (sampler_) (*device_)->destroySampler(sampler_, device_->allocation_callbacks);
262 if (raygenModule_) (*device_)->destroyShaderModule(raygenModule_, device_->allocation_callbacks);
263 if (missModule_) (*device_)->destroyShaderModule(missModule_, device_->allocation_callbacks);
264 if (closestHitModule_) (*device_)->destroyShaderModule(closestHitModule_, device_->allocation_callbacks);
265 }
266 pipeline_ = vk::Pipeline{};
267 pipelineLayout_ = vk::PipelineLayout{};
268 setLayout_ = vk::DescriptorSetLayout{};
269 descriptorPool_ = vk::DescriptorPool{};
270 descriptorSet_ = vk::DescriptorSet{};
271 sampler_ = vk::Sampler{};
272 raygenModule_ = vk::ShaderModule{};
273 missModule_ = vk::ShaderModule{};
274 closestHitModule_ = vk::ShaderModule{};
275 outputImage_ = StorageColorImage{};
276 outputWidth_ = 0;
277 outputHeight_ = 0;
278 sbtBuffer_.release();
279 raygenRegion_ = vk::StridedDeviceAddressRegionKHR{};
280 missRegion_ = vk::StridedDeviceAddressRegionKHR{};
281 hitRegion_ = vk::StridedDeviceAddressRegionKHR{};
282 callableRegion_ = vk::StridedDeviceAddressRegionKHR{};
283 device_ = nullptr;
284 uploadPool_ = vk::CommandPool{};
285 graphicsQueue_ = vk::Queue{};
286 caps_ = {};
287}
288
290 // The previous present submission may still reference these BLAS/TLAS buffers.
291 if (device_ && graphicsQueue_ && (!meshes_.empty() || tlas_.handle)) graphicsQueue_.waitIdle();
292 meshes_.clear();
293 tlas_.release();
294}
295
296Result<uint32_t> VulkanRayTracing::addTriangleMesh(const float* positionsXYZ, int vertexCount, const uint32_t* indices,
297 int indexCount, const glm::mat4& transform) {
298 if (auto attached = ensureAttached(); !attached.ok()) return Result<uint32_t>::failure(attached.status());
299 if (!positionsXYZ || vertexCount < 3 || !indices || indexCount < 3 || (indexCount % 3) != 0)
301 "addTriangleMesh: invalid geometry", "graphics.raytracing"));
302
303 auto mesh = std::make_unique<TriangleMeshRecord>();
304 mesh->vertexCount = uint32_t(vertexCount);
305 mesh->indexCount = uint32_t(indexCount);
306 mesh->transform = transform;
307
308 const vk::DeviceSize vBytes = vk::DeviceSize(vertexCount) * 3u * sizeof(float);
309 const vk::DeviceSize iBytes = vk::DeviceSize(indexCount) * sizeof(uint32_t);
310 const auto usage = vk::BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR |
311 vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst;
312
313 if (auto r = mesh->vertexBuffer.allocate(*device_, vBytes, usage); !r.ok())
314 return Result<uint32_t>::failure(r.status());
315 if (auto r = mesh->indexBuffer.allocate(*device_, iBytes, usage); !r.ok())
316 return Result<uint32_t>::failure(r.status());
317 if (auto r = mesh->vertexBuffer.upload(uploadPool_, graphicsQueue_, positionsXYZ, vBytes); !r.ok())
318 return Result<uint32_t>::failure(r.status());
319 if (auto r = mesh->indexBuffer.upload(uploadPool_, graphicsQueue_, indices, iBytes); !r.ok())
320 return Result<uint32_t>::failure(r.status());
321 if (auto r = buildBlas(*mesh); !r.ok()) return Result<uint32_t>::failure(r.status());
322
323 const uint32_t id = uint32_t(meshes_.size());
324 meshes_.push_back(std::move(mesh));
325 return Result<uint32_t>::success(id);
326}
327
329 if (auto attached = ensureAttached(); !attached.ok()) return Result<uint32_t>::failure(attached.status());
330 if (!mesh || !mesh->gpuHandle)
332 DiagnosticCode::InvalidArgument, "addMesh: null mesh or missing GPU handle", "graphics.raytracing"));
333 auto* gpu = static_cast<eve::graphics::vulkan::GpuMesh*>(mesh->gpuHandle);
334 if (gpu->vertexCount < 3 || gpu->indexCount < 3 || (gpu->indexCount % 3u) != 0)
336 Diagnostic::error(DiagnosticCode::InvalidArgument, "addMesh: invalid geometry", "graphics.raytracing"));
337
338 auto& vb = eve::graphics::vulkan::meshDrawVertices(*gpu);
339 if (!vb.buffer)
341 Diagnostic::error(DiagnosticCode::Failed, "addMesh: empty vertex buffer", "graphics.raytracing"));
342
343 std::vector<float> positions(size_t(gpu->vertexCount) * 3u);
344 {
345 void* mapped = vb.map();
346 const auto* verts = static_cast<const eve::graphics::vulkan::MeshVertex*>(mapped);
347 for (uint32_t i = 0; i < gpu->vertexCount; ++i) {
348 positions[size_t(i) * 3u + 0u] = verts[i].pos.x;
349 positions[size_t(i) * 3u + 1u] = verts[i].pos.y;
350 positions[size_t(i) * 3u + 2u] = verts[i].pos.z;
351 }
352 vb.unmap();
353 }
354
355 std::vector<uint32_t> indices(gpu->indexCount);
356 if (!gpu->cpuIndices.empty() && gpu->cpuIndices.size() >= gpu->indexCount) {
357 std::copy_n(gpu->cpuIndices.begin(), gpu->indexCount, indices.begin());
358 } else {
359 auto& ib = eve::graphics::vulkan::meshDrawIndices(*gpu);
360 if (!ib.buffer)
362 Diagnostic::error(DiagnosticCode::Failed, "addMesh: empty index buffer", "graphics.raytracing"));
363 void* mapped = ib.map();
364 if (gpu->indexType == vk::IndexType::eUint16) {
365 const auto* src = static_cast<const uint16_t*>(mapped);
366 for (uint32_t i = 0; i < gpu->indexCount; ++i) indices[i] = src[i];
367 } else {
368 std::memcpy(indices.data(), mapped, size_t(gpu->indexCount) * sizeof(uint32_t));
369 }
370 ib.unmap();
371 }
372
373 return addTriangleMesh(positions.data(), int(gpu->vertexCount), indices.data(), int(gpu->indexCount), transform);
374}
375
376Result<void> VulkanRayTracing::buildBlas(TriangleMeshRecord& mesh) {
377 vk::AccelerationStructureGeometryTrianglesDataKHR triangles{};
378 triangles.vertexFormat = vk::Format::eR32G32B32Sfloat;
379 triangles.vertexData.deviceAddress = mesh.vertexBuffer.address;
380 triangles.vertexStride = sizeof(float) * 3;
381 triangles.maxVertex = mesh.vertexCount - 1;
382 triangles.indexType = vk::IndexType::eUint32;
383 triangles.indexData.deviceAddress = mesh.indexBuffer.address;
384
385 vk::AccelerationStructureGeometryKHR geometry{};
386 geometry.geometryType = vk::GeometryTypeKHR::eTriangles;
387 geometry.flags = vk::GeometryFlagBitsKHR::eOpaque;
388 geometry.geometry.triangles = triangles;
389
390 vk::AccelerationStructureBuildGeometryInfoKHR buildInfo{};
391 buildInfo.type = vk::AccelerationStructureTypeKHR::eBottomLevel;
392 buildInfo.flags = vk::BuildAccelerationStructureFlagBitsKHR::ePreferFastTrace;
393 buildInfo.mode = vk::BuildAccelerationStructureModeKHR::eBuild;
394 buildInfo.geometryCount = 1;
395 buildInfo.pGeometries = &geometry;
396
397 const uint32_t primitiveCount = mesh.indexCount / 3;
398 const auto sizes = (*device_)->getAccelerationStructureBuildSizesKHR(vk::AccelerationStructureBuildTypeKHR::eDevice,
399 buildInfo, primitiveCount);
400
401 auto storageResult = mesh.blas.storage.allocate(
402 *device_, sizes.accelerationStructureSize,
403 vk::BufferUsageFlagBits::eAccelerationStructureStorageKHR | vk::BufferUsageFlagBits::eShaderDeviceAddress);
404 if (!storageResult.ok()) return storageResult;
405
406 vk::AccelerationStructureCreateInfoKHR createInfo{};
407 createInfo.buffer = mesh.blas.storage.buffer;
408 createInfo.size = sizes.accelerationStructureSize;
409 createInfo.type = vk::AccelerationStructureTypeKHR::eBottomLevel;
410 mesh.blas.handle = (*device_)->createAccelerationStructureKHR(createInfo, device_->allocation_callbacks);
411 mesh.blas.device = device_;
412
413 vk::AccelerationStructureDeviceAddressInfoKHR addrInfo{};
414 addrInfo.accelerationStructure = mesh.blas.handle;
415 mesh.blas.deviceAddress = (*device_)->getAccelerationStructureAddressKHR(addrInfo);
416
417 DeviceAddressBuffer scratch;
418 if (auto r =
419 scratch.allocate(*device_, sizes.buildScratchSize,
420 vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eShaderDeviceAddress);
421 !r.ok())
422 return r;
423
424 buildInfo.dstAccelerationStructure = mesh.blas.handle;
425 buildInfo.scratchData.deviceAddress = scratch.address;
426
427 vk::AccelerationStructureBuildRangeInfoKHR range{};
428 range.primitiveCount = primitiveCount;
429 const vk::AccelerationStructureBuildRangeInfoKHR* ranges = &range;
430
431 auto cmd = (*device_)->allocateCommandBuffers({uploadPool_, vk::CommandBufferLevel::ePrimary, 1}).front();
432 cmd.begin({vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
433 cmd.buildAccelerationStructuresKHR(buildInfo, ranges);
434 cmd.end();
435 vk::SubmitInfo submit{};
436 submit.commandBufferCount = 1;
437 submit.pCommandBuffers = &cmd;
438 graphicsQueue_.submit(submit, vk::Fence{});
439 graphicsQueue_.waitIdle();
440 (*device_)->freeCommandBuffers(uploadPool_, cmd);
441 return Result<void>::success();
442}
443
444Result<void> VulkanRayTracing::buildTlas() {
445 if (meshes_.empty()) {
446 if (tlas_.handle) graphicsQueue_.waitIdle();
447 tlas_.release();
448 return Result<void>::success();
449 }
450
451 std::vector<vk::AccelerationStructureInstanceKHR> instances;
452 instances.reserve(meshes_.size());
453 for (const auto& mesh : meshes_) {
454 vk::AccelerationStructureInstanceKHR inst{};
455 inst.transform = toTransformMatrix(mesh->transform);
456 inst.instanceCustomIndex = 0;
457 inst.mask = 0xFF;
458 inst.instanceShaderBindingTableRecordOffset = 0;
459 inst.flags = uint32_t(vk::GeometryInstanceFlagBitsKHR::eTriangleFacingCullDisable);
460 inst.accelerationStructureReference = mesh->blas.deviceAddress;
461 instances.push_back(inst);
462 }
463
464 AccelerationStructure candidate;
465 if (auto r = buildTlas(instances, candidate); !r.ok()) return r;
466 // The build completes on the graphics queue before replacing the live TLAS.
467 tlas_ = std::move(candidate);
468 return Result<void>::success();
469}
470
471Result<void> VulkanRayTracing::buildTlas(std::span<const vk::AccelerationStructureInstanceKHR> instances,
472 AccelerationStructure& target) {
473 TlasWorkspace workspace;
474 return buildTlas(instances, target, workspace);
475}
476
477Result<void> VulkanRayTracing::buildTlas(std::span<const vk::AccelerationStructureInstanceKHR> instances,
478 AccelerationStructure& target, TlasWorkspace& workspace) {
479 EV_PROFILE_MODULE("graphics", "Path.BuildTlas");
480 if (instances.empty() || instances.size() > UINT32_MAX)
482 DiagnosticCode::InvalidArgument, "TLAS build requires a valid instance count", "graphics.raytracing"));
483
484 auto& instanceBuffer = workspace.instances;
485 const vk::DeviceSize bytes = vk::DeviceSize(instances.size()) * sizeof(instances[0]);
486 if (auto r = instanceBuffer.initializeHostVisible(
487 *device_, instances.data(), bytes, vk::BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR);
488 !r.ok())
489 return r;
490
491 vk::AccelerationStructureGeometryInstancesDataKHR instancesData{};
492 instancesData.arrayOfPointers = VK_FALSE;
493 instancesData.data.deviceAddress = instanceBuffer.address;
494
495 vk::AccelerationStructureGeometryKHR geometry{};
496 geometry.geometryType = vk::GeometryTypeKHR::eInstances;
497 geometry.geometry.instances = instancesData;
498
499 vk::AccelerationStructureBuildGeometryInfoKHR buildInfo{};
500 buildInfo.type = vk::AccelerationStructureTypeKHR::eTopLevel;
501 buildInfo.flags = vk::BuildAccelerationStructureFlagBitsKHR::ePreferFastTrace;
502 buildInfo.mode = vk::BuildAccelerationStructureModeKHR::eBuild;
503 buildInfo.geometryCount = 1;
504 buildInfo.pGeometries = &geometry;
505
506 const uint32_t primitiveCount = uint32_t(instances.size());
507 const auto sizes = (*device_)->getAccelerationStructureBuildSizesKHR(vk::AccelerationStructureBuildTypeKHR::eDevice,
508 buildInfo, primitiveCount);
509
510 if (target.handle && target.storage.size < sizes.accelerationStructureSize) target.release();
511 if (!target.handle) {
512 if (auto r = target.storage.allocate(*device_, sizes.accelerationStructureSize,
513 vk::BufferUsageFlagBits::eAccelerationStructureStorageKHR |
514 vk::BufferUsageFlagBits::eShaderDeviceAddress);
515 !r.ok())
516 return r;
517
518 vk::AccelerationStructureCreateInfoKHR createInfo{};
519 createInfo.buffer = target.storage.buffer;
520 createInfo.size = sizes.accelerationStructureSize;
521 createInfo.type = vk::AccelerationStructureTypeKHR::eTopLevel;
522 target.handle = (*device_)->createAccelerationStructureKHR(createInfo, device_->allocation_callbacks);
523 target.device = device_;
524
525 vk::AccelerationStructureDeviceAddressInfoKHR addrInfo{};
526 addrInfo.accelerationStructure = target.handle;
527 target.deviceAddress = (*device_)->getAccelerationStructureAddressKHR(addrInfo);
528 }
529
530 auto& scratch = workspace.scratch;
531 if (auto r =
532 scratch.allocate(*device_, sizes.buildScratchSize,
533 vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eShaderDeviceAddress);
534 !r.ok())
535 return r;
536
537 buildInfo.dstAccelerationStructure = target.handle;
538 buildInfo.scratchData.deviceAddress = scratch.address;
539
540 vk::AccelerationStructureBuildRangeInfoKHR range{};
541 range.primitiveCount = primitiveCount;
542 const vk::AccelerationStructureBuildRangeInfoKHR* ranges = &range;
543
544 auto cmd = (*device_)->allocateCommandBuffers({uploadPool_, vk::CommandBufferLevel::ePrimary, 1}).front();
545 cmd.begin({vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
546 cmd.buildAccelerationStructuresKHR(buildInfo, ranges);
547 cmd.end();
548 vk::SubmitInfo submit{};
549 submit.commandBufferCount = 1;
550 submit.pCommandBuffers = &cmd;
551 graphicsQueue_.submit(submit, vk::Fence{});
552 graphicsQueue_.waitIdle();
553 (*device_)->freeCommandBuffers(uploadPool_, cmd);
554 return Result<void>::success();
555}
556
558 if (auto attached = ensureAttached(); !attached.ok()) return attached;
559 return buildTlas();
560}
561
562Result<void> VulkanRayTracing::ensurePipeline() {
563 if (pipeline_) return Result<void>::success();
565 DiagnosticCode::Unsupported, std::string("ensurePipeline") + ": hardware ray tracing unavailable", "graphics.raytracing"));
566
567 auto makeModule = [&](const uint32_t* words, size_t count) -> vk::ShaderModule {
568 vk::ShaderModuleCreateInfo ci{};
569 ci.codeSize = count * sizeof(uint32_t);
570 ci.pCode = words;
571 return (*device_)->createShaderModule(ci, device_->allocation_callbacks);
572 };
573 raygenModule_ = makeModule(rt_reflection_rgen_spv, rt_reflection_rgen_spv_count);
574 missModule_ = makeModule(rt_reflection_rmiss_spv, rt_reflection_rmiss_spv_count);
575 closestHitModule_ = makeModule(rt_reflection_rchit_spv, rt_reflection_rchit_spv_count);
576
577 vk::DescriptorSetLayoutBinding bindings[5]{};
578 bindings[0].binding = 0;
579 bindings[0].descriptorType = vk::DescriptorType::eAccelerationStructureKHR;
580 bindings[0].descriptorCount = 1;
581 bindings[0].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
582 bindings[1].binding = 1;
583 bindings[1].descriptorType = vk::DescriptorType::eStorageImage;
584 bindings[1].descriptorCount = 1;
585 bindings[1].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
586 bindings[2].binding = 2;
587 bindings[2].descriptorType = vk::DescriptorType::eCombinedImageSampler;
588 bindings[2].descriptorCount = 1;
589 bindings[2].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
590 bindings[3].binding = 3;
591 bindings[3].descriptorType = vk::DescriptorType::eCombinedImageSampler;
592 bindings[3].descriptorCount = 1;
593 bindings[3].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
594 bindings[4].binding = 4;
595 bindings[4].descriptorType = vk::DescriptorType::eCombinedImageSampler;
596 bindings[4].descriptorCount = 1;
597 bindings[4].stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
598
599 vk::DescriptorSetLayoutCreateInfo layoutCi{};
600 layoutCi.bindingCount = 5;
601 layoutCi.pBindings = bindings;
602 setLayout_ = (*device_)->createDescriptorSetLayout(layoutCi, device_->allocation_callbacks);
603
604 vk::PushConstantRange push{};
605 push.stageFlags = vk::ShaderStageFlagBits::eRaygenKHR;
606 push.offset = 0;
607 push.size = sizeof(PushConstants);
608
609 vk::PipelineLayoutCreateInfo plCi{};
610 plCi.setLayoutCount = 1;
611 plCi.pSetLayouts = &setLayout_;
612 plCi.pushConstantRangeCount = 1;
613 plCi.pPushConstantRanges = &push;
614 pipelineLayout_ = (*device_)->createPipelineLayout(plCi, device_->allocation_callbacks);
615
616 std::array<vk::PipelineShaderStageCreateInfo, 3> stages{};
617 stages[0].stage = vk::ShaderStageFlagBits::eRaygenKHR;
618 stages[0].module = raygenModule_;
619 stages[0].pName = "main";
620 stages[1].stage = vk::ShaderStageFlagBits::eMissKHR;
621 stages[1].module = missModule_;
622 stages[1].pName = "main";
623 stages[2].stage = vk::ShaderStageFlagBits::eClosestHitKHR;
624 stages[2].module = closestHitModule_;
625 stages[2].pName = "main";
626
627 std::array<vk::RayTracingShaderGroupCreateInfoKHR, 3> groups{};
628 groups[0].type = vk::RayTracingShaderGroupTypeKHR::eGeneral;
629 groups[0].generalShader = 0;
630 groups[0].closestHitShader = VK_SHADER_UNUSED_KHR;
631 groups[0].anyHitShader = VK_SHADER_UNUSED_KHR;
632 groups[0].intersectionShader = VK_SHADER_UNUSED_KHR;
633 groups[1].type = vk::RayTracingShaderGroupTypeKHR::eGeneral;
634 groups[1].generalShader = 1;
635 groups[1].closestHitShader = VK_SHADER_UNUSED_KHR;
636 groups[1].anyHitShader = VK_SHADER_UNUSED_KHR;
637 groups[1].intersectionShader = VK_SHADER_UNUSED_KHR;
638 groups[2].type = vk::RayTracingShaderGroupTypeKHR::eTrianglesHitGroup;
639 groups[2].generalShader = VK_SHADER_UNUSED_KHR;
640 groups[2].closestHitShader = 2;
641 groups[2].anyHitShader = VK_SHADER_UNUSED_KHR;
642 groups[2].intersectionShader = VK_SHADER_UNUSED_KHR;
643
644 vk::RayTracingPipelineCreateInfoKHR pipeCi{};
645 pipeCi.stageCount = uint32_t(stages.size());
646 pipeCi.pStages = stages.data();
647 pipeCi.groupCount = uint32_t(groups.size());
648 pipeCi.pGroups = groups.data();
649 pipeCi.maxPipelineRayRecursionDepth =
650 std::max(1u, std::min(1u, caps_.maxRecursionDepth ? caps_.maxRecursionDepth : 1u));
651 pipeCi.layout = pipelineLayout_;
652
653 auto created = (*device_)->createRayTracingPipelinesKHR(vk::DeferredOperationKHR{}, vk::PipelineCache{}, pipeCi,
654 device_->allocation_callbacks);
655 if (created.result != vk::Result::eSuccess || created.value.empty())
657 Diagnostic::error(DiagnosticCode::Failed, std::string("ensurePipeline") + ": " + "createRayTracingPipelinesKHR failed", "graphics.raytracing"));
658 pipeline_ = created.value.front();
659
660 return createShaderBindingTable();
661}
662
663Result<void> VulkanRayTracing::createShaderBindingTable() {
664 const uint32_t handleSize = caps_.shaderGroupHandleSize;
665 const uint32_t handleAlignment = caps_.shaderGroupHandleAlignment ? caps_.shaderGroupHandleAlignment : handleSize;
666 const uint32_t baseAlignment = caps_.shaderGroupBaseAlignment ? caps_.shaderGroupBaseAlignment : handleAlignment;
667 const uint32_t handleSizeAligned = alignedSize(handleSize, handleAlignment);
668 const uint32_t groupCount = 3;
669 const uint32_t sbtSize = groupCount * handleSizeAligned;
670
671 std::vector<uint8_t> handles(sbtSize);
672 auto result = (*device_)->getRayTracingShaderGroupHandlesKHR(pipeline_, 0, groupCount, sbtSize, handles.data());
673 if (result != vk::Result::eSuccess)
675 Diagnostic::error(DiagnosticCode::Failed, std::string("createShaderBindingTable") + ": " + "getRayTracingShaderGroupHandlesKHR failed", "graphics.raytracing"));
676
677 // Pack groups with base alignment between regions: raygen | miss | hit
678 const uint32_t raygenSize = alignedSize(handleSizeAligned, baseAlignment);
679 const uint32_t missSize = alignedSize(handleSizeAligned, baseAlignment);
680 const uint32_t hitSize = alignedSize(handleSizeAligned, baseAlignment);
681 const uint32_t total = raygenSize + missSize + hitSize;
682
683 std::vector<uint8_t> sbt(total, 0);
684 std::memcpy(sbt.data(), handles.data(), handleSize);
685 std::memcpy(sbt.data() + raygenSize, handles.data() + handleSizeAligned, handleSize);
686 std::memcpy(sbt.data() + raygenSize + missSize, handles.data() + 2 * handleSizeAligned, handleSize);
687
688 if (auto r = sbtBuffer_.allocate(*device_, total,
689 vk::BufferUsageFlagBits::eShaderBindingTableKHR |
690 vk::BufferUsageFlagBits::eShaderDeviceAddress |
691 vk::BufferUsageFlagBits::eTransferDst);
692 !r.ok())
693 return r;
694 if (auto r = sbtBuffer_.upload(uploadPool_, graphicsQueue_, sbt.data(), total); !r.ok()) return r;
695
696 raygenRegion_.deviceAddress = sbtBuffer_.address;
697 raygenRegion_.stride = raygenSize;
698 raygenRegion_.size = raygenSize;
699
700 missRegion_.deviceAddress = sbtBuffer_.address + raygenSize;
701 missRegion_.stride = handleSizeAligned;
702 missRegion_.size = missSize;
703
704 hitRegion_.deviceAddress = sbtBuffer_.address + raygenSize + missSize;
705 hitRegion_.stride = handleSizeAligned;
706 hitRegion_.size = hitSize;
707
708 callableRegion_ = vk::StridedDeviceAddressRegionKHR{};
709 return Result<void>::success();
710}
711
712Result<void> VulkanRayTracing::ensureDescriptorSets(vk::ImageView outputView, vk::ImageView sceneView,
713 vk::ImageView depthView, vk::ImageView normalView) {
714 if (!descriptorPool_) {
715 std::array<vk::DescriptorPoolSize, 3> sizes{};
716 sizes[0] = {vk::DescriptorType::eAccelerationStructureKHR, 4};
717 sizes[1] = {vk::DescriptorType::eStorageImage, 4};
718 sizes[2] = {vk::DescriptorType::eCombinedImageSampler, 12};
719 vk::DescriptorPoolCreateInfo poolCi{};
720 poolCi.maxSets = 4;
721 poolCi.poolSizeCount = uint32_t(sizes.size());
722 poolCi.pPoolSizes = sizes.data();
723 descriptorPool_ = (*device_)->createDescriptorPool(poolCi, device_->allocation_callbacks);
724 }
725 if (!descriptorSet_) {
726 vk::DescriptorSetAllocateInfo alloc{};
727 alloc.descriptorPool = descriptorPool_;
728 alloc.descriptorSetCount = 1;
729 alloc.pSetLayouts = &setLayout_;
730 descriptorSet_ = (*device_)->allocateDescriptorSets(alloc).front();
731 }
732
733 vk::WriteDescriptorSetAccelerationStructureKHR asWrite{};
734 asWrite.accelerationStructureCount = 1;
735 asWrite.pAccelerationStructures = &tlas_.handle;
736
737 vk::WriteDescriptorSet writes[5]{};
738 writes[0].pNext = &asWrite;
739 writes[0].dstSet = descriptorSet_;
740 writes[0].dstBinding = 0;
741 writes[0].descriptorCount = 1;
742 writes[0].descriptorType = vk::DescriptorType::eAccelerationStructureKHR;
743
744 // Storage image for output — sampler unused
745 vk::DescriptorImageInfo outInfo{};
746 outInfo.imageView = outputView;
747 outInfo.imageLayout = vk::ImageLayout::eGeneral;
748 writes[1].dstSet = descriptorSet_;
749 writes[1].dstBinding = 1;
750 writes[1].descriptorCount = 1;
751 writes[1].descriptorType = vk::DescriptorType::eStorageImage;
752 writes[1].pImageInfo = &outInfo;
753
754 if (auto r = ensureSampler(); !r.ok()) return r;
755
756 vk::DescriptorImageInfo sceneInfo{};
757 sceneInfo.sampler = sampler_;
758 sceneInfo.imageView = sceneView;
759 sceneInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
760 writes[2].dstSet = descriptorSet_;
761 writes[2].dstBinding = 2;
762 writes[2].descriptorCount = 1;
763 writes[2].descriptorType = vk::DescriptorType::eCombinedImageSampler;
764 writes[2].pImageInfo = &sceneInfo;
765
766 vk::DescriptorImageInfo depthInfo{};
767 depthInfo.sampler = sampler_;
768 depthInfo.imageView = depthView;
769 depthInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
770 writes[3].dstSet = descriptorSet_;
771 writes[3].dstBinding = 3;
772 writes[3].descriptorCount = 1;
773 writes[3].descriptorType = vk::DescriptorType::eCombinedImageSampler;
774 writes[3].pImageInfo = &depthInfo;
775
776 vk::DescriptorImageInfo normalInfo{};
777 normalInfo.sampler = sampler_;
778 normalInfo.imageView = normalView;
779 normalInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
780 writes[4].dstSet = descriptorSet_;
781 writes[4].dstBinding = 4;
782 writes[4].descriptorCount = 1;
783 writes[4].descriptorType = vk::DescriptorType::eCombinedImageSampler;
784 writes[4].pImageInfo = &normalInfo;
785
786 (*device_)->updateDescriptorSets(writes, {});
787 return Result<void>::success();
788}
789
790Result<void> VulkanRayTracing::ensureSampler() {
791 if (sampler_) return Result<void>::success();
792 if (!device_) return Result<void>::failure(Diagnostic::error(
793 DiagnosticCode::Unsupported, std::string("ensureSampler") + ": hardware ray tracing unavailable", "graphics.raytracing"));
794 vk::SamplerCreateInfo sci{};
795 sci.magFilter = vk::Filter::eNearest;
796 sci.minFilter = vk::Filter::eNearest;
797 sci.mipmapMode = vk::SamplerMipmapMode::eNearest;
798 sci.addressModeU = vk::SamplerAddressMode::eClampToEdge;
799 sci.addressModeV = vk::SamplerAddressMode::eClampToEdge;
800 sci.addressModeW = vk::SamplerAddressMode::eClampToEdge;
801 sampler_ = (*device_)->createSampler(sci, device_->allocation_callbacks);
802 return Result<void>::success();
803}
804
805Result<void> VulkanRayTracing::ensureOutputImage(uint32_t width, uint32_t height) {
806 if (!device_) return Result<void>::failure(Diagnostic::error(
807 DiagnosticCode::Unsupported, std::string("ensureOutputImage") + ": hardware ray tracing unavailable", "graphics.raytracing"));
808 if (width == 0 || height == 0) return Result<void>::failure(
809 Diagnostic::error(DiagnosticCode::InvalidArgument, std::string("ensureOutputImage") + ": " + "zero extent", "graphics.raytracing"));
810 if (outputImage_.image() && outputWidth_ == width && outputHeight_ == height) return Result<void>::success();
811 outputImage_ = StorageColorImage{};
812 outputWidth_ = width;
813 outputHeight_ = height;
814 outputImage_.allocate(*device_, width, height);
815 return Result<void>::success();
816}
817
819 Texture* worldNormal, Canvas* dest, const glm::mat4& invViewProj,
820 const glm::mat4& viewProj, const glm::vec3& eyeWorld) {
821 if (auto attached = ensureAttached(); !attached.ok()) return attached;
822 if (!gfx || !sceneColor || !hwDepth || !worldNormal || !dest)
824 Diagnostic::error(DiagnosticCode::InvalidArgument, std::string("applyReflections") + ": " + "null argument", "graphics.raytracing"));
825 if (meshes_.empty() || !tlas_.handle) {
826 // Empty scene: no usable RT output — callers must fall through to SSR.
828 }
829
830 auto* vkGfx = dynamic_cast<eve::graphics::vulkan::Graphics*>(gfx);
831 if (!vkGfx) return Result<void>::failure(
832 Diagnostic::error(DiagnosticCode::Failed, std::string("applyReflections") + ": " + "requires Vulkan Graphics backend", "graphics.raytracing"));
833
834 if (auto r = ensurePipeline(); !r.ok()) return r;
835
836 auto textureView = [](Texture* tex) -> vk::ImageView {
837 if (!tex || !tex->gpuHandle) return {};
838 auto* img = static_cast<eve::graphics::vulkan::GpuTexture*>(tex->gpuHandle);
839 return img->imageView();
840 };
841
842 Texture* destTex = dest->getTexture();
843 if (!destTex) return Result<void>::failure(
844 Diagnostic::error(DiagnosticCode::Failed, std::string("applyReflections") + ": " + "destination canvas has no texture", "graphics.raytracing"));
845 auto* destCanvas = dynamic_cast<eve::graphics::vulkan::OffscreenCanvas*>(dest);
846 if (!destCanvas) return Result<void>::failure(
847 Diagnostic::error(DiagnosticCode::Failed, std::string("applyReflections") + ": " + "destination must be an OffscreenCanvas", "graphics.raytracing"));
848
849 const uint32_t width = uint32_t(dest->getWidth());
850 const uint32_t height = uint32_t(dest->getHeight());
851 if (auto r = ensureOutputImage(width, height); !r.ok()) return r;
852
853 const vk::ImageView outView = outputImage_.imageView();
854 const vk::ImageView sceneView = textureView(sceneColor);
855 const vk::ImageView depthView = textureView(hwDepth);
856 const vk::ImageView normalView = textureView(worldNormal);
857 if (!outView || !sceneView || !depthView || !normalView)
859 Diagnostic::error(DiagnosticCode::Failed, std::string("applyReflections") + ": " + "missing texture image view", "graphics.raytracing"));
860
861 // Descriptor contents are shared across frames; retire prior uses before update.
862 vkGfx->waitForSharedGpuResources();
863 if (auto r = ensureDescriptorSets(outView, sceneView, depthView, normalView); !r.ok()) return r;
864
865 PushConstants push{};
866 push.invViewProj = invViewProj;
867 push.viewProj = viewProj;
868 push.eye = glm::vec4(eyeWorld, 0.f);
869
870 auto record = [&](vk::CommandBuffer cmd) {
871 outputImage_.setLayout(cmd, vk::ImageLayout::eGeneral);
872
873 vk::MemoryBarrier memBarrier{};
874 memBarrier.srcAccessMask =
875 vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentWrite;
876 memBarrier.dstAccessMask = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite;
877 cmd.pipelineBarrier(
878 vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eLateFragmentTests,
879 vk::PipelineStageFlagBits::eRayTracingShaderKHR, {}, memBarrier, {}, {});
880
881 cmd.bindPipeline(vk::PipelineBindPoint::eRayTracingKHR, pipeline_);
882 cmd.bindDescriptorSets(vk::PipelineBindPoint::eRayTracingKHR, pipelineLayout_, 0, descriptorSet_, {});
883 cmd.pushConstants(pipelineLayout_, vk::ShaderStageFlagBits::eRaygenKHR, 0, sizeof(PushConstants), &push);
884 cmd.traceRaysKHR(raygenRegion_, missRegion_, hitRegion_, callableRegion_, width, height, 1);
885
886 // Copy RT storage result into the reflection canvas for composite sampling.
887 // GenericImage's GENERAL transition covers transfer writes, whereas this
888 // image was written by ray generation. Publish those writes before copy.
889 vk::MemoryBarrier traceToCopy{};
890 traceToCopy.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
891 traceToCopy.dstAccessMask = vk::AccessFlagBits::eTransferRead;
892 cmd.pipelineBarrier(vk::PipelineStageFlagBits::eRayTracingShaderKHR, vk::PipelineStageFlagBits::eTransfer, {},
893 traceToCopy, {}, {});
894 outputImage_.setLayout(cmd, vk::ImageLayout::eTransferSrcOptimal);
895 destCanvas->colorImage().setLayout(cmd, vk::ImageLayout::eTransferDstOptimal);
896 vk::ImageCopy region{};
897 region.srcSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
898 region.dstSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
899 region.extent = vk::Extent3D{width, height, 1};
900 cmd.copyImage(outputImage_.image(), vk::ImageLayout::eTransferSrcOptimal, destCanvas->colorImage().image(),
901 vk::ImageLayout::eTransferDstOptimal, region);
902 destCanvas->colorImage().setLayout(cmd, vk::ImageLayout::eShaderReadOnlyOptimal);
903 };
904
905 if (vkGfx->canRecordPostSceneGpuWork()) {
906 record(vkGfx->postSceneCommandBuffer());
907 } else {
908 vkGfx->waitForSharedGpuResources();
909 vkb::executeImmediately(device_->instance, uploadPool_, graphicsQueue_, record);
910 }
911 return Result<void>::success();
912}
913
914namespace {
915
916struct RegisterCapability {
917 RegisterCapability() { eve::cap::provide<IRayTracing>(&vulkanRayTracing()); }
918} g_register;
919
920} // namespace
921
922} // namespace eve::graphics::raytracing
double m[16]
LogicalId target
std::string usage
std::vector< std::uint32_t > verts
Definition Builder.cpp:27
Stable, structured diagnostics shared by engine modules.
ScriptComponentRecord record
Definition ECS.cpp:228
ScriptFieldRegion region
std::uint32_t vertexCount
std::uint32_t indexCount
vkb::Device & device
vk::UniqueDeviceMemory memory
float u
Definition Grass.cpp:233
double r
std::vector< std::uint32_t > indices
std::vector< float > positions
std::uint32_t height
std::uint32_t width
Range range
std::map< std::string, PropertyRule > properties
Poco::JSON::Object::Ptr result
std::uint64_t bytes
std::vector< TriangleRef > triangles
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
uint32_t groups
Definition OnnxGpgpu.cpp:39
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::vector< ParticleBakeMaterial > bindings
PrimitiveHandle handle
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
Object::Ptr value
glm::mat4 viewProj
int created
std::string geometry
ScriptStructure out
double current
int count
Structured operation status used by the common Result foundation.
float size
Definition TreeMesh.cpp:158
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
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 Texture * getTexture()=0
Sampleable color buffer; screen Canvas returns nullptr.
virtual int getHeight() const =0
Returns the height.
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
Vulkan implementation of IRayTracing (KHR ray-tracing pipeline).
Result< void > rebuildScene() override
Rebuild scene.
~VulkanRayTracing() override
Releases VulkanRayTracing resources.
Result< uint32_t > addMesh(Mesh *mesh, const glm::mat4 &transform) override
Adds mesh.
RayTracingCaps caps() const override
Caps.
void attachDevice(vkb::Device *device, const RayTracingCaps &caps, vk::CommandPool uploadPool, vk::Queue graphicsQueue)
Bind to the live Vulkan Graphics device (call after init). @ownership device is borrowed; Graphics re...
Result< void > ensureAttached()
Lazily bind to the process Graphics singleton when RT is available.
bool isAvailable() const override
True when available.
void detachDevice()
Drop GPU resources when Graphics tears down.
Result< uint32_t > addTriangleMesh(const float *positionsXYZ, int vertexCount, const uint32_t *indices, int indexCount, const glm::mat4 &transform) override
Adds triangle mesh.
Result< void > applyReflections(Graphics *gfx, Texture *sceneColor, Texture *hwDepth, Texture *worldNormal, Canvas *dest, const glm::mat4 &invViewProj, const glm::mat4 &viewProj, const glm::vec3 &eyeWorld) override
Applies reflections.
EVENGINE_API_BACKENDS public API.
Definition Graphics.h:360
bool supportsRayTracing() const override
Supports ray tracing.
Definition Graphics.h:440
void retirePathSceneOutput()
Invalidate cached bindings before retiring completed path output; render thread only.
RayTracingCaps rayTracingCaps() const override
Ray tracing caps.
Definition Graphics.h:438
OffscreenCanvas public API.
Definition Canvas.h:15
VulkanRayTracing & vulkanRayTracing()
Process-wide Vulkan RT backend; also registered as IRayTracing.
std::string buildInfo()
One-line build metadata for diagnostics (printed by eve --version).
Definition Version.cpp:20
Hardware ray-tracing capabilities probed once at Vulkan device creation.
bool rayTracingAvailable() const
True when BLAS/TLAS + ray-tracing pipelines can be created.
Bottom- or top-level acceleration structure handle.
void steal(AccelerationStructure &o) noexcept
Steal.
Device-local buffer with shader device address (for AS builds / SBT). @ownership Owns the Vulkan buff...
Result< void > initializeHostVisible(vkb::Device &dev, const void *data, vk::DeviceSize bytes, vk::BufferUsageFlags usage)
Allocate coherent host-visible storage and initialize it without a transfer submission....
Result< void > allocate(vkb::Device &dev, vk::DeviceSize bytes, vk::BufferUsageFlags usage)
Ensure buffer capacity with usage including SHADER_DEVICE_ADDRESS. @ownership Reuses compatible stora...
Result< void > upload(vk::CommandPool pool, vk::Queue queue, const void *data, vk::DeviceSize bytes)
Upload host bytes via a staging buffer (stalls the queue).
void steal(DeviceAddressBuffer &o) noexcept
Steal.
GpuMesh public API.
Definition Graphics.h:298
GpuTexture public API.
Definition Graphics.h:264
vk::ImageView imageView() const
Image view.
Definition Graphics.h:289
MeshVertex public API.
Definition Graphics.h:148
glm::mat4 invViewProj