d3d11-subsystem.cpp 75 KB

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