19#include <SDL2/SDL_vulkan.h>
38#include "common/config.h"
42#include "zeroerr/assert.h"
47#include <assimp/mesh.h>
48#include <assimp/matrix3x3.h>
49#include <assimp/matrix4x4.h>
50#include <assimp/vector3.h>
51#include <glm/gtc/matrix_transform.hpp>
53#include "graphics/shaders/mesh3d_vert_spv.inc"
54#include "graphics/shaders/mesh3d_frag_spv.inc"
55#include "graphics/shaders/voxel_rect_vert_spv.inc"
56#include "graphics/shaders/voxel_rect_frag_spv.inc"
65 applyPendingResourceChanges();
67 if (!initialized)
throw Exception(
"begin3DFrame: graphics not initialized");
69 createMesh3DPipeline();
70 if (swapchainPassOpen) {
80 if (!beginPresentCommandBuffer())
82 currentFrame2DBuffers().primitive3DDrawIndex = 0;
83 decalLayerFresh =
false;
84 recordDeferredFrameGraph();
86 vgAnyThisFrame_ =
false;
88 ensureGpuDrivenCullResources(gbufferWidth > 0 ? gbufferWidth : int(swapchain.extent.width),
89 gbufferHeight > 0 ? gbufferHeight : int(swapchain.extent.height));
93 createSceneColorResources(
int(swapchain.extent.width),
int(swapchain.extent.height));
98 gpuDrivenScenePassPending_ = gpuDrivenEnabled_ && gpuDrivenCullReady_;
99 if (!gpuDrivenScenePassPending_) {
100 if (beginSceneColorRenderPass()) {
105 ensureScenePassPipelines(activeScenePass(), activeSceneSamples());
108 ensureScenePassPipelines(renderpass, vk::SampleCountFlagBits::e1);
109 beginSwapchainColorPass();
113 auto &cb = currentPresentCb();
114 setViewportAndScissor(cb, swapchain.extent.width, swapchain.extent.height);
117 auto &fslots = currentMesh3dFrameSlots();
118 fslots.lastDrawCount = fslots.drawIndex;
119 fslots.drawIndex = 0;
120 fslots.activePalette = 0;
121 ensureMesh3dRing(fslots);
122 auto &cslots = currentMesh3dClusteredFrameSlots();
123 cslots.lastDrawCount = cslots.drawIndex;
124 cslots.drawIndex = 0;
125 ensureMesh3dClusteredRing(cslots);
127 lastMesh3dPipeline =
nullptr;
128 lastMesh3dClusteredPipeline =
nullptr;
129 currentVoxelInstanceFrame().drawIndex = 0;
130 swapchainPassOpen = !gpuDrivenScenePassPending_;
132 hasPendingClear =
false;
136void Graphics::ensureOffscreen3DResources() {
138 auto createResources = [&](vk::Format colorFormat, vkb::BuiltRenderPass &renderPass, vk::Pipeline &meshPipeline,
139 std::array<vk::Pipeline, kMesh3DPipelineVariants> &surfacePipelines,
140 std::array<vk::Pipeline, kPrimitive3DPipelineVariants> &primitivePipelines) {
141 if (renderPass)
return;
143 dev.createRenderPass()
144 .addSampledColorAttachment(colorFormat)
145 .addDepthAttachment(depthFormat, vk::AttachmentLoadOp::eClear,
146 vk::AttachmentStoreOp::eDontCare)
147 .addSubpass(vkb::SubpassBuilder()
148 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
149 .setDepthStencilAttachment(
150 1, vk::ImageLayout::eDepthStencilAttachmentOptimal))
151 .addExternalShaderReadDependencies()
153 meshPipeline = createMesh3DStylePipeline(embeddedSpirv(mesh3d_vert_spv), embeddedSpirv(mesh3d_frag_spv),
154 mesh3dPipelineLayout, renderPass, vk::SampleCountFlagBits::e1,
156 for (
int blendValue = 0; blendValue < 5; ++blendValue) {
158 for (
int depthValue = 0; depthValue < 2; ++depthValue) {
159 for (
int doubleValue = 0; doubleValue < 2; ++doubleValue) {
161 mesh3dPipelineIndex(
blend, depthValue != 0, doubleValue != 0);
162 surfacePipelines[
index] = createMesh3DStylePipeline(
163 embeddedSpirv(mesh3d_vert_spv), embeddedSpirv(mesh3d_frag_spv), mesh3dPipelineLayout,
164 renderPass, vk::SampleCountFlagBits::e1,
blend, depthValue != 0, doubleValue != 0,
170 buildPrimitive3DPipelines(renderPass, vk::SampleCountFlagBits::e1, primitivePipelines);
172 createResources(vk::Format::eR8G8B8A8Unorm, offscreen3DRenderPass, offscreen3DMeshPipeline,
173 offscreen3DSurfacePipelines, offscreenPrimitive3DPipelines);
174 createResources(vk::Format::eR16G16B16A16Sfloat, hdrOffscreen3DRenderPass, hdrOffscreen3DMeshPipeline,
175 hdrOffscreen3DSurfacePipelines, hdrOffscreenPrimitive3DPipelines);
176 if (!offscreen3DPool) {
177 vk::CommandPoolCreateInfo poolInfo{};
178 poolInfo.flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer;
179 offscreen3DPool = dev->createCommandPool(poolInfo);
180 vk::CommandBufferAllocateInfo allocInfo{};
181 allocInfo.commandPool = offscreen3DPool;
182 allocInfo.level = vk::CommandBufferLevel::ePrimary;
183 allocInfo.commandBufferCount = 1;
184 auto bufs = dev->allocateCommandBuffers(allocInfo);
185 offscreen3DCB = bufs[0];
186 vk::FenceCreateInfo fenceInfo{};
187 fenceInfo.flags = vk::FenceCreateFlagBits::eSignaled;
188 offscreen3DFence = dev->createFence(fenceInfo);
189 const auto &
limits = dev.physical_device.properties.limits;
190 if (
limits.timestampComputeAndGraphics &&
limits.timestampPeriod > 0.f) {
191 vk::QueryPoolCreateInfo queryInfo{};
192 queryInfo.queryType = vk::QueryType::eTimestamp;
193 queryInfo.queryCount = 2;
194 offscreen3DTimestampQueryPool = dev->createQueryPool(queryInfo);
195 offscreen3DTimestampPeriodNs =
limits.timestampPeriod;
200void Graphics::destroyOffscreen3DResources() {
202 if (offscreen3DFence) {
203 dev->destroyFence(offscreen3DFence);
204 offscreen3DFence =
nullptr;
206 if (offscreen3DTimestampQueryPool) {
207 dev->destroyQueryPool(offscreen3DTimestampQueryPool);
208 offscreen3DTimestampQueryPool =
nullptr;
210 offscreen3DTimestampPeriodNs = 0.f;
211 lastOffscreen3DGpuDurationMs = 0.f;
212 if (offscreen3DPool) {
213 dev->destroyCommandPool(offscreen3DPool);
214 offscreen3DPool =
nullptr;
216 offscreen3DCB =
nullptr;
217 if (offscreen3DMeshPipeline) {
218 device->destroyPipeline(offscreen3DMeshPipeline);
219 offscreen3DMeshPipeline =
nullptr;
221 if (hdrOffscreen3DMeshPipeline) {
222 device->destroyPipeline(hdrOffscreen3DMeshPipeline);
223 hdrOffscreen3DMeshPipeline =
nullptr;
225 for (
auto &pipeline : offscreen3DSurfacePipelines) {
226 if (pipeline) device->destroyPipeline(pipeline);
229 for (
auto &pipeline : hdrOffscreen3DSurfacePipelines) {
230 if (pipeline) device->destroyPipeline(pipeline);
233 for (
auto &pipeline : offscreenPrimitive3DPipelines) {
234 if (pipeline) device->destroyPipeline(pipeline);
237 for (
auto &pipeline : hdrOffscreenPrimitive3DPipelines) {
238 if (pipeline) device->destroyPipeline(pipeline);
241 offscreenPrimitive3DBufs.clear();
242 if (offscreen3DRenderPass) {
243 device->destroyRenderPass(offscreen3DRenderPass);
244 offscreen3DRenderPass = {};
246 if (hdrOffscreen3DRenderPass) {
247 device->destroyRenderPass(hdrOffscreen3DRenderPass);
248 hdrOffscreen3DRenderPass = {};
254 applyPendingResourceChanges();
256 if (!initialized)
throw Exception(
"begin3DFrameToCanvas: graphics not initialized");
257 if (!canvas)
throw Exception(
"begin3DFrameToCanvas: null canvas");
258 createMesh3DPipeline();
260 if (!oc)
throw Exception(
"begin3DFrameToCanvas: not an offscreen canvas");
261 if (offscreen3DPassOpen)
throw Exception(
"begin3DFrameToCanvas: already open");
262 if (swapchainPassOpen) {
270 ensureOffscreen3DResources();
272 offscreen3DCanvas = oc;
273 offscreen3DHDRActive = oc->isHDR();
275 if (offscreen3DFence) (void)device->waitForFences(1, &offscreen3DFence, VK_TRUE, UINT64_MAX);
276 offscreenPrimitive3DDrawIndex = 0;
277 vk::CommandBufferBeginInfo beginInfo{};
278 offscreen3DCB.begin(beginInfo);
279 if (mesh3dShadows.
active && shadowPendingMask != 0) {
284 auto &
slot = currentShadowMap();
285 slot.image.beginDepthAttachment();
286 vk::ClearValue
clear{};
287 clear.depthStencil = vk::ClearDepthStencilValue{1.f, 0};
289 if ((shadowPendingMask & (1u << cascade)) == 0)
continue;
290 vk::RenderPassBeginInfo shadowBegin{};
291 shadowBegin.renderPass = shadowRenderPass;
292 shadowBegin.framebuffer =
slot.framebuffers[cascade];
293 const uint32_t atlasSize =
295 uint32_t viewportSize = atlasSize;
297 viewportSize = uint32_t(std::max(1, mesh3dShadows.
cascadeMapSizes[cascade]));
299 shadowBegin.renderArea = vk::Rect2D{{0, 0}, {atlasSize, atlasSize}};
300 shadowBegin.clearValueCount = 1;
301 shadowBegin.pClearValues = &
clear;
302 offscreen3DCB.beginRenderPass(shadowBegin, vk::SubpassContents::eInline);
303 recordShadowCascadeDraws(offscreen3DCB, cascade, viewportSize);
304 offscreen3DCB.endRenderPass();
305 shadowCascadeDraws[cascade].clear();
307 slot.image.endSampledLayout();
308 shadowPendingMask = 0;
311 lastOffscreen3DGpuDurationMs = 0.f;
312 if (offscreen3DTimestampQueryPool) {
313 offscreen3DCB.resetQueryPool(offscreen3DTimestampQueryPool, 0, 2);
314 offscreen3DCB.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe,
315 offscreen3DTimestampQueryPool, 0);
317 std::array<vk::ClearValue, 2> clears{};
319 vk::ClearColorValue(std::array<float, 4>{clearColor.r, clearColor.g, clearColor.b, 1.f});
320 clears[1].depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
321 vk::RenderPassBeginInfo rpBegin{};
323 rpBegin.framebuffer = oc->framebuffer3D();
325 vk::Rect2D{{0, 0}, {uint32_t(oc->getWidth()), uint32_t(oc->getHeight())}};
326 rpBegin.clearValueCount = uint32_t(clears.size());
327 rpBegin.pClearValues = clears.data();
328 oc->colorImage().beginColorAttachment();
329 oc->depthImage().beginDepthAttachment();
330 offscreen3DCB.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
331 setViewportAndScissor(offscreen3DCB, oc->getWidth(), oc->getHeight());
334 auto &fslots = currentMesh3dFrameSlots();
335 fslots.lastDrawCount = fslots.drawIndex;
336 fslots.drawIndex = 0;
337 fslots.activePalette = 0;
338 ensureMesh3dRing(fslots);
339 auto &cslots = currentMesh3dClusteredFrameSlots();
340 cslots.lastDrawCount = cslots.drawIndex;
341 cslots.drawIndex = 0;
342 ensureMesh3dClusteredRing(cslots);
344 lastMesh3dPipeline =
nullptr;
345 lastMesh3dClusteredPipeline =
nullptr;
346 offscreen3DPassOpen =
true;
348 hasPendingClear =
false;
352 if (!offscreen3DPassOpen || !offscreen3DCB)
return;
353 offscreen3DCB.endRenderPass();
354 if (offscreen3DCanvas) {
356 offscreen3DCanvas->
colorImage().endSampledLayout();
358 if (offscreen3DTimestampQueryPool) {
359 offscreen3DCB.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe,
360 offscreen3DTimestampQueryPool, 1);
367 vk::SubmitInfo submitInfo{};
368 submitInfo.commandBufferCount = 1;
369 submitInfo.pCommandBuffers = &offscreen3DCB;
370 if (offscreen3DFence) (void)device->resetFences(1, &offscreen3DFence);
371 (void)device.getQueue(vkb::QueueType::graphics).submit(1, &submitInfo, offscreen3DFence);
372 if (offscreen3DFence)
373 (void)device->waitForFences(1, &offscreen3DFence, VK_TRUE, UINT64_MAX);
374 if (offscreen3DTimestampQueryPool && offscreen3DTimestampPeriodNs > 0.f) {
375 std::array<uint64_t, 2> ticks{};
376 const vk::Result queryResult = device->getQueryPoolResults(
377 offscreen3DTimestampQueryPool, 0, uint32_t(ticks.size()),
sizeof(ticks), ticks.data(),
378 sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait);
379 if (queryResult == vk::Result::eSuccess && ticks[1] >= ticks[0]) {
380 const double nanoseconds =
381 double(ticks[1] - ticks[0]) * double(offscreen3DTimestampPeriodNs);
382 lastOffscreen3DGpuDurationMs = float(nanoseconds * 1.0e-6);
386 offscreen3DPassOpen =
false;
387 offscreen3DHDRActive =
false;
388 offscreen3DCanvas =
nullptr;
392 glm::vec3
d = glm::normalize(
dir);
393 if (glm::length(
d) < 1e-6f)
d = glm::vec3(0.f, 1.f, 0.f);
403void Graphics::destroyVoxelRectResources() {
404 for (
auto &
frame : voxelInstanceFrames) {
406 slot.buffer.release();
407 slot.capacityBytes = 0;
412 voxelInstanceFrames.clear();
413 voxelRectSets.clear();
414 auto destroyBuf = [&](vkb::GenericBuffer &
b) {
b.release(); };
415 if (voxelUnitQuadReady) {
416 destroyBuf(voxelUnitQuadVerts);
417 destroyBuf(voxelUnitQuadIndices);
418 voxelUnitQuadReady =
false;
420 if (voxelRectPipeline) {
421 device->destroyPipeline(voxelRectPipeline);
422 voxelRectPipeline = vk::Pipeline{};
424 if (voxelRectPipelineLayout) {
425 device->destroyPipelineLayout(voxelRectPipelineLayout);
426 voxelRectPipelineLayout = vk::PipelineLayout{};
428 voxelRectSetLayoutUnique.reset();
429 voxelRectSetLayout = vk::DescriptorSetLayout{};
432void Graphics::createVoxelRectPipeline() {
433 if (voxelRectPipeline)
return;
435 if (!voxelRectPipelineLayout) {
436 vkb::DescriptorSetLayoutBuilder layoutBuilder;
437 voxelRectSetLayoutUnique =
439 .image(0, vk::DescriptorType::eCombinedImageSampler,
440 vk::ShaderStageFlagBits::eFragment, 1)
441 .createUnique(device.instance);
442 voxelRectSetLayout = *voxelRectSetLayoutUnique;
444 const auto pcr = pushConstantRange(vk::ShaderStageFlagBits::eVertex,
sizeof(VoxelRectPC));
445 voxelRectPipelineLayout = createPipelineLayout(device, voxelRectSetLayout, &pcr);
448 voxelRectPipeline = buildVoxelRectPipeline(renderpass, vk::SampleCountFlagBits::e1);
449 ensureVoxelUnitQuad();
452vk::Pipeline Graphics::buildVoxelRectPipeline(
const vkb::BuiltRenderPass &rp,
453 vk::SampleCountFlagBits samples) {
454 auto vert = embeddedSpirv(voxel_rect_vert_spv);
455 auto frag = embeddedSpirv(voxel_rect_frag_spv);
456 ShaderModulePair modules(device,
vert,
frag);
458 vk::VertexInputBindingDescription
bindings[3]{};
460 bindings[0].stride =
sizeof(glm::vec2);
461 bindings[0].inputRate = vk::VertexInputRate::eVertex;
463 bindings[1].stride =
sizeof(uint32_t);
464 bindings[1].inputRate = vk::VertexInputRate::eInstance;
466 bindings[2].stride =
sizeof(uint32_t);
467 bindings[2].inputRate = vk::VertexInputRate::eInstance;
469 vk::VertexInputAttributeDescription
attrs[3]{};
470 attrs[0].location = 0;
471 attrs[0].binding = 0;
472 attrs[0].format = vk::Format::eR32G32Sfloat;
474 attrs[1].location = 1;
475 attrs[1].binding = 1;
476 attrs[1].format = vk::Format::eR32Uint;
478 attrs[2].location = 2;
479 attrs[2].binding = 2;
480 attrs[2].format = vk::Format::eR32Uint;
483 vk::PipelineVertexInputStateCreateInfo vi{};
484 vi.vertexBindingDescriptionCount = 3;
485 vi.pVertexBindingDescriptions =
bindings;
486 vi.vertexAttributeDescriptionCount = 3;
487 vi.pVertexAttributeDescriptions =
attrs;
495 return device.createPipeline()
496 .useClassicPipeline(modules.vert, modules.frag)
497 .setPipelineLayout(voxelRectPipelineLayout)
498 .setVertexInputState(vi)
499 .setDynamicStatesViewportScissor()
500 .setRasterizer(vk::PolygonMode::eFill,
false,
false, 1.0f, vk::CullModeFlagBits::eBack,
501 vk::FrontFace::eCounterClockwise)
502 .setMultisampler(
false, samples)
503 .setDepthStencil(
true,
true, vk::CompareOp::eLess)
504 .setColorAttachmentCount(1)
508void Graphics::ensureVoxelUnitQuad() {
509 if (voxelUnitQuadReady)
return;
510 const float corners[8] = {0.f, 0.f, 1.f, 0.f, 1.f, 1.f, 0.f, 1.f};
511 voxelUnitQuadVerts.allocate(frameToken(), device, vk::BufferUsageFlagBits::eVertexBuffer,
sizeof(
corners),
512 vk::MemoryPropertyFlagBits::eHostVisible |
513 vk::MemoryPropertyFlagBits::eHostCoherent);
514 voxelUnitQuadVerts.updateLocal(frameToken(),
corners,
sizeof(
corners));
515 const uint32_t
indices[6] = {0, 2, 1, 0, 3, 2};
516 voxelUnitQuadIndices.allocate(frameToken(), device, vk::BufferUsageFlagBits::eIndexBuffer,
sizeof(
indices),
517 vk::MemoryPropertyFlagBits::eHostVisible |
518 vk::MemoryPropertyFlagBits::eHostCoherent);
519 voxelUnitQuadIndices.updateLocal(frameToken(),
indices,
sizeof(
indices));
520 voxelUnitQuadReady =
true;
523vkb::BoundSet Graphics::voxelRectSetFor(GpuTexture *gpuTex) {
524 ASSERT(gpuTex !=
nullptr);
525 auto it = voxelRectSets.find(gpuTex);
526 if (it != voxelRectSets.end())
return it->second;
528 vk::DescriptorSetAllocateInfo alloc{};
529 alloc.descriptorPool = descriptorPool;
530 alloc.descriptorSetCount = 1;
531 alloc.pSetLayouts = &voxelRectSetLayout;
532 vkb::UnboundSet unbound{device->allocateDescriptorSets(alloc).front()};
534 vkb::DescriptorSetUpdater updater(4, 4, 0);
535 updater.beginDescriptorSet(unbound)
536 .beginImages(0, 0, vk::DescriptorType::eCombinedImageSampler)
537 .image(vkb::SampledImage::forLaterSample(gpuTex->sampler, gpuTex->imageView()))
538 .update(device.instance);
540 vkb::BoundSet bound = std::move(unbound).publish();
541 voxelRectSets.emplace(gpuTex, bound);
546 float originY,
float originZ,
const std::string &faceDir,
547 Texture *atlas,
int tilesPerRow,
const uint32_t *
ao) {
549 if (!initialized)
throw Exception(
"drawVoxelFaceInstances: graphics not initialized");
550 if (!swapchainPassOpen)
throw Exception(
"drawVoxelFaceInstances: call begin3DFrame first");
551 if (!voxelRectPipeline) createVoxelRectPipeline();
552 if (!packed ||
count <= 0)
return;
555 if (faceDir ==
"posX" || faceDir ==
"+x")
557 else if (faceDir ==
"negX" || faceDir ==
"-x")
559 else if (faceDir ==
"posY" || faceDir ==
"+y")
561 else if (faceDir ==
"negY" || faceDir ==
"-y")
563 else if (faceDir ==
"posZ" || faceDir ==
"+z")
565 else if (faceDir ==
"negZ" || faceDir ==
"-z")
568 throw Exception(
"drawVoxelFaceInstances: unknown faceDir '%s'", faceDir.c_str());
570 Texture *tex = atlas ? atlas : whiteTexture;
571 if (!tex || !tex->
gpuHandle)
throw Exception(
"drawVoxelFaceInstances: missing texture");
574 ensureVoxelUnitQuad();
576 const vk::DeviceSize
bytes = vk::DeviceSize(
count) *
sizeof(uint32_t);
577 auto &vframe = currentVoxelInstanceFrame();
578 const size_t slotIndex = vframe.drawIndex++;
579 while (vframe.slots.size() <= slotIndex) vframe.slots.emplace_back();
580 auto &
slot = vframe.slots[slotIndex];
581 if (
slot.capacityBytes <
size_t(
bytes) || !
slot.buffer.buffer) {
582 const size_t alloc = std::max(
size_t(
bytes),
slot.capacityBytes ?
slot.capacityBytes * 2 : size_t(
bytes));
583 slot.buffer.allocate(frameToken(), device, vk::BufferUsageFlagBits::eVertexBuffer, vk::DeviceSize(alloc),
584 vk::MemoryPropertyFlagBits::eHostVisible |
585 vk::MemoryPropertyFlagBits::eHostCoherent);
586 slot.capacityBytes = alloc;
588 slot.buffer.updateLocal(frameToken(), packed, size_t(
bytes));
591 const uint32_t defaultAO = 0xFFu;
592 std::vector<uint32_t> aoDefaults;
594 aoDefaults.assign(
size_t(
count), defaultAO);
595 ao = aoDefaults.data();
597 const vk::DeviceSize aoBytes = vk::DeviceSize(
count) *
sizeof(uint32_t);
598 if (
slot.aoCapacityBytes <
size_t(aoBytes) || !
slot.aoBuffer.buffer) {
599 const size_t alloc = std::max(
size_t(aoBytes),
600 slot.aoCapacityBytes ?
slot.aoCapacityBytes * 2
602 slot.aoBuffer.allocate(frameToken(), device, vk::BufferUsageFlagBits::eVertexBuffer,
603 vk::DeviceSize(alloc),
604 vk::MemoryPropertyFlagBits::eHostVisible |
605 vk::MemoryPropertyFlagBits::eHostCoherent);
606 slot.aoCapacityBytes = alloc;
608 slot.aoBuffer.updateLocal(frameToken(),
ao, size_t(aoBytes));
611 pc.viewProj = mesh3dFrameUbo.
mvp;
612 pc.chunkOrigin = glm::vec4(originX, originY, originZ,
float(face));
613 pc.atlasInfo = glm::vec4(
float(std::max(1, tilesPerRow)), 0.f, 0.f, 0.f);
614 pc.tint = mesh3dFrameUbo.
tint;
616 auto &cb = currentPresentCb();
617 vk::DescriptorSet set = voxelRectSetFor(gpuTex);
618 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, voxelRectPipeline);
619 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, voxelRectPipelineLayout, 0, 1, &set, 0,
621 cb.pushConstants(voxelRectPipelineLayout, vk::ShaderStageFlagBits::eVertex, 0,
sizeof(VoxelRectPC),
624 vk::Buffer vbufs[3] = {voxelUnitQuadVerts.buffer,
slot.buffer.buffer,
slot.aoBuffer.buffer};
625 vk::DeviceSize offsets[3] = {0, 0, 0};
626 cb.bindVertexBuffers(0, 3, vbufs, offsets);
627 cb.bindIndexBuffer(voxelUnitQuadIndices.buffer, 0, vk::IndexType::eUint32);
628 cb.drawIndexed(6, uint32_t(
count), 0, 0, 0);
634 mesh3dVirtualAtlas.z =
enabled ? 1.f : 0.f;
641 int atlasSlotsX,
int atlasSlotsY,
642 float borderFraction) {
643 mesh3dVirtualTexture =
644 enabled ? glm::vec4(1.f,
float(pageCountX),
float(pageCountY), borderFraction)
646 const float packedNormalMask = mesh3dVirtualAtlas.z;
647 mesh3dVirtualAtlas =
enabled ? glm::vec4(
float(atlasSlotsX),
float(atlasSlotsY), packedNormalMask, 0.f)
648 : glm::vec4(0.f, 0.f, packedNormalMask, 0.f);
659 if (!sceneColorPassOpen || sceneColorSlots.size() < 2 || !sceneColorResumeRenderPass ||
660 sceneColorSamples != vk::SampleCountFlagBits::e1)
664 const size_t sourceIndex = currentFrameSlot() % sceneColorSlots.size();
665 const size_t snapshotIndex = (sourceIndex + 1u) % sceneColorSlots.size();
666 SceneColorSlot &
source = sceneColorSlots[sourceIndex];
667 SceneColorSlot &
snapshot = sceneColorSlots[snapshotIndex];
668 auto &cb = currentPresentCb();
671 sceneColorPassOpen =
false;
672 source.color.endSampledLayout();
673 const vk::ImageSubresourceRange
range{vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
674 std::array<vk::ImageMemoryBarrier, 2> before{};
675 before[0] = vk::ImageMemoryBarrier(vk::AccessFlagBits::eColorAttachmentWrite, vk::AccessFlagBits::eTransferRead,
676 vk::ImageLayout::eShaderReadOnlyOptimal, vk::ImageLayout::eTransferSrcOptimal,
677 VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED,
source.color.image(),
range);
678 before[1] = vk::ImageMemoryBarrier(
679 snapshot.color.currentLayout() == vk::ImageLayout::eUndefined ? vk::AccessFlags{}
680 : vk::AccessFlagBits::eShaderRead,
681 vk::AccessFlagBits::eTransferWrite,
snapshot.color.currentLayout(), vk::ImageLayout::eTransferDstOptimal,
682 VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED,
snapshot.color.image(),
range);
683 cb.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eFragmentShader,
684 vk::PipelineStageFlagBits::eTransfer, {}, {}, {}, before);
685 vk::ImageCopy copy{};
686 copy.srcSubresource =
687 vk::ImageSubresourceLayers{vk::ImageAspectFlagBits::eColor, 0, 0, 1};
688 copy.dstSubresource =
689 vk::ImageSubresourceLayers{vk::ImageAspectFlagBits::eColor, 0, 0, 1};
690 copy.extent = vk::Extent3D{
static_cast<uint32_t
>(sceneColorWidth),
691 static_cast<uint32_t
>(sceneColorHeight), 1};
692 cb.copyImage(
source.color.image(), vk::ImageLayout::eTransferSrcOptimal,
693 snapshot.color.image(), vk::ImageLayout::eTransferDstOptimal, 1, ©);
694 std::array<vk::ImageMemoryBarrier, 2> after{};
696 vk::ImageMemoryBarrier(vk::AccessFlagBits::eTransferRead,
697 vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite,
698 vk::ImageLayout::eTransferSrcOptimal, vk::ImageLayout::eColorAttachmentOptimal,
699 VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED,
source.color.image(),
range);
700 after[1] = vk::ImageMemoryBarrier(vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eShaderRead,
701 vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal,
702 VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED,
snapshot.color.image(),
range);
703 cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
704 vk::PipelineStageFlagBits::eFragmentShader | vk::PipelineStageFlagBits::eColorAttachmentOutput,
706 source.color.setCurrentLayout(vk::ImageLayout::eColorAttachmentOptimal);
707 snapshot.color.setCurrentLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
708 source.depth.setLayout(cb, vk::ImageLayout::eDepthStencilAttachmentOptimal,
709 vk::ImageAspectFlagBits::eDepth);
710 vk::RenderPassBeginInfo resume{};
711 resume.renderPass = sceneColorResumeRenderPass;
712 resume.framebuffer =
source.framebuffer;
714 vk::Rect2D{{0, 0}, {
static_cast<uint32_t
>(sceneColorWidth),
715 static_cast<uint32_t
>(sceneColorHeight)}};
716 cb.beginRenderPass(resume, vk::SubpassContents::eInline);
717 source.color.beginColorAttachment();
718 source.depth.beginDepthAttachment();
719 sceneColorPassOpen =
true;
720 completedSceneColorSlot = snapshotIndex;
721 sceneColorHistoryValid =
true;
726 mesh3dEnvTexture = cube;
727 mesh3dEnvIntensity = intensity < 0.f ? 0.f : intensity;
728 if (!cube) mesh3dEnvIntensity = 0.f;
732 mesh3dEnvProbeCenter =
center;
733 mesh3dEnvProbeExtent = glm::max(extent, glm::vec3(0.f));
734 mesh3dFrameUbo.
envProbeCenter = glm::vec4(mesh3dEnvProbeCenter, 1.f);
735 mesh3dFrameUbo.
envProbeExtent = glm::vec4(mesh3dEnvProbeExtent, 0.f);
739 mesh3dReflectionProbes = upload;
747 mesh3dSkinInfluenceLimit =
static_cast<int>(
count);
753 createShadowResources();
755 throw Exception(
"beginShadowPass: cascadeIndex out of range");
757 shadowPassCascade = cascadeIndex;
758 shadowPassDraws.clear();
762 if (shadowPassCascade < 0)
throw Exception(
"drawMeshShadow: call beginShadowPass first");
768 prepareSkinPass(
mesh,
nullptr, lightMVP, glm::mat4(1.f), glm::vec4(0.f),
d.skinSet,
770 shadowPassDraws.push_back(
d);
776 if (shadowPassCascade < 0)
throw Exception(
"drawMeshShadowAlpha: call beginShadowPass first");
777 if (!
mesh || !
mesh->gpuHandle)
throw Exception(
"drawMeshShadowAlpha: null mesh");
785 lodDither ? 1.f : 0.f, 0.f);
786 prepareSkinPass(
mesh,
albedo, lightMVP, glm::mat4(1.f),
d.lodFade,
d.skinSet,
788 shadowPassDraws.push_back(
d);
792 if (shadowPassCascade < 0)
throw Exception(
"endShadowPass: no active shadow pass");
793 if (!shadowPipeline || !shadowRenderPass) {
794 shadowPassCascade = -1;
795 shadowPassDraws.clear();
798 const int cascade = shadowPassCascade;
799 shadowCascadeDraws[cascade] = std::move(shadowPassDraws);
800 shadowPassDraws.clear();
801 shadowPassCascade = -1;
802 shadowPendingMask |= (1u << cascade);
810 if (!initialized)
throw Exception(
"beginGBufferPass: graphics not initialized");
811 if (
w <= 0 ||
h <= 0)
throw Exception(
"beginGBufferPass: invalid size");
812 if (!texSetLayout || !descriptorPool)
813 throw Exception(
"beginGBufferPass: textured descriptor layout not ready");
814 createGBufferResources(
w,
h);
815 gbufferPassActive =
true;
816 gbufferPassDraws.clear();
820 Texture *
albedo,
float tintR,
float tintG,
float tintB,
float motionX,
float motionY,
822 if (!gbufferPassActive)
throw Exception(
"drawMeshGBuffer: call beginGBufferPass first");
828 const glm::mat3
normal = glm::transpose(glm::inverse(glm::mat3(
model)));
832 auto u6 = [](
float x) -> uint32_t {
833 return uint32_t(std::lround(std::clamp(
x, 0.f, 1.f) * 63.f));
838 const uint32_t rough7 = uint32_t(std::lround(std::clamp(
roughness, 0.f, 1.f) * 127.f));
839 const uint32_t metal7 = uint32_t(std::lround(std::clamp(
metallic, 0.f, 1.f) * 127.f));
840 const uint32_t packedTint = u6(tintR) | (u6(tintG) << 6) | (u6(tintB) << 12) | (rough7 << 18) | (metal7 << 25);
841 auto motion12 = [](
float value) {
842 return uint32_t(std::lround(std::clamp(
value, -1.f, 1.f) * 2047.f)) + 2047u;
844 const uint32_t packedMotion = motion12(motionX) | (motion12(motionY) << 12);
845 d.push.clip = glm::vec4(nearZ, farZ, std::bit_cast<float>(packedTint),
float(packedMotion));
847 d.pbrClip = {nearZ, farZ, motionX, motionY};
853 gbufferPassDraws.push_back(
d);
857 Texture *
albedo,
float tintR,
float tintG,
float tintB,
float motionX,
859 if (!gbufferPassActive)
throw Exception(
"drawMeshGBufferAlpha: call beginGBufferPass first");
860 if (!
mesh || !
mesh->gpuHandle)
throw Exception(
"drawMeshGBufferAlpha: null mesh");
866 const glm::mat3
normal = glm::transpose(glm::inverse(glm::mat3(
model)));
870 auto u6 = [](
float x) -> uint32_t {
871 return uint32_t(std::lround(std::clamp(
x, 0.f, 1.f) * 63.f));
873 const uint32_t rough7 = uint32_t(std::lround(std::clamp(
roughness, 0.f, 1.f) * 127.f));
874 const uint32_t metal7 = uint32_t(std::lround(std::clamp(
metallic, 0.f, 1.f) * 127.f));
875 const uint32_t packedTint = u6(tintR) | (u6(tintG) << 6) | (u6(tintB) << 12) | (rough7 << 18) | (metal7 << 25);
876 auto motion12 = [](
float value) {
877 return uint32_t(std::lround(std::clamp(
value, -1.f, 1.f) * 2047.f)) + 2047u;
879 const uint32_t packedMotion = motion12(motionX) | (motion12(motionY) << 12);
880 d.push.clip = glm::vec4(nearZ, farZ, std::bit_cast<float>(packedTint),
float(packedMotion));
882 d.pbrClip = {nearZ, farZ, motionX, motionY};
888 gbufferPassDraws.push_back(
d);
892 if (!gbufferPassActive)
throw Exception(
"endGBufferPass: no active gbuffer pass");
893 gbufferPassActive =
false;
895 auto *
slot = currentGBufferSlot();
896 if (!gbufferPipeline || !gbufferRenderPass || !
slot || !
slot->framebuffer) {
897 gbufferPassDraws.clear();
898 gbufferPending =
false;
903 gbufferPending =
true;
905 rc->getGBuffer()->setTargets(gbufferWidth, gbufferHeight, &
slot->depthColorTex, &
slot->normalTex,
906 &
slot->albedoTex, &
slot->depthTex, &
slot->pbrParamsTex, &
slot->emissiveTex);
910void Graphics::ensureDecalPlaceholders() {
911 if (decalFlatAlbedo)
return;
912 const uint8_t transparent[4] = {0, 0, 0, 0};
913 const uint8_t flatNormal[4] = {128, 128, 255, 255};
914 const uint8_t neutralParams[4] = {128, 128, 0, 255};
915 decalFlatAlbedo =
newTexture(1, 1, transparent);
916 decalFlatNormal =
newTexture(1, 1, flatNormal);
917 decalFlatParams =
newTexture(1, 1, neutralParams);
922 if (!initialized)
throw Exception(
"beginDecalPass: graphics not initialized");
923 if (
w <= 0 ||
h <= 0)
throw Exception(
"beginDecalPass: invalid size");
924 if (!texSetLayout || !descriptorPool)
925 throw Exception(
"beginDecalPass: textured descriptor layout not ready");
926 createDecalResources(
w,
h);
927 ensureDecalPlaceholders();
928 decalPassActive =
true;
929 decalPassDraws.clear();
934 decalNear = nearZ > 1e-4f ? nearZ : 0.1f;
935 decalFar = farZ > decalNear ? farZ : decalNear + 1.f;
940 float normalStrength,
float roughnessStrength,
float metalStrength,
941 float emissiveStrength,
int blendMode,
int projectionMode,
942 float blendSharpness,
float parallaxScale,
float parallaxMinLayers,
943 float parallaxMaxLayers,
float edgeFadeWidth) {
944 if (!decalPassActive)
throw Exception(
"drawDecal: call beginDecalPass first");
951 for (
int i = 0; i < 4; ++i)
d.uvRect[i] = uvRect[i];
955 d.roughnessStrength = roughnessStrength;
956 d.metalStrength = metalStrength;
957 d.emissiveStrength = emissiveStrength;
958 d.blendMode = blendMode == 1 ? 1 : 0;
959 d.projectionMode = std::clamp(projectionMode, 0, 3);
960 d.blendSharpness = blendSharpness > 0.f ? blendSharpness : 4.f;
961 d.parallaxScale = std::clamp(parallaxScale, 0.f, 1.f);
962 d.parallaxMinLayers = std::clamp(parallaxMinLayers, 1.f, 64.f);
963 d.parallaxMaxLayers = std::clamp(parallaxMaxLayers,
d.parallaxMinLayers, 64.f);
964 d.edgeFadeWidth = std::clamp(edgeFadeWidth, 0.f, 0.49f);
965 if (decalPassDraws.size() >= kMaxDecalInstances)
return;
966 decalPassDraws.push_back(
d);
970 if (!decalPassActive)
throw Exception(
"endDecalPass: no active decal pass");
971 decalPassActive =
false;
972 auto *
slot = currentDecalSlot();
973 if (!decalPipeline || !decalRenderPass || !
slot || !
slot->framebuffer) {
974 decalPassDraws.clear();
975 decalPending =
false;
981void Graphics::recordDecalPass() {
982 if (!decalPending)
return;
983 decalPending =
false;
984 auto *
slot = currentDecalSlot();
985 if (!
slot || !decalPipeline || !decalRenderPass || !
slot->framebuffer) {
986 decalPassDraws.clear();
989 auto *gslot = currentGBufferSlot();
991 decalPassDraws.clear();
995 auto &cb = currentPresentCb();
996 recordDecalPassInto(cb, *
slot, *gslot);
999void Graphics::recordDecalPassInto(vk::CommandBuffer cb, DecalSlot &
slot, GBufferSlot &gslot) {
1000 const uint32_t
w = uint32_t(decalWidth);
1001 const uint32_t
h = uint32_t(decalHeight);
1002 if (
w == 0 ||
h == 0) {
1003 decalPassDraws.clear();
1007 DecalCameraUBO cam{};
1008 cam.viewProj = decalViewProj;
1009 cam.invViewProj = glm::inverse(decalViewProj);
1011 glm::vec4(decalNear, decalFar, 1.f /
float(
w), 1.f /
float(
h));
1012 updateRingLocal(
slot.cameraUbo, 0, &cam,
sizeof(cam));
1014 slot.albedo.beginColorAttachment();
1015 slot.normal.beginColorAttachment();
1016 slot.params.beginColorAttachment();
1017 std::array<vk::ClearValue, 3> clears{};
1018 clears[0].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
1019 clears[1].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
1020 clears[2].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
1021 vk::RenderPassBeginInfo rpBegin{};
1022 rpBegin.renderPass = decalRenderPass;
1023 rpBegin.framebuffer =
slot.framebuffer;
1024 rpBegin.renderArea = vk::Rect2D{{0, 0}, {
w,
h}};
1025 rpBegin.clearValueCount = uint32_t(clears.size());
1026 rpBegin.pClearValues = clears.data();
1027 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
1028 setViewportAndScissor(cb,
w,
h);
1029 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, decalPipeline);
1030 decalLayerFresh =
true;
1032 for (
const auto &
d : decalPassDraws) {
1033 GpuTexture *gpuAlb =
d.albedo &&
d.albedo->gpuHandle
1034 ?
static_cast<GpuTexture *
>(
d.albedo->gpuHandle)
1035 : static_cast<GpuTexture *>(decalFlatAlbedo->gpuHandle);
1036 GpuTexture *gpuNrm =
d.normal &&
d.normal->gpuHandle
1037 ?
static_cast<GpuTexture *
>(
d.normal->gpuHandle)
1038 : static_cast<GpuTexture *>(decalFlatNormal->gpuHandle);
1039 GpuTexture *gpuPrm =
d.params &&
d.params->gpuHandle
1040 ?
static_cast<GpuTexture *
>(
d.params->gpuHandle)
1041 : static_cast<GpuTexture *>(decalFlatParams->gpuHandle);
1042 DecalInstanceData inst{};
1043 inst.model =
d.model;
1044 inst.uvRect = glm::vec4(
d.uvRect[0],
d.uvRect[1],
d.uvRect[2],
d.uvRect[3]);
1046 glm::vec4(
d.fade,
d.normalStrength,
d.roughnessStrength,
d.metalStrength);
1047 inst.extraParams = glm::vec4(
d.emissiveStrength,
float(
d.blendMode),
1048 float(
d.projectionMode),
d.blendSharpness);
1049 inst.surfaceParams =
1050 glm::vec4(
d.parallaxScale,
d.parallaxMinLayers,
d.parallaxMaxLayers,
d.edgeFadeWidth);
1051 const vkb::BoundSet set = decalSetFor(
slot, gpuAlb, gpuNrm, gpuPrm, &gslot.depthGpu,
1053 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, decalPipelineLayout, 0, 1,
1054 set.ptr(), 0,
nullptr);
1055 cb.pushConstants(decalPipelineLayout,
1056 vk::ShaderStageFlagBits::eVertex |
1057 vk::ShaderStageFlagBits::eFragment,
1058 0,
sizeof(inst), &inst);
1059 cb.draw(3, 1, 0, 0);
1061 decalPassDraws.clear();
1063 slot.albedo.endSampledLayout();
1064 slot.normal.endSampledLayout();
1065 slot.params.endSampledLayout();
1068void Graphics::ensureDefaultEnvCubemap() {
1069 if (defaultEnvCubemap)
return;
1070 const uint8_t black[4] = {0, 0, 0, 255};
1071 std::vector<uint8_t> faces(6u * 4u);
1072 for (
int i = 0; i < 6; ++i) {
1073 faces[size_t(i) * 4u + 0] = black[0];
1074 faces[size_t(i) * 4u + 1] = black[1];
1075 faces[size_t(i) * 4u + 2] = black[2];
1076 faces[size_t(i) * 4u + 3] = black[3];
1078 defaultEnvCubemap =
newCubemap(1, faces.data());
1090 const std::string &alphaTechnique) {
1091 mesh3dSurfaceMode = mode;
1092 mesh3dSurfaceBlend =
blend;
1093 mesh3dSurfaceDepthWrite = depthWrite;
1095 mesh3dAlphaCutoff = std::clamp(
alphaCutoff, 0.f, 1.f);
1096 mesh3dAlphaTechnique = alphaTechnique;
1100 mesh3dTexBombScale = cellScale > 1e-3f ? cellScale : 1e-3f;
1102 mesh3dTexBombRot = rotAmount < 0.f ? 0.f : (rotAmount > 1.f ? 1.f : rotAmount);
1104 glm::vec4(mesh3dTexBombScale, mesh3dTexBombStrength, mesh3dTexBombRot, 0.f);
1108 mesh3dParallaxScale =
scale < 0.f ? 0.f : (
scale > 0.25f ? 0.25f :
scale);
1109 float minL = minLayers < 1.f ? 1.f : minLayers;
1110 float maxL = maxLayers < minL ? minL : maxLayers;
1111 if (maxL > 64.f) maxL = 64.f;
1112 mesh3dParallaxMinLayers = minL;
1113 mesh3dParallaxMaxLayers = maxL;
1115 glm::vec4(mesh3dParallaxScale, mesh3dParallaxMinLayers, mesh3dParallaxMaxLayers, 0.f);
1119 mesh3dLodFade = glm::vec4(std::clamp(
weight, 0.f, 1.f), reverse ? 1.f : 0.f,
1121 mesh3dFrameUbo.
lodFade = mesh3dLodFade;
1125 mesh3dLighting =
pack;
1127 for (
size_t i = 0; i <
pack.diffuseProbeSh.size(); ++i)
1130 for (
size_t i = 0; i <
pack.diffuseVolumePosition.size(); ++i) {
1134 for (
size_t i = 0; i <
pack.diffuseVolumeSh.size(); ++i)
1140 for (
int i = 0; i <
n; ++i) {
1141 if (
pack.lights[i].posRadius.w <= 0.f) {
1147 glm::vec3
d(
pack.lights[dirI].posRadius);
1148 if (glm::length(
d) < 1e-6f)
d = glm::vec3(0.f, 1.f, 0.f);
1149 else d = glm::normalize(
d);
1150 mesh3dFrameUbo.
lightDir = glm::vec4(
d,
float(
n));
1152 glm::vec4(glm::vec3(
pack.lights[dirI].color), mesh3dFrameUbo.
lightColor.w);
1155 mesh3dFrameUbo.
lightDir = glm::vec4(0.f, 1.f, 0.f,
float(
n));
1157 glm::vec4(0.f, 0.f, 0.f, mesh3dFrameUbo.
lightColor.w);
1162 float windAngle,
float coverage,
float detail) {
1163 mesh3dFrameUbo.
cloud = glm::vec4(std::clamp(
strength, 0.f, 1.f), std::max(worldCell, 1e-4f),
1165 mesh3dFrameUbo.
cloudWind = glm::vec4(std::cos(windAngle) * windSpeed,
1166 std::sin(windAngle) * windSpeed,
1170void Graphics::ensureFlatNormalTexture3D() {
1171 if (flatNormalTexture3D)
return;
1172 const uint8_t
px[4] = {128, 128, 255, 255};
1176void Graphics::ensureFlatHeightTexture3D() {
1177 if (flatHeightTexture3D)
return;
1179 const uint8_t
px[4] = {128, 128, 128, 255};
1183vkb::BoundSet Graphics::mesh3dSetFor(GpuTexture *gpuTex, GpuTexture *normalTex, GpuTexture *envTex,
1184 GpuTexture *heightTex, GpuTexture *depthTex, GpuTexture *sceneColorTex,
1185 GpuTexture *decalAlbedo, GpuTexture *decalNormal, GpuTexture *decalParams,
1186 Mesh3dFrameSlots &fslots, vk::DescriptorSetLayout resourceLayout) {
1187 ASSERT(gpuTex !=
nullptr);
1188 ASSERT(normalTex !=
nullptr);
1189 ASSERT(envTex !=
nullptr);
1190 ASSERT(heightTex !=
nullptr);
1191 ASSERT(sceneColorTex !=
nullptr);
1192 ASSERT(decalAlbedo !=
nullptr);
1193 ASSERT(decalNormal !=
nullptr);
1194 ASSERT(decalParams !=
nullptr);
1195 ASSERT(currentShadowArrayView());
1196 ASSERT(fslots.uboRing.buffer);
1197 ASSERT(fslots.shadowRing.buffer);
1199 auto probeTexture = [&](
int index) -> GpuTexture * {
1203 auto *
gpu =
static_cast<GpuTexture *
>(
texture->gpuHandle);
1204 if (
gpu->isCube)
return gpu;
1207 return static_cast<GpuTexture *
>(defaultEnvCubemap->
gpuHandle);
1209 GpuTexture *probe0 = probeTexture(0);
1210 GpuTexture *probe1 = probeTexture(1);
1211 Mesh3dSetKey
key{gpuTex, normalTex, envTex, probe0, probe1, heightTex, depthTex, sceneColorTex,
1212 decalAlbedo, decalNormal, decalParams};
1213 key.paletteSlot = fslots.activePalette;
1214 key.resourceProgram = bool(resourceLayout);
1215 if (fslots.palettes.empty()) uploadSkinPalette(
nullptr, fslots);
1216 auto it = fslots.sets.find(
key);
1217 if (it != fslots.sets.end())
return it->second;
1219 vk::DescriptorSetAllocateInfo alloc{};
1220 alloc.descriptorPool = descriptorPool;
1221 alloc.descriptorSetCount = 1;
1222 alloc.pSetLayouts = resourceLayout ? &resourceLayout : &mesh3dSetLayout;
1223 vkb::UnboundSet unbound{device->allocateDescriptorSets(alloc).front()};
1225 if (resourceLayout) {
1226 vkb::DescriptorSetUpdater updater(3, 2, 0);
1227 updater.beginDescriptorSet(unbound)
1228 .beginBuffers(0, 0, vk::DescriptorType::eUniformBufferDynamic)
1229 .buffer(fslots.uboRing.buffer, 0,
sizeof(Mesh3DUBO))
1230 .beginBuffers(4, 0, vk::DescriptorType::eUniformBufferDynamic)
1231 .buffer(fslots.shadowRing.buffer, 0,
sizeof(ShadowUBO))
1232 .beginBuffers(21, 0, vk::DescriptorType::eStorageBuffer)
1233 .buffer(fslots.palettes[fslots.activePalette].buffer, 0, fslots.palettes[fslots.activePalette].capacity)
1234 .beginImages(1, 0, vk::DescriptorType::eCombinedImageSampler)
1235 .image(vkb::SampledImage::forLaterSample(gpuTex->sampler, gpuTex->imageView()))
1236 .beginImages(18, 0, vk::DescriptorType::eCombinedImageSampler)
1237 .image(vkb::SampledImage::forLaterSample(sceneColorTex->sampler, sceneColorTex->imageView()))
1238 .update(device.instance);
1239 auto bound = std::move(unbound).publish();
1240 fslots.sets.emplace(
key, bound);
1243 vkb::DescriptorSetUpdater updater(16, 16, 0);
1244 updater.beginDescriptorSet(unbound)
1245 .beginBuffers(0, 0, vk::DescriptorType::eUniformBufferDynamic)
1246 .buffer(fslots.uboRing.buffer, 0,
sizeof(Mesh3DUBO))
1247 .beginBuffers(21, 0, vk::DescriptorType::eStorageBuffer)
1248 .buffer(fslots.palettes[fslots.activePalette].buffer, 0, fslots.palettes[fslots.activePalette].capacity)
1249 .beginImages(1, 0, vk::DescriptorType::eCombinedImageSampler)
1250 .image(vkb::SampledImage::forLaterSample(gpuTex->sampler, gpuTex->imageView()))
1251 .beginImages(2, 0, vk::DescriptorType::eCombinedImageSampler)
1252 .image(vkb::SampledImage::forLaterSample(normalTex->sampler, normalTex->imageView()))
1253 .beginImages(3, 0, vk::DescriptorType::eCombinedImageSampler)
1254 .image(vkb::SampledImage::forLaterSample(envTex->sampler, envTex->imageView()))
1255 .beginBuffers(4, 0, vk::DescriptorType::eUniformBufferDynamic)
1256 .buffer(fslots.shadowRing.buffer, 0,
sizeof(ShadowUBO))
1257 .beginImages(5, 0, vk::DescriptorType::eCombinedImageSampler)
1258 .image(vkb::SampledImage::forLaterSample(shadowSampler, currentShadowArrayView()))
1259 .beginImages(6, 0, vk::DescriptorType::eCombinedImageSampler)
1260 .image(vkb::SampledImage::forLaterSample(heightTex->sampler, heightTex->imageView()))
1261 .beginImages(7, 0, vk::DescriptorType::eCombinedImageSampler)
1262 .image(vkb::SampledImage::forLaterSample(depthTex->sampler, depthTex->imageView()))
1263 .beginImages(8, 0, vk::DescriptorType::eCombinedImageSampler)
1264 .image(vkb::SampledImage::forLaterSample(decalAlbedo->sampler, decalAlbedo->imageView()))
1265 .beginImages(9, 0, vk::DescriptorType::eCombinedImageSampler)
1266 .image(vkb::SampledImage::forLaterSample(decalNormal->sampler, decalNormal->imageView()))
1267 .beginImages(10, 0, vk::DescriptorType::eCombinedImageSampler)
1268 .image(vkb::SampledImage::forLaterSample(decalParams->sampler, decalParams->imageView()))
1269 .beginImages(16, 0, vk::DescriptorType::eCombinedImageSampler)
1270 .image(vkb::SampledImage::forLaterSample(probe0->sampler, probe0->imageView()))
1271 .beginImages(17, 0, vk::DescriptorType::eCombinedImageSampler)
1272 .image(vkb::SampledImage::forLaterSample(probe1->sampler, probe1->imageView()))
1273 .beginImages(18, 0, vk::DescriptorType::eCombinedImageSampler)
1274 .image(vkb::SampledImage::forLaterSample(sceneColorTex->sampler, sceneColorTex->imageView()))
1275 .beginImages(20, 0, vk::DescriptorType::eCombinedImageSampler)
1276 .image(vkb::SampledImage::forLaterSample(shadowRawSampler, currentShadowArrayView()))
1277 .update(device.instance);
1279 vkb::BoundSet bound = std::move(unbound).publish();
1280 fslots.sets.emplace(
key, bound);
1293 const float n = nearZ > 1e-4f ? nearZ : 0.1f;
1294 const float f = farZ >
n ? farZ :
n + 1.f;
graphics::Texture * albedo
std::vector< std::uint32_t > indices
std::array< float, 3 > scale
std::shared_ptr< OceanGpuSpectrum > gpu
std::vector< ParticleBakeMaterial > bindings
Local-probe upload record kept off the high-fanout IGraphics3D header.
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
const AssetImportLimits & limits
EVENGINE_API_FOUNDATION public API.
void ensureFileTexturesReady()
Finish CPU decode and GPU upload for outstanding newTextureFromFile results. @thread Game/render thre...
Mesh3DSceneColorCaptureStatus
Observable result of requesting a same-frame mesh SceneColor snapshot.
RenderControl * getRenderControl()
Shared compilable 3D render control (features → pass list + GBuffer). Owned by Graphics; valid for th...
GPU mesh handle (+ optional CPU morph targets).
Declarative, compilable 3D render control.
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
void setMesh3DReflectionProbes(const ReflectionProbeUpload &upload) override
Sets the mesh 3 d reflection probes.
void beginShadowPass(int cascadeIndex) override
Begins shadow pass.
void begin3DFrame() override
Begins 3 d frame.
void setMesh3DParallax(float scale, float minLayers=8.f, float maxLayers=32.f) override
Sets the mesh 3 d parallax.
void setCloudShadows(float strength, float worldCell, float time, float windSpeed, float windAngle, float coverage, float detail) override
Sets the cloud shadows.
void drawMeshShadowAlpha(Mesh *mesh, const glm::mat4 &lightMVP, Texture *albedo=nullptr, bool doubleSided=true, float lodWeight=1.f, bool lodFadeReverse=false, bool lodDither=false) override
Draws mesh shadow alpha.
void drawVoxelFaceInstances(const uint32_t *packed, int count, float originX, float originY, float originZ, const std::string &faceDir, Texture *atlas, int tilesPerRow=16, const uint32_t *ao=nullptr) override
Draws voxel face instances.
void end3DFrameToCanvas() override
Ends 3 d frame to canvas.
void endDecalPass() override
Ends decal pass.
void setMesh3DShadowReceive(bool receive) override
Sets the mesh 3 d shadow receive.
void setMesh3DLighting(const Lighting3DPack &pack) override
Sets the mesh 3 d lighting.
void drawMeshGBufferAlpha(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ, Texture *albedo=nullptr, float tintR=1.f, float tintG=1.f, float tintB=1.f, float motionX=0.f, float motionY=0.f, float roughness=0.45f, float metallic=0.f, float tintA=1.f) override
Draws mesh g buffer alpha.
void setMesh3DEnv(Texture *cube, float intensity) override
Sets the mesh 3 d env.
Mesh3DSceneColorCaptureStatus captureMesh3DSceneColor() override
Capture mesh 3 d scene color.
void setDecalCamera(const glm::mat4 &viewProj, float nearZ, float farZ) override
Sets the decal camera.
void setMesh3DLodDither(float weight, bool reverse, bool enabled) override
Sets the mesh 3 d lod dither.
void waitForSharedGpuResources()
Block until all in-flight GPU work (all frames) has completed.
bool isCanvasActive() const override
True when canvas active.
void endGBufferPass() override
Ends g buffer pass.
void endShadowPass() override
Ends shadow pass.
void setMesh3DTexCellBomb(float cellScale, float strength, float rotAmount=1.f) override
Sets the mesh 3 d tex cell bomb.
void drawDecal(const glm::mat4 &model, Texture *albedo, Texture *normal, Texture *params, const float uvRect[4], float fade, float normalStrength, float roughnessStrength, float metalStrength, float emissiveStrength, int blendMode=0, int projectionMode=0, float blendSharpness=4.f, float parallaxScale=0.f, float parallaxMinLayers=8.f, float parallaxMaxLayers=24.f, float edgeFadeWidth=0.06f) override
Draws decal.
void setMesh3DSurface(SurfaceMode mode, BlendMode blend, bool depthWrite, bool doubleSided, float alphaCutoff, const std::string &alphaTechnique="cutoff") override
Sets the mesh 3 d surface.
void setMesh3DCameraPos(const glm::vec3 &eye) override
Sets the mesh 3 d camera pos.
void begin3DFrameToCanvas(Canvas *canvas) override
Begins 3 d frame to canvas.
void setMesh3DSceneColor(Texture *color) override
Sets the mesh 3 d scene color.
void setMesh3DViewProj(const glm::mat4 &viewProj) override
Sets the mesh 3 d view proj.
void drawMeshShadow(Mesh *mesh, const glm::mat4 &lightMVP, bool doubleSided=true) override
Draws mesh shadow.
void setMesh3DShadows(const ShadowUpload &upload) override
Sets the mesh 3 d shadows.
const vkb::BuiltRenderPass & getOffscreen3DRenderPass(bool hdr=false)
Returns the offscreen 3 d render pass.
void beginGBufferPass(int width, int height) override
Begins g buffer pass.
void setMesh3DLight(const glm::vec3 &dir, const glm::vec3 &color) override
Sets the mesh 3 d light.
void drawMeshGBuffer(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ, Texture *albedo=nullptr, float tintR=1.f, float tintG=1.f, float tintB=1.f, float motionX=0.f, float motionY=0.f, float roughness=0.45f, float metallic=0.f, float tintA=1.f) override
Draws mesh g buffer.
void setMesh3DHeightTexture(Texture *height) override
Sets the mesh 3 d height texture.
Texture * newCubemap(int faceSize, const uint8_t *rgbaFaces) override
Creates a cubemap. @ownership Caller deletes unless documented otherwise.
void setMesh3DView(const glm::mat4 &view) override
Sets the mesh 3 d view.
void setMesh3DVirtualTexture(bool enabled, int pageCountX, int pageCountY, int atlasSlotsX, int atlasSlotsY, float borderFraction) override
Sets the mesh 3 d virtual texture.
vkb::Device & getDevice()
Returns the device.
void setMesh3DNormalTexture(Texture *normal) override
Sets the mesh 3 d normal texture.
void setMesh3DClip(float nearZ, float farZ) override
Sets the mesh 3 d clip.
Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false) override
Creates a texture. @ownership Caller deletes unless documented otherwise.
void setMesh3DSceneDepth(Texture *depth) override
Sets the mesh 3 d scene depth.
void setMesh3DEnvProbe(const glm::vec3 ¢er, const glm::vec3 &extent) override
Sets the mesh 3 d env probe.
void setMesh3DPackedNormalMask(bool enabled) override
Sets the mesh 3 d packed normal mask.
void setMesh3DMaterial(float metallic, float roughness) override
Sets the mesh 3 d material.
void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth) override
Clears .
void setMesh3DSkinInfluenceLimit(SkinInfluenceLimit count) override
Sets the mesh 3 d skin influence limit.
FrameArena & currentFrameArena()
Per-frame arena for the current swapchain frame slot.
void beginDecalPass(int width, int height) override
Begins decal pass.
OffscreenCanvas public API.
vkb::ColorAttachmentImage & colorImage()
Color image.
SurfaceMode
How a 3D surface contributes to depth and color passes.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
SkinInfluenceLimit
Number of strongest vertex influences retained by GPU skinning.
std::vector< int64_t > attrs(const Node &n, const char *key, std::vector< int64_t > fallback)
Attrs.
BlendMode
Render-neutral 2D blend mode shared by graphics-facing modules.
Lighting3DPack public API.
static constexpr int kMaxLights
ReflectionProbeUpload public API.
static constexpr int kMapSize
static constexpr int kCascades
static constexpr int kTotalLayers
int cascadeMapSizes[ShadowConfig::kCascades]
Per-cascade render viewport edge length (texels); drives shadow pass viewport.
glm::vec4 diffuseVolumePosition[Lighting3DPack::kMaxDiffuseVolumeProbes]
glm::vec4 diffuseVolumeInfo
glm::vec4 diffuseProbeInfo
glm::vec4 diffuseProbeSh[9]
glm::vec4 diffuseVolumeExtent[Lighting3DPack::kMaxDiffuseVolumeProbes]
glm::vec4 diffuseVolumeSh[Lighting3DPack::kMaxDiffuseVolumeProbes *9]