SDL_gpu_d3d12.c 350 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_GPU_D3D12
  20. #include "../../core/windows/SDL_windows.h"
  21. #include "../../video/directx/SDL_d3d12.h"
  22. #include "../SDL_sysgpu.h"
  23. #ifdef __IDXGIInfoQueue_INTERFACE_DEFINED__
  24. #define HAVE_IDXGIINFOQUEUE
  25. #endif
  26. // Built-in shaders, compiled with compile_shaders.bat
  27. #define g_FullscreenVert D3D12_FullscreenVert
  28. #define g_BlitFrom2D D3D12_BlitFrom2D
  29. #define g_BlitFrom2DArray D3D12_BlitFrom2DArray
  30. #define g_BlitFrom3D D3D12_BlitFrom3D
  31. #define g_BlitFromCube D3D12_BlitFromCube
  32. #define g_BlitFromCubeArray D3D12_BlitFromCubeArray
  33. #if defined(SDL_PLATFORM_XBOXSERIES)
  34. #include "D3D12_Blit_Series.h"
  35. #elif defined(SDL_PLATFORM_XBOXONE)
  36. #include "D3D12_Blit_One.h"
  37. #else
  38. #include "D3D12_Blit.h"
  39. #endif
  40. #undef g_FullscreenVert
  41. #undef g_BlitFrom2D
  42. #undef g_BlitFrom2DArray
  43. #undef g_BlitFrom3D
  44. #undef g_BlitFromCube
  45. #undef g_BlitFromCubeArray
  46. // Macros
  47. #define SET_ERROR(fmt, msg) \
  48. do { \
  49. if (renderer->debug_mode) { \
  50. SDL_LogError(SDL_LOG_CATEGORY_GPU, fmt, msg); \
  51. } \
  52. SDL_SetError(fmt, msg); \
  53. } while (0)
  54. #define SET_ERROR_AND_RETURN(fmt, msg, ret) \
  55. do { \
  56. if (renderer->debug_mode) { \
  57. SDL_LogError(SDL_LOG_CATEGORY_GPU, fmt, msg); \
  58. } \
  59. SDL_SetError(fmt, msg); \
  60. return ret; \
  61. } while (0)
  62. #define SET_STRING_ERROR_AND_RETURN(msg, ret) SET_ERROR_AND_RETURN("%s", msg, ret)
  63. #define CHECK_D3D12_ERROR_AND_RETURN(msg, ret) \
  64. do { \
  65. if (FAILED(res)) { \
  66. D3D12_INTERNAL_SetError(renderer, msg, res); \
  67. return (ret); \
  68. } \
  69. } while (0)
  70. // Defines
  71. #if defined(_WIN32)
  72. #if defined(SDL_PLATFORM_XBOXSERIES)
  73. #define D3D12_DLL "d3d12_xs.dll"
  74. #elif defined(SDL_PLATFORM_XBOXONE)
  75. #define D3D12_DLL "d3d12_x.dll"
  76. #else
  77. #define D3D12_DLL "d3d12.dll"
  78. #define USE_PIX_RUNTIME
  79. #define WINPIXEVENTRUNTIME_DLL "WinPixEventRuntime.dll"
  80. #endif
  81. #define DXGI_DLL "dxgi.dll"
  82. #define DXGIDEBUG_DLL "dxgidebug.dll"
  83. #elif defined(__APPLE__)
  84. #define D3D12_DLL "libdxvk_d3d12.dylib"
  85. #define DXGI_DLL "libdxvk_dxgi.dylib"
  86. #define DXGIDEBUG_DLL "libdxvk_dxgidebug.dylib"
  87. #else
  88. #define D3D12_DLL "libdxvk_d3d12.so"
  89. #define DXGI_DLL "libdxvk_dxgi.so"
  90. #define DXGIDEBUG_DLL "libdxvk_dxgidebug.so"
  91. #endif
  92. #define D3D12_CREATE_DEVICE_FUNC "D3D12CreateDevice"
  93. #define D3D12_SERIALIZE_ROOT_SIGNATURE_FUNC "D3D12SerializeRootSignature"
  94. #define CREATE_DXGI_FACTORY1_FUNC "CreateDXGIFactory1"
  95. #define DXGI_GET_DEBUG_INTERFACE_FUNC "DXGIGetDebugInterface"
  96. #define D3D12_GET_DEBUG_INTERFACE_FUNC "D3D12GetDebugInterface"
  97. #define WINDOW_PROPERTY_DATA "SDL_GPUD3D12WindowPropertyData"
  98. #define D3D_FEATURE_LEVEL_CHOICE D3D_FEATURE_LEVEL_11_0
  99. #define D3D_FEATURE_LEVEL_CHOICE_STR "11_0"
  100. #define MAX_ROOT_SIGNATURE_PARAMETERS 64
  101. #define D3D12_FENCE_UNSIGNALED_VALUE 0
  102. #define D3D12_FENCE_SIGNAL_VALUE 1
  103. // TODO: do these need to be tuned?
  104. #define VIEW_GPU_DESCRIPTOR_COUNT 65536
  105. #define SAMPLER_GPU_DESCRIPTOR_COUNT 2048
  106. #define STAGING_HEAP_DESCRIPTOR_COUNT 1024
  107. #define SDL_GPU_SHADERSTAGE_COMPUTE (SDL_GPUShaderStage)2
  108. #ifdef _WIN32
  109. #define HRESULT_FMT "(0x%08lX)"
  110. #else
  111. #define HRESULT_FMT "(0x%08X)"
  112. #endif
  113. // Function Pointer Signatures
  114. typedef HRESULT (WINAPI *pfnCreateDXGIFactory1)(const GUID *riid, void **ppFactory);
  115. typedef HRESULT (WINAPI *pfnDXGIGetDebugInterface)(const GUID *riid, void **ppDebug);
  116. #ifdef USE_PIX_RUNTIME
  117. #define PIX_BEGIN_EVENT_ON_COMMAND_LIST_FUNC "PIXBeginEventOnCommandList"
  118. #define PIX_END_EVENT_ON_COMMAND_LIST_FUNC "PIXEndEventOnCommandList"
  119. #define PIX_SET_MARKER_ON_COMMAND_LIST_FUNC "PIXSetMarkerOnCommandList"
  120. typedef void(WINAPI* pfnBeginEventOnCommandList)(ID3D12GraphicsCommandList* commandList, UINT64 color, _In_ PCSTR formatString);
  121. typedef void(WINAPI* pfnEndEventOnCommandList)(ID3D12GraphicsCommandList* commandList);
  122. typedef void(WINAPI* pfnSetMarkerOnCommandList)(ID3D12GraphicsCommandList* commandList, UINT64 color, _In_ PCSTR formatString);
  123. #endif
  124. // IIDs (from https://www.magnumdb.com/)
  125. static const IID D3D_IID_IDXGIFactory1 = { 0x770aae78, 0xf26f, 0x4dba, { 0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87 } };
  126. static const IID D3D_IID_IDXGIFactory4 = { 0x1bc6ea02, 0xef36, 0x464f, { 0xbf, 0x0c, 0x21, 0xca, 0x39, 0xe5, 0x16, 0x8a } };
  127. static const IID D3D_IID_IDXGIFactory5 = { 0x7632e1f5, 0xee65, 0x4dca, { 0x87, 0xfd, 0x84, 0xcd, 0x75, 0xf8, 0x83, 0x8d } };
  128. static const IID D3D_IID_IDXGIFactory6 = { 0xc1b6694f, 0xff09, 0x44a9, { 0xb0, 0x3c, 0x77, 0x90, 0x0a, 0x0a, 0x1d, 0x17 } };
  129. static const IID D3D_IID_IDXGIAdapter1 = { 0x29038f61, 0x3839, 0x4626, { 0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05 } };
  130. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  131. static const IID D3D_IID_IDXGIDevice1 = { 0x77db970f, 0x6276, 0x48ba, { 0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c } };
  132. #else
  133. static const IID D3D_IID_IDXGIDevice = { 0x54ec77fa, 0x1377, 0x44e6, { 0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c } };
  134. #endif
  135. static const IID D3D_IID_IDXGISwapChain3 = { 0x94d99bdb, 0xf1f8, 0x4ab0, { 0xb2, 0x36, 0x7d, 0xa0, 0x17, 0x0e, 0xda, 0xb1 } };
  136. #ifdef HAVE_IDXGIINFOQUEUE
  137. static const IID D3D_IID_IDXGIDebug = { 0x119e7452, 0xde9e, 0x40fe, { 0x88, 0x06, 0x88, 0xf9, 0x0c, 0x12, 0xb4, 0x41 } };
  138. static const IID D3D_IID_IDXGIInfoQueue = { 0xd67441c7, 0x672a, 0x476f, { 0x9e, 0x82, 0xcd, 0x55, 0xb4, 0x49, 0x49, 0xce } };
  139. #endif
  140. static const GUID D3D_IID_DXGI_DEBUG_ALL = { 0xe48ae283, 0xda80, 0x490b, { 0x87, 0xe6, 0x43, 0xe9, 0xa9, 0xcf, 0xda, 0x08 } };
  141. static const IID D3D_IID_ID3D12Device = { 0x189819f1, 0x1db6, 0x4b57, { 0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7 } };
  142. static const IID D3D_IID_ID3D12CommandQueue = { 0x0ec870a6, 0x5d7e, 0x4c22, { 0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed } };
  143. static const IID D3D_IID_ID3D12DescriptorHeap = { 0x8efb471d, 0x616c, 0x4f49, { 0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51 } };
  144. static const IID D3D_IID_ID3D12Resource = { 0x696442be, 0xa72e, 0x4059, { 0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad } };
  145. static const IID D3D_IID_ID3D12CommandAllocator = { 0x6102dee4, 0xaf59, 0x4b09, { 0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24 } };
  146. static const IID D3D_IID_ID3D12CommandList = { 0x7116d91c, 0xe7e4, 0x47ce, { 0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5 } };
  147. static const IID D3D_IID_ID3D12GraphicsCommandList = { 0x5b160d0f, 0xac1b, 0x4185, { 0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55 } };
  148. static const IID D3D_IID_ID3D12Fence = { 0x0a753dcf, 0xc4d8, 0x4b91, { 0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76 } };
  149. static const IID D3D_IID_ID3D12RootSignature = { 0xc54a6b66, 0x72df, 0x4ee8, { 0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14 } };
  150. static const IID D3D_IID_ID3D12CommandSignature = { 0xc36a797c, 0xec80, 0x4f0a, { 0x89, 0x85, 0xa7, 0xb2, 0x47, 0x50, 0x82, 0xd1 } };
  151. static const IID D3D_IID_ID3D12PipelineState = { 0x765a30f3, 0xf624, 0x4c6f, { 0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45 } };
  152. static const IID D3D_IID_ID3D12Debug = { 0x344488b7, 0x6846, 0x474b, { 0xb9, 0x89, 0xf0, 0x27, 0x44, 0x82, 0x45, 0xe0 } };
  153. static const IID D3D_IID_ID3D12InfoQueue = { 0x0742a90b, 0xc387, 0x483f, { 0xb9, 0x46, 0x30, 0xa7, 0xe4, 0xe6, 0x14, 0x58 } };
  154. static const IID D3D_IID_ID3D12InfoQueue1 = { 0x2852dd88, 0xb484, 0x4c0c, { 0xb6, 0xb1, 0x67, 0x16, 0x85, 0x00, 0xe6, 0x00 } };
  155. // Enums
  156. typedef enum D3D12BufferType
  157. {
  158. D3D12_BUFFER_TYPE_GPU,
  159. D3D12_BUFFER_TYPE_UNIFORM,
  160. D3D12_BUFFER_TYPE_UPLOAD,
  161. D3D12_BUFFER_TYPE_DOWNLOAD
  162. } D3D12BufferType;
  163. // Conversions
  164. static SDL_GPUTextureFormat SwapchainCompositionToSDLTextureFormat[] = {
  165. SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, // SDR
  166. SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB, // SDR_LINEAR
  167. SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT, // HDR_EXTENDED_LINEAR
  168. SDL_GPU_TEXTUREFORMAT_R10G10B10A2_UNORM, // HDR10_ST2084
  169. };
  170. static DXGI_FORMAT SwapchainCompositionToTextureFormat[] = {
  171. DXGI_FORMAT_B8G8R8A8_UNORM, // SDR
  172. DXGI_FORMAT_B8G8R8A8_UNORM, // SDR_LINEAR (NOTE: The RTV uses the sRGB format)
  173. DXGI_FORMAT_R16G16B16A16_FLOAT, // HDR_EXTENDED_LINEAR
  174. DXGI_FORMAT_R10G10B10A2_UNORM, // HDR10_ST2084
  175. };
  176. static DXGI_COLOR_SPACE_TYPE SwapchainCompositionToColorSpace[] = {
  177. DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, // SDR
  178. DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, // SDR_LINEAR
  179. DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, // HDR_EXTENDED_LINEAR
  180. DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020 // HDR10_ST2084
  181. };
  182. static D3D12_BLEND SDLToD3D12_BlendFactor[] = {
  183. D3D12_BLEND_ZERO, // INVALID
  184. D3D12_BLEND_ZERO, // ZERO
  185. D3D12_BLEND_ONE, // ONE
  186. D3D12_BLEND_SRC_COLOR, // SRC_COLOR
  187. D3D12_BLEND_INV_SRC_COLOR, // ONE_MINUS_SRC_COLOR
  188. D3D12_BLEND_DEST_COLOR, // DST_COLOR
  189. D3D12_BLEND_INV_DEST_COLOR, // ONE_MINUS_DST_COLOR
  190. D3D12_BLEND_SRC_ALPHA, // SRC_ALPHA
  191. D3D12_BLEND_INV_SRC_ALPHA, // ONE_MINUS_SRC_ALPHA
  192. D3D12_BLEND_DEST_ALPHA, // DST_ALPHA
  193. D3D12_BLEND_INV_DEST_ALPHA, // ONE_MINUS_DST_ALPHA
  194. D3D12_BLEND_BLEND_FACTOR, // CONSTANT_COLOR
  195. D3D12_BLEND_INV_BLEND_FACTOR, // ONE_MINUS_CONSTANT_COLOR
  196. D3D12_BLEND_SRC_ALPHA_SAT, // SRC_ALPHA_SATURATE
  197. };
  198. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_BlendFactor, SDL_arraysize(SDLToD3D12_BlendFactor) == SDL_GPU_BLENDFACTOR_MAX_ENUM_VALUE);
  199. static D3D12_BLEND SDLToD3D12_BlendFactorAlpha[] = {
  200. D3D12_BLEND_ZERO, // INVALID
  201. D3D12_BLEND_ZERO, // ZERO
  202. D3D12_BLEND_ONE, // ONE
  203. D3D12_BLEND_SRC_ALPHA, // SRC_COLOR
  204. D3D12_BLEND_INV_SRC_ALPHA, // ONE_MINUS_SRC_COLOR
  205. D3D12_BLEND_DEST_ALPHA, // DST_COLOR
  206. D3D12_BLEND_INV_DEST_ALPHA, // ONE_MINUS_DST_COLOR
  207. D3D12_BLEND_SRC_ALPHA, // SRC_ALPHA
  208. D3D12_BLEND_INV_SRC_ALPHA, // ONE_MINUS_SRC_ALPHA
  209. D3D12_BLEND_DEST_ALPHA, // DST_ALPHA
  210. D3D12_BLEND_INV_DEST_ALPHA, // ONE_MINUS_DST_ALPHA
  211. D3D12_BLEND_BLEND_FACTOR, // CONSTANT_COLOR
  212. D3D12_BLEND_INV_BLEND_FACTOR, // ONE_MINUS_CONSTANT_COLOR
  213. D3D12_BLEND_SRC_ALPHA_SAT, // SRC_ALPHA_SATURATE
  214. };
  215. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_BlendFactorAlpha, SDL_arraysize(SDLToD3D12_BlendFactorAlpha) == SDL_GPU_BLENDFACTOR_MAX_ENUM_VALUE);
  216. static D3D12_BLEND_OP SDLToD3D12_BlendOp[] = {
  217. D3D12_BLEND_OP_ADD, // INVALID
  218. D3D12_BLEND_OP_ADD, // ADD
  219. D3D12_BLEND_OP_SUBTRACT, // SUBTRACT
  220. D3D12_BLEND_OP_REV_SUBTRACT, // REVERSE_SUBTRACT
  221. D3D12_BLEND_OP_MIN, // MIN
  222. D3D12_BLEND_OP_MAX // MAX
  223. };
  224. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_BlendOp, SDL_arraysize(SDLToD3D12_BlendOp) == SDL_GPU_BLENDOP_MAX_ENUM_VALUE);
  225. // These are actually color formats.
  226. // For some genius reason, D3D12 splits format capabilites for depth-stencil views.
  227. static DXGI_FORMAT SDLToD3D12_TextureFormat[] = {
  228. DXGI_FORMAT_UNKNOWN, // INVALID
  229. DXGI_FORMAT_A8_UNORM, // A8_UNORM
  230. DXGI_FORMAT_R8_UNORM, // R8_UNORM
  231. DXGI_FORMAT_R8G8_UNORM, // R8G8_UNORM
  232. DXGI_FORMAT_R8G8B8A8_UNORM, // R8G8B8A8_UNORM
  233. DXGI_FORMAT_R16_UNORM, // R16_UNORM
  234. DXGI_FORMAT_R16G16_UNORM, // R16G16_UNORM
  235. DXGI_FORMAT_R16G16B16A16_UNORM, // R16G16B16A16_UNORM
  236. DXGI_FORMAT_R10G10B10A2_UNORM, // R10G10B10A2_UNORM
  237. DXGI_FORMAT_B5G6R5_UNORM, // B5G6R5_UNORM
  238. DXGI_FORMAT_B5G5R5A1_UNORM, // B5G5R5A1_UNORM
  239. DXGI_FORMAT_B4G4R4A4_UNORM, // B4G4R4A4_UNORM
  240. DXGI_FORMAT_B8G8R8A8_UNORM, // B8G8R8A8_UNORM
  241. DXGI_FORMAT_BC1_UNORM, // BC1_UNORM
  242. DXGI_FORMAT_BC2_UNORM, // BC2_UNORM
  243. DXGI_FORMAT_BC3_UNORM, // BC3_UNORM
  244. DXGI_FORMAT_BC4_UNORM, // BC4_UNORM
  245. DXGI_FORMAT_BC5_UNORM, // BC5_UNORM
  246. DXGI_FORMAT_BC7_UNORM, // BC7_UNORM
  247. DXGI_FORMAT_BC6H_SF16, // BC6H_FLOAT
  248. DXGI_FORMAT_BC6H_UF16, // BC6H_UFLOAT
  249. DXGI_FORMAT_R8_SNORM, // R8_SNORM
  250. DXGI_FORMAT_R8G8_SNORM, // R8G8_SNORM
  251. DXGI_FORMAT_R8G8B8A8_SNORM, // R8G8B8A8_SNORM
  252. DXGI_FORMAT_R16_SNORM, // R16_SNORM
  253. DXGI_FORMAT_R16G16_SNORM, // R16G16_SNORM
  254. DXGI_FORMAT_R16G16B16A16_SNORM, // R16G16B16A16_SNORM
  255. DXGI_FORMAT_R16_FLOAT, // R16_FLOAT
  256. DXGI_FORMAT_R16G16_FLOAT, // R16G16_FLOAT
  257. DXGI_FORMAT_R16G16B16A16_FLOAT, // R16G16B16A16_FLOAT
  258. DXGI_FORMAT_R32_FLOAT, // R32_FLOAT
  259. DXGI_FORMAT_R32G32_FLOAT, // R32G32_FLOAT
  260. DXGI_FORMAT_R32G32B32A32_FLOAT, // R32G32B32A32_FLOAT
  261. DXGI_FORMAT_R11G11B10_FLOAT, // R11G11B10_UFLOAT
  262. DXGI_FORMAT_R8_UINT, // R8_UINT
  263. DXGI_FORMAT_R8G8_UINT, // R8G8_UINT
  264. DXGI_FORMAT_R8G8B8A8_UINT, // R8G8B8A8_UINT
  265. DXGI_FORMAT_R16_UINT, // R16_UINT
  266. DXGI_FORMAT_R16G16_UINT, // R16G16_UINT
  267. DXGI_FORMAT_R16G16B16A16_UINT, // R16G16B16A16_UINT
  268. DXGI_FORMAT_R32_UINT, // R32_UINT
  269. DXGI_FORMAT_R32G32_UINT, // R32G32_UINT
  270. DXGI_FORMAT_R32G32B32A32_UINT, // R32G32B32A32_UINT
  271. DXGI_FORMAT_R8_SINT, // R8_INT
  272. DXGI_FORMAT_R8G8_SINT, // R8G8_INT
  273. DXGI_FORMAT_R8G8B8A8_SINT, // R8G8B8A8_INT
  274. DXGI_FORMAT_R16_SINT, // R16_INT
  275. DXGI_FORMAT_R16G16_SINT, // R16G16_INT
  276. DXGI_FORMAT_R16G16B16A16_SINT, // R16G16B16A16_INT
  277. DXGI_FORMAT_R32_SINT, // R32_INT
  278. DXGI_FORMAT_R32G32_SINT, // R32G32_INT
  279. DXGI_FORMAT_R32G32B32A32_SINT, // R32G32B32A32_INT
  280. DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, // R8G8B8A8_UNORM_SRGB
  281. DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, // B8G8R8A8_UNORM_SRGB
  282. DXGI_FORMAT_BC1_UNORM_SRGB, // BC1_UNORM_SRGB
  283. DXGI_FORMAT_BC2_UNORM_SRGB, // BC2_UNORM_SRGB
  284. DXGI_FORMAT_BC3_UNORM_SRGB, // BC3_UNORM_SRGB
  285. DXGI_FORMAT_BC7_UNORM_SRGB, // BC7_UNORM_SRGB
  286. DXGI_FORMAT_R16_UNORM, // D16_UNORM
  287. DXGI_FORMAT_R24_UNORM_X8_TYPELESS, // D24_UNORM
  288. DXGI_FORMAT_R32_FLOAT, // D32_FLOAT
  289. DXGI_FORMAT_R24_UNORM_X8_TYPELESS, // D24_UNORM_S8_UINT
  290. DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, // D32_FLOAT_S8_UINT
  291. DXGI_FORMAT_UNKNOWN, // ASTC_4x4_UNORM
  292. DXGI_FORMAT_UNKNOWN, // ASTC_5x4_UNORM
  293. DXGI_FORMAT_UNKNOWN, // ASTC_5x5_UNORM
  294. DXGI_FORMAT_UNKNOWN, // ASTC_6x5_UNORM
  295. DXGI_FORMAT_UNKNOWN, // ASTC_6x6_UNORM
  296. DXGI_FORMAT_UNKNOWN, // ASTC_8x5_UNORM
  297. DXGI_FORMAT_UNKNOWN, // ASTC_8x6_UNORM
  298. DXGI_FORMAT_UNKNOWN, // ASTC_8x8_UNORM
  299. DXGI_FORMAT_UNKNOWN, // ASTC_10x5_UNORM
  300. DXGI_FORMAT_UNKNOWN, // ASTC_10x6_UNORM
  301. DXGI_FORMAT_UNKNOWN, // ASTC_10x8_UNORM
  302. DXGI_FORMAT_UNKNOWN, // ASTC_10x10_UNORM
  303. DXGI_FORMAT_UNKNOWN, // ASTC_12x10_UNORM
  304. DXGI_FORMAT_UNKNOWN, // ASTC_12x12_UNORM
  305. DXGI_FORMAT_UNKNOWN, // ASTC_4x4_UNORM_SRGB
  306. DXGI_FORMAT_UNKNOWN, // ASTC_5x4_UNORM_SRGB
  307. DXGI_FORMAT_UNKNOWN, // ASTC_5x5_UNORM_SRGB
  308. DXGI_FORMAT_UNKNOWN, // ASTC_6x5_UNORM_SRGB
  309. DXGI_FORMAT_UNKNOWN, // ASTC_6x6_UNORM_SRGB
  310. DXGI_FORMAT_UNKNOWN, // ASTC_8x5_UNORM_SRGB
  311. DXGI_FORMAT_UNKNOWN, // ASTC_8x6_UNORM_SRGB
  312. DXGI_FORMAT_UNKNOWN, // ASTC_8x8_UNORM_SRGB
  313. DXGI_FORMAT_UNKNOWN, // ASTC_10x5_UNORM_SRGB
  314. DXGI_FORMAT_UNKNOWN, // ASTC_10x6_UNORM_SRGB
  315. DXGI_FORMAT_UNKNOWN, // ASTC_10x8_UNORM_SRGB
  316. DXGI_FORMAT_UNKNOWN, // ASTC_10x10_UNORM_SRGB
  317. DXGI_FORMAT_UNKNOWN, // ASTC_12x10_UNORM_SRGB
  318. DXGI_FORMAT_UNKNOWN, // ASTC_12x12_UNORM_SRGB
  319. DXGI_FORMAT_UNKNOWN, // ASTC_4x4_FLOAT
  320. DXGI_FORMAT_UNKNOWN, // ASTC_5x4_FLOAT
  321. DXGI_FORMAT_UNKNOWN, // ASTC_5x5_FLOAT
  322. DXGI_FORMAT_UNKNOWN, // ASTC_6x5_FLOAT
  323. DXGI_FORMAT_UNKNOWN, // ASTC_6x6_FLOAT
  324. DXGI_FORMAT_UNKNOWN, // ASTC_8x5_FLOAT
  325. DXGI_FORMAT_UNKNOWN, // ASTC_8x6_FLOAT
  326. DXGI_FORMAT_UNKNOWN, // ASTC_8x8_FLOAT
  327. DXGI_FORMAT_UNKNOWN, // ASTC_10x5_FLOAT
  328. DXGI_FORMAT_UNKNOWN, // ASTC_10x6_FLOAT
  329. DXGI_FORMAT_UNKNOWN, // ASTC_10x8_FLOAT
  330. DXGI_FORMAT_UNKNOWN, // ASTC_10x10_FLOAT
  331. DXGI_FORMAT_UNKNOWN, // ASTC_12x10_FLOAT
  332. DXGI_FORMAT_UNKNOWN, // ASTC_12x12_FLOAT
  333. };
  334. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_TextureFormat, SDL_arraysize(SDLToD3D12_TextureFormat) == SDL_GPU_TEXTUREFORMAT_MAX_ENUM_VALUE);
  335. static DXGI_FORMAT SDLToD3D12_DepthFormat[] = {
  336. DXGI_FORMAT_UNKNOWN, // INVALID
  337. DXGI_FORMAT_UNKNOWN, // A8_UNORM
  338. DXGI_FORMAT_UNKNOWN, // R8_UNORM
  339. DXGI_FORMAT_UNKNOWN, // R8G8_UNORM
  340. DXGI_FORMAT_UNKNOWN, // R8G8B8A8_UNORM
  341. DXGI_FORMAT_UNKNOWN, // R16_UNORM
  342. DXGI_FORMAT_UNKNOWN, // R16G16_UNORM
  343. DXGI_FORMAT_UNKNOWN, // R16G16B16A16_UNORM
  344. DXGI_FORMAT_UNKNOWN, // R10G10B10A2_UNORM
  345. DXGI_FORMAT_UNKNOWN, // B5G6R5_UNORM
  346. DXGI_FORMAT_UNKNOWN, // B5G5R5A1_UNORM
  347. DXGI_FORMAT_UNKNOWN, // B4G4R4A4_UNORM
  348. DXGI_FORMAT_UNKNOWN, // B8G8R8A8_UNORM
  349. DXGI_FORMAT_UNKNOWN, // BC1_UNORM
  350. DXGI_FORMAT_UNKNOWN, // BC2_UNORM
  351. DXGI_FORMAT_UNKNOWN, // BC3_UNORM
  352. DXGI_FORMAT_UNKNOWN, // BC4_UNORM
  353. DXGI_FORMAT_UNKNOWN, // BC5_UNORM
  354. DXGI_FORMAT_UNKNOWN, // BC7_UNORM
  355. DXGI_FORMAT_UNKNOWN, // BC6H_FLOAT
  356. DXGI_FORMAT_UNKNOWN, // BC6H_UFLOAT
  357. DXGI_FORMAT_UNKNOWN, // R8_SNORM
  358. DXGI_FORMAT_UNKNOWN, // R8G8_SNORM
  359. DXGI_FORMAT_UNKNOWN, // R8G8B8A8_SNORM
  360. DXGI_FORMAT_UNKNOWN, // R16_SNORM
  361. DXGI_FORMAT_UNKNOWN, // R16G16_SNORM
  362. DXGI_FORMAT_UNKNOWN, // R16G16B16A16_SNORM
  363. DXGI_FORMAT_UNKNOWN, // R16_FLOAT
  364. DXGI_FORMAT_UNKNOWN, // R16G16_FLOAT
  365. DXGI_FORMAT_UNKNOWN, // R16G16B16A16_FLOAT
  366. DXGI_FORMAT_UNKNOWN, // R32_FLOAT
  367. DXGI_FORMAT_UNKNOWN, // R32G32_FLOAT
  368. DXGI_FORMAT_UNKNOWN, // R32G32B32A32_FLOAT
  369. DXGI_FORMAT_UNKNOWN, // R11G11B10_UFLOAT
  370. DXGI_FORMAT_UNKNOWN, // R8_UINT
  371. DXGI_FORMAT_UNKNOWN, // R8G8_UINT
  372. DXGI_FORMAT_UNKNOWN, // R8G8B8A8_UINT
  373. DXGI_FORMAT_UNKNOWN, // R16_UINT
  374. DXGI_FORMAT_UNKNOWN, // R16G16_UINT
  375. DXGI_FORMAT_UNKNOWN, // R16G16B16A16_UINT
  376. DXGI_FORMAT_UNKNOWN, // R32_UINT
  377. DXGI_FORMAT_UNKNOWN, // R32G32_UINT
  378. DXGI_FORMAT_UNKNOWN, // R32G32B32A32_UINT
  379. DXGI_FORMAT_UNKNOWN, // R8_INT
  380. DXGI_FORMAT_UNKNOWN, // R8G8_INT
  381. DXGI_FORMAT_UNKNOWN, // R8G8B8A8_INT
  382. DXGI_FORMAT_UNKNOWN, // R16_INT
  383. DXGI_FORMAT_UNKNOWN, // R16G16_INT
  384. DXGI_FORMAT_UNKNOWN, // R16G16B16A16_INT
  385. DXGI_FORMAT_UNKNOWN, // R32_INT
  386. DXGI_FORMAT_UNKNOWN, // R32G32_INT
  387. DXGI_FORMAT_UNKNOWN, // R32G32B32A32_INT
  388. DXGI_FORMAT_UNKNOWN, // R8G8B8A8_UNORM_SRGB
  389. DXGI_FORMAT_UNKNOWN, // B8G8R8A8_UNORM_SRGB
  390. DXGI_FORMAT_UNKNOWN, // BC1_UNORM_SRGB
  391. DXGI_FORMAT_UNKNOWN, // BC2_UNORM_SRGB
  392. DXGI_FORMAT_UNKNOWN, // BC3_UNORM_SRGB
  393. DXGI_FORMAT_UNKNOWN, // BC7_UNORM_SRGB
  394. DXGI_FORMAT_D16_UNORM, // D16_UNORM
  395. DXGI_FORMAT_D24_UNORM_S8_UINT, // D24_UNORM
  396. DXGI_FORMAT_D32_FLOAT, // D32_FLOAT
  397. DXGI_FORMAT_D24_UNORM_S8_UINT, // D24_UNORM_S8_UINT
  398. DXGI_FORMAT_D32_FLOAT_S8X24_UINT, // D32_FLOAT_S8_UINT
  399. DXGI_FORMAT_UNKNOWN, // ASTC_4x4_UNORM
  400. DXGI_FORMAT_UNKNOWN, // ASTC_5x4_UNORM
  401. DXGI_FORMAT_UNKNOWN, // ASTC_5x5_UNORM
  402. DXGI_FORMAT_UNKNOWN, // ASTC_6x5_UNORM
  403. DXGI_FORMAT_UNKNOWN, // ASTC_6x6_UNORM
  404. DXGI_FORMAT_UNKNOWN, // ASTC_8x5_UNORM
  405. DXGI_FORMAT_UNKNOWN, // ASTC_8x6_UNORM
  406. DXGI_FORMAT_UNKNOWN, // ASTC_8x8_UNORM
  407. DXGI_FORMAT_UNKNOWN, // ASTC_10x5_UNORM
  408. DXGI_FORMAT_UNKNOWN, // ASTC_10x6_UNORM
  409. DXGI_FORMAT_UNKNOWN, // ASTC_10x8_UNORM
  410. DXGI_FORMAT_UNKNOWN, // ASTC_10x10_UNORM
  411. DXGI_FORMAT_UNKNOWN, // ASTC_12x10_UNORM
  412. DXGI_FORMAT_UNKNOWN, // ASTC_12x12_UNORM
  413. DXGI_FORMAT_UNKNOWN, // ASTC_4x4_UNORM_SRGB
  414. DXGI_FORMAT_UNKNOWN, // ASTC_5x4_UNORM_SRGB
  415. DXGI_FORMAT_UNKNOWN, // ASTC_5x5_UNORM_SRGB
  416. DXGI_FORMAT_UNKNOWN, // ASTC_6x5_UNORM_SRGB
  417. DXGI_FORMAT_UNKNOWN, // ASTC_6x6_UNORM_SRGB
  418. DXGI_FORMAT_UNKNOWN, // ASTC_8x5_UNORM_SRGB
  419. DXGI_FORMAT_UNKNOWN, // ASTC_8x6_UNORM_SRGB
  420. DXGI_FORMAT_UNKNOWN, // ASTC_8x8_UNORM_SRGB
  421. DXGI_FORMAT_UNKNOWN, // ASTC_10x5_UNORM_SRGB
  422. DXGI_FORMAT_UNKNOWN, // ASTC_10x6_UNORM_SRGB
  423. DXGI_FORMAT_UNKNOWN, // ASTC_10x8_UNORM_SRGB
  424. DXGI_FORMAT_UNKNOWN, // ASTC_10x10_UNORM_SRGB
  425. DXGI_FORMAT_UNKNOWN, // ASTC_12x10_UNORM_SRGB
  426. DXGI_FORMAT_UNKNOWN, // ASTC_12x12_UNORM_SRGB
  427. DXGI_FORMAT_UNKNOWN, // ASTC_4x4_FLOAT
  428. DXGI_FORMAT_UNKNOWN, // ASTC_5x4_FLOAT
  429. DXGI_FORMAT_UNKNOWN, // ASTC_5x5_FLOAT
  430. DXGI_FORMAT_UNKNOWN, // ASTC_6x5_FLOAT
  431. DXGI_FORMAT_UNKNOWN, // ASTC_6x6_FLOAT
  432. DXGI_FORMAT_UNKNOWN, // ASTC_8x5_FLOAT
  433. DXGI_FORMAT_UNKNOWN, // ASTC_8x6_FLOAT
  434. DXGI_FORMAT_UNKNOWN, // ASTC_8x8_FLOAT
  435. DXGI_FORMAT_UNKNOWN, // ASTC_10x5_FLOAT
  436. DXGI_FORMAT_UNKNOWN, // ASTC_10x6_FLOAT
  437. DXGI_FORMAT_UNKNOWN, // ASTC_10x8_FLOAT
  438. DXGI_FORMAT_UNKNOWN, // ASTC_10x10_FLOAT
  439. DXGI_FORMAT_UNKNOWN, // ASTC_12x10_FLOAT
  440. DXGI_FORMAT_UNKNOWN, // ASTC_12x12_FLOAT
  441. };
  442. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_DepthFormat, SDL_arraysize(SDLToD3D12_DepthFormat) == SDL_GPU_TEXTUREFORMAT_MAX_ENUM_VALUE);
  443. static DXGI_FORMAT SDLToD3D12_TypelessFormat[] = {
  444. DXGI_FORMAT_UNKNOWN, // INVALID
  445. DXGI_FORMAT_UNKNOWN, // A8_UNORM
  446. DXGI_FORMAT_UNKNOWN, // R8_UNORM
  447. DXGI_FORMAT_UNKNOWN, // R8G8_UNORM
  448. DXGI_FORMAT_UNKNOWN, // R8G8B8A8_UNORM
  449. DXGI_FORMAT_UNKNOWN, // R16_UNORM
  450. DXGI_FORMAT_UNKNOWN, // R16G16_UNORM
  451. DXGI_FORMAT_UNKNOWN, // R16G16B16A16_UNORM
  452. DXGI_FORMAT_UNKNOWN, // R10G10B10A2_UNORM
  453. DXGI_FORMAT_UNKNOWN, // B5G6R5_UNORM
  454. DXGI_FORMAT_UNKNOWN, // B5G5R5A1_UNORM
  455. DXGI_FORMAT_UNKNOWN, // B4G4R4A4_UNORM
  456. DXGI_FORMAT_UNKNOWN, // B8G8R8A8_UNORM
  457. DXGI_FORMAT_UNKNOWN, // BC1_UNORM
  458. DXGI_FORMAT_UNKNOWN, // BC2_UNORM
  459. DXGI_FORMAT_UNKNOWN, // BC3_UNORM
  460. DXGI_FORMAT_UNKNOWN, // BC4_UNORM
  461. DXGI_FORMAT_UNKNOWN, // BC5_UNORM
  462. DXGI_FORMAT_UNKNOWN, // BC7_UNORM
  463. DXGI_FORMAT_UNKNOWN, // BC6H_FLOAT
  464. DXGI_FORMAT_UNKNOWN, // BC6H_UFLOAT
  465. DXGI_FORMAT_UNKNOWN, // R8_SNORM
  466. DXGI_FORMAT_UNKNOWN, // R8G8_SNORM
  467. DXGI_FORMAT_UNKNOWN, // R8G8B8A8_SNORM
  468. DXGI_FORMAT_UNKNOWN, // R16_SNORM
  469. DXGI_FORMAT_UNKNOWN, // R16G16_SNORM
  470. DXGI_FORMAT_UNKNOWN, // R16G16B16A16_SNORM
  471. DXGI_FORMAT_UNKNOWN, // R16_FLOAT
  472. DXGI_FORMAT_UNKNOWN, // R16G16_FLOAT
  473. DXGI_FORMAT_UNKNOWN, // R16G16B16A16_FLOAT
  474. DXGI_FORMAT_UNKNOWN, // R32_FLOAT
  475. DXGI_FORMAT_UNKNOWN, // R32G32_FLOAT
  476. DXGI_FORMAT_UNKNOWN, // R32G32B32A32_FLOAT
  477. DXGI_FORMAT_UNKNOWN, // R11G11B10_UFLOAT
  478. DXGI_FORMAT_UNKNOWN, // R8_UINT
  479. DXGI_FORMAT_UNKNOWN, // R8G8_UINT
  480. DXGI_FORMAT_UNKNOWN, // R8G8B8A8_UINT
  481. DXGI_FORMAT_UNKNOWN, // R16_UINT
  482. DXGI_FORMAT_UNKNOWN, // R16G16_UINT
  483. DXGI_FORMAT_UNKNOWN, // R16G16B16A16_UINT
  484. DXGI_FORMAT_UNKNOWN, // R32_UINT
  485. DXGI_FORMAT_UNKNOWN, // R32G32_UINT
  486. DXGI_FORMAT_UNKNOWN, // R32G32B32A32_UINT
  487. DXGI_FORMAT_UNKNOWN, // R8_INT
  488. DXGI_FORMAT_UNKNOWN, // R8G8_INT
  489. DXGI_FORMAT_UNKNOWN, // R8G8B8A8_INT
  490. DXGI_FORMAT_UNKNOWN, // R16_INT
  491. DXGI_FORMAT_UNKNOWN, // R16G16_INT
  492. DXGI_FORMAT_UNKNOWN, // R16G16B16A16_INT
  493. DXGI_FORMAT_UNKNOWN, // R32_INT
  494. DXGI_FORMAT_UNKNOWN, // R32G32_INT
  495. DXGI_FORMAT_UNKNOWN, // R32G32B32A32_INT
  496. DXGI_FORMAT_UNKNOWN, // R8G8B8A8_UNORM_SRGB
  497. DXGI_FORMAT_UNKNOWN, // B8G8R8A8_UNORM_SRGB
  498. DXGI_FORMAT_UNKNOWN, // BC1_UNORM_SRGB
  499. DXGI_FORMAT_UNKNOWN, // BC2_UNORM_SRGB
  500. DXGI_FORMAT_UNKNOWN, // BC3_UNORM_SRGB
  501. DXGI_FORMAT_UNKNOWN, // BC7_UNORM_SRGB
  502. DXGI_FORMAT_R16_TYPELESS, // D16_UNORM
  503. DXGI_FORMAT_R24G8_TYPELESS, // D24_UNORM
  504. DXGI_FORMAT_R32_TYPELESS, // D32_FLOAT
  505. DXGI_FORMAT_R24G8_TYPELESS, // D24_UNORM_S8_UINT
  506. DXGI_FORMAT_R32G8X24_TYPELESS, // D32_FLOAT_S8_UINT
  507. DXGI_FORMAT_UNKNOWN, // ASTC_4x4_UNORM
  508. DXGI_FORMAT_UNKNOWN, // ASTC_5x4_UNORM
  509. DXGI_FORMAT_UNKNOWN, // ASTC_5x5_UNORM
  510. DXGI_FORMAT_UNKNOWN, // ASTC_6x5_UNORM
  511. DXGI_FORMAT_UNKNOWN, // ASTC_6x6_UNORM
  512. DXGI_FORMAT_UNKNOWN, // ASTC_8x5_UNORM
  513. DXGI_FORMAT_UNKNOWN, // ASTC_8x6_UNORM
  514. DXGI_FORMAT_UNKNOWN, // ASTC_8x8_UNORM
  515. DXGI_FORMAT_UNKNOWN, // ASTC_10x5_UNORM
  516. DXGI_FORMAT_UNKNOWN, // ASTC_10x6_UNORM
  517. DXGI_FORMAT_UNKNOWN, // ASTC_10x8_UNORM
  518. DXGI_FORMAT_UNKNOWN, // ASTC_10x10_UNORM
  519. DXGI_FORMAT_UNKNOWN, // ASTC_12x10_UNORM
  520. DXGI_FORMAT_UNKNOWN, // ASTC_12x12_UNORM
  521. DXGI_FORMAT_UNKNOWN, // ASTC_4x4_UNORM_SRGB
  522. DXGI_FORMAT_UNKNOWN, // ASTC_5x4_UNORM_SRGB
  523. DXGI_FORMAT_UNKNOWN, // ASTC_5x5_UNORM_SRGB
  524. DXGI_FORMAT_UNKNOWN, // ASTC_6x5_UNORM_SRGB
  525. DXGI_FORMAT_UNKNOWN, // ASTC_6x6_UNORM_SRGB
  526. DXGI_FORMAT_UNKNOWN, // ASTC_8x5_UNORM_SRGB
  527. DXGI_FORMAT_UNKNOWN, // ASTC_8x6_UNORM_SRGB
  528. DXGI_FORMAT_UNKNOWN, // ASTC_8x8_UNORM_SRGB
  529. DXGI_FORMAT_UNKNOWN, // ASTC_10x5_UNORM_SRGB
  530. DXGI_FORMAT_UNKNOWN, // ASTC_10x6_UNORM_SRGB
  531. DXGI_FORMAT_UNKNOWN, // ASTC_10x8_UNORM_SRGB
  532. DXGI_FORMAT_UNKNOWN, // ASTC_10x10_UNORM_SRGB
  533. DXGI_FORMAT_UNKNOWN, // ASTC_12x10_UNORM_SRGB
  534. DXGI_FORMAT_UNKNOWN, // ASTC_12x12_UNORM_SRGB
  535. DXGI_FORMAT_UNKNOWN, // ASTC_4x4_FLOAT
  536. DXGI_FORMAT_UNKNOWN, // ASTC_5x4_FLOAT
  537. DXGI_FORMAT_UNKNOWN, // ASTC_5x5_FLOAT
  538. DXGI_FORMAT_UNKNOWN, // ASTC_6x5_FLOAT
  539. DXGI_FORMAT_UNKNOWN, // ASTC_6x6_FLOAT
  540. DXGI_FORMAT_UNKNOWN, // ASTC_8x5_FLOAT
  541. DXGI_FORMAT_UNKNOWN, // ASTC_8x6_FLOAT
  542. DXGI_FORMAT_UNKNOWN, // ASTC_8x8_FLOAT
  543. DXGI_FORMAT_UNKNOWN, // ASTC_10x5_FLOAT
  544. DXGI_FORMAT_UNKNOWN, // ASTC_10x6_FLOAT
  545. DXGI_FORMAT_UNKNOWN, // ASTC_10x8_FLOAT
  546. DXGI_FORMAT_UNKNOWN, // ASTC_10x10_FLOAT
  547. DXGI_FORMAT_UNKNOWN, // ASTC_12x10_FLOAT
  548. DXGI_FORMAT_UNKNOWN, // ASTC_12x12_FLOAT
  549. };
  550. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_TypelessFormat, SDL_arraysize(SDLToD3D12_TypelessFormat) == SDL_GPU_TEXTUREFORMAT_MAX_ENUM_VALUE);
  551. static D3D12_COMPARISON_FUNC SDLToD3D12_CompareOp[] = {
  552. D3D12_COMPARISON_FUNC_NEVER, // INVALID
  553. D3D12_COMPARISON_FUNC_NEVER, // NEVER
  554. D3D12_COMPARISON_FUNC_LESS, // LESS
  555. D3D12_COMPARISON_FUNC_EQUAL, // EQUAL
  556. D3D12_COMPARISON_FUNC_LESS_EQUAL, // LESS_OR_EQUAL
  557. D3D12_COMPARISON_FUNC_GREATER, // GREATER
  558. D3D12_COMPARISON_FUNC_NOT_EQUAL, // NOT_EQUAL
  559. D3D12_COMPARISON_FUNC_GREATER_EQUAL, // GREATER_OR_EQUAL
  560. D3D12_COMPARISON_FUNC_ALWAYS // ALWAYS
  561. };
  562. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_CompareOp, SDL_arraysize(SDLToD3D12_CompareOp) == SDL_GPU_COMPAREOP_MAX_ENUM_VALUE);
  563. static D3D12_STENCIL_OP SDLToD3D12_StencilOp[] = {
  564. D3D12_STENCIL_OP_KEEP, // INVALID
  565. D3D12_STENCIL_OP_KEEP, // KEEP
  566. D3D12_STENCIL_OP_ZERO, // ZERO
  567. D3D12_STENCIL_OP_REPLACE, // REPLACE
  568. D3D12_STENCIL_OP_INCR_SAT, // INCREMENT_AND_CLAMP
  569. D3D12_STENCIL_OP_DECR_SAT, // DECREMENT_AND_CLAMP
  570. D3D12_STENCIL_OP_INVERT, // INVERT
  571. D3D12_STENCIL_OP_INCR, // INCREMENT_AND_WRAP
  572. D3D12_STENCIL_OP_DECR // DECREMENT_AND_WRAP
  573. };
  574. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_StencilOp, SDL_arraysize(SDLToD3D12_StencilOp) == SDL_GPU_STENCILOP_MAX_ENUM_VALUE);
  575. static D3D12_CULL_MODE SDLToD3D12_CullMode[] = {
  576. D3D12_CULL_MODE_NONE, // NONE
  577. D3D12_CULL_MODE_FRONT, // FRONT
  578. D3D12_CULL_MODE_BACK // BACK
  579. };
  580. static D3D12_FILL_MODE SDLToD3D12_FillMode[] = {
  581. D3D12_FILL_MODE_SOLID, // FILL
  582. D3D12_FILL_MODE_WIREFRAME // LINE
  583. };
  584. static D3D12_INPUT_CLASSIFICATION SDLToD3D12_InputRate[] = {
  585. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, // VERTEX
  586. D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA // INSTANCE
  587. };
  588. static DXGI_FORMAT SDLToD3D12_VertexFormat[] = {
  589. DXGI_FORMAT_UNKNOWN, // UNKNOWN
  590. DXGI_FORMAT_R32_SINT, // INT
  591. DXGI_FORMAT_R32G32_SINT, // INT2
  592. DXGI_FORMAT_R32G32B32_SINT, // INT3
  593. DXGI_FORMAT_R32G32B32A32_SINT, // INT4
  594. DXGI_FORMAT_R32_UINT, // UINT
  595. DXGI_FORMAT_R32G32_UINT, // UINT2
  596. DXGI_FORMAT_R32G32B32_UINT, // UINT3
  597. DXGI_FORMAT_R32G32B32A32_UINT, // UINT4
  598. DXGI_FORMAT_R32_FLOAT, // FLOAT
  599. DXGI_FORMAT_R32G32_FLOAT, // FLOAT2
  600. DXGI_FORMAT_R32G32B32_FLOAT, // FLOAT3
  601. DXGI_FORMAT_R32G32B32A32_FLOAT, // FLOAT4
  602. DXGI_FORMAT_R8G8_SINT, // BYTE2
  603. DXGI_FORMAT_R8G8B8A8_SINT, // BYTE4
  604. DXGI_FORMAT_R8G8_UINT, // UBYTE2
  605. DXGI_FORMAT_R8G8B8A8_UINT, // UBYTE4
  606. DXGI_FORMAT_R8G8_SNORM, // BYTE2_NORM
  607. DXGI_FORMAT_R8G8B8A8_SNORM, // BYTE4_NORM
  608. DXGI_FORMAT_R8G8_UNORM, // UBYTE2_NORM
  609. DXGI_FORMAT_R8G8B8A8_UNORM, // UBYTE4_NORM
  610. DXGI_FORMAT_R16G16_SINT, // SHORT2
  611. DXGI_FORMAT_R16G16B16A16_SINT, // SHORT4
  612. DXGI_FORMAT_R16G16_UINT, // USHORT2
  613. DXGI_FORMAT_R16G16B16A16_UINT, // USHORT4
  614. DXGI_FORMAT_R16G16_SNORM, // SHORT2_NORM
  615. DXGI_FORMAT_R16G16B16A16_SNORM, // SHORT4_NORM
  616. DXGI_FORMAT_R16G16_UNORM, // USHORT2_NORM
  617. DXGI_FORMAT_R16G16B16A16_UNORM, // USHORT4_NORM
  618. DXGI_FORMAT_R16G16_FLOAT, // HALF2
  619. DXGI_FORMAT_R16G16B16A16_FLOAT // HALF4
  620. };
  621. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_VertexFormat, SDL_arraysize(SDLToD3D12_VertexFormat) == SDL_GPU_VERTEXELEMENTFORMAT_MAX_ENUM_VALUE);
  622. static Uint32 SDLToD3D12_SampleCount[] = {
  623. 1, // SDL_GPU_SAMPLECOUNT_1
  624. 2, // SDL_GPU_SAMPLECOUNT_2
  625. 4, // SDL_GPU_SAMPLECOUNT_4
  626. 8, // SDL_GPU_SAMPLECOUNT_8
  627. };
  628. static D3D12_PRIMITIVE_TOPOLOGY SDLToD3D12_PrimitiveType[] = {
  629. D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, // TRIANGLELIST
  630. D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, // TRIANGLESTRIP
  631. D3D_PRIMITIVE_TOPOLOGY_LINELIST, // LINELIST
  632. D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, // LINESTRIP
  633. D3D_PRIMITIVE_TOPOLOGY_POINTLIST // POINTLIST
  634. };
  635. static D3D12_PRIMITIVE_TOPOLOGY_TYPE SDLToD3D12_PrimitiveTopologyType[] = {
  636. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, // TRIANGLELIST
  637. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, // TRIANGLESTRIP
  638. D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, // LINELIST
  639. D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, // LINESTRIP
  640. D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT // POINTLIST
  641. };
  642. static D3D12_TEXTURE_ADDRESS_MODE SDLToD3D12_SamplerAddressMode[] = {
  643. D3D12_TEXTURE_ADDRESS_MODE_WRAP, // REPEAT
  644. D3D12_TEXTURE_ADDRESS_MODE_MIRROR, // MIRRORED_REPEAT
  645. D3D12_TEXTURE_ADDRESS_MODE_CLAMP // CLAMP_TO_EDGE
  646. };
  647. static D3D12_FILTER SDLToD3D12_Filter(
  648. SDL_GPUFilter minFilter,
  649. SDL_GPUFilter magFilter,
  650. SDL_GPUSamplerMipmapMode mipmapMode,
  651. bool comparisonEnabled,
  652. bool anisotropyEnabled)
  653. {
  654. D3D12_FILTER result = D3D12_ENCODE_BASIC_FILTER(
  655. (minFilter == SDL_GPU_FILTER_LINEAR) ? 1 : 0,
  656. (magFilter == SDL_GPU_FILTER_LINEAR) ? 1 : 0,
  657. (mipmapMode == SDL_GPU_SAMPLERMIPMAPMODE_LINEAR) ? 1 : 0,
  658. comparisonEnabled ? 1 : 0);
  659. if (anisotropyEnabled) {
  660. result = (D3D12_FILTER)(result | D3D12_ANISOTROPIC_FILTERING_BIT);
  661. }
  662. return result;
  663. }
  664. // Structures
  665. typedef struct D3D12Renderer D3D12Renderer;
  666. typedef struct D3D12CommandBufferPool D3D12CommandBufferPool;
  667. typedef struct D3D12CommandBuffer D3D12CommandBuffer;
  668. typedef struct D3D12Texture D3D12Texture;
  669. typedef struct D3D12Shader D3D12Shader;
  670. typedef struct D3D12GraphicsPipeline D3D12GraphicsPipeline;
  671. typedef struct D3D12ComputePipeline D3D12ComputePipeline;
  672. typedef struct D3D12Buffer D3D12Buffer;
  673. typedef struct D3D12BufferContainer D3D12BufferContainer;
  674. typedef struct D3D12UniformBuffer D3D12UniformBuffer;
  675. typedef struct D3D12DescriptorHeap D3D12DescriptorHeap;
  676. typedef struct D3D12StagingDescriptor D3D12StagingDescriptor;
  677. typedef struct D3D12TextureDownload D3D12TextureDownload;
  678. typedef struct D3D12Fence
  679. {
  680. ID3D12Fence *handle;
  681. HANDLE event; // used for blocking
  682. SDL_AtomicInt referenceCount;
  683. } D3D12Fence;
  684. struct D3D12DescriptorHeap
  685. {
  686. ID3D12DescriptorHeap *handle;
  687. D3D12_DESCRIPTOR_HEAP_TYPE heapType;
  688. D3D12_CPU_DESCRIPTOR_HANDLE descriptorHeapCPUStart;
  689. D3D12_GPU_DESCRIPTOR_HANDLE descriptorHeapGPUStart; // only used by GPU heaps
  690. Uint32 maxDescriptors;
  691. Uint32 descriptorSize;
  692. bool staging;
  693. Uint32 currentDescriptorIndex; // only used by GPU heaps
  694. };
  695. typedef struct D3D12GPUDescriptorHeapPool
  696. {
  697. Uint32 capacity;
  698. Uint32 count;
  699. D3D12DescriptorHeap **heaps;
  700. SDL_Mutex *lock;
  701. } D3D12GPUDescriptorHeapPool;
  702. // The only thing we care about with staging descriptors is being able to grab a free descriptor.
  703. typedef struct D3D12StagingDescriptorPool
  704. {
  705. Uint32 heapCount;
  706. D3D12DescriptorHeap **heaps;
  707. // Descriptor handles are owned by resources, so these can be thought of as descriptions of a free index within a heap.
  708. Uint32 freeDescriptorCapacity;
  709. Uint32 freeDescriptorCount;
  710. D3D12StagingDescriptor *freeDescriptors;
  711. SDL_Mutex *lock;
  712. } D3D12StagingDescriptorPool;
  713. struct D3D12StagingDescriptor
  714. {
  715. D3D12StagingDescriptorPool *pool;
  716. D3D12DescriptorHeap *heap;
  717. D3D12_CPU_DESCRIPTOR_HANDLE cpuHandle;
  718. Uint32 cpuHandleIndex;
  719. };
  720. typedef struct D3D12TextureContainer
  721. {
  722. TextureCommonHeader header;
  723. D3D12Texture *activeTexture;
  724. D3D12Texture **textures;
  725. Uint32 textureCapacity;
  726. Uint32 textureCount;
  727. // Swapchain images cannot be cycled
  728. bool canBeCycled;
  729. char *debugName;
  730. } D3D12TextureContainer;
  731. // Null views represent by heap = NULL
  732. typedef struct D3D12TextureSubresource
  733. {
  734. D3D12Texture *parent;
  735. Uint32 layer;
  736. Uint32 level;
  737. Uint32 depth;
  738. Uint32 index;
  739. // One per depth slice
  740. D3D12StagingDescriptor *rtvHandles; // NULL if not a color target
  741. D3D12StagingDescriptor uavHandle; // NULL if not a compute storage write texture
  742. D3D12StagingDescriptor dsvHandle; // NULL if not a depth stencil target
  743. } D3D12TextureSubresource;
  744. struct D3D12Texture
  745. {
  746. D3D12TextureContainer *container;
  747. Uint32 containerIndex;
  748. D3D12TextureSubresource *subresources;
  749. Uint32 subresourceCount; /* layerCount * num_levels */
  750. ID3D12Resource *resource;
  751. D3D12StagingDescriptor srvHandle;
  752. SDL_AtomicInt referenceCount;
  753. };
  754. typedef struct D3D12Sampler
  755. {
  756. SDL_GPUSamplerCreateInfo createInfo;
  757. D3D12StagingDescriptor handle;
  758. SDL_AtomicInt referenceCount;
  759. } D3D12Sampler;
  760. typedef struct D3D12WindowData
  761. {
  762. SDL_Window *window;
  763. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  764. D3D12XBOX_FRAME_PIPELINE_TOKEN frameToken;
  765. #else
  766. IDXGISwapChain3 *swapchain;
  767. #endif
  768. SDL_GPUPresentMode present_mode;
  769. SDL_GPUSwapchainComposition swapchainComposition;
  770. DXGI_COLOR_SPACE_TYPE swapchainColorSpace;
  771. Uint32 frameCounter;
  772. D3D12TextureContainer textureContainers[MAX_FRAMES_IN_FLIGHT];
  773. Uint32 swapchainTextureCount;
  774. SDL_GPUFence *inFlightFences[MAX_FRAMES_IN_FLIGHT];
  775. Uint32 width;
  776. Uint32 height;
  777. bool needsSwapchainRecreate;
  778. } D3D12WindowData;
  779. typedef struct D3D12PresentData
  780. {
  781. D3D12WindowData *windowData;
  782. Uint32 swapchainImageIndex;
  783. } D3D12PresentData;
  784. #ifdef USE_PIX_RUNTIME
  785. typedef struct WinPixEventRuntimeFns {
  786. pfnBeginEventOnCommandList pBeginEventOnCommandList;
  787. pfnEndEventOnCommandList pEndEventOnCommandList;
  788. pfnSetMarkerOnCommandList pSetMarkerOnCommandList;
  789. } WinPixEventRuntimeFns;
  790. #endif
  791. struct D3D12Renderer
  792. {
  793. // Reference to the parent device
  794. SDL_GPUDevice *sdlGPUDevice;
  795. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  796. IDXGIDebug *dxgiDebug;
  797. IDXGIFactory4 *factory;
  798. #ifdef HAVE_IDXGIINFOQUEUE
  799. IDXGIInfoQueue *dxgiInfoQueue;
  800. #endif
  801. IDXGIAdapter1 *adapter;
  802. SDL_SharedObject *dxgi_dll;
  803. SDL_SharedObject *dxgidebug_dll;
  804. #endif
  805. #ifdef USE_PIX_RUNTIME
  806. SDL_SharedObject *winpixeventruntime_dll;
  807. WinPixEventRuntimeFns winpixeventruntimeFns;
  808. #endif
  809. ID3D12Debug *d3d12Debug;
  810. BOOL supportsTearing;
  811. SDL_SharedObject *d3d12_dll;
  812. ID3D12Device *device;
  813. PFN_D3D12_SERIALIZE_ROOT_SIGNATURE pD3D12SerializeRootSignature;
  814. char *semantic;
  815. SDL_iconv_t iconv;
  816. ID3D12CommandQueue *commandQueue;
  817. bool debug_mode;
  818. bool GPUUploadHeapSupported;
  819. // FIXME: these might not be necessary since we're not using custom heaps
  820. bool UMA;
  821. bool UMACacheCoherent;
  822. SDL_PropertiesID props;
  823. Uint32 allowedFramesInFlight;
  824. // Indirect command signatures
  825. ID3D12CommandSignature *indirectDrawCommandSignature;
  826. ID3D12CommandSignature *indirectIndexedDrawCommandSignature;
  827. ID3D12CommandSignature *indirectDispatchCommandSignature;
  828. // Blit
  829. SDL_GPUShader *blitVertexShader;
  830. SDL_GPUShader *blitFrom2DShader;
  831. SDL_GPUShader *blitFrom2DArrayShader;
  832. SDL_GPUShader *blitFrom3DShader;
  833. SDL_GPUShader *blitFromCubeShader;
  834. SDL_GPUShader *blitFromCubeArrayShader;
  835. SDL_GPUSampler *blitNearestSampler;
  836. SDL_GPUSampler *blitLinearSampler;
  837. BlitPipelineCacheEntry *blitPipelines;
  838. Uint32 blitPipelineCount;
  839. Uint32 blitPipelineCapacity;
  840. // Resources
  841. D3D12CommandBuffer **availableCommandBuffers;
  842. Uint32 availableCommandBufferCount;
  843. Uint32 availableCommandBufferCapacity;
  844. D3D12CommandBuffer **submittedCommandBuffers;
  845. Uint32 submittedCommandBufferCount;
  846. Uint32 submittedCommandBufferCapacity;
  847. D3D12UniformBuffer **uniformBufferPool;
  848. Uint32 uniformBufferPoolCount;
  849. Uint32 uniformBufferPoolCapacity;
  850. D3D12WindowData **claimedWindows;
  851. Uint32 claimedWindowCount;
  852. Uint32 claimedWindowCapacity;
  853. D3D12Fence **availableFences;
  854. Uint32 availableFenceCount;
  855. Uint32 availableFenceCapacity;
  856. D3D12StagingDescriptorPool *stagingDescriptorPools[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES];
  857. D3D12GPUDescriptorHeapPool gpuDescriptorHeapPools[2];
  858. // Deferred resource releasing
  859. D3D12Buffer **buffersToDestroy;
  860. Uint32 buffersToDestroyCount;
  861. Uint32 buffersToDestroyCapacity;
  862. D3D12Texture **texturesToDestroy;
  863. Uint32 texturesToDestroyCount;
  864. Uint32 texturesToDestroyCapacity;
  865. D3D12Sampler **samplersToDestroy;
  866. Uint32 samplersToDestroyCount;
  867. Uint32 samplersToDestroyCapacity;
  868. D3D12GraphicsPipeline **graphicsPipelinesToDestroy;
  869. Uint32 graphicsPipelinesToDestroyCount;
  870. Uint32 graphicsPipelinesToDestroyCapacity;
  871. D3D12ComputePipeline **computePipelinesToDestroy;
  872. Uint32 computePipelinesToDestroyCount;
  873. Uint32 computePipelinesToDestroyCapacity;
  874. // Locks
  875. SDL_Mutex *acquireCommandBufferLock;
  876. SDL_Mutex *acquireUniformBufferLock;
  877. SDL_Mutex *submitLock;
  878. SDL_Mutex *windowLock;
  879. SDL_Mutex *fenceLock;
  880. SDL_Mutex *disposeLock;
  881. };
  882. struct D3D12CommandBuffer
  883. {
  884. // reserved for SDL_gpu
  885. CommandBufferCommonHeader common;
  886. // non owning parent reference
  887. D3D12Renderer *renderer;
  888. ID3D12CommandAllocator *commandAllocator;
  889. ID3D12GraphicsCommandList *graphicsCommandList;
  890. D3D12Fence *inFlightFence;
  891. bool autoReleaseFence;
  892. // Presentation data
  893. D3D12PresentData *presentDatas;
  894. Uint32 presentDataCount;
  895. Uint32 presentDataCapacity;
  896. D3D12TextureSubresource *colorTargetSubresources[MAX_COLOR_TARGET_BINDINGS];
  897. D3D12TextureSubresource *colorResolveSubresources[MAX_COLOR_TARGET_BINDINGS];
  898. D3D12TextureSubresource *depthStencilTextureSubresource;
  899. D3D12GraphicsPipeline *currentGraphicsPipeline;
  900. D3D12ComputePipeline *currentComputePipeline;
  901. // Set at acquire time
  902. D3D12DescriptorHeap *gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER + 1];
  903. D3D12DescriptorHeap **usedDescriptorHeaps;
  904. Uint32 usedDescriptorHeapCount;
  905. Uint32 usedDescriptorHeapCapacity;
  906. D3D12UniformBuffer **usedUniformBuffers;
  907. Uint32 usedUniformBufferCount;
  908. Uint32 usedUniformBufferCapacity;
  909. // Resource slot state
  910. bool needVertexBufferBind;
  911. bool needVertexSamplerBind;
  912. bool needVertexStorageTextureBind;
  913. bool needVertexStorageBufferBind;
  914. bool needVertexUniformBufferBind[MAX_UNIFORM_BUFFERS_PER_STAGE];
  915. bool needFragmentSamplerBind;
  916. bool needFragmentStorageTextureBind;
  917. bool needFragmentStorageBufferBind;
  918. bool needFragmentUniformBufferBind[MAX_UNIFORM_BUFFERS_PER_STAGE];
  919. bool needComputeSamplerBind;
  920. bool needComputeReadOnlyStorageTextureBind;
  921. bool needComputeReadOnlyStorageBufferBind;
  922. bool needComputeUniformBufferBind[MAX_UNIFORM_BUFFERS_PER_STAGE];
  923. D3D12Buffer *vertexBuffers[MAX_VERTEX_BUFFERS];
  924. Uint32 vertexBufferOffsets[MAX_VERTEX_BUFFERS];
  925. Uint32 vertexBufferCount;
  926. D3D12_CPU_DESCRIPTOR_HANDLE vertexSamplerTextureDescriptorHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  927. D3D12_CPU_DESCRIPTOR_HANDLE vertexSamplerDescriptorHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  928. D3D12_CPU_DESCRIPTOR_HANDLE vertexStorageTextureDescriptorHandles[MAX_STORAGE_TEXTURES_PER_STAGE];
  929. D3D12_CPU_DESCRIPTOR_HANDLE vertexStorageBufferDescriptorHandles[MAX_STORAGE_BUFFERS_PER_STAGE];
  930. D3D12UniformBuffer *vertexUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  931. D3D12_CPU_DESCRIPTOR_HANDLE fragmentSamplerTextureDescriptorHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  932. D3D12_CPU_DESCRIPTOR_HANDLE fragmentSamplerDescriptorHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  933. D3D12_CPU_DESCRIPTOR_HANDLE fragmentStorageTextureDescriptorHandles[MAX_STORAGE_TEXTURES_PER_STAGE];
  934. D3D12_CPU_DESCRIPTOR_HANDLE fragmentStorageBufferDescriptorHandles[MAX_STORAGE_BUFFERS_PER_STAGE];
  935. D3D12UniformBuffer *fragmentUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  936. D3D12_CPU_DESCRIPTOR_HANDLE computeSamplerTextureDescriptorHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  937. D3D12_CPU_DESCRIPTOR_HANDLE computeSamplerDescriptorHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  938. D3D12_CPU_DESCRIPTOR_HANDLE computeReadOnlyStorageTextureDescriptorHandles[MAX_STORAGE_TEXTURES_PER_STAGE];
  939. D3D12_CPU_DESCRIPTOR_HANDLE computeReadOnlyStorageBufferDescriptorHandles[MAX_STORAGE_BUFFERS_PER_STAGE];
  940. // Track these separately because barriers can happen mid compute pass
  941. D3D12Texture *computeReadOnlyStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  942. D3D12Buffer *computeReadOnlyStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  943. D3D12_CPU_DESCRIPTOR_HANDLE computeReadWriteStorageTextureDescriptorHandles[MAX_COMPUTE_WRITE_TEXTURES];
  944. D3D12_CPU_DESCRIPTOR_HANDLE computeReadWriteStorageBufferDescriptorHandles[MAX_COMPUTE_WRITE_BUFFERS];
  945. // Track these separately because they are bound when the compute pass begins
  946. D3D12TextureSubresource *computeReadWriteStorageTextureSubresources[MAX_COMPUTE_WRITE_TEXTURES];
  947. Uint32 computeReadWriteStorageTextureSubresourceCount;
  948. D3D12Buffer *computeReadWriteStorageBuffers[MAX_COMPUTE_WRITE_BUFFERS];
  949. Uint32 computeReadWriteStorageBufferCount;
  950. D3D12UniformBuffer *computeUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  951. // Resource tracking
  952. D3D12Texture **usedTextures;
  953. Uint32 usedTextureCount;
  954. Uint32 usedTextureCapacity;
  955. D3D12Buffer **usedBuffers;
  956. Uint32 usedBufferCount;
  957. Uint32 usedBufferCapacity;
  958. D3D12Sampler **usedSamplers;
  959. Uint32 usedSamplerCount;
  960. Uint32 usedSamplerCapacity;
  961. D3D12GraphicsPipeline **usedGraphicsPipelines;
  962. Uint32 usedGraphicsPipelineCount;
  963. Uint32 usedGraphicsPipelineCapacity;
  964. D3D12ComputePipeline **usedComputePipelines;
  965. Uint32 usedComputePipelineCount;
  966. Uint32 usedComputePipelineCapacity;
  967. // Used for texture pitch hack
  968. D3D12TextureDownload **textureDownloads;
  969. Uint32 textureDownloadCount;
  970. Uint32 textureDownloadCapacity;
  971. };
  972. struct D3D12Shader
  973. {
  974. // todo cleanup
  975. void *bytecode;
  976. size_t bytecodeSize;
  977. SDL_GPUShaderStage stage;
  978. Uint32 num_samplers;
  979. Uint32 numUniformBuffers;
  980. Uint32 numStorageBuffers;
  981. Uint32 numStorageTextures;
  982. };
  983. typedef struct D3D12GraphicsRootSignature
  984. {
  985. ID3D12RootSignature *handle;
  986. Sint32 vertexSamplerRootIndex;
  987. Sint32 vertexSamplerTextureRootIndex;
  988. Sint32 vertexStorageTextureRootIndex;
  989. Sint32 vertexStorageBufferRootIndex;
  990. Sint32 vertexUniformBufferRootIndex[MAX_UNIFORM_BUFFERS_PER_STAGE];
  991. Sint32 fragmentSamplerRootIndex;
  992. Sint32 fragmentSamplerTextureRootIndex;
  993. Sint32 fragmentStorageTextureRootIndex;
  994. Sint32 fragmentStorageBufferRootIndex;
  995. Sint32 fragmentUniformBufferRootIndex[MAX_UNIFORM_BUFFERS_PER_STAGE];
  996. } D3D12GraphicsRootSignature;
  997. struct D3D12GraphicsPipeline
  998. {
  999. GraphicsPipelineCommonHeader header;
  1000. ID3D12PipelineState *pipelineState;
  1001. D3D12GraphicsRootSignature *rootSignature;
  1002. SDL_GPUPrimitiveType primitiveType;
  1003. Uint32 vertexStrides[MAX_VERTEX_BUFFERS];
  1004. SDL_AtomicInt referenceCount;
  1005. };
  1006. typedef struct D3D12ComputeRootSignature
  1007. {
  1008. ID3D12RootSignature *handle;
  1009. Sint32 samplerRootIndex;
  1010. Sint32 samplerTextureRootIndex;
  1011. Sint32 readOnlyStorageTextureRootIndex;
  1012. Sint32 readOnlyStorageBufferRootIndex;
  1013. Sint32 readWriteStorageTextureRootIndex;
  1014. Sint32 readWriteStorageBufferRootIndex;
  1015. Sint32 uniformBufferRootIndex[MAX_UNIFORM_BUFFERS_PER_STAGE];
  1016. } D3D12ComputeRootSignature;
  1017. struct D3D12ComputePipeline
  1018. {
  1019. ComputePipelineCommonHeader header;
  1020. ID3D12PipelineState *pipelineState;
  1021. D3D12ComputeRootSignature *rootSignature;
  1022. SDL_AtomicInt referenceCount;
  1023. };
  1024. struct D3D12TextureDownload
  1025. {
  1026. D3D12Buffer *destinationBuffer;
  1027. D3D12Buffer *temporaryBuffer;
  1028. Uint32 width;
  1029. Uint32 height;
  1030. Uint32 depth;
  1031. Uint32 bufferOffset;
  1032. Uint32 bytesPerRow;
  1033. Uint32 bytesPerDepthSlice;
  1034. Uint32 alignedBytesPerRow;
  1035. };
  1036. struct D3D12Buffer
  1037. {
  1038. D3D12BufferContainer *container;
  1039. Uint32 containerIndex;
  1040. ID3D12Resource *handle;
  1041. D3D12StagingDescriptor uavDescriptor;
  1042. D3D12StagingDescriptor srvDescriptor;
  1043. D3D12StagingDescriptor cbvDescriptor;
  1044. D3D12_GPU_VIRTUAL_ADDRESS virtualAddress;
  1045. Uint8 *mapPointer; // NULL except for upload buffers and fast uniform buffers
  1046. SDL_AtomicInt referenceCount;
  1047. bool transitioned; // used for initial resource barrier
  1048. };
  1049. struct D3D12BufferContainer
  1050. {
  1051. SDL_GPUBufferUsageFlags usage;
  1052. Uint32 size;
  1053. D3D12BufferType type;
  1054. D3D12Buffer *activeBuffer;
  1055. D3D12Buffer **buffers;
  1056. Uint32 bufferCapacity;
  1057. Uint32 bufferCount;
  1058. D3D12_RESOURCE_DESC bufferDesc;
  1059. char *debugName;
  1060. };
  1061. struct D3D12UniformBuffer
  1062. {
  1063. D3D12Buffer *buffer;
  1064. Uint32 writeOffset;
  1065. Uint32 drawOffset;
  1066. };
  1067. // Forward function declarations
  1068. static void D3D12_ReleaseWindow(SDL_GPURenderer *driverData, SDL_Window *window);
  1069. static bool D3D12_Wait(SDL_GPURenderer *driverData);
  1070. static bool D3D12_WaitForFences(SDL_GPURenderer *driverData, bool waitAll, SDL_GPUFence *const *fences, Uint32 numFences);
  1071. static void D3D12_INTERNAL_ReleaseBlitPipelines(SDL_GPURenderer *driverData);
  1072. // Helpers
  1073. static Uint32 D3D12_INTERNAL_Align(Uint32 location, Uint32 alignment)
  1074. {
  1075. return (location + (alignment - 1)) & ~(alignment - 1);
  1076. }
  1077. // Xbox Hack
  1078. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  1079. // FIXME: This is purely to work around a presentation bug when recreating the device/command queue.
  1080. static ID3D12Device *s_Device;
  1081. static ID3D12CommandQueue *s_CommandQueue;
  1082. #endif
  1083. #if defined(SDL_PLATFORM_XBOXONE)
  1084. // These are not defined in d3d12_x.h.
  1085. typedef HRESULT (D3DAPI* PFN_D3D12_XBOX_CREATE_DEVICE)(_In_opt_ IGraphicsUnknown *, _In_ const D3D12XBOX_CREATE_DEVICE_PARAMETERS*, _In_ REFIID, _Outptr_opt_ void **);
  1086. #define D3D12_STANDARD_MULTISAMPLE_PATTERN DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN
  1087. #endif
  1088. // Logging
  1089. static void D3D12_INTERNAL_SetError(
  1090. D3D12Renderer *renderer,
  1091. const char *msg,
  1092. HRESULT res)
  1093. {
  1094. #define MAX_ERROR_LEN 1024 // FIXME: Arbitrary!
  1095. // Buffer for text, ensure space for \0 terminator after buffer
  1096. char wszMsgBuff[MAX_ERROR_LEN + 1];
  1097. DWORD dwChars; // Number of chars returned.
  1098. if (res == DXGI_ERROR_DEVICE_REMOVED) {
  1099. if (renderer->device) {
  1100. res = ID3D12Device_GetDeviceRemovedReason(renderer->device);
  1101. }
  1102. }
  1103. // Try to get the message from the system errors.
  1104. dwChars = FormatMessageA(
  1105. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1106. NULL,
  1107. res,
  1108. 0,
  1109. wszMsgBuff,
  1110. MAX_ERROR_LEN,
  1111. NULL);
  1112. // No message? Screw it, just post the code.
  1113. if (dwChars == 0) {
  1114. if (renderer->debug_mode) {
  1115. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s! Error Code: " HRESULT_FMT, msg, res);
  1116. }
  1117. SDL_SetError("%s! Error Code: " HRESULT_FMT, msg, res);
  1118. return;
  1119. }
  1120. // Ensure valid range
  1121. dwChars = SDL_min(dwChars, MAX_ERROR_LEN);
  1122. // Trim whitespace from tail of message
  1123. while (dwChars > 0) {
  1124. if (wszMsgBuff[dwChars - 1] <= ' ') {
  1125. dwChars--;
  1126. } else {
  1127. break;
  1128. }
  1129. }
  1130. // Ensure null-terminated string
  1131. wszMsgBuff[dwChars] = '\0';
  1132. if (renderer->debug_mode) {
  1133. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s! Error Code: %s " HRESULT_FMT, msg, wszMsgBuff, res);
  1134. }
  1135. SDL_SetError("%s! Error Code: %s " HRESULT_FMT, msg, wszMsgBuff, res);
  1136. }
  1137. // Release / Cleanup
  1138. static void D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  1139. D3D12StagingDescriptor *cpuDescriptor)
  1140. {
  1141. D3D12StagingDescriptorPool *pool = cpuDescriptor->pool;
  1142. if (pool != NULL) {
  1143. SDL_LockMutex(pool->lock);
  1144. SDL_memcpy(&pool->freeDescriptors[pool->freeDescriptorCount], cpuDescriptor, sizeof(D3D12StagingDescriptor));
  1145. pool->freeDescriptorCount += 1;
  1146. SDL_UnlockMutex(pool->lock);
  1147. }
  1148. }
  1149. static void D3D12_INTERNAL_DestroyBuffer(
  1150. D3D12Buffer *buffer)
  1151. {
  1152. if (!buffer) {
  1153. return;
  1154. }
  1155. if (buffer->mapPointer != NULL) {
  1156. ID3D12Resource_Unmap(
  1157. buffer->handle,
  1158. 0,
  1159. NULL);
  1160. }
  1161. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  1162. &buffer->srvDescriptor);
  1163. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  1164. &buffer->uavDescriptor);
  1165. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  1166. &buffer->cbvDescriptor);
  1167. if (buffer->handle) {
  1168. ID3D12Resource_Release(buffer->handle);
  1169. }
  1170. SDL_free(buffer);
  1171. }
  1172. static void D3D12_INTERNAL_ReleaseBuffer(
  1173. D3D12Renderer *renderer,
  1174. D3D12Buffer *buffer)
  1175. {
  1176. SDL_LockMutex(renderer->disposeLock);
  1177. EXPAND_ARRAY_IF_NEEDED(
  1178. renderer->buffersToDestroy,
  1179. D3D12Buffer *,
  1180. renderer->buffersToDestroyCount + 1,
  1181. renderer->buffersToDestroyCapacity,
  1182. renderer->buffersToDestroyCapacity * 2);
  1183. renderer->buffersToDestroy[renderer->buffersToDestroyCount] = buffer;
  1184. renderer->buffersToDestroyCount += 1;
  1185. SDL_UnlockMutex(renderer->disposeLock);
  1186. }
  1187. static void D3D12_INTERNAL_ReleaseBufferContainer(
  1188. D3D12Renderer *renderer,
  1189. D3D12BufferContainer *container)
  1190. {
  1191. SDL_LockMutex(renderer->disposeLock);
  1192. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  1193. D3D12_INTERNAL_ReleaseBuffer(
  1194. renderer,
  1195. container->buffers[i]);
  1196. }
  1197. // Containers are just client handles, so we can free immediately
  1198. SDL_free(container->debugName);
  1199. SDL_free(container->buffers);
  1200. SDL_free(container);
  1201. SDL_UnlockMutex(renderer->disposeLock);
  1202. }
  1203. static void D3D12_INTERNAL_DestroyTexture(
  1204. D3D12Texture *texture)
  1205. {
  1206. if (!texture) {
  1207. return;
  1208. }
  1209. for (Uint32 i = 0; i < texture->subresourceCount; i += 1) {
  1210. D3D12TextureSubresource *subresource = &texture->subresources[i];
  1211. if (subresource->rtvHandles) {
  1212. for (Uint32 depthIndex = 0; depthIndex < subresource->depth; depthIndex += 1) {
  1213. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  1214. &subresource->rtvHandles[depthIndex]);
  1215. }
  1216. SDL_free(subresource->rtvHandles);
  1217. }
  1218. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  1219. &subresource->uavHandle);
  1220. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  1221. &subresource->dsvHandle);
  1222. }
  1223. SDL_free(texture->subresources);
  1224. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  1225. &texture->srvHandle);
  1226. if (texture->resource) {
  1227. ID3D12Resource_Release(texture->resource);
  1228. }
  1229. SDL_free(texture);
  1230. }
  1231. static void D3D12_INTERNAL_ReleaseTexture(
  1232. D3D12Renderer *renderer,
  1233. D3D12Texture *texture)
  1234. {
  1235. SDL_LockMutex(renderer->disposeLock);
  1236. EXPAND_ARRAY_IF_NEEDED(
  1237. renderer->texturesToDestroy,
  1238. D3D12Texture *,
  1239. renderer->texturesToDestroyCount + 1,
  1240. renderer->texturesToDestroyCapacity,
  1241. renderer->texturesToDestroyCapacity * 2);
  1242. renderer->texturesToDestroy[renderer->texturesToDestroyCount] = texture;
  1243. renderer->texturesToDestroyCount += 1;
  1244. SDL_UnlockMutex(renderer->disposeLock);
  1245. }
  1246. static void D3D12_INTERNAL_ReleaseTextureContainer(
  1247. D3D12Renderer *renderer,
  1248. D3D12TextureContainer *container)
  1249. {
  1250. SDL_LockMutex(renderer->disposeLock);
  1251. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  1252. D3D12_INTERNAL_ReleaseTexture(
  1253. renderer,
  1254. container->textures[i]);
  1255. }
  1256. SDL_DestroyProperties(container->header.info.props);
  1257. // Containers are just client handles, so we can destroy immediately
  1258. SDL_free(container->debugName);
  1259. SDL_free(container->textures);
  1260. SDL_free(container);
  1261. SDL_UnlockMutex(renderer->disposeLock);
  1262. }
  1263. static void D3D12_INTERNAL_DestroySampler(
  1264. D3D12Sampler *sampler)
  1265. {
  1266. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  1267. &sampler->handle);
  1268. SDL_free(sampler);
  1269. }
  1270. static void D3D12_INTERNAL_DestroyGraphicsRootSignature(
  1271. D3D12GraphicsRootSignature *rootSignature)
  1272. {
  1273. if (!rootSignature) {
  1274. return;
  1275. }
  1276. if (rootSignature->handle) {
  1277. ID3D12RootSignature_Release(rootSignature->handle);
  1278. }
  1279. SDL_free(rootSignature);
  1280. }
  1281. static void D3D12_INTERNAL_DestroyGraphicsPipeline(
  1282. D3D12GraphicsPipeline *graphicsPipeline)
  1283. {
  1284. if (graphicsPipeline->pipelineState) {
  1285. ID3D12PipelineState_Release(graphicsPipeline->pipelineState);
  1286. }
  1287. D3D12_INTERNAL_DestroyGraphicsRootSignature(graphicsPipeline->rootSignature);
  1288. SDL_free(graphicsPipeline);
  1289. }
  1290. static void D3D12_INTERNAL_DestroyComputeRootSignature(
  1291. D3D12ComputeRootSignature *rootSignature)
  1292. {
  1293. if (!rootSignature) {
  1294. return;
  1295. }
  1296. if (rootSignature->handle) {
  1297. ID3D12RootSignature_Release(rootSignature->handle);
  1298. }
  1299. SDL_free(rootSignature);
  1300. }
  1301. static void D3D12_INTERNAL_DestroyComputePipeline(
  1302. D3D12ComputePipeline *computePipeline)
  1303. {
  1304. if (computePipeline->pipelineState) {
  1305. ID3D12PipelineState_Release(computePipeline->pipelineState);
  1306. }
  1307. D3D12_INTERNAL_DestroyComputeRootSignature(computePipeline->rootSignature);
  1308. SDL_free(computePipeline);
  1309. }
  1310. static void D3D12_INTERNAL_ReleaseFenceToPool(
  1311. D3D12Renderer *renderer,
  1312. D3D12Fence *fence)
  1313. {
  1314. SDL_LockMutex(renderer->fenceLock);
  1315. EXPAND_ARRAY_IF_NEEDED(
  1316. renderer->availableFences,
  1317. D3D12Fence *,
  1318. renderer->availableFenceCount + 1,
  1319. renderer->availableFenceCapacity,
  1320. renderer->availableFenceCapacity * 2);
  1321. renderer->availableFences[renderer->availableFenceCount] = fence;
  1322. renderer->availableFenceCount += 1;
  1323. SDL_UnlockMutex(renderer->fenceLock);
  1324. }
  1325. static void D3D12_ReleaseFence(
  1326. SDL_GPURenderer *driverData,
  1327. SDL_GPUFence *fence)
  1328. {
  1329. D3D12Fence *d3d12Fence = (D3D12Fence *)fence;
  1330. if (SDL_AtomicDecRef(&d3d12Fence->referenceCount)) {
  1331. D3D12_INTERNAL_ReleaseFenceToPool(
  1332. (D3D12Renderer *)driverData,
  1333. d3d12Fence);
  1334. }
  1335. }
  1336. static bool D3D12_QueryFence(
  1337. SDL_GPURenderer *driverData,
  1338. SDL_GPUFence *fence)
  1339. {
  1340. D3D12Fence *d3d12Fence = (D3D12Fence *)fence;
  1341. return ID3D12Fence_GetCompletedValue(d3d12Fence->handle) == D3D12_FENCE_SIGNAL_VALUE;
  1342. }
  1343. static void D3D12_INTERNAL_DestroyDescriptorHeap(D3D12DescriptorHeap *descriptorHeap)
  1344. {
  1345. if (!descriptorHeap) {
  1346. return;
  1347. }
  1348. if (descriptorHeap->handle) {
  1349. ID3D12DescriptorHeap_Release(descriptorHeap->handle);
  1350. }
  1351. SDL_free(descriptorHeap);
  1352. }
  1353. static void D3D12_INTERNAL_DestroyStagingDescriptorPool(
  1354. D3D12StagingDescriptorPool *pool)
  1355. {
  1356. for (Uint32 i = 0; i < pool->heapCount; i += 1) {
  1357. D3D12_INTERNAL_DestroyDescriptorHeap(pool->heaps[i]);
  1358. }
  1359. SDL_free(pool->heaps);
  1360. SDL_free(pool->freeDescriptors);
  1361. SDL_DestroyMutex(pool->lock);
  1362. SDL_free(pool);
  1363. }
  1364. static void D3D12_INTERNAL_DestroyCommandBuffer(D3D12CommandBuffer *commandBuffer)
  1365. {
  1366. if (!commandBuffer) {
  1367. return;
  1368. }
  1369. if (commandBuffer->graphicsCommandList) {
  1370. ID3D12GraphicsCommandList_Release(commandBuffer->graphicsCommandList);
  1371. }
  1372. if (commandBuffer->commandAllocator) {
  1373. ID3D12CommandAllocator_Release(commandBuffer->commandAllocator);
  1374. }
  1375. SDL_free(commandBuffer->presentDatas);
  1376. SDL_free(commandBuffer->usedTextures);
  1377. SDL_free(commandBuffer->usedBuffers);
  1378. SDL_free(commandBuffer->usedSamplers);
  1379. SDL_free(commandBuffer->usedGraphicsPipelines);
  1380. SDL_free(commandBuffer->usedComputePipelines);
  1381. SDL_free(commandBuffer->usedDescriptorHeaps);
  1382. SDL_free(commandBuffer->usedUniformBuffers);
  1383. SDL_free(commandBuffer->textureDownloads);
  1384. SDL_free(commandBuffer);
  1385. }
  1386. static void D3D12_INTERNAL_DestroyFence(D3D12Fence *fence)
  1387. {
  1388. if (!fence) {
  1389. return;
  1390. }
  1391. if (fence->handle) {
  1392. ID3D12Fence_Release(fence->handle);
  1393. }
  1394. if (fence->event) {
  1395. CloseHandle(fence->event);
  1396. }
  1397. SDL_free(fence);
  1398. }
  1399. static void D3D12_INTERNAL_DestroyRenderer(D3D12Renderer *renderer)
  1400. {
  1401. // Release uniform buffers
  1402. for (Uint32 i = 0; i < renderer->uniformBufferPoolCount; i += 1) {
  1403. D3D12_INTERNAL_DestroyBuffer(
  1404. renderer->uniformBufferPool[i]->buffer);
  1405. SDL_free(renderer->uniformBufferPool[i]);
  1406. }
  1407. // Clean up descriptor heaps
  1408. for (Uint32 i = 0; i < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; i += 1) {
  1409. if (renderer->stagingDescriptorPools[i]) {
  1410. D3D12_INTERNAL_DestroyStagingDescriptorPool(renderer->stagingDescriptorPools[i]);
  1411. renderer->stagingDescriptorPools[i] = NULL;
  1412. }
  1413. }
  1414. for (Uint32 i = 0; i < 2; i += 1) {
  1415. if (renderer->gpuDescriptorHeapPools[i].heaps) {
  1416. for (Uint32 j = 0; j < renderer->gpuDescriptorHeapPools[i].count; j += 1) {
  1417. if (renderer->gpuDescriptorHeapPools[i].heaps[j]) {
  1418. D3D12_INTERNAL_DestroyDescriptorHeap(renderer->gpuDescriptorHeapPools[i].heaps[j]);
  1419. renderer->gpuDescriptorHeapPools[i].heaps[j] = NULL;
  1420. }
  1421. }
  1422. SDL_free(renderer->gpuDescriptorHeapPools[i].heaps);
  1423. }
  1424. if (renderer->gpuDescriptorHeapPools[i].lock) {
  1425. SDL_DestroyMutex(renderer->gpuDescriptorHeapPools[i].lock);
  1426. renderer->gpuDescriptorHeapPools[i].lock = NULL;
  1427. }
  1428. }
  1429. // Release command buffers
  1430. for (Uint32 i = 0; i < renderer->availableCommandBufferCount; i += 1) {
  1431. if (renderer->availableCommandBuffers[i]) {
  1432. D3D12_INTERNAL_DestroyCommandBuffer(renderer->availableCommandBuffers[i]);
  1433. renderer->availableCommandBuffers[i] = NULL;
  1434. }
  1435. }
  1436. // Release fences
  1437. for (Uint32 i = 0; i < renderer->availableFenceCount; i += 1) {
  1438. if (renderer->availableFences[i]) {
  1439. D3D12_INTERNAL_DestroyFence(renderer->availableFences[i]);
  1440. renderer->availableFences[i] = NULL;
  1441. }
  1442. }
  1443. // Clean up allocations
  1444. SDL_free(renderer->availableCommandBuffers);
  1445. SDL_free(renderer->submittedCommandBuffers);
  1446. SDL_free(renderer->uniformBufferPool);
  1447. SDL_free(renderer->claimedWindows);
  1448. SDL_free(renderer->availableFences);
  1449. SDL_free(renderer->buffersToDestroy);
  1450. SDL_free(renderer->texturesToDestroy);
  1451. SDL_free(renderer->samplersToDestroy);
  1452. SDL_free(renderer->graphicsPipelinesToDestroy);
  1453. SDL_free(renderer->computePipelinesToDestroy);
  1454. SDL_DestroyProperties(renderer->props);
  1455. // Tear down D3D12 objects
  1456. if (renderer->indirectDrawCommandSignature) {
  1457. ID3D12CommandSignature_Release(renderer->indirectDrawCommandSignature);
  1458. renderer->indirectDrawCommandSignature = NULL;
  1459. }
  1460. if (renderer->indirectIndexedDrawCommandSignature) {
  1461. ID3D12CommandSignature_Release(renderer->indirectIndexedDrawCommandSignature);
  1462. renderer->indirectIndexedDrawCommandSignature = NULL;
  1463. }
  1464. if (renderer->indirectDispatchCommandSignature) {
  1465. ID3D12CommandSignature_Release(renderer->indirectDispatchCommandSignature);
  1466. renderer->indirectDispatchCommandSignature = NULL;
  1467. }
  1468. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  1469. if (renderer->commandQueue) {
  1470. ID3D12CommandQueue_Release(renderer->commandQueue);
  1471. renderer->commandQueue = NULL;
  1472. }
  1473. if (renderer->device) {
  1474. ID3D12Device_Release(renderer->device);
  1475. renderer->device = NULL;
  1476. }
  1477. if (renderer->adapter) {
  1478. IDXGIAdapter1_Release(renderer->adapter);
  1479. renderer->adapter = NULL;
  1480. }
  1481. if (renderer->factory) {
  1482. IDXGIFactory4_Release(renderer->factory);
  1483. renderer->factory = NULL;
  1484. }
  1485. if (renderer->dxgiDebug) {
  1486. IDXGIDebug_ReportLiveObjects(
  1487. renderer->dxgiDebug,
  1488. D3D_IID_DXGI_DEBUG_ALL,
  1489. (DXGI_DEBUG_RLO_FLAGS)(DXGI_DEBUG_RLO_SUMMARY | DXGI_DEBUG_RLO_DETAIL));
  1490. IDXGIDebug_Release(renderer->dxgiDebug);
  1491. renderer->dxgiDebug = NULL;
  1492. }
  1493. #endif
  1494. if (renderer->d3d12_dll) {
  1495. SDL_UnloadObject(renderer->d3d12_dll);
  1496. renderer->d3d12_dll = NULL;
  1497. }
  1498. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  1499. if (renderer->dxgi_dll) {
  1500. SDL_UnloadObject(renderer->dxgi_dll);
  1501. renderer->dxgi_dll = NULL;
  1502. }
  1503. if (renderer->dxgidebug_dll) {
  1504. SDL_UnloadObject(renderer->dxgidebug_dll);
  1505. renderer->dxgidebug_dll = NULL;
  1506. }
  1507. #endif
  1508. #ifdef USE_PIX_RUNTIME
  1509. if (renderer->winpixeventruntime_dll) {
  1510. SDL_UnloadObject(renderer->winpixeventruntime_dll);
  1511. renderer->winpixeventruntime_dll = NULL;
  1512. }
  1513. #endif
  1514. renderer->pD3D12SerializeRootSignature = NULL;
  1515. if (renderer->iconv) {
  1516. SDL_iconv_close(renderer->iconv);
  1517. }
  1518. SDL_DestroyMutex(renderer->acquireCommandBufferLock);
  1519. SDL_DestroyMutex(renderer->acquireUniformBufferLock);
  1520. SDL_DestroyMutex(renderer->submitLock);
  1521. SDL_DestroyMutex(renderer->windowLock);
  1522. SDL_DestroyMutex(renderer->fenceLock);
  1523. SDL_DestroyMutex(renderer->disposeLock);
  1524. SDL_free(renderer->semantic);
  1525. SDL_free(renderer);
  1526. }
  1527. static void D3D12_DestroyDevice(SDL_GPUDevice *device)
  1528. {
  1529. D3D12Renderer *renderer = (D3D12Renderer *)device->driverData;
  1530. // Release blit pipeline structures
  1531. D3D12_INTERNAL_ReleaseBlitPipelines((SDL_GPURenderer *)renderer);
  1532. // Flush any remaining GPU work...
  1533. D3D12_Wait((SDL_GPURenderer *)renderer);
  1534. // Release window data
  1535. for (Sint32 i = renderer->claimedWindowCount - 1; i >= 0; i -= 1) {
  1536. D3D12_ReleaseWindow((SDL_GPURenderer *)renderer, renderer->claimedWindows[i]->window);
  1537. }
  1538. D3D12_INTERNAL_DestroyRenderer(renderer);
  1539. SDL_free(device);
  1540. }
  1541. static SDL_PropertiesID D3D12_GetDeviceProperties(SDL_GPUDevice *device)
  1542. {
  1543. D3D12Renderer *renderer = (D3D12Renderer *)device->driverData;
  1544. return renderer->props;
  1545. }
  1546. // Barriers
  1547. static inline Uint32 D3D12_INTERNAL_CalcSubresource(
  1548. Uint32 mipLevel,
  1549. Uint32 layer,
  1550. Uint32 numLevels)
  1551. {
  1552. return mipLevel + (layer * numLevels);
  1553. }
  1554. static void D3D12_INTERNAL_ResourceBarrier(
  1555. D3D12CommandBuffer *commandBuffer,
  1556. D3D12_RESOURCE_STATES sourceState,
  1557. D3D12_RESOURCE_STATES destinationState,
  1558. ID3D12Resource *resource,
  1559. Uint32 subresourceIndex,
  1560. bool needsUavBarrier)
  1561. {
  1562. D3D12_RESOURCE_BARRIER barrierDesc[2];
  1563. Uint32 numBarriers = 0;
  1564. // No transition barrier is needed if the state is not changing.
  1565. if (sourceState != destinationState) {
  1566. barrierDesc[numBarriers].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  1567. barrierDesc[numBarriers].Flags = (D3D12_RESOURCE_BARRIER_FLAGS)0;
  1568. barrierDesc[numBarriers].Transition.StateBefore = sourceState;
  1569. barrierDesc[numBarriers].Transition.StateAfter = destinationState;
  1570. barrierDesc[numBarriers].Transition.pResource = resource;
  1571. barrierDesc[numBarriers].Transition.Subresource = subresourceIndex;
  1572. numBarriers += 1;
  1573. }
  1574. if (needsUavBarrier) {
  1575. barrierDesc[numBarriers].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
  1576. barrierDesc[numBarriers].Flags = (D3D12_RESOURCE_BARRIER_FLAGS)0;
  1577. barrierDesc[numBarriers].UAV.pResource = resource;
  1578. numBarriers += 1;
  1579. }
  1580. if (numBarriers > 0) {
  1581. ID3D12GraphicsCommandList_ResourceBarrier(
  1582. commandBuffer->graphicsCommandList,
  1583. numBarriers,
  1584. barrierDesc);
  1585. }
  1586. }
  1587. static void D3D12_INTERNAL_TextureSubresourceBarrier(
  1588. D3D12CommandBuffer *commandBuffer,
  1589. D3D12_RESOURCE_STATES sourceState,
  1590. D3D12_RESOURCE_STATES destinationState,
  1591. D3D12TextureSubresource *textureSubresource)
  1592. {
  1593. bool needsUAVBarrier =
  1594. (textureSubresource->parent->container->header.info.usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) ||
  1595. (textureSubresource->parent->container->header.info.usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE);
  1596. D3D12_INTERNAL_ResourceBarrier(
  1597. commandBuffer,
  1598. sourceState,
  1599. destinationState,
  1600. textureSubresource->parent->resource,
  1601. textureSubresource->index,
  1602. needsUAVBarrier);
  1603. }
  1604. static D3D12_RESOURCE_STATES D3D12_INTERNAL_DefaultTextureResourceState(
  1605. SDL_GPUTextureUsageFlags usageFlags)
  1606. {
  1607. // NOTE: order matters here!
  1608. if (usageFlags & SDL_GPU_TEXTUREUSAGE_SAMPLER) {
  1609. return D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  1610. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ) {
  1611. return D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  1612. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  1613. return D3D12_RESOURCE_STATE_RENDER_TARGET;
  1614. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  1615. return D3D12_RESOURCE_STATE_DEPTH_WRITE;
  1616. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ) {
  1617. return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
  1618. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) {
  1619. return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  1620. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE) {
  1621. return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  1622. } else {
  1623. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Texture has no default usage mode!");
  1624. return D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  1625. }
  1626. }
  1627. static void D3D12_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  1628. D3D12CommandBuffer *commandBuffer,
  1629. D3D12_RESOURCE_STATES destinationUsageMode,
  1630. D3D12TextureSubresource *textureSubresource)
  1631. {
  1632. D3D12_INTERNAL_TextureSubresourceBarrier(
  1633. commandBuffer,
  1634. D3D12_INTERNAL_DefaultTextureResourceState(textureSubresource->parent->container->header.info.usage),
  1635. destinationUsageMode,
  1636. textureSubresource);
  1637. }
  1638. static void D3D12_INTERNAL_TextureTransitionFromDefaultUsage(
  1639. D3D12CommandBuffer *commandBuffer,
  1640. D3D12_RESOURCE_STATES destinationUsageMode,
  1641. D3D12Texture *texture)
  1642. {
  1643. for (Uint32 i = 0; i < texture->subresourceCount; i += 1) {
  1644. D3D12_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  1645. commandBuffer,
  1646. destinationUsageMode,
  1647. &texture->subresources[i]);
  1648. }
  1649. }
  1650. static void D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  1651. D3D12CommandBuffer *commandBuffer,
  1652. D3D12_RESOURCE_STATES sourceUsageMode,
  1653. D3D12TextureSubresource *textureSubresource)
  1654. {
  1655. D3D12_INTERNAL_TextureSubresourceBarrier(
  1656. commandBuffer,
  1657. sourceUsageMode,
  1658. D3D12_INTERNAL_DefaultTextureResourceState(textureSubresource->parent->container->header.info.usage),
  1659. textureSubresource);
  1660. }
  1661. static void D3D12_INTERNAL_TextureTransitionToDefaultUsage(
  1662. D3D12CommandBuffer *commandBuffer,
  1663. D3D12_RESOURCE_STATES sourceUsageMode,
  1664. D3D12Texture *texture)
  1665. {
  1666. for (Uint32 i = 0; i < texture->subresourceCount; i += 1) {
  1667. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  1668. commandBuffer,
  1669. sourceUsageMode,
  1670. &texture->subresources[i]);
  1671. }
  1672. }
  1673. static D3D12_RESOURCE_STATES D3D12_INTERNAL_DefaultBufferResourceState(
  1674. D3D12Buffer *buffer)
  1675. {
  1676. if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_VERTEX) {
  1677. return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
  1678. } else if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_INDEX) {
  1679. return D3D12_RESOURCE_STATE_INDEX_BUFFER;
  1680. } else if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_INDIRECT) {
  1681. return D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  1682. } else if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ) {
  1683. return D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  1684. } else if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ) {
  1685. return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
  1686. } else if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE) {
  1687. return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  1688. } else {
  1689. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Buffer has no default usage mode!");
  1690. return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
  1691. }
  1692. }
  1693. static void D3D12_INTERNAL_BufferBarrier(
  1694. D3D12CommandBuffer *commandBuffer,
  1695. D3D12_RESOURCE_STATES sourceState,
  1696. D3D12_RESOURCE_STATES destinationState,
  1697. D3D12Buffer *buffer)
  1698. {
  1699. D3D12_INTERNAL_ResourceBarrier(
  1700. commandBuffer,
  1701. buffer->transitioned ? sourceState : D3D12_RESOURCE_STATE_COMMON,
  1702. destinationState,
  1703. buffer->handle,
  1704. 0,
  1705. buffer->container->usage & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE);
  1706. buffer->transitioned = true;
  1707. }
  1708. static void D3D12_INTERNAL_BufferTransitionFromDefaultUsage(
  1709. D3D12CommandBuffer *commandBuffer,
  1710. D3D12_RESOURCE_STATES destinationState,
  1711. D3D12Buffer *buffer)
  1712. {
  1713. D3D12_INTERNAL_BufferBarrier(
  1714. commandBuffer,
  1715. D3D12_INTERNAL_DefaultBufferResourceState(buffer),
  1716. destinationState,
  1717. buffer);
  1718. }
  1719. static void D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  1720. D3D12CommandBuffer *commandBuffer,
  1721. D3D12_RESOURCE_STATES sourceState,
  1722. D3D12Buffer *buffer)
  1723. {
  1724. D3D12_INTERNAL_BufferBarrier(
  1725. commandBuffer,
  1726. sourceState,
  1727. D3D12_INTERNAL_DefaultBufferResourceState(buffer),
  1728. buffer);
  1729. }
  1730. // Resource tracking
  1731. #define TRACK_RESOURCE(resource, type, array, count, capacity) \
  1732. Uint32 i; \
  1733. \
  1734. for (i = 0; i < commandBuffer->count; i += 1) { \
  1735. if (commandBuffer->array[i] == resource) { \
  1736. return; \
  1737. } \
  1738. } \
  1739. \
  1740. if (commandBuffer->count == commandBuffer->capacity) { \
  1741. commandBuffer->capacity += 1; \
  1742. commandBuffer->array = (type *)SDL_realloc( \
  1743. commandBuffer->array, \
  1744. commandBuffer->capacity * sizeof(type)); \
  1745. } \
  1746. commandBuffer->array[commandBuffer->count] = resource; \
  1747. commandBuffer->count += 1; \
  1748. SDL_AtomicIncRef(&resource->referenceCount);
  1749. static void D3D12_INTERNAL_TrackTexture(
  1750. D3D12CommandBuffer *commandBuffer,
  1751. D3D12Texture *texture)
  1752. {
  1753. TRACK_RESOURCE(
  1754. texture,
  1755. D3D12Texture *,
  1756. usedTextures,
  1757. usedTextureCount,
  1758. usedTextureCapacity)
  1759. }
  1760. static void D3D12_INTERNAL_TrackBuffer(
  1761. D3D12CommandBuffer *commandBuffer,
  1762. D3D12Buffer *buffer)
  1763. {
  1764. TRACK_RESOURCE(
  1765. buffer,
  1766. D3D12Buffer *,
  1767. usedBuffers,
  1768. usedBufferCount,
  1769. usedBufferCapacity)
  1770. }
  1771. static void D3D12_INTERNAL_TrackSampler(
  1772. D3D12CommandBuffer *commandBuffer,
  1773. D3D12Sampler *sampler)
  1774. {
  1775. TRACK_RESOURCE(
  1776. sampler,
  1777. D3D12Sampler *,
  1778. usedSamplers,
  1779. usedSamplerCount,
  1780. usedSamplerCapacity)
  1781. }
  1782. static void D3D12_INTERNAL_TrackGraphicsPipeline(
  1783. D3D12CommandBuffer *commandBuffer,
  1784. D3D12GraphicsPipeline *graphicsPipeline)
  1785. {
  1786. TRACK_RESOURCE(
  1787. graphicsPipeline,
  1788. D3D12GraphicsPipeline *,
  1789. usedGraphicsPipelines,
  1790. usedGraphicsPipelineCount,
  1791. usedGraphicsPipelineCapacity)
  1792. }
  1793. static void D3D12_INTERNAL_TrackComputePipeline(
  1794. D3D12CommandBuffer *commandBuffer,
  1795. D3D12ComputePipeline *computePipeline)
  1796. {
  1797. TRACK_RESOURCE(
  1798. computePipeline,
  1799. D3D12ComputePipeline *,
  1800. usedComputePipelines,
  1801. usedComputePipelineCount,
  1802. usedComputePipelineCapacity)
  1803. }
  1804. #undef TRACK_RESOURCE
  1805. // Debug Naming
  1806. static void D3D12_INTERNAL_SetPipelineStateName(
  1807. D3D12Renderer *renderer,
  1808. ID3D12PipelineState *pipelineState,
  1809. const char *text
  1810. ) {
  1811. if (renderer->debug_mode && text != NULL) {
  1812. WCHAR *wchar_text = WIN_UTF8ToStringW(text);
  1813. ID3D12PipelineState_SetName(
  1814. pipelineState,
  1815. wchar_text);
  1816. SDL_free(wchar_text);
  1817. }
  1818. }
  1819. static void D3D12_INTERNAL_SetResourceName(
  1820. D3D12Renderer *renderer,
  1821. ID3D12Resource *resource,
  1822. const char *text
  1823. ) {
  1824. if (renderer->debug_mode && text != NULL) {
  1825. WCHAR *wchar_text = WIN_UTF8ToStringW(text);
  1826. ID3D12Resource_SetName(
  1827. resource,
  1828. wchar_text);
  1829. SDL_free(wchar_text);
  1830. }
  1831. }
  1832. static void D3D12_SetBufferName(
  1833. SDL_GPURenderer *driverData,
  1834. SDL_GPUBuffer *buffer,
  1835. const char *text)
  1836. {
  1837. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  1838. D3D12BufferContainer *container = (D3D12BufferContainer *)buffer;
  1839. if (renderer->debug_mode && text != NULL) {
  1840. SDL_free(container->debugName);
  1841. container->debugName = SDL_strdup(text);
  1842. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  1843. D3D12_INTERNAL_SetResourceName(
  1844. renderer,
  1845. container->buffers[i]->handle,
  1846. text);
  1847. }
  1848. }
  1849. }
  1850. static void D3D12_SetTextureName(
  1851. SDL_GPURenderer *driverData,
  1852. SDL_GPUTexture *texture,
  1853. const char *text)
  1854. {
  1855. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  1856. D3D12TextureContainer *container = (D3D12TextureContainer *)texture;
  1857. if (renderer->debug_mode && text != NULL) {
  1858. SDL_free(container->debugName);
  1859. container->debugName = SDL_strdup(text);
  1860. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  1861. D3D12_INTERNAL_SetResourceName(
  1862. renderer,
  1863. container->textures[i]->resource,
  1864. text);
  1865. }
  1866. }
  1867. }
  1868. /* These debug functions now require the PIX runtime under Windows to avoid validation
  1869. * layer errors. Calling them without the PIX runtime in your path is a no-op.
  1870. */
  1871. static void D3D12_InsertDebugLabel(
  1872. SDL_GPUCommandBuffer *commandBuffer,
  1873. const char *text)
  1874. {
  1875. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  1876. #ifdef USE_PIX_RUNTIME
  1877. // Requires PIX runtime under Windows, no-op if DLL unavailable.
  1878. WinPixEventRuntimeFns *fns = &d3d12CommandBuffer->renderer->winpixeventruntimeFns;
  1879. if (fns->pSetMarkerOnCommandList) {
  1880. fns->pSetMarkerOnCommandList(d3d12CommandBuffer->graphicsCommandList, 0 /*default color*/, text);
  1881. }
  1882. #else
  1883. WCHAR *wchar_text = WIN_UTF8ToStringW(text);
  1884. ID3D12GraphicsCommandList_SetMarker(
  1885. d3d12CommandBuffer->graphicsCommandList,
  1886. 0,
  1887. wchar_text,
  1888. (UINT)SDL_wcslen(wchar_text) * sizeof(WCHAR));
  1889. SDL_free(wchar_text);
  1890. #endif
  1891. }
  1892. static void D3D12_PushDebugGroup(
  1893. SDL_GPUCommandBuffer *commandBuffer,
  1894. const char *name)
  1895. {
  1896. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  1897. #ifdef USE_PIX_RUNTIME
  1898. // Requires PIX runtime under Windows, no-op if DLL unavailable.
  1899. WinPixEventRuntimeFns *fns = &d3d12CommandBuffer->renderer->winpixeventruntimeFns;
  1900. if (fns->pBeginEventOnCommandList) {
  1901. fns->pBeginEventOnCommandList(d3d12CommandBuffer->graphicsCommandList, 0 /*default color*/, name);
  1902. }
  1903. #else
  1904. WCHAR *wchar_text = WIN_UTF8ToStringW(name);
  1905. ID3D12GraphicsCommandList_BeginEvent(
  1906. d3d12CommandBuffer->graphicsCommandList,
  1907. 0,
  1908. wchar_text,
  1909. (UINT)SDL_wcslen(wchar_text) * sizeof(WCHAR));
  1910. SDL_free(wchar_text);
  1911. #endif
  1912. }
  1913. static void D3D12_PopDebugGroup(
  1914. SDL_GPUCommandBuffer *commandBuffer)
  1915. {
  1916. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  1917. #ifdef USE_PIX_RUNTIME
  1918. // Requires PIX runtime under Windows, no-op if DLL unavailable.
  1919. WinPixEventRuntimeFns *fns = &d3d12CommandBuffer->renderer->winpixeventruntimeFns;
  1920. if (fns->pEndEventOnCommandList) {
  1921. fns->pEndEventOnCommandList(d3d12CommandBuffer->graphicsCommandList);
  1922. }
  1923. #else
  1924. ID3D12GraphicsCommandList_EndEvent(d3d12CommandBuffer->graphicsCommandList);
  1925. #endif
  1926. }
  1927. // State Creation
  1928. static D3D12DescriptorHeap *D3D12_INTERNAL_CreateDescriptorHeap(
  1929. D3D12Renderer *renderer,
  1930. D3D12_DESCRIPTOR_HEAP_TYPE type,
  1931. Uint32 descriptorCount,
  1932. bool staging)
  1933. {
  1934. D3D12DescriptorHeap *heap;
  1935. ID3D12DescriptorHeap *handle;
  1936. D3D12_DESCRIPTOR_HEAP_DESC heapDesc;
  1937. HRESULT res;
  1938. heap = (D3D12DescriptorHeap *)SDL_calloc(1, sizeof(D3D12DescriptorHeap));
  1939. if (!heap) {
  1940. return NULL;
  1941. }
  1942. heap->currentDescriptorIndex = 0;
  1943. heapDesc.NumDescriptors = descriptorCount;
  1944. heapDesc.Type = type;
  1945. heapDesc.Flags = staging ? D3D12_DESCRIPTOR_HEAP_FLAG_NONE : D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1946. heapDesc.NodeMask = 0;
  1947. res = ID3D12Device_CreateDescriptorHeap(
  1948. renderer->device,
  1949. &heapDesc,
  1950. D3D_GUID(D3D_IID_ID3D12DescriptorHeap),
  1951. (void **)&handle);
  1952. if (FAILED(res)) {
  1953. D3D12_INTERNAL_SetError(renderer, "Failed to create descriptor heap!", res);
  1954. D3D12_INTERNAL_DestroyDescriptorHeap(heap);
  1955. return NULL;
  1956. }
  1957. heap->handle = handle;
  1958. heap->heapType = type;
  1959. heap->maxDescriptors = descriptorCount;
  1960. heap->staging = staging;
  1961. heap->descriptorSize = ID3D12Device_GetDescriptorHandleIncrementSize(renderer->device, type);
  1962. D3D_CALL_RET(handle, GetCPUDescriptorHandleForHeapStart, &heap->descriptorHeapCPUStart);
  1963. if (!staging) {
  1964. D3D_CALL_RET(handle, GetGPUDescriptorHandleForHeapStart, &heap->descriptorHeapGPUStart);
  1965. }
  1966. return heap;
  1967. }
  1968. static D3D12StagingDescriptorPool *D3D12_INTERNAL_CreateStagingDescriptorPool(
  1969. D3D12Renderer *renderer,
  1970. D3D12_DESCRIPTOR_HEAP_TYPE heapType
  1971. ) {
  1972. D3D12DescriptorHeap *heap = D3D12_INTERNAL_CreateDescriptorHeap(
  1973. renderer,
  1974. heapType,
  1975. STAGING_HEAP_DESCRIPTOR_COUNT,
  1976. true);
  1977. if (!heap) {
  1978. return NULL;
  1979. }
  1980. D3D12StagingDescriptorPool *pool = (D3D12StagingDescriptorPool *)SDL_calloc(1, sizeof(D3D12StagingDescriptorPool));
  1981. pool->heapCount = 1;
  1982. pool->heaps = (D3D12DescriptorHeap **)SDL_malloc(sizeof(D3D12DescriptorHeap *));
  1983. pool->heaps[0] = heap;
  1984. pool->freeDescriptorCapacity = STAGING_HEAP_DESCRIPTOR_COUNT;
  1985. pool->freeDescriptorCount = STAGING_HEAP_DESCRIPTOR_COUNT;
  1986. pool->freeDescriptors = (D3D12StagingDescriptor *)SDL_malloc(STAGING_HEAP_DESCRIPTOR_COUNT * sizeof(D3D12StagingDescriptor));
  1987. for (Uint32 i = 0; i < STAGING_HEAP_DESCRIPTOR_COUNT; i += 1) {
  1988. pool->freeDescriptors[i].pool = pool;
  1989. pool->freeDescriptors[i].heap = heap;
  1990. pool->freeDescriptors[i].cpuHandleIndex = i;
  1991. pool->freeDescriptors[i].cpuHandle.ptr = heap->descriptorHeapCPUStart.ptr + (i * heap->descriptorSize);
  1992. }
  1993. pool->lock = SDL_CreateMutex();
  1994. return pool;
  1995. }
  1996. /* If the pool is empty, we need to refill it! */
  1997. static bool D3D12_INTERNAL_ExpandStagingDescriptorPool(
  1998. D3D12Renderer *renderer,
  1999. D3D12StagingDescriptorPool *pool
  2000. ) {
  2001. D3D12DescriptorHeap *heap = D3D12_INTERNAL_CreateDescriptorHeap(
  2002. renderer,
  2003. pool->heaps[0]->heapType,
  2004. STAGING_HEAP_DESCRIPTOR_COUNT,
  2005. true);
  2006. if (!heap) {
  2007. return false;
  2008. }
  2009. pool->heapCount += 1;
  2010. pool->heaps = (D3D12DescriptorHeap **)SDL_realloc(pool->heaps, pool->heapCount * sizeof(D3D12DescriptorHeap *));
  2011. pool->heaps[pool->heapCount - 1] = heap;
  2012. pool->freeDescriptorCapacity += STAGING_HEAP_DESCRIPTOR_COUNT;
  2013. pool->freeDescriptorCount += STAGING_HEAP_DESCRIPTOR_COUNT;
  2014. pool->freeDescriptors = (D3D12StagingDescriptor *)SDL_realloc(pool->freeDescriptors, pool->freeDescriptorCapacity * sizeof(D3D12StagingDescriptor));
  2015. for (Uint32 i = 0; i < STAGING_HEAP_DESCRIPTOR_COUNT; i += 1) {
  2016. pool->freeDescriptors[i].pool = pool;
  2017. pool->freeDescriptors[i].heap = heap;
  2018. pool->freeDescriptors[i].cpuHandleIndex = i;
  2019. pool->freeDescriptors[i].cpuHandle.ptr = heap->descriptorHeapCPUStart.ptr + (i * heap->descriptorSize);
  2020. }
  2021. return true;
  2022. }
  2023. static void D3D12_INTERNAL_TrackGPUDescriptorHeap(
  2024. D3D12CommandBuffer *commandBuffer,
  2025. D3D12DescriptorHeap *descriptorHeap)
  2026. {
  2027. Uint32 i;
  2028. for (i = 0; i < commandBuffer->usedDescriptorHeapCount; i += 1) {
  2029. if (commandBuffer->usedDescriptorHeaps[i] == descriptorHeap) {
  2030. return;
  2031. }
  2032. }
  2033. if (commandBuffer->usedDescriptorHeapCount == commandBuffer->usedDescriptorHeapCapacity) {
  2034. commandBuffer->usedDescriptorHeapCapacity += 1;
  2035. commandBuffer->usedDescriptorHeaps = (D3D12DescriptorHeap **)SDL_realloc(
  2036. commandBuffer->usedDescriptorHeaps,
  2037. commandBuffer->usedDescriptorHeapCapacity * sizeof(D3D12DescriptorHeap *));
  2038. }
  2039. commandBuffer->usedDescriptorHeaps[commandBuffer->usedDescriptorHeapCount] = descriptorHeap;
  2040. commandBuffer->usedDescriptorHeapCount += 1;
  2041. }
  2042. static D3D12DescriptorHeap *D3D12_INTERNAL_AcquireGPUDescriptorHeapFromPool(
  2043. D3D12CommandBuffer *commandBuffer,
  2044. D3D12_DESCRIPTOR_HEAP_TYPE descriptorHeapType)
  2045. {
  2046. D3D12DescriptorHeap *result;
  2047. D3D12Renderer *renderer = commandBuffer->renderer;
  2048. D3D12GPUDescriptorHeapPool *pool = &renderer->gpuDescriptorHeapPools[descriptorHeapType];
  2049. SDL_LockMutex(pool->lock);
  2050. if (pool->count > 0) {
  2051. result = pool->heaps[pool->count - 1];
  2052. pool->count -= 1;
  2053. } else {
  2054. result = D3D12_INTERNAL_CreateDescriptorHeap(
  2055. renderer,
  2056. descriptorHeapType,
  2057. descriptorHeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ? VIEW_GPU_DESCRIPTOR_COUNT : SAMPLER_GPU_DESCRIPTOR_COUNT,
  2058. false);
  2059. }
  2060. SDL_UnlockMutex(pool->lock);
  2061. D3D12_INTERNAL_TrackGPUDescriptorHeap(commandBuffer, result);
  2062. return result;
  2063. }
  2064. static void D3D12_INTERNAL_ReturnGPUDescriptorHeapToPool(
  2065. D3D12Renderer *renderer,
  2066. D3D12DescriptorHeap *heap)
  2067. {
  2068. if (heap == NULL) {
  2069. return;
  2070. }
  2071. D3D12GPUDescriptorHeapPool *pool = &renderer->gpuDescriptorHeapPools[heap->heapType];
  2072. heap->currentDescriptorIndex = 0;
  2073. SDL_LockMutex(pool->lock);
  2074. if (pool->count >= pool->capacity) {
  2075. pool->capacity *= 2;
  2076. pool->heaps = (D3D12DescriptorHeap **)SDL_realloc(
  2077. pool->heaps,
  2078. pool->capacity * sizeof(D3D12DescriptorHeap *));
  2079. }
  2080. pool->heaps[pool->count] = heap;
  2081. pool->count += 1;
  2082. SDL_UnlockMutex(pool->lock);
  2083. }
  2084. /*
  2085. * The root signature lets us define "root parameters" which are essentially bind points for resources.
  2086. * These let us define the register ranges as well as the register "space".
  2087. * The register space is akin to the descriptor set index in Vulkan, which allows us to group resources
  2088. * by stage so that the registers from the vertex and fragment shaders don't clobber each other.
  2089. *
  2090. * Most of our root parameters are implemented as "descriptor tables" so we can
  2091. * copy and then point to contiguous descriptor regions.
  2092. * Uniform buffers are the exception - these have to be implemented as raw "root descriptors" so
  2093. * that we can dynamically update the address that the constant buffer view points to.
  2094. *
  2095. * The root signature has a maximum size of 64 DWORDs.
  2096. * A descriptor table uses 1 DWORD.
  2097. * A root descriptor uses 2 DWORDS.
  2098. * This means our biggest root signature uses 24 DWORDs total, well under the limit.
  2099. *
  2100. * The root parameter indices are created dynamically and stored in the D3D12GraphicsRootSignature struct.
  2101. */
  2102. static D3D12GraphicsRootSignature *D3D12_INTERNAL_CreateGraphicsRootSignature(
  2103. D3D12Renderer *renderer,
  2104. D3D12Shader *vertexShader,
  2105. D3D12Shader *fragmentShader)
  2106. {
  2107. // FIXME: I think the max can be smaller...
  2108. D3D12_ROOT_PARAMETER rootParameters[MAX_ROOT_SIGNATURE_PARAMETERS];
  2109. D3D12_DESCRIPTOR_RANGE descriptorRanges[MAX_ROOT_SIGNATURE_PARAMETERS];
  2110. Uint32 parameterCount = 0;
  2111. Uint32 rangeCount = 0;
  2112. D3D12_DESCRIPTOR_RANGE descriptorRange;
  2113. D3D12_ROOT_PARAMETER rootParameter;
  2114. D3D12GraphicsRootSignature *d3d12GraphicsRootSignature =
  2115. (D3D12GraphicsRootSignature *)SDL_calloc(1, sizeof(D3D12GraphicsRootSignature));
  2116. if (!d3d12GraphicsRootSignature) {
  2117. return NULL;
  2118. }
  2119. SDL_zeroa(rootParameters);
  2120. SDL_zeroa(descriptorRanges);
  2121. SDL_zero(rootParameter);
  2122. d3d12GraphicsRootSignature->vertexSamplerRootIndex = -1;
  2123. d3d12GraphicsRootSignature->vertexSamplerTextureRootIndex = -1;
  2124. d3d12GraphicsRootSignature->vertexStorageTextureRootIndex = -1;
  2125. d3d12GraphicsRootSignature->vertexStorageBufferRootIndex = -1;
  2126. d3d12GraphicsRootSignature->fragmentSamplerRootIndex = -1;
  2127. d3d12GraphicsRootSignature->fragmentSamplerTextureRootIndex = -1;
  2128. d3d12GraphicsRootSignature->fragmentStorageTextureRootIndex = -1;
  2129. d3d12GraphicsRootSignature->fragmentStorageBufferRootIndex = -1;
  2130. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  2131. d3d12GraphicsRootSignature->vertexUniformBufferRootIndex[i] = -1;
  2132. d3d12GraphicsRootSignature->fragmentUniformBufferRootIndex[i] = -1;
  2133. }
  2134. if (vertexShader->num_samplers > 0) {
  2135. // Vertex Samplers
  2136. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
  2137. descriptorRange.NumDescriptors = vertexShader->num_samplers;
  2138. descriptorRange.BaseShaderRegister = 0;
  2139. descriptorRange.RegisterSpace = 0;
  2140. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2141. descriptorRanges[rangeCount] = descriptorRange;
  2142. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2143. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2144. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2145. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  2146. rootParameters[parameterCount] = rootParameter;
  2147. d3d12GraphicsRootSignature->vertexSamplerRootIndex = parameterCount;
  2148. rangeCount += 1;
  2149. parameterCount += 1;
  2150. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  2151. descriptorRange.NumDescriptors = vertexShader->num_samplers;
  2152. descriptorRange.BaseShaderRegister = 0;
  2153. descriptorRange.RegisterSpace = 0;
  2154. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2155. descriptorRanges[rangeCount] = descriptorRange;
  2156. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2157. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2158. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2159. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  2160. rootParameters[parameterCount] = rootParameter;
  2161. d3d12GraphicsRootSignature->vertexSamplerTextureRootIndex = parameterCount;
  2162. rangeCount += 1;
  2163. parameterCount += 1;
  2164. }
  2165. if (vertexShader->numStorageTextures) {
  2166. // Vertex storage textures
  2167. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  2168. descriptorRange.NumDescriptors = vertexShader->numStorageTextures;
  2169. descriptorRange.BaseShaderRegister = vertexShader->num_samplers;
  2170. descriptorRange.RegisterSpace = 0;
  2171. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2172. descriptorRanges[rangeCount] = descriptorRange;
  2173. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2174. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2175. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2176. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  2177. rootParameters[parameterCount] = rootParameter;
  2178. d3d12GraphicsRootSignature->vertexStorageTextureRootIndex = parameterCount;
  2179. rangeCount += 1;
  2180. parameterCount += 1;
  2181. }
  2182. if (vertexShader->numStorageBuffers) {
  2183. // Vertex storage buffers
  2184. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  2185. descriptorRange.NumDescriptors = vertexShader->numStorageBuffers;
  2186. descriptorRange.BaseShaderRegister = vertexShader->num_samplers + vertexShader->numStorageTextures;
  2187. descriptorRange.RegisterSpace = 0;
  2188. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2189. descriptorRanges[rangeCount] = descriptorRange;
  2190. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2191. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2192. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2193. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  2194. rootParameters[parameterCount] = rootParameter;
  2195. d3d12GraphicsRootSignature->vertexStorageBufferRootIndex = parameterCount;
  2196. rangeCount += 1;
  2197. parameterCount += 1;
  2198. }
  2199. // Vertex Uniforms
  2200. for (Uint32 i = 0; i < vertexShader->numUniformBuffers; i += 1) {
  2201. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
  2202. rootParameter.Descriptor.ShaderRegister = i;
  2203. rootParameter.Descriptor.RegisterSpace = 1;
  2204. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  2205. rootParameters[parameterCount] = rootParameter;
  2206. d3d12GraphicsRootSignature->vertexUniformBufferRootIndex[i] = parameterCount;
  2207. parameterCount += 1;
  2208. }
  2209. if (fragmentShader->num_samplers) {
  2210. // Fragment Samplers
  2211. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
  2212. descriptorRange.NumDescriptors = fragmentShader->num_samplers;
  2213. descriptorRange.BaseShaderRegister = 0;
  2214. descriptorRange.RegisterSpace = 2;
  2215. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2216. descriptorRanges[rangeCount] = descriptorRange;
  2217. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2218. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2219. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2220. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  2221. rootParameters[parameterCount] = rootParameter;
  2222. d3d12GraphicsRootSignature->fragmentSamplerRootIndex = parameterCount;
  2223. rangeCount += 1;
  2224. parameterCount += 1;
  2225. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  2226. descriptorRange.NumDescriptors = fragmentShader->num_samplers;
  2227. descriptorRange.BaseShaderRegister = 0;
  2228. descriptorRange.RegisterSpace = 2;
  2229. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2230. descriptorRanges[rangeCount] = descriptorRange;
  2231. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2232. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2233. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2234. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  2235. rootParameters[parameterCount] = rootParameter;
  2236. d3d12GraphicsRootSignature->fragmentSamplerTextureRootIndex = parameterCount;
  2237. rangeCount += 1;
  2238. parameterCount += 1;
  2239. }
  2240. if (fragmentShader->numStorageTextures) {
  2241. // Fragment Storage Textures
  2242. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  2243. descriptorRange.NumDescriptors = fragmentShader->numStorageTextures;
  2244. descriptorRange.BaseShaderRegister = fragmentShader->num_samplers;
  2245. descriptorRange.RegisterSpace = 2;
  2246. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2247. descriptorRanges[rangeCount] = descriptorRange;
  2248. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2249. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2250. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2251. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  2252. rootParameters[parameterCount] = rootParameter;
  2253. d3d12GraphicsRootSignature->fragmentStorageTextureRootIndex = parameterCount;
  2254. rangeCount += 1;
  2255. parameterCount += 1;
  2256. }
  2257. if (fragmentShader->numStorageBuffers) {
  2258. // Fragment Storage Buffers
  2259. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  2260. descriptorRange.NumDescriptors = fragmentShader->numStorageBuffers;
  2261. descriptorRange.BaseShaderRegister = fragmentShader->num_samplers + fragmentShader->numStorageTextures;
  2262. descriptorRange.RegisterSpace = 2;
  2263. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2264. descriptorRanges[rangeCount] = descriptorRange;
  2265. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2266. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2267. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2268. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  2269. rootParameters[parameterCount] = rootParameter;
  2270. d3d12GraphicsRootSignature->fragmentStorageBufferRootIndex = parameterCount;
  2271. rangeCount += 1;
  2272. parameterCount += 1;
  2273. }
  2274. // Fragment Uniforms
  2275. for (Uint32 i = 0; i < fragmentShader->numUniformBuffers; i += 1) {
  2276. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
  2277. rootParameter.Descriptor.ShaderRegister = i;
  2278. rootParameter.Descriptor.RegisterSpace = 3;
  2279. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  2280. rootParameters[parameterCount] = rootParameter;
  2281. d3d12GraphicsRootSignature->fragmentUniformBufferRootIndex[i] = parameterCount;
  2282. parameterCount += 1;
  2283. }
  2284. // FIXME: shouldn't have to assert here
  2285. SDL_assert(parameterCount <= MAX_ROOT_SIGNATURE_PARAMETERS);
  2286. SDL_assert(rangeCount <= MAX_ROOT_SIGNATURE_PARAMETERS);
  2287. // Create the root signature description
  2288. D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  2289. rootSignatureDesc.NumParameters = parameterCount;
  2290. rootSignatureDesc.pParameters = rootParameters;
  2291. rootSignatureDesc.NumStaticSamplers = 0;
  2292. rootSignatureDesc.pStaticSamplers = NULL;
  2293. rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
  2294. // Serialize the root signature
  2295. ID3DBlob *serializedRootSignature;
  2296. ID3DBlob *errorBlob;
  2297. HRESULT res = renderer->pD3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &serializedRootSignature, &errorBlob);
  2298. if (FAILED(res)) {
  2299. if (errorBlob) {
  2300. SET_ERROR("Failed to serialize RootSignature: %s", (const char *)ID3D10Blob_GetBufferPointer(errorBlob));
  2301. ID3D10Blob_Release(errorBlob);
  2302. }
  2303. D3D12_INTERNAL_DestroyGraphicsRootSignature(d3d12GraphicsRootSignature);
  2304. return NULL;
  2305. }
  2306. // Create the root signature
  2307. ID3D12RootSignature *rootSignature;
  2308. res = ID3D12Device_CreateRootSignature(
  2309. renderer->device,
  2310. 0,
  2311. ID3D10Blob_GetBufferPointer(serializedRootSignature),
  2312. ID3D10Blob_GetBufferSize(serializedRootSignature),
  2313. D3D_GUID(D3D_IID_ID3D12RootSignature),
  2314. (void **)&rootSignature);
  2315. if (FAILED(res)) {
  2316. if (errorBlob) {
  2317. SET_ERROR("Failed to create RootSignature: %s", (const char *)ID3D10Blob_GetBufferPointer(errorBlob));
  2318. ID3D10Blob_Release(errorBlob);
  2319. }
  2320. D3D12_INTERNAL_DestroyGraphicsRootSignature(d3d12GraphicsRootSignature);
  2321. return NULL;
  2322. }
  2323. d3d12GraphicsRootSignature->handle = rootSignature;
  2324. return d3d12GraphicsRootSignature;
  2325. }
  2326. static bool D3D12_INTERNAL_IsValidShaderBytecode(
  2327. const Uint8 *code,
  2328. size_t codeSize)
  2329. {
  2330. // Both DXIL and DXBC bytecode have a 4 byte header containing `DXBC`.
  2331. if (codeSize < 4 || code == NULL) {
  2332. return false;
  2333. }
  2334. return SDL_memcmp(code, "DXBC", 4) == 0;
  2335. }
  2336. static bool D3D12_INTERNAL_CreateShaderBytecode(
  2337. D3D12Renderer *renderer,
  2338. const Uint8 *code,
  2339. size_t codeSize,
  2340. SDL_GPUShaderFormat format,
  2341. void **pBytecode,
  2342. size_t *pBytecodeSize)
  2343. {
  2344. if (!D3D12_INTERNAL_IsValidShaderBytecode(code, codeSize)) {
  2345. if (format == SDL_GPU_SHADERFORMAT_DXBC) {
  2346. SET_STRING_ERROR_AND_RETURN("The provided shader code is not valid DXBC!", false);
  2347. }
  2348. SET_STRING_ERROR_AND_RETURN("The provided shader code is not valid DXIL!", false);
  2349. }
  2350. if (pBytecode != NULL) {
  2351. *pBytecode = SDL_malloc(codeSize);
  2352. if (!*pBytecode) {
  2353. return false;
  2354. }
  2355. SDL_memcpy(*pBytecode, code, codeSize);
  2356. *pBytecodeSize = codeSize;
  2357. }
  2358. return true;
  2359. }
  2360. static D3D12ComputeRootSignature *D3D12_INTERNAL_CreateComputeRootSignature(
  2361. D3D12Renderer *renderer,
  2362. const SDL_GPUComputePipelineCreateInfo *createInfo)
  2363. {
  2364. // FIXME: I think the max can be smaller...
  2365. D3D12_ROOT_PARAMETER rootParameters[MAX_ROOT_SIGNATURE_PARAMETERS];
  2366. D3D12_DESCRIPTOR_RANGE descriptorRanges[MAX_ROOT_SIGNATURE_PARAMETERS];
  2367. Uint32 parameterCount = 0;
  2368. Uint32 rangeCount = 0;
  2369. D3D12_DESCRIPTOR_RANGE descriptorRange;
  2370. D3D12_ROOT_PARAMETER rootParameter;
  2371. D3D12ComputeRootSignature *d3d12ComputeRootSignature =
  2372. (D3D12ComputeRootSignature *)SDL_calloc(1, sizeof(D3D12ComputeRootSignature));
  2373. if (!d3d12ComputeRootSignature) {
  2374. return NULL;
  2375. }
  2376. SDL_zeroa(rootParameters);
  2377. SDL_zeroa(descriptorRanges);
  2378. SDL_zero(rootParameter);
  2379. d3d12ComputeRootSignature->samplerRootIndex = -1;
  2380. d3d12ComputeRootSignature->samplerTextureRootIndex = -1;
  2381. d3d12ComputeRootSignature->readOnlyStorageTextureRootIndex = -1;
  2382. d3d12ComputeRootSignature->readOnlyStorageBufferRootIndex = -1;
  2383. d3d12ComputeRootSignature->readWriteStorageTextureRootIndex = -1;
  2384. d3d12ComputeRootSignature->readWriteStorageBufferRootIndex = -1;
  2385. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  2386. d3d12ComputeRootSignature->uniformBufferRootIndex[i] = -1;
  2387. }
  2388. if (createInfo->num_samplers) {
  2389. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
  2390. descriptorRange.NumDescriptors = createInfo->num_samplers;
  2391. descriptorRange.BaseShaderRegister = 0;
  2392. descriptorRange.RegisterSpace = 0;
  2393. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2394. descriptorRanges[rangeCount] = descriptorRange;
  2395. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2396. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2397. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2398. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  2399. rootParameters[parameterCount] = rootParameter;
  2400. d3d12ComputeRootSignature->samplerRootIndex = parameterCount;
  2401. rangeCount += 1;
  2402. parameterCount += 1;
  2403. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  2404. descriptorRange.NumDescriptors = createInfo->num_samplers;
  2405. descriptorRange.BaseShaderRegister = 0;
  2406. descriptorRange.RegisterSpace = 0;
  2407. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2408. descriptorRanges[rangeCount] = descriptorRange;
  2409. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2410. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2411. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2412. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  2413. rootParameters[parameterCount] = rootParameter;
  2414. d3d12ComputeRootSignature->samplerTextureRootIndex = parameterCount;
  2415. rangeCount += 1;
  2416. parameterCount += 1;
  2417. }
  2418. if (createInfo->num_readonly_storage_textures) {
  2419. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  2420. descriptorRange.NumDescriptors = createInfo->num_readonly_storage_textures;
  2421. descriptorRange.BaseShaderRegister = createInfo->num_samplers;
  2422. descriptorRange.RegisterSpace = 0;
  2423. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2424. descriptorRanges[rangeCount] = descriptorRange;
  2425. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2426. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2427. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2428. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  2429. rootParameters[parameterCount] = rootParameter;
  2430. d3d12ComputeRootSignature->readOnlyStorageTextureRootIndex = parameterCount;
  2431. rangeCount += 1;
  2432. parameterCount += 1;
  2433. }
  2434. if (createInfo->num_readonly_storage_buffers) {
  2435. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  2436. descriptorRange.NumDescriptors = createInfo->num_readonly_storage_buffers;
  2437. descriptorRange.BaseShaderRegister = createInfo->num_samplers + createInfo->num_readonly_storage_textures;
  2438. descriptorRange.RegisterSpace = 0;
  2439. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2440. descriptorRanges[rangeCount] = descriptorRange;
  2441. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2442. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2443. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2444. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  2445. rootParameters[parameterCount] = rootParameter;
  2446. d3d12ComputeRootSignature->readOnlyStorageBufferRootIndex = parameterCount;
  2447. rangeCount += 1;
  2448. parameterCount += 1;
  2449. }
  2450. if (createInfo->num_readwrite_storage_textures) {
  2451. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
  2452. descriptorRange.NumDescriptors = createInfo->num_readwrite_storage_textures;
  2453. descriptorRange.BaseShaderRegister = 0;
  2454. descriptorRange.RegisterSpace = 1;
  2455. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2456. descriptorRanges[rangeCount] = descriptorRange;
  2457. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2458. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2459. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2460. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  2461. rootParameters[parameterCount] = rootParameter;
  2462. d3d12ComputeRootSignature->readWriteStorageTextureRootIndex = parameterCount;
  2463. rangeCount += 1;
  2464. parameterCount += 1;
  2465. }
  2466. if (createInfo->num_readwrite_storage_buffers) {
  2467. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
  2468. descriptorRange.NumDescriptors = createInfo->num_readwrite_storage_buffers;
  2469. descriptorRange.BaseShaderRegister = createInfo->num_readwrite_storage_textures;
  2470. descriptorRange.RegisterSpace = 1;
  2471. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  2472. descriptorRanges[rangeCount] = descriptorRange;
  2473. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  2474. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  2475. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  2476. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  2477. rootParameters[parameterCount] = rootParameter;
  2478. d3d12ComputeRootSignature->readWriteStorageBufferRootIndex = parameterCount;
  2479. rangeCount += 1;
  2480. parameterCount += 1;
  2481. }
  2482. for (Uint32 i = 0; i < createInfo->num_uniform_buffers; i += 1) {
  2483. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
  2484. rootParameter.Descriptor.ShaderRegister = i;
  2485. rootParameter.Descriptor.RegisterSpace = 2;
  2486. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  2487. rootParameters[parameterCount] = rootParameter;
  2488. d3d12ComputeRootSignature->uniformBufferRootIndex[i] = parameterCount;
  2489. parameterCount += 1;
  2490. }
  2491. D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  2492. rootSignatureDesc.NumParameters = parameterCount;
  2493. rootSignatureDesc.pParameters = rootParameters;
  2494. rootSignatureDesc.NumStaticSamplers = 0;
  2495. rootSignatureDesc.pStaticSamplers = NULL;
  2496. rootSignatureDesc.Flags = (D3D12_ROOT_SIGNATURE_FLAGS)0;
  2497. ID3DBlob *serializedRootSignature;
  2498. ID3DBlob *errorBlob;
  2499. HRESULT res = renderer->pD3D12SerializeRootSignature(
  2500. &rootSignatureDesc,
  2501. D3D_ROOT_SIGNATURE_VERSION_1,
  2502. &serializedRootSignature,
  2503. &errorBlob);
  2504. if (FAILED(res)) {
  2505. if (errorBlob) {
  2506. SET_ERROR("Failed to serialize RootSignature: %s", (const char *)ID3D10Blob_GetBufferPointer(errorBlob));
  2507. ID3D10Blob_Release(errorBlob);
  2508. }
  2509. D3D12_INTERNAL_DestroyComputeRootSignature(d3d12ComputeRootSignature);
  2510. return NULL;
  2511. }
  2512. ID3D12RootSignature *rootSignature;
  2513. res = ID3D12Device_CreateRootSignature(
  2514. renderer->device,
  2515. 0,
  2516. ID3D10Blob_GetBufferPointer(serializedRootSignature),
  2517. ID3D10Blob_GetBufferSize(serializedRootSignature),
  2518. D3D_GUID(D3D_IID_ID3D12RootSignature),
  2519. (void **)&rootSignature);
  2520. if (FAILED(res)) {
  2521. if (errorBlob) {
  2522. SET_ERROR("Failed to create RootSignature: %s", (const char *)ID3D10Blob_GetBufferPointer(errorBlob));
  2523. ID3D10Blob_Release(errorBlob);
  2524. }
  2525. D3D12_INTERNAL_DestroyComputeRootSignature(d3d12ComputeRootSignature);
  2526. return NULL;
  2527. }
  2528. d3d12ComputeRootSignature->handle = rootSignature;
  2529. return d3d12ComputeRootSignature;
  2530. }
  2531. static SDL_GPUComputePipeline *D3D12_CreateComputePipeline(
  2532. SDL_GPURenderer *driverData,
  2533. const SDL_GPUComputePipelineCreateInfo *createinfo)
  2534. {
  2535. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  2536. void *bytecode;
  2537. size_t bytecodeSize;
  2538. ID3D12PipelineState *pipelineState;
  2539. if (!D3D12_INTERNAL_CreateShaderBytecode(
  2540. renderer,
  2541. createinfo->code,
  2542. createinfo->code_size,
  2543. createinfo->format,
  2544. &bytecode,
  2545. &bytecodeSize)) {
  2546. return NULL;
  2547. }
  2548. D3D12ComputeRootSignature *rootSignature = D3D12_INTERNAL_CreateComputeRootSignature(
  2549. renderer,
  2550. createinfo);
  2551. if (rootSignature == NULL) {
  2552. SDL_free(bytecode);
  2553. SET_STRING_ERROR_AND_RETURN("Could not create root signature!", NULL);
  2554. }
  2555. D3D12_COMPUTE_PIPELINE_STATE_DESC pipelineDesc;
  2556. pipelineDesc.CS.pShaderBytecode = bytecode;
  2557. pipelineDesc.CS.BytecodeLength = bytecodeSize;
  2558. pipelineDesc.pRootSignature = rootSignature->handle;
  2559. pipelineDesc.CachedPSO.CachedBlobSizeInBytes = 0;
  2560. pipelineDesc.CachedPSO.pCachedBlob = NULL;
  2561. pipelineDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  2562. pipelineDesc.NodeMask = 0;
  2563. HRESULT res = ID3D12Device_CreateComputePipelineState(
  2564. renderer->device,
  2565. &pipelineDesc,
  2566. D3D_GUID(D3D_IID_ID3D12PipelineState),
  2567. (void **)&pipelineState);
  2568. if (FAILED(res)) {
  2569. D3D12_INTERNAL_SetError(renderer, "Could not create compute pipeline state", res);
  2570. SDL_free(bytecode);
  2571. return NULL;
  2572. }
  2573. D3D12ComputePipeline *computePipeline =
  2574. (D3D12ComputePipeline *)SDL_calloc(1, sizeof(D3D12ComputePipeline));
  2575. if (!computePipeline) {
  2576. ID3D12PipelineState_Release(pipelineState);
  2577. SDL_free(bytecode);
  2578. return NULL;
  2579. }
  2580. computePipeline->pipelineState = pipelineState;
  2581. computePipeline->rootSignature = rootSignature;
  2582. computePipeline->header.numSamplers = createinfo->num_samplers;
  2583. computePipeline->header.numReadonlyStorageTextures = createinfo->num_readonly_storage_textures;
  2584. computePipeline->header.numReadonlyStorageBuffers = createinfo->num_readonly_storage_buffers;
  2585. computePipeline->header.numReadWriteStorageTextures = createinfo->num_readwrite_storage_textures;
  2586. computePipeline->header.numReadWriteStorageBuffers = createinfo->num_readwrite_storage_buffers;
  2587. computePipeline->header.numUniformBuffers = createinfo->num_uniform_buffers;
  2588. SDL_SetAtomicInt(&computePipeline->referenceCount, 0);
  2589. if (renderer->debug_mode && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_COMPUTEPIPELINE_CREATE_NAME_STRING)) {
  2590. D3D12_INTERNAL_SetPipelineStateName(
  2591. renderer,
  2592. computePipeline->pipelineState,
  2593. SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_COMPUTEPIPELINE_CREATE_NAME_STRING, NULL));
  2594. }
  2595. return (SDL_GPUComputePipeline *)computePipeline;
  2596. }
  2597. static bool D3D12_INTERNAL_ConvertRasterizerState(SDL_GPURasterizerState rasterizerState, D3D12_RASTERIZER_DESC *desc)
  2598. {
  2599. if (!desc) {
  2600. return false;
  2601. }
  2602. desc->FillMode = SDLToD3D12_FillMode[rasterizerState.fill_mode];
  2603. desc->CullMode = SDLToD3D12_CullMode[rasterizerState.cull_mode];
  2604. switch (rasterizerState.front_face) {
  2605. case SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE:
  2606. desc->FrontCounterClockwise = TRUE;
  2607. break;
  2608. case SDL_GPU_FRONTFACE_CLOCKWISE:
  2609. desc->FrontCounterClockwise = FALSE;
  2610. break;
  2611. default:
  2612. return false;
  2613. }
  2614. if (rasterizerState.enable_depth_bias) {
  2615. desc->DepthBias = SDL_lroundf(rasterizerState.depth_bias_constant_factor);
  2616. desc->DepthBiasClamp = rasterizerState.depth_bias_clamp;
  2617. desc->SlopeScaledDepthBias = rasterizerState.depth_bias_slope_factor;
  2618. } else {
  2619. desc->DepthBias = 0;
  2620. desc->DepthBiasClamp = 0.0f;
  2621. desc->SlopeScaledDepthBias = 0.0f;
  2622. }
  2623. desc->DepthClipEnable = rasterizerState.enable_depth_clip;
  2624. desc->MultisampleEnable = FALSE;
  2625. desc->AntialiasedLineEnable = FALSE;
  2626. desc->ForcedSampleCount = 0;
  2627. desc->ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  2628. return true;
  2629. }
  2630. static bool D3D12_INTERNAL_ConvertBlendState(
  2631. const SDL_GPUGraphicsPipelineCreateInfo *pipelineInfo,
  2632. D3D12_BLEND_DESC *blendDesc)
  2633. {
  2634. if (!blendDesc) {
  2635. return false;
  2636. }
  2637. SDL_zerop(blendDesc);
  2638. blendDesc->AlphaToCoverageEnable = pipelineInfo->multisample_state.enable_alpha_to_coverage;
  2639. blendDesc->IndependentBlendEnable = FALSE;
  2640. for (UINT i = 0; i < MAX_COLOR_TARGET_BINDINGS; i += 1) {
  2641. D3D12_RENDER_TARGET_BLEND_DESC rtBlendDesc;
  2642. rtBlendDesc.BlendEnable = FALSE;
  2643. rtBlendDesc.LogicOpEnable = FALSE;
  2644. rtBlendDesc.SrcBlend = D3D12_BLEND_ONE;
  2645. rtBlendDesc.DestBlend = D3D12_BLEND_ZERO;
  2646. rtBlendDesc.BlendOp = D3D12_BLEND_OP_ADD;
  2647. rtBlendDesc.SrcBlendAlpha = D3D12_BLEND_ONE;
  2648. rtBlendDesc.DestBlendAlpha = D3D12_BLEND_ZERO;
  2649. rtBlendDesc.BlendOpAlpha = D3D12_BLEND_OP_ADD;
  2650. rtBlendDesc.LogicOp = D3D12_LOGIC_OP_NOOP;
  2651. rtBlendDesc.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  2652. // If target_info has more blend states, you can set IndependentBlendEnable to TRUE and assign different blend states to each render target slot
  2653. if (i < pipelineInfo->target_info.num_color_targets) {
  2654. SDL_GPUColorTargetBlendState sdlBlendState = pipelineInfo->target_info.color_target_descriptions[i].blend_state;
  2655. SDL_GPUColorComponentFlags colorWriteMask = sdlBlendState.enable_color_write_mask ?
  2656. sdlBlendState.color_write_mask :
  2657. 0xF;
  2658. rtBlendDesc.BlendEnable = sdlBlendState.enable_blend;
  2659. rtBlendDesc.SrcBlend = SDLToD3D12_BlendFactor[sdlBlendState.src_color_blendfactor];
  2660. rtBlendDesc.DestBlend = SDLToD3D12_BlendFactor[sdlBlendState.dst_color_blendfactor];
  2661. rtBlendDesc.BlendOp = SDLToD3D12_BlendOp[sdlBlendState.color_blend_op];
  2662. rtBlendDesc.SrcBlendAlpha = SDLToD3D12_BlendFactorAlpha[sdlBlendState.src_alpha_blendfactor];
  2663. rtBlendDesc.DestBlendAlpha = SDLToD3D12_BlendFactorAlpha[sdlBlendState.dst_alpha_blendfactor];
  2664. rtBlendDesc.BlendOpAlpha = SDLToD3D12_BlendOp[sdlBlendState.alpha_blend_op];
  2665. rtBlendDesc.RenderTargetWriteMask = colorWriteMask;
  2666. if (i > 0) {
  2667. blendDesc->IndependentBlendEnable = TRUE;
  2668. }
  2669. }
  2670. blendDesc->RenderTarget[i] = rtBlendDesc;
  2671. }
  2672. return true;
  2673. }
  2674. static bool D3D12_INTERNAL_ConvertDepthStencilState(SDL_GPUDepthStencilState depthStencilState, D3D12_DEPTH_STENCIL_DESC *desc)
  2675. {
  2676. if (desc == NULL) {
  2677. return false;
  2678. }
  2679. desc->DepthEnable = depthStencilState.enable_depth_test == true ? TRUE : FALSE;
  2680. desc->DepthWriteMask = depthStencilState.enable_depth_write == true ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;
  2681. desc->DepthFunc = SDLToD3D12_CompareOp[depthStencilState.compare_op];
  2682. desc->StencilEnable = depthStencilState.enable_stencil_test == true ? TRUE : FALSE;
  2683. desc->StencilReadMask = depthStencilState.compare_mask;
  2684. desc->StencilWriteMask = depthStencilState.write_mask;
  2685. desc->FrontFace.StencilFailOp = SDLToD3D12_StencilOp[depthStencilState.front_stencil_state.fail_op];
  2686. desc->FrontFace.StencilDepthFailOp = SDLToD3D12_StencilOp[depthStencilState.front_stencil_state.depth_fail_op];
  2687. desc->FrontFace.StencilPassOp = SDLToD3D12_StencilOp[depthStencilState.front_stencil_state.pass_op];
  2688. desc->FrontFace.StencilFunc = SDLToD3D12_CompareOp[depthStencilState.front_stencil_state.compare_op];
  2689. desc->BackFace.StencilFailOp = SDLToD3D12_StencilOp[depthStencilState.back_stencil_state.fail_op];
  2690. desc->BackFace.StencilDepthFailOp = SDLToD3D12_StencilOp[depthStencilState.back_stencil_state.depth_fail_op];
  2691. desc->BackFace.StencilPassOp = SDLToD3D12_StencilOp[depthStencilState.back_stencil_state.pass_op];
  2692. desc->BackFace.StencilFunc = SDLToD3D12_CompareOp[depthStencilState.back_stencil_state.compare_op];
  2693. return true;
  2694. }
  2695. static bool D3D12_INTERNAL_ConvertVertexInputState(SDL_GPUVertexInputState vertexInputState, D3D12_INPUT_ELEMENT_DESC *desc, const char *semantic)
  2696. {
  2697. if (desc == NULL || vertexInputState.num_vertex_attributes == 0) {
  2698. return false;
  2699. }
  2700. for (Uint32 i = 0; i < vertexInputState.num_vertex_attributes; i += 1) {
  2701. SDL_GPUVertexAttribute attribute = vertexInputState.vertex_attributes[i];
  2702. desc[i].SemanticName = semantic;
  2703. desc[i].SemanticIndex = attribute.location;
  2704. desc[i].Format = SDLToD3D12_VertexFormat[attribute.format];
  2705. desc[i].InputSlot = attribute.buffer_slot;
  2706. desc[i].AlignedByteOffset = attribute.offset;
  2707. desc[i].InputSlotClass = SDLToD3D12_InputRate[vertexInputState.vertex_buffer_descriptions[attribute.buffer_slot].input_rate];
  2708. desc[i].InstanceDataStepRate = (vertexInputState.vertex_buffer_descriptions[attribute.buffer_slot].input_rate == SDL_GPU_VERTEXINPUTRATE_INSTANCE)
  2709. ? 1
  2710. : 0;
  2711. }
  2712. return true;
  2713. }
  2714. static bool D3D12_INTERNAL_AssignStagingDescriptorHandle(
  2715. D3D12Renderer *renderer,
  2716. D3D12_DESCRIPTOR_HEAP_TYPE heapType,
  2717. D3D12StagingDescriptor *cpuDescriptor)
  2718. {
  2719. D3D12StagingDescriptor *descriptor;
  2720. D3D12StagingDescriptorPool *pool = renderer->stagingDescriptorPools[heapType];
  2721. SDL_LockMutex(pool->lock);
  2722. if (pool->freeDescriptorCount == 0) {
  2723. if (!D3D12_INTERNAL_ExpandStagingDescriptorPool(renderer, pool))
  2724. {
  2725. SDL_UnlockMutex(pool->lock);
  2726. return false;
  2727. }
  2728. }
  2729. descriptor = &pool->freeDescriptors[pool->freeDescriptorCount - 1];
  2730. SDL_memcpy(cpuDescriptor, descriptor, sizeof(D3D12StagingDescriptor));
  2731. pool->freeDescriptorCount -= 1;
  2732. SDL_UnlockMutex(pool->lock);
  2733. return true;
  2734. }
  2735. static SDL_GPUGraphicsPipeline *D3D12_CreateGraphicsPipeline(
  2736. SDL_GPURenderer *driverData,
  2737. const SDL_GPUGraphicsPipelineCreateInfo *createinfo)
  2738. {
  2739. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  2740. D3D12Shader *vertShader = (D3D12Shader *)createinfo->vertex_shader;
  2741. D3D12Shader *fragShader = (D3D12Shader *)createinfo->fragment_shader;
  2742. if (renderer->debug_mode) {
  2743. if (vertShader->stage != SDL_GPU_SHADERSTAGE_VERTEX) {
  2744. SDL_assert_release(!"CreateGraphicsPipeline was passed a fragment shader for the vertex stage");
  2745. }
  2746. if (fragShader->stage != SDL_GPU_SHADERSTAGE_FRAGMENT) {
  2747. SDL_assert_release(!"CreateGraphicsPipeline was passed a vertex shader for the fragment stage");
  2748. }
  2749. }
  2750. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
  2751. SDL_zero(psoDesc);
  2752. psoDesc.VS.pShaderBytecode = vertShader->bytecode;
  2753. psoDesc.VS.BytecodeLength = vertShader->bytecodeSize;
  2754. psoDesc.PS.pShaderBytecode = fragShader->bytecode;
  2755. psoDesc.PS.BytecodeLength = fragShader->bytecodeSize;
  2756. D3D12_INPUT_ELEMENT_DESC inputElementDescs[D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT];
  2757. if (createinfo->vertex_input_state.num_vertex_attributes > 0) {
  2758. psoDesc.InputLayout.pInputElementDescs = inputElementDescs;
  2759. psoDesc.InputLayout.NumElements = createinfo->vertex_input_state.num_vertex_attributes;
  2760. D3D12_INTERNAL_ConvertVertexInputState(createinfo->vertex_input_state, inputElementDescs, renderer->semantic);
  2761. }
  2762. psoDesc.PrimitiveTopologyType = SDLToD3D12_PrimitiveTopologyType[createinfo->primitive_type];
  2763. if (!D3D12_INTERNAL_ConvertRasterizerState(createinfo->rasterizer_state, &psoDesc.RasterizerState)) {
  2764. return NULL;
  2765. }
  2766. if (!D3D12_INTERNAL_ConvertBlendState(createinfo, &psoDesc.BlendState)) {
  2767. return NULL;
  2768. }
  2769. if (!D3D12_INTERNAL_ConvertDepthStencilState(createinfo->depth_stencil_state, &psoDesc.DepthStencilState)) {
  2770. return NULL;
  2771. }
  2772. D3D12GraphicsPipeline *pipeline = (D3D12GraphicsPipeline *)SDL_calloc(1, sizeof(D3D12GraphicsPipeline));
  2773. if (!pipeline) {
  2774. return NULL;
  2775. }
  2776. psoDesc.SampleMask = 0xFFFFFFFF;
  2777. psoDesc.SampleDesc.Count = SDLToD3D12_SampleCount[createinfo->multisample_state.sample_count];
  2778. psoDesc.SampleDesc.Quality = (createinfo->multisample_state.sample_count > SDL_GPU_SAMPLECOUNT_1) ? D3D12_STANDARD_MULTISAMPLE_PATTERN : 0;
  2779. if (createinfo->target_info.has_depth_stencil_target) {
  2780. psoDesc.DSVFormat = SDLToD3D12_DepthFormat[createinfo->target_info.depth_stencil_format];
  2781. }
  2782. psoDesc.NumRenderTargets = createinfo->target_info.num_color_targets;
  2783. for (uint32_t i = 0; i < createinfo->target_info.num_color_targets; i += 1) {
  2784. psoDesc.RTVFormats[i] = SDLToD3D12_TextureFormat[createinfo->target_info.color_target_descriptions[i].format];
  2785. }
  2786. // Assuming some default values or further initialization
  2787. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  2788. psoDesc.CachedPSO.CachedBlobSizeInBytes = 0;
  2789. psoDesc.CachedPSO.pCachedBlob = NULL;
  2790. psoDesc.NodeMask = 0;
  2791. D3D12GraphicsRootSignature *rootSignature = D3D12_INTERNAL_CreateGraphicsRootSignature(
  2792. renderer,
  2793. vertShader,
  2794. fragShader);
  2795. if (rootSignature == NULL) {
  2796. D3D12_INTERNAL_DestroyGraphicsPipeline(pipeline);
  2797. return NULL;
  2798. }
  2799. pipeline->rootSignature = rootSignature;
  2800. psoDesc.pRootSignature = rootSignature->handle;
  2801. ID3D12PipelineState *pipelineState;
  2802. HRESULT res = ID3D12Device_CreateGraphicsPipelineState(
  2803. renderer->device,
  2804. &psoDesc,
  2805. D3D_GUID(D3D_IID_ID3D12PipelineState),
  2806. (void **)&pipelineState);
  2807. if (FAILED(res)) {
  2808. D3D12_INTERNAL_SetError(renderer, "Could not create graphics pipeline state", res);
  2809. D3D12_INTERNAL_DestroyGraphicsPipeline(pipeline);
  2810. return NULL;
  2811. }
  2812. pipeline->pipelineState = pipelineState;
  2813. for (Uint32 i = 0; i < createinfo->vertex_input_state.num_vertex_buffers; i += 1) {
  2814. pipeline->vertexStrides[createinfo->vertex_input_state.vertex_buffer_descriptions[i].slot] =
  2815. createinfo->vertex_input_state.vertex_buffer_descriptions[i].pitch;
  2816. }
  2817. pipeline->primitiveType = createinfo->primitive_type;
  2818. pipeline->header.num_vertex_samplers = vertShader->num_samplers;
  2819. pipeline->header.num_vertex_storage_textures = vertShader->numStorageTextures;
  2820. pipeline->header.num_vertex_storage_buffers = vertShader->numStorageBuffers;
  2821. pipeline->header.num_vertex_uniform_buffers = vertShader->numUniformBuffers;
  2822. pipeline->header.num_fragment_samplers = fragShader->num_samplers;
  2823. pipeline->header.num_fragment_storage_textures = fragShader->numStorageTextures;
  2824. pipeline->header.num_fragment_storage_buffers = fragShader->numStorageBuffers;
  2825. pipeline->header.num_fragment_uniform_buffers = fragShader->numUniformBuffers;
  2826. SDL_SetAtomicInt(&pipeline->referenceCount, 0);
  2827. if (renderer->debug_mode && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_GRAPHICSPIPELINE_CREATE_NAME_STRING)) {
  2828. D3D12_INTERNAL_SetPipelineStateName(
  2829. renderer,
  2830. pipeline->pipelineState,
  2831. SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_GRAPHICSPIPELINE_CREATE_NAME_STRING, NULL));
  2832. }
  2833. return (SDL_GPUGraphicsPipeline *)pipeline;
  2834. }
  2835. static SDL_GPUSampler *D3D12_CreateSampler(
  2836. SDL_GPURenderer *driverData,
  2837. const SDL_GPUSamplerCreateInfo *createinfo)
  2838. {
  2839. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  2840. D3D12Sampler *sampler = (D3D12Sampler *)SDL_calloc(1, sizeof(D3D12Sampler));
  2841. if (!sampler) {
  2842. return NULL;
  2843. }
  2844. D3D12_SAMPLER_DESC samplerDesc;
  2845. samplerDesc.Filter = SDLToD3D12_Filter(
  2846. createinfo->min_filter,
  2847. createinfo->mag_filter,
  2848. createinfo->mipmap_mode,
  2849. createinfo->enable_compare,
  2850. createinfo->enable_anisotropy);
  2851. samplerDesc.AddressU = SDLToD3D12_SamplerAddressMode[createinfo->address_mode_u];
  2852. samplerDesc.AddressV = SDLToD3D12_SamplerAddressMode[createinfo->address_mode_v];
  2853. samplerDesc.AddressW = SDLToD3D12_SamplerAddressMode[createinfo->address_mode_w];
  2854. samplerDesc.MaxAnisotropy = (Uint32)createinfo->max_anisotropy;
  2855. samplerDesc.ComparisonFunc = SDLToD3D12_CompareOp[createinfo->compare_op];
  2856. samplerDesc.MinLOD = createinfo->min_lod;
  2857. samplerDesc.MaxLOD = createinfo->max_lod;
  2858. samplerDesc.MipLODBias = createinfo->mip_lod_bias;
  2859. samplerDesc.BorderColor[0] = 0;
  2860. samplerDesc.BorderColor[1] = 0;
  2861. samplerDesc.BorderColor[2] = 0;
  2862. samplerDesc.BorderColor[3] = 0;
  2863. D3D12_INTERNAL_AssignStagingDescriptorHandle(
  2864. renderer,
  2865. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
  2866. &sampler->handle);
  2867. ID3D12Device_CreateSampler(
  2868. renderer->device,
  2869. &samplerDesc,
  2870. sampler->handle.cpuHandle);
  2871. sampler->createInfo = *createinfo;
  2872. SDL_SetAtomicInt(&sampler->referenceCount, 0);
  2873. // Ignore name property because it is not applicable to D3D12.
  2874. return (SDL_GPUSampler *)sampler;
  2875. }
  2876. static SDL_GPUShader *D3D12_CreateShader(
  2877. SDL_GPURenderer *driverData,
  2878. const SDL_GPUShaderCreateInfo *createinfo)
  2879. {
  2880. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  2881. void *bytecode;
  2882. size_t bytecodeSize;
  2883. D3D12Shader *shader;
  2884. if (!D3D12_INTERNAL_CreateShaderBytecode(
  2885. renderer,
  2886. createinfo->code,
  2887. createinfo->code_size,
  2888. createinfo->format,
  2889. &bytecode,
  2890. &bytecodeSize)) {
  2891. return NULL;
  2892. }
  2893. shader = (D3D12Shader *)SDL_calloc(1, sizeof(D3D12Shader));
  2894. if (!shader) {
  2895. SDL_free(bytecode);
  2896. return NULL;
  2897. }
  2898. shader->stage = createinfo->stage;
  2899. shader->num_samplers = createinfo->num_samplers;
  2900. shader->numStorageBuffers = createinfo->num_storage_buffers;
  2901. shader->numStorageTextures = createinfo->num_storage_textures;
  2902. shader->numUniformBuffers = createinfo->num_uniform_buffers;
  2903. shader->bytecode = bytecode;
  2904. shader->bytecodeSize = bytecodeSize;
  2905. // Ignore name property because it is not applicable to D3D12.
  2906. return (SDL_GPUShader *)shader;
  2907. }
  2908. static D3D12Texture *D3D12_INTERNAL_CreateTexture(
  2909. D3D12Renderer *renderer,
  2910. const SDL_GPUTextureCreateInfo *createinfo,
  2911. bool isSwapchainTexture,
  2912. const char *debugName)
  2913. {
  2914. D3D12Texture *texture;
  2915. ID3D12Resource *handle;
  2916. D3D12_HEAP_PROPERTIES heapProperties;
  2917. D3D12_HEAP_FLAGS heapFlags = (D3D12_HEAP_FLAGS)0;
  2918. D3D12_RESOURCE_DESC desc;
  2919. D3D12_RESOURCE_FLAGS resourceFlags = (D3D12_RESOURCE_FLAGS)0;
  2920. D3D12_RESOURCE_STATES initialState = (D3D12_RESOURCE_STATES)0;
  2921. D3D12_CLEAR_VALUE clearValue;
  2922. DXGI_FORMAT format;
  2923. bool useClearValue = false;
  2924. bool needsSRV =
  2925. (createinfo->usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) ||
  2926. (createinfo->usage & SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ) ||
  2927. (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ);
  2928. bool needsUAV =
  2929. (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) ||
  2930. (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE);
  2931. HRESULT res;
  2932. texture = (D3D12Texture *)SDL_calloc(1, sizeof(D3D12Texture));
  2933. if (!texture) {
  2934. return NULL;
  2935. }
  2936. Uint32 layerCount = createinfo->type == SDL_GPU_TEXTURETYPE_3D ? 1 : createinfo->layer_count_or_depth;
  2937. Uint32 depth = createinfo->type == SDL_GPU_TEXTURETYPE_3D ? createinfo->layer_count_or_depth : 1;
  2938. bool isMultisample = createinfo->sample_count > SDL_GPU_SAMPLECOUNT_1;
  2939. format = SDLToD3D12_TextureFormat[createinfo->format];
  2940. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  2941. resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
  2942. useClearValue = true;
  2943. clearValue.Format = format;
  2944. clearValue.Color[0] = SDL_GetFloatProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_D3D12_CLEAR_R_FLOAT, 0);
  2945. clearValue.Color[1] = SDL_GetFloatProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_D3D12_CLEAR_G_FLOAT, 0);
  2946. clearValue.Color[2] = SDL_GetFloatProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_D3D12_CLEAR_B_FLOAT, 0);
  2947. clearValue.Color[3] = SDL_GetFloatProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_D3D12_CLEAR_A_FLOAT, 0);
  2948. }
  2949. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  2950. resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
  2951. useClearValue = true;
  2952. clearValue.Format = SDLToD3D12_DepthFormat[createinfo->format];
  2953. clearValue.DepthStencil.Depth = SDL_GetFloatProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_D3D12_CLEAR_DEPTH_FLOAT, 0);
  2954. clearValue.DepthStencil.Stencil = (UINT8)SDL_GetNumberProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_D3D12_CLEAR_STENCIL_NUMBER, 0);
  2955. format = needsSRV ? SDLToD3D12_TypelessFormat[createinfo->format] : SDLToD3D12_DepthFormat[createinfo->format];
  2956. }
  2957. if (needsUAV) {
  2958. resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  2959. }
  2960. heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;
  2961. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  2962. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  2963. heapProperties.CreationNodeMask = 0; // We don't do multi-adapter operation
  2964. heapProperties.VisibleNodeMask = 0; // We don't do multi-adapter operation
  2965. heapFlags = isSwapchainTexture ? D3D12_HEAP_FLAG_ALLOW_DISPLAY : D3D12_HEAP_FLAG_NONE;
  2966. if (createinfo->type != SDL_GPU_TEXTURETYPE_3D) {
  2967. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  2968. desc.Alignment = isSwapchainTexture ? 0 : isMultisample ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
  2969. desc.Width = createinfo->width;
  2970. desc.Height = createinfo->height;
  2971. desc.DepthOrArraySize = (UINT16)createinfo->layer_count_or_depth;
  2972. desc.MipLevels = (UINT16)createinfo->num_levels;
  2973. desc.Format = format;
  2974. desc.SampleDesc.Count = SDLToD3D12_SampleCount[createinfo->sample_count];
  2975. desc.SampleDesc.Quality = isMultisample ? D3D12_STANDARD_MULTISAMPLE_PATTERN : 0;
  2976. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // Apparently this is the most efficient choice
  2977. desc.Flags = resourceFlags;
  2978. } else {
  2979. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
  2980. desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
  2981. desc.Width = createinfo->width;
  2982. desc.Height = createinfo->height;
  2983. desc.DepthOrArraySize = (UINT16)createinfo->layer_count_or_depth;
  2984. desc.MipLevels = (UINT16)createinfo->num_levels;
  2985. desc.Format = format;
  2986. desc.SampleDesc.Count = 1;
  2987. desc.SampleDesc.Quality = 0;
  2988. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  2989. desc.Flags = resourceFlags;
  2990. }
  2991. initialState = isSwapchainTexture ? D3D12_RESOURCE_STATE_PRESENT : D3D12_INTERNAL_DefaultTextureResourceState(createinfo->usage);
  2992. res = ID3D12Device_CreateCommittedResource(
  2993. renderer->device,
  2994. &heapProperties,
  2995. heapFlags,
  2996. &desc,
  2997. initialState,
  2998. useClearValue ? &clearValue : NULL,
  2999. D3D_GUID(D3D_IID_ID3D12Resource),
  3000. (void **)&handle);
  3001. if (FAILED(res)) {
  3002. D3D12_INTERNAL_SetError(renderer, "Failed to create texture!", res);
  3003. D3D12_INTERNAL_DestroyTexture(texture);
  3004. return NULL;
  3005. }
  3006. texture->resource = handle;
  3007. // Create the SRV if applicable
  3008. if (needsSRV) {
  3009. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  3010. D3D12_INTERNAL_AssignStagingDescriptorHandle(
  3011. renderer,
  3012. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3013. &texture->srvHandle);
  3014. srvDesc.Format = SDLToD3D12_TextureFormat[createinfo->format];
  3015. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  3016. if (createinfo->type == SDL_GPU_TEXTURETYPE_CUBE) {
  3017. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
  3018. srvDesc.TextureCube.MipLevels = createinfo->num_levels;
  3019. srvDesc.TextureCube.MostDetailedMip = 0;
  3020. srvDesc.TextureCube.ResourceMinLODClamp = 0;
  3021. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  3022. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
  3023. srvDesc.TextureCubeArray.MipLevels = createinfo->num_levels;
  3024. srvDesc.TextureCubeArray.MostDetailedMip = 0;
  3025. srvDesc.TextureCubeArray.First2DArrayFace = 0;
  3026. srvDesc.TextureCubeArray.NumCubes = createinfo->layer_count_or_depth / 6;
  3027. srvDesc.TextureCubeArray.ResourceMinLODClamp = 0;
  3028. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY) {
  3029. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
  3030. srvDesc.Texture2DArray.MipLevels = createinfo->num_levels;
  3031. srvDesc.Texture2DArray.MostDetailedMip = 0;
  3032. srvDesc.Texture2DArray.FirstArraySlice = 0;
  3033. srvDesc.Texture2DArray.ArraySize = layerCount;
  3034. srvDesc.Texture2DArray.ResourceMinLODClamp = 0;
  3035. srvDesc.Texture2DArray.PlaneSlice = 0;
  3036. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_3D) {
  3037. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
  3038. srvDesc.Texture3D.MipLevels = createinfo->num_levels;
  3039. srvDesc.Texture3D.MostDetailedMip = 0;
  3040. srvDesc.Texture3D.ResourceMinLODClamp = 0; // default behavior
  3041. } else {
  3042. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  3043. srvDesc.Texture2D.MipLevels = createinfo->num_levels;
  3044. srvDesc.Texture2D.MostDetailedMip = 0;
  3045. srvDesc.Texture2D.PlaneSlice = 0;
  3046. srvDesc.Texture2D.ResourceMinLODClamp = 0; // default behavior
  3047. }
  3048. ID3D12Device_CreateShaderResourceView(
  3049. renderer->device,
  3050. handle,
  3051. &srvDesc,
  3052. texture->srvHandle.cpuHandle);
  3053. }
  3054. SDL_SetAtomicInt(&texture->referenceCount, 0);
  3055. texture->subresourceCount = createinfo->num_levels * layerCount;
  3056. texture->subresources = (D3D12TextureSubresource *)SDL_calloc(
  3057. texture->subresourceCount, sizeof(D3D12TextureSubresource));
  3058. if (!texture->subresources) {
  3059. D3D12_INTERNAL_DestroyTexture(texture);
  3060. return NULL;
  3061. }
  3062. for (Uint32 layerIndex = 0; layerIndex < layerCount; layerIndex += 1) {
  3063. for (Uint32 levelIndex = 0; levelIndex < createinfo->num_levels; levelIndex += 1) {
  3064. Uint32 subresourceIndex = D3D12_INTERNAL_CalcSubresource(
  3065. levelIndex,
  3066. layerIndex,
  3067. createinfo->num_levels);
  3068. texture->subresources[subresourceIndex].parent = texture;
  3069. texture->subresources[subresourceIndex].layer = layerIndex;
  3070. texture->subresources[subresourceIndex].level = levelIndex;
  3071. texture->subresources[subresourceIndex].depth = depth;
  3072. texture->subresources[subresourceIndex].index = subresourceIndex;
  3073. texture->subresources[subresourceIndex].rtvHandles = NULL;
  3074. texture->subresources[subresourceIndex].uavHandle.heap = NULL;
  3075. texture->subresources[subresourceIndex].dsvHandle.heap = NULL;
  3076. // Create RTV if needed
  3077. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  3078. texture->subresources[subresourceIndex].rtvHandles = (D3D12StagingDescriptor *)SDL_calloc(depth, sizeof(D3D12StagingDescriptor));
  3079. for (Uint32 depthIndex = 0; depthIndex < depth; depthIndex += 1) {
  3080. D3D12_RENDER_TARGET_VIEW_DESC rtvDesc;
  3081. D3D12_INTERNAL_AssignStagingDescriptorHandle(
  3082. renderer,
  3083. D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  3084. &texture->subresources[subresourceIndex].rtvHandles[depthIndex]);
  3085. rtvDesc.Format = SDLToD3D12_TextureFormat[createinfo->format];
  3086. if (createinfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY || createinfo->type == SDL_GPU_TEXTURETYPE_CUBE || createinfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  3087. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
  3088. rtvDesc.Texture2DArray.MipSlice = levelIndex;
  3089. rtvDesc.Texture2DArray.FirstArraySlice = layerIndex;
  3090. rtvDesc.Texture2DArray.ArraySize = 1;
  3091. rtvDesc.Texture2DArray.PlaneSlice = 0;
  3092. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_3D) {
  3093. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D;
  3094. rtvDesc.Texture3D.MipSlice = levelIndex;
  3095. rtvDesc.Texture3D.FirstWSlice = depthIndex;
  3096. rtvDesc.Texture3D.WSize = 1;
  3097. } else if (isMultisample) {
  3098. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
  3099. } else {
  3100. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
  3101. rtvDesc.Texture2D.MipSlice = levelIndex;
  3102. rtvDesc.Texture2D.PlaneSlice = 0;
  3103. }
  3104. ID3D12Device_CreateRenderTargetView(
  3105. renderer->device,
  3106. texture->resource,
  3107. &rtvDesc,
  3108. texture->subresources[subresourceIndex].rtvHandles[depthIndex].cpuHandle);
  3109. }
  3110. }
  3111. // Create DSV if needed
  3112. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  3113. D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc;
  3114. D3D12_INTERNAL_AssignStagingDescriptorHandle(
  3115. renderer,
  3116. D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  3117. &texture->subresources[subresourceIndex].dsvHandle);
  3118. dsvDesc.Format = SDLToD3D12_DepthFormat[createinfo->format];
  3119. dsvDesc.Flags = (D3D12_DSV_FLAGS)0;
  3120. if (isMultisample) {
  3121. dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS;
  3122. } else {
  3123. dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
  3124. dsvDesc.Texture2D.MipSlice = levelIndex;
  3125. }
  3126. ID3D12Device_CreateDepthStencilView(
  3127. renderer->device,
  3128. texture->resource,
  3129. &dsvDesc,
  3130. texture->subresources[subresourceIndex].dsvHandle.cpuHandle);
  3131. }
  3132. // Create subresource UAV if necessary
  3133. if (needsUAV) {
  3134. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc;
  3135. D3D12_INTERNAL_AssignStagingDescriptorHandle(
  3136. renderer,
  3137. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3138. &texture->subresources[subresourceIndex].uavHandle);
  3139. uavDesc.Format = SDLToD3D12_TextureFormat[createinfo->format];
  3140. if (createinfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY || createinfo->type == SDL_GPU_TEXTURETYPE_CUBE || createinfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  3141. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
  3142. uavDesc.Texture2DArray.MipSlice = levelIndex;
  3143. uavDesc.Texture2DArray.FirstArraySlice = layerIndex;
  3144. uavDesc.Texture2DArray.ArraySize = 1;
  3145. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_3D) {
  3146. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
  3147. uavDesc.Texture3D.MipSlice = levelIndex;
  3148. uavDesc.Texture3D.FirstWSlice = 0;
  3149. uavDesc.Texture3D.WSize = depth;
  3150. } else {
  3151. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
  3152. uavDesc.Texture2D.MipSlice = levelIndex;
  3153. uavDesc.Texture2D.PlaneSlice = 0;
  3154. }
  3155. ID3D12Device_CreateUnorderedAccessView(
  3156. renderer->device,
  3157. texture->resource,
  3158. NULL,
  3159. &uavDesc,
  3160. texture->subresources[subresourceIndex].uavHandle.cpuHandle);
  3161. }
  3162. }
  3163. }
  3164. D3D12_INTERNAL_SetResourceName(
  3165. renderer,
  3166. texture->resource,
  3167. debugName);
  3168. return texture;
  3169. }
  3170. static SDL_GPUTexture *D3D12_CreateTexture(
  3171. SDL_GPURenderer *driverData,
  3172. const SDL_GPUTextureCreateInfo *createinfo)
  3173. {
  3174. D3D12TextureContainer *container = (D3D12TextureContainer *)SDL_calloc(1, sizeof(D3D12TextureContainer));
  3175. if (!container) {
  3176. return NULL;
  3177. }
  3178. // Copy properties so we don't lose information when the client destroys them
  3179. container->header.info = *createinfo;
  3180. container->header.info.props = SDL_CreateProperties();
  3181. if (createinfo->props) {
  3182. SDL_CopyProperties(createinfo->props, container->header.info.props);
  3183. }
  3184. container->textureCapacity = 1;
  3185. container->textureCount = 1;
  3186. container->textures = (D3D12Texture **)SDL_calloc(
  3187. container->textureCapacity, sizeof(D3D12Texture *));
  3188. if (!container->textures) {
  3189. SDL_free(container);
  3190. return NULL;
  3191. }
  3192. container->debugName = NULL;
  3193. if (SDL_HasProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_NAME_STRING)) {
  3194. container->debugName = SDL_strdup(SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_NAME_STRING, NULL));
  3195. }
  3196. container->canBeCycled = true;
  3197. D3D12Texture *texture = D3D12_INTERNAL_CreateTexture(
  3198. (D3D12Renderer *)driverData,
  3199. createinfo,
  3200. false,
  3201. container->debugName);
  3202. if (!texture) {
  3203. SDL_free(container->textures);
  3204. SDL_free(container);
  3205. return NULL;
  3206. }
  3207. container->textures[0] = texture;
  3208. container->activeTexture = texture;
  3209. texture->container = container;
  3210. texture->containerIndex = 0;
  3211. return (SDL_GPUTexture *)container;
  3212. }
  3213. static D3D12Buffer *D3D12_INTERNAL_CreateBuffer(
  3214. D3D12Renderer *renderer,
  3215. SDL_GPUBufferUsageFlags usageFlags,
  3216. Uint32 size,
  3217. D3D12BufferType type,
  3218. const char *debugName)
  3219. {
  3220. D3D12Buffer *buffer;
  3221. ID3D12Resource *handle;
  3222. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc;
  3223. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  3224. D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc;
  3225. D3D12_HEAP_PROPERTIES heapProperties;
  3226. D3D12_RESOURCE_DESC desc;
  3227. D3D12_HEAP_FLAGS heapFlags = (D3D12_HEAP_FLAGS)0;
  3228. D3D12_RESOURCE_FLAGS resourceFlags = (D3D12_RESOURCE_FLAGS)0;
  3229. D3D12_RESOURCE_STATES initialState = D3D12_RESOURCE_STATE_COMMON;
  3230. HRESULT res;
  3231. buffer = (D3D12Buffer *)SDL_calloc(1, sizeof(D3D12Buffer));
  3232. if (!buffer) {
  3233. return NULL;
  3234. }
  3235. if (usageFlags & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE) {
  3236. resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  3237. }
  3238. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  3239. if (usageFlags & SDL_GPU_BUFFERUSAGE_INDIRECT) {
  3240. resourceFlags |= D3D12XBOX_RESOURCE_FLAG_ALLOW_INDIRECT_BUFFER;
  3241. }
  3242. #endif
  3243. heapProperties.CreationNodeMask = 0; // We don't do multi-adapter operation
  3244. heapProperties.VisibleNodeMask = 0; // We don't do multi-adapter operation
  3245. if (type == D3D12_BUFFER_TYPE_GPU) {
  3246. heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;
  3247. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  3248. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  3249. heapFlags = D3D12_HEAP_FLAG_NONE;
  3250. } else if (type == D3D12_BUFFER_TYPE_UPLOAD) {
  3251. heapProperties.Type = D3D12_HEAP_TYPE_UPLOAD;
  3252. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  3253. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  3254. heapFlags = D3D12_HEAP_FLAG_NONE;
  3255. initialState = D3D12_RESOURCE_STATE_GENERIC_READ;
  3256. } else if (type == D3D12_BUFFER_TYPE_DOWNLOAD) {
  3257. heapProperties.Type = D3D12_HEAP_TYPE_READBACK;
  3258. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  3259. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  3260. heapFlags = D3D12_HEAP_FLAG_NONE;
  3261. initialState = D3D12_RESOURCE_STATE_COPY_DEST;
  3262. } else if (type == D3D12_BUFFER_TYPE_UNIFORM) {
  3263. // D3D12 is badly designed, so we have to check if the fast path for uniform buffers is enabled
  3264. if (renderer->GPUUploadHeapSupported) {
  3265. heapProperties.Type = D3D12_HEAP_TYPE_GPU_UPLOAD;
  3266. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  3267. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  3268. } else {
  3269. heapProperties.Type = D3D12_HEAP_TYPE_UPLOAD;
  3270. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  3271. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  3272. initialState = D3D12_RESOURCE_STATE_GENERIC_READ;
  3273. }
  3274. heapFlags = D3D12_HEAP_FLAG_NONE;
  3275. } else {
  3276. SET_STRING_ERROR_AND_RETURN("Unrecognized buffer type!", NULL);
  3277. }
  3278. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  3279. desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
  3280. desc.Width = size;
  3281. desc.Height = 1;
  3282. desc.DepthOrArraySize = 1;
  3283. desc.MipLevels = 1;
  3284. desc.Format = DXGI_FORMAT_UNKNOWN;
  3285. desc.SampleDesc.Count = 1;
  3286. desc.SampleDesc.Quality = 0;
  3287. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  3288. desc.Flags = resourceFlags;
  3289. res = ID3D12Device_CreateCommittedResource(
  3290. renderer->device,
  3291. &heapProperties,
  3292. heapFlags,
  3293. &desc,
  3294. initialState,
  3295. NULL,
  3296. D3D_GUID(D3D_IID_ID3D12Resource),
  3297. (void **)&handle);
  3298. if (FAILED(res)) {
  3299. D3D12_INTERNAL_SetError(renderer, "Could not create buffer!", res);
  3300. D3D12_INTERNAL_DestroyBuffer(buffer);
  3301. return NULL;
  3302. }
  3303. buffer->handle = handle;
  3304. SDL_SetAtomicInt(&buffer->referenceCount, 0);
  3305. buffer->uavDescriptor.heap = NULL;
  3306. buffer->srvDescriptor.heap = NULL;
  3307. buffer->cbvDescriptor.heap = NULL;
  3308. if (usageFlags & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE) {
  3309. D3D12_INTERNAL_AssignStagingDescriptorHandle(
  3310. renderer,
  3311. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3312. &buffer->uavDescriptor);
  3313. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  3314. uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  3315. uavDesc.Buffer.FirstElement = 0;
  3316. uavDesc.Buffer.NumElements = size / sizeof(Uint32);
  3317. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  3318. uavDesc.Buffer.CounterOffsetInBytes = 0; // TODO: support counters?
  3319. uavDesc.Buffer.StructureByteStride = 0;
  3320. // Create UAV
  3321. ID3D12Device_CreateUnorderedAccessView(
  3322. renderer->device,
  3323. handle,
  3324. NULL, // TODO: support counters?
  3325. &uavDesc,
  3326. buffer->uavDescriptor.cpuHandle);
  3327. }
  3328. if (
  3329. (usageFlags & SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ) ||
  3330. (usageFlags & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ)) {
  3331. D3D12_INTERNAL_AssignStagingDescriptorHandle(
  3332. renderer,
  3333. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3334. &buffer->srvDescriptor);
  3335. srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  3336. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  3337. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
  3338. srvDesc.Buffer.FirstElement = 0;
  3339. srvDesc.Buffer.NumElements = size / sizeof(Uint32);
  3340. srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
  3341. srvDesc.Buffer.StructureByteStride = 0;
  3342. // Create SRV
  3343. ID3D12Device_CreateShaderResourceView(
  3344. renderer->device,
  3345. handle,
  3346. &srvDesc,
  3347. buffer->srvDescriptor.cpuHandle);
  3348. }
  3349. // FIXME: we may not need a CBV since we use root descriptors
  3350. if (type == D3D12_BUFFER_TYPE_UNIFORM) {
  3351. D3D12_INTERNAL_AssignStagingDescriptorHandle(
  3352. renderer,
  3353. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3354. &buffer->cbvDescriptor);
  3355. cbvDesc.BufferLocation = ID3D12Resource_GetGPUVirtualAddress(handle);
  3356. cbvDesc.SizeInBytes = size;
  3357. // Create CBV
  3358. ID3D12Device_CreateConstantBufferView(
  3359. renderer->device,
  3360. &cbvDesc,
  3361. buffer->cbvDescriptor.cpuHandle);
  3362. }
  3363. buffer->virtualAddress = 0;
  3364. if (type == D3D12_BUFFER_TYPE_GPU || type == D3D12_BUFFER_TYPE_UNIFORM) {
  3365. buffer->virtualAddress = ID3D12Resource_GetGPUVirtualAddress(buffer->handle);
  3366. }
  3367. buffer->mapPointer = NULL;
  3368. // Persistently map upload buffers
  3369. if (type == D3D12_BUFFER_TYPE_UPLOAD) {
  3370. res = ID3D12Resource_Map(
  3371. buffer->handle,
  3372. 0,
  3373. NULL,
  3374. (void **)&buffer->mapPointer);
  3375. if (FAILED(res)) {
  3376. D3D12_INTERNAL_SetError(renderer, "Failed to map upload buffer!", res);
  3377. D3D12_INTERNAL_DestroyBuffer(buffer);
  3378. return NULL;
  3379. }
  3380. }
  3381. buffer->container = NULL;
  3382. buffer->containerIndex = 0;
  3383. buffer->transitioned = initialState != D3D12_RESOURCE_STATE_COMMON;
  3384. SDL_SetAtomicInt(&buffer->referenceCount, 0);
  3385. D3D12_INTERNAL_SetResourceName(
  3386. renderer,
  3387. buffer->handle,
  3388. debugName);
  3389. return buffer;
  3390. }
  3391. static D3D12BufferContainer *D3D12_INTERNAL_CreateBufferContainer(
  3392. D3D12Renderer *renderer,
  3393. SDL_GPUBufferUsageFlags usageFlags,
  3394. Uint32 size,
  3395. D3D12BufferType type,
  3396. const char *debugName)
  3397. {
  3398. D3D12BufferContainer *container;
  3399. D3D12Buffer *buffer;
  3400. container = (D3D12BufferContainer *)SDL_calloc(1, sizeof(D3D12BufferContainer));
  3401. if (!container) {
  3402. return NULL;
  3403. }
  3404. container->usage = usageFlags;
  3405. container->size = size;
  3406. container->type = type;
  3407. container->bufferCapacity = 1;
  3408. container->bufferCount = 1;
  3409. container->buffers = (D3D12Buffer **)SDL_calloc(
  3410. container->bufferCapacity, sizeof(D3D12Buffer *));
  3411. if (!container->buffers) {
  3412. SDL_free(container);
  3413. return NULL;
  3414. }
  3415. container->debugName = NULL;
  3416. buffer = D3D12_INTERNAL_CreateBuffer(
  3417. renderer,
  3418. usageFlags,
  3419. size,
  3420. type,
  3421. debugName);
  3422. if (buffer == NULL) {
  3423. SDL_free(container->buffers);
  3424. SDL_free(container);
  3425. return NULL;
  3426. }
  3427. container->activeBuffer = buffer;
  3428. container->buffers[0] = buffer;
  3429. buffer->container = container;
  3430. buffer->containerIndex = 0;
  3431. if (debugName != NULL) {
  3432. container->debugName = SDL_strdup(debugName);
  3433. }
  3434. return container;
  3435. }
  3436. static SDL_GPUBuffer *D3D12_CreateBuffer(
  3437. SDL_GPURenderer *driverData,
  3438. SDL_GPUBufferUsageFlags usageFlags,
  3439. Uint32 size,
  3440. const char *debugName)
  3441. {
  3442. return (SDL_GPUBuffer *)D3D12_INTERNAL_CreateBufferContainer(
  3443. (D3D12Renderer *)driverData,
  3444. usageFlags,
  3445. size,
  3446. D3D12_BUFFER_TYPE_GPU,
  3447. debugName);
  3448. }
  3449. static SDL_GPUTransferBuffer *D3D12_CreateTransferBuffer(
  3450. SDL_GPURenderer *driverData,
  3451. SDL_GPUTransferBufferUsage usage,
  3452. Uint32 size,
  3453. const char *debugName)
  3454. {
  3455. return (SDL_GPUTransferBuffer *)D3D12_INTERNAL_CreateBufferContainer(
  3456. (D3D12Renderer *)driverData,
  3457. 0,
  3458. size,
  3459. usage == SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD ? D3D12_BUFFER_TYPE_UPLOAD : D3D12_BUFFER_TYPE_DOWNLOAD,
  3460. debugName);
  3461. }
  3462. // Disposal
  3463. static void D3D12_ReleaseTexture(
  3464. SDL_GPURenderer *driverData,
  3465. SDL_GPUTexture *texture)
  3466. {
  3467. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3468. D3D12TextureContainer *container = (D3D12TextureContainer *)texture;
  3469. D3D12_INTERNAL_ReleaseTextureContainer(
  3470. renderer,
  3471. container);
  3472. }
  3473. static void D3D12_ReleaseSampler(
  3474. SDL_GPURenderer *driverData,
  3475. SDL_GPUSampler *sampler)
  3476. {
  3477. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3478. D3D12Sampler *d3d12Sampler = (D3D12Sampler *)sampler;
  3479. SDL_LockMutex(renderer->disposeLock);
  3480. EXPAND_ARRAY_IF_NEEDED(
  3481. renderer->samplersToDestroy,
  3482. D3D12Sampler *,
  3483. renderer->samplersToDestroyCount + 1,
  3484. renderer->samplersToDestroyCapacity,
  3485. renderer->samplersToDestroyCapacity * 2);
  3486. renderer->samplersToDestroy[renderer->samplersToDestroyCount] = d3d12Sampler;
  3487. renderer->samplersToDestroyCount += 1;
  3488. SDL_UnlockMutex(renderer->disposeLock);
  3489. }
  3490. static void D3D12_ReleaseBuffer(
  3491. SDL_GPURenderer *driverData,
  3492. SDL_GPUBuffer *buffer)
  3493. {
  3494. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3495. D3D12BufferContainer *bufferContainer = (D3D12BufferContainer *)buffer;
  3496. D3D12_INTERNAL_ReleaseBufferContainer(
  3497. renderer,
  3498. bufferContainer);
  3499. }
  3500. static void D3D12_ReleaseTransferBuffer(
  3501. SDL_GPURenderer *driverData,
  3502. SDL_GPUTransferBuffer *transferBuffer)
  3503. {
  3504. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3505. D3D12BufferContainer *transferBufferContainer = (D3D12BufferContainer *)transferBuffer;
  3506. D3D12_INTERNAL_ReleaseBufferContainer(
  3507. renderer,
  3508. transferBufferContainer);
  3509. }
  3510. static void D3D12_ReleaseShader(
  3511. SDL_GPURenderer *driverData,
  3512. SDL_GPUShader *shader)
  3513. {
  3514. /* D3D12Renderer *renderer = (D3D12Renderer *)driverData; */
  3515. D3D12Shader *d3d12shader = (D3D12Shader *)shader;
  3516. if (d3d12shader->bytecode) {
  3517. SDL_free(d3d12shader->bytecode);
  3518. d3d12shader->bytecode = NULL;
  3519. }
  3520. SDL_free(d3d12shader);
  3521. }
  3522. static void D3D12_ReleaseComputePipeline(
  3523. SDL_GPURenderer *driverData,
  3524. SDL_GPUComputePipeline *computePipeline)
  3525. {
  3526. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3527. D3D12ComputePipeline *d3d12ComputePipeline = (D3D12ComputePipeline *)computePipeline;
  3528. SDL_LockMutex(renderer->disposeLock);
  3529. EXPAND_ARRAY_IF_NEEDED(
  3530. renderer->computePipelinesToDestroy,
  3531. D3D12ComputePipeline *,
  3532. renderer->computePipelinesToDestroyCount + 1,
  3533. renderer->computePipelinesToDestroyCapacity,
  3534. renderer->computePipelinesToDestroyCapacity * 2);
  3535. renderer->computePipelinesToDestroy[renderer->computePipelinesToDestroyCount] = d3d12ComputePipeline;
  3536. renderer->computePipelinesToDestroyCount += 1;
  3537. SDL_UnlockMutex(renderer->disposeLock);
  3538. }
  3539. static void D3D12_ReleaseGraphicsPipeline(
  3540. SDL_GPURenderer *driverData,
  3541. SDL_GPUGraphicsPipeline *graphicsPipeline)
  3542. {
  3543. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3544. D3D12GraphicsPipeline *d3d12GraphicsPipeline = (D3D12GraphicsPipeline *)graphicsPipeline;
  3545. SDL_LockMutex(renderer->disposeLock);
  3546. EXPAND_ARRAY_IF_NEEDED(
  3547. renderer->graphicsPipelinesToDestroy,
  3548. D3D12GraphicsPipeline *,
  3549. renderer->graphicsPipelinesToDestroyCount + 1,
  3550. renderer->graphicsPipelinesToDestroyCapacity,
  3551. renderer->graphicsPipelinesToDestroyCapacity * 2);
  3552. renderer->graphicsPipelinesToDestroy[renderer->graphicsPipelinesToDestroyCount] = d3d12GraphicsPipeline;
  3553. renderer->graphicsPipelinesToDestroyCount += 1;
  3554. SDL_UnlockMutex(renderer->disposeLock);
  3555. }
  3556. static void D3D12_INTERNAL_ReleaseBlitPipelines(SDL_GPURenderer *driverData)
  3557. {
  3558. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3559. D3D12_ReleaseSampler(driverData, renderer->blitLinearSampler);
  3560. D3D12_ReleaseSampler(driverData, renderer->blitNearestSampler);
  3561. D3D12_ReleaseShader(driverData, renderer->blitVertexShader);
  3562. D3D12_ReleaseShader(driverData, renderer->blitFrom2DShader);
  3563. D3D12_ReleaseShader(driverData, renderer->blitFrom2DArrayShader);
  3564. D3D12_ReleaseShader(driverData, renderer->blitFrom3DShader);
  3565. D3D12_ReleaseShader(driverData, renderer->blitFromCubeShader);
  3566. D3D12_ReleaseShader(driverData, renderer->blitFromCubeArrayShader);
  3567. for (Uint32 i = 0; i < renderer->blitPipelineCount; i += 1) {
  3568. D3D12_ReleaseGraphicsPipeline(driverData, renderer->blitPipelines[i].pipeline);
  3569. }
  3570. SDL_free(renderer->blitPipelines);
  3571. }
  3572. // Render Pass
  3573. static void D3D12_SetViewport(
  3574. SDL_GPUCommandBuffer *commandBuffer,
  3575. const SDL_GPUViewport *viewport)
  3576. {
  3577. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3578. D3D12_VIEWPORT d3d12Viewport;
  3579. d3d12Viewport.TopLeftX = viewport->x;
  3580. d3d12Viewport.TopLeftY = viewport->y;
  3581. d3d12Viewport.Width = viewport->w;
  3582. d3d12Viewport.Height = viewport->h;
  3583. d3d12Viewport.MinDepth = viewport->min_depth;
  3584. d3d12Viewport.MaxDepth = viewport->max_depth;
  3585. ID3D12GraphicsCommandList_RSSetViewports(d3d12CommandBuffer->graphicsCommandList, 1, &d3d12Viewport);
  3586. }
  3587. static void D3D12_SetScissor(
  3588. SDL_GPUCommandBuffer *commandBuffer,
  3589. const SDL_Rect *scissor)
  3590. {
  3591. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3592. D3D12_RECT scissorRect;
  3593. scissorRect.left = scissor->x;
  3594. scissorRect.top = scissor->y;
  3595. scissorRect.right = scissor->x + scissor->w;
  3596. scissorRect.bottom = scissor->y + scissor->h;
  3597. ID3D12GraphicsCommandList_RSSetScissorRects(d3d12CommandBuffer->graphicsCommandList, 1, &scissorRect);
  3598. }
  3599. static void D3D12_SetBlendConstants(
  3600. SDL_GPUCommandBuffer *commandBuffer,
  3601. SDL_FColor blendConstants)
  3602. {
  3603. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3604. FLOAT blendFactor[4] = { blendConstants.r, blendConstants.g, blendConstants.b, blendConstants.a };
  3605. ID3D12GraphicsCommandList_OMSetBlendFactor(d3d12CommandBuffer->graphicsCommandList, blendFactor);
  3606. }
  3607. static void D3D12_SetStencilReference(
  3608. SDL_GPUCommandBuffer *commandBuffer,
  3609. Uint8 reference
  3610. ) {
  3611. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3612. ID3D12GraphicsCommandList_OMSetStencilRef(d3d12CommandBuffer->graphicsCommandList, reference);
  3613. }
  3614. static D3D12TextureSubresource *D3D12_INTERNAL_FetchTextureSubresource(
  3615. D3D12TextureContainer *container,
  3616. Uint32 layer,
  3617. Uint32 level)
  3618. {
  3619. Uint32 index = D3D12_INTERNAL_CalcSubresource(
  3620. level,
  3621. layer,
  3622. container->header.info.num_levels);
  3623. return &container->activeTexture->subresources[index];
  3624. }
  3625. static void D3D12_INTERNAL_CycleActiveTexture(
  3626. D3D12Renderer *renderer,
  3627. D3D12TextureContainer *container)
  3628. {
  3629. D3D12Texture *texture;
  3630. // If a previously-cycled texture is available, we can use that.
  3631. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  3632. texture = container->textures[i];
  3633. if (SDL_GetAtomicInt(&texture->referenceCount) == 0) {
  3634. container->activeTexture = texture;
  3635. return;
  3636. }
  3637. }
  3638. // No texture is available, generate a new one.
  3639. texture = D3D12_INTERNAL_CreateTexture(
  3640. renderer,
  3641. &container->header.info,
  3642. false,
  3643. container->debugName);
  3644. if (!texture) {
  3645. return;
  3646. }
  3647. EXPAND_ARRAY_IF_NEEDED(
  3648. container->textures,
  3649. D3D12Texture *,
  3650. container->textureCount + 1,
  3651. container->textureCapacity,
  3652. container->textureCapacity * 2);
  3653. container->textures[container->textureCount] = texture;
  3654. texture->container = container;
  3655. texture->containerIndex = container->textureCount;
  3656. container->textureCount += 1;
  3657. container->activeTexture = texture;
  3658. }
  3659. static D3D12TextureSubresource *D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  3660. D3D12CommandBuffer *commandBuffer,
  3661. D3D12TextureContainer *container,
  3662. Uint32 layer,
  3663. Uint32 level,
  3664. bool cycle,
  3665. D3D12_RESOURCE_STATES destinationUsageMode)
  3666. {
  3667. D3D12TextureSubresource *subresource = D3D12_INTERNAL_FetchTextureSubresource(
  3668. container,
  3669. layer,
  3670. level);
  3671. if (
  3672. container->canBeCycled &&
  3673. cycle &&
  3674. SDL_GetAtomicInt(&subresource->parent->referenceCount) > 0) {
  3675. D3D12_INTERNAL_CycleActiveTexture(
  3676. commandBuffer->renderer,
  3677. container);
  3678. subresource = D3D12_INTERNAL_FetchTextureSubresource(
  3679. container,
  3680. layer,
  3681. level);
  3682. }
  3683. D3D12_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  3684. commandBuffer,
  3685. destinationUsageMode,
  3686. subresource);
  3687. return subresource;
  3688. }
  3689. static void D3D12_INTERNAL_CycleActiveBuffer(
  3690. D3D12Renderer *renderer,
  3691. D3D12BufferContainer *container)
  3692. {
  3693. // If a previously-cycled buffer is available, we can use that.
  3694. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  3695. D3D12Buffer *buffer = container->buffers[i];
  3696. if (SDL_GetAtomicInt(&buffer->referenceCount) == 0) {
  3697. container->activeBuffer = buffer;
  3698. return;
  3699. }
  3700. }
  3701. // No buffer handle is available, create a new one.
  3702. D3D12Buffer *buffer = D3D12_INTERNAL_CreateBuffer(
  3703. renderer,
  3704. container->usage,
  3705. container->size,
  3706. container->type,
  3707. container->debugName);
  3708. if (!buffer) {
  3709. return;
  3710. }
  3711. EXPAND_ARRAY_IF_NEEDED(
  3712. container->buffers,
  3713. D3D12Buffer *,
  3714. container->bufferCount + 1,
  3715. container->bufferCapacity,
  3716. container->bufferCapacity * 2);
  3717. container->buffers[container->bufferCount] = buffer;
  3718. buffer->container = container;
  3719. buffer->containerIndex = container->bufferCount;
  3720. container->bufferCount += 1;
  3721. container->activeBuffer = buffer;
  3722. if (renderer->debug_mode && container->debugName != NULL) {
  3723. D3D12_INTERNAL_SetResourceName(
  3724. renderer,
  3725. container->activeBuffer->handle,
  3726. container->debugName);
  3727. }
  3728. }
  3729. static D3D12Buffer *D3D12_INTERNAL_PrepareBufferForWrite(
  3730. D3D12CommandBuffer *commandBuffer,
  3731. D3D12BufferContainer *container,
  3732. bool cycle,
  3733. D3D12_RESOURCE_STATES destinationState)
  3734. {
  3735. if (
  3736. cycle &&
  3737. SDL_GetAtomicInt(&container->activeBuffer->referenceCount) > 0) {
  3738. D3D12_INTERNAL_CycleActiveBuffer(
  3739. commandBuffer->renderer,
  3740. container);
  3741. }
  3742. D3D12_INTERNAL_BufferTransitionFromDefaultUsage(
  3743. commandBuffer,
  3744. destinationState,
  3745. container->activeBuffer);
  3746. return container->activeBuffer;
  3747. }
  3748. static void D3D12_BeginRenderPass(
  3749. SDL_GPUCommandBuffer *commandBuffer,
  3750. const SDL_GPUColorTargetInfo *colorTargetInfos,
  3751. Uint32 numColorTargets,
  3752. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo)
  3753. {
  3754. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3755. Uint32 framebufferWidth = SDL_MAX_UINT32;
  3756. Uint32 framebufferHeight = SDL_MAX_UINT32;
  3757. for (Uint32 i = 0; i < numColorTargets; i += 1) {
  3758. D3D12TextureContainer *container = (D3D12TextureContainer *)colorTargetInfos[i].texture;
  3759. Uint32 h = container->header.info.height >> colorTargetInfos[i].mip_level;
  3760. Uint32 w = container->header.info.width >> colorTargetInfos[i].mip_level;
  3761. // The framebuffer cannot be larger than the smallest target.
  3762. if (w < framebufferWidth) {
  3763. framebufferWidth = w;
  3764. }
  3765. if (h < framebufferHeight) {
  3766. framebufferHeight = h;
  3767. }
  3768. }
  3769. if (depthStencilTargetInfo != NULL) {
  3770. D3D12TextureContainer *container = (D3D12TextureContainer *)depthStencilTargetInfo->texture;
  3771. Uint32 h = container->header.info.height >> depthStencilTargetInfo->mip_level;
  3772. Uint32 w = container->header.info.width >> depthStencilTargetInfo->mip_level;
  3773. // The framebuffer cannot be larger than the smallest target.
  3774. if (w < framebufferWidth) {
  3775. framebufferWidth = w;
  3776. }
  3777. if (h < framebufferHeight) {
  3778. framebufferHeight = h;
  3779. }
  3780. }
  3781. D3D12_CPU_DESCRIPTOR_HANDLE rtvs[MAX_COLOR_TARGET_BINDINGS];
  3782. for (Uint32 i = 0; i < numColorTargets; i += 1) {
  3783. D3D12TextureContainer *container = (D3D12TextureContainer *)colorTargetInfos[i].texture;
  3784. D3D12TextureSubresource *subresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  3785. d3d12CommandBuffer,
  3786. container,
  3787. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : colorTargetInfos[i].layer_or_depth_plane,
  3788. colorTargetInfos[i].mip_level,
  3789. colorTargetInfos[i].cycle,
  3790. D3D12_RESOURCE_STATE_RENDER_TARGET);
  3791. Uint32 rtvIndex = container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? colorTargetInfos[i].layer_or_depth_plane : 0;
  3792. D3D12_CPU_DESCRIPTOR_HANDLE rtv = subresource->rtvHandles[rtvIndex].cpuHandle;
  3793. if (colorTargetInfos[i].load_op == SDL_GPU_LOADOP_CLEAR) {
  3794. float clearColor[4];
  3795. clearColor[0] = colorTargetInfos[i].clear_color.r;
  3796. clearColor[1] = colorTargetInfos[i].clear_color.g;
  3797. clearColor[2] = colorTargetInfos[i].clear_color.b;
  3798. clearColor[3] = colorTargetInfos[i].clear_color.a;
  3799. ID3D12GraphicsCommandList_ClearRenderTargetView(
  3800. d3d12CommandBuffer->graphicsCommandList,
  3801. rtv,
  3802. clearColor,
  3803. 0,
  3804. NULL);
  3805. }
  3806. rtvs[i] = rtv;
  3807. d3d12CommandBuffer->colorTargetSubresources[i] = subresource;
  3808. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, subresource->parent);
  3809. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  3810. D3D12TextureContainer *resolveContainer = (D3D12TextureContainer *)colorTargetInfos[i].resolve_texture;
  3811. D3D12TextureSubresource *resolveSubresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  3812. d3d12CommandBuffer,
  3813. resolveContainer,
  3814. colorTargetInfos[i].resolve_layer,
  3815. colorTargetInfos[i].resolve_mip_level,
  3816. colorTargetInfos[i].cycle_resolve_texture,
  3817. D3D12_RESOURCE_STATE_RESOLVE_DEST);
  3818. d3d12CommandBuffer->colorResolveSubresources[i] = resolveSubresource;
  3819. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, resolveSubresource->parent);
  3820. }
  3821. }
  3822. D3D12_CPU_DESCRIPTOR_HANDLE dsv;
  3823. if (depthStencilTargetInfo != NULL) {
  3824. D3D12TextureContainer *container = (D3D12TextureContainer *)depthStencilTargetInfo->texture;
  3825. D3D12TextureSubresource *subresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  3826. d3d12CommandBuffer,
  3827. container,
  3828. depthStencilTargetInfo->layer,
  3829. depthStencilTargetInfo->mip_level,
  3830. depthStencilTargetInfo->cycle,
  3831. D3D12_RESOURCE_STATE_DEPTH_WRITE);
  3832. if (
  3833. depthStencilTargetInfo->load_op == SDL_GPU_LOADOP_CLEAR ||
  3834. depthStencilTargetInfo->stencil_load_op == SDL_GPU_LOADOP_CLEAR) {
  3835. D3D12_CLEAR_FLAGS clearFlags = (D3D12_CLEAR_FLAGS)0;
  3836. if (depthStencilTargetInfo->load_op == SDL_GPU_LOADOP_CLEAR) {
  3837. clearFlags |= D3D12_CLEAR_FLAG_DEPTH;
  3838. }
  3839. if (depthStencilTargetInfo->stencil_load_op == SDL_GPU_LOADOP_CLEAR) {
  3840. clearFlags |= D3D12_CLEAR_FLAG_STENCIL;
  3841. }
  3842. ID3D12GraphicsCommandList_ClearDepthStencilView(
  3843. d3d12CommandBuffer->graphicsCommandList,
  3844. subresource->dsvHandle.cpuHandle,
  3845. clearFlags,
  3846. depthStencilTargetInfo->clear_depth,
  3847. depthStencilTargetInfo->clear_stencil,
  3848. 0,
  3849. NULL);
  3850. }
  3851. dsv = subresource->dsvHandle.cpuHandle;
  3852. d3d12CommandBuffer->depthStencilTextureSubresource = subresource;
  3853. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, subresource->parent);
  3854. }
  3855. ID3D12GraphicsCommandList_OMSetRenderTargets(
  3856. d3d12CommandBuffer->graphicsCommandList,
  3857. numColorTargets,
  3858. rtvs,
  3859. false,
  3860. (depthStencilTargetInfo == NULL) ? NULL : &dsv);
  3861. // Set sensible default states
  3862. SDL_GPUViewport defaultViewport;
  3863. defaultViewport.x = 0;
  3864. defaultViewport.y = 0;
  3865. defaultViewport.w = (float)framebufferWidth;
  3866. defaultViewport.h = (float)framebufferHeight;
  3867. defaultViewport.min_depth = 0;
  3868. defaultViewport.max_depth = 1;
  3869. D3D12_SetViewport(
  3870. commandBuffer,
  3871. &defaultViewport);
  3872. SDL_Rect defaultScissor;
  3873. defaultScissor.x = 0;
  3874. defaultScissor.y = 0;
  3875. defaultScissor.w = (Sint32)framebufferWidth;
  3876. defaultScissor.h = (Sint32)framebufferHeight;
  3877. D3D12_SetScissor(
  3878. commandBuffer,
  3879. &defaultScissor);
  3880. D3D12_SetStencilReference(
  3881. commandBuffer,
  3882. 0);
  3883. SDL_FColor blendConstants;
  3884. blendConstants.r = 1.0f;
  3885. blendConstants.g = 1.0f;
  3886. blendConstants.b = 1.0f;
  3887. blendConstants.a = 1.0f;
  3888. D3D12_SetBlendConstants(
  3889. commandBuffer,
  3890. blendConstants);
  3891. }
  3892. static void D3D12_INTERNAL_TrackUniformBuffer(
  3893. D3D12CommandBuffer *commandBuffer,
  3894. D3D12UniformBuffer *uniformBuffer)
  3895. {
  3896. Uint32 i;
  3897. for (i = 0; i < commandBuffer->usedUniformBufferCount; i += 1) {
  3898. if (commandBuffer->usedUniformBuffers[i] == uniformBuffer) {
  3899. return;
  3900. }
  3901. }
  3902. if (commandBuffer->usedUniformBufferCount == commandBuffer->usedUniformBufferCapacity) {
  3903. commandBuffer->usedUniformBufferCapacity += 1;
  3904. commandBuffer->usedUniformBuffers = (D3D12UniformBuffer **)SDL_realloc(
  3905. commandBuffer->usedUniformBuffers,
  3906. commandBuffer->usedUniformBufferCapacity * sizeof(D3D12UniformBuffer *));
  3907. }
  3908. commandBuffer->usedUniformBuffers[commandBuffer->usedUniformBufferCount] = uniformBuffer;
  3909. commandBuffer->usedUniformBufferCount += 1;
  3910. D3D12_INTERNAL_TrackBuffer(
  3911. commandBuffer,
  3912. uniformBuffer->buffer);
  3913. }
  3914. static D3D12UniformBuffer *D3D12_INTERNAL_AcquireUniformBufferFromPool(
  3915. D3D12CommandBuffer *commandBuffer)
  3916. {
  3917. D3D12Renderer *renderer = commandBuffer->renderer;
  3918. D3D12UniformBuffer *uniformBuffer;
  3919. SDL_LockMutex(renderer->acquireUniformBufferLock);
  3920. if (renderer->uniformBufferPoolCount > 0) {
  3921. uniformBuffer = renderer->uniformBufferPool[renderer->uniformBufferPoolCount - 1];
  3922. renderer->uniformBufferPoolCount -= 1;
  3923. } else {
  3924. uniformBuffer = (D3D12UniformBuffer *)SDL_calloc(1, sizeof(D3D12UniformBuffer));
  3925. if (!uniformBuffer) {
  3926. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  3927. return NULL;
  3928. }
  3929. uniformBuffer->buffer = D3D12_INTERNAL_CreateBuffer(
  3930. renderer,
  3931. 0,
  3932. UNIFORM_BUFFER_SIZE,
  3933. D3D12_BUFFER_TYPE_UNIFORM,
  3934. NULL);
  3935. if (!uniformBuffer->buffer) {
  3936. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  3937. return NULL;
  3938. }
  3939. }
  3940. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  3941. uniformBuffer->drawOffset = 0;
  3942. uniformBuffer->writeOffset = 0;
  3943. HRESULT res = ID3D12Resource_Map(
  3944. uniformBuffer->buffer->handle,
  3945. 0,
  3946. NULL,
  3947. (void **)&uniformBuffer->buffer->mapPointer);
  3948. CHECK_D3D12_ERROR_AND_RETURN("Failed to map buffer pool!", NULL);
  3949. D3D12_INTERNAL_TrackUniformBuffer(commandBuffer, uniformBuffer);
  3950. return uniformBuffer;
  3951. }
  3952. static void D3D12_INTERNAL_ReturnUniformBufferToPool(
  3953. D3D12Renderer *renderer,
  3954. D3D12UniformBuffer *uniformBuffer)
  3955. {
  3956. if (renderer->uniformBufferPoolCount >= renderer->uniformBufferPoolCapacity) {
  3957. renderer->uniformBufferPoolCapacity *= 2;
  3958. renderer->uniformBufferPool = (D3D12UniformBuffer **)SDL_realloc(
  3959. renderer->uniformBufferPool,
  3960. renderer->uniformBufferPoolCapacity * sizeof(D3D12UniformBuffer *));
  3961. }
  3962. renderer->uniformBufferPool[renderer->uniformBufferPoolCount] = uniformBuffer;
  3963. renderer->uniformBufferPoolCount += 1;
  3964. }
  3965. static void D3D12_INTERNAL_PushUniformData(
  3966. D3D12CommandBuffer *commandBuffer,
  3967. SDL_GPUShaderStage shaderStage,
  3968. Uint32 slotIndex,
  3969. const void *data,
  3970. Uint32 length)
  3971. {
  3972. D3D12UniformBuffer *uniformBuffer;
  3973. Uint32 blockSize;
  3974. if (shaderStage == SDL_GPU_SHADERSTAGE_VERTEX) {
  3975. if (commandBuffer->vertexUniformBuffers[slotIndex] == NULL) {
  3976. commandBuffer->vertexUniformBuffers[slotIndex] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  3977. commandBuffer);
  3978. }
  3979. uniformBuffer = commandBuffer->vertexUniformBuffers[slotIndex];
  3980. } else if (shaderStage == SDL_GPU_SHADERSTAGE_FRAGMENT) {
  3981. if (commandBuffer->fragmentUniformBuffers[slotIndex] == NULL) {
  3982. commandBuffer->fragmentUniformBuffers[slotIndex] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  3983. commandBuffer);
  3984. }
  3985. uniformBuffer = commandBuffer->fragmentUniformBuffers[slotIndex];
  3986. } else if (shaderStage == SDL_GPU_SHADERSTAGE_COMPUTE) {
  3987. if (commandBuffer->computeUniformBuffers[slotIndex] == NULL) {
  3988. commandBuffer->computeUniformBuffers[slotIndex] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  3989. commandBuffer);
  3990. }
  3991. uniformBuffer = commandBuffer->computeUniformBuffers[slotIndex];
  3992. } else {
  3993. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  3994. return;
  3995. }
  3996. blockSize =
  3997. D3D12_INTERNAL_Align(
  3998. length,
  3999. 256);
  4000. // If there is no more room, acquire a new uniform buffer
  4001. if (uniformBuffer->writeOffset + blockSize >= UNIFORM_BUFFER_SIZE) {
  4002. ID3D12Resource_Unmap(
  4003. uniformBuffer->buffer->handle,
  4004. 0,
  4005. NULL);
  4006. uniformBuffer->buffer->mapPointer = NULL;
  4007. uniformBuffer = D3D12_INTERNAL_AcquireUniformBufferFromPool(commandBuffer);
  4008. uniformBuffer->drawOffset = 0;
  4009. uniformBuffer->writeOffset = 0;
  4010. if (shaderStage == SDL_GPU_SHADERSTAGE_VERTEX) {
  4011. commandBuffer->vertexUniformBuffers[slotIndex] = uniformBuffer;
  4012. } else if (shaderStage == SDL_GPU_SHADERSTAGE_FRAGMENT) {
  4013. commandBuffer->fragmentUniformBuffers[slotIndex] = uniformBuffer;
  4014. } else if (shaderStage == SDL_GPU_SHADERSTAGE_COMPUTE) {
  4015. commandBuffer->computeUniformBuffers[slotIndex] = uniformBuffer;
  4016. } else {
  4017. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  4018. }
  4019. }
  4020. uniformBuffer->drawOffset = uniformBuffer->writeOffset;
  4021. SDL_memcpy(
  4022. (Uint8 *)uniformBuffer->buffer->mapPointer + uniformBuffer->writeOffset,
  4023. data,
  4024. length);
  4025. uniformBuffer->writeOffset += blockSize;
  4026. if (shaderStage == SDL_GPU_SHADERSTAGE_VERTEX) {
  4027. commandBuffer->needVertexUniformBufferBind[slotIndex] = true;
  4028. } else if (shaderStage == SDL_GPU_SHADERSTAGE_FRAGMENT) {
  4029. commandBuffer->needFragmentUniformBufferBind[slotIndex] = true;
  4030. } else if (shaderStage == SDL_GPU_SHADERSTAGE_COMPUTE) {
  4031. commandBuffer->needComputeUniformBufferBind[slotIndex] = true;
  4032. } else {
  4033. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  4034. }
  4035. }
  4036. static void D3D12_BindGraphicsPipeline(
  4037. SDL_GPUCommandBuffer *commandBuffer,
  4038. SDL_GPUGraphicsPipeline *graphicsPipeline)
  4039. {
  4040. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4041. D3D12GraphicsPipeline *pipeline = (D3D12GraphicsPipeline *)graphicsPipeline;
  4042. Uint32 i;
  4043. d3d12CommandBuffer->currentGraphicsPipeline = pipeline;
  4044. // Set the pipeline state
  4045. ID3D12GraphicsCommandList_SetPipelineState(d3d12CommandBuffer->graphicsCommandList, pipeline->pipelineState);
  4046. ID3D12GraphicsCommandList_SetGraphicsRootSignature(d3d12CommandBuffer->graphicsCommandList, pipeline->rootSignature->handle);
  4047. ID3D12GraphicsCommandList_IASetPrimitiveTopology(d3d12CommandBuffer->graphicsCommandList, SDLToD3D12_PrimitiveType[pipeline->primitiveType]);
  4048. // Mark that bindings are needed
  4049. d3d12CommandBuffer->needVertexSamplerBind = true;
  4050. d3d12CommandBuffer->needVertexStorageTextureBind = true;
  4051. d3d12CommandBuffer->needVertexStorageBufferBind = true;
  4052. d3d12CommandBuffer->needFragmentSamplerBind = true;
  4053. d3d12CommandBuffer->needFragmentStorageTextureBind = true;
  4054. d3d12CommandBuffer->needFragmentStorageBufferBind = true;
  4055. for (i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  4056. d3d12CommandBuffer->needVertexUniformBufferBind[i] = true;
  4057. d3d12CommandBuffer->needFragmentUniformBufferBind[i] = true;
  4058. }
  4059. for (i = 0; i < pipeline->header.num_vertex_uniform_buffers; i += 1) {
  4060. if (d3d12CommandBuffer->vertexUniformBuffers[i] == NULL) {
  4061. d3d12CommandBuffer->vertexUniformBuffers[i] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  4062. d3d12CommandBuffer);
  4063. }
  4064. }
  4065. for (i = 0; i < pipeline->header.num_fragment_uniform_buffers; i += 1) {
  4066. if (d3d12CommandBuffer->fragmentUniformBuffers[i] == NULL) {
  4067. d3d12CommandBuffer->fragmentUniformBuffers[i] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  4068. d3d12CommandBuffer);
  4069. }
  4070. }
  4071. D3D12_INTERNAL_TrackGraphicsPipeline(d3d12CommandBuffer, pipeline);
  4072. }
  4073. static void D3D12_BindVertexBuffers(
  4074. SDL_GPUCommandBuffer *commandBuffer,
  4075. Uint32 firstSlot,
  4076. const SDL_GPUBufferBinding *bindings,
  4077. Uint32 numBindings)
  4078. {
  4079. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4080. for (Uint32 i = 0; i < numBindings; i += 1) {
  4081. D3D12Buffer *currentBuffer = ((D3D12BufferContainer *)bindings[i].buffer)->activeBuffer;
  4082. if (d3d12CommandBuffer->vertexBuffers[firstSlot + i] != currentBuffer || d3d12CommandBuffer->vertexBufferOffsets[firstSlot + i] != bindings[i].offset) {
  4083. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, currentBuffer);
  4084. d3d12CommandBuffer->vertexBuffers[firstSlot + i] = currentBuffer;
  4085. d3d12CommandBuffer->vertexBufferOffsets[firstSlot + i] = bindings[i].offset;
  4086. d3d12CommandBuffer->needVertexBufferBind = true;
  4087. }
  4088. }
  4089. d3d12CommandBuffer->vertexBufferCount =
  4090. SDL_max(d3d12CommandBuffer->vertexBufferCount, firstSlot + numBindings);
  4091. }
  4092. static void D3D12_BindIndexBuffer(
  4093. SDL_GPUCommandBuffer *commandBuffer,
  4094. const SDL_GPUBufferBinding *binding,
  4095. SDL_GPUIndexElementSize indexElementSize)
  4096. {
  4097. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4098. D3D12Buffer *buffer = ((D3D12BufferContainer *)binding->buffer)->activeBuffer;
  4099. D3D12_INDEX_BUFFER_VIEW view;
  4100. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, buffer);
  4101. view.BufferLocation = buffer->virtualAddress + binding->offset;
  4102. view.SizeInBytes = buffer->container->size - binding->offset;
  4103. view.Format =
  4104. indexElementSize == SDL_GPU_INDEXELEMENTSIZE_16BIT ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  4105. ID3D12GraphicsCommandList_IASetIndexBuffer(
  4106. d3d12CommandBuffer->graphicsCommandList,
  4107. &view);
  4108. }
  4109. static void D3D12_BindVertexSamplers(
  4110. SDL_GPUCommandBuffer *commandBuffer,
  4111. Uint32 firstSlot,
  4112. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  4113. Uint32 numBindings)
  4114. {
  4115. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4116. for (Uint32 i = 0; i < numBindings; i += 1) {
  4117. D3D12TextureContainer *container = (D3D12TextureContainer *)textureSamplerBindings[i].texture;
  4118. D3D12Sampler *sampler = (D3D12Sampler *)textureSamplerBindings[i].sampler;
  4119. if (d3d12CommandBuffer->vertexSamplerDescriptorHandles[firstSlot + i].ptr != sampler->handle.cpuHandle.ptr) {
  4120. D3D12_INTERNAL_TrackSampler(
  4121. d3d12CommandBuffer,
  4122. sampler);
  4123. d3d12CommandBuffer->vertexSamplerDescriptorHandles[firstSlot + i] = sampler->handle.cpuHandle;
  4124. d3d12CommandBuffer->needVertexSamplerBind = true;
  4125. }
  4126. if (d3d12CommandBuffer->vertexSamplerTextureDescriptorHandles[firstSlot + i].ptr != container->activeTexture->srvHandle.cpuHandle.ptr) {
  4127. D3D12_INTERNAL_TrackTexture(
  4128. d3d12CommandBuffer,
  4129. container->activeTexture);
  4130. d3d12CommandBuffer->vertexSamplerTextureDescriptorHandles[firstSlot + i] = container->activeTexture->srvHandle.cpuHandle;
  4131. d3d12CommandBuffer->needVertexSamplerBind = true;
  4132. }
  4133. }
  4134. }
  4135. static void D3D12_BindVertexStorageTextures(
  4136. SDL_GPUCommandBuffer *commandBuffer,
  4137. Uint32 firstSlot,
  4138. SDL_GPUTexture *const *storageTextures,
  4139. Uint32 numBindings)
  4140. {
  4141. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4142. for (Uint32 i = 0; i < numBindings; i += 1) {
  4143. D3D12TextureContainer *container = (D3D12TextureContainer *)storageTextures[i];
  4144. D3D12Texture *texture = container->activeTexture;
  4145. if (d3d12CommandBuffer->vertexStorageTextureDescriptorHandles[firstSlot + i].ptr != texture->srvHandle.cpuHandle.ptr) {
  4146. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, texture);
  4147. d3d12CommandBuffer->vertexStorageTextureDescriptorHandles[firstSlot + i] = texture->srvHandle.cpuHandle;
  4148. d3d12CommandBuffer->needVertexStorageTextureBind = true;
  4149. }
  4150. }
  4151. }
  4152. static void D3D12_BindVertexStorageBuffers(
  4153. SDL_GPUCommandBuffer *commandBuffer,
  4154. Uint32 firstSlot,
  4155. SDL_GPUBuffer *const *storageBuffers,
  4156. Uint32 numBindings)
  4157. {
  4158. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4159. for (Uint32 i = 0; i < numBindings; i += 1) {
  4160. D3D12BufferContainer *container = (D3D12BufferContainer *)storageBuffers[i];
  4161. if (d3d12CommandBuffer->vertexStorageBufferDescriptorHandles[firstSlot + i].ptr != container->activeBuffer->srvDescriptor.cpuHandle.ptr) {
  4162. D3D12_INTERNAL_TrackBuffer(
  4163. d3d12CommandBuffer,
  4164. container->activeBuffer);
  4165. d3d12CommandBuffer->vertexStorageBufferDescriptorHandles[firstSlot + i] = container->activeBuffer->srvDescriptor.cpuHandle;
  4166. d3d12CommandBuffer->needVertexStorageBufferBind = true;
  4167. }
  4168. }
  4169. }
  4170. static void D3D12_BindFragmentSamplers(
  4171. SDL_GPUCommandBuffer *commandBuffer,
  4172. Uint32 firstSlot,
  4173. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  4174. Uint32 numBindings)
  4175. {
  4176. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4177. for (Uint32 i = 0; i < numBindings; i += 1) {
  4178. D3D12TextureContainer *container = (D3D12TextureContainer *)textureSamplerBindings[i].texture;
  4179. D3D12Sampler *sampler = (D3D12Sampler *)textureSamplerBindings[i].sampler;
  4180. if (d3d12CommandBuffer->fragmentSamplerDescriptorHandles[firstSlot + i].ptr != sampler->handle.cpuHandle.ptr) {
  4181. D3D12_INTERNAL_TrackSampler(
  4182. d3d12CommandBuffer,
  4183. sampler);
  4184. d3d12CommandBuffer->fragmentSamplerDescriptorHandles[firstSlot + i] = sampler->handle.cpuHandle;
  4185. d3d12CommandBuffer->needFragmentSamplerBind = true;
  4186. }
  4187. if (d3d12CommandBuffer->fragmentSamplerTextureDescriptorHandles[firstSlot + i].ptr != container->activeTexture->srvHandle.cpuHandle.ptr) {
  4188. D3D12_INTERNAL_TrackTexture(
  4189. d3d12CommandBuffer,
  4190. container->activeTexture);
  4191. d3d12CommandBuffer->fragmentSamplerTextureDescriptorHandles[firstSlot + i] = container->activeTexture->srvHandle.cpuHandle;
  4192. d3d12CommandBuffer->needFragmentSamplerBind = true;
  4193. }
  4194. }
  4195. }
  4196. static void D3D12_BindFragmentStorageTextures(
  4197. SDL_GPUCommandBuffer *commandBuffer,
  4198. Uint32 firstSlot,
  4199. SDL_GPUTexture *const *storageTextures,
  4200. Uint32 numBindings)
  4201. {
  4202. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4203. for (Uint32 i = 0; i < numBindings; i += 1) {
  4204. D3D12TextureContainer *container = (D3D12TextureContainer *)storageTextures[i];
  4205. D3D12Texture *texture = container->activeTexture;
  4206. if (d3d12CommandBuffer->fragmentStorageTextureDescriptorHandles[firstSlot + i].ptr != texture->srvHandle.cpuHandle.ptr) {
  4207. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, texture);
  4208. d3d12CommandBuffer->fragmentStorageTextureDescriptorHandles[firstSlot + i] = texture->srvHandle.cpuHandle;
  4209. d3d12CommandBuffer->needFragmentStorageTextureBind = true;
  4210. }
  4211. }
  4212. }
  4213. static void D3D12_BindFragmentStorageBuffers(
  4214. SDL_GPUCommandBuffer *commandBuffer,
  4215. Uint32 firstSlot,
  4216. SDL_GPUBuffer *const *storageBuffers,
  4217. Uint32 numBindings)
  4218. {
  4219. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4220. for (Uint32 i = 0; i < numBindings; i += 1) {
  4221. D3D12BufferContainer *container = (D3D12BufferContainer *)storageBuffers[i];
  4222. if (d3d12CommandBuffer->fragmentStorageBufferDescriptorHandles[firstSlot + i].ptr != container->activeBuffer->srvDescriptor.cpuHandle.ptr) {
  4223. D3D12_INTERNAL_TrackBuffer(
  4224. d3d12CommandBuffer,
  4225. container->activeBuffer);
  4226. d3d12CommandBuffer->fragmentStorageBufferDescriptorHandles[firstSlot + i] = container->activeBuffer->srvDescriptor.cpuHandle;
  4227. d3d12CommandBuffer->needFragmentStorageBufferBind = true;
  4228. }
  4229. }
  4230. }
  4231. static void D3D12_PushVertexUniformData(
  4232. SDL_GPUCommandBuffer *commandBuffer,
  4233. Uint32 slotIndex,
  4234. const void *data,
  4235. Uint32 length)
  4236. {
  4237. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4238. D3D12_INTERNAL_PushUniformData(
  4239. d3d12CommandBuffer,
  4240. SDL_GPU_SHADERSTAGE_VERTEX,
  4241. slotIndex,
  4242. data,
  4243. length);
  4244. }
  4245. static void D3D12_PushFragmentUniformData(
  4246. SDL_GPUCommandBuffer *commandBuffer,
  4247. Uint32 slotIndex,
  4248. const void *data,
  4249. Uint32 length)
  4250. {
  4251. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4252. D3D12_INTERNAL_PushUniformData(
  4253. d3d12CommandBuffer,
  4254. SDL_GPU_SHADERSTAGE_FRAGMENT,
  4255. slotIndex,
  4256. data,
  4257. length);
  4258. }
  4259. static void D3D12_INTERNAL_SetGPUDescriptorHeaps(D3D12CommandBuffer *commandBuffer)
  4260. {
  4261. ID3D12DescriptorHeap *heaps[2];
  4262. D3D12DescriptorHeap *viewHeap;
  4263. D3D12DescriptorHeap *samplerHeap;
  4264. viewHeap = D3D12_INTERNAL_AcquireGPUDescriptorHeapFromPool(commandBuffer, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  4265. samplerHeap = D3D12_INTERNAL_AcquireGPUDescriptorHeapFromPool(commandBuffer, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
  4266. commandBuffer->gpuDescriptorHeaps[0] = viewHeap;
  4267. commandBuffer->gpuDescriptorHeaps[1] = samplerHeap;
  4268. heaps[0] = viewHeap->handle;
  4269. heaps[1] = samplerHeap->handle;
  4270. ID3D12GraphicsCommandList_SetDescriptorHeaps(
  4271. commandBuffer->graphicsCommandList,
  4272. 2,
  4273. heaps);
  4274. }
  4275. static void D3D12_INTERNAL_WriteGPUDescriptors(
  4276. D3D12CommandBuffer *commandBuffer,
  4277. D3D12_DESCRIPTOR_HEAP_TYPE heapType,
  4278. D3D12_CPU_DESCRIPTOR_HANDLE *resourceDescriptorHandles,
  4279. Uint32 resourceHandleCount,
  4280. D3D12_GPU_DESCRIPTOR_HANDLE *gpuBaseDescriptor)
  4281. {
  4282. D3D12DescriptorHeap *heap;
  4283. D3D12_CPU_DESCRIPTOR_HANDLE gpuHeapCpuHandle;
  4284. /* Descriptor overflow, acquire new heaps */
  4285. if (commandBuffer->gpuDescriptorHeaps[heapType]->currentDescriptorIndex >= commandBuffer->gpuDescriptorHeaps[heapType]->maxDescriptors) {
  4286. D3D12_INTERNAL_SetGPUDescriptorHeaps(commandBuffer);
  4287. }
  4288. heap = commandBuffer->gpuDescriptorHeaps[heapType];
  4289. // FIXME: need to error on overflow
  4290. gpuHeapCpuHandle.ptr = heap->descriptorHeapCPUStart.ptr + (heap->currentDescriptorIndex * heap->descriptorSize);
  4291. gpuBaseDescriptor->ptr = heap->descriptorHeapGPUStart.ptr + (heap->currentDescriptorIndex * heap->descriptorSize);
  4292. for (Uint32 i = 0; i < resourceHandleCount; i += 1) {
  4293. // This will crash the driver if it gets a null handle! Cool!
  4294. if (resourceDescriptorHandles[i].ptr != 0)
  4295. {
  4296. ID3D12Device_CopyDescriptorsSimple(
  4297. commandBuffer->renderer->device,
  4298. 1,
  4299. gpuHeapCpuHandle,
  4300. resourceDescriptorHandles[i],
  4301. heapType);
  4302. heap->currentDescriptorIndex += 1;
  4303. gpuHeapCpuHandle.ptr += heap->descriptorSize;
  4304. }
  4305. }
  4306. }
  4307. static void D3D12_INTERNAL_BindGraphicsResources(
  4308. D3D12CommandBuffer *commandBuffer)
  4309. {
  4310. D3D12GraphicsPipeline *graphicsPipeline = commandBuffer->currentGraphicsPipeline;
  4311. /* Acquire GPU descriptor heaps if we haven't yet */
  4312. if (commandBuffer->gpuDescriptorHeaps[0] == NULL) {
  4313. D3D12_INTERNAL_SetGPUDescriptorHeaps(commandBuffer);
  4314. }
  4315. D3D12_CPU_DESCRIPTOR_HANDLE cpuHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  4316. D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorHandle;
  4317. D3D12_VERTEX_BUFFER_VIEW vertexBufferViews[MAX_VERTEX_BUFFERS];
  4318. if (commandBuffer->needVertexBufferBind) {
  4319. for (Uint32 i = 0; i < commandBuffer->vertexBufferCount; i += 1) {
  4320. vertexBufferViews[i].BufferLocation = commandBuffer->vertexBuffers[i]->virtualAddress + commandBuffer->vertexBufferOffsets[i];
  4321. vertexBufferViews[i].SizeInBytes = commandBuffer->vertexBuffers[i]->container->size - commandBuffer->vertexBufferOffsets[i];
  4322. vertexBufferViews[i].StrideInBytes = graphicsPipeline->vertexStrides[i];
  4323. }
  4324. ID3D12GraphicsCommandList_IASetVertexBuffers(
  4325. commandBuffer->graphicsCommandList,
  4326. 0,
  4327. commandBuffer->vertexBufferCount,
  4328. vertexBufferViews);
  4329. commandBuffer->needVertexBufferBind = false;
  4330. }
  4331. if (commandBuffer->needVertexSamplerBind) {
  4332. if (graphicsPipeline->header.num_vertex_samplers > 0) {
  4333. for (Uint32 i = 0; i < graphicsPipeline->header.num_vertex_samplers; i += 1) {
  4334. cpuHandles[i] = commandBuffer->vertexSamplerDescriptorHandles[i];
  4335. }
  4336. D3D12_INTERNAL_WriteGPUDescriptors(
  4337. commandBuffer,
  4338. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
  4339. cpuHandles,
  4340. graphicsPipeline->header.num_vertex_samplers,
  4341. &gpuDescriptorHandle);
  4342. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  4343. commandBuffer->graphicsCommandList,
  4344. graphicsPipeline->rootSignature->vertexSamplerRootIndex,
  4345. gpuDescriptorHandle);
  4346. for (Uint32 i = 0; i < graphicsPipeline->header.num_vertex_samplers; i += 1) {
  4347. cpuHandles[i] = commandBuffer->vertexSamplerTextureDescriptorHandles[i];
  4348. }
  4349. D3D12_INTERNAL_WriteGPUDescriptors(
  4350. commandBuffer,
  4351. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4352. cpuHandles,
  4353. graphicsPipeline->header.num_vertex_samplers,
  4354. &gpuDescriptorHandle);
  4355. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  4356. commandBuffer->graphicsCommandList,
  4357. graphicsPipeline->rootSignature->vertexSamplerTextureRootIndex,
  4358. gpuDescriptorHandle);
  4359. }
  4360. commandBuffer->needVertexSamplerBind = false;
  4361. }
  4362. if (commandBuffer->needVertexStorageTextureBind) {
  4363. if (graphicsPipeline->header.num_vertex_storage_textures > 0) {
  4364. for (Uint32 i = 0; i < graphicsPipeline->header.num_vertex_storage_textures; i += 1) {
  4365. cpuHandles[i] = commandBuffer->vertexStorageTextureDescriptorHandles[i];
  4366. }
  4367. D3D12_INTERNAL_WriteGPUDescriptors(
  4368. commandBuffer,
  4369. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4370. cpuHandles,
  4371. graphicsPipeline->header.num_vertex_storage_textures,
  4372. &gpuDescriptorHandle);
  4373. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  4374. commandBuffer->graphicsCommandList,
  4375. graphicsPipeline->rootSignature->vertexStorageTextureRootIndex,
  4376. gpuDescriptorHandle);
  4377. }
  4378. commandBuffer->needVertexStorageTextureBind = false;
  4379. }
  4380. if (commandBuffer->needVertexStorageBufferBind) {
  4381. if (graphicsPipeline->header.num_vertex_storage_buffers > 0) {
  4382. for (Uint32 i = 0; i < graphicsPipeline->header.num_vertex_storage_buffers; i += 1) {
  4383. cpuHandles[i] = commandBuffer->vertexStorageBufferDescriptorHandles[i];
  4384. }
  4385. D3D12_INTERNAL_WriteGPUDescriptors(
  4386. commandBuffer,
  4387. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4388. cpuHandles,
  4389. graphicsPipeline->header.num_vertex_storage_buffers,
  4390. &gpuDescriptorHandle);
  4391. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  4392. commandBuffer->graphicsCommandList,
  4393. graphicsPipeline->rootSignature->vertexStorageBufferRootIndex,
  4394. gpuDescriptorHandle);
  4395. }
  4396. commandBuffer->needVertexStorageBufferBind = false;
  4397. }
  4398. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  4399. if (commandBuffer->needVertexUniformBufferBind[i]) {
  4400. if (graphicsPipeline->header.num_vertex_uniform_buffers > i) {
  4401. ID3D12GraphicsCommandList_SetGraphicsRootConstantBufferView(
  4402. commandBuffer->graphicsCommandList,
  4403. graphicsPipeline->rootSignature->vertexUniformBufferRootIndex[i],
  4404. commandBuffer->vertexUniformBuffers[i]->buffer->virtualAddress + commandBuffer->vertexUniformBuffers[i]->drawOffset);
  4405. }
  4406. commandBuffer->needVertexUniformBufferBind[i] = false;
  4407. }
  4408. }
  4409. if (commandBuffer->needFragmentSamplerBind) {
  4410. if (graphicsPipeline->header.num_fragment_samplers > 0) {
  4411. for (Uint32 i = 0; i < graphicsPipeline->header.num_fragment_samplers; i += 1) {
  4412. cpuHandles[i] = commandBuffer->fragmentSamplerDescriptorHandles[i];
  4413. }
  4414. D3D12_INTERNAL_WriteGPUDescriptors(
  4415. commandBuffer,
  4416. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
  4417. cpuHandles,
  4418. graphicsPipeline->header.num_fragment_samplers,
  4419. &gpuDescriptorHandle);
  4420. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  4421. commandBuffer->graphicsCommandList,
  4422. graphicsPipeline->rootSignature->fragmentSamplerRootIndex,
  4423. gpuDescriptorHandle);
  4424. for (Uint32 i = 0; i < graphicsPipeline->header.num_fragment_samplers; i += 1) {
  4425. cpuHandles[i] = commandBuffer->fragmentSamplerTextureDescriptorHandles[i];
  4426. }
  4427. D3D12_INTERNAL_WriteGPUDescriptors(
  4428. commandBuffer,
  4429. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4430. cpuHandles,
  4431. graphicsPipeline->header.num_fragment_samplers,
  4432. &gpuDescriptorHandle);
  4433. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  4434. commandBuffer->graphicsCommandList,
  4435. graphicsPipeline->rootSignature->fragmentSamplerTextureRootIndex,
  4436. gpuDescriptorHandle);
  4437. }
  4438. commandBuffer->needFragmentSamplerBind = false;
  4439. }
  4440. if (commandBuffer->needFragmentStorageTextureBind) {
  4441. if (graphicsPipeline->header.num_fragment_storage_textures > 0) {
  4442. for (Uint32 i = 0; i < graphicsPipeline->header.num_fragment_storage_textures; i += 1) {
  4443. cpuHandles[i] = commandBuffer->fragmentStorageTextureDescriptorHandles[i];
  4444. }
  4445. D3D12_INTERNAL_WriteGPUDescriptors(
  4446. commandBuffer,
  4447. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4448. cpuHandles,
  4449. graphicsPipeline->header.num_fragment_storage_textures,
  4450. &gpuDescriptorHandle);
  4451. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  4452. commandBuffer->graphicsCommandList,
  4453. graphicsPipeline->rootSignature->fragmentStorageTextureRootIndex,
  4454. gpuDescriptorHandle);
  4455. }
  4456. commandBuffer->needFragmentStorageTextureBind = false;
  4457. }
  4458. if (commandBuffer->needFragmentStorageBufferBind) {
  4459. if (graphicsPipeline->header.num_fragment_storage_buffers > 0) {
  4460. for (Uint32 i = 0; i < graphicsPipeline->header.num_fragment_storage_buffers; i += 1) {
  4461. cpuHandles[i] = commandBuffer->fragmentStorageBufferDescriptorHandles[i];
  4462. }
  4463. D3D12_INTERNAL_WriteGPUDescriptors(
  4464. commandBuffer,
  4465. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4466. cpuHandles,
  4467. graphicsPipeline->header.num_fragment_storage_buffers,
  4468. &gpuDescriptorHandle);
  4469. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  4470. commandBuffer->graphicsCommandList,
  4471. graphicsPipeline->rootSignature->fragmentStorageBufferRootIndex,
  4472. gpuDescriptorHandle);
  4473. }
  4474. commandBuffer->needFragmentStorageBufferBind = false;
  4475. }
  4476. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  4477. if (commandBuffer->needFragmentUniformBufferBind[i]) {
  4478. if (graphicsPipeline->header.num_fragment_uniform_buffers > i) {
  4479. ID3D12GraphicsCommandList_SetGraphicsRootConstantBufferView(
  4480. commandBuffer->graphicsCommandList,
  4481. graphicsPipeline->rootSignature->fragmentUniformBufferRootIndex[i],
  4482. commandBuffer->fragmentUniformBuffers[i]->buffer->virtualAddress + commandBuffer->fragmentUniformBuffers[i]->drawOffset);
  4483. }
  4484. commandBuffer->needFragmentUniformBufferBind[i] = false;
  4485. }
  4486. }
  4487. }
  4488. static void D3D12_DrawIndexedPrimitives(
  4489. SDL_GPUCommandBuffer *commandBuffer,
  4490. Uint32 numIndices,
  4491. Uint32 numInstances,
  4492. Uint32 firstIndex,
  4493. Sint32 vertexOffset,
  4494. Uint32 firstInstance)
  4495. {
  4496. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4497. D3D12_INTERNAL_BindGraphicsResources(d3d12CommandBuffer);
  4498. ID3D12GraphicsCommandList_DrawIndexedInstanced(
  4499. d3d12CommandBuffer->graphicsCommandList,
  4500. numIndices,
  4501. numInstances,
  4502. firstIndex,
  4503. vertexOffset,
  4504. firstInstance);
  4505. }
  4506. static void D3D12_DrawPrimitives(
  4507. SDL_GPUCommandBuffer *commandBuffer,
  4508. Uint32 numVertices,
  4509. Uint32 numInstances,
  4510. Uint32 firstVertex,
  4511. Uint32 firstInstance)
  4512. {
  4513. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4514. D3D12_INTERNAL_BindGraphicsResources(d3d12CommandBuffer);
  4515. ID3D12GraphicsCommandList_DrawInstanced(
  4516. d3d12CommandBuffer->graphicsCommandList,
  4517. numVertices,
  4518. numInstances,
  4519. firstVertex,
  4520. firstInstance);
  4521. }
  4522. static void D3D12_DrawPrimitivesIndirect(
  4523. SDL_GPUCommandBuffer *commandBuffer,
  4524. SDL_GPUBuffer *buffer,
  4525. Uint32 offset,
  4526. Uint32 drawCount)
  4527. {
  4528. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4529. D3D12Buffer *d3d12Buffer = ((D3D12BufferContainer *)buffer)->activeBuffer;
  4530. D3D12_INTERNAL_BindGraphicsResources(d3d12CommandBuffer);
  4531. ID3D12GraphicsCommandList_ExecuteIndirect(
  4532. d3d12CommandBuffer->graphicsCommandList,
  4533. d3d12CommandBuffer->renderer->indirectDrawCommandSignature,
  4534. drawCount,
  4535. d3d12Buffer->handle,
  4536. offset,
  4537. NULL,
  4538. 0);
  4539. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, d3d12Buffer);
  4540. }
  4541. static void D3D12_DrawIndexedPrimitivesIndirect(
  4542. SDL_GPUCommandBuffer *commandBuffer,
  4543. SDL_GPUBuffer *buffer,
  4544. Uint32 offset,
  4545. Uint32 drawCount)
  4546. {
  4547. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4548. D3D12Buffer *d3d12Buffer = ((D3D12BufferContainer *)buffer)->activeBuffer;
  4549. D3D12_INTERNAL_BindGraphicsResources(d3d12CommandBuffer);
  4550. ID3D12GraphicsCommandList_ExecuteIndirect(
  4551. d3d12CommandBuffer->graphicsCommandList,
  4552. d3d12CommandBuffer->renderer->indirectIndexedDrawCommandSignature,
  4553. drawCount,
  4554. d3d12Buffer->handle,
  4555. offset,
  4556. NULL,
  4557. 0);
  4558. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, d3d12Buffer);
  4559. }
  4560. static void D3D12_EndRenderPass(
  4561. SDL_GPUCommandBuffer *commandBuffer)
  4562. {
  4563. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4564. Uint32 i;
  4565. for (i = 0; i < MAX_COLOR_TARGET_BINDINGS; i += 1) {
  4566. if (d3d12CommandBuffer->colorTargetSubresources[i] != NULL) {
  4567. if (d3d12CommandBuffer->colorResolveSubresources[i] != NULL) {
  4568. // Resolving requires some extra barriers
  4569. D3D12_INTERNAL_TextureSubresourceBarrier(
  4570. d3d12CommandBuffer,
  4571. D3D12_RESOURCE_STATE_RENDER_TARGET,
  4572. D3D12_RESOURCE_STATE_RESOLVE_SOURCE,
  4573. d3d12CommandBuffer->colorTargetSubresources[i]
  4574. );
  4575. ID3D12GraphicsCommandList_ResolveSubresource(
  4576. d3d12CommandBuffer->graphicsCommandList,
  4577. d3d12CommandBuffer->colorResolveSubresources[i]->parent->resource,
  4578. d3d12CommandBuffer->colorResolveSubresources[i]->index,
  4579. d3d12CommandBuffer->colorTargetSubresources[i]->parent->resource,
  4580. d3d12CommandBuffer->colorTargetSubresources[i]->index,
  4581. SDLToD3D12_TextureFormat[d3d12CommandBuffer->colorTargetSubresources[i]->parent->container->header.info.format]);
  4582. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4583. d3d12CommandBuffer,
  4584. D3D12_RESOURCE_STATE_RESOLVE_SOURCE,
  4585. d3d12CommandBuffer->colorTargetSubresources[i]);
  4586. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4587. d3d12CommandBuffer,
  4588. D3D12_RESOURCE_STATE_RESOLVE_DEST,
  4589. d3d12CommandBuffer->colorResolveSubresources[i]);
  4590. } else {
  4591. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4592. d3d12CommandBuffer,
  4593. D3D12_RESOURCE_STATE_RENDER_TARGET,
  4594. d3d12CommandBuffer->colorTargetSubresources[i]);
  4595. }
  4596. }
  4597. }
  4598. if (d3d12CommandBuffer->depthStencilTextureSubresource != NULL) {
  4599. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4600. d3d12CommandBuffer,
  4601. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  4602. d3d12CommandBuffer->depthStencilTextureSubresource);
  4603. d3d12CommandBuffer->depthStencilTextureSubresource = NULL;
  4604. }
  4605. d3d12CommandBuffer->currentGraphicsPipeline = NULL;
  4606. ID3D12GraphicsCommandList_OMSetRenderTargets(
  4607. d3d12CommandBuffer->graphicsCommandList,
  4608. 0,
  4609. NULL,
  4610. false,
  4611. NULL);
  4612. // Reset bind state
  4613. SDL_zeroa(d3d12CommandBuffer->colorTargetSubresources);
  4614. SDL_zeroa(d3d12CommandBuffer->colorResolveSubresources);
  4615. d3d12CommandBuffer->depthStencilTextureSubresource = NULL;
  4616. SDL_zeroa(d3d12CommandBuffer->vertexBuffers);
  4617. SDL_zeroa(d3d12CommandBuffer->vertexBufferOffsets);
  4618. d3d12CommandBuffer->vertexBufferCount = 0;
  4619. SDL_zeroa(d3d12CommandBuffer->vertexSamplerTextureDescriptorHandles);
  4620. SDL_zeroa(d3d12CommandBuffer->vertexSamplerDescriptorHandles);
  4621. SDL_zeroa(d3d12CommandBuffer->vertexStorageTextureDescriptorHandles);
  4622. SDL_zeroa(d3d12CommandBuffer->vertexStorageBufferDescriptorHandles);
  4623. SDL_zeroa(d3d12CommandBuffer->fragmentSamplerTextureDescriptorHandles);
  4624. SDL_zeroa(d3d12CommandBuffer->fragmentSamplerDescriptorHandles);
  4625. SDL_zeroa(d3d12CommandBuffer->fragmentStorageTextureDescriptorHandles);
  4626. SDL_zeroa(d3d12CommandBuffer->fragmentStorageBufferDescriptorHandles);
  4627. }
  4628. // Compute Pass
  4629. static void D3D12_BeginComputePass(
  4630. SDL_GPUCommandBuffer *commandBuffer,
  4631. const SDL_GPUStorageTextureReadWriteBinding *storageTextureBindings,
  4632. Uint32 numStorageTextureBindings,
  4633. const SDL_GPUStorageBufferReadWriteBinding *storageBufferBindings,
  4634. Uint32 numStorageBufferBindings)
  4635. {
  4636. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4637. d3d12CommandBuffer->computeReadWriteStorageTextureSubresourceCount = numStorageTextureBindings;
  4638. d3d12CommandBuffer->computeReadWriteStorageBufferCount = numStorageBufferBindings;
  4639. /* Read-write resources will be actually bound in BindComputePipeline
  4640. * after the root signature is set.
  4641. * We also have to scan to see which barriers we actually need because depth slices aren't separate subresources
  4642. */
  4643. if (numStorageTextureBindings > 0) {
  4644. for (Uint32 i = 0; i < numStorageTextureBindings; i += 1) {
  4645. D3D12TextureContainer *container = (D3D12TextureContainer *)storageTextureBindings[i].texture;
  4646. D3D12TextureSubresource *subresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  4647. d3d12CommandBuffer,
  4648. container,
  4649. storageTextureBindings[i].layer,
  4650. storageTextureBindings[i].mip_level,
  4651. storageTextureBindings[i].cycle,
  4652. D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  4653. d3d12CommandBuffer->computeReadWriteStorageTextureSubresources[i] = subresource;
  4654. d3d12CommandBuffer->computeReadWriteStorageTextureDescriptorHandles[i] = subresource->uavHandle.cpuHandle;
  4655. D3D12_INTERNAL_TrackTexture(
  4656. d3d12CommandBuffer,
  4657. subresource->parent);
  4658. }
  4659. }
  4660. if (numStorageBufferBindings > 0) {
  4661. for (Uint32 i = 0; i < numStorageBufferBindings; i += 1) {
  4662. D3D12BufferContainer *container = (D3D12BufferContainer *)storageBufferBindings[i].buffer;
  4663. D3D12Buffer *buffer = D3D12_INTERNAL_PrepareBufferForWrite(
  4664. d3d12CommandBuffer,
  4665. container,
  4666. storageBufferBindings[i].cycle,
  4667. D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  4668. d3d12CommandBuffer->computeReadWriteStorageBuffers[i] = buffer;
  4669. d3d12CommandBuffer->computeReadWriteStorageBufferDescriptorHandles[i] = buffer->uavDescriptor.cpuHandle;
  4670. D3D12_INTERNAL_TrackBuffer(
  4671. d3d12CommandBuffer,
  4672. buffer);
  4673. }
  4674. }
  4675. }
  4676. static void D3D12_BindComputePipeline(
  4677. SDL_GPUCommandBuffer *commandBuffer,
  4678. SDL_GPUComputePipeline *computePipeline)
  4679. {
  4680. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4681. /* Acquire GPU descriptor heaps if we haven't yet */
  4682. if (d3d12CommandBuffer->gpuDescriptorHeaps[0] == NULL) {
  4683. D3D12_INTERNAL_SetGPUDescriptorHeaps(d3d12CommandBuffer);
  4684. }
  4685. D3D12ComputePipeline *pipeline = (D3D12ComputePipeline *)computePipeline;
  4686. D3D12_CPU_DESCRIPTOR_HANDLE cpuHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  4687. D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorHandle;
  4688. ID3D12GraphicsCommandList_SetPipelineState(
  4689. d3d12CommandBuffer->graphicsCommandList,
  4690. pipeline->pipelineState);
  4691. ID3D12GraphicsCommandList_SetComputeRootSignature(
  4692. d3d12CommandBuffer->graphicsCommandList,
  4693. pipeline->rootSignature->handle);
  4694. d3d12CommandBuffer->currentComputePipeline = pipeline;
  4695. d3d12CommandBuffer->needComputeSamplerBind = true;
  4696. d3d12CommandBuffer->needComputeReadOnlyStorageTextureBind = true;
  4697. d3d12CommandBuffer->needComputeReadOnlyStorageBufferBind = true;
  4698. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  4699. d3d12CommandBuffer->needComputeUniformBufferBind[i] = true;
  4700. }
  4701. for (Uint32 i = 0; i < pipeline->header.numUniformBuffers; i += 1) {
  4702. if (d3d12CommandBuffer->computeUniformBuffers[i] == NULL) {
  4703. d3d12CommandBuffer->computeUniformBuffers[i] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  4704. d3d12CommandBuffer);
  4705. }
  4706. }
  4707. D3D12_INTERNAL_TrackComputePipeline(d3d12CommandBuffer, pipeline);
  4708. // Bind write-only resources after setting root signature
  4709. if (pipeline->header.numReadWriteStorageTextures > 0) {
  4710. for (Uint32 i = 0; i < pipeline->header.numReadWriteStorageTextures; i += 1) {
  4711. cpuHandles[i] = d3d12CommandBuffer->computeReadWriteStorageTextureDescriptorHandles[i];
  4712. }
  4713. D3D12_INTERNAL_WriteGPUDescriptors(
  4714. d3d12CommandBuffer,
  4715. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4716. cpuHandles,
  4717. d3d12CommandBuffer->computeReadWriteStorageTextureSubresourceCount,
  4718. &gpuDescriptorHandle);
  4719. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4720. d3d12CommandBuffer->graphicsCommandList,
  4721. d3d12CommandBuffer->currentComputePipeline->rootSignature->readWriteStorageTextureRootIndex,
  4722. gpuDescriptorHandle);
  4723. }
  4724. if (pipeline->header.numReadWriteStorageBuffers > 0) {
  4725. for (Uint32 i = 0; i < pipeline->header.numReadWriteStorageBuffers; i += 1) {
  4726. cpuHandles[i] = d3d12CommandBuffer->computeReadWriteStorageBufferDescriptorHandles[i];
  4727. }
  4728. D3D12_INTERNAL_WriteGPUDescriptors(
  4729. d3d12CommandBuffer,
  4730. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4731. cpuHandles,
  4732. d3d12CommandBuffer->computeReadWriteStorageBufferCount,
  4733. &gpuDescriptorHandle);
  4734. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4735. d3d12CommandBuffer->graphicsCommandList,
  4736. d3d12CommandBuffer->currentComputePipeline->rootSignature->readWriteStorageBufferRootIndex,
  4737. gpuDescriptorHandle);
  4738. }
  4739. }
  4740. static void D3D12_BindComputeSamplers(
  4741. SDL_GPUCommandBuffer *commandBuffer,
  4742. Uint32 firstSlot,
  4743. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  4744. Uint32 numBindings)
  4745. {
  4746. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4747. for (Uint32 i = 0; i < numBindings; i += 1) {
  4748. D3D12TextureContainer *container = (D3D12TextureContainer *)textureSamplerBindings[i].texture;
  4749. D3D12Sampler *sampler = (D3D12Sampler *)textureSamplerBindings[i].sampler;
  4750. if (d3d12CommandBuffer->computeSamplerDescriptorHandles[firstSlot + i].ptr != sampler->handle.cpuHandle.ptr) {
  4751. D3D12_INTERNAL_TrackSampler(
  4752. d3d12CommandBuffer,
  4753. (D3D12Sampler *)textureSamplerBindings[i].sampler);
  4754. d3d12CommandBuffer->computeSamplerDescriptorHandles[firstSlot + i] = sampler->handle.cpuHandle;
  4755. d3d12CommandBuffer->needComputeSamplerBind = true;
  4756. }
  4757. if (d3d12CommandBuffer->computeSamplerTextureDescriptorHandles[firstSlot + i].ptr != container->activeTexture->srvHandle.cpuHandle.ptr) {
  4758. D3D12_INTERNAL_TrackTexture(
  4759. d3d12CommandBuffer,
  4760. container->activeTexture);
  4761. d3d12CommandBuffer->computeSamplerTextureDescriptorHandles[firstSlot + i] = container->activeTexture->srvHandle.cpuHandle;
  4762. d3d12CommandBuffer->needComputeSamplerBind = true;
  4763. }
  4764. }
  4765. }
  4766. static void D3D12_BindComputeStorageTextures(
  4767. SDL_GPUCommandBuffer *commandBuffer,
  4768. Uint32 firstSlot,
  4769. SDL_GPUTexture *const *storageTextures,
  4770. Uint32 numBindings)
  4771. {
  4772. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4773. for (Uint32 i = 0; i < numBindings; i += 1) {
  4774. D3D12TextureContainer *container = (D3D12TextureContainer *)storageTextures[i];
  4775. if (d3d12CommandBuffer->computeReadOnlyStorageTextures[firstSlot + i] != container->activeTexture) {
  4776. /* If a different texture was in this slot, transition it back to its default usage */
  4777. if (d3d12CommandBuffer->computeReadOnlyStorageTextures[firstSlot + i] != NULL) {
  4778. D3D12_INTERNAL_TextureTransitionToDefaultUsage(
  4779. d3d12CommandBuffer,
  4780. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4781. d3d12CommandBuffer->computeReadOnlyStorageTextures[firstSlot + i]);
  4782. }
  4783. /* Then transition the new texture and prepare it for binding */
  4784. D3D12_INTERNAL_TextureTransitionFromDefaultUsage(
  4785. d3d12CommandBuffer,
  4786. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4787. container->activeTexture);
  4788. D3D12_INTERNAL_TrackTexture(
  4789. d3d12CommandBuffer,
  4790. container->activeTexture);
  4791. d3d12CommandBuffer->computeReadOnlyStorageTextures[firstSlot + i] = container->activeTexture;
  4792. d3d12CommandBuffer->computeReadOnlyStorageTextureDescriptorHandles[firstSlot + i] = container->activeTexture->srvHandle.cpuHandle;
  4793. d3d12CommandBuffer->needComputeReadOnlyStorageTextureBind = true;
  4794. }
  4795. }
  4796. }
  4797. static void D3D12_BindComputeStorageBuffers(
  4798. SDL_GPUCommandBuffer *commandBuffer,
  4799. Uint32 firstSlot,
  4800. SDL_GPUBuffer *const *storageBuffers,
  4801. Uint32 numBindings)
  4802. {
  4803. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4804. for (Uint32 i = 0; i < numBindings; i += 1) {
  4805. D3D12BufferContainer *container = (D3D12BufferContainer *)storageBuffers[i];
  4806. D3D12Buffer *buffer = container->activeBuffer;
  4807. if (d3d12CommandBuffer->computeReadOnlyStorageBuffers[firstSlot + i] != buffer) {
  4808. /* If a different buffer was in this slot, transition it back to its default usage */
  4809. if (d3d12CommandBuffer->computeReadOnlyStorageBuffers[firstSlot + i] != NULL) {
  4810. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  4811. d3d12CommandBuffer,
  4812. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4813. d3d12CommandBuffer->computeReadOnlyStorageBuffers[firstSlot + i]);
  4814. }
  4815. /* Then transition the new buffer and prepare it for binding */
  4816. D3D12_INTERNAL_BufferTransitionFromDefaultUsage(
  4817. d3d12CommandBuffer,
  4818. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4819. buffer);
  4820. D3D12_INTERNAL_TrackBuffer(
  4821. d3d12CommandBuffer,
  4822. buffer);
  4823. d3d12CommandBuffer->computeReadOnlyStorageBuffers[firstSlot + i] = buffer;
  4824. d3d12CommandBuffer->computeReadOnlyStorageBufferDescriptorHandles[firstSlot + i] = buffer->srvDescriptor.cpuHandle;
  4825. d3d12CommandBuffer->needComputeReadOnlyStorageBufferBind = true;
  4826. }
  4827. }
  4828. }
  4829. static void D3D12_PushComputeUniformData(
  4830. SDL_GPUCommandBuffer *commandBuffer,
  4831. Uint32 slotIndex,
  4832. const void *data,
  4833. Uint32 length)
  4834. {
  4835. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4836. D3D12_INTERNAL_PushUniformData(
  4837. d3d12CommandBuffer,
  4838. SDL_GPU_SHADERSTAGE_COMPUTE,
  4839. slotIndex,
  4840. data,
  4841. length);
  4842. }
  4843. static void D3D12_INTERNAL_BindComputeResources(
  4844. D3D12CommandBuffer *commandBuffer)
  4845. {
  4846. D3D12ComputePipeline *computePipeline = commandBuffer->currentComputePipeline;
  4847. /* Acquire GPU descriptor heaps if we haven't yet */
  4848. if (commandBuffer->gpuDescriptorHeaps[0] == NULL) {
  4849. D3D12_INTERNAL_SetGPUDescriptorHeaps(commandBuffer);
  4850. }
  4851. D3D12_CPU_DESCRIPTOR_HANDLE cpuHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  4852. D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorHandle;
  4853. if (commandBuffer->needComputeSamplerBind) {
  4854. if (computePipeline->header.numSamplers > 0) {
  4855. for (Uint32 i = 0; i < computePipeline->header.numSamplers; i += 1) {
  4856. cpuHandles[i] = commandBuffer->computeSamplerDescriptorHandles[i];
  4857. }
  4858. D3D12_INTERNAL_WriteGPUDescriptors(
  4859. commandBuffer,
  4860. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
  4861. cpuHandles,
  4862. computePipeline->header.numSamplers,
  4863. &gpuDescriptorHandle);
  4864. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4865. commandBuffer->graphicsCommandList,
  4866. computePipeline->rootSignature->samplerRootIndex,
  4867. gpuDescriptorHandle);
  4868. for (Uint32 i = 0; i < computePipeline->header.numSamplers; i += 1) {
  4869. cpuHandles[i] = commandBuffer->computeSamplerTextureDescriptorHandles[i];
  4870. }
  4871. D3D12_INTERNAL_WriteGPUDescriptors(
  4872. commandBuffer,
  4873. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4874. cpuHandles,
  4875. computePipeline->header.numSamplers,
  4876. &gpuDescriptorHandle);
  4877. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4878. commandBuffer->graphicsCommandList,
  4879. computePipeline->rootSignature->samplerTextureRootIndex,
  4880. gpuDescriptorHandle);
  4881. }
  4882. commandBuffer->needComputeSamplerBind = false;
  4883. }
  4884. if (commandBuffer->needComputeReadOnlyStorageTextureBind) {
  4885. if (computePipeline->header.numReadonlyStorageTextures > 0) {
  4886. for (Uint32 i = 0; i < computePipeline->header.numReadonlyStorageTextures; i += 1) {
  4887. cpuHandles[i] = commandBuffer->computeReadOnlyStorageTextureDescriptorHandles[i];
  4888. }
  4889. D3D12_INTERNAL_WriteGPUDescriptors(
  4890. commandBuffer,
  4891. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4892. cpuHandles,
  4893. computePipeline->header.numReadonlyStorageTextures,
  4894. &gpuDescriptorHandle);
  4895. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4896. commandBuffer->graphicsCommandList,
  4897. computePipeline->rootSignature->readOnlyStorageTextureRootIndex,
  4898. gpuDescriptorHandle);
  4899. }
  4900. commandBuffer->needComputeReadOnlyStorageTextureBind = false;
  4901. }
  4902. if (commandBuffer->needComputeReadOnlyStorageBufferBind) {
  4903. if (computePipeline->header.numReadonlyStorageBuffers > 0) {
  4904. for (Uint32 i = 0; i < computePipeline->header.numReadonlyStorageBuffers; i += 1) {
  4905. cpuHandles[i] = commandBuffer->computeReadOnlyStorageBufferDescriptorHandles[i];
  4906. }
  4907. D3D12_INTERNAL_WriteGPUDescriptors(
  4908. commandBuffer,
  4909. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4910. cpuHandles,
  4911. computePipeline->header.numReadonlyStorageBuffers,
  4912. &gpuDescriptorHandle);
  4913. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4914. commandBuffer->graphicsCommandList,
  4915. computePipeline->rootSignature->readOnlyStorageBufferRootIndex,
  4916. gpuDescriptorHandle);
  4917. }
  4918. commandBuffer->needComputeReadOnlyStorageBufferBind = false;
  4919. }
  4920. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  4921. if (commandBuffer->needComputeUniformBufferBind[i]) {
  4922. if (computePipeline->header.numUniformBuffers > i) {
  4923. ID3D12GraphicsCommandList_SetComputeRootConstantBufferView(
  4924. commandBuffer->graphicsCommandList,
  4925. computePipeline->rootSignature->uniformBufferRootIndex[i],
  4926. commandBuffer->computeUniformBuffers[i]->buffer->virtualAddress + commandBuffer->computeUniformBuffers[i]->drawOffset);
  4927. }
  4928. }
  4929. commandBuffer->needComputeUniformBufferBind[i] = false;
  4930. }
  4931. }
  4932. static void D3D12_DispatchCompute(
  4933. SDL_GPUCommandBuffer *commandBuffer,
  4934. Uint32 groupcountX,
  4935. Uint32 groupcountY,
  4936. Uint32 groupcountZ)
  4937. {
  4938. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4939. D3D12_INTERNAL_BindComputeResources(d3d12CommandBuffer);
  4940. ID3D12GraphicsCommandList_Dispatch(
  4941. d3d12CommandBuffer->graphicsCommandList,
  4942. groupcountX,
  4943. groupcountY,
  4944. groupcountZ);
  4945. }
  4946. static void D3D12_DispatchComputeIndirect(
  4947. SDL_GPUCommandBuffer *commandBuffer,
  4948. SDL_GPUBuffer *buffer,
  4949. Uint32 offset)
  4950. {
  4951. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4952. D3D12Buffer *d3d12Buffer = ((D3D12BufferContainer *)buffer)->activeBuffer;
  4953. D3D12_INTERNAL_BindComputeResources(d3d12CommandBuffer);
  4954. ID3D12GraphicsCommandList_ExecuteIndirect(
  4955. d3d12CommandBuffer->graphicsCommandList,
  4956. d3d12CommandBuffer->renderer->indirectDispatchCommandSignature,
  4957. 1,
  4958. d3d12Buffer->handle,
  4959. offset,
  4960. NULL,
  4961. 0);
  4962. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, d3d12Buffer);
  4963. }
  4964. static void D3D12_EndComputePass(
  4965. SDL_GPUCommandBuffer *commandBuffer)
  4966. {
  4967. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4968. for (Uint32 i = 0; i < d3d12CommandBuffer->computeReadWriteStorageTextureSubresourceCount; i += 1) {
  4969. if (d3d12CommandBuffer->computeReadWriteStorageTextureSubresources[i]) {
  4970. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4971. d3d12CommandBuffer,
  4972. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  4973. d3d12CommandBuffer->computeReadWriteStorageTextureSubresources[i]);
  4974. d3d12CommandBuffer->computeReadWriteStorageTextureSubresources[i] = NULL;
  4975. }
  4976. }
  4977. d3d12CommandBuffer->computeReadWriteStorageTextureSubresourceCount = 0;
  4978. for (Uint32 i = 0; i < d3d12CommandBuffer->computeReadWriteStorageBufferCount; i += 1) {
  4979. if (d3d12CommandBuffer->computeReadWriteStorageBuffers[i]) {
  4980. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  4981. d3d12CommandBuffer,
  4982. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  4983. d3d12CommandBuffer->computeReadWriteStorageBuffers[i]);
  4984. d3d12CommandBuffer->computeReadWriteStorageBuffers[i] = NULL;
  4985. }
  4986. }
  4987. d3d12CommandBuffer->computeReadWriteStorageBufferCount = 0;
  4988. for (Uint32 i = 0; i < MAX_STORAGE_TEXTURES_PER_STAGE; i += 1) {
  4989. if (d3d12CommandBuffer->computeReadOnlyStorageTextures[i]) {
  4990. D3D12_INTERNAL_TextureTransitionToDefaultUsage(
  4991. d3d12CommandBuffer,
  4992. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4993. d3d12CommandBuffer->computeReadOnlyStorageTextures[i]);
  4994. d3d12CommandBuffer->computeReadOnlyStorageTextures[i] = NULL;
  4995. }
  4996. }
  4997. for (Uint32 i = 0; i < MAX_STORAGE_BUFFERS_PER_STAGE; i += 1) {
  4998. if (d3d12CommandBuffer->computeReadOnlyStorageBuffers[i]) {
  4999. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  5000. d3d12CommandBuffer,
  5001. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  5002. d3d12CommandBuffer->computeReadOnlyStorageBuffers[i]);
  5003. d3d12CommandBuffer->computeReadOnlyStorageBuffers[i] = NULL;
  5004. }
  5005. }
  5006. SDL_zeroa(d3d12CommandBuffer->computeSamplerTextureDescriptorHandles);
  5007. SDL_zeroa(d3d12CommandBuffer->computeSamplerDescriptorHandles);
  5008. SDL_zeroa(d3d12CommandBuffer->computeReadWriteStorageTextureDescriptorHandles);
  5009. SDL_zeroa(d3d12CommandBuffer->computeReadWriteStorageBufferDescriptorHandles);
  5010. d3d12CommandBuffer->currentComputePipeline = NULL;
  5011. }
  5012. // TransferBuffer Data
  5013. static void *D3D12_MapTransferBuffer(
  5014. SDL_GPURenderer *driverData,
  5015. SDL_GPUTransferBuffer *transferBuffer,
  5016. bool cycle)
  5017. {
  5018. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  5019. D3D12BufferContainer *container = (D3D12BufferContainer *)transferBuffer;
  5020. void *dataPointer;
  5021. if (
  5022. cycle &&
  5023. SDL_GetAtomicInt(&container->activeBuffer->referenceCount) > 0) {
  5024. D3D12_INTERNAL_CycleActiveBuffer(
  5025. renderer,
  5026. container);
  5027. }
  5028. // Upload buffers are persistently mapped, download buffers are not
  5029. if (container->type == D3D12_BUFFER_TYPE_UPLOAD) {
  5030. dataPointer = container->activeBuffer->mapPointer;
  5031. } else {
  5032. ID3D12Resource_Map(
  5033. container->activeBuffer->handle,
  5034. 0,
  5035. NULL,
  5036. (void **)&dataPointer);
  5037. }
  5038. return dataPointer;
  5039. }
  5040. static void D3D12_UnmapTransferBuffer(
  5041. SDL_GPURenderer *driverData,
  5042. SDL_GPUTransferBuffer *transferBuffer)
  5043. {
  5044. (void)driverData;
  5045. D3D12BufferContainer *container = (D3D12BufferContainer *)transferBuffer;
  5046. // Upload buffers are persistently mapped, download buffers are not
  5047. if (container->type == D3D12_BUFFER_TYPE_DOWNLOAD) {
  5048. ID3D12Resource_Unmap(
  5049. container->activeBuffer->handle,
  5050. 0,
  5051. NULL);
  5052. }
  5053. }
  5054. // Copy Pass
  5055. static void D3D12_BeginCopyPass(
  5056. SDL_GPUCommandBuffer *commandBuffer)
  5057. {
  5058. // no-op
  5059. (void)commandBuffer;
  5060. }
  5061. static void D3D12_UploadToTexture(
  5062. SDL_GPUCommandBuffer *commandBuffer,
  5063. const SDL_GPUTextureTransferInfo *source,
  5064. const SDL_GPUTextureRegion *destination,
  5065. bool cycle)
  5066. {
  5067. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5068. D3D12BufferContainer *transferBufferContainer = (D3D12BufferContainer *)source->transfer_buffer;
  5069. D3D12Buffer *temporaryBuffer = NULL;
  5070. D3D12_TEXTURE_COPY_LOCATION sourceLocation;
  5071. D3D12_TEXTURE_COPY_LOCATION destinationLocation;
  5072. Uint32 pixelsPerRow = source->pixels_per_row;
  5073. Uint32 rowPitch;
  5074. Uint32 alignedRowPitch;
  5075. Uint32 rowsPerSlice = source->rows_per_layer;
  5076. Uint32 bytesPerSlice;
  5077. Uint32 alignedBytesPerSlice;
  5078. bool needsRealignment;
  5079. bool needsPlacementCopy;
  5080. // Note that the transfer buffer does not need a barrier, as it is synced by the client.
  5081. D3D12TextureContainer *textureContainer = (D3D12TextureContainer *)destination->texture;
  5082. D3D12TextureSubresource *textureSubresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  5083. d3d12CommandBuffer,
  5084. textureContainer,
  5085. destination->layer,
  5086. destination->mip_level,
  5087. cycle,
  5088. D3D12_RESOURCE_STATE_COPY_DEST);
  5089. /* D3D12 requires texture data row pitch to be 256 byte aligned, which is obviously insane.
  5090. * Instead of exposing that restriction to the client, which is a huge rake to step on,
  5091. * and a restriction that no other backend requires, we're going to copy data to a temporary buffer,
  5092. * copy THAT data to the texture, and then get rid of the temporary buffer ASAP.
  5093. * If we're lucky and the row pitch and depth pitch are already aligned, we can skip all of that.
  5094. *
  5095. * D3D12 also requires offsets to be 512 byte aligned. We'll fix that for the client and warn them as well.
  5096. *
  5097. * And just for some extra fun, D3D12 doesn't actually support depth pitch, so we have to realign that too!
  5098. */
  5099. if (pixelsPerRow == 0) {
  5100. pixelsPerRow = destination->w;
  5101. }
  5102. rowPitch = BytesPerRow(pixelsPerRow, textureContainer->header.info.format);
  5103. if (rowsPerSlice == 0) {
  5104. rowsPerSlice = destination->h;
  5105. }
  5106. bytesPerSlice = rowsPerSlice * rowPitch;
  5107. alignedRowPitch = BytesPerRow(destination->w, textureContainer->header.info.format);
  5108. alignedRowPitch = D3D12_INTERNAL_Align(alignedRowPitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  5109. needsRealignment = rowsPerSlice != destination->h || rowPitch != alignedRowPitch;
  5110. needsPlacementCopy = source->offset % D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT != 0;
  5111. alignedBytesPerSlice = alignedRowPitch * destination->h;
  5112. sourceLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  5113. sourceLocation.PlacedFootprint.Footprint.Format = SDLToD3D12_TextureFormat[textureContainer->header.info.format];
  5114. sourceLocation.PlacedFootprint.Footprint.RowPitch = alignedRowPitch;
  5115. destinationLocation.pResource = textureContainer->activeTexture->resource;
  5116. destinationLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  5117. destinationLocation.SubresourceIndex = textureSubresource->index;
  5118. if (needsRealignment) {
  5119. temporaryBuffer = D3D12_INTERNAL_CreateBuffer(
  5120. d3d12CommandBuffer->renderer,
  5121. 0,
  5122. alignedRowPitch * destination->h * destination->d,
  5123. D3D12_BUFFER_TYPE_UPLOAD,
  5124. NULL);
  5125. if (!temporaryBuffer) {
  5126. return;
  5127. }
  5128. sourceLocation.pResource = temporaryBuffer->handle;
  5129. for (Uint32 sliceIndex = 0; sliceIndex < destination->d; sliceIndex += 1) {
  5130. // copy row count minus one to avoid overread
  5131. for (Uint32 rowIndex = 0; rowIndex < destination->h - 1; rowIndex += 1) {
  5132. SDL_memcpy(
  5133. temporaryBuffer->mapPointer + (sliceIndex * alignedBytesPerSlice) + (rowIndex * alignedRowPitch),
  5134. transferBufferContainer->activeBuffer->mapPointer + source->offset + (sliceIndex * bytesPerSlice) + (rowIndex * rowPitch),
  5135. alignedRowPitch);
  5136. }
  5137. Uint32 offset = source->offset + (sliceIndex * bytesPerSlice) + ((destination->h - 1) * rowPitch);
  5138. SDL_memcpy(
  5139. temporaryBuffer->mapPointer + (sliceIndex * alignedBytesPerSlice) + ((destination->h - 1) * alignedRowPitch),
  5140. transferBufferContainer->activeBuffer->mapPointer + offset,
  5141. SDL_min(alignedRowPitch, transferBufferContainer->size - offset));
  5142. sourceLocation.PlacedFootprint.Footprint.Width = destination->w;
  5143. sourceLocation.PlacedFootprint.Footprint.Height = destination->h;
  5144. sourceLocation.PlacedFootprint.Footprint.Depth = 1;
  5145. sourceLocation.PlacedFootprint.Offset = (sliceIndex * alignedBytesPerSlice);
  5146. ID3D12GraphicsCommandList_CopyTextureRegion(
  5147. d3d12CommandBuffer->graphicsCommandList,
  5148. &destinationLocation,
  5149. destination->x,
  5150. destination->y,
  5151. destination->z + sliceIndex,
  5152. &sourceLocation,
  5153. NULL);
  5154. }
  5155. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, temporaryBuffer);
  5156. D3D12_INTERNAL_ReleaseBuffer(
  5157. d3d12CommandBuffer->renderer,
  5158. temporaryBuffer);
  5159. if (d3d12CommandBuffer->renderer->debug_mode) {
  5160. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Texture upload row pitch not aligned to 256 bytes! This is suboptimal on D3D12!");
  5161. }
  5162. } else if (needsPlacementCopy) {
  5163. temporaryBuffer = D3D12_INTERNAL_CreateBuffer(
  5164. d3d12CommandBuffer->renderer,
  5165. 0,
  5166. alignedRowPitch * destination->h * destination->d,
  5167. D3D12_BUFFER_TYPE_UPLOAD,
  5168. NULL);
  5169. if (!temporaryBuffer) {
  5170. return;
  5171. }
  5172. SDL_memcpy(
  5173. temporaryBuffer->mapPointer,
  5174. transferBufferContainer->activeBuffer->mapPointer + source->offset,
  5175. alignedRowPitch * destination->h * destination->d);
  5176. sourceLocation.pResource = temporaryBuffer->handle;
  5177. sourceLocation.PlacedFootprint.Offset = 0;
  5178. sourceLocation.PlacedFootprint.Footprint.Width = destination->w;
  5179. sourceLocation.PlacedFootprint.Footprint.Height = destination->h;
  5180. sourceLocation.PlacedFootprint.Footprint.Depth = destination->d;
  5181. ID3D12GraphicsCommandList_CopyTextureRegion(
  5182. d3d12CommandBuffer->graphicsCommandList,
  5183. &destinationLocation,
  5184. destination->x,
  5185. destination->y,
  5186. destination->z,
  5187. &sourceLocation,
  5188. NULL);
  5189. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, temporaryBuffer);
  5190. D3D12_INTERNAL_ReleaseBuffer(
  5191. d3d12CommandBuffer->renderer,
  5192. temporaryBuffer);
  5193. if (d3d12CommandBuffer->renderer->debug_mode) {
  5194. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Texture upload offset not aligned to 512 bytes! This is suboptimal on D3D12!");
  5195. }
  5196. } else {
  5197. sourceLocation.pResource = transferBufferContainer->activeBuffer->handle;
  5198. sourceLocation.PlacedFootprint.Offset = source->offset;
  5199. sourceLocation.PlacedFootprint.Footprint.Width = destination->w;
  5200. sourceLocation.PlacedFootprint.Footprint.Height = destination->h;
  5201. sourceLocation.PlacedFootprint.Footprint.Depth = destination->d;
  5202. ID3D12GraphicsCommandList_CopyTextureRegion(
  5203. d3d12CommandBuffer->graphicsCommandList,
  5204. &destinationLocation,
  5205. destination->x,
  5206. destination->y,
  5207. destination->z,
  5208. &sourceLocation,
  5209. NULL);
  5210. }
  5211. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  5212. d3d12CommandBuffer,
  5213. D3D12_RESOURCE_STATE_COPY_DEST,
  5214. textureSubresource);
  5215. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, transferBufferContainer->activeBuffer);
  5216. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, textureSubresource->parent);
  5217. }
  5218. static void D3D12_UploadToBuffer(
  5219. SDL_GPUCommandBuffer *commandBuffer,
  5220. const SDL_GPUTransferBufferLocation *source,
  5221. const SDL_GPUBufferRegion *destination,
  5222. bool cycle)
  5223. {
  5224. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5225. D3D12BufferContainer *transferBufferContainer = (D3D12BufferContainer *)source->transfer_buffer;
  5226. D3D12BufferContainer *bufferContainer = (D3D12BufferContainer *)destination->buffer;
  5227. // The transfer buffer does not need a barrier, it is synced by the client.
  5228. D3D12Buffer *buffer = D3D12_INTERNAL_PrepareBufferForWrite(
  5229. d3d12CommandBuffer,
  5230. bufferContainer,
  5231. cycle,
  5232. D3D12_RESOURCE_STATE_COPY_DEST);
  5233. ID3D12GraphicsCommandList_CopyBufferRegion(
  5234. d3d12CommandBuffer->graphicsCommandList,
  5235. buffer->handle,
  5236. destination->offset,
  5237. transferBufferContainer->activeBuffer->handle,
  5238. source->offset,
  5239. destination->size);
  5240. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  5241. d3d12CommandBuffer,
  5242. D3D12_RESOURCE_STATE_COPY_DEST,
  5243. buffer);
  5244. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, transferBufferContainer->activeBuffer);
  5245. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, buffer);
  5246. }
  5247. static void D3D12_CopyTextureToTexture(
  5248. SDL_GPUCommandBuffer *commandBuffer,
  5249. const SDL_GPUTextureLocation *source,
  5250. const SDL_GPUTextureLocation *destination,
  5251. Uint32 w,
  5252. Uint32 h,
  5253. Uint32 d,
  5254. bool cycle)
  5255. {
  5256. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5257. D3D12_TEXTURE_COPY_LOCATION sourceLocation;
  5258. D3D12_TEXTURE_COPY_LOCATION destinationLocation;
  5259. D3D12TextureSubresource *sourceSubresource = D3D12_INTERNAL_FetchTextureSubresource(
  5260. (D3D12TextureContainer *)source->texture,
  5261. source->layer,
  5262. source->mip_level);
  5263. D3D12TextureSubresource *destinationSubresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  5264. d3d12CommandBuffer,
  5265. (D3D12TextureContainer *)destination->texture,
  5266. destination->layer,
  5267. destination->mip_level,
  5268. cycle,
  5269. D3D12_RESOURCE_STATE_COPY_DEST);
  5270. D3D12_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  5271. d3d12CommandBuffer,
  5272. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5273. sourceSubresource);
  5274. sourceLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  5275. sourceLocation.SubresourceIndex = sourceSubresource->index;
  5276. sourceLocation.pResource = sourceSubresource->parent->resource;
  5277. destinationLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  5278. destinationLocation.SubresourceIndex = destinationSubresource->index;
  5279. destinationLocation.pResource = destinationSubresource->parent->resource;
  5280. D3D12_BOX sourceBox = { source->x, source->y, source->z, source->x + w, source->y + h, source->z + d };
  5281. ID3D12GraphicsCommandList_CopyTextureRegion(
  5282. d3d12CommandBuffer->graphicsCommandList,
  5283. &destinationLocation,
  5284. destination->x,
  5285. destination->y,
  5286. destination->z,
  5287. &sourceLocation,
  5288. &sourceBox);
  5289. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  5290. d3d12CommandBuffer,
  5291. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5292. sourceSubresource);
  5293. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  5294. d3d12CommandBuffer,
  5295. D3D12_RESOURCE_STATE_COPY_DEST,
  5296. destinationSubresource);
  5297. D3D12_INTERNAL_TrackTexture(
  5298. d3d12CommandBuffer,
  5299. sourceSubresource->parent);
  5300. D3D12_INTERNAL_TrackTexture(
  5301. d3d12CommandBuffer,
  5302. destinationSubresource->parent);
  5303. }
  5304. static void D3D12_CopyBufferToBuffer(
  5305. SDL_GPUCommandBuffer *commandBuffer,
  5306. const SDL_GPUBufferLocation *source,
  5307. const SDL_GPUBufferLocation *destination,
  5308. Uint32 size,
  5309. bool cycle)
  5310. {
  5311. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5312. D3D12BufferContainer *sourceContainer = (D3D12BufferContainer *)source->buffer;
  5313. D3D12BufferContainer *destinationContainer = (D3D12BufferContainer *)destination->buffer;
  5314. D3D12Buffer *sourceBuffer = sourceContainer->activeBuffer;
  5315. D3D12Buffer *destinationBuffer = D3D12_INTERNAL_PrepareBufferForWrite(
  5316. d3d12CommandBuffer,
  5317. destinationContainer,
  5318. cycle,
  5319. D3D12_RESOURCE_STATE_COPY_DEST);
  5320. D3D12_INTERNAL_BufferTransitionFromDefaultUsage(
  5321. d3d12CommandBuffer,
  5322. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5323. sourceBuffer);
  5324. ID3D12GraphicsCommandList_CopyBufferRegion(
  5325. d3d12CommandBuffer->graphicsCommandList,
  5326. destinationBuffer->handle,
  5327. destination->offset,
  5328. sourceBuffer->handle,
  5329. source->offset,
  5330. size);
  5331. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  5332. d3d12CommandBuffer,
  5333. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5334. sourceBuffer);
  5335. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  5336. d3d12CommandBuffer,
  5337. D3D12_RESOURCE_STATE_COPY_DEST,
  5338. destinationBuffer);
  5339. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, sourceBuffer);
  5340. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, destinationBuffer);
  5341. }
  5342. static void D3D12_DownloadFromTexture(
  5343. SDL_GPUCommandBuffer *commandBuffer,
  5344. const SDL_GPUTextureRegion *source,
  5345. const SDL_GPUTextureTransferInfo *destination)
  5346. {
  5347. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5348. D3D12_TEXTURE_COPY_LOCATION sourceLocation;
  5349. D3D12_TEXTURE_COPY_LOCATION destinationLocation;
  5350. Uint32 pixelsPerRow = destination->pixels_per_row;
  5351. Uint32 rowPitch;
  5352. Uint32 alignedRowPitch;
  5353. Uint32 rowsPerSlice = destination->rows_per_layer;
  5354. bool needsRealignment;
  5355. bool needsPlacementCopy;
  5356. D3D12TextureDownload *textureDownload = NULL;
  5357. D3D12TextureContainer *sourceContainer = (D3D12TextureContainer *)source->texture;
  5358. D3D12TextureSubresource *sourceSubresource = D3D12_INTERNAL_FetchTextureSubresource(
  5359. sourceContainer,
  5360. source->layer,
  5361. source->mip_level);
  5362. D3D12BufferContainer *destinationContainer = (D3D12BufferContainer *)destination->transfer_buffer;
  5363. D3D12Buffer *destinationBuffer = destinationContainer->activeBuffer;
  5364. /* D3D12 requires texture data row pitch to be 256 byte aligned, which is obviously insane.
  5365. * Instead of exposing that restriction to the client, which is a huge rake to step on,
  5366. * and a restriction that no other backend requires, we're going to copy data to a temporary buffer,
  5367. * copy THAT data to the texture, and then get rid of the temporary buffer ASAP.
  5368. * If we're lucky and the row pitch and depth pitch are already aligned, we can skip all of that.
  5369. *
  5370. * D3D12 also requires offsets to be 512 byte aligned. We'll fix that for the client and warn them as well.
  5371. *
  5372. * And just for some extra fun, D3D12 doesn't actually support depth pitch, so we have to realign that too!
  5373. *
  5374. * Since this is an async download we have to do all these fixups after the command is finished,
  5375. * so we'll cache the metadata and map and copy it when the command buffer is cleaned.
  5376. */
  5377. if (pixelsPerRow == 0) {
  5378. pixelsPerRow = source->w;
  5379. }
  5380. rowPitch = BytesPerRow(pixelsPerRow, sourceContainer->header.info.format);
  5381. if (rowsPerSlice == 0) {
  5382. rowsPerSlice = source->h;
  5383. }
  5384. alignedRowPitch = D3D12_INTERNAL_Align(rowPitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  5385. needsRealignment = rowsPerSlice != source->h || rowPitch != alignedRowPitch;
  5386. needsPlacementCopy = destination->offset % D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT != 0;
  5387. sourceLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  5388. sourceLocation.SubresourceIndex = sourceSubresource->index;
  5389. sourceLocation.pResource = sourceSubresource->parent->resource;
  5390. D3D12_BOX sourceBox = { source->x, source->y, source->z, source->x + source->w, source->y + rowsPerSlice, source->z + source->d };
  5391. destinationLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  5392. destinationLocation.PlacedFootprint.Footprint.Format = SDLToD3D12_TextureFormat[sourceContainer->header.info.format];
  5393. destinationLocation.PlacedFootprint.Footprint.Width = source->w;
  5394. destinationLocation.PlacedFootprint.Footprint.Height = rowsPerSlice;
  5395. destinationLocation.PlacedFootprint.Footprint.Depth = source->d;
  5396. destinationLocation.PlacedFootprint.Footprint.RowPitch = alignedRowPitch;
  5397. if (needsRealignment || needsPlacementCopy) {
  5398. textureDownload = (D3D12TextureDownload *)SDL_malloc(sizeof(D3D12TextureDownload));
  5399. if (!textureDownload) {
  5400. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create texture download structure!");
  5401. return;
  5402. }
  5403. textureDownload->temporaryBuffer = D3D12_INTERNAL_CreateBuffer(
  5404. d3d12CommandBuffer->renderer,
  5405. 0,
  5406. alignedRowPitch * rowsPerSlice * source->d,
  5407. D3D12_BUFFER_TYPE_DOWNLOAD,
  5408. NULL);
  5409. if (!textureDownload->temporaryBuffer) {
  5410. SDL_free(textureDownload);
  5411. return;
  5412. }
  5413. textureDownload->destinationBuffer = destinationBuffer;
  5414. textureDownload->bufferOffset = destination->offset;
  5415. textureDownload->width = source->w;
  5416. textureDownload->height = rowsPerSlice;
  5417. textureDownload->depth = source->d;
  5418. textureDownload->bytesPerRow = rowPitch;
  5419. textureDownload->bytesPerDepthSlice = rowPitch * rowsPerSlice;
  5420. textureDownload->alignedBytesPerRow = alignedRowPitch;
  5421. destinationLocation.pResource = textureDownload->temporaryBuffer->handle;
  5422. destinationLocation.PlacedFootprint.Offset = 0;
  5423. if (d3d12CommandBuffer->renderer->debug_mode) {
  5424. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Texture pitch or offset not aligned properly! This is suboptimal on D3D12!");
  5425. }
  5426. } else {
  5427. destinationLocation.pResource = destinationBuffer->handle;
  5428. destinationLocation.PlacedFootprint.Offset = destination->offset;
  5429. }
  5430. D3D12_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  5431. d3d12CommandBuffer,
  5432. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5433. sourceSubresource);
  5434. ID3D12GraphicsCommandList_CopyTextureRegion(
  5435. d3d12CommandBuffer->graphicsCommandList,
  5436. &destinationLocation,
  5437. 0,
  5438. 0,
  5439. 0,
  5440. &sourceLocation,
  5441. &sourceBox);
  5442. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  5443. d3d12CommandBuffer,
  5444. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5445. sourceSubresource);
  5446. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, destinationBuffer);
  5447. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, sourceSubresource->parent);
  5448. if (textureDownload != NULL) {
  5449. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, textureDownload->temporaryBuffer);
  5450. if (d3d12CommandBuffer->textureDownloadCount >= d3d12CommandBuffer->textureDownloadCapacity) {
  5451. d3d12CommandBuffer->textureDownloadCapacity *= 2;
  5452. d3d12CommandBuffer->textureDownloads = (D3D12TextureDownload **)SDL_realloc(
  5453. d3d12CommandBuffer->textureDownloads,
  5454. d3d12CommandBuffer->textureDownloadCapacity * sizeof(D3D12TextureDownload *));
  5455. }
  5456. d3d12CommandBuffer->textureDownloads[d3d12CommandBuffer->textureDownloadCount] = textureDownload;
  5457. d3d12CommandBuffer->textureDownloadCount += 1;
  5458. D3D12_INTERNAL_ReleaseBuffer(d3d12CommandBuffer->renderer, textureDownload->temporaryBuffer);
  5459. }
  5460. }
  5461. static void D3D12_DownloadFromBuffer(
  5462. SDL_GPUCommandBuffer *commandBuffer,
  5463. const SDL_GPUBufferRegion *source,
  5464. const SDL_GPUTransferBufferLocation *destination)
  5465. {
  5466. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5467. D3D12BufferContainer *sourceContainer = (D3D12BufferContainer *)source->buffer;
  5468. D3D12BufferContainer *destinationContainer = (D3D12BufferContainer *)destination->transfer_buffer;
  5469. D3D12Buffer *sourceBuffer = sourceContainer->activeBuffer;
  5470. D3D12_INTERNAL_BufferTransitionFromDefaultUsage(
  5471. d3d12CommandBuffer,
  5472. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5473. sourceBuffer);
  5474. D3D12Buffer *destinationBuffer = destinationContainer->activeBuffer;
  5475. ID3D12GraphicsCommandList_CopyBufferRegion(
  5476. d3d12CommandBuffer->graphicsCommandList,
  5477. destinationBuffer->handle,
  5478. destination->offset,
  5479. sourceBuffer->handle,
  5480. source->offset,
  5481. source->size);
  5482. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  5483. d3d12CommandBuffer,
  5484. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5485. sourceBuffer);
  5486. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, sourceBuffer);
  5487. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, destinationBuffer);
  5488. }
  5489. static void D3D12_EndCopyPass(
  5490. SDL_GPUCommandBuffer *commandBuffer)
  5491. {
  5492. // no-op
  5493. (void)commandBuffer;
  5494. }
  5495. static void D3D12_GenerateMipmaps(
  5496. SDL_GPUCommandBuffer *commandBuffer,
  5497. SDL_GPUTexture *texture)
  5498. {
  5499. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5500. D3D12Renderer *renderer = d3d12CommandBuffer->renderer;
  5501. D3D12TextureContainer *container = (D3D12TextureContainer *)texture;
  5502. SDL_GPUGraphicsPipeline *blitPipeline;
  5503. blitPipeline = SDL_GPU_FetchBlitPipeline(
  5504. renderer->sdlGPUDevice,
  5505. container->header.info.type,
  5506. container->header.info.format,
  5507. renderer->blitVertexShader,
  5508. renderer->blitFrom2DShader,
  5509. renderer->blitFrom2DArrayShader,
  5510. renderer->blitFrom3DShader,
  5511. renderer->blitFromCubeShader,
  5512. renderer->blitFromCubeArrayShader,
  5513. &renderer->blitPipelines,
  5514. &renderer->blitPipelineCount,
  5515. &renderer->blitPipelineCapacity);
  5516. if (blitPipeline == NULL) {
  5517. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Could not fetch blit pipeline");
  5518. return;
  5519. }
  5520. // We have to do this one subresource at a time
  5521. for (Uint32 layerOrDepthIndex = 0; layerOrDepthIndex < container->header.info.layer_count_or_depth; layerOrDepthIndex += 1) {
  5522. for (Uint32 levelIndex = 1; levelIndex < container->header.info.num_levels; levelIndex += 1) {
  5523. SDL_GPUBlitInfo blitInfo;
  5524. SDL_zero(blitInfo);
  5525. blitInfo.source.texture = texture;
  5526. blitInfo.source.mip_level = levelIndex - 1;
  5527. blitInfo.source.layer_or_depth_plane = layerOrDepthIndex;
  5528. blitInfo.source.x = 0;
  5529. blitInfo.source.y = 0;
  5530. blitInfo.source.w = SDL_max(container->header.info.width >> (levelIndex - 1), 1);
  5531. blitInfo.source.h = SDL_max(container->header.info.height >> (levelIndex - 1), 1);
  5532. blitInfo.destination.texture = texture;
  5533. blitInfo.destination.mip_level = levelIndex;
  5534. blitInfo.destination.layer_or_depth_plane = layerOrDepthIndex;
  5535. blitInfo.destination.x = 0;
  5536. blitInfo.destination.y = 0;
  5537. blitInfo.destination.w = SDL_max(container->header.info.width >> levelIndex, 1);
  5538. blitInfo.destination.h = SDL_max(container->header.info.height >> levelIndex, 1);
  5539. blitInfo.load_op = SDL_GPU_LOADOP_DONT_CARE;
  5540. blitInfo.filter = SDL_GPU_FILTER_LINEAR;
  5541. SDL_BlitGPUTexture(
  5542. commandBuffer,
  5543. &blitInfo);
  5544. }
  5545. }
  5546. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, container->activeTexture);
  5547. }
  5548. static void D3D12_Blit(
  5549. SDL_GPUCommandBuffer *commandBuffer,
  5550. const SDL_GPUBlitInfo *info)
  5551. {
  5552. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5553. D3D12Renderer *renderer = (D3D12Renderer *)d3d12CommandBuffer->renderer;
  5554. SDL_GPU_BlitCommon(
  5555. commandBuffer,
  5556. info,
  5557. renderer->blitLinearSampler,
  5558. renderer->blitNearestSampler,
  5559. renderer->blitVertexShader,
  5560. renderer->blitFrom2DShader,
  5561. renderer->blitFrom2DArrayShader,
  5562. renderer->blitFrom3DShader,
  5563. renderer->blitFromCubeShader,
  5564. renderer->blitFromCubeArrayShader,
  5565. &renderer->blitPipelines,
  5566. &renderer->blitPipelineCount,
  5567. &renderer->blitPipelineCapacity);
  5568. }
  5569. // Submission/Presentation
  5570. static D3D12WindowData *D3D12_INTERNAL_FetchWindowData(
  5571. SDL_Window *window)
  5572. {
  5573. SDL_PropertiesID properties = SDL_GetWindowProperties(window);
  5574. return (D3D12WindowData *)SDL_GetPointerProperty(properties, WINDOW_PROPERTY_DATA, NULL);
  5575. }
  5576. static bool D3D12_INTERNAL_OnWindowResize(void *userdata, SDL_Event *e)
  5577. {
  5578. SDL_Window *w = (SDL_Window *)userdata;
  5579. D3D12WindowData *data;
  5580. if (e->type == SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED && e->window.windowID == SDL_GetWindowID(w)) {
  5581. data = D3D12_INTERNAL_FetchWindowData(w);
  5582. data->needsSwapchainRecreate = true;
  5583. }
  5584. return true;
  5585. }
  5586. static bool D3D12_SupportsSwapchainComposition(
  5587. SDL_GPURenderer *driverData,
  5588. SDL_Window *window,
  5589. SDL_GPUSwapchainComposition swapchainComposition)
  5590. {
  5591. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  5592. // FIXME: HDR support would be nice to add, but it seems complicated...
  5593. return swapchainComposition == SDL_GPU_SWAPCHAINCOMPOSITION_SDR ||
  5594. swapchainComposition == SDL_GPU_SWAPCHAINCOMPOSITION_SDR_LINEAR;
  5595. #else
  5596. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  5597. DXGI_FORMAT format;
  5598. D3D12_FEATURE_DATA_FORMAT_SUPPORT formatSupport;
  5599. Uint32 colorSpaceSupport;
  5600. HRESULT res;
  5601. format = SwapchainCompositionToTextureFormat[swapchainComposition];
  5602. formatSupport.Format = format;
  5603. res = ID3D12Device_CheckFeatureSupport(
  5604. renderer->device,
  5605. D3D12_FEATURE_FORMAT_SUPPORT,
  5606. &formatSupport,
  5607. sizeof(formatSupport));
  5608. if (FAILED(res)) {
  5609. // Format is apparently unknown
  5610. return false;
  5611. }
  5612. if (!(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_DISPLAY)) {
  5613. return false;
  5614. }
  5615. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  5616. if (windowData == NULL) {
  5617. SET_STRING_ERROR_AND_RETURN("Must claim window before querying swapchain composition support!", false);
  5618. }
  5619. // Check the color space support if necessary
  5620. if (swapchainComposition != SDL_GPU_SWAPCHAINCOMPOSITION_SDR) {
  5621. IDXGISwapChain3_CheckColorSpaceSupport(
  5622. windowData->swapchain,
  5623. SwapchainCompositionToColorSpace[swapchainComposition],
  5624. &colorSpaceSupport);
  5625. if (!(colorSpaceSupport & DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT)) {
  5626. return false;
  5627. }
  5628. }
  5629. #endif
  5630. return true;
  5631. }
  5632. static bool D3D12_SupportsPresentMode(
  5633. SDL_GPURenderer *driverData,
  5634. SDL_Window *window,
  5635. SDL_GPUPresentMode presentMode)
  5636. {
  5637. (void)driverData;
  5638. (void)window;
  5639. switch (presentMode) {
  5640. case SDL_GPU_PRESENTMODE_IMMEDIATE:
  5641. case SDL_GPU_PRESENTMODE_VSYNC:
  5642. return true;
  5643. case SDL_GPU_PRESENTMODE_MAILBOX:
  5644. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  5645. return false;
  5646. #else
  5647. return true;
  5648. #endif
  5649. default:
  5650. SDL_assert(!"Unrecognized present mode");
  5651. return false;
  5652. }
  5653. }
  5654. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  5655. static bool D3D12_INTERNAL_CreateSwapchain(
  5656. D3D12Renderer *renderer,
  5657. D3D12WindowData *windowData,
  5658. SDL_GPUSwapchainComposition swapchain_composition,
  5659. SDL_GPUPresentMode present_mode)
  5660. {
  5661. int width, height;
  5662. SDL_GPUTextureCreateInfo createInfo;
  5663. D3D12Texture *texture;
  5664. // Get the swapchain size
  5665. SDL_SyncWindow(windowData->window);
  5666. SDL_GetWindowSizeInPixels(windowData->window, &width, &height);
  5667. // Min swapchain image count is 2
  5668. windowData->swapchainTextureCount = SDL_clamp(renderer->allowedFramesInFlight, 2, 3);
  5669. // Create the swapchain textures
  5670. SDL_zero(createInfo);
  5671. createInfo.type = SDL_GPU_TEXTURETYPE_2D;
  5672. createInfo.width = width;
  5673. createInfo.height = height;
  5674. createInfo.format = SwapchainCompositionToSDLTextureFormat[swapchain_composition];
  5675. createInfo.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
  5676. createInfo.layer_count_or_depth = 1;
  5677. createInfo.num_levels = 1;
  5678. for (Uint32 i = 0; i < windowData->swapchainTextureCount; i += 1) {
  5679. texture = D3D12_INTERNAL_CreateTexture(renderer, &createInfo, true, "Swapchain");
  5680. texture->container = &windowData->textureContainers[i];
  5681. windowData->textureContainers[i].activeTexture = texture;
  5682. windowData->textureContainers[i].canBeCycled = false;
  5683. windowData->textureContainers[i].header.info = createInfo;
  5684. windowData->textureContainers[i].textureCapacity = 1;
  5685. windowData->textureContainers[i].textureCount = 1;
  5686. windowData->textureContainers[i].textures = &windowData->textureContainers[i].activeTexture;
  5687. }
  5688. // Initialize the swapchain data
  5689. windowData->present_mode = present_mode;
  5690. windowData->swapchainComposition = swapchain_composition;
  5691. windowData->swapchainColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
  5692. windowData->frameCounter = 0;
  5693. windowData->width = width;
  5694. windowData->height = height;
  5695. // Precache blit pipelines for the swapchain format
  5696. for (Uint32 i = 0; i < 5; i += 1) {
  5697. SDL_GPU_FetchBlitPipeline(
  5698. renderer->sdlGPUDevice,
  5699. (SDL_GPUTextureType)i,
  5700. createInfo.format,
  5701. renderer->blitVertexShader,
  5702. renderer->blitFrom2DShader,
  5703. renderer->blitFrom2DArrayShader,
  5704. renderer->blitFrom3DShader,
  5705. renderer->blitFromCubeShader,
  5706. renderer->blitFromCubeArrayShader,
  5707. &renderer->blitPipelines,
  5708. &renderer->blitPipelineCount,
  5709. &renderer->blitPipelineCapacity);
  5710. }
  5711. return true;
  5712. }
  5713. static void D3D12_INTERNAL_DestroySwapchain(
  5714. D3D12Renderer *renderer,
  5715. D3D12WindowData *windowData)
  5716. {
  5717. renderer->commandQueue->PresentX(0, NULL, NULL);
  5718. for (Uint32 i = 0; i < windowData->swapchainTextureCount; i += 1) {
  5719. D3D12_INTERNAL_DestroyTexture(windowData->textureContainers[i].activeTexture);
  5720. }
  5721. }
  5722. static bool D3D12_INTERNAL_ResizeSwapchain(
  5723. D3D12Renderer *renderer,
  5724. D3D12WindowData *windowData)
  5725. {
  5726. // Wait so we don't release in-flight views
  5727. D3D12_Wait((SDL_GPURenderer *)renderer);
  5728. // Present a black screen
  5729. renderer->commandQueue->PresentX(0, NULL, NULL);
  5730. // Clean up the previous swapchain textures
  5731. for (Uint32 i = 0; i < windowData->swapchainTextureCount; i += 1) {
  5732. D3D12_INTERNAL_DestroyTexture(windowData->textureContainers[i].activeTexture);
  5733. }
  5734. // Create a new swapchain
  5735. D3D12_INTERNAL_CreateSwapchain(
  5736. renderer,
  5737. windowData,
  5738. windowData->swapchainComposition,
  5739. windowData->present_mode);
  5740. windowData->needsSwapchainRecreate = false;
  5741. return true;
  5742. }
  5743. #else
  5744. static bool D3D12_INTERNAL_InitializeSwapchainTexture(
  5745. D3D12Renderer *renderer,
  5746. IDXGISwapChain3 *swapchain,
  5747. SDL_GPUSwapchainComposition composition,
  5748. Uint32 index,
  5749. D3D12TextureContainer *pTextureContainer)
  5750. {
  5751. D3D12Texture *pTexture;
  5752. ID3D12Resource *swapchainTexture;
  5753. D3D12_RESOURCE_DESC textureDesc;
  5754. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  5755. D3D12_RENDER_TARGET_VIEW_DESC rtvDesc;
  5756. DXGI_FORMAT swapchainFormat = SwapchainCompositionToTextureFormat[composition];
  5757. HRESULT res;
  5758. res = IDXGISwapChain_GetBuffer(
  5759. swapchain,
  5760. index,
  5761. D3D_GUID(D3D_IID_ID3D12Resource),
  5762. (void **)&swapchainTexture);
  5763. CHECK_D3D12_ERROR_AND_RETURN("Could not get buffer from swapchain!", false);
  5764. pTexture = (D3D12Texture *)SDL_calloc(1, sizeof(D3D12Texture));
  5765. if (!pTexture) {
  5766. ID3D12Resource_Release(swapchainTexture);
  5767. return false;
  5768. }
  5769. pTexture->resource = NULL; // This will be set in AcquireSwapchainTexture
  5770. SDL_SetAtomicInt(&pTexture->referenceCount, 0);
  5771. pTexture->subresourceCount = 1;
  5772. pTexture->subresources = (D3D12TextureSubresource *)SDL_calloc(1, sizeof(D3D12TextureSubresource));
  5773. if (!pTexture->subresources) {
  5774. SDL_free(pTexture);
  5775. ID3D12Resource_Release(swapchainTexture);
  5776. return false;
  5777. }
  5778. pTexture->subresources[0].rtvHandles = SDL_calloc(1, sizeof(D3D12StagingDescriptor));
  5779. pTexture->subresources[0].uavHandle.heap = NULL;
  5780. pTexture->subresources[0].dsvHandle.heap = NULL;
  5781. pTexture->subresources[0].parent = pTexture;
  5782. pTexture->subresources[0].index = 0;
  5783. pTexture->subresources[0].layer = 0;
  5784. pTexture->subresources[0].depth = 1;
  5785. pTexture->subresources[0].level = 0;
  5786. ID3D12Resource_GetDesc(swapchainTexture, &textureDesc);
  5787. pTextureContainer->header.info.width = (Uint32)textureDesc.Width;
  5788. pTextureContainer->header.info.height = (Uint32)textureDesc.Height;
  5789. pTextureContainer->header.info.layer_count_or_depth = 1;
  5790. pTextureContainer->header.info.num_levels = 1;
  5791. pTextureContainer->header.info.type = SDL_GPU_TEXTURETYPE_2D;
  5792. pTextureContainer->header.info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
  5793. pTextureContainer->header.info.sample_count = SDL_GPU_SAMPLECOUNT_1;
  5794. pTextureContainer->header.info.format = SwapchainCompositionToSDLTextureFormat[composition];
  5795. pTextureContainer->debugName = NULL;
  5796. pTextureContainer->textures = (D3D12Texture **)SDL_calloc(1, sizeof(D3D12Texture *));
  5797. if (!pTextureContainer->textures) {
  5798. SDL_free(pTexture->subresources);
  5799. SDL_free(pTexture);
  5800. ID3D12Resource_Release(swapchainTexture);
  5801. return false;
  5802. }
  5803. pTextureContainer->textureCapacity = 1;
  5804. pTextureContainer->textureCount = 1;
  5805. pTextureContainer->textures[0] = pTexture;
  5806. pTextureContainer->activeTexture = pTexture;
  5807. pTextureContainer->canBeCycled = false;
  5808. pTexture->container = pTextureContainer;
  5809. pTexture->containerIndex = 0;
  5810. // Create the SRV for the swapchain
  5811. D3D12_INTERNAL_AssignStagingDescriptorHandle(
  5812. renderer,
  5813. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  5814. &pTexture->srvHandle);
  5815. srvDesc.Format = SwapchainCompositionToTextureFormat[composition];
  5816. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  5817. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  5818. srvDesc.Texture2D.MipLevels = 1;
  5819. srvDesc.Texture2D.MostDetailedMip = 0;
  5820. srvDesc.Texture2D.ResourceMinLODClamp = 0;
  5821. srvDesc.Texture2D.PlaneSlice = 0;
  5822. ID3D12Device_CreateShaderResourceView(
  5823. renderer->device,
  5824. swapchainTexture,
  5825. &srvDesc,
  5826. pTexture->srvHandle.cpuHandle);
  5827. // Create the RTV for the swapchain
  5828. D3D12_INTERNAL_AssignStagingDescriptorHandle(
  5829. renderer,
  5830. D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  5831. &pTexture->subresources[0].rtvHandles[0]);
  5832. rtvDesc.Format = (composition == SDL_GPU_SWAPCHAINCOMPOSITION_SDR_LINEAR) ? DXGI_FORMAT_B8G8R8A8_UNORM_SRGB : swapchainFormat;
  5833. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
  5834. rtvDesc.Texture2D.MipSlice = 0;
  5835. rtvDesc.Texture2D.PlaneSlice = 0;
  5836. ID3D12Device_CreateRenderTargetView(
  5837. renderer->device,
  5838. swapchainTexture,
  5839. &rtvDesc,
  5840. pTexture->subresources[0].rtvHandles[0].cpuHandle);
  5841. ID3D12Resource_Release(swapchainTexture);
  5842. return true;
  5843. }
  5844. static bool D3D12_INTERNAL_ResizeSwapchain(
  5845. D3D12Renderer *renderer,
  5846. D3D12WindowData *windowData)
  5847. {
  5848. // Wait so we don't release in-flight views
  5849. D3D12_Wait((SDL_GPURenderer *)renderer);
  5850. // Release views and clean up
  5851. for (Uint32 i = 0; i < windowData->swapchainTextureCount; i += 1) {
  5852. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  5853. &windowData->textureContainers[i].activeTexture->srvHandle);
  5854. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  5855. &windowData->textureContainers[i].activeTexture->subresources[0].rtvHandles[0]);
  5856. SDL_free(windowData->textureContainers[i].activeTexture->subresources[0].rtvHandles);
  5857. SDL_free(windowData->textureContainers[i].activeTexture->subresources);
  5858. SDL_free(windowData->textureContainers[i].activeTexture);
  5859. SDL_free(windowData->textureContainers[i].textures);
  5860. }
  5861. // Resize the swapchain
  5862. HRESULT res = IDXGISwapChain_ResizeBuffers(
  5863. windowData->swapchain,
  5864. 0, // Keep buffer count the same
  5865. 0, // use client window width
  5866. 0, // use client window height
  5867. DXGI_FORMAT_UNKNOWN, // Keep the old format
  5868. renderer->supportsTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0);
  5869. CHECK_D3D12_ERROR_AND_RETURN("Could not resize swapchain buffers", false);
  5870. // Create texture object for the swapchain
  5871. for (Uint32 i = 0; i < windowData->swapchainTextureCount; i += 1) {
  5872. if (!D3D12_INTERNAL_InitializeSwapchainTexture(
  5873. renderer,
  5874. windowData->swapchain,
  5875. windowData->swapchainComposition,
  5876. i,
  5877. &windowData->textureContainers[i])) {
  5878. return false;
  5879. }
  5880. }
  5881. DXGI_SWAP_CHAIN_DESC1 swapchainDesc;
  5882. IDXGISwapChain3_GetDesc1(windowData->swapchain, &swapchainDesc);
  5883. CHECK_D3D12_ERROR_AND_RETURN("Failed to retrieve swapchain descriptor!", false);
  5884. windowData->width = swapchainDesc.Width;
  5885. windowData->height = swapchainDesc.Height;
  5886. windowData->needsSwapchainRecreate = false;
  5887. return true;
  5888. }
  5889. static void D3D12_INTERNAL_DestroySwapchain(
  5890. D3D12Renderer *renderer,
  5891. D3D12WindowData *windowData)
  5892. {
  5893. // Release views and clean up
  5894. for (Uint32 i = 0; i < windowData->swapchainTextureCount; i += 1) {
  5895. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  5896. &windowData->textureContainers[i].activeTexture->srvHandle);
  5897. D3D12_INTERNAL_ReleaseStagingDescriptorHandle(
  5898. &windowData->textureContainers[i].activeTexture->subresources[0].rtvHandles[0]);
  5899. SDL_free(windowData->textureContainers[i].activeTexture->subresources[0].rtvHandles);
  5900. SDL_free(windowData->textureContainers[i].activeTexture->subresources);
  5901. SDL_free(windowData->textureContainers[i].activeTexture);
  5902. SDL_free(windowData->textureContainers[i].textures);
  5903. }
  5904. IDXGISwapChain_Release(windowData->swapchain);
  5905. windowData->swapchain = NULL;
  5906. }
  5907. static bool D3D12_INTERNAL_CreateSwapchain(
  5908. D3D12Renderer *renderer,
  5909. D3D12WindowData *windowData,
  5910. SDL_GPUSwapchainComposition swapchainComposition,
  5911. SDL_GPUPresentMode presentMode)
  5912. {
  5913. HWND dxgiHandle;
  5914. DXGI_SWAP_CHAIN_DESC1 swapchainDesc;
  5915. DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullscreenDesc;
  5916. DXGI_FORMAT swapchainFormat;
  5917. IDXGIFactory1 *pParent;
  5918. IDXGISwapChain1 *swapchain;
  5919. IDXGISwapChain3 *swapchain3;
  5920. HRESULT res;
  5921. // Get the DXGI handle
  5922. #ifdef _WIN32
  5923. dxgiHandle = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(windowData->window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL);
  5924. #else
  5925. dxgiHandle = (HWND)windowData->window;
  5926. #endif
  5927. swapchainFormat = SwapchainCompositionToTextureFormat[swapchainComposition];
  5928. // Min swapchain image count is 2
  5929. windowData->swapchainTextureCount = SDL_clamp(renderer->allowedFramesInFlight, 2, 3);
  5930. // Initialize the swapchain buffer descriptor
  5931. swapchainDesc.Width = 0; // use client window width
  5932. swapchainDesc.Height = 0; // use client window height
  5933. swapchainDesc.Format = swapchainFormat;
  5934. swapchainDesc.SampleDesc.Count = 1;
  5935. swapchainDesc.SampleDesc.Quality = 0;
  5936. swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  5937. swapchainDesc.BufferCount = windowData->swapchainTextureCount;
  5938. swapchainDesc.Scaling = DXGI_SCALING_NONE;
  5939. swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  5940. swapchainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
  5941. swapchainDesc.Flags = 0;
  5942. swapchainDesc.Stereo = 0;
  5943. // Initialize the fullscreen descriptor (if needed)
  5944. fullscreenDesc.RefreshRate.Numerator = 0;
  5945. fullscreenDesc.RefreshRate.Denominator = 0;
  5946. fullscreenDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  5947. fullscreenDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  5948. fullscreenDesc.Windowed = true;
  5949. if (renderer->supportsTearing) {
  5950. swapchainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
  5951. } else {
  5952. swapchainDesc.Flags = 0;
  5953. }
  5954. if (!IsWindow(dxgiHandle)) {
  5955. return false;
  5956. }
  5957. // Create the swapchain!
  5958. res = IDXGIFactory4_CreateSwapChainForHwnd(
  5959. renderer->factory,
  5960. (IUnknown *)renderer->commandQueue,
  5961. dxgiHandle,
  5962. &swapchainDesc,
  5963. &fullscreenDesc,
  5964. NULL,
  5965. &swapchain);
  5966. CHECK_D3D12_ERROR_AND_RETURN("Could not create swapchain", false);
  5967. res = IDXGISwapChain1_QueryInterface(
  5968. swapchain,
  5969. D3D_GUID(D3D_IID_IDXGISwapChain3),
  5970. (void **)&swapchain3);
  5971. IDXGISwapChain1_Release(swapchain);
  5972. CHECK_D3D12_ERROR_AND_RETURN("Could not create IDXGISwapChain3", false);
  5973. if (swapchainComposition != SDL_GPU_SWAPCHAINCOMPOSITION_SDR) {
  5974. // Support already verified if we hit this block
  5975. IDXGISwapChain3_SetColorSpace1(
  5976. swapchain3,
  5977. SwapchainCompositionToColorSpace[swapchainComposition]);
  5978. }
  5979. /*
  5980. * The swapchain's parent is a separate factory from the factory that
  5981. * we used to create the swapchain, and only that parent can be used to
  5982. * set the window association. Trying to set an association on our factory
  5983. * will silently fail and doesn't even verify arguments or return errors.
  5984. * See https://gamedev.net/forums/topic/634235-dxgidisabling-altenter/4999955/
  5985. */
  5986. res = IDXGISwapChain3_GetParent(
  5987. swapchain3,
  5988. D3D_GUID(D3D_IID_IDXGIFactory1),
  5989. (void **)&pParent);
  5990. if (FAILED(res)) {
  5991. SDL_LogWarn(
  5992. SDL_LOG_CATEGORY_GPU,
  5993. "Could not get swapchain parent! Error Code: " HRESULT_FMT,
  5994. res);
  5995. } else {
  5996. // Disable DXGI window crap
  5997. res = IDXGIFactory1_MakeWindowAssociation(
  5998. pParent,
  5999. dxgiHandle,
  6000. DXGI_MWA_NO_WINDOW_CHANGES);
  6001. if (FAILED(res)) {
  6002. SDL_LogWarn(
  6003. SDL_LOG_CATEGORY_GPU,
  6004. "MakeWindowAssociation failed! Error Code: " HRESULT_FMT,
  6005. res);
  6006. }
  6007. // We're done with the parent now
  6008. IDXGIFactory1_Release(pParent);
  6009. }
  6010. IDXGISwapChain3_GetDesc1(swapchain3, &swapchainDesc);
  6011. CHECK_D3D12_ERROR_AND_RETURN("Failed to retrieve swapchain descriptor!", false);
  6012. // Initialize the swapchain data
  6013. windowData->swapchain = swapchain3;
  6014. windowData->present_mode = presentMode;
  6015. windowData->swapchainComposition = swapchainComposition;
  6016. windowData->swapchainColorSpace = SwapchainCompositionToColorSpace[swapchainComposition];
  6017. windowData->frameCounter = 0;
  6018. windowData->width = swapchainDesc.Width;
  6019. windowData->height = swapchainDesc.Height;
  6020. // Precache blit pipelines for the swapchain format
  6021. for (Uint32 i = 0; i < 5; i += 1) {
  6022. SDL_GPU_FetchBlitPipeline(
  6023. renderer->sdlGPUDevice,
  6024. (SDL_GPUTextureType)i,
  6025. SwapchainCompositionToSDLTextureFormat[swapchainComposition],
  6026. renderer->blitVertexShader,
  6027. renderer->blitFrom2DShader,
  6028. renderer->blitFrom2DArrayShader,
  6029. renderer->blitFrom3DShader,
  6030. renderer->blitFromCubeShader,
  6031. renderer->blitFromCubeArrayShader,
  6032. &renderer->blitPipelines,
  6033. &renderer->blitPipelineCount,
  6034. &renderer->blitPipelineCapacity);
  6035. }
  6036. /* If a you are using a FLIP model format you can't create the swapchain as DXGI_FORMAT_B8G8R8A8_UNORM_SRGB.
  6037. * You have to create the swapchain as DXGI_FORMAT_B8G8R8A8_UNORM and then set the render target view's format to DXGI_FORMAT_B8G8R8A8_UNORM_SRGB
  6038. */
  6039. for (Uint32 i = 0; i < windowData->swapchainTextureCount; i += 1) {
  6040. if (!D3D12_INTERNAL_InitializeSwapchainTexture(
  6041. renderer,
  6042. swapchain3,
  6043. swapchainComposition,
  6044. i,
  6045. &windowData->textureContainers[i])) {
  6046. IDXGISwapChain3_Release(swapchain3);
  6047. return false;
  6048. }
  6049. }
  6050. return true;
  6051. }
  6052. #endif
  6053. static bool D3D12_ClaimWindow(
  6054. SDL_GPURenderer *driverData,
  6055. SDL_Window *window)
  6056. {
  6057. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6058. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  6059. if (windowData == NULL) {
  6060. windowData = (D3D12WindowData *)SDL_calloc(1, sizeof(D3D12WindowData));
  6061. if (!windowData) {
  6062. return false;
  6063. }
  6064. windowData->window = window;
  6065. if (D3D12_INTERNAL_CreateSwapchain(renderer, windowData, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, SDL_GPU_PRESENTMODE_VSYNC)) {
  6066. SDL_SetPointerProperty(SDL_GetWindowProperties(window), WINDOW_PROPERTY_DATA, windowData);
  6067. SDL_LockMutex(renderer->windowLock);
  6068. if (renderer->claimedWindowCount >= renderer->claimedWindowCapacity) {
  6069. renderer->claimedWindowCapacity *= 2;
  6070. renderer->claimedWindows = (D3D12WindowData **)SDL_realloc(
  6071. renderer->claimedWindows,
  6072. renderer->claimedWindowCapacity * sizeof(D3D12WindowData *));
  6073. }
  6074. renderer->claimedWindows[renderer->claimedWindowCount] = windowData;
  6075. renderer->claimedWindowCount += 1;
  6076. SDL_UnlockMutex(renderer->windowLock);
  6077. SDL_AddEventWatch(D3D12_INTERNAL_OnWindowResize, window);
  6078. return true;
  6079. } else {
  6080. SDL_free(windowData);
  6081. SET_STRING_ERROR_AND_RETURN("Could not create swapchain, failed to claim window!", false);
  6082. }
  6083. } else {
  6084. SET_STRING_ERROR_AND_RETURN("Window already claimed", false);
  6085. }
  6086. }
  6087. static void D3D12_ReleaseWindow(
  6088. SDL_GPURenderer *driverData,
  6089. SDL_Window *window)
  6090. {
  6091. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6092. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  6093. if (windowData == NULL) {
  6094. SET_STRING_ERROR_AND_RETURN("Window already unclaimed!", );
  6095. }
  6096. D3D12_Wait(driverData);
  6097. for (Uint32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  6098. if (windowData->inFlightFences[i] != NULL) {
  6099. D3D12_ReleaseFence(
  6100. driverData,
  6101. windowData->inFlightFences[i]);
  6102. windowData->inFlightFences[i] = NULL;
  6103. }
  6104. }
  6105. D3D12_INTERNAL_DestroySwapchain(renderer, windowData);
  6106. SDL_LockMutex(renderer->windowLock);
  6107. for (Uint32 i = 0; i < renderer->claimedWindowCount; i += 1) {
  6108. if (renderer->claimedWindows[i]->window == window) {
  6109. renderer->claimedWindows[i] = renderer->claimedWindows[renderer->claimedWindowCount - 1];
  6110. renderer->claimedWindowCount -= 1;
  6111. break;
  6112. }
  6113. }
  6114. SDL_UnlockMutex(renderer->windowLock);
  6115. SDL_free(windowData);
  6116. SDL_ClearProperty(SDL_GetWindowProperties(window), WINDOW_PROPERTY_DATA);
  6117. SDL_RemoveEventWatch(D3D12_INTERNAL_OnWindowResize, window);
  6118. }
  6119. static bool D3D12_SetSwapchainParameters(
  6120. SDL_GPURenderer *driverData,
  6121. SDL_Window *window,
  6122. SDL_GPUSwapchainComposition swapchainComposition,
  6123. SDL_GPUPresentMode presentMode)
  6124. {
  6125. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6126. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  6127. if (windowData == NULL) {
  6128. SET_STRING_ERROR_AND_RETURN("Cannot set swapchain parameters on unclaimed window!", false);
  6129. }
  6130. if (!D3D12_SupportsSwapchainComposition(driverData, window, swapchainComposition)) {
  6131. SET_STRING_ERROR_AND_RETURN("Swapchain composition not supported!", false);
  6132. }
  6133. if (!D3D12_SupportsPresentMode(driverData, window, presentMode)) {
  6134. SET_STRING_ERROR_AND_RETURN("Present mode not supported!", false);
  6135. }
  6136. if (
  6137. swapchainComposition != windowData->swapchainComposition ||
  6138. presentMode != windowData->present_mode) {
  6139. D3D12_Wait(driverData);
  6140. // Recreate the swapchain
  6141. D3D12_INTERNAL_DestroySwapchain(
  6142. renderer,
  6143. windowData);
  6144. return D3D12_INTERNAL_CreateSwapchain(
  6145. renderer,
  6146. windowData,
  6147. swapchainComposition,
  6148. presentMode);
  6149. }
  6150. return true;
  6151. }
  6152. static bool D3D12_SetAllowedFramesInFlight(
  6153. SDL_GPURenderer *driverData,
  6154. Uint32 allowedFramesInFlight)
  6155. {
  6156. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6157. if (!D3D12_Wait(driverData)) {
  6158. return false;
  6159. }
  6160. // Destroy all swapchains
  6161. for (Uint32 i = 0; i < renderer->claimedWindowCount; i += 1) {
  6162. D3D12WindowData *windowData = renderer->claimedWindows[i];
  6163. D3D12_INTERNAL_DestroySwapchain(renderer, windowData);
  6164. }
  6165. // Set the frames in flight value
  6166. renderer->allowedFramesInFlight = allowedFramesInFlight;
  6167. // Recreate all swapchains
  6168. for (Uint32 i = 0; i < renderer->claimedWindowCount; i += 1) {
  6169. D3D12WindowData *windowData = renderer->claimedWindows[i];
  6170. if (!D3D12_INTERNAL_CreateSwapchain(
  6171. renderer,
  6172. windowData,
  6173. windowData->swapchainComposition,
  6174. windowData->present_mode)) {
  6175. return false;
  6176. }
  6177. }
  6178. return true;
  6179. }
  6180. static SDL_GPUTextureFormat D3D12_GetSwapchainTextureFormat(
  6181. SDL_GPURenderer *driverData,
  6182. SDL_Window *window)
  6183. {
  6184. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6185. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  6186. if (windowData == NULL) {
  6187. SET_STRING_ERROR_AND_RETURN("Cannot get swapchain format, window has not been claimed!", SDL_GPU_TEXTUREFORMAT_INVALID);
  6188. }
  6189. return windowData->textureContainers[windowData->frameCounter].header.info.format;
  6190. }
  6191. static D3D12Fence *D3D12_INTERNAL_AcquireFence(
  6192. D3D12Renderer *renderer)
  6193. {
  6194. D3D12Fence *fence;
  6195. ID3D12Fence *handle;
  6196. HRESULT res;
  6197. SDL_LockMutex(renderer->fenceLock);
  6198. if (renderer->availableFenceCount == 0) {
  6199. res = ID3D12Device_CreateFence(
  6200. renderer->device,
  6201. D3D12_FENCE_UNSIGNALED_VALUE,
  6202. D3D12_FENCE_FLAG_NONE,
  6203. D3D_GUID(D3D_IID_ID3D12Fence),
  6204. (void **)&handle);
  6205. if (FAILED(res)) {
  6206. D3D12_INTERNAL_SetError(renderer, "Failed to create fence!", res);
  6207. SDL_UnlockMutex(renderer->fenceLock);
  6208. return NULL;
  6209. }
  6210. fence = (D3D12Fence *)SDL_calloc(1, sizeof(D3D12Fence));
  6211. if (!fence) {
  6212. ID3D12Fence_Release(handle);
  6213. SDL_UnlockMutex(renderer->fenceLock);
  6214. return NULL;
  6215. }
  6216. fence->handle = handle;
  6217. fence->event = CreateEvent(NULL, FALSE, FALSE, NULL);
  6218. SDL_SetAtomicInt(&fence->referenceCount, 0);
  6219. } else {
  6220. fence = renderer->availableFences[renderer->availableFenceCount - 1];
  6221. renderer->availableFenceCount -= 1;
  6222. ID3D12Fence_Signal(fence->handle, D3D12_FENCE_UNSIGNALED_VALUE);
  6223. }
  6224. SDL_UnlockMutex(renderer->fenceLock);
  6225. (void)SDL_AtomicIncRef(&fence->referenceCount);
  6226. return fence;
  6227. }
  6228. static bool D3D12_INTERNAL_AllocateCommandBuffer(
  6229. D3D12Renderer *renderer)
  6230. {
  6231. D3D12CommandBuffer *commandBuffer;
  6232. HRESULT res;
  6233. ID3D12CommandAllocator *commandAllocator;
  6234. ID3D12GraphicsCommandList *commandList;
  6235. commandBuffer = (D3D12CommandBuffer *)SDL_calloc(1, sizeof(D3D12CommandBuffer));
  6236. if (!commandBuffer) {
  6237. SET_STRING_ERROR_AND_RETURN("Failed to create ID3D12CommandList. Out of Memory", false);
  6238. }
  6239. res = ID3D12Device_CreateCommandAllocator(
  6240. renderer->device,
  6241. D3D12_COMMAND_LIST_TYPE_DIRECT,
  6242. D3D_GUID(D3D_IID_ID3D12CommandAllocator),
  6243. (void **)&commandAllocator);
  6244. if (FAILED(res)) {
  6245. D3D12_INTERNAL_SetError(renderer, "Failed to create ID3D12CommandAllocator", res);
  6246. D3D12_INTERNAL_DestroyCommandBuffer(commandBuffer);
  6247. return false;
  6248. }
  6249. commandBuffer->commandAllocator = commandAllocator;
  6250. res = ID3D12Device_CreateCommandList(
  6251. renderer->device,
  6252. 0,
  6253. D3D12_COMMAND_LIST_TYPE_DIRECT,
  6254. commandAllocator,
  6255. NULL,
  6256. D3D_GUID(D3D_IID_ID3D12GraphicsCommandList),
  6257. (void **)&commandList);
  6258. if (FAILED(res)) {
  6259. D3D12_INTERNAL_SetError(renderer, "Failed to create ID3D12CommandList", res);
  6260. D3D12_INTERNAL_DestroyCommandBuffer(commandBuffer);
  6261. return false;
  6262. }
  6263. commandBuffer->graphicsCommandList = commandList;
  6264. commandBuffer->renderer = renderer;
  6265. commandBuffer->inFlightFence = NULL;
  6266. // Window handling
  6267. commandBuffer->presentDataCapacity = 1;
  6268. commandBuffer->presentDataCount = 0;
  6269. commandBuffer->presentDatas = (D3D12PresentData *)SDL_calloc(
  6270. commandBuffer->presentDataCapacity, sizeof(D3D12PresentData));
  6271. // Resource tracking
  6272. commandBuffer->usedTextureCapacity = 4;
  6273. commandBuffer->usedTextureCount = 0;
  6274. commandBuffer->usedTextures = (D3D12Texture **)SDL_calloc(
  6275. commandBuffer->usedTextureCapacity, sizeof(D3D12Texture *));
  6276. commandBuffer->usedBufferCapacity = 4;
  6277. commandBuffer->usedBufferCount = 0;
  6278. commandBuffer->usedBuffers = (D3D12Buffer **)SDL_calloc(
  6279. commandBuffer->usedBufferCapacity, sizeof(D3D12Buffer *));
  6280. commandBuffer->usedSamplerCapacity = 4;
  6281. commandBuffer->usedSamplerCount = 0;
  6282. commandBuffer->usedSamplers = (D3D12Sampler **)SDL_calloc(
  6283. commandBuffer->usedSamplerCapacity, sizeof(D3D12Sampler *));
  6284. commandBuffer->usedGraphicsPipelineCapacity = 4;
  6285. commandBuffer->usedGraphicsPipelineCount = 0;
  6286. commandBuffer->usedGraphicsPipelines = (D3D12GraphicsPipeline **)SDL_calloc(
  6287. commandBuffer->usedGraphicsPipelineCapacity, sizeof(D3D12GraphicsPipeline *));
  6288. commandBuffer->usedComputePipelineCapacity = 4;
  6289. commandBuffer->usedComputePipelineCount = 0;
  6290. commandBuffer->usedComputePipelines = (D3D12ComputePipeline **)SDL_calloc(
  6291. commandBuffer->usedComputePipelineCapacity, sizeof(D3D12ComputePipeline *));
  6292. commandBuffer->usedDescriptorHeapCapacity = 4;
  6293. commandBuffer->usedDescriptorHeapCount = 0;
  6294. commandBuffer->usedDescriptorHeaps = (D3D12DescriptorHeap **)SDL_calloc(
  6295. commandBuffer->usedDescriptorHeapCapacity, sizeof(D3D12DescriptorHeap *));
  6296. commandBuffer->usedUniformBufferCapacity = 4;
  6297. commandBuffer->usedUniformBufferCount = 0;
  6298. commandBuffer->usedUniformBuffers = (D3D12UniformBuffer **)SDL_calloc(
  6299. commandBuffer->usedUniformBufferCapacity, sizeof(D3D12UniformBuffer *));
  6300. commandBuffer->textureDownloadCapacity = 4;
  6301. commandBuffer->textureDownloadCount = 0;
  6302. commandBuffer->textureDownloads = (D3D12TextureDownload **)SDL_calloc(
  6303. commandBuffer->textureDownloadCapacity, sizeof(D3D12TextureDownload *));
  6304. if (
  6305. (!commandBuffer->presentDatas) ||
  6306. (!commandBuffer->usedTextures) ||
  6307. (!commandBuffer->usedBuffers) ||
  6308. (!commandBuffer->usedSamplers) ||
  6309. (!commandBuffer->usedGraphicsPipelines) ||
  6310. (!commandBuffer->usedComputePipelines) ||
  6311. (!commandBuffer->usedUniformBuffers) ||
  6312. (!commandBuffer->textureDownloads)) {
  6313. D3D12_INTERNAL_DestroyCommandBuffer(commandBuffer);
  6314. SET_STRING_ERROR_AND_RETURN("Failed to create ID3D12CommandList. Out of Memory", false);
  6315. }
  6316. D3D12CommandBuffer **resizedAvailableCommandBuffers = (D3D12CommandBuffer **)SDL_realloc(
  6317. renderer->availableCommandBuffers,
  6318. sizeof(D3D12CommandBuffer *) * (renderer->availableCommandBufferCapacity + 1));
  6319. if (!resizedAvailableCommandBuffers) {
  6320. D3D12_INTERNAL_DestroyCommandBuffer(commandBuffer);
  6321. SET_STRING_ERROR_AND_RETURN("Failed to create ID3D12CommandList. Out of Memory", false);
  6322. }
  6323. // Add to inactive command buffer array
  6324. renderer->availableCommandBufferCapacity += 1;
  6325. renderer->availableCommandBuffers = resizedAvailableCommandBuffers;
  6326. renderer->availableCommandBuffers[renderer->availableCommandBufferCount] = commandBuffer;
  6327. renderer->availableCommandBufferCount += 1;
  6328. return true;
  6329. }
  6330. static D3D12CommandBuffer *D3D12_INTERNAL_AcquireCommandBufferFromPool(
  6331. D3D12Renderer *renderer)
  6332. {
  6333. D3D12CommandBuffer *commandBuffer;
  6334. if (renderer->availableCommandBufferCount == 0) {
  6335. if (!D3D12_INTERNAL_AllocateCommandBuffer(renderer)) {
  6336. return NULL;
  6337. }
  6338. }
  6339. commandBuffer = renderer->availableCommandBuffers[renderer->availableCommandBufferCount - 1];
  6340. renderer->availableCommandBufferCount -= 1;
  6341. return commandBuffer;
  6342. }
  6343. static SDL_GPUCommandBuffer *D3D12_AcquireCommandBuffer(
  6344. SDL_GPURenderer *driverData)
  6345. {
  6346. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6347. D3D12CommandBuffer *commandBuffer;
  6348. ID3D12DescriptorHeap *heaps[2];
  6349. SDL_zeroa(heaps);
  6350. SDL_LockMutex(renderer->acquireCommandBufferLock);
  6351. commandBuffer = D3D12_INTERNAL_AcquireCommandBufferFromPool(renderer);
  6352. SDL_UnlockMutex(renderer->acquireCommandBufferLock);
  6353. if (commandBuffer == NULL) {
  6354. return NULL;
  6355. }
  6356. // Set the bind state
  6357. commandBuffer->currentGraphicsPipeline = NULL;
  6358. SDL_zeroa(commandBuffer->colorTargetSubresources);
  6359. SDL_zeroa(commandBuffer->colorResolveSubresources);
  6360. commandBuffer->depthStencilTextureSubresource = NULL;
  6361. SDL_zeroa(commandBuffer->vertexBuffers);
  6362. SDL_zeroa(commandBuffer->vertexBufferOffsets);
  6363. commandBuffer->vertexBufferCount = 0;
  6364. SDL_zeroa(commandBuffer->vertexSamplerTextureDescriptorHandles);
  6365. SDL_zeroa(commandBuffer->vertexSamplerDescriptorHandles);
  6366. SDL_zeroa(commandBuffer->vertexStorageTextureDescriptorHandles);
  6367. SDL_zeroa(commandBuffer->vertexStorageBufferDescriptorHandles);
  6368. SDL_zeroa(commandBuffer->vertexUniformBuffers);
  6369. SDL_zeroa(commandBuffer->fragmentSamplerTextureDescriptorHandles);
  6370. SDL_zeroa(commandBuffer->fragmentSamplerDescriptorHandles);
  6371. SDL_zeroa(commandBuffer->fragmentStorageTextureDescriptorHandles);
  6372. SDL_zeroa(commandBuffer->fragmentStorageBufferDescriptorHandles);
  6373. SDL_zeroa(commandBuffer->fragmentUniformBuffers);
  6374. SDL_zeroa(commandBuffer->computeSamplerTextureDescriptorHandles);
  6375. SDL_zeroa(commandBuffer->computeSamplerDescriptorHandles);
  6376. SDL_zeroa(commandBuffer->computeReadOnlyStorageTextureDescriptorHandles);
  6377. SDL_zeroa(commandBuffer->computeReadOnlyStorageBufferDescriptorHandles);
  6378. SDL_zeroa(commandBuffer->computeReadOnlyStorageTextures);
  6379. SDL_zeroa(commandBuffer->computeReadOnlyStorageBuffers);
  6380. SDL_zeroa(commandBuffer->computeReadWriteStorageTextureSubresources);
  6381. SDL_zeroa(commandBuffer->computeReadWriteStorageBuffers);
  6382. SDL_zeroa(commandBuffer->computeUniformBuffers);
  6383. commandBuffer->autoReleaseFence = true;
  6384. return (SDL_GPUCommandBuffer *)commandBuffer;
  6385. }
  6386. static bool D3D12_WaitForSwapchain(
  6387. SDL_GPURenderer *driverData,
  6388. SDL_Window *window)
  6389. {
  6390. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6391. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  6392. if (windowData == NULL) {
  6393. SET_STRING_ERROR_AND_RETURN("Cannot wait for a swapchain from an unclaimed window!", false);
  6394. }
  6395. if (windowData->inFlightFences[windowData->frameCounter] != NULL) {
  6396. if (!D3D12_WaitForFences(
  6397. driverData,
  6398. true,
  6399. &windowData->inFlightFences[windowData->frameCounter],
  6400. 1)) {
  6401. return false;
  6402. }
  6403. }
  6404. return true;
  6405. }
  6406. static bool D3D12_INTERNAL_AcquireSwapchainTexture(
  6407. bool block,
  6408. SDL_GPUCommandBuffer *commandBuffer,
  6409. SDL_Window *window,
  6410. SDL_GPUTexture **swapchainTexture,
  6411. Uint32 *swapchainTextureWidth,
  6412. Uint32 *swapchainTextureHeight)
  6413. {
  6414. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  6415. D3D12Renderer *renderer = d3d12CommandBuffer->renderer;
  6416. D3D12WindowData *windowData;
  6417. Uint32 swapchainIndex;
  6418. HRESULT res;
  6419. *swapchainTexture = NULL;
  6420. if (swapchainTextureWidth) {
  6421. *swapchainTextureWidth = 0;
  6422. }
  6423. if (swapchainTextureHeight) {
  6424. *swapchainTextureHeight = 0;
  6425. }
  6426. windowData = D3D12_INTERNAL_FetchWindowData(window);
  6427. if (windowData == NULL) {
  6428. SET_STRING_ERROR_AND_RETURN("Cannot acquire swapchain texture from an unclaimed window!", false);
  6429. }
  6430. if (windowData->needsSwapchainRecreate) {
  6431. if (!D3D12_INTERNAL_ResizeSwapchain(renderer, windowData)) {
  6432. return false;
  6433. }
  6434. }
  6435. if (swapchainTextureWidth) {
  6436. *swapchainTextureWidth = windowData->width;
  6437. }
  6438. if (swapchainTextureHeight) {
  6439. *swapchainTextureHeight = windowData->height;
  6440. }
  6441. if (windowData->inFlightFences[windowData->frameCounter] != NULL) {
  6442. if (block) {
  6443. // In VSYNC mode, block until the least recent presented frame is done
  6444. if (!D3D12_WaitForFences(
  6445. (SDL_GPURenderer *)renderer,
  6446. true,
  6447. &windowData->inFlightFences[windowData->frameCounter],
  6448. 1)) {
  6449. return false;
  6450. }
  6451. } else {
  6452. // If we are not blocking and the least recent fence is not signaled,
  6453. // return true to indicate that there is no error but rendering should be skipped.
  6454. if (!D3D12_QueryFence(
  6455. (SDL_GPURenderer *)renderer,
  6456. windowData->inFlightFences[windowData->frameCounter])) {
  6457. return true;
  6458. }
  6459. }
  6460. D3D12_ReleaseFence(
  6461. (SDL_GPURenderer *)renderer,
  6462. windowData->inFlightFences[windowData->frameCounter]);
  6463. windowData->inFlightFences[windowData->frameCounter] = NULL;
  6464. }
  6465. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  6466. // FIXME: Should this happen before the inFlightFences stuff above?
  6467. windowData->frameToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
  6468. renderer->device->WaitFrameEventX(D3D12XBOX_FRAME_EVENT_ORIGIN, INFINITE, NULL, D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE, &windowData->frameToken);
  6469. swapchainIndex = windowData->frameCounter;
  6470. #else
  6471. swapchainIndex = IDXGISwapChain3_GetCurrentBackBufferIndex(windowData->swapchain);
  6472. // Set the handle on the windowData texture data.
  6473. res = IDXGISwapChain_GetBuffer(
  6474. windowData->swapchain,
  6475. swapchainIndex,
  6476. D3D_GUID(D3D_IID_ID3D12Resource),
  6477. (void **)&windowData->textureContainers[swapchainIndex].activeTexture->resource);
  6478. CHECK_D3D12_ERROR_AND_RETURN("Could not acquire swapchain!", false);
  6479. #endif
  6480. // Set up presentation
  6481. if (d3d12CommandBuffer->presentDataCount == d3d12CommandBuffer->presentDataCapacity) {
  6482. d3d12CommandBuffer->presentDataCapacity += 1;
  6483. d3d12CommandBuffer->presentDatas = (D3D12PresentData *)SDL_realloc(
  6484. d3d12CommandBuffer->presentDatas,
  6485. d3d12CommandBuffer->presentDataCapacity * sizeof(D3D12PresentData));
  6486. }
  6487. d3d12CommandBuffer->presentDatas[d3d12CommandBuffer->presentDataCount].windowData = windowData;
  6488. d3d12CommandBuffer->presentDatas[d3d12CommandBuffer->presentDataCount].swapchainImageIndex = swapchainIndex;
  6489. d3d12CommandBuffer->presentDataCount += 1;
  6490. // Set up resource barrier
  6491. D3D12_RESOURCE_BARRIER barrierDesc;
  6492. barrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  6493. barrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  6494. barrierDesc.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
  6495. barrierDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
  6496. barrierDesc.Transition.pResource = windowData->textureContainers[swapchainIndex].activeTexture->resource;
  6497. barrierDesc.Transition.Subresource = 0;
  6498. ID3D12GraphicsCommandList_ResourceBarrier(
  6499. d3d12CommandBuffer->graphicsCommandList,
  6500. 1,
  6501. &barrierDesc);
  6502. *swapchainTexture = (SDL_GPUTexture *)&windowData->textureContainers[swapchainIndex];
  6503. return true;
  6504. }
  6505. static bool D3D12_AcquireSwapchainTexture(
  6506. SDL_GPUCommandBuffer *command_buffer,
  6507. SDL_Window *window,
  6508. SDL_GPUTexture **swapchain_texture,
  6509. Uint32 *swapchain_texture_width,
  6510. Uint32 *swapchain_texture_height
  6511. ) {
  6512. return D3D12_INTERNAL_AcquireSwapchainTexture(
  6513. false,
  6514. command_buffer,
  6515. window,
  6516. swapchain_texture,
  6517. swapchain_texture_width,
  6518. swapchain_texture_height);
  6519. }
  6520. static bool D3D12_WaitAndAcquireSwapchainTexture(
  6521. SDL_GPUCommandBuffer *command_buffer,
  6522. SDL_Window *window,
  6523. SDL_GPUTexture **swapchain_texture,
  6524. Uint32 *swapchain_texture_width,
  6525. Uint32 *swapchain_texture_height
  6526. ) {
  6527. return D3D12_INTERNAL_AcquireSwapchainTexture(
  6528. true,
  6529. command_buffer,
  6530. window,
  6531. swapchain_texture,
  6532. swapchain_texture_width,
  6533. swapchain_texture_height);
  6534. }
  6535. static void D3D12_INTERNAL_PerformPendingDestroys(D3D12Renderer *renderer)
  6536. {
  6537. SDL_LockMutex(renderer->disposeLock);
  6538. for (Sint32 i = renderer->buffersToDestroyCount - 1; i >= 0; i -= 1) {
  6539. if (SDL_GetAtomicInt(&renderer->buffersToDestroy[i]->referenceCount) == 0) {
  6540. D3D12_INTERNAL_DestroyBuffer(
  6541. renderer->buffersToDestroy[i]);
  6542. renderer->buffersToDestroy[i] = renderer->buffersToDestroy[renderer->buffersToDestroyCount - 1];
  6543. renderer->buffersToDestroyCount -= 1;
  6544. }
  6545. }
  6546. for (Sint32 i = renderer->texturesToDestroyCount - 1; i >= 0; i -= 1) {
  6547. if (SDL_GetAtomicInt(&renderer->texturesToDestroy[i]->referenceCount) == 0) {
  6548. D3D12_INTERNAL_DestroyTexture(
  6549. renderer->texturesToDestroy[i]);
  6550. renderer->texturesToDestroy[i] = renderer->texturesToDestroy[renderer->texturesToDestroyCount - 1];
  6551. renderer->texturesToDestroyCount -= 1;
  6552. }
  6553. }
  6554. for (Sint32 i = renderer->samplersToDestroyCount - 1; i >= 0; i -= 1) {
  6555. if (SDL_GetAtomicInt(&renderer->samplersToDestroy[i]->referenceCount) == 0) {
  6556. D3D12_INTERNAL_DestroySampler(
  6557. renderer->samplersToDestroy[i]);
  6558. renderer->samplersToDestroy[i] = renderer->samplersToDestroy[renderer->samplersToDestroyCount - 1];
  6559. renderer->samplersToDestroyCount -= 1;
  6560. }
  6561. }
  6562. for (Sint32 i = renderer->graphicsPipelinesToDestroyCount - 1; i >= 0; i -= 1) {
  6563. if (SDL_GetAtomicInt(&renderer->graphicsPipelinesToDestroy[i]->referenceCount) == 0) {
  6564. D3D12_INTERNAL_DestroyGraphicsPipeline(
  6565. renderer->graphicsPipelinesToDestroy[i]);
  6566. renderer->graphicsPipelinesToDestroy[i] = renderer->graphicsPipelinesToDestroy[renderer->graphicsPipelinesToDestroyCount - 1];
  6567. renderer->graphicsPipelinesToDestroyCount -= 1;
  6568. }
  6569. }
  6570. for (Sint32 i = renderer->computePipelinesToDestroyCount - 1; i >= 0; i -= 1) {
  6571. if (SDL_GetAtomicInt(&renderer->computePipelinesToDestroy[i]->referenceCount) == 0) {
  6572. D3D12_INTERNAL_DestroyComputePipeline(
  6573. renderer->computePipelinesToDestroy[i]);
  6574. renderer->computePipelinesToDestroy[i] = renderer->computePipelinesToDestroy[renderer->computePipelinesToDestroyCount - 1];
  6575. renderer->computePipelinesToDestroyCount -= 1;
  6576. }
  6577. }
  6578. SDL_UnlockMutex(renderer->disposeLock);
  6579. }
  6580. static bool D3D12_INTERNAL_CopyTextureDownload(
  6581. D3D12CommandBuffer *commandBuffer,
  6582. D3D12TextureDownload *download)
  6583. {
  6584. D3D12Renderer *renderer = commandBuffer->renderer;
  6585. Uint8 *sourcePtr;
  6586. Uint8 *destPtr;
  6587. HRESULT res;
  6588. res = ID3D12Resource_Map(
  6589. download->temporaryBuffer->handle,
  6590. 0,
  6591. NULL,
  6592. (void **)&sourcePtr);
  6593. CHECK_D3D12_ERROR_AND_RETURN("Failed to map temporary buffer", false);
  6594. res = ID3D12Resource_Map(
  6595. download->destinationBuffer->handle,
  6596. 0,
  6597. NULL,
  6598. (void **)&destPtr);
  6599. CHECK_D3D12_ERROR_AND_RETURN("Failed to map destination buffer", false);
  6600. for (Uint32 sliceIndex = 0; sliceIndex < download->depth; sliceIndex += 1) {
  6601. for (Uint32 rowIndex = 0; rowIndex < download->height; rowIndex += 1) {
  6602. SDL_memcpy(
  6603. destPtr + download->bufferOffset + (sliceIndex * download->bytesPerDepthSlice) + (rowIndex * download->bytesPerRow),
  6604. sourcePtr + (sliceIndex * download->height) + (rowIndex * download->alignedBytesPerRow),
  6605. download->bytesPerRow);
  6606. }
  6607. }
  6608. ID3D12Resource_Unmap(
  6609. download->temporaryBuffer->handle,
  6610. 0,
  6611. NULL);
  6612. ID3D12Resource_Unmap(
  6613. download->destinationBuffer->handle,
  6614. 0,
  6615. NULL);
  6616. return true;
  6617. }
  6618. static bool D3D12_INTERNAL_CleanCommandBuffer(
  6619. D3D12Renderer *renderer,
  6620. D3D12CommandBuffer *commandBuffer,
  6621. bool cancel)
  6622. {
  6623. Uint32 i;
  6624. HRESULT res;
  6625. bool result = true;
  6626. // Perform deferred texture data copies
  6627. for (i = 0; i < commandBuffer->textureDownloadCount; i += 1) {
  6628. if (!cancel) {
  6629. result &= D3D12_INTERNAL_CopyTextureDownload(
  6630. commandBuffer,
  6631. commandBuffer->textureDownloads[i]);
  6632. }
  6633. SDL_free(commandBuffer->textureDownloads[i]);
  6634. }
  6635. commandBuffer->textureDownloadCount = 0;
  6636. if (!result) {
  6637. return false;
  6638. }
  6639. res = ID3D12CommandAllocator_Reset(commandBuffer->commandAllocator);
  6640. CHECK_D3D12_ERROR_AND_RETURN("Could not reset command allocator", false);
  6641. res = ID3D12GraphicsCommandList_Reset(
  6642. commandBuffer->graphicsCommandList,
  6643. commandBuffer->commandAllocator,
  6644. NULL);
  6645. CHECK_D3D12_ERROR_AND_RETURN("Could not reset command list", false);
  6646. // Return descriptor heaps to pool, pools own their own locks
  6647. for (i = 0; i < commandBuffer->usedDescriptorHeapCount; i += 1) {
  6648. D3D12_INTERNAL_ReturnGPUDescriptorHeapToPool(
  6649. renderer,
  6650. commandBuffer->usedDescriptorHeaps[i]);
  6651. }
  6652. commandBuffer->usedDescriptorHeapCount = 0;
  6653. commandBuffer->gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV] = NULL;
  6654. commandBuffer->gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER] = NULL;
  6655. // Uniform buffers are now available
  6656. SDL_LockMutex(renderer->acquireUniformBufferLock);
  6657. for (i = 0; i < commandBuffer->usedUniformBufferCount; i += 1) {
  6658. D3D12_INTERNAL_ReturnUniformBufferToPool(
  6659. renderer,
  6660. commandBuffer->usedUniformBuffers[i]);
  6661. }
  6662. commandBuffer->usedUniformBufferCount = 0;
  6663. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  6664. // TODO: More reference counting
  6665. for (i = 0; i < commandBuffer->usedTextureCount; i += 1) {
  6666. (void)SDL_AtomicDecRef(&commandBuffer->usedTextures[i]->referenceCount);
  6667. }
  6668. commandBuffer->usedTextureCount = 0;
  6669. for (i = 0; i < commandBuffer->usedBufferCount; i += 1) {
  6670. (void)SDL_AtomicDecRef(&commandBuffer->usedBuffers[i]->referenceCount);
  6671. }
  6672. commandBuffer->usedBufferCount = 0;
  6673. for (i = 0; i < commandBuffer->usedSamplerCount; i += 1) {
  6674. (void)SDL_AtomicDecRef(&commandBuffer->usedSamplers[i]->referenceCount);
  6675. }
  6676. commandBuffer->usedSamplerCount = 0;
  6677. for (i = 0; i < commandBuffer->usedGraphicsPipelineCount; i += 1) {
  6678. (void)SDL_AtomicDecRef(&commandBuffer->usedGraphicsPipelines[i]->referenceCount);
  6679. }
  6680. commandBuffer->usedGraphicsPipelineCount = 0;
  6681. for (i = 0; i < commandBuffer->usedComputePipelineCount; i += 1) {
  6682. (void)SDL_AtomicDecRef(&commandBuffer->usedComputePipelines[i]->referenceCount);
  6683. }
  6684. commandBuffer->usedComputePipelineCount = 0;
  6685. // Reset presentation
  6686. commandBuffer->presentDataCount = 0;
  6687. // The fence is now available (unless SubmitAndAcquireFence was called)
  6688. if (commandBuffer->autoReleaseFence) {
  6689. D3D12_ReleaseFence(
  6690. (SDL_GPURenderer *)renderer,
  6691. (SDL_GPUFence *)commandBuffer->inFlightFence);
  6692. commandBuffer->inFlightFence = NULL;
  6693. }
  6694. // Return command buffer to pool
  6695. SDL_LockMutex(renderer->acquireCommandBufferLock);
  6696. if (renderer->availableCommandBufferCount == renderer->availableCommandBufferCapacity) {
  6697. renderer->availableCommandBufferCapacity += 1;
  6698. renderer->availableCommandBuffers = (D3D12CommandBuffer **)SDL_realloc(
  6699. renderer->availableCommandBuffers,
  6700. renderer->availableCommandBufferCapacity * sizeof(D3D12CommandBuffer *));
  6701. }
  6702. renderer->availableCommandBuffers[renderer->availableCommandBufferCount] = commandBuffer;
  6703. renderer->availableCommandBufferCount += 1;
  6704. SDL_UnlockMutex(renderer->acquireCommandBufferLock);
  6705. // Remove this command buffer from the submitted list
  6706. if (!cancel) {
  6707. for (i = 0; i < renderer->submittedCommandBufferCount; i += 1) {
  6708. if (renderer->submittedCommandBuffers[i] == commandBuffer) {
  6709. renderer->submittedCommandBuffers[i] = renderer->submittedCommandBuffers[renderer->submittedCommandBufferCount - 1];
  6710. renderer->submittedCommandBufferCount -= 1;
  6711. }
  6712. }
  6713. }
  6714. return true;
  6715. }
  6716. static bool D3D12_Submit(
  6717. SDL_GPUCommandBuffer *commandBuffer)
  6718. {
  6719. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  6720. D3D12Renderer *renderer = d3d12CommandBuffer->renderer;
  6721. ID3D12CommandList *commandLists[1];
  6722. HRESULT res;
  6723. SDL_LockMutex(renderer->submitLock);
  6724. // Unmap uniform buffers
  6725. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  6726. if (d3d12CommandBuffer->vertexUniformBuffers[i] != NULL) {
  6727. ID3D12Resource_Unmap(
  6728. d3d12CommandBuffer->vertexUniformBuffers[i]->buffer->handle,
  6729. 0,
  6730. NULL);
  6731. d3d12CommandBuffer->vertexUniformBuffers[i]->buffer->mapPointer = NULL;
  6732. }
  6733. if (d3d12CommandBuffer->fragmentUniformBuffers[i] != NULL) {
  6734. ID3D12Resource_Unmap(
  6735. d3d12CommandBuffer->fragmentUniformBuffers[i]->buffer->handle,
  6736. 0,
  6737. NULL);
  6738. d3d12CommandBuffer->fragmentUniformBuffers[i]->buffer->mapPointer = NULL;
  6739. }
  6740. // TODO: compute uniforms
  6741. }
  6742. // Transition present textures to present mode
  6743. for (Uint32 i = 0; i < d3d12CommandBuffer->presentDataCount; i += 1) {
  6744. Uint32 swapchainIndex = d3d12CommandBuffer->presentDatas[i].swapchainImageIndex;
  6745. D3D12TextureContainer *container = &d3d12CommandBuffer->presentDatas[i].windowData->textureContainers[swapchainIndex];
  6746. D3D12TextureSubresource *subresource = D3D12_INTERNAL_FetchTextureSubresource(container, 0, 0);
  6747. D3D12_RESOURCE_BARRIER barrierDesc;
  6748. barrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  6749. barrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  6750. barrierDesc.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
  6751. barrierDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
  6752. barrierDesc.Transition.pResource = subresource->parent->resource;
  6753. barrierDesc.Transition.Subresource = subresource->index;
  6754. ID3D12GraphicsCommandList_ResourceBarrier(
  6755. d3d12CommandBuffer->graphicsCommandList,
  6756. 1,
  6757. &barrierDesc);
  6758. }
  6759. // Notify the command buffer that we have completed recording
  6760. res = ID3D12GraphicsCommandList_Close(d3d12CommandBuffer->graphicsCommandList);
  6761. CHECK_D3D12_ERROR_AND_RETURN("Failed to close command list!", false);
  6762. res = ID3D12GraphicsCommandList_QueryInterface(
  6763. d3d12CommandBuffer->graphicsCommandList,
  6764. D3D_GUID(D3D_IID_ID3D12CommandList),
  6765. (void **)&commandLists[0]);
  6766. if (FAILED(res)) {
  6767. SDL_UnlockMutex(renderer->submitLock);
  6768. CHECK_D3D12_ERROR_AND_RETURN("Failed to convert command list!", false);
  6769. }
  6770. // Submit the command list to the queue
  6771. ID3D12CommandQueue_ExecuteCommandLists(
  6772. renderer->commandQueue,
  6773. 1,
  6774. commandLists);
  6775. ID3D12CommandList_Release(commandLists[0]);
  6776. // Acquire a fence and set it to the in-flight fence
  6777. d3d12CommandBuffer->inFlightFence = D3D12_INTERNAL_AcquireFence(renderer);
  6778. if (!d3d12CommandBuffer->inFlightFence) {
  6779. SDL_UnlockMutex(renderer->submitLock);
  6780. return false;
  6781. }
  6782. // Mark that a fence should be signaled after command list execution
  6783. res = ID3D12CommandQueue_Signal(
  6784. renderer->commandQueue,
  6785. d3d12CommandBuffer->inFlightFence->handle,
  6786. D3D12_FENCE_SIGNAL_VALUE);
  6787. if (FAILED(res)) {
  6788. SDL_UnlockMutex(renderer->submitLock);
  6789. CHECK_D3D12_ERROR_AND_RETURN("Failed to enqueue fence signal!", false);
  6790. }
  6791. // Mark the command buffer as submitted
  6792. if (renderer->submittedCommandBufferCount + 1 >= renderer->submittedCommandBufferCapacity) {
  6793. renderer->submittedCommandBufferCapacity = renderer->submittedCommandBufferCount + 1;
  6794. renderer->submittedCommandBuffers = (D3D12CommandBuffer **)SDL_realloc(
  6795. renderer->submittedCommandBuffers,
  6796. sizeof(D3D12CommandBuffer *) * renderer->submittedCommandBufferCapacity);
  6797. }
  6798. renderer->submittedCommandBuffers[renderer->submittedCommandBufferCount] = d3d12CommandBuffer;
  6799. renderer->submittedCommandBufferCount += 1;
  6800. bool result = true;
  6801. // Present, if applicable
  6802. for (Uint32 i = 0; i < d3d12CommandBuffer->presentDataCount; i += 1) {
  6803. D3D12PresentData *presentData = &d3d12CommandBuffer->presentDatas[i];
  6804. D3D12WindowData *windowData = presentData->windowData;
  6805. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  6806. D3D12XBOX_PRESENT_PLANE_PARAMETERS planeParams;
  6807. SDL_zero(planeParams);
  6808. planeParams.Token = windowData->frameToken;
  6809. planeParams.ResourceCount = 1;
  6810. planeParams.ppResources = &windowData->textureContainers[windowData->frameCounter].activeTexture->resource;
  6811. planeParams.ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; // FIXME
  6812. D3D12XBOX_PRESENT_PARAMETERS presentParams;
  6813. SDL_zero(presentParams);
  6814. presentParams.Flags = (windowData->present_mode == SDL_GPU_PRESENTMODE_IMMEDIATE) ? D3D12XBOX_PRESENT_FLAG_IMMEDIATE : D3D12XBOX_PRESENT_FLAG_NONE;
  6815. renderer->commandQueue->PresentX(1, &planeParams, &presentParams);
  6816. if (FAILED(res)) {
  6817. result = false;
  6818. }
  6819. #else
  6820. // NOTE: flip discard always supported since DXGI 1.4 is required
  6821. Uint32 syncInterval = 1;
  6822. if (windowData->present_mode == SDL_GPU_PRESENTMODE_IMMEDIATE ||
  6823. windowData->present_mode == SDL_GPU_PRESENTMODE_MAILBOX) {
  6824. syncInterval = 0;
  6825. }
  6826. Uint32 presentFlags = 0;
  6827. if (renderer->supportsTearing &&
  6828. windowData->present_mode == SDL_GPU_PRESENTMODE_IMMEDIATE) {
  6829. presentFlags = DXGI_PRESENT_ALLOW_TEARING;
  6830. }
  6831. res = IDXGISwapChain_Present(
  6832. windowData->swapchain,
  6833. syncInterval,
  6834. presentFlags);
  6835. if (FAILED(res)) {
  6836. result = false;
  6837. }
  6838. ID3D12Resource_Release(windowData->textureContainers[presentData->swapchainImageIndex].activeTexture->resource);
  6839. #endif
  6840. windowData->inFlightFences[windowData->frameCounter] = (SDL_GPUFence *)d3d12CommandBuffer->inFlightFence;
  6841. (void)SDL_AtomicIncRef(&d3d12CommandBuffer->inFlightFence->referenceCount);
  6842. windowData->frameCounter = (windowData->frameCounter + 1) % renderer->allowedFramesInFlight;
  6843. }
  6844. // Check for cleanups
  6845. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  6846. Uint64 fenceValue = ID3D12Fence_GetCompletedValue(
  6847. renderer->submittedCommandBuffers[i]->inFlightFence->handle);
  6848. if (fenceValue == D3D12_FENCE_SIGNAL_VALUE) {
  6849. result &= D3D12_INTERNAL_CleanCommandBuffer(
  6850. renderer,
  6851. renderer->submittedCommandBuffers[i],
  6852. false);
  6853. }
  6854. }
  6855. D3D12_INTERNAL_PerformPendingDestroys(renderer);
  6856. SDL_UnlockMutex(renderer->submitLock);
  6857. return result;
  6858. }
  6859. static SDL_GPUFence *D3D12_SubmitAndAcquireFence(
  6860. SDL_GPUCommandBuffer *commandBuffer)
  6861. {
  6862. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  6863. d3d12CommandBuffer->autoReleaseFence = false;
  6864. if (!D3D12_Submit(commandBuffer)) {
  6865. return NULL;
  6866. }
  6867. return (SDL_GPUFence *)d3d12CommandBuffer->inFlightFence;
  6868. }
  6869. static bool D3D12_Cancel(
  6870. SDL_GPUCommandBuffer *commandBuffer)
  6871. {
  6872. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  6873. D3D12Renderer *renderer = d3d12CommandBuffer->renderer;
  6874. bool result;
  6875. HRESULT res;
  6876. // Notify the command buffer that we have completed recording
  6877. res = ID3D12GraphicsCommandList_Close(d3d12CommandBuffer->graphicsCommandList);
  6878. CHECK_D3D12_ERROR_AND_RETURN("Failed to close command list!", false);
  6879. d3d12CommandBuffer->autoReleaseFence = false;
  6880. SDL_LockMutex(renderer->submitLock);
  6881. result = D3D12_INTERNAL_CleanCommandBuffer(renderer, d3d12CommandBuffer, true);
  6882. SDL_UnlockMutex(renderer->submitLock);
  6883. return result;
  6884. }
  6885. static bool D3D12_Wait(
  6886. SDL_GPURenderer *driverData)
  6887. {
  6888. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6889. D3D12Fence *fence = D3D12_INTERNAL_AcquireFence(renderer);
  6890. if (!fence) {
  6891. return false;
  6892. }
  6893. HRESULT res;
  6894. SDL_LockMutex(renderer->submitLock);
  6895. if (renderer->commandQueue) {
  6896. // Insert a signal into the end of the command queue...
  6897. ID3D12CommandQueue_Signal(
  6898. renderer->commandQueue,
  6899. fence->handle,
  6900. D3D12_FENCE_SIGNAL_VALUE);
  6901. // ...and then block on it.
  6902. if (ID3D12Fence_GetCompletedValue(fence->handle) != D3D12_FENCE_SIGNAL_VALUE) {
  6903. res = ID3D12Fence_SetEventOnCompletion(
  6904. fence->handle,
  6905. D3D12_FENCE_SIGNAL_VALUE,
  6906. fence->event);
  6907. CHECK_D3D12_ERROR_AND_RETURN("Setting fence event failed", false);
  6908. DWORD waitResult = WaitForSingleObject(fence->event, INFINITE);
  6909. if (waitResult == WAIT_FAILED) {
  6910. SDL_UnlockMutex(renderer->submitLock);
  6911. SET_STRING_ERROR_AND_RETURN("Wait failed", false); // TODO: is there a better way to report this?
  6912. }
  6913. }
  6914. }
  6915. D3D12_ReleaseFence(
  6916. (SDL_GPURenderer *)renderer,
  6917. (SDL_GPUFence *)fence);
  6918. bool result = true;
  6919. // Clean up
  6920. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  6921. result &= D3D12_INTERNAL_CleanCommandBuffer(renderer, renderer->submittedCommandBuffers[i], false);
  6922. }
  6923. D3D12_INTERNAL_PerformPendingDestroys(renderer);
  6924. SDL_UnlockMutex(renderer->submitLock);
  6925. return result;
  6926. }
  6927. static bool D3D12_WaitForFences(
  6928. SDL_GPURenderer *driverData,
  6929. bool waitAll,
  6930. SDL_GPUFence *const *fences,
  6931. Uint32 numFences)
  6932. {
  6933. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6934. D3D12Fence *fence;
  6935. HANDLE *events = SDL_stack_alloc(HANDLE, numFences);
  6936. HRESULT res;
  6937. SDL_LockMutex(renderer->submitLock);
  6938. for (Uint32 i = 0; i < numFences; i += 1) {
  6939. fence = (D3D12Fence *)fences[i];
  6940. res = ID3D12Fence_SetEventOnCompletion(
  6941. fence->handle,
  6942. D3D12_FENCE_SIGNAL_VALUE,
  6943. fence->event);
  6944. CHECK_D3D12_ERROR_AND_RETURN("Setting fence event failed", false);
  6945. events[i] = fence->event;
  6946. }
  6947. DWORD waitResult = WaitForMultipleObjects(
  6948. numFences,
  6949. events,
  6950. waitAll,
  6951. INFINITE);
  6952. if (waitResult == WAIT_FAILED) {
  6953. SDL_UnlockMutex(renderer->submitLock);
  6954. SET_STRING_ERROR_AND_RETURN("Wait failed", false); // TODO: is there a better way to report this?
  6955. }
  6956. bool result = true;
  6957. // Check for cleanups
  6958. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  6959. Uint64 fenceValue = ID3D12Fence_GetCompletedValue(
  6960. renderer->submittedCommandBuffers[i]->inFlightFence->handle);
  6961. if (fenceValue == D3D12_FENCE_SIGNAL_VALUE) {
  6962. result &= D3D12_INTERNAL_CleanCommandBuffer(
  6963. renderer,
  6964. renderer->submittedCommandBuffers[i],
  6965. false);
  6966. }
  6967. }
  6968. D3D12_INTERNAL_PerformPendingDestroys(renderer);
  6969. SDL_stack_free(events);
  6970. SDL_UnlockMutex(renderer->submitLock);
  6971. return result;
  6972. }
  6973. // Feature Queries
  6974. static bool D3D12_SupportsTextureFormat(
  6975. SDL_GPURenderer *driverData,
  6976. SDL_GPUTextureFormat format,
  6977. SDL_GPUTextureType type,
  6978. SDL_GPUTextureUsageFlags usage)
  6979. {
  6980. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6981. DXGI_FORMAT dxgiFormat = SDLToD3D12_TextureFormat[format];
  6982. D3D12_FEATURE_DATA_FORMAT_SUPPORT formatSupport = { dxgiFormat, D3D12_FORMAT_SUPPORT1_NONE, D3D12_FORMAT_SUPPORT2_NONE };
  6983. HRESULT res;
  6984. res = ID3D12Device_CheckFeatureSupport(
  6985. renderer->device,
  6986. D3D12_FEATURE_FORMAT_SUPPORT,
  6987. &formatSupport,
  6988. sizeof(formatSupport));
  6989. if (FAILED(res)) {
  6990. // Format is apparently unknown
  6991. return false;
  6992. }
  6993. // Is the texture type supported?
  6994. if (type == SDL_GPU_TEXTURETYPE_2D && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D)) {
  6995. return false;
  6996. }
  6997. if (type == SDL_GPU_TEXTURETYPE_2D_ARRAY && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D)) {
  6998. return false;
  6999. }
  7000. if (type == SDL_GPU_TEXTURETYPE_3D && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE3D)) {
  7001. return false;
  7002. }
  7003. if (type == SDL_GPU_TEXTURETYPE_CUBE && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURECUBE)) {
  7004. return false;
  7005. }
  7006. if (type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURECUBE)) {
  7007. return false;
  7008. }
  7009. // Are the usage flags supported?
  7010. if ((usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE)) {
  7011. return false;
  7012. }
  7013. if ((usage & (SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ)) && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_LOAD)) {
  7014. return false;
  7015. }
  7016. if ((usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) && !(formatSupport.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) {
  7017. return false;
  7018. }
  7019. if ((usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE) && !(formatSupport.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD)) {
  7020. return false;
  7021. }
  7022. if ((usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET)) {
  7023. return false;
  7024. }
  7025. // Special case check for depth, because D3D12 is great.
  7026. formatSupport.Format = SDLToD3D12_DepthFormat[format];
  7027. formatSupport.Support1 = D3D12_FORMAT_SUPPORT1_NONE;
  7028. formatSupport.Support2 = D3D12_FORMAT_SUPPORT2_NONE;
  7029. res = ID3D12Device_CheckFeatureSupport(
  7030. renderer->device,
  7031. D3D12_FEATURE_FORMAT_SUPPORT,
  7032. &formatSupport,
  7033. sizeof(formatSupport));
  7034. if (FAILED(res)) {
  7035. // Format is apparently unknown
  7036. return false;
  7037. }
  7038. if ((usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL)) {
  7039. return false;
  7040. }
  7041. return true;
  7042. }
  7043. static bool D3D12_SupportsSampleCount(
  7044. SDL_GPURenderer *driverData,
  7045. SDL_GPUTextureFormat format,
  7046. SDL_GPUSampleCount sampleCount)
  7047. {
  7048. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  7049. D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS featureData;
  7050. HRESULT res;
  7051. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  7052. featureData.Flags = (D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG)0;
  7053. #else
  7054. featureData.Flags = (D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS)0;
  7055. #endif
  7056. featureData.Format = SDLToD3D12_TextureFormat[format];
  7057. featureData.SampleCount = SDLToD3D12_SampleCount[sampleCount];
  7058. res = ID3D12Device_CheckFeatureSupport(
  7059. renderer->device,
  7060. D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS,
  7061. &featureData,
  7062. sizeof(featureData));
  7063. return SUCCEEDED(res) && featureData.NumQualityLevels > 0;
  7064. }
  7065. static void D3D12_INTERNAL_InitBlitResources(
  7066. D3D12Renderer *renderer)
  7067. {
  7068. SDL_GPUShaderCreateInfo shaderCreateInfo;
  7069. SDL_GPUSamplerCreateInfo samplerCreateInfo;
  7070. renderer->blitPipelineCapacity = 2;
  7071. renderer->blitPipelineCount = 0;
  7072. renderer->blitPipelines = (BlitPipelineCacheEntry *)SDL_malloc(
  7073. renderer->blitPipelineCapacity * sizeof(BlitPipelineCacheEntry));
  7074. // Fullscreen vertex shader
  7075. SDL_zero(shaderCreateInfo);
  7076. shaderCreateInfo.code = (Uint8 *)D3D12_FullscreenVert;
  7077. shaderCreateInfo.code_size = sizeof(D3D12_FullscreenVert);
  7078. shaderCreateInfo.stage = SDL_GPU_SHADERSTAGE_VERTEX;
  7079. shaderCreateInfo.format = SDL_GPU_SHADERFORMAT_DXIL;
  7080. renderer->blitVertexShader = D3D12_CreateShader(
  7081. (SDL_GPURenderer *)renderer,
  7082. &shaderCreateInfo);
  7083. if (renderer->blitVertexShader == NULL) {
  7084. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile vertex shader for blit!");
  7085. }
  7086. // BlitFrom2D pixel shader
  7087. shaderCreateInfo.code = (Uint8 *)D3D12_BlitFrom2D;
  7088. shaderCreateInfo.code_size = sizeof(D3D12_BlitFrom2D);
  7089. shaderCreateInfo.stage = SDL_GPU_SHADERSTAGE_FRAGMENT;
  7090. shaderCreateInfo.num_samplers = 1;
  7091. shaderCreateInfo.num_uniform_buffers = 1;
  7092. renderer->blitFrom2DShader = D3D12_CreateShader(
  7093. (SDL_GPURenderer *)renderer,
  7094. &shaderCreateInfo);
  7095. if (renderer->blitFrom2DShader == NULL) {
  7096. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFrom2D pixel shader!");
  7097. }
  7098. // BlitFrom2DArray pixel shader
  7099. shaderCreateInfo.code = (Uint8 *)D3D12_BlitFrom2DArray;
  7100. shaderCreateInfo.code_size = sizeof(D3D12_BlitFrom2DArray);
  7101. renderer->blitFrom2DArrayShader = D3D12_CreateShader(
  7102. (SDL_GPURenderer *)renderer,
  7103. &shaderCreateInfo);
  7104. if (renderer->blitFrom2DArrayShader == NULL) {
  7105. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFrom2DArray pixel shader!");
  7106. }
  7107. // BlitFrom3D pixel shader
  7108. shaderCreateInfo.code = (Uint8 *)D3D12_BlitFrom3D;
  7109. shaderCreateInfo.code_size = sizeof(D3D12_BlitFrom3D);
  7110. renderer->blitFrom3DShader = D3D12_CreateShader(
  7111. (SDL_GPURenderer *)renderer,
  7112. &shaderCreateInfo);
  7113. if (renderer->blitFrom3DShader == NULL) {
  7114. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFrom3D pixel shader!");
  7115. }
  7116. // BlitFromCube pixel shader
  7117. shaderCreateInfo.code = (Uint8 *)D3D12_BlitFromCube;
  7118. shaderCreateInfo.code_size = sizeof(D3D12_BlitFromCube);
  7119. renderer->blitFromCubeShader = D3D12_CreateShader(
  7120. (SDL_GPURenderer *)renderer,
  7121. &shaderCreateInfo);
  7122. if (renderer->blitFromCubeShader == NULL) {
  7123. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFromCube pixel shader!");
  7124. }
  7125. // BlitFromCubeArray pixel shader
  7126. shaderCreateInfo.code = (Uint8 *)D3D12_BlitFromCubeArray;
  7127. shaderCreateInfo.code_size = sizeof(D3D12_BlitFromCubeArray);
  7128. renderer->blitFromCubeArrayShader = D3D12_CreateShader(
  7129. (SDL_GPURenderer *)renderer,
  7130. &shaderCreateInfo);
  7131. if (renderer->blitFromCubeArrayShader == NULL) {
  7132. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFromCubeArray pixel shader!");
  7133. }
  7134. // Create samplers
  7135. samplerCreateInfo.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  7136. samplerCreateInfo.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  7137. samplerCreateInfo.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  7138. samplerCreateInfo.enable_anisotropy = 0;
  7139. samplerCreateInfo.enable_compare = 0;
  7140. samplerCreateInfo.mag_filter = SDL_GPU_FILTER_NEAREST;
  7141. samplerCreateInfo.min_filter = SDL_GPU_FILTER_NEAREST;
  7142. samplerCreateInfo.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
  7143. samplerCreateInfo.mip_lod_bias = 0.0f;
  7144. samplerCreateInfo.min_lod = 0;
  7145. samplerCreateInfo.max_lod = 1000;
  7146. samplerCreateInfo.max_anisotropy = 1.0f;
  7147. samplerCreateInfo.compare_op = SDL_GPU_COMPAREOP_NEVER;
  7148. renderer->blitNearestSampler = D3D12_CreateSampler(
  7149. (SDL_GPURenderer *)renderer,
  7150. &samplerCreateInfo);
  7151. if (renderer->blitNearestSampler == NULL) {
  7152. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create blit nearest sampler!");
  7153. }
  7154. samplerCreateInfo.mag_filter = SDL_GPU_FILTER_LINEAR;
  7155. samplerCreateInfo.min_filter = SDL_GPU_FILTER_LINEAR;
  7156. samplerCreateInfo.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;
  7157. renderer->blitLinearSampler = D3D12_CreateSampler(
  7158. (SDL_GPURenderer *)renderer,
  7159. &samplerCreateInfo);
  7160. if (renderer->blitLinearSampler == NULL) {
  7161. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create blit linear sampler!");
  7162. }
  7163. }
  7164. static bool D3D12_PrepareDriver(SDL_VideoDevice *_this, SDL_PropertiesID props)
  7165. {
  7166. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  7167. return true;
  7168. #else
  7169. SDL_SharedObject *d3d12Dll;
  7170. SDL_SharedObject *dxgiDll;
  7171. PFN_D3D12_CREATE_DEVICE pD3D12CreateDevice;
  7172. pfnCreateDXGIFactory1 pCreateDXGIFactory1;
  7173. HRESULT res;
  7174. ID3D12Device *device;
  7175. IDXGIFactory1 *factory;
  7176. IDXGIFactory4 *factory4;
  7177. IDXGIFactory6 *factory6;
  7178. IDXGIAdapter1 *adapter;
  7179. bool supports_64UAVs = false;
  7180. bool needs_64UAVs = !SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_D3D12_ALLOW_FEWER_RESOURCE_SLOTS_BOOLEAN, false);
  7181. // Early check to see if the app has _any_ D3D12 formats, if not we don't
  7182. // have to fuss with loading D3D in the first place.
  7183. bool has_dxbc = SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_SHADERS_DXBC_BOOLEAN, false);
  7184. bool has_dxil = SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_SHADERS_DXIL_BOOLEAN, false);
  7185. bool supports_dxil = false;
  7186. // TODO SM7: bool has_spirv = SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_SHADERS_SPIRV_BOOLEAN, false);
  7187. // TODO SM7: bool supports_spirv = false;
  7188. if (!has_dxbc && !has_dxil) {
  7189. return false;
  7190. }
  7191. // Can we load D3D12?
  7192. d3d12Dll = SDL_LoadObject(D3D12_DLL);
  7193. if (d3d12Dll == NULL) {
  7194. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D12: Could not find " D3D12_DLL);
  7195. return false;
  7196. }
  7197. pD3D12CreateDevice = (PFN_D3D12_CREATE_DEVICE)SDL_LoadFunction(
  7198. d3d12Dll,
  7199. D3D12_CREATE_DEVICE_FUNC);
  7200. if (pD3D12CreateDevice == NULL) {
  7201. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D12: Could not find function " D3D12_CREATE_DEVICE_FUNC " in " D3D12_DLL);
  7202. SDL_UnloadObject(d3d12Dll);
  7203. return false;
  7204. }
  7205. // Can we load DXGI?
  7206. dxgiDll = SDL_LoadObject(DXGI_DLL);
  7207. if (dxgiDll == NULL) {
  7208. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D12: Could not find " DXGI_DLL);
  7209. return false;
  7210. }
  7211. pCreateDXGIFactory1 = (pfnCreateDXGIFactory1)SDL_LoadFunction(
  7212. dxgiDll,
  7213. CREATE_DXGI_FACTORY1_FUNC);
  7214. if (pCreateDXGIFactory1 == NULL) {
  7215. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D12: Could not find function " CREATE_DXGI_FACTORY1_FUNC " in " DXGI_DLL);
  7216. SDL_UnloadObject(dxgiDll);
  7217. return false;
  7218. }
  7219. // Can we create a device?
  7220. // Create the DXGI factory
  7221. res = pCreateDXGIFactory1(
  7222. &D3D_IID_IDXGIFactory1,
  7223. (void **)&factory);
  7224. if (FAILED(res)) {
  7225. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D12: Could not create DXGIFactory");
  7226. SDL_UnloadObject(d3d12Dll);
  7227. SDL_UnloadObject(dxgiDll);
  7228. return false;
  7229. }
  7230. // Check for DXGI 1.4 support
  7231. res = IDXGIFactory1_QueryInterface(
  7232. factory,
  7233. D3D_GUID(D3D_IID_IDXGIFactory4),
  7234. (void **)&factory4);
  7235. if (FAILED(res)) {
  7236. IDXGIFactory1_Release(factory);
  7237. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D12: Failed to find DXGI1.4 support, required for DX12");
  7238. SDL_UnloadObject(d3d12Dll);
  7239. SDL_UnloadObject(dxgiDll);
  7240. return false;
  7241. }
  7242. IDXGIFactory4_Release(factory4);
  7243. res = IDXGIFactory1_QueryInterface(
  7244. factory,
  7245. D3D_GUID(D3D_IID_IDXGIFactory6),
  7246. (void **)&factory6);
  7247. if (SUCCEEDED(res)) {
  7248. res = IDXGIFactory6_EnumAdapterByGpuPreference(
  7249. factory6,
  7250. 0,
  7251. DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
  7252. D3D_GUID(D3D_IID_IDXGIAdapter1),
  7253. (void **)&adapter);
  7254. IDXGIFactory6_Release(factory6);
  7255. } else {
  7256. res = IDXGIFactory1_EnumAdapters1(
  7257. factory,
  7258. 0,
  7259. &adapter);
  7260. }
  7261. if (FAILED(res)) {
  7262. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D12: Failed to find adapter for D3D12Device");
  7263. IDXGIFactory1_Release(factory);
  7264. SDL_UnloadObject(d3d12Dll);
  7265. SDL_UnloadObject(dxgiDll);
  7266. return false;
  7267. }
  7268. SDL_COMPILE_TIME_ASSERT(featurelevel, D3D_FEATURE_LEVEL_CHOICE < D3D_FEATURE_LEVEL_11_1);
  7269. /* If Windows 11 is running and the app has neither DXIL nor TIER2
  7270. * requirements, we can skip doing any device checks entirely
  7271. */
  7272. if (!needs_64UAVs && !has_dxil && WIN_IsWindows11OrGreater()) {
  7273. IDXGIAdapter1_Release(adapter);
  7274. IDXGIFactory1_Release(factory);
  7275. SDL_UnloadObject(d3d12Dll);
  7276. SDL_UnloadObject(dxgiDll);
  7277. return true;
  7278. }
  7279. res = pD3D12CreateDevice(
  7280. (IUnknown *)adapter,
  7281. D3D_FEATURE_LEVEL_CHOICE,
  7282. D3D_GUID(D3D_IID_ID3D12Device),
  7283. (void **)&device);
  7284. if (SUCCEEDED(res)) {
  7285. // Only check for Tier 2 resource binding if the app needs it
  7286. if (needs_64UAVs) {
  7287. D3D12_FEATURE_DATA_D3D12_OPTIONS featureOptions;
  7288. SDL_zero(featureOptions);
  7289. res = ID3D12Device_CheckFeatureSupport(
  7290. device,
  7291. D3D12_FEATURE_D3D12_OPTIONS,
  7292. &featureOptions,
  7293. sizeof(featureOptions));
  7294. if (SUCCEEDED(res) && featureOptions.ResourceBindingTier >= D3D12_RESOURCE_BINDING_TIER_2) {
  7295. supports_64UAVs = true;
  7296. }
  7297. }
  7298. // Only check for SM6 support if DXIL is provided
  7299. if (has_dxil) {
  7300. D3D12_FEATURE_DATA_SHADER_MODEL shaderModel;
  7301. shaderModel.HighestShaderModel = D3D_SHADER_MODEL_6_0;
  7302. res = ID3D12Device_CheckFeatureSupport(
  7303. device,
  7304. D3D12_FEATURE_SHADER_MODEL,
  7305. &shaderModel,
  7306. sizeof(shaderModel));
  7307. if (SUCCEEDED(res) && shaderModel.HighestShaderModel >= D3D_SHADER_MODEL_6_0) {
  7308. supports_dxil = true;
  7309. }
  7310. }
  7311. ID3D12Device_Release(device);
  7312. }
  7313. IDXGIAdapter1_Release(adapter);
  7314. IDXGIFactory1_Release(factory);
  7315. SDL_UnloadObject(d3d12Dll);
  7316. SDL_UnloadObject(dxgiDll);
  7317. if (!supports_64UAVs && needs_64UAVs) {
  7318. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D12: Tier 2 Resource Binding is not supported");
  7319. return false;
  7320. }
  7321. if (!supports_dxil && !has_dxbc) {
  7322. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D12: DXIL is not supported and DXBC is not being provided");
  7323. return false;
  7324. }
  7325. if (FAILED(res)) {
  7326. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D12: Could not create D3D12Device with feature level " D3D_FEATURE_LEVEL_CHOICE_STR);
  7327. return false;
  7328. }
  7329. return true;
  7330. #endif
  7331. }
  7332. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)) && defined(HAVE_IDXGIINFOQUEUE)
  7333. static bool D3D12_INTERNAL_TryInitializeDXGIDebug(D3D12Renderer *renderer)
  7334. {
  7335. pfnDXGIGetDebugInterface pDXGIGetDebugInterface;
  7336. HRESULT res;
  7337. renderer->dxgidebug_dll = SDL_LoadObject(DXGIDEBUG_DLL);
  7338. if (renderer->dxgidebug_dll == NULL) {
  7339. return false;
  7340. }
  7341. pDXGIGetDebugInterface = (pfnDXGIGetDebugInterface)SDL_LoadFunction(
  7342. renderer->dxgidebug_dll,
  7343. DXGI_GET_DEBUG_INTERFACE_FUNC);
  7344. if (pDXGIGetDebugInterface == NULL) {
  7345. return false;
  7346. }
  7347. res = pDXGIGetDebugInterface(&D3D_IID_IDXGIDebug, (void **)&renderer->dxgiDebug);
  7348. if (FAILED(res)) {
  7349. return false;
  7350. }
  7351. res = pDXGIGetDebugInterface(&D3D_IID_IDXGIInfoQueue, (void **)&renderer->dxgiInfoQueue);
  7352. if (FAILED(res)) {
  7353. return false;
  7354. }
  7355. return true;
  7356. }
  7357. #endif
  7358. static bool D3D12_INTERNAL_TryInitializeD3D12Debug(D3D12Renderer *renderer)
  7359. {
  7360. PFN_D3D12_GET_DEBUG_INTERFACE pD3D12GetDebugInterface;
  7361. HRESULT res;
  7362. pD3D12GetDebugInterface = (PFN_D3D12_GET_DEBUG_INTERFACE)SDL_LoadFunction(
  7363. renderer->d3d12_dll,
  7364. D3D12_GET_DEBUG_INTERFACE_FUNC);
  7365. if (pD3D12GetDebugInterface == NULL) {
  7366. return false;
  7367. }
  7368. res = pD3D12GetDebugInterface(D3D_GUID(D3D_IID_ID3D12Debug), (void **)&renderer->d3d12Debug);
  7369. if (FAILED(res)) {
  7370. return false;
  7371. }
  7372. ID3D12Debug_EnableDebugLayer(renderer->d3d12Debug);
  7373. return true;
  7374. }
  7375. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7376. static void D3D12_INTERNAL_TryInitializeD3D12DebugInfoQueue(D3D12Renderer *renderer)
  7377. {
  7378. ID3D12InfoQueue *infoQueue = NULL;
  7379. D3D12_MESSAGE_SEVERITY severities[] = { D3D12_MESSAGE_SEVERITY_INFO };
  7380. D3D12_INFO_QUEUE_FILTER filter;
  7381. HRESULT res;
  7382. res = ID3D12Device_QueryInterface(
  7383. renderer->device,
  7384. D3D_GUID(D3D_IID_ID3D12InfoQueue),
  7385. (void **)&infoQueue);
  7386. if (FAILED(res)) {
  7387. return;
  7388. }
  7389. SDL_zero(filter);
  7390. filter.DenyList.NumSeverities = 1;
  7391. filter.DenyList.pSeverityList = severities;
  7392. ID3D12InfoQueue_PushStorageFilter(
  7393. infoQueue,
  7394. &filter);
  7395. ID3D12InfoQueue_SetBreakOnSeverity(
  7396. infoQueue,
  7397. D3D12_MESSAGE_SEVERITY_CORRUPTION,
  7398. true);
  7399. ID3D12InfoQueue_Release(infoQueue);
  7400. }
  7401. static void WINAPI D3D12_INTERNAL_OnD3D12DebugInfoMsg(
  7402. D3D12_MESSAGE_CATEGORY category,
  7403. D3D12_MESSAGE_SEVERITY severity,
  7404. D3D12_MESSAGE_ID id,
  7405. LPCSTR description,
  7406. void *context)
  7407. {
  7408. char *catStr;
  7409. char *sevStr;
  7410. switch (category) {
  7411. case D3D12_MESSAGE_CATEGORY_APPLICATION_DEFINED:
  7412. catStr = "APPLICATION_DEFINED";
  7413. break;
  7414. case D3D12_MESSAGE_CATEGORY_MISCELLANEOUS:
  7415. catStr = "MISCELLANEOUS";
  7416. break;
  7417. case D3D12_MESSAGE_CATEGORY_INITIALIZATION:
  7418. catStr = "INITIALIZATION";
  7419. break;
  7420. case D3D12_MESSAGE_CATEGORY_CLEANUP:
  7421. catStr = "CLEANUP";
  7422. break;
  7423. case D3D12_MESSAGE_CATEGORY_COMPILATION:
  7424. catStr = "COMPILATION";
  7425. break;
  7426. case D3D12_MESSAGE_CATEGORY_STATE_CREATION:
  7427. catStr = "STATE_CREATION";
  7428. break;
  7429. case D3D12_MESSAGE_CATEGORY_STATE_SETTING:
  7430. catStr = "STATE_SETTING";
  7431. break;
  7432. case D3D12_MESSAGE_CATEGORY_STATE_GETTING:
  7433. catStr = "STATE_GETTING";
  7434. break;
  7435. case D3D12_MESSAGE_CATEGORY_RESOURCE_MANIPULATION:
  7436. catStr = "RESOURCE_MANIPULATION";
  7437. break;
  7438. case D3D12_MESSAGE_CATEGORY_EXECUTION:
  7439. catStr = "EXECUTION";
  7440. break;
  7441. case D3D12_MESSAGE_CATEGORY_SHADER:
  7442. catStr = "SHADER";
  7443. break;
  7444. default:
  7445. catStr = "UNKNOWN";
  7446. break;
  7447. }
  7448. switch (severity) {
  7449. case D3D12_MESSAGE_SEVERITY_CORRUPTION:
  7450. sevStr = "CORRUPTION";
  7451. break;
  7452. case D3D12_MESSAGE_SEVERITY_ERROR:
  7453. sevStr = "ERROR";
  7454. break;
  7455. case D3D12_MESSAGE_SEVERITY_WARNING:
  7456. sevStr = "WARNING";
  7457. break;
  7458. case D3D12_MESSAGE_SEVERITY_INFO:
  7459. sevStr = "INFO";
  7460. break;
  7461. case D3D12_MESSAGE_SEVERITY_MESSAGE:
  7462. sevStr = "MESSAGE";
  7463. break;
  7464. default:
  7465. sevStr = "UNKNOWN";
  7466. break;
  7467. }
  7468. if (severity <= D3D12_MESSAGE_SEVERITY_ERROR) {
  7469. SDL_LogError(
  7470. SDL_LOG_CATEGORY_GPU,
  7471. "D3D12 ERROR: %s [%s %s #%d]",
  7472. description,
  7473. catStr,
  7474. sevStr,
  7475. id);
  7476. } else {
  7477. SDL_LogWarn(
  7478. SDL_LOG_CATEGORY_GPU,
  7479. "D3D12 WARNING: %s [%s %s #%d]",
  7480. description,
  7481. catStr,
  7482. sevStr,
  7483. id);
  7484. }
  7485. }
  7486. static void D3D12_INTERNAL_TryInitializeD3D12DebugInfoLogger(D3D12Renderer *renderer)
  7487. {
  7488. ID3D12InfoQueue1 *infoQueue = NULL;
  7489. HRESULT res;
  7490. res = ID3D12Device_QueryInterface(
  7491. renderer->device,
  7492. D3D_GUID(D3D_IID_ID3D12InfoQueue1),
  7493. (void **)&infoQueue);
  7494. if (FAILED(res)) {
  7495. return;
  7496. }
  7497. ID3D12InfoQueue1_RegisterMessageCallback(
  7498. infoQueue,
  7499. D3D12_INTERNAL_OnD3D12DebugInfoMsg,
  7500. D3D12_MESSAGE_CALLBACK_FLAG_NONE,
  7501. NULL,
  7502. NULL);
  7503. ID3D12InfoQueue1_Release(infoQueue);
  7504. }
  7505. #endif
  7506. static SDL_GPUDevice *D3D12_CreateDevice(bool debugMode, bool preferLowPower, SDL_PropertiesID props)
  7507. {
  7508. SDL_GPUDevice *result;
  7509. D3D12Renderer *renderer;
  7510. HRESULT res;
  7511. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7512. PFN_D3D12_XBOX_CREATE_DEVICE D3D12XboxCreateDeviceFunc;
  7513. D3D12XBOX_CREATE_DEVICE_PARAMETERS createDeviceParams;
  7514. #else
  7515. pfnCreateDXGIFactory1 pCreateDXGIFactory1;
  7516. IDXGIFactory1 *factory1;
  7517. IDXGIFactory5 *factory5;
  7518. IDXGIFactory6 *factory6;
  7519. DXGI_ADAPTER_DESC1 adapterDesc;
  7520. LARGE_INTEGER umdVersion;
  7521. PFN_D3D12_CREATE_DEVICE pD3D12CreateDevice;
  7522. #endif
  7523. D3D12_FEATURE_DATA_ARCHITECTURE architecture;
  7524. D3D12_COMMAND_QUEUE_DESC queueDesc;
  7525. bool verboseLogs = SDL_GetBooleanProperty(
  7526. props,
  7527. SDL_PROP_GPU_DEVICE_CREATE_VERBOSE_BOOLEAN,
  7528. true);
  7529. renderer = (D3D12Renderer *)SDL_calloc(1, sizeof(D3D12Renderer));
  7530. bool hasDxgiDebug = false;
  7531. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7532. // Load the DXGI library
  7533. renderer->dxgi_dll = SDL_LoadObject(DXGI_DLL);
  7534. if (renderer->dxgi_dll == NULL) {
  7535. D3D12_INTERNAL_DestroyRenderer(renderer);
  7536. SET_STRING_ERROR_AND_RETURN("Could not find " DXGI_DLL, NULL);
  7537. }
  7538. #ifdef HAVE_IDXGIINFOQUEUE
  7539. // Initialize the DXGI debug layer, if applicable
  7540. if (debugMode) {
  7541. hasDxgiDebug = D3D12_INTERNAL_TryInitializeDXGIDebug(renderer);
  7542. }
  7543. #else
  7544. hasDxgiDebug = true;
  7545. #endif
  7546. #ifdef USE_PIX_RUNTIME
  7547. // Load the PIX runtime DLL so that we can set D3D12 debug events on command lists
  7548. renderer->winpixeventruntime_dll = SDL_LoadObject(WINPIXEVENTRUNTIME_DLL);
  7549. WinPixEventRuntimeFns *fns = &renderer->winpixeventruntimeFns;
  7550. if (renderer->winpixeventruntime_dll) {
  7551. // Load the specific functions we need from the PIX runtime
  7552. fns->pBeginEventOnCommandList = (pfnBeginEventOnCommandList)SDL_LoadFunction(
  7553. renderer->winpixeventruntime_dll,
  7554. PIX_BEGIN_EVENT_ON_COMMAND_LIST_FUNC);
  7555. fns->pEndEventOnCommandList = (pfnEndEventOnCommandList)SDL_LoadFunction(
  7556. renderer->winpixeventruntime_dll,
  7557. PIX_END_EVENT_ON_COMMAND_LIST_FUNC);
  7558. fns->pSetMarkerOnCommandList = (pfnSetMarkerOnCommandList)SDL_LoadFunction(
  7559. renderer->winpixeventruntime_dll,
  7560. PIX_SET_MARKER_ON_COMMAND_LIST_FUNC);
  7561. } else {
  7562. SDL_LogWarn(SDL_LOG_CATEGORY_GPU,
  7563. "WinPixEventRuntime.dll is not available. "
  7564. "It is required for SDL_Push/PopGPUDebugGroup and SDL_InsertGPUDebugLabel to function correctly. "
  7565. "See here for instructions on how to obtain it: https://devblogs.microsoft.com/pix/winpixeventruntime/");
  7566. fns->pBeginEventOnCommandList = NULL;
  7567. fns->pEndEventOnCommandList = NULL;
  7568. fns->pSetMarkerOnCommandList = NULL;
  7569. }
  7570. #endif
  7571. // Load the CreateDXGIFactory1 function
  7572. pCreateDXGIFactory1 = (pfnCreateDXGIFactory1)SDL_LoadFunction(
  7573. renderer->dxgi_dll,
  7574. CREATE_DXGI_FACTORY1_FUNC);
  7575. if (pCreateDXGIFactory1 == NULL) {
  7576. D3D12_INTERNAL_DestroyRenderer(renderer);
  7577. SET_STRING_ERROR_AND_RETURN("Could not load function: " CREATE_DXGI_FACTORY1_FUNC, NULL);
  7578. }
  7579. // Create the DXGI factory
  7580. res = pCreateDXGIFactory1(
  7581. &D3D_IID_IDXGIFactory1,
  7582. (void **)&factory1);
  7583. if (FAILED(res)) {
  7584. D3D12_INTERNAL_DestroyRenderer(renderer);
  7585. CHECK_D3D12_ERROR_AND_RETURN("Could not create DXGIFactory", NULL);
  7586. }
  7587. // Check for DXGI 1.4 support
  7588. res = IDXGIFactory1_QueryInterface(
  7589. factory1,
  7590. D3D_GUID(D3D_IID_IDXGIFactory4),
  7591. (void **)&renderer->factory);
  7592. if (FAILED(res)) {
  7593. D3D12_INTERNAL_DestroyRenderer(renderer);
  7594. CHECK_D3D12_ERROR_AND_RETURN("DXGI1.4 support not found, required for DX12", NULL);
  7595. }
  7596. IDXGIFactory1_Release(factory1);
  7597. // Check for explicit tearing support
  7598. res = IDXGIFactory4_QueryInterface(
  7599. renderer->factory,
  7600. D3D_GUID(D3D_IID_IDXGIFactory5),
  7601. (void **)&factory5);
  7602. if (SUCCEEDED(res)) {
  7603. res = IDXGIFactory5_CheckFeatureSupport(
  7604. factory5,
  7605. DXGI_FEATURE_PRESENT_ALLOW_TEARING,
  7606. &renderer->supportsTearing,
  7607. sizeof(renderer->supportsTearing));
  7608. if (FAILED(res)) {
  7609. renderer->supportsTearing = false;
  7610. }
  7611. IDXGIFactory5_Release(factory5);
  7612. }
  7613. // Select the appropriate device for rendering
  7614. res = IDXGIFactory4_QueryInterface(
  7615. renderer->factory,
  7616. D3D_GUID(D3D_IID_IDXGIFactory6),
  7617. (void **)&factory6);
  7618. if (SUCCEEDED(res)) {
  7619. res = IDXGIFactory6_EnumAdapterByGpuPreference(
  7620. factory6,
  7621. 0,
  7622. preferLowPower ? DXGI_GPU_PREFERENCE_MINIMUM_POWER : DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
  7623. D3D_GUID(D3D_IID_IDXGIAdapter1),
  7624. (void **)&renderer->adapter);
  7625. IDXGIFactory6_Release(factory6);
  7626. } else {
  7627. res = IDXGIFactory4_EnumAdapters1(
  7628. renderer->factory,
  7629. 0,
  7630. &renderer->adapter);
  7631. }
  7632. if (FAILED(res)) {
  7633. D3D12_INTERNAL_DestroyRenderer(renderer);
  7634. CHECK_D3D12_ERROR_AND_RETURN("Could not find adapter for D3D12Device", NULL);
  7635. }
  7636. // Get information about the selected adapter. Used for logging info.
  7637. res = IDXGIAdapter1_GetDesc1(renderer->adapter, &adapterDesc);
  7638. if (FAILED(res)) {
  7639. D3D12_INTERNAL_DestroyRenderer(renderer);
  7640. CHECK_D3D12_ERROR_AND_RETURN("Could not get adapter description", NULL);
  7641. }
  7642. res = IDXGIAdapter1_CheckInterfaceSupport(renderer->adapter, D3D_GUID(D3D_IID_IDXGIDevice), &umdVersion);
  7643. if (FAILED(res)) {
  7644. D3D12_INTERNAL_DestroyRenderer(renderer);
  7645. CHECK_D3D12_ERROR_AND_RETURN("Could not get adapter driver version", NULL);
  7646. }
  7647. renderer->props = SDL_CreateProperties();
  7648. if (verboseLogs) {
  7649. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "SDL_GPU Driver: D3D12");
  7650. }
  7651. // Record device name
  7652. char *deviceName = SDL_iconv_wchar_utf8(&adapterDesc.Description[0]);
  7653. SDL_SetStringProperty(
  7654. renderer->props,
  7655. SDL_PROP_GPU_DEVICE_NAME_STRING,
  7656. deviceName);
  7657. if (verboseLogs) {
  7658. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "D3D12 Adapter: %s", deviceName);
  7659. }
  7660. SDL_free(deviceName);
  7661. // Record driver version
  7662. char driverVer[64];
  7663. (void)SDL_snprintf(
  7664. driverVer,
  7665. SDL_arraysize(driverVer),
  7666. "%d.%d.%d.%d",
  7667. HIWORD(umdVersion.HighPart),
  7668. LOWORD(umdVersion.HighPart),
  7669. HIWORD(umdVersion.LowPart),
  7670. LOWORD(umdVersion.LowPart));
  7671. SDL_SetStringProperty(
  7672. renderer->props,
  7673. SDL_PROP_GPU_DEVICE_DRIVER_VERSION_STRING,
  7674. driverVer);
  7675. if (verboseLogs) {
  7676. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "D3D12 Driver: %s", driverVer);
  7677. }
  7678. #endif
  7679. // Load the D3D library
  7680. renderer->d3d12_dll = SDL_LoadObject(D3D12_DLL);
  7681. if (renderer->d3d12_dll == NULL) {
  7682. D3D12_INTERNAL_DestroyRenderer(renderer);
  7683. SET_STRING_ERROR_AND_RETURN("Could not find " D3D12_DLL, NULL);
  7684. }
  7685. // Load the CreateDevice function
  7686. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7687. D3D12XboxCreateDeviceFunc = (PFN_D3D12_XBOX_CREATE_DEVICE)SDL_LoadFunction(
  7688. renderer->d3d12_dll,
  7689. "D3D12XboxCreateDevice");
  7690. if (D3D12XboxCreateDeviceFunc == NULL) {
  7691. D3D12_INTERNAL_DestroyRenderer(renderer);
  7692. SET_STRING_ERROR_AND_RETURN("Could not load function: D3D12XboxCreateDevice", NULL);
  7693. }
  7694. #else
  7695. pD3D12CreateDevice = (PFN_D3D12_CREATE_DEVICE)SDL_LoadFunction(
  7696. renderer->d3d12_dll,
  7697. D3D12_CREATE_DEVICE_FUNC);
  7698. if (pD3D12CreateDevice == NULL) {
  7699. D3D12_INTERNAL_DestroyRenderer(renderer);
  7700. SET_STRING_ERROR_AND_RETURN("Could not load function: " D3D12_CREATE_DEVICE_FUNC, NULL);
  7701. }
  7702. #endif
  7703. renderer->pD3D12SerializeRootSignature = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)SDL_LoadFunction(
  7704. renderer->d3d12_dll,
  7705. D3D12_SERIALIZE_ROOT_SIGNATURE_FUNC);
  7706. if (renderer->pD3D12SerializeRootSignature == NULL) {
  7707. D3D12_INTERNAL_DestroyRenderer(renderer);
  7708. SET_STRING_ERROR_AND_RETURN("Could not load function: " D3D12_SERIALIZE_ROOT_SIGNATURE_FUNC, NULL);
  7709. }
  7710. // Initialize the D3D12 debug layer, if applicable
  7711. if (debugMode) {
  7712. bool hasD3d12Debug = D3D12_INTERNAL_TryInitializeD3D12Debug(renderer);
  7713. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7714. if (hasD3d12Debug) {
  7715. SDL_LogInfo(
  7716. SDL_LOG_CATEGORY_GPU,
  7717. "Validation layers enabled, expect debug level performance!");
  7718. #else
  7719. if (hasDxgiDebug && hasD3d12Debug) {
  7720. SDL_LogInfo(
  7721. SDL_LOG_CATEGORY_GPU,
  7722. "Validation layers enabled, expect debug level performance!");
  7723. } else if (hasDxgiDebug || hasD3d12Debug) {
  7724. SDL_LogWarn(
  7725. SDL_LOG_CATEGORY_GPU,
  7726. "Validation layers partially enabled, some warnings may not be available");
  7727. #endif
  7728. } else {
  7729. SDL_LogWarn(
  7730. SDL_LOG_CATEGORY_GPU,
  7731. "Validation layers not found, continuing without validation");
  7732. }
  7733. }
  7734. // Create the D3D12Device
  7735. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7736. if (s_Device != NULL) {
  7737. renderer->device = s_Device;
  7738. } else {
  7739. SDL_zero(createDeviceParams);
  7740. createDeviceParams.Version = D3D12_SDK_VERSION;
  7741. createDeviceParams.GraphicsCommandQueueRingSizeBytes = D3D12XBOX_DEFAULT_SIZE_BYTES;
  7742. createDeviceParams.GraphicsScratchMemorySizeBytes = D3D12XBOX_DEFAULT_SIZE_BYTES;
  7743. createDeviceParams.ComputeScratchMemorySizeBytes = D3D12XBOX_DEFAULT_SIZE_BYTES;
  7744. createDeviceParams.DisableGeometryShaderAllocations = TRUE;
  7745. createDeviceParams.DisableTessellationShaderAllocations = TRUE;
  7746. #if defined(SDL_PLATFORM_XBOXSERIES)
  7747. createDeviceParams.DisableDXR = TRUE;
  7748. #endif
  7749. if (debugMode) {
  7750. createDeviceParams.ProcessDebugFlags = D3D12XBOX_PROCESS_DEBUG_FLAG_DEBUG;
  7751. }
  7752. res = D3D12XboxCreateDeviceFunc(
  7753. NULL,
  7754. &createDeviceParams,
  7755. IID_GRAPHICS_PPV_ARGS(&renderer->device));
  7756. if (FAILED(res)) {
  7757. D3D12_INTERNAL_DestroyRenderer(renderer);
  7758. CHECK_D3D12_ERROR_AND_RETURN("Could not create D3D12Device", NULL);
  7759. }
  7760. s_Device = renderer->device;
  7761. }
  7762. #else
  7763. res = pD3D12CreateDevice(
  7764. (IUnknown *)renderer->adapter,
  7765. D3D_FEATURE_LEVEL_CHOICE,
  7766. D3D_GUID(D3D_IID_ID3D12Device),
  7767. (void **)&renderer->device);
  7768. if (FAILED(res)) {
  7769. D3D12_INTERNAL_DestroyRenderer(renderer);
  7770. CHECK_D3D12_ERROR_AND_RETURN("Could not create D3D12Device", NULL);
  7771. }
  7772. // Initialize the D3D12 debug info queue, if applicable
  7773. if (debugMode) {
  7774. D3D12_INTERNAL_TryInitializeD3D12DebugInfoQueue(renderer);
  7775. D3D12_INTERNAL_TryInitializeD3D12DebugInfoLogger(renderer);
  7776. }
  7777. #endif
  7778. // Check UMA
  7779. architecture.NodeIndex = 0;
  7780. res = ID3D12Device_CheckFeatureSupport(
  7781. renderer->device,
  7782. D3D12_FEATURE_ARCHITECTURE,
  7783. &architecture,
  7784. sizeof(D3D12_FEATURE_DATA_ARCHITECTURE));
  7785. if (FAILED(res)) {
  7786. D3D12_INTERNAL_DestroyRenderer(renderer);
  7787. CHECK_D3D12_ERROR_AND_RETURN("Could not get device architecture", NULL);
  7788. }
  7789. renderer->UMA = (bool)architecture.UMA;
  7790. renderer->UMACacheCoherent = (bool)architecture.CacheCoherentUMA;
  7791. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7792. renderer->GPUUploadHeapSupported = false;
  7793. #else
  7794. // Check "GPU Upload Heap" support (for fast uniform buffers)
  7795. D3D12_FEATURE_DATA_D3D12_OPTIONS16 options16; // 15 wasn't enough, huh?
  7796. renderer->GPUUploadHeapSupported = false;
  7797. res = ID3D12Device_CheckFeatureSupport(
  7798. renderer->device,
  7799. D3D12_FEATURE_D3D12_OPTIONS16,
  7800. &options16,
  7801. sizeof(options16));
  7802. if (SUCCEEDED(res)) {
  7803. renderer->GPUUploadHeapSupported = options16.GPUUploadHeapSupported;
  7804. }
  7805. #endif
  7806. // Create command queue
  7807. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7808. if (s_CommandQueue != NULL) {
  7809. renderer->commandQueue = s_CommandQueue;
  7810. } else {
  7811. #endif
  7812. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  7813. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  7814. queueDesc.NodeMask = 0;
  7815. queueDesc.Priority = 0;
  7816. res = ID3D12Device_CreateCommandQueue(
  7817. renderer->device,
  7818. &queueDesc,
  7819. D3D_GUID(D3D_IID_ID3D12CommandQueue),
  7820. (void **)&renderer->commandQueue);
  7821. if (FAILED(res)) {
  7822. D3D12_INTERNAL_DestroyRenderer(renderer);
  7823. CHECK_D3D12_ERROR_AND_RETURN("Could not create D3D12CommandQueue", NULL);
  7824. }
  7825. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7826. s_CommandQueue = renderer->commandQueue;
  7827. }
  7828. #endif
  7829. // Create indirect command signatures
  7830. D3D12_COMMAND_SIGNATURE_DESC commandSignatureDesc;
  7831. D3D12_INDIRECT_ARGUMENT_DESC indirectArgumentDesc;
  7832. SDL_zero(indirectArgumentDesc);
  7833. indirectArgumentDesc.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW;
  7834. commandSignatureDesc.NodeMask = 0;
  7835. commandSignatureDesc.ByteStride = sizeof(SDL_GPUIndirectDrawCommand);
  7836. commandSignatureDesc.NumArgumentDescs = 1;
  7837. commandSignatureDesc.pArgumentDescs = &indirectArgumentDesc;
  7838. res = ID3D12Device_CreateCommandSignature(
  7839. renderer->device,
  7840. &commandSignatureDesc,
  7841. NULL,
  7842. D3D_GUID(D3D_IID_ID3D12CommandSignature),
  7843. (void **)&renderer->indirectDrawCommandSignature);
  7844. if (FAILED(res)) {
  7845. D3D12_INTERNAL_DestroyRenderer(renderer);
  7846. CHECK_D3D12_ERROR_AND_RETURN("Could not create indirect draw command signature", NULL);
  7847. }
  7848. indirectArgumentDesc.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED;
  7849. commandSignatureDesc.ByteStride = sizeof(SDL_GPUIndexedIndirectDrawCommand);
  7850. commandSignatureDesc.pArgumentDescs = &indirectArgumentDesc;
  7851. res = ID3D12Device_CreateCommandSignature(
  7852. renderer->device,
  7853. &commandSignatureDesc,
  7854. NULL,
  7855. D3D_GUID(D3D_IID_ID3D12CommandSignature),
  7856. (void **)&renderer->indirectIndexedDrawCommandSignature);
  7857. if (FAILED(res)) {
  7858. D3D12_INTERNAL_DestroyRenderer(renderer);
  7859. CHECK_D3D12_ERROR_AND_RETURN("Could not create indirect indexed draw command signature", NULL);
  7860. }
  7861. indirectArgumentDesc.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
  7862. commandSignatureDesc.ByteStride = sizeof(SDL_GPUIndirectDispatchCommand);
  7863. commandSignatureDesc.pArgumentDescs = &indirectArgumentDesc;
  7864. res = ID3D12Device_CreateCommandSignature(
  7865. renderer->device,
  7866. &commandSignatureDesc,
  7867. NULL,
  7868. D3D_GUID(D3D_IID_ID3D12CommandSignature),
  7869. (void **)&renderer->indirectDispatchCommandSignature);
  7870. if (FAILED(res)) {
  7871. D3D12_INTERNAL_DestroyRenderer(renderer);
  7872. CHECK_D3D12_ERROR_AND_RETURN("Could not create indirect dispatch command signature", NULL);
  7873. }
  7874. // Initialize pools
  7875. renderer->submittedCommandBufferCapacity = 4;
  7876. renderer->submittedCommandBufferCount = 0;
  7877. renderer->submittedCommandBuffers = (D3D12CommandBuffer **)SDL_calloc(
  7878. renderer->submittedCommandBufferCapacity, sizeof(D3D12CommandBuffer *));
  7879. if (!renderer->submittedCommandBuffers) {
  7880. D3D12_INTERNAL_DestroyRenderer(renderer);
  7881. return NULL;
  7882. }
  7883. renderer->uniformBufferPoolCapacity = 4;
  7884. renderer->uniformBufferPoolCount = 0;
  7885. renderer->uniformBufferPool = (D3D12UniformBuffer **)SDL_calloc(
  7886. renderer->uniformBufferPoolCapacity, sizeof(D3D12UniformBuffer *));
  7887. if (!renderer->uniformBufferPool) {
  7888. D3D12_INTERNAL_DestroyRenderer(renderer);
  7889. return NULL;
  7890. }
  7891. renderer->claimedWindowCapacity = 4;
  7892. renderer->claimedWindowCount = 0;
  7893. renderer->claimedWindows = (D3D12WindowData **)SDL_calloc(
  7894. renderer->claimedWindowCapacity, sizeof(D3D12WindowData *));
  7895. if (!renderer->claimedWindows) {
  7896. D3D12_INTERNAL_DestroyRenderer(renderer);
  7897. return NULL;
  7898. }
  7899. renderer->availableFenceCapacity = 4;
  7900. renderer->availableFenceCount = 0;
  7901. renderer->availableFences = (D3D12Fence **)SDL_calloc(
  7902. renderer->availableFenceCapacity, sizeof(D3D12Fence *));
  7903. if (!renderer->availableFences) {
  7904. D3D12_INTERNAL_DestroyRenderer(renderer);
  7905. return NULL;
  7906. }
  7907. // Initialize staging descriptor pools
  7908. for (Uint32 i = 0; i < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; i += 1) {
  7909. renderer->stagingDescriptorPools[i] = D3D12_INTERNAL_CreateStagingDescriptorPool(
  7910. renderer,
  7911. (D3D12_DESCRIPTOR_HEAP_TYPE)i);
  7912. if (renderer->stagingDescriptorPools[i] == NULL) {
  7913. D3D12_INTERNAL_DestroyRenderer(renderer);
  7914. return NULL;
  7915. }
  7916. }
  7917. // Initialize GPU descriptor heaps
  7918. for (Uint32 i = 0; i < 2; i += 1) {
  7919. renderer->gpuDescriptorHeapPools[i].lock = SDL_CreateMutex();
  7920. renderer->gpuDescriptorHeapPools[i].capacity = 4;
  7921. renderer->gpuDescriptorHeapPools[i].count = 4;
  7922. renderer->gpuDescriptorHeapPools[i].heaps = (D3D12DescriptorHeap **)SDL_calloc(
  7923. renderer->gpuDescriptorHeapPools[i].capacity, sizeof(D3D12DescriptorHeap *));
  7924. for (Uint32 j = 0; j < renderer->gpuDescriptorHeapPools[i].capacity; j += 1) {
  7925. renderer->gpuDescriptorHeapPools[i].heaps[j] = D3D12_INTERNAL_CreateDescriptorHeap(
  7926. renderer,
  7927. (D3D12_DESCRIPTOR_HEAP_TYPE)i,
  7928. i == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ? VIEW_GPU_DESCRIPTOR_COUNT : SAMPLER_GPU_DESCRIPTOR_COUNT,
  7929. false);
  7930. if (renderer->gpuDescriptorHeapPools[i].heaps[j] == NULL) {
  7931. D3D12_INTERNAL_DestroyRenderer(renderer);
  7932. return NULL;
  7933. }
  7934. }
  7935. }
  7936. // Deferred resource releasing
  7937. renderer->buffersToDestroyCapacity = 4;
  7938. renderer->buffersToDestroyCount = 0;
  7939. renderer->buffersToDestroy = (D3D12Buffer **)SDL_calloc(
  7940. renderer->buffersToDestroyCapacity, sizeof(D3D12Buffer *));
  7941. if (!renderer->buffersToDestroy) {
  7942. D3D12_INTERNAL_DestroyRenderer(renderer);
  7943. return NULL;
  7944. }
  7945. renderer->texturesToDestroyCapacity = 4;
  7946. renderer->texturesToDestroyCount = 0;
  7947. renderer->texturesToDestroy = (D3D12Texture **)SDL_calloc(
  7948. renderer->texturesToDestroyCapacity, sizeof(D3D12Texture *));
  7949. if (!renderer->texturesToDestroy) {
  7950. D3D12_INTERNAL_DestroyRenderer(renderer);
  7951. return NULL;
  7952. }
  7953. renderer->samplersToDestroyCapacity = 4;
  7954. renderer->samplersToDestroyCount = 0;
  7955. renderer->samplersToDestroy = (D3D12Sampler **)SDL_calloc(
  7956. renderer->samplersToDestroyCapacity, sizeof(D3D12Sampler *));
  7957. if (!renderer->samplersToDestroy) {
  7958. D3D12_INTERNAL_DestroyRenderer(renderer);
  7959. return NULL;
  7960. }
  7961. renderer->graphicsPipelinesToDestroyCapacity = 4;
  7962. renderer->graphicsPipelinesToDestroyCount = 0;
  7963. renderer->graphicsPipelinesToDestroy = (D3D12GraphicsPipeline **)SDL_calloc(
  7964. renderer->graphicsPipelinesToDestroyCapacity, sizeof(D3D12GraphicsPipeline *));
  7965. if (!renderer->graphicsPipelinesToDestroy) {
  7966. D3D12_INTERNAL_DestroyRenderer(renderer);
  7967. return NULL;
  7968. }
  7969. renderer->computePipelinesToDestroyCapacity = 4;
  7970. renderer->computePipelinesToDestroyCount = 0;
  7971. renderer->computePipelinesToDestroy = (D3D12ComputePipeline **)SDL_calloc(
  7972. renderer->computePipelinesToDestroyCapacity, sizeof(D3D12ComputePipeline *));
  7973. if (!renderer->computePipelinesToDestroy) {
  7974. D3D12_INTERNAL_DestroyRenderer(renderer);
  7975. return NULL;
  7976. }
  7977. // Locks
  7978. renderer->acquireCommandBufferLock = SDL_CreateMutex();
  7979. renderer->acquireUniformBufferLock = SDL_CreateMutex();
  7980. renderer->submitLock = SDL_CreateMutex();
  7981. renderer->windowLock = SDL_CreateMutex();
  7982. renderer->fenceLock = SDL_CreateMutex();
  7983. renderer->disposeLock = SDL_CreateMutex();
  7984. renderer->debug_mode = debugMode;
  7985. renderer->allowedFramesInFlight = 2;
  7986. renderer->semantic = SDL_strdup(SDL_GetStringProperty(props, SDL_PROP_GPU_DEVICE_CREATE_D3D12_SEMANTIC_NAME_STRING, "TEXCOORD"));
  7987. // Blit resources
  7988. D3D12_INTERNAL_InitBlitResources(renderer);
  7989. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7990. res = renderer->device->SetFrameIntervalX(
  7991. NULL,
  7992. D3D12XBOX_FRAME_INTERVAL_60_HZ,
  7993. renderer->allowedFramesInFlight - 1,
  7994. D3D12XBOX_FRAME_INTERVAL_FLAG_NONE);
  7995. if (FAILED(res)) {
  7996. D3D12_INTERNAL_DestroyRenderer(renderer);
  7997. CHECK_D3D12_ERROR_AND_RETURN("Could not get set frame interval", NULL);
  7998. }
  7999. res = renderer->device->ScheduleFrameEventX(
  8000. D3D12XBOX_FRAME_EVENT_ORIGIN,
  8001. 0,
  8002. NULL,
  8003. D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAG_NONE);
  8004. if (FAILED(res)) {
  8005. D3D12_INTERNAL_DestroyRenderer(renderer);
  8006. CHECK_D3D12_ERROR_AND_RETURN("Could not schedule frame events", NULL);
  8007. }
  8008. #endif
  8009. // Create the SDL_GPU Device
  8010. result = (SDL_GPUDevice *)SDL_calloc(1, sizeof(SDL_GPUDevice));
  8011. if (!result) {
  8012. D3D12_INTERNAL_DestroyRenderer(renderer);
  8013. return NULL;
  8014. }
  8015. SDL_GPUShaderFormat shaderFormats = SDL_GPU_SHADERFORMAT_DXBC;
  8016. D3D12_FEATURE_DATA_SHADER_MODEL shaderModel;
  8017. shaderModel.HighestShaderModel = D3D_SHADER_MODEL_6_0;
  8018. res = ID3D12Device_CheckFeatureSupport(
  8019. renderer->device,
  8020. D3D12_FEATURE_SHADER_MODEL,
  8021. &shaderModel,
  8022. sizeof(shaderModel));
  8023. if (SUCCEEDED(res) && shaderModel.HighestShaderModel >= D3D_SHADER_MODEL_6_0) {
  8024. shaderFormats |= SDL_GPU_SHADERFORMAT_DXIL;
  8025. }
  8026. ASSIGN_DRIVER(D3D12)
  8027. result->driverData = (SDL_GPURenderer *)renderer;
  8028. result->shader_formats = shaderFormats;
  8029. result->debug_mode = debugMode;
  8030. renderer->sdlGPUDevice = result;
  8031. return result;
  8032. }
  8033. SDL_GPUBootstrap D3D12Driver = {
  8034. "direct3d12",
  8035. D3D12_PrepareDriver,
  8036. D3D12_CreateDevice
  8037. };
  8038. #endif // SDL_GPU_D3D12
  8039. // GDK-specific APIs
  8040. #ifdef SDL_PLATFORM_GDK
  8041. void SDL_GDKSuspendGPU(SDL_GPUDevice *device)
  8042. {
  8043. #if defined(SDL_GPU_D3D12) && (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  8044. D3D12Renderer *renderer = (D3D12Renderer *)device->driverData;
  8045. HRESULT res;
  8046. if (device == NULL) {
  8047. SET_STRING_ERROR_AND_RETURN("Invalid GPU device", );
  8048. }
  8049. SDL_LockMutex(renderer->submitLock);
  8050. res = renderer->commandQueue->SuspendX(0);
  8051. if (FAILED(res)) {
  8052. SDL_LogError(SDL_LOG_CATEGORY_GPU, "SuspendX failed: %X", res);
  8053. }
  8054. SDL_UnlockMutex(renderer->submitLock);
  8055. #endif
  8056. }
  8057. void SDL_GDKResumeGPU(SDL_GPUDevice *device)
  8058. {
  8059. #if defined(SDL_GPU_D3D12) && (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  8060. D3D12Renderer *renderer = (D3D12Renderer *)device->driverData;
  8061. HRESULT res;
  8062. if (device == NULL) {
  8063. SET_STRING_ERROR_AND_RETURN("Invalid GPU device", );
  8064. }
  8065. SDL_LockMutex(renderer->submitLock);
  8066. res = renderer->commandQueue->ResumeX();
  8067. if (FAILED(res)) {
  8068. SDL_LogError(SDL_LOG_CATEGORY_GPU, "ResumeX failed: %X", res);
  8069. }
  8070. SDL_UnlockMutex(renderer->submitLock);
  8071. res = renderer->device->SetFrameIntervalX(
  8072. NULL,
  8073. D3D12XBOX_FRAME_INTERVAL_60_HZ,
  8074. renderer->allowedFramesInFlight - 1,
  8075. D3D12XBOX_FRAME_INTERVAL_FLAG_NONE);
  8076. if (FAILED(res)) {
  8077. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not set frame interval: %X", res);
  8078. }
  8079. res = renderer->device->ScheduleFrameEventX(
  8080. D3D12XBOX_FRAME_EVENT_ORIGIN,
  8081. 0,
  8082. NULL,
  8083. D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAG_NONE);
  8084. if (FAILED(res)) {
  8085. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not schedule frame events: %X", res);
  8086. }
  8087. #endif
  8088. }
  8089. #endif // SDL_PLATFORM_GDK