d3d11-subsystem.cpp 56 KB

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