rendering_device_driver_d3d12.cpp 288 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668
  1. /**************************************************************************/
  2. /* rendering_device_driver_d3d12.cpp */
  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. #include "rendering_device_driver_d3d12.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/marshalls.h"
  33. #include "servers/rendering/rendering_device.h"
  34. #include "thirdparty/zlib/zlib.h"
  35. #include "d3d12_godot_nir_bridge.h"
  36. #include "dxil_hash.h"
  37. #include "rendering_context_driver_d3d12.h"
  38. // No point in fighting warnings in Mesa.
  39. #if defined(_MSC_VER)
  40. #pragma warning(push)
  41. #pragma warning(disable : 4200) // "nonstandard extension used: zero-sized array in struct/union".
  42. #pragma warning(disable : 4806) // "'&': unsafe operation: no value of type 'bool' promoted to type 'uint32_t' can equal the given constant".
  43. #endif
  44. #if defined(__GNUC__) && !defined(__clang__)
  45. #pragma GCC diagnostic push
  46. #pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
  47. #pragma GCC diagnostic ignored "-Wshadow"
  48. #pragma GCC diagnostic ignored "-Wswitch"
  49. #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  50. #elif defined(__clang__)
  51. #pragma clang diagnostic push
  52. #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  53. #pragma clang diagnostic ignored "-Wstring-plus-int"
  54. #pragma clang diagnostic ignored "-Wswitch"
  55. #pragma clang diagnostic ignored "-Wmissing-field-initializers"
  56. #endif
  57. #include "nir_spirv.h"
  58. #include "nir_to_dxil.h"
  59. #include "spirv_to_dxil.h"
  60. extern "C" {
  61. #include "dxil_spirv_nir.h"
  62. }
  63. #if defined(__GNUC__) && !defined(__clang__)
  64. #pragma GCC diagnostic pop
  65. #elif defined(__clang__)
  66. #pragma clang diagnostic pop
  67. #endif
  68. #if defined(_MSC_VER)
  69. #pragma warning(pop)
  70. #endif
  71. #if !defined(_MSC_VER)
  72. #include <guiddef.h>
  73. #include <dxguids.h>
  74. #endif
  75. // Mesa may define this.
  76. #ifdef UNUSED
  77. #undef UNUSED
  78. #endif
  79. #ifdef PIX_ENABLED
  80. #if defined(__GNUC__)
  81. #define _MSC_VER 1800
  82. #endif
  83. #define USE_PIX
  84. #include "WinPixEventRuntime/pix3.h"
  85. #if defined(__GNUC__)
  86. #undef _MSC_VER
  87. #endif
  88. #endif
  89. static const D3D12_RANGE VOID_RANGE = {};
  90. static const uint32_t ROOT_CONSTANT_REGISTER = GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER * (RDD::MAX_UNIFORM_SETS + 1);
  91. static const uint32_t RUNTIME_DATA_REGISTER = GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER * (RDD::MAX_UNIFORM_SETS + 2);
  92. /*****************/
  93. /**** GENERIC ****/
  94. /*****************/
  95. // NOTE: RD's packed format names are reversed in relation to DXGI's; e.g.:.
  96. // - DATA_FORMAT_A8B8G8R8_UNORM_PACK32 -> DXGI_FORMAT_R8G8B8A8_UNORM (packed; note ABGR vs. RGBA).
  97. // - DATA_FORMAT_B8G8R8A8_UNORM -> DXGI_FORMAT_B8G8R8A8_UNORM (not packed; note BGRA order matches).
  98. // TODO: Add YUV formats properly, which would require better support for planes in the RD API.
  99. const RenderingDeviceDriverD3D12::D3D12Format RenderingDeviceDriverD3D12::RD_TO_D3D12_FORMAT[RDD::DATA_FORMAT_MAX] = {
  100. /* DATA_FORMAT_R4G4_UNORM_PACK8 */ {},
  101. /* DATA_FORMAT_R4G4B4A4_UNORM_PACK16 */ { DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_B4G4R4A4_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(1, 2, 3, 0) },
  102. /* DATA_FORMAT_B4G4R4A4_UNORM_PACK16 */ { DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_B4G4R4A4_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(3, 2, 1, 0) },
  103. /* DATA_FORMAT_R5G6B5_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G6R5_UNORM },
  104. /* DATA_FORMAT_B5G6R5_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G6R5_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) },
  105. /* DATA_FORMAT_R5G5B5A1_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(1, 2, 3, 0) },
  106. /* DATA_FORMAT_B5G5R5A1_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(3, 2, 1, 0) },
  107. /* DATA_FORMAT_A1R5G5B5_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM },
  108. /* DATA_FORMAT_R8_UNORM */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UNORM },
  109. /* DATA_FORMAT_R8_SNORM */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_SNORM },
  110. /* DATA_FORMAT_R8_USCALED */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UINT },
  111. /* DATA_FORMAT_R8_SSCALED */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_SINT },
  112. /* DATA_FORMAT_R8_UINT */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UINT },
  113. /* DATA_FORMAT_R8_SINT */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_SINT },
  114. /* DATA_FORMAT_R8_SRGB */ {},
  115. /* DATA_FORMAT_R8G8_UNORM */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UNORM },
  116. /* DATA_FORMAT_R8G8_SNORM */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_SNORM },
  117. /* DATA_FORMAT_R8G8_USCALED */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UINT },
  118. /* DATA_FORMAT_R8G8_SSCALED */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_SINT },
  119. /* DATA_FORMAT_R8G8_UINT */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UINT },
  120. /* DATA_FORMAT_R8G8_SINT */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_SINT },
  121. /* DATA_FORMAT_R8G8_SRGB */ {},
  122. /* DATA_FORMAT_R8G8B8_UNORM */ {},
  123. /* DATA_FORMAT_R8G8B8_SNORM */ {},
  124. /* DATA_FORMAT_R8G8B8_USCALED */ {},
  125. /* DATA_FORMAT_R8G8B8_SSCALED */ {},
  126. /* DATA_FORMAT_R8G8B8_UINT */ {},
  127. /* DATA_FORMAT_R8G8B8_SINT */ {},
  128. /* DATA_FORMAT_R8G8B8_SRGB */ {},
  129. /* DATA_FORMAT_B8G8R8_UNORM */ {},
  130. /* DATA_FORMAT_B8G8R8_SNORM */ {},
  131. /* DATA_FORMAT_B8G8R8_USCALED */ {},
  132. /* DATA_FORMAT_B8G8R8_SSCALED */ {},
  133. /* DATA_FORMAT_B8G8R8_UINT */ {},
  134. /* DATA_FORMAT_B8G8R8_SINT */ {},
  135. /* DATA_FORMAT_B8G8R8_SRGB */ {},
  136. /* DATA_FORMAT_R8G8B8A8_UNORM */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM },
  137. /* DATA_FORMAT_R8G8B8A8_SNORM */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SNORM },
  138. /* DATA_FORMAT_R8G8B8A8_USCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  139. /* DATA_FORMAT_R8G8B8A8_SSCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  140. /* DATA_FORMAT_R8G8B8A8_UINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  141. /* DATA_FORMAT_R8G8B8A8_SINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  142. /* DATA_FORMAT_R8G8B8A8_SRGB */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB },
  143. /* DATA_FORMAT_B8G8R8A8_UNORM */ { DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM },
  144. /* DATA_FORMAT_B8G8R8A8_SNORM */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SNORM },
  145. /* DATA_FORMAT_B8G8R8A8_USCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  146. /* DATA_FORMAT_B8G8R8A8_SSCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  147. /* DATA_FORMAT_B8G8R8A8_UINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  148. /* DATA_FORMAT_B8G8R8A8_SINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  149. /* DATA_FORMAT_B8G8R8A8_SRGB */ { DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB },
  150. /* DATA_FORMAT_A8B8G8R8_UNORM_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM },
  151. /* DATA_FORMAT_A8B8G8R8_SNORM_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SNORM },
  152. /* DATA_FORMAT_A8B8G8R8_USCALED_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  153. /* DATA_FORMAT_A8B8G8R8_SSCALED_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  154. /* DATA_FORMAT_A8B8G8R8_UINT_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  155. /* DATA_FORMAT_A8B8G8R8_SINT_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  156. /* DATA_FORMAT_A8B8G8R8_SRGB_PACK32 */ { DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB },
  157. /* DATA_FORMAT_A2R10G10B10_UNORM_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) },
  158. /* DATA_FORMAT_A2R10G10B10_SNORM_PACK32 */ {},
  159. /* DATA_FORMAT_A2R10G10B10_USCALED_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) },
  160. /* DATA_FORMAT_A2R10G10B10_SSCALED_PACK32 */ {},
  161. /* DATA_FORMAT_A2R10G10B10_UINT_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) },
  162. /* DATA_FORMAT_A2R10G10B10_SINT_PACK32 */ {},
  163. /* DATA_FORMAT_A2B10G10R10_UNORM_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM },
  164. /* DATA_FORMAT_A2B10G10R10_SNORM_PACK32 */ {},
  165. /* DATA_FORMAT_A2B10G10R10_USCALED_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT },
  166. /* DATA_FORMAT_A2B10G10R10_SSCALED_PACK32 */ {},
  167. /* DATA_FORMAT_A2B10G10R10_UINT_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT },
  168. /* DATA_FORMAT_A2B10G10R10_SINT_PACK32 */ {},
  169. /* DATA_FORMAT_R16_UNORM */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM },
  170. /* DATA_FORMAT_R16_SNORM */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_SNORM },
  171. /* DATA_FORMAT_R16_USCALED */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UINT },
  172. /* DATA_FORMAT_R16_SSCALED */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_SINT },
  173. /* DATA_FORMAT_R16_UINT */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UINT },
  174. /* DATA_FORMAT_R16_SINT */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_SINT },
  175. /* DATA_FORMAT_R16_SFLOAT */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_FLOAT },
  176. /* DATA_FORMAT_R16G16_UNORM */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UNORM },
  177. /* DATA_FORMAT_R16G16_SNORM */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_SNORM },
  178. /* DATA_FORMAT_R16G16_USCALED */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UINT },
  179. /* DATA_FORMAT_R16G16_SSCALED */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_SINT },
  180. /* DATA_FORMAT_R16G16_UINT */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UINT },
  181. /* DATA_FORMAT_R16G16_SINT */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_SINT },
  182. /* DATA_FORMAT_R16G16_SFLOAT */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_FLOAT },
  183. /* DATA_FORMAT_R16G16B16_UNORM */ {},
  184. /* DATA_FORMAT_R16G16B16_SNORM */ {},
  185. /* DATA_FORMAT_R16G16B16_USCALED */ {},
  186. /* DATA_FORMAT_R16G16B16_SSCALED */ {},
  187. /* DATA_FORMAT_R16G16B16_UINT */ {},
  188. /* DATA_FORMAT_R16G16B16_SINT */ {},
  189. /* DATA_FORMAT_R16G16B16_SFLOAT */ {},
  190. /* DATA_FORMAT_R16G16B16A16_UNORM */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UNORM },
  191. /* DATA_FORMAT_R16G16B16A16_SNORM */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_SNORM },
  192. /* DATA_FORMAT_R16G16B16A16_USCALED */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UINT },
  193. /* DATA_FORMAT_R16G16B16A16_SSCALED */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_SINT },
  194. /* DATA_FORMAT_R16G16B16A16_UINT */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UINT },
  195. /* DATA_FORMAT_R16G16B16A16_SINT */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_SINT },
  196. /* DATA_FORMAT_R16G16B16A16_SFLOAT */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_FLOAT },
  197. /* DATA_FORMAT_R32_UINT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_UINT },
  198. /* DATA_FORMAT_R32_SINT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_SINT },
  199. /* DATA_FORMAT_R32_SFLOAT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT },
  200. /* DATA_FORMAT_R32G32_UINT */ { DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_UINT },
  201. /* DATA_FORMAT_R32G32_SINT */ { DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_SINT },
  202. /* DATA_FORMAT_R32G32_SFLOAT */ { DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_FLOAT },
  203. /* DATA_FORMAT_R32G32B32_UINT */ { DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_UINT },
  204. /* DATA_FORMAT_R32G32B32_SINT */ { DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_SINT },
  205. /* DATA_FORMAT_R32G32B32_SFLOAT */ { DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_FLOAT },
  206. /* DATA_FORMAT_R32G32B32A32_UINT */ { DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_UINT },
  207. /* DATA_FORMAT_R32G32B32A32_SINT */ { DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_SINT },
  208. /* DATA_FORMAT_R32G32B32A32_SFLOAT */ { DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_FLOAT },
  209. /* DATA_FORMAT_R64_UINT */ {},
  210. /* DATA_FORMAT_R64_SINT */ {},
  211. /* DATA_FORMAT_R64_SFLOAT */ {},
  212. /* DATA_FORMAT_R64G64_UINT */ {},
  213. /* DATA_FORMAT_R64G64_SINT */ {},
  214. /* DATA_FORMAT_R64G64_SFLOAT */ {},
  215. /* DATA_FORMAT_R64G64B64_UINT */ {},
  216. /* DATA_FORMAT_R64G64B64_SINT */ {},
  217. /* DATA_FORMAT_R64G64B64_SFLOAT */ {},
  218. /* DATA_FORMAT_R64G64B64A64_UINT */ {},
  219. /* DATA_FORMAT_R64G64B64A64_SINT */ {},
  220. /* DATA_FORMAT_R64G64B64A64_SFLOAT */ {},
  221. /* DATA_FORMAT_B10G11R11_UFLOAT_PACK32 */ { DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R11G11B10_FLOAT },
  222. /* DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32 */ { DXGI_FORMAT_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_R9G9B9E5_SHAREDEXP },
  223. /* DATA_FORMAT_D16_UNORM */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM, 0, DXGI_FORMAT_D16_UNORM },
  224. /* DATA_FORMAT_X8_D24_UNORM_PACK32 */ { DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_UNKNOWN, 0, DXGI_FORMAT_D24_UNORM_S8_UINT },
  225. /* DATA_FORMAT_D32_SFLOAT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, DXGI_FORMAT_D32_FLOAT },
  226. /* DATA_FORMAT_S8_UINT */ {},
  227. /* DATA_FORMAT_D16_UNORM_S8_UINT */ {},
  228. /* DATA_FORMAT_D24_UNORM_S8_UINT */ { DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_UNKNOWN, 0, DXGI_FORMAT_D24_UNORM_S8_UINT },
  229. /* DATA_FORMAT_D32_SFLOAT_S8_UINT */ { DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, DXGI_FORMAT_D32_FLOAT_S8X24_UINT },
  230. /* DATA_FORMAT_BC1_RGB_UNORM_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) },
  231. /* DATA_FORMAT_BC1_RGB_SRGB_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM_SRGB, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) },
  232. /* DATA_FORMAT_BC1_RGBA_UNORM_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM },
  233. /* DATA_FORMAT_BC1_RGBA_SRGB_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM_SRGB },
  234. /* DATA_FORMAT_BC2_UNORM_BLOCK */ { DXGI_FORMAT_BC2_TYPELESS, DXGI_FORMAT_BC2_UNORM },
  235. /* DATA_FORMAT_BC2_SRGB_BLOCK */ { DXGI_FORMAT_BC2_TYPELESS, DXGI_FORMAT_BC2_UNORM_SRGB },
  236. /* DATA_FORMAT_BC3_UNORM_BLOCK */ { DXGI_FORMAT_BC3_TYPELESS, DXGI_FORMAT_BC3_UNORM },
  237. /* DATA_FORMAT_BC3_SRGB_BLOCK */ { DXGI_FORMAT_BC3_TYPELESS, DXGI_FORMAT_BC3_UNORM_SRGB },
  238. /* DATA_FORMAT_BC4_UNORM_BLOCK */ { DXGI_FORMAT_BC4_TYPELESS, DXGI_FORMAT_BC4_UNORM },
  239. /* DATA_FORMAT_BC4_SNORM_BLOCK */ { DXGI_FORMAT_BC4_TYPELESS, DXGI_FORMAT_BC4_SNORM },
  240. /* DATA_FORMAT_BC5_UNORM_BLOCK */ { DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_UNORM },
  241. /* DATA_FORMAT_BC5_SNORM_BLOCK */ { DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_SNORM },
  242. /* DATA_FORMAT_BC6H_UFLOAT_BLOCK */ { DXGI_FORMAT_BC6H_TYPELESS, DXGI_FORMAT_BC6H_UF16 },
  243. /* DATA_FORMAT_BC6H_SFLOAT_BLOCK */ { DXGI_FORMAT_BC6H_TYPELESS, DXGI_FORMAT_BC6H_SF16 },
  244. /* DATA_FORMAT_BC7_UNORM_BLOCK */ { DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM },
  245. /* DATA_FORMAT_BC7_SRGB_BLOCK */ { DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM_SRGB },
  246. /* DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK */ {},
  247. /* DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK */ {},
  248. /* DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK */ {},
  249. /* DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK */ {},
  250. /* DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK */ {},
  251. /* DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK */ {},
  252. /* DATA_FORMAT_EAC_R11_UNORM_BLOCK */ {},
  253. /* DATA_FORMAT_EAC_R11_SNORM_BLOCK */ {},
  254. /* DATA_FORMAT_EAC_R11G11_UNORM_BLOCK */ {},
  255. /* DATA_FORMAT_EAC_R11G11_SNORM_BLOCK */ {},
  256. /* DATA_FORMAT_ASTC_4x4_UNORM_BLOCK */ {},
  257. /* DATA_FORMAT_ASTC_4x4_SRGB_BLOCK */ {},
  258. /* DATA_FORMAT_ASTC_5x4_UNORM_BLOCK */ {},
  259. /* DATA_FORMAT_ASTC_5x4_SRGB_BLOCK */ {},
  260. /* DATA_FORMAT_ASTC_5x5_UNORM_BLOCK */ {},
  261. /* DATA_FORMAT_ASTC_5x5_SRGB_BLOCK */ {},
  262. /* DATA_FORMAT_ASTC_6x5_UNORM_BLOCK */ {},
  263. /* DATA_FORMAT_ASTC_6x5_SRGB_BLOCK */ {},
  264. /* DATA_FORMAT_ASTC_6x6_UNORM_BLOCK */ {},
  265. /* DATA_FORMAT_ASTC_6x6_SRGB_BLOCK */ {},
  266. /* DATA_FORMAT_ASTC_8x5_UNORM_BLOCK */ {},
  267. /* DATA_FORMAT_ASTC_8x5_SRGB_BLOCK */ {},
  268. /* DATA_FORMAT_ASTC_8x6_UNORM_BLOCK */ {},
  269. /* DATA_FORMAT_ASTC_8x6_SRGB_BLOCK */ {},
  270. /* DATA_FORMAT_ASTC_8x8_UNORM_BLOCK */ {},
  271. /* DATA_FORMAT_ASTC_8x8_SRGB_BLOCK */ {},
  272. /* DATA_FORMAT_ASTC_10x5_UNORM_BLOCK */ {},
  273. /* DATA_FORMAT_ASTC_10x5_SRGB_BLOCK */ {},
  274. /* DATA_FORMAT_ASTC_10x6_UNORM_BLOCK */ {},
  275. /* DATA_FORMAT_ASTC_10x6_SRGB_BLOCK */ {},
  276. /* DATA_FORMAT_ASTC_10x8_UNORM_BLOCK */ {},
  277. /* DATA_FORMAT_ASTC_10x8_SRGB_BLOCK */ {},
  278. /* DATA_FORMAT_ASTC_10x10_UNORM_BLOCK */ {},
  279. /* DATA_FORMAT_ASTC_10x10_SRGB_BLOCK */ {},
  280. /* DATA_FORMAT_ASTC_12x10_UNORM_BLOCK */ {},
  281. /* DATA_FORMAT_ASTC_12x10_SRGB_BLOCK */ {},
  282. /* DATA_FORMAT_ASTC_12x12_UNORM_BLOCK */ {},
  283. /* DATA_FORMAT_ASTC_12x12_SRGB_BLOCK */ {},
  284. /* DATA_FORMAT_G8B8G8R8_422_UNORM */ {},
  285. /* DATA_FORMAT_B8G8R8G8_422_UNORM */ {},
  286. /* DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM */ {},
  287. /* DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM */ {},
  288. /* DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM */ {},
  289. /* DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM */ {},
  290. /* DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM */ {},
  291. /* DATA_FORMAT_R10X6_UNORM_PACK16 */ {},
  292. /* DATA_FORMAT_R10X6G10X6_UNORM_2PACK16 */ {},
  293. /* DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16 */ {},
  294. /* DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16 */ {},
  295. /* DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16 */ {},
  296. /* DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16 */ {},
  297. /* DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16 */ {},
  298. /* DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16 */ {},
  299. /* DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16 */ {},
  300. /* DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16 */ {},
  301. /* DATA_FORMAT_R12X4_UNORM_PACK16 */ {},
  302. /* DATA_FORMAT_R12X4G12X4_UNORM_2PACK16 */ {},
  303. /* DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16 */ {},
  304. /* DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16 */ {},
  305. /* DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16 */ {},
  306. /* DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16 */ {},
  307. /* DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16 */ {},
  308. /* DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16 */ {},
  309. /* DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16 */ {},
  310. /* DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16 */ {},
  311. /* DATA_FORMAT_G16B16G16R16_422_UNORM */ {},
  312. /* DATA_FORMAT_B16G16R16G16_422_UNORM */ {},
  313. /* DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM */ {},
  314. /* DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM */ {},
  315. /* DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM */ {},
  316. /* DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM */ {},
  317. /* DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM */ {},
  318. };
  319. Error RenderingDeviceDriverD3D12::DescriptorsHeap::allocate(ID3D12Device *p_device, D3D12_DESCRIPTOR_HEAP_TYPE p_type, uint32_t p_descriptor_count, bool p_for_gpu) {
  320. ERR_FAIL_COND_V(heap, ERR_ALREADY_EXISTS);
  321. ERR_FAIL_COND_V(p_descriptor_count == 0, ERR_INVALID_PARAMETER);
  322. handle_size = p_device->GetDescriptorHandleIncrementSize(p_type);
  323. desc.Type = p_type;
  324. desc.NumDescriptors = p_descriptor_count;
  325. desc.Flags = p_for_gpu ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  326. HRESULT res = p_device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(heap.GetAddressOf()));
  327. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_CANT_CREATE, "CreateDescriptorHeap failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  328. return OK;
  329. }
  330. RenderingDeviceDriverD3D12::DescriptorsHeap::Walker RenderingDeviceDriverD3D12::DescriptorsHeap::make_walker() const {
  331. Walker walker;
  332. walker.handle_size = handle_size;
  333. walker.handle_count = desc.NumDescriptors;
  334. if (heap) {
  335. #if defined(_MSC_VER) || !defined(_WIN32)
  336. walker.first_cpu_handle = heap->GetCPUDescriptorHandleForHeapStart();
  337. if ((desc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) {
  338. walker.first_gpu_handle = heap->GetGPUDescriptorHandleForHeapStart();
  339. }
  340. #else
  341. heap->GetCPUDescriptorHandleForHeapStart(&walker.first_cpu_handle);
  342. if ((desc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) {
  343. heap->GetGPUDescriptorHandleForHeapStart(&walker.first_gpu_handle);
  344. }
  345. #endif
  346. }
  347. return walker;
  348. }
  349. void RenderingDeviceDriverD3D12::DescriptorsHeap::Walker::advance(uint32_t p_count) {
  350. ERR_FAIL_COND_MSG(handle_index + p_count > handle_count, "Would advance past EOF.");
  351. handle_index += p_count;
  352. }
  353. D3D12_CPU_DESCRIPTOR_HANDLE RenderingDeviceDriverD3D12::DescriptorsHeap::Walker::get_curr_cpu_handle() {
  354. ERR_FAIL_COND_V_MSG(is_at_eof(), D3D12_CPU_DESCRIPTOR_HANDLE(), "Heap walker is at EOF.");
  355. return D3D12_CPU_DESCRIPTOR_HANDLE{ first_cpu_handle.ptr + handle_index * handle_size };
  356. }
  357. D3D12_GPU_DESCRIPTOR_HANDLE RenderingDeviceDriverD3D12::DescriptorsHeap::Walker::get_curr_gpu_handle() {
  358. ERR_FAIL_COND_V_MSG(!first_gpu_handle.ptr, D3D12_GPU_DESCRIPTOR_HANDLE(), "Can't provide a GPU handle from a non-GPU descriptors heap.");
  359. ERR_FAIL_COND_V_MSG(is_at_eof(), D3D12_GPU_DESCRIPTOR_HANDLE(), "Heap walker is at EOF.");
  360. return D3D12_GPU_DESCRIPTOR_HANDLE{ first_gpu_handle.ptr + handle_index * handle_size };
  361. }
  362. static const D3D12_COMPARISON_FUNC RD_TO_D3D12_COMPARE_OP[RD::COMPARE_OP_MAX] = {
  363. D3D12_COMPARISON_FUNC_NEVER,
  364. D3D12_COMPARISON_FUNC_LESS,
  365. D3D12_COMPARISON_FUNC_EQUAL,
  366. D3D12_COMPARISON_FUNC_LESS_EQUAL,
  367. D3D12_COMPARISON_FUNC_GREATER,
  368. D3D12_COMPARISON_FUNC_NOT_EQUAL,
  369. D3D12_COMPARISON_FUNC_GREATER_EQUAL,
  370. D3D12_COMPARISON_FUNC_ALWAYS,
  371. };
  372. uint32_t RenderingDeviceDriverD3D12::SubgroupCapabilities::supported_stages_flags_rd() const {
  373. // If there's a way to check exactly which are supported, I have yet to find it.
  374. return (
  375. RenderingDevice::ShaderStage::SHADER_STAGE_FRAGMENT_BIT |
  376. RenderingDevice::ShaderStage::SHADER_STAGE_COMPUTE_BIT);
  377. }
  378. uint32_t RenderingDeviceDriverD3D12::SubgroupCapabilities::supported_operations_flags_rd() const {
  379. if (!wave_ops_supported) {
  380. return 0;
  381. } else {
  382. return (
  383. RenderingDevice::SubgroupOperations::SUBGROUP_BASIC_BIT |
  384. RenderingDevice::SubgroupOperations::SUBGROUP_BALLOT_BIT |
  385. RenderingDevice::SubgroupOperations::SUBGROUP_VOTE_BIT |
  386. RenderingDevice::SubgroupOperations::SUBGROUP_SHUFFLE_BIT |
  387. RenderingDevice::SubgroupOperations::SUBGROUP_SHUFFLE_RELATIVE_BIT |
  388. RenderingDevice::SubgroupOperations::SUBGROUP_QUAD_BIT |
  389. RenderingDevice::SubgroupOperations::SUBGROUP_ARITHMETIC_BIT |
  390. RenderingDevice::SubgroupOperations::SUBGROUP_CLUSTERED_BIT);
  391. }
  392. }
  393. void RenderingDeviceDriverD3D12::_debug_message_func(D3D12_MESSAGE_CATEGORY p_category, D3D12_MESSAGE_SEVERITY p_severity, D3D12_MESSAGE_ID p_id, LPCSTR p_description, void *p_context) {
  394. String type_string;
  395. switch (p_category) {
  396. case D3D12_MESSAGE_CATEGORY_APPLICATION_DEFINED:
  397. type_string = "APPLICATION_DEFINED";
  398. break;
  399. case D3D12_MESSAGE_CATEGORY_MISCELLANEOUS:
  400. type_string = "MISCELLANEOUS";
  401. break;
  402. case D3D12_MESSAGE_CATEGORY_INITIALIZATION:
  403. type_string = "INITIALIZATION";
  404. break;
  405. case D3D12_MESSAGE_CATEGORY_CLEANUP:
  406. type_string = "CLEANUP";
  407. break;
  408. case D3D12_MESSAGE_CATEGORY_COMPILATION:
  409. type_string = "COMPILATION";
  410. break;
  411. case D3D12_MESSAGE_CATEGORY_STATE_CREATION:
  412. type_string = "STATE_CREATION";
  413. break;
  414. case D3D12_MESSAGE_CATEGORY_STATE_SETTING:
  415. type_string = "STATE_SETTING";
  416. break;
  417. case D3D12_MESSAGE_CATEGORY_STATE_GETTING:
  418. type_string = "STATE_GETTING";
  419. break;
  420. case D3D12_MESSAGE_CATEGORY_RESOURCE_MANIPULATION:
  421. type_string = "RESOURCE_MANIPULATION";
  422. break;
  423. case D3D12_MESSAGE_CATEGORY_EXECUTION:
  424. type_string = "EXECUTION";
  425. break;
  426. case D3D12_MESSAGE_CATEGORY_SHADER:
  427. type_string = "SHADER";
  428. break;
  429. }
  430. String error_message(type_string +
  431. " - Message Id Number: " + String::num_int64(p_id) +
  432. "\n\t" + p_description);
  433. // Convert D3D12 severity to our own log macros.
  434. switch (p_severity) {
  435. case D3D12_MESSAGE_SEVERITY_MESSAGE:
  436. print_verbose(error_message);
  437. break;
  438. case D3D12_MESSAGE_SEVERITY_INFO:
  439. print_line(error_message);
  440. break;
  441. case D3D12_MESSAGE_SEVERITY_WARNING:
  442. WARN_PRINT(error_message);
  443. break;
  444. case D3D12_MESSAGE_SEVERITY_ERROR:
  445. case D3D12_MESSAGE_SEVERITY_CORRUPTION:
  446. ERR_PRINT(error_message);
  447. CRASH_COND_MSG(Engine::get_singleton()->is_abort_on_gpu_errors_enabled(),
  448. "Crashing, because abort on GPU errors is enabled.");
  449. break;
  450. }
  451. }
  452. /******************/
  453. /**** RESOURCE ****/
  454. /******************/
  455. static const D3D12_RESOURCE_DIMENSION RD_TEXTURE_TYPE_TO_D3D12_RESOURCE_DIMENSION[RD::TEXTURE_TYPE_MAX] = {
  456. D3D12_RESOURCE_DIMENSION_TEXTURE1D,
  457. D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  458. D3D12_RESOURCE_DIMENSION_TEXTURE3D,
  459. D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  460. D3D12_RESOURCE_DIMENSION_TEXTURE1D,
  461. D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  462. D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  463. };
  464. void RenderingDeviceDriverD3D12::_resource_transition_batch(CommandBufferInfo *p_command_buffer, ResourceInfo *p_resource, uint32_t p_subresource, uint32_t p_num_planes, D3D12_RESOURCE_STATES p_new_state) {
  465. DEV_ASSERT(p_subresource != UINT32_MAX); // We don't support an "all-resources" command here.
  466. ResourceInfo::States *res_states = p_resource->states_ptr;
  467. D3D12_RESOURCE_STATES *curr_state = &res_states->subresource_states[p_subresource];
  468. // Transitions can be considered redundant if the current state has all the bits of the new state.
  469. // This check does not apply to the common state however, which must resort to checking if the state is the same (0).
  470. bool any_state_is_common = *curr_state == D3D12_RESOURCE_STATE_COMMON || p_new_state == D3D12_RESOURCE_STATE_COMMON;
  471. bool redundant_transition = any_state_is_common ? *curr_state == p_new_state : ((*curr_state) & p_new_state) == p_new_state;
  472. if (redundant_transition) {
  473. bool just_written = *curr_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  474. bool needs_uav_barrier = just_written && res_states->last_batch_with_uav_barrier != p_command_buffer->res_barriers_batch;
  475. if (needs_uav_barrier) {
  476. if (p_command_buffer->res_barriers.size() < p_command_buffer->res_barriers_count + 1) {
  477. p_command_buffer->res_barriers.resize(p_command_buffer->res_barriers_count + 1);
  478. }
  479. p_command_buffer->res_barriers[p_command_buffer->res_barriers_count] = CD3DX12_RESOURCE_BARRIER::UAV(p_resource->resource);
  480. p_command_buffer->res_barriers_count++;
  481. res_states->last_batch_with_uav_barrier = p_command_buffer->res_barriers_batch;
  482. }
  483. } else {
  484. uint64_t subres_mask_piece = ((uint64_t)1 << (p_subresource & 0b111111));
  485. uint8_t subres_qword = p_subresource >> 6;
  486. if (p_command_buffer->res_barriers_requests.has(res_states)) {
  487. BarrierRequest &br = p_command_buffer->res_barriers_requests.get(res_states);
  488. DEV_ASSERT(br.dx_resource == p_resource->resource);
  489. DEV_ASSERT(br.subres_mask_qwords == STEPIFY(res_states->subresource_states.size(), 64) / 64);
  490. DEV_ASSERT(br.planes == p_num_planes);
  491. // First, find if the subresource already has a barrier scheduled.
  492. uint8_t curr_group_idx = 0;
  493. bool same_transition_scheduled = false;
  494. for (curr_group_idx = 0; curr_group_idx < br.groups_count; curr_group_idx++) {
  495. if (unlikely(br.groups[curr_group_idx].states == BarrierRequest::DELETED_GROUP)) {
  496. continue;
  497. }
  498. if ((br.groups[curr_group_idx].subres_mask[subres_qword] & subres_mask_piece)) {
  499. uint32_t state_mask = br.groups[curr_group_idx].states;
  500. same_transition_scheduled = (state_mask & (uint32_t)p_new_state) == (uint32_t)p_new_state;
  501. break;
  502. }
  503. }
  504. if (!same_transition_scheduled) {
  505. bool subres_already_there = curr_group_idx != br.groups_count;
  506. D3D12_RESOURCE_STATES final_states = {};
  507. if (subres_already_there) {
  508. final_states = br.groups[curr_group_idx].states;
  509. final_states |= p_new_state;
  510. bool subres_alone = true;
  511. for (uint8_t i = 0; i < br.subres_mask_qwords; i++) {
  512. if (i == subres_qword) {
  513. if (br.groups[curr_group_idx].subres_mask[i] != subres_mask_piece) {
  514. subres_alone = false;
  515. break;
  516. }
  517. } else {
  518. if (br.groups[curr_group_idx].subres_mask[i] != 0) {
  519. subres_alone = false;
  520. break;
  521. }
  522. }
  523. }
  524. bool relocated = false;
  525. if (subres_alone) {
  526. // Subresource is there by itself.
  527. for (uint8_t i = 0; i < br.groups_count; i++) {
  528. if (unlikely(i == curr_group_idx)) {
  529. continue;
  530. }
  531. if (unlikely(br.groups[i].states == BarrierRequest::DELETED_GROUP)) {
  532. continue;
  533. }
  534. // There's another group with the final states; relocate to it.
  535. if (br.groups[i].states == final_states) {
  536. br.groups[curr_group_idx].subres_mask[subres_qword] &= ~subres_mask_piece;
  537. relocated = true;
  538. break;
  539. }
  540. }
  541. if (relocated) {
  542. // Let's delete the group where it used to be by itself.
  543. if (curr_group_idx == br.groups_count - 1) {
  544. br.groups_count--;
  545. } else {
  546. br.groups[curr_group_idx].states = BarrierRequest::DELETED_GROUP;
  547. }
  548. } else {
  549. // Its current group, where it's alone, can extend its states.
  550. br.groups[curr_group_idx].states = final_states;
  551. }
  552. } else {
  553. // Already there, but not by itself and the state mask is different, so it now belongs to a different group.
  554. br.groups[curr_group_idx].subres_mask[subres_qword] &= ~subres_mask_piece;
  555. subres_already_there = false;
  556. }
  557. } else {
  558. final_states = p_new_state;
  559. }
  560. if (!subres_already_there) {
  561. // See if it fits exactly the states of some of the groups to fit it there.
  562. for (uint8_t i = 0; i < br.groups_count; i++) {
  563. if (unlikely(i == curr_group_idx)) {
  564. continue;
  565. }
  566. if (unlikely(br.groups[i].states == BarrierRequest::DELETED_GROUP)) {
  567. continue;
  568. }
  569. if (br.groups[i].states == final_states) {
  570. br.groups[i].subres_mask[subres_qword] |= subres_mask_piece;
  571. subres_already_there = true;
  572. break;
  573. }
  574. }
  575. if (!subres_already_there) {
  576. // Add a new group to accommodate this subresource.
  577. uint8_t group_to_fill = 0;
  578. if (br.groups_count < BarrierRequest::MAX_GROUPS) {
  579. // There are still free groups.
  580. group_to_fill = br.groups_count;
  581. br.groups_count++;
  582. } else {
  583. // Let's try to take over a deleted one.
  584. for (; group_to_fill < br.groups_count; group_to_fill++) {
  585. if (unlikely(br.groups[group_to_fill].states == BarrierRequest::DELETED_GROUP)) {
  586. break;
  587. }
  588. }
  589. CRASH_COND(group_to_fill == br.groups_count);
  590. }
  591. br.groups[group_to_fill].states = final_states;
  592. for (uint8_t i = 0; i < br.subres_mask_qwords; i++) {
  593. if (unlikely(i == subres_qword)) {
  594. br.groups[group_to_fill].subres_mask[i] = subres_mask_piece;
  595. } else {
  596. br.groups[group_to_fill].subres_mask[i] = 0;
  597. }
  598. }
  599. }
  600. }
  601. }
  602. } else {
  603. BarrierRequest &br = p_command_buffer->res_barriers_requests[res_states];
  604. br.dx_resource = p_resource->resource;
  605. br.subres_mask_qwords = STEPIFY(p_resource->states_ptr->subresource_states.size(), 64) / 64;
  606. CRASH_COND(p_resource->states_ptr->subresource_states.size() > BarrierRequest::MAX_SUBRESOURCES);
  607. br.planes = p_num_planes;
  608. br.groups[0].states = p_new_state;
  609. for (uint8_t i = 0; i < br.subres_mask_qwords; i++) {
  610. if (unlikely(i == subres_qword)) {
  611. br.groups[0].subres_mask[i] = subres_mask_piece;
  612. } else {
  613. br.groups[0].subres_mask[i] = 0;
  614. }
  615. }
  616. br.groups_count = 1;
  617. }
  618. }
  619. }
  620. void RenderingDeviceDriverD3D12::_resource_transitions_flush(CommandBufferInfo *p_command_buffer) {
  621. for (const KeyValue<ResourceInfo::States *, BarrierRequest> &E : p_command_buffer->res_barriers_requests) {
  622. ResourceInfo::States *res_states = E.key;
  623. const BarrierRequest &br = E.value;
  624. uint32_t num_subresources = res_states->subresource_states.size();
  625. // When there's not a lot of subresources, the empirical finding is that it's better
  626. // to avoid attempting the single-barrier optimization.
  627. static const uint32_t SINGLE_BARRIER_ATTEMPT_MAX_NUM_SUBRESOURCES = 48;
  628. bool may_do_single_barrier = br.groups_count == 1 && num_subresources * br.planes >= SINGLE_BARRIER_ATTEMPT_MAX_NUM_SUBRESOURCES;
  629. if (may_do_single_barrier) {
  630. // A single group means we may be able to do a single all-subresources barrier.
  631. {
  632. // First requisite is that all subresources are involved.
  633. uint8_t subres_mask_full_qwords = num_subresources / 64;
  634. for (uint32_t i = 0; i < subres_mask_full_qwords; i++) {
  635. if (br.groups[0].subres_mask[i] != UINT64_MAX) {
  636. may_do_single_barrier = false;
  637. break;
  638. }
  639. }
  640. if (may_do_single_barrier) {
  641. if (num_subresources % 64) {
  642. DEV_ASSERT(br.subres_mask_qwords == subres_mask_full_qwords + 1);
  643. uint64_t mask_tail_qword = 0;
  644. for (uint8_t i = 0; i < num_subresources % 64; i++) {
  645. mask_tail_qword |= ((uint64_t)1 << i);
  646. }
  647. if ((br.groups[0].subres_mask[subres_mask_full_qwords] & mask_tail_qword) != mask_tail_qword) {
  648. may_do_single_barrier = false;
  649. }
  650. }
  651. }
  652. }
  653. if (may_do_single_barrier) {
  654. // Second requisite is that the source state is the same for all.
  655. for (uint32_t i = 1; i < num_subresources; i++) {
  656. if (res_states->subresource_states[i] != res_states->subresource_states[0]) {
  657. may_do_single_barrier = false;
  658. break;
  659. }
  660. }
  661. if (may_do_single_barrier) {
  662. // Hurray!, we can do a single barrier (plus maybe a UAV one, too).
  663. bool just_written = res_states->subresource_states[0] == D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  664. bool needs_uav_barrier = just_written && res_states->last_batch_with_uav_barrier != p_command_buffer->res_barriers_batch;
  665. uint32_t needed_barriers = (needs_uav_barrier ? 1 : 0) + 1;
  666. if (p_command_buffer->res_barriers.size() < p_command_buffer->res_barriers_count + needed_barriers) {
  667. p_command_buffer->res_barriers.resize(p_command_buffer->res_barriers_count + needed_barriers);
  668. }
  669. if (needs_uav_barrier) {
  670. p_command_buffer->res_barriers[p_command_buffer->res_barriers_count] = CD3DX12_RESOURCE_BARRIER::UAV(br.dx_resource);
  671. p_command_buffer->res_barriers_count++;
  672. res_states->last_batch_with_uav_barrier = p_command_buffer->res_barriers_batch;
  673. }
  674. if (res_states->subresource_states[0] != br.groups[0].states) {
  675. p_command_buffer->res_barriers[p_command_buffer->res_barriers_count] = CD3DX12_RESOURCE_BARRIER::Transition(br.dx_resource, res_states->subresource_states[0], br.groups[0].states, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES);
  676. p_command_buffer->res_barriers_count++;
  677. }
  678. for (uint32_t i = 0; i < num_subresources; i++) {
  679. res_states->subresource_states[i] = br.groups[0].states;
  680. }
  681. }
  682. }
  683. }
  684. if (!may_do_single_barrier) {
  685. for (uint8_t i = 0; i < br.groups_count; i++) {
  686. const BarrierRequest::Group &g = E.value.groups[i];
  687. if (unlikely(g.states == BarrierRequest::DELETED_GROUP)) {
  688. continue;
  689. }
  690. uint32_t subresource = 0;
  691. do {
  692. uint64_t subres_mask_piece = ((uint64_t)1 << (subresource % 64));
  693. uint8_t subres_qword = subresource / 64;
  694. if (likely(g.subres_mask[subres_qword] == 0)) {
  695. subresource += 64;
  696. continue;
  697. }
  698. if (likely(!(g.subres_mask[subres_qword] & subres_mask_piece))) {
  699. subresource++;
  700. continue;
  701. }
  702. D3D12_RESOURCE_STATES *curr_state = &res_states->subresource_states[subresource];
  703. bool just_written = *curr_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  704. bool needs_uav_barrier = just_written && res_states->last_batch_with_uav_barrier != p_command_buffer->res_barriers_batch;
  705. uint32_t needed_barriers = (needs_uav_barrier ? 1 : 0) + br.planes;
  706. if (p_command_buffer->res_barriers.size() < p_command_buffer->res_barriers_count + needed_barriers) {
  707. p_command_buffer->res_barriers.resize(p_command_buffer->res_barriers_count + needed_barriers);
  708. }
  709. if (needs_uav_barrier) {
  710. p_command_buffer->res_barriers[p_command_buffer->res_barriers_count] = CD3DX12_RESOURCE_BARRIER::UAV(br.dx_resource);
  711. p_command_buffer->res_barriers_count++;
  712. res_states->last_batch_with_uav_barrier = p_command_buffer->res_barriers_batch;
  713. }
  714. if (*curr_state != g.states) {
  715. for (uint8_t k = 0; k < br.planes; k++) {
  716. p_command_buffer->res_barriers[p_command_buffer->res_barriers_count] = CD3DX12_RESOURCE_BARRIER::Transition(br.dx_resource, *curr_state, g.states, subresource + k * num_subresources);
  717. p_command_buffer->res_barriers_count++;
  718. }
  719. }
  720. *curr_state = g.states;
  721. subresource++;
  722. } while (subresource < num_subresources);
  723. }
  724. }
  725. }
  726. if (p_command_buffer->res_barriers_count) {
  727. p_command_buffer->cmd_list->ResourceBarrier(p_command_buffer->res_barriers_count, p_command_buffer->res_barriers.ptr());
  728. p_command_buffer->res_barriers_requests.clear();
  729. }
  730. p_command_buffer->res_barriers_count = 0;
  731. p_command_buffer->res_barriers_batch++;
  732. }
  733. /*****************/
  734. /**** BUFFERS ****/
  735. /*****************/
  736. RDD::BufferID RenderingDeviceDriverD3D12::buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) {
  737. // D3D12 debug layers complain at CBV creation time if the size is not multiple of the value per the spec
  738. // but also if you give a rounded size at that point because it will extend beyond the
  739. // memory of the resource. Therefore, it seems the only way is to create it with a
  740. // rounded size.
  741. CD3DX12_RESOURCE_DESC1 resource_desc = CD3DX12_RESOURCE_DESC1::Buffer(STEPIFY(p_size, D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT));
  742. if (p_usage.has_flag(RDD::BUFFER_USAGE_STORAGE_BIT)) {
  743. resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  744. } else {
  745. resource_desc.Flags |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE;
  746. }
  747. D3D12MA::ALLOCATION_DESC allocation_desc = {};
  748. allocation_desc.HeapType = D3D12_HEAP_TYPE_DEFAULT;
  749. D3D12_RESOURCE_STATES initial_state = D3D12_RESOURCE_STATE_COMMON;
  750. switch (p_allocation_type) {
  751. case MEMORY_ALLOCATION_TYPE_CPU: {
  752. bool is_src = p_usage.has_flag(BUFFER_USAGE_TRANSFER_FROM_BIT);
  753. bool is_dst = p_usage.has_flag(BUFFER_USAGE_TRANSFER_TO_BIT);
  754. if (is_src && !is_dst) {
  755. // Looks like a staging buffer: CPU maps, writes sequentially, then GPU copies to VRAM.
  756. allocation_desc.HeapType = D3D12_HEAP_TYPE_UPLOAD;
  757. initial_state = D3D12_RESOURCE_STATE_GENERIC_READ;
  758. }
  759. if (is_dst && !is_src) {
  760. // Looks like a readback buffer: GPU copies from VRAM, then CPU maps and reads.
  761. allocation_desc.HeapType = D3D12_HEAP_TYPE_READBACK;
  762. initial_state = D3D12_RESOURCE_STATE_COPY_DEST;
  763. }
  764. } break;
  765. case MEMORY_ALLOCATION_TYPE_GPU: {
  766. // Use default parameters.
  767. } break;
  768. }
  769. ComPtr<ID3D12Resource> buffer;
  770. ComPtr<D3D12MA::Allocation> allocation;
  771. HRESULT res;
  772. if (barrier_capabilities.enhanced_barriers_supported) {
  773. res = allocator->CreateResource3(
  774. &allocation_desc,
  775. &resource_desc,
  776. D3D12_BARRIER_LAYOUT_UNDEFINED,
  777. nullptr,
  778. 0,
  779. nullptr,
  780. allocation.GetAddressOf(),
  781. IID_PPV_ARGS(buffer.GetAddressOf()));
  782. } else {
  783. res = allocator->CreateResource(
  784. &allocation_desc,
  785. reinterpret_cast<const D3D12_RESOURCE_DESC *>(&resource_desc),
  786. initial_state,
  787. nullptr,
  788. allocation.GetAddressOf(),
  789. IID_PPV_ARGS(buffer.GetAddressOf()));
  790. }
  791. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), BufferID(), "Can't create buffer of size: " + itos(p_size) + ", error " + vformat("0x%08ux", (uint64_t)res) + ".");
  792. // Bookkeep.
  793. BufferInfo *buf_info = VersatileResource::allocate<BufferInfo>(resources_allocator);
  794. buf_info->resource = buffer.Get();
  795. buf_info->owner_info.resource = buffer;
  796. buf_info->owner_info.allocation = allocation;
  797. buf_info->owner_info.states.subresource_states.push_back(initial_state);
  798. buf_info->states_ptr = &buf_info->owner_info.states;
  799. buf_info->size = p_size;
  800. buf_info->flags.usable_as_uav = (resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
  801. return BufferID(buf_info);
  802. }
  803. bool RenderingDeviceDriverD3D12::buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) {
  804. BufferInfo *buf_info = (BufferInfo *)p_buffer.id;
  805. buf_info->texel_format = p_format;
  806. return true;
  807. }
  808. void RenderingDeviceDriverD3D12::buffer_free(BufferID p_buffer) {
  809. BufferInfo *buf_info = (BufferInfo *)p_buffer.id;
  810. VersatileResource::free(resources_allocator, buf_info);
  811. }
  812. uint64_t RenderingDeviceDriverD3D12::buffer_get_allocation_size(BufferID p_buffer) {
  813. const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;
  814. return buf_info->owner_info.allocation ? buf_info->owner_info.allocation->GetSize() : 0;
  815. }
  816. uint8_t *RenderingDeviceDriverD3D12::buffer_map(BufferID p_buffer) {
  817. const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;
  818. void *data_ptr = nullptr;
  819. HRESULT res = buf_info->resource->Map(0, &VOID_RANGE, &data_ptr);
  820. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), nullptr, "Map failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  821. return (uint8_t *)data_ptr;
  822. }
  823. void RenderingDeviceDriverD3D12::buffer_unmap(BufferID p_buffer) {
  824. const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;
  825. buf_info->resource->Unmap(0, &VOID_RANGE);
  826. }
  827. /*****************/
  828. /**** TEXTURE ****/
  829. /*****************/
  830. static const D3D12_SRV_DIMENSION RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_SRV[RD::TEXTURE_TYPE_MAX] = {
  831. D3D12_SRV_DIMENSION_TEXTURE1D,
  832. D3D12_SRV_DIMENSION_TEXTURE2D,
  833. D3D12_SRV_DIMENSION_TEXTURE3D,
  834. D3D12_SRV_DIMENSION_TEXTURECUBE,
  835. D3D12_SRV_DIMENSION_TEXTURE1DARRAY,
  836. D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  837. D3D12_SRV_DIMENSION_TEXTURECUBEARRAY,
  838. };
  839. static const D3D12_SRV_DIMENSION RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_SRV_MS[RD::TEXTURE_TYPE_MAX] = {
  840. D3D12_SRV_DIMENSION_UNKNOWN,
  841. D3D12_SRV_DIMENSION_TEXTURE2DMS,
  842. D3D12_SRV_DIMENSION_UNKNOWN,
  843. D3D12_SRV_DIMENSION_UNKNOWN,
  844. D3D12_SRV_DIMENSION_UNKNOWN,
  845. D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY,
  846. D3D12_SRV_DIMENSION_UNKNOWN,
  847. };
  848. static const D3D12_UAV_DIMENSION RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_UAV[RD::TEXTURE_TYPE_MAX] = {
  849. D3D12_UAV_DIMENSION_TEXTURE1D,
  850. D3D12_UAV_DIMENSION_TEXTURE2D,
  851. D3D12_UAV_DIMENSION_TEXTURE3D,
  852. D3D12_UAV_DIMENSION_TEXTURE2DARRAY,
  853. D3D12_UAV_DIMENSION_TEXTURE1DARRAY,
  854. D3D12_UAV_DIMENSION_TEXTURE2DARRAY,
  855. D3D12_UAV_DIMENSION_TEXTURE2DARRAY,
  856. };
  857. uint32_t RenderingDeviceDriverD3D12::_find_max_common_supported_sample_count(VectorView<DXGI_FORMAT> p_formats) {
  858. uint32_t common = UINT32_MAX;
  859. MutexLock lock(format_sample_counts_mask_cache_mutex);
  860. for (uint32_t i = 0; i < p_formats.size(); i++) {
  861. if (format_sample_counts_mask_cache.has(p_formats[i])) {
  862. common &= format_sample_counts_mask_cache[p_formats[i]];
  863. } else {
  864. D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msql = {};
  865. msql.Format = p_formats[i];
  866. uint32_t mask = 0;
  867. for (int samples = 1 << (TEXTURE_SAMPLES_MAX - 1); samples >= 1; samples /= 2) {
  868. msql.SampleCount = (UINT)samples;
  869. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &msql, sizeof(msql));
  870. if (SUCCEEDED(res) && msql.NumQualityLevels) {
  871. int bit = get_shift_from_power_of_2(samples);
  872. ERR_FAIL_COND_V(bit == -1, 1);
  873. mask |= (uint32_t)(1 << bit);
  874. }
  875. }
  876. format_sample_counts_mask_cache.insert(p_formats[i], mask);
  877. common &= mask;
  878. }
  879. }
  880. if (common == UINT32_MAX) {
  881. return 1;
  882. } else {
  883. return ((uint32_t)1 << nearest_shift(common));
  884. }
  885. }
  886. UINT RenderingDeviceDriverD3D12::_compute_component_mapping(const RDD::TextureView &p_view) {
  887. UINT base_swizzle = RD_TO_D3D12_FORMAT[p_view.format].swizzle;
  888. D3D12_SHADER_COMPONENT_MAPPING component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  889. D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, // Unused.
  890. D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0,
  891. D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1,
  892. // These will be D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_*.
  893. D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(0, base_swizzle),
  894. D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(1, base_swizzle),
  895. D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(2, base_swizzle),
  896. D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(3, base_swizzle),
  897. };
  898. return D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(
  899. p_view.swizzle_r == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_R] : component_swizzles[p_view.swizzle_r],
  900. p_view.swizzle_g == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_G] : component_swizzles[p_view.swizzle_g],
  901. p_view.swizzle_b == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_B] : component_swizzles[p_view.swizzle_b],
  902. p_view.swizzle_a == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_A] : component_swizzles[p_view.swizzle_a]);
  903. }
  904. UINT RenderingDeviceDriverD3D12::_compute_plane_slice(DataFormat p_format, BitField<TextureAspectBits> p_aspect_bits) {
  905. TextureAspect aspect = TEXTURE_ASPECT_MAX;
  906. if (p_aspect_bits.has_flag(TEXTURE_ASPECT_COLOR_BIT)) {
  907. DEV_ASSERT(aspect == TEXTURE_ASPECT_MAX);
  908. aspect = TEXTURE_ASPECT_COLOR;
  909. }
  910. if (p_aspect_bits.has_flag(TEXTURE_ASPECT_DEPTH_BIT)) {
  911. DEV_ASSERT(aspect == TEXTURE_ASPECT_MAX);
  912. aspect = TEXTURE_ASPECT_DEPTH;
  913. } else if (p_aspect_bits.has_flag(TEXTURE_ASPECT_STENCIL_BIT)) {
  914. DEV_ASSERT(aspect == TEXTURE_ASPECT_MAX);
  915. aspect = TEXTURE_ASPECT_STENCIL;
  916. }
  917. DEV_ASSERT(aspect != TEXTURE_ASPECT_MAX);
  918. return _compute_plane_slice(p_format, aspect);
  919. }
  920. UINT RenderingDeviceDriverD3D12::_compute_plane_slice(DataFormat p_format, TextureAspect p_aspect) {
  921. switch (p_aspect) {
  922. case TEXTURE_ASPECT_COLOR:
  923. // The plane must be 0 for the color aspect (assuming the format is a regular color one, which must be the case).
  924. return 0;
  925. case TEXTURE_ASPECT_DEPTH:
  926. // The plane must be 0 for the color or depth aspect
  927. return 0;
  928. case TEXTURE_ASPECT_STENCIL:
  929. // The plane may be 0 for the stencil aspect (if the format is stencil-only), or 1 (if the format is depth-stencil; other cases are ill).
  930. return format_get_plane_count(p_format) == 2 ? 1 : 0;
  931. default:
  932. DEV_ASSERT(false);
  933. return 0;
  934. }
  935. }
  936. UINT RenderingDeviceDriverD3D12::_compute_subresource_from_layers(TextureInfo *p_texture, const TextureSubresourceLayers &p_layers, uint32_t p_layer_offset) {
  937. return D3D12CalcSubresource(p_layers.mipmap, p_layers.base_layer + p_layer_offset, _compute_plane_slice(p_texture->format, p_layers.aspect), p_texture->desc.MipLevels, p_texture->desc.ArraySize());
  938. }
  939. void RenderingDeviceDriverD3D12::_discard_texture_subresources(const TextureInfo *p_tex_info, const CommandBufferInfo *p_cmd_buf_info) {
  940. uint32_t planes = 1;
  941. if ((p_tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  942. planes = format_get_plane_count(p_tex_info->format);
  943. }
  944. D3D12_DISCARD_REGION dr = {};
  945. dr.NumRects = p_cmd_buf_info->render_pass_state.region_is_all ? 0 : 1;
  946. dr.pRects = p_cmd_buf_info->render_pass_state.region_is_all ? nullptr : &p_cmd_buf_info->render_pass_state.region_rect;
  947. dr.FirstSubresource = UINT_MAX;
  948. dr.NumSubresources = 0;
  949. for (uint32_t u = 0; u < planes; u++) {
  950. for (uint32_t v = 0; v < p_tex_info->layers; v++) {
  951. for (uint32_t w = 0; w < p_tex_info->mipmaps; w++) {
  952. UINT subresource = D3D12CalcSubresource(
  953. p_tex_info->base_mip + w,
  954. p_tex_info->base_layer + v,
  955. u,
  956. p_tex_info->desc.MipLevels,
  957. p_tex_info->desc.ArraySize());
  958. if (dr.NumSubresources == 0) {
  959. dr.FirstSubresource = subresource;
  960. dr.NumSubresources = 1;
  961. } else if (dr.FirstSubresource + dr.NumSubresources == subresource) {
  962. dr.NumSubresources++;
  963. } else {
  964. p_cmd_buf_info->cmd_list->DiscardResource(p_tex_info->resource, &dr);
  965. dr.FirstSubresource = subresource;
  966. dr.NumSubresources = 1;
  967. }
  968. }
  969. }
  970. }
  971. if (dr.NumSubresources) {
  972. p_cmd_buf_info->cmd_list->DiscardResource(p_tex_info->resource, &dr);
  973. }
  974. }
  975. bool RenderingDeviceDriverD3D12::_unordered_access_supported_by_format(DataFormat p_format) {
  976. switch (p_format) {
  977. case DATA_FORMAT_R4G4_UNORM_PACK8:
  978. case DATA_FORMAT_R4G4B4A4_UNORM_PACK16:
  979. case DATA_FORMAT_B4G4R4A4_UNORM_PACK16:
  980. case DATA_FORMAT_R5G6B5_UNORM_PACK16:
  981. case DATA_FORMAT_B5G6R5_UNORM_PACK16:
  982. case DATA_FORMAT_R5G5B5A1_UNORM_PACK16:
  983. case DATA_FORMAT_B5G5R5A1_UNORM_PACK16:
  984. case DATA_FORMAT_A1R5G5B5_UNORM_PACK16:
  985. case DATA_FORMAT_A8B8G8R8_UNORM_PACK32:
  986. case DATA_FORMAT_A8B8G8R8_SNORM_PACK32:
  987. case DATA_FORMAT_A8B8G8R8_USCALED_PACK32:
  988. case DATA_FORMAT_A8B8G8R8_SSCALED_PACK32:
  989. case DATA_FORMAT_A8B8G8R8_UINT_PACK32:
  990. case DATA_FORMAT_A8B8G8R8_SINT_PACK32:
  991. case DATA_FORMAT_A8B8G8R8_SRGB_PACK32:
  992. case DATA_FORMAT_A2R10G10B10_UNORM_PACK32:
  993. case DATA_FORMAT_A2R10G10B10_SNORM_PACK32:
  994. case DATA_FORMAT_A2R10G10B10_USCALED_PACK32:
  995. case DATA_FORMAT_A2R10G10B10_SSCALED_PACK32:
  996. case DATA_FORMAT_A2R10G10B10_UINT_PACK32:
  997. case DATA_FORMAT_A2R10G10B10_SINT_PACK32:
  998. case DATA_FORMAT_A2B10G10R10_UNORM_PACK32:
  999. case DATA_FORMAT_A2B10G10R10_SNORM_PACK32:
  1000. case DATA_FORMAT_A2B10G10R10_USCALED_PACK32:
  1001. case DATA_FORMAT_A2B10G10R10_SSCALED_PACK32:
  1002. case DATA_FORMAT_A2B10G10R10_UINT_PACK32:
  1003. case DATA_FORMAT_A2B10G10R10_SINT_PACK32:
  1004. case DATA_FORMAT_B10G11R11_UFLOAT_PACK32:
  1005. case DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32:
  1006. case DATA_FORMAT_X8_D24_UNORM_PACK32:
  1007. case DATA_FORMAT_R10X6_UNORM_PACK16:
  1008. case DATA_FORMAT_R10X6G10X6_UNORM_2PACK16:
  1009. case DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
  1010. case DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16:
  1011. case DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16:
  1012. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16:
  1013. case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16:
  1014. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16:
  1015. case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16:
  1016. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16:
  1017. case DATA_FORMAT_R12X4_UNORM_PACK16:
  1018. case DATA_FORMAT_R12X4G12X4_UNORM_2PACK16:
  1019. case DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16:
  1020. case DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16:
  1021. case DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16:
  1022. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16:
  1023. case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16:
  1024. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16:
  1025. case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16:
  1026. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16:
  1027. return false;
  1028. default:
  1029. return true;
  1030. }
  1031. }
  1032. RDD::TextureID RenderingDeviceDriverD3D12::texture_create(const TextureFormat &p_format, const TextureView &p_view) {
  1033. // Using D3D12_RESOURCE_DESC1. Thanks to the layout, it's sliceable down to D3D12_RESOURCE_DESC if needed.
  1034. CD3DX12_RESOURCE_DESC1 resource_desc = {};
  1035. resource_desc.Dimension = RD_TEXTURE_TYPE_TO_D3D12_RESOURCE_DIMENSION[p_format.texture_type];
  1036. resource_desc.Alignment = 0; // D3D12MA will override this to use a smaller alignment than the default if possible.
  1037. resource_desc.Width = p_format.width;
  1038. resource_desc.Height = p_format.height;
  1039. resource_desc.DepthOrArraySize = p_format.depth * p_format.array_layers;
  1040. resource_desc.MipLevels = p_format.mipmaps;
  1041. // Format.
  1042. bool cross_family_sharing = false;
  1043. bool relaxed_casting_available = false;
  1044. DXGI_FORMAT *relaxed_casting_formats = nullptr;
  1045. uint32_t relaxed_casting_format_count = 0;
  1046. {
  1047. resource_desc.Format = RD_TO_D3D12_FORMAT[p_format.format].family;
  1048. // If views of different families are wanted, special setup is needed for proper sharing among them.
  1049. // If the driver reports relaxed casting is, leverage its new extended resource creation API (via D3D12MA).
  1050. if (p_format.shareable_formats.size() && format_capabilities.relaxed_casting_supported) {
  1051. relaxed_casting_available = true;
  1052. relaxed_casting_formats = ALLOCA_ARRAY(DXGI_FORMAT, p_format.shareable_formats.size() + 1);
  1053. relaxed_casting_formats[0] = RD_TO_D3D12_FORMAT[p_format.format].general_format;
  1054. relaxed_casting_format_count++;
  1055. }
  1056. HashMap<DataFormat, D3D12_RESOURCE_FLAGS> aliases_forbidden_flags;
  1057. for (int i = 0; i < p_format.shareable_formats.size(); i++) {
  1058. DataFormat curr_format = p_format.shareable_formats[i];
  1059. String format_text = "'" + String(FORMAT_NAMES[p_format.format]) + "'";
  1060. ERR_FAIL_COND_V_MSG(RD_TO_D3D12_FORMAT[curr_format].family == DXGI_FORMAT_UNKNOWN, TextureID(), "Format " + format_text + " is not supported.");
  1061. if (RD_TO_D3D12_FORMAT[curr_format].family != RD_TO_D3D12_FORMAT[p_format.format].family) {
  1062. cross_family_sharing = true;
  1063. }
  1064. if (relaxed_casting_available) {
  1065. relaxed_casting_formats[relaxed_casting_format_count] = RD_TO_D3D12_FORMAT[curr_format].general_format;
  1066. relaxed_casting_format_count++;
  1067. }
  1068. }
  1069. if (cross_family_sharing && !relaxed_casting_available) {
  1070. // Per https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout.
  1071. if (p_format.texture_type == TEXTURE_TYPE_1D) {
  1072. ERR_FAIL_V_MSG(TextureID(), "This texture's views require aliasing, but that's not supported for a 1D texture.");
  1073. }
  1074. if (p_format.samples != TEXTURE_SAMPLES_1) {
  1075. ERR_FAIL_V_MSG(TextureID(), "This texture's views require aliasing, but that's not supported for a multi-sample texture.");
  1076. }
  1077. if ((p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  1078. ERR_FAIL_V_MSG(TextureID(), "This texture's views require aliasing, but that's not supported for a depth-stencil texture.");
  1079. }
  1080. if (RD_TO_D3D12_FORMAT[p_format.format].family == DXGI_FORMAT_R32G32B32_TYPELESS) {
  1081. ERR_FAIL_V_MSG(TextureID(), "This texture's views require aliasing, but that's not supported for an R32G32B32 texture.");
  1082. }
  1083. }
  1084. }
  1085. // Usage.
  1086. if ((p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  1087. resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
  1088. } else {
  1089. if ((p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_TO_BIT) && _unordered_access_supported_by_format(p_format.format)) {
  1090. resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // For clearing via UAV.
  1091. }
  1092. }
  1093. if ((p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  1094. resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
  1095. }
  1096. if ((p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT)) {
  1097. resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  1098. }
  1099. if ((p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) {
  1100. // For VRS images we can't use the typeless format.
  1101. resource_desc.Format = DXGI_FORMAT_R8_UINT;
  1102. }
  1103. resource_desc.SampleDesc = {};
  1104. DXGI_FORMAT format_to_test = (resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ? RD_TO_D3D12_FORMAT[p_format.format].dsv_format : RD_TO_D3D12_FORMAT[p_format.format].general_format;
  1105. if (!(resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
  1106. resource_desc.SampleDesc.Count = MIN(
  1107. _find_max_common_supported_sample_count(format_to_test),
  1108. TEXTURE_SAMPLES_COUNT[p_format.samples]);
  1109. } else {
  1110. // No MSAA in D3D12 if storage. May have become possible recently where supported, though.
  1111. resource_desc.SampleDesc.Count = 1;
  1112. }
  1113. resource_desc.SampleDesc.Quality = resource_desc.SampleDesc.Count == 1 ? 0 : DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
  1114. // Create.
  1115. D3D12MA::ALLOCATION_DESC allocation_desc = {};
  1116. allocation_desc.HeapType = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? D3D12_HEAP_TYPE_READBACK : D3D12_HEAP_TYPE_DEFAULT;
  1117. if ((resource_desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))) {
  1118. allocation_desc.ExtraHeapFlags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;
  1119. } else {
  1120. allocation_desc.ExtraHeapFlags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
  1121. }
  1122. if ((resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
  1123. allocation_desc.ExtraHeapFlags |= D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS;
  1124. }
  1125. D3D12_RESOURCE_STATES initial_state = {};
  1126. ID3D12Resource *texture = nullptr;
  1127. ComPtr<ID3D12Resource> main_texture;
  1128. ComPtr<D3D12MA::Allocation> allocation;
  1129. static const FLOAT black[4] = {};
  1130. D3D12_CLEAR_VALUE clear_value = CD3DX12_CLEAR_VALUE(RD_TO_D3D12_FORMAT[p_format.format].general_format, black);
  1131. D3D12_CLEAR_VALUE *clear_value_ptr = (resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) ? &clear_value : nullptr;
  1132. {
  1133. HRESULT res = E_FAIL;
  1134. if (barrier_capabilities.enhanced_barriers_supported || (cross_family_sharing && relaxed_casting_available)) {
  1135. // Create with undefined layout if enhanced barriers are supported. Leave as common otherwise for interop with legacy barriers.
  1136. D3D12_BARRIER_LAYOUT initial_layout = barrier_capabilities.enhanced_barriers_supported ? D3D12_BARRIER_LAYOUT_UNDEFINED : D3D12_BARRIER_LAYOUT_COMMON;
  1137. res = allocator->CreateResource3(
  1138. &allocation_desc,
  1139. &resource_desc,
  1140. initial_layout,
  1141. clear_value_ptr,
  1142. relaxed_casting_format_count,
  1143. relaxed_casting_formats,
  1144. allocation.GetAddressOf(),
  1145. IID_PPV_ARGS(main_texture.GetAddressOf()));
  1146. initial_state = D3D12_RESOURCE_STATE_COMMON;
  1147. } else {
  1148. res = allocator->CreateResource(
  1149. &allocation_desc,
  1150. (D3D12_RESOURCE_DESC *)&resource_desc,
  1151. D3D12_RESOURCE_STATE_COPY_DEST,
  1152. clear_value_ptr,
  1153. allocation.GetAddressOf(),
  1154. IID_PPV_ARGS(main_texture.GetAddressOf()));
  1155. initial_state = D3D12_RESOURCE_STATE_COPY_DEST;
  1156. }
  1157. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), TextureID(), "CreateResource failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  1158. texture = main_texture.Get();
  1159. }
  1160. // Describe views.
  1161. D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc = {};
  1162. {
  1163. srv_desc.Format = RD_TO_D3D12_FORMAT[p_view.format].general_format;
  1164. srv_desc.ViewDimension = p_format.samples == TEXTURE_SAMPLES_1 ? RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_SRV[p_format.texture_type] : RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_SRV_MS[p_format.texture_type];
  1165. srv_desc.Shader4ComponentMapping = _compute_component_mapping(p_view);
  1166. switch (srv_desc.ViewDimension) {
  1167. case D3D12_SRV_DIMENSION_TEXTURE1D: {
  1168. srv_desc.Texture1D.MipLevels = p_format.mipmaps;
  1169. } break;
  1170. case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: {
  1171. srv_desc.Texture1DArray.MipLevels = p_format.mipmaps;
  1172. srv_desc.Texture1DArray.ArraySize = p_format.array_layers;
  1173. } break;
  1174. case D3D12_SRV_DIMENSION_TEXTURE2D: {
  1175. srv_desc.Texture2D.MipLevels = p_format.mipmaps;
  1176. } break;
  1177. case D3D12_SRV_DIMENSION_TEXTURE2DMS: {
  1178. } break;
  1179. case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: {
  1180. srv_desc.Texture2DArray.MipLevels = p_format.mipmaps;
  1181. srv_desc.Texture2DArray.ArraySize = p_format.array_layers;
  1182. } break;
  1183. case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: {
  1184. srv_desc.Texture2DMSArray.ArraySize = p_format.array_layers;
  1185. } break;
  1186. case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: {
  1187. srv_desc.TextureCubeArray.MipLevels = p_format.mipmaps;
  1188. srv_desc.TextureCubeArray.NumCubes = p_format.array_layers / 6;
  1189. } break;
  1190. case D3D12_SRV_DIMENSION_TEXTURE3D: {
  1191. srv_desc.Texture3D.MipLevels = p_format.mipmaps;
  1192. } break;
  1193. case D3D12_SRV_DIMENSION_TEXTURECUBE: {
  1194. srv_desc.TextureCube.MipLevels = p_format.mipmaps;
  1195. } break;
  1196. default: {
  1197. }
  1198. }
  1199. }
  1200. D3D12_UNORDERED_ACCESS_VIEW_DESC main_uav_desc = {};
  1201. {
  1202. main_uav_desc.Format = RD_TO_D3D12_FORMAT[p_format.format].general_format;
  1203. main_uav_desc.ViewDimension = p_format.samples == TEXTURE_SAMPLES_1 ? RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_UAV[p_format.texture_type] : D3D12_UAV_DIMENSION_UNKNOWN;
  1204. switch (main_uav_desc.ViewDimension) {
  1205. case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: {
  1206. main_uav_desc.Texture1DArray.ArraySize = p_format.array_layers;
  1207. } break;
  1208. case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: {
  1209. // Either for an actual 2D texture array, cubemap or cubemap array.
  1210. main_uav_desc.Texture2DArray.ArraySize = p_format.array_layers;
  1211. } break;
  1212. case D3D12_UAV_DIMENSION_TEXTURE3D: {
  1213. main_uav_desc.Texture3D.WSize = p_format.depth;
  1214. } break;
  1215. default: {
  1216. }
  1217. }
  1218. }
  1219. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = main_uav_desc;
  1220. uav_desc.Format = RD_TO_D3D12_FORMAT[p_view.format].general_format;
  1221. // Bookkeep.
  1222. TextureInfo *tex_info = VersatileResource::allocate<TextureInfo>(resources_allocator);
  1223. tex_info->resource = texture;
  1224. tex_info->owner_info.resource = main_texture;
  1225. tex_info->owner_info.allocation = allocation;
  1226. tex_info->owner_info.states.subresource_states.resize(p_format.mipmaps * p_format.array_layers);
  1227. for (uint32_t i = 0; i < tex_info->owner_info.states.subresource_states.size(); i++) {
  1228. tex_info->owner_info.states.subresource_states[i] = initial_state;
  1229. }
  1230. tex_info->states_ptr = &tex_info->owner_info.states;
  1231. tex_info->format = p_format.format;
  1232. #if defined(__GNUC__) && !defined(__clang__)
  1233. #pragma GCC diagnostic push
  1234. #pragma GCC diagnostic ignored "-Wstrict-aliasing"
  1235. #endif
  1236. tex_info->desc = *(CD3DX12_RESOURCE_DESC *)&resource_desc;
  1237. #if defined(__GNUC__) && !defined(__clang__)
  1238. #pragma GCC diagnostic pop
  1239. #endif
  1240. tex_info->base_layer = 0;
  1241. tex_info->layers = resource_desc.ArraySize();
  1242. tex_info->base_mip = 0;
  1243. tex_info->mipmaps = resource_desc.MipLevels;
  1244. tex_info->view_descs.srv = srv_desc;
  1245. tex_info->view_descs.uav = uav_desc;
  1246. if (!barrier_capabilities.enhanced_barriers_supported && (p_format.usage_bits & (TEXTURE_USAGE_STORAGE_BIT | TEXTURE_USAGE_COLOR_ATTACHMENT_BIT))) {
  1247. // Fallback to clear resources when they're first used in a uniform set. Not necessary if enhanced barriers
  1248. // are supported, as the discard flag will be used instead when transitioning from an undefined layout.
  1249. textures_pending_clear.add(&tex_info->pending_clear);
  1250. }
  1251. return TextureID(tex_info);
  1252. }
  1253. RDD::TextureID RenderingDeviceDriverD3D12::texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil) {
  1254. ERR_FAIL_V_MSG(TextureID(), "Unimplemented!");
  1255. }
  1256. RDD::TextureID RenderingDeviceDriverD3D12::texture_create_shared(TextureID p_original_texture, const TextureView &p_view) {
  1257. return _texture_create_shared_from_slice(p_original_texture, p_view, (TextureSliceType)-1, 0, 0, 0, 0);
  1258. }
  1259. RDD::TextureID RenderingDeviceDriverD3D12::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) {
  1260. return _texture_create_shared_from_slice(p_original_texture, p_view, p_slice_type, p_layer, p_layers, p_mipmap, p_mipmaps);
  1261. }
  1262. RDD::TextureID RenderingDeviceDriverD3D12::_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) {
  1263. TextureInfo *owner_tex_info = (TextureInfo *)p_original_texture.id;
  1264. #ifdef DEBUG_ENABLED
  1265. ERR_FAIL_COND_V(!owner_tex_info->owner_info.allocation, TextureID());
  1266. #endif
  1267. ComPtr<ID3D12Resource> new_texture;
  1268. ComPtr<D3D12MA::Allocation> new_allocation;
  1269. ID3D12Resource *resource = owner_tex_info->resource;
  1270. CD3DX12_RESOURCE_DESC new_tex_resource_desc = owner_tex_info->desc;
  1271. // Describe views.
  1272. D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc = owner_tex_info->view_descs.srv;
  1273. {
  1274. srv_desc.Format = RD_TO_D3D12_FORMAT[p_view.format].general_format;
  1275. srv_desc.Shader4ComponentMapping = _compute_component_mapping(p_view);
  1276. }
  1277. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = owner_tex_info->view_descs.uav;
  1278. {
  1279. uav_desc.Format = RD_TO_D3D12_FORMAT[p_view.format].general_format;
  1280. }
  1281. if (p_slice_type != (TextureSliceType)-1) {
  1282. // Complete description with slicing.
  1283. switch (p_slice_type) {
  1284. case TEXTURE_SLICE_2D: {
  1285. if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D && p_layer == 0) {
  1286. srv_desc.Texture2D.MostDetailedMip = p_mipmap;
  1287. srv_desc.Texture2D.MipLevels = p_mipmaps;
  1288. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2D);
  1289. uav_desc.Texture1D.MipSlice = p_mipmap;
  1290. } else if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMS && p_layer == 0) {
  1291. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_UNKNOWN);
  1292. } else if ((srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY || (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D && p_layer)) || srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE || srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBEARRAY) {
  1293. srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
  1294. srv_desc.Texture2DArray.MostDetailedMip = p_mipmap;
  1295. srv_desc.Texture2DArray.MipLevels = p_mipmaps;
  1296. srv_desc.Texture2DArray.FirstArraySlice = p_layer;
  1297. srv_desc.Texture2DArray.ArraySize = 1;
  1298. srv_desc.Texture2DArray.PlaneSlice = 0;
  1299. srv_desc.Texture2DArray.ResourceMinLODClamp = 0.0f;
  1300. uav_desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
  1301. uav_desc.Texture2DArray.MipSlice = p_mipmap;
  1302. uav_desc.Texture2DArray.FirstArraySlice = p_layer;
  1303. uav_desc.Texture2DArray.ArraySize = 1;
  1304. uav_desc.Texture2DArray.PlaneSlice = 0;
  1305. } else if ((srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY || (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMS && p_layer))) {
  1306. srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
  1307. srv_desc.Texture2DMSArray.FirstArraySlice = p_layer;
  1308. srv_desc.Texture2DMSArray.ArraySize = 1;
  1309. uav_desc.ViewDimension = D3D12_UAV_DIMENSION_UNKNOWN;
  1310. } else {
  1311. DEV_ASSERT(false);
  1312. }
  1313. } break;
  1314. case TEXTURE_SLICE_CUBEMAP: {
  1315. if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE || p_layer == 0) {
  1316. srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
  1317. srv_desc.TextureCube.MostDetailedMip = p_mipmap;
  1318. srv_desc.TextureCube.MipLevels = p_mipmaps;
  1319. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
  1320. uav_desc.Texture2DArray.MipSlice = p_mipmap;
  1321. uav_desc.Texture2DArray.FirstArraySlice = p_layer;
  1322. uav_desc.Texture2DArray.ArraySize = 6;
  1323. uav_desc.Texture2DArray.PlaneSlice = 0;
  1324. } else if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBEARRAY || p_layer != 0) {
  1325. srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
  1326. srv_desc.TextureCubeArray.MostDetailedMip = p_mipmap;
  1327. srv_desc.TextureCubeArray.MipLevels = p_mipmaps;
  1328. srv_desc.TextureCubeArray.First2DArrayFace = p_layer;
  1329. srv_desc.TextureCubeArray.NumCubes = 1;
  1330. srv_desc.TextureCubeArray.ResourceMinLODClamp = 0.0f;
  1331. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
  1332. uav_desc.Texture2DArray.MipSlice = p_mipmap;
  1333. uav_desc.Texture2DArray.FirstArraySlice = p_layer;
  1334. uav_desc.Texture2DArray.ArraySize = 6;
  1335. uav_desc.Texture2DArray.PlaneSlice = 0;
  1336. } else {
  1337. DEV_ASSERT(false);
  1338. }
  1339. } break;
  1340. case TEXTURE_SLICE_3D: {
  1341. DEV_ASSERT(srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE3D);
  1342. srv_desc.Texture3D.MostDetailedMip = p_mipmap;
  1343. srv_desc.Texture3D.MipLevels = p_mipmaps;
  1344. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE3D);
  1345. uav_desc.Texture3D.MipSlice = p_mipmap;
  1346. uav_desc.Texture3D.WSize = -1;
  1347. } break;
  1348. case TEXTURE_SLICE_2D_ARRAY: {
  1349. DEV_ASSERT(srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY);
  1350. srv_desc.Texture2DArray.MostDetailedMip = p_mipmap;
  1351. srv_desc.Texture2DArray.MipLevels = p_mipmaps;
  1352. srv_desc.Texture2DArray.FirstArraySlice = p_layer;
  1353. srv_desc.Texture2DArray.ArraySize = p_layers;
  1354. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
  1355. uav_desc.Texture2DArray.MipSlice = p_mipmap;
  1356. uav_desc.Texture2DArray.FirstArraySlice = p_layer;
  1357. uav_desc.Texture2DArray.ArraySize = p_layers;
  1358. } break;
  1359. default:
  1360. break;
  1361. }
  1362. }
  1363. // Bookkeep.
  1364. TextureInfo *tex_info = VersatileResource::allocate<TextureInfo>(resources_allocator);
  1365. tex_info->resource = resource;
  1366. tex_info->states_ptr = owner_tex_info->states_ptr;
  1367. tex_info->format = p_view.format;
  1368. tex_info->desc = new_tex_resource_desc;
  1369. if (p_slice_type == (TextureSliceType)-1) {
  1370. tex_info->base_layer = owner_tex_info->base_layer;
  1371. tex_info->layers = owner_tex_info->layers;
  1372. tex_info->base_mip = owner_tex_info->base_mip;
  1373. tex_info->mipmaps = owner_tex_info->mipmaps;
  1374. } else {
  1375. tex_info->base_layer = p_layer;
  1376. tex_info->layers = p_layers;
  1377. tex_info->base_mip = p_mipmap;
  1378. tex_info->mipmaps = p_mipmaps;
  1379. }
  1380. tex_info->view_descs.srv = srv_desc;
  1381. tex_info->view_descs.uav = uav_desc;
  1382. tex_info->main_texture = owner_tex_info;
  1383. return TextureID(tex_info);
  1384. }
  1385. void RenderingDeviceDriverD3D12::texture_free(TextureID p_texture) {
  1386. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  1387. VersatileResource::free(resources_allocator, tex_info);
  1388. }
  1389. uint64_t RenderingDeviceDriverD3D12::texture_get_allocation_size(TextureID p_texture) {
  1390. const TextureInfo *tex_info = (const TextureInfo *)p_texture.id;
  1391. return tex_info->owner_info.allocation ? tex_info->owner_info.allocation->GetSize() : 0;
  1392. }
  1393. void RenderingDeviceDriverD3D12::texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) {
  1394. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  1395. UINT subresource = tex_info->desc.CalcSubresource(p_subresource.mipmap, p_subresource.layer, 0);
  1396. D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint = {};
  1397. UINT64 subresource_total_size = 0;
  1398. device->GetCopyableFootprints(
  1399. &tex_info->desc,
  1400. subresource,
  1401. 1,
  1402. 0,
  1403. &footprint,
  1404. nullptr,
  1405. nullptr,
  1406. &subresource_total_size);
  1407. *r_layout = {};
  1408. r_layout->offset = footprint.Offset;
  1409. r_layout->size = subresource_total_size;
  1410. r_layout->row_pitch = footprint.Footprint.RowPitch;
  1411. r_layout->depth_pitch = subresource_total_size / tex_info->desc.Depth();
  1412. r_layout->layer_pitch = subresource_total_size / tex_info->desc.ArraySize();
  1413. }
  1414. uint8_t *RenderingDeviceDriverD3D12::texture_map(TextureID p_texture, const TextureSubresource &p_subresource) {
  1415. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  1416. #ifdef DEBUG_ENABLED
  1417. ERR_FAIL_COND_V(tex_info->mapped_subresource != UINT_MAX, nullptr);
  1418. #endif
  1419. UINT plane = _compute_plane_slice(tex_info->format, p_subresource.aspect);
  1420. UINT subresource = tex_info->desc.CalcSubresource(p_subresource.mipmap, p_subresource.layer, plane);
  1421. void *data_ptr = nullptr;
  1422. HRESULT res = tex_info->resource->Map(subresource, &VOID_RANGE, &data_ptr);
  1423. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), nullptr, "Map failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  1424. tex_info->mapped_subresource = subresource;
  1425. return (uint8_t *)data_ptr;
  1426. }
  1427. void RenderingDeviceDriverD3D12::texture_unmap(TextureID p_texture) {
  1428. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  1429. #ifdef DEBUG_ENABLED
  1430. ERR_FAIL_COND(tex_info->mapped_subresource == UINT_MAX);
  1431. #endif
  1432. tex_info->resource->Unmap(tex_info->mapped_subresource, &VOID_RANGE);
  1433. tex_info->mapped_subresource = UINT_MAX;
  1434. }
  1435. BitField<RDD::TextureUsageBits> RenderingDeviceDriverD3D12::texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) {
  1436. D3D12_FEATURE_DATA_FORMAT_SUPPORT srv_rtv_support = {};
  1437. srv_rtv_support.Format = RD_TO_D3D12_FORMAT[p_format].general_format;
  1438. if (srv_rtv_support.Format != DXGI_FORMAT_UNKNOWN) { // Some implementations (i.e., vkd3d-proton) error out instead of returning empty.
  1439. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &srv_rtv_support, sizeof(srv_rtv_support));
  1440. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  1441. }
  1442. D3D12_FEATURE_DATA_FORMAT_SUPPORT &uav_support = srv_rtv_support; // Fine for now.
  1443. D3D12_FEATURE_DATA_FORMAT_SUPPORT dsv_support = {};
  1444. dsv_support.Format = RD_TO_D3D12_FORMAT[p_format].dsv_format;
  1445. if (dsv_support.Format != DXGI_FORMAT_UNKNOWN) { // See above.
  1446. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &dsv_support, sizeof(dsv_support));
  1447. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  1448. }
  1449. // Everything supported by default makes an all-or-nothing check easier for the caller.
  1450. BitField<RDD::TextureUsageBits> supported = INT64_MAX;
  1451. // Per https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_format_support1,
  1452. // as long as the resource can be used as a texture, Sample() will work with point filter at least.
  1453. // However, we've empirically found that checking for at least D3D12_FORMAT_SUPPORT1_SHADER_LOAD is needed.
  1454. // That's almost good for integer formats. The problem is that theoretically there may be
  1455. // float formats that support LOAD but not SAMPLE fully, so this check will not detect
  1456. // such a flaw in the format. Linearly interpolated sampling would just not work on them.
  1457. if (!(srv_rtv_support.Support1 & (D3D12_FORMAT_SUPPORT1_SHADER_LOAD | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE)) ||
  1458. RD_TO_D3D12_FORMAT[p_format].general_format == DXGI_FORMAT_UNKNOWN) {
  1459. supported.clear_flag(TEXTURE_USAGE_SAMPLING_BIT);
  1460. }
  1461. if (!(srv_rtv_support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET)) {
  1462. supported.clear_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT);
  1463. }
  1464. if (!(dsv_support.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL)) {
  1465. supported.clear_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
  1466. }
  1467. if (!(uav_support.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) { // Maybe check LOAD/STORE, too?
  1468. supported.clear_flag(TEXTURE_USAGE_STORAGE_BIT);
  1469. }
  1470. if (!(uav_support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD)) { // Check a basic atomic at least.
  1471. supported.clear_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT);
  1472. }
  1473. if (RD_TO_D3D12_FORMAT[p_format].general_format != DXGI_FORMAT_R8_UINT) {
  1474. supported.clear_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT);
  1475. }
  1476. return supported;
  1477. }
  1478. bool RenderingDeviceDriverD3D12::texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) {
  1479. r_raw_reinterpretation = false;
  1480. if (format_capabilities.relaxed_casting_supported) {
  1481. // Relaxed casting is supported, there should be no need to check for format family compatibility.
  1482. return true;
  1483. } else {
  1484. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  1485. if (tex_info->format == DATA_FORMAT_R16_UINT && p_format == DATA_FORMAT_R4G4B4A4_UNORM_PACK16) {
  1486. // Specific cases that require buffer reinterpretation.
  1487. r_raw_reinterpretation = true;
  1488. return false;
  1489. } else if (RD_TO_D3D12_FORMAT[tex_info->format].family != RD_TO_D3D12_FORMAT[p_format].family) {
  1490. // Format family is different but copying resources directly is possible.
  1491. return false;
  1492. } else {
  1493. // Format family is the same and the view can just cast the format.
  1494. return true;
  1495. }
  1496. }
  1497. }
  1498. /*****************/
  1499. /**** SAMPLER ****/
  1500. /*****************/
  1501. static const D3D12_TEXTURE_ADDRESS_MODE RD_REPEAT_MODE_TO_D3D12_ADDRES_MODE[RDD::SAMPLER_REPEAT_MODE_MAX] = {
  1502. D3D12_TEXTURE_ADDRESS_MODE_WRAP,
  1503. D3D12_TEXTURE_ADDRESS_MODE_MIRROR,
  1504. D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1505. D3D12_TEXTURE_ADDRESS_MODE_BORDER,
  1506. D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE,
  1507. };
  1508. static const FLOAT RD_TO_D3D12_SAMPLER_BORDER_COLOR[RDD::SAMPLER_BORDER_COLOR_MAX][4] = {
  1509. { 0, 0, 0, 0 },
  1510. { 0, 0, 0, 0 },
  1511. { 0, 0, 0, 1 },
  1512. { 0, 0, 0, 1 },
  1513. { 1, 1, 1, 1 },
  1514. { 1, 1, 1, 1 },
  1515. };
  1516. RDD::SamplerID RenderingDeviceDriverD3D12::sampler_create(const SamplerState &p_state) {
  1517. uint32_t slot = UINT32_MAX;
  1518. if (samplers.is_empty()) {
  1519. // Adding a seemigly busy slot 0 makes things easier elsewhere.
  1520. samplers.push_back({});
  1521. samplers.push_back({});
  1522. slot = 1;
  1523. } else {
  1524. for (uint32_t i = 1; i < samplers.size(); i++) {
  1525. if ((int)samplers[i].Filter == INT_MAX) {
  1526. slot = i;
  1527. break;
  1528. }
  1529. }
  1530. if (slot == UINT32_MAX) {
  1531. slot = samplers.size();
  1532. samplers.push_back({});
  1533. }
  1534. }
  1535. D3D12_SAMPLER_DESC &sampler_desc = samplers[slot];
  1536. if (p_state.use_anisotropy) {
  1537. sampler_desc.Filter = D3D12_ENCODE_ANISOTROPIC_FILTER(D3D12_FILTER_REDUCTION_TYPE_STANDARD);
  1538. sampler_desc.MaxAnisotropy = p_state.anisotropy_max;
  1539. } else {
  1540. static const D3D12_FILTER_TYPE RD_FILTER_TYPE_TO_D3D12[] = {
  1541. D3D12_FILTER_TYPE_POINT, // SAMPLER_FILTER_NEAREST.
  1542. D3D12_FILTER_TYPE_LINEAR, // SAMPLER_FILTER_LINEAR.
  1543. };
  1544. sampler_desc.Filter = D3D12_ENCODE_BASIC_FILTER(
  1545. RD_FILTER_TYPE_TO_D3D12[p_state.min_filter],
  1546. RD_FILTER_TYPE_TO_D3D12[p_state.mag_filter],
  1547. RD_FILTER_TYPE_TO_D3D12[p_state.mip_filter],
  1548. p_state.enable_compare ? D3D12_FILTER_REDUCTION_TYPE_COMPARISON : D3D12_FILTER_REDUCTION_TYPE_STANDARD);
  1549. }
  1550. sampler_desc.AddressU = RD_REPEAT_MODE_TO_D3D12_ADDRES_MODE[p_state.repeat_u];
  1551. sampler_desc.AddressV = RD_REPEAT_MODE_TO_D3D12_ADDRES_MODE[p_state.repeat_v];
  1552. sampler_desc.AddressW = RD_REPEAT_MODE_TO_D3D12_ADDRES_MODE[p_state.repeat_w];
  1553. for (int i = 0; i < 4; i++) {
  1554. sampler_desc.BorderColor[i] = RD_TO_D3D12_SAMPLER_BORDER_COLOR[p_state.border_color][i];
  1555. }
  1556. sampler_desc.MinLOD = p_state.min_lod;
  1557. sampler_desc.MaxLOD = p_state.max_lod;
  1558. sampler_desc.MipLODBias = p_state.lod_bias;
  1559. sampler_desc.ComparisonFunc = p_state.enable_compare ? RD_TO_D3D12_COMPARE_OP[p_state.compare_op] : D3D12_COMPARISON_FUNC_NEVER;
  1560. // TODO: Emulate somehow?
  1561. if (p_state.unnormalized_uvw) {
  1562. WARN_PRINT("Creating a sampler with unnormalized UVW, which is not supported.");
  1563. }
  1564. return SamplerID(slot);
  1565. }
  1566. void RenderingDeviceDriverD3D12::sampler_free(SamplerID p_sampler) {
  1567. samplers[p_sampler.id].Filter = (D3D12_FILTER)INT_MAX;
  1568. }
  1569. bool RenderingDeviceDriverD3D12::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) {
  1570. D3D12_FEATURE_DATA_FORMAT_SUPPORT srv_rtv_support = {};
  1571. srv_rtv_support.Format = RD_TO_D3D12_FORMAT[p_format].general_format;
  1572. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &srv_rtv_support, sizeof(srv_rtv_support));
  1573. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  1574. return (srv_rtv_support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE);
  1575. }
  1576. /**********************/
  1577. /**** VERTEX ARRAY ****/
  1578. /**********************/
  1579. RDD::VertexFormatID RenderingDeviceDriverD3D12::vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) {
  1580. VertexFormatInfo *vf_info = VersatileResource::allocate<VertexFormatInfo>(resources_allocator);
  1581. vf_info->input_elem_descs.resize(p_vertex_attribs.size());
  1582. vf_info->vertex_buffer_strides.resize(p_vertex_attribs.size());
  1583. for (uint32_t i = 0; i < p_vertex_attribs.size(); i++) {
  1584. vf_info->input_elem_descs[i] = {};
  1585. vf_info->input_elem_descs[i].SemanticName = "TEXCOORD";
  1586. vf_info->input_elem_descs[i].SemanticIndex = p_vertex_attribs[i].location;
  1587. vf_info->input_elem_descs[i].Format = RD_TO_D3D12_FORMAT[p_vertex_attribs[i].format].general_format;
  1588. vf_info->input_elem_descs[i].InputSlot = i; // TODO: Can the same slot be used if data comes from the same buffer (regardless format)?
  1589. vf_info->input_elem_descs[i].AlignedByteOffset = p_vertex_attribs[i].offset;
  1590. if (p_vertex_attribs[i].frequency == VERTEX_FREQUENCY_INSTANCE) {
  1591. vf_info->input_elem_descs[i].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA;
  1592. vf_info->input_elem_descs[i].InstanceDataStepRate = 1;
  1593. } else {
  1594. vf_info->input_elem_descs[i].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
  1595. vf_info->input_elem_descs[i].InstanceDataStepRate = 0;
  1596. }
  1597. vf_info->vertex_buffer_strides[i] = p_vertex_attribs[i].stride;
  1598. }
  1599. return VertexFormatID(vf_info);
  1600. }
  1601. void RenderingDeviceDriverD3D12::vertex_format_free(VertexFormatID p_vertex_format) {
  1602. VertexFormatInfo *vf_info = (VertexFormatInfo *)p_vertex_format.id;
  1603. VersatileResource::free(resources_allocator, vf_info);
  1604. }
  1605. /******************/
  1606. /**** BARRIERS ****/
  1607. /******************/
  1608. static D3D12_BARRIER_ACCESS _rd_texture_layout_access_mask(RDD::TextureLayout p_texture_layout) {
  1609. switch (p_texture_layout) {
  1610. case RDD::TEXTURE_LAYOUT_STORAGE_OPTIMAL:
  1611. return D3D12_BARRIER_ACCESS_UNORDERED_ACCESS;
  1612. case RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
  1613. return D3D12_BARRIER_ACCESS_RENDER_TARGET;
  1614. case RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
  1615. return D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ | D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE;
  1616. case RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
  1617. return D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ;
  1618. case RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
  1619. return D3D12_BARRIER_ACCESS_SHADER_RESOURCE;
  1620. case RDD::TEXTURE_LAYOUT_COPY_SRC_OPTIMAL:
  1621. return D3D12_BARRIER_ACCESS_COPY_SOURCE;
  1622. case RDD::TEXTURE_LAYOUT_COPY_DST_OPTIMAL:
  1623. return D3D12_BARRIER_ACCESS_COPY_DEST;
  1624. case RDD::TEXTURE_LAYOUT_RESOLVE_SRC_OPTIMAL:
  1625. return D3D12_BARRIER_ACCESS_RESOLVE_SOURCE;
  1626. case RDD::TEXTURE_LAYOUT_RESOLVE_DST_OPTIMAL:
  1627. return D3D12_BARRIER_ACCESS_RESOLVE_DEST;
  1628. case RDD::TEXTURE_LAYOUT_VRS_ATTACHMENT_OPTIMAL:
  1629. return D3D12_BARRIER_ACCESS_SHADING_RATE_SOURCE;
  1630. default:
  1631. return D3D12_BARRIER_ACCESS_NO_ACCESS;
  1632. }
  1633. }
  1634. static void _rd_access_to_d3d12_and_mask(BitField<RDD::BarrierAccessBits> p_access, RDD::TextureLayout p_texture_layout, D3D12_BARRIER_ACCESS &r_access, D3D12_BARRIER_SYNC &r_sync_mask) {
  1635. r_access = D3D12_BARRIER_ACCESS_COMMON;
  1636. r_sync_mask = D3D12_BARRIER_SYNC_NONE;
  1637. if (p_access.has_flag(RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT)) {
  1638. r_access |= D3D12_BARRIER_ACCESS_INDIRECT_ARGUMENT;
  1639. r_sync_mask |= D3D12_BARRIER_SYNC_EXECUTE_INDIRECT;
  1640. }
  1641. if (p_access.has_flag(RDD::BARRIER_ACCESS_INDEX_READ_BIT)) {
  1642. r_access |= D3D12_BARRIER_ACCESS_INDEX_BUFFER;
  1643. r_sync_mask |= D3D12_BARRIER_SYNC_INDEX_INPUT | D3D12_BARRIER_SYNC_DRAW;
  1644. }
  1645. if (p_access.has_flag(RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT)) {
  1646. r_access |= D3D12_BARRIER_ACCESS_VERTEX_BUFFER;
  1647. r_sync_mask |= D3D12_BARRIER_SYNC_VERTEX_SHADING | D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_ALL_SHADING;
  1648. }
  1649. if (p_access.has_flag(RDD::BARRIER_ACCESS_UNIFORM_READ_BIT)) {
  1650. r_access |= D3D12_BARRIER_ACCESS_CONSTANT_BUFFER;
  1651. r_sync_mask |= D3D12_BARRIER_SYNC_VERTEX_SHADING | D3D12_BARRIER_SYNC_PIXEL_SHADING | D3D12_BARRIER_SYNC_COMPUTE_SHADING |
  1652. D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_ALL_SHADING;
  1653. }
  1654. if (p_access.has_flag(RDD::BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT)) {
  1655. r_access |= D3D12_BARRIER_ACCESS_RENDER_TARGET;
  1656. r_sync_mask |= D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_RENDER_TARGET;
  1657. }
  1658. if (p_access.has_flag(RDD::BARRIER_ACCESS_COPY_READ_BIT)) {
  1659. r_access |= D3D12_BARRIER_ACCESS_COPY_SOURCE;
  1660. r_sync_mask |= D3D12_BARRIER_SYNC_COPY;
  1661. }
  1662. if (p_access.has_flag(RDD::BARRIER_ACCESS_COPY_WRITE_BIT)) {
  1663. r_access |= D3D12_BARRIER_ACCESS_COPY_DEST;
  1664. r_sync_mask |= D3D12_BARRIER_SYNC_COPY;
  1665. }
  1666. if (p_access.has_flag(RDD::BARRIER_ACCESS_RESOLVE_READ_BIT)) {
  1667. r_access |= D3D12_BARRIER_ACCESS_RESOLVE_SOURCE;
  1668. r_sync_mask |= D3D12_BARRIER_SYNC_RESOLVE;
  1669. }
  1670. if (p_access.has_flag(RDD::BARRIER_ACCESS_RESOLVE_WRITE_BIT)) {
  1671. r_access |= D3D12_BARRIER_ACCESS_RESOLVE_DEST;
  1672. r_sync_mask |= D3D12_BARRIER_SYNC_RESOLVE;
  1673. }
  1674. if (p_access.has_flag(RDD::BARRIER_ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT)) {
  1675. r_access |= D3D12_BARRIER_ACCESS_SHADING_RATE_SOURCE;
  1676. r_sync_mask |= D3D12_BARRIER_SYNC_PIXEL_SHADING | D3D12_BARRIER_SYNC_ALL_SHADING;
  1677. }
  1678. const D3D12_BARRIER_SYNC unordered_access_mask = D3D12_BARRIER_SYNC_VERTEX_SHADING | D3D12_BARRIER_SYNC_PIXEL_SHADING | D3D12_BARRIER_SYNC_COMPUTE_SHADING |
  1679. D3D12_BARRIER_SYNC_VERTEX_SHADING | D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_ALL_SHADING | D3D12_BARRIER_SYNC_CLEAR_UNORDERED_ACCESS_VIEW;
  1680. if (p_access.has_flag(RDD::BARRIER_ACCESS_STORAGE_CLEAR_BIT)) {
  1681. r_access |= D3D12_BARRIER_ACCESS_UNORDERED_ACCESS;
  1682. r_sync_mask |= unordered_access_mask;
  1683. }
  1684. // These access bits only have compatibility with certain layouts unlike in Vulkan where they imply specific operations in the same layout.
  1685. if (p_access.has_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT)) {
  1686. r_access |= D3D12_BARRIER_ACCESS_UNORDERED_ACCESS;
  1687. r_sync_mask |= unordered_access_mask;
  1688. } else if (p_access.has_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT)) {
  1689. if (p_texture_layout == RDD::TEXTURE_LAYOUT_STORAGE_OPTIMAL) {
  1690. // Unordered access must be enforced if the texture is using the storage layout.
  1691. r_access |= D3D12_BARRIER_ACCESS_UNORDERED_ACCESS;
  1692. r_sync_mask |= unordered_access_mask;
  1693. } else {
  1694. r_access |= D3D12_BARRIER_ACCESS_SHADER_RESOURCE;
  1695. r_sync_mask |= D3D12_BARRIER_SYNC_VERTEX_SHADING | D3D12_BARRIER_SYNC_PIXEL_SHADING | D3D12_BARRIER_SYNC_COMPUTE_SHADING | D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_ALL_SHADING;
  1696. }
  1697. }
  1698. if (p_access.has_flag(RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT) || p_access.has_flag(RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT)) {
  1699. r_access |= D3D12_BARRIER_ACCESS_RENDER_TARGET;
  1700. r_sync_mask |= D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_RENDER_TARGET;
  1701. }
  1702. if (p_access.has_flag(RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)) {
  1703. r_access |= D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE;
  1704. r_sync_mask |= D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_DEPTH_STENCIL;
  1705. } else if (p_access.has_flag(RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT)) {
  1706. r_access |= D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ;
  1707. r_sync_mask |= D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_DEPTH_STENCIL;
  1708. }
  1709. }
  1710. static void _rd_stages_to_d3d12(BitField<RDD::PipelineStageBits> p_stages, D3D12_BARRIER_SYNC &r_sync) {
  1711. if (p_stages.has_flag(RDD::PIPELINE_STAGE_ALL_COMMANDS_BIT)) {
  1712. r_sync = D3D12_BARRIER_SYNC_ALL;
  1713. } else {
  1714. if (p_stages.has_flag(RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT)) {
  1715. r_sync |= D3D12_BARRIER_SYNC_EXECUTE_INDIRECT;
  1716. }
  1717. if (p_stages.has_flag(RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT)) {
  1718. r_sync |= D3D12_BARRIER_SYNC_INDEX_INPUT;
  1719. }
  1720. if (p_stages.has_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT)) {
  1721. r_sync |= D3D12_BARRIER_SYNC_VERTEX_SHADING;
  1722. }
  1723. if (p_stages.has_flag(RDD::PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT) || p_stages.has_flag(RDD::PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT) || p_stages.has_flag(RDD::PIPELINE_STAGE_GEOMETRY_SHADER_BIT)) {
  1724. // There's no granularity for tessellation or geometry stages. The specification defines it as part of vertex shading.
  1725. r_sync |= D3D12_BARRIER_SYNC_VERTEX_SHADING;
  1726. }
  1727. if (p_stages.has_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT)) {
  1728. r_sync |= D3D12_BARRIER_SYNC_PIXEL_SHADING;
  1729. }
  1730. if (p_stages.has_flag(RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT) || p_stages.has_flag(RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT)) {
  1731. // Covers both read and write operations for depth stencil.
  1732. r_sync |= D3D12_BARRIER_SYNC_DEPTH_STENCIL;
  1733. }
  1734. if (p_stages.has_flag(RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)) {
  1735. r_sync |= D3D12_BARRIER_SYNC_RENDER_TARGET;
  1736. }
  1737. if (p_stages.has_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT)) {
  1738. r_sync |= D3D12_BARRIER_SYNC_COMPUTE_SHADING;
  1739. }
  1740. if (p_stages.has_flag(RDD::PIPELINE_STAGE_COPY_BIT)) {
  1741. r_sync |= D3D12_BARRIER_SYNC_COPY;
  1742. }
  1743. if (p_stages.has_flag(RDD::PIPELINE_STAGE_RESOLVE_BIT)) {
  1744. r_sync |= D3D12_BARRIER_SYNC_RESOLVE;
  1745. }
  1746. if (p_stages.has_flag(RDD::PIPELINE_STAGE_CLEAR_STORAGE_BIT)) {
  1747. r_sync |= D3D12_BARRIER_SYNC_CLEAR_UNORDERED_ACCESS_VIEW;
  1748. }
  1749. if (p_stages.has_flag(RDD::PIPELINE_STAGE_ALL_GRAPHICS_BIT)) {
  1750. r_sync |= D3D12_BARRIER_SYNC_DRAW;
  1751. }
  1752. }
  1753. }
  1754. static void _rd_stages_and_access_to_d3d12(BitField<RDD::PipelineStageBits> p_stages, RDD::TextureLayout p_texture_layout, BitField<RDD::BarrierAccessBits> p_access, D3D12_BARRIER_SYNC &r_sync, D3D12_BARRIER_ACCESS &r_access) {
  1755. D3D12_BARRIER_SYNC sync_mask;
  1756. r_sync = D3D12_BARRIER_SYNC_NONE;
  1757. if (p_texture_layout == RDD::TEXTURE_LAYOUT_UNDEFINED) {
  1758. // Undefined texture layouts are a special case where no access bits or synchronization scopes are allowed.
  1759. r_access = D3D12_BARRIER_ACCESS_NO_ACCESS;
  1760. return;
  1761. }
  1762. // Convert access bits to the D3D12 barrier access bits.
  1763. _rd_access_to_d3d12_and_mask(p_access, p_texture_layout, r_access, sync_mask);
  1764. if (p_texture_layout != RDD::TEXTURE_LAYOUT_MAX) {
  1765. // Only allow the access bits compatible with the texture layout.
  1766. r_access &= _rd_texture_layout_access_mask(p_texture_layout);
  1767. }
  1768. // Convert stage bits to the D3D12 synchronization scope bits.
  1769. _rd_stages_to_d3d12(p_stages, r_sync);
  1770. // Only enable synchronization stages compatible with the access bits that were used.
  1771. r_sync &= sync_mask;
  1772. if (r_sync == D3D12_BARRIER_SYNC_NONE) {
  1773. if (p_access.is_empty()) {
  1774. // No valid synchronization scope was defined and no access in particular is required.
  1775. r_access = D3D12_BARRIER_ACCESS_NO_ACCESS;
  1776. } else {
  1777. // Access is required but the synchronization scope wasn't compatible. We fall back to the global synchronization scope and access.
  1778. r_sync = D3D12_BARRIER_SYNC_ALL;
  1779. r_access = D3D12_BARRIER_ACCESS_COMMON;
  1780. }
  1781. }
  1782. }
  1783. static D3D12_BARRIER_LAYOUT _rd_texture_layout_to_d3d12_barrier_layout(RDD::TextureLayout p_texture_layout) {
  1784. switch (p_texture_layout) {
  1785. case RDD::TEXTURE_LAYOUT_UNDEFINED:
  1786. return D3D12_BARRIER_LAYOUT_UNDEFINED;
  1787. case RDD::TEXTURE_LAYOUT_GENERAL:
  1788. return D3D12_BARRIER_LAYOUT_COMMON;
  1789. case RDD::TEXTURE_LAYOUT_STORAGE_OPTIMAL:
  1790. return D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS;
  1791. case RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
  1792. return D3D12_BARRIER_LAYOUT_RENDER_TARGET;
  1793. case RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
  1794. return D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE;
  1795. case RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
  1796. return D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ;
  1797. case RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
  1798. return D3D12_BARRIER_LAYOUT_SHADER_RESOURCE;
  1799. case RDD::TEXTURE_LAYOUT_COPY_SRC_OPTIMAL:
  1800. return D3D12_BARRIER_LAYOUT_COPY_SOURCE;
  1801. case RDD::TEXTURE_LAYOUT_COPY_DST_OPTIMAL:
  1802. return D3D12_BARRIER_LAYOUT_COPY_DEST;
  1803. case RDD::TEXTURE_LAYOUT_RESOLVE_SRC_OPTIMAL:
  1804. return D3D12_BARRIER_LAYOUT_RESOLVE_SOURCE;
  1805. case RDD::TEXTURE_LAYOUT_RESOLVE_DST_OPTIMAL:
  1806. return D3D12_BARRIER_LAYOUT_RESOLVE_DEST;
  1807. case RDD::TEXTURE_LAYOUT_VRS_ATTACHMENT_OPTIMAL:
  1808. return D3D12_BARRIER_LAYOUT_SHADING_RATE_SOURCE;
  1809. default:
  1810. DEV_ASSERT(false && "Unknown texture layout.");
  1811. return D3D12_BARRIER_LAYOUT_UNDEFINED;
  1812. }
  1813. }
  1814. void RenderingDeviceDriverD3D12::command_pipeline_barrier(CommandBufferID p_cmd_buffer,
  1815. BitField<PipelineStageBits> p_src_stages,
  1816. BitField<PipelineStageBits> p_dst_stages,
  1817. VectorView<RDD::MemoryBarrier> p_memory_barriers,
  1818. VectorView<RDD::BufferBarrier> p_buffer_barriers,
  1819. VectorView<RDD::TextureBarrier> p_texture_barriers) {
  1820. if (!barrier_capabilities.enhanced_barriers_supported) {
  1821. // Enhanced barriers are a requirement for this function.
  1822. return;
  1823. }
  1824. if (p_memory_barriers.size() == 0 && p_buffer_barriers.size() == 0 && p_texture_barriers.size() == 0) {
  1825. // At least one barrier must be present in the arguments.
  1826. return;
  1827. }
  1828. // The command list must support the required interface.
  1829. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)(p_cmd_buffer.id);
  1830. ID3D12GraphicsCommandList7 *cmd_list_7 = nullptr;
  1831. HRESULT res = cmd_buf_info->cmd_list->QueryInterface(IID_PPV_ARGS(&cmd_list_7));
  1832. ERR_FAIL_COND(FAILED(res));
  1833. // Convert the RDD barriers to D3D12 enhanced barriers.
  1834. thread_local LocalVector<D3D12_GLOBAL_BARRIER> global_barriers;
  1835. thread_local LocalVector<D3D12_BUFFER_BARRIER> buffer_barriers;
  1836. thread_local LocalVector<D3D12_TEXTURE_BARRIER> texture_barriers;
  1837. global_barriers.clear();
  1838. buffer_barriers.clear();
  1839. texture_barriers.clear();
  1840. D3D12_GLOBAL_BARRIER global_barrier = {};
  1841. for (uint32_t i = 0; i < p_memory_barriers.size(); i++) {
  1842. const MemoryBarrier &memory_barrier = p_memory_barriers[i];
  1843. _rd_stages_and_access_to_d3d12(p_src_stages, RDD::TEXTURE_LAYOUT_MAX, memory_barrier.src_access, global_barrier.SyncBefore, global_barrier.AccessBefore);
  1844. _rd_stages_and_access_to_d3d12(p_dst_stages, RDD::TEXTURE_LAYOUT_MAX, memory_barrier.dst_access, global_barrier.SyncAfter, global_barrier.AccessAfter);
  1845. global_barriers.push_back(global_barrier);
  1846. }
  1847. D3D12_BUFFER_BARRIER buffer_barrier_d3d12 = {};
  1848. buffer_barrier_d3d12.Offset = 0;
  1849. buffer_barrier_d3d12.Size = UINT64_MAX; // The specification says this must be the size of the buffer barrier.
  1850. for (uint32_t i = 0; i < p_buffer_barriers.size(); i++) {
  1851. const BufferBarrier &buffer_barrier_rd = p_buffer_barriers[i];
  1852. const BufferInfo *buffer_info = (const BufferInfo *)(buffer_barrier_rd.buffer.id);
  1853. _rd_stages_and_access_to_d3d12(p_src_stages, RDD::TEXTURE_LAYOUT_MAX, buffer_barrier_rd.src_access, buffer_barrier_d3d12.SyncBefore, buffer_barrier_d3d12.AccessBefore);
  1854. _rd_stages_and_access_to_d3d12(p_dst_stages, RDD::TEXTURE_LAYOUT_MAX, buffer_barrier_rd.dst_access, buffer_barrier_d3d12.SyncAfter, buffer_barrier_d3d12.AccessAfter);
  1855. buffer_barrier_d3d12.pResource = buffer_info->resource;
  1856. buffer_barriers.push_back(buffer_barrier_d3d12);
  1857. }
  1858. D3D12_TEXTURE_BARRIER texture_barrier_d3d12 = {};
  1859. for (uint32_t i = 0; i < p_texture_barriers.size(); i++) {
  1860. const TextureBarrier &texture_barrier_rd = p_texture_barriers[i];
  1861. const TextureInfo *texture_info = (const TextureInfo *)(texture_barrier_rd.texture.id);
  1862. if (texture_info->main_texture) {
  1863. texture_info = texture_info->main_texture;
  1864. }
  1865. _rd_stages_and_access_to_d3d12(p_src_stages, texture_barrier_rd.prev_layout, texture_barrier_rd.src_access, texture_barrier_d3d12.SyncBefore, texture_barrier_d3d12.AccessBefore);
  1866. _rd_stages_and_access_to_d3d12(p_dst_stages, texture_barrier_rd.next_layout, texture_barrier_rd.dst_access, texture_barrier_d3d12.SyncAfter, texture_barrier_d3d12.AccessAfter);
  1867. texture_barrier_d3d12.LayoutBefore = _rd_texture_layout_to_d3d12_barrier_layout(texture_barrier_rd.prev_layout);
  1868. texture_barrier_d3d12.LayoutAfter = _rd_texture_layout_to_d3d12_barrier_layout(texture_barrier_rd.next_layout);
  1869. texture_barrier_d3d12.pResource = texture_info->resource;
  1870. if (texture_barrier_rd.subresources.mipmap_count == texture_info->mipmaps && texture_barrier_rd.subresources.layer_count == texture_info->layers) {
  1871. // So, all resources. Then, let's be explicit about it so D3D12 doesn't think
  1872. // we are dealing with a subset of subresources.
  1873. texture_barrier_d3d12.Subresources.IndexOrFirstMipLevel = 0xffffffff;
  1874. texture_barrier_d3d12.Subresources.NumMipLevels = 0;
  1875. // Because NumMipLevels == 0, all the other fields are ignored by D3D12.
  1876. } else {
  1877. texture_barrier_d3d12.Subresources.IndexOrFirstMipLevel = texture_barrier_rd.subresources.base_mipmap;
  1878. texture_barrier_d3d12.Subresources.NumMipLevels = texture_barrier_rd.subresources.mipmap_count;
  1879. texture_barrier_d3d12.Subresources.FirstArraySlice = texture_barrier_rd.subresources.base_layer;
  1880. texture_barrier_d3d12.Subresources.NumArraySlices = texture_barrier_rd.subresources.layer_count;
  1881. texture_barrier_d3d12.Subresources.FirstPlane = _compute_plane_slice(texture_info->format, texture_barrier_rd.subresources.aspect);
  1882. texture_barrier_d3d12.Subresources.NumPlanes = format_get_plane_count(texture_info->format);
  1883. }
  1884. texture_barrier_d3d12.Flags = (texture_barrier_rd.prev_layout == RDD::TEXTURE_LAYOUT_UNDEFINED) ? D3D12_TEXTURE_BARRIER_FLAG_DISCARD : D3D12_TEXTURE_BARRIER_FLAG_NONE;
  1885. texture_barriers.push_back(texture_barrier_d3d12);
  1886. }
  1887. // Define the barrier groups and execute.
  1888. D3D12_BARRIER_GROUP barrier_groups[3] = {};
  1889. uint32_t barrier_groups_count = 0;
  1890. if (!global_barriers.is_empty()) {
  1891. D3D12_BARRIER_GROUP &barrier_group = barrier_groups[barrier_groups_count++];
  1892. barrier_group.Type = D3D12_BARRIER_TYPE_GLOBAL;
  1893. barrier_group.NumBarriers = global_barriers.size();
  1894. barrier_group.pGlobalBarriers = global_barriers.ptr();
  1895. }
  1896. if (!buffer_barriers.is_empty()) {
  1897. D3D12_BARRIER_GROUP &barrier_group = barrier_groups[barrier_groups_count++];
  1898. barrier_group.Type = D3D12_BARRIER_TYPE_BUFFER;
  1899. barrier_group.NumBarriers = buffer_barriers.size();
  1900. barrier_group.pBufferBarriers = buffer_barriers.ptr();
  1901. }
  1902. if (!texture_barriers.is_empty()) {
  1903. D3D12_BARRIER_GROUP &barrier_group = barrier_groups[barrier_groups_count++];
  1904. barrier_group.Type = D3D12_BARRIER_TYPE_TEXTURE;
  1905. barrier_group.NumBarriers = texture_barriers.size();
  1906. barrier_group.pTextureBarriers = texture_barriers.ptr();
  1907. }
  1908. cmd_list_7->Barrier(barrier_groups_count, barrier_groups);
  1909. }
  1910. /****************/
  1911. /**** FENCES ****/
  1912. /****************/
  1913. RDD::FenceID RenderingDeviceDriverD3D12::fence_create() {
  1914. ComPtr<ID3D12Fence> d3d_fence;
  1915. HRESULT res = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(d3d_fence.GetAddressOf()));
  1916. ERR_FAIL_COND_V(!SUCCEEDED(res), FenceID());
  1917. HANDLE event_handle = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  1918. ERR_FAIL_NULL_V(event_handle, FenceID());
  1919. FenceInfo *fence = memnew(FenceInfo);
  1920. fence->d3d_fence = d3d_fence;
  1921. fence->event_handle = event_handle;
  1922. return FenceID(fence);
  1923. }
  1924. Error RenderingDeviceDriverD3D12::fence_wait(FenceID p_fence) {
  1925. FenceInfo *fence = (FenceInfo *)(p_fence.id);
  1926. fence->d3d_fence->SetEventOnCompletion(fence->fence_value, fence->event_handle);
  1927. DWORD res = WaitForSingleObjectEx(fence->event_handle, INFINITE, FALSE);
  1928. #ifdef PIX_ENABLED
  1929. PIXNotifyWakeFromFenceSignal(fence->event_handle);
  1930. #endif
  1931. return (res == WAIT_FAILED) ? FAILED : OK;
  1932. }
  1933. void RenderingDeviceDriverD3D12::fence_free(FenceID p_fence) {
  1934. FenceInfo *fence = (FenceInfo *)(p_fence.id);
  1935. CloseHandle(fence->event_handle);
  1936. memdelete(fence);
  1937. }
  1938. /********************/
  1939. /**** SEMAPHORES ****/
  1940. /********************/
  1941. RDD::SemaphoreID RenderingDeviceDriverD3D12::semaphore_create() {
  1942. ComPtr<ID3D12Fence> d3d_fence;
  1943. HRESULT res = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(d3d_fence.GetAddressOf()));
  1944. ERR_FAIL_COND_V(!SUCCEEDED(res), SemaphoreID());
  1945. SemaphoreInfo *semaphore = memnew(SemaphoreInfo);
  1946. semaphore->d3d_fence = d3d_fence;
  1947. return SemaphoreID(semaphore);
  1948. }
  1949. void RenderingDeviceDriverD3D12::semaphore_free(SemaphoreID p_semaphore) {
  1950. SemaphoreInfo *semaphore = (SemaphoreInfo *)(p_semaphore.id);
  1951. memdelete(semaphore);
  1952. }
  1953. /******************/
  1954. /**** COMMANDS ****/
  1955. /******************/
  1956. // ----- QUEUE FAMILY -----
  1957. RDD::CommandQueueFamilyID RenderingDeviceDriverD3D12::command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface) {
  1958. // Return the command list type encoded plus one so zero is an invalid value.
  1959. // The only ones that support presenting to a surface are direct queues.
  1960. if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_GRAPHICS_BIT) || (p_surface != 0)) {
  1961. return CommandQueueFamilyID(D3D12_COMMAND_LIST_TYPE_DIRECT + 1);
  1962. } else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_COMPUTE_BIT)) {
  1963. return CommandQueueFamilyID(D3D12_COMMAND_LIST_TYPE_COMPUTE + 1);
  1964. } else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_TRANSFER_BIT)) {
  1965. return CommandQueueFamilyID(D3D12_COMMAND_LIST_TYPE_COPY + 1);
  1966. } else {
  1967. return CommandQueueFamilyID();
  1968. }
  1969. }
  1970. // ----- QUEUE -----
  1971. RDD::CommandQueueID RenderingDeviceDriverD3D12::command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue) {
  1972. ComPtr<ID3D12CommandQueue> d3d_queue;
  1973. D3D12_COMMAND_QUEUE_DESC queue_desc = {};
  1974. queue_desc.Type = (D3D12_COMMAND_LIST_TYPE)(p_cmd_queue_family.id - 1);
  1975. HRESULT res = device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(d3d_queue.GetAddressOf()));
  1976. ERR_FAIL_COND_V(!SUCCEEDED(res), CommandQueueID());
  1977. CommandQueueInfo *command_queue = memnew(CommandQueueInfo);
  1978. command_queue->d3d_queue = d3d_queue;
  1979. return CommandQueueID(command_queue);
  1980. }
  1981. Error RenderingDeviceDriverD3D12::command_queue_execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID> p_wait_semaphores, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID> p_cmd_semaphores, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains) {
  1982. CommandQueueInfo *command_queue = (CommandQueueInfo *)(p_cmd_queue.id);
  1983. for (uint32_t i = 0; i < p_wait_semaphores.size(); i++) {
  1984. const SemaphoreInfo *semaphore = (const SemaphoreInfo *)(p_wait_semaphores[i].id);
  1985. command_queue->d3d_queue->Wait(semaphore->d3d_fence.Get(), semaphore->fence_value);
  1986. }
  1987. if (p_cmd_buffers.size() > 0) {
  1988. thread_local LocalVector<ID3D12CommandList *> command_lists;
  1989. command_lists.resize(p_cmd_buffers.size());
  1990. for (uint32_t i = 0; i < p_cmd_buffers.size(); i++) {
  1991. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)(p_cmd_buffers[i].id);
  1992. command_lists[i] = cmd_buf_info->cmd_list.Get();
  1993. }
  1994. command_queue->d3d_queue->ExecuteCommandLists(command_lists.size(), command_lists.ptr());
  1995. for (uint32_t i = 0; i < p_cmd_semaphores.size(); i++) {
  1996. SemaphoreInfo *semaphore = (SemaphoreInfo *)(p_cmd_semaphores[i].id);
  1997. semaphore->fence_value++;
  1998. command_queue->d3d_queue->Signal(semaphore->d3d_fence.Get(), semaphore->fence_value);
  1999. }
  2000. if (p_cmd_fence) {
  2001. FenceInfo *fence = (FenceInfo *)(p_cmd_fence.id);
  2002. fence->fence_value++;
  2003. command_queue->d3d_queue->Signal(fence->d3d_fence.Get(), fence->fence_value);
  2004. }
  2005. }
  2006. HRESULT res;
  2007. bool any_present_failed = false;
  2008. for (uint32_t i = 0; i < p_swap_chains.size(); i++) {
  2009. SwapChain *swap_chain = (SwapChain *)(p_swap_chains[i].id);
  2010. res = swap_chain->d3d_swap_chain->Present(swap_chain->sync_interval, swap_chain->present_flags);
  2011. if (!SUCCEEDED(res)) {
  2012. print_verbose(vformat("D3D12: Presenting swapchain failed with error 0x%08ux.", (uint64_t)res));
  2013. any_present_failed = true;
  2014. }
  2015. }
  2016. return any_present_failed ? FAILED : OK;
  2017. }
  2018. void RenderingDeviceDriverD3D12::command_queue_free(CommandQueueID p_cmd_queue) {
  2019. CommandQueueInfo *command_queue = (CommandQueueInfo *)(p_cmd_queue.id);
  2020. memdelete(command_queue);
  2021. }
  2022. // ----- POOL -----
  2023. RDD::CommandPoolID RenderingDeviceDriverD3D12::command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) {
  2024. CommandPoolInfo *command_pool = memnew(CommandPoolInfo);
  2025. command_pool->queue_family = p_cmd_queue_family;
  2026. command_pool->buffer_type = p_cmd_buffer_type;
  2027. return CommandPoolID(command_pool);
  2028. }
  2029. void RenderingDeviceDriverD3D12::command_pool_free(CommandPoolID p_cmd_pool) {
  2030. CommandPoolInfo *command_pool = (CommandPoolInfo *)(p_cmd_pool.id);
  2031. memdelete(command_pool);
  2032. }
  2033. // ----- BUFFER -----
  2034. RDD::CommandBufferID RenderingDeviceDriverD3D12::command_buffer_create(CommandPoolID p_cmd_pool) {
  2035. DEV_ASSERT(p_cmd_pool);
  2036. const CommandPoolInfo *command_pool = (CommandPoolInfo *)(p_cmd_pool.id);
  2037. D3D12_COMMAND_LIST_TYPE list_type;
  2038. if (command_pool->buffer_type == COMMAND_BUFFER_TYPE_SECONDARY) {
  2039. list_type = D3D12_COMMAND_LIST_TYPE_BUNDLE;
  2040. } else {
  2041. list_type = D3D12_COMMAND_LIST_TYPE(command_pool->queue_family.id - 1);
  2042. }
  2043. ID3D12CommandAllocator *cmd_allocator = nullptr;
  2044. {
  2045. HRESULT res = device->CreateCommandAllocator(list_type, IID_PPV_ARGS(&cmd_allocator));
  2046. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), CommandBufferID(), "CreateCommandAllocator failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2047. }
  2048. ID3D12GraphicsCommandList *cmd_list = nullptr;
  2049. {
  2050. ComPtr<ID3D12Device4> device_4;
  2051. device->QueryInterface(device_4.GetAddressOf());
  2052. HRESULT res = E_FAIL;
  2053. if (device_4) {
  2054. res = device_4->CreateCommandList1(0, list_type, D3D12_COMMAND_LIST_FLAG_NONE, IID_PPV_ARGS(&cmd_list));
  2055. } else {
  2056. res = device->CreateCommandList(0, list_type, cmd_allocator, nullptr, IID_PPV_ARGS(&cmd_list));
  2057. }
  2058. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), CommandBufferID(), "CreateCommandList failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2059. if (!device_4) {
  2060. cmd_list->Close();
  2061. }
  2062. }
  2063. // Bookkeep
  2064. CommandBufferInfo *cmd_buf_info = VersatileResource::allocate<CommandBufferInfo>(resources_allocator);
  2065. cmd_buf_info->cmd_allocator = cmd_allocator;
  2066. cmd_buf_info->cmd_list = cmd_list;
  2067. return CommandBufferID(cmd_buf_info);
  2068. }
  2069. bool RenderingDeviceDriverD3D12::command_buffer_begin(CommandBufferID p_cmd_buffer) {
  2070. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  2071. HRESULT res = cmd_buf_info->cmd_allocator->Reset();
  2072. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "Reset failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2073. res = cmd_buf_info->cmd_list->Reset(cmd_buf_info->cmd_allocator.Get(), nullptr);
  2074. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "Reset failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2075. return true;
  2076. }
  2077. bool RenderingDeviceDriverD3D12::command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) {
  2078. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  2079. HRESULT res = cmd_buf_info->cmd_allocator->Reset();
  2080. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "Reset failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2081. res = cmd_buf_info->cmd_list->Reset(cmd_buf_info->cmd_allocator.Get(), nullptr);
  2082. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "Reset failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2083. return true;
  2084. }
  2085. void RenderingDeviceDriverD3D12::command_buffer_end(CommandBufferID p_cmd_buffer) {
  2086. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  2087. HRESULT res = cmd_buf_info->cmd_list->Close();
  2088. ERR_FAIL_COND_MSG(!SUCCEEDED(res), "Close failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2089. cmd_buf_info->graphics_pso = nullptr;
  2090. cmd_buf_info->graphics_root_signature_crc = 0;
  2091. cmd_buf_info->compute_pso = nullptr;
  2092. cmd_buf_info->compute_root_signature_crc = 0;
  2093. cmd_buf_info->descriptor_heaps_set = false;
  2094. }
  2095. void RenderingDeviceDriverD3D12::command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) {
  2096. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  2097. for (uint32_t i = 0; i < p_secondary_cmd_buffers.size(); i++) {
  2098. const CommandBufferInfo *secondary_cb_info = (const CommandBufferInfo *)p_secondary_cmd_buffers[i].id;
  2099. cmd_buf_info->cmd_list->ExecuteBundle(secondary_cb_info->cmd_list.Get());
  2100. }
  2101. }
  2102. /********************/
  2103. /**** SWAP CHAIN ****/
  2104. /********************/
  2105. void RenderingDeviceDriverD3D12::_swap_chain_release(SwapChain *p_swap_chain) {
  2106. _swap_chain_release_buffers(p_swap_chain);
  2107. p_swap_chain->d3d_swap_chain.Reset();
  2108. }
  2109. void RenderingDeviceDriverD3D12::_swap_chain_release_buffers(SwapChain *p_swap_chain) {
  2110. for (ID3D12Resource *render_target : p_swap_chain->render_targets) {
  2111. render_target->Release();
  2112. }
  2113. p_swap_chain->render_targets.clear();
  2114. p_swap_chain->render_targets_info.clear();
  2115. for (RDD::FramebufferID framebuffer : p_swap_chain->framebuffers) {
  2116. framebuffer_free(framebuffer);
  2117. }
  2118. p_swap_chain->framebuffers.clear();
  2119. }
  2120. RDD::SwapChainID RenderingDeviceDriverD3D12::swap_chain_create(RenderingContextDriver::SurfaceID p_surface) {
  2121. // Create the render pass that will be used to draw to the swap chain's framebuffers.
  2122. RDD::Attachment attachment;
  2123. attachment.format = DATA_FORMAT_R8G8B8A8_UNORM;
  2124. attachment.samples = RDD::TEXTURE_SAMPLES_1;
  2125. attachment.load_op = RDD::ATTACHMENT_LOAD_OP_CLEAR;
  2126. attachment.store_op = RDD::ATTACHMENT_STORE_OP_STORE;
  2127. RDD::Subpass subpass;
  2128. RDD::AttachmentReference color_ref;
  2129. color_ref.attachment = 0;
  2130. color_ref.aspect.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);
  2131. subpass.color_references.push_back(color_ref);
  2132. RenderPassID render_pass = render_pass_create(attachment, subpass, {}, 1);
  2133. ERR_FAIL_COND_V(!render_pass, SwapChainID());
  2134. // Create the empty swap chain until it is resized.
  2135. SwapChain *swap_chain = memnew(SwapChain);
  2136. swap_chain->surface = p_surface;
  2137. swap_chain->data_format = attachment.format;
  2138. swap_chain->render_pass = render_pass;
  2139. return SwapChainID(swap_chain);
  2140. }
  2141. Error RenderingDeviceDriverD3D12::swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) {
  2142. DEV_ASSERT(p_cmd_queue.id != 0);
  2143. DEV_ASSERT(p_swap_chain.id != 0);
  2144. CommandQueueInfo *command_queue = (CommandQueueInfo *)(p_cmd_queue.id);
  2145. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  2146. RenderingContextDriverD3D12::Surface *surface = (RenderingContextDriverD3D12::Surface *)(swap_chain->surface);
  2147. if (surface->width == 0 || surface->height == 0) {
  2148. // Very likely the window is minimized, don't create a swap chain.
  2149. return ERR_SKIP;
  2150. }
  2151. HRESULT res;
  2152. const bool is_tearing_supported = context_driver->get_tearing_supported();
  2153. UINT sync_interval = 0;
  2154. UINT present_flags = 0;
  2155. UINT creation_flags = 0;
  2156. switch (surface->vsync_mode) {
  2157. case DisplayServer::VSYNC_MAILBOX: {
  2158. sync_interval = 1;
  2159. present_flags = DXGI_PRESENT_RESTART;
  2160. } break;
  2161. case DisplayServer::VSYNC_ENABLED: {
  2162. sync_interval = 1;
  2163. present_flags = 0;
  2164. } break;
  2165. case DisplayServer::VSYNC_DISABLED: {
  2166. sync_interval = 0;
  2167. present_flags = is_tearing_supported ? DXGI_PRESENT_ALLOW_TEARING : 0;
  2168. creation_flags = is_tearing_supported ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;
  2169. } break;
  2170. case DisplayServer::VSYNC_ADAPTIVE: // Unsupported.
  2171. default:
  2172. sync_interval = 1;
  2173. present_flags = 0;
  2174. break;
  2175. }
  2176. if (swap_chain->d3d_swap_chain != nullptr && creation_flags != swap_chain->creation_flags) {
  2177. // The swap chain must be recreated if the creation flags are different.
  2178. _swap_chain_release(swap_chain);
  2179. }
  2180. DXGI_SWAP_CHAIN_DESC1 swap_chain_desc = {};
  2181. if (swap_chain->d3d_swap_chain != nullptr) {
  2182. _swap_chain_release_buffers(swap_chain);
  2183. res = swap_chain->d3d_swap_chain->ResizeBuffers(p_desired_framebuffer_count, 0, 0, DXGI_FORMAT_UNKNOWN, creation_flags);
  2184. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_UNAVAILABLE);
  2185. } else {
  2186. swap_chain_desc.BufferCount = p_desired_framebuffer_count;
  2187. swap_chain_desc.Format = RD_TO_D3D12_FORMAT[swap_chain->data_format].general_format;
  2188. swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  2189. swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  2190. swap_chain_desc.SampleDesc.Count = 1;
  2191. swap_chain_desc.Flags = creation_flags;
  2192. swap_chain_desc.Scaling = DXGI_SCALING_NONE;
  2193. if (OS::get_singleton()->is_layered_allowed()) {
  2194. swap_chain_desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
  2195. has_comp_alpha[(uint64_t)p_cmd_queue.id] = true;
  2196. } else {
  2197. swap_chain_desc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
  2198. has_comp_alpha[(uint64_t)p_cmd_queue.id] = false;
  2199. }
  2200. ComPtr<IDXGISwapChain1> swap_chain_1;
  2201. res = context_driver->dxgi_factory_get()->CreateSwapChainForHwnd(command_queue->d3d_queue.Get(), surface->hwnd, &swap_chain_desc, nullptr, nullptr, swap_chain_1.GetAddressOf());
  2202. if (!SUCCEEDED(res) && swap_chain_desc.AlphaMode != DXGI_ALPHA_MODE_IGNORE) {
  2203. swap_chain_desc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
  2204. has_comp_alpha[(uint64_t)p_cmd_queue.id] = false;
  2205. res = context_driver->dxgi_factory_get()->CreateSwapChainForHwnd(command_queue->d3d_queue.Get(), surface->hwnd, &swap_chain_desc, nullptr, nullptr, swap_chain_1.GetAddressOf());
  2206. }
  2207. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  2208. swap_chain_1.As(&swap_chain->d3d_swap_chain);
  2209. ERR_FAIL_NULL_V(swap_chain->d3d_swap_chain, ERR_CANT_CREATE);
  2210. res = context_driver->dxgi_factory_get()->MakeWindowAssociation(surface->hwnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES);
  2211. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  2212. }
  2213. res = swap_chain->d3d_swap_chain->GetDesc1(&swap_chain_desc);
  2214. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  2215. ERR_FAIL_COND_V(swap_chain_desc.BufferCount == 0, ERR_CANT_CREATE);
  2216. surface->width = swap_chain_desc.Width;
  2217. surface->height = swap_chain_desc.Height;
  2218. swap_chain->creation_flags = creation_flags;
  2219. swap_chain->sync_interval = sync_interval;
  2220. swap_chain->present_flags = present_flags;
  2221. // Retrieve the render targets associated to the swap chain and recreate the framebuffers. The following code
  2222. // relies on the address of the elements remaining static when new elements are inserted, so the container must
  2223. // follow this restriction when reserving the right amount of elements beforehand.
  2224. swap_chain->render_targets.reserve(swap_chain_desc.BufferCount);
  2225. swap_chain->render_targets_info.reserve(swap_chain_desc.BufferCount);
  2226. swap_chain->framebuffers.reserve(swap_chain_desc.BufferCount);
  2227. for (uint32_t i = 0; i < swap_chain_desc.BufferCount; i++) {
  2228. // Retrieve the resource corresponding to the swap chain's buffer.
  2229. ID3D12Resource *render_target = nullptr;
  2230. res = swap_chain->d3d_swap_chain->GetBuffer(i, IID_PPV_ARGS(&render_target));
  2231. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  2232. swap_chain->render_targets.push_back(render_target);
  2233. // Create texture information for the framebuffer to reference the resource. Since the states pointer must
  2234. // reference an address of the element itself, we must insert it first and then modify it.
  2235. swap_chain->render_targets_info.push_back(TextureInfo());
  2236. TextureInfo &texture_info = swap_chain->render_targets_info[i];
  2237. texture_info.owner_info.states.subresource_states.push_back(D3D12_RESOURCE_STATE_PRESENT);
  2238. texture_info.states_ptr = &texture_info.owner_info.states;
  2239. texture_info.format = swap_chain->data_format;
  2240. #if defined(_MSC_VER) || !defined(_WIN32)
  2241. texture_info.desc = CD3DX12_RESOURCE_DESC(render_target->GetDesc());
  2242. #else
  2243. render_target->GetDesc(&texture_info.desc);
  2244. #endif
  2245. texture_info.layers = 1;
  2246. texture_info.mipmaps = 1;
  2247. texture_info.resource = render_target;
  2248. texture_info.view_descs.srv.Format = texture_info.desc.Format;
  2249. texture_info.view_descs.srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  2250. // Create the framebuffer for this buffer.
  2251. FramebufferID framebuffer = _framebuffer_create(swap_chain->render_pass, TextureID(&swap_chain->render_targets_info[i]), swap_chain_desc.Width, swap_chain_desc.Height, true);
  2252. ERR_FAIL_COND_V(!framebuffer, ERR_CANT_CREATE);
  2253. swap_chain->framebuffers.push_back(framebuffer);
  2254. }
  2255. // Once everything's been created correctly, indicate the surface no longer needs to be resized.
  2256. context_driver->surface_set_needs_resize(swap_chain->surface, false);
  2257. return OK;
  2258. }
  2259. RDD::FramebufferID RenderingDeviceDriverD3D12::swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) {
  2260. DEV_ASSERT(p_swap_chain.id != 0);
  2261. const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
  2262. if (context_driver->surface_get_needs_resize(swap_chain->surface)) {
  2263. r_resize_required = true;
  2264. return FramebufferID();
  2265. }
  2266. const uint32_t buffer_index = swap_chain->d3d_swap_chain->GetCurrentBackBufferIndex();
  2267. DEV_ASSERT(buffer_index < swap_chain->framebuffers.size());
  2268. return swap_chain->framebuffers[buffer_index];
  2269. }
  2270. RDD::RenderPassID RenderingDeviceDriverD3D12::swap_chain_get_render_pass(SwapChainID p_swap_chain) {
  2271. const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
  2272. return swap_chain->render_pass;
  2273. }
  2274. RDD::DataFormat RenderingDeviceDriverD3D12::swap_chain_get_format(SwapChainID p_swap_chain) {
  2275. const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
  2276. return swap_chain->data_format;
  2277. }
  2278. void RenderingDeviceDriverD3D12::swap_chain_free(SwapChainID p_swap_chain) {
  2279. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  2280. _swap_chain_release(swap_chain);
  2281. render_pass_free(swap_chain->render_pass);
  2282. memdelete(swap_chain);
  2283. }
  2284. /*********************/
  2285. /**** FRAMEBUFFER ****/
  2286. /*********************/
  2287. D3D12_RENDER_TARGET_VIEW_DESC RenderingDeviceDriverD3D12::_make_rtv_for_texture(const TextureInfo *p_texture_info, uint32_t p_mipmap_offset, uint32_t p_layer_offset, uint32_t p_layers, bool p_add_bases) {
  2288. D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = {};
  2289. rtv_desc.Format = p_texture_info->view_descs.srv.Format;
  2290. switch (p_texture_info->view_descs.srv.ViewDimension) {
  2291. case D3D12_SRV_DIMENSION_TEXTURE1D: {
  2292. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D;
  2293. rtv_desc.Texture1D.MipSlice = p_texture_info->base_mip + p_mipmap_offset;
  2294. } break;
  2295. case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: {
  2296. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY;
  2297. rtv_desc.Texture1DArray.MipSlice = (p_add_bases ? p_texture_info->base_mip : 0) + p_mipmap_offset;
  2298. rtv_desc.Texture1DArray.FirstArraySlice = (p_add_bases ? p_texture_info->base_layer : 0) + p_layer_offset;
  2299. rtv_desc.Texture1DArray.ArraySize = p_layers == UINT32_MAX ? p_texture_info->view_descs.srv.Texture1DArray.ArraySize : p_layers;
  2300. } break;
  2301. case D3D12_SRV_DIMENSION_TEXTURE2D: {
  2302. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
  2303. rtv_desc.Texture2D.MipSlice = (p_add_bases ? p_texture_info->base_mip : 0) + p_mipmap_offset;
  2304. rtv_desc.Texture2D.PlaneSlice = p_texture_info->view_descs.srv.Texture2D.PlaneSlice;
  2305. } break;
  2306. case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: {
  2307. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
  2308. rtv_desc.Texture2DArray.MipSlice = (p_add_bases ? p_texture_info->base_mip : 0) + p_mipmap_offset;
  2309. rtv_desc.Texture2DArray.FirstArraySlice = (p_add_bases ? p_texture_info->base_layer : 0) + p_layer_offset;
  2310. rtv_desc.Texture2DArray.ArraySize = p_layers == UINT32_MAX ? p_texture_info->view_descs.srv.Texture2DArray.ArraySize : p_layers;
  2311. rtv_desc.Texture2DArray.PlaneSlice = p_texture_info->view_descs.srv.Texture2DArray.PlaneSlice;
  2312. } break;
  2313. case D3D12_SRV_DIMENSION_TEXTURE2DMS: {
  2314. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
  2315. } break;
  2316. case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: {
  2317. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
  2318. rtv_desc.Texture2DMSArray.FirstArraySlice = (p_add_bases ? p_texture_info->base_layer : 0) + p_layer_offset;
  2319. rtv_desc.Texture2DMSArray.ArraySize = p_layers == UINT32_MAX ? p_texture_info->view_descs.srv.Texture2DMSArray.ArraySize : p_layers;
  2320. } break;
  2321. case D3D12_SRV_DIMENSION_TEXTURE3D: {
  2322. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D;
  2323. rtv_desc.Texture3D.MipSlice = p_texture_info->view_descs.srv.Texture3D.MostDetailedMip + p_mipmap_offset;
  2324. rtv_desc.Texture3D.FirstWSlice = 0;
  2325. rtv_desc.Texture3D.WSize = -1;
  2326. } break;
  2327. case D3D12_SRV_DIMENSION_TEXTURECUBE:
  2328. case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: {
  2329. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
  2330. rtv_desc.Texture2DArray.MipSlice = (p_add_bases ? p_texture_info->base_mip : 0) + p_mipmap_offset;
  2331. rtv_desc.Texture2DArray.FirstArraySlice = (p_add_bases ? p_texture_info->base_layer : 0) + p_layer_offset;
  2332. rtv_desc.Texture2DArray.ArraySize = p_layers == UINT32_MAX ? p_texture_info->layers : p_layers;
  2333. rtv_desc.Texture2DArray.PlaneSlice = 0;
  2334. } break;
  2335. default: {
  2336. DEV_ASSERT(false);
  2337. }
  2338. }
  2339. return rtv_desc;
  2340. }
  2341. D3D12_UNORDERED_ACCESS_VIEW_DESC RenderingDeviceDriverD3D12::_make_ranged_uav_for_texture(const TextureInfo *p_texture_info, uint32_t p_mipmap_offset, uint32_t p_layer_offset, uint32_t p_layers, bool p_add_bases) {
  2342. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = p_texture_info->view_descs.uav;
  2343. uint32_t mip = (p_add_bases ? p_texture_info->base_mip : 0) + p_mipmap_offset;
  2344. switch (p_texture_info->view_descs.uav.ViewDimension) {
  2345. case D3D12_UAV_DIMENSION_TEXTURE1D: {
  2346. uav_desc.Texture1DArray.MipSlice = mip;
  2347. } break;
  2348. case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: {
  2349. uav_desc.Texture1DArray.MipSlice = mip;
  2350. uav_desc.Texture1DArray.FirstArraySlice = mip;
  2351. uav_desc.Texture1DArray.ArraySize = p_layers;
  2352. } break;
  2353. case D3D12_UAV_DIMENSION_TEXTURE2D: {
  2354. uav_desc.Texture2D.MipSlice = mip;
  2355. } break;
  2356. case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: {
  2357. uav_desc.Texture2DArray.MipSlice = mip;
  2358. uav_desc.Texture2DArray.FirstArraySlice = (p_add_bases ? p_texture_info->base_layer : 0) + p_layer_offset;
  2359. uav_desc.Texture2DArray.ArraySize = p_layers;
  2360. } break;
  2361. case D3D12_UAV_DIMENSION_TEXTURE3D: {
  2362. uav_desc.Texture3D.MipSlice = mip;
  2363. uav_desc.Texture3D.WSize >>= p_mipmap_offset;
  2364. } break;
  2365. default:
  2366. break;
  2367. }
  2368. return uav_desc;
  2369. }
  2370. D3D12_DEPTH_STENCIL_VIEW_DESC RenderingDeviceDriverD3D12::_make_dsv_for_texture(const TextureInfo *p_texture_info) {
  2371. D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc = {};
  2372. dsv_desc.Format = RD_TO_D3D12_FORMAT[p_texture_info->format].dsv_format;
  2373. dsv_desc.Flags = D3D12_DSV_FLAG_NONE;
  2374. switch (p_texture_info->view_descs.srv.ViewDimension) {
  2375. case D3D12_SRV_DIMENSION_TEXTURE1D: {
  2376. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1D;
  2377. dsv_desc.Texture1D.MipSlice = p_texture_info->base_mip;
  2378. } break;
  2379. case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: {
  2380. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1DARRAY;
  2381. dsv_desc.Texture1DArray.MipSlice = p_texture_info->base_mip;
  2382. dsv_desc.Texture1DArray.FirstArraySlice = p_texture_info->base_layer;
  2383. dsv_desc.Texture1DArray.ArraySize = p_texture_info->view_descs.srv.Texture1DArray.ArraySize;
  2384. } break;
  2385. case D3D12_SRV_DIMENSION_TEXTURE2D: {
  2386. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
  2387. dsv_desc.Texture2D.MipSlice = p_texture_info->view_descs.srv.Texture2D.MostDetailedMip;
  2388. } break;
  2389. case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: {
  2390. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
  2391. dsv_desc.Texture2DArray.MipSlice = p_texture_info->base_mip;
  2392. dsv_desc.Texture2DArray.FirstArraySlice = p_texture_info->base_layer;
  2393. dsv_desc.Texture2DArray.ArraySize = p_texture_info->view_descs.srv.Texture2DArray.ArraySize;
  2394. } break;
  2395. case D3D12_SRV_DIMENSION_TEXTURE2DMS: {
  2396. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS;
  2397. dsv_desc.Texture2DMS.UnusedField_NothingToDefine = p_texture_info->view_descs.srv.Texture2DMS.UnusedField_NothingToDefine;
  2398. } break;
  2399. case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: {
  2400. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY;
  2401. dsv_desc.Texture2DMSArray.FirstArraySlice = p_texture_info->base_layer;
  2402. dsv_desc.Texture2DMSArray.ArraySize = p_texture_info->view_descs.srv.Texture2DMSArray.ArraySize;
  2403. } break;
  2404. default: {
  2405. DEV_ASSERT(false);
  2406. }
  2407. }
  2408. return dsv_desc;
  2409. }
  2410. RDD::FramebufferID RenderingDeviceDriverD3D12::_framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height, bool p_is_screen) {
  2411. // Pre-bookkeep.
  2412. FramebufferInfo *fb_info = VersatileResource::allocate<FramebufferInfo>(resources_allocator);
  2413. fb_info->is_screen = p_is_screen;
  2414. const RenderPassInfo *pass_info = (const RenderPassInfo *)p_render_pass.id;
  2415. uint32_t num_color = 0;
  2416. uint32_t num_depth_stencil = 0;
  2417. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  2418. const TextureInfo *tex_info = (const TextureInfo *)p_attachments[i].id;
  2419. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
  2420. num_color++;
  2421. } else if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  2422. num_depth_stencil++;
  2423. }
  2424. }
  2425. uint32_t vrs_index = UINT32_MAX;
  2426. for (const Subpass &E : pass_info->subpasses) {
  2427. if (E.vrs_reference.attachment != AttachmentReference::UNUSED) {
  2428. vrs_index = E.vrs_reference.attachment;
  2429. }
  2430. }
  2431. if (num_color) {
  2432. Error err = fb_info->rtv_heap.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_RTV, num_color, false);
  2433. if (err) {
  2434. VersatileResource::free(resources_allocator, fb_info);
  2435. ERR_FAIL_V(FramebufferID());
  2436. }
  2437. }
  2438. DescriptorsHeap::Walker rtv_heap_walker = fb_info->rtv_heap.make_walker();
  2439. if (num_depth_stencil) {
  2440. Error err = fb_info->dsv_heap.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_DSV, num_depth_stencil, false);
  2441. if (err) {
  2442. VersatileResource::free(resources_allocator, fb_info);
  2443. ERR_FAIL_V(FramebufferID());
  2444. }
  2445. }
  2446. DescriptorsHeap::Walker dsv_heap_walker = fb_info->dsv_heap.make_walker();
  2447. fb_info->attachments_handle_inds.resize(p_attachments.size());
  2448. fb_info->attachments.reserve(num_color + num_depth_stencil);
  2449. uint32_t color_idx = 0;
  2450. uint32_t depth_stencil_idx = 0;
  2451. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  2452. const TextureInfo *tex_info = (const TextureInfo *)p_attachments[i].id;
  2453. if (fb_info->size.x == 0) {
  2454. fb_info->size = Size2i(tex_info->desc.Width, tex_info->desc.Height);
  2455. }
  2456. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
  2457. D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = _make_rtv_for_texture(tex_info, 0, 0, UINT32_MAX);
  2458. device->CreateRenderTargetView(tex_info->resource, &rtv_desc, rtv_heap_walker.get_curr_cpu_handle());
  2459. rtv_heap_walker.advance();
  2460. fb_info->attachments_handle_inds[i] = color_idx;
  2461. fb_info->attachments.push_back(p_attachments[i]);
  2462. color_idx++;
  2463. } else if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  2464. D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc = _make_dsv_for_texture(tex_info);
  2465. device->CreateDepthStencilView(tex_info->resource, &dsv_desc, dsv_heap_walker.get_curr_cpu_handle());
  2466. dsv_heap_walker.advance();
  2467. fb_info->attachments_handle_inds[i] = depth_stencil_idx;
  2468. fb_info->attachments.push_back(p_attachments[i]);
  2469. depth_stencil_idx++;
  2470. } else if (i == vrs_index) {
  2471. fb_info->vrs_attachment = p_attachments[i];
  2472. } else {
  2473. DEV_ASSERT(false);
  2474. }
  2475. }
  2476. DEV_ASSERT(fb_info->attachments.size() == color_idx + depth_stencil_idx);
  2477. DEV_ASSERT((fb_info->vrs_attachment.id != 0) == (vrs_index != UINT32_MAX));
  2478. DEV_ASSERT(rtv_heap_walker.is_at_eof());
  2479. DEV_ASSERT(dsv_heap_walker.is_at_eof());
  2480. return FramebufferID(fb_info);
  2481. }
  2482. RDD::FramebufferID RenderingDeviceDriverD3D12::framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) {
  2483. return _framebuffer_create(p_render_pass, p_attachments, p_width, p_height, false);
  2484. }
  2485. void RenderingDeviceDriverD3D12::framebuffer_free(FramebufferID p_framebuffer) {
  2486. FramebufferInfo *fb_info = (FramebufferInfo *)p_framebuffer.id;
  2487. VersatileResource::free(resources_allocator, fb_info);
  2488. }
  2489. /****************/
  2490. /**** SHADER ****/
  2491. /****************/
  2492. static uint32_t SHADER_STAGES_BIT_OFFSET_INDICES[RenderingDevice::SHADER_STAGE_MAX] = {
  2493. /* SHADER_STAGE_VERTEX */ 0,
  2494. /* SHADER_STAGE_FRAGMENT */ 1,
  2495. /* SHADER_STAGE_TESSELATION_CONTROL */ UINT32_MAX,
  2496. /* SHADER_STAGE_TESSELATION_EVALUATION */ UINT32_MAX,
  2497. /* SHADER_STAGE_COMPUTE */ 2,
  2498. };
  2499. uint32_t RenderingDeviceDriverD3D12::_shader_patch_dxil_specialization_constant(
  2500. PipelineSpecializationConstantType p_type,
  2501. const void *p_value,
  2502. const uint64_t (&p_stages_bit_offsets)[D3D12_BITCODE_OFFSETS_NUM_STAGES],
  2503. HashMap<ShaderStage, Vector<uint8_t>> &r_stages_bytecodes,
  2504. bool p_is_first_patch) {
  2505. uint32_t patch_val = 0;
  2506. switch (p_type) {
  2507. case PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT: {
  2508. uint32_t int_value = *((const int *)p_value);
  2509. ERR_FAIL_COND_V(int_value & (1 << 31), 0);
  2510. patch_val = int_value;
  2511. } break;
  2512. case PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL: {
  2513. bool bool_value = *((const bool *)p_value);
  2514. patch_val = (uint32_t)bool_value;
  2515. } break;
  2516. case PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT: {
  2517. uint32_t int_value = *((const int *)p_value);
  2518. ERR_FAIL_COND_V(int_value & (1 << 31), 0);
  2519. patch_val = (int_value >> 1);
  2520. } break;
  2521. }
  2522. // For VBR encoding to encode the number of bits we expect (32), we need to set the MSB unconditionally.
  2523. // However, signed VBR moves the MSB to the LSB, so setting the MSB to 1 wouldn't help. Therefore,
  2524. // the bit we set to 1 is the one at index 30.
  2525. patch_val |= (1 << 30);
  2526. patch_val <<= 1; // What signed VBR does.
  2527. auto tamper_bits = [](uint8_t *p_start, uint64_t p_bit_offset, uint64_t p_tb_value) -> uint64_t {
  2528. uint64_t original = 0;
  2529. uint32_t curr_input_byte = p_bit_offset / 8;
  2530. uint8_t curr_input_bit = p_bit_offset % 8;
  2531. auto get_curr_input_bit = [&]() -> bool {
  2532. return ((p_start[curr_input_byte] >> curr_input_bit) & 1);
  2533. };
  2534. auto move_to_next_input_bit = [&]() {
  2535. if (curr_input_bit == 7) {
  2536. curr_input_bit = 0;
  2537. curr_input_byte++;
  2538. } else {
  2539. curr_input_bit++;
  2540. }
  2541. };
  2542. auto tamper_input_bit = [&](bool p_new_bit) {
  2543. p_start[curr_input_byte] &= ~((uint8_t)1 << curr_input_bit);
  2544. if (p_new_bit) {
  2545. p_start[curr_input_byte] |= (uint8_t)1 << curr_input_bit;
  2546. }
  2547. };
  2548. uint8_t value_bit_idx = 0;
  2549. for (uint32_t i = 0; i < 5; i++) { // 32 bits take 5 full bytes in VBR.
  2550. for (uint32_t j = 0; j < 7; j++) {
  2551. bool input_bit = get_curr_input_bit();
  2552. original |= (uint64_t)(input_bit ? 1 : 0) << value_bit_idx;
  2553. tamper_input_bit((p_tb_value >> value_bit_idx) & 1);
  2554. move_to_next_input_bit();
  2555. value_bit_idx++;
  2556. }
  2557. #ifdef DEV_ENABLED
  2558. bool input_bit = get_curr_input_bit();
  2559. DEV_ASSERT((i < 4 && input_bit) || (i == 4 && !input_bit));
  2560. #endif
  2561. move_to_next_input_bit();
  2562. }
  2563. return original;
  2564. };
  2565. uint32_t stages_patched_mask = 0;
  2566. for (int stage = 0; stage < SHADER_STAGE_MAX; stage++) {
  2567. if (!r_stages_bytecodes.has((ShaderStage)stage)) {
  2568. continue;
  2569. }
  2570. uint64_t offset = p_stages_bit_offsets[SHADER_STAGES_BIT_OFFSET_INDICES[stage]];
  2571. if (offset == 0) {
  2572. // This constant does not appear at this stage.
  2573. continue;
  2574. }
  2575. Vector<uint8_t> &bytecode = r_stages_bytecodes[(ShaderStage)stage];
  2576. #ifdef DEV_ENABLED
  2577. uint64_t orig_patch_val = tamper_bits(bytecode.ptrw(), offset, patch_val);
  2578. // Checking against the value the NIR patch should have set.
  2579. DEV_ASSERT(!p_is_first_patch || ((orig_patch_val >> 1) & GODOT_NIR_SC_SENTINEL_MAGIC_MASK) == GODOT_NIR_SC_SENTINEL_MAGIC);
  2580. uint64_t readback_patch_val = tamper_bits(bytecode.ptrw(), offset, patch_val);
  2581. DEV_ASSERT(readback_patch_val == patch_val);
  2582. #else
  2583. tamper_bits(bytecode.ptrw(), offset, patch_val);
  2584. #endif
  2585. stages_patched_mask |= (1 << stage);
  2586. }
  2587. return stages_patched_mask;
  2588. }
  2589. bool RenderingDeviceDriverD3D12::_shader_apply_specialization_constants(
  2590. const ShaderInfo *p_shader_info,
  2591. VectorView<PipelineSpecializationConstant> p_specialization_constants,
  2592. HashMap<ShaderStage, Vector<uint8_t>> &r_final_stages_bytecode) {
  2593. // If something needs to be patched, COW will do the trick.
  2594. r_final_stages_bytecode = p_shader_info->stages_bytecode;
  2595. uint32_t stages_re_sign_mask = 0;
  2596. for (uint32_t i = 0; i < p_specialization_constants.size(); i++) {
  2597. const PipelineSpecializationConstant &psc = p_specialization_constants[i];
  2598. if (!(p_shader_info->spirv_specialization_constants_ids_mask & (1 << psc.constant_id))) {
  2599. // This SC wasn't even in the original SPIR-V shader.
  2600. continue;
  2601. }
  2602. for (const ShaderInfo::SpecializationConstant &sc : p_shader_info->specialization_constants) {
  2603. if (psc.constant_id == sc.constant_id) {
  2604. if (psc.int_value != sc.int_value) {
  2605. stages_re_sign_mask |= _shader_patch_dxil_specialization_constant(psc.type, &psc.int_value, sc.stages_bit_offsets, r_final_stages_bytecode, false);
  2606. }
  2607. break;
  2608. }
  2609. }
  2610. }
  2611. // Re-sign patched stages.
  2612. for (KeyValue<ShaderStage, Vector<uint8_t>> &E : r_final_stages_bytecode) {
  2613. ShaderStage stage = E.key;
  2614. if ((stages_re_sign_mask & (1 << stage))) {
  2615. Vector<uint8_t> &bytecode = E.value;
  2616. _shader_sign_dxil_bytecode(stage, bytecode);
  2617. }
  2618. }
  2619. return true;
  2620. }
  2621. void RenderingDeviceDriverD3D12::_shader_sign_dxil_bytecode(ShaderStage p_stage, Vector<uint8_t> &r_dxil_blob) {
  2622. uint8_t *w = r_dxil_blob.ptrw();
  2623. compute_dxil_hash(w + 20, r_dxil_blob.size() - 20, w + 4);
  2624. }
  2625. String RenderingDeviceDriverD3D12::shader_get_binary_cache_key() {
  2626. return "D3D12-SV" + uitos(ShaderBinary::VERSION) + "-" + itos(shader_capabilities.shader_model);
  2627. }
  2628. Vector<uint8_t> RenderingDeviceDriverD3D12::shader_compile_binary_from_spirv(VectorView<ShaderStageSPIRVData> p_spirv, const String &p_shader_name) {
  2629. ShaderReflection shader_refl;
  2630. if (_reflect_spirv(p_spirv, shader_refl) != OK) {
  2631. return Vector<uint8_t>();
  2632. }
  2633. // Collect reflection data into binary data.
  2634. ShaderBinary::Data binary_data;
  2635. Vector<Vector<ShaderBinary::DataBinding>> sets_bindings;
  2636. Vector<ShaderBinary::SpecializationConstant> specialization_constants;
  2637. {
  2638. binary_data.vertex_input_mask = shader_refl.vertex_input_mask;
  2639. binary_data.fragment_output_mask = shader_refl.fragment_output_mask;
  2640. binary_data.specialization_constants_count = shader_refl.specialization_constants.size();
  2641. binary_data.is_compute = shader_refl.is_compute;
  2642. binary_data.compute_local_size[0] = shader_refl.compute_local_size[0];
  2643. binary_data.compute_local_size[1] = shader_refl.compute_local_size[1];
  2644. binary_data.compute_local_size[2] = shader_refl.compute_local_size[2];
  2645. binary_data.set_count = shader_refl.uniform_sets.size();
  2646. binary_data.push_constant_size = shader_refl.push_constant_size;
  2647. binary_data.nir_runtime_data_root_param_idx = UINT32_MAX;
  2648. binary_data.stage_count = p_spirv.size();
  2649. for (const Vector<ShaderUniform> &spirv_set : shader_refl.uniform_sets) {
  2650. Vector<ShaderBinary::DataBinding> bindings;
  2651. for (const ShaderUniform &spirv_uniform : spirv_set) {
  2652. ShaderBinary::DataBinding binding;
  2653. binding.type = (uint32_t)spirv_uniform.type;
  2654. binding.binding = spirv_uniform.binding;
  2655. binding.stages = (uint32_t)spirv_uniform.stages;
  2656. binding.length = spirv_uniform.length;
  2657. binding.writable = (uint32_t)spirv_uniform.writable;
  2658. bindings.push_back(binding);
  2659. }
  2660. sets_bindings.push_back(bindings);
  2661. }
  2662. for (const ShaderSpecializationConstant &spirv_sc : shader_refl.specialization_constants) {
  2663. ShaderBinary::SpecializationConstant spec_constant;
  2664. spec_constant.type = (uint32_t)spirv_sc.type;
  2665. spec_constant.constant_id = spirv_sc.constant_id;
  2666. spec_constant.int_value = spirv_sc.int_value;
  2667. spec_constant.stage_flags = spirv_sc.stages;
  2668. specialization_constants.push_back(spec_constant);
  2669. binary_data.spirv_specialization_constants_ids_mask |= (1 << spirv_sc.constant_id);
  2670. }
  2671. }
  2672. // Translate SPIR-V shaders to DXIL, and collect shader info from the new representation.
  2673. HashMap<ShaderStage, Vector<uint8_t>> dxil_blobs;
  2674. BitField<ShaderStage> stages_processed;
  2675. {
  2676. HashMap<int, nir_shader *> stages_nir_shaders;
  2677. auto free_nir_shaders = [&]() {
  2678. for (KeyValue<int, nir_shader *> &E : stages_nir_shaders) {
  2679. ralloc_free(E.value);
  2680. }
  2681. stages_nir_shaders.clear();
  2682. };
  2683. // This is based on spirv2dxil.c. May need updates when it changes.
  2684. // Also, this has to stay around until after linking.
  2685. nir_shader_compiler_options nir_options = *dxil_get_nir_compiler_options();
  2686. nir_options.lower_base_vertex = false;
  2687. dxil_spirv_runtime_conf dxil_runtime_conf = {};
  2688. dxil_runtime_conf.runtime_data_cbv.base_shader_register = RUNTIME_DATA_REGISTER;
  2689. dxil_runtime_conf.push_constant_cbv.base_shader_register = ROOT_CONSTANT_REGISTER;
  2690. dxil_runtime_conf.zero_based_vertex_instance_id = true;
  2691. dxil_runtime_conf.zero_based_compute_workgroup_id = true;
  2692. dxil_runtime_conf.declared_read_only_images_as_srvs = true;
  2693. // Making this explicit to let maintainers know that in practice this didn't improve performance,
  2694. // probably because data generated by one shader and consumed by another one forces the resource
  2695. // to transition from UAV to SRV, and back, instead of being an UAV all the time.
  2696. // In case someone wants to try, care must be taken so in case of incompatible bindings across stages
  2697. // happen as a result, all the stages are re-translated. That can happen if, for instance, a stage only
  2698. // uses an allegedly writable resource only for reading but the next stage doesn't.
  2699. dxil_runtime_conf.inferred_read_only_images_as_srvs = false;
  2700. // - Translate SPIR-V to NIR.
  2701. for (uint32_t i = 0; i < p_spirv.size(); i++) {
  2702. ShaderStage stage = (ShaderStage)p_spirv[i].shader_stage;
  2703. ShaderStage stage_flag = (ShaderStage)(1 << p_spirv[i].shader_stage);
  2704. stages_processed.set_flag(stage_flag);
  2705. {
  2706. const char *entry_point = "main";
  2707. static const gl_shader_stage SPIRV_TO_MESA_STAGES[SHADER_STAGE_MAX] = {
  2708. /* SHADER_STAGE_VERTEX */ MESA_SHADER_VERTEX,
  2709. /* SHADER_STAGE_FRAGMENT */ MESA_SHADER_FRAGMENT,
  2710. /* SHADER_STAGE_TESSELATION_CONTROL */ MESA_SHADER_TESS_CTRL,
  2711. /* SHADER_STAGE_TESSELATION_EVALUATION */ MESA_SHADER_TESS_EVAL,
  2712. /* SHADER_STAGE_COMPUTE */ MESA_SHADER_COMPUTE,
  2713. };
  2714. nir_shader *shader = spirv_to_nir(
  2715. (const uint32_t *)p_spirv[i].spirv.ptr(),
  2716. p_spirv[i].spirv.size() / sizeof(uint32_t),
  2717. nullptr,
  2718. 0,
  2719. SPIRV_TO_MESA_STAGES[stage],
  2720. entry_point,
  2721. dxil_spirv_nir_get_spirv_options(), &nir_options);
  2722. if (!shader) {
  2723. free_nir_shaders();
  2724. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Shader translation (step 1) at stage " + String(SHADER_STAGE_NAMES[stage]) + " failed.");
  2725. }
  2726. #ifdef DEV_ENABLED
  2727. nir_validate_shader(shader, "Validate before feeding NIR to the DXIL compiler");
  2728. #endif
  2729. if (stage == SHADER_STAGE_VERTEX) {
  2730. dxil_runtime_conf.yz_flip.y_mask = 0xffff;
  2731. dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_Y_FLIP_UNCONDITIONAL;
  2732. } else {
  2733. dxil_runtime_conf.yz_flip.y_mask = 0;
  2734. dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_YZ_FLIP_NONE;
  2735. }
  2736. // This is based on spirv2dxil.c. May need updates when it changes.
  2737. dxil_spirv_nir_prep(shader);
  2738. bool requires_runtime_data = {};
  2739. dxil_spirv_nir_passes(shader, &dxil_runtime_conf, &requires_runtime_data);
  2740. stages_nir_shaders[stage] = shader;
  2741. }
  2742. }
  2743. // - Link NIR shaders.
  2744. for (int i = SHADER_STAGE_MAX - 1; i >= 0; i--) {
  2745. if (!stages_nir_shaders.has(i)) {
  2746. continue;
  2747. }
  2748. nir_shader *shader = stages_nir_shaders[i];
  2749. nir_shader *prev_shader = nullptr;
  2750. for (int j = i - 1; j >= 0; j--) {
  2751. if (stages_nir_shaders.has(j)) {
  2752. prev_shader = stages_nir_shaders[j];
  2753. break;
  2754. }
  2755. }
  2756. if (prev_shader) {
  2757. bool requires_runtime_data = {};
  2758. dxil_spirv_nir_link(shader, prev_shader, &dxil_runtime_conf, &requires_runtime_data);
  2759. }
  2760. }
  2761. // - Translate NIR to DXIL.
  2762. for (uint32_t i = 0; i < p_spirv.size(); i++) {
  2763. ShaderStage stage = (ShaderStage)p_spirv[i].shader_stage;
  2764. struct ShaderData {
  2765. ShaderStage stage;
  2766. ShaderBinary::Data &binary_data;
  2767. Vector<Vector<ShaderBinary::DataBinding>> &sets_bindings;
  2768. Vector<ShaderBinary::SpecializationConstant> &specialization_constants;
  2769. } shader_data{ stage, binary_data, sets_bindings, specialization_constants };
  2770. GodotNirCallbacks godot_nir_callbacks = {};
  2771. godot_nir_callbacks.data = &shader_data;
  2772. godot_nir_callbacks.report_resource = [](uint32_t p_register, uint32_t p_space, uint32_t p_dxil_type, void *p_data) {
  2773. ShaderData &shader_data_in = *(ShaderData *)p_data;
  2774. // Types based on Mesa's dxil_container.h.
  2775. static const uint32_t DXIL_RES_SAMPLER = 1;
  2776. static const ResourceClass DXIL_TYPE_TO_CLASS[] = {
  2777. /* DXIL_RES_INVALID */ RES_CLASS_INVALID,
  2778. /* DXIL_RES_SAMPLER */ RES_CLASS_INVALID, // Handling sampler as a flag.
  2779. /* DXIL_RES_CBV */ RES_CLASS_CBV,
  2780. /* DXIL_RES_SRV_TYPED */ RES_CLASS_SRV,
  2781. /* DXIL_RES_SRV_RAW */ RES_CLASS_SRV,
  2782. /* DXIL_RES_SRV_STRUCTURED */ RES_CLASS_SRV,
  2783. /* DXIL_RES_UAV_TYPED */ RES_CLASS_UAV,
  2784. /* DXIL_RES_UAV_RAW */ RES_CLASS_UAV,
  2785. /* DXIL_RES_UAV_STRUCTURED */ RES_CLASS_UAV,
  2786. /* DXIL_RES_UAV_STRUCTURED_WITH_COUNTER */ RES_CLASS_INVALID,
  2787. };
  2788. DEV_ASSERT(p_dxil_type < ARRAY_SIZE(DXIL_TYPE_TO_CLASS));
  2789. ResourceClass res_class = DXIL_TYPE_TO_CLASS[p_dxil_type];
  2790. if (p_register == ROOT_CONSTANT_REGISTER && p_space == 0) {
  2791. DEV_ASSERT(res_class == RES_CLASS_CBV);
  2792. shader_data_in.binary_data.dxil_push_constant_stages |= (1 << shader_data_in.stage);
  2793. } else if (p_register == RUNTIME_DATA_REGISTER && p_space == 0) {
  2794. DEV_ASSERT(res_class == RES_CLASS_CBV);
  2795. shader_data_in.binary_data.nir_runtime_data_root_param_idx = 1; // Temporary, to be determined later.
  2796. } else {
  2797. DEV_ASSERT(p_space == 0);
  2798. uint32_t set = p_register / GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER;
  2799. uint32_t binding = (p_register % GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER) / GODOT_NIR_BINDING_MULTIPLIER;
  2800. DEV_ASSERT(set < (uint32_t)shader_data_in.sets_bindings.size());
  2801. [[maybe_unused]] bool found = false;
  2802. for (int j = 0; j < shader_data_in.sets_bindings[set].size(); j++) {
  2803. if (shader_data_in.sets_bindings[set][j].binding != binding) {
  2804. continue;
  2805. }
  2806. ShaderBinary::DataBinding &binding_info = shader_data_in.sets_bindings.write[set].write[j];
  2807. binding_info.dxil_stages |= (1 << shader_data_in.stage);
  2808. if (res_class != RES_CLASS_INVALID) {
  2809. DEV_ASSERT(binding_info.res_class == (uint32_t)RES_CLASS_INVALID || binding_info.res_class == (uint32_t)res_class);
  2810. binding_info.res_class = res_class;
  2811. } else if (p_dxil_type == DXIL_RES_SAMPLER) {
  2812. binding_info.has_sampler = (uint32_t)true;
  2813. } else {
  2814. CRASH_NOW();
  2815. }
  2816. found = true;
  2817. break;
  2818. }
  2819. DEV_ASSERT(found);
  2820. }
  2821. };
  2822. godot_nir_callbacks.report_sc_bit_offset_fn = [](uint32_t p_sc_id, uint64_t p_bit_offset, void *p_data) {
  2823. ShaderData &shader_data_in = *(ShaderData *)p_data;
  2824. [[maybe_unused]] bool found = false;
  2825. for (int j = 0; j < shader_data_in.specialization_constants.size(); j++) {
  2826. if (shader_data_in.specialization_constants[j].constant_id != p_sc_id) {
  2827. continue;
  2828. }
  2829. uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[shader_data_in.stage];
  2830. DEV_ASSERT(shader_data_in.specialization_constants.write[j].stages_bit_offsets[offset_idx] == 0);
  2831. shader_data_in.specialization_constants.write[j].stages_bit_offsets[offset_idx] = p_bit_offset;
  2832. found = true;
  2833. break;
  2834. }
  2835. DEV_ASSERT(found);
  2836. };
  2837. godot_nir_callbacks.report_bitcode_bit_offset_fn = [](uint64_t p_bit_offset, void *p_data) {
  2838. DEV_ASSERT(p_bit_offset % 8 == 0);
  2839. ShaderData &shader_data_in = *(ShaderData *)p_data;
  2840. uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[shader_data_in.stage];
  2841. for (int j = 0; j < shader_data_in.specialization_constants.size(); j++) {
  2842. if (shader_data_in.specialization_constants.write[j].stages_bit_offsets[offset_idx] == 0) {
  2843. // This SC has been optimized out from this stage.
  2844. continue;
  2845. }
  2846. shader_data_in.specialization_constants.write[j].stages_bit_offsets[offset_idx] += p_bit_offset;
  2847. }
  2848. };
  2849. auto shader_model_d3d_to_dxil = [](D3D_SHADER_MODEL p_d3d_shader_model) -> dxil_shader_model {
  2850. static_assert(SHADER_MODEL_6_0 == 0x60000);
  2851. static_assert(SHADER_MODEL_6_3 == 0x60003);
  2852. static_assert(D3D_SHADER_MODEL_6_0 == 0x60);
  2853. static_assert(D3D_SHADER_MODEL_6_3 == 0x63);
  2854. return (dxil_shader_model)((p_d3d_shader_model >> 4) * 0x10000 + (p_d3d_shader_model & 0xf));
  2855. };
  2856. nir_to_dxil_options nir_to_dxil_options = {};
  2857. nir_to_dxil_options.environment = DXIL_ENVIRONMENT_VULKAN;
  2858. nir_to_dxil_options.shader_model_max = shader_model_d3d_to_dxil(shader_capabilities.shader_model);
  2859. nir_to_dxil_options.validator_version_max = NO_DXIL_VALIDATION;
  2860. nir_to_dxil_options.godot_nir_callbacks = &godot_nir_callbacks;
  2861. dxil_logger logger = {};
  2862. logger.log = [](void *p_priv, const char *p_msg) {
  2863. #ifdef DEBUG_ENABLED
  2864. print_verbose(p_msg);
  2865. #endif
  2866. };
  2867. blob dxil_blob = {};
  2868. bool ok = nir_to_dxil(stages_nir_shaders[stage], &nir_to_dxil_options, &logger, &dxil_blob);
  2869. ralloc_free(stages_nir_shaders[stage]);
  2870. stages_nir_shaders.erase(stage);
  2871. if (!ok) {
  2872. free_nir_shaders();
  2873. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Shader translation at stage " + String(SHADER_STAGE_NAMES[stage]) + " failed.");
  2874. }
  2875. Vector<uint8_t> blob_copy;
  2876. blob_copy.resize(dxil_blob.size);
  2877. memcpy(blob_copy.ptrw(), dxil_blob.data, dxil_blob.size);
  2878. blob_finish(&dxil_blob);
  2879. dxil_blobs.insert(stage, blob_copy);
  2880. }
  2881. }
  2882. #if 0
  2883. if (dxil_blobs.has(SHADER_STAGE_FRAGMENT)) {
  2884. Ref<FileAccess> f = FileAccess::open("res://1.dxil", FileAccess::WRITE);
  2885. f->store_buffer(dxil_blobs[SHADER_STAGE_FRAGMENT].ptr(), dxil_blobs[SHADER_STAGE_FRAGMENT].size());
  2886. }
  2887. #endif
  2888. // Patch with default values of specialization constants.
  2889. if (specialization_constants.size()) {
  2890. for (const ShaderBinary::SpecializationConstant &sc : specialization_constants) {
  2891. _shader_patch_dxil_specialization_constant((PipelineSpecializationConstantType)sc.type, &sc.int_value, sc.stages_bit_offsets, dxil_blobs, true);
  2892. }
  2893. #if 0
  2894. if (dxil_blobs.has(SHADER_STAGE_FRAGMENT)) {
  2895. Ref<FileAccess> f = FileAccess::open("res://2.dxil", FileAccess::WRITE);
  2896. f->store_buffer(dxil_blobs[SHADER_STAGE_FRAGMENT].ptr(), dxil_blobs[SHADER_STAGE_FRAGMENT].size());
  2897. }
  2898. #endif
  2899. }
  2900. // Sign.
  2901. for (KeyValue<ShaderStage, Vector<uint8_t>> &E : dxil_blobs) {
  2902. ShaderStage stage = E.key;
  2903. Vector<uint8_t> &dxil_blob = E.value;
  2904. _shader_sign_dxil_bytecode(stage, dxil_blob);
  2905. }
  2906. // Build the root signature.
  2907. ComPtr<ID3DBlob> root_sig_blob;
  2908. {
  2909. auto stages_to_d3d12_visibility = [](uint32_t p_stages_mask) -> D3D12_SHADER_VISIBILITY {
  2910. switch (p_stages_mask) {
  2911. case SHADER_STAGE_VERTEX_BIT: {
  2912. return D3D12_SHADER_VISIBILITY_VERTEX;
  2913. }
  2914. case SHADER_STAGE_FRAGMENT_BIT: {
  2915. return D3D12_SHADER_VISIBILITY_PIXEL;
  2916. }
  2917. default: {
  2918. return D3D12_SHADER_VISIBILITY_ALL;
  2919. }
  2920. }
  2921. };
  2922. LocalVector<D3D12_ROOT_PARAMETER1> root_params;
  2923. // Root (push) constants.
  2924. if (binary_data.dxil_push_constant_stages) {
  2925. CD3DX12_ROOT_PARAMETER1 push_constant;
  2926. push_constant.InitAsConstants(
  2927. binary_data.push_constant_size / sizeof(uint32_t),
  2928. ROOT_CONSTANT_REGISTER,
  2929. 0,
  2930. stages_to_d3d12_visibility(binary_data.dxil_push_constant_stages));
  2931. root_params.push_back(push_constant);
  2932. }
  2933. // NIR-DXIL runtime data.
  2934. if (binary_data.nir_runtime_data_root_param_idx == 1) { // Set above to 1 when discovering runtime data is needed.
  2935. DEV_ASSERT(!binary_data.is_compute); // Could be supported if needed, but it's pointless as of now.
  2936. binary_data.nir_runtime_data_root_param_idx = root_params.size();
  2937. CD3DX12_ROOT_PARAMETER1 nir_runtime_data;
  2938. nir_runtime_data.InitAsConstants(
  2939. sizeof(dxil_spirv_vertex_runtime_data) / sizeof(uint32_t),
  2940. RUNTIME_DATA_REGISTER,
  2941. 0,
  2942. D3D12_SHADER_VISIBILITY_VERTEX);
  2943. root_params.push_back(nir_runtime_data);
  2944. }
  2945. // Descriptor tables (up to two per uniform set, for resources and/or samplers).
  2946. // These have to stay around until serialization!
  2947. struct TraceableDescriptorTable {
  2948. uint32_t stages_mask = {};
  2949. Vector<D3D12_DESCRIPTOR_RANGE1> ranges;
  2950. Vector<ShaderBinary::DataBinding::RootSignatureLocation *> root_sig_locations;
  2951. };
  2952. Vector<TraceableDescriptorTable> resource_tables_maps;
  2953. Vector<TraceableDescriptorTable> sampler_tables_maps;
  2954. for (int set = 0; set < sets_bindings.size(); set++) {
  2955. bool first_resource_in_set = true;
  2956. bool first_sampler_in_set = true;
  2957. sets_bindings.write[set].sort();
  2958. for (int i = 0; i < sets_bindings[set].size(); i++) {
  2959. const ShaderBinary::DataBinding &binding = sets_bindings[set][i];
  2960. bool really_used = binding.dxil_stages != 0;
  2961. #ifdef DEV_ENABLED
  2962. bool anybody_home = (ResourceClass)binding.res_class != RES_CLASS_INVALID || binding.has_sampler;
  2963. DEV_ASSERT(anybody_home == really_used);
  2964. #endif
  2965. if (!really_used) {
  2966. continue; // Existed in SPIR-V; went away in DXIL.
  2967. }
  2968. auto insert_range = [](D3D12_DESCRIPTOR_RANGE_TYPE p_range_type,
  2969. uint32_t p_num_descriptors,
  2970. uint32_t p_dxil_register,
  2971. uint32_t p_dxil_stages_mask,
  2972. ShaderBinary::DataBinding::RootSignatureLocation(&p_root_sig_locations),
  2973. Vector<TraceableDescriptorTable> &r_tables,
  2974. bool &r_first_in_set) {
  2975. if (r_first_in_set) {
  2976. r_tables.resize(r_tables.size() + 1);
  2977. r_first_in_set = false;
  2978. }
  2979. TraceableDescriptorTable &table = r_tables.write[r_tables.size() - 1];
  2980. table.stages_mask |= p_dxil_stages_mask;
  2981. CD3DX12_DESCRIPTOR_RANGE1 range;
  2982. // Due to the aliasing hack for SRV-UAV of different families,
  2983. // we can be causing an unintended change of data (sometimes the validation layers catch it).
  2984. D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;
  2985. if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_UAV) {
  2986. flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
  2987. } else if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_CBV) {
  2988. flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE;
  2989. }
  2990. range.Init(p_range_type, p_num_descriptors, p_dxil_register, 0, flags);
  2991. table.ranges.push_back(range);
  2992. table.root_sig_locations.push_back(&p_root_sig_locations);
  2993. };
  2994. uint32_t num_descriptors = 1;
  2995. D3D12_DESCRIPTOR_RANGE_TYPE resource_range_type = {};
  2996. switch ((ResourceClass)binding.res_class) {
  2997. case RES_CLASS_INVALID: {
  2998. num_descriptors = binding.length;
  2999. DEV_ASSERT(binding.has_sampler);
  3000. } break;
  3001. case RES_CLASS_CBV: {
  3002. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
  3003. DEV_ASSERT(!binding.has_sampler);
  3004. } break;
  3005. case RES_CLASS_SRV: {
  3006. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  3007. num_descriptors = MAX(1u, binding.length); // An unbound R/O buffer is reflected as zero-size.
  3008. } break;
  3009. case RES_CLASS_UAV: {
  3010. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
  3011. num_descriptors = MAX(1u, binding.length); // An unbound R/W buffer is reflected as zero-size.
  3012. DEV_ASSERT(!binding.has_sampler);
  3013. } break;
  3014. }
  3015. uint32_t dxil_register = set * GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER + binding.binding * GODOT_NIR_BINDING_MULTIPLIER;
  3016. if (binding.res_class != RES_CLASS_INVALID) {
  3017. insert_range(
  3018. resource_range_type,
  3019. num_descriptors,
  3020. dxil_register,
  3021. sets_bindings[set][i].dxil_stages,
  3022. sets_bindings.write[set].write[i].root_sig_locations[RS_LOC_TYPE_RESOURCE],
  3023. resource_tables_maps,
  3024. first_resource_in_set);
  3025. }
  3026. if (binding.has_sampler) {
  3027. insert_range(
  3028. D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
  3029. num_descriptors,
  3030. dxil_register,
  3031. sets_bindings[set][i].dxil_stages,
  3032. sets_bindings.write[set].write[i].root_sig_locations[RS_LOC_TYPE_SAMPLER],
  3033. sampler_tables_maps,
  3034. first_sampler_in_set);
  3035. }
  3036. }
  3037. }
  3038. auto make_descriptor_tables = [&root_params, &stages_to_d3d12_visibility](const Vector<TraceableDescriptorTable> &p_tables) {
  3039. for (const TraceableDescriptorTable &table : p_tables) {
  3040. D3D12_SHADER_VISIBILITY visibility = stages_to_d3d12_visibility(table.stages_mask);
  3041. DEV_ASSERT(table.ranges.size() == table.root_sig_locations.size());
  3042. for (int i = 0; i < table.ranges.size(); i++) {
  3043. // By now we know very well which root signature location corresponds to the pointed uniform.
  3044. table.root_sig_locations[i]->root_param_idx = root_params.size();
  3045. table.root_sig_locations[i]->range_idx = i;
  3046. }
  3047. CD3DX12_ROOT_PARAMETER1 root_table;
  3048. root_table.InitAsDescriptorTable(table.ranges.size(), table.ranges.ptr(), visibility);
  3049. root_params.push_back(root_table);
  3050. }
  3051. };
  3052. make_descriptor_tables(resource_tables_maps);
  3053. make_descriptor_tables(sampler_tables_maps);
  3054. CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC root_sig_desc = {};
  3055. D3D12_ROOT_SIGNATURE_FLAGS root_sig_flags =
  3056. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  3057. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  3058. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
  3059. D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS |
  3060. D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS;
  3061. if (!stages_processed.has_flag(SHADER_STAGE_VERTEX_BIT)) {
  3062. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS;
  3063. }
  3064. if (!stages_processed.has_flag(SHADER_STAGE_FRAGMENT_BIT)) {
  3065. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;
  3066. }
  3067. if (binary_data.vertex_input_mask) {
  3068. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
  3069. }
  3070. root_sig_desc.Init_1_1(root_params.size(), root_params.ptr(), 0, nullptr, root_sig_flags);
  3071. ComPtr<ID3DBlob> error_blob;
  3072. HRESULT res = D3DX12SerializeVersionedRootSignature(context_driver->lib_d3d12, &root_sig_desc, D3D_ROOT_SIGNATURE_VERSION_1_1, root_sig_blob.GetAddressOf(), error_blob.GetAddressOf());
  3073. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), Vector<uint8_t>(),
  3074. "Serialization of root signature failed with error " + vformat("0x%08ux", (uint64_t)res) + " and the following message:\n" + String((char *)error_blob->GetBufferPointer(), error_blob->GetBufferSize()));
  3075. binary_data.root_signature_crc = crc32(0, nullptr, 0);
  3076. binary_data.root_signature_crc = crc32(binary_data.root_signature_crc, (const Bytef *)root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());
  3077. }
  3078. Vector<Vector<uint8_t>> compressed_stages;
  3079. Vector<uint32_t> zstd_size;
  3080. uint32_t stages_binary_size = 0;
  3081. for (uint32_t i = 0; i < p_spirv.size(); i++) {
  3082. Vector<uint8_t> zstd;
  3083. Vector<uint8_t> &dxil_blob = dxil_blobs[p_spirv[i].shader_stage];
  3084. zstd.resize(Compression::get_max_compressed_buffer_size(dxil_blob.size(), Compression::MODE_ZSTD));
  3085. int dst_size = Compression::compress(zstd.ptrw(), dxil_blob.ptr(), dxil_blob.size(), Compression::MODE_ZSTD);
  3086. zstd_size.push_back(dst_size);
  3087. zstd.resize(dst_size);
  3088. compressed_stages.push_back(zstd);
  3089. uint32_t s = compressed_stages[i].size();
  3090. stages_binary_size += STEPIFY(s, 4);
  3091. }
  3092. CharString shader_name_utf = p_shader_name.utf8();
  3093. binary_data.shader_name_len = shader_name_utf.length();
  3094. uint32_t total_size = sizeof(uint32_t) * 3; // Header + version + main datasize;.
  3095. total_size += sizeof(ShaderBinary::Data);
  3096. total_size += STEPIFY(binary_data.shader_name_len, 4);
  3097. for (int i = 0; i < sets_bindings.size(); i++) {
  3098. total_size += sizeof(uint32_t);
  3099. total_size += sets_bindings[i].size() * sizeof(ShaderBinary::DataBinding);
  3100. }
  3101. total_size += sizeof(ShaderBinary::SpecializationConstant) * specialization_constants.size();
  3102. total_size += compressed_stages.size() * sizeof(uint32_t) * 3; // Sizes.
  3103. total_size += stages_binary_size;
  3104. binary_data.root_signature_len = root_sig_blob->GetBufferSize();
  3105. total_size += binary_data.root_signature_len;
  3106. Vector<uint8_t> ret;
  3107. ret.resize(total_size);
  3108. {
  3109. uint32_t offset = 0;
  3110. uint8_t *binptr = ret.ptrw();
  3111. binptr[0] = 'G';
  3112. binptr[1] = 'S';
  3113. binptr[2] = 'B';
  3114. binptr[3] = 'D'; // Godot shader binary data.
  3115. offset += 4;
  3116. encode_uint32(ShaderBinary::VERSION, binptr + offset);
  3117. offset += sizeof(uint32_t);
  3118. encode_uint32(sizeof(ShaderBinary::Data), binptr + offset);
  3119. offset += sizeof(uint32_t);
  3120. memcpy(binptr + offset, &binary_data, sizeof(ShaderBinary::Data));
  3121. offset += sizeof(ShaderBinary::Data);
  3122. #define ADVANCE_OFFSET_WITH_ALIGNMENT(m_bytes) \
  3123. { \
  3124. offset += m_bytes; \
  3125. uint32_t padding = STEPIFY(m_bytes, 4) - m_bytes; \
  3126. memset(binptr + offset, 0, padding); /* Avoid garbage data. */ \
  3127. offset += padding; \
  3128. }
  3129. if (binary_data.shader_name_len > 0) {
  3130. memcpy(binptr + offset, shader_name_utf.ptr(), binary_data.shader_name_len);
  3131. ADVANCE_OFFSET_WITH_ALIGNMENT(binary_data.shader_name_len);
  3132. }
  3133. for (int i = 0; i < sets_bindings.size(); i++) {
  3134. int count = sets_bindings[i].size();
  3135. encode_uint32(count, binptr + offset);
  3136. offset += sizeof(uint32_t);
  3137. if (count > 0) {
  3138. memcpy(binptr + offset, sets_bindings[i].ptr(), sizeof(ShaderBinary::DataBinding) * count);
  3139. offset += sizeof(ShaderBinary::DataBinding) * count;
  3140. }
  3141. }
  3142. if (specialization_constants.size()) {
  3143. memcpy(binptr + offset, specialization_constants.ptr(), sizeof(ShaderBinary::SpecializationConstant) * specialization_constants.size());
  3144. offset += sizeof(ShaderBinary::SpecializationConstant) * specialization_constants.size();
  3145. }
  3146. for (int i = 0; i < compressed_stages.size(); i++) {
  3147. encode_uint32(p_spirv[i].shader_stage, binptr + offset);
  3148. offset += sizeof(uint32_t);
  3149. encode_uint32(dxil_blobs[p_spirv[i].shader_stage].size(), binptr + offset);
  3150. offset += sizeof(uint32_t);
  3151. encode_uint32(zstd_size[i], binptr + offset);
  3152. offset += sizeof(uint32_t);
  3153. memcpy(binptr + offset, compressed_stages[i].ptr(), compressed_stages[i].size());
  3154. ADVANCE_OFFSET_WITH_ALIGNMENT(compressed_stages[i].size());
  3155. }
  3156. memcpy(binptr + offset, root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());
  3157. offset += root_sig_blob->GetBufferSize();
  3158. ERR_FAIL_COND_V(offset != (uint32_t)ret.size(), Vector<uint8_t>());
  3159. }
  3160. return ret;
  3161. }
  3162. RDD::ShaderID RenderingDeviceDriverD3D12::shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary, ShaderDescription &r_shader_desc, String &r_name) {
  3163. r_shader_desc = {}; // Driver-agnostic.
  3164. ShaderInfo shader_info_in; // Driver-specific.
  3165. const uint8_t *binptr = p_shader_binary.ptr();
  3166. uint32_t binsize = p_shader_binary.size();
  3167. uint32_t read_offset = 0;
  3168. // Consistency check.
  3169. ERR_FAIL_COND_V(binsize < sizeof(uint32_t) * 3 + sizeof(ShaderBinary::Data), ShaderID());
  3170. ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'S' || binptr[2] != 'B' || binptr[3] != 'D', ShaderID());
  3171. uint32_t bin_version = decode_uint32(binptr + 4);
  3172. ERR_FAIL_COND_V(bin_version != ShaderBinary::VERSION, ShaderID());
  3173. uint32_t bin_data_size = decode_uint32(binptr + 8);
  3174. const ShaderBinary::Data &binary_data = *(reinterpret_cast<const ShaderBinary::Data *>(binptr + 12));
  3175. r_shader_desc.push_constant_size = binary_data.push_constant_size;
  3176. shader_info_in.dxil_push_constant_size = binary_data.dxil_push_constant_stages ? binary_data.push_constant_size : 0;
  3177. shader_info_in.nir_runtime_data_root_param_idx = binary_data.nir_runtime_data_root_param_idx;
  3178. r_shader_desc.vertex_input_mask = binary_data.vertex_input_mask;
  3179. r_shader_desc.fragment_output_mask = binary_data.fragment_output_mask;
  3180. r_shader_desc.is_compute = binary_data.is_compute;
  3181. shader_info_in.is_compute = binary_data.is_compute;
  3182. r_shader_desc.compute_local_size[0] = binary_data.compute_local_size[0];
  3183. r_shader_desc.compute_local_size[1] = binary_data.compute_local_size[1];
  3184. r_shader_desc.compute_local_size[2] = binary_data.compute_local_size[2];
  3185. read_offset += sizeof(uint32_t) * 3 + bin_data_size;
  3186. if (binary_data.shader_name_len) {
  3187. r_name.parse_utf8((const char *)(binptr + read_offset), binary_data.shader_name_len);
  3188. read_offset += STEPIFY(binary_data.shader_name_len, 4);
  3189. }
  3190. r_shader_desc.uniform_sets.resize(binary_data.set_count);
  3191. shader_info_in.sets.resize(binary_data.set_count);
  3192. for (uint32_t i = 0; i < binary_data.set_count; i++) {
  3193. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) >= binsize, ShaderID());
  3194. uint32_t set_count = decode_uint32(binptr + read_offset);
  3195. read_offset += sizeof(uint32_t);
  3196. const ShaderBinary::DataBinding *set_ptr = reinterpret_cast<const ShaderBinary::DataBinding *>(binptr + read_offset);
  3197. uint32_t set_size = set_count * sizeof(ShaderBinary::DataBinding);
  3198. ERR_FAIL_COND_V(read_offset + set_size >= binsize, ShaderID());
  3199. shader_info_in.sets[i].bindings.reserve(set_count);
  3200. for (uint32_t j = 0; j < set_count; j++) {
  3201. ShaderUniform info;
  3202. info.type = UniformType(set_ptr[j].type);
  3203. info.writable = set_ptr[j].writable;
  3204. info.length = set_ptr[j].length;
  3205. info.binding = set_ptr[j].binding;
  3206. ShaderInfo::UniformBindingInfo binding;
  3207. binding.stages = set_ptr[j].dxil_stages;
  3208. binding.res_class = (ResourceClass)set_ptr[j].res_class;
  3209. binding.type = info.type;
  3210. binding.length = info.length;
  3211. #ifdef DEV_ENABLED
  3212. binding.writable = set_ptr[j].writable;
  3213. #endif
  3214. static_assert(sizeof(ShaderInfo::UniformBindingInfo::root_sig_locations) == sizeof(ShaderBinary::DataBinding::root_sig_locations));
  3215. memcpy((void *)&binding.root_sig_locations, (void *)&set_ptr[j].root_sig_locations, sizeof(ShaderInfo::UniformBindingInfo::root_sig_locations));
  3216. if (binding.root_sig_locations.resource.root_param_idx != UINT32_MAX) {
  3217. shader_info_in.sets[i].num_root_params.resources++;
  3218. }
  3219. if (binding.root_sig_locations.sampler.root_param_idx != UINT32_MAX) {
  3220. shader_info_in.sets[i].num_root_params.samplers++;
  3221. }
  3222. r_shader_desc.uniform_sets.write[i].push_back(info);
  3223. shader_info_in.sets[i].bindings.push_back(binding);
  3224. }
  3225. read_offset += set_size;
  3226. }
  3227. ERR_FAIL_COND_V(read_offset + binary_data.specialization_constants_count * sizeof(ShaderBinary::SpecializationConstant) >= binsize, ShaderID());
  3228. r_shader_desc.specialization_constants.resize(binary_data.specialization_constants_count);
  3229. shader_info_in.specialization_constants.resize(binary_data.specialization_constants_count);
  3230. for (uint32_t i = 0; i < binary_data.specialization_constants_count; i++) {
  3231. const ShaderBinary::SpecializationConstant &src_sc = *(reinterpret_cast<const ShaderBinary::SpecializationConstant *>(binptr + read_offset));
  3232. ShaderSpecializationConstant sc;
  3233. sc.type = PipelineSpecializationConstantType(src_sc.type);
  3234. sc.constant_id = src_sc.constant_id;
  3235. sc.int_value = src_sc.int_value;
  3236. sc.stages = src_sc.stage_flags;
  3237. r_shader_desc.specialization_constants.write[i] = sc;
  3238. ShaderInfo::SpecializationConstant ssc;
  3239. ssc.constant_id = src_sc.constant_id;
  3240. ssc.int_value = src_sc.int_value;
  3241. memcpy(ssc.stages_bit_offsets, src_sc.stages_bit_offsets, sizeof(ssc.stages_bit_offsets));
  3242. shader_info_in.specialization_constants[i] = ssc;
  3243. read_offset += sizeof(ShaderBinary::SpecializationConstant);
  3244. }
  3245. shader_info_in.spirv_specialization_constants_ids_mask = binary_data.spirv_specialization_constants_ids_mask;
  3246. for (uint32_t i = 0; i < binary_data.stage_count; i++) {
  3247. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) * 3 >= binsize, ShaderID());
  3248. uint32_t stage = decode_uint32(binptr + read_offset);
  3249. read_offset += sizeof(uint32_t);
  3250. uint32_t dxil_size = decode_uint32(binptr + read_offset);
  3251. read_offset += sizeof(uint32_t);
  3252. uint32_t zstd_size = decode_uint32(binptr + read_offset);
  3253. read_offset += sizeof(uint32_t);
  3254. // Decompress.
  3255. Vector<uint8_t> dxil;
  3256. dxil.resize(dxil_size);
  3257. int dec_dxil_size = Compression::decompress(dxil.ptrw(), dxil.size(), binptr + read_offset, zstd_size, Compression::MODE_ZSTD);
  3258. ERR_FAIL_COND_V(dec_dxil_size != (int32_t)dxil_size, ShaderID());
  3259. shader_info_in.stages_bytecode[ShaderStage(stage)] = dxil;
  3260. zstd_size = STEPIFY(zstd_size, 4);
  3261. read_offset += zstd_size;
  3262. ERR_FAIL_COND_V(read_offset > binsize, ShaderID());
  3263. r_shader_desc.stages.push_back(ShaderStage(stage));
  3264. }
  3265. const uint8_t *root_sig_data_ptr = binptr + read_offset;
  3266. PFN_D3D12_CREATE_ROOT_SIGNATURE_DESERIALIZER d3d_D3D12CreateRootSignatureDeserializer = (PFN_D3D12_CREATE_ROOT_SIGNATURE_DESERIALIZER)(void *)GetProcAddress(context_driver->lib_d3d12, "D3D12CreateRootSignatureDeserializer");
  3267. ERR_FAIL_NULL_V(d3d_D3D12CreateRootSignatureDeserializer, ShaderID());
  3268. HRESULT res = d3d_D3D12CreateRootSignatureDeserializer(root_sig_data_ptr, binary_data.root_signature_len, IID_PPV_ARGS(shader_info_in.root_signature_deserializer.GetAddressOf()));
  3269. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ShaderID(), "D3D12CreateRootSignatureDeserializer failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  3270. read_offset += binary_data.root_signature_len;
  3271. ERR_FAIL_COND_V(read_offset != binsize, ShaderID());
  3272. ComPtr<ID3D12RootSignature> root_signature;
  3273. res = device->CreateRootSignature(0, root_sig_data_ptr, binary_data.root_signature_len, IID_PPV_ARGS(shader_info_in.root_signature.GetAddressOf()));
  3274. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ShaderID(), "CreateRootSignature failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  3275. shader_info_in.root_signature_desc = shader_info_in.root_signature_deserializer->GetRootSignatureDesc();
  3276. shader_info_in.root_signature_crc = binary_data.root_signature_crc;
  3277. // Bookkeep.
  3278. ShaderInfo *shader_info_ptr = VersatileResource::allocate<ShaderInfo>(resources_allocator);
  3279. *shader_info_ptr = shader_info_in;
  3280. return ShaderID(shader_info_ptr);
  3281. }
  3282. uint32_t RenderingDeviceDriverD3D12::shader_get_layout_hash(ShaderID p_shader) {
  3283. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  3284. return shader_info_in->root_signature_crc;
  3285. }
  3286. void RenderingDeviceDriverD3D12::shader_free(ShaderID p_shader) {
  3287. ShaderInfo *shader_info_in = (ShaderInfo *)p_shader.id;
  3288. VersatileResource::free(resources_allocator, shader_info_in);
  3289. }
  3290. void RenderingDeviceDriverD3D12::shader_destroy_modules(ShaderID p_shader) {
  3291. ShaderInfo *shader_info_in = (ShaderInfo *)p_shader.id;
  3292. shader_info_in->stages_bytecode.clear();
  3293. }
  3294. /*********************/
  3295. /**** UNIFORM SET ****/
  3296. /*********************/
  3297. static void _add_descriptor_count_for_uniform(RenderingDevice::UniformType p_type, uint32_t p_binding_length, bool p_dobule_srv_uav_ambiguous, uint32_t &r_num_resources, uint32_t &r_num_samplers, bool &r_srv_uav_ambiguity) {
  3298. r_srv_uav_ambiguity = false;
  3299. // Some resource types can be SRV or UAV, depending on what NIR-DXIL decided for a specific shader variant.
  3300. // The goal is to generate both SRV and UAV for the descriptor sets' heaps and copy only the relevant one
  3301. // to the frame descriptor heap at binding time.
  3302. // [[SRV_UAV_AMBIGUITY]]
  3303. switch (p_type) {
  3304. case RenderingDevice::UNIFORM_TYPE_SAMPLER: {
  3305. r_num_samplers += p_binding_length;
  3306. } break;
  3307. case RenderingDevice::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE:
  3308. case RenderingDevice::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  3309. r_num_resources += p_binding_length;
  3310. r_num_samplers += p_binding_length;
  3311. } break;
  3312. case RenderingDevice::UNIFORM_TYPE_UNIFORM_BUFFER: {
  3313. r_num_resources += 1;
  3314. } break;
  3315. case RenderingDevice::UNIFORM_TYPE_STORAGE_BUFFER: {
  3316. r_num_resources += p_dobule_srv_uav_ambiguous ? 2 : 1;
  3317. r_srv_uav_ambiguity = true;
  3318. } break;
  3319. case RenderingDevice::UNIFORM_TYPE_IMAGE: {
  3320. r_num_resources += p_binding_length * (p_dobule_srv_uav_ambiguous ? 2 : 1);
  3321. r_srv_uav_ambiguity = true;
  3322. } break;
  3323. default: {
  3324. r_num_resources += p_binding_length;
  3325. }
  3326. }
  3327. }
  3328. RDD::UniformSetID RenderingDeviceDriverD3D12::uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index) {
  3329. // Pre-bookkeep.
  3330. UniformSetInfo *uniform_set_info = VersatileResource::allocate<UniformSetInfo>(resources_allocator);
  3331. // Do a first pass to count resources and samplers.
  3332. uint32_t num_resource_descs = 0;
  3333. uint32_t num_sampler_descs = 0;
  3334. for (uint32_t i = 0; i < p_uniforms.size(); i++) {
  3335. const BoundUniform &uniform = p_uniforms[i];
  3336. // Since the uniform set may be created for a shader different than the one that will be actually bound,
  3337. // which may have a different set of uniforms optimized out, the stages mask we can check now is not reliable.
  3338. // Therefore, we can't make any assumptions here about descriptors that we may not need to create,
  3339. // pixel or vertex-only shader resource states, etc.
  3340. bool srv_uav_ambiguity = false;
  3341. uint32_t binding_length = uniform.ids.size();
  3342. if (uniform.type == UNIFORM_TYPE_SAMPLER_WITH_TEXTURE || uniform.type == UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER) {
  3343. binding_length /= 2;
  3344. }
  3345. _add_descriptor_count_for_uniform(uniform.type, binding_length, true, num_resource_descs, num_sampler_descs, srv_uav_ambiguity);
  3346. }
  3347. #ifdef DEV_ENABLED
  3348. uniform_set_info->resources_desc_info.reserve(num_resource_descs);
  3349. #endif
  3350. if (num_resource_descs) {
  3351. Error err = uniform_set_info->desc_heaps.resources.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, num_resource_descs, false);
  3352. if (err) {
  3353. VersatileResource::free(resources_allocator, uniform_set_info);
  3354. ERR_FAIL_V(UniformSetID());
  3355. }
  3356. }
  3357. if (num_sampler_descs) {
  3358. Error err = uniform_set_info->desc_heaps.samplers.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, num_sampler_descs, false);
  3359. if (err) {
  3360. VersatileResource::free(resources_allocator, uniform_set_info);
  3361. ERR_FAIL_V(UniformSetID());
  3362. }
  3363. }
  3364. struct {
  3365. DescriptorsHeap::Walker resources;
  3366. DescriptorsHeap::Walker samplers;
  3367. } desc_heap_walkers;
  3368. desc_heap_walkers.resources = uniform_set_info->desc_heaps.resources.make_walker();
  3369. desc_heap_walkers.samplers = uniform_set_info->desc_heaps.samplers.make_walker();
  3370. struct NeededState {
  3371. bool is_buffer = false;
  3372. uint64_t shader_uniform_idx_mask = 0;
  3373. D3D12_RESOURCE_STATES states = {};
  3374. };
  3375. HashMap<ResourceInfo *, NeededState> resource_states;
  3376. for (uint32_t i = 0; i < p_uniforms.size(); i++) {
  3377. const BoundUniform &uniform = p_uniforms[i];
  3378. #ifdef DEV_ENABLED
  3379. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  3380. const ShaderInfo::UniformBindingInfo &shader_uniform = shader_info_in->sets[p_set_index].bindings[i];
  3381. bool is_compute = shader_info_in->stages_bytecode.has(SHADER_STAGE_COMPUTE);
  3382. DEV_ASSERT(!(is_compute && (shader_uniform.stages & (SHADER_STAGE_VERTEX_BIT | SHADER_STAGE_FRAGMENT_BIT))));
  3383. DEV_ASSERT(!(!is_compute && (shader_uniform.stages & SHADER_STAGE_COMPUTE_BIT)));
  3384. #endif
  3385. switch (uniform.type) {
  3386. case UNIFORM_TYPE_SAMPLER: {
  3387. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3388. const D3D12_SAMPLER_DESC &sampler_desc = samplers[uniform.ids[j].id];
  3389. device->CreateSampler(&sampler_desc, desc_heap_walkers.samplers.get_curr_cpu_handle());
  3390. desc_heap_walkers.samplers.advance();
  3391. }
  3392. } break;
  3393. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  3394. for (uint32_t j = 0; j < uniform.ids.size(); j += 2) {
  3395. const D3D12_SAMPLER_DESC &sampler_desc = samplers[uniform.ids[j].id];
  3396. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j + 1].id;
  3397. device->CreateSampler(&sampler_desc, desc_heap_walkers.samplers.get_curr_cpu_handle());
  3398. desc_heap_walkers.samplers.advance();
  3399. device->CreateShaderResourceView(texture_info->resource, &texture_info->view_descs.srv, desc_heap_walkers.resources.get_curr_cpu_handle());
  3400. #ifdef DEV_ENABLED
  3401. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture_info->view_descs.srv.ViewDimension });
  3402. #endif
  3403. desc_heap_walkers.resources.advance();
  3404. NeededState &ns = resource_states[texture_info];
  3405. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3406. ns.states |= D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  3407. }
  3408. } break;
  3409. case UNIFORM_TYPE_TEXTURE: {
  3410. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3411. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j].id;
  3412. device->CreateShaderResourceView(texture_info->resource, &texture_info->view_descs.srv, desc_heap_walkers.resources.get_curr_cpu_handle());
  3413. #ifdef DEV_ENABLED
  3414. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture_info->view_descs.srv.ViewDimension });
  3415. #endif
  3416. desc_heap_walkers.resources.advance();
  3417. NeededState &ns = resource_states[texture_info];
  3418. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3419. ns.states |= D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  3420. }
  3421. } break;
  3422. case UNIFORM_TYPE_IMAGE: {
  3423. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3424. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j].id;
  3425. NeededState &ns = resource_states[texture_info];
  3426. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3427. ns.states |= (D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  3428. }
  3429. // SRVs first. [[SRV_UAV_AMBIGUITY]]
  3430. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3431. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j].id;
  3432. device->CreateShaderResourceView(texture_info->resource, &texture_info->view_descs.srv, desc_heap_walkers.resources.get_curr_cpu_handle());
  3433. #ifdef DEV_ENABLED
  3434. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture_info->view_descs.srv.ViewDimension });
  3435. #endif
  3436. desc_heap_walkers.resources.advance();
  3437. }
  3438. // UAVs then. [[SRV_UAV_AMBIGUITY]]
  3439. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3440. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j].id;
  3441. device->CreateUnorderedAccessView(texture_info->resource, nullptr, &texture_info->view_descs.uav, desc_heap_walkers.resources.get_curr_cpu_handle());
  3442. #ifdef DEV_ENABLED
  3443. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_UAV, {} });
  3444. #endif
  3445. desc_heap_walkers.resources.advance();
  3446. }
  3447. } break;
  3448. case UNIFORM_TYPE_TEXTURE_BUFFER:
  3449. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  3450. CRASH_NOW_MSG("Unimplemented!");
  3451. } break;
  3452. case UNIFORM_TYPE_IMAGE_BUFFER: {
  3453. CRASH_NOW_MSG("Unimplemented!");
  3454. } break;
  3455. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  3456. BufferInfo *buf_info = (BufferInfo *)uniform.ids[0].id;
  3457. D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_desc = {};
  3458. cbv_desc.BufferLocation = buf_info->resource->GetGPUVirtualAddress();
  3459. cbv_desc.SizeInBytes = STEPIFY(buf_info->size, 256);
  3460. device->CreateConstantBufferView(&cbv_desc, desc_heap_walkers.resources.get_curr_cpu_handle());
  3461. desc_heap_walkers.resources.advance();
  3462. #ifdef DEV_ENABLED
  3463. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_CBV, {} });
  3464. #endif
  3465. NeededState &ns = resource_states[buf_info];
  3466. ns.is_buffer = true;
  3467. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3468. ns.states |= D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
  3469. } break;
  3470. case UNIFORM_TYPE_STORAGE_BUFFER: {
  3471. BufferInfo *buf_info = (BufferInfo *)uniform.ids[0].id;
  3472. // SRV first. [[SRV_UAV_AMBIGUITY]]
  3473. {
  3474. D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc = {};
  3475. srv_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  3476. srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
  3477. srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  3478. srv_desc.Buffer.FirstElement = 0;
  3479. srv_desc.Buffer.NumElements = (buf_info->size + 3) / 4;
  3480. srv_desc.Buffer.StructureByteStride = 0;
  3481. srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
  3482. device->CreateShaderResourceView(buf_info->resource, &srv_desc, desc_heap_walkers.resources.get_curr_cpu_handle());
  3483. #ifdef DEV_ENABLED
  3484. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srv_desc.ViewDimension });
  3485. #endif
  3486. desc_heap_walkers.resources.advance();
  3487. }
  3488. // UAV then. [[SRV_UAV_AMBIGUITY]]
  3489. {
  3490. if (buf_info->flags.usable_as_uav) {
  3491. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = {};
  3492. uav_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  3493. uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  3494. uav_desc.Buffer.FirstElement = 0;
  3495. uav_desc.Buffer.NumElements = (buf_info->size + 3) / 4;
  3496. uav_desc.Buffer.StructureByteStride = 0;
  3497. uav_desc.Buffer.CounterOffsetInBytes = 0;
  3498. uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  3499. device->CreateUnorderedAccessView(buf_info->resource, nullptr, &uav_desc, desc_heap_walkers.resources.get_curr_cpu_handle());
  3500. #ifdef DEV_ENABLED
  3501. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_UAV, {} });
  3502. #endif
  3503. } else {
  3504. // If can't transition to UAV, leave this one empty since it won't be
  3505. // used, and trying to create an UAV view would trigger a validation error.
  3506. }
  3507. desc_heap_walkers.resources.advance();
  3508. }
  3509. NeededState &ns = resource_states[buf_info];
  3510. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3511. ns.is_buffer = true;
  3512. ns.states |= (D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  3513. } break;
  3514. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  3515. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3516. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j].id;
  3517. device->CreateShaderResourceView(texture_info->resource, &texture_info->view_descs.srv, desc_heap_walkers.resources.get_curr_cpu_handle());
  3518. #ifdef DEV_ENABLED
  3519. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture_info->view_descs.srv.ViewDimension });
  3520. #endif
  3521. desc_heap_walkers.resources.advance();
  3522. NeededState &ns = resource_states[texture_info];
  3523. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3524. ns.states |= D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  3525. }
  3526. } break;
  3527. default: {
  3528. DEV_ASSERT(false);
  3529. }
  3530. }
  3531. }
  3532. DEV_ASSERT(desc_heap_walkers.resources.is_at_eof());
  3533. DEV_ASSERT(desc_heap_walkers.samplers.is_at_eof());
  3534. {
  3535. uniform_set_info->resource_states.reserve(resource_states.size());
  3536. for (const KeyValue<ResourceInfo *, NeededState> &E : resource_states) {
  3537. UniformSetInfo::StateRequirement sr;
  3538. sr.resource = E.key;
  3539. sr.is_buffer = E.value.is_buffer;
  3540. sr.states = E.value.states;
  3541. sr.shader_uniform_idx_mask = E.value.shader_uniform_idx_mask;
  3542. uniform_set_info->resource_states.push_back(sr);
  3543. }
  3544. }
  3545. return UniformSetID(uniform_set_info);
  3546. }
  3547. void RenderingDeviceDriverD3D12::uniform_set_free(UniformSetID p_uniform_set) {
  3548. UniformSetInfo *uniform_set_info = (UniformSetInfo *)p_uniform_set.id;
  3549. VersatileResource::free(resources_allocator, uniform_set_info);
  3550. }
  3551. // ----- COMMANDS -----
  3552. void RenderingDeviceDriverD3D12::command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  3553. if (barrier_capabilities.enhanced_barriers_supported) {
  3554. return;
  3555. }
  3556. // Perform pending blackouts.
  3557. {
  3558. SelfList<TextureInfo> *E = textures_pending_clear.first();
  3559. while (E) {
  3560. TextureSubresourceRange subresources;
  3561. subresources.layer_count = E->self()->layers;
  3562. subresources.mipmap_count = E->self()->mipmaps;
  3563. command_clear_color_texture(p_cmd_buffer, TextureID(E->self()), TEXTURE_LAYOUT_UNDEFINED, Color(), subresources);
  3564. SelfList<TextureInfo> *next = E->next();
  3565. E->remove_from_list();
  3566. E = next;
  3567. }
  3568. }
  3569. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  3570. const UniformSetInfo *uniform_set_info = (const UniformSetInfo *)p_uniform_set.id;
  3571. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  3572. const ShaderInfo::UniformSet &shader_set = shader_info_in->sets[p_set_index];
  3573. for (const UniformSetInfo::StateRequirement &sr : uniform_set_info->resource_states) {
  3574. #ifdef DEV_ENABLED
  3575. {
  3576. uint32_t stages = 0;
  3577. D3D12_RESOURCE_STATES wanted_state = {};
  3578. bool writable = false;
  3579. // Doing the full loop for debugging since the real one below may break early,
  3580. // but we want an exhaustive check
  3581. uint64_t inv_uniforms_mask = ~sr.shader_uniform_idx_mask; // Inverting the mask saves operations.
  3582. for (uint8_t bit = 0; inv_uniforms_mask != UINT64_MAX; bit++) {
  3583. uint64_t bit_mask = ((uint64_t)1 << bit);
  3584. if (likely((inv_uniforms_mask & bit_mask))) {
  3585. continue;
  3586. }
  3587. inv_uniforms_mask |= bit_mask;
  3588. const ShaderInfo::UniformBindingInfo &binding = shader_set.bindings[bit];
  3589. if (unlikely(!binding.stages)) {
  3590. continue;
  3591. }
  3592. D3D12_RESOURCE_STATES required_states = sr.states;
  3593. // Resolve a case of SRV/UAV ambiguity now. [[SRV_UAV_AMBIGUITY]]
  3594. if ((required_states & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE) && (required_states & D3D12_RESOURCE_STATE_UNORDERED_ACCESS)) {
  3595. if (binding.res_class == RES_CLASS_SRV) {
  3596. required_states &= ~D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  3597. } else {
  3598. required_states = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  3599. }
  3600. }
  3601. if (stages) { // Second occurrence at least?
  3602. CRASH_COND_MSG(binding.writable != writable, "A resource is used in the same uniform set both as R/O and R/W. That's not supported and shouldn't happen.");
  3603. CRASH_COND_MSG(required_states != wanted_state, "A resource is used in the same uniform set with different resource states. The code needs to be enhanced to support that.");
  3604. } else {
  3605. wanted_state = required_states;
  3606. stages |= binding.stages;
  3607. writable = binding.writable;
  3608. }
  3609. DEV_ASSERT((wanted_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS) == (bool)(wanted_state & D3D12_RESOURCE_STATE_UNORDERED_ACCESS));
  3610. }
  3611. }
  3612. #endif
  3613. // We may have assumed D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE for a resource,
  3614. // because at uniform set creation time we couldn't know for sure which stages
  3615. // it would be used in (due to the fact that a set can be created against a different,
  3616. // albeit compatible, shader, which may make a different usage in the end).
  3617. // However, now we know and can exclude up to one unneeded states.
  3618. // TODO: If subresources involved already in the needed states, or scheduled for it,
  3619. // maybe it's more optimal not to do anything here
  3620. uint32_t stages = 0;
  3621. D3D12_RESOURCE_STATES wanted_state = {};
  3622. uint64_t inv_uniforms_mask = ~sr.shader_uniform_idx_mask; // Inverting the mask saves operations.
  3623. for (uint8_t bit = 0; inv_uniforms_mask != UINT64_MAX; bit++) {
  3624. uint64_t bit_mask = ((uint64_t)1 << bit);
  3625. if (likely((inv_uniforms_mask & bit_mask))) {
  3626. continue;
  3627. }
  3628. inv_uniforms_mask |= bit_mask;
  3629. const ShaderInfo::UniformBindingInfo &binding = shader_set.bindings[bit];
  3630. if (unlikely(!binding.stages)) {
  3631. continue;
  3632. }
  3633. if (!stages) {
  3634. D3D12_RESOURCE_STATES required_states = sr.states;
  3635. // Resolve a case of SRV/UAV ambiguity now. [[SRV_UAV_AMBIGUITY]]
  3636. if ((required_states & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE) && (required_states & D3D12_RESOURCE_STATE_UNORDERED_ACCESS)) {
  3637. if (binding.res_class == RES_CLASS_SRV) {
  3638. required_states &= ~D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  3639. } else {
  3640. required_states = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  3641. }
  3642. }
  3643. wanted_state = required_states;
  3644. if (!(wanted_state & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE)) {
  3645. // By now, we already know the resource is used, and with no PS/NON_PS disjuntive; no need to check further.
  3646. break;
  3647. }
  3648. }
  3649. stages |= binding.stages;
  3650. if (stages == (SHADER_STAGE_VERTEX_BIT | SHADER_STAGE_FRAGMENT_BIT) || stages == SHADER_STAGE_COMPUTE_BIT) {
  3651. // By now, we already know the resource is used, and as both PS/NON_PS; no need to check further.
  3652. break;
  3653. }
  3654. }
  3655. if (likely(wanted_state)) {
  3656. if ((wanted_state & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE)) {
  3657. if (stages == SHADER_STAGE_VERTEX_BIT || stages == SHADER_STAGE_COMPUTE_BIT) {
  3658. D3D12_RESOURCE_STATES unneeded_states = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  3659. wanted_state &= ~unneeded_states;
  3660. } else if (stages == SHADER_STAGE_FRAGMENT_BIT) {
  3661. D3D12_RESOURCE_STATES unneeded_states = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
  3662. wanted_state &= ~unneeded_states;
  3663. }
  3664. }
  3665. if (likely(wanted_state)) {
  3666. if (sr.is_buffer) {
  3667. _resource_transition_batch(cmd_buf_info, sr.resource, 0, 1, wanted_state);
  3668. } else {
  3669. TextureInfo *tex_info = (TextureInfo *)sr.resource;
  3670. uint32_t planes = 1;
  3671. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  3672. planes = format_get_plane_count(tex_info->format);
  3673. }
  3674. for (uint32_t i = 0; i < tex_info->layers; i++) {
  3675. for (uint32_t j = 0; j < tex_info->mipmaps; j++) {
  3676. uint32_t subresource = D3D12CalcSubresource(tex_info->base_mip + j, tex_info->base_layer + i, 0, tex_info->desc.MipLevels, tex_info->desc.ArraySize());
  3677. _resource_transition_batch(cmd_buf_info, tex_info, subresource, planes, wanted_state);
  3678. }
  3679. }
  3680. }
  3681. }
  3682. }
  3683. }
  3684. if (p_set_index == shader_info_in->sets.size() - 1) {
  3685. _resource_transitions_flush(cmd_buf_info);
  3686. }
  3687. }
  3688. void RenderingDeviceDriverD3D12::_command_check_descriptor_sets(CommandBufferID p_cmd_buffer) {
  3689. DEV_ASSERT(segment_begun && "Unable to use commands that rely on descriptors because a segment was never begun.");
  3690. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  3691. if (!cmd_buf_info->descriptor_heaps_set) {
  3692. // Set descriptor heaps for the command buffer if they haven't been set yet.
  3693. ID3D12DescriptorHeap *heaps[] = {
  3694. frames[frame_idx].desc_heaps.resources.get_heap(),
  3695. frames[frame_idx].desc_heaps.samplers.get_heap(),
  3696. };
  3697. cmd_buf_info->cmd_list->SetDescriptorHeaps(2, heaps);
  3698. cmd_buf_info->descriptor_heaps_set = true;
  3699. }
  3700. }
  3701. void RenderingDeviceDriverD3D12::_command_bind_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index, bool p_for_compute) {
  3702. _command_check_descriptor_sets(p_cmd_buffer);
  3703. UniformSetInfo *uniform_set_info = (UniformSetInfo *)p_uniform_set.id;
  3704. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  3705. const ShaderInfo::UniformSet &shader_set = shader_info_in->sets[p_set_index];
  3706. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  3707. using SetRootDescriptorTableFn = void (STDMETHODCALLTYPE ID3D12GraphicsCommandList::*)(UINT, D3D12_GPU_DESCRIPTOR_HANDLE);
  3708. SetRootDescriptorTableFn set_root_desc_table_fn = p_for_compute ? &ID3D12GraphicsCommandList::SetComputeRootDescriptorTable : &ID3D12GraphicsCommandList1::SetGraphicsRootDescriptorTable;
  3709. // If this set's descriptors have already been set for the current execution and a compatible root signature, reuse!
  3710. uint32_t root_sig_crc = p_for_compute ? cmd_buf_info->compute_root_signature_crc : cmd_buf_info->graphics_root_signature_crc;
  3711. UniformSetInfo::RecentBind *last_bind = nullptr;
  3712. for (int i = 0; i < (int)ARRAY_SIZE(uniform_set_info->recent_binds); i++) {
  3713. if (uniform_set_info->recent_binds[i].segment_serial == frames[frame_idx].segment_serial) {
  3714. if (uniform_set_info->recent_binds[i].root_signature_crc == root_sig_crc) {
  3715. for (const RootDescriptorTable &table : uniform_set_info->recent_binds[i].root_tables.resources) {
  3716. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(table.root_param_idx, table.start_gpu_handle);
  3717. }
  3718. for (const RootDescriptorTable &table : uniform_set_info->recent_binds[i].root_tables.samplers) {
  3719. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(table.root_param_idx, table.start_gpu_handle);
  3720. }
  3721. #ifdef DEV_ENABLED
  3722. uniform_set_info->recent_binds[i].uses++;
  3723. frames[frame_idx].uniform_set_reused++;
  3724. #endif
  3725. return;
  3726. } else {
  3727. if (!last_bind || uniform_set_info->recent_binds[i].uses < last_bind->uses) {
  3728. // Prefer this one since it's been used less or we still haven't a better option.
  3729. last_bind = &uniform_set_info->recent_binds[i];
  3730. }
  3731. }
  3732. } else {
  3733. // Prefer this one since it's unused.
  3734. last_bind = &uniform_set_info->recent_binds[i];
  3735. last_bind->uses = 0;
  3736. }
  3737. }
  3738. struct {
  3739. DescriptorsHeap::Walker *resources = nullptr;
  3740. DescriptorsHeap::Walker *samplers = nullptr;
  3741. } frame_heap_walkers;
  3742. frame_heap_walkers.resources = &frames[frame_idx].desc_heap_walkers.resources;
  3743. frame_heap_walkers.samplers = &frames[frame_idx].desc_heap_walkers.samplers;
  3744. struct {
  3745. DescriptorsHeap::Walker resources;
  3746. DescriptorsHeap::Walker samplers;
  3747. } set_heap_walkers;
  3748. set_heap_walkers.resources = uniform_set_info->desc_heaps.resources.make_walker();
  3749. set_heap_walkers.samplers = uniform_set_info->desc_heaps.samplers.make_walker();
  3750. #ifdef DEV_ENABLED
  3751. // Whether we have stages where the uniform is actually used should match
  3752. // whether we have any root signature locations for it.
  3753. for (uint32_t i = 0; i < shader_set.bindings.size(); i++) {
  3754. bool has_rs_locations = false;
  3755. if (shader_set.bindings[i].root_sig_locations.resource.root_param_idx != UINT32_MAX ||
  3756. shader_set.bindings[i].root_sig_locations.sampler.root_param_idx != UINT32_MAX) {
  3757. has_rs_locations = true;
  3758. break;
  3759. }
  3760. bool has_stages = shader_set.bindings[i].stages;
  3761. DEV_ASSERT(has_rs_locations == has_stages);
  3762. }
  3763. #endif
  3764. last_bind->root_tables.resources.reserve(shader_set.num_root_params.resources);
  3765. last_bind->root_tables.resources.clear();
  3766. last_bind->root_tables.samplers.reserve(shader_set.num_root_params.samplers);
  3767. last_bind->root_tables.samplers.clear();
  3768. last_bind->uses++;
  3769. struct {
  3770. RootDescriptorTable *resources = nullptr;
  3771. RootDescriptorTable *samplers = nullptr;
  3772. } tables;
  3773. for (uint32_t i = 0; i < shader_set.bindings.size(); i++) {
  3774. const ShaderInfo::UniformBindingInfo &binding = shader_set.bindings[i];
  3775. uint32_t num_resource_descs = 0;
  3776. uint32_t num_sampler_descs = 0;
  3777. bool srv_uav_ambiguity = false;
  3778. _add_descriptor_count_for_uniform(binding.type, binding.length, false, num_resource_descs, num_sampler_descs, srv_uav_ambiguity);
  3779. bool resource_used = false;
  3780. if (shader_set.bindings[i].stages) {
  3781. {
  3782. const ShaderInfo::UniformBindingInfo::RootSignatureLocation &rs_loc_resource = shader_set.bindings[i].root_sig_locations.resource;
  3783. if (rs_loc_resource.root_param_idx != UINT32_MAX) { // Location used?
  3784. DEV_ASSERT(num_resource_descs);
  3785. DEV_ASSERT(!(srv_uav_ambiguity && (shader_set.bindings[i].res_class != RES_CLASS_SRV && shader_set.bindings[i].res_class != RES_CLASS_UAV))); // [[SRV_UAV_AMBIGUITY]]
  3786. bool must_flush_table = tables.resources && rs_loc_resource.root_param_idx != tables.resources->root_param_idx;
  3787. if (must_flush_table) {
  3788. // Check the root signature data has been filled ordered.
  3789. DEV_ASSERT(rs_loc_resource.root_param_idx > tables.resources->root_param_idx);
  3790. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(tables.resources->root_param_idx, tables.resources->start_gpu_handle);
  3791. tables.resources = nullptr;
  3792. }
  3793. if (unlikely(frame_heap_walkers.resources->get_free_handles() < num_resource_descs)) {
  3794. if (!frames[frame_idx].desc_heaps_exhausted_reported.resources) {
  3795. frames[frame_idx].desc_heaps_exhausted_reported.resources = true;
  3796. ERR_FAIL_MSG("Cannot bind uniform set because there's no enough room in current frame's RESOURCES descriptor heap.\n"
  3797. "Please increase the value of the rendering/rendering_device/d3d12/max_resource_descriptors_per_frame project setting.");
  3798. } else {
  3799. return;
  3800. }
  3801. }
  3802. if (!tables.resources) {
  3803. DEV_ASSERT(last_bind->root_tables.resources.size() < last_bind->root_tables.resources.get_capacity());
  3804. last_bind->root_tables.resources.resize(last_bind->root_tables.resources.size() + 1);
  3805. tables.resources = &last_bind->root_tables.resources[last_bind->root_tables.resources.size() - 1];
  3806. tables.resources->root_param_idx = rs_loc_resource.root_param_idx;
  3807. tables.resources->start_gpu_handle = frame_heap_walkers.resources->get_curr_gpu_handle();
  3808. }
  3809. // If there is ambiguity and it didn't clarify as SRVs, skip them, which come first. [[SRV_UAV_AMBIGUITY]]
  3810. if (srv_uav_ambiguity && shader_set.bindings[i].res_class != RES_CLASS_SRV) {
  3811. set_heap_walkers.resources.advance(num_resource_descs);
  3812. }
  3813. // TODO: Batch to avoid multiple calls where possible (in any case, flush before setting root descriptor tables, or even batch that as well).
  3814. device->CopyDescriptorsSimple(
  3815. num_resource_descs,
  3816. frame_heap_walkers.resources->get_curr_cpu_handle(),
  3817. set_heap_walkers.resources.get_curr_cpu_handle(),
  3818. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  3819. frame_heap_walkers.resources->advance(num_resource_descs);
  3820. // If there is ambiguity and it didn't clarify as UAVs, skip them, which come later. [[SRV_UAV_AMBIGUITY]]
  3821. if (srv_uav_ambiguity && shader_set.bindings[i].res_class != RES_CLASS_UAV) {
  3822. set_heap_walkers.resources.advance(num_resource_descs);
  3823. }
  3824. resource_used = true;
  3825. }
  3826. }
  3827. {
  3828. const ShaderInfo::UniformBindingInfo::RootSignatureLocation &rs_loc_sampler = shader_set.bindings[i].root_sig_locations.sampler;
  3829. if (rs_loc_sampler.root_param_idx != UINT32_MAX) { // Location used?
  3830. DEV_ASSERT(num_sampler_descs);
  3831. DEV_ASSERT(!srv_uav_ambiguity); // [[SRV_UAV_AMBIGUITY]]
  3832. bool must_flush_table = tables.samplers && rs_loc_sampler.root_param_idx != tables.samplers->root_param_idx;
  3833. if (must_flush_table) {
  3834. // Check the root signature data has been filled ordered.
  3835. DEV_ASSERT(rs_loc_sampler.root_param_idx > tables.samplers->root_param_idx);
  3836. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(tables.samplers->root_param_idx, tables.samplers->start_gpu_handle);
  3837. tables.samplers = nullptr;
  3838. }
  3839. if (unlikely(frame_heap_walkers.samplers->get_free_handles() < num_sampler_descs)) {
  3840. if (!frames[frame_idx].desc_heaps_exhausted_reported.samplers) {
  3841. frames[frame_idx].desc_heaps_exhausted_reported.samplers = true;
  3842. ERR_FAIL_MSG("Cannot bind uniform set because there's no enough room in current frame's SAMPLERS descriptors heap.\n"
  3843. "Please increase the value of the rendering/rendering_device/d3d12/max_sampler_descriptors_per_frame project setting.");
  3844. } else {
  3845. return;
  3846. }
  3847. }
  3848. if (!tables.samplers) {
  3849. DEV_ASSERT(last_bind->root_tables.samplers.size() < last_bind->root_tables.samplers.get_capacity());
  3850. last_bind->root_tables.samplers.resize(last_bind->root_tables.samplers.size() + 1);
  3851. tables.samplers = &last_bind->root_tables.samplers[last_bind->root_tables.samplers.size() - 1];
  3852. tables.samplers->root_param_idx = rs_loc_sampler.root_param_idx;
  3853. tables.samplers->start_gpu_handle = frame_heap_walkers.samplers->get_curr_gpu_handle();
  3854. }
  3855. // TODO: Batch to avoid multiple calls where possible (in any case, flush before setting root descriptor tables, or even batch that as well).
  3856. device->CopyDescriptorsSimple(
  3857. num_sampler_descs,
  3858. frame_heap_walkers.samplers->get_curr_cpu_handle(),
  3859. set_heap_walkers.samplers.get_curr_cpu_handle(),
  3860. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
  3861. frame_heap_walkers.samplers->advance(num_sampler_descs);
  3862. }
  3863. }
  3864. }
  3865. // Uniform set descriptor heaps are always full (descriptors are created for every uniform in them) despite
  3866. // the shader variant a given set is created upon may not need all of them due to DXC optimizations.
  3867. // Therefore, at this point we have to advance through the descriptor set descriptor's heap unconditionally.
  3868. set_heap_walkers.resources.advance(num_resource_descs);
  3869. if (srv_uav_ambiguity) {
  3870. DEV_ASSERT(num_resource_descs);
  3871. if (!resource_used) {
  3872. set_heap_walkers.resources.advance(num_resource_descs); // Additional skip, since both SRVs and UAVs have to be bypassed.
  3873. }
  3874. }
  3875. set_heap_walkers.samplers.advance(num_sampler_descs);
  3876. }
  3877. DEV_ASSERT(set_heap_walkers.resources.is_at_eof());
  3878. DEV_ASSERT(set_heap_walkers.samplers.is_at_eof());
  3879. {
  3880. bool must_flush_table = tables.resources;
  3881. if (must_flush_table) {
  3882. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(tables.resources->root_param_idx, tables.resources->start_gpu_handle);
  3883. }
  3884. }
  3885. {
  3886. bool must_flush_table = tables.samplers;
  3887. if (must_flush_table) {
  3888. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(tables.samplers->root_param_idx, tables.samplers->start_gpu_handle);
  3889. }
  3890. }
  3891. last_bind->root_signature_crc = root_sig_crc;
  3892. last_bind->segment_serial = frames[frame_idx].segment_serial;
  3893. }
  3894. /******************/
  3895. /**** TRANSFER ****/
  3896. /******************/
  3897. void RenderingDeviceDriverD3D12::command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) {
  3898. _command_check_descriptor_sets(p_cmd_buffer);
  3899. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  3900. BufferInfo *buf_info = (BufferInfo *)p_buffer.id;
  3901. if (frames[frame_idx].desc_heap_walkers.resources.is_at_eof()) {
  3902. if (!frames[frame_idx].desc_heaps_exhausted_reported.resources) {
  3903. frames[frame_idx].desc_heaps_exhausted_reported.resources = true;
  3904. ERR_FAIL_MSG(
  3905. "Cannot clear buffer because there's no enough room in current frame's RESOURCE descriptors heap.\n"
  3906. "Please increase the value of the rendering/rendering_device/d3d12/max_resource_descriptors_per_frame project setting.");
  3907. } else {
  3908. return;
  3909. }
  3910. }
  3911. if (frames[frame_idx].desc_heap_walkers.aux.is_at_eof()) {
  3912. if (!frames[frame_idx].desc_heaps_exhausted_reported.aux) {
  3913. frames[frame_idx].desc_heaps_exhausted_reported.aux = true;
  3914. ERR_FAIL_MSG(
  3915. "Cannot clear buffer because there's no enough room in current frame's AUX descriptors heap.\n"
  3916. "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting.");
  3917. } else {
  3918. return;
  3919. }
  3920. }
  3921. if (!barrier_capabilities.enhanced_barriers_supported) {
  3922. _resource_transition_batch(cmd_buf_info, buf_info, 0, 1, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  3923. _resource_transitions_flush(cmd_buf_info);
  3924. }
  3925. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = {};
  3926. uav_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  3927. uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  3928. uav_desc.Buffer.FirstElement = 0;
  3929. uav_desc.Buffer.NumElements = (buf_info->size + 3) / 4;
  3930. uav_desc.Buffer.StructureByteStride = 0;
  3931. uav_desc.Buffer.CounterOffsetInBytes = 0;
  3932. uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  3933. device->CreateUnorderedAccessView(
  3934. buf_info->resource,
  3935. nullptr,
  3936. &uav_desc,
  3937. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle());
  3938. device->CopyDescriptorsSimple(
  3939. 1,
  3940. frames[frame_idx].desc_heap_walkers.resources.get_curr_cpu_handle(),
  3941. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle(),
  3942. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  3943. static const UINT values[4] = {};
  3944. cmd_buf_info->cmd_list->ClearUnorderedAccessViewUint(
  3945. frames[frame_idx].desc_heap_walkers.resources.get_curr_gpu_handle(),
  3946. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle(),
  3947. buf_info->resource,
  3948. values,
  3949. 0,
  3950. nullptr);
  3951. frames[frame_idx].desc_heap_walkers.resources.advance();
  3952. frames[frame_idx].desc_heap_walkers.aux.advance();
  3953. }
  3954. void RenderingDeviceDriverD3D12::command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_buf_locfer, VectorView<BufferCopyRegion> p_regions) {
  3955. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  3956. BufferInfo *src_buf_info = (BufferInfo *)p_src_buffer.id;
  3957. BufferInfo *buf_loc_info = (BufferInfo *)p_buf_locfer.id;
  3958. if (!barrier_capabilities.enhanced_barriers_supported) {
  3959. _resource_transition_batch(cmd_buf_info, src_buf_info, 0, 1, D3D12_RESOURCE_STATE_COPY_SOURCE);
  3960. _resource_transition_batch(cmd_buf_info, buf_loc_info, 0, 1, D3D12_RESOURCE_STATE_COPY_DEST);
  3961. _resource_transitions_flush(cmd_buf_info);
  3962. }
  3963. for (uint32_t i = 0; i < p_regions.size(); i++) {
  3964. cmd_buf_info->cmd_list->CopyBufferRegion(buf_loc_info->resource, p_regions[i].dst_offset, src_buf_info->resource, p_regions[i].src_offset, p_regions[i].size);
  3965. }
  3966. }
  3967. void RenderingDeviceDriverD3D12::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) {
  3968. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  3969. TextureInfo *src_tex_info = (TextureInfo *)p_src_texture.id;
  3970. TextureInfo *dst_tex_info = (TextureInfo *)p_dst_texture.id;
  3971. if (!barrier_capabilities.enhanced_barriers_supported) {
  3972. // Batch all barrier transitions for the textures before performing the copies.
  3973. for (uint32_t i = 0; i < p_regions.size(); i++) {
  3974. uint32_t layer_count = MIN(p_regions[i].src_subresources.layer_count, p_regions[i].dst_subresources.layer_count);
  3975. for (uint32_t j = 0; j < layer_count; j++) {
  3976. UINT src_subresource = _compute_subresource_from_layers(src_tex_info, p_regions[i].src_subresources, j);
  3977. UINT dst_subresource = _compute_subresource_from_layers(dst_tex_info, p_regions[i].dst_subresources, j);
  3978. _resource_transition_batch(cmd_buf_info, src_tex_info, src_subresource, 1, D3D12_RESOURCE_STATE_COPY_SOURCE);
  3979. _resource_transition_batch(cmd_buf_info, dst_tex_info, dst_subresource, 1, D3D12_RESOURCE_STATE_COPY_DEST);
  3980. }
  3981. }
  3982. _resource_transitions_flush(cmd_buf_info);
  3983. }
  3984. CD3DX12_BOX src_box;
  3985. for (uint32_t i = 0; i < p_regions.size(); i++) {
  3986. uint32_t layer_count = MIN(p_regions[i].src_subresources.layer_count, p_regions[i].dst_subresources.layer_count);
  3987. for (uint32_t j = 0; j < layer_count; j++) {
  3988. UINT src_subresource = _compute_subresource_from_layers(src_tex_info, p_regions[i].src_subresources, j);
  3989. UINT dst_subresource = _compute_subresource_from_layers(dst_tex_info, p_regions[i].dst_subresources, j);
  3990. CD3DX12_TEXTURE_COPY_LOCATION src_location(src_tex_info->resource, src_subresource);
  3991. CD3DX12_TEXTURE_COPY_LOCATION dst_location(dst_tex_info->resource, dst_subresource);
  3992. src_box.left = p_regions[i].src_offset.x;
  3993. src_box.top = p_regions[i].src_offset.y;
  3994. src_box.front = p_regions[i].src_offset.z;
  3995. src_box.right = p_regions[i].src_offset.x + p_regions[i].size.x;
  3996. src_box.bottom = p_regions[i].src_offset.y + p_regions[i].size.y;
  3997. src_box.back = p_regions[i].src_offset.z + p_regions[i].size.z;
  3998. cmd_buf_info->cmd_list->CopyTextureRegion(&dst_location, p_regions[i].dst_offset.x, p_regions[i].dst_offset.y, p_regions[i].dst_offset.z, &src_location, &src_box);
  3999. }
  4000. }
  4001. }
  4002. void RenderingDeviceDriverD3D12::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) {
  4003. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4004. TextureInfo *src_tex_info = (TextureInfo *)p_src_texture.id;
  4005. TextureInfo *dst_tex_info = (TextureInfo *)p_dst_texture.id;
  4006. UINT src_subresource = D3D12CalcSubresource(p_src_mipmap, p_src_layer, 0, src_tex_info->desc.MipLevels, src_tex_info->desc.ArraySize());
  4007. UINT dst_subresource = D3D12CalcSubresource(p_dst_mipmap, p_dst_layer, 0, dst_tex_info->desc.MipLevels, dst_tex_info->desc.ArraySize());
  4008. if (!barrier_capabilities.enhanced_barriers_supported) {
  4009. _resource_transition_batch(cmd_buf_info, src_tex_info, src_subresource, 1, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
  4010. _resource_transition_batch(cmd_buf_info, dst_tex_info, dst_subresource, 1, D3D12_RESOURCE_STATE_RESOLVE_DEST);
  4011. _resource_transitions_flush(cmd_buf_info);
  4012. }
  4013. cmd_buf_info->cmd_list->ResolveSubresource(dst_tex_info->resource, dst_subresource, src_tex_info->resource, src_subresource, RD_TO_D3D12_FORMAT[src_tex_info->format].general_format);
  4014. }
  4015. void RenderingDeviceDriverD3D12::command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) {
  4016. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4017. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  4018. if (tex_info->main_texture) {
  4019. tex_info = tex_info->main_texture;
  4020. }
  4021. auto _transition_subresources = [&](D3D12_RESOURCE_STATES p_new_state) {
  4022. for (uint32_t i = 0; i < p_subresources.layer_count; i++) {
  4023. for (uint32_t j = 0; j < p_subresources.mipmap_count; j++) {
  4024. UINT subresource = D3D12CalcSubresource(
  4025. p_subresources.base_mipmap + j,
  4026. p_subresources.base_layer + i,
  4027. 0,
  4028. tex_info->desc.MipLevels,
  4029. tex_info->desc.ArraySize());
  4030. _resource_transition_batch(cmd_buf_info, tex_info, subresource, 1, p_new_state);
  4031. }
  4032. }
  4033. _resource_transitions_flush(cmd_buf_info);
  4034. };
  4035. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
  4036. // Clear via RTV.
  4037. if (frames[frame_idx].desc_heap_walkers.rtv.get_free_handles() < p_subresources.mipmap_count) {
  4038. if (!frames[frame_idx].desc_heaps_exhausted_reported.rtv) {
  4039. frames[frame_idx].desc_heaps_exhausted_reported.rtv = true;
  4040. ERR_FAIL_MSG(
  4041. "Cannot clear texture because there's no enough room in current frame's RENDER TARGET descriptors heap.\n"
  4042. "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting.");
  4043. } else {
  4044. return;
  4045. }
  4046. }
  4047. if (!barrier_capabilities.enhanced_barriers_supported) {
  4048. _transition_subresources(D3D12_RESOURCE_STATE_RENDER_TARGET);
  4049. }
  4050. for (uint32_t i = 0; i < p_subresources.mipmap_count; i++) {
  4051. D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = _make_rtv_for_texture(tex_info, p_subresources.base_mipmap + i, p_subresources.base_layer, p_subresources.layer_count, false);
  4052. rtv_desc.Format = tex_info->view_descs.uav.Format;
  4053. device->CreateRenderTargetView(
  4054. tex_info->resource,
  4055. &rtv_desc,
  4056. frames[frame_idx].desc_heap_walkers.rtv.get_curr_cpu_handle());
  4057. cmd_buf_info->cmd_list->ClearRenderTargetView(
  4058. frames[frame_idx].desc_heap_walkers.rtv.get_curr_cpu_handle(),
  4059. p_color.components,
  4060. 0,
  4061. nullptr);
  4062. frames[frame_idx].desc_heap_walkers.rtv.advance();
  4063. }
  4064. } else if (tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) {
  4065. // Clear via UAV.
  4066. _command_check_descriptor_sets(p_cmd_buffer);
  4067. if (frames[frame_idx].desc_heap_walkers.resources.get_free_handles() < p_subresources.mipmap_count) {
  4068. if (!frames[frame_idx].desc_heaps_exhausted_reported.resources) {
  4069. frames[frame_idx].desc_heaps_exhausted_reported.resources = true;
  4070. ERR_FAIL_MSG(
  4071. "Cannot clear texture because there's no enough room in current frame's RESOURCE descriptors heap.\n"
  4072. "Please increase the value of the rendering/rendering_device/d3d12/max_resource_descriptors_per_frame project setting.");
  4073. } else {
  4074. return;
  4075. }
  4076. }
  4077. if (frames[frame_idx].desc_heap_walkers.aux.get_free_handles() < p_subresources.mipmap_count) {
  4078. if (!frames[frame_idx].desc_heaps_exhausted_reported.aux) {
  4079. frames[frame_idx].desc_heaps_exhausted_reported.aux = true;
  4080. ERR_FAIL_MSG(
  4081. "Cannot clear texture because there's no enough room in current frame's AUX descriptors heap.\n"
  4082. "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting.");
  4083. } else {
  4084. return;
  4085. }
  4086. }
  4087. if (!barrier_capabilities.enhanced_barriers_supported) {
  4088. _transition_subresources(D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  4089. }
  4090. for (uint32_t i = 0; i < p_subresources.mipmap_count; i++) {
  4091. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = _make_ranged_uav_for_texture(tex_info, p_subresources.base_mipmap + i, p_subresources.base_layer, p_subresources.layer_count, false);
  4092. device->CreateUnorderedAccessView(
  4093. tex_info->resource,
  4094. nullptr,
  4095. &uav_desc,
  4096. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle());
  4097. device->CopyDescriptorsSimple(
  4098. 1,
  4099. frames[frame_idx].desc_heap_walkers.resources.get_curr_cpu_handle(),
  4100. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle(),
  4101. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  4102. UINT values[4] = {
  4103. (UINT)p_color.get_r8(),
  4104. (UINT)p_color.get_g8(),
  4105. (UINT)p_color.get_b8(),
  4106. (UINT)p_color.get_a8(),
  4107. };
  4108. cmd_buf_info->cmd_list->ClearUnorderedAccessViewUint(
  4109. frames[frame_idx].desc_heap_walkers.resources.get_curr_gpu_handle(),
  4110. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle(),
  4111. tex_info->resource,
  4112. values,
  4113. 0,
  4114. nullptr);
  4115. frames[frame_idx].desc_heap_walkers.resources.advance();
  4116. frames[frame_idx].desc_heap_walkers.aux.advance();
  4117. }
  4118. } else {
  4119. ERR_FAIL_MSG("Cannot clear texture because its format does not support UAV writes. You'll need to update its contents through another method.");
  4120. }
  4121. }
  4122. void RenderingDeviceDriverD3D12::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) {
  4123. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4124. BufferInfo *buf_info = (BufferInfo *)p_src_buffer.id;
  4125. TextureInfo *tex_info = (TextureInfo *)p_dst_texture.id;
  4126. if (!barrier_capabilities.enhanced_barriers_supported) {
  4127. _resource_transition_batch(cmd_buf_info, buf_info, 0, 1, D3D12_RESOURCE_STATE_COPY_SOURCE);
  4128. }
  4129. uint32_t pixel_size = get_image_format_pixel_size(tex_info->format);
  4130. uint32_t block_w = 0, block_h = 0;
  4131. get_compressed_image_format_block_dimensions(tex_info->format, block_w, block_h);
  4132. for (uint32_t i = 0; i < p_regions.size(); i++) {
  4133. uint32_t region_pitch = (p_regions[i].texture_region_size.x * pixel_size * block_w) >> get_compressed_image_format_pixel_rshift(tex_info->format);
  4134. region_pitch = STEPIFY(region_pitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  4135. D3D12_PLACED_SUBRESOURCE_FOOTPRINT src_footprint = {};
  4136. src_footprint.Offset = p_regions[i].buffer_offset;
  4137. src_footprint.Footprint = CD3DX12_SUBRESOURCE_FOOTPRINT(
  4138. RD_TO_D3D12_FORMAT[tex_info->format].family,
  4139. STEPIFY(p_regions[i].texture_region_size.x, block_w),
  4140. STEPIFY(p_regions[i].texture_region_size.y, block_h),
  4141. p_regions[i].texture_region_size.z,
  4142. region_pitch);
  4143. CD3DX12_TEXTURE_COPY_LOCATION copy_src(buf_info->resource, src_footprint);
  4144. CD3DX12_BOX src_box(
  4145. 0, 0, 0,
  4146. STEPIFY(p_regions[i].texture_region_size.x, block_w),
  4147. STEPIFY(p_regions[i].texture_region_size.y, block_h),
  4148. p_regions[i].texture_region_size.z);
  4149. if (!barrier_capabilities.enhanced_barriers_supported) {
  4150. for (uint32_t j = 0; j < p_regions[i].texture_subresources.layer_count; j++) {
  4151. UINT dst_subresource = D3D12CalcSubresource(
  4152. p_regions[i].texture_subresources.mipmap,
  4153. p_regions[i].texture_subresources.base_layer + j,
  4154. _compute_plane_slice(tex_info->format, p_regions[i].texture_subresources.aspect),
  4155. tex_info->desc.MipLevels,
  4156. tex_info->desc.ArraySize());
  4157. CD3DX12_TEXTURE_COPY_LOCATION copy_dst(tex_info->resource, dst_subresource);
  4158. _resource_transition_batch(cmd_buf_info, tex_info, dst_subresource, 1, D3D12_RESOURCE_STATE_COPY_DEST);
  4159. }
  4160. _resource_transitions_flush(cmd_buf_info);
  4161. }
  4162. for (uint32_t j = 0; j < p_regions[i].texture_subresources.layer_count; j++) {
  4163. UINT dst_subresource = D3D12CalcSubresource(
  4164. p_regions[i].texture_subresources.mipmap,
  4165. p_regions[i].texture_subresources.base_layer + j,
  4166. _compute_plane_slice(tex_info->format, p_regions[i].texture_subresources.aspect),
  4167. tex_info->desc.MipLevels,
  4168. tex_info->desc.ArraySize());
  4169. CD3DX12_TEXTURE_COPY_LOCATION copy_dst(tex_info->resource, dst_subresource);
  4170. cmd_buf_info->cmd_list->CopyTextureRegion(
  4171. &copy_dst,
  4172. p_regions[i].texture_offset.x,
  4173. p_regions[i].texture_offset.y,
  4174. p_regions[i].texture_offset.z,
  4175. &copy_src,
  4176. &src_box);
  4177. }
  4178. }
  4179. }
  4180. void RenderingDeviceDriverD3D12::command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_buf_locfer, VectorView<BufferTextureCopyRegion> p_regions) {
  4181. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4182. TextureInfo *tex_info = (TextureInfo *)p_src_texture.id;
  4183. BufferInfo *buf_info = (BufferInfo *)p_buf_locfer.id;
  4184. if (!barrier_capabilities.enhanced_barriers_supported) {
  4185. _resource_transition_batch(cmd_buf_info, buf_info, 0, 1, D3D12_RESOURCE_STATE_COPY_DEST);
  4186. }
  4187. uint32_t block_w = 0, block_h = 0;
  4188. get_compressed_image_format_block_dimensions(tex_info->format, block_w, block_h);
  4189. for (uint32_t i = 0; i < p_regions.size(); i++) {
  4190. if (!barrier_capabilities.enhanced_barriers_supported) {
  4191. for (uint32_t j = 0; j < p_regions[i].texture_subresources.layer_count; j++) {
  4192. UINT src_subresource = D3D12CalcSubresource(
  4193. p_regions[i].texture_subresources.mipmap,
  4194. p_regions[i].texture_subresources.base_layer + j,
  4195. _compute_plane_slice(tex_info->format, p_regions[i].texture_subresources.aspect),
  4196. tex_info->desc.MipLevels,
  4197. tex_info->desc.ArraySize());
  4198. _resource_transition_batch(cmd_buf_info, tex_info, src_subresource, 1, D3D12_RESOURCE_STATE_COPY_SOURCE);
  4199. }
  4200. _resource_transitions_flush(cmd_buf_info);
  4201. }
  4202. for (uint32_t j = 0; j < p_regions[i].texture_subresources.layer_count; j++) {
  4203. UINT src_subresource = D3D12CalcSubresource(
  4204. p_regions[i].texture_subresources.mipmap,
  4205. p_regions[i].texture_subresources.base_layer + j,
  4206. _compute_plane_slice(tex_info->format, p_regions[i].texture_subresources.aspect),
  4207. tex_info->desc.MipLevels,
  4208. tex_info->desc.ArraySize());
  4209. CD3DX12_TEXTURE_COPY_LOCATION copy_src(tex_info->resource, src_subresource);
  4210. uint32_t computed_d = MAX(1, tex_info->desc.DepthOrArraySize >> p_regions[i].texture_subresources.mipmap);
  4211. uint32_t image_size = get_image_format_required_size(
  4212. tex_info->format,
  4213. MAX(1u, tex_info->desc.Width >> p_regions[i].texture_subresources.mipmap),
  4214. MAX(1u, tex_info->desc.Height >> p_regions[i].texture_subresources.mipmap),
  4215. computed_d,
  4216. 1);
  4217. uint32_t row_pitch = image_size / (p_regions[i].texture_region_size.y * computed_d) * block_h;
  4218. row_pitch = STEPIFY(row_pitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  4219. D3D12_PLACED_SUBRESOURCE_FOOTPRINT dst_footprint = {};
  4220. dst_footprint.Offset = p_regions[i].buffer_offset;
  4221. dst_footprint.Footprint.Width = STEPIFY(p_regions[i].texture_region_size.x, block_w);
  4222. dst_footprint.Footprint.Height = STEPIFY(p_regions[i].texture_region_size.y, block_h);
  4223. dst_footprint.Footprint.Depth = p_regions[i].texture_region_size.z;
  4224. dst_footprint.Footprint.RowPitch = row_pitch;
  4225. dst_footprint.Footprint.Format = RD_TO_D3D12_FORMAT[tex_info->format].family;
  4226. CD3DX12_TEXTURE_COPY_LOCATION copy_dst(buf_info->resource, dst_footprint);
  4227. cmd_buf_info->cmd_list->CopyTextureRegion(&copy_dst, 0, 0, 0, &copy_src, nullptr);
  4228. }
  4229. }
  4230. }
  4231. /******************/
  4232. /**** PIPELINE ****/
  4233. /******************/
  4234. void RenderingDeviceDriverD3D12::pipeline_free(PipelineID p_pipeline) {
  4235. PipelineInfo *pipeline_info = (PipelineInfo *)(p_pipeline.id);
  4236. pipeline_info->pso->Release();
  4237. memdelete(pipeline_info);
  4238. }
  4239. // ----- BINDING -----
  4240. void RenderingDeviceDriverD3D12::command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_dst_first_index, VectorView<uint32_t> p_data) {
  4241. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  4242. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  4243. if (!shader_info_in->dxil_push_constant_size) {
  4244. return;
  4245. }
  4246. if (shader_info_in->is_compute) {
  4247. cmd_buf_info->cmd_list->SetComputeRoot32BitConstants(0, p_data.size(), p_data.ptr(), p_dst_first_index);
  4248. } else {
  4249. cmd_buf_info->cmd_list->SetGraphicsRoot32BitConstants(0, p_data.size(), p_data.ptr(), p_dst_first_index);
  4250. }
  4251. }
  4252. // ----- CACHE -----
  4253. bool RenderingDeviceDriverD3D12::pipeline_cache_create(const Vector<uint8_t> &p_data) {
  4254. WARN_PRINT("PSO caching is not implemented yet in the Direct3D 12 driver.");
  4255. return false;
  4256. }
  4257. void RenderingDeviceDriverD3D12::pipeline_cache_free() {
  4258. ERR_FAIL_MSG("Not implemented.");
  4259. }
  4260. size_t RenderingDeviceDriverD3D12::pipeline_cache_query_size() {
  4261. ERR_FAIL_V_MSG(0, "Not implemented.");
  4262. }
  4263. Vector<uint8_t> RenderingDeviceDriverD3D12::pipeline_cache_serialize() {
  4264. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Not implemented.");
  4265. }
  4266. /*******************/
  4267. /**** RENDERING ****/
  4268. /*******************/
  4269. // ----- SUBPASS -----
  4270. RDD::RenderPassID RenderingDeviceDriverD3D12::render_pass_create(VectorView<Attachment> p_attachments, VectorView<Subpass> p_subpasses, VectorView<SubpassDependency> p_subpass_dependencies, uint32_t p_view_count) {
  4271. // Pre-bookkeep.
  4272. RenderPassInfo *pass_info = VersatileResource::allocate<RenderPassInfo>(resources_allocator);
  4273. pass_info->attachments.resize(p_attachments.size());
  4274. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  4275. pass_info->attachments[i] = p_attachments[i];
  4276. }
  4277. pass_info->subpasses.resize(p_subpasses.size());
  4278. for (uint32_t i = 0; i < p_subpasses.size(); i++) {
  4279. pass_info->subpasses[i] = p_subpasses[i];
  4280. }
  4281. pass_info->view_count = p_view_count;
  4282. DXGI_FORMAT *formats = ALLOCA_ARRAY(DXGI_FORMAT, p_attachments.size());
  4283. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  4284. const D3D12Format &format = RD_TO_D3D12_FORMAT[p_attachments[i].format];
  4285. if (format.dsv_format != DXGI_FORMAT_UNKNOWN) {
  4286. formats[i] = format.dsv_format;
  4287. } else {
  4288. formats[i] = format.general_format;
  4289. }
  4290. }
  4291. pass_info->max_supported_sample_count = _find_max_common_supported_sample_count(VectorView(formats, p_attachments.size()));
  4292. return RenderPassID(pass_info);
  4293. }
  4294. void RenderingDeviceDriverD3D12::render_pass_free(RenderPassID p_render_pass) {
  4295. RenderPassInfo *pass_info = (RenderPassInfo *)p_render_pass.id;
  4296. VersatileResource::free(resources_allocator, pass_info);
  4297. }
  4298. // ----- COMMANDS -----
  4299. void RenderingDeviceDriverD3D12::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_attachment_clears) {
  4300. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4301. const RenderPassInfo *pass_info = (const RenderPassInfo *)p_render_pass.id;
  4302. const FramebufferInfo *fb_info = (const FramebufferInfo *)p_framebuffer.id;
  4303. DEV_ASSERT(cmd_buf_info->render_pass_state.current_subpass == UINT32_MAX);
  4304. auto _transition_subresources = [&](TextureInfo *p_texture_info, D3D12_RESOURCE_STATES p_states) {
  4305. uint32_t planes = 1;
  4306. if ((p_texture_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  4307. planes = format_get_plane_count(p_texture_info->format);
  4308. }
  4309. for (uint32_t i = 0; i < p_texture_info->layers; i++) {
  4310. for (uint32_t j = 0; j < p_texture_info->mipmaps; j++) {
  4311. uint32_t subresource = D3D12CalcSubresource(
  4312. p_texture_info->base_mip + j,
  4313. p_texture_info->base_layer + i,
  4314. 0,
  4315. p_texture_info->desc.MipLevels,
  4316. p_texture_info->desc.ArraySize());
  4317. _resource_transition_batch(cmd_buf_info, p_texture_info, subresource, planes, p_states);
  4318. }
  4319. }
  4320. };
  4321. if (fb_info->is_screen || !barrier_capabilities.enhanced_barriers_supported) {
  4322. // Screen framebuffers must perform this transition even if enhanced barriers are supported.
  4323. for (uint32_t i = 0; i < fb_info->attachments.size(); i++) {
  4324. TextureInfo *tex_info = (TextureInfo *)fb_info->attachments[i].id;
  4325. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
  4326. _transition_subresources(tex_info, D3D12_RESOURCE_STATE_RENDER_TARGET);
  4327. } else if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  4328. _transition_subresources(tex_info, D3D12_RESOURCE_STATE_DEPTH_WRITE);
  4329. } else {
  4330. DEV_ASSERT(false);
  4331. }
  4332. }
  4333. if (fb_info->vrs_attachment) {
  4334. TextureInfo *tex_info = (TextureInfo *)fb_info->vrs_attachment.id;
  4335. _transition_subresources(tex_info, D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE);
  4336. }
  4337. _resource_transitions_flush(cmd_buf_info);
  4338. }
  4339. cmd_buf_info->render_pass_state.region_rect = CD3DX12_RECT(
  4340. p_rect.position.x,
  4341. p_rect.position.y,
  4342. p_rect.position.x + p_rect.size.x,
  4343. p_rect.position.y + p_rect.size.y);
  4344. cmd_buf_info->render_pass_state.region_is_all = !(
  4345. cmd_buf_info->render_pass_state.region_rect.left == 0 &&
  4346. cmd_buf_info->render_pass_state.region_rect.top == 0 &&
  4347. cmd_buf_info->render_pass_state.region_rect.right == fb_info->size.x &&
  4348. cmd_buf_info->render_pass_state.region_rect.bottom == fb_info->size.y);
  4349. for (uint32_t i = 0; i < pass_info->attachments.size(); i++) {
  4350. if (pass_info->attachments[i].load_op == ATTACHMENT_LOAD_OP_DONT_CARE) {
  4351. const TextureInfo *tex_info = (const TextureInfo *)fb_info->attachments[i].id;
  4352. _discard_texture_subresources(tex_info, cmd_buf_info);
  4353. }
  4354. }
  4355. if (fb_info->vrs_attachment && vrs_capabilities.ss_image_supported) {
  4356. ComPtr<ID3D12GraphicsCommandList5> cmd_list_5;
  4357. cmd_buf_info->cmd_list->QueryInterface(cmd_list_5.GetAddressOf());
  4358. if (cmd_list_5) {
  4359. static const D3D12_SHADING_RATE_COMBINER COMBINERS[D3D12_RS_SET_SHADING_RATE_COMBINER_COUNT] = {
  4360. D3D12_SHADING_RATE_COMBINER_PASSTHROUGH,
  4361. D3D12_SHADING_RATE_COMBINER_OVERRIDE,
  4362. };
  4363. cmd_list_5->RSSetShadingRate(D3D12_SHADING_RATE_1X1, COMBINERS);
  4364. }
  4365. }
  4366. cmd_buf_info->render_pass_state.current_subpass = UINT32_MAX;
  4367. cmd_buf_info->render_pass_state.fb_info = fb_info;
  4368. cmd_buf_info->render_pass_state.pass_info = pass_info;
  4369. command_next_render_subpass(p_cmd_buffer, p_cmd_buffer_type);
  4370. AttachmentClear *clears = ALLOCA_ARRAY(AttachmentClear, pass_info->attachments.size());
  4371. Rect2i *clear_rects = ALLOCA_ARRAY(Rect2i, pass_info->attachments.size());
  4372. uint32_t num_clears = 0;
  4373. for (uint32_t i = 0; i < pass_info->attachments.size(); i++) {
  4374. TextureInfo *tex_info = (TextureInfo *)fb_info->attachments[i].id;
  4375. if (!tex_info) {
  4376. continue;
  4377. }
  4378. AttachmentClear clear;
  4379. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
  4380. if (pass_info->attachments[i].load_op == ATTACHMENT_LOAD_OP_CLEAR) {
  4381. clear.aspect.set_flag(TEXTURE_ASPECT_COLOR_BIT);
  4382. clear.color_attachment = i;
  4383. tex_info->pending_clear.remove_from_list();
  4384. }
  4385. } else if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  4386. if (pass_info->attachments[i].stencil_load_op == ATTACHMENT_LOAD_OP_CLEAR) {
  4387. clear.aspect.set_flag(TEXTURE_ASPECT_DEPTH_BIT);
  4388. }
  4389. }
  4390. if (!clear.aspect.is_empty()) {
  4391. clear.value = p_attachment_clears[i];
  4392. clears[num_clears] = clear;
  4393. clear_rects[num_clears] = p_rect;
  4394. num_clears++;
  4395. }
  4396. }
  4397. if (num_clears) {
  4398. command_render_clear_attachments(p_cmd_buffer, VectorView(clears, num_clears), VectorView(clear_rects, num_clears));
  4399. }
  4400. }
  4401. void RenderingDeviceDriverD3D12::_end_render_pass(CommandBufferID p_cmd_buffer) {
  4402. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4403. DEV_ASSERT(cmd_buf_info->render_pass_state.current_subpass != UINT32_MAX);
  4404. const FramebufferInfo *fb_info = cmd_buf_info->render_pass_state.fb_info;
  4405. const RenderPassInfo *pass_info = cmd_buf_info->render_pass_state.pass_info;
  4406. const Subpass &subpass = pass_info->subpasses[cmd_buf_info->render_pass_state.current_subpass];
  4407. if (fb_info->is_screen) {
  4408. // Screen framebuffers must transition back to present state when the render pass is finished.
  4409. for (uint32_t i = 0; i < fb_info->attachments.size(); i++) {
  4410. TextureInfo *src_tex_info = (TextureInfo *)(fb_info->attachments[i].id);
  4411. uint32_t src_subresource = D3D12CalcSubresource(src_tex_info->base_mip, src_tex_info->base_layer, 0, src_tex_info->desc.MipLevels, src_tex_info->desc.ArraySize());
  4412. _resource_transition_batch(cmd_buf_info, src_tex_info, src_subresource, 1, D3D12_RESOURCE_STATE_PRESENT);
  4413. }
  4414. }
  4415. struct Resolve {
  4416. ID3D12Resource *src_res = nullptr;
  4417. uint32_t src_subres = 0;
  4418. ID3D12Resource *dst_res = nullptr;
  4419. uint32_t dst_subres = 0;
  4420. DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
  4421. };
  4422. Resolve *resolves = ALLOCA_ARRAY(Resolve, subpass.resolve_references.size());
  4423. uint32_t num_resolves = 0;
  4424. for (uint32_t i = 0; i < subpass.resolve_references.size(); i++) {
  4425. uint32_t color_index = subpass.color_references[i].attachment;
  4426. uint32_t resolve_index = subpass.resolve_references[i].attachment;
  4427. DEV_ASSERT((color_index == AttachmentReference::UNUSED) == (resolve_index == AttachmentReference::UNUSED));
  4428. if (color_index == AttachmentReference::UNUSED || !fb_info->attachments[color_index]) {
  4429. continue;
  4430. }
  4431. TextureInfo *src_tex_info = (TextureInfo *)fb_info->attachments[color_index].id;
  4432. uint32_t src_subresource = D3D12CalcSubresource(src_tex_info->base_mip, src_tex_info->base_layer, 0, src_tex_info->desc.MipLevels, src_tex_info->desc.ArraySize());
  4433. _resource_transition_batch(cmd_buf_info, src_tex_info, src_subresource, 1, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
  4434. TextureInfo *dst_tex_info = (TextureInfo *)fb_info->attachments[resolve_index].id;
  4435. uint32_t dst_subresource = D3D12CalcSubresource(dst_tex_info->base_mip, dst_tex_info->base_layer, 0, dst_tex_info->desc.MipLevels, dst_tex_info->desc.ArraySize());
  4436. _resource_transition_batch(cmd_buf_info, dst_tex_info, dst_subresource, 1, D3D12_RESOURCE_STATE_RESOLVE_DEST);
  4437. resolves[num_resolves].src_res = src_tex_info->resource;
  4438. resolves[num_resolves].src_subres = src_subresource;
  4439. resolves[num_resolves].dst_res = dst_tex_info->resource;
  4440. resolves[num_resolves].dst_subres = dst_subresource;
  4441. resolves[num_resolves].format = RD_TO_D3D12_FORMAT[src_tex_info->format].general_format;
  4442. num_resolves++;
  4443. }
  4444. _resource_transitions_flush(cmd_buf_info);
  4445. for (uint32_t i = 0; i < num_resolves; i++) {
  4446. cmd_buf_info->cmd_list->ResolveSubresource(resolves[i].dst_res, resolves[i].dst_subres, resolves[i].src_res, resolves[i].src_subres, resolves[i].format);
  4447. }
  4448. }
  4449. void RenderingDeviceDriverD3D12::command_end_render_pass(CommandBufferID p_cmd_buffer) {
  4450. _end_render_pass(p_cmd_buffer);
  4451. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4452. DEV_ASSERT(cmd_buf_info->render_pass_state.current_subpass != UINT32_MAX);
  4453. const FramebufferInfo *fb_info = cmd_buf_info->render_pass_state.fb_info;
  4454. const RenderPassInfo *pass_info = cmd_buf_info->render_pass_state.pass_info;
  4455. if (vrs_capabilities.ss_image_supported) {
  4456. ComPtr<ID3D12GraphicsCommandList5> cmd_list_5;
  4457. cmd_buf_info->cmd_list->QueryInterface(cmd_list_5.GetAddressOf());
  4458. if (cmd_list_5) {
  4459. cmd_list_5->RSSetShadingRateImage(nullptr);
  4460. }
  4461. }
  4462. for (uint32_t i = 0; i < pass_info->attachments.size(); i++) {
  4463. if (pass_info->attachments[i].store_op == ATTACHMENT_STORE_OP_DONT_CARE) {
  4464. const TextureInfo *tex_info = (const TextureInfo *)fb_info->attachments[i].id;
  4465. _discard_texture_subresources(tex_info, cmd_buf_info);
  4466. }
  4467. }
  4468. cmd_buf_info->render_pass_state.current_subpass = UINT32_MAX;
  4469. }
  4470. void RenderingDeviceDriverD3D12::command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) {
  4471. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4472. if (cmd_buf_info->render_pass_state.current_subpass == UINT32_MAX) {
  4473. cmd_buf_info->render_pass_state.current_subpass = 0;
  4474. } else {
  4475. _end_render_pass(p_cmd_buffer);
  4476. cmd_buf_info->render_pass_state.current_subpass++;
  4477. }
  4478. const FramebufferInfo *fb_info = cmd_buf_info->render_pass_state.fb_info;
  4479. const RenderPassInfo *pass_info = cmd_buf_info->render_pass_state.pass_info;
  4480. const Subpass &subpass = pass_info->subpasses[cmd_buf_info->render_pass_state.current_subpass];
  4481. D3D12_CPU_DESCRIPTOR_HANDLE *rtv_handles = ALLOCA_ARRAY(D3D12_CPU_DESCRIPTOR_HANDLE, subpass.color_references.size());
  4482. DescriptorsHeap::Walker rtv_heap_walker = fb_info->rtv_heap.make_walker();
  4483. for (uint32_t i = 0; i < subpass.color_references.size(); i++) {
  4484. uint32_t attachment = subpass.color_references[i].attachment;
  4485. if (attachment == AttachmentReference::UNUSED) {
  4486. if (!frames[frame_idx].null_rtv_handle.ptr) {
  4487. // No null descriptor-handle created for this frame yet.
  4488. if (frames[frame_idx].desc_heap_walkers.rtv.is_at_eof()) {
  4489. if (!frames[frame_idx].desc_heaps_exhausted_reported.rtv) {
  4490. frames[frame_idx].desc_heaps_exhausted_reported.rtv = true;
  4491. ERR_FAIL_MSG("Cannot begin subpass because there's no enough room in current frame's RENDER TARGET descriptors heap.\n"
  4492. "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting.");
  4493. } else {
  4494. return;
  4495. }
  4496. }
  4497. D3D12_RENDER_TARGET_VIEW_DESC rtv_desc_null = {};
  4498. rtv_desc_null.Format = DXGI_FORMAT_R8_UINT;
  4499. rtv_desc_null.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
  4500. frames[frame_idx].null_rtv_handle = frames[frame_idx].desc_heap_walkers.rtv.get_curr_cpu_handle();
  4501. device->CreateRenderTargetView(nullptr, &rtv_desc_null, frames[frame_idx].null_rtv_handle);
  4502. frames[frame_idx].desc_heap_walkers.rtv.advance();
  4503. }
  4504. rtv_handles[i] = frames[frame_idx].null_rtv_handle;
  4505. } else {
  4506. uint32_t rt_index = fb_info->attachments_handle_inds[attachment];
  4507. rtv_heap_walker.rewind();
  4508. rtv_heap_walker.advance(rt_index);
  4509. rtv_handles[i] = rtv_heap_walker.get_curr_cpu_handle();
  4510. }
  4511. }
  4512. D3D12_CPU_DESCRIPTOR_HANDLE dsv_handle = {};
  4513. {
  4514. DescriptorsHeap::Walker dsv_heap_walker = fb_info->dsv_heap.make_walker();
  4515. if (subpass.depth_stencil_reference.attachment != AttachmentReference::UNUSED) {
  4516. uint32_t ds_index = fb_info->attachments_handle_inds[subpass.depth_stencil_reference.attachment];
  4517. dsv_heap_walker.rewind();
  4518. dsv_heap_walker.advance(ds_index);
  4519. dsv_handle = dsv_heap_walker.get_curr_cpu_handle();
  4520. }
  4521. }
  4522. cmd_buf_info->cmd_list->OMSetRenderTargets(subpass.color_references.size(), rtv_handles, false, dsv_handle.ptr ? &dsv_handle : nullptr);
  4523. }
  4524. void RenderingDeviceDriverD3D12::command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) {
  4525. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  4526. D3D12_VIEWPORT *d3d12_viewports = ALLOCA_ARRAY(D3D12_VIEWPORT, p_viewports.size());
  4527. for (uint32_t i = 0; i < p_viewports.size(); i++) {
  4528. d3d12_viewports[i] = CD3DX12_VIEWPORT(
  4529. p_viewports[i].position.x,
  4530. p_viewports[i].position.y,
  4531. p_viewports[i].size.x,
  4532. p_viewports[i].size.y);
  4533. }
  4534. cmd_buf_info->cmd_list->RSSetViewports(p_viewports.size(), d3d12_viewports);
  4535. }
  4536. void RenderingDeviceDriverD3D12::command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) {
  4537. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  4538. D3D12_RECT *d3d12_scissors = ALLOCA_ARRAY(D3D12_RECT, p_scissors.size());
  4539. for (uint32_t i = 0; i < p_scissors.size(); i++) {
  4540. d3d12_scissors[i] = CD3DX12_RECT(
  4541. p_scissors[i].position.x,
  4542. p_scissors[i].position.y,
  4543. p_scissors[i].position.x + p_scissors[i].size.x,
  4544. p_scissors[i].position.y + p_scissors[i].size.y);
  4545. }
  4546. cmd_buf_info->cmd_list->RSSetScissorRects(p_scissors.size(), d3d12_scissors);
  4547. }
  4548. void RenderingDeviceDriverD3D12::command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) {
  4549. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  4550. DEV_ASSERT(cmd_buf_info->render_pass_state.current_subpass != UINT32_MAX);
  4551. const FramebufferInfo *fb_info = cmd_buf_info->render_pass_state.fb_info;
  4552. const RenderPassInfo *pass_info = cmd_buf_info->render_pass_state.pass_info;
  4553. DescriptorsHeap::Walker rtv_heap_walker = fb_info->rtv_heap.make_walker();
  4554. DescriptorsHeap::Walker dsv_heap_walker = fb_info->dsv_heap.make_walker();
  4555. for (uint32_t i = 0; i < p_attachment_clears.size(); i++) {
  4556. uint32_t attachment = UINT32_MAX;
  4557. bool is_render_target = false;
  4558. if (p_attachment_clears[i].aspect.has_flag(TEXTURE_ASPECT_COLOR_BIT)) {
  4559. attachment = p_attachment_clears[i].color_attachment;
  4560. is_render_target = true;
  4561. } else {
  4562. attachment = pass_info->subpasses[cmd_buf_info->render_pass_state.current_subpass].depth_stencil_reference.attachment;
  4563. }
  4564. for (uint32_t j = 0; j < p_rects.size(); j++) {
  4565. D3D12_RECT rect = CD3DX12_RECT(
  4566. p_rects[j].position.x,
  4567. p_rects[j].position.y,
  4568. p_rects[j].position.x + p_rects[j].size.x,
  4569. p_rects[j].position.y + p_rects[j].size.y);
  4570. const D3D12_RECT *rect_ptr = cmd_buf_info->render_pass_state.region_is_all ? nullptr : &rect;
  4571. if (is_render_target) {
  4572. uint32_t color_idx = fb_info->attachments_handle_inds[attachment];
  4573. rtv_heap_walker.rewind();
  4574. rtv_heap_walker.advance(color_idx);
  4575. cmd_buf_info->cmd_list->ClearRenderTargetView(
  4576. rtv_heap_walker.get_curr_cpu_handle(),
  4577. p_attachment_clears[i].value.color.components,
  4578. rect_ptr ? 1 : 0,
  4579. rect_ptr);
  4580. } else {
  4581. uint32_t depth_stencil_idx = fb_info->attachments_handle_inds[attachment];
  4582. dsv_heap_walker.rewind();
  4583. dsv_heap_walker.advance(depth_stencil_idx);
  4584. D3D12_CLEAR_FLAGS flags = {};
  4585. if (p_attachment_clears[i].aspect.has_flag(TEXTURE_ASPECT_DEPTH_BIT)) {
  4586. flags |= D3D12_CLEAR_FLAG_DEPTH;
  4587. }
  4588. if (p_attachment_clears[i].aspect.has_flag(TEXTURE_ASPECT_STENCIL_BIT)) {
  4589. flags |= D3D12_CLEAR_FLAG_STENCIL;
  4590. }
  4591. cmd_buf_info->cmd_list->ClearDepthStencilView(
  4592. dsv_heap_walker.get_curr_cpu_handle(),
  4593. flags,
  4594. p_attachment_clears[i].value.depth,
  4595. p_attachment_clears[i].value.stencil,
  4596. rect_ptr ? 1 : 0,
  4597. rect_ptr);
  4598. }
  4599. }
  4600. }
  4601. }
  4602. void RenderingDeviceDriverD3D12::command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
  4603. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4604. const PipelineInfo *pipeline_info = (const PipelineInfo *)p_pipeline.id;
  4605. if (cmd_buf_info->graphics_pso == pipeline_info->pso) {
  4606. return;
  4607. }
  4608. const ShaderInfo *shader_info_in = pipeline_info->shader_info;
  4609. const RenderPipelineInfo &render_info = pipeline_info->render_info;
  4610. cmd_buf_info->cmd_list->SetPipelineState(pipeline_info->pso);
  4611. if (cmd_buf_info->graphics_root_signature_crc != shader_info_in->root_signature_crc) {
  4612. cmd_buf_info->cmd_list->SetGraphicsRootSignature(shader_info_in->root_signature.Get());
  4613. cmd_buf_info->graphics_root_signature_crc = shader_info_in->root_signature_crc;
  4614. }
  4615. cmd_buf_info->cmd_list->IASetPrimitiveTopology(render_info.dyn_params.primitive_topology);
  4616. cmd_buf_info->cmd_list->OMSetBlendFactor(render_info.dyn_params.blend_constant.components);
  4617. cmd_buf_info->cmd_list->OMSetStencilRef(render_info.dyn_params.stencil_reference);
  4618. if (misc_features_support.depth_bounds_supported) {
  4619. ComPtr<ID3D12GraphicsCommandList1> command_list_1;
  4620. cmd_buf_info->cmd_list->QueryInterface(command_list_1.GetAddressOf());
  4621. if (command_list_1) {
  4622. command_list_1->OMSetDepthBounds(render_info.dyn_params.depth_bounds_min, render_info.dyn_params.depth_bounds_max);
  4623. }
  4624. }
  4625. cmd_buf_info->render_pass_state.vf_info = render_info.vf_info;
  4626. cmd_buf_info->graphics_pso = pipeline_info->pso;
  4627. cmd_buf_info->compute_pso = nullptr;
  4628. }
  4629. void RenderingDeviceDriverD3D12::command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  4630. _command_bind_uniform_set(p_cmd_buffer, p_uniform_set, p_shader, p_set_index, false);
  4631. }
  4632. void RenderingDeviceDriverD3D12::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) {
  4633. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4634. _bind_vertex_buffers(cmd_buf_info);
  4635. cmd_buf_info->cmd_list->DrawInstanced(p_vertex_count, p_instance_count, p_base_vertex, p_first_instance);
  4636. }
  4637. void RenderingDeviceDriverD3D12::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) {
  4638. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4639. _bind_vertex_buffers(cmd_buf_info);
  4640. cmd_buf_info->cmd_list->DrawIndexedInstanced(p_index_count, p_instance_count, p_first_index, p_vertex_offset, p_first_instance);
  4641. }
  4642. void RenderingDeviceDriverD3D12::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) {
  4643. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4644. _bind_vertex_buffers(cmd_buf_info);
  4645. BufferInfo *indirect_buf_info = (BufferInfo *)p_indirect_buffer.id;
  4646. if (!barrier_capabilities.enhanced_barriers_supported) {
  4647. _resource_transition_batch(cmd_buf_info, indirect_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4648. _resource_transitions_flush(cmd_buf_info);
  4649. }
  4650. cmd_buf_info->cmd_list->ExecuteIndirect(indirect_cmd_signatures.draw_indexed.Get(), p_draw_count, indirect_buf_info->resource, p_offset, nullptr, 0);
  4651. }
  4652. void RenderingDeviceDriverD3D12::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) {
  4653. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4654. _bind_vertex_buffers(cmd_buf_info);
  4655. BufferInfo *indirect_buf_info = (BufferInfo *)p_indirect_buffer.id;
  4656. BufferInfo *count_buf_info = (BufferInfo *)p_count_buffer.id;
  4657. if (!barrier_capabilities.enhanced_barriers_supported) {
  4658. _resource_transition_batch(cmd_buf_info, indirect_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4659. _resource_transition_batch(cmd_buf_info, count_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4660. _resource_transitions_flush(cmd_buf_info);
  4661. }
  4662. cmd_buf_info->cmd_list->ExecuteIndirect(indirect_cmd_signatures.draw_indexed.Get(), p_max_draw_count, indirect_buf_info->resource, p_offset, count_buf_info->resource, p_count_buffer_offset);
  4663. }
  4664. void RenderingDeviceDriverD3D12::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) {
  4665. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4666. _bind_vertex_buffers(cmd_buf_info);
  4667. BufferInfo *indirect_buf_info = (BufferInfo *)p_indirect_buffer.id;
  4668. if (!barrier_capabilities.enhanced_barriers_supported) {
  4669. _resource_transition_batch(cmd_buf_info, indirect_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4670. _resource_transitions_flush(cmd_buf_info);
  4671. }
  4672. cmd_buf_info->cmd_list->ExecuteIndirect(indirect_cmd_signatures.draw.Get(), p_draw_count, indirect_buf_info->resource, p_offset, nullptr, 0);
  4673. }
  4674. void RenderingDeviceDriverD3D12::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) {
  4675. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4676. _bind_vertex_buffers(cmd_buf_info);
  4677. BufferInfo *indirect_buf_info = (BufferInfo *)p_indirect_buffer.id;
  4678. BufferInfo *count_buf_info = (BufferInfo *)p_count_buffer.id;
  4679. if (!barrier_capabilities.enhanced_barriers_supported) {
  4680. _resource_transition_batch(cmd_buf_info, indirect_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4681. _resource_transition_batch(cmd_buf_info, count_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4682. _resource_transitions_flush(cmd_buf_info);
  4683. }
  4684. cmd_buf_info->cmd_list->ExecuteIndirect(indirect_cmd_signatures.draw.Get(), p_max_draw_count, indirect_buf_info->resource, p_offset, count_buf_info->resource, p_count_buffer_offset);
  4685. }
  4686. void RenderingDeviceDriverD3D12::command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) {
  4687. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4688. DEV_ASSERT(cmd_buf_info->render_pass_state.current_subpass != UINT32_MAX);
  4689. // Vertex buffer views are set deferredly, to be sure we already know the strides by then,
  4690. // which is only true once the pipeline has been bound. Otherwise, we'd need that the pipeline
  4691. // is always bound first, which would be not kind of us. [[DEFERRED_VERTEX_BUFFERS]]
  4692. DEV_ASSERT(p_binding_count <= ARRAY_SIZE(cmd_buf_info->render_pass_state.vertex_buffer_views));
  4693. for (uint32_t i = 0; i < p_binding_count; i++) {
  4694. BufferInfo *buffer_info = (BufferInfo *)p_buffers[i].id;
  4695. cmd_buf_info->render_pass_state.vertex_buffer_views[i] = {};
  4696. cmd_buf_info->render_pass_state.vertex_buffer_views[i].BufferLocation = buffer_info->resource->GetGPUVirtualAddress() + p_offsets[i];
  4697. cmd_buf_info->render_pass_state.vertex_buffer_views[i].SizeInBytes = buffer_info->size - p_offsets[i];
  4698. if (!barrier_capabilities.enhanced_barriers_supported) {
  4699. _resource_transition_batch(cmd_buf_info, buffer_info, 0, 1, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
  4700. }
  4701. }
  4702. if (!barrier_capabilities.enhanced_barriers_supported) {
  4703. _resource_transitions_flush(cmd_buf_info);
  4704. }
  4705. cmd_buf_info->render_pass_state.vertex_buffer_count = p_binding_count;
  4706. }
  4707. void RenderingDeviceDriverD3D12::command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) {
  4708. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4709. BufferInfo *buffer_info = (BufferInfo *)p_buffer.id;
  4710. D3D12_INDEX_BUFFER_VIEW d3d12_ib_view = {};
  4711. d3d12_ib_view.BufferLocation = buffer_info->resource->GetGPUVirtualAddress() + p_offset;
  4712. d3d12_ib_view.SizeInBytes = buffer_info->size - p_offset;
  4713. d3d12_ib_view.Format = p_format == INDEX_BUFFER_FORMAT_UINT16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  4714. if (!barrier_capabilities.enhanced_barriers_supported) {
  4715. _resource_transition_batch(cmd_buf_info, buffer_info, 0, 1, D3D12_RESOURCE_STATE_INDEX_BUFFER);
  4716. _resource_transitions_flush(cmd_buf_info);
  4717. }
  4718. cmd_buf_info->cmd_list->IASetIndexBuffer(&d3d12_ib_view);
  4719. }
  4720. // [[DEFERRED_VERTEX_BUFFERS]]
  4721. void RenderingDeviceDriverD3D12::_bind_vertex_buffers(CommandBufferInfo *p_cmd_buf_info) {
  4722. RenderPassState &render_pass_state = p_cmd_buf_info->render_pass_state;
  4723. if (render_pass_state.vertex_buffer_count && render_pass_state.vf_info) {
  4724. for (uint32_t i = 0; i < render_pass_state.vertex_buffer_count; i++) {
  4725. render_pass_state.vertex_buffer_views[i].StrideInBytes = render_pass_state.vf_info->vertex_buffer_strides[i];
  4726. }
  4727. p_cmd_buf_info->cmd_list->IASetVertexBuffers(0, render_pass_state.vertex_buffer_count, render_pass_state.vertex_buffer_views);
  4728. render_pass_state.vertex_buffer_count = 0;
  4729. }
  4730. }
  4731. void RenderingDeviceDriverD3D12::command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) {
  4732. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  4733. cmd_buf_info->cmd_list->OMSetBlendFactor(p_constants.components);
  4734. }
  4735. void RenderingDeviceDriverD3D12::command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) {
  4736. if (!Math::is_equal_approx(p_width, 1.0f)) {
  4737. ERR_FAIL_MSG("Setting line widths other than 1.0 is not supported by the Direct3D 12 rendering driver.");
  4738. }
  4739. }
  4740. // ----- PIPELINE -----
  4741. static const D3D12_PRIMITIVE_TOPOLOGY_TYPE RD_PRIMITIVE_TO_D3D12_TOPOLOGY_TYPE[RDD::RENDER_PRIMITIVE_MAX] = {
  4742. D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT,
  4743. D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
  4744. D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
  4745. D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
  4746. D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
  4747. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4748. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4749. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4750. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4751. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4752. D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH,
  4753. };
  4754. static const D3D12_PRIMITIVE_TOPOLOGY RD_PRIMITIVE_TO_D3D12_TOPOLOGY[RDD::RENDER_PRIMITIVE_MAX] = {
  4755. D3D_PRIMITIVE_TOPOLOGY_POINTLIST,
  4756. D3D_PRIMITIVE_TOPOLOGY_LINELIST,
  4757. D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ,
  4758. D3D_PRIMITIVE_TOPOLOGY_LINESTRIP,
  4759. D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ,
  4760. D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
  4761. D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ,
  4762. D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
  4763. D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ,
  4764. D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
  4765. D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST,
  4766. };
  4767. static const D3D12_CULL_MODE RD_POLYGON_CULL_TO_D3D12_CULL_MODE[RDD::POLYGON_CULL_MAX] = {
  4768. D3D12_CULL_MODE_NONE,
  4769. D3D12_CULL_MODE_FRONT,
  4770. D3D12_CULL_MODE_BACK,
  4771. };
  4772. static const D3D12_STENCIL_OP RD_TO_D3D12_STENCIL_OP[RDD::STENCIL_OP_MAX] = {
  4773. D3D12_STENCIL_OP_KEEP,
  4774. D3D12_STENCIL_OP_ZERO,
  4775. D3D12_STENCIL_OP_REPLACE,
  4776. D3D12_STENCIL_OP_INCR_SAT,
  4777. D3D12_STENCIL_OP_DECR_SAT,
  4778. D3D12_STENCIL_OP_INVERT,
  4779. D3D12_STENCIL_OP_INCR,
  4780. D3D12_STENCIL_OP_DECR,
  4781. };
  4782. static const D3D12_LOGIC_OP RD_TO_D3D12_LOGIC_OP[RDD::LOGIC_OP_MAX] = {
  4783. D3D12_LOGIC_OP_CLEAR,
  4784. D3D12_LOGIC_OP_AND,
  4785. D3D12_LOGIC_OP_AND_REVERSE,
  4786. D3D12_LOGIC_OP_COPY,
  4787. D3D12_LOGIC_OP_AND_INVERTED,
  4788. D3D12_LOGIC_OP_NOOP,
  4789. D3D12_LOGIC_OP_XOR,
  4790. D3D12_LOGIC_OP_OR,
  4791. D3D12_LOGIC_OP_NOR,
  4792. D3D12_LOGIC_OP_EQUIV,
  4793. D3D12_LOGIC_OP_INVERT,
  4794. D3D12_LOGIC_OP_OR_REVERSE,
  4795. D3D12_LOGIC_OP_COPY_INVERTED,
  4796. D3D12_LOGIC_OP_OR_INVERTED,
  4797. D3D12_LOGIC_OP_NAND,
  4798. D3D12_LOGIC_OP_SET,
  4799. };
  4800. static const D3D12_BLEND RD_TO_D3D12_BLEND_FACTOR[RDD::BLEND_FACTOR_MAX] = {
  4801. D3D12_BLEND_ZERO,
  4802. D3D12_BLEND_ONE,
  4803. D3D12_BLEND_SRC_COLOR,
  4804. D3D12_BLEND_INV_SRC_COLOR,
  4805. D3D12_BLEND_DEST_COLOR,
  4806. D3D12_BLEND_INV_DEST_COLOR,
  4807. D3D12_BLEND_SRC_ALPHA,
  4808. D3D12_BLEND_INV_SRC_ALPHA,
  4809. D3D12_BLEND_DEST_ALPHA,
  4810. D3D12_BLEND_INV_DEST_ALPHA,
  4811. D3D12_BLEND_BLEND_FACTOR,
  4812. D3D12_BLEND_INV_BLEND_FACTOR,
  4813. D3D12_BLEND_BLEND_FACTOR,
  4814. D3D12_BLEND_INV_BLEND_FACTOR,
  4815. D3D12_BLEND_SRC_ALPHA_SAT,
  4816. D3D12_BLEND_SRC1_COLOR,
  4817. D3D12_BLEND_INV_SRC1_COLOR,
  4818. D3D12_BLEND_SRC1_ALPHA,
  4819. D3D12_BLEND_INV_SRC1_ALPHA,
  4820. };
  4821. static const D3D12_BLEND_OP RD_TO_D3D12_BLEND_OP[RDD::BLEND_OP_MAX] = {
  4822. D3D12_BLEND_OP_ADD,
  4823. D3D12_BLEND_OP_SUBTRACT,
  4824. D3D12_BLEND_OP_REV_SUBTRACT,
  4825. D3D12_BLEND_OP_MIN,
  4826. D3D12_BLEND_OP_MAX,
  4827. };
  4828. RDD::PipelineID RenderingDeviceDriverD3D12::render_pipeline_create(
  4829. ShaderID p_shader,
  4830. VertexFormatID p_vertex_format,
  4831. RenderPrimitive p_render_primitive,
  4832. PipelineRasterizationState p_rasterization_state,
  4833. PipelineMultisampleState p_multisample_state,
  4834. PipelineDepthStencilState p_depth_stencil_state,
  4835. PipelineColorBlendState p_blend_state,
  4836. VectorView<int32_t> p_color_attachments,
  4837. BitField<PipelineDynamicStateFlags> p_dynamic_state,
  4838. RenderPassID p_render_pass,
  4839. uint32_t p_render_subpass,
  4840. VectorView<PipelineSpecializationConstant> p_specialization_constants) {
  4841. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  4842. CD3DX12_PIPELINE_STATE_STREAM pipeline_desc = {};
  4843. const RenderPassInfo *pass_info = (const RenderPassInfo *)p_render_pass.id;
  4844. RenderPipelineInfo render_info;
  4845. // Attachments.
  4846. LocalVector<uint32_t> color_attachments;
  4847. {
  4848. const Subpass &subpass = pass_info->subpasses[p_render_subpass];
  4849. for (uint32_t i = 0; i < ARRAY_SIZE((&pipeline_desc.RTVFormats)->RTFormats); i++) {
  4850. (&pipeline_desc.RTVFormats)->RTFormats[i] = DXGI_FORMAT_UNKNOWN;
  4851. }
  4852. for (uint32_t i = 0; i < subpass.color_references.size(); i++) {
  4853. const AttachmentReference &ref = subpass.color_references[i];
  4854. if (ref.attachment != AttachmentReference::UNUSED) {
  4855. const Attachment &attachment = pass_info->attachments[ref.attachment];
  4856. DEV_ASSERT((&pipeline_desc.RTVFormats)->RTFormats[i] == DXGI_FORMAT_UNKNOWN);
  4857. (&pipeline_desc.RTVFormats)->RTFormats[i] = RD_TO_D3D12_FORMAT[attachment.format].general_format;
  4858. }
  4859. }
  4860. (&pipeline_desc.RTVFormats)->NumRenderTargets = p_color_attachments.size();
  4861. if (subpass.depth_stencil_reference.attachment != AttachmentReference::UNUSED) {
  4862. const Attachment &attachment = pass_info->attachments[subpass.depth_stencil_reference.attachment];
  4863. pipeline_desc.DSVFormat = RD_TO_D3D12_FORMAT[attachment.format].dsv_format;
  4864. } else {
  4865. pipeline_desc.DSVFormat = DXGI_FORMAT_UNKNOWN;
  4866. }
  4867. }
  4868. // Vertex.
  4869. if (p_vertex_format) {
  4870. const VertexFormatInfo *vf_info = (const VertexFormatInfo *)p_vertex_format.id;
  4871. (&pipeline_desc.InputLayout)->pInputElementDescs = vf_info->input_elem_descs.ptr();
  4872. (&pipeline_desc.InputLayout)->NumElements = vf_info->input_elem_descs.size();
  4873. render_info.vf_info = vf_info;
  4874. }
  4875. // Input assembly & tessellation.
  4876. pipeline_desc.PrimitiveTopologyType = RD_PRIMITIVE_TO_D3D12_TOPOLOGY_TYPE[p_render_primitive];
  4877. if (p_render_primitive == RENDER_PRIMITIVE_TESSELATION_PATCH) {
  4878. // Is there any way to get the true point count limit?
  4879. ERR_FAIL_COND_V(p_rasterization_state.patch_control_points < 1 || p_rasterization_state.patch_control_points > 32, PipelineID());
  4880. render_info.dyn_params.primitive_topology = (D3D12_PRIMITIVE_TOPOLOGY)((int)D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST + p_rasterization_state.patch_control_points);
  4881. } else {
  4882. render_info.dyn_params.primitive_topology = RD_PRIMITIVE_TO_D3D12_TOPOLOGY[p_render_primitive];
  4883. }
  4884. if (p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX) {
  4885. // TODO: This is right for 16-bit indices; for 32-bit there's a different enum value to set, but we don't know at this point.
  4886. pipeline_desc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF;
  4887. } else {
  4888. pipeline_desc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED;
  4889. }
  4890. // Rasterization.
  4891. (&pipeline_desc.RasterizerState)->DepthClipEnable = !p_rasterization_state.enable_depth_clamp;
  4892. // In D3D12, discard can be supported with some extra effort (empty pixel shader + disable depth/stencil test); that said, unsupported by now.
  4893. ERR_FAIL_COND_V(p_rasterization_state.discard_primitives, PipelineID());
  4894. (&pipeline_desc.RasterizerState)->FillMode = p_rasterization_state.wireframe ? D3D12_FILL_MODE_WIREFRAME : D3D12_FILL_MODE_SOLID;
  4895. (&pipeline_desc.RasterizerState)->CullMode = RD_POLYGON_CULL_TO_D3D12_CULL_MODE[p_rasterization_state.cull_mode];
  4896. (&pipeline_desc.RasterizerState)->FrontCounterClockwise = p_rasterization_state.front_face == POLYGON_FRONT_FACE_COUNTER_CLOCKWISE;
  4897. // In D3D12, there's still a point in setting up depth bias with no depth buffer, but just zeroing (disabling) it all in such case is closer to Vulkan.
  4898. if (p_rasterization_state.depth_bias_enabled && pipeline_desc.DSVFormat != DXGI_FORMAT_UNKNOWN) {
  4899. (&pipeline_desc.RasterizerState)->DepthBias = p_rasterization_state.depth_bias_constant_factor;
  4900. (&pipeline_desc.RasterizerState)->DepthBiasClamp = p_rasterization_state.depth_bias_clamp;
  4901. (&pipeline_desc.RasterizerState)->SlopeScaledDepthBias = p_rasterization_state.depth_bias_slope_factor;
  4902. (&pipeline_desc.RasterizerState)->DepthBias = 0;
  4903. (&pipeline_desc.RasterizerState)->DepthBiasClamp = 0.0f;
  4904. (&pipeline_desc.RasterizerState)->SlopeScaledDepthBias = 0.0f;
  4905. }
  4906. (&pipeline_desc.RasterizerState)->ForcedSampleCount = 0;
  4907. (&pipeline_desc.RasterizerState)->ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  4908. (&pipeline_desc.RasterizerState)->MultisampleEnable = TEXTURE_SAMPLES_COUNT[p_multisample_state.sample_count] != 1;
  4909. (&pipeline_desc.RasterizerState)->AntialiasedLineEnable = true;
  4910. // In D3D12, there's no line width.
  4911. ERR_FAIL_COND_V(!Math::is_equal_approx(p_rasterization_state.line_width, 1.0f), PipelineID());
  4912. // Multisample.
  4913. ERR_FAIL_COND_V(p_multisample_state.enable_sample_shading, PipelineID()); // How one enables this in D3D12?
  4914. if ((&pipeline_desc.RTVFormats)->NumRenderTargets || pipeline_desc.DSVFormat != DXGI_FORMAT_UNKNOWN) {
  4915. uint32_t sample_count = MIN(
  4916. pass_info->max_supported_sample_count,
  4917. TEXTURE_SAMPLES_COUNT[p_multisample_state.sample_count]);
  4918. (&pipeline_desc.SampleDesc)->Count = sample_count;
  4919. } else {
  4920. (&pipeline_desc.SampleDesc)->Count = 1;
  4921. }
  4922. if ((&pipeline_desc.SampleDesc)->Count > 1) {
  4923. (&pipeline_desc.SampleDesc)->Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
  4924. } else {
  4925. (&pipeline_desc.SampleDesc)->Quality = 0;
  4926. }
  4927. if (p_multisample_state.sample_mask.size()) {
  4928. for (int i = 1; i < p_multisample_state.sample_mask.size(); i++) {
  4929. // In D3D12 there's a single sample mask for every pixel.
  4930. ERR_FAIL_COND_V(p_multisample_state.sample_mask[i] != p_multisample_state.sample_mask[0], PipelineID());
  4931. }
  4932. pipeline_desc.SampleMask = p_multisample_state.sample_mask[0];
  4933. } else {
  4934. pipeline_desc.SampleMask = 0xffffffff;
  4935. }
  4936. // Depth stencil.
  4937. if (pipeline_desc.DSVFormat == DXGI_FORMAT_UNKNOWN) {
  4938. (&pipeline_desc.DepthStencilState)->DepthEnable = false;
  4939. (&pipeline_desc.DepthStencilState)->StencilEnable = false;
  4940. } else {
  4941. (&pipeline_desc.DepthStencilState)->DepthEnable = p_depth_stencil_state.enable_depth_test;
  4942. (&pipeline_desc.DepthStencilState)->DepthWriteMask = p_depth_stencil_state.enable_depth_write ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;
  4943. (&pipeline_desc.DepthStencilState)->DepthFunc = RD_TO_D3D12_COMPARE_OP[p_depth_stencil_state.depth_compare_operator];
  4944. (&pipeline_desc.DepthStencilState)->DepthBoundsTestEnable = p_depth_stencil_state.enable_depth_range;
  4945. (&pipeline_desc.DepthStencilState)->StencilEnable = p_depth_stencil_state.enable_stencil;
  4946. // In D3D12 some elements can't be different across front and back.
  4947. ERR_FAIL_COND_V(p_depth_stencil_state.front_op.compare_mask != p_depth_stencil_state.back_op.compare_mask, PipelineID());
  4948. ERR_FAIL_COND_V(p_depth_stencil_state.front_op.write_mask != p_depth_stencil_state.back_op.write_mask, PipelineID());
  4949. ERR_FAIL_COND_V(p_depth_stencil_state.front_op.reference != p_depth_stencil_state.back_op.reference, PipelineID());
  4950. (&pipeline_desc.DepthStencilState)->StencilReadMask = p_depth_stencil_state.front_op.compare_mask;
  4951. (&pipeline_desc.DepthStencilState)->StencilWriteMask = p_depth_stencil_state.front_op.write_mask;
  4952. (&pipeline_desc.DepthStencilState)->FrontFace.StencilFailOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.front_op.fail];
  4953. (&pipeline_desc.DepthStencilState)->FrontFace.StencilPassOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.front_op.pass];
  4954. (&pipeline_desc.DepthStencilState)->FrontFace.StencilDepthFailOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.front_op.depth_fail];
  4955. (&pipeline_desc.DepthStencilState)->FrontFace.StencilFunc = RD_TO_D3D12_COMPARE_OP[p_depth_stencil_state.front_op.compare];
  4956. (&pipeline_desc.DepthStencilState)->BackFace.StencilFailOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.back_op.fail];
  4957. (&pipeline_desc.DepthStencilState)->BackFace.StencilPassOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.back_op.pass];
  4958. (&pipeline_desc.DepthStencilState)->BackFace.StencilDepthFailOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.back_op.depth_fail];
  4959. (&pipeline_desc.DepthStencilState)->BackFace.StencilFunc = RD_TO_D3D12_COMPARE_OP[p_depth_stencil_state.back_op.compare];
  4960. if (misc_features_support.depth_bounds_supported) {
  4961. render_info.dyn_params.depth_bounds_min = p_depth_stencil_state.enable_depth_range ? p_depth_stencil_state.depth_range_min : 0.0f;
  4962. render_info.dyn_params.depth_bounds_max = p_depth_stencil_state.enable_depth_range ? p_depth_stencil_state.depth_range_max : 1.0f;
  4963. } else {
  4964. if (p_depth_stencil_state.enable_depth_range) {
  4965. WARN_PRINT_ONCE("Depth bounds test is not supported by the GPU driver.");
  4966. }
  4967. }
  4968. render_info.dyn_params.stencil_reference = p_depth_stencil_state.front_op.reference;
  4969. }
  4970. // Blend states.
  4971. (&pipeline_desc.BlendState)->AlphaToCoverageEnable = p_multisample_state.enable_alpha_to_coverage;
  4972. {
  4973. bool all_attachments_same_blend = true;
  4974. for (int i = 0; i < p_blend_state.attachments.size(); i++) {
  4975. const PipelineColorBlendState::Attachment &bs = p_blend_state.attachments[i];
  4976. D3D12_RENDER_TARGET_BLEND_DESC &bd = (&pipeline_desc.BlendState)->RenderTarget[i];
  4977. bd.BlendEnable = bs.enable_blend;
  4978. bd.LogicOpEnable = p_blend_state.enable_logic_op;
  4979. bd.LogicOp = RD_TO_D3D12_LOGIC_OP[p_blend_state.logic_op];
  4980. bd.SrcBlend = RD_TO_D3D12_BLEND_FACTOR[bs.src_color_blend_factor];
  4981. bd.DestBlend = RD_TO_D3D12_BLEND_FACTOR[bs.dst_color_blend_factor];
  4982. bd.BlendOp = RD_TO_D3D12_BLEND_OP[bs.color_blend_op];
  4983. bd.SrcBlendAlpha = RD_TO_D3D12_BLEND_FACTOR[bs.src_alpha_blend_factor];
  4984. bd.DestBlendAlpha = RD_TO_D3D12_BLEND_FACTOR[bs.dst_alpha_blend_factor];
  4985. bd.BlendOpAlpha = RD_TO_D3D12_BLEND_OP[bs.alpha_blend_op];
  4986. if (bs.write_r) {
  4987. bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_RED;
  4988. }
  4989. if (bs.write_g) {
  4990. bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_GREEN;
  4991. }
  4992. if (bs.write_b) {
  4993. bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_BLUE;
  4994. }
  4995. if (bs.write_a) {
  4996. bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_ALPHA;
  4997. }
  4998. if (i > 0 && all_attachments_same_blend) {
  4999. all_attachments_same_blend = &(&pipeline_desc.BlendState)->RenderTarget[i] == &(&pipeline_desc.BlendState)->RenderTarget[0];
  5000. }
  5001. }
  5002. // Per D3D12 docs, if logic op used, independent blending is not supported.
  5003. ERR_FAIL_COND_V(p_blend_state.enable_logic_op && !all_attachments_same_blend, PipelineID());
  5004. (&pipeline_desc.BlendState)->IndependentBlendEnable = !all_attachments_same_blend;
  5005. }
  5006. render_info.dyn_params.blend_constant = p_blend_state.blend_constant;
  5007. // Stages bytecodes + specialization constants.
  5008. pipeline_desc.pRootSignature = shader_info_in->root_signature.Get();
  5009. HashMap<ShaderStage, Vector<uint8_t>> final_stages_bytecode;
  5010. bool ok = _shader_apply_specialization_constants(shader_info_in, p_specialization_constants, final_stages_bytecode);
  5011. ERR_FAIL_COND_V(!ok, PipelineID());
  5012. pipeline_desc.VS = D3D12_SHADER_BYTECODE{
  5013. final_stages_bytecode[SHADER_STAGE_VERTEX].ptr(),
  5014. (SIZE_T)final_stages_bytecode[SHADER_STAGE_VERTEX].size()
  5015. };
  5016. pipeline_desc.PS = D3D12_SHADER_BYTECODE{
  5017. final_stages_bytecode[SHADER_STAGE_FRAGMENT].ptr(),
  5018. (SIZE_T)final_stages_bytecode[SHADER_STAGE_FRAGMENT].size()
  5019. };
  5020. ComPtr<ID3D12Device2> device_2;
  5021. device->QueryInterface(device_2.GetAddressOf());
  5022. ID3D12PipelineState *pso = nullptr;
  5023. HRESULT res = E_FAIL;
  5024. if (device_2) {
  5025. D3D12_PIPELINE_STATE_STREAM_DESC pssd = {};
  5026. pssd.pPipelineStateSubobjectStream = &pipeline_desc;
  5027. pssd.SizeInBytes = sizeof(pipeline_desc);
  5028. res = device_2->CreatePipelineState(&pssd, IID_PPV_ARGS(&pso));
  5029. } else {
  5030. D3D12_GRAPHICS_PIPELINE_STATE_DESC desc = pipeline_desc.GraphicsDescV0();
  5031. res = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso));
  5032. }
  5033. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), PipelineID(), "Create(Graphics)PipelineState failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5034. PipelineInfo *pipeline_info = memnew(PipelineInfo);
  5035. pipeline_info->pso = pso;
  5036. pipeline_info->shader_info = shader_info_in;
  5037. pipeline_info->render_info = render_info;
  5038. return PipelineID(pipeline_info);
  5039. }
  5040. /*****************/
  5041. /**** COMPUTE ****/
  5042. /*****************/
  5043. // ----- COMMANDS -----
  5044. void RenderingDeviceDriverD3D12::command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
  5045. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  5046. const PipelineInfo *pipeline_info = (const PipelineInfo *)p_pipeline.id;
  5047. if (cmd_buf_info->compute_pso == pipeline_info->pso) {
  5048. return;
  5049. }
  5050. const ShaderInfo *shader_info_in = pipeline_info->shader_info;
  5051. cmd_buf_info->cmd_list->SetPipelineState(pipeline_info->pso);
  5052. if (cmd_buf_info->compute_root_signature_crc != shader_info_in->root_signature_crc) {
  5053. cmd_buf_info->cmd_list->SetComputeRootSignature(shader_info_in->root_signature.Get());
  5054. cmd_buf_info->compute_root_signature_crc = shader_info_in->root_signature_crc;
  5055. }
  5056. cmd_buf_info->compute_pso = pipeline_info->pso;
  5057. cmd_buf_info->graphics_pso = nullptr;
  5058. }
  5059. void RenderingDeviceDriverD3D12::command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  5060. _command_bind_uniform_set(p_cmd_buffer, p_uniform_set, p_shader, p_set_index, true);
  5061. }
  5062. void RenderingDeviceDriverD3D12::command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  5063. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  5064. if (!barrier_capabilities.enhanced_barriers_supported) {
  5065. _resource_transitions_flush(cmd_buf_info);
  5066. }
  5067. cmd_buf_info->cmd_list->Dispatch(p_x_groups, p_y_groups, p_z_groups);
  5068. }
  5069. void RenderingDeviceDriverD3D12::command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) {
  5070. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  5071. BufferInfo *indirect_buf_info = (BufferInfo *)p_indirect_buffer.id;
  5072. if (!barrier_capabilities.enhanced_barriers_supported) {
  5073. _resource_transition_batch(cmd_buf_info, indirect_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  5074. _resource_transitions_flush(cmd_buf_info);
  5075. }
  5076. cmd_buf_info->cmd_list->ExecuteIndirect(indirect_cmd_signatures.dispatch.Get(), 1, indirect_buf_info->resource, p_offset, nullptr, 0);
  5077. }
  5078. // ----- PIPELINE -----
  5079. RDD::PipelineID RenderingDeviceDriverD3D12::compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) {
  5080. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  5081. CD3DX12_PIPELINE_STATE_STREAM pipeline_desc = {};
  5082. // Stages bytecodes + specialization constants.
  5083. pipeline_desc.pRootSignature = shader_info_in->root_signature.Get();
  5084. HashMap<ShaderStage, Vector<uint8_t>> final_stages_bytecode;
  5085. bool ok = _shader_apply_specialization_constants(shader_info_in, p_specialization_constants, final_stages_bytecode);
  5086. ERR_FAIL_COND_V(!ok, PipelineID());
  5087. pipeline_desc.CS = D3D12_SHADER_BYTECODE{
  5088. final_stages_bytecode[SHADER_STAGE_COMPUTE].ptr(),
  5089. (SIZE_T)final_stages_bytecode[SHADER_STAGE_COMPUTE].size()
  5090. };
  5091. ComPtr<ID3D12Device2> device_2;
  5092. device->QueryInterface(device_2.GetAddressOf());
  5093. ID3D12PipelineState *pso = nullptr;
  5094. HRESULT res = E_FAIL;
  5095. if (device_2) {
  5096. D3D12_PIPELINE_STATE_STREAM_DESC pssd = {};
  5097. pssd.pPipelineStateSubobjectStream = &pipeline_desc;
  5098. pssd.SizeInBytes = sizeof(pipeline_desc);
  5099. res = device_2->CreatePipelineState(&pssd, IID_PPV_ARGS(&pso));
  5100. } else {
  5101. D3D12_COMPUTE_PIPELINE_STATE_DESC desc = pipeline_desc.ComputeDescV0();
  5102. res = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso));
  5103. }
  5104. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), PipelineID(), "Create(Compute)PipelineState failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5105. PipelineInfo *pipeline_info = memnew(PipelineInfo);
  5106. pipeline_info->pso = pso;
  5107. pipeline_info->shader_info = shader_info_in;
  5108. return PipelineID(pipeline_info);
  5109. }
  5110. /*****************/
  5111. /**** QUERIES ****/
  5112. /*****************/
  5113. // ----- TIMESTAMP -----
  5114. RDD::QueryPoolID RenderingDeviceDriverD3D12::timestamp_query_pool_create(uint32_t p_query_count) {
  5115. ComPtr<ID3D12QueryHeap> query_heap;
  5116. {
  5117. D3D12_QUERY_HEAP_DESC qh_desc = {};
  5118. qh_desc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP;
  5119. qh_desc.Count = p_query_count;
  5120. qh_desc.NodeMask = 0;
  5121. HRESULT res = device->CreateQueryHeap(&qh_desc, IID_PPV_ARGS(query_heap.GetAddressOf()));
  5122. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), QueryPoolID(), "CreateQueryHeap failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5123. }
  5124. ComPtr<D3D12MA::Allocation> results_buffer_allocation;
  5125. {
  5126. D3D12MA::ALLOCATION_DESC allocation_desc = {};
  5127. allocation_desc.HeapType = D3D12_HEAP_TYPE_READBACK;
  5128. CD3DX12_RESOURCE_DESC resource_desc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(uint64_t) * p_query_count);
  5129. ComPtr<ID3D12Resource> results_buffer;
  5130. HRESULT res = allocator->CreateResource(
  5131. &allocation_desc,
  5132. &resource_desc,
  5133. D3D12_RESOURCE_STATE_COPY_DEST,
  5134. nullptr,
  5135. results_buffer_allocation.GetAddressOf(),
  5136. IID_PPV_ARGS(results_buffer.GetAddressOf()));
  5137. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), QueryPoolID(), "D3D12MA::CreateResource failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5138. }
  5139. // Bookkeep.
  5140. TimestampQueryPoolInfo *tqp_info = VersatileResource::allocate<TimestampQueryPoolInfo>(resources_allocator);
  5141. tqp_info->query_heap = query_heap;
  5142. tqp_info->query_count = p_query_count;
  5143. tqp_info->results_buffer_allocation = results_buffer_allocation;
  5144. return RDD::QueryPoolID(tqp_info);
  5145. }
  5146. void RenderingDeviceDriverD3D12::timestamp_query_pool_free(QueryPoolID p_pool_id) {
  5147. TimestampQueryPoolInfo *tqp_info = (TimestampQueryPoolInfo *)p_pool_id.id;
  5148. VersatileResource::free(resources_allocator, tqp_info);
  5149. }
  5150. void RenderingDeviceDriverD3D12::timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) {
  5151. TimestampQueryPoolInfo *tqp_info = (TimestampQueryPoolInfo *)p_pool_id.id;
  5152. ID3D12Resource *results_buffer = tqp_info->results_buffer_allocation->GetResource();
  5153. void *results_buffer_data = nullptr;
  5154. results_buffer->Map(0, &VOID_RANGE, &results_buffer_data);
  5155. memcpy(r_results, results_buffer_data, sizeof(uint64_t) * p_query_count);
  5156. results_buffer->Unmap(0, &VOID_RANGE);
  5157. }
  5158. uint64_t RenderingDeviceDriverD3D12::timestamp_query_result_to_time(uint64_t p_result) {
  5159. return p_result / (double)device_limits.timestamp_frequency * 1000000000.0;
  5160. }
  5161. void RenderingDeviceDriverD3D12::command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) {
  5162. }
  5163. void RenderingDeviceDriverD3D12::command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) {
  5164. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  5165. TimestampQueryPoolInfo *tqp_info = (TimestampQueryPoolInfo *)p_pool_id.id;
  5166. ID3D12Resource *results_buffer = tqp_info->results_buffer_allocation->GetResource();
  5167. cmd_buf_info->cmd_list->EndQuery(tqp_info->query_heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, p_index);
  5168. cmd_buf_info->cmd_list->ResolveQueryData(tqp_info->query_heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, p_index, 1, results_buffer, p_index * sizeof(uint64_t));
  5169. }
  5170. void RenderingDeviceDriverD3D12::command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) {
  5171. #ifdef PIX_ENABLED
  5172. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  5173. PIXBeginEvent(cmd_buf_info->cmd_list.Get(), p_color.to_argb32(), p_label_name);
  5174. #endif
  5175. }
  5176. void RenderingDeviceDriverD3D12::command_end_label(CommandBufferID p_cmd_buffer) {
  5177. #ifdef PIX_ENABLED
  5178. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  5179. PIXEndEvent(cmd_buf_info->cmd_list.Get());
  5180. #endif
  5181. }
  5182. void RenderingDeviceDriverD3D12::command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) {
  5183. // TODO: Implement via DRED.
  5184. }
  5185. /********************/
  5186. /**** SUBMISSION ****/
  5187. /********************/
  5188. void RenderingDeviceDriverD3D12::begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) {
  5189. frame_idx = p_frame_index;
  5190. frames_drawn = p_frames_drawn;
  5191. allocator->SetCurrentFrameIndex(p_frames_drawn);
  5192. frames[frame_idx].desc_heap_walkers.resources.rewind();
  5193. frames[frame_idx].desc_heap_walkers.samplers.rewind();
  5194. frames[frame_idx].desc_heap_walkers.aux.rewind();
  5195. frames[frame_idx].desc_heap_walkers.rtv.rewind();
  5196. frames[frame_idx].desc_heaps_exhausted_reported = {};
  5197. frames[frame_idx].null_rtv_handle = CD3DX12_CPU_DESCRIPTOR_HANDLE{};
  5198. frames[frame_idx].segment_serial = segment_serial;
  5199. segment_begun = true;
  5200. }
  5201. void RenderingDeviceDriverD3D12::end_segment() {
  5202. segment_serial++;
  5203. segment_begun = false;
  5204. }
  5205. /**************/
  5206. /**** MISC ****/
  5207. /**************/
  5208. void RenderingDeviceDriverD3D12::_set_object_name(ID3D12Object *p_object, String p_object_name) {
  5209. ERR_FAIL_NULL(p_object);
  5210. int name_len = p_object_name.size();
  5211. WCHAR *name_w = (WCHAR *)alloca(sizeof(WCHAR) * (name_len + 1));
  5212. MultiByteToWideChar(CP_UTF8, 0, p_object_name.utf8().get_data(), -1, name_w, name_len);
  5213. p_object->SetName(name_w);
  5214. }
  5215. void RenderingDeviceDriverD3D12::set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) {
  5216. switch (p_type) {
  5217. case OBJECT_TYPE_TEXTURE: {
  5218. const TextureInfo *tex_info = (const TextureInfo *)p_driver_id.id;
  5219. if (tex_info->owner_info.allocation) {
  5220. _set_object_name(tex_info->resource, p_name);
  5221. }
  5222. } break;
  5223. case OBJECT_TYPE_SAMPLER: {
  5224. } break;
  5225. case OBJECT_TYPE_BUFFER: {
  5226. const BufferInfo *buf_info = (const BufferInfo *)p_driver_id.id;
  5227. _set_object_name(buf_info->resource, p_name);
  5228. } break;
  5229. case OBJECT_TYPE_SHADER: {
  5230. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_driver_id.id;
  5231. _set_object_name(shader_info_in->root_signature.Get(), p_name);
  5232. } break;
  5233. case OBJECT_TYPE_UNIFORM_SET: {
  5234. const UniformSetInfo *uniform_set_info = (const UniformSetInfo *)p_driver_id.id;
  5235. if (uniform_set_info->desc_heaps.resources.get_heap()) {
  5236. _set_object_name(uniform_set_info->desc_heaps.resources.get_heap(), p_name + " resources heap");
  5237. }
  5238. if (uniform_set_info->desc_heaps.samplers.get_heap()) {
  5239. _set_object_name(uniform_set_info->desc_heaps.samplers.get_heap(), p_name + " samplers heap");
  5240. }
  5241. } break;
  5242. case OBJECT_TYPE_PIPELINE: {
  5243. const PipelineInfo *pipeline_info = (const PipelineInfo *)p_driver_id.id;
  5244. _set_object_name(pipeline_info->pso, p_name);
  5245. } break;
  5246. default: {
  5247. DEV_ASSERT(false);
  5248. }
  5249. }
  5250. }
  5251. uint64_t RenderingDeviceDriverD3D12::get_resource_native_handle(DriverResource p_type, ID p_driver_id) {
  5252. switch (p_type) {
  5253. case DRIVER_RESOURCE_LOGICAL_DEVICE: {
  5254. return (uint64_t)device.Get();
  5255. }
  5256. case DRIVER_RESOURCE_PHYSICAL_DEVICE: {
  5257. return (uint64_t)adapter.Get();
  5258. }
  5259. case DRIVER_RESOURCE_TOPMOST_OBJECT: {
  5260. return 0;
  5261. }
  5262. case DRIVER_RESOURCE_COMMAND_QUEUE: {
  5263. return (uint64_t)p_driver_id.id;
  5264. }
  5265. case DRIVER_RESOURCE_QUEUE_FAMILY: {
  5266. return 0;
  5267. }
  5268. case DRIVER_RESOURCE_TEXTURE: {
  5269. const TextureInfo *tex_info = (const TextureInfo *)p_driver_id.id;
  5270. return (uint64_t)tex_info->main_texture;
  5271. } break;
  5272. case DRIVER_RESOURCE_TEXTURE_VIEW: {
  5273. const TextureInfo *tex_info = (const TextureInfo *)p_driver_id.id;
  5274. return (uint64_t)tex_info->resource;
  5275. }
  5276. case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: {
  5277. const TextureInfo *tex_info = (const TextureInfo *)p_driver_id.id;
  5278. return (uint64_t)tex_info->desc.Format;
  5279. }
  5280. case DRIVER_RESOURCE_SAMPLER:
  5281. case DRIVER_RESOURCE_UNIFORM_SET:
  5282. return 0;
  5283. case DRIVER_RESOURCE_BUFFER: {
  5284. const TextureInfo *tex_info = (const TextureInfo *)p_driver_id.id;
  5285. return (uint64_t)tex_info->resource;
  5286. } break;
  5287. case DRIVER_RESOURCE_COMPUTE_PIPELINE:
  5288. case DRIVER_RESOURCE_RENDER_PIPELINE: {
  5289. return p_driver_id.id;
  5290. }
  5291. default: {
  5292. return 0;
  5293. }
  5294. }
  5295. }
  5296. uint64_t RenderingDeviceDriverD3D12::get_total_memory_used() {
  5297. D3D12MA::TotalStatistics stats;
  5298. allocator->CalculateStatistics(&stats);
  5299. return stats.Total.Stats.BlockBytes;
  5300. }
  5301. uint64_t RenderingDeviceDriverD3D12::limit_get(Limit p_limit) {
  5302. uint64_t safe_unbounded = ((uint64_t)1 << 30);
  5303. switch (p_limit) {
  5304. case LIMIT_MAX_BOUND_UNIFORM_SETS:
  5305. return safe_unbounded;
  5306. case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
  5307. return device_limits.max_srvs_per_shader_stage;
  5308. case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
  5309. return 65536;
  5310. case LIMIT_MAX_VIEWPORT_DIMENSIONS_X:
  5311. case LIMIT_MAX_VIEWPORT_DIMENSIONS_Y:
  5312. return 16384; // Based on max. texture size. Maybe not correct.
  5313. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
  5314. return D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  5315. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
  5316. return D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  5317. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
  5318. return D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  5319. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
  5320. return D3D12_CS_THREAD_GROUP_MAX_X;
  5321. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
  5322. return D3D12_CS_THREAD_GROUP_MAX_Y;
  5323. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
  5324. return D3D12_CS_THREAD_GROUP_MAX_Z;
  5325. case LIMIT_SUBGROUP_SIZE:
  5326. // Note in min/max. Shader model 6.6 supports it (see https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html),
  5327. // but at this time I don't know the implications on the transpilation to DXIL, etc.
  5328. case LIMIT_SUBGROUP_MIN_SIZE:
  5329. case LIMIT_SUBGROUP_MAX_SIZE:
  5330. return subgroup_capabilities.size;
  5331. case LIMIT_SUBGROUP_IN_SHADERS:
  5332. return subgroup_capabilities.supported_stages_flags_rd();
  5333. case LIMIT_SUBGROUP_OPERATIONS:
  5334. return subgroup_capabilities.supported_operations_flags_rd();
  5335. case LIMIT_VRS_TEXEL_WIDTH:
  5336. case LIMIT_VRS_TEXEL_HEIGHT:
  5337. return vrs_capabilities.ss_image_tile_size;
  5338. case LIMIT_VRS_MAX_FRAGMENT_WIDTH:
  5339. case LIMIT_VRS_MAX_FRAGMENT_HEIGHT:
  5340. return vrs_capabilities.ss_max_fragment_size;
  5341. default: {
  5342. #ifdef DEV_ENABLED
  5343. WARN_PRINT("Returning maximum value for unknown limit " + itos(p_limit) + ".");
  5344. #endif
  5345. return safe_unbounded;
  5346. }
  5347. }
  5348. }
  5349. uint64_t RenderingDeviceDriverD3D12::api_trait_get(ApiTrait p_trait) {
  5350. switch (p_trait) {
  5351. case API_TRAIT_HONORS_PIPELINE_BARRIERS:
  5352. return barrier_capabilities.enhanced_barriers_supported;
  5353. case API_TRAIT_SHADER_CHANGE_INVALIDATION:
  5354. return (uint64_t)SHADER_CHANGE_INVALIDATION_ALL_OR_NONE_ACCORDING_TO_LAYOUT_HASH;
  5355. case API_TRAIT_TEXTURE_TRANSFER_ALIGNMENT:
  5356. return D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT;
  5357. case API_TRAIT_TEXTURE_DATA_ROW_PITCH_STEP:
  5358. return D3D12_TEXTURE_DATA_PITCH_ALIGNMENT;
  5359. case API_TRAIT_SECONDARY_VIEWPORT_SCISSOR:
  5360. return false;
  5361. case API_TRAIT_CLEARS_WITH_COPY_ENGINE:
  5362. return false;
  5363. case API_TRAIT_USE_GENERAL_IN_COPY_QUEUES:
  5364. return true;
  5365. case API_TRAIT_BUFFERS_REQUIRE_TRANSITIONS:
  5366. return !barrier_capabilities.enhanced_barriers_supported;
  5367. default:
  5368. return RenderingDeviceDriver::api_trait_get(p_trait);
  5369. }
  5370. }
  5371. bool RenderingDeviceDriverD3D12::has_feature(Features p_feature) {
  5372. switch (p_feature) {
  5373. case SUPPORTS_MULTIVIEW:
  5374. return multiview_capabilities.is_supported && multiview_capabilities.max_view_count > 1;
  5375. case SUPPORTS_FSR_HALF_FLOAT:
  5376. return shader_capabilities.native_16bit_ops && storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported;
  5377. case SUPPORTS_ATTACHMENT_VRS:
  5378. return vrs_capabilities.ss_image_supported;
  5379. case SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS:
  5380. return true;
  5381. default:
  5382. return false;
  5383. }
  5384. }
  5385. const RDD::MultiviewCapabilities &RenderingDeviceDriverD3D12::get_multiview_capabilities() {
  5386. return multiview_capabilities;
  5387. }
  5388. String RenderingDeviceDriverD3D12::get_api_name() const {
  5389. return "D3D12";
  5390. }
  5391. String RenderingDeviceDriverD3D12::get_api_version() const {
  5392. return vformat("%d_%d", feature_level / 10, feature_level % 10);
  5393. }
  5394. String RenderingDeviceDriverD3D12::get_pipeline_cache_uuid() const {
  5395. return pipeline_cache_id;
  5396. }
  5397. const RDD::Capabilities &RenderingDeviceDriverD3D12::get_capabilities() const {
  5398. return device_capabilities;
  5399. }
  5400. bool RenderingDeviceDriverD3D12::is_composite_alpha_supported(CommandQueueID p_queue) const {
  5401. if (has_comp_alpha.has((uint64_t)p_queue.id)) {
  5402. return has_comp_alpha[(uint64_t)p_queue.id];
  5403. }
  5404. return false;
  5405. }
  5406. /******************/
  5407. RenderingDeviceDriverD3D12::RenderingDeviceDriverD3D12(RenderingContextDriverD3D12 *p_context_driver) {
  5408. DEV_ASSERT(p_context_driver != nullptr);
  5409. this->context_driver = p_context_driver;
  5410. }
  5411. RenderingDeviceDriverD3D12::~RenderingDeviceDriverD3D12() {
  5412. glsl_type_singleton_decref();
  5413. }
  5414. bool RenderingDeviceDriverD3D12::is_in_developer_mode() {
  5415. HKEY hkey = nullptr;
  5416. LSTATUS result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\AppModelUnlock", 0, KEY_READ, &hkey);
  5417. if (result != ERROR_SUCCESS) {
  5418. return false;
  5419. }
  5420. DWORD value = 0;
  5421. DWORD dword_size = sizeof(DWORD);
  5422. result = RegQueryValueExW(hkey, L"AllowDevelopmentWithoutDevLicense", nullptr, nullptr, (PBYTE)&value, &dword_size);
  5423. RegCloseKey(hkey);
  5424. if (result != ERROR_SUCCESS) {
  5425. return false;
  5426. }
  5427. return (value != 0);
  5428. }
  5429. Error RenderingDeviceDriverD3D12::_initialize_device() {
  5430. HRESULT res;
  5431. if (is_in_developer_mode()) {
  5432. typedef HRESULT(WINAPI * PFN_D3D12_ENABLE_EXPERIMENTAL_FEATURES)(_In_ UINT, _In_count_(NumFeatures) const IID *, _In_opt_count_(NumFeatures) void *, _In_opt_count_(NumFeatures) UINT *);
  5433. PFN_D3D12_ENABLE_EXPERIMENTAL_FEATURES d3d_D3D12EnableExperimentalFeatures = (PFN_D3D12_ENABLE_EXPERIMENTAL_FEATURES)(void *)GetProcAddress(context_driver->lib_d3d12, "D3D12EnableExperimentalFeatures");
  5434. ERR_FAIL_NULL_V(d3d_D3D12EnableExperimentalFeatures, ERR_CANT_CREATE);
  5435. UUID experimental_features[] = { D3D12ExperimentalShaderModels };
  5436. d3d_D3D12EnableExperimentalFeatures(1, experimental_features, nullptr, nullptr);
  5437. }
  5438. ID3D12DeviceFactory *device_factory = context_driver->device_factory_get();
  5439. if (device_factory != nullptr) {
  5440. res = device_factory->CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(device.GetAddressOf()));
  5441. } else {
  5442. PFN_D3D12_CREATE_DEVICE d3d_D3D12CreateDevice = (PFN_D3D12_CREATE_DEVICE)(void *)GetProcAddress(context_driver->lib_d3d12, "D3D12CreateDevice");
  5443. ERR_FAIL_NULL_V(d3d_D3D12CreateDevice, ERR_CANT_CREATE);
  5444. res = d3d_D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(device.GetAddressOf()));
  5445. }
  5446. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_CANT_CREATE, "D3D12CreateDevice failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5447. if (context_driver->use_validation_layers()) {
  5448. ComPtr<ID3D12InfoQueue> info_queue;
  5449. res = device.As(&info_queue);
  5450. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5451. #if CUSTOM_INFO_QUEUE_ENABLED
  5452. ComPtr<ID3D12InfoQueue1> info_queue_1;
  5453. device.As(&info_queue_1);
  5454. if (info_queue_1) {
  5455. // Custom printing supported (added in Windows 10 Release Preview build 20236). Even if the callback cookie is unused, it seems the
  5456. // argument is not optional and the function will fail if it's not specified.
  5457. DWORD callback_cookie;
  5458. info_queue_1->SetMuteDebugOutput(TRUE);
  5459. res = info_queue_1->RegisterMessageCallback(&_debug_message_func, D3D12_MESSAGE_CALLBACK_IGNORE_FILTERS, nullptr, &callback_cookie);
  5460. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5461. } else
  5462. #endif
  5463. {
  5464. // Rely on D3D12's own debug printing.
  5465. if (Engine::get_singleton()->is_abort_on_gpu_errors_enabled()) {
  5466. res = info_queue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE);
  5467. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5468. res = info_queue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, TRUE);
  5469. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5470. res = info_queue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, TRUE);
  5471. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5472. }
  5473. }
  5474. D3D12_MESSAGE_SEVERITY severities_to_mute[] = {
  5475. D3D12_MESSAGE_SEVERITY_INFO,
  5476. };
  5477. D3D12_MESSAGE_ID messages_to_mute[] = {
  5478. D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE,
  5479. D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE,
  5480. // These happen due to how D3D12MA manages buffers; seems benign.
  5481. D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_HAS_NO_RESOURCE,
  5482. D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_INTERSECTS_MULTIPLE_BUFFERS,
  5483. // Seemingly a false positive.
  5484. D3D12_MESSAGE_ID_DATA_STATIC_WHILE_SET_AT_EXECUTE_DESCRIPTOR_INVALID_DATA_CHANGE,
  5485. };
  5486. D3D12_INFO_QUEUE_FILTER filter = {};
  5487. filter.DenyList.NumSeverities = ARRAY_SIZE(severities_to_mute);
  5488. filter.DenyList.pSeverityList = severities_to_mute;
  5489. filter.DenyList.NumIDs = ARRAY_SIZE(messages_to_mute);
  5490. filter.DenyList.pIDList = messages_to_mute;
  5491. res = info_queue->PushStorageFilter(&filter);
  5492. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5493. }
  5494. return OK;
  5495. }
  5496. Error RenderingDeviceDriverD3D12::_check_capabilities() {
  5497. // Check feature levels.
  5498. const D3D_FEATURE_LEVEL FEATURE_LEVELS[] = {
  5499. D3D_FEATURE_LEVEL_11_0,
  5500. D3D_FEATURE_LEVEL_11_1,
  5501. D3D_FEATURE_LEVEL_12_0,
  5502. D3D_FEATURE_LEVEL_12_1,
  5503. D3D_FEATURE_LEVEL_12_2,
  5504. };
  5505. D3D12_FEATURE_DATA_FEATURE_LEVELS feat_levels = {};
  5506. feat_levels.NumFeatureLevels = ARRAY_SIZE(FEATURE_LEVELS);
  5507. feat_levels.pFeatureLevelsRequested = FEATURE_LEVELS;
  5508. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &feat_levels, sizeof(feat_levels));
  5509. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_UNAVAILABLE, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5510. // Example: D3D_FEATURE_LEVEL_12_1 = 0xc100.
  5511. uint32_t feat_level_major = feat_levels.MaxSupportedFeatureLevel >> 12;
  5512. uint32_t feat_level_minor = (feat_levels.MaxSupportedFeatureLevel >> 16) & 0xff;
  5513. feature_level = feat_level_major * 10 + feat_level_minor;
  5514. // Fill device capabilities.
  5515. device_capabilities.device_family = DEVICE_DIRECTX;
  5516. device_capabilities.version_major = feature_level / 10;
  5517. device_capabilities.version_minor = feature_level % 10;
  5518. // Assume not supported until proven otherwise.
  5519. vrs_capabilities.draw_call_supported = false;
  5520. vrs_capabilities.primitive_supported = false;
  5521. vrs_capabilities.primitive_in_multiviewport = false;
  5522. vrs_capabilities.ss_image_supported = false;
  5523. vrs_capabilities.ss_image_tile_size = 1;
  5524. vrs_capabilities.additional_rates_supported = false;
  5525. multiview_capabilities.is_supported = false;
  5526. multiview_capabilities.geometry_shader_is_supported = false;
  5527. multiview_capabilities.tessellation_shader_is_supported = false;
  5528. multiview_capabilities.max_view_count = 0;
  5529. multiview_capabilities.max_instance_count = 0;
  5530. multiview_capabilities.is_supported = false;
  5531. subgroup_capabilities.size = 0;
  5532. subgroup_capabilities.wave_ops_supported = false;
  5533. shader_capabilities.shader_model = (D3D_SHADER_MODEL)0;
  5534. shader_capabilities.native_16bit_ops = false;
  5535. storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported = false;
  5536. format_capabilities.relaxed_casting_supported = false;
  5537. {
  5538. static const D3D_SHADER_MODEL SMS_TO_CHECK[] = {
  5539. D3D_SHADER_MODEL_6_6,
  5540. D3D_SHADER_MODEL_6_5,
  5541. D3D_SHADER_MODEL_6_4,
  5542. D3D_SHADER_MODEL_6_3,
  5543. D3D_SHADER_MODEL_6_2,
  5544. D3D_SHADER_MODEL_6_1,
  5545. D3D_SHADER_MODEL_6_0, // Determined by NIR (dxil_min_shader_model).
  5546. };
  5547. D3D12_FEATURE_DATA_SHADER_MODEL shader_model = {};
  5548. for (uint32_t i = 0; i < ARRAY_SIZE(SMS_TO_CHECK); i++) {
  5549. shader_model.HighestShaderModel = SMS_TO_CHECK[i];
  5550. res = device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &shader_model, sizeof(shader_model));
  5551. if (SUCCEEDED(res)) {
  5552. shader_capabilities.shader_model = shader_model.HighestShaderModel;
  5553. break;
  5554. }
  5555. if (res == E_INVALIDARG) {
  5556. continue; // Must assume the device doesn't know about the SM just checked.
  5557. }
  5558. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_CANT_CREATE, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5559. }
  5560. #define D3D_SHADER_MODEL_TO_STRING(m_sm) vformat("%d.%d", (m_sm >> 4), (m_sm & 0xf))
  5561. ERR_FAIL_COND_V_MSG(!shader_capabilities.shader_model, ERR_UNAVAILABLE,
  5562. vformat("No support for any of the suitable shader models (%s-%s) has been found.", D3D_SHADER_MODEL_TO_STRING(SMS_TO_CHECK[ARRAY_SIZE(SMS_TO_CHECK) - 1]), D3D_SHADER_MODEL_TO_STRING(SMS_TO_CHECK[0])));
  5563. print_verbose("- Shader:");
  5564. print_verbose(" model: " + D3D_SHADER_MODEL_TO_STRING(shader_capabilities.shader_model));
  5565. }
  5566. D3D12_FEATURE_DATA_D3D12_OPTIONS options = {};
  5567. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options));
  5568. if (SUCCEEDED(res)) {
  5569. storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported = options.TypedUAVLoadAdditionalFormats;
  5570. }
  5571. D3D12_FEATURE_DATA_D3D12_OPTIONS1 options1 = {};
  5572. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &options1, sizeof(options1));
  5573. if (SUCCEEDED(res)) {
  5574. subgroup_capabilities.size = options1.WaveLaneCountMin;
  5575. subgroup_capabilities.wave_ops_supported = options1.WaveOps;
  5576. }
  5577. D3D12_FEATURE_DATA_D3D12_OPTIONS2 options2 = {};
  5578. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS2, &options2, sizeof(options2));
  5579. if (SUCCEEDED(res)) {
  5580. misc_features_support.depth_bounds_supported = options2.DepthBoundsTestSupported;
  5581. }
  5582. D3D12_FEATURE_DATA_D3D12_OPTIONS3 options3 = {};
  5583. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, &options3, sizeof(options3));
  5584. if (SUCCEEDED(res)) {
  5585. // https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_view_instancing_tier
  5586. // https://microsoft.github.io/DirectX-Specs/d3d/ViewInstancing.html#sv_viewid
  5587. if (options3.ViewInstancingTier >= D3D12_VIEW_INSTANCING_TIER_1) {
  5588. multiview_capabilities.is_supported = true;
  5589. multiview_capabilities.geometry_shader_is_supported = options3.ViewInstancingTier >= D3D12_VIEW_INSTANCING_TIER_3;
  5590. multiview_capabilities.tessellation_shader_is_supported = options3.ViewInstancingTier >= D3D12_VIEW_INSTANCING_TIER_3;
  5591. multiview_capabilities.max_view_count = D3D12_MAX_VIEW_INSTANCE_COUNT;
  5592. multiview_capabilities.max_instance_count = UINT32_MAX;
  5593. }
  5594. }
  5595. D3D12_FEATURE_DATA_D3D12_OPTIONS4 options4 = {};
  5596. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS4, &options4, sizeof(options4));
  5597. if (SUCCEEDED(res)) {
  5598. shader_capabilities.native_16bit_ops = options4.Native16BitShaderOpsSupported;
  5599. }
  5600. D3D12_FEATURE_DATA_D3D12_OPTIONS6 options6 = {};
  5601. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS6, &options6, sizeof(options6));
  5602. if (SUCCEEDED(res)) {
  5603. if (options6.VariableShadingRateTier >= D3D12_VARIABLE_SHADING_RATE_TIER_1) {
  5604. vrs_capabilities.draw_call_supported = true;
  5605. if (options6.VariableShadingRateTier >= D3D12_VARIABLE_SHADING_RATE_TIER_2) {
  5606. vrs_capabilities.primitive_supported = true;
  5607. vrs_capabilities.primitive_in_multiviewport = options6.PerPrimitiveShadingRateSupportedWithViewportIndexing;
  5608. vrs_capabilities.ss_image_supported = true;
  5609. vrs_capabilities.ss_image_tile_size = options6.ShadingRateImageTileSize;
  5610. vrs_capabilities.ss_max_fragment_size = 8; // TODO figure out if this is supplied and/or needed
  5611. vrs_capabilities.additional_rates_supported = options6.AdditionalShadingRatesSupported;
  5612. }
  5613. }
  5614. }
  5615. D3D12_FEATURE_DATA_D3D12_OPTIONS12 options12 = {};
  5616. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, &options12, sizeof(options12));
  5617. if (SUCCEEDED(res)) {
  5618. format_capabilities.relaxed_casting_supported = options12.RelaxedFormatCastingSupported;
  5619. barrier_capabilities.enhanced_barriers_supported = options12.EnhancedBarriersSupported;
  5620. }
  5621. if (vrs_capabilities.draw_call_supported || vrs_capabilities.primitive_supported || vrs_capabilities.ss_image_supported) {
  5622. print_verbose("- D3D12 Variable Rate Shading supported:");
  5623. if (vrs_capabilities.draw_call_supported) {
  5624. print_verbose(" Draw call");
  5625. }
  5626. if (vrs_capabilities.primitive_supported) {
  5627. print_verbose(String(" Per-primitive (multi-viewport: ") + (vrs_capabilities.primitive_in_multiviewport ? "yes" : "no") + ")");
  5628. }
  5629. if (vrs_capabilities.ss_image_supported) {
  5630. print_verbose(String(" Screen-space image (tile size: ") + itos(vrs_capabilities.ss_image_tile_size) + ")");
  5631. }
  5632. if (vrs_capabilities.additional_rates_supported) {
  5633. print_verbose(String(" Additional rates: ") + (vrs_capabilities.additional_rates_supported ? "yes" : "no"));
  5634. }
  5635. } else {
  5636. print_verbose("- D3D12 Variable Rate Shading not supported");
  5637. }
  5638. if (multiview_capabilities.is_supported) {
  5639. print_verbose("- D3D12 multiview supported:");
  5640. print_verbose(" max view count: " + itos(multiview_capabilities.max_view_count));
  5641. //print_verbose(" max instances: " + itos(multiview_capabilities.max_instance_count)); // Hardcoded; not very useful at the moment.
  5642. } else {
  5643. print_verbose("- D3D12 multiview not supported");
  5644. }
  5645. if (format_capabilities.relaxed_casting_supported) {
  5646. #if 0
  5647. print_verbose("- Relaxed casting supported");
  5648. #else
  5649. // Certain configurations (Windows 11 with an updated NVIDIA driver) crash when using relaxed casting.
  5650. // Therefore, we disable it temporarily until we can assure that it's reliable.
  5651. // There are fallbacks in place that work in every case, if less efficient.
  5652. format_capabilities.relaxed_casting_supported = false;
  5653. print_verbose("- Relaxed casting supported (but disabled for now)");
  5654. #endif
  5655. } else {
  5656. print_verbose("- Relaxed casting not supported");
  5657. }
  5658. print_verbose(String("- D3D12 16-bit ops supported: ") + (shader_capabilities.native_16bit_ops ? "yes" : "no"));
  5659. if (misc_features_support.depth_bounds_supported) {
  5660. print_verbose("- Depth bounds test supported");
  5661. } else {
  5662. print_verbose("- Depth bounds test not supported");
  5663. }
  5664. return OK;
  5665. }
  5666. Error RenderingDeviceDriverD3D12::_get_device_limits() {
  5667. D3D12_FEATURE_DATA_D3D12_OPTIONS options = {};
  5668. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options));
  5669. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_UNAVAILABLE, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5670. // https://docs.microsoft.com/en-us/windows/win32/direct3d12/hardware-support
  5671. device_limits.max_srvs_per_shader_stage = options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_1 ? 128 : UINT64_MAX;
  5672. device_limits.max_cbvs_per_shader_stage = options.ResourceBindingTier <= D3D12_RESOURCE_BINDING_TIER_2 ? 14 : UINT64_MAX;
  5673. device_limits.max_samplers_across_all_stages = options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_1 ? 16 : 2048;
  5674. if (options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_1) {
  5675. device_limits.max_uavs_across_all_stages = feature_level <= 110 ? 8 : 64;
  5676. } else if (options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_2) {
  5677. device_limits.max_uavs_across_all_stages = 64;
  5678. } else {
  5679. device_limits.max_uavs_across_all_stages = UINT64_MAX;
  5680. }
  5681. // Retrieving the timestamp frequency requires creating a command queue that will be discarded immediately.
  5682. ComPtr<ID3D12CommandQueue> unused_command_queue;
  5683. D3D12_COMMAND_QUEUE_DESC queue_desc = {};
  5684. queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  5685. res = device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(unused_command_queue.GetAddressOf()));
  5686. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5687. res = unused_command_queue->GetTimestampFrequency(&device_limits.timestamp_frequency);
  5688. if (!SUCCEEDED(res)) {
  5689. print_verbose("D3D12: GetTimestampFrequency failed with error " + vformat("0x%08ux", (uint64_t)res) + ". Timestamps will be inaccurate.");
  5690. }
  5691. return OK;
  5692. }
  5693. Error RenderingDeviceDriverD3D12::_initialize_allocator() {
  5694. D3D12MA::ALLOCATOR_DESC allocator_desc = {};
  5695. allocator_desc.pDevice = device.Get();
  5696. allocator_desc.pAdapter = adapter.Get();
  5697. allocator_desc.Flags = D3D12MA::ALLOCATOR_FLAG_DEFAULT_POOLS_NOT_ZEROED;
  5698. HRESULT res = D3D12MA::CreateAllocator(&allocator_desc, &allocator);
  5699. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_CANT_CREATE, "D3D12MA::CreateAllocator failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5700. return OK;
  5701. }
  5702. static Error create_command_signature(ID3D12Device *device, D3D12_INDIRECT_ARGUMENT_TYPE p_type, uint32_t p_stride, ComPtr<ID3D12CommandSignature> *r_cmd_sig) {
  5703. D3D12_INDIRECT_ARGUMENT_DESC iarg_desc = {};
  5704. iarg_desc.Type = p_type;
  5705. D3D12_COMMAND_SIGNATURE_DESC cs_desc = {};
  5706. cs_desc.ByteStride = p_stride;
  5707. cs_desc.NumArgumentDescs = 1;
  5708. cs_desc.pArgumentDescs = &iarg_desc;
  5709. cs_desc.NodeMask = 0;
  5710. HRESULT res = device->CreateCommandSignature(&cs_desc, nullptr, IID_PPV_ARGS(r_cmd_sig->GetAddressOf()));
  5711. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_CANT_CREATE, "CreateCommandSignature failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5712. return OK;
  5713. }
  5714. Error RenderingDeviceDriverD3D12::_initialize_frames(uint32_t p_frame_count) {
  5715. Error err;
  5716. //CD3DX12_RESOURCE_DESC resource_desc = CD3DX12_RESOURCE_DESC::Buffer(D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT);
  5717. uint32_t resource_descriptors_per_frame = GLOBAL_GET("rendering/rendering_device/d3d12/max_resource_descriptors_per_frame");
  5718. uint32_t sampler_descriptors_per_frame = GLOBAL_GET("rendering/rendering_device/d3d12/max_sampler_descriptors_per_frame");
  5719. uint32_t misc_descriptors_per_frame = GLOBAL_GET("rendering/rendering_device/d3d12/max_misc_descriptors_per_frame");
  5720. frames.resize(p_frame_count);
  5721. for (uint32_t i = 0; i < frames.size(); i++) {
  5722. err = frames[i].desc_heaps.resources.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, resource_descriptors_per_frame, true);
  5723. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Creating the frame's RESOURCE descriptors heap failed.");
  5724. err = frames[i].desc_heaps.samplers.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, sampler_descriptors_per_frame, true);
  5725. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Creating the frame's SAMPLER descriptors heap failed.");
  5726. err = frames[i].desc_heaps.aux.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, misc_descriptors_per_frame, false);
  5727. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Creating the frame's AUX descriptors heap failed.");
  5728. err = frames[i].desc_heaps.rtv.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_RTV, misc_descriptors_per_frame, false);
  5729. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Creating the frame's RENDER TARGET descriptors heap failed.");
  5730. frames[i].desc_heap_walkers.resources = frames[i].desc_heaps.resources.make_walker();
  5731. frames[i].desc_heap_walkers.samplers = frames[i].desc_heaps.samplers.make_walker();
  5732. frames[i].desc_heap_walkers.aux = frames[i].desc_heaps.aux.make_walker();
  5733. frames[i].desc_heap_walkers.rtv = frames[i].desc_heaps.rtv.make_walker();
  5734. }
  5735. return OK;
  5736. }
  5737. Error RenderingDeviceDriverD3D12::_initialize_command_signatures() {
  5738. Error err = create_command_signature(device.Get(), D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, sizeof(D3D12_DRAW_ARGUMENTS), &indirect_cmd_signatures.draw);
  5739. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5740. err = create_command_signature(device.Get(), D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED, sizeof(D3D12_DRAW_INDEXED_ARGUMENTS), &indirect_cmd_signatures.draw_indexed);
  5741. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5742. err = create_command_signature(device.Get(), D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, sizeof(D3D12_DISPATCH_ARGUMENTS), &indirect_cmd_signatures.dispatch);
  5743. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5744. return OK;
  5745. }
  5746. Error RenderingDeviceDriverD3D12::initialize(uint32_t p_device_index, uint32_t p_frame_count) {
  5747. context_device = context_driver->device_get(p_device_index);
  5748. adapter = context_driver->create_adapter(p_device_index);
  5749. ERR_FAIL_NULL_V(adapter, ERR_CANT_CREATE);
  5750. HRESULT res = adapter->GetDesc(&adapter_desc);
  5751. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5752. // Set the pipeline cache ID based on the adapter information.
  5753. pipeline_cache_id = String::hex_encode_buffer((uint8_t *)&adapter_desc.AdapterLuid, sizeof(LUID));
  5754. pipeline_cache_id += "-driver-" + itos(adapter_desc.Revision);
  5755. Error err = _initialize_device();
  5756. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5757. err = _check_capabilities();
  5758. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5759. err = _get_device_limits();
  5760. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5761. err = _initialize_allocator();
  5762. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5763. err = _initialize_frames(p_frame_count);
  5764. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5765. err = _initialize_command_signatures();
  5766. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5767. glsl_type_singleton_init_or_ref();
  5768. return OK;
  5769. }