d3d11-subsystem.cpp 64 KB

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