d3d11-subsystem.cpp 55 KB

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