rendering_device_driver_metal.mm 151 KB

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