d3d11-subsystem.cpp 89 KB

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