d3d11-subsystem.cpp 86 KB

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