d3d11-subsystem.cpp 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220
  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 DXGI_COLOR_SPACE_TYPE GetColorSpace(IDXGIOutput *const output)
  836. {
  837. DXGI_COLOR_SPACE_TYPE space = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
  838. ComPtr<IDXGIOutput6> output6;
  839. HRESULT hr = output->QueryInterface(IID_PPV_ARGS(output6.Assign()));
  840. if (SUCCEEDED(hr)) {
  841. DXGI_OUTPUT_DESC1 desc1;
  842. hr = output6->GetDesc1(&desc1);
  843. if (SUCCEEDED(hr)) {
  844. space = desc1.ColorSpace;
  845. } else {
  846. blog(LOG_WARNING,
  847. "IDXGIOutput6::GetDesc1 failed: 0x%08lX", hr);
  848. }
  849. }
  850. return space;
  851. }
  852. // Returns true if this is an integrated display panel e.g. the screen attached to tablets or laptops.
  853. static bool IsInternalVideoOutput(
  854. const DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY VideoOutputTechnologyType)
  855. {
  856. switch (VideoOutputTechnologyType) {
  857. case DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INTERNAL:
  858. case DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EMBEDDED:
  859. case DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EMBEDDED:
  860. return TRUE;
  861. default:
  862. return FALSE;
  863. }
  864. }
  865. // Note: Since an hmon can represent multiple monitors while in clone, this function as written will return
  866. // the value for the internal monitor if one exists, and otherwise the highest clone-path priority.
  867. static HRESULT GetPathInfo(_In_ PCWSTR pszDeviceName,
  868. _Out_ DISPLAYCONFIG_PATH_INFO *pPathInfo)
  869. {
  870. HRESULT hr = S_OK;
  871. UINT32 NumPathArrayElements = 0;
  872. UINT32 NumModeInfoArrayElements = 0;
  873. DISPLAYCONFIG_PATH_INFO *PathInfoArray = nullptr;
  874. DISPLAYCONFIG_MODE_INFO *ModeInfoArray = nullptr;
  875. do {
  876. // In case this isn't the first time through the loop, delete the buffers allocated
  877. delete[] PathInfoArray;
  878. PathInfoArray = nullptr;
  879. delete[] ModeInfoArray;
  880. ModeInfoArray = nullptr;
  881. hr = HRESULT_FROM_WIN32(GetDisplayConfigBufferSizes(
  882. QDC_ONLY_ACTIVE_PATHS, &NumPathArrayElements,
  883. &NumModeInfoArrayElements));
  884. if (FAILED(hr)) {
  885. break;
  886. }
  887. PathInfoArray = new (std::nothrow)
  888. DISPLAYCONFIG_PATH_INFO[NumPathArrayElements];
  889. if (PathInfoArray == nullptr) {
  890. hr = E_OUTOFMEMORY;
  891. break;
  892. }
  893. ModeInfoArray = new (std::nothrow)
  894. DISPLAYCONFIG_MODE_INFO[NumModeInfoArrayElements];
  895. if (ModeInfoArray == nullptr) {
  896. hr = E_OUTOFMEMORY;
  897. break;
  898. }
  899. hr = HRESULT_FROM_WIN32(QueryDisplayConfig(
  900. QDC_ONLY_ACTIVE_PATHS, &NumPathArrayElements,
  901. PathInfoArray, &NumModeInfoArrayElements, ModeInfoArray,
  902. nullptr));
  903. } while (hr == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
  904. INT DesiredPathIdx = -1;
  905. if (SUCCEEDED(hr)) {
  906. // Loop through all sources until the one which matches the 'monitor' is found.
  907. for (UINT PathIdx = 0; PathIdx < NumPathArrayElements;
  908. ++PathIdx) {
  909. DISPLAYCONFIG_SOURCE_DEVICE_NAME SourceName = {};
  910. SourceName.header.type =
  911. DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
  912. SourceName.header.size = sizeof(SourceName);
  913. SourceName.header.adapterId =
  914. PathInfoArray[PathIdx].sourceInfo.adapterId;
  915. SourceName.header.id =
  916. PathInfoArray[PathIdx].sourceInfo.id;
  917. hr = HRESULT_FROM_WIN32(
  918. DisplayConfigGetDeviceInfo(&SourceName.header));
  919. if (SUCCEEDED(hr)) {
  920. if (wcscmp(pszDeviceName,
  921. SourceName.viewGdiDeviceName) == 0) {
  922. // Found the source which matches this hmonitor. The paths are given in path-priority order
  923. // so the first found is the most desired, unless we later find an internal.
  924. if (DesiredPathIdx == -1 ||
  925. IsInternalVideoOutput(
  926. PathInfoArray[PathIdx]
  927. .targetInfo
  928. .outputTechnology)) {
  929. DesiredPathIdx = PathIdx;
  930. }
  931. }
  932. }
  933. }
  934. }
  935. if (DesiredPathIdx != -1) {
  936. *pPathInfo = PathInfoArray[DesiredPathIdx];
  937. } else {
  938. hr = E_INVALIDARG;
  939. }
  940. delete[] PathInfoArray;
  941. PathInfoArray = nullptr;
  942. delete[] ModeInfoArray;
  943. ModeInfoArray = nullptr;
  944. return hr;
  945. }
  946. // Overloaded function accepts an HMONITOR and converts to DeviceName
  947. static HRESULT GetPathInfo(HMONITOR hMonitor,
  948. _Out_ DISPLAYCONFIG_PATH_INFO *pPathInfo)
  949. {
  950. HRESULT hr = S_OK;
  951. // Get the name of the 'monitor' being requested
  952. MONITORINFOEXW ViewInfo;
  953. RtlZeroMemory(&ViewInfo, sizeof(ViewInfo));
  954. ViewInfo.cbSize = sizeof(ViewInfo);
  955. if (!GetMonitorInfoW(hMonitor, &ViewInfo)) {
  956. // Error condition, likely invalid monitor handle, could log error
  957. hr = HRESULT_FROM_WIN32(GetLastError());
  958. }
  959. if (SUCCEEDED(hr)) {
  960. hr = GetPathInfo(ViewInfo.szDevice, pPathInfo);
  961. }
  962. return hr;
  963. }
  964. static ULONG GetSdrWhiteNits(HMONITOR monitor)
  965. {
  966. ULONG nits = 0;
  967. DISPLAYCONFIG_PATH_INFO info;
  968. if (SUCCEEDED(GetPathInfo(monitor, &info))) {
  969. const DISPLAYCONFIG_PATH_TARGET_INFO &targetInfo =
  970. info.targetInfo;
  971. DISPLAYCONFIG_SDR_WHITE_LEVEL level;
  972. DISPLAYCONFIG_DEVICE_INFO_HEADER &header = level.header;
  973. header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL;
  974. header.size = sizeof(level);
  975. header.adapterId = targetInfo.adapterId;
  976. header.id = targetInfo.id;
  977. if (DisplayConfigGetDeviceInfo(&header) == ERROR_SUCCESS)
  978. nits = (level.SDRWhiteLevel * 80) / 1000;
  979. }
  980. return nits;
  981. }
  982. static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter)
  983. {
  984. UINT i;
  985. ComPtr<IDXGIOutput> output;
  986. for (i = 0; adapter->EnumOutputs(i, &output) == S_OK; ++i) {
  987. DXGI_OUTPUT_DESC desc;
  988. if (FAILED(output->GetDesc(&desc)))
  989. continue;
  990. unsigned refresh = 0;
  991. bool target_found = false;
  992. DISPLAYCONFIG_TARGET_DEVICE_NAME target;
  993. MONITORINFOEX info;
  994. info.cbSize = sizeof(info);
  995. if (GetMonitorInfo(desc.Monitor, &info)) {
  996. target_found = GetMonitorTarget(info, target);
  997. DEVMODE mode;
  998. mode.dmSize = sizeof(mode);
  999. mode.dmDriverExtra = 0;
  1000. if (EnumDisplaySettings(info.szDevice,
  1001. ENUM_CURRENT_SETTINGS, &mode)) {
  1002. refresh = mode.dmDisplayFrequency;
  1003. }
  1004. }
  1005. if (!target_found) {
  1006. target.monitorFriendlyDeviceName[0] = 0;
  1007. }
  1008. const char *space = "Unknown";
  1009. const DXGI_COLOR_SPACE_TYPE type = GetColorSpace(output);
  1010. switch (type) {
  1011. case DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709:
  1012. space = "RGB_FULL_G22_NONE_P709";
  1013. break;
  1014. case DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020:
  1015. space = "RGB_FULL_G2084_NONE_P2020";
  1016. break;
  1017. default:
  1018. blog(LOG_WARNING,
  1019. "Unexpected DXGI_COLOR_SPACE_TYPE: %u",
  1020. (unsigned)type);
  1021. }
  1022. const RECT &rect = desc.DesktopCoordinates;
  1023. const ULONG nits = GetSdrWhiteNits(desc.Monitor);
  1024. blog(LOG_INFO,
  1025. "\t output %u: "
  1026. "pos={%d, %d}, "
  1027. "size={%d, %d}, "
  1028. "attached=%s, "
  1029. "space=%s, "
  1030. "sdr_white_nits=%lu, "
  1031. "refresh=%u, "
  1032. "name=%ls",
  1033. i, rect.left, rect.top, rect.right - rect.left,
  1034. rect.bottom - rect.top,
  1035. desc.AttachedToDesktop ? "true" : "false", space, nits,
  1036. refresh, target.monitorFriendlyDeviceName);
  1037. }
  1038. }
  1039. static inline void LogD3DAdapters()
  1040. {
  1041. ComPtr<IDXGIFactory1> factory;
  1042. ComPtr<IDXGIAdapter1> adapter;
  1043. HRESULT hr;
  1044. UINT i;
  1045. blog(LOG_INFO, "Available Video Adapters: ");
  1046. hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory));
  1047. if (FAILED(hr))
  1048. throw HRError("Failed to create DXGIFactory", hr);
  1049. for (i = 0; factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) {
  1050. DXGI_ADAPTER_DESC desc;
  1051. char name[512] = "";
  1052. hr = adapter->GetDesc(&desc);
  1053. if (FAILED(hr))
  1054. continue;
  1055. /* ignore Microsoft's 'basic' renderer' */
  1056. if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)
  1057. continue;
  1058. os_wcs_to_utf8(desc.Description, 0, name, sizeof(name));
  1059. blog(LOG_INFO, "\tAdapter %u: %s", i, name);
  1060. blog(LOG_INFO, "\t Dedicated VRAM: %u",
  1061. desc.DedicatedVideoMemory);
  1062. blog(LOG_INFO, "\t Shared VRAM: %u",
  1063. desc.SharedSystemMemory);
  1064. blog(LOG_INFO, "\t PCI ID: %x:%x", desc.VendorId,
  1065. desc.DeviceId);
  1066. /* driver version */
  1067. LARGE_INTEGER umd;
  1068. hr = adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice),
  1069. &umd);
  1070. if (SUCCEEDED(hr)) {
  1071. const uint64_t version = umd.QuadPart;
  1072. const uint16_t aa = (version >> 48) & 0xffff;
  1073. const uint16_t bb = (version >> 32) & 0xffff;
  1074. const uint16_t ccccc = (version >> 16) & 0xffff;
  1075. const uint16_t ddddd = version & 0xffff;
  1076. blog(LOG_INFO,
  1077. "\t Driver Version: %" PRIu16 ".%" PRIu16
  1078. ".%" PRIu16 ".%" PRIu16,
  1079. aa, bb, ccccc, ddddd);
  1080. } else {
  1081. blog(LOG_INFO, "\t Driver Version: Unknown (0x%X)",
  1082. (unsigned)hr);
  1083. }
  1084. LogAdapterMonitors(adapter);
  1085. }
  1086. }
  1087. int device_create(gs_device_t **p_device, uint32_t adapter)
  1088. {
  1089. gs_device *device = NULL;
  1090. int errorcode = GS_SUCCESS;
  1091. try {
  1092. blog(LOG_INFO, "---------------------------------");
  1093. blog(LOG_INFO, "Initializing D3D11...");
  1094. LogD3DAdapters();
  1095. device = new gs_device(adapter);
  1096. } catch (const UnsupportedHWError &error) {
  1097. blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str,
  1098. error.hr);
  1099. errorcode = GS_ERROR_NOT_SUPPORTED;
  1100. } catch (const HRError &error) {
  1101. blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str,
  1102. error.hr);
  1103. errorcode = GS_ERROR_FAIL;
  1104. }
  1105. *p_device = device;
  1106. return errorcode;
  1107. }
  1108. void device_destroy(gs_device_t *device)
  1109. {
  1110. delete device;
  1111. }
  1112. void device_enter_context(gs_device_t *device)
  1113. {
  1114. /* does nothing */
  1115. UNUSED_PARAMETER(device);
  1116. }
  1117. void device_leave_context(gs_device_t *device)
  1118. {
  1119. /* does nothing */
  1120. UNUSED_PARAMETER(device);
  1121. }
  1122. void *device_get_device_obj(gs_device_t *device)
  1123. {
  1124. return (void *)device->device.Get();
  1125. }
  1126. gs_swapchain_t *device_swapchain_create(gs_device_t *device,
  1127. const struct gs_init_data *data)
  1128. {
  1129. gs_swap_chain *swap = NULL;
  1130. try {
  1131. swap = new gs_swap_chain(device, data);
  1132. } catch (const HRError &error) {
  1133. blog(LOG_ERROR, "device_swapchain_create (D3D11): %s (%08lX)",
  1134. error.str, error.hr);
  1135. LogD3D11ErrorDetails(error, device);
  1136. }
  1137. return swap;
  1138. }
  1139. void device_resize(gs_device_t *device, uint32_t cx, uint32_t cy)
  1140. {
  1141. if (!device->curSwapChain) {
  1142. blog(LOG_WARNING, "device_resize (D3D11): No active swap");
  1143. return;
  1144. }
  1145. try {
  1146. ID3D11RenderTargetView *renderView = NULL;
  1147. device->context->OMSetRenderTargets(1, &renderView, NULL);
  1148. device->curSwapChain->Resize(cx, cy);
  1149. device->curFramebufferInvalidate = true;
  1150. } catch (const HRError &error) {
  1151. blog(LOG_ERROR, "device_resize (D3D11): %s (%08lX)", error.str,
  1152. error.hr);
  1153. LogD3D11ErrorDetails(error, device);
  1154. }
  1155. }
  1156. void device_get_size(const gs_device_t *device, uint32_t *cx, uint32_t *cy)
  1157. {
  1158. if (device->curSwapChain) {
  1159. *cx = device->curSwapChain->target.width;
  1160. *cy = device->curSwapChain->target.height;
  1161. } else {
  1162. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  1163. *cx = 0;
  1164. *cy = 0;
  1165. }
  1166. }
  1167. uint32_t device_get_width(const gs_device_t *device)
  1168. {
  1169. if (device->curSwapChain) {
  1170. return device->curSwapChain->target.width;
  1171. } else {
  1172. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  1173. return 0;
  1174. }
  1175. }
  1176. uint32_t device_get_height(const gs_device_t *device)
  1177. {
  1178. if (device->curSwapChain) {
  1179. return device->curSwapChain->target.height;
  1180. } else {
  1181. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  1182. return 0;
  1183. }
  1184. }
  1185. gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width,
  1186. uint32_t height,
  1187. enum gs_color_format color_format,
  1188. uint32_t levels, const uint8_t **data,
  1189. uint32_t flags)
  1190. {
  1191. gs_texture *texture = NULL;
  1192. try {
  1193. texture = new gs_texture_2d(device, width, height, color_format,
  1194. levels, data, flags, GS_TEXTURE_2D,
  1195. false);
  1196. } catch (const HRError &error) {
  1197. blog(LOG_ERROR, "device_texture_create (D3D11): %s (%08lX)",
  1198. error.str, error.hr);
  1199. LogD3D11ErrorDetails(error, device);
  1200. } catch (const char *error) {
  1201. blog(LOG_ERROR, "device_texture_create (D3D11): %s", error);
  1202. }
  1203. return texture;
  1204. }
  1205. gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size,
  1206. enum gs_color_format color_format,
  1207. uint32_t levels, const uint8_t **data,
  1208. uint32_t flags)
  1209. {
  1210. gs_texture *texture = NULL;
  1211. try {
  1212. texture = new gs_texture_2d(device, size, size, color_format,
  1213. levels, data, flags,
  1214. GS_TEXTURE_CUBE, false);
  1215. } catch (const HRError &error) {
  1216. blog(LOG_ERROR,
  1217. "device_cubetexture_create (D3D11): %s "
  1218. "(%08lX)",
  1219. error.str, error.hr);
  1220. LogD3D11ErrorDetails(error, device);
  1221. } catch (const char *error) {
  1222. blog(LOG_ERROR, "device_cubetexture_create (D3D11): %s", error);
  1223. }
  1224. return texture;
  1225. }
  1226. gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width,
  1227. uint32_t height, uint32_t depth,
  1228. enum gs_color_format color_format,
  1229. uint32_t levels,
  1230. const uint8_t *const *data,
  1231. uint32_t flags)
  1232. {
  1233. gs_texture *texture = NULL;
  1234. try {
  1235. texture = new gs_texture_3d(device, width, height, depth,
  1236. color_format, levels, data, flags);
  1237. } catch (const HRError &error) {
  1238. blog(LOG_ERROR, "device_voltexture_create (D3D11): %s (%08lX)",
  1239. error.str, error.hr);
  1240. LogD3D11ErrorDetails(error, device);
  1241. } catch (const char *error) {
  1242. blog(LOG_ERROR, "device_voltexture_create (D3D11): %s", error);
  1243. }
  1244. return texture;
  1245. }
  1246. gs_zstencil_t *device_zstencil_create(gs_device_t *device, uint32_t width,
  1247. uint32_t height,
  1248. enum gs_zstencil_format format)
  1249. {
  1250. gs_zstencil_buffer *zstencil = NULL;
  1251. try {
  1252. zstencil =
  1253. new gs_zstencil_buffer(device, width, height, format);
  1254. } catch (const HRError &error) {
  1255. blog(LOG_ERROR, "device_zstencil_create (D3D11): %s (%08lX)",
  1256. error.str, error.hr);
  1257. LogD3D11ErrorDetails(error, device);
  1258. }
  1259. return zstencil;
  1260. }
  1261. gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width,
  1262. uint32_t height,
  1263. enum gs_color_format color_format)
  1264. {
  1265. gs_stage_surface *surf = NULL;
  1266. try {
  1267. surf = new gs_stage_surface(device, width, height,
  1268. color_format);
  1269. } catch (const HRError &error) {
  1270. blog(LOG_ERROR,
  1271. "device_stagesurface_create (D3D11): %s "
  1272. "(%08lX)",
  1273. error.str, error.hr);
  1274. LogD3D11ErrorDetails(error, device);
  1275. }
  1276. return surf;
  1277. }
  1278. gs_samplerstate_t *
  1279. device_samplerstate_create(gs_device_t *device,
  1280. const struct gs_sampler_info *info)
  1281. {
  1282. gs_sampler_state *ss = NULL;
  1283. try {
  1284. ss = new gs_sampler_state(device, info);
  1285. } catch (const HRError &error) {
  1286. blog(LOG_ERROR,
  1287. "device_samplerstate_create (D3D11): %s "
  1288. "(%08lX)",
  1289. error.str, error.hr);
  1290. LogD3D11ErrorDetails(error, device);
  1291. }
  1292. return ss;
  1293. }
  1294. gs_shader_t *device_vertexshader_create(gs_device_t *device,
  1295. const char *shader_string,
  1296. const char *file, char **error_string)
  1297. {
  1298. gs_vertex_shader *shader = NULL;
  1299. try {
  1300. shader = new gs_vertex_shader(device, file, shader_string);
  1301. } catch (const HRError &error) {
  1302. blog(LOG_ERROR,
  1303. "device_vertexshader_create (D3D11): %s "
  1304. "(%08lX)",
  1305. error.str, error.hr);
  1306. LogD3D11ErrorDetails(error, device);
  1307. } catch (const ShaderError &error) {
  1308. const char *buf =
  1309. (const char *)error.errors->GetBufferPointer();
  1310. if (error_string)
  1311. *error_string = bstrdup(buf);
  1312. blog(LOG_ERROR,
  1313. "device_vertexshader_create (D3D11): "
  1314. "Compile warnings/errors for %s:\n%s",
  1315. file, buf);
  1316. } catch (const char *error) {
  1317. blog(LOG_ERROR, "device_vertexshader_create (D3D11): %s",
  1318. error);
  1319. }
  1320. return shader;
  1321. }
  1322. gs_shader_t *device_pixelshader_create(gs_device_t *device,
  1323. const char *shader_string,
  1324. const char *file, char **error_string)
  1325. {
  1326. gs_pixel_shader *shader = NULL;
  1327. try {
  1328. shader = new gs_pixel_shader(device, file, shader_string);
  1329. } catch (const HRError &error) {
  1330. blog(LOG_ERROR,
  1331. "device_pixelshader_create (D3D11): %s "
  1332. "(%08lX)",
  1333. error.str, error.hr);
  1334. LogD3D11ErrorDetails(error, device);
  1335. } catch (const ShaderError &error) {
  1336. const char *buf =
  1337. (const char *)error.errors->GetBufferPointer();
  1338. if (error_string)
  1339. *error_string = bstrdup(buf);
  1340. blog(LOG_ERROR,
  1341. "device_pixelshader_create (D3D11): "
  1342. "Compiler warnings/errors for %s:\n%s",
  1343. file, buf);
  1344. } catch (const char *error) {
  1345. blog(LOG_ERROR, "device_pixelshader_create (D3D11): %s", error);
  1346. }
  1347. return shader;
  1348. }
  1349. gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device,
  1350. struct gs_vb_data *data,
  1351. uint32_t flags)
  1352. {
  1353. gs_vertex_buffer *buffer = NULL;
  1354. try {
  1355. buffer = new gs_vertex_buffer(device, data, flags);
  1356. } catch (const HRError &error) {
  1357. blog(LOG_ERROR,
  1358. "device_vertexbuffer_create (D3D11): %s "
  1359. "(%08lX)",
  1360. error.str, error.hr);
  1361. LogD3D11ErrorDetails(error, device);
  1362. } catch (const char *error) {
  1363. blog(LOG_ERROR, "device_vertexbuffer_create (D3D11): %s",
  1364. error);
  1365. }
  1366. return buffer;
  1367. }
  1368. gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device,
  1369. enum gs_index_type type,
  1370. void *indices, size_t num,
  1371. uint32_t flags)
  1372. {
  1373. gs_index_buffer *buffer = NULL;
  1374. try {
  1375. buffer = new gs_index_buffer(device, type, indices, num, flags);
  1376. } catch (const HRError &error) {
  1377. blog(LOG_ERROR, "device_indexbuffer_create (D3D11): %s (%08lX)",
  1378. error.str, error.hr);
  1379. LogD3D11ErrorDetails(error, device);
  1380. }
  1381. return buffer;
  1382. }
  1383. gs_timer_t *device_timer_create(gs_device_t *device)
  1384. {
  1385. gs_timer *timer = NULL;
  1386. try {
  1387. timer = new gs_timer(device);
  1388. } catch (const HRError &error) {
  1389. blog(LOG_ERROR, "device_timer_create (D3D11): %s (%08lX)",
  1390. error.str, error.hr);
  1391. LogD3D11ErrorDetails(error, device);
  1392. }
  1393. return timer;
  1394. }
  1395. gs_timer_range_t *device_timer_range_create(gs_device_t *device)
  1396. {
  1397. gs_timer_range *range = NULL;
  1398. try {
  1399. range = new gs_timer_range(device);
  1400. } catch (const HRError &error) {
  1401. blog(LOG_ERROR, "device_timer_range_create (D3D11): %s (%08lX)",
  1402. error.str, error.hr);
  1403. LogD3D11ErrorDetails(error, device);
  1404. }
  1405. return range;
  1406. }
  1407. enum gs_texture_type device_get_texture_type(const gs_texture_t *texture)
  1408. {
  1409. return texture->type;
  1410. }
  1411. void gs_device::LoadVertexBufferData()
  1412. {
  1413. if (curVertexBuffer == lastVertexBuffer &&
  1414. curVertexShader == lastVertexShader)
  1415. return;
  1416. ID3D11Buffer *buffers[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
  1417. uint32_t strides[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
  1418. uint32_t offsets[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
  1419. UINT numBuffers{};
  1420. assert(curVertexShader->NumBuffersExpected() <= _countof(buffers));
  1421. assert(curVertexShader->NumBuffersExpected() <= _countof(strides));
  1422. assert(curVertexShader->NumBuffersExpected() <= _countof(offsets));
  1423. if (curVertexBuffer && curVertexShader) {
  1424. numBuffers = curVertexBuffer->MakeBufferList(curVertexShader,
  1425. buffers, strides);
  1426. } else {
  1427. numBuffers = curVertexShader
  1428. ? curVertexShader->NumBuffersExpected()
  1429. : 0;
  1430. std::fill_n(buffers, numBuffers, nullptr);
  1431. std::fill_n(strides, numBuffers, 0);
  1432. }
  1433. std::fill_n(offsets, numBuffers, 0);
  1434. context->IASetVertexBuffers(0, numBuffers, buffers, strides, offsets);
  1435. lastVertexBuffer = curVertexBuffer;
  1436. lastVertexShader = curVertexShader;
  1437. }
  1438. void device_load_vertexbuffer(gs_device_t *device, gs_vertbuffer_t *vertbuffer)
  1439. {
  1440. if (device->curVertexBuffer == vertbuffer)
  1441. return;
  1442. device->curVertexBuffer = vertbuffer;
  1443. }
  1444. void device_load_indexbuffer(gs_device_t *device, gs_indexbuffer_t *indexbuffer)
  1445. {
  1446. DXGI_FORMAT format;
  1447. ID3D11Buffer *buffer;
  1448. if (device->curIndexBuffer == indexbuffer)
  1449. return;
  1450. if (indexbuffer) {
  1451. switch (indexbuffer->indexSize) {
  1452. case 2:
  1453. format = DXGI_FORMAT_R16_UINT;
  1454. break;
  1455. default:
  1456. case 4:
  1457. format = DXGI_FORMAT_R32_UINT;
  1458. break;
  1459. }
  1460. buffer = indexbuffer->indexBuffer;
  1461. } else {
  1462. buffer = NULL;
  1463. format = DXGI_FORMAT_R32_UINT;
  1464. }
  1465. device->curIndexBuffer = indexbuffer;
  1466. device->context->IASetIndexBuffer(buffer, format, 0);
  1467. }
  1468. static void device_load_texture_internal(gs_device_t *device, gs_texture_t *tex,
  1469. int unit,
  1470. ID3D11ShaderResourceView *view)
  1471. {
  1472. if (device->curTextures[unit] == tex)
  1473. return;
  1474. device->curTextures[unit] = tex;
  1475. device->context->PSSetShaderResources(unit, 1, &view);
  1476. }
  1477. void device_load_texture(gs_device_t *device, gs_texture_t *tex, int unit)
  1478. {
  1479. ID3D11ShaderResourceView *view;
  1480. if (tex)
  1481. view = tex->shaderRes;
  1482. else
  1483. view = NULL;
  1484. return device_load_texture_internal(device, tex, unit, view);
  1485. }
  1486. void device_load_texture_srgb(gs_device_t *device, gs_texture_t *tex, int unit)
  1487. {
  1488. ID3D11ShaderResourceView *view;
  1489. if (tex)
  1490. view = tex->shaderResLinear;
  1491. else
  1492. view = NULL;
  1493. return device_load_texture_internal(device, tex, unit, view);
  1494. }
  1495. void device_load_samplerstate(gs_device_t *device,
  1496. gs_samplerstate_t *samplerstate, int unit)
  1497. {
  1498. ID3D11SamplerState *state = NULL;
  1499. if (device->curSamplers[unit] == samplerstate)
  1500. return;
  1501. if (samplerstate)
  1502. state = samplerstate->state;
  1503. device->curSamplers[unit] = samplerstate;
  1504. device->context->PSSetSamplers(unit, 1, &state);
  1505. }
  1506. void device_load_vertexshader(gs_device_t *device, gs_shader_t *vertshader)
  1507. {
  1508. ID3D11VertexShader *shader = NULL;
  1509. ID3D11InputLayout *layout = NULL;
  1510. ID3D11Buffer *constants = NULL;
  1511. if (device->curVertexShader == vertshader)
  1512. return;
  1513. gs_vertex_shader *vs = static_cast<gs_vertex_shader *>(vertshader);
  1514. if (vertshader) {
  1515. if (vertshader->type != GS_SHADER_VERTEX) {
  1516. blog(LOG_ERROR, "device_load_vertexshader (D3D11): "
  1517. "Specified shader is not a vertex "
  1518. "shader");
  1519. return;
  1520. }
  1521. shader = vs->shader;
  1522. layout = vs->layout;
  1523. constants = vs->constants;
  1524. }
  1525. device->curVertexShader = vs;
  1526. device->context->VSSetShader(shader, NULL, 0);
  1527. device->context->IASetInputLayout(layout);
  1528. device->context->VSSetConstantBuffers(0, 1, &constants);
  1529. }
  1530. static inline void clear_textures(gs_device_t *device)
  1531. {
  1532. ID3D11ShaderResourceView *views[GS_MAX_TEXTURES];
  1533. memset(views, 0, sizeof(views));
  1534. memset(device->curTextures, 0, sizeof(device->curTextures));
  1535. device->context->PSSetShaderResources(0, GS_MAX_TEXTURES, views);
  1536. }
  1537. void device_load_pixelshader(gs_device_t *device, gs_shader_t *pixelshader)
  1538. {
  1539. ID3D11PixelShader *shader = NULL;
  1540. ID3D11Buffer *constants = NULL;
  1541. ID3D11SamplerState *states[GS_MAX_TEXTURES];
  1542. if (device->curPixelShader == pixelshader)
  1543. return;
  1544. gs_pixel_shader *ps = static_cast<gs_pixel_shader *>(pixelshader);
  1545. if (pixelshader) {
  1546. if (pixelshader->type != GS_SHADER_PIXEL) {
  1547. blog(LOG_ERROR, "device_load_pixelshader (D3D11): "
  1548. "Specified shader is not a pixel "
  1549. "shader");
  1550. return;
  1551. }
  1552. shader = ps->shader;
  1553. constants = ps->constants;
  1554. ps->GetSamplerStates(states);
  1555. } else {
  1556. memset(states, 0, sizeof(states));
  1557. }
  1558. clear_textures(device);
  1559. device->curPixelShader = ps;
  1560. device->context->PSSetShader(shader, NULL, 0);
  1561. device->context->PSSetConstantBuffers(0, 1, &constants);
  1562. device->context->PSSetSamplers(0, GS_MAX_TEXTURES, states);
  1563. for (int i = 0; i < GS_MAX_TEXTURES; i++)
  1564. if (device->curSamplers[i] &&
  1565. device->curSamplers[i]->state != states[i])
  1566. device->curSamplers[i] = nullptr;
  1567. }
  1568. void device_load_default_samplerstate(gs_device_t *device, bool b_3d, int unit)
  1569. {
  1570. /* TODO */
  1571. UNUSED_PARAMETER(device);
  1572. UNUSED_PARAMETER(b_3d);
  1573. UNUSED_PARAMETER(unit);
  1574. }
  1575. gs_shader_t *device_get_vertex_shader(const gs_device_t *device)
  1576. {
  1577. return device->curVertexShader;
  1578. }
  1579. gs_shader_t *device_get_pixel_shader(const gs_device_t *device)
  1580. {
  1581. return device->curPixelShader;
  1582. }
  1583. gs_texture_t *device_get_render_target(const gs_device_t *device)
  1584. {
  1585. if (device->curRenderTarget == &device->curSwapChain->target)
  1586. return NULL;
  1587. return device->curRenderTarget;
  1588. }
  1589. gs_zstencil_t *device_get_zstencil_target(const gs_device_t *device)
  1590. {
  1591. if (device->curZStencilBuffer == &device->curSwapChain->zs)
  1592. return NULL;
  1593. return device->curZStencilBuffer;
  1594. }
  1595. void device_set_render_target(gs_device_t *device, gs_texture_t *tex,
  1596. gs_zstencil_t *zstencil)
  1597. {
  1598. if (device->curSwapChain) {
  1599. if (!tex)
  1600. tex = &device->curSwapChain->target;
  1601. if (!zstencil)
  1602. zstencil = &device->curSwapChain->zs;
  1603. }
  1604. if (device->curRenderTarget == tex &&
  1605. device->curZStencilBuffer == zstencil)
  1606. return;
  1607. if (tex && tex->type != GS_TEXTURE_2D) {
  1608. blog(LOG_ERROR,
  1609. "device_set_render_target (D3D11): texture is not a 2D texture");
  1610. return;
  1611. }
  1612. gs_texture_2d *const tex2d = static_cast<gs_texture_2d *>(tex);
  1613. if (device->curRenderTarget != tex2d || device->curRenderSide != 0 ||
  1614. device->curZStencilBuffer != zstencil) {
  1615. device->curRenderTarget = tex2d;
  1616. device->curRenderSide = 0;
  1617. device->curZStencilBuffer = zstencil;
  1618. device->curFramebufferInvalidate = true;
  1619. }
  1620. }
  1621. void device_set_cube_render_target(gs_device_t *device, gs_texture_t *tex,
  1622. int side, gs_zstencil_t *zstencil)
  1623. {
  1624. if (device->curSwapChain) {
  1625. if (!tex) {
  1626. tex = &device->curSwapChain->target;
  1627. side = 0;
  1628. }
  1629. if (!zstencil)
  1630. zstencil = &device->curSwapChain->zs;
  1631. }
  1632. if (device->curRenderTarget == tex && device->curRenderSide == side &&
  1633. device->curZStencilBuffer == zstencil)
  1634. return;
  1635. if (tex->type != GS_TEXTURE_CUBE) {
  1636. blog(LOG_ERROR, "device_set_cube_render_target (D3D11): "
  1637. "texture is not a cube texture");
  1638. return;
  1639. }
  1640. gs_texture_2d *const tex2d = static_cast<gs_texture_2d *>(tex);
  1641. if (device->curRenderTarget != tex2d || device->curRenderSide != side ||
  1642. device->curZStencilBuffer != zstencil) {
  1643. device->curRenderTarget = tex2d;
  1644. device->curRenderSide = side;
  1645. device->curZStencilBuffer = zstencil;
  1646. device->curFramebufferInvalidate = true;
  1647. }
  1648. }
  1649. void device_enable_framebuffer_srgb(gs_device_t *device, bool enable)
  1650. {
  1651. if (device->curFramebufferSrgb != enable) {
  1652. device->curFramebufferSrgb = enable;
  1653. device->curFramebufferInvalidate = true;
  1654. }
  1655. }
  1656. bool device_framebuffer_srgb_enabled(gs_device_t *device)
  1657. {
  1658. return device->curFramebufferSrgb;
  1659. }
  1660. inline void gs_device::CopyTex(ID3D11Texture2D *dst, uint32_t dst_x,
  1661. uint32_t dst_y, gs_texture_t *src,
  1662. uint32_t src_x, uint32_t src_y, uint32_t src_w,
  1663. uint32_t src_h)
  1664. {
  1665. if (src->type != GS_TEXTURE_2D)
  1666. throw "Source texture must be a 2D texture";
  1667. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(src);
  1668. if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 &&
  1669. src_w == 0 && src_h == 0) {
  1670. context->CopyResource(dst, tex2d->texture);
  1671. } else {
  1672. D3D11_BOX sbox;
  1673. sbox.left = src_x;
  1674. if (src_w > 0)
  1675. sbox.right = src_x + src_w;
  1676. else
  1677. sbox.right = tex2d->width - 1;
  1678. sbox.top = src_y;
  1679. if (src_h > 0)
  1680. sbox.bottom = src_y + src_h;
  1681. else
  1682. sbox.bottom = tex2d->height - 1;
  1683. sbox.front = 0;
  1684. sbox.back = 1;
  1685. context->CopySubresourceRegion(dst, 0, dst_x, dst_y, 0,
  1686. tex2d->texture, 0, &sbox);
  1687. }
  1688. }
  1689. static DXGI_FORMAT get_copy_compare_format(gs_color_format format)
  1690. {
  1691. switch (format) {
  1692. case GS_RGBA_UNORM:
  1693. return DXGI_FORMAT_R8G8B8A8_TYPELESS;
  1694. case GS_BGRX_UNORM:
  1695. return DXGI_FORMAT_B8G8R8X8_TYPELESS;
  1696. case GS_BGRA_UNORM:
  1697. return DXGI_FORMAT_B8G8R8A8_TYPELESS;
  1698. default:
  1699. return ConvertGSTextureFormatResource(format);
  1700. }
  1701. }
  1702. void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst,
  1703. uint32_t dst_x, uint32_t dst_y,
  1704. gs_texture_t *src, uint32_t src_x,
  1705. uint32_t src_y, uint32_t src_w, uint32_t src_h)
  1706. {
  1707. try {
  1708. gs_texture_2d *src2d = static_cast<gs_texture_2d *>(src);
  1709. gs_texture_2d *dst2d = static_cast<gs_texture_2d *>(dst);
  1710. if (!src)
  1711. throw "Source texture is NULL";
  1712. if (!dst)
  1713. throw "Destination texture is NULL";
  1714. if (src->type != GS_TEXTURE_2D || dst->type != GS_TEXTURE_2D)
  1715. throw "Source and destination textures must be a 2D "
  1716. "textures";
  1717. if (get_copy_compare_format(dst->format) !=
  1718. get_copy_compare_format(src->format))
  1719. throw "Source and destination formats do not match";
  1720. /* apparently casting to the same type that the variable
  1721. * already exists as is supposed to prevent some warning
  1722. * when used with the conditional operator? */
  1723. uint32_t copyWidth = (uint32_t)src_w ? (uint32_t)src_w
  1724. : (src2d->width - src_x);
  1725. uint32_t copyHeight = (uint32_t)src_h ? (uint32_t)src_h
  1726. : (src2d->height - src_y);
  1727. uint32_t dstWidth = dst2d->width - dst_x;
  1728. uint32_t dstHeight = dst2d->height - dst_y;
  1729. if (dstWidth < copyWidth || dstHeight < copyHeight)
  1730. throw "Destination texture region is not big "
  1731. "enough to hold the source region";
  1732. if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 &&
  1733. src_w == 0 && src_h == 0) {
  1734. copyWidth = 0;
  1735. copyHeight = 0;
  1736. }
  1737. device->CopyTex(dst2d->texture, dst_x, dst_y, src, src_x, src_y,
  1738. copyWidth, copyHeight);
  1739. } catch (const char *error) {
  1740. blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error);
  1741. }
  1742. }
  1743. void device_copy_texture(gs_device_t *device, gs_texture_t *dst,
  1744. gs_texture_t *src)
  1745. {
  1746. device_copy_texture_region(device, dst, 0, 0, src, 0, 0, 0, 0);
  1747. }
  1748. void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst,
  1749. gs_texture_t *src)
  1750. {
  1751. try {
  1752. gs_texture_2d *src2d = static_cast<gs_texture_2d *>(src);
  1753. if (!src)
  1754. throw "Source texture is NULL";
  1755. if (src->type != GS_TEXTURE_2D)
  1756. throw "Source texture must be a 2D texture";
  1757. if (!dst)
  1758. throw "Destination surface is NULL";
  1759. if (dst->format != GS_UNKNOWN && dst->format != src->format)
  1760. throw "Source and destination formats do not match";
  1761. if (dst->width != src2d->width || dst->height != src2d->height)
  1762. throw "Source and destination must have the same "
  1763. "dimensions";
  1764. device->CopyTex(dst->texture, 0, 0, src, 0, 0, 0, 0);
  1765. } catch (const char *error) {
  1766. blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error);
  1767. }
  1768. }
  1769. extern "C" void reset_duplicators(void);
  1770. void device_begin_frame(gs_device_t *device)
  1771. {
  1772. /* does nothing in D3D11 */
  1773. UNUSED_PARAMETER(device);
  1774. reset_duplicators();
  1775. }
  1776. void device_begin_scene(gs_device_t *device)
  1777. {
  1778. clear_textures(device);
  1779. }
  1780. void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode,
  1781. uint32_t start_vert, uint32_t num_verts)
  1782. {
  1783. try {
  1784. if (!device->curVertexShader)
  1785. throw "No vertex shader specified";
  1786. if (!device->curPixelShader)
  1787. throw "No pixel shader specified";
  1788. if (!device->curVertexBuffer && (num_verts == 0))
  1789. throw "No vertex buffer specified";
  1790. if (!device->curSwapChain && !device->curRenderTarget)
  1791. throw "No render target or swap chain to render to";
  1792. device->FlushOutputViews();
  1793. gs_effect_t *effect = gs_get_effect();
  1794. if (effect)
  1795. gs_effect_update_params(effect);
  1796. device->LoadVertexBufferData();
  1797. device->UpdateBlendState();
  1798. device->UpdateRasterState();
  1799. device->UpdateZStencilState();
  1800. device->UpdateViewProjMatrix();
  1801. device->curVertexShader->UploadParams();
  1802. device->curPixelShader->UploadParams();
  1803. } catch (const char *error) {
  1804. blog(LOG_ERROR, "device_draw (D3D11): %s", error);
  1805. return;
  1806. } catch (const HRError &error) {
  1807. blog(LOG_ERROR, "device_draw (D3D11): %s (%08lX)", error.str,
  1808. error.hr);
  1809. LogD3D11ErrorDetails(error, device);
  1810. return;
  1811. }
  1812. D3D11_PRIMITIVE_TOPOLOGY newTopology = ConvertGSTopology(draw_mode);
  1813. if (device->curToplogy != newTopology) {
  1814. device->context->IASetPrimitiveTopology(newTopology);
  1815. device->curToplogy = newTopology;
  1816. }
  1817. if (device->curIndexBuffer) {
  1818. if (num_verts == 0)
  1819. num_verts = (uint32_t)device->curIndexBuffer->num;
  1820. device->context->DrawIndexed(num_verts, start_vert, 0);
  1821. } else {
  1822. if (num_verts == 0)
  1823. num_verts = (uint32_t)device->curVertexBuffer->numVerts;
  1824. device->context->Draw(num_verts, start_vert);
  1825. }
  1826. }
  1827. void device_end_scene(gs_device_t *device)
  1828. {
  1829. /* does nothing in D3D11 */
  1830. UNUSED_PARAMETER(device);
  1831. }
  1832. void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swapchain)
  1833. {
  1834. gs_texture_t *target = device->curRenderTarget;
  1835. gs_zstencil_t *zs = device->curZStencilBuffer;
  1836. bool is_cube =
  1837. device->curRenderTarget
  1838. ? (device->curRenderTarget->type == GS_TEXTURE_CUBE)
  1839. : false;
  1840. if (device->curSwapChain) {
  1841. if (target == &device->curSwapChain->target)
  1842. target = NULL;
  1843. if (zs == &device->curSwapChain->zs)
  1844. zs = NULL;
  1845. }
  1846. device->curSwapChain = swapchain;
  1847. if (is_cube)
  1848. device_set_cube_render_target(device, target,
  1849. device->curRenderSide, zs);
  1850. else
  1851. device_set_render_target(device, target, zs);
  1852. }
  1853. void device_clear(gs_device_t *device, uint32_t clear_flags,
  1854. const struct vec4 *color, float depth, uint8_t stencil)
  1855. {
  1856. int side = device->curRenderSide;
  1857. if ((clear_flags & GS_CLEAR_COLOR) != 0 && device->curRenderTarget)
  1858. device->context->ClearRenderTargetView(
  1859. device->curRenderTarget->renderTarget[side],
  1860. color->ptr);
  1861. if (device->curZStencilBuffer) {
  1862. uint32_t flags = 0;
  1863. if ((clear_flags & GS_CLEAR_DEPTH) != 0)
  1864. flags |= D3D11_CLEAR_DEPTH;
  1865. if ((clear_flags & GS_CLEAR_STENCIL) != 0)
  1866. flags |= D3D11_CLEAR_STENCIL;
  1867. if (flags && device->curZStencilBuffer->view)
  1868. device->context->ClearDepthStencilView(
  1869. device->curZStencilBuffer->view, flags, depth,
  1870. stencil);
  1871. }
  1872. }
  1873. void device_present(gs_device_t *device)
  1874. {
  1875. gs_swap_chain *const curSwapChain = device->curSwapChain;
  1876. if (curSwapChain) {
  1877. /* Skip Present at frame limit to avoid stall */
  1878. const HANDLE hWaitable = curSwapChain->hWaitable;
  1879. if ((hWaitable == NULL) ||
  1880. WaitForSingleObject(hWaitable, 0) == WAIT_OBJECT_0) {
  1881. const HRESULT hr = curSwapChain->swap->Present(
  1882. 0, curSwapChain->presentFlags);
  1883. if (hr == DXGI_ERROR_DEVICE_REMOVED ||
  1884. hr == DXGI_ERROR_DEVICE_RESET) {
  1885. device->RebuildDevice();
  1886. }
  1887. }
  1888. } else {
  1889. blog(LOG_WARNING, "device_present (D3D11): No active swap");
  1890. }
  1891. }
  1892. void device_flush(gs_device_t *device)
  1893. {
  1894. device->context->Flush();
  1895. }
  1896. void device_set_cull_mode(gs_device_t *device, enum gs_cull_mode mode)
  1897. {
  1898. if (mode == device->rasterState.cullMode)
  1899. return;
  1900. device->rasterState.cullMode = mode;
  1901. device->rasterStateChanged = true;
  1902. }
  1903. enum gs_cull_mode device_get_cull_mode(const gs_device_t *device)
  1904. {
  1905. return device->rasterState.cullMode;
  1906. }
  1907. void device_enable_blending(gs_device_t *device, bool enable)
  1908. {
  1909. if (enable == device->blendState.blendEnabled)
  1910. return;
  1911. device->blendState.blendEnabled = enable;
  1912. device->blendStateChanged = true;
  1913. }
  1914. void device_enable_depth_test(gs_device_t *device, bool enable)
  1915. {
  1916. if (enable == device->zstencilState.depthEnabled)
  1917. return;
  1918. device->zstencilState.depthEnabled = enable;
  1919. device->zstencilStateChanged = true;
  1920. }
  1921. void device_enable_stencil_test(gs_device_t *device, bool enable)
  1922. {
  1923. if (enable == device->zstencilState.stencilEnabled)
  1924. return;
  1925. device->zstencilState.stencilEnabled = enable;
  1926. device->zstencilStateChanged = true;
  1927. }
  1928. void device_enable_stencil_write(gs_device_t *device, bool enable)
  1929. {
  1930. if (enable == device->zstencilState.stencilWriteEnabled)
  1931. return;
  1932. device->zstencilState.stencilWriteEnabled = enable;
  1933. device->zstencilStateChanged = true;
  1934. }
  1935. void device_enable_color(gs_device_t *device, bool red, bool green, bool blue,
  1936. bool alpha)
  1937. {
  1938. if (device->blendState.redEnabled == red &&
  1939. device->blendState.greenEnabled == green &&
  1940. device->blendState.blueEnabled == blue &&
  1941. device->blendState.alphaEnabled == alpha)
  1942. return;
  1943. device->blendState.redEnabled = red;
  1944. device->blendState.greenEnabled = green;
  1945. device->blendState.blueEnabled = blue;
  1946. device->blendState.alphaEnabled = alpha;
  1947. device->blendStateChanged = true;
  1948. }
  1949. void device_blend_function(gs_device_t *device, enum gs_blend_type src,
  1950. enum gs_blend_type dest)
  1951. {
  1952. if (device->blendState.srcFactorC == src &&
  1953. device->blendState.destFactorC == dest &&
  1954. device->blendState.srcFactorA == src &&
  1955. device->blendState.destFactorA == dest)
  1956. return;
  1957. device->blendState.srcFactorC = src;
  1958. device->blendState.destFactorC = dest;
  1959. device->blendState.srcFactorA = src;
  1960. device->blendState.destFactorA = dest;
  1961. device->blendStateChanged = true;
  1962. }
  1963. void device_blend_function_separate(gs_device_t *device,
  1964. enum gs_blend_type src_c,
  1965. enum gs_blend_type dest_c,
  1966. enum gs_blend_type src_a,
  1967. enum gs_blend_type dest_a)
  1968. {
  1969. if (device->blendState.srcFactorC == src_c &&
  1970. device->blendState.destFactorC == dest_c &&
  1971. device->blendState.srcFactorA == src_a &&
  1972. device->blendState.destFactorA == dest_a)
  1973. return;
  1974. device->blendState.srcFactorC = src_c;
  1975. device->blendState.destFactorC = dest_c;
  1976. device->blendState.srcFactorA = src_a;
  1977. device->blendState.destFactorA = dest_a;
  1978. device->blendStateChanged = true;
  1979. }
  1980. void device_blend_op(gs_device_t *device, enum gs_blend_op_type op)
  1981. {
  1982. if (device->blendState.op == op)
  1983. return;
  1984. device->blendState.op = op;
  1985. device->blendStateChanged = true;
  1986. }
  1987. void device_depth_function(gs_device_t *device, enum gs_depth_test test)
  1988. {
  1989. if (device->zstencilState.depthFunc == test)
  1990. return;
  1991. device->zstencilState.depthFunc = test;
  1992. device->zstencilStateChanged = true;
  1993. }
  1994. static inline void update_stencilside_test(gs_device_t *device,
  1995. StencilSide &side,
  1996. gs_depth_test test)
  1997. {
  1998. if (side.test == test)
  1999. return;
  2000. side.test = test;
  2001. device->zstencilStateChanged = true;
  2002. }
  2003. void device_stencil_function(gs_device_t *device, enum gs_stencil_side side,
  2004. enum gs_depth_test test)
  2005. {
  2006. int sideVal = (int)side;
  2007. if (sideVal & GS_STENCIL_FRONT)
  2008. update_stencilside_test(
  2009. device, device->zstencilState.stencilFront, test);
  2010. if (sideVal & GS_STENCIL_BACK)
  2011. update_stencilside_test(
  2012. device, device->zstencilState.stencilBack, test);
  2013. }
  2014. static inline void update_stencilside_op(gs_device_t *device, StencilSide &side,
  2015. enum gs_stencil_op_type fail,
  2016. enum gs_stencil_op_type zfail,
  2017. enum gs_stencil_op_type zpass)
  2018. {
  2019. if (side.fail == fail && side.zfail == zfail && side.zpass == zpass)
  2020. return;
  2021. side.fail = fail;
  2022. side.zfail = zfail;
  2023. side.zpass = zpass;
  2024. device->zstencilStateChanged = true;
  2025. }
  2026. void device_stencil_op(gs_device_t *device, enum gs_stencil_side side,
  2027. enum gs_stencil_op_type fail,
  2028. enum gs_stencil_op_type zfail,
  2029. enum gs_stencil_op_type zpass)
  2030. {
  2031. int sideVal = (int)side;
  2032. if (sideVal & GS_STENCIL_FRONT)
  2033. update_stencilside_op(device,
  2034. device->zstencilState.stencilFront, fail,
  2035. zfail, zpass);
  2036. if (sideVal & GS_STENCIL_BACK)
  2037. update_stencilside_op(device, device->zstencilState.stencilBack,
  2038. fail, zfail, zpass);
  2039. }
  2040. void device_set_viewport(gs_device_t *device, int x, int y, int width,
  2041. int height)
  2042. {
  2043. D3D11_VIEWPORT vp;
  2044. memset(&vp, 0, sizeof(vp));
  2045. vp.MaxDepth = 1.0f;
  2046. vp.TopLeftX = (float)x;
  2047. vp.TopLeftY = (float)y;
  2048. vp.Width = (float)width;
  2049. vp.Height = (float)height;
  2050. device->context->RSSetViewports(1, &vp);
  2051. device->viewport.x = x;
  2052. device->viewport.y = y;
  2053. device->viewport.cx = width;
  2054. device->viewport.cy = height;
  2055. }
  2056. void device_get_viewport(const gs_device_t *device, struct gs_rect *rect)
  2057. {
  2058. memcpy(rect, &device->viewport, sizeof(gs_rect));
  2059. }
  2060. void device_set_scissor_rect(gs_device_t *device, const struct gs_rect *rect)
  2061. {
  2062. D3D11_RECT d3drect;
  2063. device->rasterState.scissorEnabled = (rect != NULL);
  2064. if (rect != NULL) {
  2065. d3drect.left = rect->x;
  2066. d3drect.top = rect->y;
  2067. d3drect.right = rect->x + rect->cx;
  2068. d3drect.bottom = rect->y + rect->cy;
  2069. device->context->RSSetScissorRects(1, &d3drect);
  2070. }
  2071. device->rasterStateChanged = true;
  2072. }
  2073. void device_ortho(gs_device_t *device, float left, float right, float top,
  2074. float bottom, float zNear, float zFar)
  2075. {
  2076. matrix4 *dst = &device->curProjMatrix;
  2077. float rml = right - left;
  2078. float bmt = bottom - top;
  2079. float fmn = zFar - zNear;
  2080. vec4_zero(&dst->x);
  2081. vec4_zero(&dst->y);
  2082. vec4_zero(&dst->z);
  2083. vec4_zero(&dst->t);
  2084. dst->x.x = 2.0f / rml;
  2085. dst->t.x = (left + right) / -rml;
  2086. dst->y.y = 2.0f / -bmt;
  2087. dst->t.y = (bottom + top) / bmt;
  2088. dst->z.z = 1.0f / fmn;
  2089. dst->t.z = zNear / -fmn;
  2090. dst->t.w = 1.0f;
  2091. }
  2092. void device_frustum(gs_device_t *device, float left, float right, float top,
  2093. float bottom, float zNear, float zFar)
  2094. {
  2095. matrix4 *dst = &device->curProjMatrix;
  2096. float rml = right - left;
  2097. float bmt = bottom - top;
  2098. float fmn = zFar - zNear;
  2099. float nearx2 = 2.0f * zNear;
  2100. vec4_zero(&dst->x);
  2101. vec4_zero(&dst->y);
  2102. vec4_zero(&dst->z);
  2103. vec4_zero(&dst->t);
  2104. dst->x.x = nearx2 / rml;
  2105. dst->z.x = (left + right) / -rml;
  2106. dst->y.y = nearx2 / -bmt;
  2107. dst->z.y = (bottom + top) / bmt;
  2108. dst->z.z = zFar / fmn;
  2109. dst->t.z = (zNear * zFar) / -fmn;
  2110. dst->z.w = 1.0f;
  2111. }
  2112. void device_projection_push(gs_device_t *device)
  2113. {
  2114. mat4float mat;
  2115. memcpy(&mat, &device->curProjMatrix, sizeof(matrix4));
  2116. device->projStack.push_back(mat);
  2117. }
  2118. void device_projection_pop(gs_device_t *device)
  2119. {
  2120. if (device->projStack.empty())
  2121. return;
  2122. const mat4float &mat = device->projStack.back();
  2123. memcpy(&device->curProjMatrix, &mat, sizeof(matrix4));
  2124. device->projStack.pop_back();
  2125. }
  2126. void gs_swapchain_destroy(gs_swapchain_t *swapchain)
  2127. {
  2128. if (swapchain->device->curSwapChain == swapchain)
  2129. device_load_swapchain(swapchain->device, nullptr);
  2130. delete swapchain;
  2131. }
  2132. void gs_texture_destroy(gs_texture_t *tex)
  2133. {
  2134. delete tex;
  2135. }
  2136. uint32_t gs_texture_get_width(const gs_texture_t *tex)
  2137. {
  2138. if (tex->type != GS_TEXTURE_2D)
  2139. return 0;
  2140. return static_cast<const gs_texture_2d *>(tex)->width;
  2141. }
  2142. uint32_t gs_texture_get_height(const gs_texture_t *tex)
  2143. {
  2144. if (tex->type != GS_TEXTURE_2D)
  2145. return 0;
  2146. return static_cast<const gs_texture_2d *>(tex)->height;
  2147. }
  2148. enum gs_color_format gs_texture_get_color_format(const gs_texture_t *tex)
  2149. {
  2150. if (tex->type != GS_TEXTURE_2D)
  2151. return GS_UNKNOWN;
  2152. return static_cast<const gs_texture_2d *>(tex)->format;
  2153. }
  2154. bool gs_texture_map(gs_texture_t *tex, uint8_t **ptr, uint32_t *linesize)
  2155. {
  2156. HRESULT hr;
  2157. if (tex->type != GS_TEXTURE_2D)
  2158. return false;
  2159. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2160. D3D11_MAPPED_SUBRESOURCE map;
  2161. hr = tex2d->device->context->Map(tex2d->texture, 0,
  2162. D3D11_MAP_WRITE_DISCARD, 0, &map);
  2163. if (FAILED(hr))
  2164. return false;
  2165. *ptr = (uint8_t *)map.pData;
  2166. *linesize = map.RowPitch;
  2167. return true;
  2168. }
  2169. void gs_texture_unmap(gs_texture_t *tex)
  2170. {
  2171. if (tex->type != GS_TEXTURE_2D)
  2172. return;
  2173. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2174. tex2d->device->context->Unmap(tex2d->texture, 0);
  2175. }
  2176. void *gs_texture_get_obj(gs_texture_t *tex)
  2177. {
  2178. if (tex->type != GS_TEXTURE_2D)
  2179. return nullptr;
  2180. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2181. return tex2d->texture.Get();
  2182. }
  2183. void gs_cubetexture_destroy(gs_texture_t *cubetex)
  2184. {
  2185. delete cubetex;
  2186. }
  2187. uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex)
  2188. {
  2189. if (cubetex->type != GS_TEXTURE_CUBE)
  2190. return 0;
  2191. const gs_texture_2d *tex = static_cast<const gs_texture_2d *>(cubetex);
  2192. return tex->width;
  2193. }
  2194. enum gs_color_format
  2195. gs_cubetexture_get_color_format(const gs_texture_t *cubetex)
  2196. {
  2197. if (cubetex->type != GS_TEXTURE_CUBE)
  2198. return GS_UNKNOWN;
  2199. const gs_texture_2d *tex = static_cast<const gs_texture_2d *>(cubetex);
  2200. return tex->format;
  2201. }
  2202. void gs_voltexture_destroy(gs_texture_t *voltex)
  2203. {
  2204. delete voltex;
  2205. }
  2206. uint32_t gs_voltexture_get_width(const gs_texture_t *voltex)
  2207. {
  2208. /* TODO */
  2209. UNUSED_PARAMETER(voltex);
  2210. return 0;
  2211. }
  2212. uint32_t gs_voltexture_get_height(const gs_texture_t *voltex)
  2213. {
  2214. /* TODO */
  2215. UNUSED_PARAMETER(voltex);
  2216. return 0;
  2217. }
  2218. uint32_t gs_voltexture_get_depth(const gs_texture_t *voltex)
  2219. {
  2220. /* TODO */
  2221. UNUSED_PARAMETER(voltex);
  2222. return 0;
  2223. }
  2224. enum gs_color_format gs_voltexture_get_color_format(const gs_texture_t *voltex)
  2225. {
  2226. /* TODO */
  2227. UNUSED_PARAMETER(voltex);
  2228. return GS_UNKNOWN;
  2229. }
  2230. void gs_stagesurface_destroy(gs_stagesurf_t *stagesurf)
  2231. {
  2232. delete stagesurf;
  2233. }
  2234. uint32_t gs_stagesurface_get_width(const gs_stagesurf_t *stagesurf)
  2235. {
  2236. return stagesurf->width;
  2237. }
  2238. uint32_t gs_stagesurface_get_height(const gs_stagesurf_t *stagesurf)
  2239. {
  2240. return stagesurf->height;
  2241. }
  2242. enum gs_color_format
  2243. gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf)
  2244. {
  2245. return stagesurf->format;
  2246. }
  2247. bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data,
  2248. uint32_t *linesize)
  2249. {
  2250. D3D11_MAPPED_SUBRESOURCE map;
  2251. if (FAILED(stagesurf->device->context->Map(stagesurf->texture, 0,
  2252. D3D11_MAP_READ, 0, &map)))
  2253. return false;
  2254. *data = (uint8_t *)map.pData;
  2255. *linesize = map.RowPitch;
  2256. return true;
  2257. }
  2258. void gs_stagesurface_unmap(gs_stagesurf_t *stagesurf)
  2259. {
  2260. stagesurf->device->context->Unmap(stagesurf->texture, 0);
  2261. }
  2262. void gs_zstencil_destroy(gs_zstencil_t *zstencil)
  2263. {
  2264. delete zstencil;
  2265. }
  2266. void gs_samplerstate_destroy(gs_samplerstate_t *samplerstate)
  2267. {
  2268. if (!samplerstate)
  2269. return;
  2270. if (samplerstate->device)
  2271. for (int i = 0; i < GS_MAX_TEXTURES; i++)
  2272. if (samplerstate->device->curSamplers[i] ==
  2273. samplerstate)
  2274. samplerstate->device->curSamplers[i] = nullptr;
  2275. delete samplerstate;
  2276. }
  2277. void gs_vertexbuffer_destroy(gs_vertbuffer_t *vertbuffer)
  2278. {
  2279. if (vertbuffer && vertbuffer->device->lastVertexBuffer == vertbuffer)
  2280. vertbuffer->device->lastVertexBuffer = nullptr;
  2281. delete vertbuffer;
  2282. }
  2283. static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vertbuffer,
  2284. const gs_vb_data *data)
  2285. {
  2286. size_t num_tex = data->num_tex < vertbuffer->uvBuffers.size()
  2287. ? data->num_tex
  2288. : vertbuffer->uvBuffers.size();
  2289. if (!vertbuffer->dynamic) {
  2290. blog(LOG_ERROR, "gs_vertexbuffer_flush: vertex buffer is "
  2291. "not dynamic");
  2292. return;
  2293. }
  2294. if (data->points)
  2295. vertbuffer->FlushBuffer(vertbuffer->vertexBuffer, data->points,
  2296. sizeof(vec3));
  2297. if (vertbuffer->normalBuffer && data->normals)
  2298. vertbuffer->FlushBuffer(vertbuffer->normalBuffer, data->normals,
  2299. sizeof(vec3));
  2300. if (vertbuffer->tangentBuffer && data->tangents)
  2301. vertbuffer->FlushBuffer(vertbuffer->tangentBuffer,
  2302. data->tangents, sizeof(vec3));
  2303. if (vertbuffer->colorBuffer && data->colors)
  2304. vertbuffer->FlushBuffer(vertbuffer->colorBuffer, data->colors,
  2305. sizeof(uint32_t));
  2306. for (size_t i = 0; i < num_tex; i++) {
  2307. gs_tvertarray &tv = data->tvarray[i];
  2308. vertbuffer->FlushBuffer(vertbuffer->uvBuffers[i], tv.array,
  2309. tv.width * sizeof(float));
  2310. }
  2311. }
  2312. void gs_vertexbuffer_flush(gs_vertbuffer_t *vertbuffer)
  2313. {
  2314. gs_vertexbuffer_flush_internal(vertbuffer, vertbuffer->vbd.data);
  2315. }
  2316. void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vertbuffer,
  2317. const gs_vb_data *data)
  2318. {
  2319. gs_vertexbuffer_flush_internal(vertbuffer, data);
  2320. }
  2321. struct gs_vb_data *gs_vertexbuffer_get_data(const gs_vertbuffer_t *vertbuffer)
  2322. {
  2323. return vertbuffer->vbd.data;
  2324. }
  2325. void gs_indexbuffer_destroy(gs_indexbuffer_t *indexbuffer)
  2326. {
  2327. delete indexbuffer;
  2328. }
  2329. static inline void gs_indexbuffer_flush_internal(gs_indexbuffer_t *indexbuffer,
  2330. const void *data)
  2331. {
  2332. HRESULT hr;
  2333. if (!indexbuffer->dynamic)
  2334. return;
  2335. D3D11_MAPPED_SUBRESOURCE map;
  2336. hr = indexbuffer->device->context->Map(
  2337. indexbuffer->indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
  2338. if (FAILED(hr))
  2339. return;
  2340. memcpy(map.pData, data, indexbuffer->num * indexbuffer->indexSize);
  2341. indexbuffer->device->context->Unmap(indexbuffer->indexBuffer, 0);
  2342. }
  2343. void gs_indexbuffer_flush(gs_indexbuffer_t *indexbuffer)
  2344. {
  2345. gs_indexbuffer_flush_internal(indexbuffer, indexbuffer->indices.data);
  2346. }
  2347. void gs_indexbuffer_flush_direct(gs_indexbuffer_t *indexbuffer,
  2348. const void *data)
  2349. {
  2350. gs_indexbuffer_flush_internal(indexbuffer, data);
  2351. }
  2352. void *gs_indexbuffer_get_data(const gs_indexbuffer_t *indexbuffer)
  2353. {
  2354. return indexbuffer->indices.data;
  2355. }
  2356. size_t gs_indexbuffer_get_num_indices(const gs_indexbuffer_t *indexbuffer)
  2357. {
  2358. return indexbuffer->num;
  2359. }
  2360. enum gs_index_type gs_indexbuffer_get_type(const gs_indexbuffer_t *indexbuffer)
  2361. {
  2362. return indexbuffer->type;
  2363. }
  2364. void gs_timer_destroy(gs_timer_t *timer)
  2365. {
  2366. delete timer;
  2367. }
  2368. void gs_timer_begin(gs_timer_t *timer)
  2369. {
  2370. timer->device->context->End(timer->query_begin);
  2371. }
  2372. void gs_timer_end(gs_timer_t *timer)
  2373. {
  2374. timer->device->context->End(timer->query_end);
  2375. }
  2376. bool gs_timer_get_data(gs_timer_t *timer, uint64_t *ticks)
  2377. {
  2378. uint64_t begin, end;
  2379. HRESULT hr_begin, hr_end;
  2380. do {
  2381. hr_begin = timer->device->context->GetData(
  2382. timer->query_begin, &begin, sizeof(begin), 0);
  2383. } while (hr_begin == S_FALSE);
  2384. do {
  2385. hr_end = timer->device->context->GetData(timer->query_end, &end,
  2386. sizeof(end), 0);
  2387. } while (hr_end == S_FALSE);
  2388. const bool succeeded = SUCCEEDED(hr_begin) && SUCCEEDED(hr_end);
  2389. if (succeeded)
  2390. *ticks = end - begin;
  2391. return succeeded;
  2392. }
  2393. void gs_timer_range_destroy(gs_timer_range_t *range)
  2394. {
  2395. delete range;
  2396. }
  2397. void gs_timer_range_begin(gs_timer_range_t *range)
  2398. {
  2399. range->device->context->Begin(range->query_disjoint);
  2400. }
  2401. void gs_timer_range_end(gs_timer_range_t *range)
  2402. {
  2403. range->device->context->End(range->query_disjoint);
  2404. }
  2405. bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint,
  2406. uint64_t *frequency)
  2407. {
  2408. D3D11_QUERY_DATA_TIMESTAMP_DISJOINT timestamp_disjoint;
  2409. HRESULT hr;
  2410. do {
  2411. hr = range->device->context->GetData(range->query_disjoint,
  2412. &timestamp_disjoint,
  2413. sizeof(timestamp_disjoint),
  2414. 0);
  2415. } while (hr == S_FALSE);
  2416. const bool succeeded = SUCCEEDED(hr);
  2417. if (succeeded) {
  2418. *disjoint = timestamp_disjoint.Disjoint;
  2419. *frequency = timestamp_disjoint.Frequency;
  2420. }
  2421. return succeeded;
  2422. }
  2423. gs_timer::gs_timer(gs_device_t *device) : gs_obj(device, gs_type::gs_timer)
  2424. {
  2425. Rebuild(device->device);
  2426. }
  2427. gs_timer_range::gs_timer_range(gs_device_t *device)
  2428. : gs_obj(device, gs_type::gs_timer_range)
  2429. {
  2430. Rebuild(device->device);
  2431. }
  2432. extern "C" EXPORT bool device_gdi_texture_available(void)
  2433. {
  2434. return true;
  2435. }
  2436. extern "C" EXPORT bool device_shared_texture_available(void)
  2437. {
  2438. return true;
  2439. }
  2440. extern "C" EXPORT bool device_nv12_available(gs_device_t *device)
  2441. {
  2442. return device->nv12Supported;
  2443. }
  2444. extern "C" EXPORT void device_debug_marker_begin(gs_device_t *,
  2445. const char *markername,
  2446. const float color[4])
  2447. {
  2448. D3DCOLOR bgra = D3DCOLOR_ARGB((DWORD)(255.0f * color[3]),
  2449. (DWORD)(255.0f * color[0]),
  2450. (DWORD)(255.0f * color[1]),
  2451. (DWORD)(255.0f * color[2]));
  2452. wchar_t wide[64];
  2453. os_utf8_to_wcs(markername, 0, wide, _countof(wide));
  2454. D3DPERF_BeginEvent(bgra, wide);
  2455. }
  2456. extern "C" EXPORT void device_debug_marker_end(gs_device_t *)
  2457. {
  2458. D3DPERF_EndEvent();
  2459. }
  2460. extern "C" EXPORT gs_texture_t *
  2461. device_texture_create_gdi(gs_device_t *device, uint32_t width, uint32_t height)
  2462. {
  2463. gs_texture *texture = nullptr;
  2464. try {
  2465. texture = new gs_texture_2d(device, width, height,
  2466. GS_BGRA_UNORM, 1, nullptr,
  2467. GS_RENDER_TARGET, GS_TEXTURE_2D,
  2468. true);
  2469. } catch (const HRError &error) {
  2470. blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s (%08lX)",
  2471. error.str, error.hr);
  2472. LogD3D11ErrorDetails(error, device);
  2473. } catch (const char *error) {
  2474. blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s", error);
  2475. }
  2476. return texture;
  2477. }
  2478. static inline bool TextureGDICompatible(gs_texture_2d *tex2d, const char *func)
  2479. {
  2480. if (!tex2d->isGDICompatible) {
  2481. blog(LOG_ERROR, "%s (D3D11): Texture is not GDI compatible",
  2482. func);
  2483. return false;
  2484. }
  2485. return true;
  2486. }
  2487. extern "C" EXPORT void *gs_texture_get_dc(gs_texture_t *tex)
  2488. {
  2489. HDC hDC = nullptr;
  2490. if (tex->type != GS_TEXTURE_2D)
  2491. return nullptr;
  2492. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2493. if (!TextureGDICompatible(tex2d, "gs_texture_get_dc"))
  2494. return nullptr;
  2495. if (!tex2d->gdiSurface)
  2496. return nullptr;
  2497. tex2d->gdiSurface->GetDC(true, &hDC);
  2498. return hDC;
  2499. }
  2500. extern "C" EXPORT void gs_texture_release_dc(gs_texture_t *tex)
  2501. {
  2502. if (tex->type != GS_TEXTURE_2D)
  2503. return;
  2504. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2505. if (!TextureGDICompatible(tex2d, "gs_texture_release_dc"))
  2506. return;
  2507. tex2d->gdiSurface->ReleaseDC(nullptr);
  2508. }
  2509. extern "C" EXPORT gs_texture_t *device_texture_open_shared(gs_device_t *device,
  2510. uint32_t handle)
  2511. {
  2512. gs_texture *texture = nullptr;
  2513. try {
  2514. texture = new gs_texture_2d(device, handle);
  2515. } catch (const HRError &error) {
  2516. blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s (%08lX)",
  2517. error.str, error.hr);
  2518. LogD3D11ErrorDetails(error, device);
  2519. } catch (const char *error) {
  2520. blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s", error);
  2521. }
  2522. return texture;
  2523. }
  2524. extern "C" EXPORT gs_texture_t *
  2525. device_texture_open_nt_shared(gs_device_t *device, uint32_t handle)
  2526. {
  2527. gs_texture *texture = nullptr;
  2528. try {
  2529. texture = new gs_texture_2d(device, handle, true);
  2530. } catch (const HRError &error) {
  2531. blog(LOG_ERROR, "gs_texture_open_nt_shared (D3D11): %s (%08lX)",
  2532. error.str, error.hr);
  2533. LogD3D11ErrorDetails(error, device);
  2534. } catch (const char *error) {
  2535. blog(LOG_ERROR, "gs_texture_open_nt_shared (D3D11): %s", error);
  2536. }
  2537. return texture;
  2538. }
  2539. extern "C" EXPORT uint32_t device_texture_get_shared_handle(gs_texture_t *tex)
  2540. {
  2541. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2542. if (tex->type != GS_TEXTURE_2D)
  2543. return GS_INVALID_HANDLE;
  2544. return tex2d->isShared ? tex2d->sharedHandle : GS_INVALID_HANDLE;
  2545. }
  2546. extern "C" EXPORT gs_texture_t *device_texture_wrap_obj(gs_device_t *device,
  2547. void *obj)
  2548. {
  2549. gs_texture *texture = nullptr;
  2550. try {
  2551. texture = new gs_texture_2d(device, (ID3D11Texture2D *)obj);
  2552. } catch (const HRError &error) {
  2553. blog(LOG_ERROR, "gs_texture_wrap_obj (D3D11): %s (%08lX)",
  2554. error.str, error.hr);
  2555. LogD3D11ErrorDetails(error, device);
  2556. } catch (const char *error) {
  2557. blog(LOG_ERROR, "gs_texture_wrap_obj (D3D11): %s", error);
  2558. }
  2559. return texture;
  2560. }
  2561. int device_texture_acquire_sync(gs_texture_t *tex, uint64_t key, uint32_t ms)
  2562. {
  2563. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2564. if (tex->type != GS_TEXTURE_2D)
  2565. return -1;
  2566. if (tex2d->acquired)
  2567. return 0;
  2568. ComQIPtr<IDXGIKeyedMutex> keyedMutex(tex2d->texture);
  2569. if (!keyedMutex)
  2570. return -1;
  2571. HRESULT hr = keyedMutex->AcquireSync(key, ms);
  2572. if (hr == S_OK) {
  2573. tex2d->acquired = true;
  2574. return 0;
  2575. } else if (hr == WAIT_TIMEOUT) {
  2576. return ETIMEDOUT;
  2577. }
  2578. return -1;
  2579. }
  2580. extern "C" EXPORT int device_texture_release_sync(gs_texture_t *tex,
  2581. uint64_t key)
  2582. {
  2583. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2584. if (tex->type != GS_TEXTURE_2D)
  2585. return -1;
  2586. if (!tex2d->acquired)
  2587. return 0;
  2588. ComQIPtr<IDXGIKeyedMutex> keyedMutex(tex2d->texture);
  2589. if (!keyedMutex)
  2590. return -1;
  2591. HRESULT hr = keyedMutex->ReleaseSync(key);
  2592. if (hr == S_OK) {
  2593. tex2d->acquired = false;
  2594. return 0;
  2595. }
  2596. return -1;
  2597. }
  2598. extern "C" EXPORT bool
  2599. device_texture_create_nv12(gs_device_t *device, gs_texture_t **p_tex_y,
  2600. gs_texture_t **p_tex_uv, uint32_t width,
  2601. uint32_t height, uint32_t flags)
  2602. {
  2603. if (!device->nv12Supported)
  2604. return false;
  2605. *p_tex_y = nullptr;
  2606. *p_tex_uv = nullptr;
  2607. gs_texture_2d *tex_y;
  2608. gs_texture_2d *tex_uv;
  2609. try {
  2610. tex_y = new gs_texture_2d(device, width, height, GS_R8, 1,
  2611. nullptr, flags, GS_TEXTURE_2D, false,
  2612. true);
  2613. tex_uv = new gs_texture_2d(device, tex_y->texture, flags);
  2614. } catch (const HRError &error) {
  2615. blog(LOG_ERROR, "gs_texture_create_nv12 (D3D11): %s (%08lX)",
  2616. error.str, error.hr);
  2617. LogD3D11ErrorDetails(error, device);
  2618. return false;
  2619. } catch (const char *error) {
  2620. blog(LOG_ERROR, "gs_texture_create_nv12 (D3D11): %s", error);
  2621. return false;
  2622. }
  2623. tex_y->pairedNV12texture = tex_uv;
  2624. tex_uv->pairedNV12texture = tex_y;
  2625. *p_tex_y = tex_y;
  2626. *p_tex_uv = tex_uv;
  2627. return true;
  2628. }
  2629. extern "C" EXPORT gs_stagesurf_t *
  2630. device_stagesurface_create_nv12(gs_device_t *device, uint32_t width,
  2631. uint32_t height)
  2632. {
  2633. gs_stage_surface *surf = NULL;
  2634. try {
  2635. surf = new gs_stage_surface(device, width, height);
  2636. } catch (const HRError &error) {
  2637. blog(LOG_ERROR,
  2638. "device_stagesurface_create (D3D11): %s "
  2639. "(%08lX)",
  2640. error.str, error.hr);
  2641. LogD3D11ErrorDetails(error, device);
  2642. }
  2643. return surf;
  2644. }
  2645. extern "C" EXPORT void
  2646. device_register_loss_callbacks(gs_device_t *device,
  2647. const gs_device_loss *callbacks)
  2648. {
  2649. device->loss_callbacks.emplace_back(*callbacks);
  2650. }
  2651. extern "C" EXPORT void device_unregister_loss_callbacks(gs_device_t *device,
  2652. void *data)
  2653. {
  2654. for (auto iter = device->loss_callbacks.begin();
  2655. iter != device->loss_callbacks.end(); ++iter) {
  2656. if (iter->data == data) {
  2657. device->loss_callbacks.erase(iter);
  2658. break;
  2659. }
  2660. }
  2661. }
  2662. uint32_t gs_get_adapter_count(void)
  2663. {
  2664. uint32_t count = 0;
  2665. ComPtr<IDXGIFactory1> factory;
  2666. HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory));
  2667. if (SUCCEEDED(hr)) {
  2668. ComPtr<IDXGIAdapter1> adapter;
  2669. for (UINT i = 0;
  2670. factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) {
  2671. DXGI_ADAPTER_DESC desc;
  2672. if (SUCCEEDED(adapter->GetDesc(&desc))) {
  2673. /* ignore Microsoft's 'basic' renderer' */
  2674. if (desc.VendorId != 0x1414 &&
  2675. desc.DeviceId != 0x8c) {
  2676. ++count;
  2677. }
  2678. }
  2679. }
  2680. }
  2681. return count;
  2682. }