d3d11-subsystem.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <cinttypes>
  15. #include <util/base.h>
  16. #include <util/platform.h>
  17. #include <util/dstr.h>
  18. #include <util/util.hpp>
  19. #include <graphics/matrix3.h>
  20. #include <winternl.h>
  21. #include <d3d9.h>
  22. #include "d3d11-subsystem.hpp"
  23. #include "d3d11-config.h"
  24. #include "intel-nv12-support.hpp"
  25. struct UnsupportedHWError : HRError {
  26. inline UnsupportedHWError(const char *str, HRESULT hr)
  27. : HRError(str, hr)
  28. {
  29. }
  30. };
  31. #ifdef _MSC_VER
  32. /* alignment warning - despite the fact that alignment is already fixed */
  33. #pragma warning(disable : 4316)
  34. #endif
  35. static inline void LogD3D11ErrorDetails(HRError error, gs_device_t *device)
  36. {
  37. if (error.hr == DXGI_ERROR_DEVICE_REMOVED) {
  38. HRESULT DeviceRemovedReason =
  39. device->device->GetDeviceRemovedReason();
  40. blog(LOG_ERROR, " Device Removed Reason: %08lX",
  41. DeviceRemovedReason);
  42. }
  43. }
  44. static const IID dxgiFactory2 = {0x50c83a1c,
  45. 0xe072,
  46. 0x4c48,
  47. {0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6,
  48. 0xd0}};
  49. gs_obj::gs_obj(gs_device_t *device_, gs_type type)
  50. : device(device_), obj_type(type)
  51. {
  52. prev_next = &device->first_obj;
  53. next = device->first_obj;
  54. device->first_obj = this;
  55. if (next)
  56. next->prev_next = &next;
  57. }
  58. gs_obj::~gs_obj()
  59. {
  60. if (prev_next)
  61. *prev_next = next;
  62. if (next)
  63. next->prev_next = prev_next;
  64. }
  65. static inline void make_swap_desc(DXGI_SWAP_CHAIN_DESC &desc,
  66. const gs_init_data *data)
  67. {
  68. memset(&desc, 0, sizeof(desc));
  69. desc.BufferCount = data->num_backbuffers;
  70. desc.BufferDesc.Format = ConvertGSTextureFormat(data->format);
  71. desc.BufferDesc.Width = data->cx;
  72. desc.BufferDesc.Height = data->cy;
  73. desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  74. desc.OutputWindow = (HWND)data->window.hwnd;
  75. desc.SampleDesc.Count = 1;
  76. desc.Windowed = true;
  77. }
  78. void gs_swap_chain::InitTarget(uint32_t cx, uint32_t cy)
  79. {
  80. HRESULT hr;
  81. target.width = cx;
  82. target.height = cy;
  83. hr = swap->GetBuffer(0, __uuidof(ID3D11Texture2D),
  84. (void **)target.texture.Assign());
  85. if (FAILED(hr))
  86. throw HRError("Failed to get swap buffer texture", hr);
  87. hr = device->device->CreateRenderTargetView(
  88. target.texture, NULL, target.renderTarget[0].Assign());
  89. if (FAILED(hr))
  90. throw HRError("Failed to create swap render target view", hr);
  91. }
  92. void gs_swap_chain::InitZStencilBuffer(uint32_t cx, uint32_t cy)
  93. {
  94. zs.width = cx;
  95. zs.height = cy;
  96. if (zs.format != GS_ZS_NONE && cx != 0 && cy != 0) {
  97. zs.InitBuffer();
  98. } else {
  99. zs.texture.Clear();
  100. zs.view.Clear();
  101. }
  102. }
  103. void gs_swap_chain::Resize(uint32_t cx, uint32_t cy)
  104. {
  105. RECT clientRect;
  106. HRESULT hr;
  107. target.texture.Clear();
  108. target.renderTarget[0].Clear();
  109. zs.texture.Clear();
  110. zs.view.Clear();
  111. initData.cx = cx;
  112. initData.cy = cy;
  113. if (cx == 0 || cy == 0) {
  114. GetClientRect(hwnd, &clientRect);
  115. if (cx == 0)
  116. cx = clientRect.right;
  117. if (cy == 0)
  118. cy = clientRect.bottom;
  119. }
  120. hr = swap->ResizeBuffers(numBuffers, cx, cy, target.dxgiFormat, 0);
  121. if (FAILED(hr))
  122. throw HRError("Failed to resize swap buffers", hr);
  123. InitTarget(cx, cy);
  124. InitZStencilBuffer(cx, cy);
  125. }
  126. void gs_swap_chain::Init()
  127. {
  128. target.device = device;
  129. target.isRenderTarget = true;
  130. target.format = initData.format;
  131. target.dxgiFormat = ConvertGSTextureFormat(initData.format);
  132. InitTarget(initData.cx, initData.cy);
  133. zs.device = device;
  134. zs.format = initData.zsformat;
  135. zs.dxgiFormat = ConvertGSZStencilFormat(initData.zsformat);
  136. InitZStencilBuffer(initData.cx, initData.cy);
  137. }
  138. gs_swap_chain::gs_swap_chain(gs_device *device, const gs_init_data *data)
  139. : gs_obj(device, gs_type::gs_swap_chain),
  140. numBuffers(data->num_backbuffers),
  141. hwnd((HWND)data->window.hwnd),
  142. initData(*data)
  143. {
  144. HRESULT hr;
  145. make_swap_desc(swapDesc, data);
  146. hr = device->factory->CreateSwapChain(device->device, &swapDesc,
  147. swap.Assign());
  148. if (FAILED(hr))
  149. throw HRError("Failed to create swap chain", hr);
  150. /* Ignore Alt+Enter */
  151. device->factory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER);
  152. Init();
  153. }
  154. void gs_device::InitCompiler()
  155. {
  156. char d3dcompiler[40] = {};
  157. int ver = 49;
  158. while (ver > 30) {
  159. sprintf(d3dcompiler, "D3DCompiler_%02d.dll", ver);
  160. HMODULE module = LoadLibraryA(d3dcompiler);
  161. if (module) {
  162. d3dCompile = (pD3DCompile)GetProcAddress(module,
  163. "D3DCompile");
  164. #ifdef DISASSEMBLE_SHADERS
  165. d3dDisassemble = (pD3DDisassemble)GetProcAddress(
  166. module, "D3DDisassemble");
  167. #endif
  168. if (d3dCompile) {
  169. return;
  170. }
  171. FreeLibrary(module);
  172. }
  173. ver--;
  174. }
  175. throw "Could not find any D3DCompiler libraries. Make sure you've "
  176. "installed the <a href=\"https://obsproject.com/go/dxwebsetup\">"
  177. "DirectX components</a> that OBS Studio requires.";
  178. }
  179. void gs_device::InitFactory(uint32_t adapterIdx)
  180. {
  181. HRESULT hr;
  182. IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2
  183. : __uuidof(IDXGIFactory1);
  184. hr = CreateDXGIFactory1(factoryIID, (void **)factory.Assign());
  185. if (FAILED(hr))
  186. throw UnsupportedHWError("Failed to create DXGIFactory", hr);
  187. hr = factory->EnumAdapters1(adapterIdx, &adapter);
  188. if (FAILED(hr))
  189. throw UnsupportedHWError("Failed to enumerate DXGIAdapter", hr);
  190. }
  191. const static D3D_FEATURE_LEVEL featureLevels[] = {
  192. D3D_FEATURE_LEVEL_11_0,
  193. D3D_FEATURE_LEVEL_10_1,
  194. D3D_FEATURE_LEVEL_10_0,
  195. };
  196. /* ------------------------------------------------------------------------- */
  197. #define VERT_IN_OUT \
  198. "\
  199. struct VertInOut { \
  200. float4 pos : POSITION; \
  201. }; "
  202. #define NV12_Y_PS \
  203. VERT_IN_OUT "\
  204. float main(VertInOut vert_in) : TARGET \
  205. { \
  206. return 1.0; \
  207. }"
  208. #define NV12_UV_PS \
  209. VERT_IN_OUT "\
  210. float2 main(VertInOut vert_in) : TARGET \
  211. { \
  212. return float2(1.0, 1.0); \
  213. }"
  214. #define NV12_VS \
  215. VERT_IN_OUT "\
  216. VertInOut main(VertInOut vert_in) \
  217. { \
  218. VertInOut vert_out; \
  219. vert_out.pos = float4(vert_in.pos.xyz, 1.0); \
  220. return vert_out; \
  221. } "
  222. /* ------------------------------------------------------------------------- */
  223. #define NV12_CX 128
  224. #define NV12_CY 128
  225. bool gs_device::HasBadNV12Output()
  226. try {
  227. vec3 points[4];
  228. vec3_set(&points[0], -1.0f, -1.0f, 0.0f);
  229. vec3_set(&points[1], -1.0f, 1.0f, 0.0f);
  230. vec3_set(&points[2], 1.0f, -1.0f, 0.0f);
  231. vec3_set(&points[3], 1.0f, 1.0f, 0.0f);
  232. gs_texture_2d nv12_y(this, NV12_CX, NV12_CY, GS_R8, 1, nullptr,
  233. GS_RENDER_TARGET | GS_SHARED_KM_TEX, GS_TEXTURE_2D,
  234. false, true);
  235. gs_texture_2d nv12_uv(this, nv12_y.texture,
  236. GS_RENDER_TARGET | GS_SHARED_KM_TEX);
  237. gs_vertex_shader nv12_vs(this, "", NV12_VS);
  238. gs_pixel_shader nv12_y_ps(this, "", NV12_Y_PS);
  239. gs_pixel_shader nv12_uv_ps(this, "", NV12_UV_PS);
  240. gs_stage_surface nv12_stage(this, NV12_CX, NV12_CY);
  241. gs_vb_data *vbd = gs_vbdata_create();
  242. vbd->num = 4;
  243. vbd->points = (vec3 *)bmemdup(&points, sizeof(points));
  244. gs_vertex_buffer buf(this, vbd, 0);
  245. device_load_vertexbuffer(this, &buf);
  246. device_load_vertexshader(this, &nv12_vs);
  247. context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
  248. device_set_viewport(this, 0, 0, NV12_CX, NV12_CY);
  249. device_set_cull_mode(this, GS_NEITHER);
  250. device_enable_depth_test(this, false);
  251. device_enable_blending(this, false);
  252. LoadVertexBufferData();
  253. device_set_render_target(this, &nv12_y, nullptr);
  254. device_load_pixelshader(this, &nv12_y_ps);
  255. UpdateBlendState();
  256. UpdateRasterState();
  257. UpdateZStencilState();
  258. context->Draw(4, 0);
  259. device_set_viewport(this, 0, 0, NV12_CX / 2, NV12_CY / 2);
  260. device_set_render_target(this, &nv12_uv, nullptr);
  261. device_load_pixelshader(this, &nv12_uv_ps);
  262. UpdateBlendState();
  263. UpdateRasterState();
  264. UpdateZStencilState();
  265. context->Draw(4, 0);
  266. device_load_pixelshader(this, nullptr);
  267. device_load_vertexbuffer(this, nullptr);
  268. device_load_vertexshader(this, nullptr);
  269. device_set_render_target(this, nullptr, nullptr);
  270. device_stage_texture(this, &nv12_stage, &nv12_y);
  271. uint8_t *data;
  272. uint32_t linesize;
  273. bool bad_driver = false;
  274. if (gs_stagesurface_map(&nv12_stage, &data, &linesize)) {
  275. bad_driver = data[linesize * NV12_CY] == 0;
  276. gs_stagesurface_unmap(&nv12_stage);
  277. } else {
  278. throw "Could not map surface";
  279. }
  280. if (bad_driver) {
  281. blog(LOG_WARNING, "Bad NV12 texture handling detected! "
  282. "Disabling NV12 texture support.");
  283. }
  284. return bad_driver;
  285. } catch (const HRError &error) {
  286. blog(LOG_WARNING, "HasBadNV12Output failed: %s (%08lX)", error.str,
  287. error.hr);
  288. return false;
  289. } catch (const char *error) {
  290. blog(LOG_WARNING, "HasBadNV12Output failed: %s", error);
  291. return false;
  292. }
  293. static bool increase_maximum_frame_latency(ID3D11Device *device)
  294. {
  295. ComQIPtr<IDXGIDevice1> dxgiDevice(device);
  296. if (!dxgiDevice) {
  297. blog(LOG_DEBUG, "%s: Failed to get IDXGIDevice1", __FUNCTION__);
  298. return false;
  299. }
  300. const HRESULT hr = dxgiDevice->SetMaximumFrameLatency(16);
  301. if (FAILED(hr)) {
  302. blog(LOG_DEBUG, "%s: SetMaximumFrameLatency failed",
  303. __FUNCTION__);
  304. return false;
  305. }
  306. blog(LOG_INFO, "DXGI increase maximum frame latency success");
  307. return true;
  308. }
  309. #if USE_GPU_PRIORITY
  310. static bool set_priority(ID3D11Device *device)
  311. {
  312. typedef enum _D3DKMT_SCHEDULINGPRIORITYCLASS {
  313. D3DKMT_SCHEDULINGPRIORITYCLASS_IDLE,
  314. D3DKMT_SCHEDULINGPRIORITYCLASS_BELOW_NORMAL,
  315. D3DKMT_SCHEDULINGPRIORITYCLASS_NORMAL,
  316. D3DKMT_SCHEDULINGPRIORITYCLASS_ABOVE_NORMAL,
  317. D3DKMT_SCHEDULINGPRIORITYCLASS_HIGH,
  318. D3DKMT_SCHEDULINGPRIORITYCLASS_REALTIME
  319. } D3DKMT_SCHEDULINGPRIORITYCLASS;
  320. ComQIPtr<IDXGIDevice> dxgiDevice(device);
  321. if (!dxgiDevice) {
  322. blog(LOG_DEBUG, "%s: Failed to get IDXGIDevice", __FUNCTION__);
  323. return false;
  324. }
  325. HMODULE gdi32 = GetModuleHandleW(L"GDI32");
  326. if (!gdi32) {
  327. blog(LOG_DEBUG, "%s: Failed to get GDI32", __FUNCTION__);
  328. return false;
  329. }
  330. NTSTATUS(WINAPI * d3dkmt_spspc)(HANDLE, D3DKMT_SCHEDULINGPRIORITYCLASS);
  331. d3dkmt_spspc = (decltype(d3dkmt_spspc))GetProcAddress(
  332. gdi32, "D3DKMTSetProcessSchedulingPriorityClass");
  333. if (!d3dkmt_spspc) {
  334. blog(LOG_DEBUG, "%s: Failed to get d3dkmt_spspc", __FUNCTION__);
  335. return false;
  336. }
  337. NTSTATUS status = d3dkmt_spspc(GetCurrentProcess(),
  338. D3DKMT_SCHEDULINGPRIORITYCLASS_REALTIME);
  339. if (status != 0) {
  340. blog(LOG_DEBUG, "%s: Failed to set process priority class: %d",
  341. __FUNCTION__, (int)status);
  342. return false;
  343. }
  344. HRESULT hr = dxgiDevice->SetGPUThreadPriority(GPU_PRIORITY_VAL);
  345. if (FAILED(hr)) {
  346. blog(LOG_DEBUG, "%s: SetGPUThreadPriority failed",
  347. __FUNCTION__);
  348. return false;
  349. }
  350. blog(LOG_INFO, "D3D11 GPU priority setup success");
  351. return true;
  352. }
  353. #endif
  354. void gs_device::InitDevice(uint32_t adapterIdx)
  355. {
  356. wstring adapterName;
  357. DXGI_ADAPTER_DESC desc;
  358. D3D_FEATURE_LEVEL levelUsed = D3D_FEATURE_LEVEL_10_0;
  359. HRESULT hr = 0;
  360. adpIdx = adapterIdx;
  361. uint32_t createFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  362. #ifdef _DEBUG
  363. //createFlags |= D3D11_CREATE_DEVICE_DEBUG;
  364. #endif
  365. adapterName = (adapter->GetDesc(&desc) == S_OK) ? desc.Description
  366. : L"<unknown>";
  367. BPtr<char> adapterNameUTF8;
  368. os_wcs_to_utf8_ptr(adapterName.c_str(), 0, &adapterNameUTF8);
  369. blog(LOG_INFO, "Loading up D3D11 on adapter %s (%" PRIu32 ")",
  370. adapterNameUTF8.Get(), adapterIdx);
  371. hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL,
  372. createFlags, featureLevels,
  373. sizeof(featureLevels) /
  374. sizeof(D3D_FEATURE_LEVEL),
  375. D3D11_SDK_VERSION, device.Assign(), &levelUsed,
  376. context.Assign());
  377. if (FAILED(hr))
  378. throw UnsupportedHWError("Failed to create device", hr);
  379. blog(LOG_INFO, "D3D11 loaded successfully, feature level used: %x",
  380. (unsigned int)levelUsed);
  381. /* prevent stalls sometimes seen in Present calls */
  382. if (!increase_maximum_frame_latency(device)) {
  383. blog(LOG_INFO, "DXGI increase maximum frame latency failed");
  384. }
  385. /* adjust gpu thread priority on non-intel GPUs */
  386. #if USE_GPU_PRIORITY
  387. if (desc.VendorId != 0x8086 && !set_priority(device)) {
  388. blog(LOG_INFO, "D3D11 GPU priority setup "
  389. "failed (not admin?)");
  390. }
  391. #endif
  392. /* ---------------------------------------- */
  393. /* check for nv12 texture output support */
  394. nv12Supported = false;
  395. /* WARP NV12 support is suspected to be buggy on older Windows */
  396. if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) {
  397. return;
  398. }
  399. /* Intel CopyResource is very slow with NV12 */
  400. if (desc.VendorId == 0x8086 && IsOldIntelPlatform(desc.DeviceId)) {
  401. return;
  402. }
  403. ComQIPtr<ID3D11Device1> d3d11_1(device);
  404. if (!d3d11_1) {
  405. return;
  406. }
  407. /* needs to support extended resource sharing */
  408. D3D11_FEATURE_DATA_D3D11_OPTIONS opts = {};
  409. hr = d3d11_1->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &opts,
  410. sizeof(opts));
  411. if (FAILED(hr) || !opts.ExtendedResourceSharing) {
  412. return;
  413. }
  414. /* needs to support the actual format */
  415. UINT support = 0;
  416. hr = device->CheckFormatSupport(DXGI_FORMAT_NV12, &support);
  417. if (FAILED(hr)) {
  418. return;
  419. }
  420. if ((support & D3D11_FORMAT_SUPPORT_TEXTURE2D) == 0) {
  421. return;
  422. }
  423. /* must be usable as a render target */
  424. if ((support & D3D11_FORMAT_SUPPORT_RENDER_TARGET) == 0) {
  425. return;
  426. }
  427. if (HasBadNV12Output()) {
  428. return;
  429. }
  430. nv12Supported = true;
  431. }
  432. static inline void ConvertStencilSide(D3D11_DEPTH_STENCILOP_DESC &desc,
  433. const StencilSide &side)
  434. {
  435. desc.StencilFunc = ConvertGSDepthTest(side.test);
  436. desc.StencilFailOp = ConvertGSStencilOp(side.fail);
  437. desc.StencilDepthFailOp = ConvertGSStencilOp(side.zfail);
  438. desc.StencilPassOp = ConvertGSStencilOp(side.zpass);
  439. }
  440. ID3D11DepthStencilState *gs_device::AddZStencilState()
  441. {
  442. HRESULT hr;
  443. D3D11_DEPTH_STENCIL_DESC dsd;
  444. ID3D11DepthStencilState *state;
  445. dsd.DepthEnable = zstencilState.depthEnabled;
  446. dsd.DepthFunc = ConvertGSDepthTest(zstencilState.depthFunc);
  447. dsd.DepthWriteMask = zstencilState.depthWriteEnabled
  448. ? D3D11_DEPTH_WRITE_MASK_ALL
  449. : D3D11_DEPTH_WRITE_MASK_ZERO;
  450. dsd.StencilEnable = zstencilState.stencilEnabled;
  451. dsd.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
  452. dsd.StencilWriteMask = zstencilState.stencilWriteEnabled
  453. ? D3D11_DEFAULT_STENCIL_WRITE_MASK
  454. : 0;
  455. ConvertStencilSide(dsd.FrontFace, zstencilState.stencilFront);
  456. ConvertStencilSide(dsd.BackFace, zstencilState.stencilBack);
  457. SavedZStencilState savedState(zstencilState, dsd);
  458. hr = device->CreateDepthStencilState(&dsd, savedState.state.Assign());
  459. if (FAILED(hr))
  460. throw HRError("Failed to create depth stencil state", hr);
  461. state = savedState.state;
  462. zstencilStates.push_back(savedState);
  463. return state;
  464. }
  465. ID3D11RasterizerState *gs_device::AddRasterState()
  466. {
  467. HRESULT hr;
  468. D3D11_RASTERIZER_DESC rd;
  469. ID3D11RasterizerState *state;
  470. memset(&rd, 0, sizeof(rd));
  471. /* use CCW to convert to a right-handed coordinate system */
  472. rd.FrontCounterClockwise = true;
  473. rd.FillMode = D3D11_FILL_SOLID;
  474. rd.CullMode = ConvertGSCullMode(rasterState.cullMode);
  475. rd.DepthClipEnable = true;
  476. rd.ScissorEnable = rasterState.scissorEnabled;
  477. SavedRasterState savedState(rasterState, rd);
  478. hr = device->CreateRasterizerState(&rd, savedState.state.Assign());
  479. if (FAILED(hr))
  480. throw HRError("Failed to create rasterizer state", hr);
  481. state = savedState.state;
  482. rasterStates.push_back(savedState);
  483. return state;
  484. }
  485. ID3D11BlendState *gs_device::AddBlendState()
  486. {
  487. HRESULT hr;
  488. D3D11_BLEND_DESC bd;
  489. ID3D11BlendState *state;
  490. memset(&bd, 0, sizeof(bd));
  491. for (int i = 0; i < 8; i++) {
  492. bd.RenderTarget[i].BlendEnable = blendState.blendEnabled;
  493. bd.RenderTarget[i].BlendOp = D3D11_BLEND_OP_ADD;
  494. bd.RenderTarget[i].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  495. bd.RenderTarget[i].SrcBlend =
  496. ConvertGSBlendType(blendState.srcFactorC);
  497. bd.RenderTarget[i].DestBlend =
  498. ConvertGSBlendType(blendState.destFactorC);
  499. bd.RenderTarget[i].SrcBlendAlpha =
  500. ConvertGSBlendType(blendState.srcFactorA);
  501. bd.RenderTarget[i].DestBlendAlpha =
  502. ConvertGSBlendType(blendState.destFactorA);
  503. bd.RenderTarget[i].RenderTargetWriteMask =
  504. (blendState.redEnabled ? D3D11_COLOR_WRITE_ENABLE_RED
  505. : 0) |
  506. (blendState.greenEnabled
  507. ? D3D11_COLOR_WRITE_ENABLE_GREEN
  508. : 0) |
  509. (blendState.blueEnabled ? D3D11_COLOR_WRITE_ENABLE_BLUE
  510. : 0) |
  511. (blendState.alphaEnabled
  512. ? D3D11_COLOR_WRITE_ENABLE_ALPHA
  513. : 0);
  514. }
  515. SavedBlendState savedState(blendState, bd);
  516. hr = device->CreateBlendState(&bd, savedState.state.Assign());
  517. if (FAILED(hr))
  518. throw HRError("Failed to create blend state", hr);
  519. state = savedState.state;
  520. blendStates.push_back(savedState);
  521. return state;
  522. }
  523. void gs_device::UpdateZStencilState()
  524. {
  525. ID3D11DepthStencilState *state = NULL;
  526. if (!zstencilStateChanged)
  527. return;
  528. for (size_t i = 0; i < zstencilStates.size(); i++) {
  529. SavedZStencilState &s = zstencilStates[i];
  530. if (memcmp(&s, &zstencilState, sizeof(zstencilState)) == 0) {
  531. state = s.state;
  532. break;
  533. }
  534. }
  535. if (!state)
  536. state = AddZStencilState();
  537. if (state != curDepthStencilState) {
  538. context->OMSetDepthStencilState(state, 0);
  539. curDepthStencilState = state;
  540. }
  541. zstencilStateChanged = false;
  542. }
  543. void gs_device::UpdateRasterState()
  544. {
  545. ID3D11RasterizerState *state = NULL;
  546. if (!rasterStateChanged)
  547. return;
  548. for (size_t i = 0; i < rasterStates.size(); i++) {
  549. SavedRasterState &s = rasterStates[i];
  550. if (memcmp(&s, &rasterState, sizeof(rasterState)) == 0) {
  551. state = s.state;
  552. break;
  553. }
  554. }
  555. if (!state)
  556. state = AddRasterState();
  557. if (state != curRasterState) {
  558. context->RSSetState(state);
  559. curRasterState = state;
  560. }
  561. rasterStateChanged = false;
  562. }
  563. void gs_device::UpdateBlendState()
  564. {
  565. ID3D11BlendState *state = NULL;
  566. if (!blendStateChanged)
  567. return;
  568. for (size_t i = 0; i < blendStates.size(); i++) {
  569. SavedBlendState &s = blendStates[i];
  570. if (memcmp(&s, &blendState, sizeof(blendState)) == 0) {
  571. state = s.state;
  572. break;
  573. }
  574. }
  575. if (!state)
  576. state = AddBlendState();
  577. if (state != curBlendState) {
  578. float f[4] = {1.0f, 1.0f, 1.0f, 1.0f};
  579. context->OMSetBlendState(state, f, 0xFFFFFFFF);
  580. curBlendState = state;
  581. }
  582. blendStateChanged = false;
  583. }
  584. void gs_device::UpdateViewProjMatrix()
  585. {
  586. gs_matrix_get(&curViewMatrix);
  587. /* negate Z col of the view matrix for right-handed coordinate system */
  588. curViewMatrix.x.z = -curViewMatrix.x.z;
  589. curViewMatrix.y.z = -curViewMatrix.y.z;
  590. curViewMatrix.z.z = -curViewMatrix.z.z;
  591. curViewMatrix.t.z = -curViewMatrix.t.z;
  592. matrix4_mul(&curViewProjMatrix, &curViewMatrix, &curProjMatrix);
  593. matrix4_transpose(&curViewProjMatrix, &curViewProjMatrix);
  594. if (curVertexShader->viewProj)
  595. gs_shader_set_matrix4(curVertexShader->viewProj,
  596. &curViewProjMatrix);
  597. }
  598. gs_device::gs_device(uint32_t adapterIdx)
  599. : curToplogy(D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED)
  600. {
  601. matrix4_identity(&curProjMatrix);
  602. matrix4_identity(&curViewMatrix);
  603. matrix4_identity(&curViewProjMatrix);
  604. memset(&viewport, 0, sizeof(viewport));
  605. for (size_t i = 0; i < GS_MAX_TEXTURES; i++) {
  606. curTextures[i] = NULL;
  607. curSamplers[i] = NULL;
  608. }
  609. InitCompiler();
  610. InitFactory(adapterIdx);
  611. InitDevice(adapterIdx);
  612. device_set_render_target(this, NULL, NULL);
  613. }
  614. gs_device::~gs_device()
  615. {
  616. context->ClearState();
  617. }
  618. const char *device_get_name(void)
  619. {
  620. return "Direct3D 11";
  621. }
  622. int device_get_type(void)
  623. {
  624. return GS_DEVICE_DIRECT3D_11;
  625. }
  626. const char *device_preprocessor_name(void)
  627. {
  628. return "_D3D11";
  629. }
  630. static inline void
  631. EnumD3DAdapters(bool (*callback)(void *, const char *, uint32_t), void *param)
  632. {
  633. ComPtr<IDXGIFactory1> factory;
  634. ComPtr<IDXGIAdapter1> adapter;
  635. HRESULT hr;
  636. UINT i;
  637. IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2
  638. : __uuidof(IDXGIFactory1);
  639. hr = CreateDXGIFactory1(factoryIID, (void **)factory.Assign());
  640. if (FAILED(hr))
  641. throw HRError("Failed to create DXGIFactory", hr);
  642. for (i = 0; factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) {
  643. DXGI_ADAPTER_DESC desc;
  644. char name[512] = "";
  645. hr = adapter->GetDesc(&desc);
  646. if (FAILED(hr))
  647. continue;
  648. /* ignore Microsoft's 'basic' renderer' */
  649. if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)
  650. continue;
  651. os_wcs_to_utf8(desc.Description, 0, name, sizeof(name));
  652. if (!callback(param, name, i))
  653. break;
  654. }
  655. }
  656. bool device_enum_adapters(bool (*callback)(void *param, const char *name,
  657. uint32_t id),
  658. void *param)
  659. {
  660. try {
  661. EnumD3DAdapters(callback, param);
  662. return true;
  663. } catch (const HRError &error) {
  664. blog(LOG_WARNING, "Failed enumerating devices: %s (%08lX)",
  665. error.str, error.hr);
  666. return false;
  667. }
  668. }
  669. static bool GetMonitorTarget(const MONITORINFOEX &info,
  670. DISPLAYCONFIG_TARGET_DEVICE_NAME &target)
  671. {
  672. bool found = false;
  673. UINT32 numPath, numMode;
  674. if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &numPath,
  675. &numMode) == ERROR_SUCCESS) {
  676. std::vector<DISPLAYCONFIG_PATH_INFO> paths(numPath);
  677. std::vector<DISPLAYCONFIG_MODE_INFO> modes(numMode);
  678. if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &numPath,
  679. paths.data(), &numMode, modes.data(),
  680. nullptr) == ERROR_SUCCESS) {
  681. paths.resize(numPath);
  682. for (size_t i = 0; i < numPath; ++i) {
  683. const DISPLAYCONFIG_PATH_INFO &path = paths[i];
  684. DISPLAYCONFIG_SOURCE_DEVICE_NAME
  685. source;
  686. source.header.type =
  687. DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
  688. source.header.size = sizeof(source);
  689. source.header.adapterId =
  690. path.sourceInfo.adapterId;
  691. source.header.id = path.sourceInfo.id;
  692. if (DisplayConfigGetDeviceInfo(
  693. &source.header) == ERROR_SUCCESS &&
  694. wcscmp(info.szDevice,
  695. source.viewGdiDeviceName) == 0) {
  696. target.header.type =
  697. DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME;
  698. target.header.size = sizeof(target);
  699. target.header.adapterId =
  700. path.sourceInfo.adapterId;
  701. target.header.id = path.targetInfo.id;
  702. found = DisplayConfigGetDeviceInfo(
  703. &target.header) ==
  704. ERROR_SUCCESS;
  705. break;
  706. }
  707. }
  708. }
  709. }
  710. return found;
  711. }
  712. static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter)
  713. {
  714. UINT i;
  715. ComPtr<IDXGIOutput> output;
  716. for (i = 0; adapter->EnumOutputs(i, &output) == S_OK; ++i) {
  717. DXGI_OUTPUT_DESC desc;
  718. if (FAILED(output->GetDesc(&desc)))
  719. continue;
  720. unsigned refresh = 0;
  721. bool target_found = false;
  722. DISPLAYCONFIG_TARGET_DEVICE_NAME target;
  723. MONITORINFOEX info;
  724. info.cbSize = sizeof(info);
  725. if (GetMonitorInfo(desc.Monitor, &info)) {
  726. target_found = GetMonitorTarget(info, target);
  727. DEVMODE mode;
  728. mode.dmSize = sizeof(mode);
  729. mode.dmDriverExtra = 0;
  730. if (EnumDisplaySettings(info.szDevice,
  731. ENUM_CURRENT_SETTINGS, &mode)) {
  732. refresh = mode.dmDisplayFrequency;
  733. }
  734. }
  735. if (!target_found) {
  736. target.monitorFriendlyDeviceName[0] = 0;
  737. }
  738. const RECT &rect = desc.DesktopCoordinates;
  739. blog(LOG_INFO,
  740. "\t output %u: "
  741. "pos={%d, %d}, "
  742. "size={%d, %d}, "
  743. "attached=%s, "
  744. "refresh=%u, "
  745. "name=%ls",
  746. i, rect.left, rect.top, rect.right - rect.left,
  747. rect.bottom - rect.top,
  748. desc.AttachedToDesktop ? "true" : "false", refresh,
  749. target.monitorFriendlyDeviceName);
  750. }
  751. }
  752. static inline void LogD3DAdapters()
  753. {
  754. ComPtr<IDXGIFactory1> factory;
  755. ComPtr<IDXGIAdapter1> adapter;
  756. HRESULT hr;
  757. UINT i;
  758. blog(LOG_INFO, "Available Video Adapters: ");
  759. IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2
  760. : __uuidof(IDXGIFactory1);
  761. hr = CreateDXGIFactory1(factoryIID, (void **)factory.Assign());
  762. if (FAILED(hr))
  763. throw HRError("Failed to create DXGIFactory", hr);
  764. for (i = 0; factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) {
  765. DXGI_ADAPTER_DESC desc;
  766. char name[512] = "";
  767. hr = adapter->GetDesc(&desc);
  768. if (FAILED(hr))
  769. continue;
  770. /* ignore Microsoft's 'basic' renderer' */
  771. if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)
  772. continue;
  773. os_wcs_to_utf8(desc.Description, 0, name, sizeof(name));
  774. blog(LOG_INFO, "\tAdapter %u: %s", i, name);
  775. blog(LOG_INFO, "\t Dedicated VRAM: %u",
  776. desc.DedicatedVideoMemory);
  777. blog(LOG_INFO, "\t Shared VRAM: %u",
  778. desc.SharedSystemMemory);
  779. blog(LOG_INFO, "\t PCI ID: %x:%x", desc.VendorId,
  780. desc.DeviceId);
  781. /* driver version */
  782. LARGE_INTEGER umd;
  783. hr = adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice),
  784. &umd);
  785. if (SUCCEEDED(hr)) {
  786. const uint64_t version = umd.QuadPart;
  787. const uint16_t aa = (version >> 48) & 0xffff;
  788. const uint16_t bb = (version >> 32) & 0xffff;
  789. const uint16_t ccccc = (version >> 16) & 0xffff;
  790. const uint16_t ddddd = version & 0xffff;
  791. blog(LOG_INFO,
  792. "\t Driver Version: %" PRIu16 ".%" PRIu16
  793. ".%" PRIu16 ".%" PRIu16,
  794. aa, bb, ccccc, ddddd);
  795. } else {
  796. blog(LOG_INFO, "\t Driver Version: Unknown (0x%X)",
  797. (unsigned)hr);
  798. }
  799. LogAdapterMonitors(adapter);
  800. }
  801. }
  802. int device_create(gs_device_t **p_device, uint32_t adapter)
  803. {
  804. gs_device *device = NULL;
  805. int errorcode = GS_SUCCESS;
  806. try {
  807. blog(LOG_INFO, "---------------------------------");
  808. blog(LOG_INFO, "Initializing D3D11...");
  809. LogD3DAdapters();
  810. device = new gs_device(adapter);
  811. } catch (const UnsupportedHWError &error) {
  812. blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str,
  813. error.hr);
  814. errorcode = GS_ERROR_NOT_SUPPORTED;
  815. } catch (const HRError &error) {
  816. blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str,
  817. error.hr);
  818. errorcode = GS_ERROR_FAIL;
  819. }
  820. *p_device = device;
  821. return errorcode;
  822. }
  823. void device_destroy(gs_device_t *device)
  824. {
  825. delete device;
  826. }
  827. void device_enter_context(gs_device_t *device)
  828. {
  829. /* does nothing */
  830. UNUSED_PARAMETER(device);
  831. }
  832. void device_leave_context(gs_device_t *device)
  833. {
  834. /* does nothing */
  835. UNUSED_PARAMETER(device);
  836. }
  837. void *device_get_device_obj(gs_device_t *device)
  838. {
  839. return (void *)device->device.Get();
  840. }
  841. gs_swapchain_t *device_swapchain_create(gs_device_t *device,
  842. const struct gs_init_data *data)
  843. {
  844. gs_swap_chain *swap = NULL;
  845. try {
  846. swap = new gs_swap_chain(device, data);
  847. } catch (const HRError &error) {
  848. blog(LOG_ERROR, "device_swapchain_create (D3D11): %s (%08lX)",
  849. error.str, error.hr);
  850. LogD3D11ErrorDetails(error, device);
  851. }
  852. return swap;
  853. }
  854. void device_resize(gs_device_t *device, uint32_t cx, uint32_t cy)
  855. {
  856. if (!device->curSwapChain) {
  857. blog(LOG_WARNING, "device_resize (D3D11): No active swap");
  858. return;
  859. }
  860. try {
  861. ID3D11RenderTargetView *renderView = NULL;
  862. ID3D11DepthStencilView *depthView = NULL;
  863. int i = device->curRenderSide;
  864. device->context->OMSetRenderTargets(1, &renderView, depthView);
  865. device->curSwapChain->Resize(cx, cy);
  866. if (device->curRenderTarget)
  867. renderView = device->curRenderTarget->renderTarget[i];
  868. if (device->curZStencilBuffer)
  869. depthView = device->curZStencilBuffer->view;
  870. device->context->OMSetRenderTargets(1, &renderView, depthView);
  871. } catch (const HRError &error) {
  872. blog(LOG_ERROR, "device_resize (D3D11): %s (%08lX)", error.str,
  873. error.hr);
  874. LogD3D11ErrorDetails(error, device);
  875. }
  876. }
  877. void device_get_size(const gs_device_t *device, uint32_t *cx, uint32_t *cy)
  878. {
  879. if (device->curSwapChain) {
  880. *cx = device->curSwapChain->target.width;
  881. *cy = device->curSwapChain->target.height;
  882. } else {
  883. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  884. *cx = 0;
  885. *cy = 0;
  886. }
  887. }
  888. uint32_t device_get_width(const gs_device_t *device)
  889. {
  890. if (device->curSwapChain) {
  891. return device->curSwapChain->target.width;
  892. } else {
  893. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  894. return 0;
  895. }
  896. }
  897. uint32_t device_get_height(const gs_device_t *device)
  898. {
  899. if (device->curSwapChain) {
  900. return device->curSwapChain->target.height;
  901. } else {
  902. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  903. return 0;
  904. }
  905. }
  906. gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width,
  907. uint32_t height,
  908. enum gs_color_format color_format,
  909. uint32_t levels, const uint8_t **data,
  910. uint32_t flags)
  911. {
  912. gs_texture *texture = NULL;
  913. try {
  914. texture = new gs_texture_2d(device, width, height, color_format,
  915. levels, data, flags, GS_TEXTURE_2D,
  916. false);
  917. } catch (const HRError &error) {
  918. blog(LOG_ERROR, "device_texture_create (D3D11): %s (%08lX)",
  919. error.str, error.hr);
  920. LogD3D11ErrorDetails(error, device);
  921. } catch (const char *error) {
  922. blog(LOG_ERROR, "device_texture_create (D3D11): %s", error);
  923. }
  924. return texture;
  925. }
  926. gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size,
  927. enum gs_color_format color_format,
  928. uint32_t levels, const uint8_t **data,
  929. uint32_t flags)
  930. {
  931. gs_texture *texture = NULL;
  932. try {
  933. texture = new gs_texture_2d(device, size, size, color_format,
  934. levels, data, flags,
  935. GS_TEXTURE_CUBE, false);
  936. } catch (const HRError &error) {
  937. blog(LOG_ERROR,
  938. "device_cubetexture_create (D3D11): %s "
  939. "(%08lX)",
  940. error.str, error.hr);
  941. LogD3D11ErrorDetails(error, device);
  942. } catch (const char *error) {
  943. blog(LOG_ERROR, "device_cubetexture_create (D3D11): %s", error);
  944. }
  945. return texture;
  946. }
  947. gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width,
  948. uint32_t height, uint32_t depth,
  949. enum gs_color_format color_format,
  950. uint32_t levels,
  951. const uint8_t *const *data,
  952. uint32_t flags)
  953. {
  954. gs_texture *texture = NULL;
  955. try {
  956. texture = new gs_texture_3d(device, width, height, depth,
  957. color_format, levels, data, flags);
  958. } catch (const HRError &error) {
  959. blog(LOG_ERROR, "device_voltexture_create (D3D11): %s (%08lX)",
  960. error.str, error.hr);
  961. LogD3D11ErrorDetails(error, device);
  962. } catch (const char *error) {
  963. blog(LOG_ERROR, "device_voltexture_create (D3D11): %s", error);
  964. }
  965. return texture;
  966. }
  967. gs_zstencil_t *device_zstencil_create(gs_device_t *device, uint32_t width,
  968. uint32_t height,
  969. enum gs_zstencil_format format)
  970. {
  971. gs_zstencil_buffer *zstencil = NULL;
  972. try {
  973. zstencil =
  974. new gs_zstencil_buffer(device, width, height, format);
  975. } catch (const HRError &error) {
  976. blog(LOG_ERROR, "device_zstencil_create (D3D11): %s (%08lX)",
  977. error.str, error.hr);
  978. LogD3D11ErrorDetails(error, device);
  979. }
  980. return zstencil;
  981. }
  982. gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width,
  983. uint32_t height,
  984. enum gs_color_format color_format)
  985. {
  986. gs_stage_surface *surf = NULL;
  987. try {
  988. surf = new gs_stage_surface(device, width, height,
  989. color_format);
  990. } catch (const HRError &error) {
  991. blog(LOG_ERROR,
  992. "device_stagesurface_create (D3D11): %s "
  993. "(%08lX)",
  994. error.str, error.hr);
  995. LogD3D11ErrorDetails(error, device);
  996. }
  997. return surf;
  998. }
  999. gs_samplerstate_t *
  1000. device_samplerstate_create(gs_device_t *device,
  1001. const struct gs_sampler_info *info)
  1002. {
  1003. gs_sampler_state *ss = NULL;
  1004. try {
  1005. ss = new gs_sampler_state(device, info);
  1006. } catch (const HRError &error) {
  1007. blog(LOG_ERROR,
  1008. "device_samplerstate_create (D3D11): %s "
  1009. "(%08lX)",
  1010. error.str, error.hr);
  1011. LogD3D11ErrorDetails(error, device);
  1012. }
  1013. return ss;
  1014. }
  1015. gs_shader_t *device_vertexshader_create(gs_device_t *device,
  1016. const char *shader_string,
  1017. const char *file, char **error_string)
  1018. {
  1019. gs_vertex_shader *shader = NULL;
  1020. try {
  1021. shader = new gs_vertex_shader(device, file, shader_string);
  1022. } catch (const HRError &error) {
  1023. blog(LOG_ERROR,
  1024. "device_vertexshader_create (D3D11): %s "
  1025. "(%08lX)",
  1026. error.str, error.hr);
  1027. LogD3D11ErrorDetails(error, device);
  1028. } catch (const ShaderError &error) {
  1029. const char *buf =
  1030. (const char *)error.errors->GetBufferPointer();
  1031. if (error_string)
  1032. *error_string = bstrdup(buf);
  1033. blog(LOG_ERROR,
  1034. "device_vertexshader_create (D3D11): "
  1035. "Compile warnings/errors for %s:\n%s",
  1036. file, buf);
  1037. } catch (const char *error) {
  1038. blog(LOG_ERROR, "device_vertexshader_create (D3D11): %s",
  1039. error);
  1040. }
  1041. return shader;
  1042. }
  1043. gs_shader_t *device_pixelshader_create(gs_device_t *device,
  1044. const char *shader_string,
  1045. const char *file, char **error_string)
  1046. {
  1047. gs_pixel_shader *shader = NULL;
  1048. try {
  1049. shader = new gs_pixel_shader(device, file, shader_string);
  1050. } catch (const HRError &error) {
  1051. blog(LOG_ERROR,
  1052. "device_pixelshader_create (D3D11): %s "
  1053. "(%08lX)",
  1054. error.str, error.hr);
  1055. LogD3D11ErrorDetails(error, device);
  1056. } catch (const ShaderError &error) {
  1057. const char *buf =
  1058. (const char *)error.errors->GetBufferPointer();
  1059. if (error_string)
  1060. *error_string = bstrdup(buf);
  1061. blog(LOG_ERROR,
  1062. "device_pixelshader_create (D3D11): "
  1063. "Compiler warnings/errors for %s:\n%s",
  1064. file, buf);
  1065. } catch (const char *error) {
  1066. blog(LOG_ERROR, "device_pixelshader_create (D3D11): %s", error);
  1067. }
  1068. return shader;
  1069. }
  1070. gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device,
  1071. struct gs_vb_data *data,
  1072. uint32_t flags)
  1073. {
  1074. gs_vertex_buffer *buffer = NULL;
  1075. try {
  1076. buffer = new gs_vertex_buffer(device, data, flags);
  1077. } catch (const HRError &error) {
  1078. blog(LOG_ERROR,
  1079. "device_vertexbuffer_create (D3D11): %s "
  1080. "(%08lX)",
  1081. error.str, error.hr);
  1082. LogD3D11ErrorDetails(error, device);
  1083. } catch (const char *error) {
  1084. blog(LOG_ERROR, "device_vertexbuffer_create (D3D11): %s",
  1085. error);
  1086. }
  1087. return buffer;
  1088. }
  1089. gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device,
  1090. enum gs_index_type type,
  1091. void *indices, size_t num,
  1092. uint32_t flags)
  1093. {
  1094. gs_index_buffer *buffer = NULL;
  1095. try {
  1096. buffer = new gs_index_buffer(device, type, indices, num, flags);
  1097. } catch (const HRError &error) {
  1098. blog(LOG_ERROR, "device_indexbuffer_create (D3D11): %s (%08lX)",
  1099. error.str, error.hr);
  1100. LogD3D11ErrorDetails(error, device);
  1101. }
  1102. return buffer;
  1103. }
  1104. gs_timer_t *device_timer_create(gs_device_t *device)
  1105. {
  1106. gs_timer *timer = NULL;
  1107. try {
  1108. timer = new gs_timer(device);
  1109. } catch (const HRError &error) {
  1110. blog(LOG_ERROR, "device_timer_create (D3D11): %s (%08lX)",
  1111. error.str, error.hr);
  1112. LogD3D11ErrorDetails(error, device);
  1113. }
  1114. return timer;
  1115. }
  1116. gs_timer_range_t *device_timer_range_create(gs_device_t *device)
  1117. {
  1118. gs_timer_range *range = NULL;
  1119. try {
  1120. range = new gs_timer_range(device);
  1121. } catch (const HRError &error) {
  1122. blog(LOG_ERROR, "device_timer_range_create (D3D11): %s (%08lX)",
  1123. error.str, error.hr);
  1124. LogD3D11ErrorDetails(error, device);
  1125. }
  1126. return range;
  1127. }
  1128. enum gs_texture_type device_get_texture_type(const gs_texture_t *texture)
  1129. {
  1130. return texture->type;
  1131. }
  1132. void gs_device::LoadVertexBufferData()
  1133. {
  1134. if (curVertexBuffer == lastVertexBuffer &&
  1135. curVertexShader == lastVertexShader)
  1136. return;
  1137. vector<ID3D11Buffer *> buffers;
  1138. vector<uint32_t> strides;
  1139. vector<uint32_t> offsets;
  1140. if (curVertexBuffer && curVertexShader) {
  1141. curVertexBuffer->MakeBufferList(curVertexShader, buffers,
  1142. strides);
  1143. } else {
  1144. size_t buffersToClear =
  1145. curVertexShader ? curVertexShader->NumBuffersExpected()
  1146. : 0;
  1147. buffers.resize(buffersToClear);
  1148. strides.resize(buffersToClear);
  1149. }
  1150. offsets.resize(buffers.size());
  1151. context->IASetVertexBuffers(0, (UINT)buffers.size(), buffers.data(),
  1152. strides.data(), offsets.data());
  1153. lastVertexBuffer = curVertexBuffer;
  1154. lastVertexShader = curVertexShader;
  1155. }
  1156. void device_load_vertexbuffer(gs_device_t *device, gs_vertbuffer_t *vertbuffer)
  1157. {
  1158. if (device->curVertexBuffer == vertbuffer)
  1159. return;
  1160. device->curVertexBuffer = vertbuffer;
  1161. }
  1162. void device_load_indexbuffer(gs_device_t *device, gs_indexbuffer_t *indexbuffer)
  1163. {
  1164. DXGI_FORMAT format;
  1165. ID3D11Buffer *buffer;
  1166. if (device->curIndexBuffer == indexbuffer)
  1167. return;
  1168. if (indexbuffer) {
  1169. switch (indexbuffer->indexSize) {
  1170. case 2:
  1171. format = DXGI_FORMAT_R16_UINT;
  1172. break;
  1173. default:
  1174. case 4:
  1175. format = DXGI_FORMAT_R32_UINT;
  1176. break;
  1177. }
  1178. buffer = indexbuffer->indexBuffer;
  1179. } else {
  1180. buffer = NULL;
  1181. format = DXGI_FORMAT_R32_UINT;
  1182. }
  1183. device->curIndexBuffer = indexbuffer;
  1184. device->context->IASetIndexBuffer(buffer, format, 0);
  1185. }
  1186. void device_load_texture(gs_device_t *device, gs_texture_t *tex, int unit)
  1187. {
  1188. ID3D11ShaderResourceView *view = NULL;
  1189. if (device->curTextures[unit] == tex)
  1190. return;
  1191. if (tex)
  1192. view = tex->shaderRes;
  1193. device->curTextures[unit] = tex;
  1194. device->context->PSSetShaderResources(unit, 1, &view);
  1195. }
  1196. void device_load_samplerstate(gs_device_t *device,
  1197. gs_samplerstate_t *samplerstate, int unit)
  1198. {
  1199. ID3D11SamplerState *state = NULL;
  1200. if (device->curSamplers[unit] == samplerstate)
  1201. return;
  1202. if (samplerstate)
  1203. state = samplerstate->state;
  1204. device->curSamplers[unit] = samplerstate;
  1205. device->context->PSSetSamplers(unit, 1, &state);
  1206. }
  1207. void device_load_vertexshader(gs_device_t *device, gs_shader_t *vertshader)
  1208. {
  1209. ID3D11VertexShader *shader = NULL;
  1210. ID3D11InputLayout *layout = NULL;
  1211. ID3D11Buffer *constants = NULL;
  1212. if (device->curVertexShader == vertshader)
  1213. return;
  1214. gs_vertex_shader *vs = static_cast<gs_vertex_shader *>(vertshader);
  1215. if (vertshader) {
  1216. if (vertshader->type != GS_SHADER_VERTEX) {
  1217. blog(LOG_ERROR, "device_load_vertexshader (D3D11): "
  1218. "Specified shader is not a vertex "
  1219. "shader");
  1220. return;
  1221. }
  1222. shader = vs->shader;
  1223. layout = vs->layout;
  1224. constants = vs->constants;
  1225. }
  1226. device->curVertexShader = vs;
  1227. device->context->VSSetShader(shader, NULL, 0);
  1228. device->context->IASetInputLayout(layout);
  1229. device->context->VSSetConstantBuffers(0, 1, &constants);
  1230. }
  1231. static inline void clear_textures(gs_device_t *device)
  1232. {
  1233. ID3D11ShaderResourceView *views[GS_MAX_TEXTURES];
  1234. memset(views, 0, sizeof(views));
  1235. memset(device->curTextures, 0, sizeof(device->curTextures));
  1236. device->context->PSSetShaderResources(0, GS_MAX_TEXTURES, views);
  1237. }
  1238. void device_load_pixelshader(gs_device_t *device, gs_shader_t *pixelshader)
  1239. {
  1240. ID3D11PixelShader *shader = NULL;
  1241. ID3D11Buffer *constants = NULL;
  1242. ID3D11SamplerState *states[GS_MAX_TEXTURES];
  1243. if (device->curPixelShader == pixelshader)
  1244. return;
  1245. gs_pixel_shader *ps = static_cast<gs_pixel_shader *>(pixelshader);
  1246. if (pixelshader) {
  1247. if (pixelshader->type != GS_SHADER_PIXEL) {
  1248. blog(LOG_ERROR, "device_load_pixelshader (D3D11): "
  1249. "Specified shader is not a pixel "
  1250. "shader");
  1251. return;
  1252. }
  1253. shader = ps->shader;
  1254. constants = ps->constants;
  1255. ps->GetSamplerStates(states);
  1256. } else {
  1257. memset(states, 0, sizeof(states));
  1258. }
  1259. clear_textures(device);
  1260. device->curPixelShader = ps;
  1261. device->context->PSSetShader(shader, NULL, 0);
  1262. device->context->PSSetConstantBuffers(0, 1, &constants);
  1263. device->context->PSSetSamplers(0, GS_MAX_TEXTURES, states);
  1264. for (int i = 0; i < GS_MAX_TEXTURES; i++)
  1265. if (device->curSamplers[i] &&
  1266. device->curSamplers[i]->state != states[i])
  1267. device->curSamplers[i] = nullptr;
  1268. }
  1269. void device_load_default_samplerstate(gs_device_t *device, bool b_3d, int unit)
  1270. {
  1271. /* TODO */
  1272. UNUSED_PARAMETER(device);
  1273. UNUSED_PARAMETER(b_3d);
  1274. UNUSED_PARAMETER(unit);
  1275. }
  1276. gs_shader_t *device_get_vertex_shader(const gs_device_t *device)
  1277. {
  1278. return device->curVertexShader;
  1279. }
  1280. gs_shader_t *device_get_pixel_shader(const gs_device_t *device)
  1281. {
  1282. return device->curPixelShader;
  1283. }
  1284. gs_texture_t *device_get_render_target(const gs_device_t *device)
  1285. {
  1286. if (device->curRenderTarget == &device->curSwapChain->target)
  1287. return NULL;
  1288. return device->curRenderTarget;
  1289. }
  1290. gs_zstencil_t *device_get_zstencil_target(const gs_device_t *device)
  1291. {
  1292. if (device->curZStencilBuffer == &device->curSwapChain->zs)
  1293. return NULL;
  1294. return device->curZStencilBuffer;
  1295. }
  1296. void device_set_render_target(gs_device_t *device, gs_texture_t *tex,
  1297. gs_zstencil_t *zstencil)
  1298. {
  1299. if (device->curSwapChain) {
  1300. if (!tex)
  1301. tex = &device->curSwapChain->target;
  1302. if (!zstencil)
  1303. zstencil = &device->curSwapChain->zs;
  1304. }
  1305. if (device->curRenderTarget == tex &&
  1306. device->curZStencilBuffer == zstencil)
  1307. return;
  1308. if (tex && tex->type != GS_TEXTURE_2D) {
  1309. blog(LOG_ERROR, "device_set_render_target (D3D11): "
  1310. "texture is not a 2D texture");
  1311. return;
  1312. }
  1313. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1314. if (tex2d && !tex2d->renderTarget[0]) {
  1315. blog(LOG_ERROR, "device_set_render_target (D3D11): "
  1316. "texture is not a render target");
  1317. return;
  1318. }
  1319. ID3D11RenderTargetView *rt = tex2d ? tex2d->renderTarget[0].Get()
  1320. : nullptr;
  1321. device->curRenderTarget = tex2d;
  1322. device->curRenderSide = 0;
  1323. device->curZStencilBuffer = zstencil;
  1324. device->context->OMSetRenderTargets(
  1325. 1, &rt, zstencil ? zstencil->view : nullptr);
  1326. }
  1327. void device_set_cube_render_target(gs_device_t *device, gs_texture_t *tex,
  1328. int side, gs_zstencil_t *zstencil)
  1329. {
  1330. if (device->curSwapChain) {
  1331. if (!tex) {
  1332. tex = &device->curSwapChain->target;
  1333. side = 0;
  1334. }
  1335. if (!zstencil)
  1336. zstencil = &device->curSwapChain->zs;
  1337. }
  1338. if (device->curRenderTarget == tex && device->curRenderSide == side &&
  1339. device->curZStencilBuffer == zstencil)
  1340. return;
  1341. if (tex->type != GS_TEXTURE_CUBE) {
  1342. blog(LOG_ERROR, "device_set_cube_render_target (D3D11): "
  1343. "texture is not a cube texture");
  1344. return;
  1345. }
  1346. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1347. if (!tex2d->renderTarget[side]) {
  1348. blog(LOG_ERROR, "device_set_cube_render_target (D3D11): "
  1349. "texture is not a render target");
  1350. return;
  1351. }
  1352. ID3D11RenderTargetView *rt = tex2d->renderTarget[0];
  1353. device->curRenderTarget = tex2d;
  1354. device->curRenderSide = side;
  1355. device->curZStencilBuffer = zstencil;
  1356. device->context->OMSetRenderTargets(1, &rt, zstencil->view);
  1357. }
  1358. inline void gs_device::CopyTex(ID3D11Texture2D *dst, uint32_t dst_x,
  1359. uint32_t dst_y, gs_texture_t *src,
  1360. uint32_t src_x, uint32_t src_y, uint32_t src_w,
  1361. uint32_t src_h)
  1362. {
  1363. if (src->type != GS_TEXTURE_2D)
  1364. throw "Source texture must be a 2D texture";
  1365. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(src);
  1366. if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 &&
  1367. src_w == 0 && src_h == 0) {
  1368. context->CopyResource(dst, tex2d->texture);
  1369. } else {
  1370. D3D11_BOX sbox;
  1371. sbox.left = src_x;
  1372. if (src_w > 0)
  1373. sbox.right = src_x + src_w;
  1374. else
  1375. sbox.right = tex2d->width - 1;
  1376. sbox.top = src_y;
  1377. if (src_h > 0)
  1378. sbox.bottom = src_y + src_h;
  1379. else
  1380. sbox.bottom = tex2d->height - 1;
  1381. sbox.front = 0;
  1382. sbox.back = 1;
  1383. context->CopySubresourceRegion(dst, 0, dst_x, dst_y, 0,
  1384. tex2d->texture, 0, &sbox);
  1385. }
  1386. }
  1387. void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst,
  1388. uint32_t dst_x, uint32_t dst_y,
  1389. gs_texture_t *src, uint32_t src_x,
  1390. uint32_t src_y, uint32_t src_w, uint32_t src_h)
  1391. {
  1392. try {
  1393. gs_texture_2d *src2d = static_cast<gs_texture_2d *>(src);
  1394. gs_texture_2d *dst2d = static_cast<gs_texture_2d *>(dst);
  1395. if (!src)
  1396. throw "Source texture is NULL";
  1397. if (!dst)
  1398. throw "Destination texture is NULL";
  1399. if (src->type != GS_TEXTURE_2D || dst->type != GS_TEXTURE_2D)
  1400. throw "Source and destination textures must be a 2D "
  1401. "textures";
  1402. if (dst->format != src->format)
  1403. throw "Source and destination formats do not match";
  1404. /* apparently casting to the same type that the variable
  1405. * already exists as is supposed to prevent some warning
  1406. * when used with the conditional operator? */
  1407. uint32_t copyWidth = (uint32_t)src_w ? (uint32_t)src_w
  1408. : (src2d->width - src_x);
  1409. uint32_t copyHeight = (uint32_t)src_h ? (uint32_t)src_h
  1410. : (src2d->height - src_y);
  1411. uint32_t dstWidth = dst2d->width - dst_x;
  1412. uint32_t dstHeight = dst2d->height - dst_y;
  1413. if (dstWidth < copyWidth || dstHeight < copyHeight)
  1414. throw "Destination texture region is not big "
  1415. "enough to hold the source region";
  1416. if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 &&
  1417. src_w == 0 && src_h == 0) {
  1418. copyWidth = 0;
  1419. copyHeight = 0;
  1420. }
  1421. device->CopyTex(dst2d->texture, dst_x, dst_y, src, src_x, src_y,
  1422. copyWidth, copyHeight);
  1423. } catch (const char *error) {
  1424. blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error);
  1425. }
  1426. }
  1427. void device_copy_texture(gs_device_t *device, gs_texture_t *dst,
  1428. gs_texture_t *src)
  1429. {
  1430. device_copy_texture_region(device, dst, 0, 0, src, 0, 0, 0, 0);
  1431. }
  1432. void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst,
  1433. gs_texture_t *src)
  1434. {
  1435. try {
  1436. gs_texture_2d *src2d = static_cast<gs_texture_2d *>(src);
  1437. if (!src)
  1438. throw "Source texture is NULL";
  1439. if (src->type != GS_TEXTURE_2D)
  1440. throw "Source texture must be a 2D texture";
  1441. if (!dst)
  1442. throw "Destination surface is NULL";
  1443. if (dst->format != GS_UNKNOWN && dst->format != src->format)
  1444. throw "Source and destination formats do not match";
  1445. if (dst->width != src2d->width || dst->height != src2d->height)
  1446. throw "Source and destination must have the same "
  1447. "dimensions";
  1448. device->CopyTex(dst->texture, 0, 0, src, 0, 0, 0, 0);
  1449. } catch (const char *error) {
  1450. blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error);
  1451. }
  1452. }
  1453. extern "C" void reset_duplicators(void);
  1454. void device_begin_frame(gs_device_t *device)
  1455. {
  1456. /* does nothing in D3D11 */
  1457. UNUSED_PARAMETER(device);
  1458. reset_duplicators();
  1459. }
  1460. void device_begin_scene(gs_device_t *device)
  1461. {
  1462. clear_textures(device);
  1463. }
  1464. void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode,
  1465. uint32_t start_vert, uint32_t num_verts)
  1466. {
  1467. try {
  1468. if (!device->curVertexShader)
  1469. throw "No vertex shader specified";
  1470. if (!device->curPixelShader)
  1471. throw "No pixel shader specified";
  1472. if (!device->curVertexBuffer && (num_verts == 0))
  1473. throw "No vertex buffer specified";
  1474. if (!device->curSwapChain && !device->curRenderTarget)
  1475. throw "No render target or swap chain to render to";
  1476. gs_effect_t *effect = gs_get_effect();
  1477. if (effect)
  1478. gs_effect_update_params(effect);
  1479. device->LoadVertexBufferData();
  1480. device->UpdateBlendState();
  1481. device->UpdateRasterState();
  1482. device->UpdateZStencilState();
  1483. device->UpdateViewProjMatrix();
  1484. device->curVertexShader->UploadParams();
  1485. device->curPixelShader->UploadParams();
  1486. } catch (const char *error) {
  1487. blog(LOG_ERROR, "device_draw (D3D11): %s", error);
  1488. return;
  1489. } catch (const HRError &error) {
  1490. blog(LOG_ERROR, "device_draw (D3D11): %s (%08lX)", error.str,
  1491. error.hr);
  1492. LogD3D11ErrorDetails(error, device);
  1493. return;
  1494. }
  1495. D3D11_PRIMITIVE_TOPOLOGY newTopology = ConvertGSTopology(draw_mode);
  1496. if (device->curToplogy != newTopology) {
  1497. device->context->IASetPrimitiveTopology(newTopology);
  1498. device->curToplogy = newTopology;
  1499. }
  1500. if (device->curIndexBuffer) {
  1501. if (num_verts == 0)
  1502. num_verts = (uint32_t)device->curIndexBuffer->num;
  1503. device->context->DrawIndexed(num_verts, start_vert, 0);
  1504. } else {
  1505. if (num_verts == 0)
  1506. num_verts = (uint32_t)device->curVertexBuffer->numVerts;
  1507. device->context->Draw(num_verts, start_vert);
  1508. }
  1509. }
  1510. void device_end_scene(gs_device_t *device)
  1511. {
  1512. /* does nothing in D3D11 */
  1513. UNUSED_PARAMETER(device);
  1514. }
  1515. void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swapchain)
  1516. {
  1517. gs_texture_t *target = device->curRenderTarget;
  1518. gs_zstencil_t *zs = device->curZStencilBuffer;
  1519. bool is_cube =
  1520. device->curRenderTarget
  1521. ? (device->curRenderTarget->type == GS_TEXTURE_CUBE)
  1522. : false;
  1523. if (device->curSwapChain) {
  1524. if (target == &device->curSwapChain->target)
  1525. target = NULL;
  1526. if (zs == &device->curSwapChain->zs)
  1527. zs = NULL;
  1528. }
  1529. device->curSwapChain = swapchain;
  1530. if (is_cube)
  1531. device_set_cube_render_target(device, target,
  1532. device->curRenderSide, zs);
  1533. else
  1534. device_set_render_target(device, target, zs);
  1535. }
  1536. void device_clear(gs_device_t *device, uint32_t clear_flags,
  1537. const struct vec4 *color, float depth, uint8_t stencil)
  1538. {
  1539. int side = device->curRenderSide;
  1540. if ((clear_flags & GS_CLEAR_COLOR) != 0 && device->curRenderTarget)
  1541. device->context->ClearRenderTargetView(
  1542. device->curRenderTarget->renderTarget[side],
  1543. color->ptr);
  1544. if (device->curZStencilBuffer) {
  1545. uint32_t flags = 0;
  1546. if ((clear_flags & GS_CLEAR_DEPTH) != 0)
  1547. flags |= D3D11_CLEAR_DEPTH;
  1548. if ((clear_flags & GS_CLEAR_STENCIL) != 0)
  1549. flags |= D3D11_CLEAR_STENCIL;
  1550. if (flags && device->curZStencilBuffer->view)
  1551. device->context->ClearDepthStencilView(
  1552. device->curZStencilBuffer->view, flags, depth,
  1553. stencil);
  1554. }
  1555. }
  1556. void device_present(gs_device_t *device)
  1557. {
  1558. HRESULT hr;
  1559. if (device->curSwapChain) {
  1560. hr = device->curSwapChain->swap->Present(0, 0);
  1561. if (hr == DXGI_ERROR_DEVICE_REMOVED ||
  1562. hr == DXGI_ERROR_DEVICE_RESET) {
  1563. device->RebuildDevice();
  1564. }
  1565. } else {
  1566. blog(LOG_WARNING, "device_present (D3D11): No active swap");
  1567. }
  1568. }
  1569. void device_flush(gs_device_t *device)
  1570. {
  1571. device->context->Flush();
  1572. }
  1573. void device_set_cull_mode(gs_device_t *device, enum gs_cull_mode mode)
  1574. {
  1575. if (mode == device->rasterState.cullMode)
  1576. return;
  1577. device->rasterState.cullMode = mode;
  1578. device->rasterStateChanged = true;
  1579. }
  1580. enum gs_cull_mode device_get_cull_mode(const gs_device_t *device)
  1581. {
  1582. return device->rasterState.cullMode;
  1583. }
  1584. void device_enable_blending(gs_device_t *device, bool enable)
  1585. {
  1586. if (enable == device->blendState.blendEnabled)
  1587. return;
  1588. device->blendState.blendEnabled = enable;
  1589. device->blendStateChanged = true;
  1590. }
  1591. void device_enable_depth_test(gs_device_t *device, bool enable)
  1592. {
  1593. if (enable == device->zstencilState.depthEnabled)
  1594. return;
  1595. device->zstencilState.depthEnabled = enable;
  1596. device->zstencilStateChanged = true;
  1597. }
  1598. void device_enable_stencil_test(gs_device_t *device, bool enable)
  1599. {
  1600. if (enable == device->zstencilState.stencilEnabled)
  1601. return;
  1602. device->zstencilState.stencilEnabled = enable;
  1603. device->zstencilStateChanged = true;
  1604. }
  1605. void device_enable_stencil_write(gs_device_t *device, bool enable)
  1606. {
  1607. if (enable == device->zstencilState.stencilWriteEnabled)
  1608. return;
  1609. device->zstencilState.stencilWriteEnabled = enable;
  1610. device->zstencilStateChanged = true;
  1611. }
  1612. void device_enable_color(gs_device_t *device, bool red, bool green, bool blue,
  1613. bool alpha)
  1614. {
  1615. if (device->blendState.redEnabled == red &&
  1616. device->blendState.greenEnabled == green &&
  1617. device->blendState.blueEnabled == blue &&
  1618. device->blendState.alphaEnabled == alpha)
  1619. return;
  1620. device->blendState.redEnabled = red;
  1621. device->blendState.greenEnabled = green;
  1622. device->blendState.blueEnabled = blue;
  1623. device->blendState.alphaEnabled = alpha;
  1624. device->blendStateChanged = true;
  1625. }
  1626. void device_blend_function(gs_device_t *device, enum gs_blend_type src,
  1627. enum gs_blend_type dest)
  1628. {
  1629. if (device->blendState.srcFactorC == src &&
  1630. device->blendState.destFactorC == dest &&
  1631. device->blendState.srcFactorA == src &&
  1632. device->blendState.destFactorA == dest)
  1633. return;
  1634. device->blendState.srcFactorC = src;
  1635. device->blendState.destFactorC = dest;
  1636. device->blendState.srcFactorA = src;
  1637. device->blendState.destFactorA = dest;
  1638. device->blendStateChanged = true;
  1639. }
  1640. void device_blend_function_separate(gs_device_t *device,
  1641. enum gs_blend_type src_c,
  1642. enum gs_blend_type dest_c,
  1643. enum gs_blend_type src_a,
  1644. enum gs_blend_type dest_a)
  1645. {
  1646. if (device->blendState.srcFactorC == src_c &&
  1647. device->blendState.destFactorC == dest_c &&
  1648. device->blendState.srcFactorA == src_a &&
  1649. device->blendState.destFactorA == dest_a)
  1650. return;
  1651. device->blendState.srcFactorC = src_c;
  1652. device->blendState.destFactorC = dest_c;
  1653. device->blendState.srcFactorA = src_a;
  1654. device->blendState.destFactorA = dest_a;
  1655. device->blendStateChanged = true;
  1656. }
  1657. void device_depth_function(gs_device_t *device, enum gs_depth_test test)
  1658. {
  1659. if (device->zstencilState.depthFunc == test)
  1660. return;
  1661. device->zstencilState.depthFunc = test;
  1662. device->zstencilStateChanged = true;
  1663. }
  1664. static inline void update_stencilside_test(gs_device_t *device,
  1665. StencilSide &side,
  1666. gs_depth_test test)
  1667. {
  1668. if (side.test == test)
  1669. return;
  1670. side.test = test;
  1671. device->zstencilStateChanged = true;
  1672. }
  1673. void device_stencil_function(gs_device_t *device, enum gs_stencil_side side,
  1674. enum gs_depth_test test)
  1675. {
  1676. int sideVal = (int)side;
  1677. if (sideVal & GS_STENCIL_FRONT)
  1678. update_stencilside_test(
  1679. device, device->zstencilState.stencilFront, test);
  1680. if (sideVal & GS_STENCIL_BACK)
  1681. update_stencilside_test(
  1682. device, device->zstencilState.stencilBack, test);
  1683. }
  1684. static inline void update_stencilside_op(gs_device_t *device, StencilSide &side,
  1685. enum gs_stencil_op_type fail,
  1686. enum gs_stencil_op_type zfail,
  1687. enum gs_stencil_op_type zpass)
  1688. {
  1689. if (side.fail == fail && side.zfail == zfail && side.zpass == zpass)
  1690. return;
  1691. side.fail = fail;
  1692. side.zfail = zfail;
  1693. side.zpass = zpass;
  1694. device->zstencilStateChanged = true;
  1695. }
  1696. void device_stencil_op(gs_device_t *device, enum gs_stencil_side side,
  1697. enum gs_stencil_op_type fail,
  1698. enum gs_stencil_op_type zfail,
  1699. enum gs_stencil_op_type zpass)
  1700. {
  1701. int sideVal = (int)side;
  1702. if (sideVal & GS_STENCIL_FRONT)
  1703. update_stencilside_op(device,
  1704. device->zstencilState.stencilFront, fail,
  1705. zfail, zpass);
  1706. if (sideVal & GS_STENCIL_BACK)
  1707. update_stencilside_op(device, device->zstencilState.stencilBack,
  1708. fail, zfail, zpass);
  1709. }
  1710. void device_set_viewport(gs_device_t *device, int x, int y, int width,
  1711. int height)
  1712. {
  1713. D3D11_VIEWPORT vp;
  1714. memset(&vp, 0, sizeof(vp));
  1715. vp.MaxDepth = 1.0f;
  1716. vp.TopLeftX = (float)x;
  1717. vp.TopLeftY = (float)y;
  1718. vp.Width = (float)width;
  1719. vp.Height = (float)height;
  1720. device->context->RSSetViewports(1, &vp);
  1721. device->viewport.x = x;
  1722. device->viewport.y = y;
  1723. device->viewport.cx = width;
  1724. device->viewport.cy = height;
  1725. }
  1726. void device_get_viewport(const gs_device_t *device, struct gs_rect *rect)
  1727. {
  1728. memcpy(rect, &device->viewport, sizeof(gs_rect));
  1729. }
  1730. void device_set_scissor_rect(gs_device_t *device, const struct gs_rect *rect)
  1731. {
  1732. D3D11_RECT d3drect;
  1733. device->rasterState.scissorEnabled = (rect != NULL);
  1734. if (rect != NULL) {
  1735. d3drect.left = rect->x;
  1736. d3drect.top = rect->y;
  1737. d3drect.right = rect->x + rect->cx;
  1738. d3drect.bottom = rect->y + rect->cy;
  1739. device->context->RSSetScissorRects(1, &d3drect);
  1740. }
  1741. device->rasterStateChanged = true;
  1742. }
  1743. void device_ortho(gs_device_t *device, float left, float right, float top,
  1744. float bottom, float zNear, float zFar)
  1745. {
  1746. matrix4 *dst = &device->curProjMatrix;
  1747. float rml = right - left;
  1748. float bmt = bottom - top;
  1749. float fmn = zFar - zNear;
  1750. vec4_zero(&dst->x);
  1751. vec4_zero(&dst->y);
  1752. vec4_zero(&dst->z);
  1753. vec4_zero(&dst->t);
  1754. dst->x.x = 2.0f / rml;
  1755. dst->t.x = (left + right) / -rml;
  1756. dst->y.y = 2.0f / -bmt;
  1757. dst->t.y = (bottom + top) / bmt;
  1758. dst->z.z = 1.0f / fmn;
  1759. dst->t.z = zNear / -fmn;
  1760. dst->t.w = 1.0f;
  1761. }
  1762. void device_frustum(gs_device_t *device, float left, float right, float top,
  1763. float bottom, float zNear, float zFar)
  1764. {
  1765. matrix4 *dst = &device->curProjMatrix;
  1766. float rml = right - left;
  1767. float bmt = bottom - top;
  1768. float fmn = zFar - zNear;
  1769. float nearx2 = 2.0f * zNear;
  1770. vec4_zero(&dst->x);
  1771. vec4_zero(&dst->y);
  1772. vec4_zero(&dst->z);
  1773. vec4_zero(&dst->t);
  1774. dst->x.x = nearx2 / rml;
  1775. dst->z.x = (left + right) / -rml;
  1776. dst->y.y = nearx2 / -bmt;
  1777. dst->z.y = (bottom + top) / bmt;
  1778. dst->z.z = zFar / fmn;
  1779. dst->t.z = (zNear * zFar) / -fmn;
  1780. dst->z.w = 1.0f;
  1781. }
  1782. void device_projection_push(gs_device_t *device)
  1783. {
  1784. mat4float mat;
  1785. memcpy(&mat, &device->curProjMatrix, sizeof(matrix4));
  1786. device->projStack.push_back(mat);
  1787. }
  1788. void device_projection_pop(gs_device_t *device)
  1789. {
  1790. if (device->projStack.empty())
  1791. return;
  1792. const mat4float &mat = device->projStack.back();
  1793. memcpy(&device->curProjMatrix, &mat, sizeof(matrix4));
  1794. device->projStack.pop_back();
  1795. }
  1796. void gs_swapchain_destroy(gs_swapchain_t *swapchain)
  1797. {
  1798. if (swapchain->device->curSwapChain == swapchain)
  1799. device_load_swapchain(swapchain->device, nullptr);
  1800. delete swapchain;
  1801. }
  1802. void gs_texture_destroy(gs_texture_t *tex)
  1803. {
  1804. delete tex;
  1805. }
  1806. uint32_t gs_texture_get_width(const gs_texture_t *tex)
  1807. {
  1808. if (tex->type != GS_TEXTURE_2D)
  1809. return 0;
  1810. return static_cast<const gs_texture_2d *>(tex)->width;
  1811. }
  1812. uint32_t gs_texture_get_height(const gs_texture_t *tex)
  1813. {
  1814. if (tex->type != GS_TEXTURE_2D)
  1815. return 0;
  1816. return static_cast<const gs_texture_2d *>(tex)->height;
  1817. }
  1818. enum gs_color_format gs_texture_get_color_format(const gs_texture_t *tex)
  1819. {
  1820. if (tex->type != GS_TEXTURE_2D)
  1821. return GS_UNKNOWN;
  1822. return static_cast<const gs_texture_2d *>(tex)->format;
  1823. }
  1824. bool gs_texture_map(gs_texture_t *tex, uint8_t **ptr, uint32_t *linesize)
  1825. {
  1826. HRESULT hr;
  1827. if (tex->type != GS_TEXTURE_2D)
  1828. return false;
  1829. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1830. D3D11_MAPPED_SUBRESOURCE map;
  1831. hr = tex2d->device->context->Map(tex2d->texture, 0,
  1832. D3D11_MAP_WRITE_DISCARD, 0, &map);
  1833. if (FAILED(hr))
  1834. return false;
  1835. *ptr = (uint8_t *)map.pData;
  1836. *linesize = map.RowPitch;
  1837. return true;
  1838. }
  1839. void gs_texture_unmap(gs_texture_t *tex)
  1840. {
  1841. if (tex->type != GS_TEXTURE_2D)
  1842. return;
  1843. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1844. tex2d->device->context->Unmap(tex2d->texture, 0);
  1845. }
  1846. void *gs_texture_get_obj(gs_texture_t *tex)
  1847. {
  1848. if (tex->type != GS_TEXTURE_2D)
  1849. return nullptr;
  1850. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1851. return tex2d->texture.Get();
  1852. }
  1853. void gs_cubetexture_destroy(gs_texture_t *cubetex)
  1854. {
  1855. delete cubetex;
  1856. }
  1857. uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex)
  1858. {
  1859. if (cubetex->type != GS_TEXTURE_CUBE)
  1860. return 0;
  1861. const gs_texture_2d *tex = static_cast<const gs_texture_2d *>(cubetex);
  1862. return tex->width;
  1863. }
  1864. enum gs_color_format
  1865. gs_cubetexture_get_color_format(const gs_texture_t *cubetex)
  1866. {
  1867. if (cubetex->type != GS_TEXTURE_CUBE)
  1868. return GS_UNKNOWN;
  1869. const gs_texture_2d *tex = static_cast<const gs_texture_2d *>(cubetex);
  1870. return tex->format;
  1871. }
  1872. void gs_voltexture_destroy(gs_texture_t *voltex)
  1873. {
  1874. delete voltex;
  1875. }
  1876. uint32_t gs_voltexture_get_width(const gs_texture_t *voltex)
  1877. {
  1878. /* TODO */
  1879. UNUSED_PARAMETER(voltex);
  1880. return 0;
  1881. }
  1882. uint32_t gs_voltexture_get_height(const gs_texture_t *voltex)
  1883. {
  1884. /* TODO */
  1885. UNUSED_PARAMETER(voltex);
  1886. return 0;
  1887. }
  1888. uint32_t gs_voltexture_get_depth(const gs_texture_t *voltex)
  1889. {
  1890. /* TODO */
  1891. UNUSED_PARAMETER(voltex);
  1892. return 0;
  1893. }
  1894. enum gs_color_format gs_voltexture_get_color_format(const gs_texture_t *voltex)
  1895. {
  1896. /* TODO */
  1897. UNUSED_PARAMETER(voltex);
  1898. return GS_UNKNOWN;
  1899. }
  1900. void gs_stagesurface_destroy(gs_stagesurf_t *stagesurf)
  1901. {
  1902. delete stagesurf;
  1903. }
  1904. uint32_t gs_stagesurface_get_width(const gs_stagesurf_t *stagesurf)
  1905. {
  1906. return stagesurf->width;
  1907. }
  1908. uint32_t gs_stagesurface_get_height(const gs_stagesurf_t *stagesurf)
  1909. {
  1910. return stagesurf->height;
  1911. }
  1912. enum gs_color_format
  1913. gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf)
  1914. {
  1915. return stagesurf->format;
  1916. }
  1917. bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data,
  1918. uint32_t *linesize)
  1919. {
  1920. D3D11_MAPPED_SUBRESOURCE map;
  1921. if (FAILED(stagesurf->device->context->Map(stagesurf->texture, 0,
  1922. D3D11_MAP_READ, 0, &map)))
  1923. return false;
  1924. *data = (uint8_t *)map.pData;
  1925. *linesize = map.RowPitch;
  1926. return true;
  1927. }
  1928. void gs_stagesurface_unmap(gs_stagesurf_t *stagesurf)
  1929. {
  1930. stagesurf->device->context->Unmap(stagesurf->texture, 0);
  1931. }
  1932. void gs_zstencil_destroy(gs_zstencil_t *zstencil)
  1933. {
  1934. delete zstencil;
  1935. }
  1936. void gs_samplerstate_destroy(gs_samplerstate_t *samplerstate)
  1937. {
  1938. if (!samplerstate)
  1939. return;
  1940. if (samplerstate->device)
  1941. for (int i = 0; i < GS_MAX_TEXTURES; i++)
  1942. if (samplerstate->device->curSamplers[i] ==
  1943. samplerstate)
  1944. samplerstate->device->curSamplers[i] = nullptr;
  1945. delete samplerstate;
  1946. }
  1947. void gs_vertexbuffer_destroy(gs_vertbuffer_t *vertbuffer)
  1948. {
  1949. if (vertbuffer && vertbuffer->device->lastVertexBuffer == vertbuffer)
  1950. vertbuffer->device->lastVertexBuffer = nullptr;
  1951. delete vertbuffer;
  1952. }
  1953. static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vertbuffer,
  1954. const gs_vb_data *data)
  1955. {
  1956. size_t num_tex = data->num_tex < vertbuffer->uvBuffers.size()
  1957. ? data->num_tex
  1958. : vertbuffer->uvBuffers.size();
  1959. if (!vertbuffer->dynamic) {
  1960. blog(LOG_ERROR, "gs_vertexbuffer_flush: vertex buffer is "
  1961. "not dynamic");
  1962. return;
  1963. }
  1964. if (data->points)
  1965. vertbuffer->FlushBuffer(vertbuffer->vertexBuffer, data->points,
  1966. sizeof(vec3));
  1967. if (vertbuffer->normalBuffer && data->normals)
  1968. vertbuffer->FlushBuffer(vertbuffer->normalBuffer, data->normals,
  1969. sizeof(vec3));
  1970. if (vertbuffer->tangentBuffer && data->tangents)
  1971. vertbuffer->FlushBuffer(vertbuffer->tangentBuffer,
  1972. data->tangents, sizeof(vec3));
  1973. if (vertbuffer->colorBuffer && data->colors)
  1974. vertbuffer->FlushBuffer(vertbuffer->colorBuffer, data->colors,
  1975. sizeof(uint32_t));
  1976. for (size_t i = 0; i < num_tex; i++) {
  1977. gs_tvertarray &tv = data->tvarray[i];
  1978. vertbuffer->FlushBuffer(vertbuffer->uvBuffers[i], tv.array,
  1979. tv.width * sizeof(float));
  1980. }
  1981. }
  1982. void gs_vertexbuffer_flush(gs_vertbuffer_t *vertbuffer)
  1983. {
  1984. gs_vertexbuffer_flush_internal(vertbuffer, vertbuffer->vbd.data);
  1985. }
  1986. void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vertbuffer,
  1987. const gs_vb_data *data)
  1988. {
  1989. gs_vertexbuffer_flush_internal(vertbuffer, data);
  1990. }
  1991. struct gs_vb_data *gs_vertexbuffer_get_data(const gs_vertbuffer_t *vertbuffer)
  1992. {
  1993. return vertbuffer->vbd.data;
  1994. }
  1995. void gs_indexbuffer_destroy(gs_indexbuffer_t *indexbuffer)
  1996. {
  1997. delete indexbuffer;
  1998. }
  1999. static inline void gs_indexbuffer_flush_internal(gs_indexbuffer_t *indexbuffer,
  2000. const void *data)
  2001. {
  2002. HRESULT hr;
  2003. if (!indexbuffer->dynamic)
  2004. return;
  2005. D3D11_MAPPED_SUBRESOURCE map;
  2006. hr = indexbuffer->device->context->Map(
  2007. indexbuffer->indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
  2008. if (FAILED(hr))
  2009. return;
  2010. memcpy(map.pData, data, indexbuffer->num * indexbuffer->indexSize);
  2011. indexbuffer->device->context->Unmap(indexbuffer->indexBuffer, 0);
  2012. }
  2013. void gs_indexbuffer_flush(gs_indexbuffer_t *indexbuffer)
  2014. {
  2015. gs_indexbuffer_flush_internal(indexbuffer, indexbuffer->indices.data);
  2016. }
  2017. void gs_indexbuffer_flush_direct(gs_indexbuffer_t *indexbuffer,
  2018. const void *data)
  2019. {
  2020. gs_indexbuffer_flush_internal(indexbuffer, data);
  2021. }
  2022. void *gs_indexbuffer_get_data(const gs_indexbuffer_t *indexbuffer)
  2023. {
  2024. return indexbuffer->indices.data;
  2025. }
  2026. size_t gs_indexbuffer_get_num_indices(const gs_indexbuffer_t *indexbuffer)
  2027. {
  2028. return indexbuffer->num;
  2029. }
  2030. enum gs_index_type gs_indexbuffer_get_type(const gs_indexbuffer_t *indexbuffer)
  2031. {
  2032. return indexbuffer->type;
  2033. }
  2034. void gs_timer_destroy(gs_timer_t *timer)
  2035. {
  2036. delete timer;
  2037. }
  2038. void gs_timer_begin(gs_timer_t *timer)
  2039. {
  2040. timer->device->context->End(timer->query_begin);
  2041. }
  2042. void gs_timer_end(gs_timer_t *timer)
  2043. {
  2044. timer->device->context->End(timer->query_end);
  2045. }
  2046. bool gs_timer_get_data(gs_timer_t *timer, uint64_t *ticks)
  2047. {
  2048. uint64_t begin, end;
  2049. HRESULT hr_begin, hr_end;
  2050. do {
  2051. hr_begin = timer->device->context->GetData(
  2052. timer->query_begin, &begin, sizeof(begin), 0);
  2053. } while (hr_begin == S_FALSE);
  2054. do {
  2055. hr_end = timer->device->context->GetData(timer->query_end, &end,
  2056. sizeof(end), 0);
  2057. } while (hr_end == S_FALSE);
  2058. const bool succeeded = SUCCEEDED(hr_begin) && SUCCEEDED(hr_end);
  2059. if (succeeded)
  2060. *ticks = end - begin;
  2061. return succeeded;
  2062. }
  2063. void gs_timer_range_destroy(gs_timer_range_t *range)
  2064. {
  2065. delete range;
  2066. }
  2067. void gs_timer_range_begin(gs_timer_range_t *range)
  2068. {
  2069. range->device->context->Begin(range->query_disjoint);
  2070. }
  2071. void gs_timer_range_end(gs_timer_range_t *range)
  2072. {
  2073. range->device->context->End(range->query_disjoint);
  2074. }
  2075. bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint,
  2076. uint64_t *frequency)
  2077. {
  2078. D3D11_QUERY_DATA_TIMESTAMP_DISJOINT timestamp_disjoint;
  2079. HRESULT hr;
  2080. do {
  2081. hr = range->device->context->GetData(range->query_disjoint,
  2082. &timestamp_disjoint,
  2083. sizeof(timestamp_disjoint),
  2084. 0);
  2085. } while (hr == S_FALSE);
  2086. const bool succeeded = SUCCEEDED(hr);
  2087. if (succeeded) {
  2088. *disjoint = timestamp_disjoint.Disjoint;
  2089. *frequency = timestamp_disjoint.Frequency;
  2090. }
  2091. return succeeded;
  2092. }
  2093. gs_timer::gs_timer(gs_device_t *device) : gs_obj(device, gs_type::gs_timer)
  2094. {
  2095. Rebuild(device->device);
  2096. }
  2097. gs_timer_range::gs_timer_range(gs_device_t *device)
  2098. : gs_obj(device, gs_type::gs_timer_range)
  2099. {
  2100. Rebuild(device->device);
  2101. }
  2102. extern "C" EXPORT bool device_gdi_texture_available(void)
  2103. {
  2104. return true;
  2105. }
  2106. extern "C" EXPORT bool device_shared_texture_available(void)
  2107. {
  2108. return true;
  2109. }
  2110. extern "C" EXPORT bool device_nv12_available(gs_device_t *device)
  2111. {
  2112. return device->nv12Supported;
  2113. }
  2114. extern "C" EXPORT void device_debug_marker_begin(gs_device_t *,
  2115. const char *markername,
  2116. const float color[4])
  2117. {
  2118. D3DCOLOR bgra = D3DCOLOR_ARGB((DWORD)(255.0f * color[3]),
  2119. (DWORD)(255.0f * color[0]),
  2120. (DWORD)(255.0f * color[1]),
  2121. (DWORD)(255.0f * color[2]));
  2122. wchar_t wide[64];
  2123. os_utf8_to_wcs(markername, 0, wide, _countof(wide));
  2124. D3DPERF_BeginEvent(bgra, wide);
  2125. }
  2126. extern "C" EXPORT void device_debug_marker_end(gs_device_t *)
  2127. {
  2128. D3DPERF_EndEvent();
  2129. }
  2130. extern "C" EXPORT gs_texture_t *
  2131. device_texture_create_gdi(gs_device_t *device, uint32_t width, uint32_t height)
  2132. {
  2133. gs_texture *texture = nullptr;
  2134. try {
  2135. texture = new gs_texture_2d(device, width, height, GS_BGRA, 1,
  2136. nullptr, GS_RENDER_TARGET,
  2137. GS_TEXTURE_2D, true);
  2138. } catch (const HRError &error) {
  2139. blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s (%08lX)",
  2140. error.str, error.hr);
  2141. LogD3D11ErrorDetails(error, device);
  2142. } catch (const char *error) {
  2143. blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s", error);
  2144. }
  2145. return texture;
  2146. }
  2147. static inline bool TextureGDICompatible(gs_texture_2d *tex2d, const char *func)
  2148. {
  2149. if (!tex2d->isGDICompatible) {
  2150. blog(LOG_ERROR, "%s (D3D11): Texture is not GDI compatible",
  2151. func);
  2152. return false;
  2153. }
  2154. return true;
  2155. }
  2156. extern "C" EXPORT void *gs_texture_get_dc(gs_texture_t *tex)
  2157. {
  2158. HDC hDC = nullptr;
  2159. if (tex->type != GS_TEXTURE_2D)
  2160. return nullptr;
  2161. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2162. if (!TextureGDICompatible(tex2d, "gs_texture_get_dc"))
  2163. return nullptr;
  2164. if (!tex2d->gdiSurface)
  2165. return nullptr;
  2166. tex2d->gdiSurface->GetDC(true, &hDC);
  2167. return hDC;
  2168. }
  2169. extern "C" EXPORT void gs_texture_release_dc(gs_texture_t *tex)
  2170. {
  2171. if (tex->type != GS_TEXTURE_2D)
  2172. return;
  2173. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2174. if (!TextureGDICompatible(tex2d, "gs_texture_release_dc"))
  2175. return;
  2176. tex2d->gdiSurface->ReleaseDC(nullptr);
  2177. }
  2178. extern "C" EXPORT gs_texture_t *device_texture_open_shared(gs_device_t *device,
  2179. uint32_t handle)
  2180. {
  2181. gs_texture *texture = nullptr;
  2182. try {
  2183. texture = new gs_texture_2d(device, handle);
  2184. } catch (const HRError &error) {
  2185. blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s (%08lX)",
  2186. error.str, error.hr);
  2187. LogD3D11ErrorDetails(error, device);
  2188. } catch (const char *error) {
  2189. blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s", error);
  2190. }
  2191. return texture;
  2192. }
  2193. extern "C" EXPORT uint32_t device_texture_get_shared_handle(gs_texture_t *tex)
  2194. {
  2195. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2196. if (tex->type != GS_TEXTURE_2D)
  2197. return GS_INVALID_HANDLE;
  2198. return tex2d->isShared ? tex2d->sharedHandle : GS_INVALID_HANDLE;
  2199. }
  2200. extern "C" EXPORT gs_texture_t *device_texture_wrap_obj(gs_device_t *device,
  2201. void *obj)
  2202. {
  2203. gs_texture *texture = nullptr;
  2204. try {
  2205. texture = new gs_texture_2d(device, (ID3D11Texture2D *)obj);
  2206. } catch (const HRError &error) {
  2207. blog(LOG_ERROR, "gs_texture_wrap_obj (D3D11): %s (%08lX)",
  2208. error.str, error.hr);
  2209. LogD3D11ErrorDetails(error, device);
  2210. } catch (const char *error) {
  2211. blog(LOG_ERROR, "gs_texture_wrap_obj (D3D11): %s", error);
  2212. }
  2213. return texture;
  2214. }
  2215. int device_texture_acquire_sync(gs_texture_t *tex, uint64_t key, uint32_t ms)
  2216. {
  2217. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2218. if (tex->type != GS_TEXTURE_2D)
  2219. return -1;
  2220. if (tex2d->acquired)
  2221. return 0;
  2222. ComQIPtr<IDXGIKeyedMutex> keyedMutex(tex2d->texture);
  2223. if (!keyedMutex)
  2224. return -1;
  2225. HRESULT hr = keyedMutex->AcquireSync(key, ms);
  2226. if (hr == S_OK) {
  2227. tex2d->acquired = true;
  2228. return 0;
  2229. } else if (hr == WAIT_TIMEOUT) {
  2230. return ETIMEDOUT;
  2231. }
  2232. return -1;
  2233. }
  2234. extern "C" EXPORT int device_texture_release_sync(gs_texture_t *tex,
  2235. uint64_t key)
  2236. {
  2237. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2238. if (tex->type != GS_TEXTURE_2D)
  2239. return -1;
  2240. if (!tex2d->acquired)
  2241. return 0;
  2242. ComQIPtr<IDXGIKeyedMutex> keyedMutex(tex2d->texture);
  2243. if (!keyedMutex)
  2244. return -1;
  2245. HRESULT hr = keyedMutex->ReleaseSync(key);
  2246. if (hr == S_OK) {
  2247. tex2d->acquired = false;
  2248. return 0;
  2249. }
  2250. return -1;
  2251. }
  2252. extern "C" EXPORT bool
  2253. device_texture_create_nv12(gs_device_t *device, gs_texture_t **p_tex_y,
  2254. gs_texture_t **p_tex_uv, uint32_t width,
  2255. uint32_t height, uint32_t flags)
  2256. {
  2257. if (!device->nv12Supported)
  2258. return false;
  2259. *p_tex_y = nullptr;
  2260. *p_tex_uv = nullptr;
  2261. gs_texture_2d *tex_y;
  2262. gs_texture_2d *tex_uv;
  2263. try {
  2264. tex_y = new gs_texture_2d(device, width, height, GS_R8, 1,
  2265. nullptr, flags, GS_TEXTURE_2D, false,
  2266. true);
  2267. tex_uv = new gs_texture_2d(device, tex_y->texture, flags);
  2268. } catch (const HRError &error) {
  2269. blog(LOG_ERROR, "gs_texture_create_nv12 (D3D11): %s (%08lX)",
  2270. error.str, error.hr);
  2271. LogD3D11ErrorDetails(error, device);
  2272. return false;
  2273. } catch (const char *error) {
  2274. blog(LOG_ERROR, "gs_texture_create_nv12 (D3D11): %s", error);
  2275. return false;
  2276. }
  2277. tex_y->pairedNV12texture = tex_uv;
  2278. tex_uv->pairedNV12texture = tex_y;
  2279. *p_tex_y = tex_y;
  2280. *p_tex_uv = tex_uv;
  2281. return true;
  2282. }
  2283. extern "C" EXPORT gs_stagesurf_t *
  2284. device_stagesurface_create_nv12(gs_device_t *device, uint32_t width,
  2285. uint32_t height)
  2286. {
  2287. gs_stage_surface *surf = NULL;
  2288. try {
  2289. surf = new gs_stage_surface(device, width, height);
  2290. } catch (const HRError &error) {
  2291. blog(LOG_ERROR,
  2292. "device_stagesurface_create (D3D11): %s "
  2293. "(%08lX)",
  2294. error.str, error.hr);
  2295. LogD3D11ErrorDetails(error, device);
  2296. }
  2297. return surf;
  2298. }
  2299. extern "C" EXPORT void
  2300. device_register_loss_callbacks(gs_device_t *device,
  2301. const gs_device_loss *callbacks)
  2302. {
  2303. device->loss_callbacks.emplace_back(*callbacks);
  2304. }
  2305. extern "C" EXPORT void device_unregister_loss_callbacks(gs_device_t *device,
  2306. void *data)
  2307. {
  2308. for (auto iter = device->loss_callbacks.begin();
  2309. iter != device->loss_callbacks.end(); ++iter) {
  2310. if (iter->data == data) {
  2311. device->loss_callbacks.erase(iter);
  2312. break;
  2313. }
  2314. }
  2315. }