d3d11-subsystem.cpp 65 KB

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