| 1 |
// Copyright 2022 Dolphin Emulator Project |
| 2 |
// SPDX-License-Identifier: GPL-2.0-or-later |
| 3 |
|
| 4 |
#include "VideoBackends/Metal/MTLObjectCache.h" |
| 5 |
|
| 6 |
#include <map> |
| 7 |
#include <mutex> |
| 8 |
#include <optional> |
| 9 |
|
| 10 |
#include "Common/Assert.h" |
| 11 |
#include "Common/MsgHandler.h" |
| 12 |
|
| 13 |
#include "VideoBackends/Metal/MTLPipeline.h" |
| 14 |
#include "VideoBackends/Metal/MTLUtil.h" |
| 15 |
#include "VideoBackends/Metal/MTLVertexFormat.h" |
| 16 |
|
| 17 |
#include "VideoCommon/AbstractPipeline.h" |
| 18 |
#include "VideoCommon/NativeVertexFormat.h" |
| 19 |
#include "VideoCommon/VertexShaderGen.h" |
| 20 |
#include "VideoCommon/VideoBackendBase.h" |
| 21 |
#include "VideoCommon/VideoConfig.h" |
| 22 |
|
| 23 |
MRCOwned<id<MTLDevice>> Metal::g_device; |
| 24 |
MRCOwned<id<MTLCommandQueue>> Metal::g_queue; |
| 25 |
std::unique_ptr<Metal::ObjectCache> Metal::g_object_cache; |
| 26 |
|
| 27 |
static void SetupDepthStencil( |
| 28 |
MRCOwned<id<MTLDepthStencilState>> (&dss)[Metal::DepthStencilSelector::N_VALUES]); |
| 29 |
|
| 30 |
void Metal::ObjectCache::Initialize(MRCOwned<id<MTLDevice>> device) |
| 31 |
{ |
| 32 |
g_device = std::move(device); |
| 33 |
g_queue = MRCTransfer([g_device newCommandQueue]); |
| 34 |
g_object_cache = std::unique_ptr<ObjectCache>(new ObjectCache); |
| 35 |
} |
| 36 |
|
| 37 |
void Metal::ObjectCache::Shutdown() |
| 38 |
{ |
| 39 |
g_object_cache.reset(); |
| 40 |
g_queue = nullptr; |
| 41 |
g_device = nullptr; |
| 42 |
} |
| 43 |
|
| 44 |
// MARK: Depth Stencil State |
| 45 |
|
| 46 |
// clang-format off |
| 47 |
|
| 48 |
static MTLCompareFunction Convert(CompareMode mode) |
| 49 |
{ |
| 50 |
const bool invert_depth = !g_backend_info.bSupportsReversedDepthRange; |
| 51 |
switch (mode) |
| 52 |
{ |
| 53 |
case CompareMode::Never: return MTLCompareFunctionNever; |
| 54 |
case CompareMode::Less: return invert_depth ? MTLCompareFunctionGreater |
| 55 |
: MTLCompareFunctionLess; |
| 56 |
case CompareMode::Equal: return MTLCompareFunctionEqual; |
| 57 |
case CompareMode::LEqual: return invert_depth ? MTLCompareFunctionGreaterEqual |
| 58 |
: MTLCompareFunctionLessEqual; |
| 59 |
case CompareMode::Greater: return invert_depth ? MTLCompareFunctionLess |
| 60 |
: MTLCompareFunctionGreater; |
| 61 |
case CompareMode::NEqual: return MTLCompareFunctionNotEqual; |
| 62 |
case CompareMode::GEqual: return invert_depth ? MTLCompareFunctionLessEqual |
| 63 |
: MTLCompareFunctionGreaterEqual; |
| 64 |
case CompareMode::Always: return MTLCompareFunctionAlways; |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
static const char* to_string(MTLCompareFunction compare) |
| 69 |
{ |
| 70 |
switch (compare) |
| 71 |
{ |
| 72 |
case MTLCompareFunctionNever: return "Never"; |
| 73 |
case MTLCompareFunctionGreater: return "Greater"; |
| 74 |
case MTLCompareFunctionEqual: return "Equal"; |
| 75 |
case MTLCompareFunctionGreaterEqual: return "GEqual"; |
| 76 |
case MTLCompareFunctionLess: return "Less"; |
| 77 |
case MTLCompareFunctionNotEqual: return "NEqual"; |
| 78 |
case MTLCompareFunctionLessEqual: return "LEqual"; |
| 79 |
case MTLCompareFunctionAlways: return "Always"; |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
// clang-format on |
| 84 |
|
| 85 |
static void |
| 86 |
SetupDepthStencil(MRCOwned<id<MTLDepthStencilState>> (&dss)[Metal::DepthStencilSelector::N_VALUES]) |
| 87 |
{ |
| 88 |
auto desc = MRCTransfer([MTLDepthStencilDescriptor new]); |
| 89 |
Metal::DepthStencilSelector sel; |
| 90 |
for (size_t i = 0; i < std::size(dss); ++i) |
| 91 |
{ |
| 92 |
sel.value = i; |
| 93 |
MTLCompareFunction mcompare = Convert(sel.CompareMode()); |
| 94 |
[desc setDepthWriteEnabled:sel.UpdateEnable()]; |
| 95 |
[desc setDepthCompareFunction:mcompare]; |
| 96 |
[desc setLabel:[NSString stringWithFormat:@"DSS %s%s", to_string(mcompare), |
| 97 |
sel.UpdateEnable() ? "+Write" : ""]]; |
| 98 |
dss[i] = MRCTransfer([Metal::g_device newDepthStencilStateWithDescriptor:desc]); |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
// MARK: Samplers |
| 103 |
|
| 104 |
// clang-format off |
| 105 |
|
| 106 |
static MTLSamplerMinMagFilter ConvertMinMag(FilterMode filter) |
| 107 |
{ |
| 108 |
switch (filter) |
| 109 |
{ |
| 110 |
case FilterMode::Linear: return MTLSamplerMinMagFilterLinear; |
| 111 |
case FilterMode::Near: return MTLSamplerMinMagFilterNearest; |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
static MTLSamplerMipFilter ConvertMip(FilterMode filter) |
| 116 |
{ |
| 117 |
switch (filter) |
| 118 |
{ |
| 119 |
case FilterMode::Linear: return MTLSamplerMipFilterLinear; |
| 120 |
case FilterMode::Near: return MTLSamplerMipFilterNearest; |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
static MTLSamplerAddressMode Convert(WrapMode wrap) |
| 125 |
{ |
| 126 |
switch (wrap) |
| 127 |
{ |
| 128 |
case WrapMode::Clamp: return MTLSamplerAddressModeClampToEdge; |
| 129 |
case WrapMode::Mirror: return MTLSamplerAddressModeMirrorRepeat; |
| 130 |
case WrapMode::Repeat: return MTLSamplerAddressModeRepeat; |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
static const char* to_string(FilterMode filter) |
| 135 |
{ |
| 136 |
switch (filter) |
| 137 |
{ |
| 138 |
case FilterMode::Linear: return "Ln"; |
| 139 |
case FilterMode::Near: return "Pt"; |
| 140 |
} |
| 141 |
} |
| 142 |
static const char* to_string(WrapMode wrap) |
| 143 |
{ |
| 144 |
switch (wrap) |
| 145 |
{ |
| 146 |
case WrapMode::Clamp: return "C"; |
| 147 |
case WrapMode::Mirror: return "M"; |
| 148 |
case WrapMode::Repeat: return "R"; |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
// clang-format on |
| 153 |
|
| 154 |
MRCOwned<id<MTLSamplerState>> Metal::ObjectCache::CreateSampler(SamplerSelector sel) |
| 155 |
{ |
| 156 |
@autoreleasepool |
| 157 |
{ |
| 158 |
auto desc = MRCTransfer([MTLSamplerDescriptor new]); |
| 159 |
[desc setMinFilter:ConvertMinMag(sel.MinFilter())]; |
| 160 |
[desc setMagFilter:ConvertMinMag(sel.MagFilter())]; |
| 161 |
[desc setMipFilter:ConvertMip(sel.MipFilter())]; |
| 162 |
[desc setSAddressMode:Convert(sel.WrapU())]; |
| 163 |
[desc setTAddressMode:Convert(sel.WrapV())]; |
| 164 |
[desc setMaxAnisotropy:1 << sel.AnisotropicFiltering()]; |
| 165 |
[desc setLabel:MRCTransfer([[NSString alloc] |
| 166 |
initWithFormat:@"%s%s%s %s%s%d", to_string(sel.MinFilter()), |
| 167 |
to_string(sel.MagFilter()), to_string(sel.MipFilter()), |
| 168 |
to_string(sel.WrapU()), to_string(sel.WrapV()), |
| 169 |
1 << sel.AnisotropicFiltering()])]; |
| 170 |
return MRCTransfer([Metal::g_device newSamplerStateWithDescriptor:desc]); |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
void Metal::ObjectCache::ReloadSamplers() |
| 175 |
{ |
| 176 |
for (auto& sampler : m_samplers) |
| 177 |
sampler = nullptr; |
| 178 |
} |
| 179 |
|
| 180 |
// MARK: Pipelines |
| 181 |
|
| 182 |
static MTLPrimitiveTopologyClass GetClass(PrimitiveType prim) |
| 183 |
{ |
| 184 |
switch (prim) |
| 185 |
{ |
| 186 |
case PrimitiveType::Points: |
| 187 |
return MTLPrimitiveTopologyClassPoint; |
| 188 |
case PrimitiveType::Lines: |
| 189 |
return MTLPrimitiveTopologyClassLine; |
| 190 |
case PrimitiveType::Triangles: |
| 191 |
case PrimitiveType::TriangleStrip: |
| 192 |
return MTLPrimitiveTopologyClassTriangle; |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
static MTLPrimitiveType Convert(PrimitiveType prim) |
| 197 |
{ |
| 198 |
// clang-format off |
| 199 |
switch (prim) |
| 200 |
{ |
| 201 |
case PrimitiveType::Points: return MTLPrimitiveTypePoint; |
| 202 |
case PrimitiveType::Lines: return MTLPrimitiveTypeLine; |
| 203 |
case PrimitiveType::Triangles: return MTLPrimitiveTypeTriangle; |
| 204 |
case PrimitiveType::TriangleStrip: return MTLPrimitiveTypeTriangleStrip; |
| 205 |
} |
| 206 |
// clang-format on |
| 207 |
} |
| 208 |
|
| 209 |
static MTLCullMode Convert(CullMode cull) |
| 210 |
{ |
| 211 |
switch (cull) |
| 212 |
{ |
| 213 |
case CullMode::None: |
| 214 |
case CullMode::All: // Handled by VertexLoaderManager::RunVertices |
| 215 |
return MTLCullModeNone; |
| 216 |
case CullMode::Front: |
| 217 |
return MTLCullModeFront; |
| 218 |
case CullMode::Back: |
| 219 |
return MTLCullModeBack; |
| 220 |
} |
| 221 |
} |
| 222 |
|
| 223 |
static MTLBlendFactor Convert(DstBlendFactor factor, bool use_dual_src) |
| 224 |
{ |
| 225 |
// clang-format off |
| 226 |
switch (factor) |
| 227 |
{ |
| 228 |
case DstBlendFactor::Zero: return MTLBlendFactorZero; |
| 229 |
case DstBlendFactor::One: return MTLBlendFactorOne; |
| 230 |
case DstBlendFactor::SrcClr: return MTLBlendFactorSourceColor; |
| 231 |
case DstBlendFactor::InvSrcClr: return MTLBlendFactorOneMinusSourceColor; |
| 232 |
case DstBlendFactor::SrcAlpha: return use_dual_src ? MTLBlendFactorSource1Alpha |
| 233 |
: MTLBlendFactorSourceAlpha; |
| 234 |
case DstBlendFactor::InvSrcAlpha: return use_dual_src ? MTLBlendFactorOneMinusSource1Alpha |
| 235 |
: MTLBlendFactorOneMinusSourceAlpha; |
| 236 |
case DstBlendFactor::DstAlpha: return MTLBlendFactorDestinationAlpha; |
| 237 |
case DstBlendFactor::InvDstAlpha: return MTLBlendFactorOneMinusDestinationAlpha; |
| 238 |
} |
| 239 |
// clang-format on |
| 240 |
} |
| 241 |
|
| 242 |
static MTLBlendFactor Convert(SrcBlendFactor factor, bool use_dual_src) |
| 243 |
{ |
| 244 |
// clang-format off |
| 245 |
switch (factor) |
| 246 |
{ |
| 247 |
case SrcBlendFactor::Zero: return MTLBlendFactorZero; |
| 248 |
case SrcBlendFactor::One: return MTLBlendFactorOne; |
| 249 |
case SrcBlendFactor::DstClr: return MTLBlendFactorDestinationColor; |
| 250 |
case SrcBlendFactor::InvDstClr: return MTLBlendFactorOneMinusDestinationColor; |
| 251 |
case SrcBlendFactor::SrcAlpha: return use_dual_src ? MTLBlendFactorSource1Alpha |
| 252 |
: MTLBlendFactorSourceAlpha; |
| 253 |
case SrcBlendFactor::InvSrcAlpha: return use_dual_src ? MTLBlendFactorOneMinusSource1Alpha |
| 254 |
: MTLBlendFactorOneMinusSourceAlpha; |
| 255 |
case SrcBlendFactor::DstAlpha: return MTLBlendFactorDestinationAlpha; |
| 256 |
case SrcBlendFactor::InvDstAlpha: return MTLBlendFactorOneMinusDestinationAlpha; |
| 257 |
} |
| 258 |
// clang-format on |
| 259 |
} |
| 260 |
|
| 261 |
class Metal::ObjectCache::Internal |
| 262 |
{ |
| 263 |
public: |
| 264 |
using StoredPipeline = std::pair<MRCOwned<id<MTLRenderPipelineState>>, PipelineReflection>; |
| 265 |
/// Holds only the things that are actually used in a Metal pipeline |
| 266 |
struct PipelineID |
| 267 |
{ |
| 268 |
struct VertexAttribute |
| 269 |
{ |
| 270 |
// Just hold the things that might differ while using the same shader |
| 271 |
// (Really only a thing for ubershaders) |
| 272 |
u8 offset : 6; |
| 273 |
u8 components : 2; |
| 274 |
VertexAttribute() = default; |
| 275 |
explicit VertexAttribute(AttributeFormat format) |
| 276 |
: offset(format.offset), components(format.components - 1) |
| 277 |
{ |
| 278 |
if (!format.enable) |
| 279 |
offset = 0x3F; // Set it to something unlikely |
| 280 |
} |
| 281 |
}; |
| 282 |
template <size_t N> |
| 283 |
static void CopyAll(std::array<VertexAttribute, N>& output, |
| 284 |
const std::array<AttributeFormat, N>& input) |
| 285 |
{ |
| 286 |
for (size_t i = 0; i < N; ++i) |
| 287 |
output[i] = VertexAttribute(input[i]); |
| 288 |
} |
| 289 |
PipelineID(const AbstractPipelineConfig& cfg) |
| 290 |
{ |
| 291 |
memset(this, 0, sizeof(*this)); |
| 292 |
if (const NativeVertexFormat* v = cfg.vertex_format) |
| 293 |
{ |
| 294 |
const PortableVertexDeclaration& decl = v->GetVertexDeclaration(); |
| 295 |
v_stride = v->GetVertexStride(); |
| 296 |
v_position = VertexAttribute(decl.position); |
| 297 |
CopyAll(v_normals, decl.normals); |
| 298 |
CopyAll(v_colors, decl.colors); |
| 299 |
CopyAll(v_texcoords, decl.texcoords); |
| 300 |
v_posmtx = VertexAttribute(decl.posmtx); |
| 301 |
} |
| 302 |
vertex_shader = static_cast<const Shader*>(cfg.vertex_shader); |
| 303 |
fragment_shader = static_cast<const Shader*>(cfg.pixel_shader); |
| 304 |
framebuffer.color_texture_format = cfg.framebuffer_state.color_texture_format.Value(); |
| 305 |
framebuffer.depth_texture_format = cfg.framebuffer_state.depth_texture_format.Value(); |
| 306 |
framebuffer.samples = cfg.framebuffer_state.samples.Value(); |
| 307 |
framebuffer.additional_color_attachment_count = |
| 308 |
cfg.framebuffer_state.additional_color_attachment_count.Value(); |
| 309 |
blend.color_update = cfg.blending_state.color_update.Value(); |
| 310 |
blend.alpha_update = cfg.blending_state.alpha_update.Value(); |
| 311 |
if (cfg.blending_state.blend_enable) |
| 312 |
{ |
| 313 |
// clang-format off |
| 314 |
blend.blend_enable = true; |
| 315 |
blend.use_dual_src = cfg.blending_state.use_dual_src.Value(); |
| 316 |
blend.src_factor = cfg.blending_state.src_factor.Value(); |
| 317 |
blend.dst_factor = cfg.blending_state.dst_factor.Value(); |
| 318 |
blend.src_factor_alpha = cfg.blending_state.src_factor_alpha.Value(); |
| 319 |
blend.dst_factor_alpha = cfg.blending_state.dst_factor_alpha.Value(); |
| 320 |
blend.subtract = cfg.blending_state.subtract.Value(); |
| 321 |
blend.subtract_alpha = cfg.blending_state.subtract_alpha.Value(); |
| 322 |
// clang-format on |
| 323 |
} |
| 324 |
|
| 325 |
if (cfg.usage != AbstractPipelineUsage::GXUber) |
| 326 |
{ |
| 327 |
if (cfg.rasterization_state.primitive == PrimitiveType::Points) |
| 328 |
is_points = true; |
| 329 |
else if (cfg.rasterization_state.primitive == PrimitiveType::Lines) |
| 330 |
is_lines = true; |
| 331 |
} |
| 332 |
} |
| 333 |
PipelineID() { memset(this, 0, sizeof(*this)); } |
| 334 |
PipelineID(const PipelineID& other) { memcpy(this, &other, sizeof(*this)); } |
| 335 |
PipelineID& operator=(const PipelineID& other) |
| 336 |
{ |
| 337 |
memcpy(this, &other, sizeof(*this)); |
| 338 |
return *this; |
| 339 |
} |
| 340 |
bool operator<(const PipelineID& other) const |
| 341 |
{ |
| 342 |
return memcmp(this, &other, sizeof(*this)) < 0; |
| 343 |
} |
| 344 |
bool operator==(const PipelineID& other) const |
| 345 |
{ |
| 346 |
return memcmp(this, &other, sizeof(*this)) == 0; |
| 347 |
} |
| 348 |
|
| 349 |
u8 v_stride; |
| 350 |
VertexAttribute v_position; |
| 351 |
std::array<VertexAttribute, 3> v_normals; |
| 352 |
std::array<VertexAttribute, 2> v_colors; |
| 353 |
std::array<VertexAttribute, 8> v_texcoords; |
| 354 |
VertexAttribute v_posmtx; |
| 355 |
const Shader* vertex_shader; |
| 356 |
const Shader* fragment_shader; |
| 357 |
union |
| 358 |
{ |
| 359 |
BlendingState blend; |
| 360 |
// Throw extras in bits we don't otherwise use |
| 361 |
BitField<30, 1, bool, u32> is_points; |
| 362 |
BitField<31, 1, bool, u32> is_lines; |
| 363 |
}; |
| 364 |
FramebufferState framebuffer; |
| 365 |
}; |
| 366 |
|
| 367 |
std::mutex m_mtx; |
| 368 |
std::condition_variable m_cv; |
| 369 |
std::map<PipelineID, StoredPipeline> m_pipelines; |
| 370 |
std::map<const Shader*, std::vector<PipelineID>> m_shaders; |
| 371 |
std::array<u32, 3> m_pipeline_counter; |
| 372 |
|
| 373 |
StoredPipeline CreatePipeline(const AbstractPipelineConfig& config) |
| 374 |
{ |
| 375 |
@autoreleasepool |
| 376 |
{ |
| 377 |
ASSERT(!config.geometry_shader); |
| 378 |
auto desc = MRCTransfer([MTLRenderPipelineDescriptor new]); |
| 379 |
[desc setVertexFunction:static_cast<const Shader*>(config.vertex_shader)->GetShader()]; |
| 380 |
[desc setFragmentFunction:static_cast<const Shader*>(config.pixel_shader)->GetShader()]; |
| 381 |
if (config.usage == AbstractPipelineUsage::GXUber) |
| 382 |
[desc setLabel:[NSString stringWithFormat:@"GX Uber Pipeline %d", m_pipeline_counter[0]++]]; |
| 383 |
else if (config.usage == AbstractPipelineUsage::GX) |
| 384 |
[desc setLabel:[NSString stringWithFormat:@"GX Pipeline %d", m_pipeline_counter[1]++]]; |
| 385 |
else |
| 386 |
[desc setLabel:[NSString stringWithFormat:@"Utility Pipeline %d", m_pipeline_counter[2]++]]; |
| 387 |
if (config.vertex_format) |
| 388 |
[desc setVertexDescriptor:static_cast<const VertexFormat*>(config.vertex_format)->Get()]; |
| 389 |
RasterizationState rs = config.rasterization_state; |
| 390 |
if (config.usage != AbstractPipelineUsage::GXUber) |
| 391 |
[desc setInputPrimitiveTopology:GetClass(rs.primitive)]; |
| 392 |
MTLRenderPipelineColorAttachmentDescriptor* color0 = |
| 393 |
[[desc colorAttachments] objectAtIndexedSubscript:0]; |
| 394 |
BlendingState bs = config.blending_state; |
| 395 |
MTLColorWriteMask mask = MTLColorWriteMaskNone; |
| 396 |
if (bs.color_update) |
| 397 |
mask |= MTLColorWriteMaskRed | MTLColorWriteMaskGreen | MTLColorWriteMaskBlue; |
| 398 |
if (bs.alpha_update) |
| 399 |
mask |= MTLColorWriteMaskAlpha; |
| 400 |
[color0 setWriteMask:mask]; |
| 401 |
if (bs.blend_enable) |
| 402 |
{ |
| 403 |
// clang-format off |
| 404 |
[color0 setBlendingEnabled:YES]; |
| 405 |
[color0 setSourceRGBBlendFactor: Convert(bs.src_factor, bs.use_dual_src)]; |
| 406 |
[color0 setSourceAlphaBlendFactor: Convert(bs.src_factor_alpha, bs.use_dual_src)]; |
| 407 |
[color0 setDestinationRGBBlendFactor: Convert(bs.dst_factor, bs.use_dual_src)]; |
| 408 |
[color0 setDestinationAlphaBlendFactor:Convert(bs.dst_factor_alpha, bs.use_dual_src)]; |
| 409 |
[color0 setRgbBlendOperation: bs.subtract ? MTLBlendOperationReverseSubtract : MTLBlendOperationAdd]; |
| 410 |
[color0 setAlphaBlendOperation:bs.subtract_alpha ? MTLBlendOperationReverseSubtract : MTLBlendOperationAdd]; |
| 411 |
// clang-format on |
| 412 |
} |
| 413 |
FramebufferState fs = config.framebuffer_state; |
| 414 |
if (fs.color_texture_format == AbstractTextureFormat::Undefined && |
| 415 |
fs.depth_texture_format == AbstractTextureFormat::Undefined) |
| 416 |
{ |
| 417 |
// Intel HD 4000's Metal driver asserts if you try to make one of these |
| 418 |
PanicAlertFmt("Attempted to create pipeline with no render targets!"); |
| 419 |
} |
| 420 |
[desc setRasterSampleCount:fs.samples]; |
| 421 |
[color0 setPixelFormat:Util::FromAbstract(fs.color_texture_format)]; |
| 422 |
if (u32 cnt = fs.additional_color_attachment_count) |
| 423 |
{ |
| 424 |
for (u32 i = 0; i < cnt; i++) |
| 425 |
[[desc colorAttachments] setObject:color0 atIndexedSubscript:i + 1]; |
| 426 |
} |
| 427 |
[desc setDepthAttachmentPixelFormat:Util::FromAbstract(fs.depth_texture_format)]; |
| 428 |
if (Util::HasStencil(fs.depth_texture_format)) |
| 429 |
[desc setStencilAttachmentPixelFormat:Util::FromAbstract(fs.depth_texture_format)]; |
| 430 |
NSError* err = nullptr; |
| 431 |
MTLRenderPipelineReflection* reflection = nullptr; |
| 432 |
id<MTLRenderPipelineState> pipe = |
| 433 |
[g_device newRenderPipelineStateWithDescriptor:desc |
| 434 |
options:MTLPipelineOptionArgumentInfo |
| 435 |
reflection:&reflection |
| 436 |
error:&err]; |
| 437 |
if (err) |
| 438 |
{ |
| 439 |
static int counter; |
| 440 |
std::string filename = VideoBackendBase::BadShaderFilename("pipeline", counter++); |
| 441 |
FILE* file = fopen(filename.c_str(), "w"); |
| 442 |
if (file) |
| 443 |
{ |
| 444 |
fmt::println(file, "=============== Error ==============="); |
| 445 |
fmt::println(file, "{}", [[err localizedDescription] UTF8String]); |
| 446 |
fmt::println(file, "============== Pipeline ============="); |
| 447 |
fmt::println(file, "VS: {}", [[[desc vertexFunction] label] UTF8String]); |
| 448 |
fmt::println(file, "PS: {}", [[[desc fragmentFunction] label] UTF8String]); |
| 449 |
fmt::println(file, "Color Format: {}", static_cast<u32>(fs.color_texture_format.Value())); |
| 450 |
fmt::println(file, "Depth Format: {}", static_cast<u32>(fs.depth_texture_format.Value())); |
| 451 |
fmt::println(file, "Sample Count: {}", fs.samples); |
| 452 |
if (u32 cnt = fs.additional_color_attachment_count) |
| 453 |
fmt::println(file, "Additional Color Attachments: {}", cnt); |
| 454 |
if (bs.color_update && bs.alpha_update) |
| 455 |
fmt::println(file, "Write Color, Alpha"); |
| 456 |
else if (bs.color_update) |
| 457 |
fmt::println(file, "Write Color"); |
| 458 |
else if (bs.alpha_update) |
| 459 |
fmt::println(file, "Write Alpha"); |
| 460 |
else |
| 461 |
fmt::println(file, "Write None"); |
| 462 |
if (bs.blend_enable) |
| 463 |
{ |
| 464 |
auto print_blend = [file](const char* name, SrcBlendFactor src, DstBlendFactor dst, |
| 465 |
bool subtract) { |
| 466 |
if (subtract) |
| 467 |
fmt::println(file, "{}: dst * {} - src * {}", name, dst, src); |
| 468 |
else |
| 469 |
fmt::println(file, "{}: src * {} + dst * {}", name, src, dst); |
| 470 |
}; |
| 471 |
print_blend("Color Blend", bs.src_factor, bs.dst_factor, bs.subtract); |
| 472 |
print_blend("Alpha Blend", bs.src_factor_alpha, bs.dst_factor_alpha, bs.subtract_alpha); |
| 473 |
fmt::println(file, "Blend Dual Source: {}", bs.use_dual_src ? "true" : "false"); |
| 474 |
} |
| 475 |
else |
| 476 |
{ |
| 477 |
fmt::println(file, "Blend Disabled"); |
| 478 |
} |
| 479 |
if (const Shader* vs = static_cast<const Shader*>(config.vertex_shader)) |
| 480 |
{ |
| 481 |
fmt::println(file, "========= Vertex Shader MSL ========="); |
| 482 |
fmt::println(file, "{}", vs->GetMSL()); |
| 483 |
} |
| 484 |
if (const Shader* ps = static_cast<const Shader*>(config.pixel_shader)) |
| 485 |
{ |
| 486 |
fmt::println(file, "========== Pixel Shader MSL ========="); |
| 487 |
fmt::println(file, "{}", ps->GetMSL()); |
| 488 |
} |
| 489 |
fclose(file); |
| 490 |
} |
| 491 |
|
| 492 |
std::string file_msg = file ? fmt::format("Details were written to {}", filename) : |
| 493 |
"Failed to write detailed info"; |
| 494 |
|
| 495 |
PanicAlertFmt("Failed to compile pipeline for {} and {}: {}\n{}", |
| 496 |
[[[desc vertexFunction] label] UTF8String], |
| 497 |
[[[desc fragmentFunction] label] UTF8String], |
| 498 |
[[err localizedDescription] UTF8String], file_msg); |
| 499 |
return std::make_pair(nullptr, PipelineReflection()); |
| 500 |
} |
| 501 |
|
| 502 |
return std::make_pair(MRCTransfer(pipe), PipelineReflection(reflection)); |
| 503 |
} |
| 504 |
} |
| 505 |
|
| 506 |
StoredPipeline GetOrCreatePipeline(const AbstractPipelineConfig& config) |
| 507 |
{ |
| 508 |
std::unique_lock<std::mutex> lock(m_mtx); |
| 509 |
PipelineID pid(config); |
| 510 |
auto it = m_pipelines.find(pid); |
| 511 |
if (it != m_pipelines.end()) |
| 512 |
{ |
| 513 |
while (!it->second.first && !it->second.second.textures) |
| 514 |
m_cv.wait(lock); // Wait for whoever's already compiling this |
| 515 |
return it->second; |
| 516 |
} |
| 517 |
// Reserve the spot now, so other threads know we're making it |
| 518 |
it = m_pipelines.insert({pid, {nullptr, PipelineReflection()}}).first; |
| 519 |
lock.unlock(); |
| 520 |
StoredPipeline pipe = CreatePipeline(config); |
| 521 |
lock.lock(); |
| 522 |
if (pipe.first) |
| 523 |
it->second = pipe; |
| 524 |
else |
| 525 |
it->second.second.textures = 1; // Abuse this as a "failed to create pipeline" flag |
| 526 |
m_shaders[pid.vertex_shader].push_back(pid); |
| 527 |
m_shaders[pid.fragment_shader].push_back(pid); |
| 528 |
lock.unlock(); |
| 529 |
m_cv.notify_all(); // Wake up anyone who might be waiting |
| 530 |
return pipe; |
| 531 |
} |
| 532 |
|
| 533 |
void ShaderDestroyed(const Shader* shader) |
| 534 |
{ |
| 535 |
std::lock_guard<std::mutex> lock(m_mtx); |
| 536 |
auto it = m_shaders.find(shader); |
| 537 |
if (it == m_shaders.end()) |
| 538 |
return; |
| 539 |
// It's unlikely, but if a shader is destroyed, a new one could be made with the same address |
| 540 |
// (Also, we know it won't be used anymore, so there's no reason to keep these around) |
| 541 |
for (const PipelineID& pid : it->second) |
| 542 |
m_pipelines.erase(pid); |
| 543 |
m_shaders.erase(it); |
| 544 |
} |
| 545 |
}; |
| 546 |
|
| 547 |
Metal::ObjectCache::ObjectCache() |
| 548 |
{ |
| 549 |
m_internal = std::make_unique<Internal>(); |
| 550 |
SetupDepthStencil(m_dss); |
| 551 |
} |
| 552 |
|
| 553 |
// This is defined here instead of the header so that the definition of Internal is visible when |
| 554 |
// m_internal is destroyed, preventing a compile error caused by calling unique_ptr's destructor |
| 555 |
// with an incomplete type. |
| 556 |
Metal::ObjectCache::~ObjectCache() = default; |
| 557 |
|
| 558 |
std::unique_ptr<AbstractPipeline> |
| 559 |
Metal::ObjectCache::CreatePipeline(const AbstractPipelineConfig& config) |
| 560 |
{ |
| 561 |
Internal::StoredPipeline pipeline = m_internal->GetOrCreatePipeline(config); |
| 562 |
if (!pipeline.first) |
| 563 |
return nullptr; |
| 564 |
return std::make_unique<Pipeline>(config, std::move(pipeline.first), pipeline.second, |
| 565 |
Convert(config.rasterization_state.primitive), |
| 566 |
Convert(config.rasterization_state.cull_mode), |
| 567 |
config.depth_state, config.usage); |
| 568 |
} |
| 569 |
|
| 570 |
void Metal::ObjectCache::ShaderDestroyed(const Shader* shader) |
| 571 |
{ |
| 572 |
m_internal->ShaderDestroyed(shader); |
| 573 |
} |