Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Common/GPU/Vulkan/VulkanQueueRunner.cpp
3187 views
1
#include <unordered_map>
2
3
#include "Common/GPU/DataFormat.h"
4
#include "Common/GPU/Vulkan/VulkanQueueRunner.h"
5
#include "Common/GPU/Vulkan/VulkanRenderManager.h"
6
#include "Common/Log.h"
7
#include "Common/TimeUtil.h"
8
9
using namespace PPSSPP_VK;
10
11
// Debug help: adb logcat -s DEBUG AndroidRuntime PPSSPPNativeActivity PPSSPP NativeGLView NativeRenderer NativeSurfaceView PowerSaveModeReceiver InputDeviceState PpssppActivity CameraHelper
12
13
static void MergeRenderAreaRectInto(VkRect2D *dest, const VkRect2D &src) {
14
if (dest->offset.x > src.offset.x) {
15
dest->extent.width += (dest->offset.x - src.offset.x);
16
dest->offset.x = src.offset.x;
17
}
18
if (dest->offset.y > src.offset.y) {
19
dest->extent.height += (dest->offset.y - src.offset.y);
20
dest->offset.y = src.offset.y;
21
}
22
if (dest->offset.x + dest->extent.width < src.offset.x + src.extent.width) {
23
dest->extent.width = src.offset.x + src.extent.width - dest->offset.x;
24
}
25
if (dest->offset.y + dest->extent.height < src.offset.y + src.extent.height) {
26
dest->extent.height = src.offset.y + src.extent.height - dest->offset.y;
27
}
28
}
29
30
// We need to take the "max" of the features used in the two render passes.
31
RenderPassType MergeRPTypes(RenderPassType a, RenderPassType b) {
32
// Either both are backbuffer type, or neither are.
33
// These can't merge with other renderpasses
34
if (a == RenderPassType::BACKBUFFER || b == RenderPassType::BACKBUFFER) {
35
_dbg_assert_(a == b);
36
return a;
37
}
38
39
_dbg_assert_((a & RenderPassType::MULTIVIEW) == (b & RenderPassType::MULTIVIEW));
40
41
// The rest we can just OR together to get the maximum feature set.
42
return (RenderPassType)((u32)a | (u32)b);
43
}
44
45
void VulkanQueueRunner::CreateDeviceObjects() {
46
INFO_LOG(Log::G3D, "VulkanQueueRunner::CreateDeviceObjects");
47
48
RPKey key{
49
VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR,
50
VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE,
51
};
52
compatibleRenderPass_ = GetRenderPass(key);
53
54
#if 0
55
// Just to check whether it makes sense to split some of these. drawidx is way bigger than the others...
56
// We should probably just move to variable-size data in a raw buffer anyway...
57
VkRenderData rd;
58
INFO_LOG(Log::G3D, "sizeof(pipeline): %d", (int)sizeof(rd.pipeline));
59
INFO_LOG(Log::G3D, "sizeof(draw): %d", (int)sizeof(rd.draw));
60
INFO_LOG(Log::G3D, "sizeof(drawidx): %d", (int)sizeof(rd.drawIndexed));
61
INFO_LOG(Log::G3D, "sizeof(clear): %d", (int)sizeof(rd.clear));
62
INFO_LOG(Log::G3D, "sizeof(viewport): %d", (int)sizeof(rd.viewport));
63
INFO_LOG(Log::G3D, "sizeof(scissor): %d", (int)sizeof(rd.scissor));
64
INFO_LOG(Log::G3D, "sizeof(blendColor): %d", (int)sizeof(rd.blendColor));
65
INFO_LOG(Log::G3D, "sizeof(push): %d", (int)sizeof(rd.push));
66
#endif
67
}
68
69
void VulkanQueueRunner::DestroyDeviceObjects() {
70
INFO_LOG(Log::G3D, "VulkanQueueRunner::DestroyDeviceObjects");
71
72
syncReadback_.Destroy(vulkan_);
73
74
renderPasses_.IterateMut([&](const RPKey &rpkey, VKRRenderPass *rp) {
75
_dbg_assert_(rp);
76
rp->Destroy(vulkan_);
77
delete rp;
78
});
79
renderPasses_.Clear();
80
}
81
82
bool VulkanQueueRunner::InitBackbufferFramebuffers(int width, int height, FrameDataShared &frameDataShared) {
83
VkResult res;
84
// We share the same depth buffer but have multiple color buffers, see the loop below.
85
VkImageView attachments[2] = { VK_NULL_HANDLE, depth_.view };
86
87
VkFramebufferCreateInfo fb_info = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
88
fb_info.renderPass = GetCompatibleRenderPass()->Get(vulkan_, RenderPassType::BACKBUFFER, VK_SAMPLE_COUNT_1_BIT);
89
fb_info.attachmentCount = 2;
90
fb_info.pAttachments = attachments;
91
fb_info.width = width;
92
fb_info.height = height;
93
fb_info.layers = 1;
94
95
framebuffers_.resize(frameDataShared.swapchainImageCount_);
96
97
for (uint32_t i = 0; i < frameDataShared.swapchainImageCount_; i++) {
98
attachments[0] = frameDataShared.swapchainImages_[i].view;
99
res = vkCreateFramebuffer(vulkan_->GetDevice(), &fb_info, nullptr, &framebuffers_[i]);
100
_dbg_assert_(res == VK_SUCCESS);
101
if (res != VK_SUCCESS) {
102
framebuffers_.clear();
103
return false;
104
}
105
}
106
107
return true;
108
}
109
110
bool VulkanQueueRunner::InitDepthStencilBuffer(VkCommandBuffer cmd, VulkanBarrierBatch *barriers) {
111
const VkFormat depth_format = vulkan_->GetDeviceInfo().preferredDepthStencilFormat;
112
int aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
113
VkImageCreateInfo image_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
114
image_info.imageType = VK_IMAGE_TYPE_2D;
115
image_info.format = depth_format;
116
image_info.extent.width = vulkan_->GetBackbufferWidth();
117
image_info.extent.height = vulkan_->GetBackbufferHeight();
118
image_info.extent.depth = 1;
119
image_info.mipLevels = 1;
120
image_info.arrayLayers = 1;
121
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
122
image_info.queueFamilyIndexCount = 0;
123
image_info.pQueueFamilyIndices = nullptr;
124
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
125
image_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;
126
image_info.flags = 0;
127
128
depth_.format = depth_format;
129
130
VmaAllocationCreateInfo allocCreateInfo{};
131
VmaAllocationInfo allocInfo{};
132
133
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
134
135
VkResult res = vmaCreateImage(vulkan_->Allocator(), &image_info, &allocCreateInfo, &depth_.image, &depth_.alloc, &allocInfo);
136
_dbg_assert_(res == VK_SUCCESS);
137
if (res != VK_SUCCESS)
138
return false;
139
140
vulkan_->SetDebugName(depth_.image, VK_OBJECT_TYPE_IMAGE, "BackbufferDepth");
141
142
VkImageMemoryBarrier *barrier = barriers->Add(depth_.image,
143
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
144
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, 0);
145
barrier->subresourceRange.aspectMask = aspectMask;
146
barrier->oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
147
barrier->newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
148
barrier->srcAccessMask = 0;
149
barrier->dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
150
151
VkImageViewCreateInfo depth_view_info = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
152
depth_view_info.image = depth_.image;
153
depth_view_info.format = depth_format;
154
depth_view_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
155
depth_view_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
156
depth_view_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
157
depth_view_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
158
depth_view_info.subresourceRange.aspectMask = aspectMask;
159
depth_view_info.subresourceRange.baseMipLevel = 0;
160
depth_view_info.subresourceRange.levelCount = 1;
161
depth_view_info.subresourceRange.baseArrayLayer = 0;
162
depth_view_info.subresourceRange.layerCount = 1;
163
depth_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
164
depth_view_info.flags = 0;
165
166
VkDevice device = vulkan_->GetDevice();
167
168
res = vkCreateImageView(device, &depth_view_info, NULL, &depth_.view);
169
vulkan_->SetDebugName(depth_.view, VK_OBJECT_TYPE_IMAGE_VIEW, "depth_stencil_backbuffer");
170
_dbg_assert_(res == VK_SUCCESS);
171
if (res != VK_SUCCESS)
172
return false;
173
174
return true;
175
}
176
177
178
void VulkanQueueRunner::DestroyBackBuffers() {
179
if (depth_.view) {
180
vulkan_->Delete().QueueDeleteImageView(depth_.view);
181
}
182
if (depth_.image) {
183
_dbg_assert_(depth_.alloc);
184
vulkan_->Delete().QueueDeleteImageAllocation(depth_.image, depth_.alloc);
185
}
186
depth_ = {};
187
for (uint32_t i = 0; i < framebuffers_.size(); i++) {
188
_dbg_assert_(framebuffers_[i] != VK_NULL_HANDLE);
189
vulkan_->Delete().QueueDeleteFramebuffer(framebuffers_[i]);
190
}
191
framebuffers_.clear();
192
193
INFO_LOG(Log::G3D, "Backbuffers destroyed");
194
}
195
196
// Self-dependency: https://github.com/gpuweb/gpuweb/issues/442#issuecomment-547604827
197
// Also see https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-pipeline-barriers-subpass-self-dependencies
198
VKRRenderPass *VulkanQueueRunner::GetRenderPass(const RPKey &key) {
199
VKRRenderPass *foundPass;
200
if (renderPasses_.Get(key, &foundPass)) {
201
return foundPass;
202
}
203
204
VKRRenderPass *pass = new VKRRenderPass(key);
205
renderPasses_.Insert(key, pass);
206
return pass;
207
}
208
209
void VulkanQueueRunner::PreprocessSteps(std::vector<VKRStep *> &steps) {
210
// Optimizes renderpasses, then sequences them.
211
// Planned optimizations:
212
// * Create copies of render target that are rendered to multiple times and textured from in sequence, and push those render passes
213
// as early as possible in the frame (Wipeout billboards). This will require taking over more of descriptor management so we can
214
// substitute descriptors, alternatively using texture array layers creatively.
215
216
for (int j = 0; j < (int)steps.size(); j++) {
217
if (steps[j]->stepType == VKRStepType::RENDER &&
218
steps[j]->render.framebuffer) {
219
if (steps[j]->render.finalColorLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
220
steps[j]->render.finalColorLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
221
}
222
if (steps[j]->render.finalDepthStencilLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
223
steps[j]->render.finalDepthStencilLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
224
}
225
}
226
}
227
228
for (int j = 0; j < (int)steps.size() - 1; j++) {
229
// Push down empty "Clear/Store" renderpasses, and merge them with the first "Load/Store" to the same framebuffer.
230
if (steps.size() > 1 && steps[j]->stepType == VKRStepType::RENDER &&
231
steps[j]->render.numDraws == 0 &&
232
steps[j]->render.numReads == 0 &&
233
steps[j]->render.colorLoad == VKRRenderPassLoadAction::CLEAR &&
234
steps[j]->render.stencilLoad == VKRRenderPassLoadAction::CLEAR &&
235
steps[j]->render.depthLoad == VKRRenderPassLoadAction::CLEAR) {
236
237
// Drop the clear step, and merge it into the next step that touches the same framebuffer.
238
for (int i = j + 1; i < (int)steps.size(); i++) {
239
if (steps[i]->stepType == VKRStepType::RENDER &&
240
steps[i]->render.framebuffer == steps[j]->render.framebuffer) {
241
if (steps[i]->render.colorLoad != VKRRenderPassLoadAction::CLEAR) {
242
steps[i]->render.colorLoad = VKRRenderPassLoadAction::CLEAR;
243
steps[i]->render.clearColor = steps[j]->render.clearColor;
244
}
245
if (steps[i]->render.depthLoad != VKRRenderPassLoadAction::CLEAR) {
246
steps[i]->render.depthLoad = VKRRenderPassLoadAction::CLEAR;
247
steps[i]->render.clearDepth = steps[j]->render.clearDepth;
248
}
249
if (steps[i]->render.stencilLoad != VKRRenderPassLoadAction::CLEAR) {
250
steps[i]->render.stencilLoad = VKRRenderPassLoadAction::CLEAR;
251
steps[i]->render.clearStencil = steps[j]->render.clearStencil;
252
}
253
MergeRenderAreaRectInto(&steps[i]->render.renderArea, steps[j]->render.renderArea);
254
steps[i]->render.renderPassType = MergeRPTypes(steps[i]->render.renderPassType, steps[j]->render.renderPassType);
255
steps[i]->render.numDraws += steps[j]->render.numDraws;
256
steps[i]->render.numReads += steps[j]->render.numReads;
257
// Cheaply skip the first step.
258
steps[j]->stepType = VKRStepType::RENDER_SKIP;
259
break;
260
} else if (steps[i]->stepType == VKRStepType::COPY &&
261
steps[i]->copy.src == steps[j]->render.framebuffer) {
262
// Can't eliminate the clear if a game copies from it before it's
263
// rendered to. However this should be rare.
264
// TODO: This should never happen when we check numReads now.
265
break;
266
}
267
}
268
}
269
}
270
271
// Queue hacks.
272
if (hacksEnabled_) {
273
if (hacksEnabled_ & QUEUE_HACK_MGS2_ACID) {
274
// Massive speedup due to re-ordering.
275
ApplyMGSHack(steps);
276
}
277
if (hacksEnabled_ & QUEUE_HACK_SONIC) {
278
ApplySonicHack(steps);
279
}
280
if (hacksEnabled_ & QUEUE_HACK_RENDERPASS_MERGE) {
281
ApplyRenderPassMerge(steps);
282
}
283
}
284
}
285
286
void VulkanQueueRunner::RunSteps(std::vector<VKRStep *> &steps, int curFrame, FrameData &frameData, FrameDataShared &frameDataShared, bool keepSteps) {
287
QueueProfileContext *profile = frameData.profile.enabled ? &frameData.profile : nullptr;
288
289
if (profile)
290
profile->cpuStartTime = time_now_d();
291
292
bool emitLabels = vulkan_->Extensions().EXT_debug_utils;
293
294
VkCommandBuffer cmd = frameData.hasPresentCommands ? frameData.presentCmd : frameData.mainCmd;
295
296
for (size_t i = 0; i < steps.size(); i++) {
297
const VKRStep &step = *steps[i];
298
if (emitLabels) {
299
VkDebugUtilsLabelEXT labelInfo{ VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT };
300
char temp[128];
301
if (step.stepType == VKRStepType::RENDER && step.render.framebuffer) {
302
snprintf(temp, sizeof(temp), "%s: %s", step.tag, step.render.framebuffer->Tag());
303
labelInfo.pLabelName = temp;
304
} else {
305
labelInfo.pLabelName = step.tag;
306
}
307
vkCmdBeginDebugUtilsLabelEXT(cmd, &labelInfo);
308
}
309
310
switch (step.stepType) {
311
case VKRStepType::RENDER:
312
{
313
bool perform = true;
314
if (!step.render.framebuffer) {
315
if (emitLabels) {
316
vkCmdEndDebugUtilsLabelEXT(cmd);
317
}
318
frameData.Submit(vulkan_, FrameSubmitType::Pending, frameDataShared);
319
320
// If the window is minimized and we don't have a swap chain, don't bother.
321
if (frameDataShared.swapchainImageCount_ > 0) {
322
// When stepping in the GE debugger, we can end up here multiple times in a "frame".
323
// So only acquire once.
324
if (!frameData.hasAcquired) {
325
frameData.AcquireNextImage(vulkan_);
326
SetBackbuffer(framebuffers_[frameData.curSwapchainImage], frameDataShared.swapchainImages_[frameData.curSwapchainImage].image);
327
}
328
329
if (!frameData.hasPresentCommands) {
330
// A RENDER step rendering to the backbuffer is normally the last step that happens in a frame,
331
// unless taking a screenshot, in which case there might be a READBACK_IMAGE after it.
332
// This is why we have to switch cmd to presentCmd, in this case.
333
VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
334
begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
335
vkBeginCommandBuffer(frameData.presentCmd, &begin);
336
frameData.hasPresentCommands = true;
337
}
338
cmd = frameData.presentCmd;
339
if (emitLabels) {
340
VkDebugUtilsLabelEXT labelInfo{VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT};
341
labelInfo.pLabelName = "present";
342
vkCmdBeginDebugUtilsLabelEXT(cmd, &labelInfo);
343
}
344
} else {
345
perform = false;
346
}
347
}
348
if (perform) {
349
PerformRenderPass(step, cmd, curFrame, frameData.profile);
350
} else {
351
frameData.skipSwap = true;
352
}
353
break;
354
}
355
case VKRStepType::COPY:
356
PerformCopy(step, cmd);
357
break;
358
case VKRStepType::BLIT:
359
PerformBlit(step, cmd);
360
break;
361
case VKRStepType::READBACK:
362
PerformReadback(step, cmd, frameData);
363
break;
364
case VKRStepType::READBACK_IMAGE:
365
PerformReadbackImage(step, cmd);
366
break;
367
case VKRStepType::RENDER_SKIP:
368
break;
369
}
370
371
if (profile && profile->timestampsEnabled && profile->timestampDescriptions.size() + 1 < MAX_TIMESTAMP_QUERIES) {
372
vkCmdWriteTimestamp(cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, profile->queryPool, (uint32_t)profile->timestampDescriptions.size());
373
profile->timestampDescriptions.push_back(StepToString(vulkan_, step));
374
}
375
376
if (emitLabels) {
377
vkCmdEndDebugUtilsLabelEXT(cmd);
378
}
379
}
380
381
// Deleting all in one go should be easier on the instruction cache than deleting
382
// them as we go - and easier to debug because we can look backwards in the frame.
383
if (!keepSteps) {
384
for (auto step : steps) {
385
delete step;
386
}
387
steps.clear();
388
}
389
390
if (profile)
391
profile->cpuEndTime = time_now_d();
392
}
393
394
void VulkanQueueRunner::ApplyMGSHack(std::vector<VKRStep *> &steps) {
395
// Really need a sane way to express transforms of steps.
396
397
// We want to turn a sequence of copy,render(1),copy,render(1),copy,render(1) to copy,copy,copy,render(n).
398
399
// TODO: Where does this first part trigger? The below depal part triggers reliably in Acid2.
400
401
for (int i = 0; i < (int)steps.size() - 3; i++) {
402
int last = -1;
403
if (!(steps[i]->stepType == VKRStepType::COPY &&
404
steps[i + 1]->stepType == VKRStepType::RENDER &&
405
steps[i + 2]->stepType == VKRStepType::COPY &&
406
steps[i + 1]->render.numDraws == 1 &&
407
steps[i]->copy.dst == steps[i + 2]->copy.dst))
408
continue;
409
// Looks promising! Let's start by finding the last one.
410
for (int j = i; j < (int)steps.size(); j++) {
411
switch (steps[j]->stepType) {
412
case VKRStepType::RENDER:
413
if (steps[j]->render.numDraws > 1)
414
last = j - 1;
415
// should really also check descriptor sets...
416
if (steps[j]->commands.size()) {
417
const VkRenderData &cmd = steps[j]->commands.back();
418
if (cmd.cmd == VKRRenderCommand::DRAW_INDEXED && cmd.draw.count != 6)
419
last = j - 1;
420
}
421
break;
422
case VKRStepType::COPY:
423
if (steps[j]->copy.dst != steps[i]->copy.dst)
424
last = j - 1;
425
break;
426
default:
427
break;
428
}
429
if (last != -1)
430
break;
431
}
432
433
if (last != -1) {
434
// We've got a sequence from i to last that needs reordering.
435
// First, let's sort it, keeping the same length.
436
std::vector<VKRStep *> copies;
437
std::vector<VKRStep *> renders;
438
copies.reserve((last - i) / 2);
439
renders.reserve((last - i) / 2);
440
for (int n = i; n <= last; n++) {
441
if (steps[n]->stepType == VKRStepType::COPY)
442
copies.push_back(steps[n]);
443
else if (steps[n]->stepType == VKRStepType::RENDER)
444
renders.push_back(steps[n]);
445
}
446
// Write the copies back. TODO: Combine them too.
447
for (int j = 0; j < (int)copies.size(); j++) {
448
steps[i + j] = copies[j];
449
}
450
451
const int firstRender = i + (int)copies.size();
452
453
// Write the renders back (so they will be deleted properly).
454
for (int j = 0; j < (int)renders.size(); j++) {
455
steps[firstRender + j] = renders[j];
456
}
457
_assert_(steps[firstRender]->stepType == VKRStepType::RENDER);
458
// Combine the renders.
459
for (int j = 1; j < (int)renders.size(); j++) {
460
steps[firstRender]->commands.reserve(renders[j]->commands.size());
461
for (int k = 0; k < (int)renders[j]->commands.size(); k++) {
462
steps[firstRender]->commands.push_back(renders[j]->commands[k]);
463
}
464
MergeRenderAreaRectInto(&steps[firstRender]->render.renderArea, renders[j]->render.renderArea);
465
// Easier than removing them from the list, though that might be the better option.
466
steps[firstRender + j]->stepType = VKRStepType::RENDER_SKIP;
467
steps[firstRender + j]->commands.clear();
468
}
469
// We're done.
470
// INFO_LOG(Log::G3D, "MGS HACK part 1: copies: %d renders: %d", (int)copies.size(), (int)renders.size());
471
break;
472
}
473
}
474
475
// There's also a post processing effect using depals that's just brutal in some parts
476
// of the game.
477
for (int i = 0; i < (int)steps.size() - 3; i++) {
478
int last = -1;
479
if (!(steps[i]->stepType == VKRStepType::RENDER &&
480
steps[i + 1]->stepType == VKRStepType::RENDER &&
481
steps[i + 2]->stepType == VKRStepType::RENDER &&
482
steps[i]->render.numDraws == 1 &&
483
steps[i + 1]->render.numDraws == 1 &&
484
steps[i + 2]->render.numDraws == 1 &&
485
steps[i]->render.colorLoad == VKRRenderPassLoadAction::DONT_CARE &&
486
steps[i + 1]->render.colorLoad == VKRRenderPassLoadAction::KEEP &&
487
steps[i + 2]->render.colorLoad == VKRRenderPassLoadAction::DONT_CARE)) {
488
continue;
489
}
490
VKRFramebuffer *depalFramebuffer = steps[i]->render.framebuffer;
491
VKRFramebuffer *targetFramebuffer = steps[i + 1]->render.framebuffer;
492
// OK, found the start of a post-process sequence. Let's scan until we find the end.
493
for (int j = i; j < (int)steps.size() - 3; j++) {
494
if (((j - i) & 1) == 0) {
495
// This should be a depal draw.
496
if (steps[j]->render.numDraws != 1)
497
break;
498
if (steps[j]->commands.size() > 5) // TODO: Not the greatest heuristic! This may change if we merge commands.
499
break;
500
if (steps[j]->render.colorLoad != VKRRenderPassLoadAction::DONT_CARE)
501
break;
502
if (steps[j]->render.framebuffer != depalFramebuffer)
503
break;
504
last = j;
505
} else {
506
// This should be a target draw.
507
if (steps[j]->render.numDraws != 1)
508
break;
509
if (steps[j]->commands.size() > 5) // TODO: Not the greatest heuristic! This may change if we merge commands.
510
break;
511
if (steps[j]->render.colorLoad != VKRRenderPassLoadAction::KEEP)
512
break;
513
if (steps[j]->render.framebuffer != targetFramebuffer)
514
break;
515
last = j;
516
}
517
}
518
519
if (last == -1)
520
continue;
521
522
if (last > 479) {
523
// Avoid some problems with the hack (oil slick crash). Some additional commands get added there that
524
// confuses this merging. NOTE: This is not really a solution! See #20306.
525
last = 479;
526
}
527
528
int minScissorX = 10000;
529
int minScissorY = 10000;
530
int maxScissorX = 0;
531
int maxScissorY = 0;
532
533
// Combine the depal renders. Also record scissor bounds.
534
for (int j = i + 2; j <= last + 1; j += 2) {
535
for (int k = 0; k < (int)steps[j]->commands.size(); k++) {
536
switch (steps[j]->commands[k].cmd) {
537
case VKRRenderCommand::DRAW:
538
case VKRRenderCommand::DRAW_INDEXED:
539
steps[i]->commands.push_back(steps[j]->commands[k]);
540
break;
541
case VKRRenderCommand::SCISSOR:
542
{
543
// TODO: Merge scissor rectangles.
544
const auto &rc = steps[j]->commands[k].scissor.scissor;
545
if (rc.offset.x < minScissorX) {
546
minScissorX = rc.offset.x;
547
}
548
if (rc.offset.y < minScissorY) {
549
minScissorY = rc.offset.y;
550
}
551
if (rc.offset.x + rc.extent.width > maxScissorX) {
552
maxScissorX = rc.offset.x + rc.extent.width;
553
}
554
if (rc.offset.y + rc.extent.height > maxScissorY) {
555
maxScissorY = rc.offset.y + rc.extent.height;
556
}
557
break;
558
}
559
default:
560
break;
561
}
562
}
563
MergeRenderAreaRectInto(&steps[i]->render.renderArea, steps[j]->render.renderArea);
564
steps[j]->stepType = VKRStepType::RENDER_SKIP;
565
}
566
567
// Update the scissor in the first draw.
568
minScissorX = std::max(0, minScissorX);
569
minScissorY = std::max(0, minScissorY);
570
if (maxScissorX > minScissorX && maxScissorY > minScissorY) {
571
for (int k = 0; k < steps[i]->commands.size(); k++) {
572
if (steps[i]->commands[k].cmd == VKRRenderCommand::SCISSOR) {
573
auto &rc = steps[i]->commands[k].scissor.scissor;
574
rc.offset.x = minScissorX;
575
rc.offset.y = minScissorY;
576
rc.extent.width = maxScissorX - minScissorX;
577
rc.extent.height = maxScissorY - minScissorY;
578
break;
579
}
580
}
581
}
582
583
// Combine the target renders.
584
for (int j = i + 3; j <= last; j += 2) {
585
for (int k = 0; k < (int)steps[j]->commands.size(); k++) {
586
switch (steps[j]->commands[k].cmd) {
587
case VKRRenderCommand::DRAW:
588
case VKRRenderCommand::DRAW_INDEXED:
589
steps[i + 1]->commands.push_back(steps[j]->commands[k]);
590
break;
591
default:
592
break;
593
}
594
}
595
MergeRenderAreaRectInto(&steps[i + 1]->render.renderArea, steps[j]->render.renderArea);
596
steps[j]->stepType = VKRStepType::RENDER_SKIP;
597
}
598
599
// INFO_LOG(Log::G3D, "MGS HACK part 2: %d-%d : %d (total steps: %d)", i, last, (last - i), (int)steps.size());
600
601
// We're done - we only expect one of these sequences per frame.
602
break;
603
}
604
}
605
606
void VulkanQueueRunner::ApplySonicHack(std::vector<VKRStep *> &steps) {
607
// We want to turn a sequence of render(3),render(1),render(6),render(1),render(6),render(1),render(3) to
608
// render(1), render(1), render(1), render(6), render(6), render(6)
609
610
for (int i = 0; i < (int)steps.size() - 4; i++) {
611
int last = -1;
612
if (!(steps[i]->stepType == VKRStepType::RENDER &&
613
steps[i + 1]->stepType == VKRStepType::RENDER &&
614
steps[i + 2]->stepType == VKRStepType::RENDER &&
615
steps[i + 3]->stepType == VKRStepType::RENDER &&
616
steps[i]->render.numDraws == 3 &&
617
steps[i + 1]->render.numDraws == 1 &&
618
steps[i + 2]->render.numDraws == 6 &&
619
steps[i + 3]->render.numDraws == 1 &&
620
steps[i]->render.framebuffer == steps[i + 2]->render.framebuffer &&
621
steps[i + 1]->render.framebuffer == steps[i + 3]->render.framebuffer))
622
continue;
623
// Looks promising! Let's start by finding the last one.
624
for (int j = i; j < (int)steps.size(); j++) {
625
switch (steps[j]->stepType) {
626
case VKRStepType::RENDER:
627
if ((j - i) & 1) {
628
if (steps[j]->render.framebuffer != steps[i + 1]->render.framebuffer)
629
last = j - 1;
630
if (steps[j]->render.numDraws != 1)
631
last = j - 1;
632
} else {
633
if (steps[j]->render.framebuffer != steps[i]->render.framebuffer)
634
last = j - 1;
635
if (steps[j]->render.numDraws != 3 && steps[j]->render.numDraws != 6)
636
last = j - 1;
637
}
638
break;
639
default:
640
break;
641
}
642
if (last != -1)
643
break;
644
}
645
646
if (last != -1) {
647
// We've got a sequence from i to last that needs reordering.
648
// First, let's sort it, keeping the same length.
649
std::vector<VKRStep *> type1;
650
std::vector<VKRStep *> type2;
651
type1.reserve((last - i) / 2);
652
type2.reserve((last - i) / 2);
653
for (int n = i; n <= last; n++) {
654
if (steps[n]->render.framebuffer == steps[i]->render.framebuffer)
655
type1.push_back(steps[n]);
656
else
657
type2.push_back(steps[n]);
658
}
659
660
// Write the renders back in order. Same amount, so deletion will work fine.
661
for (int j = 0; j < (int)type1.size(); j++) {
662
steps[i + j] = type1[j];
663
}
664
for (int j = 0; j < (int)type2.size(); j++) {
665
steps[i + j + type1.size()] = type2[j];
666
}
667
668
// Combine the renders.
669
for (int j = 1; j < (int)type1.size(); j++) {
670
for (int k = 0; k < (int)type1[j]->commands.size(); k++) {
671
steps[i]->commands.push_back(type1[j]->commands[k]);
672
}
673
steps[i + j]->stepType = VKRStepType::RENDER_SKIP;
674
}
675
for (int j = 1; j < (int)type2.size(); j++) {
676
for (int k = 0; k < (int)type2[j]->commands.size(); k++) {
677
steps[i + type1.size()]->commands.push_back(type2[j]->commands[k]);
678
}
679
// Technically, should merge render area here, but they're all the same so not needed.
680
steps[i + type1.size() + j]->stepType = VKRStepType::RENDER_SKIP;
681
}
682
// We're done.
683
break;
684
}
685
}
686
}
687
688
const char *AspectToString(VkImageAspectFlags aspect) {
689
switch (aspect) {
690
case VK_IMAGE_ASPECT_COLOR_BIT: return "COLOR";
691
case VK_IMAGE_ASPECT_DEPTH_BIT: return "DEPTH";
692
case VK_IMAGE_ASPECT_STENCIL_BIT: return "STENCIL";
693
case VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT: return "DEPTHSTENCIL";
694
default: return "UNUSUAL";
695
}
696
}
697
698
std::string VulkanQueueRunner::StepToString(VulkanContext *vulkan, const VKRStep &step) {
699
char buffer[256];
700
switch (step.stepType) {
701
case VKRStepType::RENDER:
702
{
703
int w = step.render.framebuffer ? step.render.framebuffer->width : vulkan->GetBackbufferWidth();
704
int h = step.render.framebuffer ? step.render.framebuffer->height : vulkan->GetBackbufferHeight();
705
int actual_w = step.render.renderArea.extent.width;
706
int actual_h = step.render.renderArea.extent.height;
707
const char *renderCmd = GetRPTypeName(step.render.renderPassType);
708
snprintf(buffer, sizeof(buffer), "%s %s %s (draws: %d, %dx%d/%dx%d)", renderCmd, step.tag, step.render.framebuffer ? step.render.framebuffer->Tag() : "", step.render.numDraws, actual_w, actual_h, w, h);
709
break;
710
}
711
case VKRStepType::COPY:
712
snprintf(buffer, sizeof(buffer), "COPY '%s' %s -> %s (%dx%d, %s)", step.tag, step.copy.src->Tag(), step.copy.dst->Tag(), step.copy.srcRect.extent.width, step.copy.srcRect.extent.height, AspectToString(step.copy.aspectMask));
713
break;
714
case VKRStepType::BLIT:
715
snprintf(buffer, sizeof(buffer), "BLIT '%s' %s -> %s (%dx%d->%dx%d, %s)", step.tag, step.copy.src->Tag(), step.copy.dst->Tag(), step.blit.srcRect.extent.width, step.blit.srcRect.extent.height, step.blit.dstRect.extent.width, step.blit.dstRect.extent.height, AspectToString(step.blit.aspectMask));
716
break;
717
case VKRStepType::READBACK:
718
snprintf(buffer, sizeof(buffer), "READBACK '%s' %s (%dx%d, %s)", step.tag, step.readback.src ? step.readback.src->Tag() : "(backbuffer)", step.readback.srcRect.extent.width, step.readback.srcRect.extent.height, AspectToString(step.readback.aspectMask));
719
break;
720
case VKRStepType::READBACK_IMAGE:
721
snprintf(buffer, sizeof(buffer), "READBACK_IMAGE '%s' (%dx%d)", step.tag, step.readback_image.srcRect.extent.width, step.readback_image.srcRect.extent.height);
722
break;
723
case VKRStepType::RENDER_SKIP:
724
snprintf(buffer, sizeof(buffer), "(RENDER_SKIP) %s", step.tag);
725
break;
726
default:
727
buffer[0] = 0;
728
break;
729
}
730
return std::string(buffer);
731
}
732
733
// Ideally, this should be cheap enough to be applied to all games. At least on mobile, it's pretty
734
// much a guaranteed neutral or win in terms of GPU power. However, dependency calculation really
735
// must be perfect!
736
void VulkanQueueRunner::ApplyRenderPassMerge(std::vector<VKRStep *> &steps) {
737
// First let's count how many times each framebuffer is rendered to.
738
// If it's more than one, let's do our best to merge them. This can help God of War quite a bit.
739
std::unordered_map<VKRFramebuffer *, int> counts;
740
for (int i = 0; i < (int)steps.size(); i++) {
741
if (steps[i]->stepType == VKRStepType::RENDER) {
742
counts[steps[i]->render.framebuffer]++;
743
}
744
}
745
746
auto mergeRenderSteps = [](VKRStep *dst, VKRStep *src) {
747
// OK. Now, if it's a render, slurp up all the commands and kill the step.
748
// Also slurp up any pretransitions.
749
dst->preTransitions.append(src->preTransitions);
750
dst->commands.insert(dst->commands.end(), src->commands.begin(), src->commands.end());
751
MergeRenderAreaRectInto(&dst->render.renderArea, src->render.renderArea);
752
// So we don't consider it for other things, maybe doesn't matter.
753
src->dependencies.clear();
754
src->stepType = VKRStepType::RENDER_SKIP;
755
dst->render.numDraws += src->render.numDraws;
756
dst->render.numReads += src->render.numReads;
757
dst->render.pipelineFlags |= src->render.pipelineFlags;
758
dst->render.renderPassType = MergeRPTypes(dst->render.renderPassType, src->render.renderPassType);
759
};
760
auto renderHasClear = [](const VKRStep *step) {
761
const auto &r = step->render;
762
return r.colorLoad == VKRRenderPassLoadAction::CLEAR || r.depthLoad == VKRRenderPassLoadAction::CLEAR || r.stencilLoad == VKRRenderPassLoadAction::CLEAR;
763
};
764
765
// Now, let's go through the steps. If we find one that is rendered to more than once,
766
// we'll scan forward and slurp up any rendering that can be merged across.
767
for (int i = 0; i < (int)steps.size(); i++) {
768
if (steps[i]->stepType == VKRStepType::RENDER && counts[steps[i]->render.framebuffer] > 1) {
769
auto fb = steps[i]->render.framebuffer;
770
TinySet<VKRFramebuffer *, 8> touchedFramebuffers; // must be the same fast-size as the dependencies TinySet for annoying reasons.
771
for (int j = i + 1; j < (int)steps.size(); j++) {
772
// If any other passes are reading from this framebuffer as-is, we cancel the scan.
773
if (steps[j]->dependencies.contains(fb)) {
774
// Reading from itself means a KEEP, which is okay.
775
if (steps[j]->stepType != VKRStepType::RENDER || steps[j]->render.framebuffer != fb)
776
break;
777
}
778
switch (steps[j]->stepType) {
779
case VKRStepType::RENDER:
780
if (steps[j]->render.framebuffer == fb) {
781
// Prevent Unknown's example case from https://github.com/hrydgard/ppsspp/pull/12242
782
if (renderHasClear(steps[j]) || steps[j]->dependencies.contains(touchedFramebuffers)) {
783
goto done_fb;
784
} else {
785
// Safe to merge, great.
786
mergeRenderSteps(steps[i], steps[j]);
787
}
788
} else {
789
// Remember the framebuffer this wrote to. We can't merge with later passes that depend on these.
790
touchedFramebuffers.insert(steps[j]->render.framebuffer);
791
}
792
break;
793
case VKRStepType::COPY:
794
if (steps[j]->copy.dst == fb) {
795
// Without framebuffer "renaming", we can't merge past a clobbered fb.
796
goto done_fb;
797
}
798
touchedFramebuffers.insert(steps[j]->copy.dst);
799
break;
800
case VKRStepType::BLIT:
801
if (steps[j]->blit.dst == fb) {
802
// Without framebuffer "renaming", we can't merge past a clobbered fb.
803
goto done_fb;
804
}
805
touchedFramebuffers.insert(steps[j]->blit.dst);
806
break;
807
case VKRStepType::READBACK:
808
// Not sure this has much effect, when executed READBACK is always the last step
809
// since we stall the GPU and wait immediately after.
810
break;
811
case VKRStepType::RENDER_SKIP:
812
case VKRStepType::READBACK_IMAGE:
813
break;
814
default:
815
// We added a new step? Might be unsafe.
816
goto done_fb;
817
}
818
}
819
done_fb:
820
;
821
}
822
}
823
}
824
825
void VulkanQueueRunner::LogSteps(const std::vector<VKRStep *> &steps, bool verbose) {
826
INFO_LOG(Log::G3D, "=================== FRAME ====================");
827
for (size_t i = 0; i < steps.size(); i++) {
828
const VKRStep &step = *steps[i];
829
switch (step.stepType) {
830
case VKRStepType::RENDER:
831
LogRenderPass(step, verbose);
832
break;
833
case VKRStepType::COPY:
834
LogCopy(step);
835
break;
836
case VKRStepType::BLIT:
837
LogBlit(step);
838
break;
839
case VKRStepType::READBACK:
840
LogReadback(step);
841
break;
842
case VKRStepType::READBACK_IMAGE:
843
LogReadbackImage(step);
844
break;
845
case VKRStepType::RENDER_SKIP:
846
INFO_LOG(Log::G3D, "(skipped render pass)");
847
break;
848
}
849
}
850
INFO_LOG(Log::G3D, "------------------- SUBMIT ------------------");
851
}
852
853
const char *RenderPassActionName(VKRRenderPassLoadAction a) {
854
switch (a) {
855
case VKRRenderPassLoadAction::CLEAR:
856
return "CLEAR";
857
case VKRRenderPassLoadAction::DONT_CARE:
858
return "DONT_CARE";
859
case VKRRenderPassLoadAction::KEEP:
860
return "KEEP";
861
}
862
return "?";
863
}
864
865
const char *ImageLayoutToString(VkImageLayout layout) {
866
switch (layout) {
867
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: return "COLOR_ATTACHMENT";
868
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: return "DEPTH_STENCIL_ATTACHMENT";
869
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: return "SHADER_READ_ONLY";
870
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: return "TRANSFER_SRC";
871
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: return "TRANSFER_DST";
872
case VK_IMAGE_LAYOUT_GENERAL: return "GENERAL";
873
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR: return "PRESENT_SRC_KHR";
874
case VK_IMAGE_LAYOUT_UNDEFINED: return "UNDEFINED";
875
default: return "(unknown)";
876
}
877
}
878
879
void VulkanQueueRunner::LogRenderPass(const VKRStep &pass, bool verbose) {
880
const auto &r = pass.render;
881
const char *framebuf = r.framebuffer ? r.framebuffer->Tag() : "backbuffer";
882
int w = r.framebuffer ? r.framebuffer->width : vulkan_->GetBackbufferWidth();
883
int h = r.framebuffer ? r.framebuffer->height : vulkan_->GetBackbufferHeight();
884
885
INFO_LOG(Log::G3D, "RENDER %s Begin(%s, draws: %d, %dx%d, %s, %s, %s)", pass.tag, framebuf, r.numDraws, w, h, RenderPassActionName(r.colorLoad), RenderPassActionName(r.depthLoad), RenderPassActionName(r.stencilLoad));
886
// TODO: Log these in detail.
887
for (int i = 0; i < (int)pass.preTransitions.size(); i++) {
888
INFO_LOG(Log::G3D, " PRETRANSITION: %s %s -> %s", pass.preTransitions[i].fb->Tag(), AspectToString(pass.preTransitions[i].aspect), ImageLayoutToString(pass.preTransitions[i].targetLayout));
889
}
890
891
if (verbose) {
892
for (auto &cmd : pass.commands) {
893
switch (cmd.cmd) {
894
case VKRRenderCommand::REMOVED:
895
INFO_LOG(Log::G3D, " (Removed)");
896
break;
897
case VKRRenderCommand::BIND_GRAPHICS_PIPELINE:
898
INFO_LOG(Log::G3D, " BindGraphicsPipeline(%x)", (int)(intptr_t)cmd.graphics_pipeline.pipeline);
899
break;
900
case VKRRenderCommand::BLEND:
901
INFO_LOG(Log::G3D, " BlendColor(%08x)", cmd.blendColor.color);
902
break;
903
case VKRRenderCommand::CLEAR:
904
INFO_LOG(Log::G3D, " Clear");
905
break;
906
case VKRRenderCommand::DRAW:
907
INFO_LOG(Log::G3D, " Draw(%d)", cmd.draw.count);
908
break;
909
case VKRRenderCommand::DRAW_INDEXED:
910
INFO_LOG(Log::G3D, " DrawIndexed(%d)", cmd.drawIndexed.count);
911
break;
912
case VKRRenderCommand::SCISSOR:
913
INFO_LOG(Log::G3D, " Scissor(%d, %d, %d, %d)", (int)cmd.scissor.scissor.offset.x, (int)cmd.scissor.scissor.offset.y, (int)cmd.scissor.scissor.extent.width, (int)cmd.scissor.scissor.extent.height);
914
break;
915
case VKRRenderCommand::STENCIL:
916
INFO_LOG(Log::G3D, " Stencil(ref=%d, compare=%d, write=%d)", cmd.stencil.stencilRef, cmd.stencil.stencilCompareMask, cmd.stencil.stencilWriteMask);
917
break;
918
case VKRRenderCommand::VIEWPORT:
919
INFO_LOG(Log::G3D, " Viewport(%f, %f, %f, %f, %f, %f)", cmd.viewport.vp.x, cmd.viewport.vp.y, cmd.viewport.vp.width, cmd.viewport.vp.height, cmd.viewport.vp.minDepth, cmd.viewport.vp.maxDepth);
920
break;
921
case VKRRenderCommand::PUSH_CONSTANTS:
922
INFO_LOG(Log::G3D, " PushConstants(%d)", cmd.push.size);
923
break;
924
case VKRRenderCommand::DEBUG_ANNOTATION:
925
INFO_LOG(Log::G3D, " DebugAnnotation(%s)", cmd.debugAnnotation.annotation);
926
break;
927
928
case VKRRenderCommand::NUM_RENDER_COMMANDS:
929
break;
930
}
931
}
932
}
933
934
INFO_LOG(Log::G3D, " Final: %s %s", ImageLayoutToString(pass.render.finalColorLayout), ImageLayoutToString(pass.render.finalDepthStencilLayout));
935
INFO_LOG(Log::G3D, "RENDER End(%s) - %d commands executed", framebuf, (int)pass.commands.size());
936
}
937
938
void VulkanQueueRunner::LogCopy(const VKRStep &step) {
939
INFO_LOG(Log::G3D, "%s", StepToString(vulkan_, step).c_str());
940
}
941
942
void VulkanQueueRunner::LogBlit(const VKRStep &step) {
943
INFO_LOG(Log::G3D, "%s", StepToString(vulkan_, step).c_str());
944
}
945
946
void VulkanQueueRunner::LogReadback(const VKRStep &step) {
947
INFO_LOG(Log::G3D, "%s", StepToString(vulkan_, step).c_str());
948
}
949
950
void VulkanQueueRunner::LogReadbackImage(const VKRStep &step) {
951
INFO_LOG(Log::G3D, "%s", StepToString(vulkan_, step).c_str());
952
}
953
954
void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer cmd, int curFrame, QueueProfileContext &profile) {
955
for (size_t i = 0; i < step.preTransitions.size(); i++) {
956
const TransitionRequest &iter = step.preTransitions[i];
957
if (iter.aspect == VK_IMAGE_ASPECT_COLOR_BIT && iter.fb->color.layout != iter.targetLayout) {
958
recordBarrier_.TransitionColorImageAuto(
959
&iter.fb->color,
960
iter.targetLayout
961
);
962
} else if (iter.fb->depth.image != VK_NULL_HANDLE && (iter.aspect & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) && iter.fb->depth.layout != iter.targetLayout) {
963
recordBarrier_.TransitionDepthStencilImageAuto(
964
&iter.fb->depth,
965
iter.targetLayout
966
);
967
}
968
}
969
970
// Don't execute empty renderpasses that keep the contents.
971
if (step.commands.empty() && step.render.colorLoad == VKRRenderPassLoadAction::KEEP && step.render.depthLoad == VKRRenderPassLoadAction::KEEP && step.render.stencilLoad == VKRRenderPassLoadAction::KEEP) {
972
// Flush the pending barrier
973
recordBarrier_.Flush(cmd);
974
// Nothing to do.
975
// TODO: Though - a later step might have used this step's finalColorLayout etc to get things in a layout it expects.
976
// Should we just do a barrier? Or just let the later step deal with not having things in its preferred layout, like now?
977
return;
978
}
979
980
// Write-after-write hazards. Fixed flicker in God of War on ARM (before we added another fix that removed these).
981
// NOTE: These are commented out because the normal barriers no longer check for equality, effectively generating these
982
// barriers automatically. This is safe, but sometimes I think can be improved on.
983
/*
984
if (step.render.framebuffer) {
985
int n = 0;
986
int stage = 0;
987
988
if (step.render.framebuffer->color.layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
989
recordBarrier_.TransitionImage(
990
step.render.framebuffer->color.image,
991
0,
992
1,
993
step.render.framebuffer->numLayers,
994
VK_IMAGE_ASPECT_COLOR_BIT,
995
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
996
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
997
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
998
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT,
999
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
1000
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
1001
);
1002
}
1003
if (step.render.framebuffer->depth.image != VK_NULL_HANDLE && step.render.framebuffer->depth.layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
1004
recordBarrier_.TransitionImage(
1005
step.render.framebuffer->depth.image,
1006
0,
1007
1,
1008
step.render.framebuffer->numLayers,
1009
VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT,
1010
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1011
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1012
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
1013
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT,
1014
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
1015
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
1016
);
1017
}
1018
}*/
1019
1020
// This chooses a render pass according to the load/store attachment state. We no longer transition
1021
// image layouts as part of the passes.
1022
//
1023
// NOTE: Unconditionally flushes recordBarrier_.
1024
VKRRenderPass *renderPass = PerformBindFramebufferAsRenderTarget(step, cmd);
1025
1026
int curWidth = step.render.framebuffer ? step.render.framebuffer->width : vulkan_->GetBackbufferWidth();
1027
int curHeight = step.render.framebuffer ? step.render.framebuffer->height : vulkan_->GetBackbufferHeight();
1028
1029
VKRFramebuffer *fb = step.render.framebuffer;
1030
1031
VKRGraphicsPipeline *lastGraphicsPipeline = nullptr;
1032
VKRComputePipeline *lastComputePipeline = nullptr;
1033
1034
const auto &commands = step.commands;
1035
1036
// We can do a little bit of state tracking here to eliminate some calls into the driver.
1037
// The stencil ones are very commonly mostly redundant so let's eliminate them where possible.
1038
// Might also want to consider scissor and viewport.
1039
VkPipeline lastPipeline = VK_NULL_HANDLE;
1040
FastVec<PendingDescSet> *descSets = nullptr;
1041
VkPipelineLayout pipelineLayout = VK_NULL_HANDLE;
1042
1043
bool pipelineOK = false;
1044
1045
int lastStencilWriteMask = -1;
1046
int lastStencilCompareMask = -1;
1047
int lastStencilReference = -1;
1048
1049
const RenderPassType rpType = step.render.renderPassType;
1050
1051
for (size_t i = 0; i < commands.size(); i++) {
1052
const VkRenderData &c = commands[i];
1053
#ifdef _DEBUG
1054
if (profile.enabled) {
1055
if ((size_t)step.stepType < ARRAY_SIZE(profile.commandCounts)) {
1056
profile.commandCounts[(size_t)c.cmd]++;
1057
}
1058
}
1059
#endif
1060
switch (c.cmd) {
1061
case VKRRenderCommand::REMOVED:
1062
break;
1063
1064
case VKRRenderCommand::BIND_GRAPHICS_PIPELINE:
1065
{
1066
VKRGraphicsPipeline *graphicsPipeline = c.graphics_pipeline.pipeline;
1067
if (graphicsPipeline != lastGraphicsPipeline) {
1068
VkSampleCountFlagBits fbSampleCount = fb ? fb->sampleCount : VK_SAMPLE_COUNT_1_BIT;
1069
1070
if (RenderPassTypeHasMultisample(rpType) && fbSampleCount != graphicsPipeline->SampleCount()) {
1071
// should have been invalidated.
1072
_assert_msg_(graphicsPipeline->SampleCount() == VK_SAMPLE_COUNT_FLAG_BITS_MAX_ENUM,
1073
"expected %d sample count, got %d", fbSampleCount, graphicsPipeline->SampleCount());
1074
}
1075
1076
VkPipeline pipeline;
1077
1078
{
1079
std::lock_guard<std::mutex> lock(graphicsPipeline->mutex_);
1080
if (!graphicsPipeline->pipeline[(size_t)rpType]) {
1081
// NOTE: If render steps got merged, it can happen that, as they ended during recording,
1082
// they didn't know their final render pass type so they created the wrong pipelines in EndCurRenderStep().
1083
// Unfortunately I don't know if we can fix it in any more sensible place than here.
1084
// Maybe a middle pass. But let's try to just block and compile here for now, this doesn't
1085
// happen all that much.
1086
graphicsPipeline->pipeline[(size_t)rpType] = Promise<VkPipeline>::CreateEmpty();
1087
graphicsPipeline->Create(vulkan_, renderPass->Get(vulkan_, rpType, fbSampleCount), rpType, fbSampleCount, time_now_d(), -1);
1088
}
1089
pipeline = graphicsPipeline->pipeline[(size_t)rpType]->BlockUntilReady();
1090
}
1091
1092
if (pipeline != VK_NULL_HANDLE) {
1093
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
1094
descSets = &c.graphics_pipeline.pipelineLayout->frameData[curFrame].descSets_;
1095
pipelineLayout = c.graphics_pipeline.pipelineLayout->pipelineLayout;
1096
_dbg_assert_(pipelineLayout != VK_NULL_HANDLE);
1097
lastGraphicsPipeline = graphicsPipeline;
1098
pipelineOK = true;
1099
} else {
1100
pipelineOK = false;
1101
}
1102
1103
// Reset dynamic state so it gets refreshed with the new pipeline.
1104
lastStencilWriteMask = -1;
1105
lastStencilCompareMask = -1;
1106
lastStencilReference = -1;
1107
}
1108
break;
1109
}
1110
1111
case VKRRenderCommand::VIEWPORT:
1112
if (fb != nullptr) {
1113
vkCmdSetViewport(cmd, 0, 1, &c.viewport.vp);
1114
} else {
1115
const VkViewport &vp = c.viewport.vp;
1116
DisplayRect<float> rc{ vp.x, vp.y, vp.width, vp.height };
1117
RotateRectToDisplay(rc, (float)vulkan_->GetBackbufferWidth(), (float)vulkan_->GetBackbufferHeight());
1118
VkViewport final_vp;
1119
final_vp.x = rc.x;
1120
final_vp.y = rc.y;
1121
final_vp.width = rc.w;
1122
final_vp.height = rc.h;
1123
final_vp.maxDepth = vp.maxDepth;
1124
final_vp.minDepth = vp.minDepth;
1125
vkCmdSetViewport(cmd, 0, 1, &final_vp);
1126
}
1127
break;
1128
1129
case VKRRenderCommand::SCISSOR:
1130
{
1131
if (fb != nullptr) {
1132
vkCmdSetScissor(cmd, 0, 1, &c.scissor.scissor);
1133
} else {
1134
// Rendering to backbuffer. Might need to rotate.
1135
const VkRect2D &rc = c.scissor.scissor;
1136
DisplayRect<int> rotated_rc{ rc.offset.x, rc.offset.y, (int)rc.extent.width, (int)rc.extent.height };
1137
RotateRectToDisplay(rotated_rc, vulkan_->GetBackbufferWidth(), vulkan_->GetBackbufferHeight());
1138
_dbg_assert_(rotated_rc.x >= 0);
1139
_dbg_assert_(rotated_rc.y >= 0);
1140
VkRect2D finalRect = VkRect2D{ { rotated_rc.x, rotated_rc.y }, { (uint32_t)rotated_rc.w, (uint32_t)rotated_rc.h} };
1141
vkCmdSetScissor(cmd, 0, 1, &finalRect);
1142
}
1143
break;
1144
}
1145
1146
case VKRRenderCommand::BLEND:
1147
{
1148
float bc[4];
1149
Uint8x4ToFloat4(bc, c.blendColor.color);
1150
vkCmdSetBlendConstants(cmd, bc);
1151
break;
1152
}
1153
1154
case VKRRenderCommand::PUSH_CONSTANTS:
1155
if (pipelineOK) {
1156
vkCmdPushConstants(cmd, pipelineLayout, c.push.stages, c.push.offset, c.push.size, c.push.data);
1157
}
1158
break;
1159
1160
case VKRRenderCommand::STENCIL:
1161
if (lastStencilWriteMask != c.stencil.stencilWriteMask) {
1162
lastStencilWriteMask = (int)c.stencil.stencilWriteMask;
1163
vkCmdSetStencilWriteMask(cmd, VK_STENCIL_FRONT_AND_BACK, c.stencil.stencilWriteMask);
1164
}
1165
if (lastStencilCompareMask != c.stencil.stencilCompareMask) {
1166
lastStencilCompareMask = c.stencil.stencilCompareMask;
1167
vkCmdSetStencilCompareMask(cmd, VK_STENCIL_FRONT_AND_BACK, c.stencil.stencilCompareMask);
1168
}
1169
if (lastStencilReference != c.stencil.stencilRef) {
1170
lastStencilReference = c.stencil.stencilRef;
1171
vkCmdSetStencilReference(cmd, VK_STENCIL_FRONT_AND_BACK, c.stencil.stencilRef);
1172
}
1173
break;
1174
1175
case VKRRenderCommand::DRAW_INDEXED:
1176
if (pipelineOK) {
1177
VkDescriptorSet set = (*descSets)[c.drawIndexed.descSetIndex].set;
1178
_dbg_assert_(set != VK_NULL_HANDLE);
1179
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, c.drawIndexed.numUboOffsets, c.drawIndexed.uboOffsets);
1180
vkCmdBindIndexBuffer(cmd, c.drawIndexed.ibuffer, c.drawIndexed.ioffset, VK_INDEX_TYPE_UINT16);
1181
VkDeviceSize voffset = c.drawIndexed.voffset;
1182
vkCmdBindVertexBuffers(cmd, 0, 1, &c.drawIndexed.vbuffer, &voffset);
1183
vkCmdDrawIndexed(cmd, c.drawIndexed.count, c.drawIndexed.instances, 0, 0, 0);
1184
}
1185
break;
1186
1187
case VKRRenderCommand::DRAW:
1188
if (pipelineOK) {
1189
VkDescriptorSet set = (*descSets)[c.drawIndexed.descSetIndex].set;
1190
_dbg_assert_(set != VK_NULL_HANDLE);
1191
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, c.draw.numUboOffsets, c.draw.uboOffsets);
1192
if (c.draw.vbuffer) {
1193
vkCmdBindVertexBuffers(cmd, 0, 1, &c.draw.vbuffer, &c.draw.voffset);
1194
}
1195
vkCmdDraw(cmd, c.draw.count, 1, c.draw.offset, 0);
1196
}
1197
break;
1198
1199
case VKRRenderCommand::CLEAR:
1200
{
1201
// If we get here, we failed to merge a clear into a render pass load op. This is bad for perf.
1202
int numAttachments = 0;
1203
VkClearRect rc{};
1204
rc.baseArrayLayer = 0;
1205
rc.layerCount = 1; // In multiview mode, 1 means to replicate to all the active layers.
1206
rc.rect.extent.width = (uint32_t)curWidth;
1207
rc.rect.extent.height = (uint32_t)curHeight;
1208
VkClearAttachment attachments[2]{};
1209
if (c.clear.clearMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1210
VkClearAttachment &attachment = attachments[numAttachments++];
1211
attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1212
attachment.colorAttachment = 0;
1213
Uint8x4ToFloat4(attachment.clearValue.color.float32, c.clear.clearColor);
1214
}
1215
if (c.clear.clearMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
1216
VkClearAttachment &attachment = attachments[numAttachments++];
1217
attachment.aspectMask = 0;
1218
if (c.clear.clearMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1219
attachment.clearValue.depthStencil.depth = c.clear.clearZ;
1220
attachment.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
1221
}
1222
if (c.clear.clearMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1223
attachment.clearValue.depthStencil.stencil = (uint32_t)c.clear.clearStencil;
1224
attachment.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
1225
}
1226
}
1227
if (numAttachments) {
1228
vkCmdClearAttachments(cmd, numAttachments, attachments, 1, &rc);
1229
}
1230
break;
1231
}
1232
1233
case VKRRenderCommand::DEBUG_ANNOTATION:
1234
if (vulkan_->Extensions().EXT_debug_utils) {
1235
VkDebugUtilsLabelEXT labelInfo{ VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT };
1236
labelInfo.pLabelName = c.debugAnnotation.annotation;
1237
vkCmdInsertDebugUtilsLabelEXT(cmd, &labelInfo);
1238
}
1239
break;
1240
1241
default:
1242
ERROR_LOG(Log::G3D, "Unimpl queue command");
1243
break;
1244
}
1245
}
1246
vkCmdEndRenderPass(cmd);
1247
1248
_dbg_assert_(recordBarrier_.empty());
1249
1250
if (fb) {
1251
// If the desired final layout aren't the optimal layout needed next, early-transition the image.
1252
if (step.render.finalColorLayout != fb->color.layout) {
1253
recordBarrier_.TransitionColorImageAuto(&fb->color, step.render.finalColorLayout);
1254
}
1255
if (fb->depth.image && step.render.finalDepthStencilLayout != fb->depth.layout) {
1256
recordBarrier_.TransitionDepthStencilImageAuto(&fb->depth, step.render.finalDepthStencilLayout);
1257
}
1258
}
1259
}
1260
1261
VKRRenderPass *VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKRStep &step, VkCommandBuffer cmd) {
1262
VKRRenderPass *renderPass;
1263
int numClearVals = 0;
1264
VkClearValue clearVal[4]{};
1265
VkFramebuffer framebuf;
1266
int w;
1267
int h;
1268
1269
bool hasDepth = RenderPassTypeHasDepth(step.render.renderPassType);
1270
1271
VkSampleCountFlagBits sampleCount;
1272
1273
// Can be used to separate the final*Layout barrier from the rest for debugging in renderdoc.
1274
// recordBarrier_.Flush(cmd);
1275
1276
if (step.render.framebuffer) {
1277
_dbg_assert_(step.render.finalColorLayout != VK_IMAGE_LAYOUT_UNDEFINED);
1278
_dbg_assert_(step.render.finalDepthStencilLayout != VK_IMAGE_LAYOUT_UNDEFINED);
1279
1280
RPKey key{
1281
step.render.colorLoad, step.render.depthLoad, step.render.stencilLoad,
1282
step.render.colorStore, step.render.depthStore, step.render.stencilStore,
1283
};
1284
renderPass = GetRenderPass(key);
1285
1286
VKRFramebuffer *fb = step.render.framebuffer;
1287
framebuf = fb->Get(renderPass, step.render.renderPassType);
1288
sampleCount = fb->sampleCount;
1289
_dbg_assert_(framebuf != VK_NULL_HANDLE);
1290
w = fb->width;
1291
h = fb->height;
1292
1293
// Mali driver on S8 (Android O) and S9 mishandles renderpasses that do just a clear
1294
// and then no draw calls. Memory transaction elimination gets mis-flagged or something.
1295
// To avoid this, we transition to GENERAL and back in this case (ARM-approved workaround).
1296
// See pull request #10723.
1297
bool maliBugWorkaround = step.render.numDraws == 0 &&
1298
step.render.colorLoad == VKRRenderPassLoadAction::CLEAR &&
1299
vulkan_->GetPhysicalDeviceProperties().properties.driverVersion == 0xaa9c4b29;
1300
if (maliBugWorkaround) {
1301
// A little suboptimal but let's go for maximum safety here.
1302
recordBarrier_.TransitionImage(fb->color.image, 0, 1, fb->numLayers, VK_IMAGE_ASPECT_COLOR_BIT,
1303
fb->color.layout, VK_IMAGE_LAYOUT_GENERAL,
1304
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1305
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1306
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
1307
fb->color.layout = VK_IMAGE_LAYOUT_GENERAL;
1308
}
1309
1310
recordBarrier_.TransitionColorImageAuto(&fb->color, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
1311
1312
// If the render pass doesn't touch depth, we can avoid a layout transition of the depth buffer.
1313
if (fb->depth.image && RenderPassTypeHasDepth(step.render.renderPassType)) {
1314
recordBarrier_.TransitionDepthStencilImageAuto(&fb->depth, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
1315
}
1316
1317
// The transition from the optimal format happens after EndRenderPass, now that we don't
1318
// do it as part of the renderpass itself anymore.
1319
1320
if (sampleCount != VK_SAMPLE_COUNT_1_BIT) {
1321
// We don't initialize values for these.
1322
numClearVals = hasDepth ? 2 : 1; // Skip the resolve buffers, don't need to clear those.
1323
}
1324
if (step.render.colorLoad == VKRRenderPassLoadAction::CLEAR) {
1325
Uint8x4ToFloat4(clearVal[numClearVals].color.float32, step.render.clearColor);
1326
}
1327
numClearVals++;
1328
if (hasDepth) {
1329
if (step.render.depthLoad == VKRRenderPassLoadAction::CLEAR || step.render.stencilLoad == VKRRenderPassLoadAction::CLEAR) {
1330
clearVal[numClearVals].depthStencil.depth = step.render.clearDepth;
1331
clearVal[numClearVals].depthStencil.stencil = step.render.clearStencil;
1332
}
1333
numClearVals++;
1334
}
1335
_dbg_assert_(numClearVals != 3);
1336
} else {
1337
RPKey key{
1338
VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR, VKRRenderPassLoadAction::CLEAR,
1339
VKRRenderPassStoreAction::STORE, VKRRenderPassStoreAction::DONT_CARE, VKRRenderPassStoreAction::DONT_CARE,
1340
};
1341
renderPass = GetRenderPass(key);
1342
framebuf = backbuffer_;
1343
1344
// Raw, rotated backbuffer size.
1345
w = vulkan_->GetBackbufferWidth();
1346
h = vulkan_->GetBackbufferHeight();
1347
1348
Uint8x4ToFloat4(clearVal[0].color.float32, step.render.clearColor);
1349
numClearVals = hasDepth ? 2 : 1; // We might do depth-less backbuffer in the future, though doubtful of the value.
1350
clearVal[1].depthStencil.depth = 0.0f;
1351
clearVal[1].depthStencil.stencil = 0;
1352
sampleCount = VK_SAMPLE_COUNT_1_BIT;
1353
}
1354
1355
VkRenderPassBeginInfo rp_begin = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
1356
rp_begin.renderPass = renderPass->Get(vulkan_, step.render.renderPassType, sampleCount);
1357
rp_begin.framebuffer = framebuf;
1358
1359
VkRect2D rc = step.render.renderArea;
1360
if (!step.render.framebuffer) {
1361
// Rendering to backbuffer, must rotate, just like scissors.
1362
DisplayRect<int> rotated_rc{ rc.offset.x, rc.offset.y, (int)rc.extent.width, (int)rc.extent.height };
1363
RotateRectToDisplay(rotated_rc, vulkan_->GetBackbufferWidth(), vulkan_->GetBackbufferHeight());
1364
1365
rc.offset.x = rotated_rc.x;
1366
rc.offset.y = rotated_rc.y;
1367
rc.extent.width = rotated_rc.w;
1368
rc.extent.height = rotated_rc.h;
1369
}
1370
1371
recordBarrier_.Flush(cmd);
1372
1373
rp_begin.renderArea = rc;
1374
rp_begin.clearValueCount = numClearVals;
1375
rp_begin.pClearValues = numClearVals ? clearVal : nullptr;
1376
vkCmdBeginRenderPass(cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
1377
1378
return renderPass;
1379
}
1380
1381
void VulkanQueueRunner::PerformCopy(const VKRStep &step, VkCommandBuffer cmd) {
1382
// The barrier code doesn't handle this case. We'd need to transition to GENERAL to do an intra-image copy.
1383
_dbg_assert_(step.copy.src != step.copy.dst);
1384
1385
VKRFramebuffer *src = step.copy.src;
1386
VKRFramebuffer *dst = step.copy.dst;
1387
1388
int layerCount = std::min(step.copy.src->numLayers, step.copy.dst->numLayers);
1389
_dbg_assert_(step.copy.src->numLayers >= step.copy.dst->numLayers);
1390
1391
// TODO: If dst covers exactly the whole destination, we can set up a UNDEFINED->TRANSFER_DST_OPTIMAL transition,
1392
// which can potentially be more efficient.
1393
1394
if (step.copy.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1395
recordBarrier_.TransitionColorImageAuto(&src->color, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
1396
recordBarrier_.TransitionColorImageAuto(&dst->color, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1397
}
1398
1399
// We can't copy only depth or only stencil unfortunately - or can we?.
1400
if (step.copy.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
1401
_dbg_assert_(src->depth.image != VK_NULL_HANDLE);
1402
1403
recordBarrier_.TransitionDepthStencilImageAuto(&src->depth, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
1404
if (dst->depth.layout != VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
1405
recordBarrier_.TransitionDepthStencilImageAuto(&dst->depth, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1406
} else {
1407
// Kingdom Hearts: Subsequent copies twice to the same depth buffer without any other use.
1408
// Not super sure how that happens, but we need a barrier to pass sync validation.
1409
SetupTransferDstWriteAfterWrite(dst->depth, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT, &recordBarrier_);
1410
}
1411
}
1412
1413
bool multisampled = src->sampleCount != VK_SAMPLE_COUNT_1_BIT && dst->sampleCount != VK_SAMPLE_COUNT_1_BIT;
1414
if (multisampled) {
1415
// If both the targets are multisampled, copy the msaa targets too.
1416
// For that, we need to transition them from their normally permanent VK_*_ATTACHMENT_OPTIMAL layouts, and then back.
1417
if (step.copy.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1418
recordBarrier_.TransitionColorImageAuto(&src->msaaColor, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
1419
recordBarrier_.TransitionColorImageAuto(&dst->msaaColor, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1420
}
1421
if (step.copy.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
1422
// Kingdom Hearts: Subsequent copies to the same depth buffer without any other use.
1423
// Not super sure how that happens, but we need a barrier to pass sync validation.
1424
recordBarrier_.TransitionDepthStencilImageAuto(&src->msaaDepth, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
1425
recordBarrier_.TransitionDepthStencilImageAuto(&dst->msaaDepth, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1426
}
1427
}
1428
1429
recordBarrier_.Flush(cmd);
1430
1431
VkImageCopy copy{};
1432
copy.srcOffset.x = step.copy.srcRect.offset.x;
1433
copy.srcOffset.y = step.copy.srcRect.offset.y;
1434
copy.srcOffset.z = 0;
1435
copy.srcSubresource.mipLevel = 0;
1436
copy.srcSubresource.layerCount = layerCount;
1437
copy.dstOffset.x = step.copy.dstPos.x;
1438
copy.dstOffset.y = step.copy.dstPos.y;
1439
copy.dstOffset.z = 0;
1440
copy.dstSubresource.mipLevel = 0;
1441
copy.dstSubresource.layerCount = layerCount;
1442
copy.extent.width = step.copy.srcRect.extent.width;
1443
copy.extent.height = step.copy.srcRect.extent.height;
1444
copy.extent.depth = 1;
1445
1446
if (step.copy.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1447
copy.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1448
copy.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1449
vkCmdCopyImage(cmd, src->color.image, src->color.layout, dst->color.image, dst->color.layout, 1, &copy);
1450
1451
if (multisampled) {
1452
vkCmdCopyImage(cmd, src->msaaColor.image, src->msaaColor.layout, dst->msaaColor.image, dst->msaaColor.layout, 1, &copy);
1453
}
1454
}
1455
if (step.copy.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
1456
_dbg_assert_(src->depth.image != VK_NULL_HANDLE);
1457
_dbg_assert_(dst->depth.image != VK_NULL_HANDLE);
1458
copy.srcSubresource.aspectMask = step.copy.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT);
1459
copy.dstSubresource.aspectMask = step.copy.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT);
1460
vkCmdCopyImage(cmd, src->depth.image, src->depth.layout, dst->depth.image, dst->depth.layout, 1, &copy);
1461
1462
if (multisampled) {
1463
vkCmdCopyImage(cmd, src->msaaDepth.image, src->msaaDepth.layout, dst->msaaDepth.image, dst->msaaDepth.layout, 1, &copy);
1464
}
1465
}
1466
1467
if (multisampled) {
1468
// Transition the MSAA surfaces back to optimal.
1469
if (step.copy.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1470
recordBarrier_.TransitionImage(
1471
src->msaaColor.image,
1472
0,
1473
1,
1474
src->msaaColor.numLayers,
1475
VK_IMAGE_ASPECT_COLOR_BIT,
1476
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1477
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
1478
VK_ACCESS_TRANSFER_READ_BIT,
1479
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1480
VK_PIPELINE_STAGE_TRANSFER_BIT,
1481
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
1482
);
1483
src->msaaColor.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1484
recordBarrier_.TransitionImage(
1485
dst->msaaColor.image,
1486
0,
1487
1,
1488
dst->msaaColor.numLayers,
1489
VK_IMAGE_ASPECT_COLOR_BIT,
1490
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1491
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
1492
VK_ACCESS_TRANSFER_WRITE_BIT,
1493
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1494
VK_PIPELINE_STAGE_TRANSFER_BIT,
1495
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
1496
);
1497
dst->msaaColor.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1498
}
1499
if (step.copy.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
1500
recordBarrier_.TransitionImage(
1501
src->msaaDepth.image,
1502
0,
1503
1,
1504
src->msaaDepth.numLayers,
1505
VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT,
1506
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1507
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1508
VK_ACCESS_TRANSFER_READ_BIT,
1509
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
1510
VK_PIPELINE_STAGE_TRANSFER_BIT,
1511
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT
1512
);
1513
src->msaaDepth.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
1514
recordBarrier_.TransitionImage(
1515
dst->msaaDepth.image,
1516
0,
1517
1,
1518
dst->msaaDepth.numLayers,
1519
VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT,
1520
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1521
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1522
VK_ACCESS_TRANSFER_WRITE_BIT,
1523
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
1524
VK_PIPELINE_STAGE_TRANSFER_BIT,
1525
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT
1526
);
1527
dst->msaaDepth.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
1528
}
1529
// Probably not necessary.
1530
recordBarrier_.Flush(cmd);
1531
}
1532
}
1533
1534
void VulkanQueueRunner::PerformBlit(const VKRStep &step, VkCommandBuffer cmd) {
1535
// The barrier code doesn't handle this case. We'd need to transition to GENERAL to do an intra-image copy.
1536
_dbg_assert_(step.blit.src != step.blit.dst);
1537
1538
int layerCount = std::min(step.blit.src->numLayers, step.blit.dst->numLayers);
1539
_dbg_assert_(step.blit.src->numLayers >= step.blit.dst->numLayers);
1540
1541
// Blitting is not allowed for multisample images. You're suppose to use vkCmdResolveImage but it only goes in one direction (multi to single).
1542
_dbg_assert_(step.blit.src->sampleCount == VkSampleCountFlagBits::VK_SAMPLE_COUNT_1_BIT);
1543
_dbg_assert_(step.blit.dst->sampleCount == VkSampleCountFlagBits::VK_SAMPLE_COUNT_1_BIT);
1544
1545
VKRFramebuffer *src = step.blit.src;
1546
VKRFramebuffer *dst = step.blit.dst;
1547
1548
// First source barriers.
1549
if (step.blit.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1550
recordBarrier_.TransitionColorImageAuto(&src->color, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
1551
recordBarrier_.TransitionColorImageAuto(&dst->color, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1552
}
1553
1554
// We can't copy only depth or only stencil unfortunately.
1555
if (step.blit.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
1556
_assert_(src->depth.image != VK_NULL_HANDLE);
1557
_assert_(dst->depth.image != VK_NULL_HANDLE);
1558
recordBarrier_.TransitionDepthStencilImageAuto(&src->depth, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
1559
recordBarrier_.TransitionDepthStencilImageAuto(&dst->depth, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1560
}
1561
1562
recordBarrier_.Flush(cmd);
1563
1564
// If any validation needs to be performed here, it should probably have been done
1565
// already when the blit was queued. So don't validate here.
1566
VkImageBlit blit{};
1567
blit.srcOffsets[0].x = step.blit.srcRect.offset.x;
1568
blit.srcOffsets[0].y = step.blit.srcRect.offset.y;
1569
blit.srcOffsets[0].z = 0;
1570
blit.srcOffsets[1].x = step.blit.srcRect.offset.x + step.blit.srcRect.extent.width;
1571
blit.srcOffsets[1].y = step.blit.srcRect.offset.y + step.blit.srcRect.extent.height;
1572
blit.srcOffsets[1].z = 1;
1573
blit.srcSubresource.mipLevel = 0;
1574
blit.srcSubresource.layerCount = layerCount;
1575
blit.dstOffsets[0].x = step.blit.dstRect.offset.x;
1576
blit.dstOffsets[0].y = step.blit.dstRect.offset.y;
1577
blit.dstOffsets[0].z = 0;
1578
blit.dstOffsets[1].x = step.blit.dstRect.offset.x + step.blit.dstRect.extent.width;
1579
blit.dstOffsets[1].y = step.blit.dstRect.offset.y + step.blit.dstRect.extent.height;
1580
blit.dstOffsets[1].z = 1;
1581
blit.dstSubresource.mipLevel = 0;
1582
blit.dstSubresource.layerCount = layerCount;
1583
1584
if (step.blit.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1585
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1586
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1587
vkCmdBlitImage(cmd, src->color.image, src->color.layout, dst->color.image, dst->color.layout, 1, &blit, step.blit.filter);
1588
}
1589
1590
// TODO: Need to check if the depth format is blittable.
1591
// Actually, we should probably almost always use copies rather than blits for depth buffers.
1592
if (step.blit.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
1593
blit.srcSubresource.aspectMask = 0;
1594
blit.dstSubresource.aspectMask = 0;
1595
if (step.blit.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1596
blit.srcSubresource.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
1597
blit.dstSubresource.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
1598
}
1599
if (step.blit.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1600
blit.srcSubresource.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
1601
blit.dstSubresource.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
1602
}
1603
vkCmdBlitImage(cmd, src->depth.image, src->depth.layout, dst->depth.image, dst->depth.layout, 1, &blit, step.blit.filter);
1604
}
1605
}
1606
1607
void VulkanQueueRunner::SetupTransferDstWriteAfterWrite(VKRImage &img, VkImageAspectFlags aspect, VulkanBarrierBatch *recordBarrier) {
1608
VkImageAspectFlags imageAspect = aspect;
1609
VkAccessFlags srcAccessMask = 0;
1610
VkPipelineStageFlags srcStageMask = 0;
1611
if (img.format == VK_FORMAT_D16_UNORM_S8_UINT || img.format == VK_FORMAT_D24_UNORM_S8_UINT || img.format == VK_FORMAT_D32_SFLOAT_S8_UINT) {
1612
// Barrier must specify both for combined depth/stencil buffers.
1613
imageAspect = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
1614
} else {
1615
imageAspect = aspect;
1616
}
1617
_dbg_assert_(img.layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1618
srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1619
srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
1620
recordBarrier->TransitionImage(
1621
img.image,
1622
0,
1623
1,
1624
img.numLayers,
1625
aspect,
1626
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1627
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1628
VK_ACCESS_TRANSFER_WRITE_BIT,
1629
VK_ACCESS_TRANSFER_WRITE_BIT,
1630
VK_PIPELINE_STAGE_TRANSFER_BIT,
1631
VK_PIPELINE_STAGE_TRANSFER_BIT
1632
);
1633
}
1634
1635
void VulkanQueueRunner::ResizeReadbackBuffer(CachedReadback *readback, VkDeviceSize requiredSize) {
1636
if (readback->buffer && requiredSize <= readback->bufferSize) {
1637
return;
1638
}
1639
1640
if (readback->buffer) {
1641
vulkan_->Delete().QueueDeleteBufferAllocation(readback->buffer, readback->allocation);
1642
}
1643
1644
readback->bufferSize = requiredSize;
1645
1646
VkDevice device = vulkan_->GetDevice();
1647
1648
VkBufferCreateInfo buf{ VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
1649
buf.size = readback->bufferSize;
1650
buf.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
1651
1652
VmaAllocationCreateInfo allocCreateInfo{};
1653
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
1654
VmaAllocationInfo allocInfo{};
1655
1656
VkResult res = vmaCreateBuffer(vulkan_->Allocator(), &buf, &allocCreateInfo, &readback->buffer, &readback->allocation, &allocInfo);
1657
_assert_(res == VK_SUCCESS);
1658
1659
const VkMemoryType &memoryType = vulkan_->GetMemoryProperties().memoryTypes[allocInfo.memoryType];
1660
readback->isCoherent = (memoryType.propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0;
1661
}
1662
1663
void VulkanQueueRunner::PerformReadback(const VKRStep &step, VkCommandBuffer cmd, FrameData &frameData) {
1664
VkImage image;
1665
VkImageLayout copyLayout;
1666
// Special case for backbuffer readbacks.
1667
if (step.readback.src == nullptr) {
1668
// We only take screenshots after the main render pass (anything else would be stupid) so we need to transition out of PRESENT,
1669
// and then back into it.
1670
// Regarding layers, backbuffer currently only has one layer.
1671
recordBarrier_.TransitionImage(backbufferImage_, 0, 1, 1, VK_IMAGE_ASPECT_COLOR_BIT,
1672
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1673
0, VK_ACCESS_TRANSFER_READ_BIT,
1674
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
1675
copyLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1676
image = backbufferImage_;
1677
} else {
1678
VKRImage *srcImage;
1679
if (step.readback.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1680
srcImage = &step.readback.src->color;
1681
recordBarrier_.TransitionColorImageAuto(srcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
1682
} else if (step.readback.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
1683
srcImage = &step.readback.src->depth;
1684
recordBarrier_.TransitionDepthStencilImageAuto(srcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
1685
_dbg_assert_(srcImage->image != VK_NULL_HANDLE);
1686
} else {
1687
_dbg_assert_msg_(false, "No image aspect to readback?");
1688
return;
1689
}
1690
image = srcImage->image;
1691
copyLayout = srcImage->layout;
1692
}
1693
1694
recordBarrier_.Flush(cmd);
1695
1696
// TODO: Handle different readback formats!
1697
u32 readbackSizeInBytes = sizeof(uint32_t) * step.readback.srcRect.extent.width * step.readback.srcRect.extent.height;
1698
1699
CachedReadback *cached = nullptr;
1700
1701
if (step.readback.delayed) {
1702
ReadbackKey key;
1703
key.framebuf = step.readback.src;
1704
key.width = step.readback.srcRect.extent.width;
1705
key.height = step.readback.srcRect.extent.height;
1706
1707
// See if there's already a buffer we can reuse
1708
if (!frameData.readbacks_.Get(key, &cached)) {
1709
cached = new CachedReadback();
1710
cached->bufferSize = 0;
1711
frameData.readbacks_.Insert(key, cached);
1712
}
1713
} else {
1714
cached = &syncReadback_;
1715
}
1716
1717
ResizeReadbackBuffer(cached, readbackSizeInBytes);
1718
1719
VkBufferImageCopy region{};
1720
region.imageOffset = { step.readback.srcRect.offset.x, step.readback.srcRect.offset.y, 0 };
1721
region.imageExtent = { step.readback.srcRect.extent.width, step.readback.srcRect.extent.height, 1 };
1722
region.imageSubresource.aspectMask = step.readback.aspectMask;
1723
region.imageSubresource.layerCount = 1;
1724
region.bufferOffset = 0;
1725
region.bufferRowLength = step.readback.srcRect.extent.width;
1726
region.bufferImageHeight = step.readback.srcRect.extent.height;
1727
1728
vkCmdCopyImageToBuffer(cmd, image, copyLayout, cached->buffer, 1, &region);
1729
1730
// NOTE: Can't read the buffer using the CPU here - need to sync first.
1731
1732
// If we copied from the backbuffer, transition it back.
1733
if (step.readback.src == nullptr) {
1734
// We only take screenshots after the main render pass (anything else would be stupid) so we need to transition out of PRESENT,
1735
// and then back into it.
1736
// Regarding layers, backbuffer currently only has one layer.
1737
recordBarrier_.TransitionImage(backbufferImage_, 0, 1, 1, VK_IMAGE_ASPECT_COLOR_BIT,
1738
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
1739
VK_ACCESS_TRANSFER_READ_BIT, 0,
1740
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1741
recordBarrier_.Flush(cmd); // probably not needed
1742
copyLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
1743
}
1744
}
1745
1746
void VulkanQueueRunner::PerformReadbackImage(const VKRStep &step, VkCommandBuffer cmd) {
1747
// TODO: Clean this up - just reusing `SetupTransitionToTransferSrc`.
1748
VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1749
recordBarrier_.TransitionColorImageAuto(step.readback_image.image, &layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, 0, 1, 1);
1750
recordBarrier_.Flush(cmd);
1751
1752
ResizeReadbackBuffer(&syncReadback_, sizeof(uint32_t) * step.readback_image.srcRect.extent.width * step.readback_image.srcRect.extent.height);
1753
1754
VkBufferImageCopy region{};
1755
region.imageOffset = { step.readback_image.srcRect.offset.x, step.readback_image.srcRect.offset.y, 0 };
1756
region.imageExtent = { step.readback_image.srcRect.extent.width, step.readback_image.srcRect.extent.height, 1 };
1757
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1758
region.imageSubresource.layerCount = 1;
1759
region.imageSubresource.mipLevel = step.readback_image.mipLevel;
1760
region.bufferOffset = 0;
1761
region.bufferRowLength = step.readback_image.srcRect.extent.width;
1762
region.bufferImageHeight = step.readback_image.srcRect.extent.height;
1763
vkCmdCopyImageToBuffer(cmd, step.readback_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, syncReadback_.buffer, 1, &region);
1764
1765
// Now transfer it back to a texture.
1766
recordBarrier_.TransitionImage(step.readback_image.image, 0, 1, 1, // I don't think we have any multilayer cases for regular textures. Above in PerformReadback, though..
1767
VK_IMAGE_ASPECT_COLOR_BIT,
1768
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1769
VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_SHADER_READ_BIT,
1770
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
1771
recordBarrier_.Flush(cmd); // probably not needed
1772
1773
// NOTE: Can't read the buffer using the CPU here - need to sync first.
1774
// Doing that will also act like a heavyweight barrier ensuring that device writes are visible on the host.
1775
}
1776
1777
bool VulkanQueueRunner::CopyReadbackBuffer(FrameData &frameData, VKRFramebuffer *src, int width, int height, Draw::DataFormat srcFormat, Draw::DataFormat destFormat, int pixelStride, uint8_t *pixels) {
1778
CachedReadback *readback = &syncReadback_;
1779
1780
// Look up in readback cache.
1781
if (src) {
1782
ReadbackKey key;
1783
key.framebuf = src;
1784
key.width = width;
1785
key.height = height;
1786
CachedReadback *cached;
1787
if (frameData.readbacks_.Get(key, &cached)) {
1788
readback = cached;
1789
} else {
1790
// Didn't have a cached image ready yet
1791
return false;
1792
}
1793
}
1794
1795
if (!readback->buffer)
1796
return false; // Didn't find anything in cache, or something has gone really wrong.
1797
1798
// Read back to the requested address in ram from buffer.
1799
void *mappedData;
1800
const size_t srcPixelSize = DataFormatSizeInBytes(srcFormat);
1801
VkResult res = vmaMapMemory(vulkan_->Allocator(), readback->allocation, &mappedData);
1802
1803
if (res != VK_SUCCESS) {
1804
ERROR_LOG(Log::G3D, "CopyReadbackBuffer: vkMapMemory failed! result=%d", (int)res);
1805
return false;
1806
}
1807
1808
if (!readback->isCoherent) {
1809
vmaInvalidateAllocation(vulkan_->Allocator(), readback->allocation, 0, width * height * srcPixelSize);
1810
}
1811
1812
// TODO: Perform these conversions in a compute shader on the GPU.
1813
if (srcFormat == Draw::DataFormat::R8G8B8A8_UNORM) {
1814
ConvertFromRGBA8888(pixels, (const uint8_t *)mappedData, pixelStride, width, width, height, destFormat);
1815
} else if (srcFormat == Draw::DataFormat::B8G8R8A8_UNORM) {
1816
ConvertFromBGRA8888(pixels, (const uint8_t *)mappedData, pixelStride, width, width, height, destFormat);
1817
} else if (srcFormat == destFormat) {
1818
// Can just memcpy when it matches no matter the format!
1819
uint8_t *dst = pixels;
1820
const uint8_t *src = (const uint8_t *)mappedData;
1821
for (int y = 0; y < height; ++y) {
1822
memcpy(dst, src, width * srcPixelSize);
1823
src += width * srcPixelSize;
1824
dst += pixelStride * srcPixelSize;
1825
}
1826
} else if (destFormat == Draw::DataFormat::D32F) {
1827
ConvertToD32F(pixels, (const uint8_t *)mappedData, pixelStride, width, width, height, srcFormat);
1828
} else if (destFormat == Draw::DataFormat::D16) {
1829
ConvertToD16(pixels, (const uint8_t *)mappedData, pixelStride, width, width, height, srcFormat);
1830
} else {
1831
// TODO: Maybe a depth conversion or something?
1832
ERROR_LOG(Log::G3D, "CopyReadbackBuffer: Unknown format");
1833
_assert_msg_(false, "CopyReadbackBuffer: Unknown src format %d", (int)srcFormat);
1834
}
1835
1836
vmaUnmapMemory(vulkan_->Allocator(), readback->allocation);
1837
return true;
1838
}
1839
1840
const char *VKRRenderCommandToString(VKRRenderCommand cmd) {
1841
const char * const str[] = {
1842
"REMOVED",
1843
"BIND_GRAPHICS_PIPELINE", // async
1844
"STENCIL",
1845
"BLEND",
1846
"VIEWPORT",
1847
"SCISSOR",
1848
"CLEAR",
1849
"DRAW",
1850
"DRAW_INDEXED",
1851
"PUSH_CONSTANTS",
1852
"DEBUG_ANNOTATION",
1853
};
1854
if ((int)cmd < ARRAY_SIZE(str)) {
1855
return str[(int)cmd];
1856
} else {
1857
return "N/A";
1858
}
1859
}
1860
1861