d3d11-subsystem.cpp 86 KB

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