SDL_render_d3d12.c 118 KB

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