d3d11-subsystem.cpp 86 KB

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