Debian Codegraph @

drivers/metal/rendering_device_driver_metal.mm

raw
1 /**************************************************************************/
2 /* rendering_device_driver_metal.mm */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 /**************************************************************************/
32 /* */
33 /* Portions of this code were derived from MoltenVK. */
34 /* */
35 /* Copyright (c) 2015-2023 The Brenwill Workshop Ltd. */
36 /* (http://www.brenwill.com) */
37 /* */
38 /* Licensed under the Apache License, Version 2.0 (the "License"); */
39 /* you may not use this file except in compliance with the License. */
40 /* You may obtain a copy of the License at */
41 /* */
42 /* http://www.apache.org/licenses/LICENSE-2.0 */
43 /* */
44 /* Unless required by applicable law or agreed to in writing, software */
45 /* distributed under the License is distributed on an "AS IS" BASIS, */
46 /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
47 /* implied. See the License for the specific language governing */
48 /* permissions and limitations under the License. */
49 /**************************************************************************/
50
51 #import "rendering_device_driver_metal.h"
52
53 #import "pixel_formats.h"
54 #import "rendering_context_driver_metal.h"
55 #import "rendering_shader_container_metal.h"
56
57 #include "core/io/marshalls.h"
58 #include "core/string/ustring.h"
59 #include "core/templates/hash_map.h"
60 #include "drivers/apple/foundation_helpers.h"
61
62 #import <Metal/MTLTexture.h>
63 #import <Metal/Metal.h>
64 #import <os/log.h>
65 #import <os/signpost.h>
66 #include <algorithm>
67
68 #ifndef MTLGPUAddress
69 typedef uint64_t MTLGPUAddress;
70 #endif
71
72 #pragma mark - Logging
73
74 extern os_log_t LOG_DRIVER;
75 // Used for dynamic tracing.
76 extern os_log_t LOG_INTERVALS;
77
78 /*****************/
79 /**** GENERIC ****/
80 /*****************/
81
82 // RDD::CompareOperator == VkCompareOp.
83 static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_NEVER, MTLCompareFunctionNever));
84 static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_LESS, MTLCompareFunctionLess));
85 static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_EQUAL, MTLCompareFunctionEqual));
86 static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_LESS_OR_EQUAL, MTLCompareFunctionLessEqual));
87 static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_GREATER, MTLCompareFunctionGreater));
88 static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_NOT_EQUAL, MTLCompareFunctionNotEqual));
89 static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_GREATER_OR_EQUAL, MTLCompareFunctionGreaterEqual));
90 static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_ALWAYS, MTLCompareFunctionAlways));
91
92 _FORCE_INLINE_ MTLSize mipmapLevelSizeFromSize(MTLSize p_size, NSUInteger p_level) {
93 if (p_level == 0) {
94 return p_size;
95 }
96
97 MTLSize lvlSize;
98 lvlSize.width = MAX(p_size.width >> p_level, 1UL);
99 lvlSize.height = MAX(p_size.height >> p_level, 1UL);
100 lvlSize.depth = MAX(p_size.depth >> p_level, 1UL);
101 return lvlSize;
102 }
103
104 /*****************/
105 /**** BUFFERS ****/
106 /*****************/
107
108 RDD::BufferID RenderingDeviceDriverMetal::buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type, uint64_t p_frames_drawn) {
109 const uint64_t original_size = p_size;
110 if (p_usage.has_flag(BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT)) {
111 p_size = round_up_to_alignment(p_size, 16u) * _frame_count;
112 }
113
114 MTLResourceOptions options = 0;
115 switch (p_allocation_type) {
116 case MEMORY_ALLOCATION_TYPE_CPU:
117 options = MTLResourceHazardTrackingModeTracked | MTLResourceStorageModeShared;
118 break;
119 case MEMORY_ALLOCATION_TYPE_GPU:
120 if (p_usage.has_flag(BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT)) {
121 options = MTLResourceHazardTrackingModeUntracked | MTLResourceStorageModeShared | MTLResourceCPUCacheModeWriteCombined;
122 } else {
123 options = MTLResourceHazardTrackingModeTracked | MTLResourceStorageModePrivate;
124 }
125 break;
126 }
127
128 id<MTLBuffer> obj = [device newBufferWithLength:p_size options:options];
129 ERR_FAIL_NULL_V_MSG(obj, BufferID(), "Can't create buffer of size: " + itos(p_size));
130
131 BufferInfo *buf_info;
132 if (p_usage.has_flag(BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT)) {
133 MetalBufferDynamicInfo *dyn_buffer = memnew(MetalBufferDynamicInfo);
134 buf_info = dyn_buffer;
135 #ifdef DEBUG_ENABLED
136 dyn_buffer->last_frame_mapped = p_frames_drawn - 1ul;
137 #endif
138 dyn_buffer->set_frame_index(0u);
139 dyn_buffer->size_bytes = round_up_to_alignment(original_size, 16u);
140 } else {
141 buf_info = memnew(BufferInfo);
142 }
143 buf_info->metal_buffer = obj;
144
145 return BufferID(buf_info);
146 }
147
148 bool RenderingDeviceDriverMetal::buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) {
149 // Nothing to do.
150 return true;
151 }
152
153 void RenderingDeviceDriverMetal::buffer_free(BufferID p_buffer) {
154 BufferInfo *buf_info = (BufferInfo *)p_buffer.id;
155 buf_info->metal_buffer = nil; // Tell ARC to release.
156
157 if (buf_info->is_dynamic()) {
158 memdelete((MetalBufferDynamicInfo *)buf_info);
159 } else {
160 memdelete(buf_info);
161 }
162 }
163
164 uint64_t RenderingDeviceDriverMetal::buffer_get_allocation_size(BufferID p_buffer) {
165 const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;
166 return buf_info->metal_buffer.allocatedSize;
167 }
168
169 uint8_t *RenderingDeviceDriverMetal::buffer_map(BufferID p_buffer) {
170 const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;
171 ERR_FAIL_COND_V_MSG(buf_info->metal_buffer.storageMode != MTLStorageModeShared, nullptr, "Unable to map private buffers");
172 return (uint8_t *)buf_info->metal_buffer.contents;
173 }
174
175 void RenderingDeviceDriverMetal::buffer_unmap(BufferID p_buffer) {
176 // Nothing to do.
177 }
178
179 uint8_t *RenderingDeviceDriverMetal::buffer_persistent_map_advance(BufferID p_buffer, uint64_t p_frames_drawn) {
180 MetalBufferDynamicInfo *buf_info = (MetalBufferDynamicInfo *)p_buffer.id;
181 ERR_FAIL_COND_V_MSG(!buf_info->is_dynamic(), nullptr, "Buffer must have BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT. Use buffer_map() instead.");
182 #ifdef DEBUG_ENABLED
183 ERR_FAIL_COND_V_MSG(buf_info->last_frame_mapped == p_frames_drawn, nullptr, "Buffers with BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT must only be mapped once per frame. Otherwise there could be race conditions with the GPU. Amalgamate all data uploading into one map(), use an extra buffer or remove the bit.");
184 buf_info->last_frame_mapped = p_frames_drawn;
185 #endif
186 return (uint8_t *)buf_info->metal_buffer.contents + buf_info->next_frame_index(_frame_count) * buf_info->size_bytes;
187 }
188
189 uint64_t RenderingDeviceDriverMetal::buffer_get_dynamic_offsets(Span<BufferID> p_buffers) {
190 uint64_t mask = 0u;
191 uint64_t shift = 0u;
192
193 for (const BufferID &buf : p_buffers) {
194 const BufferInfo *buf_info = (const BufferInfo *)buf.id;
195 if (!buf_info->is_dynamic()) {
196 continue;
197 }
198 mask |= buf_info->frame_index() << shift;
199 // We can encode the frame index in 2 bits since frame_count won't be > 4.
200 shift += 2UL;
201 }
202
203 return mask;
204 }
205
206 void RenderingDeviceDriverMetal::buffer_flush(BufferID p_buffer) {
207 // Nothing to do.
208 }
209
210 uint64_t RenderingDeviceDriverMetal::buffer_get_device_address(BufferID p_buffer) {
211 if (@available(iOS 16.0, macOS 13.0, *)) {
212 const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;
213 return buf_info->metal_buffer.gpuAddress;
214 } else {
215 #if DEV_ENABLED
216 WARN_PRINT_ONCE("buffer_get_device_address is not supported on this OS version.");
217 #endif
218 return 0;
219 }
220 }
221
222 #pragma mark - Texture
223
224 #pragma mark - Format Conversions
225
226 static const MTLTextureType TEXTURE_TYPE[RD::TEXTURE_TYPE_MAX] = {
227 MTLTextureType1D,
228 MTLTextureType2D,
229 MTLTextureType3D,
230 MTLTextureTypeCube,
231 MTLTextureType1DArray,
232 MTLTextureType2DArray,
233 MTLTextureTypeCubeArray,
234 };
235
236 bool RenderingDeviceDriverMetal::is_valid_linear(TextureFormat const &p_format) const {
237 MTLFormatType ft = pixel_formats->getFormatType(p_format.format);
238
239 return p_format.texture_type == TEXTURE_TYPE_2D // Linear textures must be 2D textures.
240 && ft != MTLFormatType::DepthStencil && ft != MTLFormatType::Compressed // Linear textures must not be depth/stencil or compressed formats.)
241 && p_format.mipmaps == 1 // Linear textures must have 1 mipmap level.
242 && p_format.array_layers == 1 // Linear textures must have 1 array layer.
243 && p_format.samples == TEXTURE_SAMPLES_1; // Linear textures must have 1 sample.
244 }
245
246 RDD::TextureID RenderingDeviceDriverMetal::texture_create(const TextureFormat &p_format, const TextureView &p_view) {
247 MTLTextureDescriptor *desc = [MTLTextureDescriptor new];
248 desc.textureType = TEXTURE_TYPE[p_format.texture_type];
249
250 PixelFormats &formats = *pixel_formats;
251 desc.pixelFormat = formats.getMTLPixelFormat(p_format.format);
252 MTLFmtCaps format_caps = formats.getCapabilities(desc.pixelFormat);
253
254 desc.width = p_format.width;
255 desc.height = p_format.height;
256 desc.depth = p_format.depth;
257 desc.mipmapLevelCount = p_format.mipmaps;
258
259 if (p_format.texture_type == TEXTURE_TYPE_1D_ARRAY ||
260 p_format.texture_type == TEXTURE_TYPE_2D_ARRAY) {
261 desc.arrayLength = p_format.array_layers;
262 } else if (p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY) {
263 desc.arrayLength = p_format.array_layers / 6;
264 }
265
266 // TODO(sgc): Evaluate lossy texture support (perhaps as a project option?)
267 // https://developer.apple.com/videos/play/tech-talks/10876?time=459
268 // desc.compressionType = MTLTextureCompressionTypeLossy;
269
270 if (p_format.samples > TEXTURE_SAMPLES_1) {
271 SampleCount supported = (*device_properties).find_nearest_supported_sample_count(p_format.samples);
272
273 if (supported > SampleCount1) {
274 bool ok = p_format.texture_type == TEXTURE_TYPE_2D || p_format.texture_type == TEXTURE_TYPE_2D_ARRAY;
275 if (ok) {
276 switch (p_format.texture_type) {
277 case TEXTURE_TYPE_2D:
278 desc.textureType = MTLTextureType2DMultisample;
279 break;
280 case TEXTURE_TYPE_2D_ARRAY:
281 desc.textureType = MTLTextureType2DMultisampleArray;
282 break;
283 default:
284 break;
285 }
286 desc.sampleCount = (NSUInteger)supported;
287 if (p_format.mipmaps > 1) {
288 // For a buffer-backed or multi-sample texture, the value must be 1.
289 WARN_PRINT("mipmaps == 1 for multi-sample textures");
290 desc.mipmapLevelCount = 1;
291 }
292 } else {
293 WARN_PRINT("Unsupported multi-sample texture type; disabling multi-sample");
294 }
295 }
296 }
297
298 static const MTLTextureSwizzle COMPONENT_SWIZZLE[TEXTURE_SWIZZLE_MAX] = {
299 static_cast<MTLTextureSwizzle>(255), // IDENTITY
300 MTLTextureSwizzleZero,
301 MTLTextureSwizzleOne,
302 MTLTextureSwizzleRed,
303 MTLTextureSwizzleGreen,
304 MTLTextureSwizzleBlue,
305 MTLTextureSwizzleAlpha,
306 };
307
308 MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
309 p_view.swizzle_r != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_r] : MTLTextureSwizzleRed,
310 p_view.swizzle_g != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_g] : MTLTextureSwizzleGreen,
311 p_view.swizzle_b != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_b] : MTLTextureSwizzleBlue,
312 p_view.swizzle_a != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_a] : MTLTextureSwizzleAlpha);
313
314 // Represents a swizzle operation that is a no-op.
315 static MTLTextureSwizzleChannels IDENTITY_SWIZZLE = {
316 .red = MTLTextureSwizzleRed,
317 .green = MTLTextureSwizzleGreen,
318 .blue = MTLTextureSwizzleBlue,
319 .alpha = MTLTextureSwizzleAlpha,
320 };
321
322 bool no_swizzle = memcmp(&IDENTITY_SWIZZLE, &swizzle, sizeof(MTLTextureSwizzleChannels)) == 0;
323 if (!no_swizzle) {
324 desc.swizzle = swizzle;
325 }
326
327 // Usage.
328
329 MTLResourceOptions options = 0;
330 bool is_linear = false;
331 #if defined(VISIONOS_ENABLED)
332 const bool supports_memoryless = true;
333 #else
334 GODOT_CLANG_WARNING_PUSH_AND_IGNORE("-Wdeprecated-declarations")
335 const bool supports_memoryless = (*device_properties).features.highestFamily >= MTLGPUFamilyApple2 && (*device_properties).features.highestFamily < MTLGPUFamilyMac1;
336 GODOT_CLANG_WARNING_POP
337 #endif
338 if (supports_memoryless && p_format.usage_bits & TEXTURE_USAGE_TRANSIENT_BIT) {
339 options = MTLResourceStorageModeMemoryless | MTLResourceHazardTrackingModeTracked;
340 desc.storageMode = MTLStorageModeMemoryless;
341 } else {
342 options = MTLResourceCPUCacheModeDefaultCache | MTLResourceHazardTrackingModeTracked;
343 if (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) {
344 options |= MTLResourceStorageModeShared;
345 // The user has indicated they want to read from the texture on the CPU,
346 // so we'll see if we can use a linear format.
347 // A linear format is a texture that is backed by a buffer,
348 // which allows for CPU access to the texture data via a pointer.
349 is_linear = is_valid_linear(p_format);
350 } else {
351 options |= MTLResourceStorageModePrivate;
352 }
353 }
354 desc.resourceOptions = options;
355
356 if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) {
357 desc.usage |= MTLTextureUsageShaderRead;
358 }
359
360 if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) {
361 desc.usage |= MTLTextureUsageShaderWrite;
362 }
363
364 bool can_be_attachment = flags::any(format_caps, (kMTLFmtCapsColorAtt | kMTLFmtCapsDSAtt));
365
366 if (flags::any(p_format.usage_bits, TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) &&
367 can_be_attachment) {
368 desc.usage |= MTLTextureUsageRenderTarget;
369 }
370
371 if (p_format.usage_bits & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
372 desc.usage |= MTLTextureUsageShaderRead;
373 }
374
375 if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT) {
376 ERR_FAIL_COND_V_MSG((format_caps & kMTLFmtCapsAtomic) == 0, RDD::TextureID(), "Atomic operations on this texture format are not supported.");
377 ERR_FAIL_COND_V_MSG(!device_properties->features.supports_native_image_atomics, RDD::TextureID(), "Atomic operations on textures are not supported on this OS version. Check SUPPORTS_IMAGE_ATOMIC_32_BIT.");
378 // If supports_native_image_atomics is true, this condition should always succeed, as it is set the same.
379 if (@available(macOS 14.0, iOS 17.0, tvOS 17.0, *)) {
380 desc.usage |= MTLTextureUsageShaderAtomic;
381 }
382 }
383
384 if (p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {
385 ERR_FAIL_V_MSG(RDD::TextureID(), "unsupported: TEXTURE_USAGE_VRS_ATTACHMENT_BIT");
386 }
387
388 if (flags::any(p_format.usage_bits, TEXTURE_USAGE_CAN_UPDATE_BIT | TEXTURE_USAGE_CAN_COPY_TO_BIT) &&
389 can_be_attachment && no_swizzle) {
390 // Per MoltenVK, can be cleared as a render attachment.
391 desc.usage |= MTLTextureUsageRenderTarget;
392 }
393 if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
394 // Covered by blits.
395 }
396
397 // Create texture views with a different component layout.
398 if (!p_format.shareable_formats.is_empty()) {
399 desc.usage |= MTLTextureUsagePixelFormatView;
400 }
401
402 // Allocate memory.
403
404 id<MTLTexture> obj = nil;
405 if (is_linear) {
406 // Linear textures are restricted to 2D textures, a single mipmap level and a single array layer.
407 MTLPixelFormat pixel_format = desc.pixelFormat;
408 size_t row_alignment = get_texel_buffer_alignment_for_format(p_format.format);
409 size_t bytes_per_row = formats.getBytesPerRow(pixel_format, p_format.width);
410 bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
411 size_t bytes_per_layer = formats.getBytesPerLayer(pixel_format, bytes_per_row, p_format.height);
412 size_t byte_count = bytes_per_layer * p_format.depth * p_format.array_layers;
413
414 id<MTLBuffer> buf = [device newBufferWithLength:byte_count options:options];
415 obj = [buf newTextureWithDescriptor:desc offset:0 bytesPerRow:bytes_per_row];
416 } else {
417 obj = [device newTextureWithDescriptor:desc];
418 }
419 ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create texture.");
420
421 return rid::make(obj);
422 }
423
424 RDD::TextureID RenderingDeviceDriverMetal::texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil, uint32_t p_mipmaps) {
425 id<MTLTexture> res = (__bridge id<MTLTexture>)(void *)(uintptr_t)p_native_texture;
426
427 // If the requested format is different, we need to create a view.
428 MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_format);
429 if (res.pixelFormat != format) {
430 MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
431 MTLTextureSwizzleRed,
432 MTLTextureSwizzleGreen,
433 MTLTextureSwizzleBlue,
434 MTLTextureSwizzleAlpha);
435 res = [res newTextureViewWithPixelFormat:format
436 textureType:res.textureType
437 levels:NSMakeRange(0, res.mipmapLevelCount)
438 slices:NSMakeRange(0, p_array_layers)
439 swizzle:swizzle];
440 ERR_FAIL_NULL_V_MSG(res, TextureID(), "Unable to create texture view.");
441 }
442
443 return rid::make(res);
444 }
445
446 RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared(TextureID p_original_texture, const TextureView &p_view) {
447 id<MTLTexture> src_texture = rid::get(p_original_texture);
448
449 NSUInteger slices = src_texture.arrayLength;
450 if (src_texture.textureType == MTLTextureTypeCube) {
451 // Metal expects Cube textures to have a slice count of 6.
452 slices = 6;
453 } else if (src_texture.textureType == MTLTextureTypeCubeArray) {
454 // Metal expects Cube Array textures to have 6 slices per layer.
455 slices *= 6;
456 }
457
458 #if DEV_ENABLED
459 if (src_texture.sampleCount > 1) {
460 // TODO(sgc): is it ok to create a shared texture from a multi-sample texture?
461 WARN_PRINT("Is it safe to create a shared texture from multi-sample texture?");
462 }
463 #endif
464
465 MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_view.format);
466
467 static const MTLTextureSwizzle component_swizzle[TEXTURE_SWIZZLE_MAX] = {
468 static_cast<MTLTextureSwizzle>(255), // IDENTITY
469 MTLTextureSwizzleZero,
470 MTLTextureSwizzleOne,
471 MTLTextureSwizzleRed,
472 MTLTextureSwizzleGreen,
473 MTLTextureSwizzleBlue,
474 MTLTextureSwizzleAlpha,
475 };
476
477 #define SWIZZLE(C, CHAN) (p_view.swizzle_##C != TEXTURE_SWIZZLE_IDENTITY ? component_swizzle[p_view.swizzle_##C] : MTLTextureSwizzle##CHAN)
478 MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
479 SWIZZLE(r, Red),
480 SWIZZLE(g, Green),
481 SWIZZLE(b, Blue),
482 SWIZZLE(a, Alpha));
483 #undef SWIZZLE
484 id<MTLTexture> obj = [src_texture newTextureViewWithPixelFormat:format
485 textureType:src_texture.textureType
486 levels:NSMakeRange(0, src_texture.mipmapLevelCount)
487 slices:NSMakeRange(0, slices)
488 swizzle:swizzle];
489 ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create shared texture");
490 return rid::make(obj);
491 }
492
493 RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) {
494 id<MTLTexture> src_texture = rid::get(p_original_texture);
495
496 static const MTLTextureType VIEW_TYPES[] = {
497 MTLTextureType1D, // MTLTextureType1D
498 MTLTextureType1D, // MTLTextureType1DArray
499 MTLTextureType2D, // MTLTextureType2D
500 MTLTextureType2D, // MTLTextureType2DArray
501 MTLTextureType2D, // MTLTextureType2DMultisample
502 MTLTextureType2D, // MTLTextureTypeCube
503 MTLTextureType2D, // MTLTextureTypeCubeArray
504 MTLTextureType2D, // MTLTextureType3D
505 MTLTextureType2D, // MTLTextureType2DMultisampleArray
506 };
507
508 MTLTextureType textureType = VIEW_TYPES[src_texture.textureType];
509 switch (p_slice_type) {
510 case TEXTURE_SLICE_2D: {
511 textureType = MTLTextureType2D;
512 } break;
513 case TEXTURE_SLICE_3D: {
514 textureType = MTLTextureType3D;
515 } break;
516 case TEXTURE_SLICE_CUBEMAP: {
517 textureType = MTLTextureTypeCube;
518 } break;
519 case TEXTURE_SLICE_2D_ARRAY: {
520 textureType = MTLTextureType2DArray;
521 } break;
522 case TEXTURE_SLICE_MAX: {
523 ERR_FAIL_V_MSG(TextureID(), "Invalid texture slice type");
524 } break;
525 }
526
527 MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_view.format);
528
529 static const MTLTextureSwizzle component_swizzle[TEXTURE_SWIZZLE_MAX] = {
530 static_cast<MTLTextureSwizzle>(255), // IDENTITY
531 MTLTextureSwizzleZero,
532 MTLTextureSwizzleOne,
533 MTLTextureSwizzleRed,
534 MTLTextureSwizzleGreen,
535 MTLTextureSwizzleBlue,
536 MTLTextureSwizzleAlpha,
537 };
538
539 #define SWIZZLE(C, CHAN) (p_view.swizzle_##C != TEXTURE_SWIZZLE_IDENTITY ? component_swizzle[p_view.swizzle_##C] : MTLTextureSwizzle##CHAN)
540 MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
541 SWIZZLE(r, Red),
542 SWIZZLE(g, Green),
543 SWIZZLE(b, Blue),
544 SWIZZLE(a, Alpha));
545 #undef SWIZZLE
546 id<MTLTexture> obj = [src_texture newTextureViewWithPixelFormat:format
547 textureType:textureType
548 levels:NSMakeRange(p_mipmap, p_mipmaps)
549 slices:NSMakeRange(p_layer, p_layers)
550 swizzle:swizzle];
551 ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create shared texture");
552 return rid::make(obj);
553 }
554
555 void RenderingDeviceDriverMetal::texture_free(TextureID p_texture) {
556 rid::release(p_texture);
557 }
558
559 uint64_t RenderingDeviceDriverMetal::texture_get_allocation_size(TextureID p_texture) {
560 id<MTLTexture> __unsafe_unretained obj = rid::get(p_texture);
561 return obj.allocatedSize;
562 }
563
564 void RenderingDeviceDriverMetal::texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) {
565 id<MTLTexture> __unsafe_unretained obj = rid::get(p_texture);
566
567 PixelFormats &pf = *pixel_formats;
568 DataFormat format = pf.getDataFormat(obj.pixelFormat);
569
570 uint32_t w = MAX(1u, obj.width >> p_subresource.mipmap);
571 uint32_t h = MAX(1u, obj.height >> p_subresource.mipmap);
572 uint32_t d = MAX(1u, obj.depth >> p_subresource.mipmap);
573
574 uint32_t bw = 0, bh = 0;
575 get_compressed_image_format_block_dimensions(format, bw, bh);
576
577 uint32_t sbw = 0, sbh = 0;
578 *r_layout = {};
579 r_layout->size = get_image_format_required_size(format, w, h, d, 1, &sbw, &sbh);
580 r_layout->row_pitch = r_layout->size / ((sbh / bh) * d);
581 }
582
583 Vector<uint8_t> RenderingDeviceDriverMetal::texture_get_data(TextureID p_texture, uint32_t p_layer) {
584 id<MTLTexture> obj = rid::get(p_texture);
585 ERR_FAIL_COND_V_MSG(obj.storageMode != MTLStorageModeShared, Vector<uint8_t>(), "Texture must be created with TEXTURE_USAGE_CPU_READ_BIT set.");
586
587 if (obj.buffer) {
588 ERR_FAIL_COND_V_MSG(p_layer > 0, Vector<uint8_t>(), "A linear texture has a single layer.");
589 ERR_FAIL_COND_V_MSG(obj.mipmapLevelCount > 1, Vector<uint8_t>(), "A linear texture has a single mipmap level.");
590 Vector<uint8_t> image_data;
591 image_data.resize_uninitialized(obj.buffer.length);
592 memcpy(image_data.ptrw(), obj.buffer.contents, obj.buffer.length);
593 return image_data;
594 }
595
596 DataFormat tex_format = pixel_formats->getDataFormat(obj.pixelFormat);
597 uint32_t tex_w = obj.width;
598 uint32_t tex_h = obj.height;
599 uint32_t tex_d = obj.depth;
600 uint32_t tex_mipmaps = obj.mipmapLevelCount;
601
602 // Must iteratively copy the texture data to a buffer.
603
604 uint32_t tight_mip_size = get_image_format_required_size(tex_format, tex_w, tex_h, tex_d, tex_mipmaps);
605
606 Vector<uint8_t> image_data;
607 image_data.resize(tight_mip_size);
608
609 uint32_t pixel_size = get_image_format_pixel_size(tex_format);
610 uint32_t pixel_rshift = get_compressed_image_format_pixel_rshift(tex_format);
611 uint32_t blockw = 0, blockh = 0;
612 get_compressed_image_format_block_dimensions(tex_format, blockw, blockh);
613
614 uint8_t *dest_ptr = image_data.ptrw();
615
616 for (uint32_t mm_i = 0; mm_i < tex_mipmaps; mm_i++) {
617 uint32_t bw = STEPIFY(tex_w, blockw);
618 uint32_t bh = STEPIFY(tex_h, blockh);
619
620 uint32_t bytes_per_row = (bw * pixel_size) >> pixel_rshift;
621 uint32_t bytes_per_img = bytes_per_row * bh;
622 uint32_t mip_size = bytes_per_img * tex_d;
623
624 [obj getBytes:(void *)dest_ptr
625 bytesPerRow:bytes_per_row
626 bytesPerImage:bytes_per_img
627 fromRegion:MTLRegionMake3D(0, 0, 0, bw, bh, tex_d)
628 mipmapLevel:mm_i
629 slice:p_layer];
630
631 dest_ptr += mip_size;
632
633 // Next mipmap level.
634 tex_w = MAX(blockw, tex_w >> 1);
635 tex_h = MAX(blockh, tex_h >> 1);
636 tex_d = MAX(1u, tex_d >> 1);
637 }
638
639 // Ensure that the destination pointer is at the end of the image data.
640 DEV_ASSERT(dest_ptr - image_data.ptr() == image_data.size());
641
642 return image_data;
643 }
644
645 BitField<RDD::TextureUsageBits> RenderingDeviceDriverMetal::texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) {
646 PixelFormats &pf = *pixel_formats;
647 if (pf.getMTLPixelFormat(p_format) == MTLPixelFormatInvalid) {
648 return 0;
649 }
650
651 MTLFmtCaps caps = pf.getCapabilities(p_format);
652
653 // Everything supported by default makes an all-or-nothing check easier for the caller.
654 BitField<RDD::TextureUsageBits> supported = INT64_MAX;
655 supported.clear_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT); // No VRS support for Metal.
656
657 if (!flags::any(caps, kMTLFmtCapsColorAtt)) {
658 supported.clear_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT);
659 }
660 if (!flags::any(caps, kMTLFmtCapsDSAtt)) {
661 supported.clear_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
662 }
663 if (!flags::any(caps, kMTLFmtCapsRead)) {
664 supported.clear_flag(TEXTURE_USAGE_SAMPLING_BIT);
665 }
666 if (!flags::any(caps, kMTLFmtCapsAtomic)) {
667 supported.clear_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT);
668 }
669
670 return supported;
671 }
672
673 bool RenderingDeviceDriverMetal::texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) {
674 r_raw_reinterpretation = false;
675 return true;
676 }
677
678 #pragma mark - Sampler
679
680 static const MTLCompareFunction COMPARE_OPERATORS[RD::COMPARE_OP_MAX] = {
681 MTLCompareFunctionNever,
682 MTLCompareFunctionLess,
683 MTLCompareFunctionEqual,
684 MTLCompareFunctionLessEqual,
685 MTLCompareFunctionGreater,
686 MTLCompareFunctionNotEqual,
687 MTLCompareFunctionGreaterEqual,
688 MTLCompareFunctionAlways,
689 };
690
691 static const MTLStencilOperation STENCIL_OPERATIONS[RD::STENCIL_OP_MAX] = {
692 MTLStencilOperationKeep,
693 MTLStencilOperationZero,
694 MTLStencilOperationReplace,
695 MTLStencilOperationIncrementClamp,
696 MTLStencilOperationDecrementClamp,
697 MTLStencilOperationInvert,
698 MTLStencilOperationIncrementWrap,
699 MTLStencilOperationDecrementWrap,
700 };
701
702 static const MTLBlendFactor BLEND_FACTORS[RD::BLEND_FACTOR_MAX] = {
703 MTLBlendFactorZero,
704 MTLBlendFactorOne,
705 MTLBlendFactorSourceColor,
706 MTLBlendFactorOneMinusSourceColor,
707 MTLBlendFactorDestinationColor,
708 MTLBlendFactorOneMinusDestinationColor,
709 MTLBlendFactorSourceAlpha,
710 MTLBlendFactorOneMinusSourceAlpha,
711 MTLBlendFactorDestinationAlpha,
712 MTLBlendFactorOneMinusDestinationAlpha,
713 MTLBlendFactorBlendColor,
714 MTLBlendFactorOneMinusBlendColor,
715 MTLBlendFactorBlendAlpha,
716 MTLBlendFactorOneMinusBlendAlpha,
717 MTLBlendFactorSourceAlphaSaturated,
718 MTLBlendFactorSource1Color,
719 MTLBlendFactorOneMinusSource1Color,
720 MTLBlendFactorSource1Alpha,
721 MTLBlendFactorOneMinusSource1Alpha,
722 };
723 static const MTLBlendOperation BLEND_OPERATIONS[RD::BLEND_OP_MAX] = {
724 MTLBlendOperationAdd,
725 MTLBlendOperationSubtract,
726 MTLBlendOperationReverseSubtract,
727 MTLBlendOperationMin,
728 MTLBlendOperationMax,
729 };
730
731 static const API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MTLSamplerAddressMode ADDRESS_MODES[RD::SAMPLER_REPEAT_MODE_MAX] = {
732 MTLSamplerAddressModeRepeat,
733 MTLSamplerAddressModeMirrorRepeat,
734 MTLSamplerAddressModeClampToEdge,
735 MTLSamplerAddressModeClampToBorderColor,
736 MTLSamplerAddressModeMirrorClampToEdge,
737 };
738
739 static const API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MTLSamplerBorderColor SAMPLER_BORDER_COLORS[RD::SAMPLER_BORDER_COLOR_MAX] = {
740 MTLSamplerBorderColorTransparentBlack,
741 MTLSamplerBorderColorTransparentBlack,
742 MTLSamplerBorderColorOpaqueBlack,
743 MTLSamplerBorderColorOpaqueBlack,
744 MTLSamplerBorderColorOpaqueWhite,
745 MTLSamplerBorderColorOpaqueWhite,
746 };
747
748 RDD::SamplerID RenderingDeviceDriverMetal::sampler_create(const SamplerState &p_state) {
749 MTLSamplerDescriptor *desc = [MTLSamplerDescriptor new];
750 desc.supportArgumentBuffers = YES;
751
752 desc.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
753 desc.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
754 desc.mipFilter = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMipFilterLinear : MTLSamplerMipFilterNearest;
755
756 desc.sAddressMode = ADDRESS_MODES[p_state.repeat_u];
757 desc.tAddressMode = ADDRESS_MODES[p_state.repeat_v];
758 desc.rAddressMode = ADDRESS_MODES[p_state.repeat_w];
759
760 if (p_state.use_anisotropy) {
761 desc.maxAnisotropy = p_state.anisotropy_max;
762 }
763
764 desc.compareFunction = COMPARE_OPERATORS[p_state.compare_op];
765
766 desc.lodMinClamp = p_state.min_lod;
767 desc.lodMaxClamp = p_state.max_lod;
768
769 desc.borderColor = SAMPLER_BORDER_COLORS[p_state.border_color];
770
771 desc.normalizedCoordinates = !p_state.unnormalized_uvw;
772
773 #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 260000 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 260000 || __TV_OS_VERSION_MAX_ALLOWED >= 260000 || __VISION_OS_VERSION_MAX_ALLOWED >= 260000
774 if (p_state.lod_bias != 0.0) {
775 if (@available(macOS 26.0, iOS 26.0, tvOS 26.0, visionOS 26.0, *)) {
776 desc.lodBias = p_state.lod_bias;
777 }
778 }
779 #endif
780
781 id<MTLSamplerState> obj = [device newSamplerStateWithDescriptor:desc];
782 ERR_FAIL_NULL_V_MSG(obj, SamplerID(), "newSamplerStateWithDescriptor failed");
783 return rid::make(obj);
784 }
785
786 void RenderingDeviceDriverMetal::sampler_free(SamplerID p_sampler) {
787 rid::release(p_sampler);
788 }
789
790 bool RenderingDeviceDriverMetal::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) {
791 switch (p_filter) {
792 case SAMPLER_FILTER_NEAREST:
793 return true;
794 case SAMPLER_FILTER_LINEAR: {
795 MTLFmtCaps caps = pixel_formats->getCapabilities(p_format);
796 return flags::any(caps, kMTLFmtCapsFilter);
797 }
798 }
799 }
800
801 #pragma mark - Vertex Array
802
803 RDD::VertexFormatID RenderingDeviceDriverMetal::vertex_format_create(Span<VertexAttribute> p_vertex_attribs, const VertexAttributeBindingsMap &p_vertex_bindings) {
804 MTLVertexDescriptor *desc = MTLVertexDescriptor.vertexDescriptor;
805
806 for (const VertexAttributeBindingsMap::KV &kv : p_vertex_bindings) {
807 uint32_t idx = get_metal_buffer_index_for_vertex_attribute_binding(kv.key);
808 MTLVertexBufferLayoutDescriptor *ld = desc.layouts[idx];
809 if (kv.value.stride != 0) {
810 ld.stepFunction = kv.value.frequency == VERTEX_FREQUENCY_VERTEX ? MTLVertexStepFunctionPerVertex : MTLVertexStepFunctionPerInstance;
811 ld.stepRate = 1;
812 ld.stride = kv.value.stride;
813 } else {
814 ld.stepFunction = MTLVertexStepFunctionConstant;
815 ld.stepRate = 0;
816 ld.stride = 0;
817 }
818 DEV_ASSERT(ld.stride == desc.layouts[idx].stride);
819 }
820
821 for (const VertexAttribute &vf : p_vertex_attribs) {
822 desc.attributes[vf.location].format = pixel_formats->getMTLVertexFormat(vf.format);
823 desc.attributes[vf.location].offset = vf.offset;
824 uint32_t idx = get_metal_buffer_index_for_vertex_attribute_binding(vf.binding);
825 desc.attributes[vf.location].bufferIndex = idx;
826 if (vf.stride == 0) {
827 // Constant attribute, so we must determine the stride to satisfy Metal API.
828 uint32_t stride = desc.layouts[idx].stride;
829 desc.layouts[idx].stride = std::max(stride, vf.offset + pixel_formats->getBytesPerBlock(vf.format));
830 }
831 }
832
833 return rid::make(desc);
834 }
835
836 void RenderingDeviceDriverMetal::vertex_format_free(VertexFormatID p_vertex_format) {
837 rid::release(p_vertex_format);
838 }
839
840 #pragma mark - Barriers
841
842 void RenderingDeviceDriverMetal::command_pipeline_barrier(
843 CommandBufferID p_cmd_buffer,
844 BitField<PipelineStageBits> p_src_stages,
845 BitField<PipelineStageBits> p_dst_stages,
846 VectorView<MemoryAccessBarrier> p_memory_barriers,
847 VectorView<BufferBarrier> p_buffer_barriers,
848 VectorView<TextureBarrier> p_texture_barriers) {
849 WARN_PRINT_ONCE("not implemented");
850 }
851
852 #pragma mark - Fences
853
854 RDD::FenceID RenderingDeviceDriverMetal::fence_create() {
855 Fence *fence = nullptr;
856 if (@available(macOS 10.14, iOS 12.0, tvOS 12.0, visionOS 1.0, *)) {
857 fence = memnew(FenceEvent([device newSharedEvent]));
858 } else {
859 fence = memnew(FenceSemaphore());
860 }
861 return FenceID(fence);
862 }
863
864 Error RenderingDeviceDriverMetal::fence_wait(FenceID p_fence) {
865 Fence *fence = (Fence *)(p_fence.id);
866 return fence->wait(1000);
867 }
868
869 void RenderingDeviceDriverMetal::fence_free(FenceID p_fence) {
870 Fence *fence = (Fence *)(p_fence.id);
871 memdelete(fence);
872 }
873
874 #pragma mark - Semaphores
875
876 RDD::SemaphoreID RenderingDeviceDriverMetal::semaphore_create() {
877 // Metal doesn't use semaphores, as their purpose within Godot is to ensure ordering of command buffer execution.
878 return SemaphoreID(1);
879 }
880
881 void RenderingDeviceDriverMetal::semaphore_free(SemaphoreID p_semaphore) {
882 }
883
884 #pragma mark - Queues
885
886 RDD::CommandQueueFamilyID RenderingDeviceDriverMetal::command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface) {
887 if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_GRAPHICS_BIT) || (p_surface != 0)) {
888 return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_GRAPHICS_BIT);
889 } else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_COMPUTE_BIT)) {
890 return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_COMPUTE_BIT);
891 } else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_TRANSFER_BIT)) {
892 return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_TRANSFER_BIT);
893 } else {
894 return CommandQueueFamilyID();
895 }
896 }
897
898 RDD::CommandQueueID RenderingDeviceDriverMetal::command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue) {
899 return CommandQueueID(1);
900 }
901
902 Error RenderingDeviceDriverMetal::command_queue_execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID>, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID>, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains) {
903 uint32_t size = p_cmd_buffers.size();
904 if (size == 0) {
905 return OK;
906 }
907
908 for (uint32_t i = 0; i < size - 1; i++) {
909 MDCommandBuffer *cmd_buffer = (MDCommandBuffer *)(p_cmd_buffers[i].id);
910 cmd_buffer->commit();
911 }
912
913 // The last command buffer will signal the fence and semaphores.
914 MDCommandBuffer *cmd_buffer = (MDCommandBuffer *)(p_cmd_buffers[size - 1].id);
915 Fence *fence = (Fence *)(p_cmd_fence.id);
916 if (fence != nullptr) {
917 cmd_buffer->end();
918 id<MTLCommandBuffer> cb = cmd_buffer->get_command_buffer();
919 fence->signal(cb);
920 }
921
922 for (uint32_t i = 0; i < p_swap_chains.size(); i++) {
923 SwapChain *swap_chain = (SwapChain *)(p_swap_chains[i].id);
924 RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
925 metal_surface->present(cmd_buffer);
926 }
927
928 cmd_buffer->commit();
929
930 if (p_swap_chains.size() > 0) {
931 // Used as a signal that we're presenting, so this is the end of a frame.
932 [device_scope endScope];
933 [device_scope beginScope];
934 }
935
936 return OK;
937 }
938
939 void RenderingDeviceDriverMetal::command_queue_free(CommandQueueID p_cmd_queue) {
940 }
941
942 #pragma mark - Command Buffers
943
944 // ----- POOL -----
945
946 RDD::CommandPoolID RenderingDeviceDriverMetal::command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) {
947 DEV_ASSERT(p_cmd_buffer_type == COMMAND_BUFFER_TYPE_PRIMARY);
948 return rid::make(device_queue);
949 }
950
951 bool RenderingDeviceDriverMetal::command_pool_reset(CommandPoolID p_cmd_pool) {
952 return true;
953 }
954
955 void RenderingDeviceDriverMetal::command_pool_free(CommandPoolID p_cmd_pool) {
956 rid::release(p_cmd_pool);
957 }
958
959 // ----- BUFFER -----
960
961 RDD::CommandBufferID RenderingDeviceDriverMetal::command_buffer_create(CommandPoolID p_cmd_pool) {
962 id<MTLCommandQueue> queue = rid::get(p_cmd_pool);
963 MDCommandBuffer *obj = new MDCommandBuffer(queue, this);
964 command_buffers.push_back(obj);
965 return CommandBufferID(obj);
966 }
967
968 bool RenderingDeviceDriverMetal::command_buffer_begin(CommandBufferID p_cmd_buffer) {
969 MDCommandBuffer *obj = (MDCommandBuffer *)(p_cmd_buffer.id);
970 obj->begin();
971 return true;
972 }
973
974 bool RenderingDeviceDriverMetal::command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) {
975 ERR_FAIL_V_MSG(false, "not implemented");
976 }
977
978 void RenderingDeviceDriverMetal::command_buffer_end(CommandBufferID p_cmd_buffer) {
979 MDCommandBuffer *obj = (MDCommandBuffer *)(p_cmd_buffer.id);
980 obj->end();
981 }
982
983 void RenderingDeviceDriverMetal::command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) {
984 ERR_FAIL_MSG("not implemented");
985 }
986
987 #pragma mark - Swap Chain
988
989 void RenderingDeviceDriverMetal::_swap_chain_release(SwapChain *p_swap_chain) {
990 _swap_chain_release_buffers(p_swap_chain);
991 }
992
993 void RenderingDeviceDriverMetal::_swap_chain_release_buffers(SwapChain *p_swap_chain) {
994 }
995
996 RDD::SwapChainID RenderingDeviceDriverMetal::swap_chain_create(RenderingContextDriver::SurfaceID p_surface) {
997 RenderingContextDriverMetal::Surface const *surface = (RenderingContextDriverMetal::Surface *)(p_surface);
998
999 // Create the render pass that will be used to draw to the swap chain's framebuffers.
1000 RDD::Attachment attachment;
1001 attachment.format = pixel_formats->getDataFormat(surface->get_pixel_format());
1002 attachment.samples = RDD::TEXTURE_SAMPLES_1;
1003 attachment.load_op = RDD::ATTACHMENT_LOAD_OP_CLEAR;
1004 attachment.store_op = RDD::ATTACHMENT_STORE_OP_STORE;
1005
1006 RDD::Subpass subpass;
1007 RDD::AttachmentReference color_ref;
1008 color_ref.attachment = 0;
1009 color_ref.aspect.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);
1010 subpass.color_references.push_back(color_ref);
1011
1012 RenderPassID render_pass = render_pass_create(attachment, subpass, {}, 1, RDD::AttachmentReference());
1013 ERR_FAIL_COND_V(!render_pass, SwapChainID());
1014
1015 // Create the empty swap chain until it is resized.
1016 SwapChain *swap_chain = memnew(SwapChain);
1017 swap_chain->surface = p_surface;
1018 swap_chain->data_format = attachment.format;
1019 swap_chain->render_pass = render_pass;
1020 return SwapChainID(swap_chain);
1021 }
1022
1023 Error RenderingDeviceDriverMetal::swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) {
1024 DEV_ASSERT(p_cmd_queue.id != 0);
1025 DEV_ASSERT(p_swap_chain.id != 0);
1026
1027 SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
1028 RenderingContextDriverMetal::Surface *surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
1029 surface->resize(p_desired_framebuffer_count);
1030
1031 // Once everything's been created correctly, indicate the surface no longer needs to be resized.
1032 context_driver->surface_set_needs_resize(swap_chain->surface, false);
1033
1034 return OK;
1035 }
1036
1037 RDD::FramebufferID RenderingDeviceDriverMetal::swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) {
1038 DEV_ASSERT(p_cmd_queue.id != 0);
1039 DEV_ASSERT(p_swap_chain.id != 0);
1040
1041 SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
1042 if (context_driver->surface_get_needs_resize(swap_chain->surface)) {
1043 r_resize_required = true;
1044 return FramebufferID();
1045 }
1046
1047 RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
1048 return metal_surface->acquire_next_frame_buffer();
1049 }
1050
1051 RDD::RenderPassID RenderingDeviceDriverMetal::swap_chain_get_render_pass(SwapChainID p_swap_chain) {
1052 const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
1053 return swap_chain->render_pass;
1054 }
1055
1056 RDD::DataFormat RenderingDeviceDriverMetal::swap_chain_get_format(SwapChainID p_swap_chain) {
1057 const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
1058 return swap_chain->data_format;
1059 }
1060
1061 void RenderingDeviceDriverMetal::swap_chain_set_max_fps(SwapChainID p_swap_chain, int p_max_fps) {
1062 SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
1063 RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
1064 metal_surface->set_max_fps(p_max_fps);
1065 }
1066
1067 void RenderingDeviceDriverMetal::swap_chain_free(SwapChainID p_swap_chain) {
1068 SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
1069 _swap_chain_release(swap_chain);
1070 render_pass_free(swap_chain->render_pass);
1071 memdelete(swap_chain);
1072 }
1073
1074 #pragma mark - Frame buffer
1075
1076 RDD::FramebufferID RenderingDeviceDriverMetal::framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) {
1077 MDRenderPass *pass = (MDRenderPass *)(p_render_pass.id);
1078
1079 Vector<MTL::Texture> textures;
1080 textures.resize(p_attachments.size());
1081
1082 for (uint32_t i = 0; i < p_attachments.size(); i += 1) {
1083 MDAttachment const &a = pass->attachments[i];
1084 id<MTLTexture> tex = rid::get(p_attachments[i]);
1085 if (tex == nil) {
1086 #if DEV_ENABLED
1087 WARN_PRINT("Invalid texture for attachment " + itos(i));
1088 #endif
1089 }
1090 if (a.samples > 1) {
1091 if (tex.sampleCount != a.samples) {
1092 #if DEV_ENABLED
1093 WARN_PRINT("Mismatched sample count for attachment " + itos(i) + "; expected " + itos(a.samples) + ", got " + itos(tex.sampleCount));
1094 #endif
1095 }
1096 }
1097 textures.write[i] = tex;
1098 }
1099
1100 MDFrameBuffer *fb = new MDFrameBuffer(textures, Size2i(p_width, p_height));
1101 return FramebufferID(fb);
1102 }
1103
1104 void RenderingDeviceDriverMetal::framebuffer_free(FramebufferID p_framebuffer) {
1105 MDFrameBuffer *obj = (MDFrameBuffer *)(p_framebuffer.id);
1106 delete obj;
1107 }
1108
1109 #pragma mark - Shader
1110
1111 void RenderingDeviceDriverMetal::shader_cache_free_entry(const SHA256Digest &key) {
1112 if (ShaderCacheEntry **pentry = _shader_cache.getptr(key); pentry != nullptr) {
1113 ShaderCacheEntry *entry = *pentry;
1114 _shader_cache.erase(key);
1115 entry->library = nil;
1116 memdelete(entry);
1117 }
1118 }
1119
1120 template <typename T, typename U>
1121 struct is_layout_compatible
1122 : std::bool_constant<
1123 sizeof(T) == sizeof(U) &&
1124 alignof(T) == alignof(U) &&
1125 std::is_trivially_copyable_v<T> &&
1126 std::is_trivially_copyable_v<U>> {};
1127 static_assert(is_layout_compatible<UniformInfo::Indexes, RenderingShaderContainerMetal::UniformData::Indexes>::value, "UniformInfo::Indexes layout does not match RenderingShaderContainerMetal::UniformData::Indexes layout");
1128
1129 API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
1130 static void update_uniform_info(const RenderingShaderContainerMetal::UniformData &p_data, UniformInfo &r_ui) {
1131 r_ui.active_stages = p_data.active_stages;
1132 r_ui.dataType = static_cast<MTLDataType>(p_data.data_type);
1133 memcpy(&r_ui.slot, &p_data.slot, sizeof(UniformInfo::Indexes));
1134 memcpy(&r_ui.arg_buffer, &p_data.arg_buffer, sizeof(UniformInfo::Indexes));
1135 r_ui.access = static_cast<MTLBindingAccess>(p_data.access);
1136 r_ui.usage = static_cast<MTLResourceUsage>(p_data.usage);
1137 r_ui.textureType = static_cast<MTLTextureType>(p_data.texture_type);
1138 r_ui.imageFormat = p_data.image_format;
1139 r_ui.arrayLength = p_data.array_length;
1140 r_ui.isMultisampled = p_data.is_multisampled;
1141 }
1142
1143 RDD::ShaderID RenderingDeviceDriverMetal::shader_create_from_container(const Ref<RenderingShaderContainer> &p_shader_container, const Vector<ImmutableSampler> &p_immutable_samplers) {
1144 Ref<RenderingShaderContainerMetal> shader_container = p_shader_container;
1145 using RSCM = RenderingShaderContainerMetal;
1146
1147 CharString shader_name = shader_container->shader_name;
1148 RSCM::HeaderData &mtl_reflection_data = shader_container->mtl_reflection_data;
1149 Vector<RenderingShaderContainer::Shader> &shaders = shader_container->shaders;
1150 Vector<RSCM::StageData> &mtl_shaders = shader_container->mtl_shaders;
1151
1152 // We need to regenerate the shader if the cache is moved to an incompatible device or argument buffer support differs.
1153 ERR_FAIL_COND_V_MSG(!device_properties->features.argument_buffers_supported() && mtl_reflection_data.uses_argument_buffers(),
1154 RDD::ShaderID(),
1155 "Shader was compiled with argument buffers enabled, but this device does not support them");
1156
1157 ERR_FAIL_COND_V_MSG(device_properties->features.msl_max_version < mtl_reflection_data.msl_version,
1158 RDD::ShaderID(),
1159 "Shader was compiled for a newer version of Metal");
1160
1161 MTLGPUFamily compiled_gpu_family = static_cast<MTLGPUFamily>(mtl_reflection_data.profile.gpu);
1162 ERR_FAIL_COND_V_MSG(device_properties->features.highestFamily < compiled_gpu_family,
1163 RDD::ShaderID(),
1164 "Shader was generated for a newer Apple GPU");
1165
1166 MTLCompileOptions *options = [MTLCompileOptions new];
1167 uint32_t major = mtl_reflection_data.msl_version / 10000;
1168 uint32_t minor = (mtl_reflection_data.msl_version / 100) % 100;
1169 options.languageVersion = MTLLanguageVersion((major << 0x10) + minor);
1170 if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) {
1171 options.enableLogging = mtl_reflection_data.needs_debug_logging();
1172 }
1173
1174 HashMap<RD::ShaderStage, MDLibrary *> libraries;
1175
1176 bool is_compute = false;
1177 Vector<uint8_t> decompressed_code;
1178 for (uint32_t shader_index = 0; shader_index < shaders.size(); shader_index++) {
1179 const RenderingShaderContainer::Shader &shader = shaders[shader_index];
1180 const RSCM::StageData &shader_data = mtl_shaders[shader_index];
1181
1182 if (shader.shader_stage == RD::ShaderStage::SHADER_STAGE_COMPUTE) {
1183 is_compute = true;
1184 }
1185
1186 if (ShaderCacheEntry **p = _shader_cache.getptr(shader_data.hash); p != nullptr) {
1187 libraries[shader.shader_stage] = (*p)->library;
1188 continue;
1189 }
1190
1191 if (shader.code_decompressed_size > 0) {
1192 decompressed_code.resize(shader.code_decompressed_size);
1193 bool decompressed = shader_container->decompress_code(shader.code_compressed_bytes.ptr(), shader.code_compressed_bytes.size(), shader.code_compression_flags, decompressed_code.ptrw(), decompressed_code.size());
1194 ERR_FAIL_COND_V_MSG(!decompressed, RDD::ShaderID(), vformat("Failed to decompress code on shader stage %s.", String(RDD::SHADER_STAGE_NAMES[shader.shader_stage])));
1195 } else {
1196 decompressed_code = shader.code_compressed_bytes;
1197 }
1198
1199 ShaderCacheEntry *cd = memnew(ShaderCacheEntry(*this, shader_data.hash));
1200 cd->name = shader_name;
1201 cd->stage = shader.shader_stage;
1202
1203 NSString *source = [[NSString alloc] initWithBytes:(void *)decompressed_code.ptr()
1204 length:shader_data.source_size
1205 encoding:NSUTF8StringEncoding];
1206
1207 MDLibrary *library = nil;
1208 if (shader_data.library_size > 0) {
1209 ERR_FAIL_COND_V_MSG(mtl_reflection_data.os_min_version > device_properties->os_version,
1210 RDD::ShaderID(),
1211 "Metal shader binary was generated for a newer target OS");
1212 dispatch_data_t binary = dispatch_data_create(decompressed_code.ptr() + shader_data.source_size, shader_data.library_size, dispatch_get_main_queue(), DISPATCH_DATA_DESTRUCTOR_DEFAULT);
1213 library = [MDLibrary newLibraryWithCacheEntry:cd
1214 device:device
1215 #if DEV_ENABLED
1216 source:source
1217 #endif
1218 data:binary];
1219 } else {
1220 options.preserveInvariance = shader_data.is_position_invariant;
1221 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 150000 || __IPHONE_OS_VERSION_MIN_REQUIRED >= 180000 || __TV_OS_VERSION_MIN_REQUIRED >= 180000 || defined(VISIONOS_ENABLED)
1222 options.mathMode = MTLMathModeFast;
1223 #else
1224 options.fastMathEnabled = YES;
1225 #endif
1226 library = [MDLibrary newLibraryWithCacheEntry:cd
1227 device:device
1228 source:source
1229 options:options
1230 strategy:_shader_load_strategy];
1231 }
1232
1233 _shader_cache[shader_data.hash] = cd;
1234 libraries[shader.shader_stage] = library;
1235 }
1236
1237 ShaderReflection refl = shader_container->get_shader_reflection();
1238 RSCM::MetalShaderReflection mtl_refl = shader_container->get_metal_shader_reflection();
1239
1240 Vector<UniformSet> uniform_sets;
1241 uint32_t uniform_sets_count = mtl_refl.uniform_sets.size();
1242 uniform_sets.resize(uniform_sets_count);
1243
1244 DynamicOffsetLayout dynamic_offset_layout;
1245 uint8_t dynamic_offset = 0;
1246
1247 // Create sets.
1248 for (uint32_t i = 0; i < uniform_sets_count; i++) {
1249 UniformSet &set = uniform_sets.write[i];
1250 const Vector<ShaderUniform> &refl_set = refl.uniform_sets.ptr()[i];
1251 const Vector<RSCM::UniformData> &mtl_set = mtl_refl.uniform_sets.ptr()[i];
1252 uint32_t set_size = mtl_set.size();
1253 set.uniforms.resize(set_size);
1254
1255 uint8_t dynamic_count = 0;
1256
1257 LocalVector<UniformInfo>::Iterator iter = set.uniforms.begin();
1258 for (uint32_t j = 0; j < set_size; j++) {
1259 const ShaderUniform &uniform = refl_set.ptr()[j];
1260 const RSCM::UniformData &bind = mtl_set.ptr()[j];
1261
1262 switch (uniform.type) {
1263 case UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC:
1264 case UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC: {
1265 set.dynamic_uniforms.push_back(j);
1266 dynamic_count++;
1267 } break;
1268 default: {
1269 } break;
1270 }
1271
1272 UniformInfo &ui = *iter;
1273 ++iter;
1274 update_uniform_info(bind, ui);
1275 ui.binding = uniform.binding;
1276
1277 if (ui.arg_buffer.texture == UINT32_MAX && ui.arg_buffer.buffer == UINT32_MAX && ui.arg_buffer.sampler == UINT32_MAX) {
1278 // No bindings.
1279 continue;
1280 }
1281 #define VAL(x) (x == UINT32_MAX ? 0 : x)
1282 uint32_t max = std::max({ VAL(ui.arg_buffer.texture), VAL(ui.arg_buffer.buffer), VAL(ui.arg_buffer.sampler) });
1283 max += ui.arrayLength > 0 ? ui.arrayLength - 1 : 0;
1284 set.buffer_size = std::max(set.buffer_size, (max + 1) * (uint32_t)sizeof(uint64_t));
1285 #undef VAL
1286 }
1287
1288 if (dynamic_count > 0) {
1289 dynamic_offset_layout.set_offset_count(i, dynamic_offset, dynamic_count);
1290 dynamic_offset += dynamic_count;
1291 }
1292 }
1293
1294 MDShader *shader = nullptr;
1295 if (is_compute) {
1296 MDComputeShader *cs = new MDComputeShader(
1297 shader_name,
1298 uniform_sets,
1299 mtl_reflection_data.uses_argument_buffers(),
1300 libraries[RD::ShaderStage::SHADER_STAGE_COMPUTE]);
1301
1302 cs->local = MTLSizeMake(refl.compute_local_size[0], refl.compute_local_size[1], refl.compute_local_size[2]);
1303 shader = cs;
1304 } else {
1305 MDRenderShader *rs = new MDRenderShader(
1306 shader_name,
1307 uniform_sets,
1308 mtl_reflection_data.needs_view_mask_buffer(),
1309 mtl_reflection_data.uses_argument_buffers(),
1310 libraries[RD::ShaderStage::SHADER_STAGE_VERTEX],
1311 libraries[RD::ShaderStage::SHADER_STAGE_FRAGMENT]);
1312 shader = rs;
1313 }
1314
1315 shader->push_constants.stages = refl.push_constant_stages;
1316 shader->push_constants.size = refl.push_constant_size;
1317 shader->push_constants.binding = mtl_reflection_data.push_constant_binding;
1318 shader->dynamic_offset_layout = dynamic_offset_layout;
1319
1320 return RDD::ShaderID(shader);
1321 }
1322
1323 void RenderingDeviceDriverMetal::shader_free(ShaderID p_shader) {
1324 MDShader *obj = (MDShader *)p_shader.id;
1325 delete obj;
1326 }
1327
1328 void RenderingDeviceDriverMetal::shader_destroy_modules(ShaderID p_shader) {
1329 // TODO.
1330 }
1331
1332 /*********************/
1333 /**** UNIFORM SET ****/
1334 /*********************/
1335
1336 RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) {
1337 //p_linear_pool_index = -1; // TODO:? Linear pools not implemented or not supported by API backend.
1338
1339 MDShader *shader = (MDShader *)(p_shader.id);
1340 ERR_FAIL_INDEX_V_MSG(p_set_index, shader->sets.size(), UniformSetID(), "Set index out of range");
1341 const UniformSet &shader_set = shader->sets.get(p_set_index);
1342 MDUniformSet *set = memnew(MDUniformSet);
1343
1344 if (device_properties->features.argument_buffers_supported()) {
1345 // If argument buffers are enabled, we have already verified availability, so we can skip the runtime check.
1346 GODOT_CLANG_WARNING_PUSH_AND_IGNORE("-Wunguarded-availability-new")
1347
1348 set->arg_buffer = [device newBufferWithLength:shader_set.buffer_size options:MTLResourceStorageModeShared];
1349 uint64_t *ptr = (uint64_t *)set->arg_buffer.contents;
1350
1351 HashMap<MTLResourceUnsafe, StageResourceUsage, HashMapHasherDefault> bound_resources;
1352 auto add_usage = [&bound_resources](MTLResourceUnsafe res, BitField<RDD::ShaderStage> stage, MTLResourceUsage usage) {
1353 StageResourceUsage *sru = bound_resources.getptr(res);
1354 if (sru == nullptr) {
1355 sru = &bound_resources.insert(res, ResourceUnused)->value;
1356 }
1357 if (stage.has_flag(RDD::SHADER_STAGE_VERTEX_BIT)) {
1358 *sru |= stage_resource_usage(RDD::SHADER_STAGE_VERTEX, usage);
1359 }
1360 if (stage.has_flag(RDD::SHADER_STAGE_FRAGMENT_BIT)) {
1361 *sru |= stage_resource_usage(RDD::SHADER_STAGE_FRAGMENT, usage);
1362 }
1363 if (stage.has_flag(RDD::SHADER_STAGE_COMPUTE_BIT)) {
1364 *sru |= stage_resource_usage(RDD::SHADER_STAGE_COMPUTE, usage);
1365 }
1366 };
1367
1368 // Ensure the argument buffer exists for this set as some shader pipelines may
1369 // have been generated with argument buffers enabled.
1370 for (uint32_t i = 0; i < p_uniforms.size(); i += 1) {
1371 const BoundUniform &uniform = p_uniforms[i];
1372 const UniformInfo &ui = shader_set.uniforms[i];
1373 const UniformInfo::Indexes &idx = ui.arg_buffer;
1374
1375 switch (uniform.type) {
1376 case UNIFORM_TYPE_SAMPLER: {
1377 size_t count = uniform.ids.size();
1378 for (size_t j = 0; j < count; j += 1) {
1379 id<MTLSamplerState> sampler = rid::get(uniform.ids[j]);
1380 *(MTLResourceID *)(ptr + idx.sampler + j) = sampler.gpuResourceID;
1381 }
1382 } break;
1383 case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
1384 uint32_t count = uniform.ids.size() / 2;
1385 for (uint32_t j = 0; j < count; j += 1) {
1386 id<MTLSamplerState> sampler = rid::get(uniform.ids[j * 2 + 0]);
1387 id<MTLTexture> texture = rid::get(uniform.ids[j * 2 + 1]);
1388 *(MTLResourceID *)(ptr + idx.texture + j) = texture.gpuResourceID;
1389 *(MTLResourceID *)(ptr + idx.sampler + j) = sampler.gpuResourceID;
1390
1391 add_usage(texture, ui.active_stages, ui.usage);
1392 }
1393 } break;
1394 case UNIFORM_TYPE_TEXTURE: {
1395 size_t count = uniform.ids.size();
1396 for (size_t j = 0; j < count; j += 1) {
1397 id<MTLTexture> texture = rid::get(uniform.ids[j]);
1398 *(MTLResourceID *)(ptr + idx.texture + j) = texture.gpuResourceID;
1399
1400 add_usage(texture, ui.active_stages, ui.usage);
1401 }
1402 } break;
1403 case UNIFORM_TYPE_IMAGE: {
1404 size_t count = uniform.ids.size();
1405 for (size_t j = 0; j < count; j += 1) {
1406 id<MTLTexture> texture = rid::get(uniform.ids[j]);
1407 *(MTLResourceID *)(ptr + idx.texture + j) = texture.gpuResourceID;
1408 add_usage(texture, ui.active_stages, ui.usage);
1409
1410 if (idx.buffer != UINT32_MAX) {
1411 // Emulated atomic image access.
1412 id<MTLBuffer> buffer = (texture.parentTexture ? texture.parentTexture : texture).buffer;
1413 *(MTLGPUAddress *)(ptr + idx.buffer + j) = buffer.gpuAddress;
1414
1415 add_usage(buffer, ui.active_stages, ui.usage);
1416 }
1417 }
1418 } break;
1419 case UNIFORM_TYPE_TEXTURE_BUFFER: {
1420 ERR_PRINT("not implemented: UNIFORM_TYPE_TEXTURE_BUFFER");
1421 } break;
1422 case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
1423 ERR_PRINT("not implemented: UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER");
1424 } break;
1425 case UNIFORM_TYPE_IMAGE_BUFFER: {
1426 CRASH_NOW_MSG("not implemented: UNIFORM_TYPE_IMAGE_BUFFER");
1427 } break;
1428 case UNIFORM_TYPE_STORAGE_BUFFER:
1429 case UNIFORM_TYPE_UNIFORM_BUFFER: {
1430 const BufferInfo *buffer = (const BufferInfo *)uniform.ids[0].id;
1431 *(MTLGPUAddress *)(ptr + idx.buffer) = buffer->metal_buffer.gpuAddress;
1432
1433 add_usage(buffer->metal_buffer, ui.active_stages, ui.usage);
1434 } break;
1435 case UNIFORM_TYPE_INPUT_ATTACHMENT: {
1436 size_t count = uniform.ids.size();
1437 for (size_t j = 0; j < count; j += 1) {
1438 id<MTLTexture> texture = rid::get(uniform.ids[j]);
1439 *(MTLResourceID *)(ptr + idx.texture + j) = texture.gpuResourceID;
1440
1441 add_usage(texture, ui.active_stages, ui.usage);
1442 }
1443 } break;
1444 case UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC:
1445 case UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC: {
1446 // Dynamic buffers are not supported by argument buffers currently.
1447 // so we do not encode them, as there shouldn't be any runtime shaders that used them.
1448 } break;
1449 default: {
1450 DEV_ASSERT(false);
1451 }
1452 }
1453 }
1454
1455 for (KeyValue<MTLResourceUnsafe, StageResourceUsage> const &keyval : bound_resources) {
1456 ResourceVector *resources = set->usage_to_resources.getptr(keyval.value);
1457 if (resources == nullptr) {
1458 resources = &set->usage_to_resources.insert(keyval.value, ResourceVector())->value;
1459 }
1460 int64_t pos = resources->span().bisect(keyval.key, true);
1461 if (pos == resources->size() || (*resources)[pos] != keyval.key) {
1462 resources->insert(pos, keyval.key);
1463 }
1464 }
1465
1466 GODOT_CLANG_WARNING_POP
1467 }
1468 Vector<BoundUniform> bound_uniforms;
1469 bound_uniforms.resize(p_uniforms.size());
1470 for (uint32_t i = 0; i < p_uniforms.size(); i += 1) {
1471 bound_uniforms.write[i] = p_uniforms[i];
1472 }
1473 set->uniforms = bound_uniforms;
1474 set->index = p_set_index;
1475
1476 return UniformSetID(set);
1477 }
1478
1479 void RenderingDeviceDriverMetal::uniform_set_free(UniformSetID p_uniform_set) {
1480 MDUniformSet *obj = (MDUniformSet *)p_uniform_set.id;
1481 memdelete(obj);
1482 }
1483
1484 uint32_t RenderingDeviceDriverMetal::uniform_sets_get_dynamic_offsets(VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) const {
1485 const MDShader *shader = (const MDShader *)p_shader.id;
1486 const DynamicOffsetLayout layout = shader->dynamic_offset_layout;
1487
1488 if (layout.is_empty()) {
1489 return 0u;
1490 }
1491
1492 uint32_t mask = 0u;
1493
1494 for (uint32_t i = 0; i < p_set_count; i++) {
1495 const uint32_t index = p_first_set_index + i;
1496 uint32_t shift = layout.get_offset_index_shift(index);
1497 const uint32_t count = layout.get_count(index);
1498 DEV_ASSERT(shader->sets[index].dynamic_uniforms.size() == count);
1499 if (count == 0) {
1500 continue;
1501 }
1502
1503 const MDUniformSet *usi = (const MDUniformSet *)p_uniform_sets[i].id;
1504 for (uint32_t uniform_index : shader->sets[index].dynamic_uniforms) {
1505 const RDD::BoundUniform &uniform = usi->uniforms[uniform_index];
1506 DEV_ASSERT(uniform.is_dynamic());
1507 const MetalBufferDynamicInfo *buf_info = (const MetalBufferDynamicInfo *)uniform.ids[0].id;
1508 mask |= buf_info->frame_index() << shift;
1509 shift += 4u;
1510 }
1511 }
1512
1513 return mask;
1514 }
1515
1516 void RenderingDeviceDriverMetal::command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
1517 }
1518
1519 #pragma mark - Transfer
1520
1521 void RenderingDeviceDriverMetal::command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) {
1522 MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
1523 cmd->clear_buffer(p_buffer, p_offset, p_size);
1524 }
1525
1526 void RenderingDeviceDriverMetal::command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) {
1527 MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
1528 cmd->copy_buffer(p_src_buffer, p_dst_buffer, p_regions);
1529 }
1530
1531 void RenderingDeviceDriverMetal::command_copy_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<TextureCopyRegion> p_regions) {
1532 MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
1533 cmd->copy_texture(p_src_texture, p_dst_texture, p_regions);
1534 }
1535
1536 void RenderingDeviceDriverMetal::command_resolve_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, uint32_t p_src_layer, uint32_t p_src_mipmap, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, uint32_t p_dst_layer, uint32_t p_dst_mipmap) {
1537 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1538 cb->resolve_texture(p_src_texture, p_src_texture_layout, p_src_layer, p_src_mipmap, p_dst_texture, p_dst_texture_layout, p_dst_layer, p_dst_mipmap);
1539 }
1540
1541 void RenderingDeviceDriverMetal::command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) {
1542 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1543 cb->clear_color_texture(p_texture, p_texture_layout, p_color, p_subresources);
1544 }
1545
1546 void RenderingDeviceDriverMetal::command_clear_depth_stencil_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, float p_depth, uint8_t p_stencil, const TextureSubresourceRange &p_subresources) {
1547 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1548 cb->clear_depth_stencil_texture(p_texture, p_texture_layout, p_depth, p_stencil, p_subresources);
1549 }
1550
1551 void RenderingDeviceDriverMetal::command_copy_buffer_to_texture(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<BufferTextureCopyRegion> p_regions) {
1552 MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
1553 cmd->copy_buffer_to_texture(p_src_buffer, p_dst_texture, p_regions);
1554 }
1555
1556 void RenderingDeviceDriverMetal::command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_dst_buffer, VectorView<BufferTextureCopyRegion> p_regions) {
1557 MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
1558 cmd->copy_texture_to_buffer(p_src_texture, p_dst_buffer, p_regions);
1559 }
1560
1561 #pragma mark - Pipeline
1562
1563 void RenderingDeviceDriverMetal::pipeline_free(PipelineID p_pipeline_id) {
1564 MDPipeline *obj = (MDPipeline *)(p_pipeline_id.id);
1565 delete obj;
1566 }
1567
1568 // ----- BINDING -----
1569
1570 void RenderingDeviceDriverMetal::command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_dst_first_index, VectorView<uint32_t> p_data) {
1571 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1572 cb->encode_push_constant_data(p_shader, p_data);
1573 }
1574
1575 // ----- CACHE -----
1576
1577 String RenderingDeviceDriverMetal::_pipeline_get_cache_path() const {
1578 String path = OS::get_singleton()->get_user_data_dir() + "/metal/pipelines";
1579 path += "." + context_device.name.validate_filename().replace_char(' ', '_').to_lower();
1580 if (Engine::get_singleton()->is_editor_hint()) {
1581 path += ".editor";
1582 }
1583 path += ".cache";
1584
1585 return path;
1586 }
1587
1588 bool RenderingDeviceDriverMetal::pipeline_cache_create(const Vector<uint8_t> &p_data) {
1589 return false;
1590 CharString path = _pipeline_get_cache_path().utf8();
1591 NSString *nPath = [[NSString alloc] initWithBytesNoCopy:path.ptrw()
1592 length:path.length()
1593 encoding:NSUTF8StringEncoding
1594 freeWhenDone:NO];
1595 MTLBinaryArchiveDescriptor *desc = [MTLBinaryArchiveDescriptor new];
1596 if ([[NSFileManager defaultManager] fileExistsAtPath:nPath]) {
1597 desc.url = [NSURL fileURLWithPath:nPath];
1598 }
1599 NSError *error = nil;
1600 archive = [device newBinaryArchiveWithDescriptor:desc error:&error];
1601 return true;
1602 }
1603
1604 void RenderingDeviceDriverMetal::pipeline_cache_free() {
1605 archive = nil;
1606 }
1607
1608 size_t RenderingDeviceDriverMetal::pipeline_cache_query_size() {
1609 return archive_count * 1024;
1610 }
1611
1612 Vector<uint8_t> RenderingDeviceDriverMetal::pipeline_cache_serialize() {
1613 if (!archive) {
1614 return Vector<uint8_t>();
1615 }
1616
1617 CharString path = _pipeline_get_cache_path().utf8();
1618
1619 NSString *nPath = [[NSString alloc] initWithBytesNoCopy:path.ptrw()
1620 length:path.length()
1621 encoding:NSUTF8StringEncoding
1622 freeWhenDone:NO];
1623 NSURL *target = [NSURL fileURLWithPath:nPath];
1624 NSError *error = nil;
1625 if ([archive serializeToURL:target error:&error]) {
1626 return Vector<uint8_t>();
1627 } else {
1628 print_line(error.localizedDescription.UTF8String);
1629 return Vector<uint8_t>();
1630 }
1631 }
1632
1633 #pragma mark - Rendering
1634
1635 // ----- SUBPASS -----
1636
1637 RDD::RenderPassID RenderingDeviceDriverMetal::render_pass_create(VectorView<Attachment> p_attachments, VectorView<Subpass> p_subpasses, VectorView<SubpassDependency> p_subpass_dependencies, uint32_t p_view_count, AttachmentReference p_fragment_density_map_attachment) {
1638 PixelFormats &pf = *pixel_formats;
1639
1640 size_t subpass_count = p_subpasses.size();
1641
1642 Vector<MDSubpass> subpasses;
1643 subpasses.resize(subpass_count);
1644 for (uint32_t i = 0; i < subpass_count; i++) {
1645 MDSubpass &subpass = subpasses.write[i];
1646 subpass.subpass_index = i;
1647 subpass.view_count = p_view_count;
1648 subpass.input_references = p_subpasses[i].input_references;
1649 subpass.color_references = p_subpasses[i].color_references;
1650 subpass.depth_stencil_reference = p_subpasses[i].depth_stencil_reference;
1651 subpass.resolve_references = p_subpasses[i].resolve_references;
1652 }
1653
1654 static const MTLLoadAction LOAD_ACTIONS[] = {
1655 MTLLoadActionLoad, // ATTACHMENT_LOAD_OP_LOAD
1656 MTLLoadActionClear, // ATTACHMENT_LOAD_OP_CLEAR
1657 MTLLoadActionDontCare, // ATTACHMENT_LOAD_OP_DONT_CARE
1658 };
1659
1660 static const MTLStoreAction STORE_ACTIONS[] = {
1661 MTLStoreActionStore, // ATTACHMENT_STORE_OP_STORE
1662 MTLStoreActionDontCare, // ATTACHMENT_STORE_OP_DONT_CARE
1663 };
1664
1665 Vector<MDAttachment> attachments;
1666 attachments.resize(p_attachments.size());
1667
1668 for (uint32_t i = 0; i < p_attachments.size(); i++) {
1669 Attachment const &a = p_attachments[i];
1670 MDAttachment &mda = attachments.write[i];
1671 MTLPixelFormat format = pf.getMTLPixelFormat(a.format);
1672 mda.format = format;
1673 if (a.samples > TEXTURE_SAMPLES_1) {
1674 mda.samples = (*device_properties).find_nearest_supported_sample_count(a.samples);
1675 }
1676 mda.loadAction = LOAD_ACTIONS[a.load_op];
1677 mda.storeAction = STORE_ACTIONS[a.store_op];
1678 bool is_depth = pf.isDepthFormat(format);
1679 if (is_depth) {
1680 mda.type |= MDAttachmentType::Depth;
1681 }
1682 bool is_stencil = pf.isStencilFormat(format);
1683 if (is_stencil) {
1684 mda.type |= MDAttachmentType::Stencil;
1685 mda.stencilLoadAction = LOAD_ACTIONS[a.stencil_load_op];
1686 mda.stencilStoreAction = STORE_ACTIONS[a.stencil_store_op];
1687 }
1688 if (!is_depth && !is_stencil) {
1689 mda.type |= MDAttachmentType::Color;
1690 }
1691 }
1692 MDRenderPass *obj = new MDRenderPass(attachments, subpasses);
1693 return RenderPassID(obj);
1694 }
1695
1696 void RenderingDeviceDriverMetal::render_pass_free(RenderPassID p_render_pass) {
1697 MDRenderPass *obj = (MDRenderPass *)(p_render_pass.id);
1698 delete obj;
1699 }
1700
1701 // ----- COMMANDS -----
1702
1703 void RenderingDeviceDriverMetal::command_begin_render_pass(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, FramebufferID p_framebuffer, CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView<RenderPassClearValue> p_clear_values) {
1704 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1705 cb->render_begin_pass(p_render_pass, p_framebuffer, p_cmd_buffer_type, p_rect, p_clear_values);
1706 }
1707
1708 void RenderingDeviceDriverMetal::command_end_render_pass(CommandBufferID p_cmd_buffer) {
1709 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1710 cb->render_end_pass();
1711 }
1712
1713 void RenderingDeviceDriverMetal::command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) {
1714 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1715 cb->render_next_subpass();
1716 }
1717
1718 void RenderingDeviceDriverMetal::command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) {
1719 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1720 cb->render_set_viewport(p_viewports);
1721 }
1722
1723 void RenderingDeviceDriverMetal::command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) {
1724 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1725 cb->render_set_scissor(p_scissors);
1726 }
1727
1728 void RenderingDeviceDriverMetal::command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) {
1729 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1730 cb->render_clear_attachments(p_attachment_clears, p_rects);
1731 }
1732
1733 void RenderingDeviceDriverMetal::command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
1734 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1735 cb->bind_pipeline(p_pipeline);
1736 }
1737
1738 void RenderingDeviceDriverMetal::command_bind_render_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count, uint32_t p_dynamic_offsets) {
1739 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1740 cb->render_bind_uniform_sets(p_uniform_sets, p_shader, p_first_set_index, p_set_count, p_dynamic_offsets);
1741 }
1742
1743 void RenderingDeviceDriverMetal::command_render_draw(CommandBufferID p_cmd_buffer, uint32_t p_vertex_count, uint32_t p_instance_count, uint32_t p_base_vertex, uint32_t p_first_instance) {
1744 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1745 cb->render_draw(p_vertex_count, p_instance_count, p_base_vertex, p_first_instance);
1746 }
1747
1748 void RenderingDeviceDriverMetal::command_render_draw_indexed(CommandBufferID p_cmd_buffer, uint32_t p_index_count, uint32_t p_instance_count, uint32_t p_first_index, int32_t p_vertex_offset, uint32_t p_first_instance) {
1749 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1750 cb->render_draw_indexed(p_index_count, p_instance_count, p_first_index, p_vertex_offset, p_first_instance);
1751 }
1752
1753 void RenderingDeviceDriverMetal::command_render_draw_indexed_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) {
1754 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1755 cb->render_draw_indexed_indirect(p_indirect_buffer, p_offset, p_draw_count, p_stride);
1756 }
1757
1758 void RenderingDeviceDriverMetal::command_render_draw_indexed_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) {
1759 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1760 cb->render_draw_indexed_indirect_count(p_indirect_buffer, p_offset, p_count_buffer, p_count_buffer_offset, p_max_draw_count, p_stride);
1761 }
1762
1763 void RenderingDeviceDriverMetal::command_render_draw_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) {
1764 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1765 cb->render_draw_indirect(p_indirect_buffer, p_offset, p_draw_count, p_stride);
1766 }
1767
1768 void RenderingDeviceDriverMetal::command_render_draw_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) {
1769 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1770 cb->render_draw_indirect_count(p_indirect_buffer, p_offset, p_count_buffer, p_count_buffer_offset, p_max_draw_count, p_stride);
1771 }
1772
1773 void RenderingDeviceDriverMetal::command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets, uint64_t p_dynamic_offsets) {
1774 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1775 cb->render_bind_vertex_buffers(p_binding_count, p_buffers, p_offsets, p_dynamic_offsets);
1776 }
1777
1778 void RenderingDeviceDriverMetal::command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) {
1779 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1780 cb->render_bind_index_buffer(p_buffer, p_format, p_offset);
1781 }
1782
1783 void RenderingDeviceDriverMetal::command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) {
1784 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
1785 cb->render_set_blend_constants(p_constants);
1786 }
1787
1788 void RenderingDeviceDriverMetal::command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) {
1789 if (!Math::is_equal_approx(p_width, 1.0f)) {
1790 ERR_FAIL_MSG("Setting line widths other than 1.0 is not supported by the Metal rendering driver.");
1791 }
1792 }
1793
1794 // ----- PIPELINE -----
1795
1796 RenderingDeviceDriverMetal::Result<id<MTLFunction>> RenderingDeviceDriverMetal::_create_function(MDLibrary *p_library, NSString *p_name, VectorView<PipelineSpecializationConstant> &p_specialization_constants) {
1797 id<MTLLibrary> library = p_library.library;
1798 if (!library) {
1799 ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Failed to compile Metal library");
1800 }
1801
1802 id<MTLFunction> function = [library newFunctionWithName:p_name];
1803 ERR_FAIL_NULL_V_MSG(function, ERR_CANT_CREATE, "No function named main0");
1804
1805 if (function.functionConstantsDictionary.count == 0) {
1806 return function;
1807 }
1808
1809 NSArray<MTLFunctionConstant *> *constants = function.functionConstantsDictionary.allValues;
1810 bool is_sorted = true;
1811 for (uint32_t i = 1; i < constants.count; i++) {
1812 if (constants[i - 1].index > constants[i].index) {
1813 is_sorted = false;
1814 break;
1815 }
1816 }
1817
1818 if (!is_sorted) {
1819 constants = [constants sortedArrayUsingComparator:^NSComparisonResult(MTLFunctionConstant *a, MTLFunctionConstant *b) {
1820 if (a.index < b.index) {
1821 return NSOrderedAscending;
1822 } else if (a.index > b.index) {
1823 return NSOrderedDescending;
1824 } else {
1825 return NSOrderedSame;
1826 }
1827 }];
1828 }
1829
1830 // Initialize an array of integers representing the indexes of p_specialization_constants
1831 uint32_t *indexes = (uint32_t *)alloca(p_specialization_constants.size() * sizeof(uint32_t));
1832 for (uint32_t i = 0; i < p_specialization_constants.size(); i++) {
1833 indexes[i] = i;
1834 }
1835 // Sort the array of integers based on the values in p_specialization_constants
1836 std::sort(indexes, &indexes[p_specialization_constants.size()], [&](int a, int b) {
1837 return p_specialization_constants[a].constant_id < p_specialization_constants[b].constant_id;
1838 });
1839
1840 MTLFunctionConstantValues *constantValues = [MTLFunctionConstantValues new];
1841 uint32_t i = 0;
1842 uint32_t j = 0;
1843 while (i < constants.count && j < p_specialization_constants.size()) {
1844 MTLFunctionConstant *curr = constants[i];
1845 PipelineSpecializationConstant const &sc = p_specialization_constants[indexes[j]];
1846 if (curr.index == sc.constant_id) {
1847 switch (curr.type) {
1848 case MTLDataTypeBool:
1849 case MTLDataTypeFloat:
1850 case MTLDataTypeInt:
1851 case MTLDataTypeUInt: {
1852 [constantValues setConstantValue:&sc.int_value
1853 type:curr.type
1854 atIndex:sc.constant_id];
1855 } break;
1856 default:
1857 ERR_FAIL_V_MSG(function, "Invalid specialization constant type");
1858 }
1859 i++;
1860 j++;
1861 } else if (curr.index < sc.constant_id) {
1862 i++;
1863 } else {
1864 j++;
1865 }
1866 }
1867
1868 if (i != constants.count) {
1869 MTLFunctionConstant *curr = constants[i];
1870 if (curr.index == R32UI_ALIGNMENT_CONSTANT_ID) {
1871 uint32_t alignment = 16; // TODO(sgc): is this always correct?
1872 [constantValues setConstantValue:&alignment
1873 type:curr.type
1874 atIndex:curr.index];
1875 i++;
1876 }
1877 }
1878
1879 NSError *err = nil;
1880 function = [library newFunctionWithName:@"main0"
1881 constantValues:constantValues
1882 error:&err];
1883 ERR_FAIL_NULL_V_MSG(function, ERR_CANT_CREATE, String("specialized function failed: ") + err.localizedDescription.UTF8String);
1884
1885 return function;
1886 }
1887
1888 // RDD::PolygonCullMode == MTLCullMode.
1889 static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_DISABLED, MTLCullModeNone));
1890 static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_FRONT, MTLCullModeFront));
1891 static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_BACK, MTLCullModeBack));
1892
1893 // RDD::StencilOperation == MTLStencilOperation.
1894 static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_KEEP, MTLStencilOperationKeep));
1895 static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_ZERO, MTLStencilOperationZero));
1896 static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_REPLACE, MTLStencilOperationReplace));
1897 static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INCREMENT_AND_CLAMP, MTLStencilOperationIncrementClamp));
1898 static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_DECREMENT_AND_CLAMP, MTLStencilOperationDecrementClamp));
1899 static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INVERT, MTLStencilOperationInvert));
1900 static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INCREMENT_AND_WRAP, MTLStencilOperationIncrementWrap));
1901 static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_DECREMENT_AND_WRAP, MTLStencilOperationDecrementWrap));
1902
1903 // RDD::BlendOperation == MTLBlendOperation.
1904 static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_ADD, MTLBlendOperationAdd));
1905 static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_SUBTRACT, MTLBlendOperationSubtract));
1906 static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_REVERSE_SUBTRACT, MTLBlendOperationReverseSubtract));
1907 static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_MINIMUM, MTLBlendOperationMin));
1908 static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_MAXIMUM, MTLBlendOperationMax));
1909
1910 RDD::PipelineID RenderingDeviceDriverMetal::render_pipeline_create(
1911 ShaderID p_shader,
1912 VertexFormatID p_vertex_format,
1913 RenderPrimitive p_render_primitive,
1914 PipelineRasterizationState p_rasterization_state,
1915 PipelineMultisampleState p_multisample_state,
1916 PipelineDepthStencilState p_depth_stencil_state,
1917 PipelineColorBlendState p_blend_state,
1918 VectorView<int32_t> p_color_attachments,
1919 BitField<PipelineDynamicStateFlags> p_dynamic_state,
1920 RenderPassID p_render_pass,
1921 uint32_t p_render_subpass,
1922 VectorView<PipelineSpecializationConstant> p_specialization_constants) {
1923 MDRenderShader *shader = (MDRenderShader *)(p_shader.id);
1924 MTLVertexDescriptor *vert_desc = rid::get(p_vertex_format);
1925 MDRenderPass *pass = (MDRenderPass *)(p_render_pass.id);
1926
1927 os_signpost_id_t reflect_id = os_signpost_id_make_with_pointer(LOG_INTERVALS, shader);
1928 os_signpost_interval_begin(LOG_INTERVALS, reflect_id, "render_pipeline_create", "shader_name=%{public}s", shader->name.get_data());
1929 DEFER([=]() {
1930 os_signpost_interval_end(LOG_INTERVALS, reflect_id, "render_pipeline_create");
1931 });
1932
1933 os_signpost_event_emit(LOG_DRIVER, OS_SIGNPOST_ID_EXCLUSIVE, "create_pipeline");
1934
1935 MTLRenderPipelineDescriptor *desc = [MTLRenderPipelineDescriptor new];
1936
1937 {
1938 MDSubpass const &subpass = pass->subpasses[p_render_subpass];
1939 for (uint32_t i = 0; i < subpass.color_references.size(); i++) {
1940 uint32_t attachment = subpass.color_references[i].attachment;
1941 if (attachment != AttachmentReference::UNUSED) {
1942 MDAttachment const &a = pass->attachments[attachment];
1943 desc.colorAttachments[i].pixelFormat = a.format;
1944 }
1945 }
1946
1947 if (subpass.depth_stencil_reference.attachment != AttachmentReference::UNUSED) {
1948 uint32_t attachment = subpass.depth_stencil_reference.attachment;
1949 MDAttachment const &a = pass->attachments[attachment];
1950
1951 if (a.type & MDAttachmentType::Depth) {
1952 desc.depthAttachmentPixelFormat = a.format;
1953 }
1954
1955 if (a.type & MDAttachmentType::Stencil) {
1956 desc.stencilAttachmentPixelFormat = a.format;
1957 }
1958 }
1959 }
1960
1961 desc.vertexDescriptor = vert_desc;
1962 desc.label = [NSString stringWithUTF8String:shader->name.get_data()];
1963
1964 // Input assembly & tessellation.
1965
1966 MDRenderPipeline *pipeline = new MDRenderPipeline();
1967
1968 switch (p_render_primitive) {
1969 case RENDER_PRIMITIVE_POINTS:
1970 desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassPoint;
1971 break;
1972 case RENDER_PRIMITIVE_LINES:
1973 case RENDER_PRIMITIVE_LINES_WITH_ADJACENCY:
1974 case RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY:
1975 case RENDER_PRIMITIVE_LINESTRIPS:
1976 desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassLine;
1977 break;
1978 case RENDER_PRIMITIVE_TRIANGLES:
1979 case RENDER_PRIMITIVE_TRIANGLE_STRIPS:
1980 case RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY:
1981 case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY:
1982 case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX:
1983 desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassTriangle;
1984 break;
1985 case RENDER_PRIMITIVE_TESSELATION_PATCH:
1986 desc.maxTessellationFactor = p_rasterization_state.patch_control_points;
1987 desc.tessellationPartitionMode = MTLTessellationPartitionModeInteger;
1988 ERR_FAIL_V_MSG(PipelineID(), "tessellation not implemented");
1989 break;
1990 case RENDER_PRIMITIVE_MAX:
1991 default:
1992 desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassUnspecified;
1993 break;
1994 }
1995
1996 switch (p_render_primitive) {
1997 case RENDER_PRIMITIVE_POINTS:
1998 pipeline->raster_state.render_primitive = MTLPrimitiveTypePoint;
1999 break;
2000 case RENDER_PRIMITIVE_LINES:
2001 case RENDER_PRIMITIVE_LINES_WITH_ADJACENCY:
2002 pipeline->raster_state.render_primitive = MTLPrimitiveTypeLine;
2003 break;
2004 case RENDER_PRIMITIVE_LINESTRIPS:
2005 case RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY:
2006 pipeline->raster_state.render_primitive = MTLPrimitiveTypeLineStrip;
2007 break;
2008 case RENDER_PRIMITIVE_TRIANGLES:
2009 case RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY:
2010 pipeline->raster_state.render_primitive = MTLPrimitiveTypeTriangle;
2011 break;
2012 case RENDER_PRIMITIVE_TRIANGLE_STRIPS:
2013 case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY:
2014 case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX:
2015 pipeline->raster_state.render_primitive = MTLPrimitiveTypeTriangleStrip;
2016 break;
2017 default:
2018 break;
2019 }
2020
2021 // Rasterization.
2022 desc.rasterizationEnabled = !p_rasterization_state.discard_primitives;
2023 pipeline->raster_state.clip_mode = p_rasterization_state.enable_depth_clamp ? MTLDepthClipModeClamp : MTLDepthClipModeClip;
2024 pipeline->raster_state.fill_mode = p_rasterization_state.wireframe ? MTLTriangleFillModeLines : MTLTriangleFillModeFill;
2025
2026 static const MTLCullMode CULL_MODE[3] = {
2027 MTLCullModeNone,
2028 MTLCullModeFront,
2029 MTLCullModeBack,
2030 };
2031 pipeline->raster_state.cull_mode = CULL_MODE[p_rasterization_state.cull_mode];
2032 pipeline->raster_state.winding = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE) ? MTLWindingClockwise : MTLWindingCounterClockwise;
2033 pipeline->raster_state.depth_bias.enabled = p_rasterization_state.depth_bias_enabled;
2034 pipeline->raster_state.depth_bias.depth_bias = p_rasterization_state.depth_bias_constant_factor;
2035 pipeline->raster_state.depth_bias.slope_scale = p_rasterization_state.depth_bias_slope_factor;
2036 pipeline->raster_state.depth_bias.clamp = p_rasterization_state.depth_bias_clamp;
2037 // In Metal there is no line width.
2038 if (!Math::is_equal_approx(p_rasterization_state.line_width, 1.0f)) {
2039 WARN_PRINT("unsupported: line width");
2040 }
2041
2042 // Multisample.
2043 if (p_multisample_state.enable_sample_shading) {
2044 WARN_PRINT("unsupported: multi-sample shading");
2045 }
2046
2047 if (p_multisample_state.sample_count > TEXTURE_SAMPLES_1) {
2048 pipeline->sample_count = (*device_properties).find_nearest_supported_sample_count(p_multisample_state.sample_count);
2049 }
2050 desc.rasterSampleCount = static_cast<NSUInteger>(pipeline->sample_count);
2051 desc.alphaToCoverageEnabled = p_multisample_state.enable_alpha_to_coverage;
2052 desc.alphaToOneEnabled = p_multisample_state.enable_alpha_to_one;
2053
2054 // Depth buffer.
2055 bool depth_enabled = p_depth_stencil_state.enable_depth_test && desc.depthAttachmentPixelFormat != MTLPixelFormatInvalid;
2056 bool stencil_enabled = p_depth_stencil_state.enable_stencil && desc.stencilAttachmentPixelFormat != MTLPixelFormatInvalid;
2057
2058 if (depth_enabled || stencil_enabled) {
2059 MTLDepthStencilDescriptor *ds_desc = [MTLDepthStencilDescriptor new];
2060
2061 pipeline->raster_state.depth_test.enabled = depth_enabled;
2062 ds_desc.depthWriteEnabled = p_depth_stencil_state.enable_depth_write;
2063 ds_desc.depthCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.depth_compare_operator];
2064 if (p_depth_stencil_state.enable_depth_range) {
2065 WARN_PRINT("unsupported: depth range");
2066 }
2067
2068 if (stencil_enabled) {
2069 pipeline->raster_state.stencil.enabled = true;
2070 pipeline->raster_state.stencil.front_reference = p_depth_stencil_state.front_op.reference;
2071 pipeline->raster_state.stencil.back_reference = p_depth_stencil_state.back_op.reference;
2072
2073 {
2074 // Front.
2075 MTLStencilDescriptor *sd = [MTLStencilDescriptor new];
2076 sd.stencilFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.fail];
2077 sd.depthStencilPassOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.pass];
2078 sd.depthFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.depth_fail];
2079 sd.stencilCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.front_op.compare];
2080 sd.readMask = p_depth_stencil_state.front_op.compare_mask;
2081 sd.writeMask = p_depth_stencil_state.front_op.write_mask;
2082 ds_desc.frontFaceStencil = sd;
2083 }
2084 {
2085 // Back.
2086 MTLStencilDescriptor *sd = [MTLStencilDescriptor new];
2087 sd.stencilFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.fail];
2088 sd.depthStencilPassOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.pass];
2089 sd.depthFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.depth_fail];
2090 sd.stencilCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.back_op.compare];
2091 sd.readMask = p_depth_stencil_state.back_op.compare_mask;
2092 sd.writeMask = p_depth_stencil_state.back_op.write_mask;
2093 ds_desc.backFaceStencil = sd;
2094 }
2095 }
2096
2097 pipeline->depth_stencil = [device newDepthStencilStateWithDescriptor:ds_desc];
2098 ERR_FAIL_NULL_V_MSG(pipeline->depth_stencil, PipelineID(), "Failed to create depth stencil state");
2099 } else {
2100 // TODO(sgc): FB13671991 raised as Apple docs state calling setDepthStencilState:nil is valid, but currently generates an exception
2101 pipeline->depth_stencil = get_resource_cache().get_depth_stencil_state(false, false);
2102 }
2103
2104 // Blend state.
2105 {
2106 for (uint32_t i = 0; i < p_color_attachments.size(); i++) {
2107 if (p_color_attachments[i] == ATTACHMENT_UNUSED) {
2108 continue;
2109 }
2110
2111 const PipelineColorBlendState::Attachment &bs = p_blend_state.attachments[i];
2112
2113 MTLRenderPipelineColorAttachmentDescriptor *ca_desc = desc.colorAttachments[p_color_attachments[i]];
2114 ca_desc.blendingEnabled = bs.enable_blend;
2115
2116 ca_desc.sourceRGBBlendFactor = BLEND_FACTORS[bs.src_color_blend_factor];
2117 ca_desc.destinationRGBBlendFactor = BLEND_FACTORS[bs.dst_color_blend_factor];
2118 ca_desc.rgbBlendOperation = BLEND_OPERATIONS[bs.color_blend_op];
2119
2120 ca_desc.sourceAlphaBlendFactor = BLEND_FACTORS[bs.src_alpha_blend_factor];
2121 ca_desc.destinationAlphaBlendFactor = BLEND_FACTORS[bs.dst_alpha_blend_factor];
2122 ca_desc.alphaBlendOperation = BLEND_OPERATIONS[bs.alpha_blend_op];
2123
2124 ca_desc.writeMask = MTLColorWriteMaskNone;
2125 if (bs.write_r) {
2126 ca_desc.writeMask |= MTLColorWriteMaskRed;
2127 }
2128 if (bs.write_g) {
2129 ca_desc.writeMask |= MTLColorWriteMaskGreen;
2130 }
2131 if (bs.write_b) {
2132 ca_desc.writeMask |= MTLColorWriteMaskBlue;
2133 }
2134 if (bs.write_a) {
2135 ca_desc.writeMask |= MTLColorWriteMaskAlpha;
2136 }
2137 }
2138
2139 pipeline->raster_state.blend.r = p_blend_state.blend_constant.r;
2140 pipeline->raster_state.blend.g = p_blend_state.blend_constant.g;
2141 pipeline->raster_state.blend.b = p_blend_state.blend_constant.b;
2142 pipeline->raster_state.blend.a = p_blend_state.blend_constant.a;
2143 }
2144
2145 // Dynamic state.
2146
2147 if (p_dynamic_state.has_flag(DYNAMIC_STATE_DEPTH_BIAS)) {
2148 pipeline->raster_state.depth_bias.enabled = true;
2149 }
2150
2151 if (p_dynamic_state.has_flag(DYNAMIC_STATE_BLEND_CONSTANTS)) {
2152 pipeline->raster_state.blend.enabled = true;
2153 }
2154
2155 if (p_dynamic_state.has_flag(DYNAMIC_STATE_DEPTH_BOUNDS)) {
2156 // TODO(sgc): ??
2157 }
2158
2159 if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_COMPARE_MASK)) {
2160 // TODO(sgc): ??
2161 }
2162
2163 if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_WRITE_MASK)) {
2164 // TODO(sgc): ??
2165 }
2166
2167 if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_REFERENCE)) {
2168 pipeline->raster_state.stencil.enabled = true;
2169 }
2170
2171 if (shader->vert != nil) {
2172 Result<id<MTLFunction>> function_or_err = _create_function(shader->vert, @"main0", p_specialization_constants);
2173 ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
2174 desc.vertexFunction = std::get<id<MTLFunction>>(function_or_err);
2175 }
2176
2177 if (shader->frag != nil) {
2178 Result<id<MTLFunction>> function_or_err = _create_function(shader->frag, @"main0", p_specialization_constants);
2179 ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
2180 desc.fragmentFunction = std::get<id<MTLFunction>>(function_or_err);
2181 }
2182
2183 if (archive) {
2184 desc.binaryArchives = @[ archive ];
2185 }
2186
2187 NSError *error = nil;
2188 pipeline->state = [device newRenderPipelineStateWithDescriptor:desc
2189 error:&error];
2190 pipeline->shader = shader;
2191
2192 ERR_FAIL_COND_V_MSG(error != nil, PipelineID(), ([NSString stringWithFormat:@"error creating pipeline: %@", error.localizedDescription].UTF8String));
2193
2194 if (archive) {
2195 if ([archive addRenderPipelineFunctionsWithDescriptor:desc error:&error]) {
2196 archive_count += 1;
2197 } else {
2198 print_error(error.localizedDescription.UTF8String);
2199 }
2200 }
2201
2202 return PipelineID(pipeline);
2203 }
2204
2205 #pragma mark - Compute
2206
2207 // ----- COMMANDS -----
2208
2209 void RenderingDeviceDriverMetal::command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
2210 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
2211 cb->bind_pipeline(p_pipeline);
2212 }
2213
2214 void RenderingDeviceDriverMetal::command_bind_compute_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count, uint32_t p_dynamic_offsets) {
2215 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
2216 cb->compute_bind_uniform_sets(p_uniform_sets, p_shader, p_first_set_index, p_set_count, p_dynamic_offsets);
2217 }
2218
2219 void RenderingDeviceDriverMetal::command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
2220 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
2221 cb->compute_dispatch(p_x_groups, p_y_groups, p_z_groups);
2222 }
2223
2224 void RenderingDeviceDriverMetal::command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) {
2225 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
2226 cb->compute_dispatch_indirect(p_indirect_buffer, p_offset);
2227 }
2228
2229 // ----- PIPELINE -----
2230
2231 RDD::PipelineID RenderingDeviceDriverMetal::compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) {
2232 MDComputeShader *shader = (MDComputeShader *)(p_shader.id);
2233
2234 os_signpost_id_t reflect_id = os_signpost_id_make_with_pointer(LOG_INTERVALS, shader);
2235 os_signpost_interval_begin(LOG_INTERVALS, reflect_id, "compute_pipeline_create", "shader_name=%{public}s", shader->name.get_data());
2236 DEFER([=]() {
2237 os_signpost_interval_end(LOG_INTERVALS, reflect_id, "compute_pipeline_create");
2238 });
2239
2240 os_signpost_event_emit(LOG_DRIVER, OS_SIGNPOST_ID_EXCLUSIVE, "create_pipeline");
2241
2242 Result<id<MTLFunction>> function_or_err = _create_function(shader->kernel, @"main0", p_specialization_constants);
2243 ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
2244 id<MTLFunction> function = std::get<id<MTLFunction>>(function_or_err);
2245
2246 MTLComputePipelineDescriptor *desc = [MTLComputePipelineDescriptor new];
2247 desc.computeFunction = function;
2248 desc.label = conv::to_nsstring(shader->name);
2249 if (archive) {
2250 desc.binaryArchives = @[ archive ];
2251 }
2252
2253 NSError *error;
2254 id<MTLComputePipelineState> state = [device newComputePipelineStateWithDescriptor:desc
2255 options:MTLPipelineOptionNone
2256 reflection:nil
2257 error:&error];
2258 ERR_FAIL_COND_V_MSG(error != nil, PipelineID(), ([NSString stringWithFormat:@"error creating pipeline: %@", error.localizedDescription].UTF8String));
2259
2260 MDComputePipeline *pipeline = new MDComputePipeline(state);
2261 pipeline->compute_state.local = shader->local;
2262 pipeline->shader = shader;
2263
2264 if (archive) {
2265 if ([archive addComputePipelineFunctionsWithDescriptor:desc error:&error]) {
2266 archive_count += 1;
2267 } else {
2268 print_error(error.localizedDescription.UTF8String);
2269 }
2270 }
2271
2272 return PipelineID(pipeline);
2273 }
2274
2275 #pragma mark - Queries
2276
2277 // ----- TIMESTAMP -----
2278
2279 RDD::QueryPoolID RenderingDeviceDriverMetal::timestamp_query_pool_create(uint32_t p_query_count) {
2280 return QueryPoolID(1);
2281 }
2282
2283 void RenderingDeviceDriverMetal::timestamp_query_pool_free(QueryPoolID p_pool_id) {
2284 }
2285
2286 void RenderingDeviceDriverMetal::timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) {
2287 // Metal doesn't support timestamp queries, so we just clear the buffer.
2288 bzero(r_results, p_query_count * sizeof(uint64_t));
2289 }
2290
2291 uint64_t RenderingDeviceDriverMetal::timestamp_query_result_to_time(uint64_t p_result) {
2292 return p_result;
2293 }
2294
2295 void RenderingDeviceDriverMetal::command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) {
2296 }
2297
2298 void RenderingDeviceDriverMetal::command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) {
2299 }
2300
2301 #pragma mark - Labels
2302
2303 void RenderingDeviceDriverMetal::command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) {
2304 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
2305 cb->begin_label(p_label_name, p_color);
2306 }
2307
2308 void RenderingDeviceDriverMetal::command_end_label(CommandBufferID p_cmd_buffer) {
2309 MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
2310 cb->end_label();
2311 }
2312
2313 #pragma mark - Debug
2314
2315 void RenderingDeviceDriverMetal::command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) {
2316 // TODO: Implement.
2317 }
2318
2319 #pragma mark - Submission
2320
2321 void RenderingDeviceDriverMetal::begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) {
2322 _frame_index = p_frame_index;
2323 _frames_drawn = p_frames_drawn;
2324 }
2325
2326 void RenderingDeviceDriverMetal::end_segment() {
2327 }
2328
2329 #pragma mark - Misc
2330
2331 void RenderingDeviceDriverMetal::set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) {
2332 switch (p_type) {
2333 case OBJECT_TYPE_TEXTURE: {
2334 id<MTLTexture> tex = rid::get(p_driver_id);
2335 tex.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
2336 } break;
2337 case OBJECT_TYPE_SAMPLER: {
2338 // Can't set label after creation.
2339 } break;
2340 case OBJECT_TYPE_BUFFER: {
2341 const BufferInfo *buf_info = (const BufferInfo *)p_driver_id.id;
2342 buf_info->metal_buffer.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
2343 } break;
2344 case OBJECT_TYPE_SHADER: {
2345 NSString *label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
2346 MDShader *shader = (MDShader *)(p_driver_id.id);
2347 if (MDRenderShader *rs = dynamic_cast<MDRenderShader *>(shader); rs != nullptr) {
2348 [rs->vert setLabel:label];
2349 [rs->frag setLabel:label];
2350 } else if (MDComputeShader *cs = dynamic_cast<MDComputeShader *>(shader); cs != nullptr) {
2351 [cs->kernel setLabel:label];
2352 } else {
2353 DEV_ASSERT(false);
2354 }
2355 } break;
2356 case OBJECT_TYPE_UNIFORM_SET: {
2357 MDUniformSet *set = (MDUniformSet *)(p_driver_id.id);
2358 set->arg_buffer.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
2359 } break;
2360 case OBJECT_TYPE_PIPELINE: {
2361 // Can't set label after creation.
2362 } break;
2363 default: {
2364 DEV_ASSERT(false);
2365 }
2366 }
2367 }
2368
2369 uint64_t RenderingDeviceDriverMetal::get_resource_native_handle(DriverResource p_type, ID p_driver_id) {
2370 switch (p_type) {
2371 case DRIVER_RESOURCE_LOGICAL_DEVICE: {
2372 return (uint64_t)(uintptr_t)(__bridge void *)device;
2373 }
2374 case DRIVER_RESOURCE_PHYSICAL_DEVICE: {
2375 return 0;
2376 }
2377 case DRIVER_RESOURCE_TOPMOST_OBJECT: {
2378 return 0;
2379 }
2380 case DRIVER_RESOURCE_COMMAND_QUEUE: {
2381 return (uint64_t)(uintptr_t)(__bridge void *)device_queue;
2382 }
2383 case DRIVER_RESOURCE_QUEUE_FAMILY: {
2384 return 0;
2385 }
2386 case DRIVER_RESOURCE_TEXTURE: {
2387 return p_driver_id.id;
2388 }
2389 case DRIVER_RESOURCE_TEXTURE_VIEW: {
2390 return p_driver_id.id;
2391 }
2392 case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: {
2393 return 0;
2394 }
2395 case DRIVER_RESOURCE_SAMPLER: {
2396 return p_driver_id.id;
2397 }
2398 case DRIVER_RESOURCE_UNIFORM_SET: {
2399 return 0;
2400 }
2401 case DRIVER_RESOURCE_BUFFER: {
2402 return p_driver_id.id;
2403 }
2404 case DRIVER_RESOURCE_COMPUTE_PIPELINE: {
2405 MDComputePipeline *pipeline = (MDComputePipeline *)(p_driver_id.id);
2406 return (uint64_t)(uintptr_t)(__bridge void *)pipeline->state;
2407 }
2408 case DRIVER_RESOURCE_RENDER_PIPELINE: {
2409 MDRenderPipeline *pipeline = (MDRenderPipeline *)(p_driver_id.id);
2410 return (uint64_t)(uintptr_t)(__bridge void *)pipeline->state;
2411 }
2412 default: {
2413 return 0;
2414 }
2415 }
2416 }
2417
2418 uint64_t RenderingDeviceDriverMetal::get_total_memory_used() {
2419 return device.currentAllocatedSize;
2420 }
2421
2422 uint64_t RenderingDeviceDriverMetal::get_lazily_memory_used() {
2423 return 0; // TODO: Track this (grep for memoryless in Godot's Metal backend).
2424 }
2425
2426 uint64_t RenderingDeviceDriverMetal::limit_get(Limit p_limit) {
2427 MetalDeviceProperties const &props = (*device_properties);
2428 MetalLimits const &limits = props.limits;
2429 uint64_t safe_unbounded = ((uint64_t)1 << 30);
2430 #if defined(DEV_ENABLED)
2431 #define UNKNOWN(NAME) \
2432 case NAME: \
2433 WARN_PRINT_ONCE("Returning maximum value for unknown limit " #NAME "."); \
2434 return safe_unbounded;
2435 #else
2436 #define UNKNOWN(NAME) \
2437 case NAME: \
2438 return safe_unbounded
2439 #endif
2440
2441 // clang-format off
2442 switch (p_limit) {
2443 case LIMIT_MAX_BOUND_UNIFORM_SETS:
2444 return limits.maxBoundDescriptorSets;
2445 case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS:
2446 return limits.maxColorAttachments;
2447 case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET:
2448 return limits.maxTexturesPerArgumentBuffer;
2449 case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET:
2450 return limits.maxSamplersPerArgumentBuffer;
2451 case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET:
2452 return limits.maxBuffersPerArgumentBuffer;
2453 case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET:
2454 return limits.maxTexturesPerArgumentBuffer;
2455 case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET:
2456 return limits.maxBuffersPerArgumentBuffer;
2457 case LIMIT_MAX_DRAW_INDEXED_INDEX:
2458 return limits.maxDrawIndexedIndexValue;
2459 case LIMIT_MAX_FRAMEBUFFER_HEIGHT:
2460 return limits.maxFramebufferHeight;
2461 case LIMIT_MAX_FRAMEBUFFER_WIDTH:
2462 return limits.maxFramebufferWidth;
2463 case LIMIT_MAX_TEXTURE_ARRAY_LAYERS:
2464 return limits.maxImageArrayLayers;
2465 case LIMIT_MAX_TEXTURE_SIZE_1D:
2466 return limits.maxImageDimension1D;
2467 case LIMIT_MAX_TEXTURE_SIZE_2D:
2468 return limits.maxImageDimension2D;
2469 case LIMIT_MAX_TEXTURE_SIZE_3D:
2470 return limits.maxImageDimension3D;
2471 case LIMIT_MAX_TEXTURE_SIZE_CUBE:
2472 return limits.maxImageDimensionCube;
2473 case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
2474 return limits.maxTexturesPerArgumentBuffer;
2475 case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE:
2476 return limits.maxSamplersPerArgumentBuffer;
2477 case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE:
2478 return limits.maxBuffersPerArgumentBuffer;
2479 case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE:
2480 return limits.maxTexturesPerArgumentBuffer;
2481 case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE:
2482 return limits.maxBuffersPerArgumentBuffer;
2483 case LIMIT_MAX_PUSH_CONSTANT_SIZE:
2484 return limits.maxBufferLength;
2485 case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
2486 return limits.maxBufferLength;
2487 case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET:
2488 return limits.maxVertexDescriptorLayoutStride;
2489 case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES:
2490 return limits.maxVertexInputAttributes;
2491 case LIMIT_MAX_VERTEX_INPUT_BINDINGS:
2492 return limits.maxVertexInputBindings;
2493 case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE:
2494 return limits.maxVertexInputBindingStride;
2495 case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
2496 return limits.minUniformBufferOffsetAlignment;
2497 case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
2498 return limits.maxComputeWorkGroupCount.width;
2499 case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
2500 return limits.maxComputeWorkGroupCount.height;
2501 case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
2502 return limits.maxComputeWorkGroupCount.depth;
2503 case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS:
2504 return std::max({ limits.maxThreadsPerThreadGroup.width, limits.maxThreadsPerThreadGroup.height, limits.maxThreadsPerThreadGroup.depth });
2505 case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
2506 return limits.maxThreadsPerThreadGroup.width;
2507 case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
2508 return limits.maxThreadsPerThreadGroup.height;
2509 case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
2510 return limits.maxThreadsPerThreadGroup.depth;
2511 case LIMIT_MAX_COMPUTE_SHARED_MEMORY_SIZE:
2512 return limits.maxThreadGroupMemoryAllocation;
2513 case LIMIT_MAX_VIEWPORT_DIMENSIONS_X:
2514 return limits.maxViewportDimensionX;
2515 case LIMIT_MAX_VIEWPORT_DIMENSIONS_Y:
2516 return limits.maxViewportDimensionY;
2517 case LIMIT_SUBGROUP_SIZE:
2518 // MoltenVK sets the subgroupSize to the same as the maxSubgroupSize.
2519 return limits.maxSubgroupSize;
2520 case LIMIT_SUBGROUP_MIN_SIZE:
2521 return limits.minSubgroupSize;
2522 case LIMIT_SUBGROUP_MAX_SIZE:
2523 return limits.maxSubgroupSize;
2524 case LIMIT_SUBGROUP_IN_SHADERS:
2525 return (uint64_t)limits.subgroupSupportedShaderStages;
2526 case LIMIT_SUBGROUP_OPERATIONS:
2527 return (uint64_t)limits.subgroupSupportedOperations;
2528 case LIMIT_METALFX_TEMPORAL_SCALER_MIN_SCALE:
2529 return (uint64_t)((1.0 / limits.temporalScalerInputContentMaxScale) * 1000'000);
2530 case LIMIT_METALFX_TEMPORAL_SCALER_MAX_SCALE:
2531 return (uint64_t)((1.0 / limits.temporalScalerInputContentMinScale) * 1000'000);
2532 case LIMIT_MAX_SHADER_VARYINGS:
2533 return limits.maxShaderVaryings;
2534 default: {
2535 #ifdef DEV_ENABLED
2536 WARN_PRINT("Returning maximum value for unknown limit " + itos(p_limit) + ".");
2537 #endif
2538 return safe_unbounded;
2539 }
2540 }
2541 // clang-format on
2542 return 0;
2543 }
2544
2545 uint64_t RenderingDeviceDriverMetal::api_trait_get(ApiTrait p_trait) {
2546 switch (p_trait) {
2547 case API_TRAIT_HONORS_PIPELINE_BARRIERS:
2548 return false;
2549 case API_TRAIT_CLEARS_WITH_COPY_ENGINE:
2550 return false;
2551 default:
2552 return RenderingDeviceDriver::api_trait_get(p_trait);
2553 }
2554 }
2555
2556 bool RenderingDeviceDriverMetal::has_feature(Features p_feature) {
2557 switch (p_feature) {
2558 case SUPPORTS_HALF_FLOAT:
2559 return true;
2560 case SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS:
2561 return true;
2562 case SUPPORTS_BUFFER_DEVICE_ADDRESS:
2563 return device_properties->features.supports_gpu_address;
2564 case SUPPORTS_METALFX_SPATIAL:
2565 return device_properties->features.metal_fx_spatial;
2566 case SUPPORTS_METALFX_TEMPORAL:
2567 return device_properties->features.metal_fx_temporal;
2568 case SUPPORTS_IMAGE_ATOMIC_32_BIT:
2569 return device_properties->features.supports_native_image_atomics;
2570 case SUPPORTS_VULKAN_MEMORY_MODEL:
2571 return true;
2572 case SUPPORTS_POINT_SIZE:
2573 return true;
2574 default:
2575 return false;
2576 }
2577 }
2578
2579 const RDD::MultiviewCapabilities &RenderingDeviceDriverMetal::get_multiview_capabilities() {
2580 return multiview_capabilities;
2581 }
2582
2583 const RDD::FragmentShadingRateCapabilities &RenderingDeviceDriverMetal::get_fragment_shading_rate_capabilities() {
2584 return fsr_capabilities;
2585 }
2586
2587 const RDD::FragmentDensityMapCapabilities &RenderingDeviceDriverMetal::get_fragment_density_map_capabilities() {
2588 return fdm_capabilities;
2589 }
2590
2591 String RenderingDeviceDriverMetal::get_api_version() const {
2592 return vformat("%d.%d", capabilities.version_major, capabilities.version_minor);
2593 }
2594
2595 String RenderingDeviceDriverMetal::get_pipeline_cache_uuid() const {
2596 return pipeline_cache_id;
2597 }
2598
2599 const RDD::Capabilities &RenderingDeviceDriverMetal::get_capabilities() const {
2600 return capabilities;
2601 }
2602
2603 bool RenderingDeviceDriverMetal::is_composite_alpha_supported(CommandQueueID p_queue) const {
2604 // The CAMetalLayer.opaque property is configured according to this global setting.
2605 return OS::get_singleton()->is_layered_allowed();
2606 }
2607
2608 size_t RenderingDeviceDriverMetal::get_texel_buffer_alignment_for_format(RDD::DataFormat p_format) const {
2609 return [device minimumLinearTextureAlignmentForPixelFormat:pixel_formats->getMTLPixelFormat(p_format)];
2610 }
2611
2612 size_t RenderingDeviceDriverMetal::get_texel_buffer_alignment_for_format(MTLPixelFormat p_format) const {
2613 return [device minimumLinearTextureAlignmentForPixelFormat:p_format];
2614 }
2615
2616 /******************/
2617
2618 RenderingDeviceDriverMetal::RenderingDeviceDriverMetal(RenderingContextDriverMetal *p_context_driver) :
2619 context_driver(p_context_driver) {
2620 DEV_ASSERT(p_context_driver != nullptr);
2621
2622 #if TARGET_OS_OSX
2623 if (String res = OS::get_singleton()->get_environment("GODOT_MTL_SHADER_LOAD_STRATEGY"); res == U"lazy") {
2624 _shader_load_strategy = ShaderLoadStrategy::LAZY;
2625 }
2626 #else
2627 // Always use the lazy strategy on other OSs like iOS, tvOS, or visionOS.
2628 _shader_load_strategy = ShaderLoadStrategy::LAZY;
2629 #endif
2630 }
2631
2632 RenderingDeviceDriverMetal::~RenderingDeviceDriverMetal() {
2633 for (MDCommandBuffer *cb : command_buffers) {
2634 delete cb;
2635 }
2636
2637 for (KeyValue<SHA256Digest, ShaderCacheEntry *> &kv : _shader_cache) {
2638 memdelete(kv.value);
2639 }
2640
2641 if (shader_container_format != nullptr) {
2642 memdelete(shader_container_format);
2643 }
2644
2645 if (pixel_formats != nullptr) {
2646 memdelete(pixel_formats);
2647 }
2648
2649 if (device_properties != nullptr) {
2650 memdelete(device_properties);
2651 }
2652 }
2653
2654 #pragma mark - Initialization
2655
2656 Error RenderingDeviceDriverMetal::_create_device() {
2657 device = context_driver->get_metal_device();
2658
2659 device_queue = [device newCommandQueue];
2660 ERR_FAIL_NULL_V(device_queue, ERR_CANT_CREATE);
2661
2662 device_scope = [MTLCaptureManager.sharedCaptureManager newCaptureScopeWithCommandQueue:device_queue];
2663 device_scope.label = @"Godot Frame";
2664 [device_scope beginScope]; // Allow Xcode to capture the first frame, if desired.
2665
2666 resource_cache = std::make_unique<MDResourceCache>(this);
2667
2668 return OK;
2669 }
2670
2671 void RenderingDeviceDriverMetal::_check_capabilities() {
2672 capabilities.device_family = DEVICE_METAL;
2673 parse_msl_version(device_properties->features.msl_target_version, capabilities.version_major, capabilities.version_minor);
2674 }
2675
2676 API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
2677 static MetalDeviceProfile device_profile_from_properties(MetalDeviceProperties *p_device_properties) {
2678 using DP = MetalDeviceProfile;
2679 NSOperatingSystemVersion os_version = NSProcessInfo.processInfo.operatingSystemVersion;
2680 MetalDeviceProfile res;
2681 res.min_os_version = MinOsVersion(os_version.majorVersion, os_version.minorVersion, os_version.patchVersion);
2682 #if TARGET_OS_OSX
2683 res.platform = DP::Platform::macOS;
2684 #else
2685 res.platform = DP::Platform::iOS;
2686 #endif
2687 res.features = {
2688 .msl_version = p_device_properties->features.msl_target_version,
2689 .use_argument_buffers = p_device_properties->features.argument_buffers_enabled(),
2690 .simdPermute = p_device_properties->features.simdPermute,
2691 };
2692
2693 // highestFamily will only be set to an Apple GPU family
2694 switch (p_device_properties->features.highestFamily) {
2695 case MTLGPUFamilyApple1:
2696 res.gpu = DP::GPU::Apple1;
2697 break;
2698 case MTLGPUFamilyApple2:
2699 res.gpu = DP::GPU::Apple2;
2700 break;
2701 case MTLGPUFamilyApple3:
2702 res.gpu = DP::GPU::Apple3;
2703 break;
2704 case MTLGPUFamilyApple4:
2705 res.gpu = DP::GPU::Apple4;
2706 break;
2707 case MTLGPUFamilyApple5:
2708 res.gpu = DP::GPU::Apple5;
2709 break;
2710 case MTLGPUFamilyApple6:
2711 res.gpu = DP::GPU::Apple6;
2712 break;
2713 case MTLGPUFamilyApple7:
2714 res.gpu = DP::GPU::Apple7;
2715 break;
2716 case MTLGPUFamilyApple8:
2717 res.gpu = DP::GPU::Apple8;
2718 break;
2719 case MTLGPUFamilyApple9:
2720 res.gpu = DP::GPU::Apple9;
2721 break;
2722 default: {
2723 // Programming error if the default case is hit.
2724 CRASH_NOW_MSG("Unsupported GPU family");
2725 } break;
2726 }
2727
2728 return res;
2729 }
2730
2731 Error RenderingDeviceDriverMetal::initialize(uint32_t p_device_index, uint32_t p_frame_count) {
2732 context_device = context_driver->device_get(p_device_index);
2733 Error err = _create_device();
2734 ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
2735
2736 device_properties = memnew(MetalDeviceProperties(device));
2737 device_profile = device_profile_from_properties(device_properties);
2738 shader_container_format = memnew(RenderingShaderContainerFormatMetal(&device_profile));
2739
2740 _check_capabilities();
2741
2742 _frame_count = p_frame_count;
2743
2744 // Set the pipeline cache ID based on the Metal version.
2745 pipeline_cache_id = "metal-driver-" + get_api_version();
2746
2747 pixel_formats = memnew(PixelFormats(device, device_properties->features));
2748 if (device_properties->features.layeredRendering) {
2749 multiview_capabilities.is_supported = true;
2750 multiview_capabilities.max_view_count = device_properties->limits.maxViewports;
2751 // NOTE: I'm not sure what the limit is as I don't see it referenced anywhere
2752 multiview_capabilities.max_instance_count = UINT32_MAX;
2753
2754 print_verbose("- Metal multiview supported:");
2755 print_verbose(" max view count: " + itos(multiview_capabilities.max_view_count));
2756 print_verbose(" max instances: " + itos(multiview_capabilities.max_instance_count));
2757 } else {
2758 print_verbose("- Metal multiview not supported");
2759 }
2760
2761 // The Metal renderer requires Apple4 family. This is 2017 era A11 chips and newer.
2762 if (device_properties->features.highestFamily < MTLGPUFamilyApple4) {
2763 String error_string = vformat("Your Apple GPU does not support the following features, which are required to use Metal-based renderers in Godot:\n\n");
2764 if (!device_properties->features.imageCubeArray) {
2765 error_string += "- No support for image cube arrays.\n";
2766 }
2767
2768 #if defined(APPLE_EMBEDDED_ENABLED)
2769 // Apple Embedded platforms exports currently don't exit themselves when this method returns `ERR_CANT_CREATE`.
2770 OS::get_singleton()->alert(error_string + "\nClick OK to exit (black screen will be visible).");
2771 #else
2772 OS::get_singleton()->alert(error_string + "\nClick OK to exit.");
2773 #endif
2774
2775 return ERR_CANT_CREATE;
2776 }
2777
2778 return OK;
2779 }
2780
2781 const RenderingShaderContainerFormat &RenderingDeviceDriverMetal::get_shader_container_format() const {
2782 return *shader_container_format;
2783 }