SDL_render_d3d11.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2012 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_config.h"
  19. #if SDL_VIDEO_RENDER_D3D11 && !SDL_RENDER_DISABLED
  20. #ifdef __WINRT__
  21. #include <windows.ui.core.h>
  22. #include <windows.foundation.h>
  23. #if WINAPI_FAMILY == WINAPI_FAMILY_APP
  24. #include <windows.ui.xaml.media.dxinterop.h>
  25. #endif
  26. #endif
  27. extern "C" {
  28. #include "../../core/windows/SDL_windows.h"
  29. #include "SDL_hints.h"
  30. //#include "SDL_loadso.h"
  31. #include "SDL_system.h"
  32. #include "SDL_syswm.h"
  33. #include "../SDL_sysrender.h"
  34. #include "SDL_log.h"
  35. #include "../../video/SDL_sysvideo.h"
  36. //#include "stdio.h"
  37. }
  38. #include <fstream>
  39. #include <string>
  40. #include <vector>
  41. #include "SDL_render_d3d11_cpp.h"
  42. using namespace DirectX;
  43. using namespace Microsoft::WRL;
  44. using namespace std;
  45. #ifdef __WINRT__
  46. using namespace Windows::Graphics::Display;
  47. using namespace Windows::UI::Core;
  48. #endif
  49. /* Texture sampling types */
  50. static const D3D11_FILTER SDL_D3D11_NEAREST_PIXEL_FILTER = D3D11_FILTER_MIN_MAG_MIP_POINT;
  51. static const D3D11_FILTER SDL_D3D11_LINEAR_FILTER = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  52. /* Direct3D 11.1 renderer implementation */
  53. static SDL_Renderer *D3D11_CreateRenderer(SDL_Window * window, Uint32 flags);
  54. static void D3D11_WindowEvent(SDL_Renderer * renderer,
  55. const SDL_WindowEvent *event);
  56. static int D3D11_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture);
  57. static int D3D11_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
  58. const SDL_Rect * rect, const void *srcPixels,
  59. int srcPitch);
  60. static int D3D11_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture,
  61. const SDL_Rect * rect, void **pixels, int *pitch);
  62. static void D3D11_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture);
  63. static int D3D11_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture);
  64. static int D3D11_UpdateViewport(SDL_Renderer * renderer);
  65. static int D3D11_UpdateClipRect(SDL_Renderer * renderer);
  66. static int D3D11_RenderClear(SDL_Renderer * renderer);
  67. static int D3D11_RenderDrawPoints(SDL_Renderer * renderer,
  68. const SDL_FPoint * points, int count);
  69. static int D3D11_RenderDrawLines(SDL_Renderer * renderer,
  70. const SDL_FPoint * points, int count);
  71. static int D3D11_RenderFillRects(SDL_Renderer * renderer,
  72. const SDL_FRect * rects, int count);
  73. static int D3D11_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture,
  74. const SDL_Rect * srcrect, const SDL_FRect * dstrect);
  75. static int D3D11_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
  76. const SDL_Rect * srcrect, const SDL_FRect * dstrect,
  77. const double angle, const SDL_FPoint * center, const SDL_RendererFlip flip);
  78. static int D3D11_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
  79. Uint32 format, void * pixels, int pitch);
  80. static void D3D11_RenderPresent(SDL_Renderer * renderer);
  81. static void D3D11_DestroyTexture(SDL_Renderer * renderer,
  82. SDL_Texture * texture);
  83. static void D3D11_DestroyRenderer(SDL_Renderer * renderer);
  84. /* Direct3D 11.1 Internal Functions */
  85. HRESULT D3D11_CreateDeviceResources(SDL_Renderer * renderer);
  86. HRESULT D3D11_CreateWindowSizeDependentResources(SDL_Renderer * renderer);
  87. HRESULT D3D11_UpdateForWindowSizeChange(SDL_Renderer * renderer);
  88. HRESULT D3D11_HandleDeviceLost(SDL_Renderer * renderer);
  89. extern "C" SDL_RenderDriver D3D11_RenderDriver = {
  90. D3D11_CreateRenderer,
  91. {
  92. "direct3d 11.1",
  93. (
  94. SDL_RENDERER_ACCELERATED |
  95. SDL_RENDERER_PRESENTVSYNC |
  96. SDL_RENDERER_TARGETTEXTURE
  97. ), // flags. see SDL_RendererFlags
  98. 2, // num_texture_formats
  99. { // texture_formats
  100. SDL_PIXELFORMAT_RGB888,
  101. SDL_PIXELFORMAT_ARGB8888
  102. },
  103. 0, // max_texture_width: will be filled in later
  104. 0 // max_texture_height: will be filled in later
  105. }
  106. };
  107. static Uint32
  108. DXGIFormatToSDLPixelFormat(DXGI_FORMAT dxgiFormat) {
  109. switch (dxgiFormat) {
  110. case DXGI_FORMAT_B8G8R8A8_UNORM:
  111. return SDL_PIXELFORMAT_ARGB8888;
  112. case DXGI_FORMAT_B8G8R8X8_UNORM:
  113. return SDL_PIXELFORMAT_RGB888;
  114. default:
  115. return SDL_PIXELFORMAT_UNKNOWN;
  116. }
  117. }
  118. static DXGI_FORMAT
  119. SDLPixelFormatToDXGIFormat(Uint32 sdlFormat)
  120. {
  121. switch (sdlFormat) {
  122. case SDL_PIXELFORMAT_ARGB8888:
  123. return DXGI_FORMAT_B8G8R8A8_UNORM;
  124. case SDL_PIXELFORMAT_RGB888:
  125. return DXGI_FORMAT_B8G8R8X8_UNORM;
  126. default:
  127. return DXGI_FORMAT_UNKNOWN;
  128. }
  129. }
  130. //typedef struct
  131. //{
  132. // float x, y, z;
  133. // DWORD color;
  134. // float u, v;
  135. //} Vertex;
  136. SDL_Renderer *
  137. D3D11_CreateRenderer(SDL_Window * window, Uint32 flags)
  138. {
  139. SDL_Renderer *renderer;
  140. D3D11_RenderData *data;
  141. renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer));
  142. if (!renderer) {
  143. SDL_OutOfMemory();
  144. return NULL;
  145. }
  146. SDL_zerop(renderer);
  147. data = new D3D11_RenderData; // Use the C++ 'new' operator to make sure the struct's members initialize using C++ rules
  148. if (!data) {
  149. SDL_OutOfMemory();
  150. return NULL;
  151. }
  152. data->featureLevel = (D3D_FEATURE_LEVEL) 0;
  153. data->windowSizeInDIPs = XMFLOAT2(0, 0);
  154. data->renderTargetSize = XMFLOAT2(0, 0);
  155. renderer->WindowEvent = D3D11_WindowEvent;
  156. renderer->CreateTexture = D3D11_CreateTexture;
  157. renderer->UpdateTexture = D3D11_UpdateTexture;
  158. renderer->LockTexture = D3D11_LockTexture;
  159. renderer->UnlockTexture = D3D11_UnlockTexture;
  160. renderer->SetRenderTarget = D3D11_SetRenderTarget;
  161. renderer->UpdateViewport = D3D11_UpdateViewport;
  162. renderer->UpdateClipRect = D3D11_UpdateClipRect;
  163. renderer->RenderClear = D3D11_RenderClear;
  164. renderer->RenderDrawPoints = D3D11_RenderDrawPoints;
  165. renderer->RenderDrawLines = D3D11_RenderDrawLines;
  166. renderer->RenderFillRects = D3D11_RenderFillRects;
  167. renderer->RenderCopy = D3D11_RenderCopy;
  168. renderer->RenderCopyEx = D3D11_RenderCopyEx;
  169. renderer->RenderReadPixels = D3D11_RenderReadPixels;
  170. renderer->RenderPresent = D3D11_RenderPresent;
  171. renderer->DestroyTexture = D3D11_DestroyTexture;
  172. renderer->DestroyRenderer = D3D11_DestroyRenderer;
  173. renderer->info = D3D11_RenderDriver.info;
  174. renderer->driverdata = data;
  175. // HACK: make sure the SDL_Renderer references the SDL_Window data now, in
  176. // order to give init functions access to the underlying window handle:
  177. renderer->window = window;
  178. /* Initialize Direct3D resources */
  179. if (FAILED(D3D11_CreateDeviceResources(renderer))) {
  180. D3D11_DestroyRenderer(renderer);
  181. return NULL;
  182. }
  183. if (FAILED(D3D11_CreateWindowSizeDependentResources(renderer))) {
  184. D3D11_DestroyRenderer(renderer);
  185. return NULL;
  186. }
  187. // TODO, WinRT: fill in renderer->info.texture_formats where appropriate
  188. return renderer;
  189. }
  190. static void
  191. D3D11_DestroyRenderer(SDL_Renderer * renderer)
  192. {
  193. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  194. if (data) {
  195. delete data;
  196. data = NULL;
  197. }
  198. }
  199. static bool
  200. D3D11_ReadFileContents(const wstring & fileName, vector<char> & out)
  201. {
  202. ifstream in(fileName, ios::in | ios::binary);
  203. if (!in) {
  204. return false;
  205. }
  206. in.seekg(0, ios::end);
  207. out.resize((size_t) in.tellg());
  208. in.seekg(0, ios::beg);
  209. in.read(&out[0], out.size());
  210. return in.good();
  211. }
  212. static bool
  213. D3D11_ReadShaderContents(const wstring & shaderName, vector<char> & out)
  214. {
  215. wstring fileName;
  216. #if WINAPI_FAMILY == WINAPI_FAMILY_APP
  217. fileName = SDL_WinRTGetFSPathUNICODE(SDL_WINRT_PATH_INSTALLED_LOCATION);
  218. fileName += L"\\SDL_VS2012_WinRT\\";
  219. #elif WINAPI_FAMILY == WINAPI_PHONE_APP
  220. fileName = SDL_WinRTGetFSPathUNICODE(SDL_WINRT_PATH_INSTALLED_LOCATION);
  221. fileName += L"\\";
  222. #endif
  223. // TODO, WinRT: test Direct3D 11.1 shader loading on Win32
  224. fileName += shaderName;
  225. return D3D11_ReadFileContents(fileName, out);
  226. }
  227. static HRESULT
  228. D3D11_LoadPixelShader(SDL_Renderer * renderer,
  229. const wstring & shaderName,
  230. ID3D11PixelShader ** shaderOutput)
  231. {
  232. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  233. HRESULT result = S_OK;
  234. vector<char> fileData;
  235. if (!D3D11_ReadShaderContents(shaderName, fileData)) {
  236. SDL_SetError("Unable to open SDL's pixel shader file.");
  237. return E_FAIL;
  238. }
  239. result = data->d3dDevice->CreatePixelShader(
  240. &fileData[0],
  241. fileData.size(),
  242. nullptr,
  243. shaderOutput
  244. );
  245. if (FAILED(result)) {
  246. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  247. return result;
  248. }
  249. return S_OK;
  250. }
  251. static HRESULT
  252. D3D11_CreateBlendMode(SDL_Renderer * renderer,
  253. BOOL enableBlending,
  254. D3D11_BLEND srcBlend,
  255. D3D11_BLEND destBlend,
  256. ID3D11BlendState ** blendStateOutput)
  257. {
  258. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  259. HRESULT result = S_OK;
  260. D3D11_BLEND_DESC blendDesc;
  261. memset(&blendDesc, 0, sizeof(blendDesc));
  262. blendDesc.AlphaToCoverageEnable = FALSE;
  263. blendDesc.IndependentBlendEnable = FALSE;
  264. blendDesc.RenderTarget[0].BlendEnable = enableBlending;
  265. blendDesc.RenderTarget[0].SrcBlend = srcBlend;
  266. blendDesc.RenderTarget[0].DestBlend = destBlend;
  267. blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  268. blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
  269. blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
  270. blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  271. blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  272. result = data->d3dDevice->CreateBlendState(&blendDesc, blendStateOutput);
  273. if (FAILED(result)) {
  274. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  275. return result;
  276. }
  277. return S_OK;
  278. }
  279. // Create resources that depend on the device.
  280. HRESULT
  281. D3D11_CreateDeviceResources(SDL_Renderer * renderer)
  282. {
  283. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  284. // This flag adds support for surfaces with a different color channel ordering
  285. // than the API default. It is required for compatibility with Direct2D.
  286. UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  287. // Make sure Direct3D's debugging feature gets used, if the app requests it.
  288. const char *hint = SDL_GetHint(SDL_HINT_RENDER_DIRECT3D11_DEBUG);
  289. if (hint) {
  290. if (*hint == '1') {
  291. creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
  292. }
  293. }
  294. // This array defines the set of DirectX hardware feature levels this app will support.
  295. // Note the ordering should be preserved.
  296. // Don't forget to declare your application's minimum required feature level in its
  297. // description. All applications are assumed to support 9.1 unless otherwise stated.
  298. D3D_FEATURE_LEVEL featureLevels[] =
  299. {
  300. D3D_FEATURE_LEVEL_11_1,
  301. D3D_FEATURE_LEVEL_11_0,
  302. D3D_FEATURE_LEVEL_10_1,
  303. D3D_FEATURE_LEVEL_10_0,
  304. D3D_FEATURE_LEVEL_9_3,
  305. D3D_FEATURE_LEVEL_9_2,
  306. D3D_FEATURE_LEVEL_9_1
  307. };
  308. // Create the Direct3D 11 API device object and a corresponding context.
  309. ComPtr<ID3D11Device> device;
  310. ComPtr<ID3D11DeviceContext> context;
  311. HRESULT result = S_OK;
  312. result = D3D11CreateDevice(
  313. nullptr, // Specify nullptr to use the default adapter.
  314. D3D_DRIVER_TYPE_HARDWARE,
  315. nullptr,
  316. creationFlags, // Set set debug and Direct2D compatibility flags.
  317. featureLevels, // List of feature levels this app can support.
  318. ARRAYSIZE(featureLevels),
  319. D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps.
  320. &device, // Returns the Direct3D device created.
  321. &data->featureLevel, // Returns feature level of device created.
  322. &context // Returns the device immediate context.
  323. );
  324. if (FAILED(result)) {
  325. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  326. return result;
  327. }
  328. // Get the Direct3D 11.1 API device and context interfaces.
  329. Microsoft::WRL::ComPtr<ID3D11Device1> d3dDevice1;
  330. result = device.As(&(data->d3dDevice));
  331. if (FAILED(result)) {
  332. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  333. return result;
  334. }
  335. result = context.As(&data->d3dContext);
  336. if (FAILED(result)) {
  337. return result;
  338. }
  339. //
  340. // Make note of the maximum texture size
  341. // Max texture sizes are documented on MSDN, at:
  342. // http://msdn.microsoft.com/en-us/library/windows/apps/ff476876.aspx
  343. //
  344. switch (data->d3dDevice->GetFeatureLevel()) {
  345. case D3D_FEATURE_LEVEL_11_1:
  346. case D3D_FEATURE_LEVEL_11_0:
  347. renderer->info.max_texture_width = renderer->info.max_texture_height = 16384;
  348. break;
  349. case D3D_FEATURE_LEVEL_10_1:
  350. case D3D_FEATURE_LEVEL_10_0:
  351. renderer->info.max_texture_width = renderer->info.max_texture_height = 8192;
  352. break;
  353. case D3D_FEATURE_LEVEL_9_3:
  354. renderer->info.max_texture_width = renderer->info.max_texture_height = 4096;
  355. break;
  356. case D3D_FEATURE_LEVEL_9_2:
  357. case D3D_FEATURE_LEVEL_9_1:
  358. renderer->info.max_texture_width = renderer->info.max_texture_height = 2048;
  359. break;
  360. }
  361. //
  362. // Load in SDL's one and only vertex shader:
  363. //
  364. vector<char> fileData;
  365. if (!D3D11_ReadShaderContents(L"SDL_D3D11_VertexShader_Default.cso", fileData)) {
  366. SDL_SetError("Unable to open SDL's vertex shader file.");
  367. return E_FAIL;
  368. }
  369. result = data->d3dDevice->CreateVertexShader(
  370. &fileData[0],
  371. fileData.size(),
  372. nullptr,
  373. &data->vertexShader
  374. );
  375. if (FAILED(result)) {
  376. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  377. return result;
  378. }
  379. //
  380. // Create an input layout for SDL's vertex shader:
  381. //
  382. const D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
  383. {
  384. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
  385. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
  386. { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 },
  387. };
  388. result = data->d3dDevice->CreateInputLayout(
  389. vertexDesc,
  390. ARRAYSIZE(vertexDesc),
  391. &fileData[0],
  392. fileData.size(),
  393. &data->inputLayout
  394. );
  395. if (FAILED(result)) {
  396. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  397. return result;
  398. }
  399. //
  400. // Load in SDL's pixel shaders
  401. //
  402. result = D3D11_LoadPixelShader(renderer, L"SDL_D3D11_PixelShader_TextureColored.cso", &data->texturePixelShader);
  403. if (FAILED(result)) {
  404. // D3D11_LoadPixelShader will have aleady set the SDL error
  405. return result;
  406. }
  407. result = D3D11_LoadPixelShader(renderer, L"SDL_D3D11_PixelShader_FixedColor.cso", &data->colorPixelShader);
  408. if (FAILED(result)) {
  409. // D3D11_LoadPixelShader will have aleady set the SDL error
  410. return result;
  411. }
  412. //
  413. // Setup space to hold vertex shader constants:
  414. //
  415. CD3D11_BUFFER_DESC constantBufferDesc(sizeof(SDL_VertexShaderConstants), D3D11_BIND_CONSTANT_BUFFER);
  416. result = data->d3dDevice->CreateBuffer(
  417. &constantBufferDesc,
  418. nullptr,
  419. &data->vertexShaderConstants
  420. );
  421. if (FAILED(result)) {
  422. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  423. return result;
  424. }
  425. //
  426. // Make sure that the vertex buffer, if already created, gets freed.
  427. // It will be recreated later.
  428. //
  429. data->vertexBuffer = nullptr;
  430. //
  431. // Create samplers to use when drawing textures:
  432. //
  433. D3D11_SAMPLER_DESC samplerDesc;
  434. samplerDesc.Filter = SDL_D3D11_NEAREST_PIXEL_FILTER;
  435. samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
  436. samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
  437. samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
  438. samplerDesc.MipLODBias = 0.0f;
  439. samplerDesc.MaxAnisotropy = 1;
  440. samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  441. samplerDesc.BorderColor[0] = 0.0f;
  442. samplerDesc.BorderColor[1] = 0.0f;
  443. samplerDesc.BorderColor[2] = 0.0f;
  444. samplerDesc.BorderColor[3] = 0.0f;
  445. samplerDesc.MinLOD = 0.0f;
  446. samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
  447. result = data->d3dDevice->CreateSamplerState(
  448. &samplerDesc,
  449. &data->nearestPixelSampler
  450. );
  451. if (FAILED(result)) {
  452. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  453. return result;
  454. }
  455. samplerDesc.Filter = SDL_D3D11_LINEAR_FILTER;
  456. result = data->d3dDevice->CreateSamplerState(
  457. &samplerDesc,
  458. &data->linearSampler
  459. );
  460. if (FAILED(result)) {
  461. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  462. return result;
  463. }
  464. //
  465. // Setup the Direct3D rasterizer
  466. //
  467. D3D11_RASTERIZER_DESC rasterDesc;
  468. memset(&rasterDesc, 0, sizeof(rasterDesc));
  469. rasterDesc.AntialiasedLineEnable = false;
  470. rasterDesc.CullMode = D3D11_CULL_NONE;
  471. rasterDesc.DepthBias = 0;
  472. rasterDesc.DepthBiasClamp = 0.0f;
  473. rasterDesc.DepthClipEnable = true;
  474. rasterDesc.FillMode = D3D11_FILL_SOLID;
  475. rasterDesc.FrontCounterClockwise = false;
  476. rasterDesc.MultisampleEnable = false;
  477. rasterDesc.ScissorEnable = false;
  478. rasterDesc.SlopeScaledDepthBias = 0.0f;
  479. result = data->d3dDevice->CreateRasterizerState(&rasterDesc, &data->mainRasterizer);
  480. if (FAILED(result)) {
  481. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  482. return result;
  483. }
  484. //
  485. // Create blending states:
  486. //
  487. result = D3D11_CreateBlendMode(
  488. renderer,
  489. TRUE,
  490. D3D11_BLEND_SRC_ALPHA,
  491. D3D11_BLEND_INV_SRC_ALPHA,
  492. &data->blendModeBlend);
  493. if (FAILED(result)) {
  494. // D3D11_CreateBlendMode will set the SDL error, if it fails
  495. return result;
  496. }
  497. result = D3D11_CreateBlendMode(
  498. renderer,
  499. TRUE,
  500. D3D11_BLEND_SRC_ALPHA,
  501. D3D11_BLEND_ONE,
  502. &data->blendModeAdd);
  503. if (FAILED(result)) {
  504. // D3D11_CreateBlendMode will set the SDL error, if it fails
  505. return result;
  506. }
  507. result = D3D11_CreateBlendMode(
  508. renderer,
  509. TRUE,
  510. D3D11_BLEND_ZERO,
  511. D3D11_BLEND_SRC_COLOR,
  512. &data->blendModeMod);
  513. if (FAILED(result)) {
  514. // D3D11_CreateBlendMode will set the SDL error, if it fails
  515. return result;
  516. }
  517. //
  518. // All done!
  519. //
  520. return S_OK;
  521. }
  522. #ifdef __WINRT__
  523. static ABI::Windows::UI::Core::ICoreWindow *
  524. D3D11_GetCoreWindowFromSDLRenderer(SDL_Renderer * renderer)
  525. {
  526. SDL_Window * sdlWindow = renderer->window;
  527. if ( ! renderer->window ) {
  528. return nullptr;
  529. }
  530. SDL_SysWMinfo sdlWindowInfo;
  531. SDL_VERSION(&sdlWindowInfo.version);
  532. if ( ! SDL_GetWindowWMInfo(sdlWindow, &sdlWindowInfo) ) {
  533. return nullptr;
  534. }
  535. if (sdlWindowInfo.subsystem != SDL_SYSWM_WINRT) {
  536. return nullptr;
  537. }
  538. if ( ! sdlWindowInfo.info.winrt.window ) {
  539. return nullptr;
  540. }
  541. ABI::Windows::UI::Core::ICoreWindow * coreWindow = nullptr;
  542. if (FAILED(sdlWindowInfo.info.winrt.window->QueryInterface(&coreWindow))) {
  543. return nullptr;
  544. }
  545. return coreWindow;
  546. }
  547. // Method to convert a length in device-independent pixels (DIPs) to a length in physical pixels.
  548. static float
  549. D3D11_ConvertDipsToPixels(float dips)
  550. {
  551. static const float dipsPerInch = 96.0f;
  552. return floor(dips * DisplayProperties::LogicalDpi / dipsPerInch + 0.5f); // Round to nearest integer.
  553. }
  554. #endif
  555. #if WINAPI_FAMILY == WINAPI_FAMILY_APP
  556. // TODO, WinRT, XAML: get the ISwapChainBackgroundPanelNative from something other than a global var
  557. extern ISwapChainBackgroundPanelNative * WINRT_GlobalSwapChainBackgroundPanelNative;
  558. #endif
  559. static DXGI_MODE_ROTATION
  560. D3D11_GetRotationForOrientation(Windows::Graphics::Display::DisplayOrientations orientation)
  561. {
  562. switch (orientation)
  563. {
  564. #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
  565. //
  566. // Windows Phone rotations
  567. //
  568. case DisplayOrientations::Landscape:
  569. return DXGI_MODE_ROTATION_ROTATE90;
  570. case DisplayOrientations::Portrait:
  571. return DXGI_MODE_ROTATION_IDENTITY;
  572. case DisplayOrientations::LandscapeFlipped:
  573. return DXGI_MODE_ROTATION_ROTATE270;
  574. case DisplayOrientations::PortraitFlipped:
  575. return DXGI_MODE_ROTATION_ROTATE180;
  576. #else
  577. //
  578. // Non-Windows-Phone rotations (ex: Windows 8, Windows RT)
  579. //
  580. case DisplayOrientations::Landscape:
  581. return DXGI_MODE_ROTATION_IDENTITY;
  582. case DisplayOrientations::Portrait:
  583. return DXGI_MODE_ROTATION_ROTATE270;
  584. case DisplayOrientations::LandscapeFlipped:
  585. return DXGI_MODE_ROTATION_ROTATE180;
  586. case DisplayOrientations::PortraitFlipped:
  587. return DXGI_MODE_ROTATION_ROTATE90;
  588. #endif // WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
  589. default:
  590. return DXGI_MODE_ROTATION_UNSPECIFIED;
  591. }
  592. }
  593. // Initialize all resources that change when the window's size changes.
  594. // TODO, WinRT: get D3D11_CreateWindowSizeDependentResources working on Win32
  595. HRESULT
  596. D3D11_CreateWindowSizeDependentResources(SDL_Renderer * renderer)
  597. {
  598. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  599. HRESULT result = S_OK;
  600. ABI::Windows::UI::Core::ICoreWindow * coreWindow = D3D11_GetCoreWindowFromSDLRenderer(renderer);
  601. // Store the window bounds so the next time we get a SizeChanged event we can
  602. // avoid rebuilding everything if the size is identical.
  603. ABI::Windows::Foundation::Rect nativeWindowBounds;
  604. if (coreWindow) {
  605. result = coreWindow->get_Bounds(&nativeWindowBounds);
  606. if (FAILED(result)) {
  607. WIN_SetErrorFromHRESULT(__FUNCTION__", Get Window Bounds", result);
  608. return result;
  609. }
  610. } else {
  611. // TODO, WinRT, XAML: clean up window-bounds code in D3D11_CreateWindowSizeDependentResources
  612. SDL_DisplayMode displayMode;
  613. if (SDL_GetDesktopDisplayMode(0, &displayMode) < 0) {
  614. SDL_SetError(__FUNCTION__", Get Window Bounds (XAML): Unable to retrieve the native window's size");
  615. return E_FAIL;
  616. }
  617. nativeWindowBounds.Width = (FLOAT) displayMode.w;
  618. nativeWindowBounds.Height = (FLOAT) displayMode.h;
  619. }
  620. // TODO, WinRT, XAML: see if window/control sizes are in DIPs, or something else. If something else, then adjust renderer size tracking accordingly.
  621. data->windowSizeInDIPs.x = nativeWindowBounds.Width;
  622. data->windowSizeInDIPs.y = nativeWindowBounds.Height;
  623. // Calculate the necessary swap chain and render target size in pixels.
  624. float windowWidth = D3D11_ConvertDipsToPixels(data->windowSizeInDIPs.x);
  625. float windowHeight = D3D11_ConvertDipsToPixels(data->windowSizeInDIPs.y);
  626. // The width and height of the swap chain must be based on the window's
  627. // landscape-oriented width and height. If the window is in a portrait
  628. // orientation, the dimensions must be reversed.
  629. data->orientation = DisplayProperties::CurrentOrientation;
  630. #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
  631. const bool swapDimensions = false;
  632. #else
  633. const bool swapDimensions =
  634. data->orientation == DisplayOrientations::Portrait ||
  635. data->orientation == DisplayOrientations::PortraitFlipped;
  636. #endif
  637. data->renderTargetSize.x = swapDimensions ? windowHeight : windowWidth;
  638. data->renderTargetSize.y = swapDimensions ? windowWidth : windowHeight;
  639. if(data->swapChain != nullptr)
  640. {
  641. // If the swap chain already exists, resize it.
  642. result = data->swapChain->ResizeBuffers(
  643. 2, // Double-buffered swap chain.
  644. static_cast<UINT>(data->renderTargetSize.x),
  645. static_cast<UINT>(data->renderTargetSize.y),
  646. DXGI_FORMAT_B8G8R8A8_UNORM,
  647. 0
  648. );
  649. if (FAILED(result)) {
  650. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  651. return result;
  652. }
  653. }
  654. else
  655. {
  656. const bool usingXAML = (coreWindow == nullptr);
  657. // Otherwise, create a new one using the same adapter as the existing Direct3D device.
  658. DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
  659. swapChainDesc.Width = static_cast<UINT>(data->renderTargetSize.x); // Match the size of the window.
  660. swapChainDesc.Height = static_cast<UINT>(data->renderTargetSize.y);
  661. swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format.
  662. swapChainDesc.Stereo = false;
  663. swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
  664. swapChainDesc.SampleDesc.Quality = 0;
  665. swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  666. swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
  667. #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
  668. swapChainDesc.Scaling = DXGI_SCALING_STRETCH; // On phone, only stretch and aspect-ratio stretch scaling are allowed.
  669. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // On phone, no swap effects are supported.
  670. #else
  671. if (usingXAML) {
  672. swapChainDesc.Scaling = DXGI_SCALING_STRETCH;
  673. } else {
  674. swapChainDesc.Scaling = DXGI_SCALING_NONE;
  675. }
  676. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Store apps must use this SwapEffect.
  677. #endif
  678. swapChainDesc.Flags = 0;
  679. ComPtr<IDXGIDevice1> dxgiDevice;
  680. result = data->d3dDevice.As(&dxgiDevice);
  681. if (FAILED(result)) {
  682. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  683. return result;
  684. }
  685. ComPtr<IDXGIAdapter> dxgiAdapter;
  686. result = dxgiDevice->GetAdapter(&dxgiAdapter);
  687. if (FAILED(result)) {
  688. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  689. return result;
  690. }
  691. ComPtr<IDXGIFactory2> dxgiFactory;
  692. result = dxgiAdapter->GetParent(
  693. __uuidof(IDXGIFactory2),
  694. &dxgiFactory
  695. );
  696. if (FAILED(result)) {
  697. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  698. return result;
  699. }
  700. if (usingXAML) {
  701. result = dxgiFactory->CreateSwapChainForComposition(
  702. data->d3dDevice.Get(),
  703. &swapChainDesc,
  704. nullptr,
  705. &data->swapChain);
  706. if (FAILED(result)) {
  707. WIN_SetErrorFromHRESULT(__FUNCTION__ ", CreateSwapChainForComposition", result);
  708. return result;
  709. }
  710. #if WINAPI_FAMILY == WINAPI_FAMILY_APP
  711. result = WINRT_GlobalSwapChainBackgroundPanelNative->SetSwapChain(data->swapChain.Get());
  712. if (FAILED(result)) {
  713. WIN_SetErrorFromHRESULT(__FUNCTION__ ", ISwapChainBackgroundPanelNative::SetSwapChain", result);
  714. return result;
  715. }
  716. #else
  717. SDL_SetError(__FUNCTION__ ", XAML support is not yet available for Windows Phone");
  718. return E_FAIL;
  719. #endif
  720. } else {
  721. IUnknown * coreWindowAsIUnknown = nullptr;
  722. result = coreWindow->QueryInterface(&coreWindowAsIUnknown);
  723. if (FAILED(result)) {
  724. WIN_SetErrorFromHRESULT(__FUNCTION__ ", CoreWindow to IUnknown", result);
  725. return result;
  726. }
  727. result = dxgiFactory->CreateSwapChainForCoreWindow(
  728. data->d3dDevice.Get(),
  729. coreWindowAsIUnknown,
  730. &swapChainDesc,
  731. nullptr, // Allow on all displays.
  732. &data->swapChain
  733. );
  734. if (FAILED(result)) {
  735. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  736. return result;
  737. }
  738. }
  739. // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
  740. // ensures that the application will only render after each VSync, minimizing power consumption.
  741. result = dxgiDevice->SetMaximumFrameLatency(1);
  742. if (FAILED(result)) {
  743. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  744. return result;
  745. }
  746. }
  747. #if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
  748. // Set the proper orientation for the swap chain, and generate the
  749. // 3D matrix transformation for rendering to the rotated swap chain.
  750. //
  751. // To note, the call for this, IDXGISwapChain1::SetRotation, is not necessary
  752. // on Windows Phone, nor is it supported there. It's only needed in Windows 8/RT.
  753. DXGI_MODE_ROTATION rotation = D3D11_GetRotationForOrientation(data->orientation);
  754. result = data->swapChain->SetRotation(rotation);
  755. if (FAILED(result)) {
  756. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  757. return result;
  758. }
  759. #endif
  760. // Create a render target view of the swap chain back buffer.
  761. ComPtr<ID3D11Texture2D> backBuffer;
  762. result = data->swapChain->GetBuffer(
  763. 0,
  764. __uuidof(ID3D11Texture2D),
  765. &backBuffer
  766. );
  767. if (FAILED(result)) {
  768. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  769. return result;
  770. }
  771. result = data->d3dDevice->CreateRenderTargetView(
  772. backBuffer.Get(),
  773. nullptr,
  774. &data->mainRenderTargetView
  775. );
  776. if (FAILED(result)) {
  777. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  778. return result;
  779. }
  780. if (D3D11_UpdateViewport(renderer) != 0) {
  781. // D3D11_UpdateViewport will set the SDL error if it fails.
  782. return E_FAIL;
  783. }
  784. return S_OK;
  785. }
  786. // This method is called when the window's size changes.
  787. HRESULT
  788. D3D11_UpdateForWindowSizeChange(SDL_Renderer * renderer)
  789. {
  790. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  791. HRESULT result = S_OK;
  792. ABI::Windows::UI::Core::ICoreWindow * coreWindow = D3D11_GetCoreWindowFromSDLRenderer(renderer);
  793. ABI::Windows::Foundation::Rect coreWindowBounds;
  794. result = coreWindow->get_Bounds(&coreWindowBounds);
  795. if (FAILED(result)) {
  796. WIN_SetErrorFromHRESULT(__FUNCTION__ ", Get Window Bounds", result);
  797. return result;
  798. }
  799. if (coreWindowBounds.Width != data->windowSizeInDIPs.x ||
  800. coreWindowBounds.Height != data->windowSizeInDIPs.y ||
  801. data->orientation != DisplayProperties::CurrentOrientation)
  802. {
  803. ID3D11RenderTargetView* nullViews[] = {nullptr};
  804. data->d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
  805. data->mainRenderTargetView = nullptr;
  806. data->d3dContext->Flush();
  807. result = D3D11_CreateWindowSizeDependentResources(renderer);
  808. if (FAILED(result)) {
  809. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  810. return result;
  811. }
  812. }
  813. return S_OK;
  814. }
  815. HRESULT
  816. D3D11_HandleDeviceLost(SDL_Renderer * renderer)
  817. {
  818. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  819. HRESULT result = S_OK;
  820. // Reset these member variables to ensure that D3D11_UpdateForWindowSizeChange recreates all resources.
  821. data->windowSizeInDIPs.x = 0;
  822. data->windowSizeInDIPs.y = 0;
  823. data->swapChain = nullptr;
  824. result = D3D11_CreateDeviceResources(renderer);
  825. if (FAILED(result)) {
  826. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  827. return result;
  828. }
  829. result = D3D11_UpdateForWindowSizeChange(renderer);
  830. if (FAILED(result)) {
  831. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  832. return result;
  833. }
  834. return S_OK;
  835. }
  836. static void
  837. D3D11_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event)
  838. {
  839. //D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  840. if (event->event == SDL_WINDOWEVENT_SIZE_CHANGED) {
  841. D3D11_UpdateForWindowSizeChange(renderer);
  842. }
  843. }
  844. static D3D11_FILTER
  845. GetScaleQuality(void)
  846. {
  847. const char *hint = SDL_GetHint(SDL_HINT_RENDER_SCALE_QUALITY);
  848. if (!hint || *hint == '0' || SDL_strcasecmp(hint, "nearest") == 0) {
  849. return SDL_D3D11_NEAREST_PIXEL_FILTER;
  850. } else /* if (*hint == '1' || SDL_strcasecmp(hint, "linear") == 0) */ {
  851. return SDL_D3D11_LINEAR_FILTER;
  852. }
  853. }
  854. static int
  855. D3D11_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
  856. {
  857. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  858. D3D11_TextureData *textureData;
  859. HRESULT result;
  860. DXGI_FORMAT textureFormat = SDLPixelFormatToDXGIFormat(texture->format);
  861. if (textureFormat == SDL_PIXELFORMAT_UNKNOWN) {
  862. SDL_SetError("%s, An unsupported SDL pixel format (0x%x) was specified",
  863. __FUNCTION__, texture->format);
  864. return -1;
  865. }
  866. textureData = new D3D11_TextureData;
  867. if (!textureData) {
  868. SDL_OutOfMemory();
  869. return -1;
  870. }
  871. textureData->pixelFormat = SDL_AllocFormat(texture->format);
  872. textureData->lockedTexturePosition = XMINT2(0, 0);
  873. textureData->scaleMode = GetScaleQuality();
  874. texture->driverdata = textureData;
  875. D3D11_TEXTURE2D_DESC textureDesc = {0};
  876. textureDesc.Width = texture->w;
  877. textureDesc.Height = texture->h;
  878. textureDesc.MipLevels = 1;
  879. textureDesc.ArraySize = 1;
  880. textureDesc.Format = textureFormat;
  881. textureDesc.SampleDesc.Count = 1;
  882. textureDesc.SampleDesc.Quality = 0;
  883. textureDesc.MiscFlags = 0;
  884. if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
  885. textureDesc.Usage = D3D11_USAGE_DYNAMIC;
  886. textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  887. } else {
  888. textureDesc.Usage = D3D11_USAGE_DEFAULT;
  889. textureDesc.CPUAccessFlags = 0;
  890. }
  891. if (texture->access == SDL_TEXTUREACCESS_TARGET) {
  892. textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
  893. } else {
  894. textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  895. }
  896. #if 0
  897. // Fill the texture with a non-black color, for debugging purposes:
  898. const int numPixels = textureDesc.Width * textureDesc.Height;
  899. const int pixelSizeInBytes = textureData->pixelFormat->BytesPerPixel;
  900. std::vector<uint8> initialTexturePixels(numPixels * pixelSizeInBytes, 0x00);
  901. for (int i = 0; i < (numPixels * pixelSizeInBytes); i += pixelSizeInBytes) {
  902. initialTexturePixels[i+0] = 0xff;
  903. initialTexturePixels[i+1] = 0xff;
  904. initialTexturePixels[i+2] = 0x00;
  905. initialTexturePixels[i+3] = 0xff;
  906. }
  907. D3D11_SUBRESOURCE_DATA initialTextureData = {0};
  908. initialTextureData.pSysMem = (void *)&(initialTexturePixels[0]);
  909. initialTextureData.SysMemPitch = textureDesc.Width * pixelSizeInBytes;
  910. initialTextureData.SysMemSlicePitch = numPixels * pixelSizeInBytes;
  911. #endif
  912. result = rendererData->d3dDevice->CreateTexture2D(
  913. &textureDesc,
  914. NULL, // &initialTextureData,
  915. &textureData->mainTexture
  916. );
  917. if (FAILED(result)) {
  918. D3D11_DestroyTexture(renderer, texture);
  919. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  920. return -1;
  921. }
  922. if (texture->access & SDL_TEXTUREACCESS_TARGET) {
  923. D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
  924. renderTargetViewDesc.Format = textureDesc.Format;
  925. renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  926. renderTargetViewDesc.Texture2D.MipSlice = 0;
  927. result = rendererData->d3dDevice->CreateRenderTargetView(
  928. textureData->mainTexture.Get(),
  929. &renderTargetViewDesc,
  930. &textureData->mainTextureRenderTargetView);
  931. if (FAILED(result)) {
  932. D3D11_DestroyTexture(renderer, texture);
  933. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  934. return -1;
  935. }
  936. }
  937. D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
  938. resourceViewDesc.Format = textureDesc.Format;
  939. resourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  940. resourceViewDesc.Texture2D.MostDetailedMip = 0;
  941. resourceViewDesc.Texture2D.MipLevels = textureDesc.MipLevels;
  942. result = rendererData->d3dDevice->CreateShaderResourceView(
  943. textureData->mainTexture.Get(),
  944. &resourceViewDesc,
  945. &textureData->mainTextureResourceView
  946. );
  947. if (FAILED(result)) {
  948. D3D11_DestroyTexture(renderer, texture);
  949. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  950. return -1;
  951. }
  952. return 0;
  953. }
  954. static void
  955. D3D11_DestroyTexture(SDL_Renderer * renderer,
  956. SDL_Texture * texture)
  957. {
  958. D3D11_TextureData *textureData = (D3D11_TextureData *) texture->driverdata;
  959. if (textureData) {
  960. if (textureData->pixelFormat) {
  961. SDL_FreeFormat(textureData->pixelFormat);
  962. textureData->pixelFormat = NULL;
  963. }
  964. delete textureData;
  965. texture->driverdata = NULL;
  966. }
  967. }
  968. static int
  969. D3D11_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
  970. const SDL_Rect * rect, const void * srcPixels,
  971. int srcPitch)
  972. {
  973. // Lock the texture, retrieving a buffer to write pixel data to:
  974. void * destPixels = NULL;
  975. int destPitch = 0;
  976. if (D3D11_LockTexture(renderer, texture, rect, &destPixels, &destPitch) != 0) {
  977. // An error is already set. Attach some info to it, then return to
  978. // the caller.
  979. std::string errorMessage = string(__FUNCTION__ ", Lock Texture Failed: ") + SDL_GetError();
  980. SDL_SetError(errorMessage.c_str());
  981. return -1;
  982. }
  983. // Copy pixel data to the locked texture's memory:
  984. for (int y = 0; y < rect->h; ++y) {
  985. memcpy(
  986. ((Uint8 *)destPixels) + (destPitch * y),
  987. ((Uint8 *)srcPixels) + (srcPitch * y),
  988. srcPitch
  989. );
  990. }
  991. // Commit the texture's memory back to Direct3D:
  992. D3D11_UnlockTexture(renderer, texture);
  993. // Return to the caller:
  994. return 0;
  995. }
  996. static int
  997. D3D11_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture,
  998. const SDL_Rect * rect, void **pixels, int *pitch)
  999. {
  1000. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1001. D3D11_TextureData *textureData = (D3D11_TextureData *) texture->driverdata;
  1002. HRESULT result = S_OK;
  1003. if (textureData->stagingTexture) {
  1004. SDL_SetError("texture is already locked");
  1005. return -1;
  1006. }
  1007. // Create a 'staging' texture, which will be used to write to a portion
  1008. // of the main texture. This is necessary, as Direct3D 11.1 does not
  1009. // have the ability to write a CPU-bound pixel buffer to a rectangular
  1010. // subrect of a texture. Direct3D 11.1 can, however, write a pixel
  1011. // buffer to an entire texture, hence the use of a staging texture.
  1012. D3D11_TEXTURE2D_DESC stagingTextureDesc;
  1013. textureData->mainTexture->GetDesc(&stagingTextureDesc);
  1014. stagingTextureDesc.Width = rect->w;
  1015. stagingTextureDesc.Height = rect->h;
  1016. stagingTextureDesc.BindFlags = 0;
  1017. stagingTextureDesc.MiscFlags = 0;
  1018. stagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  1019. stagingTextureDesc.Usage = D3D11_USAGE_STAGING;
  1020. result = rendererData->d3dDevice->CreateTexture2D(
  1021. &stagingTextureDesc,
  1022. NULL,
  1023. &textureData->stagingTexture);
  1024. if (FAILED(result)) {
  1025. WIN_SetErrorFromHRESULT(__FUNCTION__ ", Create Staging Texture", result);
  1026. return -1;
  1027. }
  1028. // Get a write-only pointer to data in the staging texture:
  1029. D3D11_MAPPED_SUBRESOURCE textureMemory = {0};
  1030. result = rendererData->d3dContext->Map(
  1031. textureData->stagingTexture.Get(),
  1032. D3D11CalcSubresource(0, 0, 0),
  1033. D3D11_MAP_WRITE,
  1034. 0,
  1035. &textureMemory
  1036. );
  1037. if (FAILED(result)) {
  1038. WIN_SetErrorFromHRESULT(__FUNCTION__ ", Map Staging Texture", result);
  1039. textureData->stagingTexture = nullptr;
  1040. return -1;
  1041. }
  1042. // Make note of where the staging texture will be written to (on a
  1043. // call to SDL_UnlockTexture):
  1044. textureData->lockedTexturePosition = XMINT2(rect->x, rect->y);
  1045. // Make sure the caller has information on the texture's pixel buffer,
  1046. // then return:
  1047. *pixels = textureMemory.pData;
  1048. *pitch = textureMemory.RowPitch;
  1049. return 0;
  1050. }
  1051. static void
  1052. D3D11_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture)
  1053. {
  1054. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1055. D3D11_TextureData *textureData = (D3D11_TextureData *) texture->driverdata;
  1056. // Commit the pixel buffer's changes back to the staging texture:
  1057. rendererData->d3dContext->Unmap(
  1058. textureData->stagingTexture.Get(),
  1059. 0);
  1060. // Copy the staging texture's contents back to the main texture:
  1061. rendererData->d3dContext->CopySubresourceRegion(
  1062. textureData->mainTexture.Get(),
  1063. D3D11CalcSubresource(0, 0, 0),
  1064. textureData->lockedTexturePosition.x,
  1065. textureData->lockedTexturePosition.y,
  1066. 0,
  1067. textureData->stagingTexture.Get(),
  1068. D3D11CalcSubresource(0, 0, 0),
  1069. NULL);
  1070. // Clean up and return:
  1071. textureData->stagingTexture = nullptr;
  1072. textureData->lockedTexturePosition = XMINT2(0, 0);
  1073. }
  1074. static int
  1075. D3D11_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture)
  1076. {
  1077. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1078. if (texture == NULL) {
  1079. rendererData->currentOffscreenRenderTargetView = nullptr;
  1080. return 0;
  1081. }
  1082. D3D11_TextureData *textureData = (D3D11_TextureData *) texture->driverdata;
  1083. if (!textureData->mainTextureRenderTargetView) {
  1084. std::string errorMessage = string(__FUNCTION__) + ": specified texture is not a render target";
  1085. SDL_SetError(errorMessage.c_str());
  1086. return -1;
  1087. }
  1088. rendererData->currentOffscreenRenderTargetView = textureData->mainTextureRenderTargetView;
  1089. return 0;
  1090. }
  1091. static int
  1092. D3D11_UpdateViewport(SDL_Renderer * renderer)
  1093. {
  1094. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  1095. if (renderer->viewport.w == 0 || renderer->viewport.h == 0) {
  1096. // If the viewport is empty, assume that it is because
  1097. // SDL_CreateRenderer is calling it, and will call it again later
  1098. // with a non-empty viewport.
  1099. return 0;
  1100. }
  1101. // Make sure the SDL viewport gets rotated to that of the physical display's orientation.
  1102. // Keep in mind here that the Y-axis will be been inverted (from Direct3D's
  1103. // default coordinate system) so rotations will be done in the opposite
  1104. // direction of the DXGI_MODE_ROTATION enumeration.
  1105. switch (D3D11_GetRotationForOrientation(data->orientation))
  1106. {
  1107. case DXGI_MODE_ROTATION_IDENTITY:
  1108. XMStoreFloat4x4(&data->vertexShaderConstantsData.projection, XMMatrixIdentity());
  1109. break;
  1110. case DXGI_MODE_ROTATION_ROTATE270:
  1111. XMStoreFloat4x4(&data->vertexShaderConstantsData.projection, XMMatrixRotationZ(XM_PIDIV2));
  1112. break;
  1113. case DXGI_MODE_ROTATION_ROTATE180:
  1114. XMStoreFloat4x4(&data->vertexShaderConstantsData.projection, XMMatrixRotationZ(XM_PI));
  1115. break;
  1116. case DXGI_MODE_ROTATION_ROTATE90:
  1117. XMStoreFloat4x4(&data->vertexShaderConstantsData.projection, XMMatrixRotationZ(-XM_PIDIV2));
  1118. break;
  1119. default:
  1120. SDL_SetError("An unknown DisplayOrientation is being used");
  1121. return -1;
  1122. }
  1123. //
  1124. // Update the view matrix
  1125. //
  1126. float viewportWidth = (float) renderer->viewport.w;
  1127. float viewportHeight = (float) renderer->viewport.h;
  1128. XMStoreFloat4x4(&data->vertexShaderConstantsData.view,
  1129. XMMatrixMultiply(
  1130. XMMatrixScaling(2.0f / viewportWidth, 2.0f / viewportHeight, 1.0f),
  1131. XMMatrixMultiply(
  1132. XMMatrixTranslation(-1, -1, 0),
  1133. XMMatrixRotationX(XM_PI)
  1134. )));
  1135. #if 0
  1136. data->vertexShaderConstantsData.view = XMMatrixIdentity();
  1137. #endif
  1138. //
  1139. // Reset the model matrix
  1140. //
  1141. XMStoreFloat4x4(&data->vertexShaderConstantsData.model, XMMatrixIdentity());
  1142. //
  1143. // Update the Direct3D viewport, which seems to be aligned to the
  1144. // swap buffer's coordinate space, which is always in either
  1145. // a landscape mode, for all Windows 8/RT devices, or a portrait mode,
  1146. // for Windows Phone devices.
  1147. //
  1148. SDL_FRect orientationAlignedViewport;
  1149. #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
  1150. const bool swapDimensions =
  1151. data->orientation == DisplayOrientations::Landscape ||
  1152. data->orientation == DisplayOrientations::LandscapeFlipped;
  1153. #else
  1154. const bool swapDimensions =
  1155. data->orientation == DisplayOrientations::Portrait ||
  1156. data->orientation == DisplayOrientations::PortraitFlipped;
  1157. #endif
  1158. if (swapDimensions) {
  1159. orientationAlignedViewport.x = (float) renderer->viewport.y;
  1160. orientationAlignedViewport.y = (float) renderer->viewport.x;
  1161. orientationAlignedViewport.w = (float) renderer->viewport.h;
  1162. orientationAlignedViewport.h = (float) renderer->viewport.w;
  1163. } else {
  1164. orientationAlignedViewport.x = (float) renderer->viewport.x;
  1165. orientationAlignedViewport.y = (float) renderer->viewport.y;
  1166. orientationAlignedViewport.w = (float) renderer->viewport.w;
  1167. orientationAlignedViewport.h = (float) renderer->viewport.h;
  1168. }
  1169. // TODO, WinRT: get custom viewports working with non-Landscape modes (Portrait, PortraitFlipped, and LandscapeFlipped)
  1170. D3D11_VIEWPORT viewport;
  1171. memset(&viewport, 0, sizeof(viewport));
  1172. viewport.TopLeftX = orientationAlignedViewport.x;
  1173. viewport.TopLeftY = orientationAlignedViewport.y;
  1174. viewport.Width = orientationAlignedViewport.w;
  1175. viewport.Height = orientationAlignedViewport.h;
  1176. viewport.MinDepth = 0.0f;
  1177. viewport.MaxDepth = 1.0f;
  1178. data->d3dContext->RSSetViewports(1, &viewport);
  1179. #if 0
  1180. SDL_Log("%s, oav={%.0f,%.0f,%.0f,%.0f}, rend={%.0f,%.0f}\n",
  1181. __FUNCTION__,
  1182. orientationAlignedViewport.x,
  1183. orientationAlignedViewport.y,
  1184. orientationAlignedViewport.w,
  1185. orientationAlignedViewport.h,
  1186. data->renderTargetSize.x,
  1187. data->renderTargetSize.y);
  1188. #endif
  1189. return 0;
  1190. }
  1191. static int
  1192. D3D11_UpdateClipRect(SDL_Renderer * renderer)
  1193. {
  1194. // TODO, WinRT: implement D3D11_UpdateClipRect
  1195. return 0;
  1196. }
  1197. static ComPtr<ID3D11RenderTargetView> &
  1198. D3D11_GetCurrentRenderTargetView(SDL_Renderer * renderer)
  1199. {
  1200. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  1201. if (data->currentOffscreenRenderTargetView) {
  1202. return data->currentOffscreenRenderTargetView;
  1203. } else {
  1204. return data->mainRenderTargetView;
  1205. }
  1206. }
  1207. static int
  1208. D3D11_RenderClear(SDL_Renderer * renderer)
  1209. {
  1210. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  1211. const float colorRGBA[] = {
  1212. (renderer->r / 255.0f),
  1213. (renderer->g / 255.0f),
  1214. (renderer->b / 255.0f),
  1215. (renderer->a / 255.0f)
  1216. };
  1217. data->d3dContext->ClearRenderTargetView(
  1218. D3D11_GetCurrentRenderTargetView(renderer).Get(),
  1219. colorRGBA
  1220. );
  1221. return 0;
  1222. }
  1223. static int
  1224. D3D11_UpdateVertexBuffer(SDL_Renderer *renderer,
  1225. const void * vertexData, unsigned int dataSizeInBytes)
  1226. {
  1227. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1228. HRESULT result = S_OK;
  1229. D3D11_BUFFER_DESC vertexBufferDesc;
  1230. if (rendererData->vertexBuffer) {
  1231. rendererData->vertexBuffer->GetDesc(&vertexBufferDesc);
  1232. } else {
  1233. memset(&vertexBufferDesc, 0, sizeof(vertexBufferDesc));
  1234. }
  1235. if (vertexBufferDesc.ByteWidth >= dataSizeInBytes) {
  1236. rendererData->d3dContext->UpdateSubresource(rendererData->vertexBuffer.Get(), 0, NULL, vertexData, dataSizeInBytes, 0);
  1237. } else {
  1238. vertexBufferDesc.ByteWidth = dataSizeInBytes;
  1239. vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  1240. D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
  1241. vertexBufferData.pSysMem = vertexData;
  1242. vertexBufferData.SysMemPitch = 0;
  1243. vertexBufferData.SysMemSlicePitch = 0;
  1244. result = rendererData->d3dDevice->CreateBuffer(
  1245. &vertexBufferDesc,
  1246. &vertexBufferData,
  1247. &rendererData->vertexBuffer
  1248. );
  1249. if (FAILED(result)) {
  1250. WIN_SetErrorFromHRESULT(__FUNCTION__, result);
  1251. return -1;
  1252. }
  1253. }
  1254. UINT stride = sizeof(VertexPositionColor);
  1255. UINT offset = 0;
  1256. rendererData->d3dContext->IASetVertexBuffers(
  1257. 0,
  1258. 1,
  1259. rendererData->vertexBuffer.GetAddressOf(),
  1260. &stride,
  1261. &offset
  1262. );
  1263. return 0;
  1264. }
  1265. static void
  1266. D3D11_RenderStartDrawOp(SDL_Renderer * renderer)
  1267. {
  1268. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1269. rendererData->d3dContext->OMSetRenderTargets(
  1270. 1,
  1271. D3D11_GetCurrentRenderTargetView(renderer).GetAddressOf(),
  1272. nullptr
  1273. );
  1274. }
  1275. static void
  1276. D3D11_RenderSetBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode)
  1277. {
  1278. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1279. switch (blendMode) {
  1280. case SDL_BLENDMODE_BLEND:
  1281. rendererData->d3dContext->OMSetBlendState(rendererData->blendModeBlend.Get(), 0, 0xFFFFFFFF);
  1282. break;
  1283. case SDL_BLENDMODE_ADD:
  1284. rendererData->d3dContext->OMSetBlendState(rendererData->blendModeAdd.Get(), 0, 0xFFFFFFFF);
  1285. break;
  1286. case SDL_BLENDMODE_MOD:
  1287. rendererData->d3dContext->OMSetBlendState(rendererData->blendModeMod.Get(), 0, 0xFFFFFFFF);
  1288. break;
  1289. case SDL_BLENDMODE_NONE:
  1290. rendererData->d3dContext->OMSetBlendState(NULL, 0, 0xFFFFFFFF);
  1291. break;
  1292. }
  1293. }
  1294. static void
  1295. D3D11_SetPixelShader(SDL_Renderer * renderer,
  1296. ID3D11PixelShader * shader,
  1297. ID3D11ShaderResourceView * shaderResource,
  1298. ID3D11SamplerState * sampler)
  1299. {
  1300. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1301. rendererData->d3dContext->PSSetShader(shader, nullptr, 0);
  1302. rendererData->d3dContext->PSSetShaderResources(0, 1, &shaderResource);
  1303. rendererData->d3dContext->PSSetSamplers(0, 1, &sampler);
  1304. }
  1305. static void
  1306. D3D11_RenderFinishDrawOp(SDL_Renderer * renderer,
  1307. D3D11_PRIMITIVE_TOPOLOGY primitiveTopology,
  1308. UINT vertexCount)
  1309. {
  1310. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1311. rendererData->d3dContext->UpdateSubresource(
  1312. rendererData->vertexShaderConstants.Get(),
  1313. 0,
  1314. NULL,
  1315. &rendererData->vertexShaderConstantsData,
  1316. 0,
  1317. 0
  1318. );
  1319. rendererData->d3dContext->IASetPrimitiveTopology(primitiveTopology);
  1320. rendererData->d3dContext->IASetInputLayout(rendererData->inputLayout.Get());
  1321. rendererData->d3dContext->VSSetShader(rendererData->vertexShader.Get(), nullptr, 0);
  1322. rendererData->d3dContext->VSSetConstantBuffers(0, 1, rendererData->vertexShaderConstants.GetAddressOf());
  1323. rendererData->d3dContext->RSSetState(rendererData->mainRasterizer.Get());
  1324. rendererData->d3dContext->Draw(vertexCount, 0);
  1325. }
  1326. static int
  1327. D3D11_RenderDrawPoints(SDL_Renderer * renderer,
  1328. const SDL_FPoint * points, int count)
  1329. {
  1330. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1331. float r, g, b, a;
  1332. r = (float)(renderer->r / 255.0f);
  1333. g = (float)(renderer->g / 255.0f);
  1334. b = (float)(renderer->b / 255.0f);
  1335. a = (float)(renderer->a / 255.0f);
  1336. VertexPositionColor * vertices = SDL_stack_alloc(VertexPositionColor, count);
  1337. for (int i = 0; i < min(count, 128); ++i) {
  1338. const VertexPositionColor v = {XMFLOAT3(points[i].x, points[i].y, 0.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT4(r, g, b, a)};
  1339. vertices[i] = v;
  1340. }
  1341. D3D11_RenderStartDrawOp(renderer);
  1342. D3D11_RenderSetBlendMode(renderer, renderer->blendMode);
  1343. if (D3D11_UpdateVertexBuffer(renderer, vertices, (unsigned int)count * sizeof(VertexPositionColor)) != 0) {
  1344. SDL_stack_free(vertices);
  1345. return -1;
  1346. }
  1347. D3D11_SetPixelShader(
  1348. renderer,
  1349. rendererData->colorPixelShader.Get(),
  1350. nullptr,
  1351. nullptr);
  1352. D3D11_RenderFinishDrawOp(renderer, D3D11_PRIMITIVE_TOPOLOGY_POINTLIST, count);
  1353. SDL_stack_free(vertices);
  1354. return 0;
  1355. }
  1356. static int
  1357. D3D11_RenderDrawLines(SDL_Renderer * renderer,
  1358. const SDL_FPoint * points, int count)
  1359. {
  1360. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1361. float r, g, b, a;
  1362. r = (float)(renderer->r / 255.0f);
  1363. g = (float)(renderer->g / 255.0f);
  1364. b = (float)(renderer->b / 255.0f);
  1365. a = (float)(renderer->a / 255.0f);
  1366. VertexPositionColor * vertices = SDL_stack_alloc(VertexPositionColor, count);
  1367. for (int i = 0; i < count; ++i) {
  1368. const VertexPositionColor v = {XMFLOAT3(points[i].x, points[i].y, 0.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT4(r, g, b, a)};
  1369. vertices[i] = v;
  1370. }
  1371. D3D11_RenderStartDrawOp(renderer);
  1372. D3D11_RenderSetBlendMode(renderer, renderer->blendMode);
  1373. if (D3D11_UpdateVertexBuffer(renderer, vertices, (unsigned int)count * sizeof(VertexPositionColor)) != 0) {
  1374. SDL_stack_free(vertices);
  1375. return -1;
  1376. }
  1377. D3D11_SetPixelShader(
  1378. renderer,
  1379. rendererData->colorPixelShader.Get(),
  1380. nullptr,
  1381. nullptr);
  1382. D3D11_RenderFinishDrawOp(renderer, D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP, count);
  1383. SDL_stack_free(vertices);
  1384. return 0;
  1385. }
  1386. static int
  1387. D3D11_RenderFillRects(SDL_Renderer * renderer,
  1388. const SDL_FRect * rects, int count)
  1389. {
  1390. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1391. float r, g, b, a;
  1392. r = (float)(renderer->r / 255.0f);
  1393. g = (float)(renderer->g / 255.0f);
  1394. b = (float)(renderer->b / 255.0f);
  1395. a = (float)(renderer->a / 255.0f);
  1396. #if 0
  1397. // Set up a test pattern:
  1398. SDL_FRect _rects[] = {
  1399. {-1.1f, 1.1f, 1.1f, -1.1f},
  1400. {-1.0f, 1.0f, 1.0f, -1.0f}, // red
  1401. {0.0f, 1.0f, 1.0f, -1.0f}, // green
  1402. {-1.0f, 0.0f, 1.0f, -1.0f}, // blue
  1403. {0.0f, 0.0f, 1.0f, -1.0f} // white
  1404. };
  1405. count = sizeof(_rects) / sizeof(SDL_FRect);
  1406. #define rects _rects
  1407. #endif
  1408. for (int i = 0; i < count; ++i) {
  1409. D3D11_RenderStartDrawOp(renderer);
  1410. D3D11_RenderSetBlendMode(renderer, renderer->blendMode);
  1411. #if 0
  1412. // Set colors for the test pattern:
  1413. a = 1.0f;
  1414. switch (i) {
  1415. case 0: r = 1.0f; g = 1.0f; b = 0.0f; break;
  1416. case 1: r = 1.0f; g = 0.0f; b = 0.0f; break;
  1417. case 2: r = 0.0f; g = 1.0f; b = 0.0f; break;
  1418. case 3: r = 0.0f; g = 0.0f; b = 1.0f; break;
  1419. case 4: r = 1.0f; g = 1.0f; b = 1.0f; break;
  1420. }
  1421. #endif
  1422. VertexPositionColor vertices[] = {
  1423. {XMFLOAT3(rects[i].x, rects[i].y, 0.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT4(r, g, b, a)},
  1424. {XMFLOAT3(rects[i].x, rects[i].y + rects[i].h, 0.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT4(r, g, b, a)},
  1425. {XMFLOAT3(rects[i].x + rects[i].w, rects[i].y, 0.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT4(r, g, b, a)},
  1426. {XMFLOAT3(rects[i].x + rects[i].w, rects[i].y + rects[i].h, 0.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT4(r, g, b, a)},
  1427. };
  1428. if (D3D11_UpdateVertexBuffer(renderer, vertices, sizeof(vertices)) != 0) {
  1429. return -1;
  1430. }
  1431. D3D11_SetPixelShader(
  1432. renderer,
  1433. rendererData->colorPixelShader.Get(),
  1434. nullptr,
  1435. nullptr);
  1436. D3D11_RenderFinishDrawOp(renderer, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, sizeof(vertices) / sizeof(VertexPositionColor));
  1437. }
  1438. return 0;
  1439. }
  1440. static ID3D11SamplerState *
  1441. D3D11_RenderGetSampler(SDL_Renderer * renderer, SDL_Texture * texture)
  1442. {
  1443. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1444. D3D11_TextureData *textureData = (D3D11_TextureData *) texture->driverdata;
  1445. switch (textureData->scaleMode) {
  1446. case SDL_D3D11_NEAREST_PIXEL_FILTER:
  1447. return rendererData->nearestPixelSampler.Get();
  1448. case SDL_D3D11_LINEAR_FILTER:
  1449. return rendererData->linearSampler.Get();
  1450. default:
  1451. return NULL;
  1452. }
  1453. }
  1454. static int
  1455. D3D11_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture,
  1456. const SDL_Rect * srcrect, const SDL_FRect * dstrect)
  1457. {
  1458. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1459. D3D11_TextureData *textureData = (D3D11_TextureData *) texture->driverdata;
  1460. D3D11_RenderStartDrawOp(renderer);
  1461. D3D11_RenderSetBlendMode(renderer, texture->blendMode);
  1462. float minu = (float) srcrect->x / texture->w;
  1463. float maxu = (float) (srcrect->x + srcrect->w) / texture->w;
  1464. float minv = (float) srcrect->y / texture->h;
  1465. float maxv = (float) (srcrect->y + srcrect->h) / texture->h;
  1466. float r = 1.0f;
  1467. float g = 1.0f;
  1468. float b = 1.0f;
  1469. float a = 1.0f;
  1470. if (texture->modMode & SDL_TEXTUREMODULATE_COLOR) {
  1471. r = (float)(texture->r / 255.0f);
  1472. g = (float)(texture->g / 255.0f);
  1473. b = (float)(texture->b / 255.0f);
  1474. }
  1475. if (texture->modMode & SDL_TEXTUREMODULATE_ALPHA) {
  1476. a = (float)(texture->a / 255.0f);
  1477. }
  1478. VertexPositionColor vertices[] = {
  1479. {XMFLOAT3(dstrect->x, dstrect->y, 0.0f), XMFLOAT2(minu, minv), XMFLOAT4(r, g, b, a)},
  1480. {XMFLOAT3(dstrect->x, dstrect->y + dstrect->h, 0.0f), XMFLOAT2(minu, maxv), XMFLOAT4(r, g, b, a)},
  1481. {XMFLOAT3(dstrect->x + dstrect->w, dstrect->y, 0.0f), XMFLOAT2(maxu, minv), XMFLOAT4(r, g, b, a)},
  1482. {XMFLOAT3(dstrect->x + dstrect->w, dstrect->y + dstrect->h, 0.0f), XMFLOAT2(maxu, maxv), XMFLOAT4(r, g, b, a)},
  1483. };
  1484. if (D3D11_UpdateVertexBuffer(renderer, vertices, sizeof(vertices)) != 0) {
  1485. return -1;
  1486. }
  1487. ID3D11SamplerState *textureSampler = D3D11_RenderGetSampler(renderer, texture);
  1488. D3D11_SetPixelShader(
  1489. renderer,
  1490. rendererData->texturePixelShader.Get(),
  1491. textureData->mainTextureResourceView.Get(),
  1492. textureSampler);
  1493. D3D11_RenderFinishDrawOp(renderer, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, sizeof(vertices) / sizeof(VertexPositionColor));
  1494. return 0;
  1495. }
  1496. static int
  1497. D3D11_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
  1498. const SDL_Rect * srcrect, const SDL_FRect * dstrect,
  1499. const double angle, const SDL_FPoint * center, const SDL_RendererFlip flip)
  1500. {
  1501. D3D11_RenderData *rendererData = (D3D11_RenderData *) renderer->driverdata;
  1502. D3D11_TextureData *textureData = (D3D11_TextureData *) texture->driverdata;
  1503. D3D11_RenderStartDrawOp(renderer);
  1504. D3D11_RenderSetBlendMode(renderer, texture->blendMode);
  1505. float minu = (float) srcrect->x / texture->w;
  1506. float maxu = (float) (srcrect->x + srcrect->w) / texture->w;
  1507. float minv = (float) srcrect->y / texture->h;
  1508. float maxv = (float) (srcrect->y + srcrect->h) / texture->h;
  1509. float r = 1.0f;
  1510. float g = 1.0f;
  1511. float b = 1.0f;
  1512. float a = 1.0f;
  1513. if (texture->modMode & SDL_TEXTUREMODULATE_COLOR) {
  1514. r = (float)(texture->r / 255.0f);
  1515. g = (float)(texture->g / 255.0f);
  1516. b = (float)(texture->b / 255.0f);
  1517. }
  1518. if (texture->modMode & SDL_TEXTUREMODULATE_ALPHA) {
  1519. a = (float)(texture->a / 255.0f);
  1520. }
  1521. if (flip & SDL_FLIP_HORIZONTAL) {
  1522. float tmp = maxu;
  1523. maxu = minu;
  1524. minu = tmp;
  1525. }
  1526. if (flip & SDL_FLIP_VERTICAL) {
  1527. float tmp = maxv;
  1528. maxv = minv;
  1529. minv = tmp;
  1530. }
  1531. XMFLOAT4X4 oldModelMatrix = rendererData->vertexShaderConstantsData.model;
  1532. XMStoreFloat4x4(
  1533. &rendererData->vertexShaderConstantsData.model,
  1534. XMMatrixMultiply(
  1535. XMMatrixRotationZ((float)(XM_PI * (float) angle / 180.0f)),
  1536. XMMatrixTranslation(dstrect->x + center->x, dstrect->y + center->y, 0)
  1537. ));
  1538. const float minx = -center->x;
  1539. const float maxx = dstrect->w - center->x;
  1540. const float miny = -center->y;
  1541. const float maxy = dstrect->h - center->y;
  1542. VertexPositionColor vertices[] = {
  1543. {XMFLOAT3(minx, miny, 0.0f), XMFLOAT2(minu, minv), XMFLOAT4(r, g, b, a)},
  1544. {XMFLOAT3(minx, maxy, 0.0f), XMFLOAT2(minu, maxv), XMFLOAT4(r, g, b, a)},
  1545. {XMFLOAT3(maxx, miny, 0.0f), XMFLOAT2(maxu, minv), XMFLOAT4(r, g, b, a)},
  1546. {XMFLOAT3(maxx, maxy, 0.0f), XMFLOAT2(maxu, maxv), XMFLOAT4(r, g, b, a)},
  1547. };
  1548. if (D3D11_UpdateVertexBuffer(renderer, vertices, sizeof(vertices)) != 0) {
  1549. return -1;
  1550. }
  1551. ID3D11SamplerState *textureSampler = D3D11_RenderGetSampler(renderer, texture);
  1552. D3D11_SetPixelShader(
  1553. renderer,
  1554. rendererData->texturePixelShader.Get(),
  1555. textureData->mainTextureResourceView.Get(),
  1556. textureSampler);
  1557. D3D11_RenderFinishDrawOp(renderer, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, sizeof(vertices) / sizeof(VertexPositionColor));
  1558. rendererData->vertexShaderConstantsData.model = oldModelMatrix;
  1559. return 0;
  1560. }
  1561. static int
  1562. D3D11_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
  1563. Uint32 format, void * pixels, int pitch)
  1564. {
  1565. D3D11_RenderData * data = (D3D11_RenderData *) renderer->driverdata;
  1566. HRESULT result = S_OK;
  1567. // Retrieve a pointer to the back buffer:
  1568. ComPtr<ID3D11Texture2D> backBuffer;
  1569. result = data->swapChain->GetBuffer(
  1570. 0,
  1571. __uuidof(ID3D11Texture2D),
  1572. &backBuffer
  1573. );
  1574. if (FAILED(result)) {
  1575. WIN_SetErrorFromHRESULT(__FUNCTION__ ", Get Back Buffer", result);
  1576. return -1;
  1577. }
  1578. // Create a staging texture to copy the screen's data to:
  1579. ComPtr<ID3D11Texture2D> stagingTexture;
  1580. D3D11_TEXTURE2D_DESC stagingTextureDesc;
  1581. backBuffer->GetDesc(&stagingTextureDesc);
  1582. stagingTextureDesc.Width = rect->w;
  1583. stagingTextureDesc.Height = rect->h;
  1584. stagingTextureDesc.BindFlags = 0;
  1585. stagingTextureDesc.MiscFlags = 0;
  1586. stagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  1587. stagingTextureDesc.Usage = D3D11_USAGE_STAGING;
  1588. result = data->d3dDevice->CreateTexture2D(
  1589. &stagingTextureDesc,
  1590. NULL,
  1591. &stagingTexture);
  1592. if (FAILED(result)) {
  1593. WIN_SetErrorFromHRESULT(__FUNCTION__ ", Create Staging Texture", result);
  1594. return -1;
  1595. }
  1596. // Copy the desired portion of the back buffer to the staging texture:
  1597. D3D11_BOX srcBox;
  1598. switch (D3D11_GetRotationForOrientation(data->orientation)) {
  1599. case DXGI_MODE_ROTATION_IDENTITY:
  1600. srcBox.left = rect->x;
  1601. srcBox.right = rect->x + rect->w;
  1602. srcBox.top = rect->y;
  1603. srcBox.bottom = rect->y + rect->h;
  1604. break;
  1605. case DXGI_MODE_ROTATION_ROTATE270:
  1606. srcBox.left = rect->y;
  1607. srcBox.right = rect->y + rect->h;
  1608. srcBox.top = renderer->viewport.w - rect->x - rect->w;
  1609. srcBox.bottom = renderer->viewport.w - rect->x;
  1610. break;
  1611. case DXGI_MODE_ROTATION_ROTATE180:
  1612. srcBox.left = renderer->viewport.w - rect->x - rect->w;
  1613. srcBox.right = renderer->viewport.w - rect->x;
  1614. srcBox.top = renderer->viewport.h - rect->y - rect->h;
  1615. srcBox.bottom = renderer->viewport.h - rect->y;
  1616. break;
  1617. case DXGI_MODE_ROTATION_ROTATE90:
  1618. srcBox.left = renderer->viewport.h - rect->y - rect->h;
  1619. srcBox.right = renderer->viewport.h - rect->y;
  1620. srcBox.top = rect->x;
  1621. srcBox.bottom = rect->x + rect->h;
  1622. break;
  1623. default:
  1624. return SDL_SetError("The physical display is in an unknown or unsupported orientation");
  1625. }
  1626. srcBox.front = 0;
  1627. srcBox.back = 1;
  1628. data->d3dContext->CopySubresourceRegion(
  1629. stagingTexture.Get(),
  1630. D3D11CalcSubresource(0, 0, 0),
  1631. 0, 0, 0,
  1632. backBuffer.Get(),
  1633. D3D11CalcSubresource(0, 0, 0),
  1634. &srcBox);
  1635. // Map the staging texture's data to CPU-accessible memory:
  1636. D3D11_MAPPED_SUBRESOURCE textureMemory = {0};
  1637. result = data->d3dContext->Map(
  1638. stagingTexture.Get(),
  1639. D3D11CalcSubresource(0, 0, 0),
  1640. D3D11_MAP_READ,
  1641. 0,
  1642. &textureMemory);
  1643. if (FAILED(result)) {
  1644. WIN_SetErrorFromHRESULT(__FUNCTION__ ", Map Staging Texture to CPU Memory", result);
  1645. return -1;
  1646. }
  1647. // Copy the data into the desired buffer, converting pixels to the
  1648. // desired format at the same time:
  1649. if (SDL_ConvertPixels(
  1650. rect->w, rect->h,
  1651. DXGIFormatToSDLPixelFormat(stagingTextureDesc.Format),
  1652. textureMemory.pData,
  1653. textureMemory.RowPitch,
  1654. format,
  1655. pixels,
  1656. pitch) != 0)
  1657. {
  1658. // When SDL_ConvertPixels fails, it'll have already set the format.
  1659. // Get the error message, and attach some extra data to it.
  1660. std::string errorMessage = string(__FUNCTION__ ", Convert Pixels failed: ") + SDL_GetError();
  1661. SDL_SetError(errorMessage.c_str());
  1662. return -1;
  1663. }
  1664. // Unmap the texture:
  1665. data->d3dContext->Unmap(
  1666. stagingTexture.Get(),
  1667. D3D11CalcSubresource(0, 0, 0));
  1668. // All done. The staging texture will be cleaned up in it's container
  1669. // ComPtr<>'s destructor.
  1670. return 0;
  1671. }
  1672. static void
  1673. D3D11_RenderPresent(SDL_Renderer * renderer)
  1674. {
  1675. D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
  1676. #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
  1677. // The first argument instructs DXGI to block until VSync, putting the application
  1678. // to sleep until the next VSync. This ensures we don't waste any cycles rendering
  1679. // frames that will never be displayed to the screen.
  1680. HRESULT hr = data->swapChain->Present(1, 0);
  1681. #else
  1682. // The application may optionally specify "dirty" or "scroll"
  1683. // rects to improve efficiency in certain scenarios.
  1684. // This option is not available on Windows Phone 8, to note.
  1685. DXGI_PRESENT_PARAMETERS parameters = {0};
  1686. parameters.DirtyRectsCount = 0;
  1687. parameters.pDirtyRects = nullptr;
  1688. parameters.pScrollRect = nullptr;
  1689. parameters.pScrollOffset = nullptr;
  1690. // The first argument instructs DXGI to block until VSync, putting the application
  1691. // to sleep until the next VSync. This ensures we don't waste any cycles rendering
  1692. // frames that will never be displayed to the screen.
  1693. HRESULT hr = data->swapChain->Present1(1, 0, &parameters);
  1694. #endif
  1695. // Discard the contents of the render target.
  1696. // This is a valid operation only when the existing contents will be entirely
  1697. // overwritten. If dirty or scroll rects are used, this call should be removed.
  1698. data->d3dContext->DiscardView(data->mainRenderTargetView.Get());
  1699. // If the device was removed either by a disconnect or a driver upgrade, we
  1700. // must recreate all device resources.
  1701. //
  1702. // TODO, WinRT: consider throwing an exception if D3D11_RenderPresent fails, especially if there is a way to salvedge debug info from users' machines
  1703. if (hr == DXGI_ERROR_DEVICE_REMOVED)
  1704. {
  1705. hr = D3D11_HandleDeviceLost(renderer);
  1706. if (FAILED(hr)) {
  1707. WIN_SetErrorFromHRESULT(__FUNCTION__, hr);
  1708. }
  1709. }
  1710. else
  1711. {
  1712. WIN_SetErrorFromHRESULT(__FUNCTION__, hr);
  1713. }
  1714. }
  1715. #endif /* SDL_VIDEO_RENDER_D3D && !SDL_RENDER_DISABLED */
  1716. /* vi: set ts=4 sw=4 expandtab: */