Debian Codegraph @

Source/Core/VideoBackends/Metal/MTLGfx.mm

raw
1 // Copyright 2022 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoBackends/Metal/MTLGfx.h"
5
6 #include "VideoBackends/Metal/MTLBoundingBox.h"
7 #include "VideoBackends/Metal/MTLObjectCache.h"
8 #include "VideoBackends/Metal/MTLPipeline.h"
9 #include "VideoBackends/Metal/MTLStateTracker.h"
10 #include "VideoBackends/Metal/MTLTexture.h"
11 #include "VideoBackends/Metal/MTLUtil.h"
12 #include "VideoBackends/Metal/MTLVertexFormat.h"
13 #include "VideoBackends/Metal/MTLVertexManager.h"
14
15 #include "VideoCommon/FramebufferManager.h"
16 #include "VideoCommon/Present.h"
17 #include "VideoCommon/VideoBackendBase.h"
18
19 #include <fstream>
20
21 Metal::Gfx::Gfx(MRCOwned<CAMetalLayer*> layer) : m_layer(std::move(layer))
22 {
23 UpdateActiveConfig();
24 [m_layer setDisplaySyncEnabled:g_ActiveConfig.bVSyncActive];
25
26 SetupSurface();
27 g_state_tracker->FlushEncoders();
28 }
29
30 Metal::Gfx::~Gfx() = default;
31
32 bool Metal::Gfx::IsHeadless() const
33 {
34 return m_layer == nullptr;
35 }
36
37 // MARK: Texture Creation
38
39 static MTLTextureType FromAbstract(AbstractTextureType type, bool multisample)
40 {
41 switch (type)
42 {
43 case AbstractTextureType::Texture_2D:
44 return multisample ? MTLTextureType2DMultisample : MTLTextureType2D;
45 case AbstractTextureType::Texture_2DArray:
46 return multisample ? MTLTextureType2DMultisampleArray : MTLTextureType2DArray;
47 case AbstractTextureType::Texture_CubeMap:
48 return MTLTextureTypeCube;
49 }
50
51 ASSERT(false);
52 return MTLTextureType2DArray;
53 }
54
55 std::unique_ptr<AbstractTexture> Metal::Gfx::CreateTexture(const TextureConfig& config,
56 std::string_view name)
57 {
58 @autoreleasepool
59 {
60 MRCOwned<MTLTextureDescriptor*> desc = MRCTransfer([MTLTextureDescriptor new]);
61 [desc setTextureType:FromAbstract(config.type, config.samples > 1)];
62 [desc setPixelFormat:Util::FromAbstract(config.format)];
63 [desc setWidth:config.width];
64 [desc setHeight:config.height];
65 [desc setMipmapLevelCount:config.levels];
66 [desc setArrayLength:config.layers];
67 [desc setSampleCount:config.samples];
68 [desc setStorageMode:MTLStorageModePrivate];
69 MTLTextureUsage usage = MTLTextureUsageShaderRead;
70 if (config.IsRenderTarget())
71 usage |= MTLTextureUsageRenderTarget;
72 if (config.IsComputeImage())
73 usage |= MTLTextureUsageShaderWrite;
74 [desc setUsage:usage];
75 id<MTLTexture> texture = [g_device newTextureWithDescriptor:desc];
76 if (!texture)
77 return nullptr;
78
79 if (name.empty())
80 [texture setLabel:[NSString stringWithFormat:@"Texture %d", m_texture_counter++]];
81 else
82 [texture setLabel:MRCTransfer([[NSString alloc] initWithBytes:name.data()
83 length:name.size()
84 encoding:NSUTF8StringEncoding])];
85 return std::make_unique<Texture>(MRCTransfer(texture), config);
86 }
87 }
88
89 std::unique_ptr<AbstractStagingTexture>
90 Metal::Gfx::CreateStagingTexture(StagingTextureType type, const TextureConfig& config)
91 {
92 @autoreleasepool
93 {
94 const size_t stride = config.GetStride();
95 const size_t buffer_size = stride * static_cast<size_t>(config.height);
96
97 MTLResourceOptions options = MTLStorageModeShared;
98 if (type == StagingTextureType::Upload)
99 options |= MTLResourceCPUCacheModeWriteCombined;
100
101 id<MTLBuffer> buffer = [g_device newBufferWithLength:buffer_size options:options];
102 if (!buffer)
103 return nullptr;
104 [buffer
105 setLabel:[NSString stringWithFormat:@"Staging Texture %d", m_staging_texture_counter++]];
106 return std::make_unique<StagingTexture>(MRCTransfer(buffer), type, config);
107 }
108 }
109
110 std::unique_ptr<AbstractFramebuffer>
111 Metal::Gfx::CreateFramebuffer(AbstractTexture* color_attachment, AbstractTexture* depth_attachment,
112 std::vector<AbstractTexture*> additional_color_attachments)
113 {
114 AbstractTexture* const either_attachment = color_attachment ? color_attachment : depth_attachment;
115 return std::make_unique<Framebuffer>(
116 color_attachment, depth_attachment, std::move(additional_color_attachments),
117 either_attachment->GetWidth(), either_attachment->GetHeight(), either_attachment->GetLayers(),
118 either_attachment->GetSamples());
119 }
120
121 // MARK: Pipeline Creation
122
123 std::unique_ptr<AbstractShader>
124 Metal::Gfx::CreateShaderFromSource(ShaderStage stage, std::string_view source,
125 VideoCommon::ShaderIncluder* shader_includer,
126 std::string_view name)
127 {
128 std::optional<std::string> msl = Util::TranslateShaderToMSL(stage, source, shader_includer);
129 if (!msl.has_value())
130 {
131 PanicAlertFmt("Failed to convert shader {} to MSL", name);
132 return nullptr;
133 }
134
135 return CreateShaderFromMSL(stage, std::move(*msl), source, name);
136 }
137
138 std::unique_ptr<AbstractShader> Metal::Gfx::CreateShaderFromBinary(ShaderStage stage,
139 const void* data, size_t length,
140 std::string_view name)
141 {
142 return CreateShaderFromMSL(stage, std::string(static_cast<const char*>(data), length), {}, name);
143 }
144
145 // clang-format off
146
147 static const char* StageFilename(ShaderStage stage)
148 {
149 switch (stage)
150 {
151 case ShaderStage::Vertex: return "vs";
152 case ShaderStage::Geometry: return "gs";
153 case ShaderStage::Pixel: return "ps";
154 case ShaderStage::Compute: return "cs";
155 }
156 }
157
158 static NSString* GenericShaderName(ShaderStage stage)
159 {
160 switch (stage)
161 {
162 case ShaderStage::Vertex: return @"Vertex shader %d";
163 case ShaderStage::Geometry: return @"Geometry shader %d";
164 case ShaderStage::Pixel: return @"Pixel shader %d";
165 case ShaderStage::Compute: return @"Compute shader %d";
166 }
167 }
168
169 // clang-format on
170
171 std::unique_ptr<AbstractShader> Metal::Gfx::CreateShaderFromMSL(ShaderStage stage, std::string msl,
172 std::string_view glsl,
173 std::string_view name)
174 {
175 @autoreleasepool
176 {
177 NSError* err = nullptr;
178 auto DumpBadShader = [&](std::string_view msg) {
179 static int counter = 0;
180 std::string filename = VideoBackendBase::BadShaderFilename(StageFilename(stage), counter++);
181 std::ofstream stream(filename);
182 if (stream.good())
183 {
184 stream << msl << std::endl;
185 stream << "/*" << std::endl;
186 stream << msg << std::endl;
187 stream << "Error:" << std::endl;
188 stream << [[err localizedDescription] UTF8String] << std::endl;
189 if (!glsl.empty())
190 {
191 stream << "Original GLSL:" << std::endl;
192 stream << glsl << std::endl;
193 }
194 else
195 {
196 stream << "Shader was created with cached MSL so no GLSL is available." << std::endl;
197 }
198 }
199
200 stream << std::endl;
201 stream << "Dolphin Version: " << Common::GetScmRevStr() << std::endl;
202 stream << "Video Backend: " << g_video_backend->GetDisplayName() << std::endl;
203 stream << "*/" << std::endl;
204 stream.close();
205
206 PanicAlertFmt("{} (written to {})\n", msg, filename);
207 };
208
209 auto lib = MRCTransfer([g_device newLibraryWithSource:[NSString stringWithUTF8String:msl.data()]
210 options:nil
211 error:&err]);
212 if (err)
213 {
214 DumpBadShader(fmt::format("Failed to compile {}", name));
215 return nullptr;
216 }
217 auto fn = MRCTransfer([lib newFunctionWithName:@"main0"]);
218 if (!fn)
219 {
220 DumpBadShader(fmt::format("Shader {} is missing its main0 function", name));
221 return nullptr;
222 }
223 if (!name.empty())
224 [fn setLabel:MRCTransfer([[NSString alloc] initWithBytes:name.data()
225 length:name.size()
226 encoding:NSUTF8StringEncoding])];
227 else
228 [fn setLabel:[NSString stringWithFormat:GenericShaderName(stage),
229 m_shader_counter[static_cast<u32>(stage)]++]];
230 [lib setLabel:[fn label]];
231 if (stage == ShaderStage::Compute)
232 {
233 MTLComputePipelineReflection* reflection = nullptr;
234 auto desc = [MTLComputePipelineDescriptor new];
235 [desc setComputeFunction:fn];
236 [desc setLabel:[fn label]];
237 MRCOwned<id<MTLComputePipelineState>> pipeline =
238 MRCTransfer([g_device newComputePipelineStateWithDescriptor:desc
239 options:MTLPipelineOptionArgumentInfo
240 reflection:&reflection
241 error:&err]);
242 if (err)
243 {
244 DumpBadShader(fmt::format("Failed to compile compute pipeline {}", name));
245 return nullptr;
246 }
247 return std::make_unique<ComputePipeline>(stage, reflection, std::move(msl), std::move(fn),
248 std::move(pipeline));
249 }
250 return std::make_unique<Shader>(stage, std::move(msl), std::move(fn));
251 }
252 }
253
254 std::unique_ptr<NativeVertexFormat>
255 Metal::Gfx::CreateNativeVertexFormat(const PortableVertexDeclaration& vtx_decl)
256 {
257 @autoreleasepool
258 {
259 return std::make_unique<VertexFormat>(vtx_decl);
260 }
261 }
262
263 std::unique_ptr<AbstractPipeline> Metal::Gfx::CreatePipeline(const AbstractPipelineConfig& config,
264 const void* cache_data,
265 size_t cache_data_length)
266 {
267 return g_object_cache->CreatePipeline(config);
268 }
269
270 void Metal::Gfx::Flush()
271 {
272 @autoreleasepool
273 {
274 g_state_tracker->FlushEncoders();
275 }
276 }
277
278 void Metal::Gfx::WaitForGPUIdle()
279 {
280 @autoreleasepool
281 {
282 g_state_tracker->FlushEncoders();
283 g_state_tracker->WaitForFlushedEncoders();
284 }
285 }
286
287 void Metal::Gfx::OnConfigChanged(u32 bits)
288 {
289 AbstractGfx::OnConfigChanged(bits);
290
291 if (bits & CONFIG_CHANGE_BIT_VSYNC)
292 [m_layer setDisplaySyncEnabled:g_ActiveConfig.bVSyncActive];
293
294 if (bits & CONFIG_CHANGE_BIT_ANISOTROPY)
295 {
296 g_object_cache->ReloadSamplers();
297 g_state_tracker->ReloadSamplers();
298 }
299 }
300
301 void Metal::Gfx::ClearRegion(const MathUtil::Rectangle<int>& target_rc, bool color_enable,
302 bool alpha_enable, bool z_enable, u32 color, u32 z)
303 {
304 u32 framebuffer_width = m_current_framebuffer->GetWidth();
305 u32 framebuffer_height = m_current_framebuffer->GetHeight();
306 // All Metal render passes are fullscreen, so we can only run a fast clear if the target is too
307 if (target_rc == MathUtil::Rectangle<int>(0, 0, framebuffer_width, framebuffer_height))
308 {
309 // Determine whether the EFB has an alpha channel. If it doesn't, we can clear the alpha
310 // channel to 0xFF. This hopefully allows us to use the fast path in most cases.
311 if (bpmem.zcontrol.pixel_format == PixelFormat::RGB565_Z16 ||
312 bpmem.zcontrol.pixel_format == PixelFormat::RGB8_Z24 ||
313 bpmem.zcontrol.pixel_format == PixelFormat::Z24)
314 {
315 // Force alpha writes, and clear the alpha channel. This is different from the other backends,
316 // where the existing values of the alpha channel are preserved.
317 alpha_enable = true;
318 color &= 0x00FFFFFF;
319 }
320
321 bool c_ok = (color_enable && alpha_enable) ||
322 g_state_tracker->GetCurrentFramebuffer()->GetColorFormat() ==
323 AbstractTextureFormat::Undefined;
324 bool z_ok = z_enable || g_state_tracker->GetCurrentFramebuffer()->GetDepthFormat() ==
325 AbstractTextureFormat::Undefined;
326 if (c_ok && z_ok)
327 {
328 @autoreleasepool
329 {
330 // clang-format off
331 MTLClearColor clear_color = MTLClearColorMake(
332 static_cast<double>((color >> 16) & 0xFF) / 255.0,
333 static_cast<double>((color >> 8) & 0xFF) / 255.0,
334 static_cast<double>((color >> 0) & 0xFF) / 255.0,
335 static_cast<double>((color >> 24) & 0xFF) / 255.0);
336 // clang-format on
337 float z_normalized = static_cast<float>(z & 0xFFFFFF) / 16777216.0f;
338 if (!g_backend_info.bSupportsReversedDepthRange)
339 z_normalized = 1.f - z_normalized;
340 g_state_tracker->BeginClearRenderPass(clear_color, z_normalized);
341 return;
342 }
343 }
344 }
345
346 g_state_tracker->EnableEncoderLabel(false);
347 AbstractGfx::ClearRegion(target_rc, color_enable, alpha_enable, z_enable, color, z);
348 g_state_tracker->EnableEncoderLabel(true);
349 }
350
351 void Metal::Gfx::SetPipeline(const AbstractPipeline* pipeline)
352 {
353 g_state_tracker->SetPipeline(static_cast<const Pipeline*>(pipeline));
354 }
355
356 void Metal::Gfx::SetFramebuffer(AbstractFramebuffer* framebuffer)
357 {
358 // Shouldn't be bound as a texture.
359 if (AbstractTexture* color = framebuffer->GetColorAttachment())
360 g_state_tracker->UnbindTexture(static_cast<Texture*>(color)->GetMTLTexture());
361 if (AbstractTexture* depth = framebuffer->GetDepthAttachment())
362 g_state_tracker->UnbindTexture(static_cast<Texture*>(depth)->GetMTLTexture());
363
364 m_current_framebuffer = framebuffer;
365 g_state_tracker->SetCurrentFramebuffer(static_cast<Framebuffer*>(framebuffer));
366 }
367
368 void Metal::Gfx::SetAndDiscardFramebuffer(AbstractFramebuffer* framebuffer)
369 {
370 @autoreleasepool
371 {
372 SetFramebuffer(framebuffer);
373 g_state_tracker->BeginRenderPass(MTLLoadActionDontCare);
374 }
375 }
376
377 void Metal::Gfx::SetAndClearFramebuffer(AbstractFramebuffer* framebuffer,
378 const ClearColor& color_value, float depth_value)
379 {
380 @autoreleasepool
381 {
382 SetFramebuffer(framebuffer);
383 MTLClearColor color =
384 MTLClearColorMake(color_value[0], color_value[1], color_value[2], color_value[3]);
385 g_state_tracker->BeginClearRenderPass(color, depth_value);
386 }
387 }
388
389 void Metal::Gfx::SetScissorRect(const MathUtil::Rectangle<int>& rc)
390 {
391 g_state_tracker->SetScissor(rc);
392 }
393
394 void Metal::Gfx::SetTexture(u32 index, const AbstractTexture* texture)
395 {
396 g_state_tracker->SetTexture(
397 index, texture ? static_cast<const Texture*>(texture)->GetMTLTexture() : nullptr);
398 }
399
400 void Metal::Gfx::SetSamplerState(u32 index, const SamplerState& state)
401 {
402 g_state_tracker->SetSampler(index, state);
403 }
404
405 void Metal::Gfx::SetComputeImageTexture(u32 index, AbstractTexture* texture, bool read, bool write)
406 {
407 g_state_tracker->SetTexture(index + VideoCommon::MAX_COMPUTE_SHADER_SAMPLERS,
408 texture ? static_cast<const Texture*>(texture)->GetMTLTexture() :
409 nullptr);
410 }
411
412 void Metal::Gfx::UnbindTexture(const AbstractTexture* texture)
413 {
414 g_state_tracker->UnbindTexture(static_cast<const Texture*>(texture)->GetMTLTexture());
415 }
416
417 void Metal::Gfx::SetViewport(float x, float y, float width, float height, float near_depth,
418 float far_depth)
419 {
420 g_state_tracker->SetViewport(x, y, width, height, near_depth, far_depth);
421 }
422
423 void Metal::Gfx::Draw(u32 base_vertex, u32 num_vertices)
424 {
425 @autoreleasepool
426 {
427 g_state_tracker->Draw(base_vertex, num_vertices);
428 }
429 }
430
431 void Metal::Gfx::DrawIndexed(u32 base_index, u32 num_indices, u32 base_vertex)
432 {
433 @autoreleasepool
434 {
435 g_state_tracker->DrawIndexed(base_index, num_indices, base_vertex);
436 }
437 }
438
439 void Metal::Gfx::DispatchComputeShader(const AbstractShader* shader, //
440 u32 groupsize_x, u32 groupsize_y, u32 groupsize_z,
441 u32 groups_x, u32 groups_y, u32 groups_z)
442 {
443 @autoreleasepool
444 {
445 g_state_tracker->SetPipeline(static_cast<const ComputePipeline*>(shader));
446 g_state_tracker->DispatchComputeShader(groupsize_x, groupsize_y, groupsize_z, //
447 groups_x, groups_y, groups_z);
448 }
449 }
450
451 bool Metal::Gfx::BindBackbuffer(const ClearColor& clear_color)
452 {
453 @autoreleasepool
454 {
455 CheckForSurfaceChange();
456 CheckForSurfaceResize();
457 m_drawable = MRCRetain([m_layer nextDrawable]);
458 m_backbuffer->UpdateBackbufferTexture([m_drawable texture]);
459 SetAndClearFramebuffer(m_backbuffer.get(), clear_color);
460 return m_drawable != nullptr;
461 }
462 }
463
464 void Metal::Gfx::PresentBackbuffer()
465 {
466 @autoreleasepool
467 {
468 g_state_tracker->EndRenderPass();
469 if (m_drawable)
470 {
471 // PresentDrawable refuses to allow Dolphin to present faster than the display's refresh rate
472 // when windowed (or fullscreen with vsync enabled, but that's more understandable).
473 // On the other hand, it helps Xcode's GPU captures start and stop on frame boundaries
474 // which is convenient. Put it here as a default-off config, which we can override in Xcode.
475 // It also seems to improve frame pacing, so enable it by default with vsync
476 if (g_ActiveConfig.iUsePresentDrawable == TriState::On ||
477 (g_ActiveConfig.iUsePresentDrawable == TriState::Auto && g_ActiveConfig.bVSyncActive))
478 [g_state_tracker->GetRenderCmdBuf() presentDrawable:m_drawable];
479 else
480 [g_state_tracker->GetRenderCmdBuf()
481 addScheduledHandler:[drawable = std::move(m_drawable)](id) { [drawable present]; }];
482 m_backbuffer->UpdateBackbufferTexture(nullptr);
483 m_drawable = nullptr;
484 }
485 g_state_tracker->FlushEncoders();
486 }
487 }
488
489 void Metal::Gfx::CheckForSurfaceChange()
490 {
491 if (!g_presenter->SurfaceChangedTestAndClear())
492 return;
493 m_layer = MRCRetain(static_cast<CAMetalLayer*>(g_presenter->GetNewSurfaceHandle()));
494 SetupSurface();
495 }
496
497 void Metal::Gfx::CheckForSurfaceResize()
498 {
499 if (!g_presenter->SurfaceResizedTestAndClear())
500 return;
501 SetupSurface();
502 }
503
504 void Metal::Gfx::SetupSurface()
505 {
506 auto info = GetSurfaceInfo();
507
508 [m_layer setDrawableSize:{static_cast<double>(info.width), static_cast<double>(info.height)}];
509
510 TextureConfig cfg(info.width, info.height, 1, 1, 1, info.format, AbstractTextureFlag_RenderTarget,
511 AbstractTextureType::Texture_2DArray);
512 m_bb_texture = std::make_unique<Texture>(nullptr, cfg);
513 m_backbuffer = std::make_unique<Framebuffer>(
514 m_bb_texture.get(), nullptr, std::vector<AbstractTexture*>{}, info.width, info.height, 1, 1);
515
516 if (g_presenter)
517 g_presenter->SetBackbuffer(info);
518 }
519
520 SurfaceInfo Metal::Gfx::GetSurfaceInfo() const
521 {
522 if (!m_layer) // Headless
523 return {};
524
525 CGSize size = [m_layer bounds].size;
526 const float scale = [m_layer contentsScale];
527
528 return {static_cast<u32>(size.width * scale), static_cast<u32>(size.height * scale), scale,
529 Util::ToAbstract([m_layer pixelFormat])};
530 }