rendering_device_driver_metal.mm 114 KB

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