11#include "graphics/shaders/pbr_gbuffer_frag_spv.inc"
12#include "graphics/shaders/pbr_gbuffer_separated_frag_spv.inc"
13#include "graphics/shaders/pbr_surface_frag_spv.inc"
14#include "graphics/shaders/pbr_surface_separated_frag_spv.inc"
15#include "graphics/shaders/pbr_surface_vert_spv.inc"
22void Graphics::releaseFramePostTargets() {
23 const bool empty = std::all_of(framePostTargets_.begin(), framePostTargets_.end(),
24 [](
const auto&
slots) { return slots.empty(); });
29 invalidateTextureBindings();
31 for (
auto&
slots : framePostTargets_) {
33 auto it = std::find_if(ownedCanvases.begin(), ownedCanvases.end(),
34 [
target](
const auto&
owned) { return owned.get() == target; });
35 if (it != ownedCanvases.end()) ownedCanvases.erase(it);
41Canvas& Graphics::prepareFramePostTarget(FramePostTarget
target,
int width,
int height) {
43 const size_t count = frameSlotCount();
44 const bool resized = std::any_of(framePostTargets_.begin(), framePostTargets_.end(), [&](
const auto&
slots) {
45 return !slots.empty() &&
46 (slots.size() != count || std::any_of(slots.begin(), slots.end(), [&](const Canvas* canvas) {
47 return canvas && (canvas->getWidth() != width || canvas->getHeight() != height);
50 if (resized) releaseFramePostTargets();
51 auto&
slots = framePostTargets_[
static_cast<size_t>(
target)];
53 auto& canvas =
slots[currentFrameSlot()];
55 if (!canvas)
throw Exception(
"Post-process frame target allocation failed");
59void Graphics::flushToOffscreen(OffscreenCanvas* canvas) {
61 auto solid = std::move(solidBatches);
62 auto textured = std::move(texturedBatches);
63 auto lit = std::move(litBatches);
67 texturedBatches.clear();
70 const Color cc = canvas->pendingClearColor();
71 const bool needClear = canvas->takePendingClear();
72 bool hasSolid =
false;
73 for (
const auto& sb : solid)
74 if (!sb.batch.empty()) hasSolid = true;
75 if (!hasSolid && textured.empty() && lit.empty() && !needClear)
return;
79 const bool frameLocal = canRecordPostSceneGpuWork() &&
80 std::any_of(framePostTargets_.begin(), framePostTargets_.end(), [&](
const auto&
slots) {
81 return currentFrameSlot() < slots.size() && slots[currentFrameSlot()] == canvas;
83 if (!frameLocal) waitForSharedGpuResources();
84 EV_PROFILE_MODULE(
"graphics", frameLocal ?
"Offscreen.FrameLocalRecord" :
"Offscreen.SharedRecord");
86 auto recordOffscreen = [&](vk::CommandBuffer cb) {
87 canvas->colorImage().setLayout(cb, vk::ImageLayout::eColorAttachmentOptimal);
89 vk::ClearValue cv{vk::ClearColorValue(std::array<float, 4>{cc.r, cc.g, cc.b, cc.a})};
90 vk::RenderPassBeginInfo rpBegin{};
91 rpBegin.renderPass = canvas->isHDR() ? hdrOffscreenRenderPass : offscreenRenderPass;
92 rpBegin.framebuffer = canvas->framebuffer();
93 rpBegin.renderArea.extent = vk::Extent2D{uint32_t(canvas->getWidth()), uint32_t(canvas->getHeight())};
94 rpBegin.clearValueCount = 1;
95 rpBegin.pClearValues = &cv;
96 canvas->colorImage().beginColorAttachment();
97 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
99 vk::ClearAttachment attachment{};
100 attachment.aspectMask = vk::ImageAspectFlagBits::eColor;
101 attachment.colorAttachment = 0;
102 attachment.clearValue = cv;
103 vk::ClearRect rect{};
104 rect.rect = rpBegin.renderArea;
106 cb.clearAttachments(attachment, rect);
109 setViewportAndScissor(cb, uint32_t(canvas->getWidth()), uint32_t(canvas->getHeight()));
111 std::vector<vkb::HostVertexBuffer>& solidBufs = offscreenBuffers.solidBufs;
112 std::vector<vkb::HostVertexBuffer>& texBufs = offscreenBuffers.texBufs;
113 size_t texBufIndex = 0;
114 const int vw = canvas->getWidth();
115 const int vh = canvas->getHeight();
117 auto offscreenTexPipe = [&](
BlendMode mode) -> vk::Pipeline {
120 return canvas->isHDR() ? hdrOffscreenAdditiveTexPipeline : offscreenAdditiveTexPipeline;
122 return canvas->isHDR() ? hdrOffscreenPremultipliedTexPipeline : offscreenPremultipliedTexPipeline;
124 return canvas->isHDR() ? hdrOffscreenMultiplyTexPipeline : offscreenMultiplyTexPipeline;
126 return canvas->isHDR() ? hdrOffscreenOpaqueTexPipeline : offscreenOpaqueTexPipeline;
128 default:
return canvas->isHDR() ? hdrOffscreenTexPipeline : offscreenTexPipeline;
131 auto offscreenSolidPipe = [&](
BlendMode mode) -> vk::Pipeline {
138 default:
return offscreenSolidPipeline;
142 auto drawOffscreenTextured = [&](TexturedBatch&
tb) {
143 if (
tb.batch.empty() || !
tb.texture || !
tb.texture->gpuHandle)
return;
144 auto*
gpu =
static_cast<GpuTexture*
>(
tb.texture->gpuHandle);
145 vk::DescriptorSet texSet =
gpu->descriptorSet;
146 if ((
tb.depth &&
tb.depth->gpuHandle) || (
tb.motion &&
tb.motion->gpuHandle) ||
147 (
tb.extra &&
tb.extra->gpuHandle)) {
148 auto* depthGpu =
tb.depth ?
static_cast<GpuTexture*
>(
tb.depth->gpuHandle) : nullptr;
149 auto* motionGpu =
tb.motion ?
static_cast<GpuTexture*
>(
tb.motion->gpuHandle) : nullptr;
150 auto* extraGpu =
tb.extra ?
static_cast<GpuTexture*
>(
tb.extra->gpuHandle) : nullptr;
151 auto* specularGpu =
tb.specular ?
static_cast<GpuTexture*
>(
tb.specular->gpuHandle) : nullptr;
152 if (vk::DescriptorSet combo = post2SetFor(
gpu, depthGpu, motionGpu, extraGpu, specularGpu))
155 Batcher ndc =
tb.batch;
157 std::vector<TexturedVertex> gpuVerts;
158 gpuVerts.reserve(ndc.vertices().size());
161 vk::Buffer vertexBuffer{};
162 vk::DeviceSize vertexOffset = 0;
163 if (canRecordPostSceneGpuWork()) {
165 auto& arena = currentFrameArena();
166 if (!arena.ensure(
device, 8u << 20,
167 vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eStorageBuffer |
168 vk::BufferUsageFlagBits::eIndirectBuffer | vk::BufferUsageFlagBits::eTransferDst))
169 throw Exception(
"Offscreen frame arena unavailable");
170 auto allocation = arena.alloc(gpuVerts.size() *
sizeof(TexturedVertex),
alignof(TexturedVertex));
171 if (!allocation.mapped)
throw Exception(
"Offscreen frame arena exhausted");
172 std::memcpy(allocation.mapped, gpuVerts.data(),
size_t(allocation.size));
173 vertexBuffer = arena.buffer();
174 vertexOffset = allocation.offset;
176 if (texBufIndex >= texBufs.size()) texBufs.emplace_back();
177 vkb::HostVertexBuffer& vb = texBufs[texBufIndex++];
178 vb.allocate<TexturedVertex>(frameToken(),
device, gpuVerts);
179 vertexBuffer = vb.buffer;
182 if (
tb.shader &&
tb.shader->gpuHandle) {
184 ensureShaderHdrOffscreenPipeline(
tb.shader);
186 ensureShaderOffscreenPipeline(
tb.shader);
187 auto* gs =
static_cast<GpuShader*
>(
tb.shader->gpuHandle);
188 vk::Pipeline alphaPipe = canvas->isHDR() ? gs->hdrOffscreenPipeline : gs->offscreenPipeline;
189 vk::Pipeline opaquePipe =
190 canvas->isHDR() ? gs->hdrOffscreenOpaquePipeline : gs->offscreenOpaquePipeline;
191 if (!alphaPipe)
return;
192 vk::Pipeline customPipeline =
tb.blend ==
BlendMode::Opaque && opaquePipe ? opaquePipe : alphaPipe;
193 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, customPipeline);
194 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, shaderPipelineLayout, 0, 1, &texSet, 0,
196 cb.pushConstants(shaderPipelineLayout,
197 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0,
200 vk::Pipeline pipe = offscreenTexPipe(
tb.blend);
202 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, pipe);
203 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, texPipelineLayout, 0, 1, &texSet, 0,
nullptr);
205 cb.bindVertexBuffers(0, 1, &vertexBuffer, &vertexOffset);
206 cb.draw(uint32_t(gpuVerts.size()), 1, 0, 0);
209 std::vector<bool> solidUploaded(solid.size(),
false);
210 auto uploadSolid = [&](
size_t idx) {
211 if (
idx >= solid.size() || solidUploaded[
idx] || solid[
idx].batch.empty())
return;
212 vk::Pipeline pipe = offscreenSolidPipe(solid[
idx].
blend);
214 Batcher ndc = solid[
idx].batch;
216 std::vector<ColorVertex> gpuVerts;
217 gpuVerts.reserve(ndc.vertices().size());
219 if (solidBufs.size() <=
idx) solidBufs.resize(
idx + 1);
220 solidBufs[
idx].allocate<ColorVertex>(frameToken(),
device, gpuVerts);
221 solidUploaded[
idx] =
true;
224 auto drawSolidSpan = [&](uint32_t batchIndex, uint32_t
begin, uint32_t
count) {
225 if (batchIndex >= solid.size() ||
count == 0 || solid[batchIndex].batch.empty())
return;
226 vk::Pipeline pipe = offscreenSolidPipe(solid[batchIndex].
blend);
228 uploadSolid(batchIndex);
229 vk::DeviceSize
offset = 0;
230 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, pipe);
231 cb.bindVertexBuffers(0, 1, solidBufs[batchIndex], &
offset);
235 const bool litOk = canvas->isHDR() ? bool(hdrOffscreenLitPipeline) : bool(offscreenLitPipeline);
236 if (!spans.empty()) {
237 for (
const auto& sp : spans) {
238 if (sp.kind == OverlayKind::Solid)
239 drawSolidSpan(sp.index, sp.vertBegin, sp.vertCount);
240 else if (sp.kind == OverlayKind::Textured && sp.index < textured.size())
241 drawOffscreenTextured(textured[sp.index]);
242 else if (sp.kind == OverlayKind::Lit && litOk && sp.index < lit.size()) {
243 std::vector<LitBatch> one;
244 one.push_back(std::move(lit[sp.index]));
245 drawLitBatches(cb, vw, vh, one, texBufs, texBufIndex,
true, canvas->isHDR());
249 for (
size_t i = 0; i < solid.size(); ++i) {
250 if (!solid[i].batch.empty()) drawSolidSpan(uint32_t(i), 0, uint32_t(solid[i].batch.vertices().size()));
252 for (
auto&
tb : textured) drawOffscreenTextured(
tb);
253 if (litOk) drawLitBatches(cb, vw, vh, lit, texBufs, texBufIndex,
true, canvas->isHDR());
257 canvas->colorImage().endSampledLayout();
259 if (canRecordPostSceneGpuWork()) {
260 recordOffscreen(currentPresentCb());
263 vkb::executeImmediately(
device.instance, uploadPool,
device.getQueue(vkb::QueueType::graphics),
274using detail::PbrUniformGpu;
275vk::SamplerAddressMode addressMode(uint32_t
value) {
276 return value == 33071 ? vk::SamplerAddressMode::eClampToEdge
277 :
value == 33648 ? vk::SamplerAddressMode::eMirroredRepeat
278 : vk::SamplerAddressMode::eRepeat;
280enum class PbrSamplerBinding { Combined, Separated };
281Result<PbrSamplerBinding> planPbrSamplerBinding(
size_t uniqueOrdinarySamplers,
const vk::PhysicalDeviceLimits&
limits) {
283 const auto supports = [&](uint32_t fragmentSamplers) {
284 return limits.maxPerStageDescriptorSamplers >= fragmentSamplers &&
285 limits.maxDescriptorSetSamplers >= fragmentSamplers + 3u &&
286 limits.maxPerStageDescriptorSampledImages >= 19u &&
limits.maxDescriptorSetSampledImages >= 22u;
288 if (uniqueOrdinarySamplers <= 15 && supports(16))
293 "PBR material exceeds the device sampler/image descriptor budget",
"graphics.pbr.samplers"));
295vk::Pipeline createPbrPipeline(vkb::Device&
device, vk::PipelineLayout
layout,
const vkb::BuiltRenderPass& pass,
297 bool alphaToCoverage,
bool separatedSamplers,
bool gbuffer) {
298 ShaderModulePair
shaders(
device, embeddedSpirv(pbr_surface_vert_spv),
299 gbuffer ? (separatedSamplers ? embeddedSpirv(pbr_gbuffer_separated_frag_spv)
300 : embeddedSpirv(pbr_gbuffer_frag_spv))
301 : (separatedSamplers ? embeddedSpirv(pbr_surface_separated_frag_spv)
302 : embeddedSpirv(pbr_surface_frag_spv)));
303 auto input = vkb::VertexInputStateBuilder();
304 input.addInputBinding<MeshVertex>();
309 input.input_attributes.emplace_back(0, 0, vk::Format::eR32G32B32Sfloat, uint32_t(offsetof(MeshVertex,
pos)));
310 input.input_attributes.emplace_back(1, 0, vk::Format::eR32G32B32Sfloat, uint32_t(offsetof(MeshVertex,
normal)));
311 input.input_attributes.emplace_back(2, 0, vk::Format::eR32G32Sfloat, uint32_t(offsetof(MeshVertex,
uv)));
312 input.input_attributes.emplace_back(3, 0, vk::Format::eR16G16B16A16Uint, uint32_t(offsetof(MeshVertex, joints)));
313 input.input_attributes.emplace_back(4, 0, vk::Format::eR32G32B32A32Sfloat, uint32_t(offsetof(MeshVertex,
weights)));
316 for (uint32_t i = 0; i < 11; ++i) {
317 input.input_bindings.emplace_back(i + 1, uint32_t(2 *
sizeof(
float)), vk::VertexInputRate::eVertex);
318 input.input_attributes.emplace_back(i + 5, i + 1, vk::Format::eR32G32Sfloat, 0);
320 auto attachment = makeBlendAttachment(
blend);
322 vk::PipelineColorBlendStateCreateInfo
color{};
323 std::array<vk::PipelineColorBlendAttachmentState, 5> attachments;
324 attachments.fill(attachment);
325 color.attachmentCount = gbuffer ? 5u : 1u;
326 color.pAttachments = attachments.data();
327 vk::PipelineMultisampleStateCreateInfo multisampling{};
328 multisampling.rasterizationSamples = samples;
329 multisampling.alphaToCoverageEnable = alphaToCoverage && samples != vk::SampleCountFlagBits::e1;
330 return device.createPipeline()
332 .setPipelineLayout(
layout)
333 .setVertexInputState(
input)
334 .setDynamicStatesViewportScissor()
335 .setRasterizer(vk::PolygonMode::eFill,
false,
false, 1.0f,
338 : vk::CullModeFlagBits::eBack),
339 vk::FrontFace::eCounterClockwise)
340 .setMultisampler(multisampling)
343 .setDepthStencil(true, depthWrite,
345 .setColorBlending(
color)
352 std::array<vk::DescriptorPool, 2>
pools{};
353 std::array<vk::DescriptorSet, 2>
sets{};
358 std::map<std::tuple<VkRenderPass, uint32_t, size_t, bool>, vk::Pipeline>
pipelines;
359 std::map<std::array<uint32_t, 4>, vk::Sampler>
samplers;
365 for (
auto pool :
draw->pools)
366 if (pool)
device.destroyDescriptorPool(pool);
372 if (setLayout)
device.destroyDescriptorSetLayout(setLayout);
376void Graphics::destroyPbrResources() { pbrResources_.reset(); }
377void Graphics::destroyPbrGBufferResources() {
378 if (!pbrResources_)
return;
381 auto&
r = *pbrResources_;
382 for (
auto it =
r.pipelines.begin(); it !=
r.pipelines.end();) {
383 if (std::get<0>(it->first) == VkRenderPass(gbufferRenderPass.handle)) {
384 device->destroyPipeline(it->second);
385 it =
r.pipelines.erase(it);
390 for (
auto&
frame :
r.gbufferFrames)
392 for (auto pool :
draw->pools)
393 if (pool)
device->destroyDescriptorPool(pool);
394 r.gbufferFrames.clear();
434 (array && std::uint32_t(
texture->layers) < minimumLayers))
440 auto ready = requireKind(
binding.texture,
"PBR texture",
false,
false);
441 if (!ready)
return ready;
444 auto ready = requireKind(
binding.texture,
"PBR detail texture",
false,
false);
445 if (!ready)
return ready;
447 for (
auto [
texture, role,
layer] : std::array<std::tuple<Texture*, const char*, std::uint32_t>, 4>{
452 auto ready = requireKind(
texture, role,
true,
false,
layer + 1u);
453 if (!ready)
return ready;
456 if (!ready)
return ready;
458 if (!ready)
return ready;
459 pbrSurface_ = *surface;
463 if (!pbrResources_) {
464 pbrResources_.reset(
new PbrResources());
465 auto&
r = *pbrResources_;
468 auto&
r = *pbrResources_;
469 auto& fslots = currentMesh3dFrameSlots();
471 auto frame = currentFrameSlot();
472 auto& frames = gbuffer ?
r.gbufferFrames :
r.frames;
473 if (frames.size() <=
frame) frames.resize(
frame + 1);
474 auto& draws = frames[
frame];
475 const auto index = gbuffer ? gbufferPassDraws.size() : fslots.drawIndex++;
476 while (draws.size() <=
index) draws.emplace_back(std::make_unique<PbrResources::Draw>());
478 const auto&
s = *pbrSurface_;
482 u.view = mesh3dFrameUbo.
view;
483 u.camera = glm::vec4(glm::vec3(mesh3dFrameUbo.
cameraPos),
s.anisotropyRotation);
485 u.ambient = glm::vec4(glm::vec3(mesh3dLighting.
ambient),
s.anisotropyStrength);
486 u.material = {mesh3dMetallic, mesh3dRoughness, float(
int(mesh3dSurfaceMode)),
487 std::clamp(mesh3dAlphaCutoff +
s.vegetationColor.globalAlphaThresholdOffset, 0.f, 1.f)};
490 u.emissive = {
s.emissive[0],
s.emissive[1],
s.emissive[2],
s.emissiveStrength};
491 u.specular = {
s.specularColor[0],
s.specularColor[1],
s.specularColor[2],
s.specularFactor};
492 u.coat = {
s.clearcoatFactor,
s.clearcoatRoughness,
s.clearcoatNormalScale,
s.ior};
493 u.colorMaskSecondary = {
s.colorMaskSecondary[0],
s.colorMaskSecondary[1],
s.colorMaskSecondary[2],
494 float(
s.normalMode)};
495 u.colorMaskParams = {
s.colorMaskEnabled ? 1.f : 0.f,
s.colorMaskMin,
s.colorMaskMax,
s.albedoTextureStrength};
496 const auto& trans =
s.translucency;
497 u.translucencyColor = {trans.color[0], trans.color[1], trans.color[2], trans.intensity};
498 u.translucencyParams = {trans.strength, trans.normalDistortion, trans.scattering, trans.direct};
499 u.translucencyLighting = {trans.ambient, trans.shadow, trans.maskAmount, trans.globalIntensity * trans.overlay};
500 u.translucencyMask = {trans.maskMinimum, trans.maskMaximum, 0, 0};
501 u.motionHighlightColor = {
s.motionHighlightColor[0],
s.motionHighlightColor[1],
s.motionHighlightColor[2],
502 s.vegetationColor.overlaySubsurface};
503 u.vegetationOverlay = {
s.vegetationColor.overlayColor[0],
s.vegetationColor.overlayColor[1],
504 s.vegetationColor.overlayColor[2],
s.vegetationColor.overlay};
505 u.vegetationWetness = {
s.vegetationColor.wetness,
s.vegetationColor.overlayNormalScale,
506 s.vegetationColor.wetnessNormalScale,
s.vegetationColor.overlaySmoothness};
507 u.vegetationStageParams = {
s.vegetationColor.overlayVariation,
s.vegetationColor.overlayProjection,
508 s.vegetationColor.vertexOcclusionAlpha,
s.vegetationColor.wetnessContrast};
509 u.vegetationFieldColor = {
s.vegetationColor.fieldColor[0],
s.vegetationColor.fieldColor[1],
510 s.vegetationColor.fieldColor[2],
s.vegetationColor.fieldColor[3]};
511 u.vegetationColorParams = {
s.vegetationColor.colorsCoverage,
s.vegetationColor.colorsIntensity,
512 s.vegetationColor.colorsMask,
s.vegetationColor.colorsVariation};
513 u.vegetationOcclusionParams = {
s.vegetationColor.vertexOcclusionMinimum,
s.vegetationColor.vertexOcclusionMaximum,
515 u.vegetationOcclusionColor = {
s.vegetationColor.vertexOcclusionColor[0],
s.vegetationColor.vertexOcclusionColor[1],
516 s.vegetationColor.vertexOcclusionColor[2],
517 float(
s.vegetationColor.backfaceNormalMode)};
518 u.vegetationGlobalMasks = {
s.vegetationColor.globalColorMaskMinimum,
s.vegetationColor.globalColorMaskMaximum,
519 s.vegetationColor.globalOverlayMaskMinimum,
s.vegetationColor.globalOverlayMaskMaximum};
520 const auto&
d =
s.vegetationDetail;
521 u.detailUv = {
d.uvScale[0],
d.uvScale[1],
d.uvOffset[0],
d.uvOffset[1]};
522 u.detailColor = {
d.color[0],
d.color[1],
d.color[2],
d.normalBlendValue};
523 u.detailColorTwo = {
d.colorTwo[0],
d.colorTwo[1],
d.colorTwo[2],
d.colorTwo[3]};
524 u.detailValues = {
d.value,
d.normalValue,
d.albedoValue,
d.metallicValue};
525 u.detailMaterial = {
d.occlusionValue,
d.smoothnessValue,
d.blendMinimum,
d.blendMaximum};
526 u.detailMasks = {
d.maskMinimum,
d.maskMaximum,
d.meshMinimum,
d.meshMaximum};
527 u.detailInfo = {
d.uvMode,
d.colorMode,
d.blendMode,
d.alphaMode};
528 uint32_t detailPresent = 0;
529 for (
size_t i = 0; i <
d.textures.size(); ++i)
530 if (
d.textures[i].texture) detailPresent |= 1u << i;
531 u.detailInfo2 = {
d.maskMode,
d.meshMode,
d.inverseUvScale ? 1u : 0
u, detailPresent};
532 const auto& extras =
s.vegetationExtras;
533 u.extrasCoords = {extras.coords[0], extras.coords[1], extras.coords[2], extras.coords[3]};
534 u.extrasFallback = {extras.fallback[0], extras.fallback[1], extras.fallback[2], extras.fallback[3]};
535 u.extrasUsage0 = {extras.usage[0], extras.usage[1], extras.usage[2], extras.usage[3]};
536 u.extrasUsage1 = {extras.usage[4], extras.usage[5], extras.usage[6], extras.usage[7]};
537 u.extrasUsage2 = {extras.usage[8], 0, 0, 0};
538 u.extrasInfo = {extras.layer, extras.usePivotPosition ? 1u : 0
u, extras.texture ? 1u : 0
u,
539 s.vegetationAlpha.enabled ? 1u : 0
u};
540 u.extrasUsage2.y =
s.vegetationAlpha.global;
541 u.extrasUsage2.z =
s.vegetationAlpha.variation;
542 u.extrasUsage2.w =
s.vegetationAlpha.detailFade ? 1.f : 0.f;
543 u.vegetationAlphaFade = {
s.vegetationAlpha.glancing,
s.vegetationAlpha.camera,
s.vegetationAlpha.constant,
544 s.vegetationAlpha.noiseTiling};
545 u.vegetationAlphaCamera = {
s.vegetationAlpha.cameraFadeMin,
s.vegetationAlpha.cameraFadeMax, 0, 0};
546 u.vegetationEmission = {
s.vegetationEmission.minimum,
s.vegetationEmission.maximum,
s.vegetationEmission.phase,
547 s.vegetationEmission.enabled ?
s.vegetationEmission.global : -1.f};
548 u.vegetationGradientOne = {
s.vegetationGradient.colorOne[0],
s.vegetationGradient.colorOne[1],
549 s.vegetationGradient.colorOne[2],
550 s.vegetationGradient.enabled ?
s.vegetationGradient.minimum : -1.f};
551 u.vegetationGradientTwo = {
s.vegetationGradient.colorTwo[0],
s.vegetationGradient.colorTwo[1],
552 s.vegetationGradient.colorTwo[2],
s.vegetationGradient.maximum};
553 const auto&
colors =
s.vegetationColors;
558 u.colorsUsage2 = {
colors.usage[8], 0, 0, 0};
560 const auto& vertex =
s.vegetationVertex;
561 u.vertexCoords = {vertex.coords[0], vertex.coords[1], vertex.coords[2], vertex.coords[3]};
562 u.vertexFallback = {vertex.fallback[0], vertex.fallback[1], vertex.fallback[2], vertex.fallback[3]};
563 u.vertexUsage0 = {vertex.usage[0], vertex.usage[1], vertex.usage[2], vertex.usage[3]};
564 u.vertexUsage1 = {vertex.usage[4], vertex.usage[5], vertex.usage[6], vertex.usage[7]};
565 u.vertexUsage2 = {vertex.usage[8], 0, 0, 0};
566 u.vertexSize = {vertex.globalSize, vertex.sizeFadeStart, vertex.sizeFadeEnd, vertex.distanceFadeBias};
567 u.vertexInfo = {vertex.layer, uint32_t(vertex.source), 0
u, 0
u};
568 const auto& motion =
s.vegetationMotion;
569 u.motionCoords = {motion.coords[0], motion.coords[1], motion.coords[2], motion.coords[3]};
570 u.motionFallback = {motion.fallback[0], motion.fallback[1], motion.fallback[2], motion.fallback[3]};
571 u.motionUsage0 = {motion.usage[0], motion.usage[1], motion.usage[2], motion.usage[3]};
572 u.motionUsage1 = {motion.usage[4], motion.usage[5], motion.usage[6], motion.usage[7]};
573 u.motionUsage2 = {motion.usage[8], 0, 0, 0};
574 u.motionGlobal0 = {motion.globalDirection[0], motion.globalDirection[1], motion.worldOrigin[0],
575 motion.worldOrigin[1]};
576 u.motionGlobal1 = {motion.worldOrigin[2], motion.dynamicMode, motion.rigidity, motion.facing};
577 u.motionTime = {float(motion.time), 0, 0, 0};
578 u.motionBending = {motion.bending, motion.bendingSpeed, motion.bendingScale, motion.bendingVariation};
579 u.motionBranch = {motion.branch, motion.rolling, motion.branchSpeed, motion.branchScale};
580 u.motionBranch2 = {motion.branchVariation, motion.globalBending, motion.globalBranch, motion.globalFlutter};
581 u.motionFlutter = {motion.flutter, motion.flutterSpeed, motion.flutterScale, motion.flutterVariation};
582 u.motionControl = {motion.noiseTiling, motion.interaction, motion.interactionMask, motion.fadeDistance};
583 u.motionPerspective = {motion.perspectivePush, motion.perspectiveNoise, motion.perspectiveAngle, 0};
584 u.motionInfo = {motion.layer, uint32_t(motion.mode), 0
u, 0
u};
585 const bool skinned =
mesh->hasGpuSkinning() &&
mesh->getSkinPaletteCount() > 0;
586 u.misc = {
s.normalScale,
s.occlusionStrength,
s.unlit ? 1.f : 0.f,
587 skinned ? float(
mesh->getSkinPaletteCount()) : 0.f};
588 for (
int i = 0; i < std::min(mesh3dLighting.
count, 8); ++i)
u.lights[i] = mesh3dLighting.
lights[i];
589 u.lights[0].color.w = mesh3dEnvTexture ? mesh3dEnvIntensity : 0;
590 std::map<uint32_t, size_t> offsets;
592 std::vector<float> coordinates(
size_t(
mesh->getVertexCount()) * 2, 0.f);
593 std::array<vk::DescriptorImageInfo, 11> images;
594 std::array<vk::DescriptorImageInfo, 3> detailImages;
595 for (
size_t i = 0; i < 11; ++i) {
596 const auto&
b =
s.textures[i];
597 uint32_t
offset = UINT32_MAX;
600 if (
values.empty() &&
b.texcoord != 0)
throw Exception(
"PBR texture references missing mesh UV channel");
602 auto found = offsets.find(
b.texcoord);
603 if (
found == offsets.end()) {
604 size_t start = coordinates.size() / 2;
605 offsets.emplace(
b.texcoord,
start);
606 coordinates.insert(coordinates.end(),
values.begin(),
values.end());
612 u.uvTransform[i] = {
b.offset[0],
b.offset[1],
b.scale[0],
b.scale[1]};
613 u.uvInfo[i] = {
b.rotation,
offset,
b.texture ? 1.f : 0.f,
b.srgbDecode ? 1.f : 0.f};
614 auto* tex =
static_cast<GpuTexture*
>((
b.texture ?
b.texture : whiteTexture)->gpuHandle);
615 if (tex->isCube)
throw Exception(
"PBR material texture must be two-dimensional");
616 const std::array<uint32_t, 4>
key{
b.wrapS,
b.wrapT,
b.minFilter,
b.magFilter};
618 if (
found ==
r.samplers.end()) {
619 vk::SamplerCreateInfo
info{};
620 info.magFilter =
b.magFilter == 9728 ? vk::Filter::eNearest : vk::Filter::eLinear;
621 info.minFilter = (
b.minFilter == 9728 ||
b.minFilter == 9984 ||
b.minFilter == 9986) ? vk::Filter::eNearest
623 info.mipmapMode =
b.minFilter >= 9986 ? vk::SamplerMipmapMode::eLinear : vk::SamplerMipmapMode::eNearest;
624 info.addressModeU = addressMode(
b.wrapS);
625 info.addressModeV = addressMode(
b.wrapT);
626 info.addressModeW = vk::SamplerAddressMode::eRepeat;
627 info.maxLod =
b.minFilter >= 9984 ? VK_LOD_CLAMP_NONE : 0;
630 images[i] = {
found->second, tex->imageView(), vk::ImageLayout::eShaderReadOnlyOptimal};
632 for (
size_t i = 0; i <
d.textures.size(); ++i) {
633 const auto&
b =
d.textures[i];
634 auto* tex =
static_cast<GpuTexture*
>((
b.texture ?
b.texture : whiteTexture)->gpuHandle);
635 if (tex->isCube)
throw Exception(
"PBR detail texture must be two-dimensional");
636 const std::array<uint32_t, 4>
key{
b.wrapS,
b.wrapT,
b.minFilter,
b.magFilter};
638 if (
found ==
r.samplers.end()) {
639 vk::SamplerCreateInfo
info{};
640 info.magFilter =
b.magFilter == 9728 ? vk::Filter::eNearest : vk::Filter::eLinear;
641 info.minFilter = (
b.minFilter == 9728 ||
b.minFilter == 9984 ||
b.minFilter == 9986) ? vk::Filter::eNearest
643 info.mipmapMode =
b.minFilter >= 9986 ? vk::SamplerMipmapMode::eLinear : vk::SamplerMipmapMode::eNearest;
644 info.addressModeU = addressMode(
b.wrapS);
645 info.addressModeV = addressMode(
b.wrapT);
646 info.addressModeW = vk::SamplerAddressMode::eRepeat;
647 info.maxLod =
b.minFilter >= 9984 ? VK_LOD_CLAMP_NONE : 0;
650 detailImages[i] = {
found->second, tex->imageView(), vk::ImageLayout::eShaderReadOnlyOptimal};
652 if (!extras.texture && !defaultExtrasArray) {
653 const std::array<uint16_t, 4> neutral{0x3c00u, 0
u, 0
u, 0x3c00u};
655 if (!
created.ok())
throw Exception(
"PBR could not create its neutral Extras array");
656 defaultExtrasArray =
created.value();
658 Texture* extrasTexture = extras.texture ? extras.texture : defaultExtrasArray;
659 auto* extrasGpu =
static_cast<GpuTexture*
>(extrasTexture->gpuHandle);
660 if (!extrasGpu->isArray || (extras.texture && extrasTexture->layers < 9))
661 throw Exception(
"PBR Extras texture must be a nine-layer 2D array");
662 vk::DescriptorImageInfo extrasImage{extrasGpu->sampler, extrasGpu->imageView(),
663 vk::ImageLayout::eShaderReadOnlyOptimal};
664 if (!
colors.texture && !defaultColorsArray) {
665 const std::array<uint16_t, 4> neutral{0x3c00u, 0x3c00u, 0x3c00u, 0
u};
667 if (!
created.ok())
throw Exception(
"PBR could not create its neutral Colors array");
668 defaultColorsArray =
created.value();
671 auto* colorsGpu =
static_cast<GpuTexture*
>(colorsTexture->gpuHandle);
672 if (!colorsGpu->isArray || (
colors.texture && colorsTexture->layers < 9))
673 throw Exception(
"PBR Colors texture must be a nine-layer 2D array");
674 vk::DescriptorImageInfo colorsImage{colorsGpu->sampler, colorsGpu->imageView(),
675 vk::ImageLayout::eShaderReadOnlyOptimal};
676 if (!vertex.texture && !defaultVertexArray) {
677 const std::array<uint16_t, 4> neutral{0
u, 0
u, 0
u, 0x3c00u};
679 if (!
created.ok())
throw Exception(
"PBR could not create its neutral Vertex array");
680 defaultVertexArray =
created.value();
682 Texture* vertexTexture = vertex.texture ? vertex.texture : defaultVertexArray;
683 auto* vertexGpu =
static_cast<GpuTexture*
>(vertexTexture->gpuHandle);
684 if (!vertexGpu->isArray || (vertex.texture && vertexTexture->layers < 9))
685 throw Exception(
"PBR Vertex texture must be a nine-layer 2D array");
689 throw Exception(
"PBR GPU vegetation deformation requires an unskinned object-mode mesh");
690 vk::DescriptorImageInfo vertexImage{vertexGpu->sampler, vertexGpu->imageView(),
691 vk::ImageLayout::eShaderReadOnlyOptimal};
692 if (!motion.texture && !defaultMotionArray) {
693 const std::array<uint16_t, 4> neutral{0x3c00u, 0
u, 0x3800u, 0
u};
695 if (!
created.ok())
throw Exception(
"PBR could not create its neutral Motion array");
696 defaultMotionArray =
created.value();
698 Texture* motionTexture = motion.texture ? motion.texture : defaultMotionArray;
699 auto* motionGpu =
static_cast<GpuTexture*
>(motionTexture->gpuHandle);
700 if (!motionGpu->isArray || (motion.texture && motionTexture->layers < 9))
701 throw Exception(
"PBR Motion texture must be a nine-layer 2D array");
702 vk::DescriptorImageInfo motionImage{motionGpu->sampler, motionGpu->imageView(),
703 vk::ImageLayout::eShaderReadOnlyOptimal};
704 Texture* noiseTexture = motion.noise ? motion.noise : whiteTexture;
705 auto* noiseGpu =
static_cast<GpuTexture*
>(noiseTexture->gpuHandle);
706 if (noiseGpu->isArray || noiseGpu->isCube)
throw Exception(
"PBR motion noise must be two-dimensional");
707 vk::DescriptorImageInfo noiseImage{noiseGpu->sampler, noiseGpu->imageView(),
708 vk::ImageLayout::eShaderReadOnlyOptimal};
709 if (!defaultVegetationFadeNoise) {
710 const std::array<uint8_t, 4> zero{0, 0, 0, 255};
712 if (!
created.ok())
throw Exception(
"PBR could not create its neutral vegetation fade volume");
713 defaultVegetationFadeNoise =
created.value();
715 Texture* fadeNoiseTexture =
s.vegetationAlpha.noise ?
s.vegetationAlpha.noise : defaultVegetationFadeNoise;
716 auto* fadeNoiseGpu =
static_cast<GpuTexture*
>(fadeNoiseTexture->gpuHandle);
717 if (!fadeNoiseGpu->isVolume)
throw Exception(
"PBR vegetation fade noise must be three-dimensional");
718 vk::DescriptorImageInfo fadeNoiseImage{fadeNoiseGpu->sampler, fadeNoiseGpu->imageView(),
719 vk::ImageLayout::eShaderReadOnlyOptimal};
720 if (coordinates.empty()) coordinates.resize(2);
722 const auto& tangents =
mesh->importedTangents();
723 const auto& bitangents =
mesh->importedBitangents();
724 if (tangents.size() !=
size_t(
mesh->getVertexCount()) * 3 || bitangents.size() != tangents.size())
725 throw Exception(
"PBR authored tangent frame does not match mesh vertices");
726 if (coordinates.size() > UINT32_MAX || tangents.size() > (UINT32_MAX - coordinates.size()) / 2)
727 throw Exception(
"PBR tangent stream exceeds addressable range");
728 u.tangentInfo = {uint32_t(coordinates.size()), 1, 0, 0};
729 for (
size_t i = 0; i < tangents.size(); i += 3) {
730 coordinates.insert(coordinates.end(), tangents.begin() + i, tangents.begin() + i + 3);
731 coordinates.insert(coordinates.end(), bitangents.begin() + i, bitangents.begin() + i + 3);
734 const auto highlights =
mesh->motionHighlights();
735 if (!highlights.empty()) {
736 auto valid =
mesh->validateMotionHighlights(highlights);
737 if (!
valid)
throw Exception(
"PBR motion highlights do not match mesh vertices");
738 if (coordinates.size() > UINT32_MAX || highlights.size() > UINT32_MAX - coordinates.size())
739 throw Exception(
"PBR highlight stream exceeds addressable range");
740 u.tangentInfo.z = uint32_t(coordinates.size());
742 coordinates.insert(coordinates.end(), highlights.begin(), highlights.end());
744 const auto vegetationFactors =
mesh->vegetationFactors();
745 if (!vegetationFactors.empty()) {
746 auto valid =
mesh->validateVegetationFactors(vegetationFactors);
747 if (!
valid)
throw Exception(
"PBR vegetation factors do not match mesh vertices");
748 if (coordinates.size() > UINT32_MAX || vegetationFactors.size() > UINT32_MAX - coordinates.size())
749 throw Exception(
"PBR vegetation factor stream exceeds addressable range");
750 u.vegetationInfo = {uint32_t(coordinates.size()), 1,
s.vegetationColor.invertVertexOcclusion ? 1u : 0
u,
751 s.vegetationColor.invertVertexOcclusionColors ? 1u : 0
u};
752 coordinates.insert(coordinates.end(), vegetationFactors.begin(), vegetationFactors.end());
754 const auto deformationFactors =
mesh->vegetationDeformationFactors();
755 if (!deformationFactors.empty()) {
756 auto valid =
mesh->validateVegetationDeformationFactors(deformationFactors);
757 if (!
valid)
throw Exception(
"PBR vegetation deformation factors do not match mesh vertices");
758 if (coordinates.size() > UINT32_MAX || deformationFactors.size() > UINT32_MAX - coordinates.size())
759 throw Exception(
"PBR vegetation deformation stream exceeds addressable range");
760 u.vertexInfo.z = uint32_t(coordinates.size());
762 coordinates.insert(coordinates.end(), deformationFactors.begin(), deformationFactors.end());
765 throw Exception(
"PBR GPU vegetation motion requires a nine-float rest-deformation stream");
766 const auto upload = [&](vkb::GenericBuffer&
buffer, vk::BufferUsageFlags
usage,
const void* data,
size_t bytes) {
767 if ((
usage & vk::BufferUsageFlagBits::eStorageBuffer) &&
768 bytes >
device.physical_device.properties.limits.maxStorageBufferRange)
769 throw Exception(
"PBR mesh storage exceeds device maxStorageBufferRange");
774 u.mvp = gbuffer->push.mvp;
775 u.material.x = gbuffer->pbrFactors.x;
776 u.material.y = gbuffer->pbrFactors.y;
777 u.material.z = gbuffer->alphaTest ? 1.f : 0.f;
778 u.lights[0].posRadius = gbuffer->pbrClip;
780 upload(
draw.uniform, vk::BufferUsageFlagBits::eUniformBuffer, &
u,
sizeof(
u));
781 upload(
draw.uv, vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eStorageBuffer,
782 coordinates.data(), coordinates.size() *
sizeof(
float));
784 upload(
draw.skin, vk::BufferUsageFlagBits::eStorageBuffer, skinned ?
mesh->skinPalette().data() : &
identity[0][0],
786 auto shadow = mesh3dShadows.
ubo;
787 if (!mesh3dShadows.
active) {
791 shadow.bias.z = mesh3dShadowReceive ? 1.f : 0.f;
792 upload(
draw.shadow, vk::BufferUsageFlagBits::eUniformBuffer, &shadow,
sizeof(shadow));
793 ensureDefaultEnvCubemap();
794 auto* env =
static_cast<GpuTexture*
>((mesh3dEnvTexture ? mesh3dEnvTexture : defaultEnvCubemap)->gpuHandle);
795 if (!env->isCube)
throw Exception(
"PBR environment must be a cubemap");
796 vk::DescriptorImageInfo envInfo{env->sampler, env->imageView(), vk::ImageLayout::eShaderReadOnlyOptimal};
797 vk::DescriptorImageInfo shadowInfo{shadowSampler, currentShadowArrayView(),
798 currentShadowMap().image.currentLayout()};
801 std::array<vk::DescriptorImageInfo, 18> ordinaryImages{};
802 std::copy(images.begin(), images.end(), ordinaryImages.begin());
803 std::copy(detailImages.begin(), detailImages.end(), ordinaryImages.begin() + 11);
804 ordinaryImages[14] = envInfo;
805 ordinaryImages[15] = extrasImage;
806 ordinaryImages[16] = colorsImage;
807 ordinaryImages[17] = fadeNoiseImage;
808 std::vector<vk::Sampler> uniqueSamplers;
809 std::array<uint32_t, 20> samplerSlots{};
810 for (
size_t role = 0; role < ordinaryImages.size(); ++role) {
811 const auto sampler = ordinaryImages[role].sampler;
812 auto found = std::find(uniqueSamplers.begin(), uniqueSamplers.end(),
sampler);
813 if (
found == uniqueSamplers.end()) {
814 samplerSlots[role] = uint32_t(uniqueSamplers.size());
815 uniqueSamplers.push_back(
sampler);
817 samplerSlots[role] = uint32_t(
found - uniqueSamplers.begin());
822 const auto binding = planPbrSamplerBinding(uniqueSamplers.size(),
device.physical_device.properties.limits)
823 .expect(
"Cannot draw PBR material");
824 const bool separatedSamplers =
binding == PbrSamplerBinding::Separated;
825 const size_t mode = separatedSamplers ? 1u : 0
u;
826 if (!
r.setLayouts[mode]) {
827 const auto both = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment;
828 const auto fragment = vk::ShaderStageFlagBits::eFragment;
829 const auto vertex = vk::ShaderStageFlagBits::eVertex;
833 std::vector<vk::DescriptorSetLayoutBinding>
bindings{
834 {0, vk::DescriptorType::eUniformBuffer, 1, both},
835 {14, vk::DescriptorType::eCombinedImageSampler, 11, fragment},
836 {3, vk::DescriptorType::eStorageBuffer, 1, vertex},
837 {4, vk::DescriptorType::eCombinedImageSampler, 1, fragment},
838 {5, vk::DescriptorType::eUniformBuffer, 1, fragment},
839 {6, vk::DescriptorType::eCombinedImageSampler, 1, fragment},
840 {15, vk::DescriptorType::eCombinedImageSampler, 3, fragment},
841 {8, vk::DescriptorType::eCombinedImageSampler, 1, fragment},
842 {9, vk::DescriptorType::eCombinedImageSampler, 1, fragment},
843 {10, vk::DescriptorType::eCombinedImageSampler, 1, vertex},
844 {11, vk::DescriptorType::eCombinedImageSampler, 1, vertex},
845 {12, vk::DescriptorType::eCombinedImageSampler, 1, vertex},
846 {13, vk::DescriptorType::eCombinedImageSampler, 1, fragment},
847 {2, vk::DescriptorType::eStorageBuffer, 1, vertex}};
848 if (separatedSamplers) {
852 binding.descriptorType = vk::DescriptorType::eSampledImage;
853 bindings.emplace_back(16, vk::DescriptorType::eSampler, 15, fragment);
854 bindings.emplace_back(17, vk::DescriptorType::eUniformBuffer, 1, fragment);
856 vk::DescriptorSetLayoutCreateInfo
info{};
859 r.setLayouts[mode] =
device->createDescriptorSetLayout(
info);
860 r.layouts[mode] = createPipelineLayout(device,
r.setLayouts[mode]);
862 if (!
draw.pools[mode]) {
863 std::vector<vk::DescriptorPoolSize> sizes{{vk::DescriptorType::eUniformBuffer, 2},
864 {vk::DescriptorType::eStorageBuffer, 2},
865 {vk::DescriptorType::eCombinedImageSampler, 22}};
866 if (separatedSamplers) {
867 sizes[0].descriptorCount = 3;
868 sizes[2].descriptorCount = 4;
869 sizes.emplace_back(vk::DescriptorType::eSampledImage, 18);
870 sizes.emplace_back(vk::DescriptorType::eSampler, 15);
872 vk::DescriptorPoolCreateInfo
info{};
874 info.poolSizeCount = uint32_t(sizes.size());
875 info.pPoolSizes = sizes.data();
877 vk::DescriptorSetAllocateInfo alloc{};
878 alloc.descriptorPool =
draw.pools[mode];
879 alloc.descriptorSetCount = 1;
880 alloc.pSetLayouts = &
r.setLayouts[mode];
881 draw.sets[mode] =
device->allocateDescriptorSets(alloc).front();
883 const auto set =
draw.sets[mode];
884 std::array<vk::DescriptorImageInfo, 15> samplerInfos{};
885 vk::DescriptorBufferInfo samplerSlotsInfo{};
886 if (separatedSamplers) {
887 for (
size_t i = 0; i < samplerInfos.size(); ++i)
888 samplerInfos[i].
sampler = uniqueSamplers[i < uniqueSamplers.size() ? i : 0];
889 upload(
draw.samplerSlots, vk::BufferUsageFlagBits::eUniformBuffer, samplerSlots.data(),
sizeof(samplerSlots));
890 samplerSlotsInfo = vk::DescriptorBufferInfo{
draw.samplerSlots.buffer, 0,
sizeof(samplerSlots)};
892 std::array<vk::DescriptorBufferInfo, 4> buffers{{{
draw.uniform.buffer, 0,
sizeof(
u)},
893 {
draw.skin.buffer, 0,
draw.skin.size},
894 {
draw.shadow.buffer, 0,
sizeof(shadow)},
895 {
draw.uv.buffer, 0,
draw.uv.size}}};
896 std::vector<vk::WriteDescriptorSet> writes(14);
897 const std::array<uint32_t, 14>
bindings{0, 14, 3, 4, 5, 6, 15, 8, 9, 10, 11, 12, 13, 2};
898 for (
size_t i = 0; i < writes.size(); ++i) {
899 writes[i].dstSet = set;
901 writes[i].descriptorCount = 1;
903 for (
auto [
write,
buffer] :
std::array<
std::pair<int, int>, 4>{{{0, 0}, {2, 1}, {4, 2}, {13, 3}}}) {
904 writes[
write].descriptorType =
905 (
write == 2 ||
write == 13) ? vk::DescriptorType::eStorageBuffer : vk::DescriptorType::eUniformBuffer;
908 writes[1].descriptorType = writes[3].descriptorType = writes[5].descriptorType = writes[6].descriptorType =
909 writes[7].descriptorType = writes[8].descriptorType = writes[9].descriptorType = writes[10].descriptorType =
910 writes[11].descriptorType = writes[12].descriptorType = vk::DescriptorType::eCombinedImageSampler;
911 writes[1].descriptorCount = 11;
912 writes[1].pImageInfo = images.data();
913 writes[3].pImageInfo = &envInfo;
914 writes[5].pImageInfo = &shadowInfo;
915 writes[6].descriptorCount = 3;
916 writes[6].pImageInfo = detailImages.data();
917 writes[7].pImageInfo = &extrasImage;
918 writes[8].pImageInfo = &colorsImage;
919 writes[9].pImageInfo = &vertexImage;
920 writes[10].pImageInfo = &motionImage;
921 writes[11].pImageInfo = &noiseImage;
922 writes[12].pImageInfo = &fadeNoiseImage;
923 if (separatedSamplers) {
924 for (
size_t index : {1u, 3u, 6u, 7u, 8u, 12u}) writes[
index].descriptorType = vk::DescriptorType::eSampledImage;
925 vk::WriteDescriptorSet samplersWrite{};
926 samplersWrite.dstSet = set;
927 samplersWrite.dstBinding = 16;
928 samplersWrite.descriptorCount = uint32_t(samplerInfos.size());
929 samplersWrite.descriptorType = vk::DescriptorType::eSampler;
930 samplersWrite.pImageInfo = samplerInfos.data();
931 writes.push_back(samplersWrite);
932 vk::WriteDescriptorSet slotsWrite{};
933 slotsWrite.dstSet = set;
934 slotsWrite.dstBinding = 17;
935 slotsWrite.descriptorCount = 1;
936 slotsWrite.descriptorType = vk::DescriptorType::eUniformBuffer;
937 slotsWrite.pBufferInfo = &samplerSlotsInfo;
938 writes.push_back(slotsWrite);
940 device->updateDescriptorSets(writes, {});
941 const auto& rp = gbuffer ? gbufferRenderPass
942 : offscreen3DPassOpen ? (offscreen3DHDRActive ? hdrOffscreen3DRenderPass : offscreen3DRenderPass)
944 const auto samples = (gbuffer || offscreen3DPassOpen) ? vk::SampleCountFlagBits::e1 : activeSceneSamples();
947 const bool depthWrite = !transparent || mesh3dSurfaceDepthWrite;
951 const bool alphaToCoverage = !gbuffer &&
s.alphaToCoverage && mesh3dSurfaceMode ==
SurfaceMode::Masked;
952 const size_t pipelineVariant =
953 size_t(
blend) * 12u + (depthWrite ? 6u : 0
u) + (alphaToCoverage ? 3u : 0
u) + size_t(resolvedCull) - 1u;
954 auto key = std::make_tuple(VkRenderPass(rp.handle), uint32_t(samples), pipelineVariant, separatedSamplers);
956 if (
found ==
r.pipelines.end())
959 .emplace(
key, createPbrPipeline(device,
r.layouts[mode], rp, samples,
blend, depthWrite, resolvedCull,
960 alphaToCoverage, separatedSamplers, gbuffer !=
nullptr))
962 std::array<vk::Buffer, 11> uvBuffers;
963 uvBuffers.fill(
draw.uv.buffer);
964 std::array<vk::DeviceSize, 11> uvOffsets{};
965 for (
size_t i = 0; i < uvOffsets.size(); ++i)
966 if (
u.uvInfo[i].offset != UINT32_MAX) uvOffsets[i] = vk::DeviceSize(
u.uvInfo[i].offset) * 2 *
sizeof(float);
968 gbuffer->pbrPipeline =
found->second;
969 gbuffer->pbrLayout =
r.layouts[mode];
970 gbuffer->pbrSet = set;
971 gbuffer->pbrUv =
draw.uv.buffer;
972 gbuffer->pbrUvOffsets = uvOffsets;
975 auto& cb = currentPresentCb();
976 cb.bindPipeline(vk::PipelineBindPoint::eGraphics,
found->second);
977 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics,
r.layouts[mode], 0, 1, &set, 0,
nullptr);
978 cb.bindVertexBuffers(1, uvBuffers, uvOffsets);
979 drawIndexedMesh(cb, *
static_cast<GpuMesh*
>(
mesh->gpuHandle));
980 lastMesh3dPipeline = vk::Pipeline{};
981 lastMesh3dClusteredPipeline = vk::Pipeline{};
998 auto found = std::find_if(ownedGpuShaders.begin(), ownedGpuShaders.end(),
999 [&](
const auto&
g) { return g->owner == &shader; });
1000 if (
found == ownedGpuShaders.end() || !(*found)->isMesh3D || (*found)->isHair3D ||
shader.isXray() ||
1001 swapchainPassOpen || offscreen3DPassOpen)
1010 std::array<vk::Pipeline, 3> prepared{};
1013 createMesh3DStylePipeline(
shader.vertexSpirv(),
shader.fragmentSpirv(),
gpu.pipelineLayout,
1014 activeScenePass(), activeSceneSamples(),
blend, depthWrite,
doubleSided, raster);
1015 prepared[1] = createMesh3DStylePipeline(
shader.vertexSpirv(),
shader.fragmentSpirv(),
gpu.pipelineLayout,
1016 offscreen3DRenderPass, vk::SampleCountFlagBits::e1,
blend, depthWrite,
1018 prepared[2] = createMesh3DStylePipeline(
shader.vertexSpirv(),
shader.fragmentSpirv(),
gpu.pipelineLayout,
1019 hdrOffscreen3DRenderPass, vk::SampleCountFlagBits::e1,
blend,
1022 }
catch (
const std::exception& e) {
1023 for (
auto pipeline : prepared)
1024 if (pipeline)
device->destroyPipeline(pipeline);
1027 for (
auto pipeline : {
gpu.mesh3dPipeline,
gpu.mesh3dOffscreenPipeline,
gpu.mesh3dHdrOffscreenPipeline})
1028 if (pipeline)
device->destroyPipeline(pipeline);
1029 gpu.mesh3dPipeline = prepared[0];
1030 gpu.mesh3dOffscreenPipeline = prepared[1];
1031 gpu.mesh3dHdrOffscreenPipeline = prepared[2];
1033 shader.meshDepthWrite = depthWrite;
1035 shader.meshRaster_ = raster;
1036 lastMesh3dPipeline =
nullptr;
1045size_t Graphics::uploadSkinPalette(Mesh*
mesh, Mesh3dFrameSlots& fslots) {
1046 const bool skinned =
mesh &&
mesh->hasGpuSkinning() &&
mesh->getSkinPaletteCount() > 0;
1047 const size_t slot = skinned ? fslots.drawIndex + 1 : 0;
1048 const size_t bytes = skinned ?
mesh->skinPalette().size() *
sizeof(float) : sizeof(glm::mat4);
1049 if (
bytes >
device.physical_device.properties.limits.maxStorageBufferRange)
1050 throw Exception(
"Skin palette exceeds device maxStorageBufferRange");
1051 if (fslots.palettes.size() <=
slot) fslots.palettes.resize(
slot + 1);
1054 buffer.allocate(frameToken(), device, vk::BufferUsageFlagBits::eStorageBuffer,
bytes, kHostVisibleCoherent);
1057 fslots.sets.clear();
1058 fslots.skinSets.clear();
1062 fslots.activePalette =
slot;
1066vk::DescriptorSet Graphics::skinPassSetFor(GpuTexture*
albedo, Mesh3dFrameSlots& fslots) {
1067 const auto key = std::make_pair(fslots.activePalette,
albedo);
1068 auto it = fslots.skinSets.find(
key);
1069 if (it != fslots.skinSets.end())
return it->second;
1070 vk::DescriptorSetAllocateInfo alloc{};
1071 alloc.descriptorPool = descriptorPool;
1072 alloc.descriptorSetCount = 1;
1073 alloc.pSetLayouts = &skinPassSetLayout;
1074 vkb::UnboundSet unbound{
device->allocateDescriptorSets(alloc).front()};
1075 vkb::DescriptorSetUpdater updater(2, 1, 0);
1076 updater.beginDescriptorSet(unbound)
1077 .beginBuffers(0, 0, vk::DescriptorType::eUniformBufferDynamic)
1078 .buffer(fslots.uboRing.buffer, 0,
sizeof(SkinPassUBO))
1079 .beginBuffers(2, 0, vk::DescriptorType::eStorageBuffer)
1080 .buffer(fslots.palettes[fslots.activePalette].buffer, 0, fslots.palettes[fslots.activePalette].capacity)
1081 .beginImages(1, 0, vk::DescriptorType::eCombinedImageSampler)
1082 .image(vkb::SampledImage::forLaterSample(
albedo->sampler,
albedo->imageView()))
1083 .update(
device.instance);
1084 vkb::BoundSet bound = std::move(unbound).publish();
1085 auto [inserted, ignored] = fslots.skinSets.emplace(
key, bound);
1086 return inserted->second;
1089bool Graphics::prepareSkinPass(Mesh*
mesh, Texture*
albedo,
const glm::mat4&
mvp,
const glm::mat4&
model,
1090 const glm::vec4&
clip, vk::DescriptorSet& set, uint32_t& uboOffset) {
1091 if (!
mesh || !
mesh->hasGpuSkinning())
return false;
1092 auto& fslots = currentMesh3dFrameSlots();
1098 if (!fslots.uboRing.buffer || fslots.capacity == 0) ensureMesh3dRing(fslots);
1099 if (fslots.drawIndex >= fslots.capacity) {
1100 std::fprintf(stderr,
"[vulkan] skin pass UBO ring exhausted (%zu draws); draw skipped\n", fslots.capacity);
1107 ubo.skinInfo.x =
static_cast<float>(
mesh->getSkinPaletteCount());
1108 ubo.skinInfo.y =
static_cast<float>(mesh3dSkinInfluenceLimit);
1109 uploadSkinPalette(
mesh, fslots);
1110 const size_t slot = fslots.drawIndex++;
1111 ensureMesh3dStrides();
1112 uboOffset = uint32_t(
slot) * mesh3dUboStride;
1113 updateRingLocal(fslots.uboRing, uboOffset, &ubo,
sizeof(ubo));
1116 set = skinPassSetFor(
static_cast<GpuTexture*
>(
texture->gpuHandle), fslots);
graphics::Texture * albedo
vk::UniqueSampler sampler
std::function< void(b3JointId, const Numbers &)> write
ScriptMotionSinkStore< ScriptMotionSink< MotionColorTraits > > colors
std::shared_ptr< OceanGpuSpectrum > gpu
std::vector< std::weak_ptr< DeviceBytes > > resources
std::unique_ptr< gpgpu::GpuBuffer > buffer
std::unordered_map< std::string, ShaderEntry > shaders
eve::action::ActionVfxBinding binding
std::vector< ParticleBakeMaterial > bindings
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
std::set< std::string > values
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
std::array< double, 2 > vertices[3]
const AssetImportLimits & limits
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
Canvas()
Constructs a Canvas.
bool recordingEngine3D_
True while RenderSystem3D is submitting (AO / engine overlays).
Canvas * spatialAAResolve_
virtual Canvas & prepareFramePostTarget(FramePostTarget target, int width, int height)
Prepare a pipeline output for this acquired frame. @ownership Borrows backend-owned Canvas; render th...
GPU mesh handle (+ optional CPU morph targets).
static constexpr uint32_t kPushConstantBytes
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Result< void > setMesh3DPbrSurface(const PbrSurface *surface) override
Sets the mesh 3 d pbr surface.
Result< Texture * > newTextureArrayRgba16f(uint32_t width, uint32_t height, uint32_t layers, std::span< const uint16_t > rgbaHalf) override
Creates a texture array rgba 16 f. @ownership Caller deletes unless documented otherwise.
void waitForSharedGpuResources()
Block until all in-flight GPU work (all frames) has completed.
bool canRecordPostSceneGpuWork() const
True when the present command buffer is open and the scene-color pass has ended, so post-scene GPU wo...
eve::Result< void > configureMeshShaderSurface(Shader &shader, BlendMode blend, bool depthWrite, bool doubleSided) override
Configure mesh shader surface.
eve::Result< void > configureMeshShaderRaster(Shader &shader, const MeshShaderRasterState &state) override
Configure mesh shader raster.
Result< Texture * > newTexture3DRgba8(uint32_t width, uint32_t height, uint32_t depth, std::span< const uint8_t > rgba) override
Creates a texture 3 d rgba 8. @ownership Caller deletes unless documented otherwise.
PbrCullMode
Raster face culling requested by a PBR material.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Result< void > validatePbrSurface(const PbrSurface &s)
Validate finite material factors and sampler enums without changing the input.
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
Result< void > validateMeshShaderRasterState(const MeshShaderRasterState &state)
Validate a borrowed value without touching graphics state; safe on any thread.
CompareOp
CompareOp public API.
ControlEdit combo(const char *label, int &selected, const std::vector< const char * > &items)
Shared immediate renderer for indexed combo boxes.
BlendMode
Render-neutral 2D blend mode shared by graphics-facing modules.
Light3DGpu lights[kMaxLights]
Value snapshot of custom mesh rasterization state, independent of blending/culling.
std::uint8_t colorWriteMask
MeshDepthCompare depthCompare
Owning material parameter snapshot; texture pointers remain borrowed. Base color/metallic/roughness c...
PbrVegetationMotion vegetationMotion
PbrVegetationExtras vegetationExtras
std::array< PbrTextureBinding, std::size_t(PbrTextureSlot::Count)> textures
PbrVegetationVertex vegetationVertex
PbrVegetationColors vegetationColors
PbrVegetationDetail vegetationDetail
PbrVegetationAlpha vegetationAlpha
std::array< PbrTextureBinding, 3 > textures
vkb::GenericBuffer samplerSlots
vkb::GenericBuffer shadow
vkb::GenericBuffer uniform
std::array< vk::DescriptorSet, 2 > sets
std::array< vk::DescriptorPool, 2 > pools
std::map< std::tuple< VkRenderPass, uint32_t, size_t, bool >, vk::Pipeline > pipelines
std::vector< std::vector< std::unique_ptr< Draw > > > gbufferFrames
std::array< vk::PipelineLayout, 2 > layouts
std::array< vk::DescriptorSetLayout, 2 > setLayouts
std::map< std::array< uint32_t, 4 >, vk::Sampler > samplers
std::vector< std::vector< std::unique_ptr< Draw > > > frames