d3d11-subsystem.cpp 80 KB

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