d3d11-subsystem.cpp 87 KB

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