Blender V5.3
GHOST_ContextMTL.mm
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2013 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
10
11/* Don't generate OpenGL deprecation warning. This is a known thing, and is not something easily
12 * solvable in a short term. */
13#ifdef __clang__
14# pragma clang diagnostic ignored "-Wdeprecated-declarations"
15#endif
16
17#include "GHOST_ContextMTL.hh"
18
19#import <Cocoa/Cocoa.h>
20#import <Metal/Metal.h>
21#import <QuartzCore/QuartzCore.h>
22
23#include <cassert>
24#include <mutex>
25#include <vector>
26
27static const MTLPixelFormat METAL_FRAMEBUFFERPIXEL_FORMAT_EDR = MTLPixelFormatRGBA16Float;
28
29static void ghost_fatal_error_dialog(const char *msg)
30{
31 @autoreleasepool {
32 NSString *message = [NSString stringWithFormat:@"Error opening window:\n%s", msg];
33
34 NSAlert *alert = [[NSAlert alloc] init];
35
36 alert.messageText = @"Blender";
37 alert.informativeText = message;
38 alert.alertStyle = NSAlertStyleCritical;
39
40 [alert addButtonWithTitle:@"Quit"];
41 [alert runModal];
42 }
43
44 exit(1);
45}
46
47MTLCommandQueue *GHOST_ContextMTL::s_sharedMetalCommandQueue = nil;
48int GHOST_ContextMTL::s_sharedCount = 0;
49
51 NSView *metalView,
52 CAMetalLayer *metalLayer)
53 : GHOST_Context(context_params),
54 metal_view_(metalView),
55 metal_layer_(metalLayer),
56 metal_render_pipeline_(nil)
57{
58 @autoreleasepool {
59 /* Initialize Metal Swap-chain. */
60 current_swapchain_index = 0;
61 for (int i = 0; i < METAL_SWAPCHAIN_SIZE; i++) {
62 default_framebuffer_metal_texture_[i].texture = nil;
63 default_framebuffer_metal_texture_[i].index = i;
64 }
65
66 if (metal_view_) {
67 owns_metal_device_ = false;
68 metalInit();
69 }
70 else {
71 /* Prepare offscreen GHOST Context Metal device. */
72 id<MTLDevice> metalDevice = MTLCreateSystemDefaultDevice();
73
75 printf("Selected Metal Device: %s\n", [metalDevice.name UTF8String]);
76 }
77
78 owns_metal_device_ = true;
79 if (metalDevice) {
80 metal_layer_ = [[CAMetalLayer alloc] init];
81 metal_layer_.edgeAntialiasingMask = 0;
82 metal_layer_.masksToBounds = NO;
83 metal_layer_.opaque = YES;
84 metal_layer_.framebufferOnly = YES;
85 metal_layer_.presentsWithTransaction = NO;
86 [metal_layer_ removeAllAnimations];
87 metal_layer_.device = metalDevice;
88 metal_layer_.allowsNextDrawableTimeout = NO;
89
90 {
91 const GHOST_TVSyncModes vsync = getVSync();
92 if (vsync != GHOST_kVSyncModeUnset) {
93 metal_layer_.displaySyncEnabled = (vsync == GHOST_kVSyncModeOff) ? NO : YES;
94 }
95 }
96
97 /* Enable EDR support. This is done by:
98 * 1. Using a floating point render target, so that values outside 0..1 can be used
99 * 2. Informing the OS that we are EDR aware, and intend to use values outside 0..1
100 * 3. Setting the extended sRGB color space so that the OS knows how to interpret the
101 * values.
102 */
103 metal_layer_.wantsExtendedDynamicRangeContent = YES;
104 metal_layer_.pixelFormat = METAL_FRAMEBUFFERPIXEL_FORMAT_EDR;
105 const CFStringRef name = kCGColorSpaceExtendedSRGB;
106 CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(name);
107 metal_layer_.colorspace = colorspace;
108 CGColorSpaceRelease(colorspace);
109
110 metalInit();
111 }
112 else {
114 "[ERROR] Failed to create Metal device for offscreen GHOST Context.\n");
115 }
116 }
117
118 /* Initialize swap-interval. */
119 mtl_SwapInterval = 60;
120 }
121}
122
124{
125 /* Multiple threads can release their own context at the same time. */
126 static std::mutex mutex;
127 std::scoped_lock lock(mutex);
128
129 metalFree();
130
131 if (owns_metal_device_) {
132 if (metal_layer_) {
133 [metal_layer_ release];
134 metal_layer_ = nil;
135 }
136 }
137 assert(s_sharedCount);
138
139 s_sharedCount--;
140 [s_sharedMetalCommandQueue release];
141 if (s_sharedCount == 0) {
142 s_sharedMetalCommandQueue = nil;
143 }
144}
145
147{
148 if (metal_view_) {
149 metalSwapBuffers();
150 }
151 return GHOST_kSuccess;
152}
153
155{
156 mtl_SwapInterval = interval;
157 return GHOST_kSuccess;
158}
159
161{
162 interval_out = mtl_SwapInterval;
163 return GHOST_kSuccess;
164}
165
171
177
179{
180 /* NOTE(Metal): This is not valid. */
181 return 0;
182}
183
185{
186 if (metal_view_) {
187 metalUpdateFramebuffer();
188 return GHOST_kSuccess;
189 }
190 return GHOST_kFailure;
191}
192
194{
195 /* Increment Swap-chain - Only needed if context is requesting a new texture */
196 current_swapchain_index = (current_swapchain_index + 1) % METAL_SWAPCHAIN_SIZE;
197
198 /* Ensure backing texture is ready for current swapchain index */
200
201 /* Return texture. */
202 return default_framebuffer_metal_texture_[current_swapchain_index].texture;
203}
204
206{
207 return s_sharedMetalCommandQueue;
208}
210{
211 id<MTLDevice> device = metal_layer_.device;
212 return (MTLDevice *)device;
213}
214
216 MTLRenderPassDescriptor *, id<MTLRenderPipelineState>, id<MTLTexture>, id<CAMetalDrawable>))
217{
218 this->contextPresentCallback = callback;
219}
220
222 void (*callback)(id<MTLTexture>, int, int, int, int))
223{
224 this->xrBlitCallback = callback;
225}
226
228{
229 @autoreleasepool {
230 if (metal_view_) {
231 metalInitFramebuffer();
232 }
233 }
234 active_context_ = this;
235 return GHOST_kSuccess;
236}
237
239{
240 metal_view_ = nil;
241
242 return GHOST_kSuccess;
243}
244
245void GHOST_ContextMTL::metalInit()
246{
247 @autoreleasepool {
248 id<MTLDevice> device = metal_layer_.device;
249
250 /* Create a command queue for blit/present operation.
251 * NOTE: All context should share a single command queue
252 * to ensure correct ordering of work submitted from multiple contexts. */
253 if (s_sharedMetalCommandQueue == nil) {
254 s_sharedMetalCommandQueue = (MTLCommandQueue *)[device
255 newCommandQueueWithMaxCommandBufferCount:GHOST_ContextMTL::max_command_buffer_count];
256 }
257 /* Ensure active GHOSTContext retains a reference to the shared context. */
258 [s_sharedMetalCommandQueue retain];
259 s_sharedCount++;
260
261 /* Create shaders for blit operation. */
262 NSString *source = @R"msl(
263 using namespace metal;
264
265 struct Vertex {
266 float4 position [[position]];
267 float2 texCoord [[attribute(0)]];
268 };
269
270 vertex Vertex vertex_shader(uint v_id [[vertex_id]]) {
271 Vertex vtx;
272
273 vtx.position.x = float(v_id & 1) * 4.0 - 1.0;
274 vtx.position.y = float(v_id >> 1) * 4.0 - 1.0;
275 vtx.position.z = 0.0;
276 vtx.position.w = 1.0;
277
278 vtx.texCoord = vtx.position.xy * 0.5 + 0.5;
279
280 return vtx;
281 }
282
283 constexpr sampler s {};
284
285 fragment float4 fragment_shader(Vertex v [[stage_in]],
286 texture2d<float> t [[texture(0)]]) {
287
288 /* Final blit should ensure alpha is 1.0. This resolves
289 * rendering artifacts for blitting of final back-buffer.
290 * Also clamp the RGB values to avoid artifacts. */
291 float4 out_tex = t.sample(s, v.texCoord);
292 out_tex.rgb = min(out_tex.rgb, 16384.0);
293 out_tex.a = 1.0;
294 return out_tex;
295 }
296 )msl";
297
298 MTLCompileOptions *options = [[[MTLCompileOptions alloc] init] autorelease];
299 options.languageVersion = MTLLanguageVersion1_1;
300
301 NSError *error = nil;
302 id<MTLLibrary> library = [device newLibraryWithSource:source options:options error:&error];
303 if (error) {
305 "GHOST_ContextMTL::metalInit: newLibraryWithSource:options:error: failed!");
306 }
307
308 /* Create a render pipeline for blit operation. */
309 MTLRenderPipelineDescriptor *desc = [[[MTLRenderPipelineDescriptor alloc] init] autorelease];
310
311 desc.fragmentFunction = [library newFunctionWithName:@"fragment_shader"];
312 desc.vertexFunction = [library newFunctionWithName:@"vertex_shader"];
313 [desc.colorAttachments objectAtIndexedSubscript:0].pixelFormat =
315
316 /* Ensure library is released. */
317 [library autorelease];
318
319 metal_render_pipeline_ = (MTLRenderPipelineState *)[device
320 newRenderPipelineStateWithDescriptor:desc
321 error:&error];
322 if (error) {
324 "GHOST_ContextMTL::metalInit: newRenderPipelineStateWithDescriptor:error: failed!");
325 }
326
327 [desc.fragmentFunction release];
328 [desc.vertexFunction release];
329 }
330}
331
332void GHOST_ContextMTL::metalFree()
333{
334 if (metal_render_pipeline_) {
335 [metal_render_pipeline_ release];
336 metal_render_pipeline_ = nil;
337 }
338
339 for (int i = 0; i < METAL_SWAPCHAIN_SIZE; i++) {
340 if (default_framebuffer_metal_texture_[i].texture) {
341 [default_framebuffer_metal_texture_[i].texture release];
342 default_framebuffer_metal_texture_[i].texture = nil;
343 }
344 }
345}
346
347void GHOST_ContextMTL::metalInitFramebuffer()
348{
350}
351
352void GHOST_ContextMTL::metalUpdateFramebuffer()
353{
354 @autoreleasepool {
355 const NSSize drawableSize = metal_layer_.drawableSize;
356 const size_t width = size_t(drawableSize.width);
357 const size_t height = size_t(drawableSize.height);
358
359 if (default_framebuffer_metal_texture_[current_swapchain_index].texture &&
360 default_framebuffer_metal_texture_[current_swapchain_index].texture.width == width &&
361 default_framebuffer_metal_texture_[current_swapchain_index].texture.height == height)
362 {
363 return;
364 }
365
366 /* Free old texture */
367 [default_framebuffer_metal_texture_[current_swapchain_index].texture release];
368
369 id<MTLDevice> device = metal_layer_.device;
370 MTLTextureDescriptor *overlayDesc = [MTLTextureDescriptor
371 texture2DDescriptorWithPixelFormat:METAL_FRAMEBUFFERPIXEL_FORMAT_EDR
372 width:width
373 height:height
374 mipmapped:NO];
375 overlayDesc.storageMode = MTLStorageModePrivate;
376 overlayDesc.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
377
378 id<MTLTexture> overlayTex = [device newTextureWithDescriptor:overlayDesc];
379 if (!overlayTex) {
381 "GHOST_ContextMTL::metalUpdateFramebuffer: failed to create Metal overlay texture!");
382 }
383 else {
384 overlayTex.label = [NSString
385 stringWithFormat:@"Metal Overlay for GHOST Context %p", this]; //@"";
386 }
387
388 default_framebuffer_metal_texture_[current_swapchain_index].texture = overlayTex;
389
390 /* Clear texture on create */
391 id<MTLCommandBuffer> cmdBuffer = [s_sharedMetalCommandQueue commandBuffer];
392 MTLRenderPassDescriptor *passDescriptor = [MTLRenderPassDescriptor renderPassDescriptor];
393 {
394 auto attachment = [passDescriptor.colorAttachments objectAtIndexedSubscript:0];
395 attachment.texture = default_framebuffer_metal_texture_[current_swapchain_index].texture;
396 attachment.loadAction = MTLLoadActionClear;
397 attachment.clearColor = MTLClearColorMake(0.294, 0.294, 0.294, 1.000);
398 attachment.storeAction = MTLStoreActionStore;
399 }
400 {
401 id<MTLRenderCommandEncoder> enc = [cmdBuffer
402 renderCommandEncoderWithDescriptor:passDescriptor];
403 [enc endEncoding];
404 }
405 [cmdBuffer commit];
406
407 metal_layer_.drawableSize = CGSizeMake(CGFloat(width), CGFloat(height));
408 }
409}
410
411void GHOST_ContextMTL::metalSwapBuffers()
412{
413 @autoreleasepool {
415
416 id<CAMetalDrawable> drawable = [metal_layer_ nextDrawable];
417 if (!drawable) {
418 return;
419 }
420
421 MTLRenderPassDescriptor *passDescriptor = [MTLRenderPassDescriptor renderPassDescriptor];
422 {
423 auto attachment = [passDescriptor.colorAttachments objectAtIndexedSubscript:0];
424 attachment.texture = drawable.texture;
425 attachment.loadAction = MTLLoadActionClear;
426 attachment.clearColor = MTLClearColorMake(1.0, 0.294, 0.294, 1.000);
427 attachment.storeAction = MTLStoreActionStore;
428 }
429
430 assert(contextPresentCallback);
431 assert(default_framebuffer_metal_texture_[current_swapchain_index].texture != nil);
432 (*contextPresentCallback)(passDescriptor,
433 (id<MTLRenderPipelineState>)metal_render_pipeline_,
434 default_framebuffer_metal_texture_[current_swapchain_index].texture,
435 drawable);
436 }
437}
static const MTLPixelFormat METAL_FRAMEBUFFERPIXEL_FORMAT_EDR
static void ghost_fatal_error_dialog(const char *msg)
GHOST_TSuccess
@ GHOST_kFailure
@ GHOST_kSuccess
GHOST_TVSyncModes
@ GHOST_kVSyncModeUnset
@ GHOST_kVSyncModeOff
volatile int lock
void init()
GHOST_TSuccess releaseDrawingContext() override
static const int max_command_buffer_count
void metalRegisterXrBlitCallback(void(*callback)(id< MTLTexture >, int, int, int, int))
MTLCommandQueue * metalCommandQueue()
MTLDevice * metalDevice()
GHOST_TSuccess activateDrawingContext() override
void metalRegisterPresentCallback(void(*callback)(MTLRenderPassDescriptor *, id< MTLRenderPipelineState >, id< MTLTexture >, id< CAMetalDrawable >))
GHOST_TSuccess setSwapInterval(int interval) override
GHOST_ContextMTL(const GHOST_ContextParams &context_params, NSView *metalView, CAMetalLayer *metalLayer)
GHOST_TSuccess swapBufferRelease() override
GHOST_TSuccess updateDrawingContext() override
GHOST_TSuccess initializeDrawingContext() override
GHOST_TSuccess releaseNativeHandles() override
id< MTLTexture > metalOverlayTexture()
~GHOST_ContextMTL() override
unsigned int getDefaultFramebuffer() override
GHOST_TSuccess getSwapInterval(int &interval_out) override
GHOST_Context(const GHOST_ContextParams &context_params)
static GHOST_Context * active_context_
virtual GHOST_TVSyncModes getVSync()
GHOST_ContextParams context_params_
#define printf
CCL_NAMESPACE_BEGIN struct Options options
#define assert(assertion)
TEX_TEMPLATE DataVec texture(T, FltCoord, float=0.0f) RET