d3d11-subsystem.cpp 81 KB

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