SDL_gpu_d3d12.c 340 KB

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