SDL_gpu_d3d12.c 338 KB

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