CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/Common/GPU/Vulkan/thin3d_vulkan.cpp
Views: 1401
1
// Copyright (c) 2015- PPSSPP Project.
2
3
// This program is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, version 2.0 or later versions.
6
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License 2.0 for more details.
11
12
// A copy of the GPL 2.0 should have been included with the program.
13
// If not, see http://www.gnu.org/licenses/
14
15
// Official git repository and contact information can be found at
16
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17
18
#include <cstdio>
19
#include <vector>
20
#include <string>
21
#include <map>
22
23
#include "Common/Log.h"
24
#include "Common/StringUtils.h"
25
#include "Common/System/Display.h"
26
#include "Common/Math/lin/matrix4x4.h"
27
#include "Common/Data/Convert/SmallDataConvert.h"
28
#include "Common/GPU/thin3d.h"
29
#include "Common/GPU/Vulkan/VulkanRenderManager.h"
30
#include "Common/GPU/Vulkan/VulkanContext.h"
31
#include "Common/GPU/Vulkan/VulkanImage.h"
32
#include "Common/GPU/Vulkan/VulkanMemory.h"
33
#include "Common/GPU/Vulkan/VulkanLoader.h"
34
#include "Common/Thread/Promise.h"
35
36
// For descriptor set 0 (the only one), we use a simple descriptor set for all thin3d rendering: 1 UBO binding point, 3 combined texture/samples.
37
//
38
// binding 0 - uniform buffer
39
// binding 1 - texture/sampler
40
// binding 2 - texture/sampler
41
// binding 3 - texture/sampler
42
//
43
// Vertex data lives in a separate namespace (location = 0, 1, etc).
44
45
using namespace PPSSPP_VK;
46
47
namespace Draw {
48
49
// This can actually be replaced with a cast as the values are in the right order.
50
static const VkCompareOp compToVK[] = {
51
VK_COMPARE_OP_NEVER,
52
VK_COMPARE_OP_LESS,
53
VK_COMPARE_OP_EQUAL,
54
VK_COMPARE_OP_LESS_OR_EQUAL,
55
VK_COMPARE_OP_GREATER,
56
VK_COMPARE_OP_NOT_EQUAL,
57
VK_COMPARE_OP_GREATER_OR_EQUAL,
58
VK_COMPARE_OP_ALWAYS
59
};
60
61
// So can this.
62
static const VkBlendOp blendEqToVk[] = {
63
VK_BLEND_OP_ADD,
64
VK_BLEND_OP_SUBTRACT,
65
VK_BLEND_OP_REVERSE_SUBTRACT,
66
VK_BLEND_OP_MIN,
67
VK_BLEND_OP_MAX,
68
};
69
70
static const VkBlendFactor blendFactorToVk[] = {
71
VK_BLEND_FACTOR_ZERO,
72
VK_BLEND_FACTOR_ONE,
73
VK_BLEND_FACTOR_SRC_COLOR,
74
VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR,
75
VK_BLEND_FACTOR_DST_COLOR,
76
VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR,
77
VK_BLEND_FACTOR_SRC_ALPHA,
78
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
79
VK_BLEND_FACTOR_DST_ALPHA,
80
VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA,
81
VK_BLEND_FACTOR_CONSTANT_COLOR,
82
VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR,
83
VK_BLEND_FACTOR_CONSTANT_ALPHA,
84
VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA,
85
VK_BLEND_FACTOR_SRC1_COLOR,
86
VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR,
87
VK_BLEND_FACTOR_SRC1_ALPHA,
88
VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA,
89
};
90
91
static const VkLogicOp logicOpToVK[] = {
92
VK_LOGIC_OP_CLEAR,
93
VK_LOGIC_OP_SET,
94
VK_LOGIC_OP_COPY,
95
VK_LOGIC_OP_COPY_INVERTED,
96
VK_LOGIC_OP_NO_OP,
97
VK_LOGIC_OP_INVERT,
98
VK_LOGIC_OP_AND,
99
VK_LOGIC_OP_NAND,
100
VK_LOGIC_OP_OR,
101
VK_LOGIC_OP_NOR,
102
VK_LOGIC_OP_XOR,
103
VK_LOGIC_OP_EQUIVALENT,
104
VK_LOGIC_OP_AND_REVERSE,
105
VK_LOGIC_OP_AND_INVERTED,
106
VK_LOGIC_OP_OR_REVERSE,
107
VK_LOGIC_OP_OR_INVERTED,
108
};
109
110
static const VkPrimitiveTopology primToVK[] = {
111
VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
112
VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
113
VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
114
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
115
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
116
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN,
117
// Tesselation shader primitive.
118
VK_PRIMITIVE_TOPOLOGY_PATCH_LIST,
119
// The rest are for geometry shaders only.
120
VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
121
VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY,
122
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY,
123
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY,
124
};
125
126
127
static const VkStencilOp stencilOpToVK[8] = {
128
VK_STENCIL_OP_KEEP,
129
VK_STENCIL_OP_ZERO,
130
VK_STENCIL_OP_REPLACE,
131
VK_STENCIL_OP_INCREMENT_AND_CLAMP,
132
VK_STENCIL_OP_DECREMENT_AND_CLAMP,
133
VK_STENCIL_OP_INVERT,
134
VK_STENCIL_OP_INCREMENT_AND_WRAP,
135
VK_STENCIL_OP_DECREMENT_AND_WRAP,
136
};
137
138
class VKBlendState : public BlendState {
139
public:
140
VkPipelineColorBlendStateCreateInfo info{ VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO };
141
std::vector<VkPipelineColorBlendAttachmentState> attachments;
142
};
143
144
class VKDepthStencilState : public DepthStencilState {
145
public:
146
VkPipelineDepthStencilStateCreateInfo info{ VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO };
147
};
148
149
class VKRasterState : public RasterState {
150
public:
151
VKRasterState(VulkanContext *vulkan, const RasterStateDesc &desc) {
152
cullFace = desc.cull;
153
frontFace = desc.frontFace;
154
}
155
Facing frontFace;
156
CullMode cullFace;
157
158
void ToVulkan(VkPipelineRasterizationStateCreateInfo *info) const {
159
memset(info, 0, sizeof(*info));
160
info->sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
161
info->frontFace = frontFace == Facing::CCW ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE;
162
switch (cullFace) {
163
case CullMode::BACK: info->cullMode = VK_CULL_MODE_BACK_BIT; break;
164
case CullMode::FRONT: info->cullMode = VK_CULL_MODE_FRONT_BIT; break;
165
case CullMode::FRONT_AND_BACK: info->cullMode = VK_CULL_MODE_FRONT_AND_BACK; break;
166
case CullMode::NONE: info->cullMode = VK_CULL_MODE_NONE; break;
167
}
168
info->polygonMode = VK_POLYGON_MODE_FILL;
169
info->lineWidth = 1.0f;
170
}
171
};
172
173
VkShaderStageFlagBits StageToVulkan(ShaderStage stage) {
174
switch (stage) {
175
case ShaderStage::Vertex: return VK_SHADER_STAGE_VERTEX_BIT;
176
case ShaderStage::Geometry: return VK_SHADER_STAGE_GEOMETRY_BIT;
177
case ShaderStage::Compute: return VK_SHADER_STAGE_COMPUTE_BIT;
178
case ShaderStage::Fragment: return VK_SHADER_STAGE_FRAGMENT_BIT;
179
}
180
return VK_SHADER_STAGE_FRAGMENT_BIT;
181
}
182
183
// Not registering this as a resource holder, instead the pipeline is registered. It will
184
// invoke Compile again to recreate the shader then link them together.
185
class VKShaderModule : public ShaderModule {
186
public:
187
VKShaderModule(ShaderStage stage, const std::string &tag) : stage_(stage), tag_(tag) {
188
vkstage_ = StageToVulkan(stage);
189
}
190
bool Compile(VulkanContext *vulkan, ShaderLanguage language, const uint8_t *data, size_t size);
191
const std::string &GetSource() const { return source_; }
192
~VKShaderModule() {
193
if (module_) {
194
VkShaderModule shaderModule = module_->BlockUntilReady();
195
vulkan_->Delete().QueueDeleteShaderModule(shaderModule);
196
vulkan_->Delete().QueueCallback([](VulkanContext *context, void *m) {
197
auto module = (Promise<VkShaderModule> *)m;
198
delete module;
199
}, module_);
200
}
201
}
202
Promise<VkShaderModule> *Get() const { return module_; }
203
ShaderStage GetStage() const override {
204
return stage_;
205
}
206
207
private:
208
VulkanContext *vulkan_ = nullptr;
209
Promise<VkShaderModule> *module_ = nullptr;
210
VkShaderStageFlagBits vkstage_;
211
bool ok_ = false;
212
ShaderStage stage_;
213
std::string source_; // So we can recompile in case of context loss.
214
std::string tag_;
215
};
216
217
bool VKShaderModule::Compile(VulkanContext *vulkan, ShaderLanguage language, const uint8_t *data, size_t size) {
218
// We'll need this to free it later.
219
vulkan_ = vulkan;
220
source_ = (const char *)data;
221
std::vector<uint32_t> spirv;
222
std::string errorMessage;
223
if (!GLSLtoSPV(vkstage_, source_.c_str(), GLSLVariant::VULKAN, spirv, &errorMessage)) {
224
WARN_LOG(Log::G3D, "Shader compile to module failed (%s): %s", tag_.c_str(), errorMessage.c_str());
225
return false;
226
}
227
228
// Just for kicks, sanity check the SPIR-V. The disasm isn't perfect
229
// but gives you some idea of what's going on.
230
#if 0
231
std::string disasm;
232
if (DisassembleSPIRV(spirv, &disasm)) {
233
OutputDebugStringA(disasm.c_str());
234
}
235
#endif
236
237
VkShaderModule shaderModule = VK_NULL_HANDLE;
238
if (vulkan->CreateShaderModule(spirv, &shaderModule, tag_.c_str())) {
239
module_ = Promise<VkShaderModule>::AlreadyDone(shaderModule);
240
ok_ = true;
241
} else {
242
WARN_LOG(Log::G3D, "vkCreateShaderModule failed (%s)", tag_.c_str());
243
ok_ = false;
244
}
245
return ok_;
246
}
247
248
class VKInputLayout : public InputLayout {
249
public:
250
VkVertexInputBindingDescription binding;
251
std::vector<VkVertexInputAttributeDescription> attributes;
252
VkPipelineVertexInputStateCreateInfo visc;
253
};
254
255
class VKPipeline : public Pipeline {
256
public:
257
VKPipeline(VulkanContext *vulkan, size_t size, PipelineFlags _flags, const char *tag) : vulkan_(vulkan), flags(_flags), tag_(tag) {
258
uboSize_ = (int)size;
259
ubo_ = new uint8_t[uboSize_];
260
vkrDesc = new VKRGraphicsPipelineDesc();
261
}
262
~VKPipeline() {
263
if (pipeline) {
264
pipeline->QueueForDeletion(vulkan_);
265
}
266
for (auto dep : deps) {
267
dep->Release();
268
}
269
delete[] ubo_;
270
vkrDesc->Release();
271
}
272
273
void SetDynamicUniformData(const void *data, size_t size) {
274
_dbg_assert_(size <= uboSize_);
275
memcpy(ubo_, data, size);
276
}
277
278
// Returns the binding offset, and the VkBuffer to bind.
279
size_t PushUBO(VulkanPushPool *buf, VulkanContext *vulkan, VkBuffer *vkbuf) {
280
return buf->Push(ubo_, uboSize_, vulkan->GetPhysicalDeviceProperties().properties.limits.minUniformBufferOffsetAlignment, vkbuf);
281
}
282
283
int GetUBOSize() const {
284
return uboSize_;
285
}
286
287
VKRGraphicsPipeline *pipeline = nullptr;
288
VKRGraphicsPipelineDesc *vkrDesc = nullptr;
289
PipelineFlags flags;
290
291
std::vector<VKShaderModule *> deps;
292
293
int stride = 0;
294
int dynamicUniformSize = 0;
295
296
bool usesStencil = false;
297
298
private:
299
VulkanContext *vulkan_;
300
uint8_t *ubo_;
301
int uboSize_;
302
std::string tag_;
303
};
304
305
class VKTexture;
306
class VKBuffer;
307
class VKSamplerState;
308
309
enum {
310
MAX_BOUND_TEXTURES = MAX_TEXTURE_SLOTS,
311
};
312
313
struct DescriptorSetKey {
314
VkImageView imageViews_[MAX_BOUND_TEXTURES];
315
VKSamplerState *samplers_[MAX_BOUND_TEXTURES];
316
VkBuffer buffer_;
317
318
bool operator < (const DescriptorSetKey &other) const {
319
for (int i = 0; i < MAX_BOUND_TEXTURES; ++i) {
320
if (imageViews_[i] < other.imageViews_[i]) return true; else if (imageViews_[i] > other.imageViews_[i]) return false;
321
if (samplers_[i] < other.samplers_[i]) return true; else if (samplers_[i] > other.samplers_[i]) return false;
322
}
323
if (buffer_ < other.buffer_) return true; else if (buffer_ > other.buffer_) return false;
324
return false;
325
}
326
};
327
328
class VKTexture : public Texture {
329
public:
330
VKTexture(VulkanContext *vulkan, VkCommandBuffer cmd, VulkanPushPool *pushBuffer, const TextureDesc &desc)
331
: vulkan_(vulkan), mipLevels_(desc.mipLevels) {
332
format_ = desc.format;
333
}
334
bool Create(VkCommandBuffer cmd, VulkanBarrierBatch *postBarriers, VulkanPushPool *pushBuffer, const TextureDesc &desc);
335
void Update(VkCommandBuffer cmd, VulkanBarrierBatch *postBarriers, VulkanPushPool *pushBuffer, const uint8_t *const *data, TextureCallback callback, int numLevels);
336
337
~VKTexture() {
338
Destroy();
339
}
340
341
VkImageView GetImageView() {
342
if (vkTex_) {
343
return vkTex_->GetImageView();
344
}
345
return VK_NULL_HANDLE; // This would be bad.
346
}
347
348
VkImageView GetImageArrayView() {
349
if (vkTex_) {
350
return vkTex_->GetImageArrayView();
351
}
352
return VK_NULL_HANDLE; // This would be bad.
353
}
354
355
int NumLevels() const {
356
return mipLevels_;
357
}
358
359
private:
360
void UpdateInternal(VkCommandBuffer cmd, VulkanPushPool *pushBuffer, const uint8_t *const *data, TextureCallback callback, int numLevels);
361
362
void Destroy() {
363
if (vkTex_) {
364
vkTex_->Destroy();
365
delete vkTex_;
366
vkTex_ = nullptr;
367
}
368
}
369
370
VulkanContext *vulkan_;
371
VulkanTexture *vkTex_ = nullptr;
372
373
int mipLevels_ = 0;
374
};
375
376
class VKFramebuffer;
377
378
class VKContext : public DrawContext {
379
public:
380
VKContext(VulkanContext *vulkan, bool useRenderThread);
381
~VKContext();
382
383
BackendState GetCurrentBackendState() const override {
384
return BackendState{
385
(u32)renderManager_.GetNumSteps(),
386
true, // Means that the other value is meaningful.
387
};
388
}
389
390
void DebugAnnotate(const char *annotation) override;
391
void Wait() override {
392
vkDeviceWaitIdle(vulkan_->GetDevice());
393
}
394
395
const DeviceCaps &GetDeviceCaps() const override {
396
return caps_;
397
}
398
std::vector<std::string> GetDeviceList() const override {
399
std::vector<std::string> list;
400
for (int i = 0; i < vulkan_->GetNumPhysicalDevices(); i++) {
401
list.push_back(vulkan_->GetPhysicalDeviceProperties(i).properties.deviceName);
402
}
403
return list;
404
}
405
std::vector<std::string> GetPresentModeList(std::string_view currentMarkerString) const override {
406
std::vector<std::string> list;
407
for (auto mode : vulkan_->GetAvailablePresentModes()) {
408
std::string str = VulkanPresentModeToString(mode);
409
if (mode == vulkan_->GetPresentMode()) {
410
str += std::string(" (") + std::string(currentMarkerString) + ")";
411
}
412
list.push_back(str);
413
}
414
return list;
415
}
416
std::vector<std::string> GetSurfaceFormatList() const override {
417
std::vector<std::string> list;
418
for (auto &format : vulkan_->SurfaceFormats()) {
419
std::string str = StringFromFormat("%s : %s", VulkanFormatToString(format.format), VulkanColorSpaceToString(format.colorSpace));
420
list.push_back(str);
421
}
422
return list;
423
}
424
425
uint32_t GetSupportedShaderLanguages() const override {
426
return (uint32_t)ShaderLanguage::GLSL_VULKAN;
427
}
428
uint32_t GetDataFormatSupport(DataFormat fmt) const override;
429
430
PresentMode GetPresentMode() const {
431
switch (vulkan_->GetPresentMode()) {
432
case VK_PRESENT_MODE_FIFO_KHR: return PresentMode::FIFO;
433
case VK_PRESENT_MODE_FIFO_RELAXED_KHR: return PresentMode::FIFO; // We treat is as FIFO for now (and won't ever enable it anyway...)
434
case VK_PRESENT_MODE_IMMEDIATE_KHR: return PresentMode::IMMEDIATE;
435
case VK_PRESENT_MODE_MAILBOX_KHR: return PresentMode::MAILBOX;
436
default: return PresentMode::FIFO;
437
}
438
}
439
440
DepthStencilState *CreateDepthStencilState(const DepthStencilStateDesc &desc) override;
441
BlendState *CreateBlendState(const BlendStateDesc &desc) override;
442
InputLayout *CreateInputLayout(const InputLayoutDesc &desc) override;
443
SamplerState *CreateSamplerState(const SamplerStateDesc &desc) override;
444
RasterState *CreateRasterState(const RasterStateDesc &desc) override;
445
Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) override;
446
ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize, const char *tag) override;
447
448
Texture *CreateTexture(const TextureDesc &desc) override;
449
Buffer *CreateBuffer(size_t size, uint32_t usageFlags) override;
450
Framebuffer *CreateFramebuffer(const FramebufferDesc &desc) override;
451
452
void UpdateBuffer(Buffer *buffer, const uint8_t *data, size_t offset, size_t size, UpdateBufferFlags flags) override;
453
void UpdateTextureLevels(Texture *texture, const uint8_t **data, TextureCallback initDataCallback, int numLevels) override;
454
455
void CopyFramebufferImage(Framebuffer *src, int level, int x, int y, int z, Framebuffer *dst, int dstLevel, int dstX, int dstY, int dstZ, int width, int height, int depth, int channelBits, const char *tag) override;
456
bool BlitFramebuffer(Framebuffer *src, int srcX1, int srcY1, int srcX2, int srcY2, Framebuffer *dst, int dstX1, int dstY1, int dstX2, int dstY2, int channelBits, FBBlitFilter filter, const char *tag) override;
457
bool CopyFramebufferToMemory(Framebuffer *src, int channelBits, int x, int y, int w, int h, Draw::DataFormat format, void *pixels, int pixelStride, ReadbackMode mode, const char *tag) override;
458
DataFormat PreferredFramebufferReadbackFormat(Framebuffer *src) override;
459
460
// These functions should be self explanatory.
461
void BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPassInfo &rp, const char *tag) override;
462
void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) override;
463
464
void GetFramebufferDimensions(Framebuffer *fbo, int *w, int *h) override;
465
466
void SetScissorRect(int left, int top, int width, int height) override;
467
void SetViewport(const Viewport &viewport) override;
468
void SetBlendFactor(float color[4]) override;
469
void SetStencilParams(uint8_t refValue, uint8_t writeMask, uint8_t compareMask) override;
470
471
void BindSamplerStates(int start, int count, SamplerState **state) override;
472
void BindTextures(int start, int count, Texture **textures, TextureBindFlags flags) override;
473
void BindNativeTexture(int sampler, void *nativeTexture) override;
474
475
void BindPipeline(Pipeline *pipeline) override {
476
curPipeline_ = (VKPipeline *)pipeline;
477
}
478
479
void BindVertexBuffer(Buffer *vertexBuffer, int offset) override {
480
curVBuffer_ = (VKBuffer *)vertexBuffer;
481
curVBufferOffset_ = offset;
482
}
483
void BindIndexBuffer(Buffer *indexBuffer, int offset) override {
484
curIBuffer_ = (VKBuffer *)indexBuffer;
485
curIBufferOffset_ = offset;
486
}
487
488
void UpdateDynamicUniformBuffer(const void *ub, size_t size) override;
489
490
// TODO: Add more sophisticated draws.
491
void Draw(int vertexCount, int offset) override;
492
void DrawIndexed(int vertexCount, int offset) override;
493
void DrawUP(const void *vdata, int vertexCount) override;
494
495
void BindCurrentPipeline();
496
void ApplyDynamicState();
497
498
void Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) override;
499
500
void BeginFrame(DebugFlags debugFlags) override;
501
void EndFrame() override;
502
void Present(PresentMode presentMode, int vblanks) override;
503
504
int GetFrameCount() override {
505
return frameCount_;
506
}
507
508
void FlushState() override {}
509
510
void ResetStats() override {
511
renderManager_.ResetStats();
512
}
513
void StopThreads() override {
514
renderManager_.StopThreads();
515
}
516
517
void StartThreads() override {
518
renderManager_.StartThreads();
519
}
520
521
522
std::string GetInfoString(InfoField info) const override {
523
// TODO: Make these actually query the right information
524
switch (info) {
525
case InfoField::APINAME: return "Vulkan";
526
case InfoField::VENDORSTRING: return vulkan_->GetPhysicalDeviceProperties().properties.deviceName;
527
case InfoField::VENDOR: return VulkanVendorString(vulkan_->GetPhysicalDeviceProperties().properties.vendorID);
528
case InfoField::DRIVER: return FormatDriverVersion(vulkan_->GetPhysicalDeviceProperties().properties);
529
case InfoField::SHADELANGVERSION: return "N/A";;
530
case InfoField::APIVERSION: return FormatAPIVersion(vulkan_->InstanceApiVersion());
531
case InfoField::DEVICE_API_VERSION: return FormatAPIVersion(vulkan_->DeviceApiVersion());
532
default: return "?";
533
}
534
}
535
536
void BindDescriptors(VkBuffer buffer, PackedDescriptor descriptors[4]);
537
538
std::vector<std::string> GetFeatureList() const override;
539
std::vector<std::string> GetExtensionList(bool device, bool enabledOnly) const override;
540
541
uint64_t GetNativeObject(NativeObject obj, void *srcObject) override;
542
543
void HandleEvent(Event ev, int width, int height, void *param1, void *param2) override;
544
545
void Invalidate(InvalidationFlags flags) override;
546
547
void InvalidateFramebuffer(FBInvalidationStage stage, uint32_t channels) override;
548
549
void SetInvalidationCallback(InvalidationCallback callback) override {
550
renderManager_.SetInvalidationCallback(callback);
551
}
552
553
std::string GetGpuProfileString() const override {
554
return renderManager_.GetGpuProfileString();
555
}
556
557
private:
558
VulkanTexture *GetNullTexture();
559
VulkanContext *vulkan_ = nullptr;
560
561
int frameCount_ = 0;
562
VulkanRenderManager renderManager_;
563
564
VulkanTexture *nullTexture_ = nullptr;
565
566
AutoRef<VKPipeline> curPipeline_;
567
AutoRef<VKBuffer> curVBuffer_;
568
int curVBufferOffset_ = 0;
569
AutoRef<VKBuffer> curIBuffer_;
570
int curIBufferOffset_ = 0;
571
572
VKRPipelineLayout *pipelineLayout_ = nullptr;
573
VkPipelineCache pipelineCache_ = VK_NULL_HANDLE;
574
AutoRef<VKFramebuffer> curFramebuffer_;
575
576
VkDevice device_;
577
578
enum {
579
MAX_FRAME_COMMAND_BUFFERS = 256,
580
};
581
AutoRef<VKTexture> boundTextures_[MAX_BOUND_TEXTURES];
582
AutoRef<VKSamplerState> boundSamplers_[MAX_BOUND_TEXTURES];
583
VkImageView boundImageView_[MAX_BOUND_TEXTURES]{};
584
TextureBindFlags boundTextureFlags_[MAX_BOUND_TEXTURES]{};
585
586
VulkanPushPool *push_ = nullptr;
587
588
DeviceCaps caps_{};
589
590
uint8_t stencilRef_ = 0;
591
uint8_t stencilWriteMask_ = 0xFF;
592
uint8_t stencilCompareMask_ = 0xFF;
593
};
594
595
// Bits per pixel, not bytes.
596
static int GetBpp(VkFormat format) {
597
switch (format) {
598
case VK_FORMAT_R8G8B8A8_UNORM:
599
case VK_FORMAT_B8G8R8A8_UNORM:
600
return 32;
601
case VK_FORMAT_R8_UNORM:
602
return 8;
603
case VK_FORMAT_R8G8_UNORM:
604
case VK_FORMAT_R16_UNORM:
605
return 16;
606
case VK_FORMAT_R4G4B4A4_UNORM_PACK16:
607
case VK_FORMAT_B4G4R4A4_UNORM_PACK16:
608
case VK_FORMAT_R5G5B5A1_UNORM_PACK16:
609
case VK_FORMAT_R5G6B5_UNORM_PACK16:
610
case VK_FORMAT_B5G5R5A1_UNORM_PACK16:
611
case VK_FORMAT_B5G6R5_UNORM_PACK16:
612
case VK_FORMAT_A1R5G5B5_UNORM_PACK16:
613
return 16;
614
case VK_FORMAT_D24_UNORM_S8_UINT:
615
return 32;
616
case VK_FORMAT_D16_UNORM:
617
return 16;
618
case VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
619
return 4;
620
case VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
621
case VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK:
622
return 8;
623
case VK_FORMAT_ASTC_4x4_UNORM_BLOCK:
624
return 8;
625
case VK_FORMAT_BC1_RGBA_UNORM_BLOCK:
626
return 4;
627
case VK_FORMAT_BC2_UNORM_BLOCK:
628
case VK_FORMAT_BC3_UNORM_BLOCK:
629
case VK_FORMAT_BC4_UNORM_BLOCK:
630
case VK_FORMAT_BC5_UNORM_BLOCK:
631
case VK_FORMAT_BC7_UNORM_BLOCK:
632
return 8;
633
default:
634
return 0;
635
}
636
}
637
638
static VkFormat DataFormatToVulkan(DataFormat format) {
639
switch (format) {
640
case DataFormat::D16: return VK_FORMAT_D16_UNORM;
641
case DataFormat::D16_S8: return VK_FORMAT_D16_UNORM_S8_UINT;
642
case DataFormat::D24_S8: return VK_FORMAT_D24_UNORM_S8_UINT;
643
case DataFormat::D32F: return VK_FORMAT_D32_SFLOAT;
644
case DataFormat::D32F_S8: return VK_FORMAT_D32_SFLOAT_S8_UINT;
645
case DataFormat::S8: return VK_FORMAT_S8_UINT;
646
647
case DataFormat::R16_UNORM: return VK_FORMAT_R16_UNORM;
648
649
case DataFormat::R16_FLOAT: return VK_FORMAT_R16_SFLOAT;
650
case DataFormat::R16G16_FLOAT: return VK_FORMAT_R16G16_SFLOAT;
651
case DataFormat::R16G16B16A16_FLOAT: return VK_FORMAT_R16G16B16A16_SFLOAT;
652
case DataFormat::R8_UNORM: return VK_FORMAT_R8_UNORM;
653
case DataFormat::R8G8_UNORM: return VK_FORMAT_R8G8_UNORM;
654
case DataFormat::R8G8B8_UNORM: return VK_FORMAT_R8G8B8_UNORM;
655
case DataFormat::R8G8B8A8_UNORM: return VK_FORMAT_R8G8B8A8_UNORM;
656
case DataFormat::R4G4_UNORM_PACK8: return VK_FORMAT_R4G4_UNORM_PACK8;
657
658
// Note: A4R4G4B4_UNORM_PACK16 is not supported.
659
case DataFormat::R4G4B4A4_UNORM_PACK16: return VK_FORMAT_R4G4B4A4_UNORM_PACK16;
660
case DataFormat::B4G4R4A4_UNORM_PACK16: return VK_FORMAT_B4G4R4A4_UNORM_PACK16;
661
case DataFormat::R5G5B5A1_UNORM_PACK16: return VK_FORMAT_R5G5B5A1_UNORM_PACK16;
662
case DataFormat::B5G5R5A1_UNORM_PACK16: return VK_FORMAT_B5G5R5A1_UNORM_PACK16;
663
case DataFormat::R5G6B5_UNORM_PACK16: return VK_FORMAT_R5G6B5_UNORM_PACK16;
664
case DataFormat::B5G6R5_UNORM_PACK16: return VK_FORMAT_B5G6R5_UNORM_PACK16;
665
case DataFormat::A1R5G5B5_UNORM_PACK16: return VK_FORMAT_A1R5G5B5_UNORM_PACK16;
666
667
case DataFormat::R32_FLOAT: return VK_FORMAT_R32_SFLOAT;
668
case DataFormat::R32G32_FLOAT: return VK_FORMAT_R32G32_SFLOAT;
669
case DataFormat::R32G32B32_FLOAT: return VK_FORMAT_R32G32B32_SFLOAT;
670
case DataFormat::R32G32B32A32_FLOAT: return VK_FORMAT_R32G32B32A32_SFLOAT;
671
672
case DataFormat::BC1_RGBA_UNORM_BLOCK: return VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
673
case DataFormat::BC2_UNORM_BLOCK: return VK_FORMAT_BC2_UNORM_BLOCK;
674
case DataFormat::BC3_UNORM_BLOCK: return VK_FORMAT_BC3_UNORM_BLOCK;
675
case DataFormat::BC4_UNORM_BLOCK: return VK_FORMAT_BC4_UNORM_BLOCK;
676
case DataFormat::BC5_UNORM_BLOCK: return VK_FORMAT_BC5_UNORM_BLOCK;
677
case DataFormat::BC7_UNORM_BLOCK: return VK_FORMAT_BC7_UNORM_BLOCK;
678
679
case DataFormat::ETC2_R8G8B8A1_UNORM_BLOCK: return VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK;
680
case DataFormat::ETC2_R8G8B8A8_UNORM_BLOCK: return VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK;
681
case DataFormat::ETC2_R8G8B8_UNORM_BLOCK: return VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;
682
683
case DataFormat::ASTC_4x4_UNORM_BLOCK: return VK_FORMAT_ASTC_4x4_UNORM_BLOCK;
684
685
default:
686
return VK_FORMAT_UNDEFINED;
687
}
688
}
689
690
static inline VkSamplerAddressMode AddressModeToVulkan(Draw::TextureAddressMode mode) {
691
switch (mode) {
692
case TextureAddressMode::CLAMP_TO_BORDER: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
693
case TextureAddressMode::CLAMP_TO_EDGE: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
694
case TextureAddressMode::REPEAT_MIRROR: return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
695
default:
696
case TextureAddressMode::REPEAT: return VK_SAMPLER_ADDRESS_MODE_REPEAT;
697
}
698
}
699
700
VulkanTexture *VKContext::GetNullTexture() {
701
if (!nullTexture_) {
702
VkCommandBuffer cmdInit = renderManager_.GetInitCmd();
703
nullTexture_ = new VulkanTexture(vulkan_, "Null");
704
int w = 8;
705
int h = 8;
706
VulkanBarrierBatch barrier;
707
nullTexture_->CreateDirect(w, h, 1, 1, VK_FORMAT_A8B8G8R8_UNORM_PACK32, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
708
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, &barrier);
709
barrier.Flush(cmdInit);
710
uint32_t bindOffset;
711
VkBuffer bindBuf;
712
uint32_t *data = (uint32_t *)push_->Allocate(w * h * 4, 4, &bindBuf, &bindOffset);
713
_assert_(data != nullptr);
714
for (int y = 0; y < h; y++) {
715
for (int x = 0; x < w; x++) {
716
// data[y*w + x] = ((x ^ y) & 1) ? 0xFF808080 : 0xFF000000; // gray/black checkerboard
717
data[y*w + x] = 0; // black
718
}
719
}
720
TextureCopyBatch batch;
721
nullTexture_->CopyBufferToMipLevel(cmdInit, &batch, 0, w, h, 0, bindBuf, bindOffset, w);
722
nullTexture_->FinishCopyBatch(cmdInit, &batch);
723
nullTexture_->EndCreate(cmdInit, false, VK_PIPELINE_STAGE_TRANSFER_BIT);
724
}
725
return nullTexture_;
726
}
727
728
class VKSamplerState : public SamplerState {
729
public:
730
VKSamplerState(VulkanContext *vulkan, const SamplerStateDesc &desc) : vulkan_(vulkan) {
731
VkSamplerCreateInfo s = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
732
s.addressModeU = AddressModeToVulkan(desc.wrapU);
733
s.addressModeV = AddressModeToVulkan(desc.wrapV);
734
s.addressModeW = AddressModeToVulkan(desc.wrapW);
735
s.anisotropyEnable = desc.maxAniso > 1.0f;
736
s.maxAnisotropy = desc.maxAniso;
737
s.magFilter = desc.magFilter == TextureFilter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
738
s.minFilter = desc.minFilter == TextureFilter::LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
739
s.mipmapMode = desc.mipFilter == TextureFilter::LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST;
740
s.maxLod = VK_LOD_CLAMP_NONE;
741
VkResult res = vkCreateSampler(vulkan_->GetDevice(), &s, nullptr, &sampler_);
742
_assert_(VK_SUCCESS == res);
743
}
744
~VKSamplerState() {
745
vulkan_->Delete().QueueDeleteSampler(sampler_);
746
}
747
748
VkSampler GetSampler() { return sampler_; }
749
750
private:
751
VulkanContext *vulkan_;
752
VkSampler sampler_;
753
};
754
755
SamplerState *VKContext::CreateSamplerState(const SamplerStateDesc &desc) {
756
return new VKSamplerState(vulkan_, desc);
757
}
758
759
RasterState *VKContext::CreateRasterState(const RasterStateDesc &desc) {
760
return new VKRasterState(vulkan_, desc);
761
}
762
763
void VKContext::BindSamplerStates(int start, int count, SamplerState **state) {
764
_assert_(start + count <= MAX_BOUND_TEXTURES);
765
for (int i = start; i < start + count; i++) {
766
boundSamplers_[i] = (VKSamplerState *)state[i - start];
767
}
768
}
769
770
enum class TextureState {
771
UNINITIALIZED,
772
STAGED,
773
INITIALIZED,
774
PENDING_DESTRUCTION,
775
};
776
777
bool VKTexture::Create(VkCommandBuffer cmd, VulkanBarrierBatch *postBarriers, VulkanPushPool *pushBuffer, const TextureDesc &desc) {
778
// Zero-sized textures not allowed.
779
_assert_(desc.width * desc.height * desc.depth > 0); // remember to set depth to 1!
780
if (desc.width * desc.height * desc.depth <= 0) {
781
ERROR_LOG(Log::G3D, "Bad texture dimensions %dx%dx%d", desc.width, desc.height, desc.depth);
782
return false;
783
}
784
_dbg_assert_(pushBuffer);
785
format_ = desc.format;
786
mipLevels_ = desc.mipLevels;
787
width_ = desc.width;
788
height_ = desc.height;
789
depth_ = desc.depth;
790
vkTex_ = new VulkanTexture(vulkan_, desc.tag);
791
VkFormat vulkanFormat = DataFormatToVulkan(format_);
792
int usageBits = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
793
if (mipLevels_ > (int)desc.initData.size()) {
794
// Gonna have to generate some, which requires TRANSFER_SRC
795
usageBits |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
796
}
797
798
VkComponentMapping r8AsAlpha[4] = { VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_R };
799
800
VulkanBarrierBatch barrier;
801
if (!vkTex_->CreateDirect(width_, height_, 1, mipLevels_, vulkanFormat, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, usageBits, &barrier, desc.swizzle == TextureSwizzle::R8_AS_ALPHA ? r8AsAlpha : nullptr)) {
802
ERROR_LOG(Log::G3D, "Failed to create VulkanTexture: %dx%dx%d fmt %d, %d levels", width_, height_, depth_, (int)vulkanFormat, mipLevels_);
803
return false;
804
}
805
barrier.Flush(cmd);
806
VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
807
if (desc.initData.size()) {
808
UpdateInternal(cmd, pushBuffer, desc.initData.data(), desc.initDataCallback, (int)desc.initData.size());
809
// Generate the rest of the mips automatically.
810
if (desc.initData.size() < mipLevels_) {
811
vkTex_->GenerateMips(cmd, (int)desc.initData.size(), false);
812
layout = VK_IMAGE_LAYOUT_GENERAL;
813
}
814
}
815
vkTex_->EndCreate(cmd, false, VK_PIPELINE_STAGE_TRANSFER_BIT, layout);
816
return true;
817
}
818
819
void VKTexture::Update(VkCommandBuffer cmd, VulkanBarrierBatch *postBarriers, VulkanPushPool *pushBuffer, const uint8_t * const *data, TextureCallback initDataCallback, int numLevels) {
820
// Before we can use UpdateInternal, we need to transition the image to the same state as after CreateDirect,
821
// making it ready for writing.
822
vkTex_->PrepareForTransferDst(cmd, numLevels);
823
UpdateInternal(cmd, pushBuffer, data, initDataCallback, numLevels);
824
vkTex_->RestoreAfterTransferDst(numLevels, postBarriers);
825
}
826
827
void VKTexture::UpdateInternal(VkCommandBuffer cmd, VulkanPushPool *pushBuffer, const uint8_t * const *data, TextureCallback initDataCallback, int numLevels) {
828
int w = width_;
829
int h = height_;
830
int d = depth_;
831
VkFormat vulkanFormat = DataFormatToVulkan(format_);
832
int bpp = GetBpp(vulkanFormat);
833
int bytesPerPixel = bpp / 8;
834
TextureCopyBatch batch;
835
batch.reserve(numLevels);
836
for (int i = 0; i < numLevels; i++) {
837
uint32_t offset;
838
VkBuffer buf;
839
size_t size = w * h * d * bytesPerPixel;
840
uint8_t *dest = (uint8_t *)pushBuffer->Allocate(size, 16, &buf, &offset);
841
if (initDataCallback) {
842
_assert_(dest != nullptr);
843
if (!initDataCallback(dest, data[i], w, h, d, w * bytesPerPixel, h * w * bytesPerPixel)) {
844
memcpy(dest, data[i], size);
845
}
846
} else {
847
memcpy(dest, data[i], size);
848
}
849
vkTex_->CopyBufferToMipLevel(cmd, &batch, i, w, h, 0, buf, offset, w);
850
w = (w + 1) / 2;
851
h = (h + 1) / 2;
852
d = (d + 1) / 2;
853
}
854
vkTex_->FinishCopyBatch(cmd, &batch);
855
}
856
857
static DataFormat DataFormatFromVulkanDepth(VkFormat fmt) {
858
switch (fmt) {
859
case VK_FORMAT_D24_UNORM_S8_UINT:
860
return DataFormat::D24_S8;
861
case VK_FORMAT_D16_UNORM:
862
return DataFormat::D16;
863
case VK_FORMAT_D32_SFLOAT:
864
return DataFormat::D32F;
865
case VK_FORMAT_D32_SFLOAT_S8_UINT:
866
return DataFormat::D32F_S8;
867
case VK_FORMAT_D16_UNORM_S8_UINT:
868
return DataFormat::D16_S8;
869
default:
870
break;
871
}
872
873
return DataFormat::UNDEFINED;
874
}
875
876
VKContext::VKContext(VulkanContext *vulkan, bool useRenderThread)
877
: vulkan_(vulkan), renderManager_(vulkan, useRenderThread, frameTimeHistory_) {
878
shaderLanguageDesc_.Init(GLSL_VULKAN);
879
880
VkFormat depthStencilFormat = vulkan->GetDeviceInfo().preferredDepthStencilFormat;
881
882
INFO_LOG(Log::G3D, "Determining Vulkan device caps");
883
884
caps_.setMaxFrameLatencySupported = true;
885
caps_.anisoSupported = vulkan->GetDeviceFeatures().enabled.standard.samplerAnisotropy != 0;
886
caps_.geometryShaderSupported = vulkan->GetDeviceFeatures().enabled.standard.geometryShader != 0;
887
caps_.tesselationShaderSupported = vulkan->GetDeviceFeatures().enabled.standard.tessellationShader != 0;
888
caps_.dualSourceBlend = vulkan->GetDeviceFeatures().enabled.standard.dualSrcBlend != 0;
889
caps_.depthClampSupported = vulkan->GetDeviceFeatures().enabled.standard.depthClamp != 0;
890
891
// Comment out these two to test geometry shader culling on any geometry shader-supporting hardware.
892
caps_.clipDistanceSupported = vulkan->GetDeviceFeatures().enabled.standard.shaderClipDistance != 0;
893
caps_.cullDistanceSupported = vulkan->GetDeviceFeatures().enabled.standard.shaderCullDistance != 0;
894
895
caps_.framebufferBlitSupported = true;
896
caps_.framebufferCopySupported = true;
897
caps_.framebufferDepthBlitSupported = vulkan->GetDeviceInfo().canBlitToPreferredDepthStencilFormat;
898
caps_.framebufferStencilBlitSupported = caps_.framebufferDepthBlitSupported;
899
caps_.framebufferDepthCopySupported = true; // Will pretty much always be the case.
900
caps_.framebufferSeparateDepthCopySupported = true; // Will pretty much always be the case.
901
// This doesn't affect what depth/stencil format is actually used, see VulkanQueueRunner.
902
caps_.preferredDepthBufferFormat = DataFormatFromVulkanDepth(vulkan->GetDeviceInfo().preferredDepthStencilFormat);
903
caps_.texture3DSupported = true;
904
caps_.textureDepthSupported = true;
905
caps_.fragmentShaderInt32Supported = true;
906
caps_.textureNPOTFullySupported = true;
907
caps_.fragmentShaderDepthWriteSupported = true;
908
caps_.fragmentShaderStencilWriteSupported = vulkan->Extensions().EXT_shader_stencil_export;
909
caps_.blendMinMaxSupported = true;
910
caps_.logicOpSupported = vulkan->GetDeviceFeatures().enabled.standard.logicOp != 0;
911
caps_.multiViewSupported = vulkan->GetDeviceFeatures().enabled.multiview.multiview != 0;
912
caps_.sampleRateShadingSupported = vulkan->GetDeviceFeatures().enabled.standard.sampleRateShading != 0;
913
caps_.textureSwizzleSupported = true;
914
915
// Note that it must also be enabled on the pipelines (which we do).
916
caps_.provokingVertexLast = vulkan->GetDeviceFeatures().enabled.provokingVertex.provokingVertexLast;
917
918
// Present mode stuff
919
caps_.presentMaxInterval = 1;
920
caps_.presentInstantModeChange = false; // TODO: Fix this with some work in VulkanContext
921
caps_.presentModesSupported = (PresentMode)0;
922
for (auto mode : vulkan->GetAvailablePresentModes()) {
923
switch (mode) {
924
case VK_PRESENT_MODE_FIFO_KHR: caps_.presentModesSupported |= PresentMode::FIFO; break;
925
case VK_PRESENT_MODE_IMMEDIATE_KHR: caps_.presentModesSupported |= PresentMode::IMMEDIATE; break;
926
case VK_PRESENT_MODE_MAILBOX_KHR: caps_.presentModesSupported |= PresentMode::MAILBOX; break;
927
default: break; // Ignore any other modes.
928
}
929
}
930
931
const auto &limits = vulkan->GetPhysicalDeviceProperties().properties.limits;
932
933
auto deviceProps = vulkan->GetPhysicalDeviceProperties(vulkan_->GetCurrentPhysicalDeviceIndex()).properties;
934
935
switch (deviceProps.vendorID) {
936
case VULKAN_VENDOR_AMD: caps_.vendor = GPUVendor::VENDOR_AMD; break;
937
case VULKAN_VENDOR_ARM: caps_.vendor = GPUVendor::VENDOR_ARM; break;
938
case VULKAN_VENDOR_IMGTEC: caps_.vendor = GPUVendor::VENDOR_IMGTEC; break;
939
case VULKAN_VENDOR_NVIDIA: caps_.vendor = GPUVendor::VENDOR_NVIDIA; break;
940
case VULKAN_VENDOR_QUALCOMM: caps_.vendor = GPUVendor::VENDOR_QUALCOMM; break;
941
case VULKAN_VENDOR_INTEL: caps_.vendor = GPUVendor::VENDOR_INTEL; break;
942
case VULKAN_VENDOR_APPLE: caps_.vendor = GPUVendor::VENDOR_APPLE; break;
943
case VULKAN_VENDOR_MESA: caps_.vendor = GPUVendor::VENDOR_MESA; break;
944
default:
945
WARN_LOG(Log::G3D, "Unknown vendor ID %08x", deviceProps.vendorID);
946
caps_.vendor = GPUVendor::VENDOR_UNKNOWN;
947
break;
948
}
949
950
switch (caps_.vendor) {
951
case GPUVendor::VENDOR_ARM:
952
case GPUVendor::VENDOR_IMGTEC:
953
case GPUVendor::VENDOR_QUALCOMM:
954
caps_.isTilingGPU = true;
955
break;
956
default:
957
caps_.isTilingGPU = false;
958
break;
959
}
960
961
if (caps_.vendor == GPUVendor::VENDOR_IMGTEC) {
962
// Enable some things that cut down pipeline counts but may have other costs.
963
caps_.verySlowShaderCompiler = true;
964
}
965
966
// Hide D3D9 when we know it likely won't work well.
967
#if PPSSPP_PLATFORM(WINDOWS)
968
caps_.supportsD3D9 = true;
969
if (!strcmp(deviceProps.deviceName, "Intel(R) Iris(R) Xe Graphics")) {
970
caps_.supportsD3D9 = false;
971
}
972
#endif
973
974
// VkSampleCountFlagBits is arranged correctly for our purposes.
975
// Only support MSAA levels that have support for all three of color, depth, stencil.
976
977
bool multisampleAllowed = true;
978
979
caps_.deviceID = deviceProps.deviceID;
980
981
if (caps_.vendor == GPUVendor::VENDOR_QUALCOMM) {
982
if (caps_.deviceID < 0x6000000) { // On sub 6xx series GPUs, disallow multisample.
983
INFO_LOG(Log::G3D, "Multisampling was disabled due to old driver version (Adreno)");
984
multisampleAllowed = false;
985
}
986
987
// Adreno 5xx devices, all known driver versions, fail to discard stencil when depth write is off.
988
// See: https://github.com/hrydgard/ppsspp/pull/11684
989
if (deviceProps.deviceID >= 0x05000000 && deviceProps.deviceID < 0x06000000) {
990
if (deviceProps.driverVersion < 0x80180000) {
991
bugs_.Infest(Bugs::NO_DEPTH_CANNOT_DISCARD_STENCIL_ADRENO);
992
}
993
}
994
// Color write mask not masking write in certain scenarios with a depth test, see #10421.
995
// Known still present on driver 0x80180000 and Adreno 5xx (possibly more.)
996
// Known working on driver 0x801EA000 and Adreno 620.
997
if (deviceProps.driverVersion < 0x801EA000 || deviceProps.deviceID < 0x06000000)
998
bugs_.Infest(Bugs::COLORWRITEMASK_BROKEN_WITH_DEPTHTEST);
999
1000
// Trying to follow all the rules in https://registry.khronos.org/vulkan/specs/1.3/html/vkspec.html#synchronization-pipeline-barriers-subpass-self-dependencies
1001
// and https://registry.khronos.org/vulkan/specs/1.3/html/vkspec.html#renderpass-feedbackloop, but still it doesn't
1002
// quite work - artifacts on triangle boundaries on Adreno.
1003
bugs_.Infest(Bugs::SUBPASS_FEEDBACK_BROKEN);
1004
} else if (caps_.vendor == GPUVendor::VENDOR_AMD) {
1005
// See issue #10074, and also #10065 (AMD) and #10109 for the choice of the driver version to check for.
1006
if (deviceProps.driverVersion < 0x00407000) {
1007
bugs_.Infest(Bugs::DUAL_SOURCE_BLENDING_BROKEN);
1008
}
1009
} else if (caps_.vendor == GPUVendor::VENDOR_INTEL) {
1010
// Workaround for Intel driver bug. TODO: Re-enable after some driver version
1011
bugs_.Infest(Bugs::DUAL_SOURCE_BLENDING_BROKEN);
1012
} else if (caps_.vendor == GPUVendor::VENDOR_ARM) {
1013
// Really old Vulkan drivers for Mali didn't have proper versions. We try to detect that (can't be 100% but pretty good).
1014
bool isOldVersion = IsHashMaliDriverVersion(deviceProps);
1015
1016
int majorVersion = VK_API_VERSION_MAJOR(deviceProps.driverVersion);
1017
1018
// These GPUs (up to some certain hardware version?) have a bug where draws where gl_Position.w == .z
1019
// corrupt the depth buffer. This is easily worked around by simply scaling Z down a tiny bit when this case
1020
// is detected. See: https://github.com/hrydgard/ppsspp/issues/11937
1021
bugs_.Infest(Bugs::EQUAL_WZ_CORRUPTS_DEPTH);
1022
1023
// Nearly identical to the the Adreno bug, see #13833 (Midnight Club map broken) and other issues.
1024
// It has the additional caveat that combining depth writes with NEVER depth tests crashes the driver.
1025
// Reported fixed in major version 40 - let's add a check once confirmed.
1026
bugs_.Infest(Bugs::NO_DEPTH_CANNOT_DISCARD_STENCIL_MALI);
1027
1028
// This started in driver 31 or 32, fixed in 40 - let's add a check once confirmed.
1029
if (majorVersion >= 32) {
1030
bugs_.Infest(Bugs::MALI_CONSTANT_LOAD_BUG); // See issue #15661
1031
}
1032
1033
// Older ARM devices have very slow geometry shaders, not worth using. At least before 15.
1034
// Also seen to cause weird issues on 18, so let's lump it in.
1035
if (majorVersion <= 18 || isOldVersion) {
1036
bugs_.Infest(Bugs::GEOMETRY_SHADERS_SLOW_OR_BROKEN);
1037
}
1038
1039
// Attempt to workaround #17386
1040
if (isOldVersion) {
1041
if (!strcmp(deviceProps.deviceName, "Mali-T880") ||
1042
!strcmp(deviceProps.deviceName, "Mali-T860") ||
1043
!strcmp(deviceProps.deviceName, "Mali-T830")) {
1044
bugs_.Infest(Bugs::UNIFORM_INDEXING_BROKEN);
1045
}
1046
}
1047
1048
if (isOldVersion) {
1049
// Very rough heuristic.
1050
multisampleAllowed = false;
1051
}
1052
} else if (caps_.vendor == GPUVendor::VENDOR_IMGTEC) {
1053
// Not sure about driver versions, so let's just ban, impact is tiny.
1054
bugs_.Infest(Bugs::PVR_BAD_16BIT_TEXFORMATS);
1055
}
1056
1057
if (!vulkan->Extensions().KHR_depth_stencil_resolve) {
1058
INFO_LOG(Log::G3D, "KHR_depth_stencil_resolve not supported, disabling multisampling");
1059
multisampleAllowed = false;
1060
}
1061
1062
if (!vulkan->Extensions().KHR_create_renderpass2) {
1063
WARN_LOG(Log::G3D, "KHR_create_renderpass2 not supported, disabling multisampling");
1064
multisampleAllowed = false;
1065
} else {
1066
_dbg_assert_(vkCreateRenderPass2 != nullptr);
1067
}
1068
1069
// We limit multisampling functionality to reasonably recent and known-good tiling GPUs.
1070
if (multisampleAllowed) {
1071
// Check for depth stencil resolve. Without it, depth textures won't work, and we don't want that mess
1072
// of compatibility reports, so we'll just disable multisampling in this case for now.
1073
// There are potential workarounds for devices that don't support it, but those are nearly non-existent now.
1074
const auto &resolveProperties = vulkan->GetPhysicalDeviceProperties().depthStencilResolve;
1075
if (((resolveProperties.supportedDepthResolveModes & resolveProperties.supportedStencilResolveModes) & VK_RESOLVE_MODE_SAMPLE_ZERO_BIT) != 0) {
1076
caps_.multiSampleLevelsMask = (limits.framebufferColorSampleCounts & limits.framebufferDepthSampleCounts & limits.framebufferStencilSampleCounts);
1077
INFO_LOG(Log::G3D, "Multisample levels mask: %d", caps_.multiSampleLevelsMask);
1078
} else {
1079
INFO_LOG(Log::G3D, "Not enough depth/stencil resolve modes supported, disabling multisampling. Color: %d Depth: %d Stencil: %d",
1080
limits.framebufferColorSampleCounts, limits.framebufferDepthSampleCounts, limits.framebufferStencilSampleCounts);
1081
caps_.multiSampleLevelsMask = 1;
1082
}
1083
} else {
1084
caps_.multiSampleLevelsMask = 1;
1085
}
1086
1087
// Vulkan can support this through input attachments and various extensions, but not worth
1088
// the trouble.
1089
caps_.framebufferFetchSupported = false;
1090
1091
device_ = vulkan->GetDevice();
1092
1093
VkBufferUsageFlags usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
1094
push_ = new VulkanPushPool(vulkan_, "pushBuffer", 4 * 1024 * 1024, usage);
1095
1096
// binding 0 - uniform data
1097
// binding 1 - combined sampler/image 0
1098
// binding 2 - combined sampler/image 1
1099
// ...etc
1100
BindingType bindings[MAX_BOUND_TEXTURES + 1];
1101
bindings[0] = BindingType::UNIFORM_BUFFER_DYNAMIC_ALL;
1102
for (int i = 0; i < MAX_BOUND_TEXTURES; ++i) {
1103
bindings[1 + i] = BindingType::COMBINED_IMAGE_SAMPLER;
1104
}
1105
pipelineLayout_ = renderManager_.CreatePipelineLayout(bindings, ARRAY_SIZE(bindings), caps_.geometryShaderSupported, "thin3d_layout");
1106
1107
VkPipelineCacheCreateInfo pc{ VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO };
1108
VkResult res = vkCreatePipelineCache(vulkan_->GetDevice(), &pc, nullptr, &pipelineCache_);
1109
_assert_(VK_SUCCESS == res);
1110
}
1111
1112
VKContext::~VKContext() {
1113
DestroyPresets();
1114
1115
delete nullTexture_;
1116
push_->Destroy();
1117
delete push_;
1118
renderManager_.DestroyPipelineLayout(pipelineLayout_);
1119
vulkan_->Delete().QueueDeletePipelineCache(pipelineCache_);
1120
}
1121
1122
void VKContext::BeginFrame(DebugFlags debugFlags) {
1123
renderManager_.BeginFrame(debugFlags & DebugFlags::PROFILE_TIMESTAMPS, debugFlags & DebugFlags::PROFILE_SCOPES);
1124
push_->BeginFrame();
1125
}
1126
1127
void VKContext::EndFrame() {
1128
// Do all the work to submit the command buffers etc.
1129
renderManager_.Finish();
1130
// Unbind stuff, to avoid accidentally relying on it across frames (and provide some protection against forgotten unbinds of deleted things).
1131
Invalidate(InvalidationFlags::CACHED_RENDER_STATE);
1132
}
1133
1134
void VKContext::Present(PresentMode presentMode, int vblanks) {
1135
if (presentMode == PresentMode::FIFO) {
1136
_dbg_assert_(vblanks == 0 || vblanks == 1);
1137
}
1138
renderManager_.Present();
1139
frameCount_++;
1140
}
1141
1142
void VKContext::Invalidate(InvalidationFlags flags) {
1143
if (flags & InvalidationFlags::CACHED_RENDER_STATE) {
1144
curPipeline_ = nullptr;
1145
1146
for (auto &view : boundImageView_) {
1147
view = VK_NULL_HANDLE;
1148
}
1149
for (auto &sampler : boundSamplers_) {
1150
sampler = nullptr;
1151
}
1152
for (auto &texture : boundTextures_) {
1153
texture = nullptr;
1154
}
1155
}
1156
}
1157
1158
void VKContext::BindDescriptors(VkBuffer buf, PackedDescriptor descriptors[4]) {
1159
descriptors[0].buffer.buffer = buf;
1160
descriptors[0].buffer.offset = 0; // dynamic
1161
descriptors[0].buffer.range = curPipeline_->GetUBOSize();
1162
1163
int numDescs = 1;
1164
for (int i = 0; i < MAX_BOUND_TEXTURES; ++i) {
1165
VkImageView view;
1166
VkSampler sampler;
1167
if (boundTextures_[i]) {
1168
view = (boundTextureFlags_[i] & TextureBindFlags::VULKAN_BIND_ARRAY) ? boundTextures_[i]->GetImageArrayView() : boundTextures_[i]->GetImageView();
1169
} else {
1170
view = boundImageView_[i];
1171
}
1172
sampler = boundSamplers_[i] ? boundSamplers_[i]->GetSampler() : VK_NULL_HANDLE;
1173
1174
if (view && sampler) {
1175
descriptors[i + 1].image.view = view;
1176
descriptors[i + 1].image.sampler = sampler;
1177
} else {
1178
descriptors[i + 1].image.view = VK_NULL_HANDLE;
1179
descriptors[i + 1].image.sampler = VK_NULL_HANDLE;
1180
}
1181
}
1182
}
1183
1184
Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc, const char *tag) {
1185
VKInputLayout *input = (VKInputLayout *)desc.inputLayout;
1186
VKBlendState *blend = (VKBlendState *)desc.blend;
1187
VKDepthStencilState *depth = (VKDepthStencilState *)desc.depthStencil;
1188
VKRasterState *raster = (VKRasterState *)desc.raster;
1189
1190
PipelineFlags pipelineFlags = (PipelineFlags)0;
1191
if (depth->info.depthTestEnable || depth->info.stencilTestEnable) {
1192
pipelineFlags |= PipelineFlags::USES_DEPTH_STENCIL;
1193
}
1194
// TODO: We need code to set USES_BLEND_CONSTANT here too, if we're ever gonna use those in thin3d code.
1195
1196
VKPipeline *pipeline = new VKPipeline(vulkan_, desc.uniformDesc ? desc.uniformDesc->uniformBufferSize : 16 * sizeof(float), pipelineFlags, tag);
1197
1198
VKRGraphicsPipelineDesc &gDesc = *pipeline->vkrDesc;
1199
1200
std::vector<VkPipelineShaderStageCreateInfo> stages;
1201
stages.resize(desc.shaders.size());
1202
1203
for (auto &iter : desc.shaders) {
1204
VKShaderModule *vkshader = (VKShaderModule *)iter;
1205
vkshader->AddRef();
1206
pipeline->deps.push_back(vkshader);
1207
if (vkshader->GetStage() == ShaderStage::Vertex) {
1208
gDesc.vertexShader = vkshader->Get();
1209
} else if (vkshader->GetStage() == ShaderStage::Fragment) {
1210
gDesc.fragmentShader = vkshader->Get();
1211
} else {
1212
ERROR_LOG(Log::G3D, "Bad stage");
1213
delete pipeline;
1214
return nullptr;
1215
}
1216
}
1217
1218
_dbg_assert_(input);
1219
_dbg_assert_((int)input->attributes.size() == (int)input->visc.vertexAttributeDescriptionCount);
1220
1221
pipeline->stride = input->binding.stride;
1222
gDesc.ibd = input->binding;
1223
for (size_t i = 0; i < input->attributes.size(); i++) {
1224
gDesc.attrs[i] = input->attributes[i];
1225
}
1226
gDesc.vis.vertexAttributeDescriptionCount = input->visc.vertexAttributeDescriptionCount;
1227
gDesc.vis.vertexBindingDescriptionCount = input->visc.vertexBindingDescriptionCount;
1228
gDesc.vis.pVertexBindingDescriptions = &gDesc.ibd;
1229
gDesc.vis.pVertexAttributeDescriptions = gDesc.attrs;
1230
1231
gDesc.blend0 = blend->attachments[0];
1232
gDesc.cbs = blend->info;
1233
gDesc.cbs.pAttachments = &gDesc.blend0;
1234
1235
gDesc.dss = depth->info;
1236
1237
// Copy bindings from input layout.
1238
gDesc.topology = primToVK[(int)desc.prim];
1239
1240
// We treat the three stencil states as a unit in other places, so let's do that here too.
1241
const VkDynamicState dynamics[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_STENCIL_WRITE_MASK };
1242
gDesc.ds.dynamicStateCount = depth->info.stencilTestEnable ? ARRAY_SIZE(dynamics) : 2;
1243
for (size_t i = 0; i < gDesc.ds.dynamicStateCount; i++) {
1244
gDesc.dynamicStates[i] = dynamics[i];
1245
}
1246
gDesc.ds.pDynamicStates = gDesc.dynamicStates;
1247
1248
gDesc.views.viewportCount = 1;
1249
gDesc.views.scissorCount = 1;
1250
gDesc.views.pViewports = nullptr; // dynamic
1251
gDesc.views.pScissors = nullptr; // dynamic
1252
1253
gDesc.pipelineLayout = pipelineLayout_;
1254
1255
VkPipelineRasterizationStateCreateInfo rs{ VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO };
1256
raster->ToVulkan(&gDesc.rs);
1257
1258
if (renderManager_.GetVulkanContext()->GetDeviceFeatures().enabled.provokingVertex.provokingVertexLast) {
1259
ChainStruct(gDesc.rs, &gDesc.rs_provoking);
1260
gDesc.rs_provoking.provokingVertexMode = VK_PROVOKING_VERTEX_MODE_LAST_VERTEX_EXT;
1261
}
1262
1263
pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc, pipelineFlags, 1 << (size_t)RenderPassType::BACKBUFFER, VK_SAMPLE_COUNT_1_BIT, false, tag ? tag : "thin3d");
1264
1265
if (desc.uniformDesc) {
1266
pipeline->dynamicUniformSize = (int)desc.uniformDesc->uniformBufferSize;
1267
}
1268
if (depth->info.stencilTestEnable) {
1269
pipeline->usesStencil = true;
1270
}
1271
return pipeline;
1272
}
1273
1274
void VKContext::SetScissorRect(int left, int top, int width, int height) {
1275
renderManager_.SetScissor(left, top, width, height);
1276
}
1277
1278
void VKContext::SetViewport(const Viewport &viewport) {
1279
// Ignore viewports more than the first.
1280
VkViewport vkViewport;
1281
vkViewport.x = viewport.TopLeftX;
1282
vkViewport.y = viewport.TopLeftY;
1283
vkViewport.width = viewport.Width;
1284
vkViewport.height = viewport.Height;
1285
vkViewport.minDepth = viewport.MinDepth;
1286
vkViewport.maxDepth = viewport.MaxDepth;
1287
renderManager_.SetViewport(vkViewport);
1288
}
1289
1290
void VKContext::SetBlendFactor(float color[4]) {
1291
uint32_t col = Float4ToUint8x4(color);
1292
renderManager_.SetBlendFactor(col);
1293
}
1294
1295
void VKContext::SetStencilParams(uint8_t refValue, uint8_t writeMask, uint8_t compareMask) {
1296
if (curPipeline_->usesStencil)
1297
renderManager_.SetStencilParams(writeMask, compareMask, refValue);
1298
stencilRef_ = refValue;
1299
stencilWriteMask_ = writeMask;
1300
stencilCompareMask_ = compareMask;
1301
}
1302
1303
InputLayout *VKContext::CreateInputLayout(const InputLayoutDesc &desc) {
1304
VKInputLayout *vl = new VKInputLayout();
1305
vl->visc = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO };
1306
vl->visc.flags = 0;
1307
vl->visc.vertexBindingDescriptionCount = 1;
1308
vl->visc.vertexAttributeDescriptionCount = (uint32_t)desc.attributes.size();
1309
vl->attributes.resize(vl->visc.vertexAttributeDescriptionCount);
1310
vl->visc.pVertexBindingDescriptions = &vl->binding;
1311
vl->visc.pVertexAttributeDescriptions = vl->attributes.data();
1312
for (size_t i = 0; i < desc.attributes.size(); i++) {
1313
vl->attributes[i].binding = 0;
1314
vl->attributes[i].format = DataFormatToVulkan(desc.attributes[i].format);
1315
vl->attributes[i].location = desc.attributes[i].location;
1316
vl->attributes[i].offset = desc.attributes[i].offset;
1317
}
1318
vl->binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
1319
vl->binding.binding = 0;
1320
vl->binding.stride = desc.stride;
1321
return vl;
1322
}
1323
1324
Texture *VKContext::CreateTexture(const TextureDesc &desc) {
1325
VkCommandBuffer initCmd = renderManager_.GetInitCmd();
1326
if (!push_ || !initCmd) {
1327
// Too early! Fail.
1328
ERROR_LOG(Log::G3D, "Can't create textures before the first frame has started.");
1329
return nullptr;
1330
}
1331
VKTexture *tex = new VKTexture(vulkan_, initCmd, push_, desc);
1332
if (tex->Create(initCmd, &renderManager_.PostInitBarrier(), push_, desc)) {
1333
return tex;
1334
} else {
1335
ERROR_LOG(Log::G3D, "Failed to create texture");
1336
tex->Release();
1337
return nullptr;
1338
}
1339
}
1340
1341
void VKContext::UpdateTextureLevels(Texture *texture, const uint8_t **data, TextureCallback initDataCallback, int numLevels) {
1342
VkCommandBuffer initCmd = renderManager_.GetInitCmd();
1343
if (!push_ || !initCmd) {
1344
// Too early! Fail.
1345
ERROR_LOG(Log::G3D, "Can't create textures before the first frame has started.");
1346
return;
1347
}
1348
1349
VKTexture *tex = (VKTexture *)texture;
1350
1351
_dbg_assert_(numLevels <= tex->NumLevels());
1352
tex->Update(initCmd, &renderManager_.PostInitBarrier(), push_, data, initDataCallback, numLevels);
1353
}
1354
1355
static inline void CopySide(VkStencilOpState &dest, const StencilSetup &src) {
1356
dest.compareOp = compToVK[(int)src.compareOp];
1357
dest.failOp = stencilOpToVK[(int)src.failOp];
1358
dest.passOp = stencilOpToVK[(int)src.passOp];
1359
dest.depthFailOp = stencilOpToVK[(int)src.depthFailOp];
1360
}
1361
1362
DepthStencilState *VKContext::CreateDepthStencilState(const DepthStencilStateDesc &desc) {
1363
VKDepthStencilState *ds = new VKDepthStencilState();
1364
ds->info.depthCompareOp = compToVK[(int)desc.depthCompare];
1365
ds->info.depthTestEnable = desc.depthTestEnabled;
1366
ds->info.depthWriteEnable = desc.depthWriteEnabled;
1367
ds->info.stencilTestEnable = desc.stencilEnabled;
1368
ds->info.depthBoundsTestEnable = false;
1369
if (ds->info.stencilTestEnable) {
1370
CopySide(ds->info.front, desc.stencil);
1371
CopySide(ds->info.back, desc.stencil);
1372
}
1373
return ds;
1374
}
1375
1376
BlendState *VKContext::CreateBlendState(const BlendStateDesc &desc) {
1377
VKBlendState *bs = new VKBlendState();
1378
bs->info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
1379
bs->info.attachmentCount = 1;
1380
bs->info.logicOp = logicOpToVK[(int)desc.logicOp];
1381
bs->info.logicOpEnable = desc.logicEnabled;
1382
bs->attachments.resize(1);
1383
bs->attachments[0].blendEnable = desc.enabled;
1384
bs->attachments[0].colorBlendOp = blendEqToVk[(int)desc.eqCol];
1385
bs->attachments[0].alphaBlendOp = blendEqToVk[(int)desc.eqAlpha];
1386
bs->attachments[0].colorWriteMask = desc.colorMask;
1387
bs->attachments[0].dstAlphaBlendFactor = blendFactorToVk[(int)desc.dstAlpha];
1388
bs->attachments[0].dstColorBlendFactor = blendFactorToVk[(int)desc.dstCol];
1389
bs->attachments[0].srcAlphaBlendFactor = blendFactorToVk[(int)desc.srcAlpha];
1390
bs->attachments[0].srcColorBlendFactor = blendFactorToVk[(int)desc.srcCol];
1391
bs->info.pAttachments = bs->attachments.data();
1392
return bs;
1393
}
1394
1395
// Very simplistic buffer that will simply copy its contents into our "pushbuffer" when it's time to draw,
1396
// to avoid synchronization issues.
1397
class VKBuffer : public Buffer {
1398
public:
1399
VKBuffer(size_t size, uint32_t flags) : dataSize_(size) {
1400
data_ = new uint8_t[size];
1401
}
1402
~VKBuffer() {
1403
delete[] data_;
1404
}
1405
1406
size_t GetSize() const { return dataSize_; }
1407
const uint8_t *GetData() const { return data_; }
1408
1409
uint8_t *data_;
1410
size_t dataSize_;
1411
};
1412
1413
Buffer *VKContext::CreateBuffer(size_t size, uint32_t usageFlags) {
1414
return new VKBuffer(size, usageFlags);
1415
}
1416
1417
void VKContext::UpdateBuffer(Buffer *buffer, const uint8_t *data, size_t offset, size_t size, UpdateBufferFlags flags) {
1418
VKBuffer *buf = (VKBuffer *)buffer;
1419
memcpy(buf->data_ + offset, data, size);
1420
}
1421
1422
void VKContext::BindTextures(int start, int count, Texture **textures, TextureBindFlags flags) {
1423
_assert_(start + count <= MAX_BOUND_TEXTURES);
1424
for (int i = start; i < start + count; i++) {
1425
_dbg_assert_(i >= 0 && i < MAX_BOUND_TEXTURES);
1426
boundTextures_[i] = static_cast<VKTexture *>(textures[i - start]);
1427
boundTextureFlags_[i] = flags;
1428
if (boundTextures_[i]) {
1429
// If a texture is bound, we set these up in BindDescriptors too.
1430
// But we might need to set the view here anyway so it can be queried using GetNativeObject.
1431
if (flags & TextureBindFlags::VULKAN_BIND_ARRAY) {
1432
boundImageView_[i] = boundTextures_[i]->GetImageArrayView();
1433
} else {
1434
boundImageView_[i] = boundTextures_[i]->GetImageView();
1435
}
1436
} else {
1437
if (flags & TextureBindFlags::VULKAN_BIND_ARRAY) {
1438
boundImageView_[i] = GetNullTexture()->GetImageArrayView();
1439
} else {
1440
boundImageView_[i] = GetNullTexture()->GetImageView();
1441
}
1442
}
1443
}
1444
}
1445
1446
void VKContext::BindNativeTexture(int sampler, void *nativeTexture) {
1447
_dbg_assert_(sampler >= 0 && sampler < MAX_BOUND_TEXTURES);
1448
boundTextures_[sampler] = nullptr;
1449
boundImageView_[sampler] = (VkImageView)nativeTexture;
1450
}
1451
1452
ShaderModule *VKContext::CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t size, const char *tag) {
1453
VKShaderModule *shader = new VKShaderModule(stage, tag);
1454
if (shader->Compile(vulkan_, language, data, size)) {
1455
return shader;
1456
} else {
1457
ERROR_LOG(Log::G3D, "Failed to compile shader %s:\n%s", tag, (const char *)LineNumberString((const char *)data).c_str());
1458
shader->Release();
1459
return nullptr;
1460
}
1461
}
1462
1463
void VKContext::UpdateDynamicUniformBuffer(const void *ub, size_t size) {
1464
curPipeline_->SetDynamicUniformData(ub, size);
1465
}
1466
1467
void VKContext::ApplyDynamicState() {
1468
// TODO: blend constants, stencil, viewports should be here, after bindpipeline..
1469
if (curPipeline_->usesStencil) {
1470
renderManager_.SetStencilParams(stencilWriteMask_, stencilCompareMask_, stencilRef_);
1471
}
1472
}
1473
1474
void VKContext::Draw(int vertexCount, int offset) {
1475
VKBuffer *vbuf = curVBuffer_;
1476
1477
VkBuffer vulkanVbuf;
1478
VkBuffer vulkanUBObuf;
1479
uint32_t ubo_offset = (uint32_t)curPipeline_->PushUBO(push_, vulkan_, &vulkanUBObuf);
1480
size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize(), 4, &vulkanVbuf);
1481
1482
BindCurrentPipeline();
1483
ApplyDynamicState();
1484
int descSetIndex;
1485
PackedDescriptor *descriptors = renderManager_.PushDescriptorSet(4, &descSetIndex);
1486
BindDescriptors(vulkanUBObuf, descriptors);
1487
renderManager_.Draw(descSetIndex, 1, &ubo_offset, vulkanVbuf, (int)vbBindOffset + curVBufferOffset_, vertexCount, offset);
1488
}
1489
1490
void VKContext::DrawIndexed(int vertexCount, int offset) {
1491
VKBuffer *ibuf = curIBuffer_;
1492
VKBuffer *vbuf = curVBuffer_;
1493
1494
VkBuffer vulkanVbuf, vulkanIbuf, vulkanUBObuf;
1495
uint32_t ubo_offset = (uint32_t)curPipeline_->PushUBO(push_, vulkan_, &vulkanUBObuf);
1496
size_t vbBindOffset = push_->Push(vbuf->GetData(), vbuf->GetSize(), 4, &vulkanVbuf);
1497
size_t ibBindOffset = push_->Push(ibuf->GetData(), ibuf->GetSize(), 4, &vulkanIbuf);
1498
1499
BindCurrentPipeline();
1500
ApplyDynamicState();
1501
int descSetIndex;
1502
PackedDescriptor *descriptors = renderManager_.PushDescriptorSet(4, &descSetIndex);
1503
BindDescriptors(vulkanUBObuf, descriptors);
1504
renderManager_.DrawIndexed(descSetIndex, 1, &ubo_offset, vulkanVbuf, (int)vbBindOffset + curVBufferOffset_, vulkanIbuf, (int)ibBindOffset + offset * sizeof(uint32_t), vertexCount, 1);
1505
}
1506
1507
void VKContext::DrawUP(const void *vdata, int vertexCount) {
1508
_dbg_assert_(vertexCount >= 0);
1509
if (vertexCount <= 0) {
1510
return;
1511
}
1512
1513
VkBuffer vulkanVbuf, vulkanUBObuf;
1514
size_t dataSize = vertexCount * curPipeline_->stride;
1515
uint32_t vbBindOffset;
1516
uint8_t *dataPtr = push_->Allocate(dataSize, 4, &vulkanVbuf, &vbBindOffset);
1517
_assert_(dataPtr != nullptr);
1518
memcpy(dataPtr, vdata, dataSize);
1519
1520
uint32_t ubo_offset = (uint32_t)curPipeline_->PushUBO(push_, vulkan_, &vulkanUBObuf);
1521
1522
BindCurrentPipeline();
1523
ApplyDynamicState();
1524
int descSetIndex;
1525
PackedDescriptor *descriptors = renderManager_.PushDescriptorSet(4, &descSetIndex);
1526
BindDescriptors(vulkanUBObuf, descriptors);
1527
renderManager_.Draw(descSetIndex, 1, &ubo_offset, vulkanVbuf, (int)vbBindOffset + curVBufferOffset_, vertexCount);
1528
}
1529
1530
void VKContext::BindCurrentPipeline() {
1531
renderManager_.BindPipeline(curPipeline_->pipeline, curPipeline_->flags, pipelineLayout_);
1532
}
1533
1534
void VKContext::Clear(int clearMask, uint32_t colorval, float depthVal, int stencilVal) {
1535
int mask = 0;
1536
if (clearMask & FBChannel::FB_COLOR_BIT)
1537
mask |= VK_IMAGE_ASPECT_COLOR_BIT;
1538
if (clearMask & FBChannel::FB_DEPTH_BIT)
1539
mask |= VK_IMAGE_ASPECT_DEPTH_BIT;
1540
if (clearMask & FBChannel::FB_STENCIL_BIT)
1541
mask |= VK_IMAGE_ASPECT_STENCIL_BIT;
1542
renderManager_.Clear(colorval, depthVal, stencilVal, mask);
1543
}
1544
1545
DrawContext *T3DCreateVulkanContext(VulkanContext *vulkan, bool useRenderThread) {
1546
return new VKContext(vulkan, useRenderThread);
1547
}
1548
1549
void AddFeature(std::vector<std::string> &features, const char *name, VkBool32 available, VkBool32 enabled) {
1550
char buf[512];
1551
snprintf(buf, sizeof(buf), "%s: Available: %d Enabled: %d", name, (int)available, (int)enabled);
1552
features.push_back(buf);
1553
}
1554
1555
std::vector<std::string> VKContext::GetFeatureList() const {
1556
const VkPhysicalDeviceFeatures &available = vulkan_->GetDeviceFeatures().available.standard;
1557
const VkPhysicalDeviceFeatures &enabled = vulkan_->GetDeviceFeatures().enabled.standard;
1558
1559
std::vector<std::string> features;
1560
AddFeature(features, "dualSrcBlend", available.dualSrcBlend, enabled.dualSrcBlend);
1561
AddFeature(features, "logicOp", available.logicOp, enabled.logicOp);
1562
AddFeature(features, "geometryShader", available.geometryShader, enabled.geometryShader);
1563
AddFeature(features, "depthBounds", available.depthBounds, enabled.depthBounds);
1564
AddFeature(features, "depthClamp", available.depthClamp, enabled.depthClamp);
1565
AddFeature(features, "pipelineStatisticsQuery", available.pipelineStatisticsQuery, enabled.pipelineStatisticsQuery);
1566
AddFeature(features, "samplerAnisotropy", available.samplerAnisotropy, enabled.samplerAnisotropy);
1567
AddFeature(features, "textureCompressionBC", available.textureCompressionBC, enabled.textureCompressionBC);
1568
AddFeature(features, "textureCompressionETC2", available.textureCompressionETC2, enabled.textureCompressionETC2);
1569
AddFeature(features, "textureCompressionASTC_LDR", available.textureCompressionASTC_LDR, enabled.textureCompressionASTC_LDR);
1570
AddFeature(features, "shaderClipDistance", available.shaderClipDistance, enabled.shaderClipDistance);
1571
AddFeature(features, "shaderCullDistance", available.shaderCullDistance, enabled.shaderCullDistance);
1572
AddFeature(features, "occlusionQueryPrecise", available.occlusionQueryPrecise, enabled.occlusionQueryPrecise);
1573
AddFeature(features, "multiDrawIndirect", available.multiDrawIndirect, enabled.multiDrawIndirect);
1574
AddFeature(features, "robustBufferAccess", available.robustBufferAccess, enabled.robustBufferAccess);
1575
AddFeature(features, "fullDrawIndexUint32", available.fullDrawIndexUint32, enabled.fullDrawIndexUint32);
1576
AddFeature(features, "fragmentStoresAndAtomics", available.fragmentStoresAndAtomics, enabled.fragmentStoresAndAtomics);
1577
AddFeature(features, "shaderInt16", available.shaderInt16, enabled.shaderInt16);
1578
1579
AddFeature(features, "multiview", vulkan_->GetDeviceFeatures().available.multiview.multiview, vulkan_->GetDeviceFeatures().enabled.multiview.multiview);
1580
AddFeature(features, "multiviewGeometryShader", vulkan_->GetDeviceFeatures().available.multiview.multiviewGeometryShader, vulkan_->GetDeviceFeatures().enabled.multiview.multiviewGeometryShader);
1581
AddFeature(features, "presentId", vulkan_->GetDeviceFeatures().available.presentId.presentId, vulkan_->GetDeviceFeatures().enabled.presentId.presentId);
1582
AddFeature(features, "presentWait", vulkan_->GetDeviceFeatures().available.presentWait.presentWait, vulkan_->GetDeviceFeatures().enabled.presentWait.presentWait);
1583
AddFeature(features, "provokingVertexLast", vulkan_->GetDeviceFeatures().available.provokingVertex.provokingVertexLast, vulkan_->GetDeviceFeatures().enabled.provokingVertex.provokingVertexLast);
1584
1585
features.emplace_back(std::string("Preferred depth buffer format: ") + VulkanFormatToString(vulkan_->GetDeviceInfo().preferredDepthStencilFormat));
1586
1587
return features;
1588
}
1589
1590
std::vector<std::string> VKContext::GetExtensionList(bool device, bool enabledOnly) const {
1591
std::vector<std::string> extensions;
1592
if (enabledOnly) {
1593
const auto& enabled = (device ? vulkan_->GetDeviceExtensionsEnabled() : vulkan_->GetInstanceExtensionsEnabled());
1594
extensions.reserve(enabled.size());
1595
for (auto &iter : enabled) {
1596
extensions.push_back(iter);
1597
}
1598
} else {
1599
const auto& available = (device ? vulkan_->GetDeviceExtensionsAvailable() : vulkan_->GetInstanceExtensionsAvailable());
1600
extensions.reserve(available.size());
1601
for (auto &iter : available) {
1602
extensions.push_back(iter.extensionName);
1603
}
1604
}
1605
return extensions;
1606
}
1607
1608
uint32_t VKContext::GetDataFormatSupport(DataFormat fmt) const {
1609
VkFormat vulkan_format = DataFormatToVulkan(fmt);
1610
VkFormatProperties properties;
1611
vkGetPhysicalDeviceFormatProperties(vulkan_->GetCurrentPhysicalDevice(), vulkan_format, &properties);
1612
uint32_t flags = 0;
1613
if (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) {
1614
flags |= FMT_RENDERTARGET;
1615
}
1616
if (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {
1617
flags |= FMT_DEPTHSTENCIL;
1618
}
1619
if (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) {
1620
flags |= FMT_TEXTURE;
1621
}
1622
if (properties.bufferFeatures & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) {
1623
flags |= FMT_INPUTLAYOUT;
1624
}
1625
if ((properties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT) && (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT)) {
1626
flags |= FMT_BLIT;
1627
}
1628
if (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) {
1629
flags |= FMT_STORAGE_IMAGE;
1630
}
1631
return flags;
1632
}
1633
1634
// A VKFramebuffer is a VkFramebuffer (note caps difference) plus all the textures it owns.
1635
// It also has a reference to the command buffer that it was last rendered to with.
1636
// If it needs to be transitioned, and the frame number matches, use it, otherwise
1637
// use this frame's init command buffer.
1638
class VKFramebuffer : public Framebuffer {
1639
public:
1640
VKFramebuffer(VKRFramebuffer *fb, int multiSampleLevel) : buf_(fb) {
1641
_assert_msg_(fb, "Null fb in VKFramebuffer constructor");
1642
width_ = fb->width;
1643
height_ = fb->height;
1644
layers_ = fb->numLayers;
1645
multiSampleLevel_ = multiSampleLevel;
1646
}
1647
~VKFramebuffer() {
1648
_assert_msg_(buf_, "Null buf_ in VKFramebuffer - double delete?");
1649
buf_->Vulkan()->Delete().QueueCallback([](VulkanContext *vulkan, void *fb) {
1650
VKRFramebuffer *vfb = static_cast<VKRFramebuffer *>(fb);
1651
delete vfb;
1652
}, buf_);
1653
buf_ = nullptr;
1654
}
1655
VKRFramebuffer *GetFB() const { return buf_; }
1656
void UpdateTag(const char *newTag) override {
1657
buf_->UpdateTag(newTag);
1658
}
1659
private:
1660
VKRFramebuffer *buf_;
1661
};
1662
1663
Framebuffer *VKContext::CreateFramebuffer(const FramebufferDesc &desc) {
1664
_assert_(desc.multiSampleLevel >= 0);
1665
_assert_(desc.numLayers > 0);
1666
_assert_(desc.width > 0);
1667
_assert_(desc.height > 0);
1668
1669
VkCommandBuffer cmd = renderManager_.GetInitCmd();
1670
VKRFramebuffer *vkrfb = new VKRFramebuffer(vulkan_, &renderManager_.PostInitBarrier(), cmd, renderManager_.GetQueueRunner()->GetCompatibleRenderPass(), desc.width, desc.height, desc.numLayers, desc.multiSampleLevel, desc.z_stencil, desc.tag);
1671
return new VKFramebuffer(vkrfb, desc.multiSampleLevel);
1672
}
1673
1674
void VKContext::CopyFramebufferImage(Framebuffer *srcfb, int level, int x, int y, int z, Framebuffer *dstfb, int dstLevel, int dstX, int dstY, int dstZ, int width, int height, int depth, int channelBits, const char *tag) {
1675
VKFramebuffer *src = (VKFramebuffer *)srcfb;
1676
VKFramebuffer *dst = (VKFramebuffer *)dstfb;
1677
1678
int aspectMask = 0;
1679
if (channelBits & FBChannel::FB_COLOR_BIT) aspectMask |= VK_IMAGE_ASPECT_COLOR_BIT;
1680
if (channelBits & FBChannel::FB_DEPTH_BIT) aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
1681
if (channelBits & FBChannel::FB_STENCIL_BIT) aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
1682
1683
renderManager_.CopyFramebuffer(src->GetFB(), VkRect2D{ {x, y}, {(uint32_t)width, (uint32_t)height } }, dst->GetFB(), VkOffset2D{ dstX, dstY }, aspectMask, tag);
1684
}
1685
1686
bool VKContext::BlitFramebuffer(Framebuffer *srcfb, int srcX1, int srcY1, int srcX2, int srcY2, Framebuffer *dstfb, int dstX1, int dstY1, int dstX2, int dstY2, int channelBits, FBBlitFilter filter, const char *tag) {
1687
VKFramebuffer *src = (VKFramebuffer *)srcfb;
1688
VKFramebuffer *dst = (VKFramebuffer *)dstfb;
1689
1690
int aspectMask = 0;
1691
if (channelBits & FBChannel::FB_COLOR_BIT) aspectMask |= VK_IMAGE_ASPECT_COLOR_BIT;
1692
if (channelBits & FBChannel::FB_DEPTH_BIT) aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
1693
if (channelBits & FBChannel::FB_STENCIL_BIT) aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
1694
1695
renderManager_.BlitFramebuffer(src->GetFB(), VkRect2D{ {srcX1, srcY1}, {(uint32_t)(srcX2 - srcX1), (uint32_t)(srcY2 - srcY1) } }, dst->GetFB(), VkRect2D{ {dstX1, dstY1}, {(uint32_t)(dstX2 - dstX1), (uint32_t)(dstY2 - dstY1) } }, aspectMask, filter == FB_BLIT_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST, tag);
1696
return true;
1697
}
1698
1699
bool VKContext::CopyFramebufferToMemory(Framebuffer *srcfb, int channelBits, int x, int y, int w, int h, Draw::DataFormat format, void *pixels, int pixelStride, ReadbackMode mode, const char *tag) {
1700
VKFramebuffer *src = (VKFramebuffer *)srcfb;
1701
1702
int aspectMask = 0;
1703
if (channelBits & FBChannel::FB_COLOR_BIT) aspectMask |= VK_IMAGE_ASPECT_COLOR_BIT;
1704
if (channelBits & FBChannel::FB_DEPTH_BIT) aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
1705
if (channelBits & FBChannel::FB_STENCIL_BIT) aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
1706
1707
return renderManager_.CopyFramebufferToMemory(src ? src->GetFB() : nullptr, aspectMask, x, y, w, h, format, (uint8_t *)pixels, pixelStride, mode, tag);
1708
}
1709
1710
DataFormat VKContext::PreferredFramebufferReadbackFormat(Framebuffer *src) {
1711
if (src) {
1712
return DrawContext::PreferredFramebufferReadbackFormat(src);
1713
}
1714
1715
if (vulkan_->GetSwapchainFormat() == VK_FORMAT_B8G8R8A8_UNORM) {
1716
return Draw::DataFormat::B8G8R8A8_UNORM;
1717
}
1718
return DrawContext::PreferredFramebufferReadbackFormat(src);
1719
}
1720
1721
void VKContext::BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPassInfo &rp, const char *tag) {
1722
VKFramebuffer *fb = (VKFramebuffer *)fbo;
1723
VKRRenderPassLoadAction color = (VKRRenderPassLoadAction)rp.color;
1724
VKRRenderPassLoadAction depth = (VKRRenderPassLoadAction)rp.depth;
1725
VKRRenderPassLoadAction stencil = (VKRRenderPassLoadAction)rp.stencil;
1726
1727
renderManager_.BindFramebufferAsRenderTarget(fb ? fb->GetFB() : nullptr, color, depth, stencil, rp.clearColor, rp.clearDepth, rp.clearStencil, tag);
1728
curFramebuffer_ = fb;
1729
}
1730
1731
void VKContext::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) {
1732
VKFramebuffer *fb = (VKFramebuffer *)fbo;
1733
_assert_(binding >= 0 && binding < MAX_BOUND_TEXTURES);
1734
1735
// TODO: There are cases where this is okay, actually. But requires layout transitions and stuff -
1736
// we're not ready for this.
1737
_assert_(fb != curFramebuffer_);
1738
1739
int aspect = 0;
1740
switch (channelBit) {
1741
case FBChannel::FB_COLOR_BIT:
1742
aspect = VK_IMAGE_ASPECT_COLOR_BIT;
1743
break;
1744
case FBChannel::FB_DEPTH_BIT:
1745
aspect = VK_IMAGE_ASPECT_DEPTH_BIT;
1746
break;
1747
default:
1748
_assert_(false);
1749
break;
1750
}
1751
1752
boundTextures_[binding].reset(nullptr);
1753
boundImageView_[binding] = renderManager_.BindFramebufferAsTexture(fb->GetFB(), binding, aspect, layer);
1754
}
1755
1756
void VKContext::GetFramebufferDimensions(Framebuffer *fbo, int *w, int *h) {
1757
VKFramebuffer *fb = (VKFramebuffer *)fbo;
1758
if (fb) {
1759
*w = fb->GetFB()->width;
1760
*h = fb->GetFB()->height;
1761
} else {
1762
*w = vulkan_->GetBackbufferWidth();
1763
*h = vulkan_->GetBackbufferHeight();
1764
}
1765
}
1766
1767
void VKContext::HandleEvent(Event ev, int width, int height, void *param1, void *param2) {
1768
switch (ev) {
1769
case Event::LOST_BACKBUFFER:
1770
renderManager_.DestroyBackbuffers();
1771
break;
1772
case Event::GOT_BACKBUFFER:
1773
renderManager_.CreateBackbuffers();
1774
break;
1775
default:
1776
_assert_(false);
1777
break;
1778
}
1779
}
1780
1781
void VKContext::InvalidateFramebuffer(FBInvalidationStage stage, uint32_t channels) {
1782
VkImageAspectFlags flags = 0;
1783
if (channels & FBChannel::FB_COLOR_BIT)
1784
flags |= VK_IMAGE_ASPECT_COLOR_BIT;
1785
if (channels & FBChannel::FB_DEPTH_BIT)
1786
flags |= VK_IMAGE_ASPECT_DEPTH_BIT;
1787
if (channels & FBChannel::FB_STENCIL_BIT)
1788
flags |= VK_IMAGE_ASPECT_STENCIL_BIT;
1789
if (stage == FB_INVALIDATION_LOAD) {
1790
renderManager_.SetLoadDontCare(flags);
1791
} else if (stage == FB_INVALIDATION_STORE) {
1792
renderManager_.SetStoreDontCare(flags);
1793
}
1794
}
1795
1796
uint64_t VKContext::GetNativeObject(NativeObject obj, void *srcObject) {
1797
switch (obj) {
1798
case NativeObject::CONTEXT:
1799
return (uint64_t)vulkan_;
1800
case NativeObject::INIT_COMMANDBUFFER:
1801
return (uint64_t)renderManager_.GetInitCmd();
1802
case NativeObject::BOUND_TEXTURE0_IMAGEVIEW:
1803
return (uint64_t)boundImageView_[0];
1804
case NativeObject::BOUND_TEXTURE1_IMAGEVIEW:
1805
return (uint64_t)boundImageView_[1];
1806
case NativeObject::RENDER_MANAGER:
1807
return (uint64_t)(uintptr_t)&renderManager_;
1808
case NativeObject::NULL_IMAGEVIEW:
1809
return (uint64_t)GetNullTexture()->GetImageView();
1810
case NativeObject::NULL_IMAGEVIEW_ARRAY:
1811
return (uint64_t)GetNullTexture()->GetImageArrayView();
1812
case NativeObject::TEXTURE_VIEW:
1813
return (uint64_t)(((VKTexture *)srcObject)->GetImageView());
1814
case NativeObject::BOUND_FRAMEBUFFER_COLOR_IMAGEVIEW_ALL_LAYERS:
1815
return (uint64_t)curFramebuffer_->GetFB()->color.texAllLayersView;
1816
case NativeObject::BOUND_FRAMEBUFFER_COLOR_IMAGEVIEW_RT:
1817
return (uint64_t)curFramebuffer_->GetFB()->GetRTView();
1818
case NativeObject::THIN3D_PIPELINE_LAYOUT:
1819
return (uint64_t)pipelineLayout_;
1820
case NativeObject::PUSH_POOL:
1821
return (uint64_t)push_;
1822
default:
1823
Crash();
1824
return 0;
1825
}
1826
}
1827
1828
void VKContext::DebugAnnotate(const char *annotation) {
1829
renderManager_.DebugAnnotate(annotation);
1830
}
1831
1832
} // namespace Draw
1833
1834