d3d11-subsystem.cpp 87 KB

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