载入中...
搜索中...
未找到
GraphicsDeferredGraph.cpp
浏览该文件的文档.
1// Deferred shadow/G-buffer graph ownership and recording.
2#include <algorithm>
3#include <array>
4#include <cstring>
5#include <memory>
6#include <string>
7#include "common/Profile.h"
12#include "thread/Thread.h"
13
14namespace eve::graphics::vulkan {
15
16void Graphics::resetDeferredFrameGraphs() {
17 // Graph command pools/framebuffers borrow these targets. Retire every
18 // submitted slot before destroying graphs, then destroy target images.
19 if (device.instance) device->waitIdle();
20 for (auto &slot : deferredFrameGraphs_)
21 for (auto &graph : slot) graph.reset();
22 deferredRecordingState_ = {};
23 deferredGraphRecorded_ = false;
24 deferredGraphRecordedSlot_ = 0;
25}
26
27vkb::FrameGraph *Graphics::currentDeferredFrameGraph() {
28 const size_t variant = shadowPendingMask != 0 ? 1u : 0u;
29 return deferredFrameGraphs_[currentFrameSlot() % deferredFrameGraphs_.size()][variant].get();
30}
31
32void Graphics::buildDeferredFrameGraphs() {
33 // Cache both shadow-update and G-buffer-only plans per in-flight slot.
34 // Build a variant lazily, once, rather than rebuilding on light toggles.
35 // Shadow resources are initialized into sampled layout at creation; frames
36 // without pending updates need neither clear passes nor layout transitions.
37 // The engine keeps image ownership so
38 // renderEntityIdMask / readGBufferToImageData and the postFX wrappers are
39 // unaffected. Each graph is only used on its slot's frames, so its command
40 // buffer is reused two frames later — by then the present slot fence
41 // guarantees the previous graph submit completed (same queue, submitted
42 // before the present command buffer).
43 const vk::Format depthFmt = vk::Format::eD32Sfloat;
44 const vk::Format colorFmt = pickGBufferColorFormat(device);
45 const uint32_t mapSize = uint32_t(
46 allocatedShadowMapSize > 0 ? allocatedShadowMapSize : ShadowSchemeSettings::current().resolvedAtlasMapSize());
47 const uint32_t shadowLayers = uint32_t(ShadowConfig::kTotalLayers);
48 const uint32_t w = gbufferWidth > 0 ? uint32_t(gbufferWidth) : 1u;
49 const uint32_t h = gbufferHeight > 0 ? uint32_t(gbufferHeight) : 1u;
50 const size_t variant = shadowPendingMask != 0 ? 1u : 0u;
51
52 for (size_t i = 0; i < deferredFrameGraphs_.size(); ++i) {
53 auto graph = std::make_unique<vkb::FrameGraph>(&device, 1);
54
55 vkb::TextureDesc shadowDesc;
56 shadowDesc.format = depthFmt;
57 shadowDesc.extent = vk::Extent3D{mapSize, mapSize, 1};
58 shadowDesc.arrayLayers = shadowLayers;
59 shadowDesc.aspect = vk::ImageAspectFlagBits::eDepth;
60 shadowDesc.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eDepthStencilAttachment;
61 // Shadow descriptors sample the depth array in SHADER_READ_ONLY, matching
62 // the legacy shadow pass and the layout of every imported cascade.
63 shadowDesc.afterLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
64 vk::ClearValue shadowClear{};
65 shadowClear.depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
66 const bool haveShadowSlot = i < shadowMaps.size() && shadowMaps[i].image.layerCount() >= shadowLayers;
67 if (haveShadowSlot && variant != 0) {
68 const vk::Image shadowImage = shadowMaps[i].image.image();
69 for (uint32_t c = 0; c < shadowLayers; ++c) {
70 auto shadowH = graph->importTexture("shadowCascade" + std::to_string(c), shadowImage,
71 shadowMaps[i].image.layerView(c), shadowDesc);
72 graph->addPass("shadow" + std::to_string(c))
73 .depthAttachment(shadowH, vkb::AttachmentOp::clear(shadowClear))
74 .record([this, c](vkb::FrameGraphPassContext &ctx) { recordShadowCascadePass(ctx, int(c)); });
75 }
76 }
77
78 if (i < gbufferSlots.size() && gbufferWidth > 0 && gbufferHeight > 0) {
79 auto &slot = gbufferSlots[i];
80 vkb::TextureDesc colorDesc;
81 colorDesc.format = colorFmt;
82 colorDesc.extent = vk::Extent3D{w, h, 1};
83 colorDesc.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment |
84 vk::ImageUsageFlagBits::eTransferSrc;
85 colorDesc.afterLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
86 auto normalH = graph->importTexture("gbNormal", slot.normal.image(), slot.normal.imageView(), colorDesc);
87 auto depthColorH =
88 graph->importTexture("gbDepthColor", slot.depthColor.image(), slot.depthColor.imageView(), colorDesc);
89 auto albedoH = graph->importTexture("gbAlbedo", slot.albedo.image(), slot.albedo.imageView(), colorDesc);
90 auto pbrParamsH =
91 graph->importTexture("gbPbrParams", slot.pbrParams.image(), slot.pbrParams.imageView(), colorDesc);
92 colorDesc.format = vk::Format::eR16G16B16A16Sfloat;
93 auto emissiveH =
94 graph->importTexture("gbEmissive", slot.emissive.image(), slot.emissive.imageView(), colorDesc);
95
96 vkb::TextureDesc depthDesc;
97 depthDesc.format = depthFmt;
98 depthDesc.extent = vk::Extent3D{w, h, 1};
99 depthDesc.aspect = vk::ImageAspectFlagBits::eDepth;
100 depthDesc.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eDepthStencilAttachment;
101 depthDesc.afterLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
102 auto depthH = graph->importTexture("gbHwDepth", slot.depth.image(), slot.depth.imageView(), depthDesc);
103
104 std::array<vk::ClearValue, 6> clears{};
105 clears[0].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
106 clears[1].color = vk::ClearColorValue(std::array<float, 4>{1, 1, 1, 1});
107 clears[2].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
108 clears[3].color = vk::ClearColorValue(std::array<float, 4>{0, 1, 1, 1});
109 clears[4].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
110 clears[5].depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
111 graph->addPass("gbuffer")
112 .colorAttachment(normalH, vkb::AttachmentOp::clear(clears[0]))
113 .colorAttachment(depthColorH, vkb::AttachmentOp::clear(clears[1]))
114 .colorAttachment(albedoH, vkb::AttachmentOp::clear(clears[2]))
115 .colorAttachment(pbrParamsH, vkb::AttachmentOp::clear(clears[3]))
116 .colorAttachment(emissiveH, vkb::AttachmentOp::clear(clears[4]))
117 .depthAttachment(depthH, vkb::AttachmentOp::clear(clears[5]))
118 .record([this](vkb::FrameGraphPassContext& ctx) { recordGBufferPassDraws(ctx); });
119 }
120 graph->compile();
121 deferredFrameGraphs_[i][variant] = std::move(graph);
122 }
123}
124
125void Graphics::recordShadowCascadePass(vkb::FrameGraphPassContext &ctx, int cascade) {
126 // Runs inside the FrameGraph's "shadow<cascade>" render-pass instance
127 // (already begun with a depth clear); only draw commands go here. The pass
128 // may be recorded on a JobSystem worker, so everything below must be
129 // read-only: shadowCascadeDraws was captured by endShadowPass on the main
130 // thread before the graph records.
131 auto &cb = ctx.commandBuffer();
132 // Adaptive CSM: each cascade may occupy only a top-left viewport of the
133 // shared depth-array layer. Local spot layers keep the full atlas extent.
134 uint32_t size = uint32_t(allocatedShadowMapSize > 0 ? allocatedShadowMapSize
135 : ShadowSchemeSettings::current().resolvedAtlasMapSize());
136 if (cascade >= 0 && cascade < ShadowConfig::kCascades && mesh3dShadows.active) {
137 size = uint32_t(std::max(1, mesh3dShadows.cascadeMapSizes[cascade]));
138 }
139 recordShadowCascadeDraws(cb, cascade, size);
140}
141
142void Graphics::recordShadowCascadeDraws(vk::CommandBuffer cb, int cascade, uint32_t size) {
143 setViewportAndScissor(cb, size, size);
144 vk::Pipeline boundPipeline{};
145 for (const auto &d : shadowCascadeDraws[cascade]) {
146 if (!d.mesh || !d.mesh->gpuHandle) continue;
147 const bool wantAlpha = d.alphaTest && shadowAlphaPipeline;
148 const bool skinned = d.skinSet && d.mesh->hasGpuSkinning();
149 vk::Pipeline wanted{};
150 if (skinned) {
151 wanted = wantAlpha ? (d.doubleSided ? shadowSkinAlphaPipeline : shadowSkinAlphaSingleSidedPipeline)
152 : (d.doubleSided ? shadowSkinPipeline : shadowSkinSingleSidedPipeline);
153 } else {
154 wanted = wantAlpha ? (d.doubleSided ? shadowAlphaPipeline : shadowAlphaSingleSidedPipeline)
155 : (d.doubleSided ? shadowPipeline : shadowSingleSidedPipeline);
156 }
157 if (wanted != boundPipeline) {
158 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, wanted);
159 boundPipeline = wanted;
160 }
161 auto *gpuMesh = static_cast<GpuMesh *>(d.mesh->gpuHandle);
162 if (skinned) {
163 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, skinPassPipelineLayout, 0, 1, &d.skinSet, 1,
164 &d.skinUboOffset);
165 } else if (wantAlpha) {
166 Texture *alb = d.albedo ? d.albedo : whiteTexture;
167 if (alb && alb->gpuHandle && texSetLayout) {
168 auto *gpuTex = static_cast<GpuTexture *>(alb->gpuHandle);
169 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, shadowAlphaPipelineLayout, 0, 1,
170 gpuTex->descriptorSet.ptr(), 0, nullptr);
171 }
172 }
173 if (!skinned) {
174 if (wantAlpha) {
175 ShadowAlphaPush push{d.mvp, d.lodFade};
176 cb.pushConstants(shadowAlphaPipelineLayout,
177 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
178 0, sizeof(push), &push);
179 } else {
180 cb.pushConstants(shadowPipelineLayout, vk::ShaderStageFlagBits::eVertex,
181 0, sizeof(glm::mat4), &d.mvp);
182 }
183 }
184 drawIndexedMesh(cb, *gpuMesh);
185 }
186}
187
188void Graphics::recordGBufferPassDraws(vkb::FrameGraphPassContext &ctx) {
189 EV_PROFILE_MODULE("graphics", "GBuffer.RecordDraws");
190 // Runs inside the FrameGraph's "gbuffer" render-pass instance (already
191 // begun with the planned clear values); only draw commands go here. The
192 // pass may be recorded on a JobSystem worker, so everything below must be
193 // read-only: gbufferPassDraws was captured on the main thread.
194 auto &cb = ctx.commandBuffer();
195 const vk::Extent2D extent = ctx.extent();
196 const uint32_t w = extent.width ? extent.width : uint32_t(gbufferWidth);
197 const uint32_t h = extent.height ? extent.height : uint32_t(gbufferHeight);
198 setViewportAndScissor(cb, w, h);
199 vk::Pipeline boundPipeline{};
200 size_t batchIndex = 0;
201 for (size_t drawIndex = 0; drawIndex < gbufferPassDraws.size();) {
202 const auto& d = gbufferPassDraws[drawIndex];
203 if (batchIndex < gbufferInstancedBatches.size() && gbufferInstancedBatches[batchIndex].first == drawIndex) {
204 const auto& batch = gbufferInstancedBatches[batchIndex++];
205 auto* gpuMesh = static_cast<GpuMesh*>(d.mesh->gpuHandle);
206 if (gbufferInstancedPipeline != boundPipeline) {
207 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, gbufferInstancedPipeline);
208 boundPipeline = gbufferInstancedPipeline;
209 }
210 Texture* alb = d.albedo ? d.albedo : whiteTexture;
211 auto* gpuTex = static_cast<GpuTexture*>(alb->gpuHandle);
212 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, gbufferPipelineLayout, 0, 1,
213 gpuTex->descriptorSet.ptr(), 0, nullptr);
214 cb.bindVertexBuffers(1, 1, &batch.buffer, &batch.offset);
215 drawIndexedMesh(cb, *gpuMesh, batch.count);
216 drawIndex += batch.count;
217 continue;
218 }
219 ++drawIndex;
220 if (!d.mesh || !d.mesh->gpuHandle) continue;
221 if (d.pbrPipeline) {
222 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, d.pbrPipeline);
223 boundPipeline = d.pbrPipeline;
224 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, d.pbrLayout, 0, 1, &d.pbrSet, 0, nullptr);
225 std::array<vk::Buffer, 11> uvBuffers;
226 uvBuffers.fill(d.pbrUv);
227 cb.bindVertexBuffers(1, uvBuffers, d.pbrUvOffsets);
228 drawIndexedMesh(cb, *static_cast<GpuMesh *>(d.mesh->gpuHandle));
229 continue;
230 }
231 const bool wantAlpha = d.alphaTest && gbufferAlphaPipeline;
232 const bool skinned = d.skinSet && d.mesh->hasGpuSkinning();
233 vk::Pipeline wanted = skinned ? (wantAlpha ? gbufferSkinAlphaPipeline : gbufferSkinPipeline)
234 : (wantAlpha ? gbufferAlphaPipeline : gbufferPipeline);
235 if (wanted != boundPipeline) {
236 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, wanted);
237 boundPipeline = wanted;
238 }
239 auto *gpuMesh = static_cast<GpuMesh *>(d.mesh->gpuHandle);
240 Texture *alb = d.albedo ? d.albedo : whiteTexture;
241 if (skinned) {
242 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, skinPassPipelineLayout, 0, 1, &d.skinSet, 1,
243 &d.skinUboOffset);
244 } else if (alb && alb->gpuHandle && texSetLayout) {
245 auto *gpuTex = static_cast<GpuTexture *>(alb->gpuHandle);
246 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, gbufferPipelineLayout, 0, 1,
247 gpuTex->descriptorSet.ptr(), 0, nullptr);
248 }
249 if (!skinned)
250 cb.pushConstants(gbufferPipelineLayout,
251 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0,
252 sizeof(GBufferPush), &d.push);
253 drawIndexedMesh(cb, *gpuMesh);
254 }
255}
256
257void Graphics::prepareGBufferInstanceBatches() {
258 EV_PROFILE_MODULE("graphics", "GBuffer.PrepareInstances");
259 gbufferInstancedBatches.clear();
260 if (!gbufferPending || !gbufferInstancedPipeline || gbufferSlots.empty()) return;
261 size_t total = 0;
262 for (size_t i = 0; i < gbufferPassDraws.size();) {
263 const auto& first = gbufferPassDraws[i];
264 if (!first.mesh || !first.mesh->gpuHandle || first.mesh->hasGpuSkinning() || first.alphaTest || first.skinSet ||
265 first.pbrPipeline) {
266 ++i;
267 continue;
268 }
269 size_t end = i + 1;
270 while (end < gbufferPassDraws.size()) {
271 const auto& next = gbufferPassDraws[end];
272 if (next.mesh != first.mesh || next.albedo != first.albedo || next.alphaTest || next.skinSet ||
273 next.pbrPipeline)
274 break;
275 ++end;
276 }
277 if (end - i >= 128) {
278 gbufferInstancedBatches.push_back({i, uint32_t(end - i), {}, vk::DeviceSize(total * sizeof(GBufferPush))});
279 total += end - i;
280 }
281 i = end;
282 }
283 if (total == 0) return;
284 auto& slot = *currentGBufferSlot();
285 if (slot.instanceCapacity < total) {
286 const size_t capacity = std::max(total, slot.instanceCapacity * 2);
287 slot.instanceBuffer =
288 vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eVertexBuffer, capacity * sizeof(GBufferPush),
289 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
290 slot.instanceCapacity = capacity;
291 }
292 auto* mapped = static_cast<GBufferPush*>(slot.instanceBuffer.map());
293 size_t cursor = 0;
294 for (auto& batch : gbufferInstancedBatches) {
295 batch.buffer = slot.instanceBuffer.buffer;
296 batch.offset = vk::DeviceSize(cursor * sizeof(GBufferPush));
297 for (uint32_t j = 0; j < batch.count; ++j) mapped[cursor++] = gbufferPassDraws[batch.first + j].push;
298 }
299 slot.instanceBuffer.unmap();
300}
301
302void Graphics::recordDeferredFrameGraph() {
303 // Voxel / script begin3DFrame paths never fill G-buffer or CSM. Submitting
304 // the empty four-pass graph every frame still waits on the JobSystem and
305 // can hitch the orbit camera (MAILBOX then shows a newer pose, then an
306 // older in-flight image — a short reverse jump).
307 if (!gbufferPending && shadowPendingMask == 0) {
308 dropPendingOffscreenPasses();
309 return;
310 }
311 const size_t slot = currentFrameSlot();
312 if (deferredGraphRecorded_ && deferredGraphRecordedSlot_ == slot) {
313 // render3D can be called several times per script frame (e.g. the
314 // render tests call it 3x before present). The deferred graph's command
315 // buffers must only be recorded once per slot per frame — re-recording
316 // them while the previous submit is still in flight would reset
317 // in-use command buffers (UB, GPU hang).
318 return;
319 }
320 auto *graph = currentDeferredFrameGraph();
321 if (!graph && (!shadowMaps.empty() || !gbufferSlots.empty())) {
322 // Shadows can be enabled without a G-buffer pass (or vice versa); build
323 // the deferred graphs on demand from whatever targets exist today.
324 buildDeferredFrameGraphs();
325 graph = currentDeferredFrameGraph();
326 }
327 if (!graph || !gbufferPipeline || !gbufferRenderPass || !shadowPipeline) {
328 dropPendingOffscreenPasses();
329 return;
330 }
331 // Acquisition can rebuild the swapchain and change the slot after
332 // endGBufferPass published its targets. Consumers must sample the slot
333 // this graph actually writes, including the first frame after a resize.
334 if (gbufferPending && renderControl_) {
335 auto *targets = currentGBufferSlot();
336 renderControl_->getGBuffer()->setTargets(gbufferWidth, gbufferHeight, &targets->depthColorTex,
337 &targets->normalTex, &targets->albedoTex, &targets->depthTex,
338 &targets->pbrParamsTex, &targets->emissiveTex);
339 }
340 prepareGBufferInstanceBatches();
341 // Record the selected deferred plan (G-buffer, plus shadow layers only
342 // when updates are pending) with the JobSystem executor, then submit on the
343 // graphics queue before the swapchain pass begins. Layout transitions and
344 // the render-pass instances are planned by the FrameGraph. Same-queue
345 // submission order plus the present slot fence (waited in Present::begin)
346 // keep this slot's graph command buffers safe to reuse two frames later.
347 auto *jobs = thread::Thread::create()->getJobSystem();
348 jobs->beginFrame(); // idempotent wait; recycles the per-frame arena
349 // Re-plan every frame (cheap; device objects are cached) so the graph is
350 // in the compiled phase for this record cycle — vkb::FrameGraph enforces
351 // build -> compile -> record -> submit and record() exactly once per
352 // compile.
353 {
354 EV_PROFILE_MODULE("graphics", "DeferredGraph.Compile");
355 graph->compile();
356 }
357 // Parallel executor: each pass owns a dedicated command pool (one pool per
358 // frame slot per pass), so the workers never share a pool while recording
359 // concurrently — the Vulkan external-synchronization rule for command
360 // pools is satisfied structurally.
361 {
362 EV_PROFILE_MODULE("graphics", "DeferredGraph.RecordAndJoin");
363 recordFrameGraphWithJobSystem(*graph, jobs, deferredRecordingState_);
364 }
365 {
366 EV_PROFILE_MODULE("graphics", "DeferredGraph.Submit");
367 submitGpuTimingPrefix();
368 graph->submit();
369 }
370 // Match shadowDesc.afterLayout: descriptors must describe the layout the
371 // graph actually submitted, including clear-only shadow passes.
372 if (!shadowMaps.empty()) currentShadowMap().image.setCurrentLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
373 jobs->endFrame();
374 for (auto &d : shadowCascadeDraws) d.clear();
375 gbufferPassDraws.clear();
376 gbufferInstancedBatches.clear();
377 shadowPendingMask = 0;
378 gbufferPending = false;
379 deferredGraphRecorded_ = true;
380 deferredGraphRecordedSlot_ = slot;
381}
382
383} // namespace eve::graphics::vulkan
float w
Definition AnimClip.cpp:738
std::size_t cursor
std::string variant
std::vector< FieldTarget > targets
std::uint32_t capacity
vk::UniqueImage image
float u
Definition Grass.cpp:233
std::int32_t c
std::int32_t first
int h
bool doubleSided
std::map< std::string, std::vector< std::string > > graph
Definition Package.cpp:173
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
float d
std::string slot
size_t end
double current
float size
Definition TreeMesh.cpp:158
virtual void reset()
Resets the current color, background color, line style, and so forth.
void push(bool all)
Pushes .
std::unique_ptr< RenderControl > renderControl_
Definition Graphics.h:2340
void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth) override
Clears .
void recordFrameGraphWithJobSystem(vkb::FrameGraph &graph, eve::thread::JobSystem *jobs, FrameGraphRecordingState &state)
Record a vkb::FrameGraph with the engine JobSystem as the parallel recording executor,...
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
static constexpr int kCascades
Definition Shadow.h:24
static constexpr int kTotalLayers
Definition Shadow.h:27
int cascadeMapSizes[ShadowConfig::kCascades]
Per-cascade render viewport edge length (texels); drives shadow pass viewport.
Definition Shadow.h:66