rendering_device_driver_metal.mm 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174
  1. /**************************************************************************/
  2. /* rendering_device_driver_metal.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. /**************************************************************************/
  31. /* */
  32. /* Portions of this code were derived from MoltenVK. */
  33. /* */
  34. /* Copyright (c) 2015-2023 The Brenwill Workshop Ltd. */
  35. /* (http://www.brenwill.com) */
  36. /* */
  37. /* Licensed under the Apache License, Version 2.0 (the "License"); */
  38. /* you may not use this file except in compliance with the License. */
  39. /* You may obtain a copy of the License at */
  40. /* */
  41. /* http://www.apache.org/licenses/LICENSE-2.0 */
  42. /* */
  43. /* Unless required by applicable law or agreed to in writing, software */
  44. /* distributed under the License is distributed on an "AS IS" BASIS, */
  45. /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
  46. /* implied. See the License for the specific language governing */
  47. /* permissions and limitations under the License. */
  48. /**************************************************************************/
  49. #import "rendering_device_driver_metal.h"
  50. #import "pixel_formats.h"
  51. #import "rendering_context_driver_metal.h"
  52. #import "core/io/compression.h"
  53. #import "core/io/marshalls.h"
  54. #import "core/string/ustring.h"
  55. #import "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. #endif
  1712. bool disable_argument_buffers = false;
  1713. if (String v = OS::get_singleton()->get_environment(U"GODOT_DISABLE_ARGUMENT_BUFFERS"); v == U"1") {
  1714. disable_argument_buffers = true;
  1715. }
  1716. if (device_properties->features.argument_buffers_tier >= MTLArgumentBuffersTier2 && !disable_argument_buffers) {
  1717. msl_options.argument_buffers_tier = CompilerMSL::Options::ArgumentBuffersTier::Tier2;
  1718. msl_options.argument_buffers = true;
  1719. bin_data.set_uses_argument_buffers(true);
  1720. } else {
  1721. msl_options.argument_buffers_tier = CompilerMSL::Options::ArgumentBuffersTier::Tier1;
  1722. // Tier 1 argument buffers don't support writable textures, so we disable them completely.
  1723. msl_options.argument_buffers = false;
  1724. bin_data.set_uses_argument_buffers(false);
  1725. }
  1726. msl_options.force_active_argument_buffer_resources = true;
  1727. // We can't use this, as we have to add the descriptor sets via compiler.add_msl_resource_binding.
  1728. // msl_options.pad_argument_buffer_resources = true;
  1729. msl_options.texture_buffer_native = true; // Enable texture buffer support.
  1730. msl_options.use_framebuffer_fetch_subpasses = false;
  1731. msl_options.pad_fragment_output_components = true;
  1732. msl_options.r32ui_alignment_constant_id = R32UI_ALIGNMENT_CONSTANT_ID;
  1733. msl_options.agx_manual_cube_grad_fixup = true;
  1734. if (shader_meta.has_multiview) {
  1735. msl_options.multiview = true;
  1736. msl_options.multiview_layered_rendering = true;
  1737. msl_options.view_mask_buffer_index = VIEW_MASK_BUFFER_INDEX;
  1738. }
  1739. CompilerGLSL::Options options{};
  1740. options.vertex.flip_vert_y = true;
  1741. #if DEV_ENABLED
  1742. options.emit_line_directives = true;
  1743. #endif
  1744. for (uint32_t i = 0; i < p_spirv.size(); i++) {
  1745. ShaderStageSPIRVData const &v = p_spirv[i];
  1746. ShaderStage stage = v.shader_stage;
  1747. char const *stage_name = SHADER_STAGE_NAMES[stage];
  1748. uint32_t const *const ir = reinterpret_cast<uint32_t const *const>(v.spirv.ptr());
  1749. size_t word_count = v.spirv.size() / sizeof(uint32_t);
  1750. Parser parser(ir, word_count);
  1751. try {
  1752. parser.parse();
  1753. } catch (CompilerError &e) {
  1754. ERR_FAIL_V_MSG(Result(), "Failed to parse IR at stage " + String(SHADER_STAGE_NAMES[stage]) + ": " + e.what());
  1755. }
  1756. CompilerMSL compiler(std::move(parser.get_parsed_ir()));
  1757. compiler.set_msl_options(msl_options);
  1758. compiler.set_common_options(options);
  1759. std::unordered_set<VariableID> active = compiler.get_active_interface_variables();
  1760. ShaderResources resources = compiler.get_shader_resources();
  1761. std::string source;
  1762. try {
  1763. source = compiler.compile();
  1764. } catch (CompilerError &e) {
  1765. ERR_FAIL_V_MSG(Result(), "Failed to compile stage " + String(SHADER_STAGE_NAMES[stage]) + ": " + e.what());
  1766. }
  1767. ERR_FAIL_COND_V_MSG(compiler.get_entry_points_and_stages().size() != 1, Result(), "Expected a single entry point and stage.");
  1768. SmallVector<EntryPoint> entry_pts_stages = compiler.get_entry_points_and_stages();
  1769. EntryPoint &entry_point_stage = entry_pts_stages.front();
  1770. SPIREntryPoint &entry_point = compiler.get_entry_point(entry_point_stage.name, entry_point_stage.execution_model);
  1771. // Process specialization constants.
  1772. if (!compiler.get_specialization_constants().empty()) {
  1773. for (SpecializationConstant const &constant : compiler.get_specialization_constants()) {
  1774. LocalVector<SpecializationConstantData>::Iterator res = bin_data.constants.begin();
  1775. while (res != bin_data.constants.end()) {
  1776. if (res->constant_id == constant.constant_id) {
  1777. res->used_stages |= 1 << stage;
  1778. break;
  1779. }
  1780. ++res;
  1781. }
  1782. if (res == bin_data.constants.end()) {
  1783. WARN_PRINT(String(stage_name) + ": unable to find constant_id: " + itos(constant.constant_id));
  1784. }
  1785. }
  1786. }
  1787. // Process bindings.
  1788. LocalVector<UniformSetData> &uniform_sets = bin_data.uniforms;
  1789. using BT = SPIRType::BaseType;
  1790. // Always clearer than a boolean.
  1791. enum class Writable {
  1792. No,
  1793. Maybe,
  1794. };
  1795. // Returns a std::optional containing the value of the
  1796. // decoration, if it exists.
  1797. auto get_decoration = [&compiler](spirv_cross::ID id, spv::Decoration decoration) {
  1798. uint32_t res = -1;
  1799. if (compiler.has_decoration(id, decoration)) {
  1800. res = compiler.get_decoration(id, decoration);
  1801. }
  1802. return res;
  1803. };
  1804. auto descriptor_bindings = [&compiler, &active, &uniform_sets, stage, &get_decoration](SmallVector<Resource> &p_resources, Writable p_writable) {
  1805. for (Resource const &res : p_resources) {
  1806. uint32_t dset = get_decoration(res.id, spv::DecorationDescriptorSet);
  1807. uint32_t dbin = get_decoration(res.id, spv::DecorationBinding);
  1808. UniformData *found = nullptr;
  1809. if (dset != (uint32_t)-1 && dbin != (uint32_t)-1 && dset < uniform_sets.size()) {
  1810. UniformSetData &set = uniform_sets[dset];
  1811. LocalVector<UniformData>::Iterator pos = set.uniforms.begin();
  1812. while (pos != set.uniforms.end()) {
  1813. if (dbin == pos->binding) {
  1814. found = &(*pos);
  1815. break;
  1816. }
  1817. ++pos;
  1818. }
  1819. }
  1820. ERR_FAIL_NULL_V_MSG(found, ERR_CANT_CREATE, "UniformData not found");
  1821. bool is_active = active.find(res.id) != active.end();
  1822. if (is_active) {
  1823. found->active_stages |= 1 << stage;
  1824. }
  1825. BindingInfo primary{};
  1826. SPIRType const &a_type = compiler.get_type(res.type_id);
  1827. BT basetype = a_type.basetype;
  1828. switch (basetype) {
  1829. case BT::Struct: {
  1830. primary.dataType = MTLDataTypePointer;
  1831. } break;
  1832. case BT::Image:
  1833. case BT::SampledImage: {
  1834. primary.dataType = MTLDataTypeTexture;
  1835. } break;
  1836. case BT::Sampler: {
  1837. primary.dataType = MTLDataTypeSampler;
  1838. primary.arrayLength = 1;
  1839. for (uint32_t const &a : a_type.array) {
  1840. primary.arrayLength *= a;
  1841. }
  1842. } break;
  1843. default: {
  1844. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Unexpected BaseType");
  1845. } break;
  1846. }
  1847. // Find array length of image.
  1848. if (basetype == BT::Image || basetype == BT::SampledImage) {
  1849. primary.arrayLength = 1;
  1850. for (uint32_t const &a : a_type.array) {
  1851. primary.arrayLength *= a;
  1852. }
  1853. primary.isMultisampled = a_type.image.ms;
  1854. SPIRType::ImageType const &image = a_type.image;
  1855. primary.imageFormat = image.format;
  1856. switch (image.dim) {
  1857. case spv::Dim1D: {
  1858. if (image.arrayed) {
  1859. primary.textureType = MTLTextureType1DArray;
  1860. } else {
  1861. primary.textureType = MTLTextureType1D;
  1862. }
  1863. } break;
  1864. case spv::DimSubpassData: {
  1865. DISPATCH_FALLTHROUGH;
  1866. }
  1867. case spv::Dim2D: {
  1868. if (image.arrayed && image.ms) {
  1869. primary.textureType = MTLTextureType2DMultisampleArray;
  1870. } else if (image.arrayed) {
  1871. primary.textureType = MTLTextureType2DArray;
  1872. } else if (image.ms) {
  1873. primary.textureType = MTLTextureType2DMultisample;
  1874. } else {
  1875. primary.textureType = MTLTextureType2D;
  1876. }
  1877. } break;
  1878. case spv::Dim3D: {
  1879. primary.textureType = MTLTextureType3D;
  1880. } break;
  1881. case spv::DimCube: {
  1882. if (image.arrayed) {
  1883. primary.textureType = MTLTextureTypeCube;
  1884. }
  1885. } break;
  1886. case spv::DimRect: {
  1887. } break;
  1888. case spv::DimBuffer: {
  1889. // VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER
  1890. primary.textureType = MTLTextureTypeTextureBuffer;
  1891. } break;
  1892. case spv::DimMax: {
  1893. // Add all enumerations to silence the compiler warning
  1894. // and generate future warnings, should a new one be added.
  1895. } break;
  1896. }
  1897. }
  1898. // Update writable.
  1899. if (p_writable == Writable::Maybe) {
  1900. if (basetype == BT::Struct) {
  1901. Bitset flags = compiler.get_buffer_block_flags(res.id);
  1902. if (!flags.get(spv::DecorationNonWritable)) {
  1903. if (flags.get(spv::DecorationNonReadable)) {
  1904. primary.access = MTLBindingAccessWriteOnly;
  1905. } else {
  1906. primary.access = MTLBindingAccessReadWrite;
  1907. }
  1908. }
  1909. } else if (basetype == BT::Image) {
  1910. switch (a_type.image.access) {
  1911. case spv::AccessQualifierWriteOnly:
  1912. primary.access = MTLBindingAccessWriteOnly;
  1913. break;
  1914. case spv::AccessQualifierReadWrite:
  1915. primary.access = MTLBindingAccessReadWrite;
  1916. break;
  1917. case spv::AccessQualifierReadOnly:
  1918. break;
  1919. case spv::AccessQualifierMax:
  1920. DISPATCH_FALLTHROUGH;
  1921. default:
  1922. if (!compiler.has_decoration(res.id, spv::DecorationNonWritable)) {
  1923. if (compiler.has_decoration(res.id, spv::DecorationNonReadable)) {
  1924. primary.access = MTLBindingAccessWriteOnly;
  1925. } else {
  1926. primary.access = MTLBindingAccessReadWrite;
  1927. }
  1928. }
  1929. break;
  1930. }
  1931. }
  1932. }
  1933. switch (primary.access) {
  1934. case MTLBindingAccessReadOnly:
  1935. primary.usage = MTLResourceUsageRead;
  1936. break;
  1937. case MTLBindingAccessWriteOnly:
  1938. primary.usage = MTLResourceUsageWrite;
  1939. break;
  1940. case MTLBindingAccessReadWrite:
  1941. primary.usage = MTLResourceUsageRead | MTLResourceUsageWrite;
  1942. break;
  1943. }
  1944. primary.index = compiler.get_automatic_msl_resource_binding(res.id);
  1945. found->bindings[stage] = primary;
  1946. // A sampled image contains two bindings, the primary
  1947. // is to the image, and the secondary is to the associated sampler.
  1948. if (basetype == BT::SampledImage) {
  1949. uint32_t binding = compiler.get_automatic_msl_resource_binding_secondary(res.id);
  1950. if (binding != (uint32_t)-1) {
  1951. found->bindings_secondary[stage] = BindingInfo{
  1952. .dataType = MTLDataTypeSampler,
  1953. .index = binding,
  1954. .access = MTLBindingAccessReadOnly,
  1955. };
  1956. }
  1957. }
  1958. // An image may have a secondary binding if it is used
  1959. // for atomic operations.
  1960. if (basetype == BT::Image) {
  1961. uint32_t binding = compiler.get_automatic_msl_resource_binding_secondary(res.id);
  1962. if (binding != (uint32_t)-1) {
  1963. found->bindings_secondary[stage] = BindingInfo{
  1964. .dataType = MTLDataTypePointer,
  1965. .index = binding,
  1966. .access = MTLBindingAccessReadWrite,
  1967. };
  1968. }
  1969. }
  1970. }
  1971. return Error::OK;
  1972. };
  1973. if (!resources.uniform_buffers.empty()) {
  1974. Error err = descriptor_bindings(resources.uniform_buffers, Writable::No);
  1975. ERR_FAIL_COND_V(err != OK, Result());
  1976. }
  1977. if (!resources.storage_buffers.empty()) {
  1978. Error err = descriptor_bindings(resources.storage_buffers, Writable::Maybe);
  1979. ERR_FAIL_COND_V(err != OK, Result());
  1980. }
  1981. if (!resources.storage_images.empty()) {
  1982. Error err = descriptor_bindings(resources.storage_images, Writable::Maybe);
  1983. ERR_FAIL_COND_V(err != OK, Result());
  1984. }
  1985. if (!resources.sampled_images.empty()) {
  1986. Error err = descriptor_bindings(resources.sampled_images, Writable::No);
  1987. ERR_FAIL_COND_V(err != OK, Result());
  1988. }
  1989. if (!resources.separate_images.empty()) {
  1990. Error err = descriptor_bindings(resources.separate_images, Writable::No);
  1991. ERR_FAIL_COND_V(err != OK, Result());
  1992. }
  1993. if (!resources.separate_samplers.empty()) {
  1994. Error err = descriptor_bindings(resources.separate_samplers, Writable::No);
  1995. ERR_FAIL_COND_V(err != OK, Result());
  1996. }
  1997. if (!resources.subpass_inputs.empty()) {
  1998. Error err = descriptor_bindings(resources.subpass_inputs, Writable::No);
  1999. ERR_FAIL_COND_V(err != OK, Result());
  2000. }
  2001. if (!resources.push_constant_buffers.empty()) {
  2002. for (Resource const &res : resources.push_constant_buffers) {
  2003. uint32_t binding = compiler.get_automatic_msl_resource_binding(res.id);
  2004. if (binding != (uint32_t)-1) {
  2005. bin_data.push_constant.used_stages |= 1 << stage;
  2006. bin_data.push_constant.msl_binding[stage] = binding;
  2007. }
  2008. }
  2009. }
  2010. ERR_FAIL_COND_V_MSG(!resources.atomic_counters.empty(), Result(), "Atomic counters not supported");
  2011. ERR_FAIL_COND_V_MSG(!resources.acceleration_structures.empty(), Result(), "Acceleration structures not supported");
  2012. ERR_FAIL_COND_V_MSG(!resources.shader_record_buffers.empty(), Result(), "Shader record buffers not supported");
  2013. if (!resources.stage_inputs.empty()) {
  2014. for (Resource const &res : resources.stage_inputs) {
  2015. uint32_t binding = compiler.get_automatic_msl_resource_binding(res.id);
  2016. if (binding != (uint32_t)-1) {
  2017. bin_data.vertex_input_mask |= 1 << binding;
  2018. }
  2019. }
  2020. }
  2021. ShaderStageData stage_data;
  2022. stage_data.stage = v.shader_stage;
  2023. stage_data.is_position_invariant = compiler.is_position_invariant();
  2024. stage_data.supports_fast_math = !entry_point.flags.get(spv::ExecutionModeSignedZeroInfNanPreserve);
  2025. stage_data.entry_point_name = entry_point.name.c_str();
  2026. stage_data.source = source.c_str();
  2027. bin_data.stages.push_back(stage_data);
  2028. }
  2029. size_t vec_size = bin_data.serialize_size() + 8;
  2030. ::Vector<uint8_t> ret;
  2031. ret.resize(vec_size);
  2032. BufWriter writer(ret.ptrw(), vec_size);
  2033. const uint8_t HEADER[4] = { 'G', 'M', 'S', 'L' };
  2034. writer.write(*(uint32_t *)HEADER);
  2035. writer.write(SHADER_BINARY_VERSION);
  2036. bin_data.serialize(writer);
  2037. ret.resize(writer.get_pos());
  2038. return ret;
  2039. }
  2040. void RenderingDeviceDriverMetal::shader_cache_free_entry(const SHA256Digest &key) {
  2041. if (ShaderCacheEntry **pentry = _shader_cache.getptr(key); pentry != nullptr) {
  2042. ShaderCacheEntry *entry = *pentry;
  2043. _shader_cache.erase(key);
  2044. entry->library = nil;
  2045. memdelete(entry);
  2046. }
  2047. }
  2048. 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) {
  2049. r_shader_desc = {}; // Driver-agnostic.
  2050. const uint8_t *binptr = p_shader_binary.ptr();
  2051. uint32_t binsize = p_shader_binary.size();
  2052. BufReader reader(binptr, binsize);
  2053. uint8_t header[4];
  2054. reader.read((uint32_t &)header);
  2055. ERR_FAIL_COND_V_MSG(memcmp(header, "GMSL", 4) != 0, ShaderID(), "Invalid header");
  2056. uint32_t version = 0;
  2057. reader.read(version);
  2058. ERR_FAIL_COND_V_MSG(version != SHADER_BINARY_VERSION, ShaderID(), "Invalid shader binary version");
  2059. ShaderBinaryData binary_data;
  2060. binary_data.deserialize(reader);
  2061. switch (reader.status) {
  2062. case BufReader::Status::OK:
  2063. break;
  2064. case BufReader::Status::BAD_COMPRESSION:
  2065. ERR_FAIL_V_MSG(ShaderID(), "Invalid compressed data");
  2066. case BufReader::Status::SHORT_BUFFER:
  2067. ERR_FAIL_V_MSG(ShaderID(), "Unexpected end of buffer");
  2068. }
  2069. // We need to regenerate the shader if the cache is moved to an incompatible device.
  2070. ERR_FAIL_COND_V_MSG(device_properties->features.argument_buffers_tier < MTLArgumentBuffersTier2 && binary_data.uses_argument_buffers(),
  2071. ShaderID(),
  2072. "Shader was generated with argument buffers, but device has limited support");
  2073. MTLCompileOptions *options = [MTLCompileOptions new];
  2074. options.languageVersion = binary_data.get_msl_version();
  2075. HashMap<ShaderStage, MDLibrary *> libraries;
  2076. for (ShaderStageData &shader_data : binary_data.stages) {
  2077. SHA256Digest key = SHA256Digest(shader_data.source.ptr(), shader_data.source.length());
  2078. if (ShaderCacheEntry **p = _shader_cache.getptr(key); p != nullptr) {
  2079. libraries[shader_data.stage] = (*p)->library;
  2080. continue;
  2081. }
  2082. NSString *source = [[NSString alloc] initWithBytes:(void *)shader_data.source.ptr()
  2083. length:shader_data.source.length()
  2084. encoding:NSUTF8StringEncoding];
  2085. ShaderCacheEntry *cd = memnew(ShaderCacheEntry(*this, key));
  2086. cd->name = binary_data.shader_name;
  2087. cd->stage = shader_data.stage;
  2088. options.preserveInvariance = shader_data.is_position_invariant;
  2089. options.fastMathEnabled = YES;
  2090. MDLibrary *library = [MDLibrary newLibraryWithCacheEntry:cd
  2091. device:device
  2092. source:source
  2093. options:options
  2094. strategy:_shader_load_strategy];
  2095. _shader_cache[key] = cd;
  2096. libraries[shader_data.stage] = library;
  2097. }
  2098. Vector<UniformSet> uniform_sets;
  2099. uniform_sets.resize(binary_data.uniforms.size());
  2100. r_shader_desc.uniform_sets.resize(binary_data.uniforms.size());
  2101. // Create sets.
  2102. for (UniformSetData &uniform_set : binary_data.uniforms) {
  2103. UniformSet &set = uniform_sets.write[uniform_set.index];
  2104. set.uniforms.resize(uniform_set.uniforms.size());
  2105. Vector<ShaderUniform> &uset = r_shader_desc.uniform_sets.write[uniform_set.index];
  2106. uset.resize(uniform_set.uniforms.size());
  2107. for (uint32_t i = 0; i < uniform_set.uniforms.size(); i++) {
  2108. UniformData &uniform = uniform_set.uniforms[i];
  2109. ShaderUniform su;
  2110. su.type = uniform.type;
  2111. su.writable = uniform.writable;
  2112. su.length = uniform.length;
  2113. su.binding = uniform.binding;
  2114. su.stages = uniform.stages;
  2115. uset.write[i] = su;
  2116. UniformInfo ui;
  2117. ui.binding = uniform.binding;
  2118. ui.active_stages = uniform.active_stages;
  2119. for (KeyValue<RDC::ShaderStage, BindingInfo> &kv : uniform.bindings) {
  2120. ui.bindings.insert(kv.key, kv.value);
  2121. }
  2122. for (KeyValue<RDC::ShaderStage, BindingInfo> &kv : uniform.bindings_secondary) {
  2123. ui.bindings_secondary.insert(kv.key, kv.value);
  2124. }
  2125. set.uniforms[i] = ui;
  2126. }
  2127. }
  2128. for (UniformSetData &uniform_set : binary_data.uniforms) {
  2129. UniformSet &set = uniform_sets.write[uniform_set.index];
  2130. // Make encoders.
  2131. for (ShaderStageData const &stage_data : binary_data.stages) {
  2132. ShaderStage stage = stage_data.stage;
  2133. NSMutableArray<MTLArgumentDescriptor *> *descriptors = [NSMutableArray new];
  2134. for (UniformInfo const &uniform : set.uniforms) {
  2135. BindingInfo const *binding_info = uniform.bindings.getptr(stage);
  2136. if (binding_info == nullptr) {
  2137. continue;
  2138. }
  2139. [descriptors addObject:binding_info->new_argument_descriptor()];
  2140. BindingInfo const *secondary_binding_info = uniform.bindings_secondary.getptr(stage);
  2141. if (secondary_binding_info != nullptr) {
  2142. [descriptors addObject:secondary_binding_info->new_argument_descriptor()];
  2143. }
  2144. }
  2145. if (descriptors.count == 0) {
  2146. // No bindings.
  2147. continue;
  2148. }
  2149. // Sort by index.
  2150. [descriptors sortUsingComparator:^NSComparisonResult(MTLArgumentDescriptor *a, MTLArgumentDescriptor *b) {
  2151. if (a.index < b.index) {
  2152. return NSOrderedAscending;
  2153. } else if (a.index > b.index) {
  2154. return NSOrderedDescending;
  2155. } else {
  2156. return NSOrderedSame;
  2157. }
  2158. }];
  2159. id<MTLArgumentEncoder> enc = [device newArgumentEncoderWithArguments:descriptors];
  2160. set.encoders[stage] = enc;
  2161. set.offsets[stage] = set.buffer_size;
  2162. set.buffer_size += enc.encodedLength;
  2163. }
  2164. }
  2165. r_shader_desc.specialization_constants.resize(binary_data.constants.size());
  2166. for (uint32_t i = 0; i < binary_data.constants.size(); i++) {
  2167. SpecializationConstantData &c = binary_data.constants[i];
  2168. ShaderSpecializationConstant sc;
  2169. sc.type = c.type;
  2170. sc.constant_id = c.constant_id;
  2171. sc.int_value = c.int_value;
  2172. sc.stages = c.stages;
  2173. r_shader_desc.specialization_constants.write[i] = sc;
  2174. }
  2175. MDShader *shader = nullptr;
  2176. if (binary_data.is_compute()) {
  2177. MDComputeShader *cs = new MDComputeShader(
  2178. binary_data.shader_name,
  2179. uniform_sets,
  2180. binary_data.uses_argument_buffers(),
  2181. libraries[ShaderStage::SHADER_STAGE_COMPUTE]);
  2182. uint32_t *binding = binary_data.push_constant.msl_binding.getptr(SHADER_STAGE_COMPUTE);
  2183. if (binding) {
  2184. cs->push_constants.size = binary_data.push_constant.size;
  2185. cs->push_constants.binding = *binding;
  2186. }
  2187. cs->local = MTLSizeMake(binary_data.compute_local_size.x, binary_data.compute_local_size.y, binary_data.compute_local_size.z);
  2188. #if DEV_ENABLED
  2189. cs->kernel_source = binary_data.stages[0].source;
  2190. #endif
  2191. shader = cs;
  2192. } else {
  2193. MDRenderShader *rs = new MDRenderShader(
  2194. binary_data.shader_name,
  2195. uniform_sets,
  2196. binary_data.needs_view_mask_buffer(),
  2197. binary_data.uses_argument_buffers(),
  2198. libraries[ShaderStage::SHADER_STAGE_VERTEX],
  2199. libraries[ShaderStage::SHADER_STAGE_FRAGMENT]);
  2200. uint32_t *vert_binding = binary_data.push_constant.msl_binding.getptr(SHADER_STAGE_VERTEX);
  2201. if (vert_binding) {
  2202. rs->push_constants.vert.size = binary_data.push_constant.size;
  2203. rs->push_constants.vert.binding = *vert_binding;
  2204. }
  2205. uint32_t *frag_binding = binary_data.push_constant.msl_binding.getptr(SHADER_STAGE_FRAGMENT);
  2206. if (frag_binding) {
  2207. rs->push_constants.frag.size = binary_data.push_constant.size;
  2208. rs->push_constants.frag.binding = *frag_binding;
  2209. }
  2210. #if DEV_ENABLED
  2211. for (ShaderStageData &stage_data : binary_data.stages) {
  2212. if (stage_data.stage == ShaderStage::SHADER_STAGE_VERTEX) {
  2213. rs->vert_source = stage_data.source;
  2214. } else if (stage_data.stage == ShaderStage::SHADER_STAGE_FRAGMENT) {
  2215. rs->frag_source = stage_data.source;
  2216. }
  2217. }
  2218. #endif
  2219. shader = rs;
  2220. }
  2221. r_shader_desc.vertex_input_mask = binary_data.vertex_input_mask;
  2222. r_shader_desc.fragment_output_mask = binary_data.fragment_output_mask;
  2223. r_shader_desc.is_compute = binary_data.is_compute();
  2224. r_shader_desc.compute_local_size[0] = binary_data.compute_local_size.x;
  2225. r_shader_desc.compute_local_size[1] = binary_data.compute_local_size.y;
  2226. r_shader_desc.compute_local_size[2] = binary_data.compute_local_size.z;
  2227. r_shader_desc.push_constant_size = binary_data.push_constant.size;
  2228. return ShaderID(shader);
  2229. }
  2230. void RenderingDeviceDriverMetal::shader_free(ShaderID p_shader) {
  2231. MDShader *obj = (MDShader *)p_shader.id;
  2232. delete obj;
  2233. }
  2234. void RenderingDeviceDriverMetal::shader_destroy_modules(ShaderID p_shader) {
  2235. // TODO.
  2236. }
  2237. /*********************/
  2238. /**** UNIFORM SET ****/
  2239. /*********************/
  2240. RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) {
  2241. //p_linear_pool_index = -1; // TODO:? Linear pools not implemented or not supported by API backend.
  2242. MDUniformSet *set = memnew(MDUniformSet);
  2243. Vector<BoundUniform> bound_uniforms;
  2244. bound_uniforms.resize(p_uniforms.size());
  2245. for (uint32_t i = 0; i < p_uniforms.size(); i += 1) {
  2246. bound_uniforms.write[i] = p_uniforms[i];
  2247. }
  2248. set->uniforms = bound_uniforms;
  2249. set->index = p_set_index;
  2250. return UniformSetID(set);
  2251. }
  2252. void RenderingDeviceDriverMetal::uniform_set_free(UniformSetID p_uniform_set) {
  2253. MDUniformSet *obj = (MDUniformSet *)p_uniform_set.id;
  2254. memdelete(obj);
  2255. }
  2256. void RenderingDeviceDriverMetal::command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  2257. }
  2258. #pragma mark - Transfer
  2259. void RenderingDeviceDriverMetal::command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) {
  2260. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  2261. id<MTLBuffer> buffer = rid::get(p_buffer);
  2262. id<MTLBlitCommandEncoder> blit = cmd->blit_command_encoder();
  2263. [blit fillBuffer:buffer
  2264. range:NSMakeRange(p_offset, p_size)
  2265. value:0];
  2266. }
  2267. void RenderingDeviceDriverMetal::command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) {
  2268. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  2269. id<MTLBuffer> src = rid::get(p_src_buffer);
  2270. id<MTLBuffer> dst = rid::get(p_dst_buffer);
  2271. id<MTLBlitCommandEncoder> blit = cmd->blit_command_encoder();
  2272. for (uint32_t i = 0; i < p_regions.size(); i++) {
  2273. BufferCopyRegion region = p_regions[i];
  2274. [blit copyFromBuffer:src
  2275. sourceOffset:region.src_offset
  2276. toBuffer:dst
  2277. destinationOffset:region.dst_offset
  2278. size:region.size];
  2279. }
  2280. }
  2281. MTLSize MTLSizeFromVector3i(Vector3i p_size) {
  2282. return MTLSizeMake(p_size.x, p_size.y, p_size.z);
  2283. }
  2284. MTLOrigin MTLOriginFromVector3i(Vector3i p_origin) {
  2285. return MTLOriginMake(p_origin.x, p_origin.y, p_origin.z);
  2286. }
  2287. // Clamps the size so that the sum of the origin and size do not exceed the maximum size.
  2288. static inline MTLSize clampMTLSize(MTLSize p_size, MTLOrigin p_origin, MTLSize p_max_size) {
  2289. MTLSize clamped;
  2290. clamped.width = MIN(p_size.width, p_max_size.width - p_origin.x);
  2291. clamped.height = MIN(p_size.height, p_max_size.height - p_origin.y);
  2292. clamped.depth = MIN(p_size.depth, p_max_size.depth - p_origin.z);
  2293. return clamped;
  2294. }
  2295. 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) {
  2296. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  2297. id<MTLTexture> src = rid::get(p_src_texture);
  2298. id<MTLTexture> dst = rid::get(p_dst_texture);
  2299. id<MTLBlitCommandEncoder> blit = cmd->blit_command_encoder();
  2300. PixelFormats &pf = *pixel_formats;
  2301. MTLPixelFormat src_fmt = src.pixelFormat;
  2302. bool src_is_compressed = pf.getFormatType(src_fmt) == MTLFormatType::Compressed;
  2303. MTLPixelFormat dst_fmt = dst.pixelFormat;
  2304. bool dst_is_compressed = pf.getFormatType(dst_fmt) == MTLFormatType::Compressed;
  2305. // Validate copy.
  2306. if (src.sampleCount != dst.sampleCount || pf.getBytesPerBlock(src_fmt) != pf.getBytesPerBlock(dst_fmt)) {
  2307. ERR_FAIL_MSG("Cannot copy between incompatible pixel formats, such as formats of different pixel sizes, or between images with different sample counts.");
  2308. }
  2309. // If source and destination have different formats and at least one is compressed, a temporary buffer is required.
  2310. bool need_tmp_buffer = (src_fmt != dst_fmt) && (src_is_compressed || dst_is_compressed);
  2311. if (need_tmp_buffer) {
  2312. ERR_FAIL_MSG("not implemented: copy with intermediate buffer");
  2313. }
  2314. if (src_fmt != dst_fmt) {
  2315. // Map the source pixel format to the dst through a texture view on the source texture.
  2316. src = [src newTextureViewWithPixelFormat:dst_fmt];
  2317. }
  2318. for (uint32_t i = 0; i < p_regions.size(); i++) {
  2319. TextureCopyRegion region = p_regions[i];
  2320. MTLSize extent = MTLSizeFromVector3i(region.size);
  2321. // If copies can be performed using direct texture-texture copying, do so.
  2322. uint32_t src_level = region.src_subresources.mipmap;
  2323. uint32_t src_base_layer = region.src_subresources.base_layer;
  2324. MTLSize src_extent = mipmapLevelSizeFromTexture(src, src_level);
  2325. uint32_t dst_level = region.dst_subresources.mipmap;
  2326. uint32_t dst_base_layer = region.dst_subresources.base_layer;
  2327. MTLSize dst_extent = mipmapLevelSizeFromTexture(dst, dst_level);
  2328. // All layers may be copied at once, if the extent completely covers both images.
  2329. if (src_extent == extent && dst_extent == extent) {
  2330. [blit copyFromTexture:src
  2331. sourceSlice:src_base_layer
  2332. sourceLevel:src_level
  2333. toTexture:dst
  2334. destinationSlice:dst_base_layer
  2335. destinationLevel:dst_level
  2336. sliceCount:region.src_subresources.layer_count
  2337. levelCount:1];
  2338. } else {
  2339. MTLOrigin src_origin = MTLOriginFromVector3i(region.src_offset);
  2340. MTLSize src_size = clampMTLSize(extent, src_origin, src_extent);
  2341. uint32_t layer_count = 0;
  2342. if ((src.textureType == MTLTextureType3D) != (dst.textureType == MTLTextureType3D)) {
  2343. // In the case, the number of layers to copy is in extent.depth. Use that value,
  2344. // then clamp the depth, so we don't try to copy more than Metal will allow.
  2345. layer_count = extent.depth;
  2346. src_size.depth = 1;
  2347. } else {
  2348. layer_count = region.src_subresources.layer_count;
  2349. }
  2350. MTLOrigin dst_origin = MTLOriginFromVector3i(region.dst_offset);
  2351. for (uint32_t layer = 0; layer < layer_count; layer++) {
  2352. // We can copy between a 3D and a 2D image easily. Just copy between
  2353. // one slice of the 2D image and one plane of the 3D image at a time.
  2354. if ((src.textureType == MTLTextureType3D) == (dst.textureType == MTLTextureType3D)) {
  2355. [blit copyFromTexture:src
  2356. sourceSlice:src_base_layer + layer
  2357. sourceLevel:src_level
  2358. sourceOrigin:src_origin
  2359. sourceSize:src_size
  2360. toTexture:dst
  2361. destinationSlice:dst_base_layer + layer
  2362. destinationLevel:dst_level
  2363. destinationOrigin:dst_origin];
  2364. } else if (src.textureType == MTLTextureType3D) {
  2365. [blit copyFromTexture:src
  2366. sourceSlice:src_base_layer
  2367. sourceLevel:src_level
  2368. sourceOrigin:MTLOriginMake(src_origin.x, src_origin.y, src_origin.z + layer)
  2369. sourceSize:src_size
  2370. toTexture:dst
  2371. destinationSlice:dst_base_layer + layer
  2372. destinationLevel:dst_level
  2373. destinationOrigin:dst_origin];
  2374. } else {
  2375. DEV_ASSERT(dst.textureType == MTLTextureType3D);
  2376. [blit copyFromTexture:src
  2377. sourceSlice:src_base_layer + layer
  2378. sourceLevel:src_level
  2379. sourceOrigin:src_origin
  2380. sourceSize:src_size
  2381. toTexture:dst
  2382. destinationSlice:dst_base_layer
  2383. destinationLevel:dst_level
  2384. destinationOrigin:MTLOriginMake(dst_origin.x, dst_origin.y, dst_origin.z + layer)];
  2385. }
  2386. }
  2387. }
  2388. }
  2389. }
  2390. 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) {
  2391. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2392. id<MTLTexture> src_tex = rid::get(p_src_texture);
  2393. id<MTLTexture> dst_tex = rid::get(p_dst_texture);
  2394. MTLRenderPassDescriptor *mtlRPD = [MTLRenderPassDescriptor renderPassDescriptor];
  2395. MTLRenderPassColorAttachmentDescriptor *mtlColorAttDesc = mtlRPD.colorAttachments[0];
  2396. mtlColorAttDesc.loadAction = MTLLoadActionLoad;
  2397. mtlColorAttDesc.storeAction = MTLStoreActionMultisampleResolve;
  2398. mtlColorAttDesc.texture = src_tex;
  2399. mtlColorAttDesc.resolveTexture = dst_tex;
  2400. mtlColorAttDesc.level = p_src_mipmap;
  2401. mtlColorAttDesc.slice = p_src_layer;
  2402. mtlColorAttDesc.resolveLevel = p_dst_mipmap;
  2403. mtlColorAttDesc.resolveSlice = p_dst_layer;
  2404. cb->encodeRenderCommandEncoderWithDescriptor(mtlRPD, @"Resolve Image");
  2405. }
  2406. 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) {
  2407. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2408. id<MTLTexture> src_tex = rid::get(p_texture);
  2409. if (src_tex.parentTexture) {
  2410. // Clear via the parent texture rather than the view.
  2411. src_tex = src_tex.parentTexture;
  2412. }
  2413. PixelFormats &pf = *pixel_formats;
  2414. if (pf.isDepthFormat(src_tex.pixelFormat) || pf.isStencilFormat(src_tex.pixelFormat)) {
  2415. ERR_FAIL_MSG("invalid: depth or stencil texture format");
  2416. }
  2417. MTLRenderPassDescriptor *desc = MTLRenderPassDescriptor.renderPassDescriptor;
  2418. if (p_subresources.aspect.has_flag(TEXTURE_ASPECT_COLOR_BIT)) {
  2419. MTLRenderPassColorAttachmentDescriptor *caDesc = desc.colorAttachments[0];
  2420. caDesc.texture = src_tex;
  2421. caDesc.loadAction = MTLLoadActionClear;
  2422. caDesc.storeAction = MTLStoreActionStore;
  2423. caDesc.clearColor = MTLClearColorMake(p_color.r, p_color.g, p_color.b, p_color.a);
  2424. // Extract the mipmap levels that are to be updated.
  2425. uint32_t mipLvlStart = p_subresources.base_mipmap;
  2426. uint32_t mipLvlCnt = p_subresources.mipmap_count;
  2427. uint32_t mipLvlEnd = mipLvlStart + mipLvlCnt;
  2428. uint32_t levelCount = src_tex.mipmapLevelCount;
  2429. // Extract the cube or array layers (slices) that are to be updated.
  2430. bool is3D = src_tex.textureType == MTLTextureType3D;
  2431. uint32_t layerStart = is3D ? 0 : p_subresources.base_layer;
  2432. uint32_t layerCnt = p_subresources.layer_count;
  2433. uint32_t layerEnd = layerStart + layerCnt;
  2434. MetalFeatures const &features = (*device_properties).features;
  2435. // Iterate across mipmap levels and layers, and perform and empty render to clear each.
  2436. for (uint32_t mipLvl = mipLvlStart; mipLvl < mipLvlEnd; mipLvl++) {
  2437. ERR_FAIL_INDEX_MSG(mipLvl, levelCount, "mip level out of range");
  2438. caDesc.level = mipLvl;
  2439. // If a 3D image, we need to get the depth for each level.
  2440. if (is3D) {
  2441. layerCnt = mipmapLevelSizeFromTexture(src_tex, mipLvl).depth;
  2442. layerEnd = layerStart + layerCnt;
  2443. }
  2444. if ((features.layeredRendering && src_tex.sampleCount == 1) || features.multisampleLayeredRendering) {
  2445. // We can clear all layers at once.
  2446. if (is3D) {
  2447. caDesc.depthPlane = layerStart;
  2448. } else {
  2449. caDesc.slice = layerStart;
  2450. }
  2451. desc.renderTargetArrayLength = layerCnt;
  2452. cb->encodeRenderCommandEncoderWithDescriptor(desc, @"Clear Image");
  2453. } else {
  2454. for (uint32_t layer = layerStart; layer < layerEnd; layer++) {
  2455. if (is3D) {
  2456. caDesc.depthPlane = layer;
  2457. } else {
  2458. caDesc.slice = layer;
  2459. }
  2460. cb->encodeRenderCommandEncoderWithDescriptor(desc, @"Clear Image");
  2461. }
  2462. }
  2463. }
  2464. }
  2465. }
  2466. API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0))
  2467. bool isArrayTexture(MTLTextureType p_type) {
  2468. return (p_type == MTLTextureType3D ||
  2469. p_type == MTLTextureType2DArray ||
  2470. p_type == MTLTextureType2DMultisampleArray ||
  2471. p_type == MTLTextureType1DArray);
  2472. }
  2473. void RenderingDeviceDriverMetal::_copy_texture_buffer(CommandBufferID p_cmd_buffer,
  2474. CopySource p_source,
  2475. TextureID p_texture,
  2476. BufferID p_buffer,
  2477. VectorView<BufferTextureCopyRegion> p_regions) {
  2478. MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
  2479. id<MTLBuffer> buffer = rid::get(p_buffer);
  2480. id<MTLTexture> texture = rid::get(p_texture);
  2481. id<MTLBlitCommandEncoder> enc = cmd->blit_command_encoder();
  2482. PixelFormats &pf = *pixel_formats;
  2483. MTLPixelFormat mtlPixFmt = texture.pixelFormat;
  2484. MTLBlitOption options = MTLBlitOptionNone;
  2485. if (pf.isPVRTCFormat(mtlPixFmt)) {
  2486. options |= MTLBlitOptionRowLinearPVRTC;
  2487. }
  2488. for (uint32_t i = 0; i < p_regions.size(); i++) {
  2489. BufferTextureCopyRegion region = p_regions[i];
  2490. uint32_t mip_level = region.texture_subresources.mipmap;
  2491. MTLOrigin txt_origin = MTLOriginMake(region.texture_offset.x, region.texture_offset.y, region.texture_offset.z);
  2492. MTLSize src_extent = mipmapLevelSizeFromTexture(texture, mip_level);
  2493. MTLSize txt_size = clampMTLSize(MTLSizeMake(region.texture_region_size.x, region.texture_region_size.y, region.texture_region_size.z),
  2494. txt_origin,
  2495. src_extent);
  2496. uint32_t buffImgWd = region.texture_region_size.x;
  2497. uint32_t buffImgHt = region.texture_region_size.y;
  2498. NSUInteger bytesPerRow = pf.getBytesPerRow(mtlPixFmt, buffImgWd);
  2499. NSUInteger bytesPerImg = pf.getBytesPerLayer(mtlPixFmt, bytesPerRow, buffImgHt);
  2500. MTLBlitOption blit_options = options;
  2501. if (pf.isDepthFormat(mtlPixFmt) && pf.isStencilFormat(mtlPixFmt)) {
  2502. bool want_depth = flags::all(region.texture_subresources.aspect, TEXTURE_ASPECT_DEPTH_BIT);
  2503. bool want_stencil = flags::all(region.texture_subresources.aspect, TEXTURE_ASPECT_STENCIL_BIT);
  2504. // The stencil component is always 1 byte per pixel.
  2505. // Don't reduce depths of 32-bit depth/stencil formats.
  2506. if (want_depth && !want_stencil) {
  2507. if (pf.getBytesPerTexel(mtlPixFmt) != 4) {
  2508. bytesPerRow -= buffImgWd;
  2509. bytesPerImg -= buffImgWd * buffImgHt;
  2510. }
  2511. blit_options |= MTLBlitOptionDepthFromDepthStencil;
  2512. } else if (want_stencil && !want_depth) {
  2513. bytesPerRow = buffImgWd;
  2514. bytesPerImg = buffImgWd * buffImgHt;
  2515. blit_options |= MTLBlitOptionStencilFromDepthStencil;
  2516. }
  2517. }
  2518. if (!isArrayTexture(texture.textureType)) {
  2519. bytesPerImg = 0;
  2520. }
  2521. if (p_source == CopySource::Buffer) {
  2522. for (uint32_t lyrIdx = 0; lyrIdx < region.texture_subresources.layer_count; lyrIdx++) {
  2523. [enc copyFromBuffer:buffer
  2524. sourceOffset:region.buffer_offset + (bytesPerImg * lyrIdx)
  2525. sourceBytesPerRow:bytesPerRow
  2526. sourceBytesPerImage:bytesPerImg
  2527. sourceSize:txt_size
  2528. toTexture:texture
  2529. destinationSlice:region.texture_subresources.base_layer + lyrIdx
  2530. destinationLevel:mip_level
  2531. destinationOrigin:txt_origin
  2532. options:blit_options];
  2533. }
  2534. } else {
  2535. for (uint32_t lyrIdx = 0; lyrIdx < region.texture_subresources.layer_count; lyrIdx++) {
  2536. [enc copyFromTexture:texture
  2537. sourceSlice:region.texture_subresources.base_layer + lyrIdx
  2538. sourceLevel:mip_level
  2539. sourceOrigin:txt_origin
  2540. sourceSize:txt_size
  2541. toBuffer:buffer
  2542. destinationOffset:region.buffer_offset + (bytesPerImg * lyrIdx)
  2543. destinationBytesPerRow:bytesPerRow
  2544. destinationBytesPerImage:bytesPerImg
  2545. options:blit_options];
  2546. }
  2547. }
  2548. }
  2549. }
  2550. 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) {
  2551. _copy_texture_buffer(p_cmd_buffer, CopySource::Buffer, p_dst_texture, p_src_buffer, p_regions);
  2552. }
  2553. 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) {
  2554. _copy_texture_buffer(p_cmd_buffer, CopySource::Texture, p_src_texture, p_dst_buffer, p_regions);
  2555. }
  2556. #pragma mark - Pipeline
  2557. void RenderingDeviceDriverMetal::pipeline_free(PipelineID p_pipeline_id) {
  2558. MDPipeline *obj = (MDPipeline *)(p_pipeline_id.id);
  2559. delete obj;
  2560. }
  2561. // ----- BINDING -----
  2562. void RenderingDeviceDriverMetal::command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_dst_first_index, VectorView<uint32_t> p_data) {
  2563. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2564. MDShader *shader = (MDShader *)(p_shader.id);
  2565. shader->encode_push_constant_data(p_data, cb);
  2566. }
  2567. // ----- CACHE -----
  2568. String RenderingDeviceDriverMetal::_pipeline_get_cache_path() const {
  2569. String path = OS::get_singleton()->get_user_data_dir() + "/metal/pipelines";
  2570. path += "." + context_device.name.validate_filename().replace(" ", "_").to_lower();
  2571. if (Engine::get_singleton()->is_editor_hint()) {
  2572. path += ".editor";
  2573. }
  2574. path += ".cache";
  2575. return path;
  2576. }
  2577. bool RenderingDeviceDriverMetal::pipeline_cache_create(const Vector<uint8_t> &p_data) {
  2578. return false;
  2579. CharString path = _pipeline_get_cache_path().utf8();
  2580. NSString *nPath = [[NSString alloc] initWithBytesNoCopy:path.ptrw()
  2581. length:path.length()
  2582. encoding:NSUTF8StringEncoding
  2583. freeWhenDone:NO];
  2584. MTLBinaryArchiveDescriptor *desc = [MTLBinaryArchiveDescriptor new];
  2585. if ([[NSFileManager defaultManager] fileExistsAtPath:nPath]) {
  2586. desc.url = [NSURL fileURLWithPath:nPath];
  2587. }
  2588. NSError *error = nil;
  2589. archive = [device newBinaryArchiveWithDescriptor:desc error:&error];
  2590. return true;
  2591. }
  2592. void RenderingDeviceDriverMetal::pipeline_cache_free() {
  2593. archive = nil;
  2594. }
  2595. size_t RenderingDeviceDriverMetal::pipeline_cache_query_size() {
  2596. return archive_count * 1024;
  2597. }
  2598. Vector<uint8_t> RenderingDeviceDriverMetal::pipeline_cache_serialize() {
  2599. if (!archive) {
  2600. return Vector<uint8_t>();
  2601. }
  2602. CharString path = _pipeline_get_cache_path().utf8();
  2603. NSString *nPath = [[NSString alloc] initWithBytesNoCopy:path.ptrw()
  2604. length:path.length()
  2605. encoding:NSUTF8StringEncoding
  2606. freeWhenDone:NO];
  2607. NSURL *target = [NSURL fileURLWithPath:nPath];
  2608. NSError *error = nil;
  2609. if ([archive serializeToURL:target error:&error]) {
  2610. return Vector<uint8_t>();
  2611. } else {
  2612. print_line(error.localizedDescription.UTF8String);
  2613. return Vector<uint8_t>();
  2614. }
  2615. }
  2616. #pragma mark - Rendering
  2617. // ----- SUBPASS -----
  2618. RDD::RenderPassID RenderingDeviceDriverMetal::render_pass_create(VectorView<Attachment> p_attachments, VectorView<Subpass> p_subpasses, VectorView<SubpassDependency> p_subpass_dependencies, uint32_t p_view_count) {
  2619. PixelFormats &pf = *pixel_formats;
  2620. size_t subpass_count = p_subpasses.size();
  2621. Vector<MDSubpass> subpasses;
  2622. subpasses.resize(subpass_count);
  2623. for (uint32_t i = 0; i < subpass_count; i++) {
  2624. MDSubpass &subpass = subpasses.write[i];
  2625. subpass.subpass_index = i;
  2626. subpass.view_count = p_view_count;
  2627. subpass.input_references = p_subpasses[i].input_references;
  2628. subpass.color_references = p_subpasses[i].color_references;
  2629. subpass.depth_stencil_reference = p_subpasses[i].depth_stencil_reference;
  2630. subpass.resolve_references = p_subpasses[i].resolve_references;
  2631. }
  2632. static const MTLLoadAction LOAD_ACTIONS[] = {
  2633. [ATTACHMENT_LOAD_OP_LOAD] = MTLLoadActionLoad,
  2634. [ATTACHMENT_LOAD_OP_CLEAR] = MTLLoadActionClear,
  2635. [ATTACHMENT_LOAD_OP_DONT_CARE] = MTLLoadActionDontCare,
  2636. };
  2637. static const MTLStoreAction STORE_ACTIONS[] = {
  2638. [ATTACHMENT_STORE_OP_STORE] = MTLStoreActionStore,
  2639. [ATTACHMENT_STORE_OP_DONT_CARE] = MTLStoreActionDontCare,
  2640. };
  2641. Vector<MDAttachment> attachments;
  2642. attachments.resize(p_attachments.size());
  2643. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  2644. Attachment const &a = p_attachments[i];
  2645. MDAttachment &mda = attachments.write[i];
  2646. MTLPixelFormat format = pf.getMTLPixelFormat(a.format);
  2647. mda.format = format;
  2648. if (a.samples > TEXTURE_SAMPLES_1) {
  2649. mda.samples = (*device_properties).find_nearest_supported_sample_count(a.samples);
  2650. }
  2651. mda.loadAction = LOAD_ACTIONS[a.load_op];
  2652. mda.storeAction = STORE_ACTIONS[a.store_op];
  2653. bool is_depth = pf.isDepthFormat(format);
  2654. if (is_depth) {
  2655. mda.type |= MDAttachmentType::Depth;
  2656. }
  2657. bool is_stencil = pf.isStencilFormat(format);
  2658. if (is_stencil) {
  2659. mda.type |= MDAttachmentType::Stencil;
  2660. mda.stencilLoadAction = LOAD_ACTIONS[a.stencil_load_op];
  2661. mda.stencilStoreAction = STORE_ACTIONS[a.stencil_store_op];
  2662. }
  2663. if (!is_depth && !is_stencil) {
  2664. mda.type |= MDAttachmentType::Color;
  2665. }
  2666. }
  2667. MDRenderPass *obj = new MDRenderPass(attachments, subpasses);
  2668. return RenderPassID(obj);
  2669. }
  2670. void RenderingDeviceDriverMetal::render_pass_free(RenderPassID p_render_pass) {
  2671. MDRenderPass *obj = (MDRenderPass *)(p_render_pass.id);
  2672. delete obj;
  2673. }
  2674. // ----- COMMANDS -----
  2675. 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) {
  2676. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2677. cb->render_begin_pass(p_render_pass, p_framebuffer, p_cmd_buffer_type, p_rect, p_clear_values);
  2678. }
  2679. void RenderingDeviceDriverMetal::command_end_render_pass(CommandBufferID p_cmd_buffer) {
  2680. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2681. cb->render_end_pass();
  2682. }
  2683. void RenderingDeviceDriverMetal::command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) {
  2684. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2685. cb->render_next_subpass();
  2686. }
  2687. void RenderingDeviceDriverMetal::command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) {
  2688. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2689. cb->render_set_viewport(p_viewports);
  2690. }
  2691. void RenderingDeviceDriverMetal::command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) {
  2692. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2693. cb->render_set_scissor(p_scissors);
  2694. }
  2695. void RenderingDeviceDriverMetal::command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) {
  2696. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2697. cb->render_clear_attachments(p_attachment_clears, p_rects);
  2698. }
  2699. void RenderingDeviceDriverMetal::command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
  2700. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2701. cb->bind_pipeline(p_pipeline);
  2702. }
  2703. void RenderingDeviceDriverMetal::command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  2704. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2705. cb->render_bind_uniform_set(p_uniform_set, p_shader, p_set_index);
  2706. }
  2707. 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) {
  2708. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2709. cb->render_bind_uniform_sets(p_uniform_sets, p_shader, p_first_set_index, p_set_count);
  2710. }
  2711. 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) {
  2712. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2713. cb->render_draw(p_vertex_count, p_instance_count, p_base_vertex, p_first_instance);
  2714. }
  2715. 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) {
  2716. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2717. cb->render_draw_indexed(p_index_count, p_instance_count, p_first_index, p_vertex_offset, p_first_instance);
  2718. }
  2719. 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) {
  2720. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2721. cb->render_draw_indexed_indirect(p_indirect_buffer, p_offset, p_draw_count, p_stride);
  2722. }
  2723. 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) {
  2724. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2725. cb->render_draw_indexed_indirect_count(p_indirect_buffer, p_offset, p_count_buffer, p_count_buffer_offset, p_max_draw_count, p_stride);
  2726. }
  2727. 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) {
  2728. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2729. cb->render_draw_indirect(p_indirect_buffer, p_offset, p_draw_count, p_stride);
  2730. }
  2731. 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) {
  2732. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2733. cb->render_draw_indirect_count(p_indirect_buffer, p_offset, p_count_buffer, p_count_buffer_offset, p_max_draw_count, p_stride);
  2734. }
  2735. 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) {
  2736. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2737. cb->render_bind_vertex_buffers(p_binding_count, p_buffers, p_offsets);
  2738. }
  2739. void RenderingDeviceDriverMetal::command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) {
  2740. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2741. cb->render_bind_index_buffer(p_buffer, p_format, p_offset);
  2742. }
  2743. void RenderingDeviceDriverMetal::command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) {
  2744. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  2745. cb->render_set_blend_constants(p_constants);
  2746. }
  2747. void RenderingDeviceDriverMetal::command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) {
  2748. if (!Math::is_equal_approx(p_width, 1.0f)) {
  2749. ERR_FAIL_MSG("Setting line widths other than 1.0 is not supported by the Metal rendering driver.");
  2750. }
  2751. }
  2752. // ----- PIPELINE -----
  2753. RenderingDeviceDriverMetal::Result<id<MTLFunction>> RenderingDeviceDriverMetal::_create_function(MDLibrary *p_library, NSString *p_name, VectorView<PipelineSpecializationConstant> &p_specialization_constants) {
  2754. id<MTLLibrary> library = p_library.library;
  2755. if (!library) {
  2756. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Failed to compile Metal library");
  2757. }
  2758. id<MTLFunction> function = [library newFunctionWithName:p_name];
  2759. ERR_FAIL_NULL_V_MSG(function, ERR_CANT_CREATE, "No function named main0");
  2760. if (function.functionConstantsDictionary.count == 0) {
  2761. return function;
  2762. }
  2763. NSArray<MTLFunctionConstant *> *constants = function.functionConstantsDictionary.allValues;
  2764. bool is_sorted = true;
  2765. for (uint32_t i = 1; i < constants.count; i++) {
  2766. if (constants[i - 1].index > constants[i].index) {
  2767. is_sorted = false;
  2768. break;
  2769. }
  2770. }
  2771. if (!is_sorted) {
  2772. constants = [constants sortedArrayUsingComparator:^NSComparisonResult(MTLFunctionConstant *a, MTLFunctionConstant *b) {
  2773. if (a.index < b.index) {
  2774. return NSOrderedAscending;
  2775. } else if (a.index > b.index) {
  2776. return NSOrderedDescending;
  2777. } else {
  2778. return NSOrderedSame;
  2779. }
  2780. }];
  2781. }
  2782. // Initialize an array of integers representing the indexes of p_specialization_constants
  2783. uint32_t *indexes = (uint32_t *)alloca(p_specialization_constants.size() * sizeof(uint32_t));
  2784. for (uint32_t i = 0; i < p_specialization_constants.size(); i++) {
  2785. indexes[i] = i;
  2786. }
  2787. // Sort the array of integers based on the values in p_specialization_constants
  2788. std::sort(indexes, &indexes[p_specialization_constants.size()], [&](int a, int b) {
  2789. return p_specialization_constants[a].constant_id < p_specialization_constants[b].constant_id;
  2790. });
  2791. MTLFunctionConstantValues *constantValues = [MTLFunctionConstantValues new];
  2792. uint32_t i = 0;
  2793. uint32_t j = 0;
  2794. while (i < constants.count && j < p_specialization_constants.size()) {
  2795. MTLFunctionConstant *curr = constants[i];
  2796. PipelineSpecializationConstant const &sc = p_specialization_constants[indexes[j]];
  2797. if (curr.index == sc.constant_id) {
  2798. switch (curr.type) {
  2799. case MTLDataTypeBool:
  2800. case MTLDataTypeFloat:
  2801. case MTLDataTypeInt:
  2802. case MTLDataTypeUInt: {
  2803. [constantValues setConstantValue:&sc.int_value
  2804. type:curr.type
  2805. atIndex:sc.constant_id];
  2806. } break;
  2807. default:
  2808. ERR_FAIL_V_MSG(function, "Invalid specialization constant type");
  2809. }
  2810. i++;
  2811. j++;
  2812. } else if (curr.index < sc.constant_id) {
  2813. i++;
  2814. } else {
  2815. j++;
  2816. }
  2817. }
  2818. if (i != constants.count) {
  2819. MTLFunctionConstant *curr = constants[i];
  2820. if (curr.index == R32UI_ALIGNMENT_CONSTANT_ID) {
  2821. uint32_t alignment = 16; // TODO(sgc): is this always correct?
  2822. [constantValues setConstantValue:&alignment
  2823. type:curr.type
  2824. atIndex:curr.index];
  2825. i++;
  2826. }
  2827. }
  2828. NSError *err = nil;
  2829. function = [library newFunctionWithName:@"main0"
  2830. constantValues:constantValues
  2831. error:&err];
  2832. ERR_FAIL_NULL_V_MSG(function, ERR_CANT_CREATE, String("specialized function failed: ") + err.localizedDescription.UTF8String);
  2833. return function;
  2834. }
  2835. // RDD::PolygonCullMode == MTLCullMode.
  2836. static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_DISABLED, MTLCullModeNone));
  2837. static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_FRONT, MTLCullModeFront));
  2838. static_assert(ENUM_MEMBERS_EQUAL(RDD::POLYGON_CULL_BACK, MTLCullModeBack));
  2839. // RDD::StencilOperation == MTLStencilOperation.
  2840. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_KEEP, MTLStencilOperationKeep));
  2841. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_ZERO, MTLStencilOperationZero));
  2842. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_REPLACE, MTLStencilOperationReplace));
  2843. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INCREMENT_AND_CLAMP, MTLStencilOperationIncrementClamp));
  2844. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_DECREMENT_AND_CLAMP, MTLStencilOperationDecrementClamp));
  2845. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INVERT, MTLStencilOperationInvert));
  2846. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_INCREMENT_AND_WRAP, MTLStencilOperationIncrementWrap));
  2847. static_assert(ENUM_MEMBERS_EQUAL(RDD::STENCIL_OP_DECREMENT_AND_WRAP, MTLStencilOperationDecrementWrap));
  2848. // RDD::BlendOperation == MTLBlendOperation.
  2849. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_ADD, MTLBlendOperationAdd));
  2850. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_SUBTRACT, MTLBlendOperationSubtract));
  2851. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_REVERSE_SUBTRACT, MTLBlendOperationReverseSubtract));
  2852. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_MINIMUM, MTLBlendOperationMin));
  2853. static_assert(ENUM_MEMBERS_EQUAL(RDD::BLEND_OP_MAXIMUM, MTLBlendOperationMax));
  2854. RDD::PipelineID RenderingDeviceDriverMetal::render_pipeline_create(
  2855. ShaderID p_shader,
  2856. VertexFormatID p_vertex_format,
  2857. RenderPrimitive p_render_primitive,
  2858. PipelineRasterizationState p_rasterization_state,
  2859. PipelineMultisampleState p_multisample_state,
  2860. PipelineDepthStencilState p_depth_stencil_state,
  2861. PipelineColorBlendState p_blend_state,
  2862. VectorView<int32_t> p_color_attachments,
  2863. BitField<PipelineDynamicStateFlags> p_dynamic_state,
  2864. RenderPassID p_render_pass,
  2865. uint32_t p_render_subpass,
  2866. VectorView<PipelineSpecializationConstant> p_specialization_constants) {
  2867. MDRenderShader *shader = (MDRenderShader *)(p_shader.id);
  2868. MTLVertexDescriptor *vert_desc = rid::get(p_vertex_format);
  2869. MDRenderPass *pass = (MDRenderPass *)(p_render_pass.id);
  2870. os_signpost_id_t reflect_id = os_signpost_id_make_with_pointer(LOG_INTERVALS, shader);
  2871. os_signpost_interval_begin(LOG_INTERVALS, reflect_id, "render_pipeline_create", "shader_name=%{public}s", shader->name.get_data());
  2872. DEFER([=]() {
  2873. os_signpost_interval_end(LOG_INTERVALS, reflect_id, "render_pipeline_create");
  2874. });
  2875. os_signpost_event_emit(LOG_DRIVER, OS_SIGNPOST_ID_EXCLUSIVE, "create_pipeline");
  2876. MTLRenderPipelineDescriptor *desc = [MTLRenderPipelineDescriptor new];
  2877. {
  2878. MDSubpass const &subpass = pass->subpasses[p_render_subpass];
  2879. for (uint32_t i = 0; i < subpass.color_references.size(); i++) {
  2880. uint32_t attachment = subpass.color_references[i].attachment;
  2881. if (attachment != AttachmentReference::UNUSED) {
  2882. MDAttachment const &a = pass->attachments[attachment];
  2883. desc.colorAttachments[i].pixelFormat = a.format;
  2884. }
  2885. }
  2886. if (subpass.depth_stencil_reference.attachment != AttachmentReference::UNUSED) {
  2887. uint32_t attachment = subpass.depth_stencil_reference.attachment;
  2888. MDAttachment const &a = pass->attachments[attachment];
  2889. if (a.type & MDAttachmentType::Depth) {
  2890. desc.depthAttachmentPixelFormat = a.format;
  2891. }
  2892. if (a.type & MDAttachmentType::Stencil) {
  2893. desc.stencilAttachmentPixelFormat = a.format;
  2894. }
  2895. }
  2896. }
  2897. desc.vertexDescriptor = vert_desc;
  2898. desc.label = [NSString stringWithUTF8String:shader->name.get_data()];
  2899. // Input assembly & tessellation.
  2900. MDRenderPipeline *pipeline = new MDRenderPipeline();
  2901. switch (p_render_primitive) {
  2902. case RENDER_PRIMITIVE_POINTS:
  2903. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassPoint;
  2904. break;
  2905. case RENDER_PRIMITIVE_LINES:
  2906. case RENDER_PRIMITIVE_LINES_WITH_ADJACENCY:
  2907. case RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY:
  2908. case RENDER_PRIMITIVE_LINESTRIPS:
  2909. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassLine;
  2910. break;
  2911. case RENDER_PRIMITIVE_TRIANGLES:
  2912. case RENDER_PRIMITIVE_TRIANGLE_STRIPS:
  2913. case RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY:
  2914. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY:
  2915. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX:
  2916. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassTriangle;
  2917. break;
  2918. case RENDER_PRIMITIVE_TESSELATION_PATCH:
  2919. desc.maxTessellationFactor = p_rasterization_state.patch_control_points;
  2920. desc.tessellationPartitionMode = MTLTessellationPartitionModeInteger;
  2921. ERR_FAIL_V_MSG(PipelineID(), "tessellation not implemented");
  2922. break;
  2923. case RENDER_PRIMITIVE_MAX:
  2924. default:
  2925. desc.inputPrimitiveTopology = MTLPrimitiveTopologyClassUnspecified;
  2926. break;
  2927. }
  2928. switch (p_render_primitive) {
  2929. case RENDER_PRIMITIVE_POINTS:
  2930. pipeline->raster_state.render_primitive = MTLPrimitiveTypePoint;
  2931. break;
  2932. case RENDER_PRIMITIVE_LINES:
  2933. case RENDER_PRIMITIVE_LINES_WITH_ADJACENCY:
  2934. pipeline->raster_state.render_primitive = MTLPrimitiveTypeLine;
  2935. break;
  2936. case RENDER_PRIMITIVE_LINESTRIPS:
  2937. case RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY:
  2938. pipeline->raster_state.render_primitive = MTLPrimitiveTypeLineStrip;
  2939. break;
  2940. case RENDER_PRIMITIVE_TRIANGLES:
  2941. case RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY:
  2942. pipeline->raster_state.render_primitive = MTLPrimitiveTypeTriangle;
  2943. break;
  2944. case RENDER_PRIMITIVE_TRIANGLE_STRIPS:
  2945. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY:
  2946. case RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX:
  2947. pipeline->raster_state.render_primitive = MTLPrimitiveTypeTriangleStrip;
  2948. break;
  2949. default:
  2950. break;
  2951. }
  2952. // Rasterization.
  2953. desc.rasterizationEnabled = !p_rasterization_state.discard_primitives;
  2954. pipeline->raster_state.clip_mode = p_rasterization_state.enable_depth_clamp ? MTLDepthClipModeClamp : MTLDepthClipModeClip;
  2955. pipeline->raster_state.fill_mode = p_rasterization_state.wireframe ? MTLTriangleFillModeLines : MTLTriangleFillModeFill;
  2956. static const MTLCullMode CULL_MODE[3] = {
  2957. MTLCullModeNone,
  2958. MTLCullModeFront,
  2959. MTLCullModeBack,
  2960. };
  2961. pipeline->raster_state.cull_mode = CULL_MODE[p_rasterization_state.cull_mode];
  2962. pipeline->raster_state.winding = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE) ? MTLWindingClockwise : MTLWindingCounterClockwise;
  2963. pipeline->raster_state.depth_bias.enabled = p_rasterization_state.depth_bias_enabled;
  2964. pipeline->raster_state.depth_bias.depth_bias = p_rasterization_state.depth_bias_constant_factor;
  2965. pipeline->raster_state.depth_bias.slope_scale = p_rasterization_state.depth_bias_slope_factor;
  2966. pipeline->raster_state.depth_bias.clamp = p_rasterization_state.depth_bias_clamp;
  2967. // In Metal there is no line width.
  2968. if (!Math::is_equal_approx(p_rasterization_state.line_width, 1.0f)) {
  2969. WARN_PRINT("unsupported: line width");
  2970. }
  2971. // Multisample.
  2972. if (p_multisample_state.enable_sample_shading) {
  2973. WARN_PRINT("unsupported: multi-sample shading");
  2974. }
  2975. if (p_multisample_state.sample_count > TEXTURE_SAMPLES_1) {
  2976. pipeline->sample_count = (*device_properties).find_nearest_supported_sample_count(p_multisample_state.sample_count);
  2977. }
  2978. desc.rasterSampleCount = static_cast<NSUInteger>(pipeline->sample_count);
  2979. desc.alphaToCoverageEnabled = p_multisample_state.enable_alpha_to_coverage;
  2980. desc.alphaToOneEnabled = p_multisample_state.enable_alpha_to_one;
  2981. // Depth stencil.
  2982. if (p_depth_stencil_state.enable_depth_test && desc.depthAttachmentPixelFormat != MTLPixelFormatInvalid) {
  2983. pipeline->raster_state.depth_test.enabled = true;
  2984. MTLDepthStencilDescriptor *ds_desc = [MTLDepthStencilDescriptor new];
  2985. ds_desc.depthWriteEnabled = p_depth_stencil_state.enable_depth_write;
  2986. ds_desc.depthCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.depth_compare_operator];
  2987. if (p_depth_stencil_state.enable_depth_range) {
  2988. WARN_PRINT("unsupported: depth range");
  2989. }
  2990. if (p_depth_stencil_state.enable_stencil) {
  2991. pipeline->raster_state.stencil.front_reference = p_depth_stencil_state.front_op.reference;
  2992. pipeline->raster_state.stencil.back_reference = p_depth_stencil_state.back_op.reference;
  2993. {
  2994. // Front.
  2995. MTLStencilDescriptor *sd = [MTLStencilDescriptor new];
  2996. sd.stencilFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.fail];
  2997. sd.depthStencilPassOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.pass];
  2998. sd.depthFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.front_op.depth_fail];
  2999. sd.stencilCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.front_op.compare];
  3000. sd.readMask = p_depth_stencil_state.front_op.compare_mask;
  3001. sd.writeMask = p_depth_stencil_state.front_op.write_mask;
  3002. ds_desc.frontFaceStencil = sd;
  3003. }
  3004. {
  3005. // Back.
  3006. MTLStencilDescriptor *sd = [MTLStencilDescriptor new];
  3007. sd.stencilFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.fail];
  3008. sd.depthStencilPassOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.pass];
  3009. sd.depthFailureOperation = STENCIL_OPERATIONS[p_depth_stencil_state.back_op.depth_fail];
  3010. sd.stencilCompareFunction = COMPARE_OPERATORS[p_depth_stencil_state.back_op.compare];
  3011. sd.readMask = p_depth_stencil_state.back_op.compare_mask;
  3012. sd.writeMask = p_depth_stencil_state.back_op.write_mask;
  3013. ds_desc.backFaceStencil = sd;
  3014. }
  3015. }
  3016. pipeline->depth_stencil = [device newDepthStencilStateWithDescriptor:ds_desc];
  3017. ERR_FAIL_NULL_V_MSG(pipeline->depth_stencil, PipelineID(), "Failed to create depth stencil state");
  3018. } else {
  3019. // TODO(sgc): FB13671991 raised as Apple docs state calling setDepthStencilState:nil is valid, but currently generates an exception
  3020. pipeline->depth_stencil = get_resource_cache().get_depth_stencil_state(false, false);
  3021. }
  3022. // Blend state.
  3023. {
  3024. for (uint32_t i = 0; i < p_color_attachments.size(); i++) {
  3025. if (p_color_attachments[i] == ATTACHMENT_UNUSED) {
  3026. continue;
  3027. }
  3028. const PipelineColorBlendState::Attachment &bs = p_blend_state.attachments[i];
  3029. MTLRenderPipelineColorAttachmentDescriptor *ca_desc = desc.colorAttachments[p_color_attachments[i]];
  3030. ca_desc.blendingEnabled = bs.enable_blend;
  3031. ca_desc.sourceRGBBlendFactor = BLEND_FACTORS[bs.src_color_blend_factor];
  3032. ca_desc.destinationRGBBlendFactor = BLEND_FACTORS[bs.dst_color_blend_factor];
  3033. ca_desc.rgbBlendOperation = BLEND_OPERATIONS[bs.color_blend_op];
  3034. ca_desc.sourceAlphaBlendFactor = BLEND_FACTORS[bs.src_alpha_blend_factor];
  3035. ca_desc.destinationAlphaBlendFactor = BLEND_FACTORS[bs.dst_alpha_blend_factor];
  3036. ca_desc.alphaBlendOperation = BLEND_OPERATIONS[bs.alpha_blend_op];
  3037. ca_desc.writeMask = MTLColorWriteMaskNone;
  3038. if (bs.write_r) {
  3039. ca_desc.writeMask |= MTLColorWriteMaskRed;
  3040. }
  3041. if (bs.write_g) {
  3042. ca_desc.writeMask |= MTLColorWriteMaskGreen;
  3043. }
  3044. if (bs.write_b) {
  3045. ca_desc.writeMask |= MTLColorWriteMaskBlue;
  3046. }
  3047. if (bs.write_a) {
  3048. ca_desc.writeMask |= MTLColorWriteMaskAlpha;
  3049. }
  3050. }
  3051. pipeline->raster_state.blend.r = p_blend_state.blend_constant.r;
  3052. pipeline->raster_state.blend.g = p_blend_state.blend_constant.g;
  3053. pipeline->raster_state.blend.b = p_blend_state.blend_constant.b;
  3054. pipeline->raster_state.blend.a = p_blend_state.blend_constant.a;
  3055. }
  3056. // Dynamic state.
  3057. if (p_dynamic_state.has_flag(DYNAMIC_STATE_DEPTH_BIAS)) {
  3058. pipeline->raster_state.depth_bias.enabled = true;
  3059. }
  3060. if (p_dynamic_state.has_flag(DYNAMIC_STATE_BLEND_CONSTANTS)) {
  3061. pipeline->raster_state.blend.enabled = true;
  3062. }
  3063. if (p_dynamic_state.has_flag(DYNAMIC_STATE_DEPTH_BOUNDS)) {
  3064. // TODO(sgc): ??
  3065. }
  3066. if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_COMPARE_MASK)) {
  3067. // TODO(sgc): ??
  3068. }
  3069. if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_WRITE_MASK)) {
  3070. // TODO(sgc): ??
  3071. }
  3072. if (p_dynamic_state.has_flag(DYNAMIC_STATE_STENCIL_REFERENCE)) {
  3073. pipeline->raster_state.stencil.enabled = true;
  3074. }
  3075. if (shader->vert != nil) {
  3076. Result<id<MTLFunction>> function_or_err = _create_function(shader->vert, @"main0", p_specialization_constants);
  3077. ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
  3078. desc.vertexFunction = std::get<id<MTLFunction>>(function_or_err);
  3079. }
  3080. if (shader->frag != nil) {
  3081. Result<id<MTLFunction>> function_or_err = _create_function(shader->frag, @"main0", p_specialization_constants);
  3082. ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
  3083. desc.fragmentFunction = std::get<id<MTLFunction>>(function_or_err);
  3084. }
  3085. if (archive) {
  3086. desc.binaryArchives = @[ archive ];
  3087. }
  3088. NSError *error = nil;
  3089. pipeline->state = [device newRenderPipelineStateWithDescriptor:desc
  3090. error:&error];
  3091. pipeline->shader = shader;
  3092. ERR_FAIL_COND_V_MSG(error != nil, PipelineID(), ([NSString stringWithFormat:@"error creating pipeline: %@", error.localizedDescription].UTF8String));
  3093. if (archive) {
  3094. if ([archive addRenderPipelineFunctionsWithDescriptor:desc error:&error]) {
  3095. archive_count += 1;
  3096. } else {
  3097. print_error(error.localizedDescription.UTF8String);
  3098. }
  3099. }
  3100. return PipelineID(pipeline);
  3101. }
  3102. #pragma mark - Compute
  3103. // ----- COMMANDS -----
  3104. void RenderingDeviceDriverMetal::command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
  3105. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3106. cb->bind_pipeline(p_pipeline);
  3107. }
  3108. void RenderingDeviceDriverMetal::command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  3109. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3110. cb->compute_bind_uniform_set(p_uniform_set, p_shader, p_set_index);
  3111. }
  3112. 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) {
  3113. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3114. cb->compute_bind_uniform_sets(p_uniform_sets, p_shader, p_first_set_index, p_set_count);
  3115. }
  3116. void RenderingDeviceDriverMetal::command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  3117. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3118. cb->compute_dispatch(p_x_groups, p_y_groups, p_z_groups);
  3119. }
  3120. void RenderingDeviceDriverMetal::command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) {
  3121. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3122. cb->compute_dispatch_indirect(p_indirect_buffer, p_offset);
  3123. }
  3124. // ----- PIPELINE -----
  3125. RDD::PipelineID RenderingDeviceDriverMetal::compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) {
  3126. MDComputeShader *shader = (MDComputeShader *)(p_shader.id);
  3127. os_signpost_id_t reflect_id = os_signpost_id_make_with_pointer(LOG_INTERVALS, shader);
  3128. os_signpost_interval_begin(LOG_INTERVALS, reflect_id, "compute_pipeline_create", "shader_name=%{public}s", shader->name.get_data());
  3129. DEFER([=]() {
  3130. os_signpost_interval_end(LOG_INTERVALS, reflect_id, "compute_pipeline_create");
  3131. });
  3132. os_signpost_event_emit(LOG_DRIVER, OS_SIGNPOST_ID_EXCLUSIVE, "create_pipeline");
  3133. Result<id<MTLFunction>> function_or_err = _create_function(shader->kernel, @"main0", p_specialization_constants);
  3134. ERR_FAIL_COND_V(std::holds_alternative<Error>(function_or_err), PipelineID());
  3135. id<MTLFunction> function = std::get<id<MTLFunction>>(function_or_err);
  3136. MTLComputePipelineDescriptor *desc = [MTLComputePipelineDescriptor new];
  3137. desc.computeFunction = function;
  3138. if (archive) {
  3139. desc.binaryArchives = @[ archive ];
  3140. }
  3141. NSError *error;
  3142. id<MTLComputePipelineState> state = [device newComputePipelineStateWithDescriptor:desc
  3143. options:MTLPipelineOptionNone
  3144. reflection:nil
  3145. error:&error];
  3146. ERR_FAIL_COND_V_MSG(error != nil, PipelineID(), ([NSString stringWithFormat:@"error creating pipeline: %@", error.localizedDescription].UTF8String));
  3147. MDComputePipeline *pipeline = new MDComputePipeline(state);
  3148. pipeline->compute_state.local = shader->local;
  3149. pipeline->shader = shader;
  3150. if (archive) {
  3151. if ([archive addComputePipelineFunctionsWithDescriptor:desc error:&error]) {
  3152. archive_count += 1;
  3153. } else {
  3154. print_error(error.localizedDescription.UTF8String);
  3155. }
  3156. }
  3157. return PipelineID(pipeline);
  3158. }
  3159. #pragma mark - Queries
  3160. // ----- TIMESTAMP -----
  3161. RDD::QueryPoolID RenderingDeviceDriverMetal::timestamp_query_pool_create(uint32_t p_query_count) {
  3162. return QueryPoolID(1);
  3163. }
  3164. void RenderingDeviceDriverMetal::timestamp_query_pool_free(QueryPoolID p_pool_id) {
  3165. }
  3166. void RenderingDeviceDriverMetal::timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) {
  3167. // Metal doesn't support timestamp queries, so we just clear the buffer.
  3168. bzero(r_results, p_query_count * sizeof(uint64_t));
  3169. }
  3170. uint64_t RenderingDeviceDriverMetal::timestamp_query_result_to_time(uint64_t p_result) {
  3171. return p_result;
  3172. }
  3173. void RenderingDeviceDriverMetal::command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) {
  3174. }
  3175. void RenderingDeviceDriverMetal::command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) {
  3176. }
  3177. #pragma mark - Labels
  3178. void RenderingDeviceDriverMetal::command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) {
  3179. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3180. NSString *s = [[NSString alloc] initWithBytesNoCopy:(void *)p_label_name length:strlen(p_label_name) encoding:NSUTF8StringEncoding freeWhenDone:NO];
  3181. [cb->get_command_buffer() pushDebugGroup:s];
  3182. }
  3183. void RenderingDeviceDriverMetal::command_end_label(CommandBufferID p_cmd_buffer) {
  3184. MDCommandBuffer *cb = (MDCommandBuffer *)(p_cmd_buffer.id);
  3185. [cb->get_command_buffer() popDebugGroup];
  3186. }
  3187. #pragma mark - Debug
  3188. void RenderingDeviceDriverMetal::command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) {
  3189. // TODO: Implement.
  3190. }
  3191. #pragma mark - Submission
  3192. void RenderingDeviceDriverMetal::begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) {
  3193. }
  3194. void RenderingDeviceDriverMetal::end_segment() {
  3195. }
  3196. #pragma mark - Misc
  3197. void RenderingDeviceDriverMetal::set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) {
  3198. switch (p_type) {
  3199. case OBJECT_TYPE_TEXTURE: {
  3200. id<MTLTexture> tex = rid::get(p_driver_id);
  3201. tex.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  3202. } break;
  3203. case OBJECT_TYPE_SAMPLER: {
  3204. // Can't set label after creation.
  3205. } break;
  3206. case OBJECT_TYPE_BUFFER: {
  3207. id<MTLBuffer> buffer = rid::get(p_driver_id);
  3208. buffer.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  3209. } break;
  3210. case OBJECT_TYPE_SHADER: {
  3211. NSString *label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  3212. MDShader *shader = (MDShader *)(p_driver_id.id);
  3213. if (MDRenderShader *rs = dynamic_cast<MDRenderShader *>(shader); rs != nullptr) {
  3214. [rs->vert setLabel:label];
  3215. [rs->frag setLabel:label];
  3216. } else if (MDComputeShader *cs = dynamic_cast<MDComputeShader *>(shader); cs != nullptr) {
  3217. [cs->kernel setLabel:label];
  3218. } else {
  3219. DEV_ASSERT(false);
  3220. }
  3221. } break;
  3222. case OBJECT_TYPE_UNIFORM_SET: {
  3223. MDUniformSet *set = (MDUniformSet *)(p_driver_id.id);
  3224. for (KeyValue<MDShader *, BoundUniformSet> &keyval : set->bound_uniforms) {
  3225. keyval.value.buffer.label = [NSString stringWithUTF8String:p_name.utf8().get_data()];
  3226. }
  3227. } break;
  3228. case OBJECT_TYPE_PIPELINE: {
  3229. // Can't set label after creation.
  3230. } break;
  3231. default: {
  3232. DEV_ASSERT(false);
  3233. }
  3234. }
  3235. }
  3236. uint64_t RenderingDeviceDriverMetal::get_resource_native_handle(DriverResource p_type, ID p_driver_id) {
  3237. switch (p_type) {
  3238. case DRIVER_RESOURCE_LOGICAL_DEVICE: {
  3239. return (uint64_t)(uintptr_t)(__bridge void *)device;
  3240. }
  3241. case DRIVER_RESOURCE_PHYSICAL_DEVICE: {
  3242. return 0;
  3243. }
  3244. case DRIVER_RESOURCE_TOPMOST_OBJECT: {
  3245. return 0;
  3246. }
  3247. case DRIVER_RESOURCE_COMMAND_QUEUE: {
  3248. return (uint64_t)(uintptr_t)(__bridge void *)device_queue;
  3249. }
  3250. case DRIVER_RESOURCE_QUEUE_FAMILY: {
  3251. return 0;
  3252. }
  3253. case DRIVER_RESOURCE_TEXTURE: {
  3254. return p_driver_id.id;
  3255. }
  3256. case DRIVER_RESOURCE_TEXTURE_VIEW: {
  3257. return p_driver_id.id;
  3258. }
  3259. case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: {
  3260. return 0;
  3261. }
  3262. case DRIVER_RESOURCE_SAMPLER: {
  3263. return p_driver_id.id;
  3264. }
  3265. case DRIVER_RESOURCE_UNIFORM_SET: {
  3266. return 0;
  3267. }
  3268. case DRIVER_RESOURCE_BUFFER: {
  3269. return p_driver_id.id;
  3270. }
  3271. case DRIVER_RESOURCE_COMPUTE_PIPELINE: {
  3272. MDComputePipeline *pipeline = (MDComputePipeline *)(p_driver_id.id);
  3273. return (uint64_t)(uintptr_t)(__bridge void *)pipeline->state;
  3274. }
  3275. case DRIVER_RESOURCE_RENDER_PIPELINE: {
  3276. MDRenderPipeline *pipeline = (MDRenderPipeline *)(p_driver_id.id);
  3277. return (uint64_t)(uintptr_t)(__bridge void *)pipeline->state;
  3278. }
  3279. default: {
  3280. return 0;
  3281. }
  3282. }
  3283. }
  3284. uint64_t RenderingDeviceDriverMetal::get_total_memory_used() {
  3285. return device.currentAllocatedSize;
  3286. }
  3287. uint64_t RenderingDeviceDriverMetal::get_lazily_memory_used() {
  3288. return 0; // TODO: Track this (grep for memoryless in Godot's Metal backend).
  3289. }
  3290. uint64_t RenderingDeviceDriverMetal::limit_get(Limit p_limit) {
  3291. MetalDeviceProperties const &props = (*device_properties);
  3292. MetalLimits const &limits = props.limits;
  3293. #if defined(DEV_ENABLED)
  3294. #define UNKNOWN(NAME) \
  3295. case NAME: \
  3296. WARN_PRINT_ONCE("Returning maximum value for unknown limit " #NAME "."); \
  3297. return (uint64_t)1 << 30;
  3298. #else
  3299. #define UNKNOWN(NAME) \
  3300. case NAME: \
  3301. return (uint64_t)1 << 30
  3302. #endif
  3303. // clang-format off
  3304. switch (p_limit) {
  3305. case LIMIT_MAX_BOUND_UNIFORM_SETS:
  3306. return limits.maxBoundDescriptorSets;
  3307. case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS:
  3308. return limits.maxColorAttachments;
  3309. case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET:
  3310. return limits.maxTexturesPerArgumentBuffer;
  3311. case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET:
  3312. return limits.maxSamplersPerArgumentBuffer;
  3313. case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET:
  3314. return limits.maxBuffersPerArgumentBuffer;
  3315. case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET:
  3316. return limits.maxTexturesPerArgumentBuffer;
  3317. case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET:
  3318. return limits.maxBuffersPerArgumentBuffer;
  3319. case LIMIT_MAX_DRAW_INDEXED_INDEX:
  3320. return limits.maxDrawIndexedIndexValue;
  3321. case LIMIT_MAX_FRAMEBUFFER_HEIGHT:
  3322. return limits.maxFramebufferHeight;
  3323. case LIMIT_MAX_FRAMEBUFFER_WIDTH:
  3324. return limits.maxFramebufferWidth;
  3325. case LIMIT_MAX_TEXTURE_ARRAY_LAYERS:
  3326. return limits.maxImageArrayLayers;
  3327. case LIMIT_MAX_TEXTURE_SIZE_1D:
  3328. return limits.maxImageDimension1D;
  3329. case LIMIT_MAX_TEXTURE_SIZE_2D:
  3330. return limits.maxImageDimension2D;
  3331. case LIMIT_MAX_TEXTURE_SIZE_3D:
  3332. return limits.maxImageDimension3D;
  3333. case LIMIT_MAX_TEXTURE_SIZE_CUBE:
  3334. return limits.maxImageDimensionCube;
  3335. case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
  3336. return limits.maxTexturesPerArgumentBuffer;
  3337. case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE:
  3338. return limits.maxSamplersPerArgumentBuffer;
  3339. case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE:
  3340. return limits.maxBuffersPerArgumentBuffer;
  3341. case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE:
  3342. return limits.maxTexturesPerArgumentBuffer;
  3343. case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE:
  3344. return limits.maxBuffersPerArgumentBuffer;
  3345. case LIMIT_MAX_PUSH_CONSTANT_SIZE:
  3346. return limits.maxBufferLength;
  3347. case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
  3348. return limits.maxBufferLength;
  3349. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET:
  3350. return limits.maxVertexDescriptorLayoutStride;
  3351. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES:
  3352. return limits.maxVertexInputAttributes;
  3353. case LIMIT_MAX_VERTEX_INPUT_BINDINGS:
  3354. return limits.maxVertexInputBindings;
  3355. case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE:
  3356. return limits.maxVertexInputBindingStride;
  3357. case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
  3358. return limits.minUniformBufferOffsetAlignment;
  3359. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
  3360. return limits.maxComputeWorkGroupCount.width;
  3361. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
  3362. return limits.maxComputeWorkGroupCount.height;
  3363. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
  3364. return limits.maxComputeWorkGroupCount.depth;
  3365. case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS:
  3366. return std::max({ limits.maxThreadsPerThreadGroup.width, limits.maxThreadsPerThreadGroup.height, limits.maxThreadsPerThreadGroup.depth });
  3367. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
  3368. return limits.maxThreadsPerThreadGroup.width;
  3369. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
  3370. return limits.maxThreadsPerThreadGroup.height;
  3371. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
  3372. return limits.maxThreadsPerThreadGroup.depth;
  3373. case LIMIT_MAX_VIEWPORT_DIMENSIONS_X:
  3374. return limits.maxViewportDimensionX;
  3375. case LIMIT_MAX_VIEWPORT_DIMENSIONS_Y:
  3376. return limits.maxViewportDimensionY;
  3377. case LIMIT_SUBGROUP_SIZE:
  3378. // MoltenVK sets the subgroupSize to the same as the maxSubgroupSize.
  3379. return limits.maxSubgroupSize;
  3380. case LIMIT_SUBGROUP_MIN_SIZE:
  3381. return limits.minSubgroupSize;
  3382. case LIMIT_SUBGROUP_MAX_SIZE:
  3383. return limits.maxSubgroupSize;
  3384. case LIMIT_SUBGROUP_IN_SHADERS:
  3385. return (uint64_t)limits.subgroupSupportedShaderStages;
  3386. case LIMIT_SUBGROUP_OPERATIONS:
  3387. return (uint64_t)limits.subgroupSupportedOperations;
  3388. case LIMIT_METALFX_TEMPORAL_SCALER_MIN_SCALE:
  3389. return (uint64_t)((1.0 / limits.temporalScalerInputContentMaxScale) * 1000'000);
  3390. case LIMIT_METALFX_TEMPORAL_SCALER_MAX_SCALE:
  3391. return (uint64_t)((1.0 / limits.temporalScalerInputContentMinScale) * 1000'000);
  3392. case LIMIT_MAX_SHADER_VARYINGS:
  3393. return limits.maxShaderVaryings;
  3394. UNKNOWN(LIMIT_VRS_TEXEL_WIDTH);
  3395. UNKNOWN(LIMIT_VRS_TEXEL_HEIGHT);
  3396. UNKNOWN(LIMIT_VRS_MAX_FRAGMENT_WIDTH);
  3397. UNKNOWN(LIMIT_VRS_MAX_FRAGMENT_HEIGHT);
  3398. default:
  3399. ERR_FAIL_V(0);
  3400. }
  3401. // clang-format on
  3402. return 0;
  3403. }
  3404. uint64_t RenderingDeviceDriverMetal::api_trait_get(ApiTrait p_trait) {
  3405. switch (p_trait) {
  3406. case API_TRAIT_HONORS_PIPELINE_BARRIERS:
  3407. return 0;
  3408. default:
  3409. return RenderingDeviceDriver::api_trait_get(p_trait);
  3410. }
  3411. }
  3412. bool RenderingDeviceDriverMetal::has_feature(Features p_feature) {
  3413. switch (p_feature) {
  3414. case SUPPORTS_MULTIVIEW:
  3415. return multiview_capabilities.is_supported;
  3416. case SUPPORTS_FSR_HALF_FLOAT:
  3417. return true;
  3418. case SUPPORTS_ATTACHMENT_VRS:
  3419. // TODO(sgc): Maybe supported via https://developer.apple.com/documentation/metal/render_passes/rendering_at_different_rasterization_rates?language=objc
  3420. // See also:
  3421. //
  3422. // * https://forum.beyond3d.com/threads/variable-rate-shading-vs-variable-rate-rasterization.62243/post-2191363
  3423. //
  3424. return false;
  3425. case SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS:
  3426. return true;
  3427. case SUPPORTS_BUFFER_DEVICE_ADDRESS:
  3428. return device_properties->features.supports_gpu_address;
  3429. case SUPPORTS_METALFX_SPATIAL:
  3430. return device_properties->features.metal_fx_spatial;
  3431. case SUPPORTS_METALFX_TEMPORAL:
  3432. return device_properties->features.metal_fx_temporal;
  3433. default:
  3434. return false;
  3435. }
  3436. }
  3437. const RDD::MultiviewCapabilities &RenderingDeviceDriverMetal::get_multiview_capabilities() {
  3438. return multiview_capabilities;
  3439. }
  3440. String RenderingDeviceDriverMetal::get_api_version() const {
  3441. return vformat("%d.%d", version_major, version_minor);
  3442. }
  3443. String RenderingDeviceDriverMetal::get_pipeline_cache_uuid() const {
  3444. return pipeline_cache_id;
  3445. }
  3446. const RDD::Capabilities &RenderingDeviceDriverMetal::get_capabilities() const {
  3447. return capabilities;
  3448. }
  3449. bool RenderingDeviceDriverMetal::is_composite_alpha_supported(CommandQueueID p_queue) const {
  3450. // The CAMetalLayer.opaque property is configured according to this global setting.
  3451. return OS::get_singleton()->is_layered_allowed();
  3452. }
  3453. size_t RenderingDeviceDriverMetal::get_texel_buffer_alignment_for_format(RDD::DataFormat p_format) const {
  3454. return [device minimumLinearTextureAlignmentForPixelFormat:pixel_formats->getMTLPixelFormat(p_format)];
  3455. }
  3456. size_t RenderingDeviceDriverMetal::get_texel_buffer_alignment_for_format(MTLPixelFormat p_format) const {
  3457. return [device minimumLinearTextureAlignmentForPixelFormat:p_format];
  3458. }
  3459. /******************/
  3460. RenderingDeviceDriverMetal::RenderingDeviceDriverMetal(RenderingContextDriverMetal *p_context_driver) :
  3461. context_driver(p_context_driver) {
  3462. DEV_ASSERT(p_context_driver != nullptr);
  3463. if (String res = OS::get_singleton()->get_environment("GODOT_MTL_SHADER_LOAD_STRATEGY"); res == U"lazy") {
  3464. _shader_load_strategy = ShaderLoadStrategy::LAZY;
  3465. }
  3466. }
  3467. RenderingDeviceDriverMetal::~RenderingDeviceDriverMetal() {
  3468. for (MDCommandBuffer *cb : command_buffers) {
  3469. delete cb;
  3470. }
  3471. for (KeyValue<SHA256Digest, ShaderCacheEntry *> &kv : _shader_cache) {
  3472. memdelete(kv.value);
  3473. }
  3474. }
  3475. #pragma mark - Initialization
  3476. Error RenderingDeviceDriverMetal::_create_device() {
  3477. device = context_driver->get_metal_device();
  3478. device_queue = [device newCommandQueue];
  3479. ERR_FAIL_NULL_V(device_queue, ERR_CANT_CREATE);
  3480. device_scope = [MTLCaptureManager.sharedCaptureManager newCaptureScopeWithCommandQueue:device_queue];
  3481. device_scope.label = @"Godot Frame";
  3482. [device_scope beginScope]; // Allow Xcode to capture the first frame, if desired.
  3483. resource_cache = std::make_unique<MDResourceCache>(this);
  3484. return OK;
  3485. }
  3486. Error RenderingDeviceDriverMetal::_check_capabilities() {
  3487. MTLCompileOptions *options = [MTLCompileOptions new];
  3488. version_major = (options.languageVersion >> 0x10) & 0xff;
  3489. version_minor = (options.languageVersion >> 0x00) & 0xff;
  3490. capabilities.device_family = DEVICE_METAL;
  3491. capabilities.version_major = version_major;
  3492. capabilities.version_minor = version_minor;
  3493. return OK;
  3494. }
  3495. Error RenderingDeviceDriverMetal::initialize(uint32_t p_device_index, uint32_t p_frame_count) {
  3496. context_device = context_driver->device_get(p_device_index);
  3497. Error err = _create_device();
  3498. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  3499. err = _check_capabilities();
  3500. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  3501. // Set the pipeline cache ID based on the Metal version.
  3502. pipeline_cache_id = "metal-driver-" + get_api_version();
  3503. device_properties = memnew(MetalDeviceProperties(device));
  3504. pixel_formats = memnew(PixelFormats(device, device_properties->features));
  3505. if (device_properties->features.layeredRendering) {
  3506. multiview_capabilities.is_supported = true;
  3507. multiview_capabilities.max_view_count = device_properties->limits.maxViewports;
  3508. // NOTE: I'm not sure what the limit is as I don't see it referenced anywhere
  3509. multiview_capabilities.max_instance_count = UINT32_MAX;
  3510. print_verbose("- Metal multiview supported:");
  3511. print_verbose(" max view count: " + itos(multiview_capabilities.max_view_count));
  3512. print_verbose(" max instances: " + itos(multiview_capabilities.max_instance_count));
  3513. } else {
  3514. print_verbose("- Metal multiview not supported");
  3515. }
  3516. // The Metal renderer requires Apple4 family. This is 2017 era A11 chips and newer.
  3517. if (device_properties->features.highestFamily < MTLGPUFamilyApple4) {
  3518. 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");
  3519. if (!device_properties->features.imageCubeArray) {
  3520. error_string += "- No support for image cube arrays.\n";
  3521. }
  3522. #if defined(IOS_ENABLED)
  3523. // iOS platform ports currently don't exit themselves when this method returns `ERR_CANT_CREATE`.
  3524. OS::get_singleton()->alert(error_string + "\nClick OK to exit (black screen will be visible).");
  3525. #else
  3526. OS::get_singleton()->alert(error_string + "\nClick OK to exit.");
  3527. #endif
  3528. return ERR_CANT_CREATE;
  3529. }
  3530. return OK;
  3531. }