rendering_device_driver_metal.mm 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206
  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. #include "core/io/compression.h"
  53. #include "core/io/marshalls.h"
  54. #include "core/string/ustring.h"
  55. #include "core/templates/hash_map.h"
  56. #import <Metal/MTLTexture.h>
  57. #import <Metal/Metal.h>
  58. #import <os/log.h>
  59. #import <os/signpost.h>
  60. #import <spirv.hpp>
  61. #import <spirv_msl.hpp>
  62. #import <spirv_parser.hpp>
  63. #pragma mark - Logging
  64. os_log_t LOG_DRIVER;
  65. // Used for dynamic tracing.
  66. os_log_t LOG_INTERVALS;
  67. __attribute__((constructor)) static void InitializeLogging(void) {
  68. LOG_DRIVER = os_log_create("org.godotengine.godot.metal", OS_LOG_CATEGORY_POINTS_OF_INTEREST);
  69. LOG_INTERVALS = os_log_create("org.godotengine.godot.metal", "events");
  70. }
  71. /*****************/
  72. /**** GENERIC ****/
  73. /*****************/
  74. // RDD::CompareOperator == VkCompareOp.
  75. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_NEVER, MTLCompareFunctionNever));
  76. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_LESS, MTLCompareFunctionLess));
  77. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_EQUAL, MTLCompareFunctionEqual));
  78. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_LESS_OR_EQUAL, MTLCompareFunctionLessEqual));
  79. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_GREATER, MTLCompareFunctionGreater));
  80. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_NOT_EQUAL, MTLCompareFunctionNotEqual));
  81. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_GREATER_OR_EQUAL, MTLCompareFunctionGreaterEqual));
  82. static_assert(ENUM_MEMBERS_EQUAL(RDD::COMPARE_OP_ALWAYS, MTLCompareFunctionAlways));
  83. _FORCE_INLINE_ MTLSize mipmapLevelSizeFromTexture(id<MTLTexture> p_tex, NSUInteger p_level) {
  84. MTLSize lvlSize;
  85. lvlSize.width = MAX(p_tex.width >> p_level, 1UL);
  86. lvlSize.height = MAX(p_tex.height >> p_level, 1UL);
  87. lvlSize.depth = MAX(p_tex.depth >> p_level, 1UL);
  88. return lvlSize;
  89. }
  90. _FORCE_INLINE_ MTLSize mipmapLevelSizeFromSize(MTLSize p_size, NSUInteger p_level) {
  91. if (p_level == 0) {
  92. return p_size;
  93. }
  94. MTLSize lvlSize;
  95. lvlSize.width = MAX(p_size.width >> p_level, 1UL);
  96. lvlSize.height = MAX(p_size.height >> p_level, 1UL);
  97. lvlSize.depth = MAX(p_size.depth >> p_level, 1UL);
  98. return lvlSize;
  99. }
  100. _FORCE_INLINE_ static bool operator==(MTLSize p_a, MTLSize p_b) {
  101. return p_a.width == p_b.width && p_a.height == p_b.height && p_a.depth == p_b.depth;
  102. }
  103. /*****************/
  104. /**** BUFFERS ****/
  105. /*****************/
  106. RDD::BufferID RenderingDeviceDriverMetal::buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) {
  107. MTLResourceOptions options = MTLResourceHazardTrackingModeTracked;
  108. switch (p_allocation_type) {
  109. case MEMORY_ALLOCATION_TYPE_CPU:
  110. options |= MTLResourceStorageModeShared;
  111. break;
  112. case MEMORY_ALLOCATION_TYPE_GPU:
  113. options |= MTLResourceStorageModePrivate;
  114. break;
  115. }
  116. id<MTLBuffer> obj = [device newBufferWithLength:p_size options:options];
  117. ERR_FAIL_NULL_V_MSG(obj, BufferID(), "Can't create buffer of size: " + itos(p_size));
  118. return rid::make(obj);
  119. }
  120. bool RenderingDeviceDriverMetal::buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) {
  121. // Nothing to do.
  122. return true;
  123. }
  124. void RenderingDeviceDriverMetal::buffer_free(BufferID p_buffer) {
  125. rid::release(p_buffer);
  126. }
  127. uint64_t RenderingDeviceDriverMetal::buffer_get_allocation_size(BufferID p_buffer) {
  128. id<MTLBuffer> obj = rid::get(p_buffer);
  129. return obj.allocatedSize;
  130. }
  131. uint8_t *RenderingDeviceDriverMetal::buffer_map(BufferID p_buffer) {
  132. id<MTLBuffer> obj = rid::get(p_buffer);
  133. ERR_FAIL_COND_V_MSG(obj.storageMode != MTLStorageModeShared, nullptr, "Unable to map private buffers");
  134. return (uint8_t *)obj.contents;
  135. }
  136. void RenderingDeviceDriverMetal::buffer_unmap(BufferID p_buffer) {
  137. // Nothing to do.
  138. }
  139. uint64_t RenderingDeviceDriverMetal::buffer_get_device_address(BufferID p_buffer) {
  140. if (@available(iOS 16.0, macOS 13.0, *)) {
  141. id<MTLBuffer> obj = rid::get(p_buffer);
  142. return obj.gpuAddress;
  143. } else {
  144. #if DEV_ENABLED
  145. WARN_PRINT_ONCE("buffer_get_device_address is not supported on this OS version.");
  146. #endif
  147. return 0;
  148. }
  149. }
  150. #pragma mark - Texture
  151. #pragma mark - Format Conversions
  152. static const MTLTextureType TEXTURE_TYPE[RD::TEXTURE_TYPE_MAX] = {
  153. MTLTextureType1D,
  154. MTLTextureType2D,
  155. MTLTextureType3D,
  156. MTLTextureTypeCube,
  157. MTLTextureType1DArray,
  158. MTLTextureType2DArray,
  159. MTLTextureTypeCubeArray,
  160. };
  161. RenderingDeviceDriverMetal::Result<bool> RenderingDeviceDriverMetal::is_valid_linear(TextureFormat const &p_format) const {
  162. if (!flags::any(p_format.usage_bits, TEXTURE_USAGE_CPU_READ_BIT)) {
  163. return false;
  164. }
  165. PixelFormats &pf = *pixel_formats;
  166. MTLFormatType ft = pf.getFormatType(p_format.format);
  167. // Requesting a linear format, which has further restrictions, similar to Vulkan
  168. // when specifying VK_IMAGE_TILING_LINEAR.
  169. 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");
  170. 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");
  171. ERR_FAIL_COND_V_MSG(ft != MTLFormatType::Compressed, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must not be a compressed format");
  172. ERR_FAIL_COND_V_MSG(p_format.mipmaps != 1, ERR_CANT_CREATE, "Linear (TEXTURE_USAGE_CPU_READ_BIT) textures must have 1 mipmap level");
  173. 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");
  174. 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");
  175. return true;
  176. }
  177. RDD::TextureID RenderingDeviceDriverMetal::texture_create(const TextureFormat &p_format, const TextureView &p_view) {
  178. MTLTextureDescriptor *desc = [MTLTextureDescriptor new];
  179. desc.textureType = TEXTURE_TYPE[p_format.texture_type];
  180. PixelFormats &formats = *pixel_formats;
  181. desc.pixelFormat = formats.getMTLPixelFormat(p_format.format);
  182. MTLFmtCaps format_caps = formats.getCapabilities(desc.pixelFormat);
  183. desc.width = p_format.width;
  184. desc.height = p_format.height;
  185. desc.depth = p_format.depth;
  186. desc.mipmapLevelCount = p_format.mipmaps;
  187. if (p_format.texture_type == TEXTURE_TYPE_1D_ARRAY ||
  188. p_format.texture_type == TEXTURE_TYPE_2D_ARRAY) {
  189. desc.arrayLength = p_format.array_layers;
  190. } else if (p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY) {
  191. desc.arrayLength = p_format.array_layers / 6;
  192. }
  193. // TODO(sgc): Evaluate lossy texture support (perhaps as a project option?)
  194. // https://developer.apple.com/videos/play/tech-talks/10876?time=459
  195. // desc.compressionType = MTLTextureCompressionTypeLossy;
  196. if (p_format.samples > TEXTURE_SAMPLES_1) {
  197. SampleCount supported = (*device_properties).find_nearest_supported_sample_count(p_format.samples);
  198. if (supported > SampleCount1) {
  199. bool ok = p_format.texture_type == TEXTURE_TYPE_2D || p_format.texture_type == TEXTURE_TYPE_2D_ARRAY;
  200. if (ok) {
  201. switch (p_format.texture_type) {
  202. case TEXTURE_TYPE_2D:
  203. desc.textureType = MTLTextureType2DMultisample;
  204. break;
  205. case TEXTURE_TYPE_2D_ARRAY:
  206. desc.textureType = MTLTextureType2DMultisampleArray;
  207. break;
  208. default:
  209. break;
  210. }
  211. desc.sampleCount = (NSUInteger)supported;
  212. if (p_format.mipmaps > 1) {
  213. // For a buffer-backed or multi-sample texture, the value must be 1.
  214. WARN_PRINT("mipmaps == 1 for multi-sample textures");
  215. desc.mipmapLevelCount = 1;
  216. }
  217. } else {
  218. WARN_PRINT("Unsupported multi-sample texture type; disabling multi-sample");
  219. }
  220. }
  221. }
  222. static const MTLTextureSwizzle COMPONENT_SWIZZLE[TEXTURE_SWIZZLE_MAX] = {
  223. static_cast<MTLTextureSwizzle>(255), // IDENTITY
  224. MTLTextureSwizzleZero,
  225. MTLTextureSwizzleOne,
  226. MTLTextureSwizzleRed,
  227. MTLTextureSwizzleGreen,
  228. MTLTextureSwizzleBlue,
  229. MTLTextureSwizzleAlpha,
  230. };
  231. MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
  232. p_view.swizzle_r != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_r] : MTLTextureSwizzleRed,
  233. p_view.swizzle_g != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_g] : MTLTextureSwizzleGreen,
  234. p_view.swizzle_b != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_b] : MTLTextureSwizzleBlue,
  235. p_view.swizzle_a != TEXTURE_SWIZZLE_IDENTITY ? COMPONENT_SWIZZLE[p_view.swizzle_a] : MTLTextureSwizzleAlpha);
  236. // Represents a swizzle operation that is a no-op.
  237. static MTLTextureSwizzleChannels IDENTITY_SWIZZLE = {
  238. .red = MTLTextureSwizzleRed,
  239. .green = MTLTextureSwizzleGreen,
  240. .blue = MTLTextureSwizzleBlue,
  241. .alpha = MTLTextureSwizzleAlpha,
  242. };
  243. bool no_swizzle = memcmp(&IDENTITY_SWIZZLE, &swizzle, sizeof(MTLTextureSwizzleChannels)) == 0;
  244. if (!no_swizzle) {
  245. desc.swizzle = swizzle;
  246. }
  247. // Usage.
  248. MTLResourceOptions options = 0;
  249. #if defined(VISIONOS_ENABLED)
  250. const bool supports_memoryless = true;
  251. #else
  252. const bool supports_memoryless = (*device_properties).features.highestFamily >= MTLGPUFamilyApple2 && (*device_properties).features.highestFamily < MTLGPUFamilyMac1;
  253. #endif
  254. if (supports_memoryless && p_format.usage_bits & TEXTURE_USAGE_TRANSIENT_BIT) {
  255. options = MTLResourceStorageModeMemoryless | MTLResourceHazardTrackingModeTracked;
  256. desc.storageMode = MTLStorageModeMemoryless;
  257. } else {
  258. options = MTLResourceCPUCacheModeDefaultCache | MTLResourceHazardTrackingModeTracked;
  259. if (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) {
  260. options |= MTLResourceStorageModeShared;
  261. } else {
  262. options |= MTLResourceStorageModePrivate;
  263. }
  264. }
  265. desc.resourceOptions = options;
  266. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) {
  267. desc.usage |= MTLTextureUsageShaderRead;
  268. }
  269. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) {
  270. desc.usage |= MTLTextureUsageShaderWrite;
  271. }
  272. if (@available(macOS 14.0, iOS 17.0, tvOS 17.0, *)) {
  273. if (format_caps & kMTLFmtCapsAtomic) {
  274. desc.usage |= MTLTextureUsageShaderAtomic;
  275. }
  276. }
  277. bool can_be_attachment = flags::any(format_caps, (kMTLFmtCapsColorAtt | kMTLFmtCapsDSAtt));
  278. if (flags::any(p_format.usage_bits, TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) &&
  279. can_be_attachment) {
  280. desc.usage |= MTLTextureUsageRenderTarget;
  281. }
  282. if (p_format.usage_bits & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
  283. desc.usage |= MTLTextureUsageShaderRead;
  284. }
  285. if (p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {
  286. ERR_FAIL_V_MSG(RDD::TextureID(), "unsupported: TEXTURE_USAGE_VRS_ATTACHMENT_BIT");
  287. }
  288. if (flags::any(p_format.usage_bits, TEXTURE_USAGE_CAN_UPDATE_BIT | TEXTURE_USAGE_CAN_COPY_TO_BIT) &&
  289. can_be_attachment && no_swizzle) {
  290. // Per MoltenVK, can be cleared as a render attachment.
  291. desc.usage |= MTLTextureUsageRenderTarget;
  292. }
  293. if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
  294. // Covered by blits.
  295. }
  296. // Create texture views with a different component layout.
  297. if (!p_format.shareable_formats.is_empty()) {
  298. desc.usage |= MTLTextureUsagePixelFormatView;
  299. }
  300. // Allocate memory.
  301. bool is_linear;
  302. {
  303. Result<bool> is_linear_or_err = is_valid_linear(p_format);
  304. ERR_FAIL_COND_V(std::holds_alternative<Error>(is_linear_or_err), TextureID());
  305. is_linear = std::get<bool>(is_linear_or_err);
  306. }
  307. // Check if it is a linear format for atomic operations and therefore needs a buffer,
  308. // as generally Metal does not support atomic operations on textures.
  309. bool needs_buffer = is_linear || (p_format.array_layers == 1 && p_format.mipmaps == 1 && p_format.texture_type == TEXTURE_TYPE_2D && flags::any(p_format.usage_bits, TEXTURE_USAGE_STORAGE_BIT) && (p_format.format == DATA_FORMAT_R32_UINT || p_format.format == DATA_FORMAT_R32_SINT || p_format.format == DATA_FORMAT_R32G32_UINT || p_format.format == DATA_FORMAT_R32G32_SINT));
  310. id<MTLTexture> obj = nil;
  311. if (needs_buffer) {
  312. // Linear textures are restricted to 2D textures, a single mipmap level and a single array layer.
  313. MTLPixelFormat pixel_format = desc.pixelFormat;
  314. size_t row_alignment = get_texel_buffer_alignment_for_format(p_format.format);
  315. size_t bytes_per_row = formats.getBytesPerRow(pixel_format, p_format.width);
  316. bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
  317. size_t bytes_per_layer = formats.getBytesPerLayer(pixel_format, bytes_per_row, p_format.height);
  318. size_t byte_count = bytes_per_layer * p_format.depth * p_format.array_layers;
  319. id<MTLBuffer> buf = [device newBufferWithLength:byte_count options:options];
  320. obj = [buf newTextureWithDescriptor:desc offset:0 bytesPerRow:bytes_per_row];
  321. } else {
  322. obj = [device newTextureWithDescriptor:desc];
  323. }
  324. ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create texture.");
  325. return rid::make(obj);
  326. }
  327. 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) {
  328. id<MTLTexture> res = (__bridge id<MTLTexture>)(void *)(uintptr_t)p_native_texture;
  329. // If the requested format is different, we need to create a view.
  330. MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_format);
  331. if (res.pixelFormat != format) {
  332. MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
  333. MTLTextureSwizzleRed,
  334. MTLTextureSwizzleGreen,
  335. MTLTextureSwizzleBlue,
  336. MTLTextureSwizzleAlpha);
  337. res = [res newTextureViewWithPixelFormat:format
  338. textureType:res.textureType
  339. levels:NSMakeRange(0, res.mipmapLevelCount)
  340. slices:NSMakeRange(0, p_array_layers)
  341. swizzle:swizzle];
  342. ERR_FAIL_NULL_V_MSG(res, TextureID(), "Unable to create texture view.");
  343. }
  344. return rid::make(res);
  345. }
  346. RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared(TextureID p_original_texture, const TextureView &p_view) {
  347. id<MTLTexture> src_texture = rid::get(p_original_texture);
  348. NSUInteger slices = src_texture.arrayLength;
  349. if (src_texture.textureType == MTLTextureTypeCube) {
  350. // Metal expects Cube textures to have a slice count of 6.
  351. slices = 6;
  352. } else if (src_texture.textureType == MTLTextureTypeCubeArray) {
  353. // Metal expects Cube Array textures to have 6 slices per layer.
  354. slices *= 6;
  355. }
  356. #if DEV_ENABLED
  357. if (src_texture.sampleCount > 1) {
  358. // TODO(sgc): is it ok to create a shared texture from a multi-sample texture?
  359. WARN_PRINT("Is it safe to create a shared texture from multi-sample texture?");
  360. }
  361. #endif
  362. MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_view.format);
  363. static const MTLTextureSwizzle component_swizzle[TEXTURE_SWIZZLE_MAX] = {
  364. static_cast<MTLTextureSwizzle>(255), // IDENTITY
  365. MTLTextureSwizzleZero,
  366. MTLTextureSwizzleOne,
  367. MTLTextureSwizzleRed,
  368. MTLTextureSwizzleGreen,
  369. MTLTextureSwizzleBlue,
  370. MTLTextureSwizzleAlpha,
  371. };
  372. #define SWIZZLE(C, CHAN) (p_view.swizzle_##C != TEXTURE_SWIZZLE_IDENTITY ? component_swizzle[p_view.swizzle_##C] : MTLTextureSwizzle##CHAN)
  373. MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
  374. SWIZZLE(r, Red),
  375. SWIZZLE(g, Green),
  376. SWIZZLE(b, Blue),
  377. SWIZZLE(a, Alpha));
  378. #undef SWIZZLE
  379. id<MTLTexture> obj = [src_texture newTextureViewWithPixelFormat:format
  380. textureType:src_texture.textureType
  381. levels:NSMakeRange(0, src_texture.mipmapLevelCount)
  382. slices:NSMakeRange(0, slices)
  383. swizzle:swizzle];
  384. ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create shared texture");
  385. return rid::make(obj);
  386. }
  387. 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) {
  388. id<MTLTexture> src_texture = rid::get(p_original_texture);
  389. static const MTLTextureType VIEW_TYPES[] = {
  390. MTLTextureType1D, // MTLTextureType1D
  391. MTLTextureType1D, // MTLTextureType1DArray
  392. MTLTextureType2D, // MTLTextureType2D
  393. MTLTextureType2D, // MTLTextureType2DArray
  394. MTLTextureType2D, // MTLTextureType2DMultisample
  395. MTLTextureType2D, // MTLTextureTypeCube
  396. MTLTextureType2D, // MTLTextureTypeCubeArray
  397. MTLTextureType2D, // MTLTextureType3D
  398. MTLTextureType2D, // MTLTextureType2DMultisampleArray
  399. };
  400. MTLTextureType textureType = VIEW_TYPES[src_texture.textureType];
  401. switch (p_slice_type) {
  402. case TEXTURE_SLICE_2D: {
  403. textureType = MTLTextureType2D;
  404. } break;
  405. case TEXTURE_SLICE_3D: {
  406. textureType = MTLTextureType3D;
  407. } break;
  408. case TEXTURE_SLICE_CUBEMAP: {
  409. textureType = MTLTextureTypeCube;
  410. } break;
  411. case TEXTURE_SLICE_2D_ARRAY: {
  412. textureType = MTLTextureType2DArray;
  413. } break;
  414. case TEXTURE_SLICE_MAX: {
  415. ERR_FAIL_V_MSG(TextureID(), "Invalid texture slice type");
  416. } break;
  417. }
  418. MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_view.format);
  419. static const MTLTextureSwizzle component_swizzle[TEXTURE_SWIZZLE_MAX] = {
  420. static_cast<MTLTextureSwizzle>(255), // IDENTITY
  421. MTLTextureSwizzleZero,
  422. MTLTextureSwizzleOne,
  423. MTLTextureSwizzleRed,
  424. MTLTextureSwizzleGreen,
  425. MTLTextureSwizzleBlue,
  426. MTLTextureSwizzleAlpha,
  427. };
  428. #define SWIZZLE(C, CHAN) (p_view.swizzle_##C != TEXTURE_SWIZZLE_IDENTITY ? component_swizzle[p_view.swizzle_##C] : MTLTextureSwizzle##CHAN)
  429. MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
  430. SWIZZLE(r, Red),
  431. SWIZZLE(g, Green),
  432. SWIZZLE(b, Blue),
  433. SWIZZLE(a, Alpha));
  434. #undef SWIZZLE
  435. id<MTLTexture> obj = [src_texture newTextureViewWithPixelFormat:format
  436. textureType:textureType
  437. levels:NSMakeRange(p_mipmap, p_mipmaps)
  438. slices:NSMakeRange(p_layer, p_layers)
  439. swizzle:swizzle];
  440. ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create shared texture");
  441. return rid::make(obj);
  442. }
  443. void RenderingDeviceDriverMetal::texture_free(TextureID p_texture) {
  444. rid::release(p_texture);
  445. }
  446. uint64_t RenderingDeviceDriverMetal::texture_get_allocation_size(TextureID p_texture) {
  447. id<MTLTexture> obj = rid::get(p_texture);
  448. return obj.allocatedSize;
  449. }
  450. void RenderingDeviceDriverMetal::_get_sub_resource(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) const {
  451. id<MTLTexture> obj = rid::get(p_texture);
  452. *r_layout = {};
  453. PixelFormats &pf = *pixel_formats;
  454. size_t row_alignment = get_texel_buffer_alignment_for_format(obj.pixelFormat);
  455. size_t offset = 0;
  456. size_t array_layers = obj.arrayLength;
  457. MTLSize size = MTLSizeMake(obj.width, obj.height, obj.depth);
  458. MTLPixelFormat pixel_format = obj.pixelFormat;
  459. // First skip over the mipmap levels.
  460. for (uint32_t mipLvl = 0; mipLvl < p_subresource.mipmap; mipLvl++) {
  461. MTLSize mip_size = mipmapLevelSizeFromSize(size, mipLvl);
  462. size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mip_size.width);
  463. bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
  464. size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mip_size.height);
  465. offset += bytes_per_layer * mip_size.depth * array_layers;
  466. }
  467. // Get current mipmap.
  468. MTLSize mip_size = mipmapLevelSizeFromSize(size, p_subresource.mipmap);
  469. size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mip_size.width);
  470. bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
  471. size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mip_size.height);
  472. r_layout->size = bytes_per_layer * mip_size.depth;
  473. r_layout->offset = offset + (r_layout->size * p_subresource.layer - 1);
  474. r_layout->depth_pitch = bytes_per_layer;
  475. r_layout->row_pitch = bytes_per_row;
  476. r_layout->layer_pitch = r_layout->size * array_layers;
  477. }
  478. void RenderingDeviceDriverMetal::texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) {
  479. id<MTLTexture> obj = rid::get(p_texture);
  480. *r_layout = {};
  481. if ((obj.resourceOptions & MTLResourceStorageModePrivate) != 0) {
  482. MTLSize sz = MTLSizeMake(obj.width, obj.height, obj.depth);
  483. PixelFormats &pf = *pixel_formats;
  484. DataFormat format = pf.getDataFormat(obj.pixelFormat);
  485. if (p_subresource.mipmap > 0) {
  486. r_layout->offset = get_image_format_required_size(format, sz.width, sz.height, sz.depth, p_subresource.mipmap);
  487. }
  488. sz = mipmapLevelSizeFromSize(sz, p_subresource.mipmap);
  489. uint32_t bw = 0, bh = 0;
  490. get_compressed_image_format_block_dimensions(format, bw, bh);
  491. uint32_t sbw = 0, sbh = 0;
  492. r_layout->size = get_image_format_required_size(format, sz.width, sz.height, sz.depth, 1, &sbw, &sbh);
  493. r_layout->row_pitch = r_layout->size / ((sbh / bh) * sz.depth);
  494. r_layout->depth_pitch = r_layout->size / sz.depth;
  495. uint32_t array_length = obj.arrayLength;
  496. if (obj.textureType == MTLTextureTypeCube) {
  497. array_length = 6;
  498. } else if (obj.textureType == MTLTextureTypeCubeArray) {
  499. array_length *= 6;
  500. }
  501. r_layout->layer_pitch = r_layout->size / array_length;
  502. } else {
  503. CRASH_NOW_MSG("need to calculate layout for shared texture");
  504. }
  505. }
  506. uint8_t *RenderingDeviceDriverMetal::texture_map(TextureID p_texture, const TextureSubresource &p_subresource) {
  507. id<MTLTexture> obj = rid::get(p_texture);
  508. ERR_FAIL_NULL_V_MSG(obj.buffer, nullptr, "texture is not created from a buffer");
  509. TextureCopyableLayout layout;
  510. _get_sub_resource(p_texture, p_subresource, &layout);
  511. return (uint8_t *)(obj.buffer.contents) + layout.offset;
  512. PixelFormats &pf = *pixel_formats;
  513. size_t row_alignment = get_texel_buffer_alignment_for_format(obj.pixelFormat);
  514. size_t offset = 0;
  515. size_t array_layers = obj.arrayLength;
  516. MTLSize size = MTLSizeMake(obj.width, obj.height, obj.depth);
  517. MTLPixelFormat pixel_format = obj.pixelFormat;
  518. // First skip over the mipmap levels.
  519. for (uint32_t mipLvl = 0; mipLvl < p_subresource.mipmap; mipLvl++) {
  520. MTLSize mipExtent = mipmapLevelSizeFromSize(size, mipLvl);
  521. size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mipExtent.width);
  522. bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
  523. size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mipExtent.height);
  524. offset += bytes_per_layer * mipExtent.depth * array_layers;
  525. }
  526. if (p_subresource.layer > 1) {
  527. // Calculate offset to desired layer.
  528. MTLSize mipExtent = mipmapLevelSizeFromSize(size, p_subresource.mipmap);
  529. size_t bytes_per_row = pf.getBytesPerRow(pixel_format, mipExtent.width);
  530. bytes_per_row = round_up_to_alignment(bytes_per_row, row_alignment);
  531. size_t bytes_per_layer = pf.getBytesPerLayer(pixel_format, bytes_per_row, mipExtent.height);
  532. offset += bytes_per_layer * mipExtent.depth * (p_subresource.layer - 1);
  533. }
  534. // TODO: Confirm with rendering team that there is no other way Godot may attempt to map a texture with multiple mipmaps or array layers.
  535. // NOTE: It is not possible to create a buffer-backed texture with mipmaps or array layers,
  536. // as noted in the is_valid_linear function, so the offset calculation SHOULD always be zero.
  537. // Given that, this code should be simplified.
  538. return (uint8_t *)(obj.buffer.contents) + offset;
  539. }
  540. void RenderingDeviceDriverMetal::texture_unmap(TextureID p_texture) {
  541. // Nothing to do.
  542. }
  543. BitField<RDD::TextureUsageBits> RenderingDeviceDriverMetal::texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) {
  544. PixelFormats &pf = *pixel_formats;
  545. if (pf.getMTLPixelFormat(p_format) == MTLPixelFormatInvalid) {
  546. return 0;
  547. }
  548. MTLFmtCaps caps = pf.getCapabilities(p_format);
  549. // Everything supported by default makes an all-or-nothing check easier for the caller.
  550. BitField<RDD::TextureUsageBits> supported = INT64_MAX;
  551. supported.clear_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT); // No VRS support for Metal.
  552. if (!flags::any(caps, kMTLFmtCapsColorAtt)) {
  553. supported.clear_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT);
  554. }
  555. if (!flags::any(caps, kMTLFmtCapsDSAtt)) {
  556. supported.clear_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
  557. }
  558. if (!flags::any(caps, kMTLFmtCapsRead)) {
  559. supported.clear_flag(TEXTURE_USAGE_SAMPLING_BIT);
  560. }
  561. if (!flags::any(caps, kMTLFmtCapsAtomic)) {
  562. supported.clear_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT);
  563. }
  564. return supported;
  565. }
  566. bool RenderingDeviceDriverMetal::texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) {
  567. r_raw_reinterpretation = false;
  568. return true;
  569. }
  570. #pragma mark - Sampler
  571. static const MTLCompareFunction COMPARE_OPERATORS[RD::COMPARE_OP_MAX] = {
  572. MTLCompareFunctionNever,
  573. MTLCompareFunctionLess,
  574. MTLCompareFunctionEqual,
  575. MTLCompareFunctionLessEqual,
  576. MTLCompareFunctionGreater,
  577. MTLCompareFunctionNotEqual,
  578. MTLCompareFunctionGreaterEqual,
  579. MTLCompareFunctionAlways,
  580. };
  581. static const MTLStencilOperation STENCIL_OPERATIONS[RD::STENCIL_OP_MAX] = {
  582. MTLStencilOperationKeep,
  583. MTLStencilOperationZero,
  584. MTLStencilOperationReplace,
  585. MTLStencilOperationIncrementClamp,
  586. MTLStencilOperationDecrementClamp,
  587. MTLStencilOperationInvert,
  588. MTLStencilOperationIncrementWrap,
  589. MTLStencilOperationDecrementWrap,
  590. };
  591. static const MTLBlendFactor BLEND_FACTORS[RD::BLEND_FACTOR_MAX] = {
  592. MTLBlendFactorZero,
  593. MTLBlendFactorOne,
  594. MTLBlendFactorSourceColor,
  595. MTLBlendFactorOneMinusSourceColor,
  596. MTLBlendFactorDestinationColor,
  597. MTLBlendFactorOneMinusDestinationColor,
  598. MTLBlendFactorSourceAlpha,
  599. MTLBlendFactorOneMinusSourceAlpha,
  600. MTLBlendFactorDestinationAlpha,
  601. MTLBlendFactorOneMinusDestinationAlpha,
  602. MTLBlendFactorBlendColor,
  603. MTLBlendFactorOneMinusBlendColor,
  604. MTLBlendFactorBlendAlpha,
  605. MTLBlendFactorOneMinusBlendAlpha,
  606. MTLBlendFactorSourceAlphaSaturated,
  607. MTLBlendFactorSource1Color,
  608. MTLBlendFactorOneMinusSource1Color,
  609. MTLBlendFactorSource1Alpha,
  610. MTLBlendFactorOneMinusSource1Alpha,
  611. };
  612. static const MTLBlendOperation BLEND_OPERATIONS[RD::BLEND_OP_MAX] = {
  613. MTLBlendOperationAdd,
  614. MTLBlendOperationSubtract,
  615. MTLBlendOperationReverseSubtract,
  616. MTLBlendOperationMin,
  617. MTLBlendOperationMax,
  618. };
  619. static const API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MTLSamplerAddressMode ADDRESS_MODES[RD::SAMPLER_REPEAT_MODE_MAX] = {
  620. MTLSamplerAddressModeRepeat,
  621. MTLSamplerAddressModeMirrorRepeat,
  622. MTLSamplerAddressModeClampToEdge,
  623. MTLSamplerAddressModeClampToBorderColor,
  624. MTLSamplerAddressModeMirrorClampToEdge,
  625. };
  626. static const API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MTLSamplerBorderColor SAMPLER_BORDER_COLORS[RD::SAMPLER_BORDER_COLOR_MAX] = {
  627. MTLSamplerBorderColorTransparentBlack,
  628. MTLSamplerBorderColorTransparentBlack,
  629. MTLSamplerBorderColorOpaqueBlack,
  630. MTLSamplerBorderColorOpaqueBlack,
  631. MTLSamplerBorderColorOpaqueWhite,
  632. MTLSamplerBorderColorOpaqueWhite,
  633. };
  634. RDD::SamplerID RenderingDeviceDriverMetal::sampler_create(const SamplerState &p_state) {
  635. MTLSamplerDescriptor *desc = [MTLSamplerDescriptor new];
  636. desc.supportArgumentBuffers = YES;
  637. desc.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
  638. desc.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
  639. desc.mipFilter = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? MTLSamplerMipFilterLinear : MTLSamplerMipFilterNearest;
  640. desc.sAddressMode = ADDRESS_MODES[p_state.repeat_u];
  641. desc.tAddressMode = ADDRESS_MODES[p_state.repeat_v];
  642. desc.rAddressMode = ADDRESS_MODES[p_state.repeat_w];
  643. if (p_state.use_anisotropy) {
  644. desc.maxAnisotropy = p_state.anisotropy_max;
  645. }
  646. desc.compareFunction = COMPARE_OPERATORS[p_state.compare_op];
  647. desc.lodMinClamp = p_state.min_lod;
  648. desc.lodMaxClamp = p_state.max_lod;
  649. desc.borderColor = SAMPLER_BORDER_COLORS[p_state.border_color];
  650. desc.normalizedCoordinates = !p_state.unnormalized_uvw;
  651. if (p_state.lod_bias != 0.0) {
  652. WARN_PRINT_ONCE("Metal does not support LOD bias for samplers.");
  653. }
  654. id<MTLSamplerState> obj = [device newSamplerStateWithDescriptor:desc];
  655. ERR_FAIL_NULL_V_MSG(obj, SamplerID(), "newSamplerStateWithDescriptor failed");
  656. return rid::make(obj);
  657. }
  658. void RenderingDeviceDriverMetal::sampler_free(SamplerID p_sampler) {
  659. rid::release(p_sampler);
  660. }
  661. bool RenderingDeviceDriverMetal::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) {
  662. switch (p_filter) {
  663. case SAMPLER_FILTER_NEAREST:
  664. return true;
  665. case SAMPLER_FILTER_LINEAR: {
  666. MTLFmtCaps caps = pixel_formats->getCapabilities(p_format);
  667. return flags::any(caps, kMTLFmtCapsFilter);
  668. }
  669. }
  670. }
  671. #pragma mark - Vertex Array
  672. RDD::VertexFormatID RenderingDeviceDriverMetal::vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) {
  673. MTLVertexDescriptor *desc = MTLVertexDescriptor.vertexDescriptor;
  674. for (uint32_t i = 0; i < p_vertex_attribs.size(); i++) {
  675. VertexAttribute const &vf = p_vertex_attribs[i];
  676. ERR_FAIL_COND_V_MSG(get_format_vertex_size(vf.format) == 0, VertexFormatID(),
  677. "Data format for attachment (" + itos(i) + "), '" + FORMAT_NAMES[vf.format] + "', is not valid for a vertex array.");
  678. desc.attributes[vf.location].format = pixel_formats->getMTLVertexFormat(vf.format);
  679. desc.attributes[vf.location].offset = vf.offset;
  680. uint32_t idx = get_metal_buffer_index_for_vertex_attribute_binding(i);
  681. desc.attributes[vf.location].bufferIndex = idx;
  682. if (vf.stride == 0) {
  683. desc.layouts[idx].stepFunction = MTLVertexStepFunctionConstant;
  684. desc.layouts[idx].stepRate = 0;
  685. desc.layouts[idx].stride = pixel_formats->getBytesPerBlock(vf.format);
  686. } else {
  687. desc.layouts[idx].stepFunction = vf.frequency == VERTEX_FREQUENCY_VERTEX ? MTLVertexStepFunctionPerVertex : MTLVertexStepFunctionPerInstance;
  688. desc.layouts[idx].stepRate = 1;
  689. desc.layouts[idx].stride = vf.stride;
  690. }
  691. }
  692. return rid::make(desc);
  693. }
  694. void RenderingDeviceDriverMetal::vertex_format_free(VertexFormatID p_vertex_format) {
  695. rid::release(p_vertex_format);
  696. }
  697. #pragma mark - Barriers
  698. void RenderingDeviceDriverMetal::command_pipeline_barrier(
  699. CommandBufferID p_cmd_buffer,
  700. BitField<PipelineStageBits> p_src_stages,
  701. BitField<PipelineStageBits> p_dst_stages,
  702. VectorView<MemoryBarrier> p_memory_barriers,
  703. VectorView<BufferBarrier> p_buffer_barriers,
  704. VectorView<TextureBarrier> p_texture_barriers) {
  705. WARN_PRINT_ONCE("not implemented");
  706. }
  707. #pragma mark - Fences
  708. RDD::FenceID RenderingDeviceDriverMetal::fence_create() {
  709. Fence *fence = memnew(Fence);
  710. return FenceID(fence);
  711. }
  712. Error RenderingDeviceDriverMetal::fence_wait(FenceID p_fence) {
  713. Fence *fence = (Fence *)(p_fence.id);
  714. // Wait forever, so this function is infallible.
  715. dispatch_semaphore_wait(fence->semaphore, DISPATCH_TIME_FOREVER);
  716. return OK;
  717. }
  718. void RenderingDeviceDriverMetal::fence_free(FenceID p_fence) {
  719. Fence *fence = (Fence *)(p_fence.id);
  720. memdelete(fence);
  721. }
  722. #pragma mark - Semaphores
  723. RDD::SemaphoreID RenderingDeviceDriverMetal::semaphore_create() {
  724. // Metal doesn't use semaphores, as their purpose within Godot is to ensure ordering of command buffer execution.
  725. return SemaphoreID(1);
  726. }
  727. void RenderingDeviceDriverMetal::semaphore_free(SemaphoreID p_semaphore) {
  728. }
  729. #pragma mark - Queues
  730. RDD::CommandQueueFamilyID RenderingDeviceDriverMetal::command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface) {
  731. if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_GRAPHICS_BIT) || (p_surface != 0)) {
  732. return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_GRAPHICS_BIT);
  733. } else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_COMPUTE_BIT)) {
  734. return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_COMPUTE_BIT);
  735. } else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_TRANSFER_BIT)) {
  736. return CommandQueueFamilyID(COMMAND_QUEUE_FAMILY_TRANSFER_BIT);
  737. } else {
  738. return CommandQueueFamilyID();
  739. }
  740. }
  741. RDD::CommandQueueID RenderingDeviceDriverMetal::command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue) {
  742. return CommandQueueID(1);
  743. }
  744. 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) {
  745. uint32_t size = p_cmd_buffers.size();
  746. if (size == 0) {
  747. return OK;
  748. }
  749. for (uint32_t i = 0; i < size - 1; i++) {
  750. MDCommandBuffer *cmd_buffer = (MDCommandBuffer *)(p_cmd_buffers[i].id);
  751. cmd_buffer->commit();
  752. }
  753. // The last command buffer will signal the fence and semaphores.
  754. MDCommandBuffer *cmd_buffer = (MDCommandBuffer *)(p_cmd_buffers[size - 1].id);
  755. Fence *fence = (Fence *)(p_cmd_fence.id);
  756. if (fence != nullptr) {
  757. [cmd_buffer->get_command_buffer() addCompletedHandler:^(id<MTLCommandBuffer> buffer) {
  758. dispatch_semaphore_signal(fence->semaphore);
  759. }];
  760. }
  761. for (uint32_t i = 0; i < p_swap_chains.size(); i++) {
  762. SwapChain *swap_chain = (SwapChain *)(p_swap_chains[i].id);
  763. RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
  764. metal_surface->present(cmd_buffer);
  765. }
  766. cmd_buffer->commit();
  767. if (p_swap_chains.size() > 0) {
  768. // Used as a signal that we're presenting, so this is the end of a frame.
  769. [device_scope endScope];
  770. [device_scope beginScope];
  771. }
  772. return OK;
  773. }
  774. void RenderingDeviceDriverMetal::command_queue_free(CommandQueueID p_cmd_queue) {
  775. }
  776. #pragma mark - Command Buffers
  777. // ----- POOL -----
  778. RDD::CommandPoolID RenderingDeviceDriverMetal::command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) {
  779. DEV_ASSERT(p_cmd_buffer_type == COMMAND_BUFFER_TYPE_PRIMARY);
  780. return rid::make(device_queue);
  781. }
  782. bool RenderingDeviceDriverMetal::command_pool_reset(CommandPoolID p_cmd_pool) {
  783. return true;
  784. }
  785. void RenderingDeviceDriverMetal::command_pool_free(CommandPoolID p_cmd_pool) {
  786. rid::release(p_cmd_pool);
  787. }
  788. // ----- BUFFER -----
  789. RDD::CommandBufferID RenderingDeviceDriverMetal::command_buffer_create(CommandPoolID p_cmd_pool) {
  790. id<MTLCommandQueue> queue = rid::get(p_cmd_pool);
  791. MDCommandBuffer *obj = new MDCommandBuffer(queue, this);
  792. command_buffers.push_back(obj);
  793. return CommandBufferID(obj);
  794. }
  795. bool RenderingDeviceDriverMetal::command_buffer_begin(CommandBufferID p_cmd_buffer) {
  796. MDCommandBuffer *obj = (MDCommandBuffer *)(p_cmd_buffer.id);
  797. obj->begin();
  798. return true;
  799. }
  800. bool RenderingDeviceDriverMetal::command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) {
  801. ERR_FAIL_V_MSG(false, "not implemented");
  802. }
  803. void RenderingDeviceDriverMetal::command_buffer_end(CommandBufferID p_cmd_buffer) {
  804. MDCommandBuffer *obj = (MDCommandBuffer *)(p_cmd_buffer.id);
  805. obj->end();
  806. }
  807. void RenderingDeviceDriverMetal::command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) {
  808. ERR_FAIL_MSG("not implemented");
  809. }
  810. #pragma mark - Swap Chain
  811. void RenderingDeviceDriverMetal::_swap_chain_release(SwapChain *p_swap_chain) {
  812. _swap_chain_release_buffers(p_swap_chain);
  813. }
  814. void RenderingDeviceDriverMetal::_swap_chain_release_buffers(SwapChain *p_swap_chain) {
  815. }
  816. RDD::SwapChainID RenderingDeviceDriverMetal::swap_chain_create(RenderingContextDriver::SurfaceID p_surface) {
  817. RenderingContextDriverMetal::Surface const *surface = (RenderingContextDriverMetal::Surface *)(p_surface);
  818. // Create the render pass that will be used to draw to the swap chain's framebuffers.
  819. RDD::Attachment attachment;
  820. attachment.format = pixel_formats->getDataFormat(surface->get_pixel_format());
  821. attachment.samples = RDD::TEXTURE_SAMPLES_1;
  822. attachment.load_op = RDD::ATTACHMENT_LOAD_OP_CLEAR;
  823. attachment.store_op = RDD::ATTACHMENT_STORE_OP_STORE;
  824. RDD::Subpass subpass;
  825. RDD::AttachmentReference color_ref;
  826. color_ref.attachment = 0;
  827. color_ref.aspect.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);
  828. subpass.color_references.push_back(color_ref);
  829. RenderPassID render_pass = render_pass_create(attachment, subpass, {}, 1, RDD::AttachmentReference());
  830. ERR_FAIL_COND_V(!render_pass, SwapChainID());
  831. // Create the empty swap chain until it is resized.
  832. SwapChain *swap_chain = memnew(SwapChain);
  833. swap_chain->surface = p_surface;
  834. swap_chain->data_format = attachment.format;
  835. swap_chain->render_pass = render_pass;
  836. return SwapChainID(swap_chain);
  837. }
  838. Error RenderingDeviceDriverMetal::swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) {
  839. DEV_ASSERT(p_cmd_queue.id != 0);
  840. DEV_ASSERT(p_swap_chain.id != 0);
  841. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  842. RenderingContextDriverMetal::Surface *surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
  843. surface->resize(p_desired_framebuffer_count);
  844. // Once everything's been created correctly, indicate the surface no longer needs to be resized.
  845. context_driver->surface_set_needs_resize(swap_chain->surface, false);
  846. return OK;
  847. }
  848. RDD::FramebufferID RenderingDeviceDriverMetal::swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) {
  849. DEV_ASSERT(p_cmd_queue.id != 0);
  850. DEV_ASSERT(p_swap_chain.id != 0);
  851. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  852. if (context_driver->surface_get_needs_resize(swap_chain->surface)) {
  853. r_resize_required = true;
  854. return FramebufferID();
  855. }
  856. RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
  857. return metal_surface->acquire_next_frame_buffer();
  858. }
  859. RDD::RenderPassID RenderingDeviceDriverMetal::swap_chain_get_render_pass(SwapChainID p_swap_chain) {
  860. const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
  861. return swap_chain->render_pass;
  862. }
  863. RDD::DataFormat RenderingDeviceDriverMetal::swap_chain_get_format(SwapChainID p_swap_chain) {
  864. const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
  865. return swap_chain->data_format;
  866. }
  867. void RenderingDeviceDriverMetal::swap_chain_set_max_fps(SwapChainID p_swap_chain, int p_max_fps) {
  868. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  869. RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
  870. metal_surface->set_max_fps(p_max_fps);
  871. }
  872. void RenderingDeviceDriverMetal::swap_chain_free(SwapChainID p_swap_chain) {
  873. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  874. _swap_chain_release(swap_chain);
  875. render_pass_free(swap_chain->render_pass);
  876. memdelete(swap_chain);
  877. }
  878. #pragma mark - Frame buffer
  879. RDD::FramebufferID RenderingDeviceDriverMetal::framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) {
  880. MDRenderPass *pass = (MDRenderPass *)(p_render_pass.id);
  881. Vector<MTL::Texture> textures;
  882. textures.resize(p_attachments.size());
  883. for (uint32_t i = 0; i < p_attachments.size(); i += 1) {
  884. MDAttachment const &a = pass->attachments[i];
  885. id<MTLTexture> tex = rid::get(p_attachments[i]);
  886. if (tex == nil) {
  887. #if DEV_ENABLED
  888. WARN_PRINT("Invalid texture for attachment " + itos(i));
  889. #endif
  890. }
  891. if (a.samples > 1) {
  892. if (tex.sampleCount != a.samples) {
  893. #if DEV_ENABLED
  894. WARN_PRINT("Mismatched sample count for attachment " + itos(i) + "; expected " + itos(a.samples) + ", got " + itos(tex.sampleCount));
  895. #endif
  896. }
  897. }
  898. textures.write[i] = tex;
  899. }
  900. MDFrameBuffer *fb = new MDFrameBuffer(textures, Size2i(p_width, p_height));
  901. return FramebufferID(fb);
  902. }
  903. void RenderingDeviceDriverMetal::framebuffer_free(FramebufferID p_framebuffer) {
  904. MDFrameBuffer *obj = (MDFrameBuffer *)(p_framebuffer.id);
  905. delete obj;
  906. }
  907. #pragma mark - Shader
  908. const uint32_t SHADER_BINARY_VERSION = 4;
  909. // region Serialization
  910. class BufWriter;
  911. template <typename T>
  912. concept Serializable = requires(T t, BufWriter &p_writer) {
  913. {
  914. t.serialize_size()
  915. } -> std::same_as<size_t>;
  916. {
  917. t.serialize(p_writer)
  918. } -> std::same_as<void>;
  919. };
  920. class BufWriter {
  921. uint8_t *data = nullptr;
  922. uint64_t length = 0; // Length of data.
  923. uint64_t pos = 0;
  924. public:
  925. BufWriter(uint8_t *p_data, uint64_t p_length) :
  926. data(p_data), length(p_length) {}
  927. template <Serializable T>
  928. void write(T const &p_value) {
  929. p_value.serialize(*this);
  930. }
  931. _FORCE_INLINE_ void write(uint32_t p_value) {
  932. DEV_ASSERT(pos + sizeof(uint32_t) <= length);
  933. pos += encode_uint32(p_value, data + pos);
  934. }
  935. _FORCE_INLINE_ void write(RD::ShaderStage p_value) {
  936. write((uint32_t)p_value);
  937. }
  938. _FORCE_INLINE_ void write(bool p_value) {
  939. DEV_ASSERT(pos + sizeof(uint8_t) <= length);
  940. *(data + pos) = p_value ? 1 : 0;
  941. pos += 1;
  942. }
  943. _FORCE_INLINE_ void write(int p_value) {
  944. write((uint32_t)p_value);
  945. }
  946. _FORCE_INLINE_ void write(uint64_t p_value) {
  947. DEV_ASSERT(pos + sizeof(uint64_t) <= length);
  948. pos += encode_uint64(p_value, data + pos);
  949. }
  950. _FORCE_INLINE_ void write(float p_value) {
  951. DEV_ASSERT(pos + sizeof(float) <= length);
  952. pos += encode_float(p_value, data + pos);
  953. }
  954. _FORCE_INLINE_ void write(double p_value) {
  955. DEV_ASSERT(pos + sizeof(double) <= length);
  956. pos += encode_double(p_value, data + pos);
  957. }
  958. void write_compressed(CharString const &p_string) {
  959. write(p_string.length()); // Uncompressed size.
  960. DEV_ASSERT(pos + sizeof(uint32_t) + Compression::get_max_compressed_buffer_size(p_string.length(), Compression::MODE_ZSTD) <= length);
  961. // Save pointer for compressed size.
  962. uint8_t *dst_size_ptr = data + pos; // Compressed size.
  963. pos += sizeof(uint32_t);
  964. int dst_size = Compression::compress(data + pos, reinterpret_cast<uint8_t const *>(p_string.ptr()), p_string.length(), Compression::MODE_ZSTD);
  965. encode_uint32(dst_size, dst_size_ptr);
  966. pos += dst_size;
  967. }
  968. void write(CharString const &p_string) {
  969. write_buffer(reinterpret_cast<const uint8_t *>(p_string.ptr()), p_string.length());
  970. }
  971. template <typename T>
  972. void write(VectorView<T> p_vector) {
  973. write(p_vector.size());
  974. for (uint32_t i = 0; i < p_vector.size(); i++) {
  975. T const &e = p_vector[i];
  976. write(e);
  977. }
  978. }
  979. void write(VectorView<uint8_t> p_vector) {
  980. write_buffer(p_vector.ptr(), p_vector.size());
  981. }
  982. template <typename K, typename V>
  983. void write(HashMap<K, V> const &p_map) {
  984. write(p_map.size());
  985. for (KeyValue<K, V> const &e : p_map) {
  986. write(e.key);
  987. write(e.value);
  988. }
  989. }
  990. uint64_t get_pos() const {
  991. return pos;
  992. }
  993. uint64_t get_length() const {
  994. return length;
  995. }
  996. private:
  997. void write_buffer(uint8_t const *p_buffer, uint32_t p_length) {
  998. write(p_length);
  999. DEV_ASSERT(pos + p_length <= length);
  1000. memcpy(data + pos, p_buffer, p_length);
  1001. pos += p_length;
  1002. }
  1003. };
  1004. class BufReader;
  1005. template <typename T>
  1006. concept Deserializable = requires(T t, BufReader &p_reader) {
  1007. {
  1008. t.serialize_size()
  1009. } -> std::same_as<size_t>;
  1010. {
  1011. t.deserialize(p_reader)
  1012. } -> std::same_as<void>;
  1013. };
  1014. class BufReader {
  1015. uint8_t const *data = nullptr;
  1016. uint64_t length = 0;
  1017. uint64_t pos = 0;
  1018. bool check_length(size_t p_size) {
  1019. if (status != Status::OK) {
  1020. return false;
  1021. }
  1022. if (pos + p_size > length) {
  1023. status = Status::SHORT_BUFFER;
  1024. return false;
  1025. }
  1026. return true;
  1027. }
  1028. #define CHECK(p_size) \
  1029. if (!check_length(p_size)) \
  1030. return
  1031. public:
  1032. enum class Status {
  1033. OK,
  1034. SHORT_BUFFER,
  1035. BAD_COMPRESSION,
  1036. };
  1037. Status status = Status::OK;
  1038. BufReader(uint8_t const *p_data, uint64_t p_length) :
  1039. data(p_data), length(p_length) {}
  1040. template <Deserializable T>
  1041. void read(T &p_value) {
  1042. p_value.deserialize(*this);
  1043. }
  1044. _FORCE_INLINE_ void read(uint32_t &p_val) {
  1045. CHECK(sizeof(uint32_t));
  1046. p_val = decode_uint32(data + pos);
  1047. pos += sizeof(uint32_t);
  1048. }
  1049. _FORCE_INLINE_ void read(RD::ShaderStage &p_val) {
  1050. uint32_t val;
  1051. read(val);
  1052. p_val = (RD::ShaderStage)val;
  1053. }
  1054. _FORCE_INLINE_ void read(bool &p_val) {
  1055. CHECK(sizeof(uint8_t));
  1056. p_val = *(data + pos) > 0;
  1057. pos += 1;
  1058. }
  1059. _FORCE_INLINE_ void read(uint64_t &p_val) {
  1060. CHECK(sizeof(uint64_t));
  1061. p_val = decode_uint64(data + pos);
  1062. pos += sizeof(uint64_t);
  1063. }
  1064. _FORCE_INLINE_ void read(float &p_val) {
  1065. CHECK(sizeof(float));
  1066. p_val = decode_float(data + pos);
  1067. pos += sizeof(float);
  1068. }
  1069. _FORCE_INLINE_ void read(double &p_val) {
  1070. CHECK(sizeof(double));
  1071. p_val = decode_double(data + pos);
  1072. pos += sizeof(double);
  1073. }
  1074. void read(CharString &p_val) {
  1075. uint32_t len;
  1076. read(len);
  1077. CHECK(len);
  1078. p_val.resize(len + 1 /* NUL */);
  1079. memcpy(p_val.ptrw(), data + pos, len);
  1080. p_val.set(len, 0);
  1081. pos += len;
  1082. }
  1083. void read_compressed(CharString &p_val) {
  1084. uint32_t len;
  1085. read(len);
  1086. uint32_t comp_size;
  1087. read(comp_size);
  1088. CHECK(comp_size);
  1089. p_val.resize(len + 1 /* NUL */);
  1090. uint32_t bytes = (uint32_t)Compression::decompress(reinterpret_cast<uint8_t *>(p_val.ptrw()), len, data + pos, comp_size, Compression::MODE_ZSTD);
  1091. if (bytes != len) {
  1092. status = Status::BAD_COMPRESSION;
  1093. return;
  1094. }
  1095. p_val.set(len, 0);
  1096. pos += comp_size;
  1097. }
  1098. void read(LocalVector<uint8_t> &p_val) {
  1099. uint32_t len;
  1100. read(len);
  1101. CHECK(len);
  1102. p_val.resize(len);
  1103. memcpy(p_val.ptr(), data + pos, len);
  1104. pos += len;
  1105. }
  1106. template <typename T>
  1107. void read(LocalVector<T> &p_val) {
  1108. uint32_t len;
  1109. read(len);
  1110. CHECK(len);
  1111. p_val.resize(len);
  1112. for (uint32_t i = 0; i < len; i++) {
  1113. read(p_val[i]);
  1114. }
  1115. }
  1116. template <typename K, typename V>
  1117. void read(HashMap<K, V> &p_map) {
  1118. uint32_t len;
  1119. read(len);
  1120. CHECK(len);
  1121. p_map.reserve(len);
  1122. for (uint32_t i = 0; i < len; i++) {
  1123. K key;
  1124. read(key);
  1125. V value;
  1126. read(value);
  1127. p_map[key] = value;
  1128. }
  1129. }
  1130. #undef CHECK
  1131. };
  1132. const uint32_t R32UI_ALIGNMENT_CONSTANT_ID = 65535;
  1133. struct ComputeSize {
  1134. uint32_t x = 0;
  1135. uint32_t y = 0;
  1136. uint32_t z = 0;
  1137. size_t serialize_size() const {
  1138. return sizeof(uint32_t) * 3;
  1139. }
  1140. void serialize(BufWriter &p_writer) const {
  1141. p_writer.write(x);
  1142. p_writer.write(y);
  1143. p_writer.write(z);
  1144. }
  1145. void deserialize(BufReader &p_reader) {
  1146. p_reader.read(x);
  1147. p_reader.read(y);
  1148. p_reader.read(z);
  1149. }
  1150. };
  1151. struct ShaderStageData {
  1152. RD::ShaderStage stage = RD::ShaderStage::SHADER_STAGE_MAX;
  1153. uint32_t is_position_invariant = UINT32_MAX;
  1154. uint32_t supports_fast_math = UINT32_MAX;
  1155. CharString entry_point_name;
  1156. CharString source;
  1157. size_t serialize_size() const {
  1158. int comp_size = Compression::get_max_compressed_buffer_size(source.length(), Compression::MODE_ZSTD);
  1159. return sizeof(uint32_t) // Stage.
  1160. + sizeof(uint32_t) // is_position_invariant
  1161. + sizeof(uint32_t) // supports_fast_math
  1162. + sizeof(uint32_t) /* entry_point_name.utf8().length */
  1163. + entry_point_name.length() + sizeof(uint32_t) /* uncompressed size */ + sizeof(uint32_t) /* compressed size */ + comp_size;
  1164. }
  1165. void serialize(BufWriter &p_writer) const {
  1166. p_writer.write((uint32_t)stage);
  1167. p_writer.write(is_position_invariant);
  1168. p_writer.write(supports_fast_math);
  1169. p_writer.write(entry_point_name);
  1170. p_writer.write_compressed(source);
  1171. }
  1172. void deserialize(BufReader &p_reader) {
  1173. p_reader.read((uint32_t &)stage);
  1174. p_reader.read(is_position_invariant);
  1175. p_reader.read(supports_fast_math);
  1176. p_reader.read(entry_point_name);
  1177. p_reader.read_compressed(source);
  1178. }
  1179. };
  1180. struct SpecializationConstantData {
  1181. uint32_t constant_id = UINT32_MAX;
  1182. RD::PipelineSpecializationConstantType type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT;
  1183. ShaderStageUsage stages = ShaderStageUsage::None;
  1184. // Specifies the stages the constant is used by Metal.
  1185. ShaderStageUsage used_stages = ShaderStageUsage::None;
  1186. uint32_t int_value = UINT32_MAX;
  1187. size_t serialize_size() const {
  1188. return sizeof(constant_id) + sizeof(uint32_t) // type
  1189. + sizeof(stages) + sizeof(used_stages) // used_stages
  1190. + sizeof(int_value); // int_value
  1191. }
  1192. void serialize(BufWriter &p_writer) const {
  1193. p_writer.write(constant_id);
  1194. p_writer.write((uint32_t)type);
  1195. p_writer.write(stages);
  1196. p_writer.write(used_stages);
  1197. p_writer.write(int_value);
  1198. }
  1199. void deserialize(BufReader &p_reader) {
  1200. p_reader.read(constant_id);
  1201. p_reader.read((uint32_t &)type);
  1202. p_reader.read((uint32_t &)stages);
  1203. p_reader.read((uint32_t &)used_stages);
  1204. p_reader.read(int_value);
  1205. }
  1206. };
  1207. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) UniformData {
  1208. RD::UniformType type = RD::UniformType::UNIFORM_TYPE_MAX;
  1209. uint32_t binding = UINT32_MAX;
  1210. bool writable = false;
  1211. uint32_t length = UINT32_MAX;
  1212. ShaderStageUsage stages = ShaderStageUsage::None;
  1213. // Specifies the stages the uniform data is
  1214. // used by the Metal shader.
  1215. ShaderStageUsage active_stages = ShaderStageUsage::None;
  1216. BindingInfoMap bindings;
  1217. BindingInfoMap bindings_secondary;
  1218. size_t serialize_size() const {
  1219. size_t size = 0;
  1220. size += sizeof(uint32_t); // type
  1221. size += sizeof(uint32_t); // binding
  1222. size += sizeof(uint32_t); // writable
  1223. size += sizeof(uint32_t); // length
  1224. size += sizeof(uint32_t); // stages
  1225. size += sizeof(uint32_t); // active_stages
  1226. size += sizeof(uint32_t); // bindings.size()
  1227. size += sizeof(uint32_t) * bindings.size(); // Total size of keys.
  1228. for (KeyValue<RD::ShaderStage, BindingInfo> const &e : bindings) {
  1229. size += e.value.serialize_size();
  1230. }
  1231. size += sizeof(uint32_t); // bindings_secondary.size()
  1232. size += sizeof(uint32_t) * bindings_secondary.size(); // Total size of keys.
  1233. for (KeyValue<RD::ShaderStage, BindingInfo> const &e : bindings_secondary) {
  1234. size += e.value.serialize_size();
  1235. }
  1236. return size;
  1237. }
  1238. void serialize(BufWriter &p_writer) const {
  1239. p_writer.write((uint32_t)type);
  1240. p_writer.write(binding);
  1241. p_writer.write(writable);
  1242. p_writer.write(length);
  1243. p_writer.write(stages);
  1244. p_writer.write(active_stages);
  1245. p_writer.write(bindings);
  1246. p_writer.write(bindings_secondary);
  1247. }
  1248. void deserialize(BufReader &p_reader) {
  1249. p_reader.read((uint32_t &)type);
  1250. p_reader.read(binding);
  1251. p_reader.read(writable);
  1252. p_reader.read(length);
  1253. p_reader.read((uint32_t &)stages);
  1254. p_reader.read((uint32_t &)active_stages);
  1255. p_reader.read(bindings);
  1256. p_reader.read(bindings_secondary);
  1257. }
  1258. };
  1259. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) UniformSetData {
  1260. uint32_t index = UINT32_MAX;
  1261. LocalVector<UniformData> uniforms;
  1262. size_t serialize_size() const {
  1263. size_t size = 0;
  1264. size += sizeof(uint32_t); // index
  1265. size += sizeof(uint32_t); // uniforms.size()
  1266. for (UniformData const &e : uniforms) {
  1267. size += e.serialize_size();
  1268. }
  1269. return size;
  1270. }
  1271. void serialize(BufWriter &p_writer) const {
  1272. p_writer.write(index);
  1273. p_writer.write(VectorView(uniforms));
  1274. }
  1275. void deserialize(BufReader &p_reader) {
  1276. p_reader.read(index);
  1277. p_reader.read(uniforms);
  1278. }
  1279. UniformSetData() = default;
  1280. UniformSetData(uint32_t p_index) :
  1281. index(p_index) {}
  1282. };
  1283. struct PushConstantData {
  1284. uint32_t size = UINT32_MAX;
  1285. ShaderStageUsage stages = ShaderStageUsage::None;
  1286. ShaderStageUsage used_stages = ShaderStageUsage::None;
  1287. HashMap<RD::ShaderStage, uint32_t> msl_binding;
  1288. size_t serialize_size() const {
  1289. return sizeof(uint32_t) // size
  1290. + sizeof(uint32_t) // stages
  1291. + sizeof(uint32_t) // used_stages
  1292. + sizeof(uint32_t) // msl_binding.size()
  1293. + sizeof(uint32_t) * msl_binding.size() // keys
  1294. + sizeof(uint32_t) * msl_binding.size(); // values
  1295. }
  1296. void serialize(BufWriter &p_writer) const {
  1297. p_writer.write(size);
  1298. p_writer.write((uint32_t)stages);
  1299. p_writer.write((uint32_t)used_stages);
  1300. p_writer.write(msl_binding);
  1301. }
  1302. void deserialize(BufReader &p_reader) {
  1303. p_reader.read(size);
  1304. p_reader.read((uint32_t &)stages);
  1305. p_reader.read((uint32_t &)used_stages);
  1306. p_reader.read(msl_binding);
  1307. }
  1308. };
  1309. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) ShaderBinaryData {
  1310. enum Flags : uint32_t {
  1311. NONE = 0,
  1312. NEEDS_VIEW_MASK_BUFFER = 1 << 0,
  1313. USES_ARGUMENT_BUFFERS = 1 << 1,
  1314. };
  1315. CharString shader_name;
  1316. // The Metal language version specified when compiling SPIR-V to MSL.
  1317. // Format is major * 10000 + minor * 100 + patch.
  1318. uint32_t msl_version = UINT32_MAX;
  1319. uint32_t vertex_input_mask = UINT32_MAX;
  1320. uint32_t fragment_output_mask = UINT32_MAX;
  1321. uint32_t spirv_specialization_constants_ids_mask = UINT32_MAX;
  1322. uint32_t flags = NONE;
  1323. ComputeSize compute_local_size;
  1324. PushConstantData push_constant;
  1325. LocalVector<ShaderStageData> stages;
  1326. LocalVector<SpecializationConstantData> constants;
  1327. LocalVector<UniformSetData> uniforms;
  1328. MTLLanguageVersion get_msl_version() const {
  1329. uint32_t major = msl_version / 10000;
  1330. uint32_t minor = (msl_version / 100) % 100;
  1331. return MTLLanguageVersion((major << 0x10) + minor);
  1332. }
  1333. bool is_compute() const {
  1334. return std::any_of(stages.begin(), stages.end(), [](ShaderStageData const &e) {
  1335. return e.stage == RD::ShaderStage::SHADER_STAGE_COMPUTE;
  1336. });
  1337. }
  1338. bool needs_view_mask_buffer() const {
  1339. return flags & NEEDS_VIEW_MASK_BUFFER;
  1340. }
  1341. void set_needs_view_mask_buffer(bool p_value) {
  1342. if (p_value) {
  1343. flags |= NEEDS_VIEW_MASK_BUFFER;
  1344. } else {
  1345. flags &= ~NEEDS_VIEW_MASK_BUFFER;
  1346. }
  1347. }
  1348. bool uses_argument_buffers() const {
  1349. return flags & USES_ARGUMENT_BUFFERS;
  1350. }
  1351. void set_uses_argument_buffers(bool p_value) {
  1352. if (p_value) {
  1353. flags |= USES_ARGUMENT_BUFFERS;
  1354. } else {
  1355. flags &= ~USES_ARGUMENT_BUFFERS;
  1356. }
  1357. }
  1358. size_t serialize_size() const {
  1359. size_t size = 0;
  1360. size += sizeof(uint32_t) + shader_name.length(); // shader_name
  1361. size += sizeof(msl_version);
  1362. size += sizeof(vertex_input_mask);
  1363. size += sizeof(fragment_output_mask);
  1364. size += sizeof(spirv_specialization_constants_ids_mask);
  1365. size += sizeof(flags);
  1366. size += compute_local_size.serialize_size();
  1367. size += push_constant.serialize_size();
  1368. size += sizeof(uint32_t); // stages.size()
  1369. for (ShaderStageData const &e : stages) {
  1370. size += e.serialize_size();
  1371. }
  1372. size += sizeof(uint32_t); // constants.size()
  1373. for (SpecializationConstantData const &e : constants) {
  1374. size += e.serialize_size();
  1375. }
  1376. size += sizeof(uint32_t); // uniforms.size()
  1377. for (UniformSetData const &e : uniforms) {
  1378. size += e.serialize_size();
  1379. }
  1380. return size;
  1381. }
  1382. void serialize(BufWriter &p_writer) const {
  1383. p_writer.write(shader_name);
  1384. p_writer.write(msl_version);
  1385. p_writer.write(vertex_input_mask);
  1386. p_writer.write(fragment_output_mask);
  1387. p_writer.write(spirv_specialization_constants_ids_mask);
  1388. p_writer.write(flags);
  1389. p_writer.write(compute_local_size);
  1390. p_writer.write(push_constant);
  1391. p_writer.write(VectorView(stages));
  1392. p_writer.write(VectorView(constants));
  1393. p_writer.write(VectorView(uniforms));
  1394. }
  1395. void deserialize(BufReader &p_reader) {
  1396. p_reader.read(shader_name);
  1397. p_reader.read(msl_version);
  1398. p_reader.read(vertex_input_mask);
  1399. p_reader.read(fragment_output_mask);
  1400. p_reader.read(spirv_specialization_constants_ids_mask);
  1401. p_reader.read(flags);
  1402. p_reader.read(compute_local_size);
  1403. p_reader.read(push_constant);
  1404. p_reader.read(stages);
  1405. p_reader.read(constants);
  1406. p_reader.read(uniforms);
  1407. }
  1408. };
  1409. // endregion
  1410. String RenderingDeviceDriverMetal::shader_get_binary_cache_key() {
  1411. static const String cache_key = "Metal-SV" + uitos(SHADER_BINARY_VERSION);
  1412. return cache_key;
  1413. }
  1414. Error RenderingDeviceDriverMetal::_reflect_spirv16(VectorView<ShaderStageSPIRVData> p_spirv, ShaderReflection &r_reflection, ShaderMeta &r_shader_meta) {
  1415. using namespace spirv_cross;
  1416. using spirv_cross::Resource;
  1417. r_reflection = {};
  1418. r_shader_meta = {};
  1419. for (uint32_t i = 0; i < p_spirv.size(); i++) {
  1420. ShaderStageSPIRVData const &v = p_spirv[i];
  1421. ShaderStage stage = v.shader_stage;
  1422. uint32_t const *const ir = reinterpret_cast<uint32_t const *const>(v.spirv.ptr());
  1423. size_t word_count = v.spirv.size() / sizeof(uint32_t);
  1424. Parser parser(ir, word_count);
  1425. try {
  1426. parser.parse();
  1427. } catch (CompilerError &e) {
  1428. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Failed to parse IR at stage " + String(SHADER_STAGE_NAMES[stage]) + ": " + e.what());
  1429. }
  1430. ShaderStage stage_flag = (ShaderStage)(1 << p_spirv[i].shader_stage);
  1431. if (p_spirv[i].shader_stage == SHADER_STAGE_COMPUTE) {
  1432. r_reflection.is_compute = true;
  1433. ERR_FAIL_COND_V_MSG(p_spirv.size() != 1, FAILED,
  1434. "Compute shaders can only receive one stage, dedicated to compute.");
  1435. }
  1436. ERR_FAIL_COND_V_MSG(r_reflection.stages.has_flag(stage_flag), FAILED,
  1437. "Stage " + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + " submitted more than once.");
  1438. ParsedIR &pir = parser.get_parsed_ir();
  1439. using BT = SPIRType::BaseType;
  1440. Compiler compiler(std::move(pir));
  1441. if (r_reflection.is_compute) {
  1442. r_reflection.compute_local_size[0] = compiler.get_execution_mode_argument(spv::ExecutionModeLocalSize, 0);
  1443. r_reflection.compute_local_size[1] = compiler.get_execution_mode_argument(spv::ExecutionModeLocalSize, 1);
  1444. r_reflection.compute_local_size[2] = compiler.get_execution_mode_argument(spv::ExecutionModeLocalSize, 2);
  1445. }
  1446. // Parse bindings.
  1447. auto get_decoration = [&compiler](spirv_cross::ID id, spv::Decoration decoration) {
  1448. uint32_t res = -1;
  1449. if (compiler.has_decoration(id, decoration)) {
  1450. res = compiler.get_decoration(id, decoration);
  1451. }
  1452. return res;
  1453. };
  1454. // Always clearer than a boolean.
  1455. enum class Writable {
  1456. No,
  1457. Maybe,
  1458. };
  1459. // clang-format off
  1460. enum {
  1461. SPIRV_WORD_SIZE = sizeof(uint32_t),
  1462. SPIRV_DATA_ALIGNMENT = 4 * SPIRV_WORD_SIZE,
  1463. };
  1464. // clang-format on
  1465. auto process_uniforms = [&r_reflection, &compiler, &get_decoration, stage, stage_flag](SmallVector<Resource> &resources, Writable writable, std::function<RDD::UniformType(SPIRType const &)> uniform_type) {
  1466. for (Resource const &res : resources) {
  1467. ShaderUniform uniform;
  1468. std::string const &name = compiler.get_name(res.id);
  1469. uint32_t set = get_decoration(res.id, spv::DecorationDescriptorSet);
  1470. ERR_FAIL_COND_V_MSG(set == (uint32_t)-1, FAILED, "No descriptor set found");
  1471. ERR_FAIL_COND_V_MSG(set >= MAX_UNIFORM_SETS, FAILED, "On shader stage '" + String(SHADER_STAGE_NAMES[stage]) + "', uniform '" + name.c_str() + "' uses a set (" + itos(set) + ") index larger than what is supported (" + itos(MAX_UNIFORM_SETS) + ").");
  1472. uniform.binding = get_decoration(res.id, spv::DecorationBinding);
  1473. ERR_FAIL_COND_V_MSG(uniform.binding == (uint32_t)-1, FAILED, "No binding found");
  1474. SPIRType const &a_type = compiler.get_type(res.type_id);
  1475. uniform.type = uniform_type(a_type);
  1476. // Update length.
  1477. switch (a_type.basetype) {
  1478. case BT::Struct: {
  1479. if (uniform.type == UNIFORM_TYPE_STORAGE_BUFFER) {
  1480. // Consistent with spirv_reflect.
  1481. uniform.length = 0;
  1482. } else {
  1483. uniform.length = round_up_to_alignment(compiler.get_declared_struct_size(a_type), SPIRV_DATA_ALIGNMENT);
  1484. }
  1485. } break;
  1486. case BT::Image:
  1487. case BT::Sampler:
  1488. case BT::SampledImage: {
  1489. uniform.length = 1;
  1490. for (uint32_t const &a : a_type.array) {
  1491. uniform.length *= a;
  1492. }
  1493. } break;
  1494. default:
  1495. break;
  1496. }
  1497. // Update writable.
  1498. if (writable == Writable::Maybe) {
  1499. if (a_type.basetype == BT::Struct) {
  1500. Bitset flags = compiler.get_buffer_block_flags(res.id);
  1501. uniform.writable = !compiler.has_decoration(res.id, spv::DecorationNonWritable) && !flags.get(spv::DecorationNonWritable);
  1502. } else if (a_type.basetype == BT::Image) {
  1503. if (a_type.image.access == spv::AccessQualifierMax) {
  1504. uniform.writable = !compiler.has_decoration(res.id, spv::DecorationNonWritable);
  1505. } else {
  1506. uniform.writable = a_type.image.access != spv::AccessQualifierReadOnly;
  1507. }
  1508. }
  1509. }
  1510. if (set < (uint32_t)r_reflection.uniform_sets.size()) {
  1511. // Check if this already exists.
  1512. bool exists = false;
  1513. for (uint32_t k = 0; k < r_reflection.uniform_sets[set].size(); k++) {
  1514. if (r_reflection.uniform_sets[set][k].binding == uniform.binding) {
  1515. // Already exists, verify that it's the same type.
  1516. ERR_FAIL_COND_V_MSG(r_reflection.uniform_sets[set][k].type != uniform.type, FAILED,
  1517. "On shader stage '" + String(SHADER_STAGE_NAMES[stage]) + "', uniform '" + name.c_str() + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(uniform.binding) + " with different uniform type.");
  1518. // Also, verify that it's the same size.
  1519. ERR_FAIL_COND_V_MSG(r_reflection.uniform_sets[set][k].length != uniform.length, FAILED,
  1520. "On shader stage '" + String(SHADER_STAGE_NAMES[stage]) + "', uniform '" + name.c_str() + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(uniform.binding) + " with different uniform size.");
  1521. // Also, verify that it has the same writability.
  1522. ERR_FAIL_COND_V_MSG(r_reflection.uniform_sets[set][k].writable != uniform.writable, FAILED,
  1523. "On shader stage '" + String(SHADER_STAGE_NAMES[stage]) + "', uniform '" + name.c_str() + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(uniform.binding) + " with different writability.");
  1524. // Just append stage mask and continue.
  1525. r_reflection.uniform_sets.write[set].write[k].stages.set_flag(stage_flag);
  1526. exists = true;
  1527. break;
  1528. }
  1529. }
  1530. if (exists) {
  1531. continue; // Merged.
  1532. }
  1533. }
  1534. uniform.stages.set_flag(stage_flag);
  1535. if (set >= (uint32_t)r_reflection.uniform_sets.size()) {
  1536. r_reflection.uniform_sets.resize(set + 1);
  1537. }
  1538. r_reflection.uniform_sets.write[set].push_back(uniform);
  1539. }
  1540. return OK;
  1541. };
  1542. ShaderResources resources = compiler.get_shader_resources();
  1543. process_uniforms(resources.uniform_buffers, Writable::No, [](SPIRType const &a_type) {
  1544. DEV_ASSERT(a_type.basetype == BT::Struct);
  1545. return UNIFORM_TYPE_UNIFORM_BUFFER;
  1546. });
  1547. process_uniforms(resources.storage_buffers, Writable::Maybe, [](SPIRType const &a_type) {
  1548. DEV_ASSERT(a_type.basetype == BT::Struct);
  1549. return UNIFORM_TYPE_STORAGE_BUFFER;
  1550. });
  1551. process_uniforms(resources.storage_images, Writable::Maybe, [](SPIRType const &a_type) {
  1552. DEV_ASSERT(a_type.basetype == BT::Image);
  1553. if (a_type.image.dim == spv::DimBuffer) {
  1554. return UNIFORM_TYPE_IMAGE_BUFFER;
  1555. } else {
  1556. return UNIFORM_TYPE_IMAGE;
  1557. }
  1558. });
  1559. process_uniforms(resources.sampled_images, Writable::No, [](SPIRType const &a_type) {
  1560. DEV_ASSERT(a_type.basetype == BT::SampledImage);
  1561. return UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  1562. });
  1563. process_uniforms(resources.separate_images, Writable::No, [](SPIRType const &a_type) {
  1564. DEV_ASSERT(a_type.basetype == BT::Image);
  1565. if (a_type.image.dim == spv::DimBuffer) {
  1566. return UNIFORM_TYPE_TEXTURE_BUFFER;
  1567. } else {
  1568. return UNIFORM_TYPE_TEXTURE;
  1569. }
  1570. });
  1571. process_uniforms(resources.separate_samplers, Writable::No, [](SPIRType const &a_type) {
  1572. DEV_ASSERT(a_type.basetype == BT::Sampler);
  1573. return UNIFORM_TYPE_SAMPLER;
  1574. });
  1575. process_uniforms(resources.subpass_inputs, Writable::No, [](SPIRType const &a_type) {
  1576. DEV_ASSERT(a_type.basetype == BT::Image && a_type.image.dim == spv::DimSubpassData);
  1577. return UNIFORM_TYPE_INPUT_ATTACHMENT;
  1578. });
  1579. if (!resources.push_constant_buffers.empty()) {
  1580. // There can be only one push constant block.
  1581. Resource const &res = resources.push_constant_buffers.front();
  1582. size_t push_constant_size = round_up_to_alignment(compiler.get_declared_struct_size(compiler.get_type(res.base_type_id)), SPIRV_DATA_ALIGNMENT);
  1583. ERR_FAIL_COND_V_MSG(r_reflection.push_constant_size && r_reflection.push_constant_size != push_constant_size, FAILED,
  1584. "Reflection of SPIR-V shader stage '" + String(SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "': Push constant block must be the same across shader stages.");
  1585. r_reflection.push_constant_size = push_constant_size;
  1586. r_reflection.push_constant_stages.set_flag(stage_flag);
  1587. }
  1588. ERR_FAIL_COND_V_MSG(!resources.atomic_counters.empty(), FAILED, "Atomic counters not supported");
  1589. ERR_FAIL_COND_V_MSG(!resources.acceleration_structures.empty(), FAILED, "Acceleration structures not supported");
  1590. ERR_FAIL_COND_V_MSG(!resources.shader_record_buffers.empty(), FAILED, "Shader record buffers not supported");
  1591. if (stage == SHADER_STAGE_VERTEX && !resources.stage_inputs.empty()) {
  1592. for (Resource const &res : resources.stage_inputs) {
  1593. SPIRType a_type = compiler.get_type(res.base_type_id);
  1594. uint32_t loc = get_decoration(res.id, spv::DecorationLocation);
  1595. if (loc != (uint32_t)-1) {
  1596. r_reflection.vertex_input_mask |= 1 << loc;
  1597. }
  1598. }
  1599. }
  1600. if (stage == SHADER_STAGE_FRAGMENT && !resources.stage_outputs.empty()) {
  1601. for (Resource const &res : resources.stage_outputs) {
  1602. SPIRType a_type = compiler.get_type(res.base_type_id);
  1603. uint32_t loc = get_decoration(res.id, spv::DecorationLocation);
  1604. uint32_t built_in = spv::BuiltIn(get_decoration(res.id, spv::DecorationBuiltIn));
  1605. if (loc != (uint32_t)-1 && built_in != spv::BuiltInFragDepth) {
  1606. r_reflection.fragment_output_mask |= 1 << loc;
  1607. }
  1608. }
  1609. }
  1610. for (const BuiltInResource &res : resources.builtin_inputs) {
  1611. if (res.builtin == spv::BuiltInViewIndex || res.builtin == spv::BuiltInViewportIndex) {
  1612. r_shader_meta.has_multiview = true;
  1613. }
  1614. }
  1615. if (!r_shader_meta.has_multiview) {
  1616. for (const BuiltInResource &res : resources.builtin_outputs) {
  1617. if (res.builtin == spv::BuiltInViewIndex || res.builtin == spv::BuiltInViewportIndex) {
  1618. r_shader_meta.has_multiview = true;
  1619. }
  1620. }
  1621. }
  1622. // Specialization constants.
  1623. for (SpecializationConstant const &constant : compiler.get_specialization_constants()) {
  1624. int32_t existing = -1;
  1625. ShaderSpecializationConstant sconst;
  1626. SPIRConstant &spc = compiler.get_constant(constant.id);
  1627. SPIRType const &spct = compiler.get_type(spc.constant_type);
  1628. sconst.constant_id = constant.constant_id;
  1629. sconst.int_value = 0;
  1630. switch (spct.basetype) {
  1631. case BT::Boolean: {
  1632. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL;
  1633. sconst.bool_value = spc.scalar() != 0;
  1634. } break;
  1635. case BT::Int:
  1636. case BT::UInt: {
  1637. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT;
  1638. sconst.int_value = spc.scalar();
  1639. } break;
  1640. case BT::Float: {
  1641. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT;
  1642. sconst.float_value = spc.scalar_f32();
  1643. } break;
  1644. default:
  1645. ERR_FAIL_V_MSG(FAILED, "Unsupported specialization constant type");
  1646. }
  1647. sconst.stages.set_flag(stage_flag);
  1648. for (uint32_t k = 0; k < r_reflection.specialization_constants.size(); k++) {
  1649. if (r_reflection.specialization_constants[k].constant_id == sconst.constant_id) {
  1650. ERR_FAIL_COND_V_MSG(r_reflection.specialization_constants[k].type != sconst.type, FAILED, "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their types differ.");
  1651. ERR_FAIL_COND_V_MSG(r_reflection.specialization_constants[k].int_value != sconst.int_value, FAILED, "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their default values differ.");
  1652. existing = k;
  1653. break;
  1654. }
  1655. }
  1656. if (existing > 0) {
  1657. r_reflection.specialization_constants.write[existing].stages.set_flag(stage_flag);
  1658. } else {
  1659. r_reflection.specialization_constants.push_back(sconst);
  1660. }
  1661. }
  1662. r_reflection.stages.set_flag(stage_flag);
  1663. }
  1664. // Sort all uniform_sets.
  1665. for (uint32_t i = 0; i < r_reflection.uniform_sets.size(); i++) {
  1666. r_reflection.uniform_sets.write[i].sort();
  1667. }
  1668. return OK;
  1669. }
  1670. Vector<uint8_t> RenderingDeviceDriverMetal::shader_compile_binary_from_spirv(VectorView<ShaderStageSPIRVData> p_spirv, const String &p_shader_name) {
  1671. using Result = ::Vector<uint8_t>;
  1672. using namespace spirv_cross;
  1673. using spirv_cross::CompilerMSL;
  1674. using spirv_cross::Resource;
  1675. ShaderReflection spirv_data;
  1676. ShaderMeta shader_meta;
  1677. ERR_FAIL_COND_V(_reflect_spirv16(p_spirv, spirv_data, shader_meta), Result());
  1678. ShaderBinaryData bin_data{};
  1679. if (!p_shader_name.is_empty()) {
  1680. bin_data.shader_name = p_shader_name.utf8();
  1681. } else {
  1682. bin_data.shader_name = "unnamed";
  1683. }
  1684. bin_data.vertex_input_mask = spirv_data.vertex_input_mask;
  1685. bin_data.fragment_output_mask = spirv_data.fragment_output_mask;
  1686. bin_data.compute_local_size = ComputeSize{
  1687. .x = spirv_data.compute_local_size[0],
  1688. .y = spirv_data.compute_local_size[1],
  1689. .z = spirv_data.compute_local_size[2],
  1690. };
  1691. bin_data.push_constant.size = spirv_data.push_constant_size;
  1692. bin_data.push_constant.stages = (ShaderStageUsage)(uint8_t)spirv_data.push_constant_stages;
  1693. bin_data.set_needs_view_mask_buffer(shader_meta.has_multiview);
  1694. for (uint32_t i = 0; i < spirv_data.uniform_sets.size(); i++) {
  1695. const ::Vector<ShaderUniform> &spirv_set = spirv_data.uniform_sets[i];
  1696. UniformSetData set(i);
  1697. for (const ShaderUniform &spirv_uniform : spirv_set) {
  1698. UniformData binding{};
  1699. binding.type = spirv_uniform.type;
  1700. binding.binding = spirv_uniform.binding;
  1701. binding.writable = spirv_uniform.writable;
  1702. binding.stages = (ShaderStageUsage)(uint8_t)spirv_uniform.stages;
  1703. binding.length = spirv_uniform.length;
  1704. set.uniforms.push_back(binding);
  1705. }
  1706. bin_data.uniforms.push_back(set);
  1707. }
  1708. for (const ShaderSpecializationConstant &spirv_sc : spirv_data.specialization_constants) {
  1709. SpecializationConstantData spec_constant{};
  1710. spec_constant.type = spirv_sc.type;
  1711. spec_constant.constant_id = spirv_sc.constant_id;
  1712. spec_constant.int_value = spirv_sc.int_value;
  1713. spec_constant.stages = (ShaderStageUsage)(uint8_t)spirv_sc.stages;
  1714. bin_data.constants.push_back(spec_constant);
  1715. bin_data.spirv_specialization_constants_ids_mask |= (1 << spirv_sc.constant_id);
  1716. }
  1717. // Reflection using SPIRV-Cross:
  1718. // https://github.com/KhronosGroup/SPIRV-Cross/wiki/Reflection-API-user-guide
  1719. CompilerMSL::Options msl_options{};
  1720. msl_options.set_msl_version(version_major, version_minor);
  1721. bin_data.msl_version = msl_options.msl_version;
  1722. #if TARGET_OS_OSX
  1723. msl_options.platform = CompilerMSL::Options::macOS;
  1724. #else
  1725. msl_options.platform = CompilerMSL::Options::iOS;
  1726. #endif
  1727. #if TARGET_OS_IPHONE
  1728. msl_options.ios_use_simdgroup_functions = (*device_properties).features.simdPermute;
  1729. msl_options.ios_support_base_vertex_instance = true;
  1730. #endif
  1731. bool disable_argument_buffers = false;
  1732. if (String v = OS::get_singleton()->get_environment(U"GODOT_DISABLE_ARGUMENT_BUFFERS"); v == U"1") {
  1733. disable_argument_buffers = true;
  1734. }
  1735. if (device_properties->features.argument_buffers_tier >= MTLArgumentBuffersTier2 && !disable_argument_buffers) {
  1736. msl_options.argument_buffers_tier = CompilerMSL::Options::ArgumentBuffersTier::Tier2;
  1737. msl_options.argument_buffers = true;
  1738. bin_data.set_uses_argument_buffers(true);
  1739. } else {
  1740. msl_options.argument_buffers_tier = CompilerMSL::Options::ArgumentBuffersTier::Tier1;
  1741. // Tier 1 argument buffers don't support writable textures, so we disable them completely.
  1742. msl_options.argument_buffers = false;
  1743. bin_data.set_uses_argument_buffers(false);
  1744. }
  1745. msl_options.force_active_argument_buffer_resources = true;
  1746. // We can't use this, as we have to add the descriptor sets via compiler.add_msl_resource_binding.
  1747. // msl_options.pad_argument_buffer_resources = true;
  1748. msl_options.texture_buffer_native = true; // Enable texture buffer support.
  1749. msl_options.use_framebuffer_fetch_subpasses = false;
  1750. msl_options.pad_fragment_output_components = true;
  1751. msl_options.r32ui_alignment_constant_id = R32UI_ALIGNMENT_CONSTANT_ID;
  1752. msl_options.agx_manual_cube_grad_fixup = true;
  1753. if (shader_meta.has_multiview) {
  1754. msl_options.multiview = true;
  1755. msl_options.multiview_layered_rendering = true;
  1756. msl_options.view_mask_buffer_index = VIEW_MASK_BUFFER_INDEX;
  1757. }
  1758. CompilerGLSL::Options options{};
  1759. options.vertex.flip_vert_y = true;
  1760. #if DEV_ENABLED
  1761. options.emit_line_directives = true;
  1762. #endif
  1763. for (uint32_t i = 0; i < p_spirv.size(); i++) {
  1764. ShaderStageSPIRVData const &v = p_spirv[i];
  1765. ShaderStage stage = v.shader_stage;
  1766. char const *stage_name = SHADER_STAGE_NAMES[stage];
  1767. uint32_t const *const ir = reinterpret_cast<uint32_t const *const>(v.spirv.ptr());
  1768. size_t word_count = v.spirv.size() / sizeof(uint32_t);
  1769. Parser parser(ir, word_count);
  1770. try {
  1771. parser.parse();
  1772. } catch (CompilerError &e) {
  1773. ERR_FAIL_V_MSG(Result(), "Failed to parse IR at stage " + String(SHADER_STAGE_NAMES[stage]) + ": " + e.what());
  1774. }
  1775. CompilerMSL compiler(std::move(parser.get_parsed_ir()));
  1776. compiler.set_msl_options(msl_options);
  1777. compiler.set_common_options(options);
  1778. std::unordered_set<VariableID> active = compiler.get_active_interface_variables();
  1779. ShaderResources resources = compiler.get_shader_resources();
  1780. std::string source;
  1781. try {
  1782. source = compiler.compile();
  1783. } catch (CompilerError &e) {
  1784. ERR_FAIL_V_MSG(Result(), "Failed to compile stage " + String(SHADER_STAGE_NAMES[stage]) + ": " + e.what());
  1785. }
  1786. ERR_FAIL_COND_V_MSG(compiler.get_entry_points_and_stages().size() != 1, Result(), "Expected a single entry point and stage.");
  1787. SmallVector<EntryPoint> entry_pts_stages = compiler.get_entry_points_and_stages();
  1788. EntryPoint &entry_point_stage = entry_pts_stages.front();
  1789. SPIREntryPoint &entry_point = compiler.get_entry_point(entry_point_stage.name, entry_point_stage.execution_model);
  1790. // Process specialization constants.
  1791. if (!compiler.get_specialization_constants().empty()) {
  1792. for (SpecializationConstant const &constant : compiler.get_specialization_constants()) {
  1793. LocalVector<SpecializationConstantData>::Iterator res = bin_data.constants.begin();
  1794. while (res != bin_data.constants.end()) {
  1795. if (res->constant_id == constant.constant_id) {
  1796. res->used_stages |= 1 << stage;
  1797. break;
  1798. }
  1799. ++res;
  1800. }
  1801. if (res == bin_data.constants.end()) {
  1802. WARN_PRINT(String(stage_name) + ": unable to find constant_id: " + itos(constant.constant_id));
  1803. }
  1804. }
  1805. }
  1806. // Process bindings.
  1807. LocalVector<UniformSetData> &uniform_sets = bin_data.uniforms;
  1808. using BT = SPIRType::BaseType;
  1809. // Always clearer than a boolean.
  1810. enum class Writable {
  1811. No,
  1812. Maybe,
  1813. };
  1814. // Returns a std::optional containing the value of the
  1815. // decoration, if it exists.
  1816. auto get_decoration = [&compiler](spirv_cross::ID id, spv::Decoration decoration) {
  1817. uint32_t res = -1;
  1818. if (compiler.has_decoration(id, decoration)) {
  1819. res = compiler.get_decoration(id, decoration);
  1820. }
  1821. return res;
  1822. };
  1823. auto descriptor_bindings = [&compiler, &active, &uniform_sets, stage, &get_decoration](SmallVector<Resource> &p_resources, Writable p_writable) {
  1824. for (Resource const &res : p_resources) {
  1825. uint32_t dset = get_decoration(res.id, spv::DecorationDescriptorSet);
  1826. uint32_t dbin = get_decoration(res.id, spv::DecorationBinding);
  1827. UniformData *found = nullptr;
  1828. if (dset != (uint32_t)-1 && dbin != (uint32_t)-1 && dset < uniform_sets.size()) {
  1829. UniformSetData &set = uniform_sets[dset];
  1830. LocalVector<UniformData>::Iterator pos = set.uniforms.begin();
  1831. while (pos != set.uniforms.end()) {
  1832. if (dbin == pos->binding) {
  1833. found = &(*pos);
  1834. break;
  1835. }
  1836. ++pos;
  1837. }
  1838. }
  1839. ERR_FAIL_NULL_V_MSG(found, ERR_CANT_CREATE, "UniformData not found");
  1840. bool is_active = active.find(res.id) != active.end();
  1841. if (is_active) {
  1842. found->active_stages |= 1 << stage;
  1843. }
  1844. BindingInfo primary{};
  1845. SPIRType const &a_type = compiler.get_type(res.type_id);
  1846. BT basetype = a_type.basetype;
  1847. switch (basetype) {
  1848. case BT::Struct: {
  1849. primary.dataType = MTLDataTypePointer;
  1850. } break;
  1851. case BT::Image:
  1852. case BT::SampledImage: {
  1853. primary.dataType = MTLDataTypeTexture;
  1854. } break;
  1855. case BT::Sampler: {
  1856. primary.dataType = MTLDataTypeSampler;
  1857. primary.arrayLength = 1;
  1858. for (uint32_t const &a : a_type.array) {
  1859. primary.arrayLength *= a;
  1860. }
  1861. } break;
  1862. default: {
  1863. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Unexpected BaseType");
  1864. } break;
  1865. }
  1866. // Find array length of image.
  1867. if (basetype == BT::Image || basetype == BT::SampledImage) {
  1868. primary.arrayLength = 1;
  1869. for (uint32_t const &a : a_type.array) {
  1870. primary.arrayLength *= a;
  1871. }
  1872. primary.isMultisampled = a_type.image.ms;
  1873. SPIRType::ImageType const &image = a_type.image;
  1874. primary.imageFormat = image.format;
  1875. switch (image.dim) {
  1876. case spv::Dim1D: {
  1877. if (image.arrayed) {
  1878. primary.textureType = MTLTextureType1DArray;
  1879. } else {
  1880. primary.textureType = MTLTextureType1D;
  1881. }
  1882. } break;
  1883. case spv::DimSubpassData: {
  1884. DISPATCH_FALLTHROUGH;
  1885. }
  1886. case spv::Dim2D: {
  1887. if (image.arrayed && image.ms) {
  1888. primary.textureType = MTLTextureType2DMultisampleArray;
  1889. } else if (image.arrayed) {
  1890. primary.textureType = MTLTextureType2DArray;
  1891. } else if (image.ms) {
  1892. primary.textureType = MTLTextureType2DMultisample;
  1893. } else {
  1894. primary.textureType = MTLTextureType2D;
  1895. }
  1896. } break;
  1897. case spv::Dim3D: {
  1898. primary.textureType = MTLTextureType3D;
  1899. } break;
  1900. case spv::DimCube: {
  1901. if (image.arrayed) {
  1902. primary.textureType = MTLTextureTypeCube;
  1903. }
  1904. } break;
  1905. case spv::DimRect: {
  1906. } break;
  1907. case spv::DimBuffer: {
  1908. // VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER
  1909. primary.textureType = MTLTextureTypeTextureBuffer;
  1910. } break;
  1911. case spv::DimMax: {
  1912. // Add all enumerations to silence the compiler warning
  1913. // and generate future warnings, should a new one be added.
  1914. } break;
  1915. }
  1916. }
  1917. // Update writable.
  1918. if (p_writable == Writable::Maybe) {
  1919. if (basetype == BT::Struct) {
  1920. Bitset flags = compiler.get_buffer_block_flags(res.id);
  1921. if (!flags.get(spv::DecorationNonWritable)) {
  1922. if (flags.get(spv::DecorationNonReadable)) {
  1923. primary.access = MTLBindingAccessWriteOnly;
  1924. } else {
  1925. primary.access = MTLBindingAccessReadWrite;
  1926. }
  1927. }
  1928. } else if (basetype == BT::Image) {
  1929. switch (a_type.image.access) {
  1930. case spv::AccessQualifierWriteOnly:
  1931. primary.access = MTLBindingAccessWriteOnly;
  1932. break;
  1933. case spv::AccessQualifierReadWrite:
  1934. primary.access = MTLBindingAccessReadWrite;
  1935. break;
  1936. case spv::AccessQualifierReadOnly:
  1937. break;
  1938. case spv::AccessQualifierMax:
  1939. DISPATCH_FALLTHROUGH;
  1940. default:
  1941. if (!compiler.has_decoration(res.id, spv::DecorationNonWritable)) {
  1942. if (compiler.has_decoration(res.id, spv::DecorationNonReadable)) {
  1943. primary.access = MTLBindingAccessWriteOnly;
  1944. } else {
  1945. primary.access = MTLBindingAccessReadWrite;
  1946. }
  1947. }
  1948. break;
  1949. }
  1950. }
  1951. }
  1952. switch (primary.access) {
  1953. case MTLBindingAccessReadOnly:
  1954. primary.usage = MTLResourceUsageRead;
  1955. break;
  1956. case MTLBindingAccessWriteOnly:
  1957. primary.usage = MTLResourceUsageWrite;
  1958. break;
  1959. case MTLBindingAccessReadWrite:
  1960. primary.usage = MTLResourceUsageRead | MTLResourceUsageWrite;
  1961. break;
  1962. }
  1963. primary.index = compiler.get_automatic_msl_resource_binding(res.id);
  1964. found->bindings[stage] = primary;
  1965. // A sampled image contains two bindings, the primary
  1966. // is to the image, and the secondary is to the associated sampler.
  1967. if (basetype == BT::SampledImage) {
  1968. uint32_t binding = compiler.get_automatic_msl_resource_binding_secondary(res.id);
  1969. if (binding != (uint32_t)-1) {
  1970. found->bindings_secondary[stage] = BindingInfo{
  1971. .dataType = MTLDataTypeSampler,
  1972. .index = binding,
  1973. .access = MTLBindingAccessReadOnly,
  1974. };
  1975. }
  1976. }
  1977. // An image may have a secondary binding if it is used
  1978. // for atomic operations.
  1979. if (basetype == BT::Image) {
  1980. uint32_t binding = compiler.get_automatic_msl_resource_binding_secondary(res.id);
  1981. if (binding != (uint32_t)-1) {
  1982. found->bindings_secondary[stage] = BindingInfo{
  1983. .dataType = MTLDataTypePointer,
  1984. .index = binding,
  1985. .access = MTLBindingAccessReadWrite,
  1986. };
  1987. }
  1988. }
  1989. }
  1990. return Error::OK;
  1991. };
  1992. if (!resources.uniform_buffers.empty()) {
  1993. Error err = descriptor_bindings(resources.uniform_buffers, Writable::No);
  1994. ERR_FAIL_COND_V(err != OK, Result());
  1995. }
  1996. if (!resources.storage_buffers.empty()) {
  1997. Error err = descriptor_bindings(resources.storage_buffers, Writable::Maybe);
  1998. ERR_FAIL_COND_V(err != OK, Result());
  1999. }
  2000. if (!resources.storage_images.empty()) {
  2001. Error err = descriptor_bindings(resources.storage_images, Writable::Maybe);
  2002. ERR_FAIL_COND_V(err != OK, Result());
  2003. }
  2004. if (!resources.sampled_images.empty()) {
  2005. Error err = descriptor_bindings(resources.sampled_images, Writable::No);
  2006. ERR_FAIL_COND_V(err != OK, Result());
  2007. }
  2008. if (!resources.separate_images.empty()) {
  2009. Error err = descriptor_bindings(resources.separate_images, Writable::No);
  2010. ERR_FAIL_COND_V(err != OK, Result());
  2011. }
  2012. if (!resources.separate_samplers.empty()) {
  2013. Error err = descriptor_bindings(resources.separate_samplers, Writable::No);
  2014. ERR_FAIL_COND_V(err != OK, Result());
  2015. }
  2016. if (!resources.subpass_inputs.empty()) {
  2017. Error err = descriptor_bindings(resources.subpass_inputs, Writable::No);
  2018. ERR_FAIL_COND_V(err != OK, Result());
  2019. }
  2020. if (!resources.push_constant_buffers.empty()) {
  2021. for (Resource const &res : resources.push_constant_buffers) {
  2022. uint32_t binding = compiler.get_automatic_msl_resource_binding(res.id);
  2023. if (binding != (uint32_t)-1) {
  2024. bin_data.push_constant.used_stages |= 1 << stage;
  2025. bin_data.push_constant.msl_binding[stage] = binding;
  2026. }
  2027. }
  2028. }
  2029. ERR_FAIL_COND_V_MSG(!resources.atomic_counters.empty(), Result(), "Atomic counters not supported");
  2030. ERR_FAIL_COND_V_MSG(!resources.acceleration_structures.empty(), Result(), "Acceleration structures not supported");
  2031. ERR_FAIL_COND_V_MSG(!resources.shader_record_buffers.empty(), Result(), "Shader record buffers not supported");
  2032. if (!resources.stage_inputs.empty()) {
  2033. for (Resource const &res : resources.stage_inputs) {
  2034. uint32_t binding = compiler.get_automatic_msl_resource_binding(res.id);
  2035. if (binding != (uint32_t)-1) {
  2036. bin_data.vertex_input_mask |= 1 << binding;
  2037. }
  2038. }
  2039. }
  2040. ShaderStageData stage_data;
  2041. stage_data.stage = v.shader_stage;
  2042. stage_data.is_position_invariant = compiler.is_position_invariant();
  2043. stage_data.supports_fast_math = !entry_point.flags.get(spv::ExecutionModeSignedZeroInfNanPreserve);
  2044. stage_data.entry_point_name = entry_point.name.c_str();
  2045. stage_data.source = source.c_str();
  2046. bin_data.stages.push_back(stage_data);
  2047. }
  2048. size_t vec_size = bin_data.serialize_size() + 8;
  2049. ::Vector<uint8_t> ret;
  2050. ret.resize(vec_size);
  2051. BufWriter writer(ret.ptrw(), vec_size);
  2052. const uint8_t HEADER[4] = { 'G', 'M', 'S', 'L' };
  2053. writer.write(*(uint32_t *)HEADER);
  2054. writer.write(SHADER_BINARY_VERSION);
  2055. bin_data.serialize(writer);
  2056. ret.resize(writer.get_pos());
  2057. return ret;
  2058. }
  2059. void RenderingDeviceDriverMetal::shader_cache_free_entry(const SHA256Digest &key) {
  2060. if (ShaderCacheEntry **pentry = _shader_cache.getptr(key); pentry != nullptr) {
  2061. ShaderCacheEntry *entry = *pentry;
  2062. _shader_cache.erase(key);
  2063. entry->library = nil;
  2064. memdelete(entry);
  2065. }
  2066. }
  2067. RDD::ShaderID RenderingDeviceDriverMetal::shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary, ShaderDescription &r_shader_desc, String &r_name, const Vector<ImmutableSampler> &p_immutable_samplers) {
  2068. r_shader_desc = {}; // Driver-agnostic.
  2069. const uint8_t *binptr = p_shader_binary.ptr();
  2070. uint32_t binsize = p_shader_binary.size();
  2071. BufReader reader(binptr, binsize);
  2072. uint8_t header[4];
  2073. reader.read((uint32_t &)header);
  2074. ERR_FAIL_COND_V_MSG(memcmp(header, "GMSL", 4) != 0, ShaderID(), "Invalid header");
  2075. uint32_t version = 0;
  2076. reader.read(version);
  2077. ERR_FAIL_COND_V_MSG(version != SHADER_BINARY_VERSION, ShaderID(), "Invalid shader binary version");
  2078. ShaderBinaryData binary_data;
  2079. binary_data.deserialize(reader);
  2080. switch (reader.status) {
  2081. case BufReader::Status::OK:
  2082. break;
  2083. case BufReader::Status::BAD_COMPRESSION:
  2084. ERR_FAIL_V_MSG(ShaderID(), "Invalid compressed data");
  2085. case BufReader::Status::SHORT_BUFFER:
  2086. ERR_FAIL_V_MSG(ShaderID(), "Unexpected end of buffer");
  2087. }
  2088. // We need to regenerate the shader if the cache is moved to an incompatible device.
  2089. ERR_FAIL_COND_V_MSG(device_properties->features.argument_buffers_tier < MTLArgumentBuffersTier2 && binary_data.uses_argument_buffers(),
  2090. ShaderID(),
  2091. "Shader was generated with argument buffers, but device has limited support");
  2092. MTLCompileOptions *options = [MTLCompileOptions new];
  2093. options.languageVersion = binary_data.get_msl_version();
  2094. HashMap<ShaderStage, MDLibrary *> libraries;
  2095. for (ShaderStageData &shader_data : binary_data.stages) {
  2096. r_shader_desc.stages.push_back(shader_data.stage);
  2097. SHA256Digest key = SHA256Digest(shader_data.source.ptr(), shader_data.source.length());
  2098. if (ShaderCacheEntry **p = _shader_cache.getptr(key); p != nullptr) {
  2099. libraries[shader_data.stage] = (*p)->library;
  2100. continue;
  2101. }
  2102. NSString *source = [[NSString alloc] initWithBytes:(void *)shader_data.source.ptr()
  2103. length:shader_data.source.length()
  2104. encoding:NSUTF8StringEncoding];
  2105. ShaderCacheEntry *cd = memnew(ShaderCacheEntry(*this, key));
  2106. cd->name = binary_data.shader_name;
  2107. cd->stage = shader_data.stage;
  2108. options.preserveInvariance = shader_data.is_position_invariant;
  2109. #if defined(VISIONOS_ENABLED)
  2110. options.mathMode = MTLMathModeFast;
  2111. #else
  2112. options.fastMathEnabled = YES;
  2113. #endif
  2114. MDLibrary *library = [MDLibrary newLibraryWithCacheEntry:cd
  2115. device:device
  2116. source:source
  2117. options:options
  2118. strategy:_shader_load_strategy];
  2119. _shader_cache[key] = cd;
  2120. libraries[shader_data.stage] = library;
  2121. }
  2122. Vector<UniformSet> uniform_sets;
  2123. uniform_sets.resize(binary_data.uniforms.size());
  2124. r_shader_desc.uniform_sets.resize(binary_data.uniforms.size());
  2125. // Create sets.
  2126. for (UniformSetData &uniform_set : binary_data.uniforms) {
  2127. UniformSet &set = uniform_sets.write[uniform_set.index];
  2128. set.uniforms.resize(uniform_set.uniforms.size());
  2129. Vector<ShaderUniform> &uset = r_shader_desc.uniform_sets.write[uniform_set.index];
  2130. uset.resize(uniform_set.uniforms.size());
  2131. for (uint32_t i = 0; i < uniform_set.uniforms.size(); i++) {
  2132. UniformData &uniform = uniform_set.uniforms[i];
  2133. ShaderUniform su;
  2134. su.type = uniform.type;
  2135. su.writable = uniform.writable;
  2136. su.length = uniform.length;
  2137. su.binding = uniform.binding;
  2138. su.stages = (ShaderStage)(uint8_t)uniform.stages;
  2139. uset.write[i] = su;
  2140. UniformInfo ui;
  2141. ui.binding = uniform.binding;
  2142. ui.active_stages = uniform.active_stages;
  2143. for (KeyValue<RDC::ShaderStage, BindingInfo> &kv : uniform.bindings) {
  2144. ui.bindings.insert(kv.key, kv.value);
  2145. }
  2146. for (KeyValue<RDC::ShaderStage, BindingInfo> &kv : uniform.bindings_secondary) {
  2147. ui.bindings_secondary.insert(kv.key, kv.value);
  2148. }
  2149. set.uniforms[i] = ui;
  2150. }
  2151. }
  2152. for (UniformSetData &uniform_set : binary_data.uniforms) {
  2153. UniformSet &set = uniform_sets.write[uniform_set.index];
  2154. // Make encoders.
  2155. for (ShaderStageData const &stage_data : binary_data.stages) {
  2156. ShaderStage stage = stage_data.stage;
  2157. NSMutableArray<MTLArgumentDescriptor *> *descriptors = [NSMutableArray new];
  2158. for (UniformInfo const &uniform : set.uniforms) {
  2159. BindingInfo const *binding_info = uniform.bindings.getptr(stage);
  2160. if (binding_info == nullptr) {
  2161. continue;
  2162. }
  2163. [descriptors addObject:binding_info->new_argument_descriptor()];
  2164. BindingInfo const *secondary_binding_info = uniform.bindings_secondary.getptr(stage);
  2165. if (secondary_binding_info != nullptr) {
  2166. [descriptors addObject:secondary_binding_info->new_argument_descriptor()];
  2167. }
  2168. }
  2169. if (descriptors.count == 0) {
  2170. // No bindings.
  2171. continue;
  2172. }
  2173. // Sort by index.
  2174. [descriptors sortUsingComparator:^NSComparisonResult(MTLArgumentDescriptor *a, MTLArgumentDescriptor *b) {
  2175. if (a.index < b.index) {
  2176. return NSOrderedAscending;
  2177. } else if (a.index > b.index) {
  2178. return NSOrderedDescending;
  2179. } else {
  2180. return NSOrderedSame;
  2181. }
  2182. }];
  2183. id<MTLArgumentEncoder> enc = [device newArgumentEncoderWithArguments:descriptors];
  2184. set.encoders[stage] = enc;
  2185. set.offsets[stage] = set.buffer_size;
  2186. set.buffer_size += enc.encodedLength;
  2187. }
  2188. }
  2189. r_shader_desc.specialization_constants.resize(binary_data.constants.size());
  2190. for (uint32_t i = 0; i < binary_data.constants.size(); i++) {
  2191. SpecializationConstantData &c = binary_data.constants[i];
  2192. ShaderSpecializationConstant sc;
  2193. sc.type = c.type;
  2194. sc.constant_id = c.constant_id;
  2195. sc.int_value = c.int_value;
  2196. sc.stages = (ShaderStage)(uint8_t)c.stages;
  2197. r_shader_desc.specialization_constants.write[i] = sc;
  2198. }
  2199. MDShader *shader = nullptr;
  2200. if (binary_data.is_compute()) {
  2201. MDComputeShader *cs = new MDComputeShader(
  2202. binary_data.shader_name,
  2203. uniform_sets,
  2204. binary_data.uses_argument_buffers(),
  2205. libraries[ShaderStage::SHADER_STAGE_COMPUTE]);
  2206. uint32_t *binding = binary_data.push_constant.msl_binding.getptr(SHADER_STAGE_COMPUTE);
  2207. if (binding) {
  2208. cs->push_constants.size = binary_data.push_constant.size;
  2209. cs->push_constants.binding = *binding;
  2210. }
  2211. cs->local = MTLSizeMake(binary_data.compute_local_size.x, binary_data.compute_local_size.y, binary_data.compute_local_size.z);
  2212. #if DEV_ENABLED
  2213. cs->kernel_source = binary_data.stages[0].source;
  2214. #endif
  2215. shader = cs;
  2216. } else {
  2217. MDRenderShader *rs = new MDRenderShader(
  2218. binary_data.shader_name,
  2219. uniform_sets,
  2220. binary_data.needs_view_mask_buffer(),
  2221. binary_data.uses_argument_buffers(),
  2222. libraries[ShaderStage::SHADER_STAGE_VERTEX],
  2223. libraries[ShaderStage::SHADER_STAGE_FRAGMENT]);
  2224. uint32_t *vert_binding = binary_data.push_constant.msl_binding.getptr(SHADER_STAGE_VERTEX);
  2225. if (vert_binding) {
  2226. rs->push_constants.vert.size = binary_data.push_constant.size;
  2227. rs->push_constants.vert.binding = *vert_binding;
  2228. }
  2229. uint32_t *frag_binding = binary_data.push_constant.msl_binding.getptr(SHADER_STAGE_FRAGMENT);
  2230. if (frag_binding) {
  2231. rs->push_constants.frag.size = binary_data.push_constant.size;
  2232. rs->push_constants.frag.binding = *frag_binding;
  2233. }
  2234. #if DEV_ENABLED
  2235. for (ShaderStageData &stage_data : binary_data.stages) {
  2236. if (stage_data.stage == ShaderStage::SHADER_STAGE_VERTEX) {
  2237. rs->vert_source = stage_data.source;
  2238. } else if (stage_data.stage == ShaderStage::SHADER_STAGE_FRAGMENT) {
  2239. rs->frag_source = stage_data.source;
  2240. }
  2241. }
  2242. #endif
  2243. shader = rs;
  2244. }
  2245. r_shader_desc.vertex_input_mask = binary_data.vertex_input_mask;
  2246. r_shader_desc.fragment_output_mask = binary_data.fragment_output_mask;
  2247. r_shader_desc.is_compute = binary_data.is_compute();
  2248. r_shader_desc.compute_local_size[0] = binary_data.compute_local_size.x;
  2249. r_shader_desc.compute_local_size[1] = binary_data.compute_local_size.y;
  2250. r_shader_desc.compute_local_size[2] = binary_data.compute_local_size.z;
  2251. r_shader_desc.push_constant_size = binary_data.push_constant.size;
  2252. return ShaderID(shader);
  2253. }
  2254. void RenderingDeviceDriverMetal::shader_free(ShaderID p_shader) {
  2255. MDShader *obj = (MDShader *)p_shader.id;
  2256. delete obj;
  2257. }
  2258. void RenderingDeviceDriverMetal::shader_destroy_modules(ShaderID p_shader) {
  2259. // TODO.
  2260. }
  2261. /*********************/
  2262. /**** UNIFORM SET ****/
  2263. /*********************/
  2264. RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) {
  2265. //p_linear_pool_index = -1; // TODO:? Linear pools not implemented or not supported by API backend.
  2266. MDUniformSet *set = memnew(MDUniformSet);
  2267. Vector<BoundUniform> bound_uniforms;
  2268. bound_uniforms.resize(p_uniforms.size());
  2269. for (uint32_t i = 0; i < p_uniforms.size(); i += 1) {
  2270. bound_uniforms.write[i] = p_uniforms[i];
  2271. }
  2272. set->uniforms = bound_uniforms;
  2273. set->index = p_set_index;
  2274. return UniformSetID(set);
  2275. }
  2276. void RenderingDeviceDriverMetal::uniform_set_free(UniformSetID p_uniform_set) {
  2277. MDUniformSet *obj = (MDUniformSet *)p_uniform_set.id;
  2278. memdelete(obj);
  2279. }
  2280. void RenderingDeviceDriverMetal::command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  2281. }
  2282. #pragma mark - Transfer
  2283. void RenderingDeviceDriverMetal::command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) {
  2284. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  2285. id<MTLBuffer> buffer = rid::get(p_buffer);
  2286. id<MTLBlitCommandEncoder> blit = cmd->blit_command_encoder();
  2287. [blit fillBuffer:buffer
  2288. range:NSMakeRange(p_offset, p_size)
  2289. value:0];
  2290. }
  2291. void RenderingDeviceDriverMetal::command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) {
  2292. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  2293. id<MTLBuffer> src = rid::get(p_src_buffer);
  2294. id<MTLBuffer> dst = rid::get(p_dst_buffer);
  2295. id<MTLBlitCommandEncoder> blit = cmd->blit_command_encoder();
  2296. for (uint32_t i = 0; i < p_regions.size(); i++) {
  2297. BufferCopyRegion region = p_regions[i];
  2298. [blit copyFromBuffer:src
  2299. sourceOffset:region.src_offset
  2300. toBuffer:dst
  2301. destinationOffset:region.dst_offset
  2302. size:region.size];
  2303. }
  2304. }
  2305. MTLSize MTLSizeFromVector3i(Vector3i p_size) {
  2306. return MTLSizeMake(p_size.x, p_size.y, p_size.z);
  2307. }
  2308. MTLOrigin MTLOriginFromVector3i(Vector3i p_origin) {
  2309. return MTLOriginMake(p_origin.x, p_origin.y, p_origin.z);
  2310. }
  2311. // Clamps the size so that the sum of the origin and size do not exceed the maximum size.
  2312. static inline MTLSize clampMTLSize(MTLSize p_size, MTLOrigin p_origin, MTLSize p_max_size) {
  2313. MTLSize clamped;
  2314. clamped.width = MIN(p_size.width, p_max_size.width - p_origin.x);
  2315. clamped.height = MIN(p_size.height, p_max_size.height - p_origin.y);
  2316. clamped.depth = MIN(p_size.depth, p_max_size.depth - p_origin.z);
  2317. return clamped;
  2318. }
  2319. 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) {
  2320. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  2321. id<MTLTexture> src = rid::get(p_src_texture);
  2322. id<MTLTexture> dst = rid::get(p_dst_texture);
  2323. id<MTLBlitCommandEncoder> blit = cmd->blit_command_encoder();
  2324. PixelFormats &pf = *pixel_formats;
  2325. MTLPixelFormat src_fmt = src.pixelFormat;
  2326. bool src_is_compressed = pf.getFormatType(src_fmt) == MTLFormatType::Compressed;
  2327. MTLPixelFormat dst_fmt = dst.pixelFormat;
  2328. bool dst_is_compressed = pf.getFormatType(dst_fmt) == MTLFormatType::Compressed;
  2329. // Validate copy.
  2330. if (src.sampleCount != dst.sampleCount || pf.getBytesPerBlock(src_fmt) != pf.getBytesPerBlock(dst_fmt)) {
  2331. ERR_FAIL_MSG("Cannot copy between incompatible pixel formats, such as formats of different pixel sizes, or between images with different sample counts.");
  2332. }
  2333. // If source and destination have different formats and at least one is compressed, a temporary buffer is required.
  2334. bool need_tmp_buffer = (src_fmt != dst_fmt) && (src_is_compressed || dst_is_compressed);
  2335. if (need_tmp_buffer) {
  2336. ERR_FAIL_MSG("not implemented: copy with intermediate buffer");
  2337. }
  2338. if (src_fmt != dst_fmt) {
  2339. // Map the source pixel format to the dst through a texture view on the source texture.
  2340. src = [src newTextureViewWithPixelFormat:dst_fmt];
  2341. }
  2342. for (uint32_t i = 0; i < p_regions.size(); i++) {
  2343. TextureCopyRegion region = p_regions[i];
  2344. MTLSize extent = MTLSizeFromVector3i(region.size);
  2345. // If copies can be performed using direct texture-texture copying, do so.
  2346. uint32_t src_level = region.src_subresources.mipmap;
  2347. uint32_t src_base_layer = region.src_subresources.base_layer;
  2348. MTLSize src_extent = mipmapLevelSizeFromTexture(src, src_level);
  2349. uint32_t dst_level = region.dst_subresources.mipmap;
  2350. uint32_t dst_base_layer = region.dst_subresources.base_layer;
  2351. MTLSize dst_extent = mipmapLevelSizeFromTexture(dst, dst_level);
  2352. // All layers may be copied at once, if the extent completely covers both images.
  2353. if (src_extent == extent && dst_extent == extent) {
  2354. [blit copyFromTexture:src
  2355. sourceSlice:src_base_layer
  2356. sourceLevel:src_level
  2357. toTexture:dst
  2358. destinationSlice:dst_base_layer
  2359. destinationLevel:dst_level
  2360. sliceCount:region.src_subresources.layer_count
  2361. levelCount:1];
  2362. } else {
  2363. MTLOrigin src_origin = MTLOriginFromVector3i(region.src_offset);
  2364. MTLSize src_size = clampMTLSize(extent, src_origin, src_extent);
  2365. uint32_t layer_count = 0;
  2366. if ((src.textureType == MTLTextureType3D) != (dst.textureType == MTLTextureType3D)) {
  2367. // In the case, the number of layers to copy is in extent.depth. Use that value,
  2368. // then clamp the depth, so we don't try to copy more than Metal will allow.
  2369. layer_count = extent.depth;
  2370. src_size.depth = 1;
  2371. } else {
  2372. layer_count = region.src_subresources.layer_count;
  2373. }
  2374. MTLOrigin dst_origin = MTLOriginFromVector3i(region.dst_offset);
  2375. for (uint32_t layer = 0; layer < layer_count; layer++) {
  2376. // We can copy between a 3D and a 2D image easily. Just copy between
  2377. // one slice of the 2D image and one plane of the 3D image at a time.
  2378. if ((src.textureType == MTLTextureType3D) == (dst.textureType == MTLTextureType3D)) {
  2379. [blit copyFromTexture:src
  2380. sourceSlice:src_base_layer + layer
  2381. sourceLevel:src_level
  2382. sourceOrigin:src_origin
  2383. sourceSize:src_size
  2384. toTexture:dst
  2385. destinationSlice:dst_base_layer + layer
  2386. destinationLevel:dst_level
  2387. destinationOrigin:dst_origin];
  2388. } else if (src.textureType == MTLTextureType3D) {
  2389. [blit copyFromTexture:src
  2390. sourceSlice:src_base_layer
  2391. sourceLevel:src_level
  2392. sourceOrigin:MTLOriginMake(src_origin.x, src_origin.y, src_origin.z + layer)
  2393. sourceSize:src_size
  2394. toTexture:dst
  2395. destinationSlice:dst_base_layer + layer
  2396. destinationLevel:dst_level
  2397. destinationOrigin:dst_origin];
  2398. } else {
  2399. DEV_ASSERT(dst.textureType == MTLTextureType3D);
  2400. [blit copyFromTexture:src
  2401. sourceSlice:src_base_layer + layer
  2402. sourceLevel:src_level
  2403. sourceOrigin:src_origin
  2404. sourceSize:src_size
  2405. toTexture:dst
  2406. destinationSlice:dst_base_layer
  2407. destinationLevel:dst_level
  2408. destinationOrigin:MTLOriginMake(dst_origin.x, dst_origin.y, dst_origin.z + layer)];
  2409. }
  2410. }
  2411. }
  2412. }
  2413. }
  2414. 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) {
  2415. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2416. id<MTLTexture> src_tex = rid::get(p_src_texture);
  2417. id<MTLTexture> dst_tex = rid::get(p_dst_texture);
  2418. MTLRenderPassDescriptor *mtlRPD = [MTLRenderPassDescriptor renderPassDescriptor];
  2419. MTLRenderPassColorAttachmentDescriptor *mtlColorAttDesc = mtlRPD.colorAttachments[0];
  2420. mtlColorAttDesc.loadAction = MTLLoadActionLoad;
  2421. mtlColorAttDesc.storeAction = MTLStoreActionMultisampleResolve;
  2422. mtlColorAttDesc.texture = src_tex;
  2423. mtlColorAttDesc.resolveTexture = dst_tex;
  2424. mtlColorAttDesc.level = p_src_mipmap;
  2425. mtlColorAttDesc.slice = p_src_layer;
  2426. mtlColorAttDesc.resolveLevel = p_dst_mipmap;
  2427. mtlColorAttDesc.resolveSlice = p_dst_layer;
  2428. cb->encodeRenderCommandEncoderWithDescriptor(mtlRPD, @"Resolve Image");
  2429. }
  2430. 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) {
  2431. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2432. id<MTLTexture> src_tex = rid::get(p_texture);
  2433. if (src_tex.parentTexture) {
  2434. // Clear via the parent texture rather than the view.
  2435. src_tex = src_tex.parentTexture;
  2436. }
  2437. PixelFormats &pf = *pixel_formats;
  2438. if (pf.isDepthFormat(src_tex.pixelFormat) || pf.isStencilFormat(src_tex.pixelFormat)) {
  2439. ERR_FAIL_MSG("invalid: depth or stencil texture format");
  2440. }
  2441. MTLRenderPassDescriptor *desc = MTLRenderPassDescriptor.renderPassDescriptor;
  2442. if (p_subresources.aspect.has_flag(TEXTURE_ASPECT_COLOR_BIT)) {
  2443. MTLRenderPassColorAttachmentDescriptor *caDesc = desc.colorAttachments[0];
  2444. caDesc.texture = src_tex;
  2445. caDesc.loadAction = MTLLoadActionClear;
  2446. caDesc.storeAction = MTLStoreActionStore;
  2447. caDesc.clearColor = MTLClearColorMake(p_color.r, p_color.g, p_color.b, p_color.a);
  2448. // Extract the mipmap levels that are to be updated.
  2449. uint32_t mipLvlStart = p_subresources.base_mipmap;
  2450. uint32_t mipLvlCnt = p_subresources.mipmap_count;
  2451. uint32_t mipLvlEnd = mipLvlStart + mipLvlCnt;
  2452. uint32_t levelCount = src_tex.mipmapLevelCount;
  2453. // Extract the cube or array layers (slices) that are to be updated.
  2454. bool is3D = src_tex.textureType == MTLTextureType3D;
  2455. uint32_t layerStart = is3D ? 0 : p_subresources.base_layer;
  2456. uint32_t layerCnt = p_subresources.layer_count;
  2457. uint32_t layerEnd = layerStart + layerCnt;
  2458. MetalFeatures const &features = (*device_properties).features;
  2459. // Iterate across mipmap levels and layers, and perform and empty render to clear each.
  2460. for (uint32_t mipLvl = mipLvlStart; mipLvl < mipLvlEnd; mipLvl++) {
  2461. ERR_FAIL_INDEX_MSG(mipLvl, levelCount, "mip level out of range");
  2462. caDesc.level = mipLvl;
  2463. // If a 3D image, we need to get the depth for each level.
  2464. if (is3D) {
  2465. layerCnt = mipmapLevelSizeFromTexture(src_tex, mipLvl).depth;
  2466. layerEnd = layerStart + layerCnt;
  2467. }
  2468. if ((features.layeredRendering && src_tex.sampleCount == 1) || features.multisampleLayeredRendering) {
  2469. // We can clear all layers at once.
  2470. if (is3D) {
  2471. caDesc.depthPlane = layerStart;
  2472. } else {
  2473. caDesc.slice = layerStart;
  2474. }
  2475. desc.renderTargetArrayLength = layerCnt;
  2476. cb->encodeRenderCommandEncoderWithDescriptor(desc, @"Clear Image");
  2477. } else {
  2478. for (uint32_t layer = layerStart; layer < layerEnd; layer++) {
  2479. if (is3D) {
  2480. caDesc.depthPlane = layer;
  2481. } else {
  2482. caDesc.slice = layer;
  2483. }
  2484. cb->encodeRenderCommandEncoderWithDescriptor(desc, @"Clear Image");
  2485. }
  2486. }
  2487. }
  2488. }
  2489. }
  2490. API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
  2491. bool isArrayTexture(MTLTextureType p_type) {
  2492. return (p_type == MTLTextureType3D ||
  2493. p_type == MTLTextureType2DArray ||
  2494. p_type == MTLTextureType2DMultisampleArray ||
  2495. p_type == MTLTextureType1DArray);
  2496. }
  2497. void RenderingDeviceDriverMetal::_copy_texture_buffer(CommandBufferID p_cmd_buffer,
  2498. CopySource p_source,
  2499. TextureID p_texture,
  2500. BufferID p_buffer,
  2501. VectorView<BufferTextureCopyRegion> p_regions) {
  2502. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  2503. id<MTLBuffer> buffer = rid::get(p_buffer);
  2504. id<MTLTexture> texture = rid::get(p_texture);
  2505. id<MTLBlitCommandEncoder> enc = cmd->blit_command_encoder();
  2506. PixelFormats &pf = *pixel_formats;
  2507. MTLPixelFormat mtlPixFmt = texture.pixelFormat;
  2508. MTLBlitOption options = MTLBlitOptionNone;
  2509. if (pf.isPVRTCFormat(mtlPixFmt)) {
  2510. options |= MTLBlitOptionRowLinearPVRTC;
  2511. }
  2512. for (uint32_t i = 0; i < p_regions.size(); i++) {
  2513. BufferTextureCopyRegion region = p_regions[i];
  2514. uint32_t mip_level = region.texture_subresources.mipmap;
  2515. MTLOrigin txt_origin = MTLOriginMake(region.texture_offset.x, region.texture_offset.y, region.texture_offset.z);
  2516. MTLSize src_extent = mipmapLevelSizeFromTexture(texture, mip_level);
  2517. MTLSize txt_size = clampMTLSize(MTLSizeMake(region.texture_region_size.x, region.texture_region_size.y, region.texture_region_size.z),
  2518. txt_origin,
  2519. src_extent);
  2520. uint32_t buffImgWd = region.texture_region_size.x;
  2521. uint32_t buffImgHt = region.texture_region_size.y;
  2522. NSUInteger bytesPerRow = pf.getBytesPerRow(mtlPixFmt, buffImgWd);
  2523. NSUInteger bytesPerImg = pf.getBytesPerLayer(mtlPixFmt, bytesPerRow, buffImgHt);
  2524. MTLBlitOption blit_options = options;
  2525. if (pf.isDepthFormat(mtlPixFmt) && pf.isStencilFormat(mtlPixFmt)) {
  2526. bool want_depth = flags::all(region.texture_subresources.aspect, TEXTURE_ASPECT_DEPTH_BIT);
  2527. bool want_stencil = flags::all(region.texture_subresources.aspect, TEXTURE_ASPECT_STENCIL_BIT);
  2528. // The stencil component is always 1 byte per pixel.
  2529. // Don't reduce depths of 32-bit depth/stencil formats.
  2530. if (want_depth && !want_stencil) {
  2531. if (pf.getBytesPerTexel(mtlPixFmt) != 4) {
  2532. bytesPerRow -= buffImgWd;
  2533. bytesPerImg -= buffImgWd * buffImgHt;
  2534. }
  2535. blit_options |= MTLBlitOptionDepthFromDepthStencil;
  2536. } else if (want_stencil && !want_depth) {
  2537. bytesPerRow = buffImgWd;
  2538. bytesPerImg = buffImgWd * buffImgHt;
  2539. blit_options |= MTLBlitOptionStencilFromDepthStencil;
  2540. }
  2541. }
  2542. if (!isArrayTexture(texture.textureType)) {
  2543. bytesPerImg = 0;
  2544. }
  2545. if (p_source == CopySource::Buffer) {
  2546. for (uint32_t lyrIdx = 0; lyrIdx < region.texture_subresources.layer_count; lyrIdx++) {
  2547. [enc copyFromBuffer:buffer
  2548. sourceOffset:region.buffer_offset + (bytesPerImg * lyrIdx)
  2549. sourceBytesPerRow:bytesPerRow
  2550. sourceBytesPerImage:bytesPerImg
  2551. sourceSize:txt_size
  2552. toTexture:texture
  2553. destinationSlice:region.texture_subresources.base_layer + lyrIdx
  2554. destinationLevel:mip_level
  2555. destinationOrigin:txt_origin
  2556. options:blit_options];
  2557. }
  2558. } else {
  2559. for (uint32_t lyrIdx = 0; lyrIdx < region.texture_subresources.layer_count; lyrIdx++) {
  2560. [enc copyFromTexture:texture
  2561. sourceSlice:region.texture_subresources.base_layer + lyrIdx
  2562. sourceLevel:mip_level
  2563. sourceOrigin:txt_origin
  2564. sourceSize:txt_size
  2565. toBuffer:buffer
  2566. destinationOffset:region.buffer_offset + (bytesPerImg * lyrIdx)
  2567. destinationBytesPerRow:bytesPerRow
  2568. destinationBytesPerImage:bytesPerImg
  2569. options:blit_options];
  2570. }
  2571. }
  2572. }
  2573. }
  2574. 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) {
  2575. _copy_texture_buffer(p_cmd_buffer, CopySource::Buffer, p_dst_texture, p_src_buffer, p_regions);
  2576. }
  2577. 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) {
  2578. _copy_texture_buffer(p_cmd_buffer, CopySource::Texture, p_src_texture, p_dst_buffer, p_regions);
  2579. }
  2580. #pragma mark - Pipeline
  2581. void RenderingDeviceDriverMetal::pipeline_free(PipelineID p_pipeline_id) {
  2582. MDPipeline *obj = (MDPipeline *)(p_pipeline_id.id);
  2583. delete obj;
  2584. }
  2585. // ----- BINDING -----
  2586. void RenderingDeviceDriverMetal::command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_dst_first_index, VectorView<uint32_t> p_data) {
  2587. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2588. MDShader *shader = (MDShader *)(p_shader.id);
  2589. shader->encode_push_constant_data(p_data, cb);
  2590. }
  2591. // ----- CACHE -----
  2592. String RenderingDeviceDriverMetal::_pipeline_get_cache_path() const {
  2593. String path = OS::get_singleton()->get_user_data_dir() + "/metal/pipelines";
  2594. path += "." + context_device.name.validate_filename().replace_char(' ', '_').to_lower();
  2595. if (Engine::get_singleton()->is_editor_hint()) {
  2596. path += ".editor";
  2597. }
  2598. path += ".cache";
  2599. return path;
  2600. }
  2601. bool RenderingDeviceDriverMetal::pipeline_cache_create(const Vector<uint8_t> &p_data) {
  2602. return false;
  2603. CharString path = _pipeline_get_cache_path().utf8();
  2604. NSString *nPath = [[NSString alloc] initWithBytesNoCopy:path.ptrw()
  2605. length:path.length()
  2606. encoding:NSUTF8StringEncoding
  2607. freeWhenDone:NO];
  2608. MTLBinaryArchiveDescriptor *desc = [MTLBinaryArchiveDescriptor new];
  2609. if ([[NSFileManager defaultManager] fileExistsAtPath:nPath]) {
  2610. desc.url = [NSURL fileURLWithPath:nPath];
  2611. }
  2612. NSError *error = nil;
  2613. archive = [device newBinaryArchiveWithDescriptor:desc error:&error];
  2614. return true;
  2615. }
  2616. void RenderingDeviceDriverMetal::pipeline_cache_free() {
  2617. archive = nil;
  2618. }
  2619. size_t RenderingDeviceDriverMetal::pipeline_cache_query_size() {
  2620. return archive_count * 1024;
  2621. }
  2622. Vector<uint8_t> RenderingDeviceDriverMetal::pipeline_cache_serialize() {
  2623. if (!archive) {
  2624. return Vector<uint8_t>();
  2625. }
  2626. CharString path = _pipeline_get_cache_path().utf8();
  2627. NSString *nPath = [[NSString alloc] initWithBytesNoCopy:path.ptrw()
  2628. length:path.length()
  2629. encoding:NSUTF8StringEncoding
  2630. freeWhenDone:NO];
  2631. NSURL *target = [NSURL fileURLWithPath:nPath];
  2632. NSError *error = nil;
  2633. if ([archive serializeToURL:target error:&error]) {
  2634. return Vector<uint8_t>();
  2635. } else {
  2636. print_line(error.localizedDescription.UTF8String);
  2637. return Vector<uint8_t>();
  2638. }
  2639. }
  2640. #pragma mark - Rendering
  2641. // ----- SUBPASS -----
  2642. 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) {
  2643. PixelFormats &pf = *pixel_formats;
  2644. size_t subpass_count = p_subpasses.size();
  2645. Vector<MDSubpass> subpasses;
  2646. subpasses.resize(subpass_count);
  2647. for (uint32_t i = 0; i < subpass_count; i++) {
  2648. MDSubpass &subpass = subpasses.write[i];
  2649. subpass.subpass_index = i;
  2650. subpass.view_count = p_view_count;
  2651. subpass.input_references = p_subpasses[i].input_references;
  2652. subpass.color_references = p_subpasses[i].color_references;
  2653. subpass.depth_stencil_reference = p_subpasses[i].depth_stencil_reference;
  2654. subpass.resolve_references = p_subpasses[i].resolve_references;
  2655. }
  2656. static const MTLLoadAction LOAD_ACTIONS[] = {
  2657. [ATTACHMENT_LOAD_OP_LOAD] = MTLLoadActionLoad,
  2658. [ATTACHMENT_LOAD_OP_CLEAR] = MTLLoadActionClear,
  2659. [ATTACHMENT_LOAD_OP_DONT_CARE] = MTLLoadActionDontCare,
  2660. };
  2661. static const MTLStoreAction STORE_ACTIONS[] = {
  2662. [ATTACHMENT_STORE_OP_STORE] = MTLStoreActionStore,
  2663. [ATTACHMENT_STORE_OP_DONT_CARE] = MTLStoreActionDontCare,
  2664. };
  2665. Vector<MDAttachment> attachments;
  2666. attachments.resize(p_attachments.size());
  2667. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  2668. Attachment const &a = p_attachments[i];
  2669. MDAttachment &mda = attachments.write[i];
  2670. MTLPixelFormat format = pf.getMTLPixelFormat(a.format);
  2671. mda.format = format;
  2672. if (a.samples > TEXTURE_SAMPLES_1) {
  2673. mda.samples = (*device_properties).find_nearest_supported_sample_count(a.samples);
  2674. }
  2675. mda.loadAction = LOAD_ACTIONS[a.load_op];
  2676. mda.storeAction = STORE_ACTIONS[a.store_op];
  2677. bool is_depth = pf.isDepthFormat(format);
  2678. if (is_depth) {
  2679. mda.type |= MDAttachmentType::Depth;
  2680. }
  2681. bool is_stencil = pf.isStencilFormat(format);
  2682. if (is_stencil) {
  2683. mda.type |= MDAttachmentType::Stencil;
  2684. mda.stencilLoadAction = LOAD_ACTIONS[a.stencil_load_op];
  2685. mda.stencilStoreAction = STORE_ACTIONS[a.stencil_store_op];
  2686. }
  2687. if (!is_depth && !is_stencil) {
  2688. mda.type |= MDAttachmentType::Color;
  2689. }
  2690. }
  2691. MDRenderPass *obj = new MDRenderPass(attachments, subpasses);
  2692. return RenderPassID(obj);
  2693. }
  2694. void RenderingDeviceDriverMetal::render_pass_free(RenderPassID p_render_pass) {
  2695. MDRenderPass *obj = (MDRenderPass *)(p_render_pass.id);
  2696. delete obj;
  2697. }
  2698. // ----- COMMANDS -----
  2699. 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) {
  2700. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2701. cb->render_begin_pass(p_render_pass, p_framebuffer, p_cmd_buffer_type, p_rect, p_clear_values);
  2702. }
  2703. void RenderingDeviceDriverMetal::command_end_render_pass(CommandBufferID p_cmd_buffer) {
  2704. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2705. cb->render_end_pass();
  2706. }
  2707. void RenderingDeviceDriverMetal::command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) {
  2708. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2709. cb->render_next_subpass();
  2710. }
  2711. void RenderingDeviceDriverMetal::command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) {
  2712. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2713. cb->render_set_viewport(p_viewports);
  2714. }
  2715. void RenderingDeviceDriverMetal::command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) {
  2716. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2717. cb->render_set_scissor(p_scissors);
  2718. }
  2719. void RenderingDeviceDriverMetal::command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) {
  2720. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2721. cb->render_clear_attachments(p_attachment_clears, p_rects);
  2722. }
  2723. void RenderingDeviceDriverMetal::command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
  2724. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2725. cb->bind_pipeline(p_pipeline);
  2726. }
  2727. void RenderingDeviceDriverMetal::command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  2728. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2729. cb->render_bind_uniform_set(p_uniform_set, p_shader, p_set_index);
  2730. }
  2731. 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) {
  2732. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2733. cb->render_bind_uniform_sets(p_uniform_sets, p_shader, p_first_set_index, p_set_count);
  2734. }
  2735. 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) {
  2736. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2737. cb->render_draw(p_vertex_count, p_instance_count, p_base_vertex, p_first_instance);
  2738. }
  2739. 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) {
  2740. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2741. cb->render_draw_indexed(p_index_count, p_instance_count, p_first_index, p_vertex_offset, p_first_instance);
  2742. }
  2743. 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) {
  2744. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2745. cb->render_draw_indexed_indirect(p_indirect_buffer, p_offset, p_draw_count, p_stride);
  2746. }
  2747. 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) {
  2748. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2749. cb->render_draw_indexed_indirect_count(p_indirect_buffer, p_offset, p_count_buffer, p_count_buffer_offset, p_max_draw_count, p_stride);
  2750. }
  2751. 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) {
  2752. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2753. cb->render_draw_indirect(p_indirect_buffer, p_offset, p_draw_count, p_stride);
  2754. }
  2755. 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) {
  2756. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2757. cb->render_draw_indirect_count(p_indirect_buffer, p_offset, p_count_buffer, p_count_buffer_offset, p_max_draw_count, p_stride);
  2758. }
  2759. 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) {
  2760. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2761. cb->render_bind_vertex_buffers(p_binding_count, p_buffers, p_offsets);
  2762. }
  2763. void RenderingDeviceDriverMetal::command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) {
  2764. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2765. cb->render_bind_index_buffer(p_buffer, p_format, p_offset);
  2766. }
  2767. void RenderingDeviceDriverMetal::command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) {
  2768. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2769. cb->render_set_blend_constants(p_constants);
  2770. }
  2771. void RenderingDeviceDriverMetal::command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) {
  2772. if (!Math::is_equal_approx(p_width, 1.0f)) {
  2773. ERR_FAIL_MSG("Setting line widths other than 1.0 is not supported by the Metal rendering driver.");
  2774. }
  2775. }
  2776. // ----- PIPELINE -----
  2777. RenderingDeviceDriverMetal::Result<id<MTLFunction>> RenderingDeviceDriverMetal::_create_function(MDLibrary *p_library, NSString *p_name, VectorView<PipelineSpecializationConstant> &p_specialization_constants) {
  2778. id<MTLLibrary> library = p_library.library;
  2779. if (!library) {
  2780. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Failed to compile Metal library");
  2781. }
  2782. id<MTLFunction> function = [library newFunctionWithName:p_name];
  2783. ERR_FAIL_NULL_V_MSG(function, ERR_CANT_CREATE, "No function named main0");
  2784. if (function.functionConstantsDictionary.count == 0) {
  2785. return function;
  2786. }
  2787. NSArray<MTLFunctionConstant *> *constants = function.functionConstantsDictionary.allValues;
  2788. bool is_sorted = true;
  2789. for (uint32_t i = 1; i < constants.count; i++) {
  2790. if (constants[i - 1].index > constants[i].index) {
  2791. is_sorted = false;
  2792. break;
  2793. }
  2794. }
  2795. if (!is_sorted) {
  2796. constants = [constants sortedArrayUsingComparator:^NSComparisonResult(MTLFunctionConstant *a, MTLFunctionConstant *b) {
  2797. if (a.index < b.index) {
  2798. return NSOrderedAscending;
  2799. } else if (a.index > b.index) {
  2800. return NSOrderedDescending;
  2801. } else {
  2802. return NSOrderedSame;
  2803. }
  2804. }];
  2805. }
  2806. // Initialize an array of integers representing the indexes of p_specialization_constants
  2807. uint32_t *indexes = (uint32_t *)alloca(p_specialization_constants.size() * sizeof(uint32_t));
  2808. for (uint32_t i = 0; i < p_specialization_constants.size(); i++) {
  2809. indexes[i] = i;
  2810. }
  2811. // Sort the array of integers based on the values in p_specialization_constants
  2812. std::sort(indexes, &indexes[p_specialization_constants.size()], [&](int a, int b) {
  2813. return p_specialization_constants[a].constant_id < p_specialization_constants[b].constant_id;
  2814. });
  2815. MTLFunctionConstantValues *constantValues = [MTLFunctionConstantValues new];
  2816. uint32_t i = 0;
  2817. uint32_t j = 0;
  2818. while (i < constants.count && j < p_specialization_constants.size()) {
  2819. MTLFunctionConstant *curr = constants[i];
  2820. PipelineSpecializationConstant const &sc = p_specialization_constants[indexes[j]];
  2821. if (curr.index == sc.constant_id) {
  2822. switch (curr.type) {
  2823. case MTLDataTypeBool:
  2824. case MTLDataTypeFloat:
  2825. case MTLDataTypeInt:
  2826. case MTLDataTypeUInt: {
  2827. [constantValues setConstantValue:&sc.int_value
  2828. type:curr.type
  2829. atIndex:sc.constant_id];
  2830. } break;
  2831. default:
  2832. ERR_FAIL_V_MSG(function, "Invalid specialization constant type");
  2833. }
  2834. i++;
  2835. j++;
  2836. } else if (curr.index < sc.constant_id) {
  2837. i++;
  2838. } else {
  2839. j++;
  2840. }
  2841. }
  2842. if (i != constants.count) {
  2843. MTLFunctionConstant *curr = constants[i];
  2844. if (curr.index == R32UI_ALIGNMENT_CONSTANT_ID) {
  2845. uint32_t alignment = 16; // TODO(sgc): is this always correct?
  2846. [constantValues setConstantValue:&alignment
  2847. type:curr.type
  2848. atIndex:curr.index];
  2849. i++;
  2850. }
  2851. }
  2852. NSError *err = nil;
  2853. function = [library newFunctionWithName:@"main0"
  2854. constantValues:constantValues
  2855. error:&err];
  2856. ERR_FAIL_NULL_V_MSG(function, ERR_CANT_CREATE, String("specialized function failed: ") + err.localizedDescription.UTF8String);
  2857. return function;
  2858. }
  2859. // RDD::PolygonCullMode == MTLCullMode.
  2860. static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_DISABLED, MTLCullModeNone));
  2861. static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_FRONT, MTLCullModeFront));
  2862. static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_BACK, MTLCullModeBack));
  2863. // RDD::StencilOperation == MTLStencilOperation.
  2864. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_KEEP, MTLStencilOperationKeep));
  2865. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_ZERO, MTLStencilOperationZero));
  2866. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_REPLACE, MTLStencilOperationReplace));
  2867. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INCREMENT_AND_CLAMP, MTLStencilOperationIncrementClamp));
  2868. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_DECREMENT_AND_CLAMP, MTLStencilOperationDecrementClamp));
  2869. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INVERT, MTLStencilOperationInvert));
  2870. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INCREMENT_AND_WRAP, MTLStencilOperationIncrementWrap));
  2871. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_DECREMENT_AND_WRAP, MTLStencilOperationDecrementWrap));
  2872. // RDD::BlendOperation == MTLBlendOperation.
  2873. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_ADD, MTLBlendOperationAdd));
  2874. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_SUBTRACT, MTLBlendOperationSubtract));
  2875. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_REVERSE_SUBTRACT, MTLBlendOperationReverseSubtract));
  2876. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_MINIMUM, MTLBlendOperationMin));
  2877. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_MAXIMUM, MTLBlendOperationMax));
  2878. RDD::PipelineID RenderingDeviceDriverMetal::render_pipeline_create(
  2879. ShaderID p_shader,
  2880. VertexFormatID p_vertex_format,
  2881. RenderPrimitive p_render_primitive,
  2882. PipelineRasterizationState p_rasterization_state,
  2883. PipelineMultisampleState p_multisample_state,
  2884. PipelineDepthStencilState p_depth_stencil_state,
  2885. PipelineColorBlendState p_blend_state,
  2886. VectorView<int32_t> p_color_attachments,
  2887. BitField<PipelineDynamicStateFlags> p_dynamic_state,
  2888. RenderPassID p_render_pass,
  2889. uint32_t p_render_subpass,
  2890. VectorView<PipelineSpecializationConstant> p_specialization_constants) {
  2891. MDRenderShader *shader = (MDRenderShader *)(p_shader.id);
  2892. MTLVertexDescriptor *vert_desc = rid::get(p_vertex_format);
  2893. MDRenderPass *pass = (MDRenderPass *)(p_render_pass.id);
  2894. os_signpost_id_t reflect_id = os_signpost_id_make_with_pointer(LOG_INTERVALS, shader);
  2895. os_signpost_interval_begin(LOG_INTERVALS, reflect_id, "render_pipeline_create", "shader_name=%{public}s", shader->name.get_data());
  2896. DEFER([=]() {
  2897. os_signpost_interval_end(LOG_INTERVALS, reflect_id, "render_pipeline_create");
  2898. });
  2899. os_signpost_event_emit(LOG_DRIVER, OS_SIGNPOST_ID_EXCLUSIVE, "create_pipeline");
  2900. MTLRenderPipelineDescriptor *desc = [MTLRenderPipelineDescriptor new];
  2901. {
  2902. MDSubpass const &subpass = pass->subpasses[p_render_subpass];
  2903. for (uint32_t i = 0; i < subpass.color_references.size(); i++) {
  2904. uint32_t attachment = subpass.color_references[i].attachment;
  2905. if (attachment != AttachmentReference::UNUSED) {
  2906. MDAttachment const &a = pass->attachments[attachment];
  2907. desc.colorAttachments[i].pixelFormat = a.format;
  2908. }
  2909. }
  2910. if (subpass.depth_stencil_reference.attachment != AttachmentReference::UNUSED) {
  2911. uint32_t attachment = subpass.depth_stencil_reference.attachment;
  2912. MDAttachment const &a = pass->attachments[attachment];
  2913. if (a.type & MDAttachmentType::Depth) {
  2914. desc.depthAttachmentPixelFormat = a.format;
  2915. }
  2916. if (a.type & MDAttachmentType::Stencil) {
  2917. desc.stencilAttachmentPixelFormat = a.format;
  2918. }
  2919. }
  2920. }
  2921. desc.vertexDescriptor = vert_desc;
  2922. desc.label = [NSString stringWithUTF8String:shader->name.get_data()];
  2923. // Input assembly & tessellation.
  2924. MDRenderPipeline *pipeline = new MDRenderPipeline();
  2925. switch (p_render_primitive) {
  2926. case RENDER_PRIMITIVE_POINTS:
  2927. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassPoint;
  2928. break;
  2929. case RENDER_PRIMITIVE_LINES:
  2930. case RENDER_PRIMITIVE_LINES_WITH_ADJACENCY:
  2931. case RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY:
  2932. case RENDER_PRIMITIVE_LINESTRIPS:
  2933. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassLine;
  2934. break;
  2935. case RENDER_PRIMITIVE_TRIANGLES:
  2936. case RENDER_PRIMITIVE_TRIANGLE_STRIPS:
  2937. case RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY:
  2938. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY:
  2939. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX:
  2940. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassTriangle;
  2941. break;
  2942. case RENDER_PRIMITIVE_TESSELATION_PATCH:
  2943. desc.maxTessellationFactor = p_rasterization_state.patch_control_points;
  2944. desc.tessellationPartitionMode = MTLTessellationPartitionModeInteger;
  2945. ERR_FAIL_V_MSG(PipelineID(), "tessellation not implemented");
  2946. break;
  2947. case RENDER_PRIMITIVE_MAX:
  2948. default:
  2949. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassUnspecified;
  2950. break;
  2951. }
  2952. switch (p_render_primitive) {
  2953. case RENDER_PRIMITIVE_POINTS:
  2954. pipeline->raster_state.render_primitive = MTLPrimitiveTypePoint;
  2955. break;
  2956. case RENDER_PRIMITIVE_LINES:
  2957. case RENDER_PRIMITIVE_LINES_WITH_ADJACENCY:
  2958. pipeline->raster_state.render_primitive = MTLPrimitiveTypeLine;
  2959. break;
  2960. case RENDER_PRIMITIVE_LINESTRIPS:
  2961. case RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY:
  2962. pipeline->raster_state.render_primitive = MTLPrimitiveTypeLineStrip;
  2963. break;
  2964. case RENDER_PRIMITIVE_TRIANGLES:
  2965. case RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY:
  2966. pipeline->raster_state.render_primitive = MTLPrimitiveTypeTriangle;
  2967. break;
  2968. case RENDER_PRIMITIVE_TRIANGLE_STRIPS:
  2969. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY:
  2970. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX:
  2971. pipeline->raster_state.render_primitive = MTLPrimitiveTypeTriangleStrip;
  2972. break;
  2973. default:
  2974. break;
  2975. }
  2976. // Rasterization.
  2977. desc.rasterizationEnabled = !p_rasterization_state.discard_primitives;
  2978. pipeline->raster_state.clip_mode = p_rasterization_state.enable_depth_clamp ? MTLDepthClipModeClamp : MTLDepthClipModeClip;
  2979. pipeline->raster_state.fill_mode = p_rasterization_state.wireframe ? MTLTriangleFillModeLines : MTLTriangleFillModeFill;
  2980. static const MTLCullMode CULL_MODE[3] = {
  2981. MTLCullModeNone,
  2982. MTLCullModeFront,
  2983. MTLCullModeBack,
  2984. };
  2985. pipeline->raster_state.cull_mode = CULL_MODE[p_rasterization_state.cull_mode];
  2986. pipeline->raster_state.winding = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE) ? MTLWindingClockwise : MTLWindingCounterClockwise;
  2987. pipeline->raster_state.depth_bias.enabled = p_rasterization_state.depth_bias_enabled;
  2988. pipeline->raster_state.depth_bias.depth_bias = p_rasterization_state.depth_bias_constant_factor;
  2989. pipeline->raster_state.depth_bias.slope_scale = p_rasterization_state.depth_bias_slope_factor;
  2990. pipeline->raster_state.depth_bias.clamp = p_rasterization_state.depth_bias_clamp;
  2991. // In Metal there is no line width.
  2992. if (!Math::is_equal_approx(p_rasterization_state.line_width, 1.0f)) {
  2993. WARN_PRINT("unsupported: line width");
  2994. }
  2995. // Multisample.
  2996. if (p_multisample_state.enable_sample_shading) {
  2997. WARN_PRINT("unsupported: multi-sample shading");
  2998. }
  2999. if (p_multisample_state.sample_count > TEXTURE_SAMPLES_1) {
  3000. pipeline->sample_count = (*device_properties).find_nearest_supported_sample_count(p_multisample_state.sample_count);
  3001. }
  3002. desc.rasterSampleCount = static_cast<NSUInteger>(pipeline->sample_count);
  3003. desc.alphaToCoverageEnabled = p_multisample_state.enable_alpha_to_coverage;
  3004. desc.alphaToOneEnabled = p_multisample_state.enable_alpha_to_one;
  3005. // Depth stencil.
  3006. if (p_depth_stencil_state.enable_depth_test && desc.depthAttachmentPixelFormat != MTLPixelFormatInvalid) {
  3007. pipeline->raster_state.depth_test.enabled = true;
  3008. MTLDepthStencilDescriptor *ds_desc = [MTLDepthStencilDescriptor new];
  3009. ds_desc.depthWriteEnabled = p_depth_stencil_state.enable_depth_write;
  3010. ds_desc.depthCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.depth_compare_operator];
  3011. if (p_depth_stencil_state.enable_depth_range) {
  3012. WARN_PRINT("unsupported: depth range");
  3013. }
  3014. if (p_depth_stencil_state.enable_stencil) {
  3015. pipeline->raster_state.stencil.front_reference = p_depth_stencil_state.front_op.reference;
  3016. pipeline->raster_state.stencil.back_reference = p_depth_stencil_state.back_op.reference;
  3017. {
  3018. // Front.
  3019. MTLStencilDescriptor *sd = [MTLStencilDescriptor new];
  3020. sd.stencilFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.fail];
  3021. sd.depthStencilPassOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.pass];
  3022. sd.depthFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.depth_fail];
  3023. sd.stencilCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.front_op.compare];
  3024. sd.readMask = p_depth_stencil_state.front_op.compare_mask;
  3025. sd.writeMask = p_depth_stencil_state.front_op.write_mask;
  3026. ds_desc.frontFaceStencil = sd;
  3027. }
  3028. {
  3029. // Back.
  3030. MTLStencilDescriptor *sd = [MTLStencilDescriptor new];
  3031. sd.stencilFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.fail];
  3032. sd.depthStencilPassOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.pass];
  3033. sd.depthFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.depth_fail];
  3034. sd.stencilCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.back_op.compare];
  3035. sd.readMask = p_depth_stencil_state.back_op.compare_mask;
  3036. sd.writeMask = p_depth_stencil_state.back_op.write_mask;
  3037. ds_desc.backFaceStencil = sd;
  3038. }
  3039. }
  3040. pipeline->depth_stencil = [device newDepthStencilStateWithDescriptor:ds_desc];
  3041. ERR_FAIL_NULL_V_MSG(pipeline->depth_stencil, PipelineID(), "Failed to create depth stencil state");
  3042. } else {
  3043. // TODO(sgc): FB13671991 raised as Apple docs state calling setDepthStencilState:nil is valid, but currently generates an exception
  3044. pipeline->depth_stencil = get_resource_cache().get_depth_stencil_state(false, false);
  3045. }
  3046. // Blend state.
  3047. {
  3048. for (uint32_t i = 0; i < p_color_attachments.size(); i++) {
  3049. if (p_color_attachments[i] == ATTACHMENT_UNUSED) {
  3050. continue;
  3051. }
  3052. const PipelineColorBlendState::Attachment &bs = p_blend_state.attachments[i];
  3053. MTLRenderPipelineColorAttachmentDescriptor *ca_desc = desc.colorAttachments[p_color_attachments[i]];
  3054. ca_desc.blendingEnabled = bs.enable_blend;
  3055. ca_desc.sourceRGBBlendFactor = BLEND_FACTORS[bs.src_color_blend_factor];
  3056. ca_desc.destinationRGBBlendFactor = BLEND_FACTORS[bs.dst_color_blend_factor];
  3057. ca_desc.rgbBlendOperation = BLEND_OPERATIONS[bs.color_blend_op];
  3058. ca_desc.sourceAlphaBlendFactor = BLEND_FACTORS[bs.src_alpha_blend_factor];
  3059. ca_desc.destinationAlphaBlendFactor = BLEND_FACTORS[bs.dst_alpha_blend_factor];
  3060. ca_desc.alphaBlendOperation = BLEND_OPERATIONS[bs.alpha_blend_op];
  3061. ca_desc.writeMask = MTLColorWriteMaskNone;
  3062. if (bs.write_r) {
  3063. ca_desc.writeMask |= MTLColorWriteMaskRed;
  3064. }
  3065. if (bs.write_g) {
  3066. ca_desc.writeMask |= MTLColorWriteMaskGreen;
  3067. }
  3068. if (bs.write_b) {
  3069. ca_desc.writeMask |= MTLColorWriteMaskBlue;
  3070. }
  3071. if (bs.write_a) {
  3072. ca_desc.writeMask |= MTLColorWriteMaskAlpha;
  3073. }
  3074. }
  3075. pipeline->raster_state.blend.r = p_blend_state.blend_constant.r;
  3076. pipeline->raster_state.blend.g = p_blend_state.blend_constant.g;
  3077. pipeline->raster_state.blend.b = p_blend_state.blend_constant.b;
  3078. pipeline->raster_state.blend.a = p_blend_state.blend_constant.a;
  3079. }
  3080. // Dynamic state.
  3081. if (p_dynamic_state.has_flag(DYNAMIC_STATE_DEPTH_BIAS)) {
  3082. pipeline->raster_state.depth_bias.enabled = true;
  3083. }
  3084. if (p_dynamic_state.has_flag(DYNAMIC_STATE_BLEND_CONSTANTS)) {
  3085. pipeline->raster_state.blend.enabled = true;
  3086. }
  3087. if (p_dynamic_state.has_flag(DYNAMIC_STATE_DEPTH_BOUNDS)) {
  3088. // TODO(sgc): ??
  3089. }
  3090. if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_COMPARE_MASK)) {
  3091. // TODO(sgc): ??
  3092. }
  3093. if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_WRITE_MASK)) {
  3094. // TODO(sgc): ??
  3095. }
  3096. if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_REFERENCE)) {
  3097. pipeline->raster_state.stencil.enabled = true;
  3098. }
  3099. if (shader->vert != nil) {
  3100. Result<id<MTLFunction>> function_or_err = _create_function(shader->vert, @"main0", p_specialization_constants);
  3101. ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
  3102. desc.vertexFunction = std::get<id<MTLFunction>>(function_or_err);
  3103. }
  3104. if (shader->frag != nil) {
  3105. Result<id<MTLFunction>> function_or_err = _create_function(shader->frag, @"main0", p_specialization_constants);
  3106. ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
  3107. desc.fragmentFunction = std::get<id<MTLFunction>>(function_or_err);
  3108. }
  3109. if (archive) {
  3110. desc.binaryArchives = @[ archive ];
  3111. }
  3112. NSError *error = nil;
  3113. pipeline->state = [device newRenderPipelineStateWithDescriptor:desc
  3114. error:&error];
  3115. pipeline->shader = shader;
  3116. ERR_FAIL_COND_V_MSG(error != nil, PipelineID(), ([NSString stringWithFormat:@"error creating pipeline: %@", error.localizedDescription].UTF8String));
  3117. if (archive) {
  3118. if ([archive addRenderPipelineFunctionsWithDescriptor:desc error:&error]) {
  3119. archive_count += 1;
  3120. } else {
  3121. print_error(error.localizedDescription.UTF8String);
  3122. }
  3123. }
  3124. return PipelineID(pipeline);
  3125. }
  3126. #pragma mark - Compute
  3127. // ----- COMMANDS -----
  3128. void RenderingDeviceDriverMetal::command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
  3129. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3130. cb->bind_pipeline(p_pipeline);
  3131. }
  3132. void RenderingDeviceDriverMetal::command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  3133. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3134. cb->compute_bind_uniform_set(p_uniform_set, p_shader, p_set_index);
  3135. }
  3136. 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) {
  3137. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3138. cb->compute_bind_uniform_sets(p_uniform_sets, p_shader, p_first_set_index, p_set_count);
  3139. }
  3140. void RenderingDeviceDriverMetal::command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  3141. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3142. cb->compute_dispatch(p_x_groups, p_y_groups, p_z_groups);
  3143. }
  3144. void RenderingDeviceDriverMetal::command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) {
  3145. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3146. cb->compute_dispatch_indirect(p_indirect_buffer, p_offset);
  3147. }
  3148. // ----- PIPELINE -----
  3149. RDD::PipelineID RenderingDeviceDriverMetal::compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) {
  3150. MDComputeShader *shader = (MDComputeShader *)(p_shader.id);
  3151. os_signpost_id_t reflect_id = os_signpost_id_make_with_pointer(LOG_INTERVALS, shader);
  3152. os_signpost_interval_begin(LOG_INTERVALS, reflect_id, "compute_pipeline_create", "shader_name=%{public}s", shader->name.get_data());
  3153. DEFER([=]() {
  3154. os_signpost_interval_end(LOG_INTERVALS, reflect_id, "compute_pipeline_create");
  3155. });
  3156. os_signpost_event_emit(LOG_DRIVER, OS_SIGNPOST_ID_EXCLUSIVE, "create_pipeline");
  3157. Result<id<MTLFunction>> function_or_err = _create_function(shader->kernel, @"main0", p_specialization_constants);
  3158. ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
  3159. id<MTLFunction> function = std::get<id<MTLFunction>>(function_or_err);
  3160. MTLComputePipelineDescriptor *desc = [MTLComputePipelineDescriptor new];
  3161. desc.computeFunction = function;
  3162. if (archive) {
  3163. desc.binaryArchives = @[ archive ];
  3164. }
  3165. NSError *error;
  3166. id<MTLComputePipelineState> state = [device newComputePipelineStateWithDescriptor:desc
  3167. options:MTLPipelineOptionNone
  3168. reflection:nil
  3169. error:&error];
  3170. ERR_FAIL_COND_V_MSG(error != nil, PipelineID(), ([NSString stringWithFormat:@"error creating pipeline: %@", error.localizedDescription].UTF8String));
  3171. MDComputePipeline *pipeline = new MDComputePipeline(state);
  3172. pipeline->compute_state.local = shader->local;
  3173. pipeline->shader = shader;
  3174. if (archive) {
  3175. if ([archive addComputePipelineFunctionsWithDescriptor:desc error:&error]) {
  3176. archive_count += 1;
  3177. } else {
  3178. print_error(error.localizedDescription.UTF8String);
  3179. }
  3180. }
  3181. return PipelineID(pipeline);
  3182. }
  3183. #pragma mark - Queries
  3184. // ----- TIMESTAMP -----
  3185. RDD::QueryPoolID RenderingDeviceDriverMetal::timestamp_query_pool_create(uint32_t p_query_count) {
  3186. return QueryPoolID(1);
  3187. }
  3188. void RenderingDeviceDriverMetal::timestamp_query_pool_free(QueryPoolID p_pool_id) {
  3189. }
  3190. void RenderingDeviceDriverMetal::timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) {
  3191. // Metal doesn't support timestamp queries, so we just clear the buffer.
  3192. bzero(r_results, p_query_count * sizeof(uint64_t));
  3193. }
  3194. uint64_t RenderingDeviceDriverMetal::timestamp_query_result_to_time(uint64_t p_result) {
  3195. return p_result;
  3196. }
  3197. void RenderingDeviceDriverMetal::command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) {
  3198. }
  3199. void RenderingDeviceDriverMetal::command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) {
  3200. }
  3201. #pragma mark - Labels
  3202. void RenderingDeviceDriverMetal::command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) {
  3203. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3204. NSString *s = [[NSString alloc] initWithBytesNoCopy:(void *)p_label_name length:strlen(p_label_name) encoding:NSUTF8StringEncoding freeWhenDone:NO];
  3205. [cb->get_command_buffer() pushDebugGroup:s];
  3206. }
  3207. void RenderingDeviceDriverMetal::command_end_label(CommandBufferID p_cmd_buffer) {
  3208. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3209. [cb->get_command_buffer() popDebugGroup];
  3210. }
  3211. #pragma mark - Debug
  3212. void RenderingDeviceDriverMetal::command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) {
  3213. // TODO: Implement.
  3214. }
  3215. #pragma mark - Submission
  3216. void RenderingDeviceDriverMetal::begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) {
  3217. }
  3218. void RenderingDeviceDriverMetal::end_segment() {
  3219. }
  3220. #pragma mark - Misc
  3221. void RenderingDeviceDriverMetal::set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) {
  3222. switch (p_type) {
  3223. case OBJECT_TYPE_TEXTURE: {
  3224. id<MTLTexture> tex = rid::get(p_driver_id);
  3225. tex.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  3226. } break;
  3227. case OBJECT_TYPE_SAMPLER: {
  3228. // Can't set label after creation.
  3229. } break;
  3230. case OBJECT_TYPE_BUFFER: {
  3231. id<MTLBuffer> buffer = rid::get(p_driver_id);
  3232. buffer.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  3233. } break;
  3234. case OBJECT_TYPE_SHADER: {
  3235. NSString *label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  3236. MDShader *shader = (MDShader *)(p_driver_id.id);
  3237. if (MDRenderShader *rs = dynamic_cast<MDRenderShader *>(shader); rs != nullptr) {
  3238. [rs->vert setLabel:label];
  3239. [rs->frag setLabel:label];
  3240. } else if (MDComputeShader *cs = dynamic_cast<MDComputeShader *>(shader); cs != nullptr) {
  3241. [cs->kernel setLabel:label];
  3242. } else {
  3243. DEV_ASSERT(false);
  3244. }
  3245. } break;
  3246. case OBJECT_TYPE_UNIFORM_SET: {
  3247. MDUniformSet *set = (MDUniformSet *)(p_driver_id.id);
  3248. for (KeyValue<MDShader *, BoundUniformSet> &keyval : set->bound_uniforms) {
  3249. keyval.value.buffer.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  3250. }
  3251. } break;
  3252. case OBJECT_TYPE_PIPELINE: {
  3253. // Can't set label after creation.
  3254. } break;
  3255. default: {
  3256. DEV_ASSERT(false);
  3257. }
  3258. }
  3259. }
  3260. uint64_t RenderingDeviceDriverMetal::get_resource_native_handle(DriverResource p_type, ID p_driver_id) {
  3261. switch (p_type) {
  3262. case DRIVER_RESOURCE_LOGICAL_DEVICE: {
  3263. return (uint64_t)(uintptr_t)(__bridge void *)device;
  3264. }
  3265. case DRIVER_RESOURCE_PHYSICAL_DEVICE: {
  3266. return 0;
  3267. }
  3268. case DRIVER_RESOURCE_TOPMOST_OBJECT: {
  3269. return 0;
  3270. }
  3271. case DRIVER_RESOURCE_COMMAND_QUEUE: {
  3272. return (uint64_t)(uintptr_t)(__bridge void *)device_queue;
  3273. }
  3274. case DRIVER_RESOURCE_QUEUE_FAMILY: {
  3275. return 0;
  3276. }
  3277. case DRIVER_RESOURCE_TEXTURE: {
  3278. return p_driver_id.id;
  3279. }
  3280. case DRIVER_RESOURCE_TEXTURE_VIEW: {
  3281. return p_driver_id.id;
  3282. }
  3283. case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: {
  3284. return 0;
  3285. }
  3286. case DRIVER_RESOURCE_SAMPLER: {
  3287. return p_driver_id.id;
  3288. }
  3289. case DRIVER_RESOURCE_UNIFORM_SET: {
  3290. return 0;
  3291. }
  3292. case DRIVER_RESOURCE_BUFFER: {
  3293. return p_driver_id.id;
  3294. }
  3295. case DRIVER_RESOURCE_COMPUTE_PIPELINE: {
  3296. MDComputePipeline *pipeline = (MDComputePipeline *)(p_driver_id.id);
  3297. return (uint64_t)(uintptr_t)(__bridge void *)pipeline->state;
  3298. }
  3299. case DRIVER_RESOURCE_RENDER_PIPELINE: {
  3300. MDRenderPipeline *pipeline = (MDRenderPipeline *)(p_driver_id.id);
  3301. return (uint64_t)(uintptr_t)(__bridge void *)pipeline->state;
  3302. }
  3303. default: {
  3304. return 0;
  3305. }
  3306. }
  3307. }
  3308. uint64_t RenderingDeviceDriverMetal::get_total_memory_used() {
  3309. return device.currentAllocatedSize;
  3310. }
  3311. uint64_t RenderingDeviceDriverMetal::get_lazily_memory_used() {
  3312. return 0; // TODO: Track this (grep for memoryless in Godot's Metal backend).
  3313. }
  3314. uint64_t RenderingDeviceDriverMetal::limit_get(Limit p_limit) {
  3315. MetalDeviceProperties const &props = (*device_properties);
  3316. MetalLimits const &limits = props.limits;
  3317. uint64_t safe_unbounded = ((uint64_t)1 << 30);
  3318. #if defined(DEV_ENABLED)
  3319. #define UNKNOWN(NAME) \
  3320. case NAME: \
  3321. WARN_PRINT_ONCE("Returning maximum value for unknown limit " #NAME "."); \
  3322. return safe_unbounded;
  3323. #else
  3324. #define UNKNOWN(NAME) \
  3325. case NAME: \
  3326. return safe_unbounded
  3327. #endif
  3328. // clang-format off
  3329. switch (p_limit) {
  3330. case LIMIT_MAX_BOUND_UNIFORM_SETS:
  3331. return limits.maxBoundDescriptorSets;
  3332. case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS:
  3333. return limits.maxColorAttachments;
  3334. case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET:
  3335. return limits.maxTexturesPerArgumentBuffer;
  3336. case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET:
  3337. return limits.maxSamplersPerArgumentBuffer;
  3338. case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET:
  3339. return limits.maxBuffersPerArgumentBuffer;
  3340. case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET:
  3341. return limits.maxTexturesPerArgumentBuffer;
  3342. case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET:
  3343. return limits.maxBuffersPerArgumentBuffer;
  3344. case LIMIT_MAX_DRAW_INDEXED_INDEX:
  3345. return limits.maxDrawIndexedIndexValue;
  3346. case LIMIT_MAX_FRAMEBUFFER_HEIGHT:
  3347. return limits.maxFramebufferHeight;
  3348. case LIMIT_MAX_FRAMEBUFFER_WIDTH:
  3349. return limits.maxFramebufferWidth;
  3350. case LIMIT_MAX_TEXTURE_ARRAY_LAYERS:
  3351. return limits.maxImageArrayLayers;
  3352. case LIMIT_MAX_TEXTURE_SIZE_1D:
  3353. return limits.maxImageDimension1D;
  3354. case LIMIT_MAX_TEXTURE_SIZE_2D:
  3355. return limits.maxImageDimension2D;
  3356. case LIMIT_MAX_TEXTURE_SIZE_3D:
  3357. return limits.maxImageDimension3D;
  3358. case LIMIT_MAX_TEXTURE_SIZE_CUBE:
  3359. return limits.maxImageDimensionCube;
  3360. case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
  3361. return limits.maxTexturesPerArgumentBuffer;
  3362. case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE:
  3363. return limits.maxSamplersPerArgumentBuffer;
  3364. case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE:
  3365. return limits.maxBuffersPerArgumentBuffer;
  3366. case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE:
  3367. return limits.maxTexturesPerArgumentBuffer;
  3368. case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE:
  3369. return limits.maxBuffersPerArgumentBuffer;
  3370. case LIMIT_MAX_PUSH_CONSTANT_SIZE:
  3371. return limits.maxBufferLength;
  3372. case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
  3373. return limits.maxBufferLength;
  3374. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET:
  3375. return limits.maxVertexDescriptorLayoutStride;
  3376. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES:
  3377. return limits.maxVertexInputAttributes;
  3378. case LIMIT_MAX_VERTEX_INPUT_BINDINGS:
  3379. return limits.maxVertexInputBindings;
  3380. case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE:
  3381. return limits.maxVertexInputBindingStride;
  3382. case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
  3383. return limits.minUniformBufferOffsetAlignment;
  3384. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
  3385. return limits.maxComputeWorkGroupCount.width;
  3386. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
  3387. return limits.maxComputeWorkGroupCount.height;
  3388. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
  3389. return limits.maxComputeWorkGroupCount.depth;
  3390. case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS:
  3391. return std::max({ limits.maxThreadsPerThreadGroup.width, limits.maxThreadsPerThreadGroup.height, limits.maxThreadsPerThreadGroup.depth });
  3392. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
  3393. return limits.maxThreadsPerThreadGroup.width;
  3394. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
  3395. return limits.maxThreadsPerThreadGroup.height;
  3396. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
  3397. return limits.maxThreadsPerThreadGroup.depth;
  3398. case LIMIT_MAX_COMPUTE_SHARED_MEMORY_SIZE:
  3399. return limits.maxThreadGroupMemoryAllocation;
  3400. case LIMIT_MAX_VIEWPORT_DIMENSIONS_X:
  3401. return limits.maxViewportDimensionX;
  3402. case LIMIT_MAX_VIEWPORT_DIMENSIONS_Y:
  3403. return limits.maxViewportDimensionY;
  3404. case LIMIT_SUBGROUP_SIZE:
  3405. // MoltenVK sets the subgroupSize to the same as the maxSubgroupSize.
  3406. return limits.maxSubgroupSize;
  3407. case LIMIT_SUBGROUP_MIN_SIZE:
  3408. return limits.minSubgroupSize;
  3409. case LIMIT_SUBGROUP_MAX_SIZE:
  3410. return limits.maxSubgroupSize;
  3411. case LIMIT_SUBGROUP_IN_SHADERS:
  3412. return (uint64_t)limits.subgroupSupportedShaderStages;
  3413. case LIMIT_SUBGROUP_OPERATIONS:
  3414. return (uint64_t)limits.subgroupSupportedOperations;
  3415. case LIMIT_METALFX_TEMPORAL_SCALER_MIN_SCALE:
  3416. return (uint64_t)((1.0 / limits.temporalScalerInputContentMaxScale) * 1000'000);
  3417. case LIMIT_METALFX_TEMPORAL_SCALER_MAX_SCALE:
  3418. return (uint64_t)((1.0 / limits.temporalScalerInputContentMinScale) * 1000'000);
  3419. case LIMIT_MAX_SHADER_VARYINGS:
  3420. return limits.maxShaderVaryings;
  3421. default: {
  3422. #ifdef DEV_ENABLED
  3423. WARN_PRINT("Returning maximum value for unknown limit " + itos(p_limit) + ".");
  3424. #endif
  3425. return safe_unbounded;
  3426. }
  3427. }
  3428. // clang-format on
  3429. return 0;
  3430. }
  3431. uint64_t RenderingDeviceDriverMetal::api_trait_get(ApiTrait p_trait) {
  3432. switch (p_trait) {
  3433. case API_TRAIT_HONORS_PIPELINE_BARRIERS:
  3434. return 0;
  3435. default:
  3436. return RenderingDeviceDriver::api_trait_get(p_trait);
  3437. }
  3438. }
  3439. bool RenderingDeviceDriverMetal::has_feature(Features p_feature) {
  3440. switch (p_feature) {
  3441. case SUPPORTS_FSR_HALF_FLOAT:
  3442. return true;
  3443. case SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS:
  3444. return true;
  3445. case SUPPORTS_BUFFER_DEVICE_ADDRESS:
  3446. return device_properties->features.supports_gpu_address;
  3447. case SUPPORTS_METALFX_SPATIAL:
  3448. return device_properties->features.metal_fx_spatial;
  3449. case SUPPORTS_METALFX_TEMPORAL:
  3450. return device_properties->features.metal_fx_temporal;
  3451. default:
  3452. return false;
  3453. }
  3454. }
  3455. const RDD::MultiviewCapabilities &RenderingDeviceDriverMetal::get_multiview_capabilities() {
  3456. return multiview_capabilities;
  3457. }
  3458. const RDD::FragmentShadingRateCapabilities &RenderingDeviceDriverMetal::get_fragment_shading_rate_capabilities() {
  3459. return fsr_capabilities;
  3460. }
  3461. const RDD::FragmentDensityMapCapabilities &RenderingDeviceDriverMetal::get_fragment_density_map_capabilities() {
  3462. return fdm_capabilities;
  3463. }
  3464. String RenderingDeviceDriverMetal::get_api_version() const {
  3465. return vformat("%d.%d", version_major, version_minor);
  3466. }
  3467. String RenderingDeviceDriverMetal::get_pipeline_cache_uuid() const {
  3468. return pipeline_cache_id;
  3469. }
  3470. const RDD::Capabilities &RenderingDeviceDriverMetal::get_capabilities() const {
  3471. return capabilities;
  3472. }
  3473. bool RenderingDeviceDriverMetal::is_composite_alpha_supported(CommandQueueID p_queue) const {
  3474. // The CAMetalLayer.opaque property is configured according to this global setting.
  3475. return OS::get_singleton()->is_layered_allowed();
  3476. }
  3477. size_t RenderingDeviceDriverMetal::get_texel_buffer_alignment_for_format(RDD::DataFormat p_format) const {
  3478. return [device minimumLinearTextureAlignmentForPixelFormat:pixel_formats->getMTLPixelFormat(p_format)];
  3479. }
  3480. size_t RenderingDeviceDriverMetal::get_texel_buffer_alignment_for_format(MTLPixelFormat p_format) const {
  3481. return [device minimumLinearTextureAlignmentForPixelFormat:p_format];
  3482. }
  3483. /******************/
  3484. RenderingDeviceDriverMetal::RenderingDeviceDriverMetal(RenderingContextDriverMetal *p_context_driver) :
  3485. context_driver(p_context_driver) {
  3486. DEV_ASSERT(p_context_driver != nullptr);
  3487. #if TARGET_OS_OSX
  3488. if (String res = OS::get_singleton()->get_environment("GODOT_MTL_SHADER_LOAD_STRATEGY"); res == U"lazy") {
  3489. _shader_load_strategy = ShaderLoadStrategy::LAZY;
  3490. }
  3491. #else
  3492. // Always use the lazy strategy on other OSs like iOS, tvOS, or visionOS.
  3493. _shader_load_strategy = ShaderLoadStrategy::LAZY;
  3494. #endif
  3495. }
  3496. RenderingDeviceDriverMetal::~RenderingDeviceDriverMetal() {
  3497. for (MDCommandBuffer *cb : command_buffers) {
  3498. delete cb;
  3499. }
  3500. for (KeyValue<SHA256Digest, ShaderCacheEntry *> &kv : _shader_cache) {
  3501. memdelete(kv.value);
  3502. }
  3503. }
  3504. #pragma mark - Initialization
  3505. Error RenderingDeviceDriverMetal::_create_device() {
  3506. device = context_driver->get_metal_device();
  3507. device_queue = [device newCommandQueue];
  3508. ERR_FAIL_NULL_V(device_queue, ERR_CANT_CREATE);
  3509. device_scope = [MTLCaptureManager.sharedCaptureManager newCaptureScopeWithCommandQueue:device_queue];
  3510. device_scope.label = @"Godot Frame";
  3511. [device_scope beginScope]; // Allow Xcode to capture the first frame, if desired.
  3512. resource_cache = std::make_unique<MDResourceCache>(this);
  3513. return OK;
  3514. }
  3515. Error RenderingDeviceDriverMetal::_check_capabilities() {
  3516. MTLCompileOptions *options = [MTLCompileOptions new];
  3517. version_major = (options.languageVersion >> 0x10) & 0xff;
  3518. version_minor = (options.languageVersion >> 0x00) & 0xff;
  3519. capabilities.device_family = DEVICE_METAL;
  3520. capabilities.version_major = version_major;
  3521. capabilities.version_minor = version_minor;
  3522. return OK;
  3523. }
  3524. Error RenderingDeviceDriverMetal::initialize(uint32_t p_device_index, uint32_t p_frame_count) {
  3525. context_device = context_driver->device_get(p_device_index);
  3526. Error err = _create_device();
  3527. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  3528. err = _check_capabilities();
  3529. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  3530. // Set the pipeline cache ID based on the Metal version.
  3531. pipeline_cache_id = "metal-driver-" + get_api_version();
  3532. device_properties = memnew(MetalDeviceProperties(device));
  3533. pixel_formats = memnew(PixelFormats(device, device_properties->features));
  3534. if (device_properties->features.layeredRendering) {
  3535. multiview_capabilities.is_supported = true;
  3536. multiview_capabilities.max_view_count = device_properties->limits.maxViewports;
  3537. // NOTE: I'm not sure what the limit is as I don't see it referenced anywhere
  3538. multiview_capabilities.max_instance_count = UINT32_MAX;
  3539. print_verbose("- Metal multiview supported:");
  3540. print_verbose(" max view count: " + itos(multiview_capabilities.max_view_count));
  3541. print_verbose(" max instances: " + itos(multiview_capabilities.max_instance_count));
  3542. } else {
  3543. print_verbose("- Metal multiview not supported");
  3544. }
  3545. // The Metal renderer requires Apple4 family. This is 2017 era A11 chips and newer.
  3546. if (device_properties->features.highestFamily < MTLGPUFamilyApple4) {
  3547. 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");
  3548. if (!device_properties->features.imageCubeArray) {
  3549. error_string += "- No support for image cube arrays.\n";
  3550. }
  3551. #if defined(APPLE_EMBEDDED_ENABLED)
  3552. // Apple Embedded platforms exports currently don't exit themselves when this method returns `ERR_CANT_CREATE`.
  3553. OS::get_singleton()->alert(error_string + "\nClick OK to exit (black screen will be visible).");
  3554. #else
  3555. OS::get_singleton()->alert(error_string + "\nClick OK to exit.");
  3556. #endif
  3557. return ERR_CANT_CREATE;
  3558. }
  3559. return OK;
  3560. }