载入中...
搜索中...
未找到
GraphicsOffscreen.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <array>
3#include <cstdint>
4#include <cstring>
5#include <map>
6#include <tuple>
7#include <vector>
8#include "common/Exception.h"
9#include "common/Profile.h"
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"
19
20// GraphicsOffscreen.cpp
21namespace eve::graphics::vulkan {
22void Graphics::releaseFramePostTargets() {
23 const bool empty = std::all_of(framePostTargets_.begin(), framePostTargets_.end(),
24 [](const auto& slots) { return slots.empty(); });
25 if (empty) return;
26 // Cache keys and descriptor payloads borrow these images. Drain consumers
27 // before retiring targets during resize, graph recreation or owner teardown.
28 device->waitIdle();
29 invalidateTextureBindings();
30 spatialAAResolve_ = nullptr;
31 for (auto& slots : framePostTargets_) {
32 for (Canvas* target : slots) {
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);
36 }
37 slots.clear();
38 }
39}
40
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);
48 }));
49 });
50 if (resized) releaseFramePostTargets();
51 auto& slots = framePostTargets_[static_cast<size_t>(target)];
52 if (slots.empty()) slots.resize(count, nullptr);
53 auto& canvas = slots[currentFrameSlot()];
54 if (!canvas) canvas = newHDRCanvas(width, height);
55 if (!canvas) throw Exception("Post-process frame target allocation failed");
56 return *canvas;
57}
58
59void Graphics::flushToOffscreen(OffscreenCanvas* canvas) {
60 EV_PROFILE_MODULE("graphics", "Offscreen.Record");
61 auto solid = std::move(solidBatches);
62 auto textured = std::move(texturedBatches);
63 auto lit = std::move(litBatches);
64 auto spans = std::move(recordingEngine3D_ ? engine3DSpans : overlaySpans);
65 // Drain this target's draws without resetting the pending scene/UI resolves.
66 solidBatches.clear();
67 texturedBatches.clear();
68 litBatches.clear();
69
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;
76
77 // The acquired slot fence protects each pipeline intermediate and its immutable
78 // frame-arena vertices. All other canvases retain shared-image semantics.
79 const bool frameLocal = canRecordPostSceneGpuWork() &&
80 std::any_of(framePostTargets_.begin(), framePostTargets_.end(), [&](const auto& slots) {
81 return currentFrameSlot() < slots.size() && slots[currentFrameSlot()] == canvas;
82 });
83 if (!frameLocal) waitForSharedGpuResources();
84 EV_PROFILE_MODULE("graphics", frameLocal ? "Offscreen.FrameLocalRecord" : "Offscreen.SharedRecord");
85
86 auto recordOffscreen = [&](vk::CommandBuffer cb) {
87 canvas->colorImage().setLayout(cb, vk::ImageLayout::eColorAttachmentOptimal);
88
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);
98 if (needClear) {
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;
105 rect.layerCount = 1;
106 cb.clearAttachments(attachment, rect);
107 }
108
109 setViewportAndScissor(cb, uint32_t(canvas->getWidth()), uint32_t(canvas->getHeight()));
110
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();
116
117 auto offscreenTexPipe = [&](BlendMode mode) -> vk::Pipeline {
118 switch (mode) {
120 return canvas->isHDR() ? hdrOffscreenAdditiveTexPipeline : offscreenAdditiveTexPipeline;
122 return canvas->isHDR() ? hdrOffscreenPremultipliedTexPipeline : offscreenPremultipliedTexPipeline;
124 return canvas->isHDR() ? hdrOffscreenMultiplyTexPipeline : offscreenMultiplyTexPipeline;
126 return canvas->isHDR() ? hdrOffscreenOpaqueTexPipeline : offscreenOpaqueTexPipeline;
127 case BlendMode::Alpha:
128 default: return canvas->isHDR() ? hdrOffscreenTexPipeline : offscreenTexPipeline;
129 }
130 };
131 auto offscreenSolidPipe = [&](BlendMode mode) -> vk::Pipeline {
132 switch (mode) {
133 case BlendMode::Additive: return offscreenAdditiveSolidPipeline;
134 case BlendMode::Premultiplied: return offscreenPremultipliedSolidPipeline;
135 case BlendMode::Multiply: return offscreenMultiplySolidPipeline;
136 case BlendMode::Alpha: return offscreenSolidAlphaPipeline;
138 default: return offscreenSolidPipeline;
139 }
140 };
141
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))
153 texSet = combo;
154 }
155 Batcher ndc = tb.batch;
156 ndc.toNDC(vw, vh);
157 std::vector<TexturedVertex> gpuVerts;
158 gpuVerts.reserve(ndc.vertices().size());
159 for (const auto& v : ndc.vertices()) gpuVerts.push_back(TexturedVertex{v.pos, v.color, v.uv});
160
161 vk::Buffer vertexBuffer{};
162 vk::DeviceSize vertexOffset = 0;
163 if (canRecordPostSceneGpuWork()) {
164 // Each recorded pass needs immutable vertices until submission.
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;
175 } else {
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;
180 }
181
182 if (tb.shader && tb.shader->gpuHandle) {
183 if (canvas->isHDR())
184 ensureShaderHdrOffscreenPipeline(tb.shader);
185 else
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,
195 nullptr);
196 cb.pushConstants(shaderPipelineLayout,
197 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0,
198 Shader::kPushConstantBytes, tb.shader->pushConstantData());
199 } else {
200 vk::Pipeline pipe = offscreenTexPipe(tb.blend);
201 if (!pipe) return;
202 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, pipe);
203 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, texPipelineLayout, 0, 1, &texSet, 0, nullptr);
204 }
205 cb.bindVertexBuffers(0, 1, &vertexBuffer, &vertexOffset);
206 cb.draw(uint32_t(gpuVerts.size()), 1, 0, 0);
207 };
208
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);
213 if (!pipe) return;
214 Batcher ndc = solid[idx].batch;
215 ndc.toNDC(vw, vh);
216 std::vector<ColorVertex> gpuVerts;
217 gpuVerts.reserve(ndc.vertices().size());
218 for (const auto& v : ndc.vertices()) gpuVerts.push_back(ColorVertex{v.pos, v.color});
219 if (solidBufs.size() <= idx) solidBufs.resize(idx + 1);
220 solidBufs[idx].allocate<ColorVertex>(frameToken(), device, gpuVerts);
221 solidUploaded[idx] = true;
222 };
223
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);
227 if (!pipe) return;
228 uploadSolid(batchIndex);
229 vk::DeviceSize offset = 0;
230 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, pipe);
231 cb.bindVertexBuffers(0, 1, solidBufs[batchIndex], &offset);
232 cb.draw(count, 1, begin, 0);
233 };
234
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());
246 }
247 }
248 } else {
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()));
251 }
252 for (auto& tb : textured) drawOffscreenTextured(tb);
253 if (litOk) drawLitBatches(cb, vw, vh, lit, texBufs, texBufIndex, true, canvas->isHDR());
254 }
255
256 cb.endRenderPass();
257 canvas->colorImage().endSampledLayout();
258 };
259 if (canRecordPostSceneGpuWork()) {
260 recordOffscreen(currentPresentCb());
261 } else {
262 EV_PROFILE_MODULE("graphics", "Offscreen.SubmitAndWait");
263 vkb::executeImmediately(device.instance, uploadPool, device.getQueue(vkb::QueueType::graphics),
264 recordOffscreen);
265 }
266}
267
268
269} // namespace eve::graphics::vulkan
270
271// GraphicsPbr.cpp
272namespace eve::graphics::vulkan {
273namespace {
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;
279}
280enum class PbrSamplerBinding { Combined, Separated };
281Result<PbrSamplerBinding> planPbrSamplerBinding(size_t uniqueOrdinarySamplers, const vk::PhysicalDeviceLimits& limits) {
282 // Three combined vertex resources are independent of the fragment budget.
283 const auto supports = [&](uint32_t fragmentSamplers) {
284 return limits.maxPerStageDescriptorSamplers >= fragmentSamplers &&
285 limits.maxDescriptorSetSamplers >= fragmentSamplers + 3u &&
286 limits.maxPerStageDescriptorSampledImages >= 19u && limits.maxDescriptorSetSampledImages >= 22u;
287 };
288 if (uniqueOrdinarySamplers <= 15 && supports(16))
289 return Result<PbrSamplerBinding>::success(PbrSamplerBinding::Separated);
290 if (supports(19)) return Result<PbrSamplerBinding>::success(PbrSamplerBinding::Combined);
293 "PBR material exceeds the device sampler/image descriptor budget", "graphics.pbr.samplers"));
294}
295vk::Pipeline createPbrPipeline(vkb::Device& device, vk::PipelineLayout layout, const vkb::BuiltRenderPass& pass,
296 vk::SampleCountFlagBits samples, BlendMode blend, bool depthWrite, PbrCullMode cullMode,
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>();
305 // The dedicated PBR shader reserves locations 5..15 for its eleven material
306 // UV streams. MeshVertex gained a color attribute at location 5 for the
307 // regular mesh pipelines, so describe only the five attributes consumed by
308 // pbr_surface.vert here instead of importing the shared six-attribute list.
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)));
314 // Five mesh attributes plus eleven material UV streams fit Vulkan's minimum
315 // sixteen vertex attributes. Each role can select any canonical mesh UV set.
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);
319 }
320 auto attachment = makeBlendAttachment(blend);
321 attachment.blendEnable = blend != BlendMode::Opaque;
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()
331 .useClassicPipeline(shaders.vert, shaders.frag)
332 .setPipelineLayout(layout)
333 .setVertexInputState(input)
334 .setDynamicStatesViewportScissor()
335 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
336 cullMode == PbrCullMode::None ? vk::CullModeFlagBits::eNone
337 : (cullMode == PbrCullMode::Front ? vk::CullModeFlagBits::eFront
338 : vk::CullModeFlagBits::eBack),
339 vk::FrontFace::eCounterClockwise)
340 .setMultisampler(multisampling)
341 // Built-in opaque PBR can replace the same surface written by Hybrid;
342 // alpha/additive materials retain strict depth and their blend contract.
343 .setDepthStencil(true, depthWrite,
344 blend == BlendMode::Opaque && depthWrite ? vk::CompareOp::eLessOrEqual : vk::CompareOp::eLess)
345 .setColorBlending(color)
346 .build(pass);
347}
348} // namespace
350 struct Draw {
351 vkb::GenericBuffer uniform, uv, skin, shadow, samplerSlots;
352 std::array<vk::DescriptorPool, 2> pools{};
353 std::array<vk::DescriptorSet, 2> sets{};
354 };
355 vk::Device device{};
356 std::array<vk::DescriptorSetLayout, 2> setLayouts{};
357 std::array<vk::PipelineLayout, 2> layouts{};
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;
360 std::vector<std::vector<std::unique_ptr<Draw>>> frames, gbufferFrames;
362 for (auto* slots : {&frames, &gbufferFrames})
363 for (auto& frame : *slots)
364 for (auto& draw : frame)
365 for (auto pool : draw->pools)
366 if (pool) device.destroyDescriptorPool(pool);
367 for (auto& [key, pipeline] : pipelines) device.destroyPipeline(pipeline);
368 for (auto& [key, sampler] : samplers) device.destroySampler(sampler);
369 for (auto layout : layouts)
370 if (layout) device.destroyPipelineLayout(layout);
371 for (auto setLayout : setLayouts)
372 if (setLayout) device.destroyDescriptorSetLayout(setLayout);
373 }
374};
375void Graphics::deletePbrResources(PbrResources* resources) { delete resources; }
376void Graphics::destroyPbrResources() { pbrResources_.reset(); }
377void Graphics::destroyPbrGBufferResources() {
378 if (!pbrResources_) return;
379 // The caller has retired deferred submissions. Forward resources may still
380 // be referenced by an open scene pass, so only retire this pass's cache.
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);
386 } else {
387 ++it;
388 }
389 }
390 for (auto& frame : r.gbufferFrames)
391 for (auto& draw : frame)
392 for (auto pool : draw->pools)
393 if (pool) device->destroyDescriptorPool(pool);
394 r.gbufferFrames.clear();
395}
397 if (!surface) {
398 pbrSurface_.reset();
399 return Result<void>::success();
400 }
401 auto result = validatePbrSurface(*surface);
402 if (!result) return result;
403 for (const auto& binding : surface->textures)
404 if (binding.texture && !binding.texture->gpuHandle)
406 Diagnostic::error(DiagnosticCode::InvalidArgument, "PBR texture has no GPU resource"));
407 for (const auto& binding : surface->vegetationDetail.textures)
408 if (binding.texture && !binding.texture->gpuHandle)
410 Diagnostic::error(DiagnosticCode::InvalidArgument, "PBR detail texture has no GPU resource"));
411 if (surface->vegetationExtras.texture && !surface->vegetationExtras.texture->gpuHandle)
413 Diagnostic::error(DiagnosticCode::InvalidArgument, "PBR Extras texture has no GPU resource"));
414 if (surface->vegetationColors.texture && !surface->vegetationColors.texture->gpuHandle)
416 Diagnostic::error(DiagnosticCode::InvalidArgument, "PBR Colors texture has no GPU resource"));
417 if (surface->vegetationVertex.texture && !surface->vegetationVertex.texture->gpuHandle)
419 Diagnostic::error(DiagnosticCode::InvalidArgument, "PBR Vertex texture has no GPU resource"));
420 if (surface->vegetationMotion.texture && !surface->vegetationMotion.texture->gpuHandle)
422 Diagnostic::error(DiagnosticCode::InvalidArgument, "PBR Motion texture has no GPU resource"));
423 if (surface->vegetationMotion.noise && !surface->vegetationMotion.noise->gpuHandle)
425 Diagnostic::error(DiagnosticCode::InvalidArgument, "PBR motion noise has no GPU resource"));
426 if (surface->vegetationAlpha.noise && !surface->vegetationAlpha.noise->gpuHandle)
428 Diagnostic::error(DiagnosticCode::InvalidArgument, "PBR vegetation fade noise has no GPU resource"));
429 const auto requireKind = [](Texture* texture, const char* role, bool array, bool volume,
430 std::uint32_t minimumLayers = 1u) -> Result<void> {
431 if (!texture) return Result<void>::success();
432 const auto* gpu = static_cast<const GpuTexture*>(texture->gpuHandle);
433 if (!gpu || gpu->isCube || gpu->isVolume != volume || (!volume && gpu->isArray != array) ||
434 (array && std::uint32_t(texture->layers) < minimumLayers))
436 DiagnosticCode::InvalidArgument, std::string(role) + " has an incompatible texture dimension"));
437 return Result<void>::success();
438 };
439 for (const auto& binding : surface->textures) {
440 auto ready = requireKind(binding.texture, "PBR texture", false, false);
441 if (!ready) return ready;
442 }
443 for (const auto& binding : surface->vegetationDetail.textures) {
444 auto ready = requireKind(binding.texture, "PBR detail texture", false, false);
445 if (!ready) return ready;
446 }
447 for (auto [texture, role, layer] : std::array<std::tuple<Texture*, const char*, std::uint32_t>, 4>{
448 {{surface->vegetationExtras.texture, "PBR Extras texture", surface->vegetationExtras.layer},
449 {surface->vegetationColors.texture, "PBR Colors texture", surface->vegetationColors.layer},
450 {surface->vegetationVertex.texture, "PBR Vertex texture", surface->vegetationVertex.layer},
451 {surface->vegetationMotion.texture, "PBR Motion texture", surface->vegetationMotion.layer}}}) {
452 auto ready = requireKind(texture, role, true, false, layer + 1u);
453 if (!ready) return ready;
454 }
455 auto ready = requireKind(surface->vegetationMotion.noise, "PBR motion noise", false, false);
456 if (!ready) return ready;
457 ready = requireKind(surface->vegetationAlpha.noise, "PBR fade noise", false, true);
458 if (!ready) return ready;
459 pbrSurface_ = *surface;
460 return Result<void>::success();
461}
462void Graphics::drawPbrMesh(Mesh* mesh, const glm::mat4& model, const Color& tint, GBufferDraw* gbuffer) {
463 if (!pbrResources_) {
464 pbrResources_.reset(new PbrResources());
465 auto& r = *pbrResources_;
466 r.device = device.instance;
467 }
468 auto& r = *pbrResources_;
469 auto& fslots = currentMesh3dFrameSlots();
470 // All snapshots belong to this fenced frame slot and unique draw index.
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>());
477 auto& draw = *draws[index];
478 const auto& s = *pbrSurface_;
479 PbrUniformGpu u;
480 u.model = model;
481 u.mvp = mesh3dFrameUbo.mvp * model;
482 u.view = mesh3dFrameUbo.view;
483 u.camera = glm::vec4(glm::vec3(mesh3dFrameUbo.cameraPos), s.anisotropyRotation);
484 u.tint = {tint.r, tint.g, tint.b, tint.a};
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)};
488 if (mesh3dSurfaceMode == SurfaceMode::Transparent && mesh3dSurfaceBlend == BlendMode::Premultiplied)
489 u.material.z = 3;
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,
514 0, 0};
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 : 0u, 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 : 0u, extras.texture ? 1u : 0u,
539 s.vegetationAlpha.enabled ? 1u : 0u};
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;
554 u.colorsCoords = {colors.coords[0], colors.coords[1], colors.coords[2], colors.coords[3]};
555 u.colorsFallback = {colors.fallback[0], colors.fallback[1], colors.fallback[2], colors.fallback[3]};
556 u.colorsUsage0 = {colors.usage[0], colors.usage[1], colors.usage[2], colors.usage[3]};
557 u.colorsUsage1 = {colors.usage[4], colors.usage[5], colors.usage[6], colors.usage[7]};
558 u.colorsUsage2 = {colors.usage[8], 0, 0, 0};
559 u.colorsInfo = {colors.layer, colors.usePivotPosition ? 1u : 0u, colors.texture ? 1u : 0u, 0u};
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), 0u, 0u};
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), 0u, 0u};
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;
591 // Binding a valid dummy stream also covers roles using the mesh vertex UV0.
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;
598 if (b.texture) {
599 auto values = mesh->texcoordSet(b.texcoord);
600 if (values.empty() && b.texcoord != 0) throw Exception("PBR texture references missing mesh UV channel");
601 if (!values.empty()) {
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());
607 offset = uint32_t(start);
608 } else
609 offset = uint32_t(found->second);
610 }
611 }
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};
617 auto found = r.samplers.find(key);
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
622 : vk::Filter::eLinear;
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;
628 found = r.samplers.emplace(key, device->createSampler(info)).first;
629 }
630 images[i] = {found->second, tex->imageView(), vk::ImageLayout::eShaderReadOnlyOptimal};
631 }
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};
637 auto found = r.samplers.find(key);
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
642 : vk::Filter::eLinear;
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;
648 found = r.samplers.emplace(key, device->createSampler(info)).first;
649 }
650 detailImages[i] = {found->second, tex->imageView(), vk::ImageLayout::eShaderReadOnlyOptimal};
651 }
652 if (!extras.texture && !defaultExtrasArray) {
653 const std::array<uint16_t, 4> neutral{0x3c00u, 0u, 0u, 0x3c00u};
654 auto created = newTextureArrayRgba16f(1, 1, 1, neutral);
655 if (!created.ok()) throw Exception("PBR could not create its neutral Extras array");
656 defaultExtrasArray = created.value();
657 }
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, 0u};
666 auto created = newTextureArrayRgba16f(1, 1, 1, neutral);
667 if (!created.ok()) throw Exception("PBR could not create its neutral Colors array");
668 defaultColorsArray = created.value();
669 }
670 Texture* colorsTexture = colors.texture ? colors.texture : defaultColorsArray;
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{0u, 0u, 0u, 0x3c00u};
678 auto created = newTextureArrayRgba16f(1, 1, 1, neutral);
679 if (!created.ok()) throw Exception("PBR could not create its neutral Vertex array");
680 defaultVertexArray = created.value();
681 }
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");
686 if ((vertex.source == PbrVegetationDeformationSource::GpuFields ||
687 motion.mode != PbrVegetationMotionMode::Disabled) &&
688 skinned)
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, 0u, 0x3800u, 0u};
694 auto created = newTextureArrayRgba16f(1, 1, 1, neutral);
695 if (!created.ok()) throw Exception("PBR could not create its neutral Motion array");
696 defaultMotionArray = created.value();
697 }
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};
711 auto created = newTexture3DRgba8(1, 1, 1, zero);
712 if (!created.ok()) throw Exception("PBR could not create its neutral vegetation fade volume");
713 defaultVegetationFadeNoise = created.value();
714 }
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);
721 if (s.normalMode != PbrNormalMode::TangentXYZ && mesh->hasImportedTangents()) {
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);
732 }
733 }
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());
741 u.tangentInfo.w = 1;
742 coordinates.insert(coordinates.end(), highlights.begin(), highlights.end());
743 }
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 : 0u,
751 s.vegetationColor.invertVertexOcclusionColors ? 1u : 0u};
752 coordinates.insert(coordinates.end(), vegetationFactors.begin(), vegetationFactors.end());
753 }
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());
761 u.vertexInfo.w = 1;
762 coordinates.insert(coordinates.end(), deformationFactors.begin(), deformationFactors.end());
763 }
764 if (motion.mode == PbrVegetationMotionMode::Object && deformationFactors.empty())
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");
770 buffer.allocate(frameToken(), device, usage, bytes, kHostVisibleCoherent);
771 updateRingLocal(buffer, 0, data, bytes);
772 };
773 if (gbuffer) {
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;
779 }
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));
783 const glm::mat4 identity(1);
784 upload(draw.skin, vk::BufferUsageFlagBits::eStorageBuffer, skinned ? mesh->skinPalette().data() : &identity[0][0],
785 skinned ? mesh->skinPalette().size() * sizeof(float) : sizeof(identity));
786 auto shadow = mesh3dShadows.ubo;
787 if (!mesh3dShadows.active) {
788 shadow.bias.y = 0;
789 shadow.splits.w = 0;
790 }
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()};
799 // The shader keeps all eighteen ordinary images. Only identical sampler
800 // handles share a slot, so distinct filtering and wrapping remain intact.
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);
816 } else {
817 samplerSlots[role] = uint32_t(found - uniqueSamplers.begin());
818 }
819 }
820 // The existing immediate draw API reports failures by exception. Preserve the
821 // structured diagnostic through the Result expectation bridge at that boundary.
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 : 0u;
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;
830 // Keep fragment-only arrays after the vertex resources. Older Metal
831 // translators size inactive array placeholders as one element, shifting
832 // the storage-buffer addresses that follow them in an argument buffer.
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) {
849 for (auto& binding : bindings)
850 if (binding.binding == 14 || binding.binding == 15 || binding.binding == 4 || binding.binding == 8 ||
851 binding.binding == 9 || binding.binding == 13)
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);
855 }
856 vk::DescriptorSetLayoutCreateInfo info{};
857 info.bindingCount = uint32_t(bindings.size());
858 info.pBindings = bindings.data();
859 r.setLayouts[mode] = device->createDescriptorSetLayout(info);
860 r.layouts[mode] = createPipelineLayout(device, r.setLayouts[mode]);
861 }
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);
871 }
872 vk::DescriptorPoolCreateInfo info{};
873 info.maxSets = 1;
874 info.poolSizeCount = uint32_t(sizes.size());
875 info.pPoolSizes = sizes.data();
876 draw.pools[mode] = device->createDescriptorPool(info);
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();
882 }
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)};
891 }
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;
900 writes[i].dstBinding = bindings[i];
901 writes[i].descriptorCount = 1;
902 }
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;
906 writes[write].pBufferInfo = &buffers[buffer];
907 }
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);
939 }
940 device->updateDescriptorSets(writes, {});
941 const auto& rp = gbuffer ? gbufferRenderPass
942 : offscreen3DPassOpen ? (offscreen3DHDRActive ? hdrOffscreen3DRenderPass : offscreen3DRenderPass)
943 : activeScenePass();
944 const auto samples = (gbuffer || offscreen3DPassOpen) ? vk::SampleCountFlagBits::e1 : activeSceneSamples();
945 const bool transparent = !gbuffer && mesh3dSurfaceMode == SurfaceMode::Transparent;
946 const auto blend = transparent ? mesh3dSurfaceBlend : BlendMode::Opaque;
947 const bool depthWrite = !transparent || mesh3dSurfaceDepthWrite;
948 const auto resolvedCull = s.cullMode == PbrCullMode::Inherit
949 ? (mesh3dSurfaceDoubleSided ? PbrCullMode::None : PbrCullMode::Back)
950 : s.cullMode;
951 const bool alphaToCoverage = !gbuffer && s.alphaToCoverage && mesh3dSurfaceMode == SurfaceMode::Masked;
952 const size_t pipelineVariant =
953 size_t(blend) * 12u + (depthWrite ? 6u : 0u) + (alphaToCoverage ? 3u : 0u) + size_t(resolvedCull) - 1u;
954 auto key = std::make_tuple(VkRenderPass(rp.handle), uint32_t(samples), pipelineVariant, separatedSamplers);
955 auto found = r.pipelines.find(key);
956 if (found == r.pipelines.end())
957 found =
958 r.pipelines
959 .emplace(key, createPbrPipeline(device, r.layouts[mode], rp, samples, blend, depthWrite, resolvedCull,
960 alphaToCoverage, separatedSamplers, gbuffer != nullptr))
961 .first;
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);
967 if (gbuffer) {
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;
973 return;
974 }
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{};
982}
983} // namespace eve::graphics::vulkan
984
985// GraphicsShaderSurface.cpp
986namespace eve::graphics::vulkan {
988 bool doubleSided) {
989 return rebuildMeshShaderSurface(shader, blend, depthWrite, doubleSided, shader.meshRasterState());
990}
993 if (!valid) return valid;
994 return rebuildMeshShaderSurface(shader, shader.meshBlend, shader.meshDepthWrite, shader.meshDoubleSided, state);
995}
996eve::Result<void> Graphics::rebuildMeshShaderSurface(Shader& shader, BlendMode blend, bool depthWrite, bool doubleSided,
997 const MeshShaderRasterState& raster) {
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)
1003 eve::DiagnosticCode::InvalidArgument, "Expected an owned mesh shader outside frame submission"));
1004 const auto& current = shader.meshRasterState();
1005 if (shader.meshBlend == blend && shader.meshDepthWrite == depthWrite && shader.meshDoubleSided == doubleSided &&
1006 current.depthCompare == raster.depthCompare && current.depthBiasConstant == raster.depthBiasConstant &&
1007 current.depthBiasSlope == raster.depthBiasSlope && current.colorWriteMask == raster.colorWriteMask)
1009 auto& gpu = **found;
1010 std::array<vk::Pipeline, 3> prepared{};
1011 try {
1012 prepared[0] =
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,
1017 doubleSided, raster);
1018 prepared[2] = createMesh3DStylePipeline(shader.vertexSpirv(), shader.fragmentSpirv(), gpu.pipelineLayout,
1019 hdrOffscreen3DRenderPass, vk::SampleCountFlagBits::e1, blend,
1020 depthWrite, doubleSided, raster);
1022 } catch (const std::exception& e) {
1023 for (auto pipeline : prepared)
1024 if (pipeline) device->destroyPipeline(pipeline);
1026 }
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];
1032 shader.meshBlend = blend;
1033 shader.meshDepthWrite = depthWrite;
1034 shader.meshDoubleSided = doubleSided;
1035 shader.meshRaster_ = raster;
1036 lastMesh3dPipeline = nullptr;
1038}
1039} // namespace eve::graphics::vulkan
1040
1041// GraphicsSkin.cpp
1042namespace eve::graphics::vulkan {
1043// Per-frame, per-draw storage: queued draws own snapshots until the frame fence.
1044// A slot can grow only before that slot has been referenced by this frame.
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);
1052 auto& buffer = fslots.palettes[slot];
1053 if (!buffer.buffer || buffer.capacity < bytes) {
1054 buffer.allocate(frameToken(), device, vk::BufferUsageFlagBits::eStorageBuffer, bytes, kHostVisibleCoherent);
1055 // The fence protects earlier frames. Other slots used this frame retain
1056 // their buffers and published descriptor sets unchanged.
1057 fslots.sets.clear();
1058 fslots.skinSets.clear();
1059 }
1060 const glm::mat4 identity(1.f);
1061 updateRingLocal(buffer, 0, skinned ? mesh->skinPalette().data() : &identity[0][0], bytes);
1062 fslots.activePalette = slot;
1063 return slot;
1064}
1065
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;
1087}
1088
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();
1093 // A 3D frame can inherit an already-open present command buffer (for
1094 // example, when script-side 2D clear work precedes render3D). In that
1095 // path begin3DFrame may not have initialized this slot yet. Allocate the
1096 // empty slot lazily before the first skinned draw; no recorded command can
1097 // reference it while capacity is zero.
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);
1101 return false;
1102 }
1103 SkinPassUBO ubo;
1104 ubo.mvp = mvp;
1105 ubo.model = model;
1106 ubo.clip = clip;
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));
1114 Texture* texture = albedo ? albedo : whiteTexture;
1115 if (!texture || !texture->gpuHandle) return false;
1116 set = skinPassSetFor(static_cast<GpuTexture*>(texture->gpuHandle), fslots);
1117 return bool(set);
1118}
1119
1120
1121} // namespace eve::graphics::vulkan
LogicalId target
Duration start
std::string usage
ActiveSource owned
double volume
const std::string & s
float uv
graphics::Texture * albedo
SQObjectPtr key
Definition ECS.cpp:155
EvpackChunkInput input
Definition Evpack.cpp:170
std::string layout
tensor::Graph g
Definition GpuGraph.cpp:7
vkb::Device & device
vk::UniqueSampler sampler
glm::vec4 clip
glm::vec4 tint
glm::mat4 mvp
float u
Definition Grass.cpp:233
double r
float v
float blend
std::uint32_t height
std::uint32_t width
std::function< void(b3JointId, const Numbers &)> write
size_t offset
Poco::JSON::Object::Ptr result
std::uint64_t bytes
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeshVfxBatchedDraw draw
float tb
bool doubleSided
Texture * normal
ScriptMotionSinkStore< ScriptMotionSink< MotionColorTraits > > colors
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
ssq::Object frame
std::vector< std::weak_ptr< DeviceBytes > > resources
Definition OnnxGpgpu.cpp:55
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::unordered_map< std::string, ShaderEntry > shaders
Definition OnnxGpgpu.cpp:44
eve::action::ActionVfxBinding binding
Texture * texture
TileLayer * layer
int idx
std::vector< ParticleBakeMaterial > bindings
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
std::set< std::string > values
Object::Ptr value
float d
std::string build
std::string slot
Shader * shader
glm::mat4 model
bool found
int created
size_t begin
double current
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
int count
float weights[3]
std::array< double, 2 > vertices[3]
float size
Definition TreeMesh.cpp:158
const AssetImportLimits & limits
uint32_t index
uint64_t identity
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.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Canvas()
Constructs a Canvas.
Definition Canvas.h:25
bool recordingEngine3D_
True while RenderSystem3D is submitting (AO / engine overlays).
Definition Graphics.h:2325
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).
Definition Mesh.h:26
Custom GPU program.
Definition Shader.h:41
static constexpr uint32_t kPushConstantBytes
Definition Shader.h:45
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
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.
Definition Graphics.cpp:943
bool canRecordPostSceneGpuWork() const
True when the present command buffer is open and the scene-color pass has ended, so post-scene GPU wo...
Definition Graphics.h:1065
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.
Definition PbrSurface.h:20
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
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.
Definition BlendMode.h:8
Result< void > validateMeshShaderRasterState(const MeshShaderRasterState &state)
Validate a borrowed value without touching graphics state; safe on any thread.
CompareOp
CompareOp public API.
Definition NpcAi.h:27
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.
Definition RenderTypes.h:11
Light3DGpu lights[kMaxLights]
Definition Light.h:174
Value snapshot of custom mesh rasterization state, independent of blending/culling.
Owning material parameter snapshot; texture pointers remain borrowed. Base color/metallic/roughness c...
Definition PbrSurface.h:240
PbrVegetationMotion vegetationMotion
Definition PbrSurface.h:281
PbrVegetationExtras vegetationExtras
Definition PbrSurface.h:278
std::array< PbrTextureBinding, std::size_t(PbrTextureSlot::Count)> textures
Definition PbrSurface.h:241
PbrVegetationVertex vegetationVertex
Definition PbrSurface.h:280
PbrVegetationColors vegetationColors
Definition PbrSurface.h:279
PbrVegetationDetail vegetationDetail
Definition PbrSurface.h:277
PbrVegetationAlpha vegetationAlpha
Definition PbrSurface.h:282
std::array< PbrTextureBinding, 3 > textures
Definition PbrSurface.h:110
GpuTexture public API.
Definition Graphics.h:264
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
glm::uvec4 info
glm::vec4 color