-
-
Notifications
You must be signed in to change notification settings - Fork 21.9k
/
Copy pathrendering_device_driver_metal.mm
3974 lines (3349 loc) · 143 KB
/
rendering_device_driver_metal.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************************/
/* rendering_device_driver_metal.mm */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
/**************************************************************************/
/* */
/* Portions of this code were derived from MoltenVK. */
/* */
/* Copyright (c) 2015-2023 The Brenwill Workshop Ltd. */
/* (http://www.brenwill.com) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/**************************************************************************/
#import "rendering_device_driver_metal.h"
#import "pixel_formats.h"
#import "rendering_context_driver_metal.h"
#import "core/io/compression.h"
#import "core/io/marshalls.h"
#import "core/string/ustring.h"
#import "core/templates/hash_map.h"
#import <Metal/MTLTexture.h>
#import <Metal/Metal.h>
#import <os/log.h>
#import <os/signpost.h>
#import <spirv_msl.hpp>
#import <spirv_parser.hpp>
#pragma mark - Logging
os_log_t LOG_DRIVER;
// Used for dynamic tracing.
os_log_t LOG_INTERVALS;
__attribute__((constructor)) static void InitializeLogging(void) {
LOG_DRIVER = os_log_create("org.godotengine.godot.metal", OS_LOG_CATEGORY_POINTS_OF_INTEREST);
LOG_INTERVALS = os_log_create("org.godotengine.godot.metal", "events");
}
/*****************/
/**** GENERIC ****/
/*****************/
// RDD::CompareOperator == VkCompareOp.
static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_NEVER, MTLCompareFunctionNever));
static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_LESS, MTLCompareFunctionLess));
static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_EQUAL, MTLCompareFunctionEqual));
static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_LESS_OR_EQUAL, MTLCompareFunctionLessEqual));
static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_GREATER, MTLCompareFunctionGreater));
static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_NOT_EQUAL, MTLCompareFunctionNotEqual));
static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_GREATER_OR_EQUAL, MTLCompareFunctionGreaterEqual));
static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_ALWAYS, MTLCompareFunctionAlways));
_FORCE_INLINE_ MTLSize mipmapLevelSizeFromTexture(id<MTLTexture> p_tex, NSUInteger p_level) {
MTLSize lvlSize;
lvlSize.width = MAX(p_tex.width >> p_level, 1UL);
lvlSize.height = MAX(p_tex.height >> p_level, 1UL);
lvlSize.depth = MAX(p_tex.depth >> p_level, 1UL);
return lvlSize;
}
_FORCE_INLINE_ MTLSize mipmapLevelSizeFromSize(MTLSize p_size, NSUInteger p_level) {
if (p_level == 0) {
return p_size;
}
MTLSize lvlSize;
lvlSize.width = MAX(p_size.width >> p_level, 1UL);
lvlSize.height = MAX(p_size.height >> p_level, 1UL);
lvlSize.depth = MAX(p_size.depth >> p_level, 1UL);
return lvlSize;
}
_FORCE_INLINE_ static bool operator==(MTLSize p_a, MTLSize p_b) {
return p_a.width == p_b.width && p_a.height == p_b.height && p_a.depth == p_b.depth;
}
/*****************/
/**** BUFFERS ****/
/*****************/
RDD::BufferID RenderingDeviceDriverMetal::buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) {
MTLResourceOptions options = MTLResourceHazardTrackingModeTracked;
switch (p_allocation_type) {
case MEMORY_ALLOCATION_TYPE_CPU:
options |= MTLResourceStorageModeShared;
break;
case MEMORY_ALLOCATION_TYPE_GPU:
options |= MTLResourceStorageModePrivate;
break;
}
id<MTLBuffer> obj = [device newBufferWithLength:p_size options:options];
ERR_FAIL_NULL_V_MSG(obj, BufferID(), "Can't create buffer of size: " + itos(p_size));
return rid::make(obj);
}
bool RenderingDeviceDriverMetal::buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) {
// Nothing to do.
return true;
}
void RenderingDeviceDriverMetal::buffer_free(BufferID p_buffer) {
rid::release(p_buffer);
}
uint64_t RenderingDeviceDriverMetal::buffer_get_allocation_size(BufferID p_buffer) {
id<MTLBuffer> obj = rid::get(p_buffer);
return obj.allocatedSize;
}
uint8_t *RenderingDeviceDriverMetal::buffer_map(BufferID p_buffer) {
id<MTLBuffer> obj = rid::get(p_buffer);
ERR_FAIL_COND_V_MSG(obj.storageMode != MTLStorageModeShared, nullptr, "Unable to map private buffers");
return (uint8_t *)obj.contents;
}
void RenderingDeviceDriverMetal::buffer_unmap(BufferID p_buffer) {
// Nothing to do.
}
#pragma mark - Texture
#pragma mark - Format Conversions
static const MTLTextureType TEXTURE_TYPE[RD::TEXTURE_TYPE_MAX] = {
MTLTextureType1D,
MTLTextureType2D,
MTLTextureType3D,
MTLTextureTypeCube,
MTLTextureType1DArray,
MTLTextureType2DArray,
MTLTextureTypeCubeArray,
};
RenderingDeviceDriverMetal::Result<bool> RenderingDeviceDriverMetal::is_valid_linear(TextureFormat const &p_format) const {
if (!flags::any(p_format.usage_bits, TEXTURE_USAGE_CPU_READ_BIT)) {
return false;
}
PixelFormats &pf = *pixel_formats;
MTLFormatType ft = pf.getFormatType(p_format.format);
// Requesting a linear format, which has further restrictions, similar to Vulkan
// when specifying VK_IMAGE_TILING_LINEAR.
ERR_FAIL_COND_V_MSG(p_format.texture_type != TEXTURE_TYPE_2D, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must be 2D");
ERR_FAIL_COND_V_MSG(ft != MTLFormatType::DepthStencil, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must not be a depth/stencil format");
ERR_FAIL_COND_V_MSG(ft != MTLFormatType::Compressed, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must not be a compressed format");
ERR_FAIL_COND_V_MSG(p_format.mipmaps != 1, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must have 1 mipmap level");
ERR_FAIL_COND_V_MSG(p_format.array_layers != 1, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must have 1 array layer");
ERR_FAIL_COND_V_MSG(p_format.samples != TEXTURE_SAMPLES_1, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must have 1 sample");
return true;
}
RDD::TextureID RenderingDeviceDriverMetal::texture_create(const TextureFormat &p_format, const TextureView &p_view) {
MTLTextureDescriptor *desc = [MTLTextureDescriptor new];
desc.textureType = TEXTURE_TYPE[p_format.texture_type];
PixelFormats &formats = *pixel_formats;
desc.pixelFormat = formats.getMTLPixelFormat(p_format.format);
MTLFmtCaps format_caps = formats.getCapabilities(desc.pixelFormat);
desc.width = p_format.width;
desc.height = p_format.height;
desc.depth = p_format.depth;
desc.mipmapLevelCount = p_format.mipmaps;
if (p_format.texture_type == TEXTURE_TYPE_1D_ARRAY ||
p_format.texture_type == TEXTURE_TYPE_2D_ARRAY) {
desc.arrayLength = p_format.array_layers;
} else if (p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY) {
desc.arrayLength = p_format.array_layers / 6;
}
// TODO(sgc): Evaluate lossy texture support (perhaps as a project option?)
// https://developer.apple.com/videos/play/tech-talks/10876?time=459
// desc.compressionType = MTLTextureCompressionTypeLossy;
if (p_format.samples > TEXTURE_SAMPLES_1) {
SampleCount supported = (*metal_device_properties).find_nearest_supported_sample_count(p_format.samples);
if (supported > SampleCount1) {
bool ok = p_format.texture_type == TEXTURE_TYPE_2D || p_format.texture_type == TEXTURE_TYPE_2D_ARRAY;
if (ok) {
switch (p_format.texture_type) {
case TEXTURE_TYPE_2D:
desc.textureType = MTLTextureType2DMultisample;
break;
case TEXTURE_TYPE_2D_ARRAY:
desc.textureType = MTLTextureType2DMultisampleArray;
break;
default:
break;
}
desc.sampleCount = (NSUInteger)supported;
if (p_format.mipmaps > 1) {
// For a buffer-backed or multi-sample texture, the value must be 1.
WARN_PRINT("mipmaps == 1 for multi-sample textures");
desc.mipmapLevelCount = 1;
}
} else {
WARN_PRINT("Unsupported multi-sample texture type; disabling multi-sample");
}
}
}
static const MTLTextureSwizzle COMPONENT_SWIZZLE[TEXTURE_SWIZZLE_MAX] = {
static_cast<MTLTextureSwizzle>(255), // IDENTITY
MTLTextureSwizzleZero,
MTLTextureSwizzleOne,
MTLTextureSwizzleRed,
MTLTextureSwizzleGreen,
MTLTextureSwizzleBlue,
MTLTextureSwizzleAlpha,
};
MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
p_view.swizzle_r != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_r] : MTLTextureSwizzleRed,
p_view.swizzle_g != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_g] : MTLTextureSwizzleGreen,
p_view.swizzle_b != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_b] : MTLTextureSwizzleBlue,
p_view.swizzle_a != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_a] : MTLTextureSwizzleAlpha);
// Represents a swizzle operation that is a no-op.
static MTLTextureSwizzleChannels IDENTITY_SWIZZLE = {
.red = MTLTextureSwizzleRed,
.green = MTLTextureSwizzleGreen,
.blue = MTLTextureSwizzleBlue,
.alpha = MTLTextureSwizzleAlpha,
};
bool no_swizzle = memcmp(&IDENTITY_SWIZZLE, &swizzle, sizeof(MTLTextureSwizzleChannels)) == 0;
if (!no_swizzle) {
desc.swizzle = swizzle;
}
// Usage.
MTLResourceOptions options = MTLResourceCPUCacheModeDefaultCache | MTLResourceHazardTrackingModeTracked;
if (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) {
options |= MTLResourceStorageModeShared;
} else {
options |= MTLResourceStorageModePrivate;
}
desc.resourceOptions = options;
if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) {
desc.usage |= MTLTextureUsageShaderRead;
}
if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) {
desc.usage |= MTLTextureUsageShaderWrite;
}
if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT) {
desc.usage |= MTLTextureUsageShaderWrite;
}
bool can_be_attachment = flags::any(format_caps, (kMTLFmtCapsColorAtt | kMTLFmtCapsDSAtt));
if (flags::any(p_format.usage_bits, TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) &&
can_be_attachment) {
desc.usage |= MTLTextureUsageRenderTarget;
}
if (p_format.usage_bits & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
desc.usage |= MTLTextureUsageShaderRead;
}
if (p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {
ERR_FAIL_V_MSG(RDD::TextureID(), "unsupported: TEXTURE_USAGE_VRS_ATTACHMENT_BIT");
}
if (flags::any(p_format.usage_bits, TEXTURE_USAGE_CAN_UPDATE_BIT | TEXTURE_USAGE_CAN_COPY_TO_BIT) &&
can_be_attachment && no_swizzle) {
// Per MoltenVK, can be cleared as a render attachment.
desc.usage |= MTLTextureUsageRenderTarget;
}
if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
// Covered by blits.
}
// Create texture views with a different component layout.
if (!p_format.shareable_formats.is_empty()) {
desc.usage |= MTLTextureUsagePixelFormatView;
}
// Allocate memory.
bool is_linear;
{
Result<bool> is_linear_or_err = is_valid_linear(p_format);
ERR_FAIL_COND_V(std::holds_alternative<Error>(is_linear_or_err), TextureID());
is_linear = std::get<bool>(is_linear_or_err);
}
// Check if it is a linear format for atomic operations and therefore needs a buffer,
// as generally Metal does not support atomic operations on textures.
bool needs_buffer = is_linear || (p_format.array_layers == 1 && p_format.mipmaps == 1 && p_format.texture_type == TEXTURE_TYPE_2D && flags::any(p_format.usage_bits, TEXTURE_USAGE_STORAGE_BIT) && (p_format.format == DATA_FORMAT_R32_UINT || p_format.format == DATA_FORMAT_R32_SINT));
id<MTLTexture> obj = nil;
if (needs_buffer) {
// Linear textures are restricted to 2D textures, a single mipmap level and a single array layer.
MTLPixelFormat pixel_format = desc.pixelFormat;
size_t row_alignment = get_texel_buffer_alignment_for_format(p_format.format);
size_t bytes_per_row = formats.getBytesPerRow(pixel_format, p_format.width);
bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
size_t bytes_per_layer = formats.getBytesPerLayer(pixel_format, bytes_per_row, p_format.height);
size_t byte_count = bytes_per_layer * p_format.depth * p_format.array_layers;
id<MTLBuffer> buf = [device newBufferWithLength:byte_count options:options];
obj = [buf newTextureWithDescriptor:desc offset:0 bytesPerRow:bytes_per_row];
} else {
obj = [device newTextureWithDescriptor:desc];
}
ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create texture.");
return rid::make(obj);
}
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) {
id<MTLTexture> obj = (__bridge id<MTLTexture>)(void *)(uintptr_t)p_native_texture;
// We only need to create a RDD::TextureID for an existing, natively-provided texture.
return rid::make(obj);
}
RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared(TextureID p_original_texture, const TextureView &p_view) {
id<MTLTexture> src_texture = rid::get(p_original_texture);
#if DEV_ENABLED
if (src_texture.sampleCount > 1) {
// TODO(sgc): is it ok to create a shared texture from a multi-sample texture?
WARN_PRINT("Is it safe to create a shared texture from multi-sample texture?");
}
#endif
MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_view.format);
static const MTLTextureSwizzle component_swizzle[TEXTURE_SWIZZLE_MAX] = {
static_cast<MTLTextureSwizzle>(255), // IDENTITY
MTLTextureSwizzleZero,
MTLTextureSwizzleOne,
MTLTextureSwizzleRed,
MTLTextureSwizzleGreen,
MTLTextureSwizzleBlue,
MTLTextureSwizzleAlpha,
};
#define SWIZZLE(C, CHAN) (p_view.swizzle_##C != TEXTURE_SWIZZLE_IDENTITY ? component_swizzle[p_view.swizzle_##C] : MTLTextureSwizzle##CHAN)
MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
SWIZZLE(r, Red),
SWIZZLE(g, Green),
SWIZZLE(b, Blue),
SWIZZLE(a, Alpha));
#undef SWIZZLE
id<MTLTexture> obj = [src_texture newTextureViewWithPixelFormat:format
textureType:src_texture.textureType
levels:NSMakeRange(0, src_texture.mipmapLevelCount)
slices:NSMakeRange(0, src_texture.arrayLength)
swizzle:swizzle];
ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create shared texture");
return rid::make(obj);
}
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) {
id<MTLTexture> src_texture = rid::get(p_original_texture);
static const MTLTextureType VIEW_TYPES[] = {
MTLTextureType1D, // MTLTextureType1D
MTLTextureType1D, // MTLTextureType1DArray
MTLTextureType2D, // MTLTextureType2D
MTLTextureType2D, // MTLTextureType2DArray
MTLTextureType2D, // MTLTextureType2DMultisample
MTLTextureType2D, // MTLTextureTypeCube
MTLTextureType2D, // MTLTextureTypeCubeArray
MTLTextureType2D, // MTLTextureType3D
MTLTextureType2D, // MTLTextureType2DMultisampleArray
};
MTLTextureType textureType = VIEW_TYPES[src_texture.textureType];
switch (p_slice_type) {
case TEXTURE_SLICE_2D: {
textureType = MTLTextureType2D;
} break;
case TEXTURE_SLICE_3D: {
textureType = MTLTextureType3D;
} break;
case TEXTURE_SLICE_CUBEMAP: {
textureType = MTLTextureTypeCube;
} break;
case TEXTURE_SLICE_2D_ARRAY: {
textureType = MTLTextureType2DArray;
} break;
case TEXTURE_SLICE_MAX: {
ERR_FAIL_V_MSG(TextureID(), "Invalid texture slice type");
} break;
}
MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_view.format);
static const MTLTextureSwizzle component_swizzle[TEXTURE_SWIZZLE_MAX] = {
static_cast<MTLTextureSwizzle>(255), // IDENTITY
MTLTextureSwizzleZero,
MTLTextureSwizzleOne,
MTLTextureSwizzleRed,
MTLTextureSwizzleGreen,
MTLTextureSwizzleBlue,
MTLTextureSwizzleAlpha,
};
#define SWIZZLE(C, CHAN) (p_view.swizzle_##C != TEXTURE_SWIZZLE_IDENTITY ? component_swizzle[p_view.swizzle_##C] : MTLTextureSwizzle##CHAN)
MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
SWIZZLE(r, Red),
SWIZZLE(g, Green),
SWIZZLE(b, Blue),
SWIZZLE(a, Alpha));
#undef SWIZZLE
id<MTLTexture> obj = [src_texture newTextureViewWithPixelFormat:format
textureType:textureType
levels:NSMakeRange(p_mipmap, p_mipmaps)
slices:NSMakeRange(p_layer, p_layers)
swizzle:swizzle];
ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create shared texture");
return rid::make(obj);
}
void RenderingDeviceDriverMetal::texture_free(TextureID p_texture) {
rid::release(p_texture);
}
uint64_t RenderingDeviceDriverMetal::texture_get_allocation_size(TextureID p_texture) {
id<MTLTexture> obj = rid::get(p_texture);
return obj.allocatedSize;
}
void RenderingDeviceDriverMetal::_get_sub_resource(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) const {
id<MTLTexture> obj = rid::get(p_texture);
*r_layout = {};
PixelFormats &pf = *pixel_formats;
size_t row_alignment = get_texel_buffer_alignment_for_format(obj.pixelFormat);
size_t offset = 0;
size_t array_layers = obj.arrayLength;
MTLSize size = MTLSizeMake(obj.width, obj.height, obj.depth);
MTLPixelFormat pixel_format = obj.pixelFormat;
// First skip over the mipmap levels.
for (uint32_t mipLvl = 0; mipLvl < p_subresource.mipmap; mipLvl++) {
MTLSize mip_size = mipmapLevelSizeFromSize(size, mipLvl);
size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mip_size.width);
bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mip_size.height);
offset += bytes_per_layer * mip_size.depth * array_layers;
}
// Get current mipmap.
MTLSize mip_size = mipmapLevelSizeFromSize(size, p_subresource.mipmap);
size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mip_size.width);
bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mip_size.height);
r_layout->size = bytes_per_layer * mip_size.depth;
r_layout->offset = offset + (r_layout->size * p_subresource.layer - 1);
r_layout->depth_pitch = bytes_per_layer;
r_layout->row_pitch = bytes_per_row;
r_layout->layer_pitch = r_layout->size * array_layers;
}
void RenderingDeviceDriverMetal::texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) {
id<MTLTexture> obj = rid::get(p_texture);
*r_layout = {};
if ((obj.resourceOptions & MTLResourceStorageModePrivate) != 0) {
MTLSize sz = MTLSizeMake(obj.width, obj.height, obj.depth);
PixelFormats &pf = *pixel_formats;
DataFormat format = pf.getDataFormat(obj.pixelFormat);
if (p_subresource.mipmap > 0) {
r_layout->offset = get_image_format_required_size(format, sz.width, sz.height, sz.depth, p_subresource.mipmap);
}
sz = mipmapLevelSizeFromSize(sz, p_subresource.mipmap);
uint32_t bw = 0, bh = 0;
get_compressed_image_format_block_dimensions(format, bw, bh);
uint32_t sbw = 0, sbh = 0;
r_layout->size = get_image_format_required_size(format, sz.width, sz.height, sz.depth, 1, &sbw, &sbh);
r_layout->row_pitch = r_layout->size / ((sbh / bh) * sz.depth);
r_layout->depth_pitch = r_layout->size / sz.depth;
r_layout->layer_pitch = r_layout->size / obj.arrayLength;
} else {
CRASH_NOW_MSG("need to calculate layout for shared texture");
}
}
uint8_t *RenderingDeviceDriverMetal::texture_map(TextureID p_texture, const TextureSubresource &p_subresource) {
id<MTLTexture> obj = rid::get(p_texture);
ERR_FAIL_NULL_V_MSG(obj.buffer, nullptr, "texture is not created from a buffer");
TextureCopyableLayout layout;
_get_sub_resource(p_texture, p_subresource, &layout);
return (uint8_t *)(obj.buffer.contents) + layout.offset;
PixelFormats &pf = *pixel_formats;
size_t row_alignment = get_texel_buffer_alignment_for_format(obj.pixelFormat);
size_t offset = 0;
size_t array_layers = obj.arrayLength;
MTLSize size = MTLSizeMake(obj.width, obj.height, obj.depth);
MTLPixelFormat pixel_format = obj.pixelFormat;
// First skip over the mipmap levels.
for (uint32_t mipLvl = 0; mipLvl < p_subresource.mipmap; mipLvl++) {
MTLSize mipExtent = mipmapLevelSizeFromSize(size, mipLvl);
size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mipExtent.width);
bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mipExtent.height);
offset += bytes_per_layer * mipExtent.depth * array_layers;
}
if (p_subresource.layer > 1) {
// Calculate offset to desired layer.
MTLSize mipExtent = mipmapLevelSizeFromSize(size, p_subresource.mipmap);
size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mipExtent.width);
bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mipExtent.height);
offset += bytes_per_layer * mipExtent.depth * (p_subresource.layer - 1);
}
// TODO: Confirm with rendering team that there is no other way Godot may attempt to map a texture with multiple mipmaps or array layers.
// NOTE: It is not possible to create a buffer-backed texture with mipmaps or array layers,
// as noted in the is_valid_linear function, so the offset calculation SHOULD always be zero.
// Given that, this code should be simplified.
return (uint8_t *)(obj.buffer.contents) + offset;
}
void RenderingDeviceDriverMetal::texture_unmap(TextureID p_texture) {
// Nothing to do.
}
BitField<RDD::TextureUsageBits> RenderingDeviceDriverMetal::texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) {
PixelFormats &pf = *pixel_formats;
if (pf.getMTLPixelFormat(p_format) == MTLPixelFormatInvalid) {
return 0;
}
MTLFmtCaps caps = pf.getCapabilities(p_format);
// Everything supported by default makes an all-or-nothing check easier for the caller.
BitField<RDD::TextureUsageBits> supported = INT64_MAX;
supported.clear_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT); // No VRS support for Metal.
if (!flags::any(caps, kMTLFmtCapsColorAtt)) {
supported.clear_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT);
}
if (!flags::any(caps, kMTLFmtCapsDSAtt)) {
supported.clear_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
}
if (!flags::any(caps, kMTLFmtCapsRead)) {
supported.clear_flag(TEXTURE_USAGE_SAMPLING_BIT);
}
if (!flags::any(caps, kMTLFmtCapsAtomic)) {
supported.clear_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT);
}
return supported;
}
bool RenderingDeviceDriverMetal::texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) {
r_raw_reinterpretation = false;
return true;
}
#pragma mark - Sampler
static const MTLCompareFunction COMPARE_OPERATORS[RD::COMPARE_OP_MAX] = {
MTLCompareFunctionNever,
MTLCompareFunctionLess,
MTLCompareFunctionEqual,
MTLCompareFunctionLessEqual,
MTLCompareFunctionGreater,
MTLCompareFunctionNotEqual,
MTLCompareFunctionGreaterEqual,
MTLCompareFunctionAlways,
};
static const MTLStencilOperation STENCIL_OPERATIONS[RD::STENCIL_OP_MAX] = {
MTLStencilOperationKeep,
MTLStencilOperationZero,
MTLStencilOperationReplace,
MTLStencilOperationIncrementClamp,
MTLStencilOperationDecrementClamp,
MTLStencilOperationInvert,
MTLStencilOperationIncrementWrap,
MTLStencilOperationDecrementWrap,
};
static const MTLBlendFactor BLEND_FACTORS[RD::BLEND_FACTOR_MAX] = {
MTLBlendFactorZero,
MTLBlendFactorOne,
MTLBlendFactorSourceColor,
MTLBlendFactorOneMinusSourceColor,
MTLBlendFactorDestinationColor,
MTLBlendFactorOneMinusDestinationColor,
MTLBlendFactorSourceAlpha,
MTLBlendFactorOneMinusSourceAlpha,
MTLBlendFactorDestinationAlpha,
MTLBlendFactorOneMinusDestinationAlpha,
MTLBlendFactorBlendColor,
MTLBlendFactorOneMinusBlendColor,
MTLBlendFactorBlendAlpha,
MTLBlendFactorOneMinusBlendAlpha,
MTLBlendFactorSourceAlphaSaturated,
MTLBlendFactorSource1Color,
MTLBlendFactorOneMinusSource1Color,
MTLBlendFactorSource1Alpha,
MTLBlendFactorOneMinusSource1Alpha,
};
static const MTLBlendOperation BLEND_OPERATIONS[RD::BLEND_OP_MAX] = {
MTLBlendOperationAdd,
MTLBlendOperationSubtract,
MTLBlendOperationReverseSubtract,
MTLBlendOperationMin,
MTLBlendOperationMax,
};
static const API_AVAILABLE(macos(11.0), ios(14.0)) MTLSamplerAddressMode ADDRESS_MODES[RD::SAMPLER_REPEAT_MODE_MAX] = {
MTLSamplerAddressModeRepeat,
MTLSamplerAddressModeMirrorRepeat,
MTLSamplerAddressModeClampToEdge,
MTLSamplerAddressModeClampToBorderColor,
MTLSamplerAddressModeMirrorClampToEdge,
};
static const API_AVAILABLE(macos(11.0), ios(14.0)) MTLSamplerBorderColor SAMPLER_BORDER_COLORS[RD::SAMPLER_BORDER_COLOR_MAX] = {
MTLSamplerBorderColorTransparentBlack,
MTLSamplerBorderColorTransparentBlack,
MTLSamplerBorderColorOpaqueBlack,
MTLSamplerBorderColorOpaqueBlack,
MTLSamplerBorderColorOpaqueWhite,
MTLSamplerBorderColorOpaqueWhite,
};
RDD::SamplerID RenderingDeviceDriverMetal::sampler_create(const SamplerState &p_state) {
MTLSamplerDescriptor *desc = [MTLSamplerDescriptor new];
desc.supportArgumentBuffers = YES;
desc.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
desc.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
desc.mipFilter = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMipFilterLinear : MTLSamplerMipFilterNearest;
desc.sAddressMode = ADDRESS_MODES[p_state.repeat_u];
desc.tAddressMode = ADDRESS_MODES[p_state.repeat_v];
desc.rAddressMode = ADDRESS_MODES[p_state.repeat_w];
if (p_state.use_anisotropy) {
desc.maxAnisotropy = p_state.anisotropy_max;
}
desc.compareFunction = COMPARE_OPERATORS[p_state.compare_op];
desc.lodMinClamp = p_state.min_lod;
desc.lodMaxClamp = p_state.max_lod;
desc.borderColor = SAMPLER_BORDER_COLORS[p_state.border_color];
desc.normalizedCoordinates = !p_state.unnormalized_uvw;
if (p_state.lod_bias != 0.0) {
WARN_VERBOSE("Metal does not support LOD bias for samplers.");
}
id<MTLSamplerState> obj = [device newSamplerStateWithDescriptor:desc];
ERR_FAIL_NULL_V_MSG(obj, SamplerID(), "newSamplerStateWithDescriptor failed");
return rid::make(obj);
}
void RenderingDeviceDriverMetal::sampler_free(SamplerID p_sampler) {
rid::release(p_sampler);
}
bool RenderingDeviceDriverMetal::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) {
switch (p_filter) {
case SAMPLER_FILTER_NEAREST:
return true;
case SAMPLER_FILTER_LINEAR: {
MTLFmtCaps caps = pixel_formats->getCapabilities(p_format);
return flags::any(caps, kMTLFmtCapsFilter);
}
}
}
#pragma mark - Vertex Array
RDD::VertexFormatID RenderingDeviceDriverMetal::vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) {
MTLVertexDescriptor *desc = MTLVertexDescriptor.vertexDescriptor;
for (uint32_t i = 0; i < p_vertex_attribs.size(); i++) {
VertexAttribute const &vf = p_vertex_attribs[i];
ERR_FAIL_COND_V_MSG(get_format_vertex_size(vf.format) == 0, VertexFormatID(),
"Data format for attachment (" + itos(i) + "), '" + FORMAT_NAMES[vf.format] + "', is not valid for a vertex array.");
desc.attributes[vf.location].format = pixel_formats->getMTLVertexFormat(vf.format);
desc.attributes[vf.location].offset = vf.offset;
uint32_t idx = get_metal_buffer_index_for_vertex_attribute_binding(i);
desc.attributes[vf.location].bufferIndex = idx;
if (vf.stride == 0) {
desc.layouts[idx].stepFunction = MTLVertexStepFunctionConstant;
desc.layouts[idx].stepRate = 0;
desc.layouts[idx].stride = pixel_formats->getBytesPerBlock(vf.format);
} else {
desc.layouts[idx].stepFunction = vf.frequency == VERTEX_FREQUENCY_VERTEX ? MTLVertexStepFunctionPerVertex : MTLVertexStepFunctionPerInstance;
desc.layouts[idx].stepRate = 1;
desc.layouts[idx].stride = vf.stride;
}
}
return rid::make(desc);
}
void RenderingDeviceDriverMetal::vertex_format_free(VertexFormatID p_vertex_format) {
rid::release(p_vertex_format);
}
#pragma mark - Barriers
void RenderingDeviceDriverMetal::command_pipeline_barrier(
CommandBufferID p_cmd_buffer,
BitField<PipelineStageBits> p_src_stages,
BitField<PipelineStageBits> p_dst_stages,
VectorView<MemoryBarrier> p_memory_barriers,
VectorView<BufferBarrier> p_buffer_barriers,
VectorView<TextureBarrier> p_texture_barriers) {
WARN_PRINT_ONCE("not implemented");
}
#pragma mark - Fences
RDD::FenceID RenderingDeviceDriverMetal::fence_create() {
Fence *fence = memnew(Fence);
return FenceID(fence);
}
Error RenderingDeviceDriverMetal::fence_wait(FenceID p_fence) {
Fence *fence = (Fence *)(p_fence.id);
// Wait forever, so this function is infallible.
dispatch_semaphore_wait(fence->semaphore, DISPATCH_TIME_FOREVER);
return OK;
}
void RenderingDeviceDriverMetal::fence_free(FenceID p_fence) {
Fence *fence = (Fence *)(p_fence.id);
memdelete(fence);
}
#pragma mark - Semaphores
RDD::SemaphoreID RenderingDeviceDriverMetal::semaphore_create() {
// Metal doesn't use semaphores, as their purpose within Godot is to ensure ordering of command buffer execution.
return SemaphoreID(1);
}
void RenderingDeviceDriverMetal::semaphore_free(SemaphoreID p_semaphore) {
}
#pragma mark - Queues
RDD::CommandQueueFamilyID RenderingDeviceDriverMetal::command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface) {
if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_GRAPHICS_BIT) || (p_surface != 0)) {
return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_GRAPHICS_BIT);
} else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_COMPUTE_BIT)) {
return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_COMPUTE_BIT);
} else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_TRANSFER_BIT)) {
return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_TRANSFER_BIT);
} else {
return CommandQueueFamilyID();
}
}
RDD::CommandQueueID RenderingDeviceDriverMetal::command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue) {
return CommandQueueID(1);
}
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) {
uint32_t size = p_cmd_buffers.size();
if (size == 0) {
return OK;
}
for (uint32_t i = 0; i < size - 1; i++) {
MDCommandBuffer *cmd_buffer = (MDCommandBuffer *)(p_cmd_buffers[i].id);
cmd_buffer->commit();
}
// The last command buffer will signal the fence and semaphores.
MDCommandBuffer *cmd_buffer = (MDCommandBuffer *)(p_cmd_buffers[size - 1].id);
Fence *fence = (Fence *)(p_cmd_fence.id);
if (fence != nullptr) {
[cmd_buffer->get_command_buffer() addCompletedHandler:^(id<MTLCommandBuffer> buffer) {
dispatch_semaphore_signal(fence->semaphore);
}];
}
for (uint32_t i = 0; i < p_swap_chains.size(); i++) {
SwapChain *swap_chain = (SwapChain *)(p_swap_chains[i].id);
RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
metal_surface->present(cmd_buffer);
}
cmd_buffer->commit();
if (p_swap_chains.size() > 0) {
// Used as a signal that we're presenting, so this is the end of a frame.
[device_scope endScope];
[device_scope beginScope];
}
return OK;
}
void RenderingDeviceDriverMetal::command_queue_free(CommandQueueID p_cmd_queue) {
}
#pragma mark - Command Buffers
// ----- POOL -----
RDD::CommandPoolID RenderingDeviceDriverMetal::command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) {
DEV_ASSERT(p_cmd_buffer_type == COMMAND_BUFFER_TYPE_PRIMARY);
return rid::make(device_queue);
}
void RenderingDeviceDriverMetal::command_pool_free(CommandPoolID p_cmd_pool) {
rid::release(p_cmd_pool);
}
// ----- BUFFER -----
RDD::CommandBufferID RenderingDeviceDriverMetal::command_buffer_create(CommandPoolID p_cmd_pool) {
id<MTLCommandQueue> queue = rid::get(p_cmd_pool);
MDCommandBuffer *obj = new MDCommandBuffer(queue, this);
command_buffers.push_back(obj);
return CommandBufferID(obj);
}
bool RenderingDeviceDriverMetal::command_buffer_begin(CommandBufferID p_cmd_buffer) {
MDCommandBuffer *obj = (MDCommandBuffer *)(p_cmd_buffer.id);
obj->begin();
return true;
}
bool RenderingDeviceDriverMetal::command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) {
ERR_FAIL_V_MSG(false, "not implemented");
}
void RenderingDeviceDriverMetal::command_buffer_end(CommandBufferID p_cmd_buffer) {
MDCommandBuffer *obj = (MDCommandBuffer *)(p_cmd_buffer.id);
obj->end();
}
void RenderingDeviceDriverMetal::command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) {
ERR_FAIL_MSG("not implemented");
}
#pragma mark - Swap Chain
void RenderingDeviceDriverMetal::_swap_chain_release(SwapChain *p_swap_chain) {
_swap_chain_release_buffers(p_swap_chain);
}
void RenderingDeviceDriverMetal::_swap_chain_release_buffers(SwapChain *p_swap_chain) {
}
RDD::SwapChainID RenderingDeviceDriverMetal::swap_chain_create(RenderingContextDriver::SurfaceID p_surface) {
RenderingContextDriverMetal::Surface const *surface = (RenderingContextDriverMetal::Surface *)(p_surface);
// Create the render pass that will be used to draw to the swap chain's framebuffers.
RDD::Attachment attachment;
attachment.format = pixel_formats->getDataFormat(surface->get_pixel_format());
attachment.samples = RDD::TEXTURE_SAMPLES_1;
attachment.load_op = RDD::ATTACHMENT_LOAD_OP_CLEAR;
attachment.store_op = RDD::ATTACHMENT_STORE_OP_STORE;
RDD::Subpass subpass;
RDD::AttachmentReference color_ref;
color_ref.attachment = 0;
color_ref.aspect.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);
subpass.color_references.push_back(color_ref);
RenderPassID render_pass = render_pass_create(attachment, subpass, {}, 1);
ERR_FAIL_COND_V(!render_pass, SwapChainID());
// Create the empty swap chain until it is resized.
SwapChain *swap_chain = memnew(SwapChain);
swap_chain->surface = p_surface;
swap_chain->data_format = attachment.format;
swap_chain->render_pass = render_pass;
return SwapChainID(swap_chain);
}
Error RenderingDeviceDriverMetal::swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) {
DEV_ASSERT(p_cmd_queue.id != 0);
DEV_ASSERT(p_swap_chain.id != 0);
SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
RenderingContextDriverMetal::Surface *surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
surface->resize(p_desired_framebuffer_count);
// Once everything's been created correctly, indicate the surface no longer needs to be resized.
context_driver->surface_set_needs_resize(swap_chain->surface, false);
return OK;
}
RDD::FramebufferID RenderingDeviceDriverMetal::swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) {
DEV_ASSERT(p_cmd_queue.id != 0);
DEV_ASSERT(p_swap_chain.id != 0);
SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
if (context_driver->surface_get_needs_resize(swap_chain->surface)) {
r_resize_required = true;
return FramebufferID();
}
RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
return metal_surface->acquire_next_frame_buffer();
}
RDD::RenderPassID RenderingDeviceDriverMetal::swap_chain_get_render_pass(SwapChainID p_swap_chain) {
const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
return swap_chain->render_pass;
}
RDD::DataFormat RenderingDeviceDriverMetal::swap_chain_get_format(SwapChainID p_swap_chain) {
const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
return swap_chain->data_format;
}
void RenderingDeviceDriverMetal::swap_chain_free(SwapChainID p_swap_chain) {
SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
_swap_chain_release(swap_chain);
render_pass_free(swap_chain->render_pass);
memdelete(swap_chain);
}
#pragma mark - Frame buffer
RDD::FramebufferID RenderingDeviceDriverMetal::framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) {
MDRenderPass *pass = (MDRenderPass *)(p_render_pass.id);
Vector<MTL::Texture> textures;
textures.resize(p_attachments.size());
for (uint32_t i = 0; i < p_attachments.size(); i += 1) {