载入中...
搜索中...
未找到
GraphicsDeferredLighting.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cmath>
3#include <cstring>
4#include <limits>
5#include <optional>
6#include <vector>
7#include "common/Exception.h"
10#include "graphics/Shadow.h"
11#include "graphics/shaders/deferred_lighting_frag_spv.inc"
12#include "graphics/shaders/deferred_lighting_vert_spv.inc"
15
16// GraphicsDeferredLighting.cpp
17// Hybrid clustered deferred lighting (Phase C): fullscreen pass that samples
18// the Phase B GBuffer and evaluates core PBR with ClusteredLight + CSM.
19
20
21namespace eve::graphics::vulkan {
22namespace {
23
24std::vector<uint32_t> embeddedSpirv(const uint32_t* words, size_t count) {
25 return std::vector<uint32_t>(words, words + count);
26}
27
28} // namespace
29
30void Graphics::destroyDeferredLightingResources() {
31 destroyPipeline(device, deferredLightingPipeline);
32 destroyPipelineLayout(device, deferredLightingPipelineLayout);
33 deferredLightingSetLayout = vk::DescriptorSetLayout{};
34 deferredLightingSetLayoutUnique.reset();
35 deferredLightingFrames.clear();
36 if (deferredLightingSampler) {
37 device->destroySampler(deferredLightingSampler);
38 deferredLightingSampler = nullptr;
39 }
40}
41
42void Graphics::createDeferredLightingPipeline() {
43 if (deferredLightingPipeline || !sceneColorRenderPass) return;
44
45 vkb::DescriptorSetLayoutBuilder layoutBuilder;
46 deferredLightingSetLayoutUnique =
47 layoutBuilder.buffer(0, vk::DescriptorType::eUniformBuffer, vk::ShaderStageFlagBits::eFragment, 1)
48 .image(1, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
49 .image(2, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
50 .image(3, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
51 .image(4, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
52 .image(5, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
53 .image(6, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
54 .buffer(7, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eFragment, 1)
55 .buffer(8, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eFragment, 1)
56 .buffer(9, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eFragment, 1)
57 .buffer(10, vk::DescriptorType::eUniformBuffer, vk::ShaderStageFlagBits::eFragment, 1)
58 .image(11, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
59 .createUnique(device.instance);
60 deferredLightingSetLayout = *deferredLightingSetLayoutUnique;
61 deferredLightingPipelineLayout = createPipelineLayout(device, deferredLightingSetLayout);
62
63 auto vert = embeddedSpirv(deferred_lighting_vert_spv, deferred_lighting_vert_spv_count);
64 auto frag = embeddedSpirv(deferred_lighting_frag_spv, deferred_lighting_frag_spv_count);
65 vk::ShaderModule vertModule = vkb::PipelineBuilder::createShaderModule(device.instance, vert);
66 vk::ShaderModule fragModule = vkb::PipelineBuilder::createShaderModule(device.instance, frag);
67 deferredLightingPipeline = device.createPipeline()
68 .useClassicPipeline(vertModule, fragModule)
69 .setPipelineLayout(deferredLightingPipelineLayout)
70 .setDynamicStatesViewportScissor()
71 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
72 vk::CullModeFlagBits::eNone, vk::FrontFace::eClockwise)
73 .setMultisampler(false, sceneColorSamples)
74 // Always pass; fragment writes gl_FragDepth from GBuffer hwDepth so
75 // transparent Forward+ can depth-test against deferred opaques.
76 .setDepthStencil(true, true, vk::CompareOp::eAlways)
77 .setColorAttachmentCount(1)
78 .build(sceneColorRenderPass);
79 device->destroyShaderModule(vertModule);
80 device->destroyShaderModule(fragModule);
81
82 if (!deferredLightingSampler) {
83 vkb::SamplerBuilder sb;
84 deferredLightingSampler = sb.nearestClamp().build(device);
85 }
86}
87
89 if (!sceneColorPassOpen || !sceneColorRenderPass) return;
90 auto* gslot = currentGBufferSlot();
91 if (!gslot || !gslot->normalGpu.sampler) return;
92 createDeferredLightingPipeline();
93 if (!deferredLightingPipeline || !descriptorPool) return;
94 auto& frame = currentSlot(deferredLightingFrames, frameSlotCount(), currentFrameSlot());
95 frame.ubo.allocate(frameToken(), device, vk::BufferUsageFlagBits::eUniformBuffer, sizeof(DeferredLightingUBO),
96 kHostVisibleCoherent);
97 if (!frame.set) {
98 vk::DescriptorSetAllocateInfo alloc{};
99 alloc.descriptorPool = descriptorPool;
100 alloc.descriptorSetCount = 1;
101 alloc.pSetLayouts = &deferredLightingSetLayout;
102 frame.set = device->allocateDescriptorSets(alloc).front();
103 }
104 const auto deferredLightingSet = frame.set;
105
106 createShadowResources();
107 vk::ImageView shadowView = currentShadowArrayView();
108 if (!shadowView || !shadowSampler) return;
109
110 // Ensure clustered storage exists even with an empty/inactive upload so
111 // the SSBO bindings stay valid. Hybrid always samples the cluster tables.
112 if (!mesh3dClustered.active) {
113 std::vector<ClusteredLightGpu> dirs;
114 if (glm::length(glm::vec3(mesh3dFrameUbo.lightDir)) > 1e-4f) {
116 d.posRadius = glm::vec4(glm::normalize(glm::vec3(mesh3dFrameUbo.lightDir)), 0.f);
117 d.color = glm::vec4(glm::vec3(mesh3dFrameUbo.lightColor), 1.f);
118 dirs.push_back(d);
119 }
121 {}, dirs, mesh3dFrameUbo.view, mesh3dFrameUbo.clipInfo.x, mesh3dFrameUbo.clipInfo.y,
122 std::max(1, sceneColorWidth), std::max(1, sceneColorHeight), /*fovYRad*/ 1.f, mesh3dFrameUbo.ambient);
123 empty.active = true;
125 } else {
126 uploadClusteredLighting(mesh3dClustered);
127 }
128 auto& storage = currentClusteredStorage();
129 if (!storage.lightsBuf.buffer || !storage.tableBuf.buffer || !storage.indicesBuf.buffer) return;
130
132 ubo.invViewProj = glm::inverse(mesh3dFrameUbo.mvp);
133 ubo.view = mesh3dFrameUbo.view;
134 ubo.lightDir = mesh3dFrameUbo.lightDir;
135 // Mesh3DUBO packs lightCount in lightDir.w; deferred_lighting.frag uses w as
136 // the primary-enable flag. Re-encode enable from the direction vector.
137 ubo.lightDir.w = glm::length(glm::vec3(mesh3dFrameUbo.lightDir)) > 1e-4f ? 1.f : 0.f;
138 ubo.lightColor = mesh3dFrameUbo.lightColor;
139 ubo.cameraPos = glm::vec4(glm::vec3(mesh3dFrameUbo.cameraPos), 0.f);
140 ubo.ambient = mesh3dFrameUbo.ambient;
141 if (mesh3dClustered.active) {
142 ubo.gridInfo = mesh3dClustered.gridInfo;
143 ubo.clipInfo = mesh3dClustered.clipInfo;
144 ubo.ambient = mesh3dClustered.ambient;
145 ubo.lightDir = mesh3dClustered.primaryDir;
146 ubo.lightColor = glm::vec4(glm::vec3(mesh3dClustered.primaryColor), 0.f);
147 ubo.view = mesh3dClustered.view;
148 }
149 ubo.clipInfo.z = float(std::max(1, sceneColorWidth));
150 ubo.clipInfo.w = float(std::max(1, sceneColorHeight));
151 frame.ubo.updateLocal(frameToken(), &ubo, sizeof(ubo));
152
153 // Shadow UBO: stage the latest CSM upload into the clustered shadow ring.
154 ensureMesh3dStrides();
155 auto& cfslots = currentMesh3dClusteredFrameSlots();
156 ensureMesh3dClusteredRing(cfslots);
157 if (cfslots.drawIndex >= cfslots.capacity)
158 throw Exception("drawDeferredLighting: clustered shadow UBO ring exhausted (%zu draws)", cfslots.capacity);
159 // Reserve a slot just as Forward+ draws do: their per-object receive-shadow
160 // upload must not overwrite this fullscreen pass's shadow state before submit.
161 const size_t shadowSlot = cfslots.drawIndex++;
162 const uint32_t shadowOffset = uint32_t(shadowSlot) * shadowUboStride;
163 updateRingLocal(cfslots.shadowRing, shadowOffset, &mesh3dShadows.ubo, sizeof(ShadowUBO));
164
165 auto writeImage = [&](uint32_t binding, vk::ImageView view, vk::Sampler sampler,
166 vk::ImageLayout layout = vk::ImageLayout::eShaderReadOnlyOptimal) {
167 vk::DescriptorImageInfo img{};
168 img.sampler = sampler;
169 img.imageView = view;
170 img.imageLayout = layout;
171 vk::WriteDescriptorSet w{};
172 w.dstSet = deferredLightingSet;
173 w.dstBinding = binding;
174 w.descriptorCount = 1;
175 w.descriptorType = vk::DescriptorType::eCombinedImageSampler;
176 w.pImageInfo = &img;
177 device->updateDescriptorSets(w, {});
178 };
179 auto writeBuffer = [&](uint32_t binding, vk::Buffer buffer, vk::DeviceSize size, vk::DescriptorType type) {
180 vk::DescriptorBufferInfo buf{};
181 buf.buffer = buffer;
182 buf.offset = 0;
183 buf.range = size;
184 vk::WriteDescriptorSet w{};
185 w.dstSet = deferredLightingSet;
186 w.dstBinding = binding;
187 w.descriptorCount = 1;
188 w.descriptorType = type;
189 w.pBufferInfo = &buf;
190 device->updateDescriptorSets(w, {});
191 };
192
193 writeBuffer(0, frame.ubo.buffer, sizeof(DeferredLightingUBO), vk::DescriptorType::eUniformBuffer);
194 writeImage(1, gslot->normal.imageView(), deferredLightingSampler);
195 writeImage(2, gslot->depthColor.imageView(), deferredLightingSampler);
196 writeImage(3, gslot->albedo.imageView(), deferredLightingSampler);
197 writeImage(4, gslot->pbrParams.imageView(), deferredLightingSampler);
198 writeImage(5, gslot->emissive.imageView(), deferredLightingSampler);
199 writeImage(6, gslot->depth.imageView(), deferredLightingSampler);
200 writeBuffer(7, storage.lightsBuf.buffer, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
201 writeBuffer(8, storage.tableBuf.buffer, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
202 writeBuffer(9, storage.indicesBuf.buffer, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
203 {
204 vk::DescriptorBufferInfo buf{};
205 buf.buffer = cfslots.shadowRing.buffer;
206 buf.offset = shadowOffset;
207 buf.range = sizeof(ShadowUBO);
208 vk::WriteDescriptorSet w{};
209 w.dstSet = deferredLightingSet;
210 w.dstBinding = 10;
211 w.descriptorCount = 1;
212 w.descriptorType = vk::DescriptorType::eUniformBuffer;
213 w.pBufferInfo = &buf;
214 device->updateDescriptorSets(w, {});
215 }
216 writeImage(11, shadowView, vk::Sampler(shadowSampler), currentShadowMap().image.currentLayout());
217
218 auto& cb = currentPresentCb();
219 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, deferredLightingPipeline);
220 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, deferredLightingPipelineLayout, 0, 1, &deferredLightingSet,
221 0, nullptr);
222 setViewportAndScissor(cb, uint32_t(sceneColorWidth), uint32_t(sceneColorHeight));
223 cb.draw(3, 1, 0, 0);
224}
225
226} // namespace eve::graphics::vulkan
227
228// GraphicsDisplayOutput.cpp
229namespace eve::graphics::vulkan {
230namespace {
231
232Graphics::DisplayOutputSupport probeSupport(vk::PhysicalDevice phys, vk::SurfaceKHR surface) {
234 if (!phys || !surface) return support;
235 const auto formats = phys.getSurfaceFormatsKHR(surface);
236 for (const auto& fmt : formats) {
237 if (fmt.colorSpace == vk::ColorSpaceKHR::eHdr10St2084EXT &&
238 (fmt.format == vk::Format::eA2B10G10R10UnormPack32 || fmt.format == vk::Format::eA2R10G10B10UnormPack32))
239 support.hdr10 = true;
240 if (fmt.colorSpace == vk::ColorSpaceKHR::eExtendedSrgbLinearEXT &&
241 (fmt.format == vk::Format::eR16G16B16A16Sfloat || fmt.format == vk::Format::eB10G11R11UfloatPack32))
242 support.scRgb = true;
243 }
244 return support;
245}
246
247vk::SurfaceFormatKHR chooseSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& available,
249 auto has = [&](vk::Format format, vk::ColorSpaceKHR space) {
250 for (const auto& fmt : available)
251 if (fmt.format == format && fmt.colorSpace == space) return true;
252 return false;
253 };
254 auto pickHdr10 = [&]() -> std::optional<vk::SurfaceFormatKHR> {
255 const vk::Format formats[] = {vk::Format::eA2B10G10R10UnormPack32, vk::Format::eA2R10G10B10UnormPack32};
256 for (vk::Format format : formats) {
257 if (has(format, vk::ColorSpaceKHR::eHdr10St2084EXT))
258 return vk::SurfaceFormatKHR{format, vk::ColorSpaceKHR::eHdr10St2084EXT};
259 }
260 return std::nullopt;
261 };
262 auto pickScRgb = [&]() -> std::optional<vk::SurfaceFormatKHR> {
263 const vk::Format formats[] = {vk::Format::eR16G16B16A16Sfloat, vk::Format::eB10G11R11UfloatPack32};
264 for (vk::Format format : formats) {
265 if (has(format, vk::ColorSpaceKHR::eExtendedSrgbLinearEXT))
266 return vk::SurfaceFormatKHR{format, vk::ColorSpaceKHR::eExtendedSrgbLinearEXT};
267 }
268 return std::nullopt;
269 };
270
271 std::optional<vk::SurfaceFormatKHR> chosen;
273 switch (mode) {
274 case Graphics::DisplayOutputMode::Hdr10: chosen = pickHdr10(); break;
275 case Graphics::DisplayOutputMode::ScRgb: chosen = pickScRgb(); break;
277 chosen = pickHdr10();
278 if (!chosen) chosen = pickScRgb();
279 break;
281 default: break;
282 }
283 if (chosen) {
284 activeOut = chosen->colorSpace == vk::ColorSpaceKHR::eHdr10St2084EXT ? Graphics::DisplayColorSpace::Hdr10
286 return *chosen;
287 }
288
289 const vk::SurfaceFormatKHR sdrPrefs[] = {
290 {vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear},
291 {vk::Format::eR8G8B8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear},
292 {vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear},
293 {vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear},
294 };
295 for (const auto& pref : sdrPrefs) {
296 if (has(pref.format, pref.colorSpace)) return pref;
297 }
298 if (!available.empty()) return available.front();
299 return sdrPrefs[0];
300}
301
302} // namespace
303
308 Diagnostic::error(DiagnosticCode::InvalidArgument, "Unknown display output mode", "graphics.presentation"));
309 if (mode == displayOutputMode_) return Result<void>::success();
310 displayOutputMode_ = mode;
311 markSwapchainDirty();
312 return Result<void>::success();
313}
314
315Result<void> Graphics::setDisplayHdrCalibration(float paperWhiteNits, float peakNits) {
316 if (!std::isfinite(paperWhiteNits) || !std::isfinite(peakNits))
318 DiagnosticCode::InvalidArgument, "Display HDR calibration must be finite", "graphics.presentation"));
319 display::clampCalibration(paperWhiteNits, peakNits);
320 displayPaperWhiteNits_ = paperWhiteNits;
321 displayPeakNits_ = peakNits;
322 return Result<void>::success();
323}
324
326 if (!initialized || !surface)
328 Diagnostic::error(DiagnosticCode::Failed, "Display output support requires an initialized window surface",
329 "graphics.presentation"));
330 return Result<DisplayOutputSupport>::success(probeSupport(device.physical_device, surface));
331}
332
333void Graphics::applyPreferredSwapchainFormats(vkb::SwapchainBuilder& builder) {
335 std::vector<vk::SurfaceFormatKHR> available;
336 if (surface) available = device.physical_device->getSurfaceFormatsKHR(surface);
337 selectedSurfaceFormat_ = chooseSurfaceFormat(available, displayOutputMode_, active);
339 builder.set_desired_format(selectedSurfaceFormat_);
340 builder.add_fallback_format({vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear});
341 builder.add_fallback_format({vk::Format::eR8G8B8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear});
342 builder.add_fallback_format({vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear});
343 builder.add_fallback_format({vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear});
344}
345
346void Graphics::destroyPresentComposeResources() {
347 if (device.instance) device->waitIdle();
348 for (auto& slot : presentComposeSlots) {
349 slot.colorTex.gpuHandle = nullptr;
350 if (slot.framebuffer) {
351 device->destroyFramebuffer(slot.framebuffer);
352 slot.framebuffer = vk::Framebuffer{};
353 }
354 destroySampler(device, slot.colorGpu.sampler);
355 }
356 presentComposeSlots.clear();
357 presentComposeWidth = 0;
358 presentComposeHeight = 0;
359}
360
361void Graphics::ensurePresentComposeResources(int composeW, int composeH) {
362 if (composeW <= 0 || composeH <= 0) return;
363 ensureHdrOffscreenPipelines();
364 if (!texSetLayout || !descriptorPool || !hdrOffscreenRenderPass) return;
365 if (!presentComposeSlots.empty() && presentComposeWidth == composeW && presentComposeHeight == composeH) return;
366 destroyPresentComposeResources();
367 presentComposeWidth = composeW;
368 presentComposeHeight = composeH;
369 const uint32_t w = uint32_t(composeW);
370 const uint32_t h = uint32_t(composeH);
371 const vk::Format colorFmt = vk::Format::eR16G16B16A16Sfloat;
372 presentComposeSlots.resize(kAsyncResourceCopies);
373 for (auto& slot : presentComposeSlots) {
374 slot.color = device.createColorTarget(w, h, colorFmt);
375 slot.framebuffer = hdrOffscreenRenderPass.createFramebuffer(device, w, h, {slot.color.asAttachment()});
376 vkb::SamplerBuilder sb;
377 slot.colorGpu.sampler = sb.magFilter(vk::Filter::eLinear)
378 .minFilter(vk::Filter::eLinear)
379 .addressModeU(vk::SamplerAddressMode::eClampToEdge)
380 .addressModeV(vk::SamplerAddressMode::eClampToEdge)
381 .build(device);
382 auto sets = vkb::DescriptorSetBuilder().layout(texSetLayout).build(device.instance, descriptorPool);
383 slot.colorGpu.descriptorSet = vkb::BoundSet{sets[0]};
384 slot.colorGpu.width = composeW;
385 slot.colorGpu.height = composeH;
386 slot.colorGpu.viewOverride = slot.color.imageView();
387 writeCombinedImageDescriptor(&slot.colorGpu);
388 slot.colorTex.width = composeW;
389 slot.colorTex.height = composeH;
390 slot.colorTex.pixelWidth = composeW;
391 slot.colorTex.pixelHeight = composeH;
392 slot.colorTex.gpuHandle = &slot.colorGpu;
393 }
394}
395
396Graphics::PresentComposeSlot* Graphics::currentPresentComposeSlot() {
397 if (presentComposeSlots.empty()) return nullptr;
398 return &presentComposeSlots[currentFrameSlot() % presentComposeSlots.size()];
399}
400
401bool Graphics::beginPresentComposePass() {
402 ensurePresentComposeResources(int(swapchain.extent.width), int(swapchain.extent.height));
403 auto* slot = currentPresentComposeSlot();
404 if (!slot || !hdrOffscreenRenderPass || !slot->framebuffer) return false;
405 auto& cb = currentPresentCb();
406 vk::ClearValue clear{};
407 clear.color = vk::ClearColorValue(std::array<float, 4>{clearColor.r, clearColor.g, clearColor.b, clearColor.a});
408 vk::RenderPassBeginInfo rpBegin{};
409 rpBegin.renderPass = hdrOffscreenRenderPass;
410 rpBegin.framebuffer = slot->framebuffer;
411 rpBegin.renderArea = vk::Rect2D{{0, 0}, {uint32_t(presentComposeWidth), uint32_t(presentComposeHeight)}};
412 rpBegin.clearValueCount = 1;
413 rpBegin.pClearValues = &clear;
414 slot->color.beginColorAttachment();
415 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
416 presentComposeActive_ = true;
417 return true;
418}
419
420void Graphics::endPresentComposePass() {
421 if (!presentComposeActive_) return;
422 auto& cb = currentPresentCb();
423 cb.endRenderPass();
424 if (auto* slot = currentPresentComposeSlot()) slot->color.endSampledLayout();
425 presentComposeActive_ = false;
426}
427
428void Graphics::encodePresentComposeToSwapchain(vk::CommandBuffer cb) {
429 auto* slot = currentPresentComposeSlot();
430 if (!slot || !slot->colorTex.gpuHandle || !sceneTonemapPipeline) return;
431 auto* gpu = static_cast<GpuTexture*>(slot->colorTex.gpuHandle);
436 Batcher batch;
437 batch.addTexturedRect(0.f, 0.f, float(width), float(height), tint, 0.f, 0.f, 1.f, 1.f);
438 batch.toNDC(width, height);
439 std::vector<TexturedVertex> gpuVerts;
440 gpuVerts.reserve(batch.vertices().size());
441 for (const auto& v : batch.vertices()) gpuVerts.push_back(TexturedVertex{v.pos, v.color, v.uv});
442 auto& frameBufs = currentFrame2DBuffers();
443 if (frameBufs.texBufs.empty()) frameBufs.texBufs.emplace_back();
444 // Append a dedicated vertex buffer so the encode blit does not overwrite
445 // buffers still referenced by the just-recorded compose draws.
446 frameBufs.texBufs.emplace_back();
447 vkb::HostVertexBuffer& vb = frameBufs.texBufs.back();
448 vb.allocate<TexturedVertex>(frameToken(), device, gpuVerts);
449 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, sceneTonemapPipeline);
450 vk::DescriptorSet texSet = gpu->descriptorSet;
451 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, texPipelineLayout, 0, 1, &texSet, 0, nullptr);
452 vk::DeviceSize offset = 0;
453 cb.bindVertexBuffers(0, 1, vb, &offset);
454 cb.draw(uint32_t(gpuVerts.size()), 1, 0, 0);
455}
456
457} // namespace eve::graphics::vulkan
458
459// GraphicsMeshPool.cpp
460namespace eve::graphics::vulkan {
461void Graphics::ensureGpuVertexPool() {
462 if (gpuVertexPool_.positions.buffer) return;
463 constexpr uint32_t kInitialVertices = 256u << 10; // 256k verts (~11 MB total)
464 constexpr uint32_t kInitialIndices = 768u << 10; // 768k u32 indices (3 MB)
465 const auto hostMem = kHostVisibleCoherent;
466 gpuVertexPool_.positions = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
467 kInitialVertices * sizeof(glm::vec4), hostMem);
468 gpuVertexPool_.normals = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
469 kInitialVertices * sizeof(glm::vec4), hostMem);
470 gpuVertexPool_.uvs = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
471 kInitialVertices * sizeof(glm::vec2), hostMem);
472 gpuVertexPool_.indices = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
473 kInitialIndices * sizeof(uint32_t), hostMem);
474 gpuVertexPool_.vertexCount = 0;
475 gpuVertexPool_.indexCount = 0;
476}
477
478void Graphics::growGpuVertexPool(uint32_t needVertices, uint32_t needIndices) {
479 // Pool growth reallocates the buffers; a pending frame may still be reading
480 // them, so drain the GPU first (rare path: first-time mesh registration).
481 device->waitIdle();
482 const uint32_t oldVerts = gpuVertexPool_.vertexCount;
483 const uint32_t oldInds = gpuVertexPool_.indexCount;
484 const auto hostMem = kHostVisibleCoherent;
485 auto copyInto = [&](vkb::GenericBuffer& dst, vkb::GenericBuffer& src, vk::DeviceSize oldBytes,
486 vk::DeviceSize newBytes) {
487 vkb::GenericBuffer grown(device, vk::BufferUsageFlagBits::eStorageBuffer, newBytes, hostMem);
488 if (oldBytes > 0) {
489 void* srcMap = src.map();
490 void* dstMap = grown.map();
491 std::memcpy(dstMap, srcMap, oldBytes);
492 grown.unmap();
493 src.unmap();
494 }
495 src.release();
496 dst = std::move(grown);
497 };
498 // Leave room after a large first insertion. Exact-fit growth made the next
499 // tiny mesh copy the entire large allocation immediately afterwards.
500 const auto capacity = [](uint32_t needed) {
501 return uint32_t(std::min(uint64_t(needed) * 2u, uint64_t(UINT32_MAX)));
502 };
503 const uint32_t newVerts =
504 std::max(capacity(needVertices), uint32_t(gpuVertexPool_.positions.size / sizeof(glm::vec4)));
505 const uint32_t newInds = std::max(capacity(needIndices), uint32_t(gpuVertexPool_.indices.size / sizeof(uint32_t)));
506 copyInto(gpuVertexPool_.positions, gpuVertexPool_.positions, vk::DeviceSize(oldVerts) * sizeof(glm::vec4),
507 vk::DeviceSize(newVerts) * sizeof(glm::vec4));
508 copyInto(gpuVertexPool_.normals, gpuVertexPool_.normals, vk::DeviceSize(oldVerts) * sizeof(glm::vec4),
509 vk::DeviceSize(newVerts) * sizeof(glm::vec4));
510 copyInto(gpuVertexPool_.uvs, gpuVertexPool_.uvs, vk::DeviceSize(oldVerts) * sizeof(glm::vec2),
511 vk::DeviceSize(newVerts) * sizeof(glm::vec2));
512 copyInto(gpuVertexPool_.indices, gpuVertexPool_.indices, vk::DeviceSize(oldInds) * sizeof(uint32_t),
513 vk::DeviceSize(newInds) * sizeof(uint32_t));
514 bindGpuVertexPoolBindless();
515}
516
517void Graphics::bindGpuVertexPoolBindless() {
518 if (bindlessSets_.empty() || !gpuVertexPool_.positions.buffer) return;
519 auto bufWrite = [&](vk::DescriptorSet set, uint32_t binding, vk::Buffer buffer, vk::DeviceSize size) {
520 vk::DescriptorBufferInfo info{buffer, 0, size};
521 vk::WriteDescriptorSet w{};
522 w.dstSet = set;
523 w.dstBinding = binding;
524 w.descriptorCount = 1;
525 w.descriptorType = vk::DescriptorType::eStorageBuffer;
526 w.pBufferInfo = &info;
527 device->updateDescriptorSets(1, &w, 0, nullptr);
528 };
529 const uint32_t cap = [&]() {
530 const vk::DeviceSize bytes = gpuVertexPool_.positions.size;
531 return uint32_t(bytes / sizeof(glm::vec4));
532 }();
533 const uint32_t indCap = uint32_t(gpuVertexPool_.indices.size / sizeof(uint32_t));
534 for (vk::DescriptorSet set : bindlessSets_) {
535 bufWrite(set, 18, gpuVertexPool_.positions.buffer, vk::DeviceSize(cap) * sizeof(glm::vec4));
536 bufWrite(set, 19, gpuVertexPool_.normals.buffer, vk::DeviceSize(cap) * sizeof(glm::vec4));
537 bufWrite(set, 20, gpuVertexPool_.uvs.buffer, vk::DeviceSize(cap) * sizeof(glm::vec2));
538 bufWrite(set, 21, gpuVertexPool_.indices.buffer, vk::DeviceSize(indCap) * sizeof(uint32_t));
539 }
540}
541
542void Graphics::appendGpuMeshToPool(GpuMesh& gpu, const std::vector<MeshVertex>* vertices,
543 const std::vector<uint32_t>* indices) {
544 if (!gpu.vertices.buffer || !gpu.indices.buffer) return;
545 ensureGpuVertexPool();
546 const uint32_t nVerts = gpu.record.vertexCount;
547 const uint32_t nInds = gpu.record.indexCount;
548 if (nVerts == 0 || nInds == 0) return;
549 const uint32_t newVerts = gpuVertexPool_.vertexCount + nVerts;
550 const uint32_t newInds = gpuVertexPool_.indexCount + nInds;
551 const uint32_t capVerts = uint32_t(gpuVertexPool_.positions.size / sizeof(glm::vec4));
552 const uint32_t capInds = uint32_t(gpuVertexPool_.indices.size / sizeof(uint32_t));
553 if (newVerts > capVerts || newInds > capInds) {
554 growGpuVertexPool(newVerts, newInds);
555 }
556
557 const void* vMap = vertices ? vertices->data() : gpu.vertices.map();
558 const void* iMap = indices ? indices->data() : gpu.indices.map();
559 if (!vMap || !iMap) return;
560 auto* verts = static_cast<const MeshVertex*>(vMap);
561 auto* posDst = static_cast<glm::vec4*>(gpuVertexPool_.positions.map());
562 auto* nrmDst = static_cast<glm::vec4*>(gpuVertexPool_.normals.map());
563 auto* uvDst = static_cast<glm::vec2*>(gpuVertexPool_.uvs.map());
564 auto* idxDst = static_cast<uint32_t*>(gpuVertexPool_.indices.map());
565 if (!posDst || !nrmDst || !uvDst || !idxDst) {
566 if (!vertices) gpu.vertices.unmap();
567 if (!indices) gpu.indices.unmap();
568 return;
569 }
570 posDst += gpuVertexPool_.vertexCount;
571 nrmDst += gpuVertexPool_.vertexCount;
572 uvDst += gpuVertexPool_.vertexCount;
573 idxDst += gpuVertexPool_.indexCount;
574 for (uint32_t i = 0; i < nVerts; ++i) {
575 posDst[i] = glm::vec4(verts[i].pos, 0.f);
576 nrmDst[i] = glm::vec4(verts[i].normal, 0.f);
577 uvDst[i] = verts[i].uv;
578 }
579 if (!indices && gpu.indexType == vk::IndexType::eUint16) {
580 const auto* src16 = static_cast<const uint16_t*>(iMap);
581 for (uint32_t i = 0; i < nInds; ++i) idxDst[i] = uint32_t(src16[i]);
582 } else {
583 const auto* src32 = static_cast<const uint32_t*>(iMap);
584 for (uint32_t i = 0; i < nInds; ++i) idxDst[i] = src32[i];
585 }
586 gpuVertexPool_.positions.unmap();
587 gpuVertexPool_.normals.unmap();
588 gpuVertexPool_.uvs.unmap();
589 gpuVertexPool_.indices.unmap();
590 if (!vertices) gpu.vertices.unmap();
591 if (!indices) gpu.indices.unmap();
592
593 // Pool offsets are vertex/index counts, resolved by the vis shaders.
594 gpu.record.vertexOffset = gpuVertexPool_.vertexCount;
595 gpu.record.indexOffset = gpuVertexPool_.indexCount;
596 gpu.record.firstIndex = 0; // vis pass draws non-indexed from the pool
597 gpu.record.vertexBase = 0;
598 gpuVertexPool_.vertexCount = newVerts;
599 gpuVertexPool_.indexCount = newInds;
600}
601
602uint32_t Graphics::registerMeshRecord(GpuMesh* gpu, const std::vector<MeshVertex>* vertices,
603 const std::vector<uint32_t>* indices) {
604 if (!gpu) return kInvalidBindlessSlot;
605 if (gpu->gpuRecordIndex != kInvalidBindlessSlot) return gpu->gpuRecordIndex;
606 if (meshTableRecords_.size() >= meshTableCapacity_) return kInvalidBindlessSlot;
607 // dev's mesh factories do not populate GpuMeshRecord; build it on first
608 // registration from the host-visible buffers (bounds + ranges).
609 if (gpu->record.vertexCount == 0 && gpu->vertices.buffer) {
610 const uint32_t vertexCount = uint32_t(gpu->vertices.size / sizeof(MeshVertex));
611 gpu->record.vertexCount = vertexCount;
612 gpu->record.indexCount = gpu->indexCount;
613 gpu->record.indexType = gpu->indexType == vk::IndexType::eUint16 ? 0u : 1u;
614 const void* map = vertices ? vertices->data() : gpu->vertices.map();
615 if (map && vertexCount > 0) {
616 const auto* verts = static_cast<const MeshVertex*>(map);
617 glm::vec3 minv(1e30f), maxv(-1e30f);
618 for (uint32_t i = 0; i < vertexCount; ++i) {
619 minv = glm::min(minv, verts[i].pos);
620 maxv = glm::max(maxv, verts[i].pos);
621 }
622 const glm::vec3 center = (minv + maxv) * 0.5f;
623 float radius = 0.f;
624 for (uint32_t i = 0; i < vertexCount; ++i) radius = std::max(radius, glm::length(verts[i].pos - center));
625 gpu->record.boundsCenterRadius = glm::vec4(center, radius);
626 }
627 if (map && !vertices) gpu->vertices.unmap();
628 }
629 // Stage 3: lazily pool the mesh's vertices/indices so the vis resolve can
630 // fetch attributes by (pool offset + triangle + barycentric).
631 appendGpuMeshToPool(*gpu, vertices, indices);
632 const uint32_t idx = uint32_t(meshTableRecords_.size());
633 meshTableRecords_.push_back(gpu->record);
634 meshRecordOwners_.push_back(gpu);
635 gpu->gpuRecordIndex = idx;
636 syncMeshTable();
637 return idx;
638}
639
640
641} // namespace eve::graphics::vulkan
642
643// GraphicsMeshStylePipeline.cpp
644namespace eve::graphics::vulkan {
645vk::Pipeline Graphics::createMesh3DStylePipeline(const std::vector<uint32_t>& vert, const std::vector<uint32_t>& frag,
646 vk::PipelineLayout layout, const vkb::BuiltRenderPass& rp,
647 vk::SampleCountFlagBits samples, BlendMode blend, bool depthWrite,
648 bool doubleSided, const MeshShaderRasterState& raster) {
649 vk::ShaderModuleCreateInfo vertexInfo{};
650 vertexInfo.codeSize = vert.size() * sizeof(uint32_t);
651 vertexInfo.pCode = vert.data();
652 auto vertModule = device->createShaderModuleUnique(vertexInfo);
653 vk::ShaderModuleCreateInfo fragmentInfo{};
654 fragmentInfo.codeSize = frag.size() * sizeof(uint32_t);
655 fragmentInfo.pCode = frag.data();
656 auto fragModule = device->createShaderModuleUnique(fragmentInfo);
657 const auto cull = doubleSided ? vk::CullModeFlagBits::eNone : vk::CullModeFlagBits::eBack;
658 const auto compare = raster.depthCompare == MeshDepthCompare::Always ? vk::CompareOp::eAlways
659 : raster.depthCompare == MeshDepthCompare::LessEqual ? vk::CompareOp::eLessOrEqual
660 : vk::CompareOp::eLess;
661 vk::Pipeline pipe{};
662 if (blend != BlendMode::Opaque || raster.colorWriteMask != 15) {
663 std::vector<vk::PipelineColorBlendAttachmentState> attachments(1, makeBlendAttachment(blend));
664 attachments[0].blendEnable = blend != BlendMode::Opaque;
665 attachments[0].colorWriteMask = vk::ColorComponentFlags(raster.colorWriteMask);
666 vk::PipelineColorBlendStateCreateInfo cbs{};
667 cbs.attachmentCount = 1;
668 cbs.pAttachments = attachments.data();
669 pipe =
670 device.createPipeline()
671 .useClassicPipeline(vertModule.get(), fragModule.get())
672 .setPipelineLayout(layout)
673 .setVertexInputState(
674 vkb::VertexInputStateBuilder().addInputBinding<MeshVertex>().addAttributeDescription<MeshVertex>())
675 .setDynamicStatesViewportScissor()
676 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, cull, vk::FrontFace::eCounterClockwise)
677 .setMultisampler(false, samples)
678 .setDepthBias(raster.depthBiasConstant, raster.depthBiasSlope)
679 .setDepthStencil(true, depthWrite, compare)
680 .setColorBlending(cbs)
681 .build(rp);
682 } else {
683 pipe =
684 device.createPipeline()
685 .useClassicPipeline(vertModule.get(), fragModule.get())
686 .setPipelineLayout(layout)
687 .setVertexInputState(
688 vkb::VertexInputStateBuilder().addInputBinding<MeshVertex>().addAttributeDescription<MeshVertex>())
689 .setDynamicStatesViewportScissor()
690 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, cull, vk::FrontFace::eCounterClockwise)
691 .setMultisampler(false, samples)
692 .setDepthBias(raster.depthBiasConstant, raster.depthBiasSlope)
693 .setDepthStencil(true, depthWrite, compare)
694 .setColorAttachmentCount(1)
695 .build(rp);
696 }
697 return pipe;
698}
699
700} // namespace eve::graphics::vulkan
bool & active
float w
Definition AnimClip.cpp:738
std::string colorSpace
std::vector< std::uint32_t > verts
Definition Builder.cpp:27
float uv
std::string layout
std::uint32_t vertexCount
vkb::Device & device
vk::ShaderModule vert
vk::ShaderModule frag
std::uint32_t capacity
vk::UniqueSampler sampler
vk::UniqueImage image
glm::vec4 tint
float u
Definition Grass.cpp:233
std::vector< std::uint32_t > indices
float v
float blend
int h
size_t offset
std::uint64_t bytes
double radius
Definition MeleeHit.cpp:42
bool doubleSided
Texture * normal
std::shared_ptr< OceanGpuSpectrum > gpu
ssq::Object frame
glm::dvec2 center
OceanSprayView view
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
eve::action::ActionVfxBinding binding
int idx
float d
std::string slot
int count
std::array< double, 2 > vertices[3]
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.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
DisplayOutputMode
Requested swapchain present preference.
Definition Graphics.h:1388
DisplayColorSpace activeDisplayColorSpace_
Definition Graphics.h:2330
DisplayColorSpace
Color space actually selected for the live swapchain.
Definition Graphics.h:1390
DisplayOutputMode displayOutputMode_
Definition Graphics.h:2329
void drawDeferredLighting() override
Draws deferred lighting.
Result< void > setDisplayOutputMode(DisplayOutputMode mode) override
Sets the display output mode.
Result< DisplayOutputSupport > queryDisplayOutputSupport() const override
Queries display output support.
Result< void > setDisplayHdrCalibration(float paperWhiteNits, float peakNits) override
Sets the display hdr calibration.
void setMesh3DClusteredLighting(const ClusteredLightingUpload &upload) override
Sets the mesh 3 d clustered lighting.
void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth) override
Clears .
Color sceneResolveTint(bool aces, ActiveColorSpace space, bool attachmentEncodesSrgb, float paperWhiteNits, float peakNits) noexcept
Build the Color tint used by the final scene present resolve.
void clampCalibration(float &paperWhiteNits, float &peakNits) noexcept
Clamp paper-white / peak luminance into the engine-supported range.
ActiveColorSpace
Active present color encoding after swapchain selection.
constexpr uint32_t kInvalidBindlessSlot
Definition GpuDriven.h:22
ClusteredLightingUpload buildClusteredLighting(const std::vector< ClusteredLightGpu > &points, const std::vector< ClusteredLightGpu > &dirs, const glm::mat4 &view, float nearZ, float farZ, int screenW, int screenH, float fovYRad, const glm::vec4 &ambient)
Build clustered tables for point lights in view space.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
Definition BlendMode.h:8
bool has(const std::vector< std::reference_wrapper< const HouseComponent > > &values)
CPU-built clustered lighting upload for one frame/camera. Point lights are clustered; directional lig...
Surface present formats the current device/window can offer.
Definition Graphics.h:1392
GPU light packing for mesh3d / PBR (std140-friendly).
Definition Light.h:160
Per-frame / per-draw CSM + local-spot constants (std140).
Definition Shadow.h:36
DeferredLightingUBO public API.
Definition Graphics.h:229
glm::uvec4 info
glm::vec4 color