SDL_render_d3d12.c 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2024 Sam Lantinga <[email protected]>
  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. #if SDL_VIDEO_RENDER_D3D12
  20. #define SDL_D3D12_NUM_BUFFERS 2
  21. #define SDL_D3D12_NUM_VERTEX_BUFFERS 256
  22. #define SDL_D3D12_MAX_NUM_TEXTURES 16384
  23. #define SDL_D3D12_NUM_UPLOAD_BUFFERS 32
  24. #include "../../core/windows/SDL_windows.h"
  25. #include "../../video/windows/SDL_windowswindow.h"
  26. #include "../SDL_sysrender.h"
  27. #include "../SDL_d3dmath.h"
  28. #include "../../video/SDL_pixels_c.h"
  29. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  30. #include "SDL_render_d3d12_xbox.h"
  31. #ifndef D3D12_TEXTURE_DATA_PITCH_ALIGNMENT
  32. #define D3D12_TEXTURE_DATA_PITCH_ALIGNMENT 256
  33. #endif
  34. #else
  35. #include <d3d12.h>
  36. #include <dxgi1_6.h>
  37. #include <dxgidebug.h>
  38. #include <d3d12sdklayers.h>
  39. #endif
  40. #include "SDL_shaders_d3d12.h"
  41. #if defined(_MSC_VER) && !defined(__clang__)
  42. #define SDL_COMPOSE_ERROR(str) __FUNCTION__ ", " str
  43. #else
  44. #define SDL_COMPOSE_ERROR(str) SDL_STRINGIFY_ARG(__FUNCTION__) ", " str
  45. #endif
  46. #ifdef __cplusplus
  47. #define SAFE_RELEASE(X) \
  48. if (X) { \
  49. (X)->Release(); \
  50. X = NULL; \
  51. }
  52. #define D3D_CALL(THIS, FUNC, ...) (THIS)->FUNC(__VA_ARGS__)
  53. #define D3D_CALL_RET(THIS, FUNC, RETVAL, ...) *(RETVAL) = (THIS)->FUNC(__VA_ARGS__)
  54. #define D3D_GUID(X) (X)
  55. #else
  56. #define SAFE_RELEASE(X) \
  57. if (X) { \
  58. (X)->lpVtbl->Release(X); \
  59. X = NULL; \
  60. }
  61. #define D3D_CALL(THIS, FUNC, ...) (THIS)->lpVtbl->FUNC((THIS), ##__VA_ARGS__)
  62. #define D3D_CALL_RET(THIS, FUNC, ...) (THIS)->lpVtbl->FUNC((THIS), ##__VA_ARGS__)
  63. #define D3D_GUID(X) &(X)
  64. #endif
  65. /* Set up for C function definitions, even when using C++ */
  66. #ifdef __cplusplus
  67. extern "C" {
  68. #endif
  69. /* !!! FIXME: vertex buffer bandwidth could be lower; only use UV coords when
  70. !!! FIXME: textures are needed. */
  71. /* Vertex shader, common values */
  72. typedef struct
  73. {
  74. Float4X4 model;
  75. Float4X4 projectionAndView;
  76. } VertexShaderConstants;
  77. typedef struct
  78. {
  79. float scRGB_output;
  80. float color_scale;
  81. float unused1;
  82. float unused2;
  83. float YCbCr_matrix[16];
  84. } PixelShaderConstants;
  85. /* Per-vertex data */
  86. typedef struct
  87. {
  88. Float2 pos;
  89. Float2 tex;
  90. SDL_FColor color;
  91. } VertexPositionColor;
  92. /* Per-texture data */
  93. typedef struct
  94. {
  95. int w, h;
  96. ID3D12Resource *mainTexture;
  97. D3D12_CPU_DESCRIPTOR_HANDLE mainTextureResourceView;
  98. D3D12_RESOURCE_STATES mainResourceState;
  99. SIZE_T mainSRVIndex;
  100. D3D12_CPU_DESCRIPTOR_HANDLE mainTextureRenderTargetView;
  101. DXGI_FORMAT mainTextureFormat;
  102. ID3D12Resource *stagingBuffer;
  103. D3D12_RESOURCE_STATES stagingResourceState;
  104. D3D12_FILTER scaleMode;
  105. D3D12_Shader shader;
  106. const float *shader_params;
  107. #if SDL_HAVE_YUV
  108. /* YV12 texture support */
  109. SDL_bool yuv;
  110. ID3D12Resource *mainTextureU;
  111. D3D12_CPU_DESCRIPTOR_HANDLE mainTextureResourceViewU;
  112. D3D12_RESOURCE_STATES mainResourceStateU;
  113. SIZE_T mainSRVIndexU;
  114. ID3D12Resource *mainTextureV;
  115. D3D12_CPU_DESCRIPTOR_HANDLE mainTextureResourceViewV;
  116. D3D12_RESOURCE_STATES mainResourceStateV;
  117. SIZE_T mainSRVIndexV;
  118. /* NV12 texture support */
  119. SDL_bool nv12;
  120. D3D12_CPU_DESCRIPTOR_HANDLE mainTextureResourceViewNV;
  121. SIZE_T mainSRVIndexNV;
  122. Uint8 *pixels;
  123. int pitch;
  124. #endif
  125. SDL_Rect lockedRect;
  126. } D3D12_TextureData;
  127. /* Pipeline State Object data */
  128. typedef struct
  129. {
  130. D3D12_Shader shader;
  131. SDL_bool scRGB_output;
  132. float color_scale;
  133. const float *shader_params;
  134. SDL_BlendMode blendMode;
  135. D3D12_PRIMITIVE_TOPOLOGY_TYPE topology;
  136. DXGI_FORMAT rtvFormat;
  137. ID3D12PipelineState *pipelineState;
  138. } D3D12_PipelineState;
  139. /* Vertex Buffer */
  140. typedef struct
  141. {
  142. ID3D12Resource *resource;
  143. D3D12_VERTEX_BUFFER_VIEW view;
  144. size_t size;
  145. } D3D12_VertexBuffer;
  146. /* For SRV pool allocator */
  147. typedef struct
  148. {
  149. SIZE_T index;
  150. void *next;
  151. } D3D12_SRVPoolNode;
  152. /* Private renderer data */
  153. typedef struct
  154. {
  155. void *hDXGIMod;
  156. void *hD3D12Mod;
  157. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  158. UINT64 frameToken;
  159. #else
  160. IDXGIFactory6 *dxgiFactory;
  161. IDXGIAdapter4 *dxgiAdapter;
  162. IDXGIDebug *dxgiDebug;
  163. IDXGISwapChain4 *swapChain;
  164. #endif
  165. ID3D12Device1 *d3dDevice;
  166. ID3D12Debug *debugInterface;
  167. ID3D12CommandQueue *commandQueue;
  168. ID3D12GraphicsCommandList2 *commandList;
  169. DXGI_SWAP_EFFECT swapEffect;
  170. UINT swapFlags;
  171. DXGI_FORMAT renderTargetFormat;
  172. SDL_bool pixelSizeChanged;
  173. /* Descriptor heaps */
  174. ID3D12DescriptorHeap *rtvDescriptorHeap;
  175. UINT rtvDescriptorSize;
  176. ID3D12DescriptorHeap *textureRTVDescriptorHeap;
  177. ID3D12DescriptorHeap *srvDescriptorHeap;
  178. UINT srvDescriptorSize;
  179. ID3D12DescriptorHeap *samplerDescriptorHeap;
  180. UINT samplerDescriptorSize;
  181. /* Data needed per backbuffer */
  182. ID3D12CommandAllocator *commandAllocators[SDL_D3D12_NUM_BUFFERS];
  183. ID3D12Resource *renderTargets[SDL_D3D12_NUM_BUFFERS];
  184. UINT64 fenceValue;
  185. int currentBackBufferIndex;
  186. /* Fences */
  187. ID3D12Fence *fence;
  188. HANDLE fenceEvent;
  189. /* Root signature and pipeline state data */
  190. ID3D12RootSignature *rootSignatures[NUM_ROOTSIGS];
  191. int pipelineStateCount;
  192. D3D12_PipelineState *pipelineStates;
  193. D3D12_PipelineState *currentPipelineState;
  194. D3D12_VertexBuffer vertexBuffers[SDL_D3D12_NUM_VERTEX_BUFFERS];
  195. D3D12_CPU_DESCRIPTOR_HANDLE nearestPixelSampler;
  196. D3D12_CPU_DESCRIPTOR_HANDLE linearSampler;
  197. /* Data for staging/allocating textures */
  198. ID3D12Resource *uploadBuffers[SDL_D3D12_NUM_UPLOAD_BUFFERS];
  199. int currentUploadBuffer;
  200. /* Pool allocator to handle reusing SRV heap indices */
  201. D3D12_SRVPoolNode *srvPoolHead;
  202. D3D12_SRVPoolNode srvPoolNodes[SDL_D3D12_MAX_NUM_TEXTURES];
  203. /* Vertex buffer constants */
  204. VertexShaderConstants vertexShaderConstantsData;
  205. /* Cached renderer properties */
  206. DXGI_MODE_ROTATION rotation;
  207. D3D12_TextureData *textureRenderTarget;
  208. D3D12_CPU_DESCRIPTOR_HANDLE currentRenderTargetView;
  209. D3D12_CPU_DESCRIPTOR_HANDLE currentShaderResource;
  210. D3D12_CPU_DESCRIPTOR_HANDLE currentSampler;
  211. SDL_bool cliprectDirty;
  212. SDL_bool currentCliprectEnabled;
  213. SDL_Rect currentCliprect;
  214. SDL_Rect currentViewport;
  215. int currentViewportRotation;
  216. SDL_bool viewportDirty;
  217. Float4X4 identity;
  218. int currentVertexBuffer;
  219. SDL_bool issueBatch;
  220. } D3D12_RenderData;
  221. /* Define D3D GUIDs here so we don't have to include uuid.lib. */
  222. #ifdef HAVE_GCC_DIAGNOSTIC_PRAGMA
  223. #pragma GCC diagnostic push
  224. #pragma GCC diagnostic ignored "-Wunused-const-variable"
  225. #endif
  226. static const GUID SDL_IID_IDXGIFactory6 = { 0xc1b6694f, 0xff09, 0x44a9, { 0xb0, 0x3c, 0x77, 0x90, 0x0a, 0x0a, 0x1d, 0x17 } };
  227. static const GUID SDL_IID_IDXGIAdapter4 = { 0x3c8d99d1, 0x4fbf, 0x4181, { 0xa8, 0x2c, 0xaf, 0x66, 0xbf, 0x7b, 0xd2, 0x4e } };
  228. static const GUID SDL_IID_IDXGIDevice1 = { 0x77db970f, 0x6276, 0x48ba, { 0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c } };
  229. static const GUID SDL_IID_ID3D12Device1 = { 0x77acce80, 0x638e, 0x4e65, { 0x88, 0x95, 0xc1, 0xf2, 0x33, 0x86, 0x86, 0x3e } };
  230. static const GUID SDL_IID_IDXGISwapChain4 = { 0x3D585D5A, 0xBD4A, 0x489E, { 0xB1, 0xF4, 0x3D, 0xBC, 0xB6, 0x45, 0x2F, 0xFB } };
  231. static const GUID SDL_IID_IDXGIDebug1 = { 0xc5a05f0c, 0x16f2, 0x4adf, { 0x9f, 0x4d, 0xa8, 0xc4, 0xd5, 0x8a, 0xc5, 0x50 } };
  232. static const GUID SDL_IID_IDXGIInfoQueue = { 0xD67441C7, 0x672A, 0x476f, { 0x9E, 0x82, 0xCD, 0x55, 0xB4, 0x49, 0x49, 0xCE } };
  233. static const GUID SDL_IID_ID3D12Debug = { 0x344488b7, 0x6846, 0x474b, { 0xb9, 0x89, 0xf0, 0x27, 0x44, 0x82, 0x45, 0xe0 } };
  234. static const GUID SDL_DXGI_DEBUG_ALL = { 0xe48ae283, 0xda80, 0x490b, { 0x87, 0xe6, 0x43, 0xe9, 0xa9, 0xcf, 0xda, 0x8 } };
  235. static const GUID SDL_IID_ID3D12CommandQueue = { 0x0ec870a6, 0x5d7e, 0x4c22, { 0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed } };
  236. static const GUID SDL_IID_ID3D12DescriptorHeap = { 0x8efb471d, 0x616c, 0x4f49, { 0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51 } };
  237. static const GUID SDL_IID_ID3D12CommandAllocator = { 0x6102dee4, 0xaf59, 0x4b09, { 0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24 } };
  238. static const GUID SDL_IID_ID3D12GraphicsCommandList2 = { 0x38C3E585, 0xFF17, 0x412C, { 0x91, 0x50, 0x4F, 0xC6, 0xF9, 0xD7, 0x2A, 0x28 } };
  239. static const GUID SDL_IID_ID3D12Fence = { 0x0a753dcf, 0xc4d8, 0x4b91, { 0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76 } };
  240. static const GUID SDL_IID_ID3D12Resource = { 0x696442be, 0xa72e, 0x4059, { 0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad } };
  241. static const GUID SDL_IID_ID3D12RootSignature = { 0xc54a6b66, 0x72df, 0x4ee8, { 0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14 } };
  242. static const GUID SDL_IID_ID3D12PipelineState = { 0x765a30f3, 0xf624, 0x4c6f, { 0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45 } };
  243. static const GUID SDL_IID_ID3D12Heap = { 0x6b3b2502, 0x6e51, 0x45b3, { 0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3 } };
  244. static const GUID SDL_IID_ID3D12InfoQueue = { 0x0742a90b, 0xc387, 0x483f, { 0xb9, 0x46, 0x30, 0xa7, 0xe4, 0xe6, 0x14, 0x58 } };
  245. #ifdef HAVE_GCC_DIAGNOSTIC_PRAGMA
  246. #pragma GCC diagnostic pop
  247. #endif
  248. UINT D3D12_Align(UINT location, UINT alignment)
  249. {
  250. return (location + (alignment - 1)) & ~(alignment - 1);
  251. }
  252. Uint32 D3D12_DXGIFormatToSDLPixelFormat(DXGI_FORMAT dxgiFormat)
  253. {
  254. switch (dxgiFormat) {
  255. case DXGI_FORMAT_B8G8R8A8_UNORM:
  256. case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
  257. return SDL_PIXELFORMAT_ARGB8888;
  258. case DXGI_FORMAT_B8G8R8X8_UNORM:
  259. case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
  260. return SDL_PIXELFORMAT_XRGB8888;
  261. case DXGI_FORMAT_R10G10B10A2_UNORM:
  262. return SDL_PIXELFORMAT_XBGR2101010;
  263. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  264. return SDL_PIXELFORMAT_RGBA64_FLOAT;
  265. default:
  266. return SDL_PIXELFORMAT_UNKNOWN;
  267. }
  268. }
  269. static DXGI_FORMAT SDLPixelFormatToDXGITextureFormat(Uint32 format, Uint32 colorspace)
  270. {
  271. switch (format) {
  272. case SDL_PIXELFORMAT_RGBA64_FLOAT:
  273. return DXGI_FORMAT_R16G16B16A16_FLOAT;
  274. case SDL_PIXELFORMAT_ARGB8888:
  275. if (colorspace == SDL_COLORSPACE_SCRGB) {
  276. return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
  277. }
  278. return DXGI_FORMAT_B8G8R8A8_UNORM;
  279. case SDL_PIXELFORMAT_XRGB8888:
  280. if (colorspace == SDL_COLORSPACE_SCRGB) {
  281. return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
  282. }
  283. return DXGI_FORMAT_B8G8R8X8_UNORM;
  284. case SDL_PIXELFORMAT_YV12:
  285. case SDL_PIXELFORMAT_IYUV:
  286. return DXGI_FORMAT_R8_UNORM;
  287. case SDL_PIXELFORMAT_NV12:
  288. case SDL_PIXELFORMAT_NV21:
  289. return DXGI_FORMAT_NV12;
  290. case SDL_PIXELFORMAT_P010:
  291. return DXGI_FORMAT_P010;
  292. case SDL_PIXELFORMAT_P016:
  293. return DXGI_FORMAT_P016;
  294. default:
  295. return DXGI_FORMAT_UNKNOWN;
  296. }
  297. }
  298. static DXGI_FORMAT SDLPixelFormatToDXGIMainResourceViewFormat(Uint32 format, Uint32 colorspace)
  299. {
  300. switch (format) {
  301. case SDL_PIXELFORMAT_RGBA64_FLOAT:
  302. return DXGI_FORMAT_R16G16B16A16_FLOAT;
  303. case SDL_PIXELFORMAT_ARGB8888:
  304. if (colorspace == SDL_COLORSPACE_SCRGB) {
  305. return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
  306. }
  307. return DXGI_FORMAT_B8G8R8A8_UNORM;
  308. case SDL_PIXELFORMAT_XRGB8888:
  309. if (colorspace == SDL_COLORSPACE_SCRGB) {
  310. return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
  311. }
  312. return DXGI_FORMAT_B8G8R8X8_UNORM;
  313. case SDL_PIXELFORMAT_YV12:
  314. case SDL_PIXELFORMAT_IYUV:
  315. case SDL_PIXELFORMAT_NV12: /* For the Y texture */
  316. case SDL_PIXELFORMAT_NV21: /* For the Y texture */
  317. return DXGI_FORMAT_R8_UNORM;
  318. case SDL_PIXELFORMAT_P010: /* For the Y texture */
  319. case SDL_PIXELFORMAT_P016: /* For the Y texture */
  320. return DXGI_FORMAT_R16_UNORM;
  321. default:
  322. return DXGI_FORMAT_UNKNOWN;
  323. }
  324. }
  325. static void D3D12_DestroyTexture(SDL_Renderer *renderer, SDL_Texture *texture);
  326. static void D3D12_ReleaseAll(SDL_Renderer *renderer)
  327. {
  328. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  329. SDL_Texture *texture = NULL;
  330. SDL_PropertiesID props = SDL_GetRendererProperties(renderer);
  331. SDL_SetProperty(props, SDL_PROP_RENDERER_D3D12_DEVICE_POINTER, NULL);
  332. SDL_SetProperty(props, SDL_PROP_RENDERER_D3D12_COMMAND_QUEUE_POINTER, NULL);
  333. /* Release all textures */
  334. for (texture = renderer->textures; texture; texture = texture->next) {
  335. D3D12_DestroyTexture(renderer, texture);
  336. }
  337. /* Release/reset everything else */
  338. if (data) {
  339. int i;
  340. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  341. SAFE_RELEASE(data->dxgiFactory);
  342. SAFE_RELEASE(data->dxgiAdapter);
  343. SAFE_RELEASE(data->swapChain);
  344. #endif
  345. SAFE_RELEASE(data->d3dDevice);
  346. SAFE_RELEASE(data->debugInterface);
  347. SAFE_RELEASE(data->commandQueue);
  348. SAFE_RELEASE(data->commandList);
  349. SAFE_RELEASE(data->rtvDescriptorHeap);
  350. SAFE_RELEASE(data->textureRTVDescriptorHeap);
  351. SAFE_RELEASE(data->srvDescriptorHeap);
  352. SAFE_RELEASE(data->samplerDescriptorHeap);
  353. SAFE_RELEASE(data->fence);
  354. for (i = 0; i < SDL_D3D12_NUM_BUFFERS; ++i) {
  355. SAFE_RELEASE(data->commandAllocators[i]);
  356. SAFE_RELEASE(data->renderTargets[i]);
  357. }
  358. if (data->pipelineStateCount > 0) {
  359. for (i = 0; i < data->pipelineStateCount; ++i) {
  360. SAFE_RELEASE(data->pipelineStates[i].pipelineState);
  361. }
  362. SDL_free(data->pipelineStates);
  363. data->pipelineStateCount = 0;
  364. }
  365. for (i = 0; i < NUM_ROOTSIGS; ++i) {
  366. SAFE_RELEASE(data->rootSignatures[i]);
  367. }
  368. for (i = 0; i < SDL_D3D12_NUM_VERTEX_BUFFERS; ++i) {
  369. SAFE_RELEASE(data->vertexBuffers[i].resource);
  370. data->vertexBuffers[i].size = 0;
  371. }
  372. data->swapEffect = (DXGI_SWAP_EFFECT)0;
  373. data->swapFlags = 0;
  374. data->currentRenderTargetView.ptr = 0;
  375. data->currentSampler.ptr = 0;
  376. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  377. /* Check for any leaks if in debug mode */
  378. if (data->dxgiDebug) {
  379. DXGI_DEBUG_RLO_FLAGS rloFlags = (DXGI_DEBUG_RLO_FLAGS)(DXGI_DEBUG_RLO_DETAIL | DXGI_DEBUG_RLO_IGNORE_INTERNAL);
  380. D3D_CALL(data->dxgiDebug, ReportLiveObjects, SDL_DXGI_DEBUG_ALL, rloFlags);
  381. SAFE_RELEASE(data->dxgiDebug);
  382. }
  383. #endif
  384. /* Unload the D3D libraries. This should be done last, in order
  385. * to prevent IUnknown::Release() calls from crashing.
  386. */
  387. if (data->hD3D12Mod) {
  388. SDL_UnloadObject(data->hD3D12Mod);
  389. data->hD3D12Mod = NULL;
  390. }
  391. if (data->hDXGIMod) {
  392. SDL_UnloadObject(data->hDXGIMod);
  393. data->hDXGIMod = NULL;
  394. }
  395. }
  396. }
  397. static D3D12_GPU_DESCRIPTOR_HANDLE D3D12_CPUtoGPUHandle(ID3D12DescriptorHeap *heap, D3D12_CPU_DESCRIPTOR_HANDLE CPUHandle)
  398. {
  399. D3D12_CPU_DESCRIPTOR_HANDLE CPUHeapStart;
  400. D3D12_GPU_DESCRIPTOR_HANDLE GPUHandle;
  401. SIZE_T offset;
  402. /* Calculate the correct offset into the heap */
  403. D3D_CALL_RET(heap, GetCPUDescriptorHandleForHeapStart, &CPUHeapStart);
  404. offset = CPUHandle.ptr - CPUHeapStart.ptr;
  405. D3D_CALL_RET(heap, GetGPUDescriptorHandleForHeapStart, &GPUHandle);
  406. GPUHandle.ptr += offset;
  407. return GPUHandle;
  408. }
  409. static void D3D12_WaitForGPU(D3D12_RenderData *data)
  410. {
  411. if (data->commandQueue && data->fence && data->fenceEvent) {
  412. D3D_CALL(data->commandQueue, Signal, data->fence, data->fenceValue);
  413. if (D3D_CALL(data->fence, GetCompletedValue) < data->fenceValue) {
  414. D3D_CALL(data->fence, SetEventOnCompletion,
  415. data->fenceValue,
  416. data->fenceEvent);
  417. WaitForSingleObjectEx(data->fenceEvent, INFINITE, FALSE);
  418. }
  419. data->fenceValue++;
  420. }
  421. }
  422. static D3D12_CPU_DESCRIPTOR_HANDLE D3D12_GetCurrentRenderTargetView(SDL_Renderer *renderer)
  423. {
  424. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  425. D3D12_CPU_DESCRIPTOR_HANDLE rtvDescriptor;
  426. if (data->textureRenderTarget) {
  427. return data->textureRenderTarget->mainTextureRenderTargetView;
  428. }
  429. SDL_zero(rtvDescriptor);
  430. D3D_CALL_RET(data->rtvDescriptorHeap, GetCPUDescriptorHandleForHeapStart, &rtvDescriptor);
  431. rtvDescriptor.ptr += data->currentBackBufferIndex * data->rtvDescriptorSize;
  432. return rtvDescriptor;
  433. }
  434. static void D3D12_TransitionResource(D3D12_RenderData *data,
  435. ID3D12Resource *resource,
  436. D3D12_RESOURCE_STATES beforeState,
  437. D3D12_RESOURCE_STATES afterState)
  438. {
  439. D3D12_RESOURCE_BARRIER barrier;
  440. if (beforeState != afterState) {
  441. SDL_zero(barrier);
  442. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  443. barrier.Transition.pResource = resource;
  444. barrier.Transition.StateBefore = beforeState;
  445. barrier.Transition.StateAfter = afterState;
  446. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  447. D3D_CALL(data->commandList, ResourceBarrier, 1, &barrier);
  448. }
  449. }
  450. static void D3D12_ResetCommandList(D3D12_RenderData *data)
  451. {
  452. int i;
  453. ID3D12DescriptorHeap *rootDescriptorHeaps[] = { data->srvDescriptorHeap, data->samplerDescriptorHeap };
  454. ID3D12CommandAllocator *commandAllocator = data->commandAllocators[data->currentBackBufferIndex];
  455. D3D_CALL(commandAllocator, Reset);
  456. D3D_CALL(data->commandList, Reset, commandAllocator, NULL);
  457. data->currentPipelineState = NULL;
  458. data->currentVertexBuffer = 0;
  459. data->issueBatch = SDL_FALSE;
  460. data->cliprectDirty = SDL_TRUE;
  461. data->viewportDirty = SDL_TRUE;
  462. data->currentRenderTargetView.ptr = 0;
  463. /* FIXME should we also clear currentSampler.ptr and currentRenderTargetView.ptr ? (and use D3D12_InvalidateCachedState() instead) */
  464. /* Release any upload buffers that were inflight */
  465. for (i = 0; i < data->currentUploadBuffer; ++i) {
  466. SAFE_RELEASE(data->uploadBuffers[i]);
  467. }
  468. data->currentUploadBuffer = 0;
  469. D3D_CALL(data->commandList, SetDescriptorHeaps, 2, rootDescriptorHeaps);
  470. }
  471. static int D3D12_IssueBatch(D3D12_RenderData *data)
  472. {
  473. HRESULT result = S_OK;
  474. /* Issue the command list */
  475. result = D3D_CALL(data->commandList, Close);
  476. if (FAILED(result)) {
  477. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("D3D12_IssueBatch"), result);
  478. return result;
  479. }
  480. D3D_CALL(data->commandQueue, ExecuteCommandLists, 1, (ID3D12CommandList *const *)&data->commandList);
  481. D3D12_WaitForGPU(data);
  482. D3D12_ResetCommandList(data);
  483. return result;
  484. }
  485. static void D3D12_DestroyRenderer(SDL_Renderer *renderer)
  486. {
  487. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  488. D3D12_WaitForGPU(data);
  489. D3D12_ReleaseAll(renderer);
  490. if (data) {
  491. SDL_free(data);
  492. }
  493. SDL_free(renderer);
  494. }
  495. static D3D12_BLEND GetBlendFunc(SDL_BlendFactor factor)
  496. {
  497. switch (factor) {
  498. case SDL_BLENDFACTOR_ZERO:
  499. return D3D12_BLEND_ZERO;
  500. case SDL_BLENDFACTOR_ONE:
  501. return D3D12_BLEND_ONE;
  502. case SDL_BLENDFACTOR_SRC_COLOR:
  503. return D3D12_BLEND_SRC_COLOR;
  504. case SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR:
  505. return D3D12_BLEND_INV_SRC_COLOR;
  506. case SDL_BLENDFACTOR_SRC_ALPHA:
  507. return D3D12_BLEND_SRC_ALPHA;
  508. case SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA:
  509. return D3D12_BLEND_INV_SRC_ALPHA;
  510. case SDL_BLENDFACTOR_DST_COLOR:
  511. return D3D12_BLEND_DEST_COLOR;
  512. case SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR:
  513. return D3D12_BLEND_INV_DEST_COLOR;
  514. case SDL_BLENDFACTOR_DST_ALPHA:
  515. return D3D12_BLEND_DEST_ALPHA;
  516. case SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA:
  517. return D3D12_BLEND_INV_DEST_ALPHA;
  518. default:
  519. return (D3D12_BLEND)0;
  520. }
  521. }
  522. static D3D12_BLEND_OP GetBlendEquation(SDL_BlendOperation operation)
  523. {
  524. switch (operation) {
  525. case SDL_BLENDOPERATION_ADD:
  526. return D3D12_BLEND_OP_ADD;
  527. case SDL_BLENDOPERATION_SUBTRACT:
  528. return D3D12_BLEND_OP_SUBTRACT;
  529. case SDL_BLENDOPERATION_REV_SUBTRACT:
  530. return D3D12_BLEND_OP_REV_SUBTRACT;
  531. case SDL_BLENDOPERATION_MINIMUM:
  532. return D3D12_BLEND_OP_MIN;
  533. case SDL_BLENDOPERATION_MAXIMUM:
  534. return D3D12_BLEND_OP_MAX;
  535. default:
  536. return (D3D12_BLEND_OP)0;
  537. }
  538. }
  539. static void D3D12_CreateBlendState(SDL_Renderer *renderer, SDL_BlendMode blendMode, D3D12_BLEND_DESC *outBlendDesc)
  540. {
  541. SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode);
  542. SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode);
  543. SDL_BlendOperation colorOperation = SDL_GetBlendModeColorOperation(blendMode);
  544. SDL_BlendFactor dstColorFactor = SDL_GetBlendModeDstColorFactor(blendMode);
  545. SDL_BlendFactor dstAlphaFactor = SDL_GetBlendModeDstAlphaFactor(blendMode);
  546. SDL_BlendOperation alphaOperation = SDL_GetBlendModeAlphaOperation(blendMode);
  547. SDL_zerop(outBlendDesc);
  548. outBlendDesc->AlphaToCoverageEnable = FALSE;
  549. outBlendDesc->IndependentBlendEnable = FALSE;
  550. outBlendDesc->RenderTarget[0].BlendEnable = TRUE;
  551. outBlendDesc->RenderTarget[0].SrcBlend = GetBlendFunc(srcColorFactor);
  552. outBlendDesc->RenderTarget[0].DestBlend = GetBlendFunc(dstColorFactor);
  553. outBlendDesc->RenderTarget[0].BlendOp = GetBlendEquation(colorOperation);
  554. outBlendDesc->RenderTarget[0].SrcBlendAlpha = GetBlendFunc(srcAlphaFactor);
  555. outBlendDesc->RenderTarget[0].DestBlendAlpha = GetBlendFunc(dstAlphaFactor);
  556. outBlendDesc->RenderTarget[0].BlendOpAlpha = GetBlendEquation(alphaOperation);
  557. outBlendDesc->RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  558. }
  559. static D3D12_PipelineState *D3D12_CreatePipelineState(SDL_Renderer *renderer,
  560. D3D12_Shader shader,
  561. SDL_BlendMode blendMode,
  562. D3D12_PRIMITIVE_TOPOLOGY_TYPE topology,
  563. DXGI_FORMAT rtvFormat)
  564. {
  565. const D3D12_INPUT_ELEMENT_DESC vertexDesc[] = {
  566. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  567. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  568. { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  569. };
  570. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  571. D3D12_GRAPHICS_PIPELINE_STATE_DESC pipelineDesc;
  572. ID3D12PipelineState *pipelineState = NULL;
  573. D3D12_PipelineState *pipelineStates;
  574. HRESULT result = S_OK;
  575. SDL_zero(pipelineDesc);
  576. pipelineDesc.pRootSignature = data->rootSignatures[D3D12_GetRootSignatureType(shader)];
  577. D3D12_GetVertexShader(shader, &pipelineDesc.VS);
  578. D3D12_GetPixelShader(shader, &pipelineDesc.PS);
  579. D3D12_CreateBlendState(renderer, blendMode, &pipelineDesc.BlendState);
  580. pipelineDesc.SampleMask = 0xffffffff;
  581. pipelineDesc.RasterizerState.AntialiasedLineEnable = FALSE;
  582. pipelineDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
  583. pipelineDesc.RasterizerState.DepthBias = 0;
  584. pipelineDesc.RasterizerState.DepthBiasClamp = 0.0f;
  585. pipelineDesc.RasterizerState.DepthClipEnable = TRUE;
  586. pipelineDesc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
  587. pipelineDesc.RasterizerState.FrontCounterClockwise = FALSE;
  588. pipelineDesc.RasterizerState.MultisampleEnable = FALSE;
  589. pipelineDesc.RasterizerState.SlopeScaledDepthBias = 0.0f;
  590. pipelineDesc.InputLayout.pInputElementDescs = vertexDesc;
  591. pipelineDesc.InputLayout.NumElements = 3;
  592. pipelineDesc.PrimitiveTopologyType = topology;
  593. pipelineDesc.NumRenderTargets = 1;
  594. pipelineDesc.RTVFormats[0] = rtvFormat;
  595. pipelineDesc.SampleDesc.Count = 1;
  596. pipelineDesc.SampleDesc.Quality = 0;
  597. result = D3D_CALL(data->d3dDevice, CreateGraphicsPipelineState,
  598. &pipelineDesc,
  599. D3D_GUID(SDL_IID_ID3D12PipelineState),
  600. (void **)&pipelineState);
  601. if (FAILED(result)) {
  602. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateGraphicsPipelineState"), result);
  603. return NULL;
  604. }
  605. pipelineStates = (D3D12_PipelineState *)SDL_realloc(data->pipelineStates, (data->pipelineStateCount + 1) * sizeof(*pipelineStates));
  606. if (!pipelineStates) {
  607. SAFE_RELEASE(pipelineState);
  608. return NULL;
  609. }
  610. pipelineStates[data->pipelineStateCount].shader = shader;
  611. pipelineStates[data->pipelineStateCount].blendMode = blendMode;
  612. pipelineStates[data->pipelineStateCount].topology = topology;
  613. pipelineStates[data->pipelineStateCount].rtvFormat = rtvFormat;
  614. pipelineStates[data->pipelineStateCount].pipelineState = pipelineState;
  615. data->pipelineStates = pipelineStates;
  616. ++data->pipelineStateCount;
  617. return &pipelineStates[data->pipelineStateCount - 1];
  618. }
  619. static HRESULT D3D12_CreateVertexBuffer(D3D12_RenderData *data, size_t vbidx, size_t size)
  620. {
  621. D3D12_HEAP_PROPERTIES vbufferHeapProps;
  622. D3D12_RESOURCE_DESC vbufferDesc;
  623. HRESULT result;
  624. SAFE_RELEASE(data->vertexBuffers[vbidx].resource);
  625. SDL_zero(vbufferHeapProps);
  626. vbufferHeapProps.Type = D3D12_HEAP_TYPE_UPLOAD;
  627. vbufferHeapProps.CreationNodeMask = 1;
  628. vbufferHeapProps.VisibleNodeMask = 1;
  629. SDL_zero(vbufferDesc);
  630. vbufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  631. vbufferDesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
  632. vbufferDesc.Width = size;
  633. vbufferDesc.Height = 1;
  634. vbufferDesc.DepthOrArraySize = 1;
  635. vbufferDesc.MipLevels = 1;
  636. vbufferDesc.Format = DXGI_FORMAT_UNKNOWN;
  637. vbufferDesc.SampleDesc.Count = 1;
  638. vbufferDesc.SampleDesc.Quality = 0;
  639. vbufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  640. vbufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
  641. result = D3D_CALL(data->d3dDevice, CreateCommittedResource,
  642. &vbufferHeapProps,
  643. D3D12_HEAP_FLAG_NONE,
  644. &vbufferDesc,
  645. D3D12_RESOURCE_STATE_GENERIC_READ,
  646. NULL,
  647. D3D_GUID(SDL_IID_ID3D12Resource),
  648. (void **)&data->vertexBuffers[vbidx].resource);
  649. if (FAILED(result)) {
  650. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreatePlacedResource [vertex buffer]"), result);
  651. return result;
  652. }
  653. data->vertexBuffers[vbidx].view.BufferLocation = D3D_CALL(data->vertexBuffers[vbidx].resource, GetGPUVirtualAddress);
  654. data->vertexBuffers[vbidx].view.StrideInBytes = sizeof(VertexPositionColor);
  655. data->vertexBuffers[vbidx].size = size;
  656. return result;
  657. }
  658. /* Create resources that depend on the device. */
  659. static HRESULT D3D12_CreateDeviceResources(SDL_Renderer *renderer)
  660. {
  661. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  662. typedef HRESULT(WINAPI * PFN_CREATE_DXGI_FACTORY)(UINT flags, REFIID riid, void **ppFactory);
  663. PFN_CREATE_DXGI_FACTORY CreateDXGIFactoryFunc;
  664. PFN_D3D12_CREATE_DEVICE D3D12CreateDeviceFunc;
  665. #endif
  666. typedef HANDLE(WINAPI * PFN_CREATE_EVENT_EX)(LPSECURITY_ATTRIBUTES lpEventAttributes, LPCWSTR lpName, DWORD dwFlags, DWORD dwDesiredAccess);
  667. PFN_CREATE_EVENT_EX CreateEventExFunc;
  668. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  669. ID3D12Device *d3dDevice = NULL;
  670. HRESULT result = S_OK;
  671. UINT creationFlags = 0;
  672. int i;
  673. SDL_bool createDebug;
  674. D3D12_COMMAND_QUEUE_DESC queueDesc;
  675. D3D12_DESCRIPTOR_HEAP_DESC descriptorHeapDesc;
  676. D3D12_SAMPLER_DESC samplerDesc;
  677. ID3D12DescriptorHeap *rootDescriptorHeaps[2];
  678. /* See if we need debug interfaces */
  679. createDebug = SDL_GetHintBoolean(SDL_HINT_RENDER_DIRECT3D11_DEBUG, SDL_FALSE);
  680. #ifdef SDL_PLATFORM_GDK
  681. CreateEventExFunc = CreateEventExW;
  682. #else
  683. /* CreateEventEx() arrived in Vista, so we need to load it with GetProcAddress for XP. */
  684. {
  685. HMODULE kernel32 = GetModuleHandle(TEXT("kernel32.dll"));
  686. CreateEventExFunc = NULL;
  687. if (kernel32) {
  688. CreateEventExFunc = (PFN_CREATE_EVENT_EX)GetProcAddress(kernel32, "CreateEventExW");
  689. }
  690. }
  691. #endif
  692. if (!CreateEventExFunc) {
  693. result = E_FAIL;
  694. goto done;
  695. }
  696. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  697. data->hDXGIMod = SDL_LoadObject("dxgi.dll");
  698. if (!data->hDXGIMod) {
  699. result = E_FAIL;
  700. goto done;
  701. }
  702. CreateDXGIFactoryFunc = (PFN_CREATE_DXGI_FACTORY)SDL_LoadFunction(data->hDXGIMod, "CreateDXGIFactory2");
  703. if (!CreateDXGIFactoryFunc) {
  704. result = E_FAIL;
  705. goto done;
  706. }
  707. data->hD3D12Mod = SDL_LoadObject("D3D12.dll");
  708. if (!data->hD3D12Mod) {
  709. result = E_FAIL;
  710. goto done;
  711. }
  712. D3D12CreateDeviceFunc = (PFN_D3D12_CREATE_DEVICE)SDL_LoadFunction(data->hD3D12Mod, "D3D12CreateDevice");
  713. if (!D3D12CreateDeviceFunc) {
  714. result = E_FAIL;
  715. goto done;
  716. }
  717. if (createDebug) {
  718. PFN_D3D12_GET_DEBUG_INTERFACE D3D12GetDebugInterfaceFunc;
  719. D3D12GetDebugInterfaceFunc = (PFN_D3D12_GET_DEBUG_INTERFACE)SDL_LoadFunction(data->hD3D12Mod, "D3D12GetDebugInterface");
  720. if (!D3D12GetDebugInterfaceFunc) {
  721. result = E_FAIL;
  722. goto done;
  723. }
  724. if (SUCCEEDED(D3D12GetDebugInterfaceFunc(D3D_GUID(SDL_IID_ID3D12Debug), (void **)&data->debugInterface))) {
  725. D3D_CALL(data->debugInterface, EnableDebugLayer);
  726. }
  727. }
  728. #endif /*!defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)*/
  729. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  730. result = D3D12_XBOX_CreateDevice(&d3dDevice, createDebug);
  731. if (FAILED(result)) {
  732. /* SDL Error is set by D3D12_XBOX_CreateDevice */
  733. goto done;
  734. }
  735. #else
  736. if (createDebug) {
  737. #ifdef __IDXGIInfoQueue_INTERFACE_DEFINED__
  738. IDXGIInfoQueue *dxgiInfoQueue = NULL;
  739. PFN_CREATE_DXGI_FACTORY DXGIGetDebugInterfaceFunc;
  740. /* If the debug hint is set, also create the DXGI factory in debug mode */
  741. DXGIGetDebugInterfaceFunc = (PFN_CREATE_DXGI_FACTORY)SDL_LoadFunction(data->hDXGIMod, "DXGIGetDebugInterface1");
  742. if (!DXGIGetDebugInterfaceFunc) {
  743. result = E_FAIL;
  744. goto done;
  745. }
  746. result = DXGIGetDebugInterfaceFunc(0, D3D_GUID(SDL_IID_IDXGIDebug1), (void **)&data->dxgiDebug);
  747. if (FAILED(result)) {
  748. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("DXGIGetDebugInterface1"), result);
  749. goto done;
  750. }
  751. result = DXGIGetDebugInterfaceFunc(0, D3D_GUID(SDL_IID_IDXGIInfoQueue), (void **)&dxgiInfoQueue);
  752. if (FAILED(result)) {
  753. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("DXGIGetDebugInterface1"), result);
  754. goto done;
  755. }
  756. D3D_CALL(dxgiInfoQueue, SetBreakOnSeverity, SDL_DXGI_DEBUG_ALL, DXGI_INFO_QUEUE_MESSAGE_SEVERITY_ERROR, TRUE);
  757. D3D_CALL(dxgiInfoQueue, SetBreakOnSeverity, SDL_DXGI_DEBUG_ALL, DXGI_INFO_QUEUE_MESSAGE_SEVERITY_CORRUPTION, TRUE);
  758. SAFE_RELEASE(dxgiInfoQueue);
  759. #endif /* __IDXGIInfoQueue_INTERFACE_DEFINED__ */
  760. creationFlags = DXGI_CREATE_FACTORY_DEBUG;
  761. }
  762. result = CreateDXGIFactoryFunc(creationFlags, D3D_GUID(SDL_IID_IDXGIFactory6), (void **)&data->dxgiFactory);
  763. if (FAILED(result)) {
  764. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("CreateDXGIFactory"), result);
  765. goto done;
  766. }
  767. /* Prefer a high performance adapter if there are multiple choices */
  768. result = D3D_CALL(data->dxgiFactory, EnumAdapterByGpuPreference,
  769. 0,
  770. DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
  771. D3D_GUID(SDL_IID_IDXGIAdapter4),
  772. (void **)&data->dxgiAdapter);
  773. if (FAILED(result)) {
  774. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("D3D12CreateDevice"), result);
  775. goto done;
  776. }
  777. result = D3D12CreateDeviceFunc((IUnknown *)data->dxgiAdapter,
  778. D3D_FEATURE_LEVEL_11_0, /* Request minimum feature level 11.0 for maximum compatibility */
  779. D3D_GUID(SDL_IID_ID3D12Device1),
  780. (void **)&d3dDevice);
  781. if (FAILED(result)) {
  782. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("D3D12CreateDevice"), result);
  783. goto done;
  784. }
  785. /* Setup the info queue if in debug mode */
  786. if (createDebug) {
  787. ID3D12InfoQueue *infoQueue = NULL;
  788. D3D12_MESSAGE_SEVERITY severities[] = { D3D12_MESSAGE_SEVERITY_INFO };
  789. D3D12_INFO_QUEUE_FILTER filter;
  790. result = D3D_CALL(d3dDevice, QueryInterface, D3D_GUID(SDL_IID_ID3D12InfoQueue), (void **)&infoQueue);
  791. if (FAILED(result)) {
  792. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device to ID3D12InfoQueue"), result);
  793. goto done;
  794. }
  795. SDL_zero(filter);
  796. filter.DenyList.NumSeverities = 1;
  797. filter.DenyList.pSeverityList = severities;
  798. D3D_CALL(infoQueue, PushStorageFilter, &filter);
  799. D3D_CALL(infoQueue, SetBreakOnSeverity, D3D12_MESSAGE_SEVERITY_ERROR, TRUE);
  800. D3D_CALL(infoQueue, SetBreakOnSeverity, D3D12_MESSAGE_SEVERITY_CORRUPTION, TRUE);
  801. SAFE_RELEASE(infoQueue);
  802. }
  803. #endif /*!defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)*/
  804. result = D3D_CALL(d3dDevice, QueryInterface, D3D_GUID(SDL_IID_ID3D12Device1), (void **)&data->d3dDevice);
  805. if (FAILED(result)) {
  806. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device to ID3D12Device1"), result);
  807. goto done;
  808. }
  809. /* Create a command queue */
  810. SDL_zero(queueDesc);
  811. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  812. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  813. result = D3D_CALL(data->d3dDevice, CreateCommandQueue,
  814. &queueDesc,
  815. D3D_GUID(SDL_IID_ID3D12CommandQueue),
  816. (void **)&data->commandQueue);
  817. if (FAILED(result)) {
  818. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateCommandQueue"), result);
  819. goto done;
  820. }
  821. /* Create the descriptor heaps for the render target view, texture SRVs, and samplers */
  822. SDL_zero(descriptorHeapDesc);
  823. descriptorHeapDesc.NumDescriptors = SDL_D3D12_NUM_BUFFERS;
  824. descriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  825. result = D3D_CALL(data->d3dDevice, CreateDescriptorHeap,
  826. &descriptorHeapDesc,
  827. D3D_GUID(SDL_IID_ID3D12DescriptorHeap),
  828. (void **)&data->rtvDescriptorHeap);
  829. if (FAILED(result)) {
  830. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateDescriptorHeap [rtv]"), result);
  831. goto done;
  832. }
  833. data->rtvDescriptorSize = D3D_CALL(d3dDevice, GetDescriptorHandleIncrementSize, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  834. descriptorHeapDesc.NumDescriptors = SDL_D3D12_MAX_NUM_TEXTURES;
  835. result = D3D_CALL(data->d3dDevice, CreateDescriptorHeap,
  836. &descriptorHeapDesc,
  837. D3D_GUID(SDL_IID_ID3D12DescriptorHeap),
  838. (void **)&data->textureRTVDescriptorHeap);
  839. if (FAILED(result)) {
  840. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateDescriptorHeap [texture rtv]"), result);
  841. goto done;
  842. }
  843. SDL_zero(descriptorHeapDesc);
  844. descriptorHeapDesc.NumDescriptors = SDL_D3D12_MAX_NUM_TEXTURES;
  845. descriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  846. descriptorHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  847. result = D3D_CALL(data->d3dDevice, CreateDescriptorHeap,
  848. &descriptorHeapDesc,
  849. D3D_GUID(SDL_IID_ID3D12DescriptorHeap),
  850. (void **)&data->srvDescriptorHeap);
  851. if (FAILED(result)) {
  852. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateDescriptorHeap [srv]"), result);
  853. goto done;
  854. }
  855. rootDescriptorHeaps[0] = data->srvDescriptorHeap;
  856. data->srvDescriptorSize = D3D_CALL(d3dDevice, GetDescriptorHandleIncrementSize, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  857. SDL_zero(descriptorHeapDesc);
  858. descriptorHeapDesc.NumDescriptors = 2;
  859. descriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER;
  860. descriptorHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  861. result = D3D_CALL(data->d3dDevice, CreateDescriptorHeap,
  862. &descriptorHeapDesc,
  863. D3D_GUID(SDL_IID_ID3D12DescriptorHeap),
  864. (void **)&data->samplerDescriptorHeap);
  865. if (FAILED(result)) {
  866. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateDescriptorHeap [sampler]"), result);
  867. goto done;
  868. }
  869. rootDescriptorHeaps[1] = data->samplerDescriptorHeap;
  870. data->samplerDescriptorSize = D3D_CALL(d3dDevice, GetDescriptorHandleIncrementSize, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
  871. /* Create a command allocator for each back buffer */
  872. for (i = 0; i < SDL_D3D12_NUM_BUFFERS; ++i) {
  873. result = D3D_CALL(data->d3dDevice, CreateCommandAllocator,
  874. D3D12_COMMAND_LIST_TYPE_DIRECT,
  875. D3D_GUID(SDL_IID_ID3D12CommandAllocator),
  876. (void **)&data->commandAllocators[i]);
  877. if (FAILED(result)) {
  878. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateCommandAllocator"), result);
  879. goto done;
  880. }
  881. }
  882. /* Create the command list */
  883. result = D3D_CALL(data->d3dDevice, CreateCommandList,
  884. 0,
  885. D3D12_COMMAND_LIST_TYPE_DIRECT,
  886. data->commandAllocators[0],
  887. NULL,
  888. D3D_GUID(SDL_IID_ID3D12GraphicsCommandList2),
  889. (void **)&data->commandList);
  890. if (FAILED(result)) {
  891. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateCommandList"), result);
  892. goto done;
  893. }
  894. /* Set the descriptor heaps to the correct initial value */
  895. D3D_CALL(data->commandList, SetDescriptorHeaps, 2, rootDescriptorHeaps);
  896. /* Create the fence and fence event */
  897. result = D3D_CALL(data->d3dDevice, CreateFence,
  898. data->fenceValue,
  899. D3D12_FENCE_FLAG_NONE,
  900. D3D_GUID(SDL_IID_ID3D12Fence),
  901. (void **)&data->fence);
  902. if (FAILED(result)) {
  903. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateFence"), result);
  904. goto done;
  905. }
  906. data->fenceValue++;
  907. data->fenceEvent = CreateEventExFunc(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE);
  908. if (!data->fenceEvent) {
  909. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("CreateEventEx"), result);
  910. goto done;
  911. }
  912. /* Create all the root signatures */
  913. for (i = 0; i < NUM_ROOTSIGS; ++i) {
  914. D3D12_SHADER_BYTECODE rootSigData;
  915. D3D12_GetRootSignatureData((D3D12_RootSignature)i, &rootSigData);
  916. result = D3D_CALL(data->d3dDevice, CreateRootSignature,
  917. 0,
  918. rootSigData.pShaderBytecode,
  919. rootSigData.BytecodeLength,
  920. D3D_GUID(SDL_IID_ID3D12RootSignature),
  921. (void **)&data->rootSignatures[i]);
  922. if (FAILED(result)) {
  923. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateRootSignature"), result);
  924. goto done;
  925. }
  926. }
  927. #if 0 /* Actually, don't do this, it causes a huge startup time on some systems */
  928. {
  929. const SDL_BlendMode defaultBlendModes[] = {
  930. SDL_BLENDMODE_NONE,
  931. SDL_BLENDMODE_BLEND,
  932. SDL_BLENDMODE_ADD,
  933. SDL_BLENDMODE_MOD,
  934. SDL_BLENDMODE_MUL
  935. };
  936. const DXGI_FORMAT defaultRTVFormats[] = {
  937. DXGI_FORMAT_R16G16B16A16_FLOAT,
  938. DXGI_FORMAT_R10G10B10A2_UNORM,
  939. DXGI_FORMAT_B8G8R8A8_UNORM,
  940. DXGI_FORMAT_B8G8R8X8_UNORM,
  941. DXGI_FORMAT_R8_UNORM
  942. };
  943. int i, j, k, l;
  944. /* Create all the default pipeline state objects
  945. (will add everything except custom blend states) */
  946. for (i = 0; i < NUM_SHADERS; ++i) {
  947. for (j = 0; j < SDL_arraysize(defaultBlendModes); ++j) {
  948. for (k = D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT; k < D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH; ++k) {
  949. for (l = 0; l < SDL_arraysize(defaultRTVFormats); ++l) {
  950. if (!D3D12_CreatePipelineState(renderer, (D3D12_Shader)i, defaultBlendModes[j], (D3D12_PRIMITIVE_TOPOLOGY_TYPE)k, defaultRTVFormats[l])) {
  951. /* D3D12_CreatePipelineState will set the SDL error, if it fails */
  952. goto done;
  953. }
  954. }
  955. }
  956. }
  957. }
  958. }
  959. #endif /* 0 */
  960. /* Create default vertex buffers */
  961. for (i = 0; i < SDL_D3D12_NUM_VERTEX_BUFFERS; ++i) {
  962. D3D12_CreateVertexBuffer(data, i, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT);
  963. }
  964. /* Create samplers to use when drawing textures: */
  965. SDL_zero(samplerDesc);
  966. samplerDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
  967. samplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  968. samplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  969. samplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  970. samplerDesc.MipLODBias = 0.0f;
  971. samplerDesc.MaxAnisotropy = 1;
  972. samplerDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  973. samplerDesc.MinLOD = 0.0f;
  974. samplerDesc.MaxLOD = D3D12_FLOAT32_MAX;
  975. D3D_CALL_RET(data->samplerDescriptorHeap, GetCPUDescriptorHandleForHeapStart, &data->nearestPixelSampler);
  976. D3D_CALL(data->d3dDevice, CreateSampler, &samplerDesc, data->nearestPixelSampler);
  977. samplerDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  978. data->linearSampler.ptr = data->nearestPixelSampler.ptr + data->samplerDescriptorSize;
  979. D3D_CALL(data->d3dDevice, CreateSampler, &samplerDesc, data->linearSampler);
  980. /* Initialize the pool allocator for SRVs */
  981. for (i = 0; i < SDL_D3D12_MAX_NUM_TEXTURES; ++i) {
  982. data->srvPoolNodes[i].index = (SIZE_T)i;
  983. if (i != SDL_D3D12_MAX_NUM_TEXTURES - 1) {
  984. data->srvPoolNodes[i].next = &data->srvPoolNodes[i + 1];
  985. }
  986. }
  987. data->srvPoolHead = &data->srvPoolNodes[0];
  988. SDL_PropertiesID props = SDL_GetRendererProperties(renderer);
  989. SDL_SetProperty(props, SDL_PROP_RENDERER_D3D12_DEVICE_POINTER, data->d3dDevice);
  990. SDL_SetProperty(props, SDL_PROP_RENDERER_D3D12_COMMAND_QUEUE_POINTER, data->commandQueue);
  991. done:
  992. SAFE_RELEASE(d3dDevice);
  993. return result;
  994. }
  995. static DXGI_MODE_ROTATION D3D12_GetCurrentRotation()
  996. {
  997. /* FIXME */
  998. return DXGI_MODE_ROTATION_IDENTITY;
  999. }
  1000. static BOOL D3D12_IsDisplayRotated90Degrees(DXGI_MODE_ROTATION rotation)
  1001. {
  1002. switch (rotation) {
  1003. case DXGI_MODE_ROTATION_ROTATE90:
  1004. case DXGI_MODE_ROTATION_ROTATE270:
  1005. return TRUE;
  1006. default:
  1007. return FALSE;
  1008. }
  1009. }
  1010. static int D3D12_GetRotationForCurrentRenderTarget(SDL_Renderer *renderer)
  1011. {
  1012. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  1013. if (data->textureRenderTarget) {
  1014. return DXGI_MODE_ROTATION_IDENTITY;
  1015. } else {
  1016. return data->rotation;
  1017. }
  1018. }
  1019. static int D3D12_GetViewportAlignedD3DRect(SDL_Renderer *renderer, const SDL_Rect *sdlRect, D3D12_RECT *outRect, BOOL includeViewportOffset)
  1020. {
  1021. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  1022. const int rotation = D3D12_GetRotationForCurrentRenderTarget(renderer);
  1023. const SDL_Rect *viewport = &data->currentViewport;
  1024. switch (rotation) {
  1025. case DXGI_MODE_ROTATION_IDENTITY:
  1026. outRect->left = sdlRect->x;
  1027. outRect->right = (LONG)sdlRect->x + sdlRect->w;
  1028. outRect->top = sdlRect->y;
  1029. outRect->bottom = (LONG)sdlRect->y + sdlRect->h;
  1030. if (includeViewportOffset) {
  1031. outRect->left += viewport->x;
  1032. outRect->right += viewport->x;
  1033. outRect->top += viewport->y;
  1034. outRect->bottom += viewport->y;
  1035. }
  1036. break;
  1037. case DXGI_MODE_ROTATION_ROTATE270:
  1038. outRect->left = sdlRect->y;
  1039. outRect->right = (LONG)sdlRect->y + sdlRect->h;
  1040. outRect->top = viewport->w - sdlRect->x - sdlRect->w;
  1041. outRect->bottom = viewport->w - sdlRect->x;
  1042. break;
  1043. case DXGI_MODE_ROTATION_ROTATE180:
  1044. outRect->left = viewport->w - sdlRect->x - sdlRect->w;
  1045. outRect->right = viewport->w - sdlRect->x;
  1046. outRect->top = viewport->h - sdlRect->y - sdlRect->h;
  1047. outRect->bottom = viewport->h - sdlRect->y;
  1048. break;
  1049. case DXGI_MODE_ROTATION_ROTATE90:
  1050. outRect->left = viewport->h - sdlRect->y - sdlRect->h;
  1051. outRect->right = viewport->h - sdlRect->y;
  1052. outRect->top = sdlRect->x;
  1053. outRect->bottom = (LONG)sdlRect->x + sdlRect->h;
  1054. break;
  1055. default:
  1056. return SDL_SetError("The physical display is in an unknown or unsupported rotation");
  1057. }
  1058. return 0;
  1059. }
  1060. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  1061. static HRESULT D3D12_CreateSwapChain(SDL_Renderer *renderer, int w, int h)
  1062. {
  1063. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  1064. IDXGISwapChain1 *swapChain = NULL;
  1065. HRESULT result = S_OK;
  1066. /* Create a swap chain using the same adapter as the existing Direct3D device. */
  1067. DXGI_SWAP_CHAIN_DESC1 swapChainDesc;
  1068. SDL_zero(swapChainDesc);
  1069. swapChainDesc.Width = w;
  1070. swapChainDesc.Height = h;
  1071. switch (renderer->output_colorspace) {
  1072. case SDL_COLORSPACE_SCRGB:
  1073. swapChainDesc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;
  1074. data->renderTargetFormat = DXGI_FORMAT_R16G16B16A16_FLOAT;
  1075. break;
  1076. case SDL_COLORSPACE_HDR10:
  1077. swapChainDesc.Format = DXGI_FORMAT_R10G10B10A2_UNORM;
  1078. data->renderTargetFormat = DXGI_FORMAT_R10G10B10A2_UNORM;
  1079. break;
  1080. default:
  1081. swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; /* This is the most common swap chain format. */
  1082. data->renderTargetFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
  1083. break;
  1084. }
  1085. swapChainDesc.Stereo = FALSE;
  1086. swapChainDesc.SampleDesc.Count = 1; /* Don't use multi-sampling. */
  1087. swapChainDesc.SampleDesc.Quality = 0;
  1088. swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  1089. swapChainDesc.BufferCount = 2; /* Use double-buffering to minimize latency. */
  1090. if (WIN_IsWindows8OrGreater()) {
  1091. swapChainDesc.Scaling = DXGI_SCALING_NONE;
  1092. } else {
  1093. swapChainDesc.Scaling = DXGI_SCALING_STRETCH;
  1094. }
  1095. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; /* All Windows Store apps must use this SwapEffect. */
  1096. swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT | /* To support SetMaximumFrameLatency */
  1097. DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING; /* To support presenting with allow tearing on */
  1098. HWND hwnd = (HWND)SDL_GetProperty(SDL_GetWindowProperties(renderer->window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL);
  1099. result = D3D_CALL(data->dxgiFactory, CreateSwapChainForHwnd,
  1100. (IUnknown *)data->commandQueue,
  1101. hwnd,
  1102. &swapChainDesc,
  1103. NULL,
  1104. NULL, /* Allow on all displays. */
  1105. &swapChain);
  1106. if (FAILED(result)) {
  1107. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("IDXGIFactory2::CreateSwapChainForHwnd"), result);
  1108. goto done;
  1109. }
  1110. D3D_CALL(data->dxgiFactory, MakeWindowAssociation, hwnd, DXGI_MWA_NO_WINDOW_CHANGES);
  1111. result = D3D_CALL(swapChain, QueryInterface, D3D_GUID(SDL_IID_IDXGISwapChain4), (void **)&data->swapChain);
  1112. if (FAILED(result)) {
  1113. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("IDXGISwapChain1::QueryInterface"), result);
  1114. goto done;
  1115. }
  1116. /* Ensure that the swapchain does not queue more than one frame at a time. This both reduces latency
  1117. * and ensures that the application will only render after each VSync, minimizing power consumption.
  1118. */
  1119. result = D3D_CALL(data->swapChain, SetMaximumFrameLatency, 1);
  1120. if (FAILED(result)) {
  1121. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("IDXGISwapChain4::SetMaximumFrameLatency"), result);
  1122. goto done;
  1123. }
  1124. data->swapEffect = swapChainDesc.SwapEffect;
  1125. data->swapFlags = swapChainDesc.Flags;
  1126. UINT colorspace_support = 0;
  1127. DXGI_COLOR_SPACE_TYPE colorspace;
  1128. switch (renderer->output_colorspace) {
  1129. case SDL_COLORSPACE_SCRGB:
  1130. colorspace = DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709;
  1131. break;
  1132. case SDL_COLORSPACE_HDR10:
  1133. colorspace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
  1134. break;
  1135. default:
  1136. /* sRGB */
  1137. colorspace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
  1138. break;
  1139. }
  1140. if (SUCCEEDED(D3D_CALL(data->swapChain, CheckColorSpaceSupport, colorspace, &colorspace_support)) &&
  1141. (colorspace_support & DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT)) {
  1142. result = D3D_CALL(data->swapChain, SetColorSpace1, colorspace);
  1143. if (FAILED(result)) {
  1144. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("IDXGISwapChain3::SetColorSpace1"), result);
  1145. goto done;
  1146. }
  1147. } else {
  1148. /* Not the default, we're not going to be able to present in this colorspace */
  1149. SDL_SetError("Unsupported output colorspace");
  1150. result = DXGI_ERROR_UNSUPPORTED;
  1151. }
  1152. done:
  1153. SAFE_RELEASE(swapChain);
  1154. return result;
  1155. }
  1156. #endif
  1157. static HRESULT D3D12_UpdateForWindowSizeChange(SDL_Renderer *renderer);
  1158. HRESULT
  1159. D3D12_HandleDeviceLost(SDL_Renderer *renderer)
  1160. {
  1161. HRESULT result = S_OK;
  1162. D3D12_ReleaseAll(renderer);
  1163. result = D3D12_CreateDeviceResources(renderer);
  1164. if (FAILED(result)) {
  1165. /* D3D12_CreateDeviceResources will set the SDL error */
  1166. return result;
  1167. }
  1168. result = D3D12_UpdateForWindowSizeChange(renderer);
  1169. if (FAILED(result)) {
  1170. /* D3D12_UpdateForWindowSizeChange will set the SDL error */
  1171. return result;
  1172. }
  1173. /* Let the application know that the device has been reset */
  1174. {
  1175. SDL_Event event;
  1176. event.type = SDL_EVENT_RENDER_DEVICE_RESET;
  1177. event.common.timestamp = 0;
  1178. SDL_PushEvent(&event);
  1179. }
  1180. return S_OK;
  1181. }
  1182. /* Initialize all resources that change when the window's size changes. */
  1183. static HRESULT D3D12_CreateWindowSizeDependentResources(SDL_Renderer *renderer)
  1184. {
  1185. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  1186. HRESULT result = S_OK;
  1187. int i, w, h;
  1188. D3D12_RENDER_TARGET_VIEW_DESC rtvDesc;
  1189. D3D12_CPU_DESCRIPTOR_HANDLE rtvDescriptor;
  1190. /* Release resources in the current command list */
  1191. D3D12_IssueBatch(data);
  1192. D3D_CALL(data->commandList, OMSetRenderTargets, 0, NULL, FALSE, NULL);
  1193. /* Release render targets */
  1194. for (i = 0; i < SDL_D3D12_NUM_BUFFERS; ++i) {
  1195. SAFE_RELEASE(data->renderTargets[i]);
  1196. }
  1197. /* The width and height of the swap chain must be based on the display's
  1198. * non-rotated size.
  1199. */
  1200. SDL_GetWindowSizeInPixels(renderer->window, &w, &h);
  1201. data->rotation = D3D12_GetCurrentRotation();
  1202. if (D3D12_IsDisplayRotated90Degrees(data->rotation)) {
  1203. int tmp = w;
  1204. w = h;
  1205. h = tmp;
  1206. }
  1207. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  1208. if (data->swapChain) {
  1209. /* If the swap chain already exists, resize it. */
  1210. result = D3D_CALL(data->swapChain, ResizeBuffers,
  1211. 0,
  1212. w, h,
  1213. DXGI_FORMAT_UNKNOWN,
  1214. data->swapFlags);
  1215. if (result == DXGI_ERROR_DEVICE_REMOVED) {
  1216. /* If the device was removed for any reason, a new device and swap chain will need to be created. */
  1217. D3D12_HandleDeviceLost(renderer);
  1218. /* Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method
  1219. * and correctly set up the new device.
  1220. */
  1221. goto done;
  1222. } else if (FAILED(result)) {
  1223. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("IDXGISwapChain::ResizeBuffers"), result);
  1224. goto done;
  1225. }
  1226. } else {
  1227. result = D3D12_CreateSwapChain(renderer, w, h);
  1228. if (FAILED(result) || !data->swapChain) {
  1229. goto done;
  1230. }
  1231. }
  1232. /* Set the proper rotation for the swap chain. */
  1233. if (WIN_IsWindows8OrGreater()) {
  1234. if (data->swapEffect == DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL) {
  1235. result = D3D_CALL(data->swapChain, SetRotation, data->rotation); /* NOLINT(clang-analyzer-core.NullDereference) */
  1236. if (FAILED(result)) {
  1237. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("IDXGISwapChain4::SetRotation"), result);
  1238. goto done;
  1239. }
  1240. }
  1241. }
  1242. #endif /*!defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)*/
  1243. /* Get each back buffer render target and create render target views */
  1244. for (i = 0; i < SDL_D3D12_NUM_BUFFERS; ++i) {
  1245. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  1246. result = D3D12_XBOX_CreateBackBufferTarget(data->d3dDevice, renderer->window->w, renderer->window->h, (void **)&data->renderTargets[i]);
  1247. if (FAILED(result)) {
  1248. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("D3D12_XBOX_CreateBackBufferTarget"), result);
  1249. goto done;
  1250. }
  1251. #else
  1252. result = D3D_CALL(data->swapChain, GetBuffer, /* NOLINT(clang-analyzer-core.NullDereference) */
  1253. i,
  1254. D3D_GUID(SDL_IID_ID3D12Resource),
  1255. (void **)&data->renderTargets[i]);
  1256. if (FAILED(result)) {
  1257. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("IDXGISwapChain4::GetBuffer"), result);
  1258. goto done;
  1259. }
  1260. #endif
  1261. SDL_zero(rtvDesc);
  1262. rtvDesc.Format = data->renderTargetFormat;
  1263. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
  1264. SDL_zero(rtvDescriptor);
  1265. D3D_CALL_RET(data->rtvDescriptorHeap, GetCPUDescriptorHandleForHeapStart, &rtvDescriptor);
  1266. rtvDescriptor.ptr += i * data->rtvDescriptorSize;
  1267. D3D_CALL(data->d3dDevice, CreateRenderTargetView, data->renderTargets[i], &rtvDesc, rtvDescriptor);
  1268. }
  1269. /* Set back buffer index to current buffer */
  1270. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  1271. data->currentBackBufferIndex = 0;
  1272. #else
  1273. data->currentBackBufferIndex = D3D_CALL(data->swapChain, GetCurrentBackBufferIndex);
  1274. #endif
  1275. /* Set the swap chain target immediately, so that a target is always set
  1276. * even before we get to SetDrawState. Without this it's possible to hit
  1277. * null references in places like ReadPixels!
  1278. */
  1279. data->currentRenderTargetView = D3D12_GetCurrentRenderTargetView(renderer);
  1280. D3D_CALL(data->commandList, OMSetRenderTargets, 1, &data->currentRenderTargetView, FALSE, NULL);
  1281. D3D12_TransitionResource(data,
  1282. data->renderTargets[data->currentBackBufferIndex],
  1283. D3D12_RESOURCE_STATE_PRESENT,
  1284. D3D12_RESOURCE_STATE_RENDER_TARGET);
  1285. data->viewportDirty = SDL_TRUE;
  1286. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  1287. D3D12_XBOX_StartFrame(data->d3dDevice, &data->frameToken);
  1288. #endif
  1289. done:
  1290. return result;
  1291. }
  1292. /* This method is called when the window's size changes. */
  1293. static HRESULT D3D12_UpdateForWindowSizeChange(SDL_Renderer *renderer)
  1294. {
  1295. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  1296. /* If the GPU has previous work, wait for it to be done first */
  1297. D3D12_WaitForGPU(data);
  1298. return D3D12_CreateWindowSizeDependentResources(renderer);
  1299. }
  1300. static void D3D12_WindowEvent(SDL_Renderer *renderer, const SDL_WindowEvent *event)
  1301. {
  1302. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  1303. if (event->type == SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED) {
  1304. data->pixelSizeChanged = SDL_TRUE;
  1305. }
  1306. }
  1307. static SDL_bool D3D12_SupportsBlendMode(SDL_Renderer *renderer, SDL_BlendMode blendMode)
  1308. {
  1309. SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode);
  1310. SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode);
  1311. SDL_BlendOperation colorOperation = SDL_GetBlendModeColorOperation(blendMode);
  1312. SDL_BlendFactor dstColorFactor = SDL_GetBlendModeDstColorFactor(blendMode);
  1313. SDL_BlendFactor dstAlphaFactor = SDL_GetBlendModeDstAlphaFactor(blendMode);
  1314. SDL_BlendOperation alphaOperation = SDL_GetBlendModeAlphaOperation(blendMode);
  1315. if (!GetBlendFunc(srcColorFactor) || !GetBlendFunc(srcAlphaFactor) ||
  1316. !GetBlendEquation(colorOperation) ||
  1317. !GetBlendFunc(dstColorFactor) || !GetBlendFunc(dstAlphaFactor) ||
  1318. !GetBlendEquation(alphaOperation)) {
  1319. return SDL_FALSE;
  1320. }
  1321. return SDL_TRUE;
  1322. }
  1323. static SIZE_T D3D12_GetAvailableSRVIndex(SDL_Renderer *renderer)
  1324. {
  1325. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  1326. if (rendererData->srvPoolHead) {
  1327. SIZE_T index = rendererData->srvPoolHead->index;
  1328. rendererData->srvPoolHead = (D3D12_SRVPoolNode *)(rendererData->srvPoolHead->next);
  1329. return index;
  1330. } else {
  1331. SDL_SetError("[d3d12] Cannot allocate more than %d textures!", SDL_D3D12_MAX_NUM_TEXTURES);
  1332. return SDL_D3D12_MAX_NUM_TEXTURES + 1;
  1333. }
  1334. }
  1335. static void D3D12_FreeSRVIndex(SDL_Renderer *renderer, SIZE_T index)
  1336. {
  1337. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  1338. rendererData->srvPoolNodes[index].next = rendererData->srvPoolHead;
  1339. rendererData->srvPoolHead = &rendererData->srvPoolNodes[index];
  1340. }
  1341. static int GetTextureProperty(SDL_PropertiesID props, const char *name, ID3D12Resource **texture)
  1342. {
  1343. IUnknown *unknown = (IUnknown*)SDL_GetProperty(props, name, NULL);
  1344. if (unknown) {
  1345. HRESULT result = D3D_CALL(unknown, QueryInterface, D3D_GUID(SDL_IID_ID3D12Resource), (void **)texture);
  1346. if (FAILED(result)) {
  1347. return WIN_SetErrorFromHRESULT(name, result);
  1348. }
  1349. }
  1350. return 0;
  1351. }
  1352. static int D3D12_CreateTexture(SDL_Renderer *renderer, SDL_Texture *texture, SDL_PropertiesID create_props)
  1353. {
  1354. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  1355. D3D12_TextureData *textureData;
  1356. HRESULT result;
  1357. DXGI_FORMAT textureFormat = SDLPixelFormatToDXGITextureFormat(texture->format, renderer->output_colorspace);
  1358. D3D12_RESOURCE_DESC textureDesc;
  1359. D3D12_HEAP_PROPERTIES heapProps;
  1360. D3D12_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
  1361. if (textureFormat == DXGI_FORMAT_UNKNOWN) {
  1362. return SDL_SetError("%s, An unsupported SDL pixel format (0x%x) was specified", __FUNCTION__, texture->format);
  1363. }
  1364. textureData = (D3D12_TextureData *)SDL_calloc(1, sizeof(*textureData));
  1365. if (!textureData) {
  1366. return -1;
  1367. }
  1368. textureData->scaleMode = (texture->scaleMode == SDL_SCALEMODE_NEAREST) ? D3D12_FILTER_MIN_MAG_MIP_POINT : D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  1369. texture->driverdata = textureData;
  1370. textureData->mainTextureFormat = textureFormat;
  1371. SDL_zero(textureDesc);
  1372. textureDesc.Width = texture->w;
  1373. textureDesc.Height = texture->h;
  1374. textureDesc.MipLevels = 1;
  1375. textureDesc.DepthOrArraySize = 1;
  1376. textureDesc.Format = textureFormat;
  1377. textureDesc.SampleDesc.Count = 1;
  1378. textureDesc.SampleDesc.Quality = 0;
  1379. textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  1380. textureDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
  1381. /* NV12 textures must have even width and height */
  1382. if (texture->format == SDL_PIXELFORMAT_NV12 ||
  1383. texture->format == SDL_PIXELFORMAT_NV21 ||
  1384. texture->format == SDL_PIXELFORMAT_P010 ||
  1385. texture->format == SDL_PIXELFORMAT_P016) {
  1386. textureDesc.Width = (textureDesc.Width + 1) & ~1;
  1387. textureDesc.Height = (textureDesc.Height + 1) & ~1;
  1388. }
  1389. textureData->w = (int)textureDesc.Width;
  1390. textureData->h = (int)textureDesc.Height;
  1391. textureData->shader = SHADER_RGB;
  1392. if (texture->access == SDL_TEXTUREACCESS_TARGET) {
  1393. textureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
  1394. }
  1395. SDL_zero(heapProps);
  1396. heapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
  1397. heapProps.CreationNodeMask = 1;
  1398. heapProps.VisibleNodeMask = 1;
  1399. if (GetTextureProperty(create_props, "d3d12.texture", &textureData->mainTexture) < 0) {
  1400. return -1;
  1401. }
  1402. if (!textureData->mainTexture) {
  1403. result = D3D_CALL(rendererData->d3dDevice, CreateCommittedResource,
  1404. &heapProps,
  1405. D3D12_HEAP_FLAG_NONE,
  1406. &textureDesc,
  1407. D3D12_RESOURCE_STATE_COPY_DEST,
  1408. NULL,
  1409. D3D_GUID(SDL_IID_ID3D12Resource),
  1410. (void **)&textureData->mainTexture);
  1411. if (FAILED(result)) {
  1412. return WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateCommittedResource [texture]"), result);
  1413. }
  1414. }
  1415. textureData->mainResourceState = D3D12_RESOURCE_STATE_COPY_DEST;
  1416. SDL_SetProperty(SDL_GetTextureProperties(texture), SDL_PROP_TEXTURE_D3D12_TEXTURE_POINTER, textureData->mainTexture);
  1417. #if SDL_HAVE_YUV
  1418. if (texture->format == SDL_PIXELFORMAT_YV12 ||
  1419. texture->format == SDL_PIXELFORMAT_IYUV) {
  1420. textureData->yuv = SDL_TRUE;
  1421. textureDesc.Width = (textureDesc.Width + 1) / 2;
  1422. textureDesc.Height = (textureDesc.Height + 1) / 2;
  1423. if (GetTextureProperty(create_props, "d3d12.texture_u", &textureData->mainTextureU) < 0) {
  1424. return -1;
  1425. }
  1426. if (!textureData->mainTextureU) {
  1427. result = D3D_CALL(rendererData->d3dDevice, CreateCommittedResource,
  1428. &heapProps,
  1429. D3D12_HEAP_FLAG_NONE,
  1430. &textureDesc,
  1431. D3D12_RESOURCE_STATE_COPY_DEST,
  1432. NULL,
  1433. D3D_GUID(SDL_IID_ID3D12Resource),
  1434. (void **)&textureData->mainTextureU);
  1435. if (FAILED(result)) {
  1436. return WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateCommittedResource [texture]"), result);
  1437. }
  1438. }
  1439. textureData->mainResourceStateU = D3D12_RESOURCE_STATE_COPY_DEST;
  1440. SDL_SetProperty(SDL_GetTextureProperties(texture), SDL_PROP_TEXTURE_D3D12_TEXTURE_U_POINTER, textureData->mainTextureU);
  1441. if (GetTextureProperty(create_props, "d3d12.texture_v", &textureData->mainTextureV) < 0) {
  1442. return -1;
  1443. }
  1444. if (!textureData->mainTextureV) {
  1445. result = D3D_CALL(rendererData->d3dDevice, CreateCommittedResource,
  1446. &heapProps,
  1447. D3D12_HEAP_FLAG_NONE,
  1448. &textureDesc,
  1449. D3D12_RESOURCE_STATE_COPY_DEST,
  1450. NULL,
  1451. D3D_GUID(SDL_IID_ID3D12Resource),
  1452. (void **)&textureData->mainTextureV);
  1453. if (FAILED(result)) {
  1454. return WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateCommittedResource [texture]"), result);
  1455. }
  1456. }
  1457. textureData->mainResourceStateV = D3D12_RESOURCE_STATE_COPY_DEST;
  1458. SDL_SetProperty(SDL_GetTextureProperties(texture), SDL_PROP_TEXTURE_D3D12_TEXTURE_V_POINTER, textureData->mainTextureV);
  1459. textureData->shader = SHADER_YUV;
  1460. textureData->shader_params = SDL_GetYCbCRtoRGBConversionMatrix(texture->colorspace, texture->w, texture->h, 8);
  1461. if (!textureData->shader_params) {
  1462. return SDL_SetError("Unsupported YUV colorspace");
  1463. }
  1464. }
  1465. if (texture->format == SDL_PIXELFORMAT_NV12 ||
  1466. texture->format == SDL_PIXELFORMAT_NV21 ||
  1467. texture->format == SDL_PIXELFORMAT_P010 ||
  1468. texture->format == SDL_PIXELFORMAT_P016) {
  1469. int bits_per_pixel;
  1470. textureData->nv12 = SDL_TRUE;
  1471. switch (texture->format) {
  1472. case SDL_PIXELFORMAT_NV12:
  1473. textureData->shader = SHADER_NV12;
  1474. break;
  1475. case SDL_PIXELFORMAT_NV21:
  1476. textureData->shader = SHADER_NV21;
  1477. break;
  1478. case SDL_PIXELFORMAT_P010:
  1479. case SDL_PIXELFORMAT_P016:
  1480. if(SDL_COLORSPACEPRIMARIES(texture->colorspace) == SDL_COLOR_PRIMARIES_BT2020 &&
  1481. SDL_COLORSPACETRANSFER(texture->colorspace) == SDL_TRANSFER_CHARACTERISTICS_PQ) {
  1482. textureData->shader = SHADER_HDR10;
  1483. } else {
  1484. return SDL_SetError("Unsupported YUV colorspace");
  1485. }
  1486. break;
  1487. default:
  1488. /* This should never happen because of the check above */
  1489. return SDL_SetError("Unsupported YUV colorspace");
  1490. }
  1491. switch (texture->format) {
  1492. case SDL_PIXELFORMAT_P010:
  1493. bits_per_pixel = 10;
  1494. break;
  1495. case SDL_PIXELFORMAT_P016:
  1496. bits_per_pixel = 16;
  1497. break;
  1498. default:
  1499. bits_per_pixel = 8;
  1500. break;
  1501. }
  1502. textureData->shader_params = SDL_GetYCbCRtoRGBConversionMatrix(texture->colorspace, texture->w, texture->h, bits_per_pixel);
  1503. if (!textureData->shader_params) {
  1504. return SDL_SetError("Unsupported YUV colorspace");
  1505. }
  1506. }
  1507. #endif /* SDL_HAVE_YUV */
  1508. SDL_zero(resourceViewDesc);
  1509. resourceViewDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  1510. resourceViewDesc.Format = SDLPixelFormatToDXGIMainResourceViewFormat(texture->format, renderer->output_colorspace);
  1511. resourceViewDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  1512. resourceViewDesc.Texture2D.MipLevels = textureDesc.MipLevels;
  1513. textureData->mainSRVIndex = D3D12_GetAvailableSRVIndex(renderer);
  1514. D3D_CALL_RET(rendererData->srvDescriptorHeap, GetCPUDescriptorHandleForHeapStart, &textureData->mainTextureResourceView);
  1515. textureData->mainTextureResourceView.ptr += textureData->mainSRVIndex * rendererData->srvDescriptorSize;
  1516. D3D_CALL(rendererData->d3dDevice, CreateShaderResourceView,
  1517. textureData->mainTexture,
  1518. &resourceViewDesc,
  1519. textureData->mainTextureResourceView);
  1520. #if SDL_HAVE_YUV
  1521. if (textureData->yuv) {
  1522. D3D_CALL_RET(rendererData->srvDescriptorHeap, GetCPUDescriptorHandleForHeapStart, &textureData->mainTextureResourceViewU);
  1523. textureData->mainSRVIndexU = D3D12_GetAvailableSRVIndex(renderer);
  1524. textureData->mainTextureResourceViewU.ptr += textureData->mainSRVIndexU * rendererData->srvDescriptorSize;
  1525. D3D_CALL(rendererData->d3dDevice, CreateShaderResourceView,
  1526. textureData->mainTextureU,
  1527. &resourceViewDesc,
  1528. textureData->mainTextureResourceViewU);
  1529. D3D_CALL_RET(rendererData->srvDescriptorHeap, GetCPUDescriptorHandleForHeapStart, &textureData->mainTextureResourceViewV);
  1530. textureData->mainSRVIndexV = D3D12_GetAvailableSRVIndex(renderer);
  1531. textureData->mainTextureResourceViewV.ptr += textureData->mainSRVIndexV * rendererData->srvDescriptorSize;
  1532. D3D_CALL(rendererData->d3dDevice, CreateShaderResourceView,
  1533. textureData->mainTextureV,
  1534. &resourceViewDesc,
  1535. textureData->mainTextureResourceViewV);
  1536. }
  1537. if (textureData->nv12) {
  1538. D3D12_SHADER_RESOURCE_VIEW_DESC nvResourceViewDesc = resourceViewDesc;
  1539. if (texture->format == SDL_PIXELFORMAT_NV12 || texture->format == SDL_PIXELFORMAT_NV21) {
  1540. nvResourceViewDesc.Format = DXGI_FORMAT_R8G8_UNORM;
  1541. } else if (texture->format == SDL_PIXELFORMAT_P010 || texture->format == SDL_PIXELFORMAT_P016) {
  1542. nvResourceViewDesc.Format = DXGI_FORMAT_R16G16_UNORM;
  1543. }
  1544. nvResourceViewDesc.Texture2D.PlaneSlice = 1;
  1545. D3D_CALL_RET(rendererData->srvDescriptorHeap, GetCPUDescriptorHandleForHeapStart, &textureData->mainTextureResourceViewNV);
  1546. textureData->mainSRVIndexNV = D3D12_GetAvailableSRVIndex(renderer);
  1547. textureData->mainTextureResourceViewNV.ptr += textureData->mainSRVIndexNV * rendererData->srvDescriptorSize;
  1548. D3D_CALL(rendererData->d3dDevice, CreateShaderResourceView,
  1549. textureData->mainTexture,
  1550. &nvResourceViewDesc,
  1551. textureData->mainTextureResourceViewNV);
  1552. }
  1553. #endif /* SDL_HAVE_YUV */
  1554. if (texture->access & SDL_TEXTUREACCESS_TARGET) {
  1555. D3D12_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
  1556. SDL_zero(renderTargetViewDesc);
  1557. renderTargetViewDesc.Format = textureDesc.Format;
  1558. renderTargetViewDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
  1559. renderTargetViewDesc.Texture2D.MipSlice = 0;
  1560. D3D_CALL_RET(rendererData->textureRTVDescriptorHeap, GetCPUDescriptorHandleForHeapStart, &textureData->mainTextureRenderTargetView);
  1561. textureData->mainTextureRenderTargetView.ptr += textureData->mainSRVIndex * rendererData->rtvDescriptorSize;
  1562. D3D_CALL(rendererData->d3dDevice, CreateRenderTargetView,
  1563. (ID3D12Resource *)textureData->mainTexture,
  1564. &renderTargetViewDesc,
  1565. textureData->mainTextureRenderTargetView);
  1566. }
  1567. return 0;
  1568. }
  1569. static void D3D12_DestroyTexture(SDL_Renderer *renderer,
  1570. SDL_Texture *texture)
  1571. {
  1572. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  1573. D3D12_TextureData *textureData = (D3D12_TextureData *)texture->driverdata;
  1574. if (!textureData) {
  1575. return;
  1576. }
  1577. /* Because SDL_DestroyTexture might be called while the data is in-flight, we need to issue the batch first
  1578. Unfortunately, this means that deleting a lot of textures mid-frame will have poor performance. */
  1579. D3D12_IssueBatch(rendererData);
  1580. SAFE_RELEASE(textureData->mainTexture);
  1581. SAFE_RELEASE(textureData->stagingBuffer);
  1582. D3D12_FreeSRVIndex(renderer, textureData->mainSRVIndex);
  1583. #if SDL_HAVE_YUV
  1584. SAFE_RELEASE(textureData->mainTextureU);
  1585. SAFE_RELEASE(textureData->mainTextureV);
  1586. if (textureData->yuv) {
  1587. D3D12_FreeSRVIndex(renderer, textureData->mainSRVIndexU);
  1588. D3D12_FreeSRVIndex(renderer, textureData->mainSRVIndexV);
  1589. }
  1590. if (textureData->nv12) {
  1591. D3D12_FreeSRVIndex(renderer, textureData->mainSRVIndexNV);
  1592. }
  1593. SDL_free(textureData->pixels);
  1594. #endif
  1595. SDL_free(textureData);
  1596. texture->driverdata = NULL;
  1597. }
  1598. static int D3D12_UpdateTextureInternal(D3D12_RenderData *rendererData, ID3D12Resource *texture, int plane, int x, int y, int w, int h, const void *pixels, int pitch, D3D12_RESOURCE_STATES *resourceState)
  1599. {
  1600. const Uint8 *src;
  1601. Uint8 *dst;
  1602. UINT length;
  1603. HRESULT result;
  1604. D3D12_RESOURCE_DESC textureDesc;
  1605. D3D12_RESOURCE_DESC uploadDesc;
  1606. D3D12_HEAP_PROPERTIES heapProps;
  1607. D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedTextureDesc;
  1608. D3D12_TEXTURE_COPY_LOCATION srcLocation;
  1609. D3D12_TEXTURE_COPY_LOCATION dstLocation;
  1610. BYTE *textureMemory;
  1611. ID3D12Resource *uploadBuffer;
  1612. UINT row, NumRows, RowPitch;
  1613. UINT64 RowLength;
  1614. /* Create an upload buffer, which will be used to write to the main texture. */
  1615. SDL_zero(textureDesc);
  1616. D3D_CALL_RET(texture, GetDesc, &textureDesc);
  1617. textureDesc.Width = w;
  1618. textureDesc.Height = h;
  1619. if (textureDesc.Format == DXGI_FORMAT_NV12 ||
  1620. textureDesc.Format == DXGI_FORMAT_P010 ||
  1621. textureDesc.Format == DXGI_FORMAT_P016) {
  1622. textureDesc.Width = (textureDesc.Width + 1) & ~1;
  1623. textureDesc.Height = (textureDesc.Height + 1) & ~1;
  1624. }
  1625. SDL_zero(uploadDesc);
  1626. uploadDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  1627. uploadDesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
  1628. uploadDesc.Height = 1;
  1629. uploadDesc.DepthOrArraySize = 1;
  1630. uploadDesc.MipLevels = 1;
  1631. uploadDesc.Format = DXGI_FORMAT_UNKNOWN;
  1632. uploadDesc.SampleDesc.Count = 1;
  1633. uploadDesc.SampleDesc.Quality = 0;
  1634. uploadDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  1635. uploadDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
  1636. /* Figure out how much we need to allocate for the upload buffer */
  1637. D3D_CALL(rendererData->d3dDevice, GetCopyableFootprints,
  1638. &textureDesc,
  1639. plane,
  1640. 1,
  1641. 0,
  1642. &placedTextureDesc,
  1643. &NumRows,
  1644. &RowLength,
  1645. &uploadDesc.Width);
  1646. RowPitch = placedTextureDesc.Footprint.RowPitch;
  1647. SDL_zero(heapProps);
  1648. heapProps.Type = D3D12_HEAP_TYPE_UPLOAD;
  1649. heapProps.CreationNodeMask = 1;
  1650. heapProps.VisibleNodeMask = 1;
  1651. /* Create the upload buffer */
  1652. result = D3D_CALL(rendererData->d3dDevice, CreateCommittedResource,
  1653. &heapProps,
  1654. D3D12_HEAP_FLAG_NONE,
  1655. &uploadDesc,
  1656. D3D12_RESOURCE_STATE_GENERIC_READ,
  1657. NULL,
  1658. D3D_GUID(SDL_IID_ID3D12Resource),
  1659. (void **)&rendererData->uploadBuffers[rendererData->currentUploadBuffer]);
  1660. if (FAILED(result)) {
  1661. return WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateCommittedResource [create upload buffer]"), result);
  1662. }
  1663. /* Get a write-only pointer to data in the upload buffer: */
  1664. uploadBuffer = rendererData->uploadBuffers[rendererData->currentUploadBuffer];
  1665. result = D3D_CALL(uploadBuffer, Map,
  1666. 0,
  1667. NULL,
  1668. (void **)&textureMemory);
  1669. if (FAILED(result)) {
  1670. SAFE_RELEASE(rendererData->uploadBuffers[rendererData->currentUploadBuffer]);
  1671. return WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Resource::Map [map staging texture]"), result);
  1672. }
  1673. src = (const Uint8 *)pixels;
  1674. dst = textureMemory;
  1675. length = (UINT)RowLength;
  1676. if (length == (UINT)pitch && length == RowPitch) {
  1677. SDL_memcpy(dst, src, (size_t)length * NumRows);
  1678. } else {
  1679. if (length > (UINT)pitch) {
  1680. length = pitch;
  1681. }
  1682. if (length > RowPitch) {
  1683. length = RowPitch;
  1684. }
  1685. for (row = NumRows; row--; ) {
  1686. SDL_memcpy(dst, src, length);
  1687. src += pitch;
  1688. dst += RowPitch;
  1689. }
  1690. }
  1691. /* Commit the changes back to the upload buffer: */
  1692. D3D_CALL(uploadBuffer, Unmap, 0, NULL);
  1693. /* Make sure the destination is in the correct resource state */
  1694. D3D12_TransitionResource(rendererData, texture, *resourceState, D3D12_RESOURCE_STATE_COPY_DEST);
  1695. *resourceState = D3D12_RESOURCE_STATE_COPY_DEST;
  1696. SDL_zero(dstLocation);
  1697. dstLocation.pResource = texture;
  1698. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  1699. dstLocation.SubresourceIndex = plane;
  1700. SDL_zero(srcLocation);
  1701. srcLocation.pResource = rendererData->uploadBuffers[rendererData->currentUploadBuffer];
  1702. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  1703. srcLocation.PlacedFootprint = placedTextureDesc;
  1704. D3D_CALL(rendererData->commandList, CopyTextureRegion,
  1705. &dstLocation,
  1706. x,
  1707. y,
  1708. 0,
  1709. &srcLocation,
  1710. NULL);
  1711. /* Transition the texture to be shader accessible */
  1712. D3D12_TransitionResource(rendererData, texture, *resourceState, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
  1713. *resourceState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  1714. rendererData->currentUploadBuffer++;
  1715. /* If we've used up all the upload buffers, we need to issue the batch */
  1716. if (rendererData->currentUploadBuffer == SDL_D3D12_NUM_UPLOAD_BUFFERS) {
  1717. D3D12_IssueBatch(rendererData);
  1718. }
  1719. return 0;
  1720. }
  1721. static int D3D12_UpdateTexture(SDL_Renderer *renderer, SDL_Texture *texture,
  1722. const SDL_Rect *rect, const void *srcPixels,
  1723. int srcPitch)
  1724. {
  1725. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  1726. D3D12_TextureData *textureData = (D3D12_TextureData *)texture->driverdata;
  1727. if (!textureData) {
  1728. return SDL_SetError("Texture is not currently available");
  1729. }
  1730. if (D3D12_UpdateTextureInternal(rendererData, textureData->mainTexture, 0, rect->x, rect->y, rect->w, rect->h, srcPixels, srcPitch, &textureData->mainResourceState) < 0) {
  1731. return -1;
  1732. }
  1733. #if SDL_HAVE_YUV
  1734. if (textureData->yuv) {
  1735. /* Skip to the correct offset into the next texture */
  1736. srcPixels = (const void *)((const Uint8 *)srcPixels + rect->h * srcPitch);
  1737. if (D3D12_UpdateTextureInternal(rendererData, texture->format == SDL_PIXELFORMAT_YV12 ? textureData->mainTextureV : textureData->mainTextureU, 0, rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2, srcPixels, (srcPitch + 1) / 2, texture->format == SDL_PIXELFORMAT_YV12 ? &textureData->mainResourceStateV : &textureData->mainResourceStateU) < 0) {
  1738. return -1;
  1739. }
  1740. /* Skip to the correct offset into the next texture */
  1741. srcPixels = (const void *)((const Uint8 *)srcPixels + ((rect->h + 1) / 2) * ((srcPitch + 1) / 2));
  1742. if (D3D12_UpdateTextureInternal(rendererData, texture->format == SDL_PIXELFORMAT_YV12 ? textureData->mainTextureU : textureData->mainTextureV, 0, rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2, srcPixels, (srcPitch + 1) / 2, texture->format == SDL_PIXELFORMAT_YV12 ? &textureData->mainResourceStateU : &textureData->mainResourceStateV) < 0) {
  1743. return -1;
  1744. }
  1745. }
  1746. if (textureData->nv12) {
  1747. /* Skip to the correct offset into the next texture */
  1748. srcPixels = (const void *)((const Uint8 *)srcPixels + rect->h * srcPitch);
  1749. if (D3D12_UpdateTextureInternal(rendererData, textureData->mainTexture, 1, rect->x, rect->y, (rect->w + 1) & ~1, (rect->h + 1) & ~1, srcPixels, (srcPitch + 1) & ~1, &textureData->mainResourceState) < 0) {
  1750. return -1;
  1751. }
  1752. }
  1753. #endif /* SDL_HAVE_YUV */
  1754. return 0;
  1755. }
  1756. #if SDL_HAVE_YUV
  1757. static int D3D12_UpdateTextureYUV(SDL_Renderer *renderer, SDL_Texture *texture,
  1758. const SDL_Rect *rect,
  1759. const Uint8 *Yplane, int Ypitch,
  1760. const Uint8 *Uplane, int Upitch,
  1761. const Uint8 *Vplane, int Vpitch)
  1762. {
  1763. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  1764. D3D12_TextureData *textureData = (D3D12_TextureData *)texture->driverdata;
  1765. if (!textureData) {
  1766. return SDL_SetError("Texture is not currently available");
  1767. }
  1768. if (D3D12_UpdateTextureInternal(rendererData, textureData->mainTexture, 0, rect->x, rect->y, rect->w, rect->h, Yplane, Ypitch, &textureData->mainResourceState) < 0) {
  1769. return -1;
  1770. }
  1771. if (D3D12_UpdateTextureInternal(rendererData, textureData->mainTextureU, 0, rect->x / 2, rect->y / 2, rect->w / 2, rect->h / 2, Uplane, Upitch, &textureData->mainResourceStateU) < 0) {
  1772. return -1;
  1773. }
  1774. if (D3D12_UpdateTextureInternal(rendererData, textureData->mainTextureV, 0, rect->x / 2, rect->y / 2, rect->w / 2, rect->h / 2, Vplane, Vpitch, &textureData->mainResourceStateV) < 0) {
  1775. return -1;
  1776. }
  1777. return 0;
  1778. }
  1779. static int D3D12_UpdateTextureNV(SDL_Renderer *renderer, SDL_Texture *texture,
  1780. const SDL_Rect *rect,
  1781. const Uint8 *Yplane, int Ypitch,
  1782. const Uint8 *UVplane, int UVpitch)
  1783. {
  1784. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  1785. D3D12_TextureData *textureData = (D3D12_TextureData *)texture->driverdata;
  1786. if (!textureData) {
  1787. return SDL_SetError("Texture is not currently available");
  1788. }
  1789. if (D3D12_UpdateTextureInternal(rendererData, textureData->mainTexture, 0, rect->x, rect->y, rect->w, rect->h, Yplane, Ypitch, &textureData->mainResourceState) < 0) {
  1790. return -1;
  1791. }
  1792. if (D3D12_UpdateTextureInternal(rendererData, textureData->mainTexture, 1, rect->x, rect->y, rect->w, rect->h, UVplane, UVpitch, &textureData->mainResourceState) < 0) {
  1793. return -1;
  1794. }
  1795. return 0;
  1796. }
  1797. #endif
  1798. static int D3D12_LockTexture(SDL_Renderer *renderer, SDL_Texture *texture,
  1799. const SDL_Rect *rect, void **pixels, int *pitch)
  1800. {
  1801. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  1802. D3D12_TextureData *textureData = (D3D12_TextureData *)texture->driverdata;
  1803. HRESULT result = S_OK;
  1804. D3D12_RESOURCE_DESC textureDesc;
  1805. D3D12_RESOURCE_DESC uploadDesc;
  1806. D3D12_HEAP_PROPERTIES heapProps;
  1807. D3D12_SUBRESOURCE_FOOTPRINT pitchedDesc;
  1808. BYTE *textureMemory;
  1809. int bpp;
  1810. if (!textureData) {
  1811. return SDL_SetError("Texture is not currently available");
  1812. }
  1813. #if SDL_HAVE_YUV
  1814. if (textureData->yuv || textureData->nv12) {
  1815. /* It's more efficient to upload directly... */
  1816. if (!textureData->pixels) {
  1817. textureData->pitch = texture->w;
  1818. textureData->pixels = (Uint8 *)SDL_malloc((texture->h * textureData->pitch * 3) / 2);
  1819. if (!textureData->pixels) {
  1820. return -1;
  1821. }
  1822. }
  1823. textureData->lockedRect = *rect;
  1824. *pixels =
  1825. (void *)(textureData->pixels + rect->y * textureData->pitch +
  1826. rect->x * SDL_BYTESPERPIXEL(texture->format));
  1827. *pitch = textureData->pitch;
  1828. return 0;
  1829. }
  1830. #endif
  1831. if (textureData->stagingBuffer) {
  1832. return SDL_SetError("texture is already locked");
  1833. }
  1834. /* Create an upload buffer, which will be used to write to the main texture. */
  1835. SDL_zero(textureDesc);
  1836. D3D_CALL_RET(textureData->mainTexture, GetDesc, &textureDesc);
  1837. textureDesc.Width = rect->w;
  1838. textureDesc.Height = rect->h;
  1839. SDL_zero(uploadDesc);
  1840. uploadDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  1841. uploadDesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
  1842. uploadDesc.Height = 1;
  1843. uploadDesc.DepthOrArraySize = 1;
  1844. uploadDesc.MipLevels = 1;
  1845. uploadDesc.Format = DXGI_FORMAT_UNKNOWN;
  1846. uploadDesc.SampleDesc.Count = 1;
  1847. uploadDesc.SampleDesc.Quality = 0;
  1848. uploadDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  1849. uploadDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
  1850. /* Figure out how much we need to allocate for the upload buffer */
  1851. D3D_CALL(rendererData->d3dDevice, GetCopyableFootprints,
  1852. &textureDesc,
  1853. 0,
  1854. 1,
  1855. 0,
  1856. NULL,
  1857. NULL,
  1858. NULL,
  1859. &uploadDesc.Width);
  1860. SDL_zero(heapProps);
  1861. heapProps.Type = D3D12_HEAP_TYPE_UPLOAD;
  1862. heapProps.CreationNodeMask = 1;
  1863. heapProps.VisibleNodeMask = 1;
  1864. /* Create the upload buffer */
  1865. result = D3D_CALL(rendererData->d3dDevice, CreateCommittedResource,
  1866. &heapProps,
  1867. D3D12_HEAP_FLAG_NONE,
  1868. &uploadDesc,
  1869. D3D12_RESOURCE_STATE_GENERIC_READ,
  1870. NULL,
  1871. D3D_GUID(SDL_IID_ID3D12Resource),
  1872. (void **)&textureData->stagingBuffer);
  1873. if (FAILED(result)) {
  1874. return WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateCommittedResource [create upload buffer]"), result);
  1875. }
  1876. /* Get a write-only pointer to data in the upload buffer: */
  1877. result = D3D_CALL(textureData->stagingBuffer, Map,
  1878. 0,
  1879. NULL,
  1880. (void **)&textureMemory);
  1881. if (FAILED(result)) {
  1882. SAFE_RELEASE(rendererData->uploadBuffers[rendererData->currentUploadBuffer]);
  1883. return WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Resource::Map [map staging texture]"), result);
  1884. }
  1885. SDL_zero(pitchedDesc);
  1886. pitchedDesc.Format = textureDesc.Format;
  1887. pitchedDesc.Width = rect->w;
  1888. pitchedDesc.Height = rect->h;
  1889. pitchedDesc.Depth = 1;
  1890. if (pitchedDesc.Format == DXGI_FORMAT_R8_UNORM) {
  1891. bpp = 1;
  1892. } else {
  1893. bpp = 4;
  1894. }
  1895. pitchedDesc.RowPitch = D3D12_Align(rect->w * bpp, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  1896. /* Make note of where the staging texture will be written to
  1897. * (on a call to SDL_UnlockTexture):
  1898. */
  1899. textureData->lockedRect = *rect;
  1900. /* Make sure the caller has information on the texture's pixel buffer,
  1901. * then return:
  1902. */
  1903. *pixels = textureMemory;
  1904. *pitch = pitchedDesc.RowPitch;
  1905. return 0;
  1906. }
  1907. static void D3D12_UnlockTexture(SDL_Renderer *renderer, SDL_Texture *texture)
  1908. {
  1909. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  1910. D3D12_TextureData *textureData = (D3D12_TextureData *)texture->driverdata;
  1911. D3D12_RESOURCE_DESC textureDesc;
  1912. D3D12_SUBRESOURCE_FOOTPRINT pitchedDesc;
  1913. D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedTextureDesc;
  1914. D3D12_TEXTURE_COPY_LOCATION srcLocation;
  1915. D3D12_TEXTURE_COPY_LOCATION dstLocation;
  1916. int bpp;
  1917. if (!textureData) {
  1918. return;
  1919. }
  1920. #if SDL_HAVE_YUV
  1921. if (textureData->yuv || textureData->nv12) {
  1922. const SDL_Rect *rect = &textureData->lockedRect;
  1923. void *pixels =
  1924. (void *)(textureData->pixels + rect->y * textureData->pitch +
  1925. rect->x * SDL_BYTESPERPIXEL(texture->format));
  1926. D3D12_UpdateTexture(renderer, texture, rect, pixels, textureData->pitch);
  1927. return;
  1928. }
  1929. #endif
  1930. /* Commit the pixel buffer's changes back to the staging texture: */
  1931. D3D_CALL(textureData->stagingBuffer, Unmap, 0, NULL);
  1932. SDL_zero(textureDesc);
  1933. D3D_CALL_RET(textureData->mainTexture, GetDesc, &textureDesc);
  1934. textureDesc.Width = textureData->lockedRect.w;
  1935. textureDesc.Height = textureData->lockedRect.h;
  1936. SDL_zero(pitchedDesc);
  1937. pitchedDesc.Format = textureDesc.Format;
  1938. pitchedDesc.Width = (UINT)textureDesc.Width;
  1939. pitchedDesc.Height = textureDesc.Height;
  1940. pitchedDesc.Depth = 1;
  1941. if (pitchedDesc.Format == DXGI_FORMAT_R8_UNORM) {
  1942. bpp = 1;
  1943. } else {
  1944. bpp = 4;
  1945. }
  1946. pitchedDesc.RowPitch = D3D12_Align(textureData->lockedRect.w * bpp, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  1947. SDL_zero(placedTextureDesc);
  1948. placedTextureDesc.Offset = 0;
  1949. placedTextureDesc.Footprint = pitchedDesc;
  1950. D3D12_TransitionResource(rendererData, textureData->mainTexture, textureData->mainResourceState, D3D12_RESOURCE_STATE_COPY_DEST);
  1951. textureData->mainResourceState = D3D12_RESOURCE_STATE_COPY_DEST;
  1952. SDL_zero(dstLocation);
  1953. dstLocation.pResource = textureData->mainTexture;
  1954. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  1955. dstLocation.SubresourceIndex = 0;
  1956. SDL_zero(srcLocation);
  1957. srcLocation.pResource = textureData->stagingBuffer;
  1958. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  1959. srcLocation.PlacedFootprint = placedTextureDesc;
  1960. D3D_CALL(rendererData->commandList, CopyTextureRegion,
  1961. &dstLocation,
  1962. textureData->lockedRect.x,
  1963. textureData->lockedRect.y,
  1964. 0,
  1965. &srcLocation,
  1966. NULL);
  1967. /* Transition the texture to be shader accessible */
  1968. D3D12_TransitionResource(rendererData, textureData->mainTexture, textureData->mainResourceState, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
  1969. textureData->mainResourceState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  1970. /* Execute the command list before releasing the staging buffer */
  1971. D3D12_IssueBatch(rendererData);
  1972. SAFE_RELEASE(textureData->stagingBuffer);
  1973. }
  1974. static void D3D12_SetTextureScaleMode(SDL_Renderer *renderer, SDL_Texture *texture, SDL_ScaleMode scaleMode)
  1975. {
  1976. D3D12_TextureData *textureData = (D3D12_TextureData *)texture->driverdata;
  1977. if (!textureData) {
  1978. return;
  1979. }
  1980. textureData->scaleMode = (scaleMode == SDL_SCALEMODE_NEAREST) ? D3D12_FILTER_MIN_MAG_MIP_POINT : D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  1981. }
  1982. static int D3D12_SetRenderTarget(SDL_Renderer *renderer, SDL_Texture *texture)
  1983. {
  1984. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  1985. D3D12_TextureData *textureData = NULL;
  1986. if (!texture) {
  1987. if (rendererData->textureRenderTarget) {
  1988. D3D12_TransitionResource(rendererData,
  1989. rendererData->textureRenderTarget->mainTexture,
  1990. rendererData->textureRenderTarget->mainResourceState,
  1991. D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
  1992. rendererData->textureRenderTarget->mainResourceState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  1993. }
  1994. rendererData->textureRenderTarget = NULL;
  1995. return 0;
  1996. }
  1997. textureData = (D3D12_TextureData *)texture->driverdata;
  1998. if (!textureData->mainTextureRenderTargetView.ptr) {
  1999. return SDL_SetError("specified texture is not a render target");
  2000. }
  2001. rendererData->textureRenderTarget = textureData;
  2002. D3D12_TransitionResource(rendererData,
  2003. rendererData->textureRenderTarget->mainTexture,
  2004. rendererData->textureRenderTarget->mainResourceState,
  2005. D3D12_RESOURCE_STATE_RENDER_TARGET);
  2006. rendererData->textureRenderTarget->mainResourceState = D3D12_RESOURCE_STATE_RENDER_TARGET;
  2007. return 0;
  2008. }
  2009. static int D3D12_QueueNoOp(SDL_Renderer *renderer, SDL_RenderCommand *cmd)
  2010. {
  2011. return 0; /* nothing to do in this backend. */
  2012. }
  2013. static int D3D12_QueueDrawPoints(SDL_Renderer *renderer, SDL_RenderCommand *cmd, const SDL_FPoint *points, int count)
  2014. {
  2015. VertexPositionColor *verts = (VertexPositionColor *)SDL_AllocateRenderVertices(renderer, count * sizeof(VertexPositionColor), 0, &cmd->data.draw.first);
  2016. int i;
  2017. SDL_FColor color = cmd->data.draw.color;
  2018. SDL_bool convert_color = SDL_RenderingLinearSpace(renderer);
  2019. if (!verts) {
  2020. return -1;
  2021. }
  2022. cmd->data.draw.count = count;
  2023. if (convert_color) {
  2024. SDL_ConvertToLinear(&color);
  2025. }
  2026. for (i = 0; i < count; i++) {
  2027. verts->pos.x = points[i].x + 0.5f;
  2028. verts->pos.y = points[i].y + 0.5f;
  2029. verts->tex.x = 0.0f;
  2030. verts->tex.y = 0.0f;
  2031. verts->color = color;
  2032. verts++;
  2033. }
  2034. return 0;
  2035. }
  2036. static int D3D12_QueueGeometry(SDL_Renderer *renderer, SDL_RenderCommand *cmd, SDL_Texture *texture,
  2037. const float *xy, int xy_stride, const SDL_FColor *color, int color_stride, const float *uv, int uv_stride,
  2038. int num_vertices, const void *indices, int num_indices, int size_indices,
  2039. float scale_x, float scale_y)
  2040. {
  2041. int i;
  2042. int count = indices ? num_indices : num_vertices;
  2043. VertexPositionColor *verts = (VertexPositionColor *)SDL_AllocateRenderVertices(renderer, count * sizeof(VertexPositionColor), 0, &cmd->data.draw.first);
  2044. SDL_bool convert_color = SDL_RenderingLinearSpace(renderer);
  2045. D3D12_TextureData *textureData = texture ? (D3D12_TextureData *)texture->driverdata : NULL;
  2046. float u_scale = textureData ? (float)texture->w / textureData->w : 0.0f;
  2047. float v_scale = textureData ? (float)texture->h / textureData->h : 0.0f;
  2048. if (!verts) {
  2049. return -1;
  2050. }
  2051. cmd->data.draw.count = count;
  2052. size_indices = indices ? size_indices : 0;
  2053. for (i = 0; i < count; i++) {
  2054. int j;
  2055. float *xy_;
  2056. if (size_indices == 4) {
  2057. j = ((const Uint32 *)indices)[i];
  2058. } else if (size_indices == 2) {
  2059. j = ((const Uint16 *)indices)[i];
  2060. } else if (size_indices == 1) {
  2061. j = ((const Uint8 *)indices)[i];
  2062. } else {
  2063. j = i;
  2064. }
  2065. xy_ = (float *)((char *)xy + j * xy_stride);
  2066. verts->pos.x = xy_[0] * scale_x;
  2067. verts->pos.y = xy_[1] * scale_y;
  2068. verts->color = *(SDL_FColor *)((char *)color + j * color_stride);
  2069. if (convert_color) {
  2070. SDL_ConvertToLinear(&verts->color);
  2071. }
  2072. if (texture) {
  2073. float *uv_ = (float *)((char *)uv + j * uv_stride);
  2074. verts->tex.x = uv_[0] * u_scale;
  2075. verts->tex.y = uv_[1] * v_scale;
  2076. } else {
  2077. verts->tex.x = 0.0f;
  2078. verts->tex.y = 0.0f;
  2079. }
  2080. verts += 1;
  2081. }
  2082. return 0;
  2083. }
  2084. static int D3D12_UpdateVertexBuffer(SDL_Renderer *renderer,
  2085. const void *vertexData, size_t dataSizeInBytes)
  2086. {
  2087. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  2088. HRESULT result = S_OK;
  2089. const int vbidx = rendererData->currentVertexBuffer;
  2090. UINT8 *vertexBufferData = NULL;
  2091. D3D12_RANGE range;
  2092. ID3D12Resource *vertexBuffer;
  2093. range.Begin = 0;
  2094. range.End = 0;
  2095. if (dataSizeInBytes == 0) {
  2096. return 0; /* nothing to do. */
  2097. }
  2098. if (rendererData->issueBatch) {
  2099. if (FAILED(D3D12_IssueBatch(rendererData))) {
  2100. SDL_SetError("Failed to issue intermediate batch");
  2101. return E_FAIL;
  2102. }
  2103. }
  2104. /* If the existing vertex buffer isn't big enough, we need to recreate a big enough one */
  2105. if (dataSizeInBytes > rendererData->vertexBuffers[vbidx].size) {
  2106. D3D12_CreateVertexBuffer(rendererData, vbidx, dataSizeInBytes);
  2107. }
  2108. vertexBuffer = rendererData->vertexBuffers[vbidx].resource;
  2109. result = D3D_CALL(vertexBuffer, Map, 0, &range, (void **)&vertexBufferData);
  2110. if (FAILED(result)) {
  2111. return WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Resource::Map [vertex buffer]"), result);
  2112. }
  2113. SDL_memcpy(vertexBufferData, vertexData, dataSizeInBytes);
  2114. D3D_CALL(vertexBuffer, Unmap, 0, NULL);
  2115. rendererData->vertexBuffers[vbidx].view.SizeInBytes = (UINT)dataSizeInBytes;
  2116. D3D_CALL(rendererData->commandList, IASetVertexBuffers, 0, 1, &rendererData->vertexBuffers[vbidx].view);
  2117. rendererData->currentVertexBuffer++;
  2118. if (rendererData->currentVertexBuffer >= SDL_D3D12_NUM_VERTEX_BUFFERS) {
  2119. rendererData->currentVertexBuffer = 0;
  2120. rendererData->issueBatch = SDL_TRUE;
  2121. }
  2122. return S_OK;
  2123. }
  2124. static int D3D12_UpdateViewport(SDL_Renderer *renderer)
  2125. {
  2126. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  2127. const SDL_Rect *viewport = &data->currentViewport;
  2128. Float4X4 projection;
  2129. Float4X4 view;
  2130. SDL_FRect orientationAlignedViewport;
  2131. BOOL swapDimensions;
  2132. D3D12_VIEWPORT d3dviewport;
  2133. const int rotation = D3D12_GetRotationForCurrentRenderTarget(renderer);
  2134. if (viewport->w == 0 || viewport->h == 0) {
  2135. /* If the viewport is empty, assume that it is because
  2136. * SDL_CreateRenderer is calling it, and will call it again later
  2137. * with a non-empty viewport.
  2138. */
  2139. /* SDL_Log("%s, no viewport was set!\n", __FUNCTION__); */
  2140. return -1;
  2141. }
  2142. /* Make sure the SDL viewport gets rotated to that of the physical display's rotation.
  2143. * Keep in mind here that the Y-axis will be been inverted (from Direct3D's
  2144. * default coordinate system) so rotations will be done in the opposite
  2145. * direction of the DXGI_MODE_ROTATION enumeration.
  2146. */
  2147. switch (rotation) {
  2148. case DXGI_MODE_ROTATION_IDENTITY:
  2149. projection = MatrixIdentity();
  2150. break;
  2151. case DXGI_MODE_ROTATION_ROTATE270:
  2152. projection = MatrixRotationZ(SDL_PI_F * 0.5f);
  2153. break;
  2154. case DXGI_MODE_ROTATION_ROTATE180:
  2155. projection = MatrixRotationZ(SDL_PI_F);
  2156. break;
  2157. case DXGI_MODE_ROTATION_ROTATE90:
  2158. projection = MatrixRotationZ(-SDL_PI_F * 0.5f);
  2159. break;
  2160. default:
  2161. return SDL_SetError("An unknown DisplayOrientation is being used");
  2162. }
  2163. /* Update the view matrix */
  2164. SDL_zero(view);
  2165. view.m[0][0] = 2.0f / viewport->w;
  2166. view.m[1][1] = -2.0f / viewport->h;
  2167. view.m[2][2] = 1.0f;
  2168. view.m[3][0] = -1.0f;
  2169. view.m[3][1] = 1.0f;
  2170. view.m[3][3] = 1.0f;
  2171. /* Combine the projection + view matrix together now, as both only get
  2172. * set here (as of this writing, on Dec 26, 2013). When done, store it
  2173. * for eventual transfer to the GPU.
  2174. */
  2175. data->vertexShaderConstantsData.projectionAndView = MatrixMultiply(
  2176. view,
  2177. projection);
  2178. /* Update the Direct3D viewport, which seems to be aligned to the
  2179. * swap buffer's coordinate space, which is always in either
  2180. * a landscape mode, for all Windows 8/RT devices, or a portrait mode,
  2181. * for Windows Phone devices.
  2182. */
  2183. swapDimensions = D3D12_IsDisplayRotated90Degrees((DXGI_MODE_ROTATION)rotation);
  2184. if (swapDimensions) {
  2185. orientationAlignedViewport.x = (float)viewport->y;
  2186. orientationAlignedViewport.y = (float)viewport->x;
  2187. orientationAlignedViewport.w = (float)viewport->h;
  2188. orientationAlignedViewport.h = (float)viewport->w;
  2189. } else {
  2190. orientationAlignedViewport.x = (float)viewport->x;
  2191. orientationAlignedViewport.y = (float)viewport->y;
  2192. orientationAlignedViewport.w = (float)viewport->w;
  2193. orientationAlignedViewport.h = (float)viewport->h;
  2194. }
  2195. d3dviewport.TopLeftX = orientationAlignedViewport.x;
  2196. d3dviewport.TopLeftY = orientationAlignedViewport.y;
  2197. d3dviewport.Width = orientationAlignedViewport.w;
  2198. d3dviewport.Height = orientationAlignedViewport.h;
  2199. d3dviewport.MinDepth = 0.0f;
  2200. d3dviewport.MaxDepth = 1.0f;
  2201. /* SDL_Log("%s: D3D viewport = {%f,%f,%f,%f}\n", __FUNCTION__, d3dviewport.TopLeftX, d3dviewport.TopLeftY, d3dviewport.Width, d3dviewport.Height); */
  2202. D3D_CALL(data->commandList, RSSetViewports, 1, &d3dviewport);
  2203. data->viewportDirty = SDL_FALSE;
  2204. return 0;
  2205. }
  2206. static int D3D12_SetDrawState(SDL_Renderer *renderer, const SDL_RenderCommand *cmd, D3D12_Shader shader, const float *shader_params,
  2207. D3D12_PRIMITIVE_TOPOLOGY_TYPE topology,
  2208. const int numShaderResources, D3D12_CPU_DESCRIPTOR_HANDLE *shaderResources,
  2209. D3D12_CPU_DESCRIPTOR_HANDLE *sampler, const Float4X4 *matrix)
  2210. {
  2211. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  2212. const Float4X4 *newmatrix = matrix ? matrix : &rendererData->identity;
  2213. D3D12_CPU_DESCRIPTOR_HANDLE renderTargetView = D3D12_GetCurrentRenderTargetView(renderer);
  2214. const SDL_BlendMode blendMode = cmd->data.draw.blend;
  2215. SDL_bool updateSubresource = SDL_FALSE;
  2216. int i;
  2217. D3D12_CPU_DESCRIPTOR_HANDLE firstShaderResource;
  2218. DXGI_FORMAT rtvFormat = rendererData->renderTargetFormat;
  2219. SDL_bool scRGB_output = SDL_RenderingLinearSpace(renderer);
  2220. float color_scale = cmd->data.draw.color_scale;
  2221. if (rendererData->textureRenderTarget) {
  2222. rtvFormat = rendererData->textureRenderTarget->mainTextureFormat;
  2223. }
  2224. /* See if we need to change the pipeline state */
  2225. if (!rendererData->currentPipelineState ||
  2226. rendererData->currentPipelineState->shader != shader ||
  2227. rendererData->currentPipelineState->blendMode != blendMode ||
  2228. rendererData->currentPipelineState->topology != topology ||
  2229. rendererData->currentPipelineState->rtvFormat != rtvFormat) {
  2230. /* Find the matching pipeline.
  2231. NOTE: Although it may seem inefficient to linearly search through ~450 pipelines
  2232. to find the correct one, in profiling this doesn't come up at all.
  2233. It's unlikely that using a hash table would affect performance a measurable amount unless
  2234. it's a degenerate case that's changing the pipeline state dozens of times per frame.
  2235. */
  2236. rendererData->currentPipelineState = NULL;
  2237. for (i = 0; i < rendererData->pipelineStateCount; ++i) {
  2238. D3D12_PipelineState *candidatePiplineState = &rendererData->pipelineStates[i];
  2239. if (candidatePiplineState->shader == shader &&
  2240. candidatePiplineState->blendMode == blendMode &&
  2241. candidatePiplineState->topology == topology &&
  2242. candidatePiplineState->rtvFormat == rtvFormat) {
  2243. rendererData->currentPipelineState = candidatePiplineState;
  2244. break;
  2245. }
  2246. }
  2247. /* If we didn't find a match, create a new one -- it must mean the blend mode is non-standard */
  2248. if (!rendererData->currentPipelineState) {
  2249. rendererData->currentPipelineState = D3D12_CreatePipelineState(renderer, shader, blendMode, topology, rtvFormat);
  2250. }
  2251. if (!rendererData->currentPipelineState) {
  2252. /* The error has been set inside D3D12_CreatePipelineState() */
  2253. return -1;
  2254. }
  2255. D3D_CALL(rendererData->commandList, SetPipelineState, rendererData->currentPipelineState->pipelineState);
  2256. D3D_CALL(rendererData->commandList, SetGraphicsRootSignature,
  2257. rendererData->rootSignatures[D3D12_GetRootSignatureType(rendererData->currentPipelineState->shader)]);
  2258. /* When we change these we will need to re-upload the constant buffer and reset any descriptors */
  2259. updateSubresource = SDL_TRUE;
  2260. rendererData->currentSampler.ptr = 0;
  2261. rendererData->currentShaderResource.ptr = 0;
  2262. }
  2263. if (renderTargetView.ptr != rendererData->currentRenderTargetView.ptr) {
  2264. D3D_CALL(rendererData->commandList, OMSetRenderTargets, 1, &renderTargetView, FALSE, NULL);
  2265. rendererData->currentRenderTargetView = renderTargetView;
  2266. }
  2267. if (rendererData->viewportDirty) {
  2268. if (D3D12_UpdateViewport(renderer) == 0) {
  2269. /* vertexShaderConstantsData.projectionAndView has changed */
  2270. updateSubresource = SDL_TRUE;
  2271. }
  2272. }
  2273. if (rendererData->cliprectDirty) {
  2274. D3D12_RECT scissorRect;
  2275. if (D3D12_GetViewportAlignedD3DRect(renderer, &rendererData->currentCliprect, &scissorRect, TRUE) != 0) {
  2276. /* D3D12_GetViewportAlignedD3DRect will have set the SDL error */
  2277. return -1;
  2278. }
  2279. D3D_CALL(rendererData->commandList, RSSetScissorRects, 1, &scissorRect);
  2280. rendererData->cliprectDirty = SDL_FALSE;
  2281. }
  2282. if (numShaderResources > 0) {
  2283. firstShaderResource = shaderResources[0];
  2284. } else {
  2285. firstShaderResource.ptr = 0;
  2286. }
  2287. if (firstShaderResource.ptr != rendererData->currentShaderResource.ptr) {
  2288. for (i = 0; i < numShaderResources; ++i) {
  2289. D3D12_GPU_DESCRIPTOR_HANDLE GPUHandle = D3D12_CPUtoGPUHandle(rendererData->srvDescriptorHeap, shaderResources[i]);
  2290. D3D_CALL(rendererData->commandList, SetGraphicsRootDescriptorTable, i + 2, GPUHandle);
  2291. }
  2292. rendererData->currentShaderResource.ptr = firstShaderResource.ptr;
  2293. }
  2294. if (sampler && sampler->ptr != rendererData->currentSampler.ptr) {
  2295. D3D12_GPU_DESCRIPTOR_HANDLE GPUHandle = D3D12_CPUtoGPUHandle(rendererData->samplerDescriptorHeap, *sampler);
  2296. UINT tableIndex = 0;
  2297. /* Figure out the correct sampler descriptor table index based on the type of shader */
  2298. switch (shader) {
  2299. case SHADER_RGB:
  2300. tableIndex = 3;
  2301. break;
  2302. #if SDL_HAVE_YUV
  2303. case SHADER_YUV:
  2304. tableIndex = 5;
  2305. break;
  2306. case SHADER_NV12:
  2307. case SHADER_NV21:
  2308. case SHADER_HDR10:
  2309. tableIndex = 4;
  2310. break;
  2311. #endif
  2312. default:
  2313. return SDL_SetError("[direct3d12] Trying to set a sampler for a shader which doesn't have one");
  2314. break;
  2315. }
  2316. D3D_CALL(rendererData->commandList, SetGraphicsRootDescriptorTable, tableIndex, GPUHandle);
  2317. rendererData->currentSampler = *sampler;
  2318. }
  2319. if (updateSubresource == SDL_TRUE || SDL_memcmp(&rendererData->vertexShaderConstantsData.model, newmatrix, sizeof(*newmatrix)) != 0) {
  2320. SDL_memcpy(&rendererData->vertexShaderConstantsData.model, newmatrix, sizeof(*newmatrix));
  2321. D3D_CALL(rendererData->commandList, SetGraphicsRoot32BitConstants,
  2322. 0,
  2323. 32,
  2324. &rendererData->vertexShaderConstantsData,
  2325. 0);
  2326. }
  2327. if (updateSubresource == SDL_TRUE ||
  2328. scRGB_output != rendererData->currentPipelineState->scRGB_output ||
  2329. color_scale != rendererData->currentPipelineState->color_scale ||
  2330. (shader_params && shader_params != rendererData->currentPipelineState->shader_params)) {
  2331. PixelShaderConstants constants;
  2332. constants.scRGB_output = (float)scRGB_output;
  2333. constants.color_scale = color_scale;
  2334. if (shader_params) {
  2335. SDL_memcpy(constants.YCbCr_matrix, shader_params, sizeof(constants.YCbCr_matrix));
  2336. }
  2337. D3D_CALL(rendererData->commandList, SetGraphicsRoot32BitConstants,
  2338. 1,
  2339. 20,
  2340. &constants,
  2341. 0);
  2342. rendererData->currentPipelineState->scRGB_output = scRGB_output;
  2343. rendererData->currentPipelineState->color_scale = color_scale;
  2344. rendererData->currentPipelineState->shader_params = shader_params;
  2345. }
  2346. return 0;
  2347. }
  2348. static int D3D12_SetCopyState(SDL_Renderer *renderer, const SDL_RenderCommand *cmd, const Float4X4 *matrix)
  2349. {
  2350. SDL_Texture *texture = cmd->data.draw.texture;
  2351. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  2352. D3D12_TextureData *textureData = (D3D12_TextureData *)texture->driverdata;
  2353. D3D12_CPU_DESCRIPTOR_HANDLE *textureSampler;
  2354. switch (textureData->scaleMode) {
  2355. case D3D12_FILTER_MIN_MAG_MIP_POINT:
  2356. textureSampler = &rendererData->nearestPixelSampler;
  2357. break;
  2358. case D3D12_FILTER_MIN_MAG_MIP_LINEAR:
  2359. textureSampler = &rendererData->linearSampler;
  2360. break;
  2361. default:
  2362. return SDL_SetError("Unknown scale mode: %d\n", textureData->scaleMode);
  2363. }
  2364. #if SDL_HAVE_YUV
  2365. if (textureData->yuv) {
  2366. D3D12_CPU_DESCRIPTOR_HANDLE shaderResources[3];
  2367. shaderResources[0] = textureData->mainTextureResourceView;
  2368. shaderResources[1] = textureData->mainTextureResourceViewU;
  2369. shaderResources[2] = textureData->mainTextureResourceViewV;
  2370. /* Make sure each texture is in the correct state to be accessed by the pixel shader. */
  2371. D3D12_TransitionResource(rendererData, textureData->mainTexture, textureData->mainResourceState, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
  2372. textureData->mainResourceState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  2373. D3D12_TransitionResource(rendererData, textureData->mainTextureU, textureData->mainResourceStateU, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
  2374. textureData->mainResourceStateU = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  2375. D3D12_TransitionResource(rendererData, textureData->mainTextureV, textureData->mainResourceStateV, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
  2376. textureData->mainResourceStateV = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  2377. return D3D12_SetDrawState(renderer, cmd, textureData->shader, textureData->shader_params, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, SDL_arraysize(shaderResources), shaderResources, textureSampler, matrix);
  2378. } else if (textureData->nv12) {
  2379. D3D12_CPU_DESCRIPTOR_HANDLE shaderResources[2];
  2380. shaderResources[0] = textureData->mainTextureResourceView;
  2381. shaderResources[1] = textureData->mainTextureResourceViewNV;
  2382. /* Make sure each texture is in the correct state to be accessed by the pixel shader. */
  2383. D3D12_TransitionResource(rendererData, textureData->mainTexture, textureData->mainResourceState, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
  2384. textureData->mainResourceState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  2385. return D3D12_SetDrawState(renderer, cmd, textureData->shader, textureData->shader_params, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, SDL_arraysize(shaderResources), shaderResources, textureSampler, matrix);
  2386. }
  2387. #endif /* SDL_HAVE_YUV */
  2388. D3D12_TransitionResource(rendererData, textureData->mainTexture, textureData->mainResourceState, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
  2389. textureData->mainResourceState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  2390. return D3D12_SetDrawState(renderer, cmd, textureData->shader, textureData->shader_params, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, 1, &textureData->mainTextureResourceView, textureSampler, matrix);
  2391. }
  2392. static void D3D12_DrawPrimitives(SDL_Renderer *renderer, D3D12_PRIMITIVE_TOPOLOGY primitiveTopology, const size_t vertexStart, const size_t vertexCount)
  2393. {
  2394. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  2395. D3D_CALL(rendererData->commandList, IASetPrimitiveTopology, primitiveTopology);
  2396. D3D_CALL(rendererData->commandList, DrawInstanced, (UINT)vertexCount, 1, (UINT)vertexStart, 0);
  2397. }
  2398. static void D3D12_InvalidateCachedState(SDL_Renderer *renderer)
  2399. {
  2400. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  2401. data->currentRenderTargetView.ptr = 0;
  2402. data->currentShaderResource.ptr = 0;
  2403. data->currentSampler.ptr = 0;
  2404. data->cliprectDirty = SDL_TRUE;
  2405. data->viewportDirty = SDL_TRUE;
  2406. }
  2407. static int D3D12_RunCommandQueue(SDL_Renderer *renderer, SDL_RenderCommand *cmd, void *vertices, size_t vertsize)
  2408. {
  2409. D3D12_RenderData *rendererData = (D3D12_RenderData *)renderer->driverdata;
  2410. const int viewportRotation = D3D12_GetRotationForCurrentRenderTarget(renderer);
  2411. if (rendererData->pixelSizeChanged) {
  2412. D3D12_UpdateForWindowSizeChange(renderer);
  2413. rendererData->pixelSizeChanged = SDL_FALSE;
  2414. }
  2415. if (rendererData->currentViewportRotation != viewportRotation) {
  2416. rendererData->currentViewportRotation = viewportRotation;
  2417. rendererData->viewportDirty = SDL_TRUE;
  2418. }
  2419. if (D3D12_UpdateVertexBuffer(renderer, vertices, vertsize) < 0) {
  2420. return -1;
  2421. }
  2422. while (cmd) {
  2423. switch (cmd->command) {
  2424. case SDL_RENDERCMD_SETDRAWCOLOR:
  2425. {
  2426. break; /* this isn't currently used in this render backend. */
  2427. }
  2428. case SDL_RENDERCMD_SETCOLORSCALE:
  2429. {
  2430. break;
  2431. }
  2432. case SDL_RENDERCMD_SETVIEWPORT:
  2433. {
  2434. SDL_Rect *viewport = &rendererData->currentViewport;
  2435. if (SDL_memcmp(viewport, &cmd->data.viewport.rect, sizeof(cmd->data.viewport.rect)) != 0) {
  2436. SDL_copyp(viewport, &cmd->data.viewport.rect);
  2437. rendererData->viewportDirty = SDL_TRUE;
  2438. }
  2439. break;
  2440. }
  2441. case SDL_RENDERCMD_SETCLIPRECT:
  2442. {
  2443. const SDL_Rect *rect = &cmd->data.cliprect.rect;
  2444. SDL_Rect viewport_cliprect;
  2445. if (rendererData->currentCliprectEnabled != cmd->data.cliprect.enabled) {
  2446. rendererData->currentCliprectEnabled = cmd->data.cliprect.enabled;
  2447. rendererData->cliprectDirty = SDL_TRUE;
  2448. }
  2449. if (!rendererData->currentCliprectEnabled) {
  2450. /* If the clip rect is disabled, then the scissor rect should be the whole viewport,
  2451. since direct3d12 doesn't allow disabling the scissor rectangle */
  2452. viewport_cliprect.x = 0;
  2453. viewport_cliprect.y = 0;
  2454. viewport_cliprect.w = rendererData->currentViewport.w;
  2455. viewport_cliprect.h = rendererData->currentViewport.h;
  2456. rect = &viewport_cliprect;
  2457. }
  2458. if (SDL_memcmp(&rendererData->currentCliprect, rect, sizeof(*rect)) != 0) {
  2459. SDL_copyp(&rendererData->currentCliprect, rect);
  2460. rendererData->cliprectDirty = SDL_TRUE;
  2461. }
  2462. break;
  2463. }
  2464. case SDL_RENDERCMD_CLEAR:
  2465. {
  2466. D3D12_CPU_DESCRIPTOR_HANDLE rtvDescriptor = D3D12_GetCurrentRenderTargetView(renderer);
  2467. SDL_bool convert_color = SDL_RenderingLinearSpace(renderer);
  2468. SDL_FColor color = cmd->data.color.color;
  2469. if (convert_color) {
  2470. SDL_ConvertToLinear(&color);
  2471. }
  2472. color.r *= cmd->data.color.color_scale;
  2473. color.g *= cmd->data.color.color_scale;
  2474. color.b *= cmd->data.color.color_scale;
  2475. D3D_CALL(rendererData->commandList, ClearRenderTargetView, rtvDescriptor, &color.r, 0, NULL);
  2476. break;
  2477. }
  2478. case SDL_RENDERCMD_DRAW_POINTS:
  2479. {
  2480. const size_t count = cmd->data.draw.count;
  2481. const size_t first = cmd->data.draw.first;
  2482. const size_t start = first / sizeof(VertexPositionColor);
  2483. D3D12_SetDrawState(renderer, cmd, SHADER_SOLID, NULL, D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT, 0, NULL, NULL, NULL);
  2484. D3D12_DrawPrimitives(renderer, D3D_PRIMITIVE_TOPOLOGY_POINTLIST, start, count);
  2485. break;
  2486. }
  2487. case SDL_RENDERCMD_DRAW_LINES:
  2488. {
  2489. const size_t count = cmd->data.draw.count;
  2490. const size_t first = cmd->data.draw.first;
  2491. const size_t start = first / sizeof(VertexPositionColor);
  2492. const VertexPositionColor *verts = (VertexPositionColor *)(((Uint8 *)vertices) + first);
  2493. D3D12_SetDrawState(renderer, cmd, SHADER_SOLID, NULL, D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, 0, NULL, NULL, NULL);
  2494. D3D12_DrawPrimitives(renderer, D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, start, count);
  2495. if (verts[0].pos.x != verts[count - 1].pos.x || verts[0].pos.y != verts[count - 1].pos.y) {
  2496. D3D12_DrawPrimitives(renderer, D3D_PRIMITIVE_TOPOLOGY_POINTLIST, start + (count - 1), 1);
  2497. }
  2498. break;
  2499. }
  2500. case SDL_RENDERCMD_FILL_RECTS: /* unused */
  2501. break;
  2502. case SDL_RENDERCMD_COPY: /* unused */
  2503. break;
  2504. case SDL_RENDERCMD_COPY_EX: /* unused */
  2505. break;
  2506. case SDL_RENDERCMD_GEOMETRY:
  2507. {
  2508. SDL_Texture *texture = cmd->data.draw.texture;
  2509. const size_t count = cmd->data.draw.count;
  2510. const size_t first = cmd->data.draw.first;
  2511. const size_t start = first / sizeof(VertexPositionColor);
  2512. if (texture) {
  2513. D3D12_SetCopyState(renderer, cmd, NULL);
  2514. } else {
  2515. D3D12_SetDrawState(renderer, cmd, SHADER_SOLID, NULL, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, 0, NULL, NULL, NULL);
  2516. }
  2517. D3D12_DrawPrimitives(renderer, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, start, count);
  2518. break;
  2519. }
  2520. case SDL_RENDERCMD_NO_OP:
  2521. break;
  2522. }
  2523. cmd = cmd->next;
  2524. }
  2525. return 0;
  2526. }
  2527. static SDL_Surface *D3D12_RenderReadPixels(SDL_Renderer *renderer, const SDL_Rect *rect)
  2528. {
  2529. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  2530. ID3D12Resource *backBuffer = NULL;
  2531. ID3D12Resource *readbackBuffer = NULL;
  2532. HRESULT result;
  2533. D3D12_RESOURCE_DESC textureDesc;
  2534. D3D12_RESOURCE_DESC readbackDesc;
  2535. D3D12_HEAP_PROPERTIES heapProps;
  2536. D3D12_RECT srcRect = { 0, 0, 0, 0 };
  2537. D3D12_BOX srcBox;
  2538. D3D12_TEXTURE_COPY_LOCATION dstLocation;
  2539. D3D12_TEXTURE_COPY_LOCATION srcLocation;
  2540. D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedTextureDesc;
  2541. D3D12_SUBRESOURCE_FOOTPRINT pitchedDesc;
  2542. BYTE *textureMemory;
  2543. int bpp;
  2544. SDL_Surface *output = NULL;
  2545. if (data->textureRenderTarget) {
  2546. backBuffer = data->textureRenderTarget->mainTexture;
  2547. } else {
  2548. backBuffer = data->renderTargets[data->currentBackBufferIndex];
  2549. }
  2550. /* Create a staging texture to copy the screen's data to: */
  2551. SDL_zero(textureDesc);
  2552. D3D_CALL_RET(backBuffer, GetDesc, &textureDesc);
  2553. textureDesc.Width = rect->w;
  2554. textureDesc.Height = rect->h;
  2555. SDL_zero(readbackDesc);
  2556. readbackDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  2557. readbackDesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
  2558. readbackDesc.Height = 1;
  2559. readbackDesc.DepthOrArraySize = 1;
  2560. readbackDesc.MipLevels = 1;
  2561. readbackDesc.Format = DXGI_FORMAT_UNKNOWN;
  2562. readbackDesc.SampleDesc.Count = 1;
  2563. readbackDesc.SampleDesc.Quality = 0;
  2564. readbackDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  2565. readbackDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
  2566. /* Figure out how much we need to allocate for the upload buffer */
  2567. D3D_CALL(data->d3dDevice, GetCopyableFootprints,
  2568. &textureDesc,
  2569. 0,
  2570. 1,
  2571. 0,
  2572. NULL,
  2573. NULL,
  2574. NULL,
  2575. &readbackDesc.Width);
  2576. SDL_zero(heapProps);
  2577. heapProps.Type = D3D12_HEAP_TYPE_READBACK;
  2578. heapProps.CreationNodeMask = 1;
  2579. heapProps.VisibleNodeMask = 1;
  2580. result = D3D_CALL(data->d3dDevice, CreateCommittedResource,
  2581. &heapProps,
  2582. D3D12_HEAP_FLAG_NONE,
  2583. &readbackDesc,
  2584. D3D12_RESOURCE_STATE_COPY_DEST,
  2585. NULL,
  2586. D3D_GUID(SDL_IID_ID3D12Resource),
  2587. (void **)&readbackBuffer);
  2588. if (FAILED(result)) {
  2589. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Device::CreateTexture2D [create staging texture]"), result);
  2590. goto done;
  2591. }
  2592. /* Transition the render target to be copyable from */
  2593. D3D12_TransitionResource(data, backBuffer, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
  2594. /* Copy the desired portion of the back buffer to the staging texture: */
  2595. if (D3D12_GetViewportAlignedD3DRect(renderer, rect, &srcRect, FALSE) != 0) {
  2596. /* D3D12_GetViewportAlignedD3DRect will have set the SDL error */
  2597. goto done;
  2598. }
  2599. srcBox.left = srcRect.left;
  2600. srcBox.right = srcRect.right;
  2601. srcBox.top = srcRect.top;
  2602. srcBox.bottom = srcRect.bottom;
  2603. srcBox.front = 0;
  2604. srcBox.back = 1;
  2605. /* Issue the copy texture region */
  2606. SDL_zero(pitchedDesc);
  2607. pitchedDesc.Format = textureDesc.Format;
  2608. pitchedDesc.Width = (UINT)textureDesc.Width;
  2609. pitchedDesc.Height = textureDesc.Height;
  2610. pitchedDesc.Depth = 1;
  2611. if (pitchedDesc.Format == DXGI_FORMAT_R8_UNORM) {
  2612. bpp = 1;
  2613. } else {
  2614. bpp = 4;
  2615. }
  2616. pitchedDesc.RowPitch = D3D12_Align(pitchedDesc.Width * bpp, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  2617. SDL_zero(placedTextureDesc);
  2618. placedTextureDesc.Offset = 0;
  2619. placedTextureDesc.Footprint = pitchedDesc;
  2620. SDL_zero(dstLocation);
  2621. dstLocation.pResource = readbackBuffer;
  2622. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  2623. dstLocation.PlacedFootprint = placedTextureDesc;
  2624. SDL_zero(srcLocation);
  2625. srcLocation.pResource = backBuffer;
  2626. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  2627. srcLocation.SubresourceIndex = 0;
  2628. D3D_CALL(data->commandList, CopyTextureRegion,
  2629. &dstLocation,
  2630. 0, 0, 0,
  2631. &srcLocation,
  2632. &srcBox);
  2633. /* We need to issue the command list for the copy to finish */
  2634. D3D12_IssueBatch(data);
  2635. /* Transition the render target back to a render target */
  2636. D3D12_TransitionResource(data, backBuffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
  2637. /* Map the staging texture's data to CPU-accessible memory: */
  2638. result = D3D_CALL(readbackBuffer, Map,
  2639. 0,
  2640. NULL,
  2641. (void **)&textureMemory);
  2642. if (FAILED(result)) {
  2643. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D12Resource::Map [map staging texture]"), result);
  2644. goto done;
  2645. }
  2646. output = SDL_DuplicatePixels(
  2647. rect->w, rect->h,
  2648. D3D12_DXGIFormatToSDLPixelFormat(textureDesc.Format),
  2649. renderer->target ? renderer->target->colorspace : renderer->output_colorspace,
  2650. textureMemory,
  2651. pitchedDesc.RowPitch);
  2652. /* Unmap the texture: */
  2653. D3D_CALL(readbackBuffer, Unmap, 0, NULL);
  2654. done:
  2655. SAFE_RELEASE(readbackBuffer);
  2656. return output;
  2657. }
  2658. static int D3D12_RenderPresent(SDL_Renderer *renderer)
  2659. {
  2660. D3D12_RenderData *data = (D3D12_RenderData *)renderer->driverdata;
  2661. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2662. UINT syncInterval;
  2663. UINT presentFlags;
  2664. #endif
  2665. HRESULT result;
  2666. /* Transition the render target to present state */
  2667. D3D12_TransitionResource(data,
  2668. data->renderTargets[data->currentBackBufferIndex],
  2669. D3D12_RESOURCE_STATE_RENDER_TARGET,
  2670. D3D12_RESOURCE_STATE_PRESENT);
  2671. /* Issue the command list */
  2672. result = D3D_CALL(data->commandList, Close);
  2673. D3D_CALL(data->commandQueue, ExecuteCommandLists, 1, (ID3D12CommandList *const *)&data->commandList);
  2674. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  2675. result = D3D12_XBOX_PresentFrame(data->commandQueue, data->frameToken, data->renderTargets[data->currentBackBufferIndex]);
  2676. #else
  2677. if (renderer->info.flags & SDL_RENDERER_PRESENTVSYNC) {
  2678. syncInterval = 1;
  2679. presentFlags = 0;
  2680. } else {
  2681. syncInterval = 0;
  2682. presentFlags = DXGI_PRESENT_ALLOW_TEARING;
  2683. }
  2684. /* The application may optionally specify "dirty" or "scroll"
  2685. * rects to improve efficiency in certain scenarios.
  2686. */
  2687. result = D3D_CALL(data->swapChain, Present, syncInterval, presentFlags);
  2688. #endif
  2689. if (FAILED(result) && result != DXGI_ERROR_WAS_STILL_DRAWING) {
  2690. /* If the device was removed either by a disconnect or a driver upgrade, we
  2691. * must recreate all device resources.
  2692. */
  2693. if (result == DXGI_ERROR_DEVICE_REMOVED) {
  2694. D3D12_HandleDeviceLost(renderer);
  2695. } else if (result == DXGI_ERROR_INVALID_CALL) {
  2696. /* We probably went through a fullscreen <-> windowed transition */
  2697. D3D12_CreateWindowSizeDependentResources(renderer);
  2698. } else {
  2699. WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("IDXGISwapChain::Present"), result);
  2700. }
  2701. return -1;
  2702. } else {
  2703. /* Wait for the GPU and move to the next frame */
  2704. result = D3D_CALL(data->commandQueue, Signal, data->fence, data->fenceValue);
  2705. if (D3D_CALL(data->fence, GetCompletedValue) < data->fenceValue) {
  2706. result = D3D_CALL(data->fence, SetEventOnCompletion,
  2707. data->fenceValue,
  2708. data->fenceEvent);
  2709. WaitForSingleObjectEx(data->fenceEvent, INFINITE, FALSE);
  2710. }
  2711. data->fenceValue++;
  2712. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  2713. data->currentBackBufferIndex++;
  2714. data->currentBackBufferIndex %= SDL_D3D12_NUM_BUFFERS;
  2715. #else
  2716. data->currentBackBufferIndex = D3D_CALL(data->swapChain, GetCurrentBackBufferIndex);
  2717. #endif
  2718. /* Reset the command allocator and command list, and transition back to render target */
  2719. D3D12_ResetCommandList(data);
  2720. D3D12_TransitionResource(data,
  2721. data->renderTargets[data->currentBackBufferIndex],
  2722. D3D12_RESOURCE_STATE_PRESENT,
  2723. D3D12_RESOURCE_STATE_RENDER_TARGET);
  2724. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  2725. D3D12_XBOX_StartFrame(data->d3dDevice, &data->frameToken);
  2726. #endif
  2727. return 0;
  2728. }
  2729. }
  2730. static int D3D12_SetVSync(SDL_Renderer *renderer, const int vsync)
  2731. {
  2732. if (vsync) {
  2733. renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC;
  2734. } else {
  2735. renderer->info.flags &= ~SDL_RENDERER_PRESENTVSYNC;
  2736. }
  2737. return 0;
  2738. }
  2739. SDL_Renderer *D3D12_CreateRenderer(SDL_Window *window, SDL_PropertiesID create_props)
  2740. {
  2741. SDL_Renderer *renderer;
  2742. D3D12_RenderData *data;
  2743. if (SDL_GetWindowFlags(window) & SDL_WINDOW_TRANSPARENT) {
  2744. /* D3D12 removed the swap effect needed to support transparent windows, use D3D11 instead */
  2745. SDL_SetError("The direct3d12 renderer doesn't work with transparent windows");
  2746. return NULL;
  2747. }
  2748. renderer = (SDL_Renderer *)SDL_calloc(1, sizeof(*renderer));
  2749. if (!renderer) {
  2750. return NULL;
  2751. }
  2752. renderer->magic = &SDL_renderer_magic;
  2753. SDL_SetupRendererColorspace(renderer, create_props);
  2754. if (renderer->output_colorspace != SDL_COLORSPACE_SRGB &&
  2755. renderer->output_colorspace != SDL_COLORSPACE_SCRGB
  2756. /*&& renderer->output_colorspace != SDL_COLORSPACE_HDR10*/) {
  2757. SDL_SetError("Unsupported output colorspace");
  2758. SDL_free(renderer);
  2759. return NULL;
  2760. }
  2761. data = (D3D12_RenderData *)SDL_calloc(1, sizeof(*data));
  2762. if (!data) {
  2763. SDL_free(renderer);
  2764. return NULL;
  2765. }
  2766. data->identity = MatrixIdentity();
  2767. renderer->WindowEvent = D3D12_WindowEvent;
  2768. renderer->SupportsBlendMode = D3D12_SupportsBlendMode;
  2769. renderer->CreateTexture = D3D12_CreateTexture;
  2770. renderer->UpdateTexture = D3D12_UpdateTexture;
  2771. #if SDL_HAVE_YUV
  2772. renderer->UpdateTextureYUV = D3D12_UpdateTextureYUV;
  2773. renderer->UpdateTextureNV = D3D12_UpdateTextureNV;
  2774. #endif
  2775. renderer->LockTexture = D3D12_LockTexture;
  2776. renderer->UnlockTexture = D3D12_UnlockTexture;
  2777. renderer->SetTextureScaleMode = D3D12_SetTextureScaleMode;
  2778. renderer->SetRenderTarget = D3D12_SetRenderTarget;
  2779. renderer->QueueSetViewport = D3D12_QueueNoOp;
  2780. renderer->QueueSetDrawColor = D3D12_QueueNoOp;
  2781. renderer->QueueSetColorScale = D3D12_QueueNoOp;
  2782. renderer->QueueDrawPoints = D3D12_QueueDrawPoints;
  2783. renderer->QueueDrawLines = D3D12_QueueDrawPoints; /* lines and points queue vertices the same way. */
  2784. renderer->QueueGeometry = D3D12_QueueGeometry;
  2785. renderer->InvalidateCachedState = D3D12_InvalidateCachedState;
  2786. renderer->RunCommandQueue = D3D12_RunCommandQueue;
  2787. renderer->RenderReadPixels = D3D12_RenderReadPixels;
  2788. renderer->RenderPresent = D3D12_RenderPresent;
  2789. renderer->DestroyTexture = D3D12_DestroyTexture;
  2790. renderer->DestroyRenderer = D3D12_DestroyRenderer;
  2791. renderer->info = D3D12_RenderDriver.info;
  2792. renderer->info.flags = SDL_RENDERER_ACCELERATED;
  2793. renderer->driverdata = data;
  2794. D3D12_InvalidateCachedState(renderer);
  2795. if (SDL_GetBooleanProperty(create_props, SDL_PROP_RENDERER_CREATE_PRESENT_VSYNC_BOOLEAN, SDL_FALSE)) {
  2796. renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC;
  2797. }
  2798. renderer->SetVSync = D3D12_SetVSync;
  2799. /* HACK: make sure the SDL_Renderer references the SDL_Window data now, in
  2800. * order to give init functions access to the underlying window handle:
  2801. */
  2802. renderer->window = window;
  2803. /* Initialize Direct3D resources */
  2804. if (FAILED(D3D12_CreateDeviceResources(renderer))) {
  2805. D3D12_DestroyRenderer(renderer);
  2806. return NULL;
  2807. }
  2808. if (FAILED(D3D12_CreateWindowSizeDependentResources(renderer))) {
  2809. D3D12_DestroyRenderer(renderer);
  2810. return NULL;
  2811. }
  2812. return renderer;
  2813. }
  2814. SDL_RenderDriver D3D12_RenderDriver = {
  2815. D3D12_CreateRenderer,
  2816. {
  2817. "direct3d12",
  2818. (SDL_RENDERER_ACCELERATED |
  2819. SDL_RENDERER_PRESENTVSYNC), /* flags. see SDL_RendererFlags */
  2820. 9, /* num_texture_formats */
  2821. { /* texture_formats */
  2822. SDL_PIXELFORMAT_ARGB8888,
  2823. SDL_PIXELFORMAT_XRGB8888,
  2824. SDL_PIXELFORMAT_RGBA64_FLOAT,
  2825. SDL_PIXELFORMAT_YV12,
  2826. SDL_PIXELFORMAT_IYUV,
  2827. SDL_PIXELFORMAT_NV12,
  2828. SDL_PIXELFORMAT_NV21,
  2829. SDL_PIXELFORMAT_P010,
  2830. SDL_PIXELFORMAT_P016 },
  2831. 16384, /* max_texture_width */
  2832. 16384 /* max_texture_height */
  2833. }
  2834. };
  2835. /* Ends C function definitions when using C++ */
  2836. #ifdef __cplusplus
  2837. }
  2838. #endif
  2839. #endif /* SDL_VIDEO_RENDER_D3D12 && !SDL_RENDER_DISABLED */