d3d11-subsystem.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678
  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 <cinttypes>
  15. #include <util/base.h>
  16. #include <util/platform.h>
  17. #include <util/dstr.h>
  18. #include <util/util.hpp>
  19. #include <graphics/matrix3.h>
  20. #include <winternl.h>
  21. #include <d3d9.h>
  22. #include "d3d11-subsystem.hpp"
  23. #include "d3d11-config.h"
  24. struct UnsupportedHWError : HRError {
  25. inline UnsupportedHWError(const char *str, HRESULT hr)
  26. : HRError(str, hr)
  27. {
  28. }
  29. };
  30. #ifdef _MSC_VER
  31. /* alignment warning - despite the fact that alignment is already fixed */
  32. #pragma warning(disable : 4316)
  33. #endif
  34. static inline void LogD3D11ErrorDetails(HRError error, gs_device_t *device)
  35. {
  36. if (error.hr == DXGI_ERROR_DEVICE_REMOVED) {
  37. HRESULT DeviceRemovedReason =
  38. device->device->GetDeviceRemovedReason();
  39. blog(LOG_ERROR, " Device Removed Reason: %08lX",
  40. DeviceRemovedReason);
  41. }
  42. }
  43. static const IID dxgiFactory2 = {0x50c83a1c,
  44. 0xe072,
  45. 0x4c48,
  46. {0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6,
  47. 0xd0}};
  48. gs_obj::gs_obj(gs_device_t *device_, gs_type type)
  49. : device(device_), obj_type(type)
  50. {
  51. prev_next = &device->first_obj;
  52. next = device->first_obj;
  53. device->first_obj = this;
  54. if (next)
  55. next->prev_next = &next;
  56. }
  57. gs_obj::~gs_obj()
  58. {
  59. if (prev_next)
  60. *prev_next = next;
  61. if (next)
  62. next->prev_next = prev_next;
  63. }
  64. static inline void make_swap_desc_common(DXGI_SWAP_CHAIN_DESC &desc,
  65. const gs_init_data *data,
  66. UINT num_backbuffers,
  67. DXGI_SWAP_EFFECT effect)
  68. {
  69. memset(&desc, 0, sizeof(desc));
  70. desc.BufferDesc.Width = data->cx;
  71. desc.BufferDesc.Height = data->cy;
  72. desc.BufferDesc.Format = ConvertGSTextureFormat(data->format);
  73. desc.SampleDesc.Count = 1;
  74. desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  75. desc.BufferCount = num_backbuffers;
  76. desc.OutputWindow = (HWND)data->window.hwnd;
  77. desc.Windowed = true;
  78. desc.SwapEffect = effect;
  79. }
  80. static inline void make_swap_desc_win7(DXGI_SWAP_CHAIN_DESC &desc,
  81. const gs_init_data *data)
  82. {
  83. UINT num_backbuffers = data->num_backbuffers;
  84. if (num_backbuffers == 0)
  85. num_backbuffers = 1;
  86. make_swap_desc_common(desc, data, num_backbuffers,
  87. DXGI_SWAP_EFFECT_DISCARD);
  88. }
  89. static inline void make_swap_desc_win10(DXGI_SWAP_CHAIN_DESC &desc,
  90. const gs_init_data *data)
  91. {
  92. UINT num_backbuffers = data->num_backbuffers;
  93. if (num_backbuffers == 0)
  94. num_backbuffers = 2;
  95. make_swap_desc_common(desc, data, num_backbuffers,
  96. DXGI_SWAP_EFFECT_FLIP_DISCARD);
  97. }
  98. void gs_swap_chain::InitTarget(uint32_t cx, uint32_t cy)
  99. {
  100. HRESULT hr;
  101. target.width = cx;
  102. target.height = cy;
  103. hr = swap->GetBuffer(0, __uuidof(ID3D11Texture2D),
  104. (void **)target.texture.Assign());
  105. if (FAILED(hr))
  106. throw HRError("Failed to get swap buffer texture", hr);
  107. hr = device->device->CreateRenderTargetView(
  108. target.texture, NULL, target.renderTarget[0].Assign());
  109. if (FAILED(hr))
  110. throw HRError("Failed to create swap render target view", hr);
  111. }
  112. void gs_swap_chain::InitZStencilBuffer(uint32_t cx, uint32_t cy)
  113. {
  114. zs.width = cx;
  115. zs.height = cy;
  116. if (zs.format != GS_ZS_NONE && cx != 0 && cy != 0) {
  117. zs.InitBuffer();
  118. } else {
  119. zs.texture.Clear();
  120. zs.view.Clear();
  121. }
  122. }
  123. void gs_swap_chain::Resize(uint32_t cx, uint32_t cy)
  124. {
  125. RECT clientRect;
  126. HRESULT hr;
  127. target.texture.Clear();
  128. target.renderTarget[0].Clear();
  129. zs.texture.Clear();
  130. zs.view.Clear();
  131. initData.cx = cx;
  132. initData.cy = cy;
  133. if (cx == 0 || cy == 0) {
  134. GetClientRect(hwnd, &clientRect);
  135. if (cx == 0)
  136. cx = clientRect.right;
  137. if (cy == 0)
  138. cy = clientRect.bottom;
  139. }
  140. hr = swap->ResizeBuffers(numBuffers, cx, cy, target.dxgiFormat, 0);
  141. if (FAILED(hr))
  142. throw HRError("Failed to resize swap buffers", hr);
  143. InitTarget(cx, cy);
  144. InitZStencilBuffer(cx, cy);
  145. }
  146. void gs_swap_chain::Init()
  147. {
  148. target.device = device;
  149. target.isRenderTarget = true;
  150. target.format = initData.format;
  151. target.dxgiFormat = ConvertGSTextureFormat(initData.format);
  152. InitTarget(initData.cx, initData.cy);
  153. zs.device = device;
  154. zs.format = initData.zsformat;
  155. zs.dxgiFormat = ConvertGSZStencilFormat(initData.zsformat);
  156. InitZStencilBuffer(initData.cx, initData.cy);
  157. }
  158. gs_swap_chain::gs_swap_chain(gs_device *device, const gs_init_data *data)
  159. : gs_obj(device, gs_type::gs_swap_chain),
  160. numBuffers(data->num_backbuffers),
  161. hwnd((HWND)data->window.hwnd),
  162. initData(*data)
  163. {
  164. HRESULT hr;
  165. make_swap_desc_win10(swapDesc, data);
  166. hr = device->factory->CreateSwapChain(device->device, &swapDesc,
  167. swap.Assign());
  168. if (FAILED(hr)) {
  169. make_swap_desc_win7(swapDesc, data);
  170. hr = device->factory->CreateSwapChain(device->device, &swapDesc,
  171. swap.Assign());
  172. if (FAILED(hr))
  173. throw HRError("Failed to create swap chain", hr);
  174. }
  175. /* Ignore Alt+Enter */
  176. device->factory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER);
  177. Init();
  178. }
  179. void gs_device::InitCompiler()
  180. {
  181. char d3dcompiler[40] = {};
  182. int ver = 49;
  183. while (ver > 30) {
  184. sprintf(d3dcompiler, "D3DCompiler_%02d.dll", ver);
  185. HMODULE module = LoadLibraryA(d3dcompiler);
  186. if (module) {
  187. d3dCompile = (pD3DCompile)GetProcAddress(module,
  188. "D3DCompile");
  189. #ifdef DISASSEMBLE_SHADERS
  190. d3dDisassemble = (pD3DDisassemble)GetProcAddress(
  191. module, "D3DDisassemble");
  192. #endif
  193. if (d3dCompile) {
  194. return;
  195. }
  196. FreeLibrary(module);
  197. }
  198. ver--;
  199. }
  200. throw "Could not find any D3DCompiler libraries. Make sure you've "
  201. "installed the <a href=\"https://obsproject.com/go/dxwebsetup\">"
  202. "DirectX components</a> that OBS Studio requires.";
  203. }
  204. void gs_device::InitFactory(uint32_t adapterIdx)
  205. {
  206. HRESULT hr;
  207. IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2
  208. : __uuidof(IDXGIFactory1);
  209. hr = CreateDXGIFactory1(factoryIID, (void **)factory.Assign());
  210. if (FAILED(hr))
  211. throw UnsupportedHWError("Failed to create DXGIFactory", hr);
  212. hr = factory->EnumAdapters1(adapterIdx, &adapter);
  213. if (FAILED(hr))
  214. throw UnsupportedHWError("Failed to enumerate DXGIAdapter", hr);
  215. }
  216. const static D3D_FEATURE_LEVEL featureLevels[] = {
  217. D3D_FEATURE_LEVEL_11_0,
  218. D3D_FEATURE_LEVEL_10_1,
  219. D3D_FEATURE_LEVEL_10_0,
  220. D3D_FEATURE_LEVEL_9_3,
  221. };
  222. /* ------------------------------------------------------------------------- */
  223. #define VERT_IN_OUT \
  224. "\
  225. struct VertInOut { \
  226. float4 pos : POSITION; \
  227. }; "
  228. #define NV12_Y_PS \
  229. VERT_IN_OUT "\
  230. float main(VertInOut vert_in) : TARGET \
  231. { \
  232. return 1.0; \
  233. }"
  234. #define NV12_UV_PS \
  235. VERT_IN_OUT "\
  236. float2 main(VertInOut vert_in) : TARGET \
  237. { \
  238. return float2(1.0, 1.0); \
  239. }"
  240. #define NV12_VS \
  241. VERT_IN_OUT "\
  242. VertInOut main(VertInOut vert_in) \
  243. { \
  244. VertInOut vert_out; \
  245. vert_out.pos = float4(vert_in.pos.xyz, 1.0); \
  246. return vert_out; \
  247. } "
  248. /* ------------------------------------------------------------------------- */
  249. #define NV12_CX 128
  250. #define NV12_CY 128
  251. bool gs_device::HasBadNV12Output()
  252. try {
  253. vec3 points[4];
  254. vec3_set(&points[0], -1.0f, -1.0f, 0.0f);
  255. vec3_set(&points[1], -1.0f, 1.0f, 0.0f);
  256. vec3_set(&points[2], 1.0f, -1.0f, 0.0f);
  257. vec3_set(&points[3], 1.0f, 1.0f, 0.0f);
  258. gs_texture_2d nv12_y(this, NV12_CX, NV12_CY, GS_R8, 1, nullptr,
  259. GS_RENDER_TARGET | GS_SHARED_KM_TEX, GS_TEXTURE_2D,
  260. false, true);
  261. gs_texture_2d nv12_uv(this, nv12_y.texture,
  262. GS_RENDER_TARGET | GS_SHARED_KM_TEX);
  263. gs_vertex_shader nv12_vs(this, "", NV12_VS);
  264. gs_pixel_shader nv12_y_ps(this, "", NV12_Y_PS);
  265. gs_pixel_shader nv12_uv_ps(this, "", NV12_UV_PS);
  266. gs_stage_surface nv12_stage(this, NV12_CX, NV12_CY);
  267. gs_vb_data *vbd = gs_vbdata_create();
  268. vbd->num = 4;
  269. vbd->points = (vec3 *)bmemdup(&points, sizeof(points));
  270. gs_vertex_buffer buf(this, vbd, 0);
  271. device_load_vertexbuffer(this, &buf);
  272. device_load_vertexshader(this, &nv12_vs);
  273. context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
  274. device_set_viewport(this, 0, 0, NV12_CX, NV12_CY);
  275. device_set_cull_mode(this, GS_NEITHER);
  276. device_enable_depth_test(this, false);
  277. device_enable_blending(this, false);
  278. LoadVertexBufferData();
  279. device_set_render_target(this, &nv12_y, nullptr);
  280. device_load_pixelshader(this, &nv12_y_ps);
  281. UpdateBlendState();
  282. UpdateRasterState();
  283. UpdateZStencilState();
  284. context->Draw(4, 0);
  285. device_set_viewport(this, 0, 0, NV12_CX / 2, NV12_CY / 2);
  286. device_set_render_target(this, &nv12_uv, nullptr);
  287. device_load_pixelshader(this, &nv12_uv_ps);
  288. UpdateBlendState();
  289. UpdateRasterState();
  290. UpdateZStencilState();
  291. context->Draw(4, 0);
  292. device_load_pixelshader(this, nullptr);
  293. device_load_vertexbuffer(this, nullptr);
  294. device_load_vertexshader(this, nullptr);
  295. device_set_render_target(this, nullptr, nullptr);
  296. device_stage_texture(this, &nv12_stage, &nv12_y);
  297. uint8_t *data;
  298. uint32_t linesize;
  299. bool bad_driver = false;
  300. if (gs_stagesurface_map(&nv12_stage, &data, &linesize)) {
  301. bad_driver = data[linesize * NV12_CY] == 0;
  302. gs_stagesurface_unmap(&nv12_stage);
  303. } else {
  304. throw "Could not map surface";
  305. }
  306. if (bad_driver) {
  307. blog(LOG_WARNING, "Bad NV12 texture handling detected! "
  308. "Disabling NV12 texture support.");
  309. }
  310. return bad_driver;
  311. } catch (const HRError &error) {
  312. blog(LOG_WARNING, "HasBadNV12Output failed: %s (%08lX)", error.str,
  313. error.hr);
  314. return false;
  315. } catch (const char *error) {
  316. blog(LOG_WARNING, "HasBadNV12Output failed: %s", error);
  317. return false;
  318. }
  319. #if USE_GPU_PRIORITY
  320. static bool set_priority(ID3D11Device *device)
  321. {
  322. typedef enum _D3DKMT_SCHEDULINGPRIORITYCLASS {
  323. D3DKMT_SCHEDULINGPRIORITYCLASS_IDLE,
  324. D3DKMT_SCHEDULINGPRIORITYCLASS_BELOW_NORMAL,
  325. D3DKMT_SCHEDULINGPRIORITYCLASS_NORMAL,
  326. D3DKMT_SCHEDULINGPRIORITYCLASS_ABOVE_NORMAL,
  327. D3DKMT_SCHEDULINGPRIORITYCLASS_HIGH,
  328. D3DKMT_SCHEDULINGPRIORITYCLASS_REALTIME
  329. } D3DKMT_SCHEDULINGPRIORITYCLASS;
  330. ComQIPtr<IDXGIDevice> dxgiDevice(device);
  331. if (!dxgiDevice) {
  332. blog(LOG_DEBUG, "%s: Failed to get IDXGIDevice", __FUNCTION__);
  333. return false;
  334. }
  335. HMODULE gdi32 = GetModuleHandleW(L"GDI32");
  336. if (!gdi32) {
  337. blog(LOG_DEBUG, "%s: Failed to get GDI32", __FUNCTION__);
  338. return false;
  339. }
  340. NTSTATUS(WINAPI * d3dkmt_spspc)(HANDLE, D3DKMT_SCHEDULINGPRIORITYCLASS);
  341. d3dkmt_spspc = (decltype(d3dkmt_spspc))GetProcAddress(
  342. gdi32, "D3DKMTSetProcessSchedulingPriorityClass");
  343. if (!d3dkmt_spspc) {
  344. blog(LOG_DEBUG, "%s: Failed to get d3dkmt_spspc", __FUNCTION__);
  345. return false;
  346. }
  347. NTSTATUS status = d3dkmt_spspc(GetCurrentProcess(),
  348. D3DKMT_SCHEDULINGPRIORITYCLASS_REALTIME);
  349. if (status != 0) {
  350. blog(LOG_DEBUG, "%s: Failed to set process priority class: %d",
  351. __FUNCTION__, (int)status);
  352. return false;
  353. }
  354. HRESULT hr = dxgiDevice->SetGPUThreadPriority(GPU_PRIORITY_VAL);
  355. if (FAILED(hr)) {
  356. blog(LOG_DEBUG, "%s: SetGPUThreadPriority failed",
  357. __FUNCTION__);
  358. return false;
  359. }
  360. blog(LOG_INFO, "D3D11 GPU priority setup success");
  361. return true;
  362. }
  363. static bool is_intel(const wstring &name)
  364. {
  365. return wstrstri(name.c_str(), L"intel") != nullptr;
  366. }
  367. #endif
  368. void gs_device::InitDevice(uint32_t adapterIdx)
  369. {
  370. wstring adapterName;
  371. DXGI_ADAPTER_DESC desc;
  372. D3D_FEATURE_LEVEL levelUsed = D3D_FEATURE_LEVEL_9_3;
  373. HRESULT hr = 0;
  374. adpIdx = adapterIdx;
  375. uint32_t createFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  376. #ifdef _DEBUG
  377. //createFlags |= D3D11_CREATE_DEVICE_DEBUG;
  378. #endif
  379. adapterName = (adapter->GetDesc(&desc) == S_OK) ? desc.Description
  380. : L"<unknown>";
  381. BPtr<char> adapterNameUTF8;
  382. os_wcs_to_utf8_ptr(adapterName.c_str(), 0, &adapterNameUTF8);
  383. blog(LOG_INFO, "Loading up D3D11 on adapter %s (%" PRIu32 ")",
  384. adapterNameUTF8.Get(), adapterIdx);
  385. hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL,
  386. createFlags, featureLevels,
  387. sizeof(featureLevels) /
  388. sizeof(D3D_FEATURE_LEVEL),
  389. D3D11_SDK_VERSION, device.Assign(), &levelUsed,
  390. context.Assign());
  391. if (FAILED(hr))
  392. throw UnsupportedHWError("Failed to create device", hr);
  393. blog(LOG_INFO, "D3D11 loaded successfully, feature level used: %x",
  394. (unsigned int)levelUsed);
  395. /* adjust gpu thread priority */
  396. #if USE_GPU_PRIORITY
  397. if (!is_intel(adapterName) && !set_priority(device)) {
  398. blog(LOG_INFO, "D3D11 GPU priority setup "
  399. "failed (not admin?)");
  400. }
  401. #endif
  402. /* ---------------------------------------- */
  403. /* check for nv12 texture output support */
  404. nv12Supported = false;
  405. /* WARP NV12 support is suspected to be buggy on older Windows */
  406. if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) {
  407. return;
  408. }
  409. /* Intel CopyResource is very slow with NV12 */
  410. if (desc.VendorId == 0x8086) {
  411. return;
  412. }
  413. ComQIPtr<ID3D11Device1> d3d11_1(device);
  414. if (!d3d11_1) {
  415. return;
  416. }
  417. /* needs to support extended resource sharing */
  418. D3D11_FEATURE_DATA_D3D11_OPTIONS opts = {};
  419. hr = d3d11_1->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &opts,
  420. sizeof(opts));
  421. if (FAILED(hr) || !opts.ExtendedResourceSharing) {
  422. return;
  423. }
  424. /* needs to support the actual format */
  425. UINT support = 0;
  426. hr = device->CheckFormatSupport(DXGI_FORMAT_NV12, &support);
  427. if (FAILED(hr)) {
  428. return;
  429. }
  430. if ((support & D3D11_FORMAT_SUPPORT_TEXTURE2D) == 0) {
  431. return;
  432. }
  433. /* must be usable as a render target */
  434. if ((support & D3D11_FORMAT_SUPPORT_RENDER_TARGET) == 0) {
  435. return;
  436. }
  437. if (HasBadNV12Output()) {
  438. return;
  439. }
  440. nv12Supported = true;
  441. }
  442. static inline void ConvertStencilSide(D3D11_DEPTH_STENCILOP_DESC &desc,
  443. const StencilSide &side)
  444. {
  445. desc.StencilFunc = ConvertGSDepthTest(side.test);
  446. desc.StencilFailOp = ConvertGSStencilOp(side.fail);
  447. desc.StencilDepthFailOp = ConvertGSStencilOp(side.zfail);
  448. desc.StencilPassOp = ConvertGSStencilOp(side.zpass);
  449. }
  450. ID3D11DepthStencilState *gs_device::AddZStencilState()
  451. {
  452. HRESULT hr;
  453. D3D11_DEPTH_STENCIL_DESC dsd;
  454. ID3D11DepthStencilState *state;
  455. dsd.DepthEnable = zstencilState.depthEnabled;
  456. dsd.DepthFunc = ConvertGSDepthTest(zstencilState.depthFunc);
  457. dsd.DepthWriteMask = zstencilState.depthWriteEnabled
  458. ? D3D11_DEPTH_WRITE_MASK_ALL
  459. : D3D11_DEPTH_WRITE_MASK_ZERO;
  460. dsd.StencilEnable = zstencilState.stencilEnabled;
  461. dsd.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
  462. dsd.StencilWriteMask = zstencilState.stencilWriteEnabled
  463. ? D3D11_DEFAULT_STENCIL_WRITE_MASK
  464. : 0;
  465. ConvertStencilSide(dsd.FrontFace, zstencilState.stencilFront);
  466. ConvertStencilSide(dsd.BackFace, zstencilState.stencilBack);
  467. SavedZStencilState savedState(zstencilState, dsd);
  468. hr = device->CreateDepthStencilState(&dsd, savedState.state.Assign());
  469. if (FAILED(hr))
  470. throw HRError("Failed to create depth stencil state", hr);
  471. state = savedState.state;
  472. zstencilStates.push_back(savedState);
  473. return state;
  474. }
  475. ID3D11RasterizerState *gs_device::AddRasterState()
  476. {
  477. HRESULT hr;
  478. D3D11_RASTERIZER_DESC rd;
  479. ID3D11RasterizerState *state;
  480. memset(&rd, 0, sizeof(rd));
  481. /* use CCW to convert to a right-handed coordinate system */
  482. rd.FrontCounterClockwise = true;
  483. rd.FillMode = D3D11_FILL_SOLID;
  484. rd.CullMode = ConvertGSCullMode(rasterState.cullMode);
  485. rd.DepthClipEnable = true;
  486. rd.ScissorEnable = rasterState.scissorEnabled;
  487. SavedRasterState savedState(rasterState, rd);
  488. hr = device->CreateRasterizerState(&rd, savedState.state.Assign());
  489. if (FAILED(hr))
  490. throw HRError("Failed to create rasterizer state", hr);
  491. state = savedState.state;
  492. rasterStates.push_back(savedState);
  493. return state;
  494. }
  495. ID3D11BlendState *gs_device::AddBlendState()
  496. {
  497. HRESULT hr;
  498. D3D11_BLEND_DESC bd;
  499. ID3D11BlendState *state;
  500. memset(&bd, 0, sizeof(bd));
  501. for (int i = 0; i < 8; i++) {
  502. bd.RenderTarget[i].BlendEnable = blendState.blendEnabled;
  503. bd.RenderTarget[i].BlendOp = D3D11_BLEND_OP_ADD;
  504. bd.RenderTarget[i].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  505. bd.RenderTarget[i].SrcBlend =
  506. ConvertGSBlendType(blendState.srcFactorC);
  507. bd.RenderTarget[i].DestBlend =
  508. ConvertGSBlendType(blendState.destFactorC);
  509. bd.RenderTarget[i].SrcBlendAlpha =
  510. ConvertGSBlendType(blendState.srcFactorA);
  511. bd.RenderTarget[i].DestBlendAlpha =
  512. ConvertGSBlendType(blendState.destFactorA);
  513. bd.RenderTarget[i].RenderTargetWriteMask =
  514. (blendState.redEnabled ? D3D11_COLOR_WRITE_ENABLE_RED
  515. : 0) |
  516. (blendState.greenEnabled
  517. ? D3D11_COLOR_WRITE_ENABLE_GREEN
  518. : 0) |
  519. (blendState.blueEnabled ? D3D11_COLOR_WRITE_ENABLE_BLUE
  520. : 0) |
  521. (blendState.alphaEnabled
  522. ? D3D11_COLOR_WRITE_ENABLE_ALPHA
  523. : 0);
  524. }
  525. SavedBlendState savedState(blendState, bd);
  526. hr = device->CreateBlendState(&bd, savedState.state.Assign());
  527. if (FAILED(hr))
  528. throw HRError("Failed to create blend state", hr);
  529. state = savedState.state;
  530. blendStates.push_back(savedState);
  531. return state;
  532. }
  533. void gs_device::UpdateZStencilState()
  534. {
  535. ID3D11DepthStencilState *state = NULL;
  536. if (!zstencilStateChanged)
  537. return;
  538. for (size_t i = 0; i < zstencilStates.size(); i++) {
  539. SavedZStencilState &s = zstencilStates[i];
  540. if (memcmp(&s, &zstencilState, sizeof(zstencilState)) == 0) {
  541. state = s.state;
  542. break;
  543. }
  544. }
  545. if (!state)
  546. state = AddZStencilState();
  547. if (state != curDepthStencilState) {
  548. context->OMSetDepthStencilState(state, 0);
  549. curDepthStencilState = state;
  550. }
  551. zstencilStateChanged = false;
  552. }
  553. void gs_device::UpdateRasterState()
  554. {
  555. ID3D11RasterizerState *state = NULL;
  556. if (!rasterStateChanged)
  557. return;
  558. for (size_t i = 0; i < rasterStates.size(); i++) {
  559. SavedRasterState &s = rasterStates[i];
  560. if (memcmp(&s, &rasterState, sizeof(rasterState)) == 0) {
  561. state = s.state;
  562. break;
  563. }
  564. }
  565. if (!state)
  566. state = AddRasterState();
  567. if (state != curRasterState) {
  568. context->RSSetState(state);
  569. curRasterState = state;
  570. }
  571. rasterStateChanged = false;
  572. }
  573. void gs_device::UpdateBlendState()
  574. {
  575. ID3D11BlendState *state = NULL;
  576. if (!blendStateChanged)
  577. return;
  578. for (size_t i = 0; i < blendStates.size(); i++) {
  579. SavedBlendState &s = blendStates[i];
  580. if (memcmp(&s, &blendState, sizeof(blendState)) == 0) {
  581. state = s.state;
  582. break;
  583. }
  584. }
  585. if (!state)
  586. state = AddBlendState();
  587. if (state != curBlendState) {
  588. float f[4] = {1.0f, 1.0f, 1.0f, 1.0f};
  589. context->OMSetBlendState(state, f, 0xFFFFFFFF);
  590. curBlendState = state;
  591. }
  592. blendStateChanged = false;
  593. }
  594. void gs_device::UpdateViewProjMatrix()
  595. {
  596. gs_matrix_get(&curViewMatrix);
  597. /* negate Z col of the view matrix for right-handed coordinate system */
  598. curViewMatrix.x.z = -curViewMatrix.x.z;
  599. curViewMatrix.y.z = -curViewMatrix.y.z;
  600. curViewMatrix.z.z = -curViewMatrix.z.z;
  601. curViewMatrix.t.z = -curViewMatrix.t.z;
  602. matrix4_mul(&curViewProjMatrix, &curViewMatrix, &curProjMatrix);
  603. matrix4_transpose(&curViewProjMatrix, &curViewProjMatrix);
  604. if (curVertexShader->viewProj)
  605. gs_shader_set_matrix4(curVertexShader->viewProj,
  606. &curViewProjMatrix);
  607. }
  608. gs_device::gs_device(uint32_t adapterIdx)
  609. : curToplogy(D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED)
  610. {
  611. matrix4_identity(&curProjMatrix);
  612. matrix4_identity(&curViewMatrix);
  613. matrix4_identity(&curViewProjMatrix);
  614. memset(&viewport, 0, sizeof(viewport));
  615. for (size_t i = 0; i < GS_MAX_TEXTURES; i++) {
  616. curTextures[i] = NULL;
  617. curSamplers[i] = NULL;
  618. }
  619. InitCompiler();
  620. InitFactory(adapterIdx);
  621. InitDevice(adapterIdx);
  622. device_set_render_target(this, NULL, NULL);
  623. }
  624. gs_device::~gs_device()
  625. {
  626. context->ClearState();
  627. }
  628. const char *device_get_name(void)
  629. {
  630. return "Direct3D 11";
  631. }
  632. int device_get_type(void)
  633. {
  634. return GS_DEVICE_DIRECT3D_11;
  635. }
  636. const char *device_preprocessor_name(void)
  637. {
  638. return "_D3D11";
  639. }
  640. static inline void
  641. EnumD3DAdapters(bool (*callback)(void *, const char *, uint32_t), void *param)
  642. {
  643. ComPtr<IDXGIFactory1> factory;
  644. ComPtr<IDXGIAdapter1> adapter;
  645. HRESULT hr;
  646. UINT i;
  647. IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2
  648. : __uuidof(IDXGIFactory1);
  649. hr = CreateDXGIFactory1(factoryIID, (void **)factory.Assign());
  650. if (FAILED(hr))
  651. throw HRError("Failed to create DXGIFactory", hr);
  652. for (i = 0; factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) {
  653. DXGI_ADAPTER_DESC desc;
  654. char name[512] = "";
  655. hr = adapter->GetDesc(&desc);
  656. if (FAILED(hr))
  657. continue;
  658. /* ignore Microsoft's 'basic' renderer' */
  659. if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)
  660. continue;
  661. os_wcs_to_utf8(desc.Description, 0, name, sizeof(name));
  662. if (!callback(param, name, i))
  663. break;
  664. }
  665. }
  666. bool device_enum_adapters(bool (*callback)(void *param, const char *name,
  667. uint32_t id),
  668. void *param)
  669. {
  670. try {
  671. EnumD3DAdapters(callback, param);
  672. return true;
  673. } catch (const HRError &error) {
  674. blog(LOG_WARNING, "Failed enumerating devices: %s (%08lX)",
  675. error.str, error.hr);
  676. return false;
  677. }
  678. }
  679. static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter)
  680. {
  681. UINT i;
  682. ComPtr<IDXGIOutput> output;
  683. for (i = 0; adapter->EnumOutputs(i, &output) == S_OK; ++i) {
  684. DXGI_OUTPUT_DESC desc;
  685. if (FAILED(output->GetDesc(&desc)))
  686. continue;
  687. RECT rect = desc.DesktopCoordinates;
  688. blog(LOG_INFO,
  689. "\t output %u: "
  690. "pos={%d, %d}, "
  691. "size={%d, %d}, "
  692. "attached=%s",
  693. i, rect.left, rect.top, rect.right - rect.left,
  694. rect.bottom - rect.top,
  695. desc.AttachedToDesktop ? "true" : "false");
  696. }
  697. }
  698. static inline void LogD3DAdapters()
  699. {
  700. ComPtr<IDXGIFactory1> factory;
  701. ComPtr<IDXGIAdapter1> adapter;
  702. HRESULT hr;
  703. UINT i;
  704. blog(LOG_INFO, "Available Video Adapters: ");
  705. IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2
  706. : __uuidof(IDXGIFactory1);
  707. hr = CreateDXGIFactory1(factoryIID, (void **)factory.Assign());
  708. if (FAILED(hr))
  709. throw HRError("Failed to create DXGIFactory", hr);
  710. for (i = 0; factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) {
  711. DXGI_ADAPTER_DESC desc;
  712. char name[512] = "";
  713. hr = adapter->GetDesc(&desc);
  714. if (FAILED(hr))
  715. continue;
  716. /* ignore Microsoft's 'basic' renderer' */
  717. if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)
  718. continue;
  719. os_wcs_to_utf8(desc.Description, 0, name, sizeof(name));
  720. blog(LOG_INFO, "\tAdapter %u: %s", i, name);
  721. blog(LOG_INFO, "\t Dedicated VRAM: %u",
  722. desc.DedicatedVideoMemory);
  723. blog(LOG_INFO, "\t Shared VRAM: %u",
  724. desc.SharedSystemMemory);
  725. LogAdapterMonitors(adapter);
  726. }
  727. }
  728. int device_create(gs_device_t **p_device, uint32_t adapter)
  729. {
  730. gs_device *device = NULL;
  731. int errorcode = GS_SUCCESS;
  732. try {
  733. blog(LOG_INFO, "---------------------------------");
  734. blog(LOG_INFO, "Initializing D3D11...");
  735. LogD3DAdapters();
  736. device = new gs_device(adapter);
  737. } catch (const UnsupportedHWError &error) {
  738. blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str,
  739. error.hr);
  740. errorcode = GS_ERROR_NOT_SUPPORTED;
  741. } catch (const HRError &error) {
  742. blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str,
  743. error.hr);
  744. errorcode = GS_ERROR_FAIL;
  745. }
  746. *p_device = device;
  747. return errorcode;
  748. }
  749. void device_destroy(gs_device_t *device)
  750. {
  751. delete device;
  752. }
  753. void device_enter_context(gs_device_t *device)
  754. {
  755. /* does nothing */
  756. UNUSED_PARAMETER(device);
  757. }
  758. void device_leave_context(gs_device_t *device)
  759. {
  760. /* does nothing */
  761. UNUSED_PARAMETER(device);
  762. }
  763. void *device_get_device_obj(gs_device_t *device)
  764. {
  765. return (void *)device->device.Get();
  766. }
  767. gs_swapchain_t *device_swapchain_create(gs_device_t *device,
  768. const struct gs_init_data *data)
  769. {
  770. gs_swap_chain *swap = NULL;
  771. try {
  772. swap = new gs_swap_chain(device, data);
  773. } catch (const HRError &error) {
  774. blog(LOG_ERROR, "device_swapchain_create (D3D11): %s (%08lX)",
  775. error.str, error.hr);
  776. LogD3D11ErrorDetails(error, device);
  777. }
  778. return swap;
  779. }
  780. void device_resize(gs_device_t *device, uint32_t cx, uint32_t cy)
  781. {
  782. if (!device->curSwapChain) {
  783. blog(LOG_WARNING, "device_resize (D3D11): No active swap");
  784. return;
  785. }
  786. try {
  787. ID3D11RenderTargetView *renderView = NULL;
  788. ID3D11DepthStencilView *depthView = NULL;
  789. int i = device->curRenderSide;
  790. device->context->OMSetRenderTargets(1, &renderView, depthView);
  791. device->curSwapChain->Resize(cx, cy);
  792. if (device->curRenderTarget)
  793. renderView = device->curRenderTarget->renderTarget[i];
  794. if (device->curZStencilBuffer)
  795. depthView = device->curZStencilBuffer->view;
  796. device->context->OMSetRenderTargets(1, &renderView, depthView);
  797. } catch (const HRError &error) {
  798. blog(LOG_ERROR, "device_resize (D3D11): %s (%08lX)", error.str,
  799. error.hr);
  800. LogD3D11ErrorDetails(error, device);
  801. }
  802. }
  803. void device_get_size(const gs_device_t *device, uint32_t *cx, uint32_t *cy)
  804. {
  805. if (device->curSwapChain) {
  806. *cx = device->curSwapChain->target.width;
  807. *cy = device->curSwapChain->target.height;
  808. } else {
  809. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  810. *cx = 0;
  811. *cy = 0;
  812. }
  813. }
  814. uint32_t device_get_width(const gs_device_t *device)
  815. {
  816. if (device->curSwapChain) {
  817. return device->curSwapChain->target.width;
  818. } else {
  819. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  820. return 0;
  821. }
  822. }
  823. uint32_t device_get_height(const gs_device_t *device)
  824. {
  825. if (device->curSwapChain) {
  826. return device->curSwapChain->target.height;
  827. } else {
  828. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  829. return 0;
  830. }
  831. }
  832. gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width,
  833. uint32_t height,
  834. enum gs_color_format color_format,
  835. uint32_t levels, const uint8_t **data,
  836. uint32_t flags)
  837. {
  838. gs_texture *texture = NULL;
  839. try {
  840. texture = new gs_texture_2d(device, width, height, color_format,
  841. levels, data, flags, GS_TEXTURE_2D,
  842. false);
  843. } catch (const HRError &error) {
  844. blog(LOG_ERROR, "device_texture_create (D3D11): %s (%08lX)",
  845. error.str, error.hr);
  846. LogD3D11ErrorDetails(error, device);
  847. } catch (const char *error) {
  848. blog(LOG_ERROR, "device_texture_create (D3D11): %s", error);
  849. }
  850. return texture;
  851. }
  852. gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size,
  853. enum gs_color_format color_format,
  854. uint32_t levels, const uint8_t **data,
  855. uint32_t flags)
  856. {
  857. gs_texture *texture = NULL;
  858. try {
  859. texture = new gs_texture_2d(device, size, size, color_format,
  860. levels, data, flags,
  861. GS_TEXTURE_CUBE, false);
  862. } catch (const HRError &error) {
  863. blog(LOG_ERROR,
  864. "device_cubetexture_create (D3D11): %s "
  865. "(%08lX)",
  866. error.str, error.hr);
  867. LogD3D11ErrorDetails(error, device);
  868. } catch (const char *error) {
  869. blog(LOG_ERROR, "device_cubetexture_create (D3D11): %s", error);
  870. }
  871. return texture;
  872. }
  873. gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width,
  874. uint32_t height, uint32_t depth,
  875. enum gs_color_format color_format,
  876. uint32_t levels, const uint8_t **data,
  877. uint32_t flags)
  878. {
  879. /* TODO */
  880. UNUSED_PARAMETER(device);
  881. UNUSED_PARAMETER(width);
  882. UNUSED_PARAMETER(height);
  883. UNUSED_PARAMETER(depth);
  884. UNUSED_PARAMETER(color_format);
  885. UNUSED_PARAMETER(levels);
  886. UNUSED_PARAMETER(data);
  887. UNUSED_PARAMETER(flags);
  888. return NULL;
  889. }
  890. gs_zstencil_t *device_zstencil_create(gs_device_t *device, uint32_t width,
  891. uint32_t height,
  892. enum gs_zstencil_format format)
  893. {
  894. gs_zstencil_buffer *zstencil = NULL;
  895. try {
  896. zstencil =
  897. new gs_zstencil_buffer(device, width, height, format);
  898. } catch (const HRError &error) {
  899. blog(LOG_ERROR, "device_zstencil_create (D3D11): %s (%08lX)",
  900. error.str, error.hr);
  901. LogD3D11ErrorDetails(error, device);
  902. }
  903. return zstencil;
  904. }
  905. gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width,
  906. uint32_t height,
  907. enum gs_color_format color_format)
  908. {
  909. gs_stage_surface *surf = NULL;
  910. try {
  911. surf = new gs_stage_surface(device, width, height,
  912. color_format);
  913. } catch (const HRError &error) {
  914. blog(LOG_ERROR,
  915. "device_stagesurface_create (D3D11): %s "
  916. "(%08lX)",
  917. error.str, error.hr);
  918. LogD3D11ErrorDetails(error, device);
  919. }
  920. return surf;
  921. }
  922. gs_samplerstate_t *
  923. device_samplerstate_create(gs_device_t *device,
  924. const struct gs_sampler_info *info)
  925. {
  926. gs_sampler_state *ss = NULL;
  927. try {
  928. ss = new gs_sampler_state(device, info);
  929. } catch (const HRError &error) {
  930. blog(LOG_ERROR,
  931. "device_samplerstate_create (D3D11): %s "
  932. "(%08lX)",
  933. error.str, error.hr);
  934. LogD3D11ErrorDetails(error, device);
  935. }
  936. return ss;
  937. }
  938. gs_shader_t *device_vertexshader_create(gs_device_t *device,
  939. const char *shader_string,
  940. const char *file, char **error_string)
  941. {
  942. gs_vertex_shader *shader = NULL;
  943. try {
  944. shader = new gs_vertex_shader(device, file, shader_string);
  945. } catch (const HRError &error) {
  946. blog(LOG_ERROR,
  947. "device_vertexshader_create (D3D11): %s "
  948. "(%08lX)",
  949. error.str, error.hr);
  950. LogD3D11ErrorDetails(error, device);
  951. } catch (const ShaderError &error) {
  952. const char *buf =
  953. (const char *)error.errors->GetBufferPointer();
  954. if (error_string)
  955. *error_string = bstrdup(buf);
  956. blog(LOG_ERROR,
  957. "device_vertexshader_create (D3D11): "
  958. "Compile warnings/errors for %s:\n%s",
  959. file, buf);
  960. } catch (const char *error) {
  961. blog(LOG_ERROR, "device_vertexshader_create (D3D11): %s",
  962. error);
  963. }
  964. return shader;
  965. }
  966. gs_shader_t *device_pixelshader_create(gs_device_t *device,
  967. const char *shader_string,
  968. const char *file, char **error_string)
  969. {
  970. gs_pixel_shader *shader = NULL;
  971. try {
  972. shader = new gs_pixel_shader(device, file, shader_string);
  973. } catch (const HRError &error) {
  974. blog(LOG_ERROR,
  975. "device_pixelshader_create (D3D11): %s "
  976. "(%08lX)",
  977. error.str, error.hr);
  978. LogD3D11ErrorDetails(error, device);
  979. } catch (const ShaderError &error) {
  980. const char *buf =
  981. (const char *)error.errors->GetBufferPointer();
  982. if (error_string)
  983. *error_string = bstrdup(buf);
  984. blog(LOG_ERROR,
  985. "device_pixelshader_create (D3D11): "
  986. "Compiler warnings/errors for %s:\n%s",
  987. file, buf);
  988. } catch (const char *error) {
  989. blog(LOG_ERROR, "device_pixelshader_create (D3D11): %s", error);
  990. }
  991. return shader;
  992. }
  993. gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device,
  994. struct gs_vb_data *data,
  995. uint32_t flags)
  996. {
  997. gs_vertex_buffer *buffer = NULL;
  998. try {
  999. buffer = new gs_vertex_buffer(device, data, flags);
  1000. } catch (const HRError &error) {
  1001. blog(LOG_ERROR,
  1002. "device_vertexbuffer_create (D3D11): %s "
  1003. "(%08lX)",
  1004. error.str, error.hr);
  1005. LogD3D11ErrorDetails(error, device);
  1006. } catch (const char *error) {
  1007. blog(LOG_ERROR, "device_vertexbuffer_create (D3D11): %s",
  1008. error);
  1009. }
  1010. return buffer;
  1011. }
  1012. gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device,
  1013. enum gs_index_type type,
  1014. void *indices, size_t num,
  1015. uint32_t flags)
  1016. {
  1017. gs_index_buffer *buffer = NULL;
  1018. try {
  1019. buffer = new gs_index_buffer(device, type, indices, num, flags);
  1020. } catch (const HRError &error) {
  1021. blog(LOG_ERROR, "device_indexbuffer_create (D3D11): %s (%08lX)",
  1022. error.str, error.hr);
  1023. LogD3D11ErrorDetails(error, device);
  1024. }
  1025. return buffer;
  1026. }
  1027. gs_timer_t *device_timer_create(gs_device_t *device)
  1028. {
  1029. gs_timer *timer = NULL;
  1030. try {
  1031. timer = new gs_timer(device);
  1032. } catch (const HRError &error) {
  1033. blog(LOG_ERROR, "device_timer_create (D3D11): %s (%08lX)",
  1034. error.str, error.hr);
  1035. LogD3D11ErrorDetails(error, device);
  1036. }
  1037. return timer;
  1038. }
  1039. gs_timer_range_t *device_timer_range_create(gs_device_t *device)
  1040. {
  1041. gs_timer_range *range = NULL;
  1042. try {
  1043. range = new gs_timer_range(device);
  1044. } catch (const HRError &error) {
  1045. blog(LOG_ERROR, "device_timer_range_create (D3D11): %s (%08lX)",
  1046. error.str, error.hr);
  1047. LogD3D11ErrorDetails(error, device);
  1048. }
  1049. return range;
  1050. }
  1051. enum gs_texture_type device_get_texture_type(const gs_texture_t *texture)
  1052. {
  1053. return texture->type;
  1054. }
  1055. void gs_device::LoadVertexBufferData()
  1056. {
  1057. if (curVertexBuffer == lastVertexBuffer &&
  1058. curVertexShader == lastVertexShader)
  1059. return;
  1060. vector<ID3D11Buffer *> buffers;
  1061. vector<uint32_t> strides;
  1062. vector<uint32_t> offsets;
  1063. if (curVertexBuffer && curVertexShader) {
  1064. curVertexBuffer->MakeBufferList(curVertexShader, buffers,
  1065. strides);
  1066. } else {
  1067. size_t buffersToClear =
  1068. curVertexShader ? curVertexShader->NumBuffersExpected()
  1069. : 0;
  1070. buffers.resize(buffersToClear);
  1071. strides.resize(buffersToClear);
  1072. }
  1073. offsets.resize(buffers.size());
  1074. context->IASetVertexBuffers(0, (UINT)buffers.size(), buffers.data(),
  1075. strides.data(), offsets.data());
  1076. lastVertexBuffer = curVertexBuffer;
  1077. lastVertexShader = curVertexShader;
  1078. }
  1079. void device_load_vertexbuffer(gs_device_t *device, gs_vertbuffer_t *vertbuffer)
  1080. {
  1081. if (device->curVertexBuffer == vertbuffer)
  1082. return;
  1083. device->curVertexBuffer = vertbuffer;
  1084. }
  1085. void device_load_indexbuffer(gs_device_t *device, gs_indexbuffer_t *indexbuffer)
  1086. {
  1087. DXGI_FORMAT format;
  1088. ID3D11Buffer *buffer;
  1089. if (device->curIndexBuffer == indexbuffer)
  1090. return;
  1091. if (indexbuffer) {
  1092. switch (indexbuffer->indexSize) {
  1093. case 2:
  1094. format = DXGI_FORMAT_R16_UINT;
  1095. break;
  1096. default:
  1097. case 4:
  1098. format = DXGI_FORMAT_R32_UINT;
  1099. break;
  1100. }
  1101. buffer = indexbuffer->indexBuffer;
  1102. } else {
  1103. buffer = NULL;
  1104. format = DXGI_FORMAT_R32_UINT;
  1105. }
  1106. device->curIndexBuffer = indexbuffer;
  1107. device->context->IASetIndexBuffer(buffer, format, 0);
  1108. }
  1109. void device_load_texture(gs_device_t *device, gs_texture_t *tex, int unit)
  1110. {
  1111. ID3D11ShaderResourceView *view = NULL;
  1112. if (device->curTextures[unit] == tex)
  1113. return;
  1114. if (tex)
  1115. view = tex->shaderRes;
  1116. device->curTextures[unit] = tex;
  1117. device->context->PSSetShaderResources(unit, 1, &view);
  1118. }
  1119. void device_load_samplerstate(gs_device_t *device,
  1120. gs_samplerstate_t *samplerstate, int unit)
  1121. {
  1122. ID3D11SamplerState *state = NULL;
  1123. if (device->curSamplers[unit] == samplerstate)
  1124. return;
  1125. if (samplerstate)
  1126. state = samplerstate->state;
  1127. device->curSamplers[unit] = samplerstate;
  1128. device->context->PSSetSamplers(unit, 1, &state);
  1129. }
  1130. void device_load_vertexshader(gs_device_t *device, gs_shader_t *vertshader)
  1131. {
  1132. ID3D11VertexShader *shader = NULL;
  1133. ID3D11InputLayout *layout = NULL;
  1134. ID3D11Buffer *constants = NULL;
  1135. if (device->curVertexShader == vertshader)
  1136. return;
  1137. gs_vertex_shader *vs = static_cast<gs_vertex_shader *>(vertshader);
  1138. if (vertshader) {
  1139. if (vertshader->type != GS_SHADER_VERTEX) {
  1140. blog(LOG_ERROR, "device_load_vertexshader (D3D11): "
  1141. "Specified shader is not a vertex "
  1142. "shader");
  1143. return;
  1144. }
  1145. shader = vs->shader;
  1146. layout = vs->layout;
  1147. constants = vs->constants;
  1148. }
  1149. device->curVertexShader = vs;
  1150. device->context->VSSetShader(shader, NULL, 0);
  1151. device->context->IASetInputLayout(layout);
  1152. device->context->VSSetConstantBuffers(0, 1, &constants);
  1153. }
  1154. static inline void clear_textures(gs_device_t *device)
  1155. {
  1156. ID3D11ShaderResourceView *views[GS_MAX_TEXTURES];
  1157. memset(views, 0, sizeof(views));
  1158. memset(device->curTextures, 0, sizeof(device->curTextures));
  1159. device->context->PSSetShaderResources(0, GS_MAX_TEXTURES, views);
  1160. }
  1161. void device_load_pixelshader(gs_device_t *device, gs_shader_t *pixelshader)
  1162. {
  1163. ID3D11PixelShader *shader = NULL;
  1164. ID3D11Buffer *constants = NULL;
  1165. ID3D11SamplerState *states[GS_MAX_TEXTURES];
  1166. if (device->curPixelShader == pixelshader)
  1167. return;
  1168. gs_pixel_shader *ps = static_cast<gs_pixel_shader *>(pixelshader);
  1169. if (pixelshader) {
  1170. if (pixelshader->type != GS_SHADER_PIXEL) {
  1171. blog(LOG_ERROR, "device_load_pixelshader (D3D11): "
  1172. "Specified shader is not a pixel "
  1173. "shader");
  1174. return;
  1175. }
  1176. shader = ps->shader;
  1177. constants = ps->constants;
  1178. ps->GetSamplerStates(states);
  1179. } else {
  1180. memset(states, 0, sizeof(states));
  1181. }
  1182. clear_textures(device);
  1183. device->curPixelShader = ps;
  1184. device->context->PSSetShader(shader, NULL, 0);
  1185. device->context->PSSetConstantBuffers(0, 1, &constants);
  1186. device->context->PSSetSamplers(0, GS_MAX_TEXTURES, states);
  1187. for (int i = 0; i < GS_MAX_TEXTURES; i++)
  1188. if (device->curSamplers[i] &&
  1189. device->curSamplers[i]->state != states[i])
  1190. device->curSamplers[i] = nullptr;
  1191. }
  1192. void device_load_default_samplerstate(gs_device_t *device, bool b_3d, int unit)
  1193. {
  1194. /* TODO */
  1195. UNUSED_PARAMETER(device);
  1196. UNUSED_PARAMETER(b_3d);
  1197. UNUSED_PARAMETER(unit);
  1198. }
  1199. gs_shader_t *device_get_vertex_shader(const gs_device_t *device)
  1200. {
  1201. return device->curVertexShader;
  1202. }
  1203. gs_shader_t *device_get_pixel_shader(const gs_device_t *device)
  1204. {
  1205. return device->curPixelShader;
  1206. }
  1207. gs_texture_t *device_get_render_target(const gs_device_t *device)
  1208. {
  1209. if (device->curRenderTarget == &device->curSwapChain->target)
  1210. return NULL;
  1211. return device->curRenderTarget;
  1212. }
  1213. gs_zstencil_t *device_get_zstencil_target(const gs_device_t *device)
  1214. {
  1215. if (device->curZStencilBuffer == &device->curSwapChain->zs)
  1216. return NULL;
  1217. return device->curZStencilBuffer;
  1218. }
  1219. void device_set_render_target(gs_device_t *device, gs_texture_t *tex,
  1220. gs_zstencil_t *zstencil)
  1221. {
  1222. if (device->curSwapChain) {
  1223. if (!tex)
  1224. tex = &device->curSwapChain->target;
  1225. if (!zstencil)
  1226. zstencil = &device->curSwapChain->zs;
  1227. }
  1228. if (device->curRenderTarget == tex &&
  1229. device->curZStencilBuffer == zstencil)
  1230. return;
  1231. if (tex && tex->type != GS_TEXTURE_2D) {
  1232. blog(LOG_ERROR, "device_set_render_target (D3D11): "
  1233. "texture is not a 2D texture");
  1234. return;
  1235. }
  1236. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1237. if (tex2d && !tex2d->renderTarget[0]) {
  1238. blog(LOG_ERROR, "device_set_render_target (D3D11): "
  1239. "texture is not a render target");
  1240. return;
  1241. }
  1242. ID3D11RenderTargetView *rt = tex2d ? tex2d->renderTarget[0].Get()
  1243. : nullptr;
  1244. device->curRenderTarget = tex2d;
  1245. device->curRenderSide = 0;
  1246. device->curZStencilBuffer = zstencil;
  1247. device->context->OMSetRenderTargets(
  1248. 1, &rt, zstencil ? zstencil->view : nullptr);
  1249. }
  1250. void device_set_cube_render_target(gs_device_t *device, gs_texture_t *tex,
  1251. int side, gs_zstencil_t *zstencil)
  1252. {
  1253. if (device->curSwapChain) {
  1254. if (!tex) {
  1255. tex = &device->curSwapChain->target;
  1256. side = 0;
  1257. }
  1258. if (!zstencil)
  1259. zstencil = &device->curSwapChain->zs;
  1260. }
  1261. if (device->curRenderTarget == tex && device->curRenderSide == side &&
  1262. device->curZStencilBuffer == zstencil)
  1263. return;
  1264. if (tex->type != GS_TEXTURE_CUBE) {
  1265. blog(LOG_ERROR, "device_set_cube_render_target (D3D11): "
  1266. "texture is not a cube texture");
  1267. return;
  1268. }
  1269. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1270. if (!tex2d->renderTarget[side]) {
  1271. blog(LOG_ERROR, "device_set_cube_render_target (D3D11): "
  1272. "texture is not a render target");
  1273. return;
  1274. }
  1275. ID3D11RenderTargetView *rt = tex2d->renderTarget[0];
  1276. device->curRenderTarget = tex2d;
  1277. device->curRenderSide = side;
  1278. device->curZStencilBuffer = zstencil;
  1279. device->context->OMSetRenderTargets(1, &rt, zstencil->view);
  1280. }
  1281. inline void gs_device::CopyTex(ID3D11Texture2D *dst, uint32_t dst_x,
  1282. uint32_t dst_y, gs_texture_t *src,
  1283. uint32_t src_x, uint32_t src_y, uint32_t src_w,
  1284. uint32_t src_h)
  1285. {
  1286. if (src->type != GS_TEXTURE_2D)
  1287. throw "Source texture must be a 2D texture";
  1288. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(src);
  1289. if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 &&
  1290. src_w == 0 && src_h == 0) {
  1291. context->CopyResource(dst, tex2d->texture);
  1292. } else {
  1293. D3D11_BOX sbox;
  1294. sbox.left = src_x;
  1295. if (src_w > 0)
  1296. sbox.right = src_x + src_w;
  1297. else
  1298. sbox.right = tex2d->width - 1;
  1299. sbox.top = src_y;
  1300. if (src_h > 0)
  1301. sbox.bottom = src_y + src_h;
  1302. else
  1303. sbox.bottom = tex2d->height - 1;
  1304. sbox.front = 0;
  1305. sbox.back = 1;
  1306. context->CopySubresourceRegion(dst, 0, dst_x, dst_y, 0,
  1307. tex2d->texture, 0, &sbox);
  1308. }
  1309. }
  1310. void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst,
  1311. uint32_t dst_x, uint32_t dst_y,
  1312. gs_texture_t *src, uint32_t src_x,
  1313. uint32_t src_y, uint32_t src_w, uint32_t src_h)
  1314. {
  1315. try {
  1316. gs_texture_2d *src2d = static_cast<gs_texture_2d *>(src);
  1317. gs_texture_2d *dst2d = static_cast<gs_texture_2d *>(dst);
  1318. if (!src)
  1319. throw "Source texture is NULL";
  1320. if (!dst)
  1321. throw "Destination texture is NULL";
  1322. if (src->type != GS_TEXTURE_2D || dst->type != GS_TEXTURE_2D)
  1323. throw "Source and destination textures must be a 2D "
  1324. "textures";
  1325. if (dst->format != src->format)
  1326. throw "Source and destination formats do not match";
  1327. /* apparently casting to the same type that the variable
  1328. * already exists as is supposed to prevent some warning
  1329. * when used with the conditional operator? */
  1330. uint32_t copyWidth = (uint32_t)src_w ? (uint32_t)src_w
  1331. : (src2d->width - src_x);
  1332. uint32_t copyHeight = (uint32_t)src_h ? (uint32_t)src_h
  1333. : (src2d->height - src_y);
  1334. uint32_t dstWidth = dst2d->width - dst_x;
  1335. uint32_t dstHeight = dst2d->height - dst_y;
  1336. if (dstWidth < copyWidth || dstHeight < copyHeight)
  1337. throw "Destination texture region is not big "
  1338. "enough to hold the source region";
  1339. if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 &&
  1340. src_w == 0 && src_h == 0) {
  1341. copyWidth = 0;
  1342. copyHeight = 0;
  1343. }
  1344. device->CopyTex(dst2d->texture, dst_x, dst_y, src, src_x, src_y,
  1345. copyWidth, copyHeight);
  1346. } catch (const char *error) {
  1347. blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error);
  1348. }
  1349. }
  1350. void device_copy_texture(gs_device_t *device, gs_texture_t *dst,
  1351. gs_texture_t *src)
  1352. {
  1353. device_copy_texture_region(device, dst, 0, 0, src, 0, 0, 0, 0);
  1354. }
  1355. void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst,
  1356. gs_texture_t *src)
  1357. {
  1358. try {
  1359. gs_texture_2d *src2d = static_cast<gs_texture_2d *>(src);
  1360. if (!src)
  1361. throw "Source texture is NULL";
  1362. if (src->type != GS_TEXTURE_2D)
  1363. throw "Source texture must be a 2D texture";
  1364. if (!dst)
  1365. throw "Destination surface is NULL";
  1366. if (dst->format != GS_UNKNOWN && dst->format != src->format)
  1367. throw "Source and destination formats do not match";
  1368. if (dst->width != src2d->width || dst->height != src2d->height)
  1369. throw "Source and destination must have the same "
  1370. "dimensions";
  1371. device->CopyTex(dst->texture, 0, 0, src, 0, 0, 0, 0);
  1372. } catch (const char *error) {
  1373. blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error);
  1374. }
  1375. }
  1376. void device_begin_scene(gs_device_t *device)
  1377. {
  1378. clear_textures(device);
  1379. }
  1380. void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode,
  1381. uint32_t start_vert, uint32_t num_verts)
  1382. {
  1383. try {
  1384. if (!device->curVertexShader)
  1385. throw "No vertex shader specified";
  1386. if (!device->curPixelShader)
  1387. throw "No pixel shader specified";
  1388. if (!device->curVertexBuffer && (num_verts == 0))
  1389. throw "No vertex buffer specified";
  1390. if (!device->curSwapChain && !device->curRenderTarget)
  1391. throw "No render target or swap chain to render to";
  1392. gs_effect_t *effect = gs_get_effect();
  1393. if (effect)
  1394. gs_effect_update_params(effect);
  1395. device->LoadVertexBufferData();
  1396. device->UpdateBlendState();
  1397. device->UpdateRasterState();
  1398. device->UpdateZStencilState();
  1399. device->UpdateViewProjMatrix();
  1400. device->curVertexShader->UploadParams();
  1401. device->curPixelShader->UploadParams();
  1402. } catch (const char *error) {
  1403. blog(LOG_ERROR, "device_draw (D3D11): %s", error);
  1404. return;
  1405. } catch (const HRError &error) {
  1406. blog(LOG_ERROR, "device_draw (D3D11): %s (%08lX)", error.str,
  1407. error.hr);
  1408. LogD3D11ErrorDetails(error, device);
  1409. return;
  1410. }
  1411. D3D11_PRIMITIVE_TOPOLOGY newTopology = ConvertGSTopology(draw_mode);
  1412. if (device->curToplogy != newTopology) {
  1413. device->context->IASetPrimitiveTopology(newTopology);
  1414. device->curToplogy = newTopology;
  1415. }
  1416. if (device->curIndexBuffer) {
  1417. if (num_verts == 0)
  1418. num_verts = (uint32_t)device->curIndexBuffer->num;
  1419. device->context->DrawIndexed(num_verts, start_vert, 0);
  1420. } else {
  1421. if (num_verts == 0)
  1422. num_verts = (uint32_t)device->curVertexBuffer->numVerts;
  1423. device->context->Draw(num_verts, start_vert);
  1424. }
  1425. }
  1426. void device_end_scene(gs_device_t *device)
  1427. {
  1428. /* does nothing in D3D11 */
  1429. UNUSED_PARAMETER(device);
  1430. }
  1431. void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swapchain)
  1432. {
  1433. gs_texture_t *target = device->curRenderTarget;
  1434. gs_zstencil_t *zs = device->curZStencilBuffer;
  1435. bool is_cube =
  1436. device->curRenderTarget
  1437. ? (device->curRenderTarget->type == GS_TEXTURE_CUBE)
  1438. : false;
  1439. if (device->curSwapChain) {
  1440. if (target == &device->curSwapChain->target)
  1441. target = NULL;
  1442. if (zs == &device->curSwapChain->zs)
  1443. zs = NULL;
  1444. }
  1445. device->curSwapChain = swapchain;
  1446. if (is_cube)
  1447. device_set_cube_render_target(device, target,
  1448. device->curRenderSide, zs);
  1449. else
  1450. device_set_render_target(device, target, zs);
  1451. }
  1452. void device_clear(gs_device_t *device, uint32_t clear_flags,
  1453. const struct vec4 *color, float depth, uint8_t stencil)
  1454. {
  1455. int side = device->curRenderSide;
  1456. if ((clear_flags & GS_CLEAR_COLOR) != 0 && device->curRenderTarget)
  1457. device->context->ClearRenderTargetView(
  1458. device->curRenderTarget->renderTarget[side],
  1459. color->ptr);
  1460. if (device->curZStencilBuffer) {
  1461. uint32_t flags = 0;
  1462. if ((clear_flags & GS_CLEAR_DEPTH) != 0)
  1463. flags |= D3D11_CLEAR_DEPTH;
  1464. if ((clear_flags & GS_CLEAR_STENCIL) != 0)
  1465. flags |= D3D11_CLEAR_STENCIL;
  1466. if (flags && device->curZStencilBuffer->view)
  1467. device->context->ClearDepthStencilView(
  1468. device->curZStencilBuffer->view, flags, depth,
  1469. stencil);
  1470. }
  1471. }
  1472. void device_present(gs_device_t *device)
  1473. {
  1474. HRESULT hr;
  1475. if (device->curSwapChain) {
  1476. hr = device->curSwapChain->swap->Present(0, 0);
  1477. if (hr == DXGI_ERROR_DEVICE_REMOVED ||
  1478. hr == DXGI_ERROR_DEVICE_RESET) {
  1479. device->RebuildDevice();
  1480. }
  1481. } else {
  1482. blog(LOG_WARNING, "device_present (D3D11): No active swap");
  1483. }
  1484. }
  1485. extern "C" void reset_duplicators(void);
  1486. void device_flush(gs_device_t *device)
  1487. {
  1488. device->context->Flush();
  1489. reset_duplicators();
  1490. }
  1491. void device_set_cull_mode(gs_device_t *device, enum gs_cull_mode mode)
  1492. {
  1493. if (mode == device->rasterState.cullMode)
  1494. return;
  1495. device->rasterState.cullMode = mode;
  1496. device->rasterStateChanged = true;
  1497. }
  1498. enum gs_cull_mode device_get_cull_mode(const gs_device_t *device)
  1499. {
  1500. return device->rasterState.cullMode;
  1501. }
  1502. void device_enable_blending(gs_device_t *device, bool enable)
  1503. {
  1504. if (enable == device->blendState.blendEnabled)
  1505. return;
  1506. device->blendState.blendEnabled = enable;
  1507. device->blendStateChanged = true;
  1508. }
  1509. void device_enable_depth_test(gs_device_t *device, bool enable)
  1510. {
  1511. if (enable == device->zstencilState.depthEnabled)
  1512. return;
  1513. device->zstencilState.depthEnabled = enable;
  1514. device->zstencilStateChanged = true;
  1515. }
  1516. void device_enable_stencil_test(gs_device_t *device, bool enable)
  1517. {
  1518. if (enable == device->zstencilState.stencilEnabled)
  1519. return;
  1520. device->zstencilState.stencilEnabled = enable;
  1521. device->zstencilStateChanged = true;
  1522. }
  1523. void device_enable_stencil_write(gs_device_t *device, bool enable)
  1524. {
  1525. if (enable == device->zstencilState.stencilWriteEnabled)
  1526. return;
  1527. device->zstencilState.stencilWriteEnabled = enable;
  1528. device->zstencilStateChanged = true;
  1529. }
  1530. void device_enable_color(gs_device_t *device, bool red, bool green, bool blue,
  1531. bool alpha)
  1532. {
  1533. if (device->blendState.redEnabled == red &&
  1534. device->blendState.greenEnabled == green &&
  1535. device->blendState.blueEnabled == blue &&
  1536. device->blendState.alphaEnabled == alpha)
  1537. return;
  1538. device->blendState.redEnabled = red;
  1539. device->blendState.greenEnabled = green;
  1540. device->blendState.blueEnabled = blue;
  1541. device->blendState.alphaEnabled = alpha;
  1542. device->blendStateChanged = true;
  1543. }
  1544. void device_blend_function(gs_device_t *device, enum gs_blend_type src,
  1545. enum gs_blend_type dest)
  1546. {
  1547. if (device->blendState.srcFactorC == src &&
  1548. device->blendState.destFactorC == dest &&
  1549. device->blendState.srcFactorA == src &&
  1550. device->blendState.destFactorA == dest)
  1551. return;
  1552. device->blendState.srcFactorC = src;
  1553. device->blendState.destFactorC = dest;
  1554. device->blendState.srcFactorA = src;
  1555. device->blendState.destFactorA = dest;
  1556. device->blendStateChanged = true;
  1557. }
  1558. void device_blend_function_separate(gs_device_t *device,
  1559. enum gs_blend_type src_c,
  1560. enum gs_blend_type dest_c,
  1561. enum gs_blend_type src_a,
  1562. enum gs_blend_type dest_a)
  1563. {
  1564. if (device->blendState.srcFactorC == src_c &&
  1565. device->blendState.destFactorC == dest_c &&
  1566. device->blendState.srcFactorA == src_a &&
  1567. device->blendState.destFactorA == dest_a)
  1568. return;
  1569. device->blendState.srcFactorC = src_c;
  1570. device->blendState.destFactorC = dest_c;
  1571. device->blendState.srcFactorA = src_a;
  1572. device->blendState.destFactorA = dest_a;
  1573. device->blendStateChanged = true;
  1574. }
  1575. void device_depth_function(gs_device_t *device, enum gs_depth_test test)
  1576. {
  1577. if (device->zstencilState.depthFunc == test)
  1578. return;
  1579. device->zstencilState.depthFunc = test;
  1580. device->zstencilStateChanged = true;
  1581. }
  1582. static inline void update_stencilside_test(gs_device_t *device,
  1583. StencilSide &side,
  1584. gs_depth_test test)
  1585. {
  1586. if (side.test == test)
  1587. return;
  1588. side.test = test;
  1589. device->zstencilStateChanged = true;
  1590. }
  1591. void device_stencil_function(gs_device_t *device, enum gs_stencil_side side,
  1592. enum gs_depth_test test)
  1593. {
  1594. int sideVal = (int)side;
  1595. if (sideVal & GS_STENCIL_FRONT)
  1596. update_stencilside_test(
  1597. device, device->zstencilState.stencilFront, test);
  1598. if (sideVal & GS_STENCIL_BACK)
  1599. update_stencilside_test(
  1600. device, device->zstencilState.stencilBack, test);
  1601. }
  1602. static inline void update_stencilside_op(gs_device_t *device, StencilSide &side,
  1603. enum gs_stencil_op_type fail,
  1604. enum gs_stencil_op_type zfail,
  1605. enum gs_stencil_op_type zpass)
  1606. {
  1607. if (side.fail == fail && side.zfail == zfail && side.zpass == zpass)
  1608. return;
  1609. side.fail = fail;
  1610. side.zfail = zfail;
  1611. side.zpass = zpass;
  1612. device->zstencilStateChanged = true;
  1613. }
  1614. void device_stencil_op(gs_device_t *device, enum gs_stencil_side side,
  1615. enum gs_stencil_op_type fail,
  1616. enum gs_stencil_op_type zfail,
  1617. enum gs_stencil_op_type zpass)
  1618. {
  1619. int sideVal = (int)side;
  1620. if (sideVal & GS_STENCIL_FRONT)
  1621. update_stencilside_op(device,
  1622. device->zstencilState.stencilFront, fail,
  1623. zfail, zpass);
  1624. if (sideVal & GS_STENCIL_BACK)
  1625. update_stencilside_op(device, device->zstencilState.stencilBack,
  1626. fail, zfail, zpass);
  1627. }
  1628. void device_set_viewport(gs_device_t *device, int x, int y, int width,
  1629. int height)
  1630. {
  1631. D3D11_VIEWPORT vp;
  1632. memset(&vp, 0, sizeof(vp));
  1633. vp.MaxDepth = 1.0f;
  1634. vp.TopLeftX = (float)x;
  1635. vp.TopLeftY = (float)y;
  1636. vp.Width = (float)width;
  1637. vp.Height = (float)height;
  1638. device->context->RSSetViewports(1, &vp);
  1639. device->viewport.x = x;
  1640. device->viewport.y = y;
  1641. device->viewport.cx = width;
  1642. device->viewport.cy = height;
  1643. }
  1644. void device_get_viewport(const gs_device_t *device, struct gs_rect *rect)
  1645. {
  1646. memcpy(rect, &device->viewport, sizeof(gs_rect));
  1647. }
  1648. void device_set_scissor_rect(gs_device_t *device, const struct gs_rect *rect)
  1649. {
  1650. D3D11_RECT d3drect;
  1651. device->rasterState.scissorEnabled = (rect != NULL);
  1652. if (rect != NULL) {
  1653. d3drect.left = rect->x;
  1654. d3drect.top = rect->y;
  1655. d3drect.right = rect->x + rect->cx;
  1656. d3drect.bottom = rect->y + rect->cy;
  1657. device->context->RSSetScissorRects(1, &d3drect);
  1658. }
  1659. device->rasterStateChanged = true;
  1660. }
  1661. void device_ortho(gs_device_t *device, float left, float right, float top,
  1662. float bottom, float zNear, float zFar)
  1663. {
  1664. matrix4 *dst = &device->curProjMatrix;
  1665. float rml = right - left;
  1666. float bmt = bottom - top;
  1667. float fmn = zFar - zNear;
  1668. vec4_zero(&dst->x);
  1669. vec4_zero(&dst->y);
  1670. vec4_zero(&dst->z);
  1671. vec4_zero(&dst->t);
  1672. dst->x.x = 2.0f / rml;
  1673. dst->t.x = (left + right) / -rml;
  1674. dst->y.y = 2.0f / -bmt;
  1675. dst->t.y = (bottom + top) / bmt;
  1676. dst->z.z = 1.0f / fmn;
  1677. dst->t.z = zNear / -fmn;
  1678. dst->t.w = 1.0f;
  1679. }
  1680. void device_frustum(gs_device_t *device, float left, float right, float top,
  1681. float bottom, float zNear, float zFar)
  1682. {
  1683. matrix4 *dst = &device->curProjMatrix;
  1684. float rml = right - left;
  1685. float bmt = bottom - top;
  1686. float fmn = zFar - zNear;
  1687. float nearx2 = 2.0f * zNear;
  1688. vec4_zero(&dst->x);
  1689. vec4_zero(&dst->y);
  1690. vec4_zero(&dst->z);
  1691. vec4_zero(&dst->t);
  1692. dst->x.x = nearx2 / rml;
  1693. dst->z.x = (left + right) / -rml;
  1694. dst->y.y = nearx2 / -bmt;
  1695. dst->z.y = (bottom + top) / bmt;
  1696. dst->z.z = zFar / fmn;
  1697. dst->t.z = (zNear * zFar) / -fmn;
  1698. dst->z.w = 1.0f;
  1699. }
  1700. void device_projection_push(gs_device_t *device)
  1701. {
  1702. mat4float mat;
  1703. memcpy(&mat, &device->curProjMatrix, sizeof(matrix4));
  1704. device->projStack.push_back(mat);
  1705. }
  1706. void device_projection_pop(gs_device_t *device)
  1707. {
  1708. if (device->projStack.empty())
  1709. return;
  1710. const mat4float &mat = device->projStack.back();
  1711. memcpy(&device->curProjMatrix, &mat, sizeof(matrix4));
  1712. device->projStack.pop_back();
  1713. }
  1714. void gs_swapchain_destroy(gs_swapchain_t *swapchain)
  1715. {
  1716. if (swapchain->device->curSwapChain == swapchain)
  1717. device_load_swapchain(swapchain->device, nullptr);
  1718. delete swapchain;
  1719. }
  1720. void gs_texture_destroy(gs_texture_t *tex)
  1721. {
  1722. delete tex;
  1723. }
  1724. uint32_t gs_texture_get_width(const gs_texture_t *tex)
  1725. {
  1726. if (tex->type != GS_TEXTURE_2D)
  1727. return 0;
  1728. return static_cast<const gs_texture_2d *>(tex)->width;
  1729. }
  1730. uint32_t gs_texture_get_height(const gs_texture_t *tex)
  1731. {
  1732. if (tex->type != GS_TEXTURE_2D)
  1733. return 0;
  1734. return static_cast<const gs_texture_2d *>(tex)->height;
  1735. }
  1736. enum gs_color_format gs_texture_get_color_format(const gs_texture_t *tex)
  1737. {
  1738. if (tex->type != GS_TEXTURE_2D)
  1739. return GS_UNKNOWN;
  1740. return static_cast<const gs_texture_2d *>(tex)->format;
  1741. }
  1742. bool gs_texture_map(gs_texture_t *tex, uint8_t **ptr, uint32_t *linesize)
  1743. {
  1744. HRESULT hr;
  1745. if (tex->type != GS_TEXTURE_2D)
  1746. return false;
  1747. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1748. D3D11_MAPPED_SUBRESOURCE map;
  1749. hr = tex2d->device->context->Map(tex2d->texture, 0,
  1750. D3D11_MAP_WRITE_DISCARD, 0, &map);
  1751. if (FAILED(hr))
  1752. return false;
  1753. *ptr = (uint8_t *)map.pData;
  1754. *linesize = map.RowPitch;
  1755. return true;
  1756. }
  1757. void gs_texture_unmap(gs_texture_t *tex)
  1758. {
  1759. if (tex->type != GS_TEXTURE_2D)
  1760. return;
  1761. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1762. tex2d->device->context->Unmap(tex2d->texture, 0);
  1763. }
  1764. void *gs_texture_get_obj(gs_texture_t *tex)
  1765. {
  1766. if (tex->type != GS_TEXTURE_2D)
  1767. return nullptr;
  1768. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1769. return tex2d->texture.Get();
  1770. }
  1771. void gs_cubetexture_destroy(gs_texture_t *cubetex)
  1772. {
  1773. delete cubetex;
  1774. }
  1775. uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex)
  1776. {
  1777. if (cubetex->type != GS_TEXTURE_CUBE)
  1778. return 0;
  1779. const gs_texture_2d *tex = static_cast<const gs_texture_2d *>(cubetex);
  1780. return tex->width;
  1781. }
  1782. enum gs_color_format
  1783. gs_cubetexture_get_color_format(const gs_texture_t *cubetex)
  1784. {
  1785. if (cubetex->type != GS_TEXTURE_CUBE)
  1786. return GS_UNKNOWN;
  1787. const gs_texture_2d *tex = static_cast<const gs_texture_2d *>(cubetex);
  1788. return tex->format;
  1789. }
  1790. void gs_voltexture_destroy(gs_texture_t *voltex)
  1791. {
  1792. delete voltex;
  1793. }
  1794. uint32_t gs_voltexture_get_width(const gs_texture_t *voltex)
  1795. {
  1796. /* TODO */
  1797. UNUSED_PARAMETER(voltex);
  1798. return 0;
  1799. }
  1800. uint32_t gs_voltexture_get_height(const gs_texture_t *voltex)
  1801. {
  1802. /* TODO */
  1803. UNUSED_PARAMETER(voltex);
  1804. return 0;
  1805. }
  1806. uint32_t gs_voltexture_get_depth(const gs_texture_t *voltex)
  1807. {
  1808. /* TODO */
  1809. UNUSED_PARAMETER(voltex);
  1810. return 0;
  1811. }
  1812. enum gs_color_format gs_voltexture_get_color_format(const gs_texture_t *voltex)
  1813. {
  1814. /* TODO */
  1815. UNUSED_PARAMETER(voltex);
  1816. return GS_UNKNOWN;
  1817. }
  1818. void gs_stagesurface_destroy(gs_stagesurf_t *stagesurf)
  1819. {
  1820. delete stagesurf;
  1821. }
  1822. uint32_t gs_stagesurface_get_width(const gs_stagesurf_t *stagesurf)
  1823. {
  1824. return stagesurf->width;
  1825. }
  1826. uint32_t gs_stagesurface_get_height(const gs_stagesurf_t *stagesurf)
  1827. {
  1828. return stagesurf->height;
  1829. }
  1830. enum gs_color_format
  1831. gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf)
  1832. {
  1833. return stagesurf->format;
  1834. }
  1835. bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data,
  1836. uint32_t *linesize)
  1837. {
  1838. D3D11_MAPPED_SUBRESOURCE map;
  1839. if (FAILED(stagesurf->device->context->Map(stagesurf->texture, 0,
  1840. D3D11_MAP_READ, 0, &map)))
  1841. return false;
  1842. *data = (uint8_t *)map.pData;
  1843. *linesize = map.RowPitch;
  1844. return true;
  1845. }
  1846. void gs_stagesurface_unmap(gs_stagesurf_t *stagesurf)
  1847. {
  1848. stagesurf->device->context->Unmap(stagesurf->texture, 0);
  1849. }
  1850. void gs_zstencil_destroy(gs_zstencil_t *zstencil)
  1851. {
  1852. delete zstencil;
  1853. }
  1854. void gs_samplerstate_destroy(gs_samplerstate_t *samplerstate)
  1855. {
  1856. if (!samplerstate)
  1857. return;
  1858. if (samplerstate->device)
  1859. for (int i = 0; i < GS_MAX_TEXTURES; i++)
  1860. if (samplerstate->device->curSamplers[i] ==
  1861. samplerstate)
  1862. samplerstate->device->curSamplers[i] = nullptr;
  1863. delete samplerstate;
  1864. }
  1865. void gs_vertexbuffer_destroy(gs_vertbuffer_t *vertbuffer)
  1866. {
  1867. if (vertbuffer && vertbuffer->device->lastVertexBuffer == vertbuffer)
  1868. vertbuffer->device->lastVertexBuffer = nullptr;
  1869. delete vertbuffer;
  1870. }
  1871. static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vertbuffer,
  1872. const gs_vb_data *data)
  1873. {
  1874. size_t num_tex = data->num_tex < vertbuffer->uvBuffers.size()
  1875. ? data->num_tex
  1876. : vertbuffer->uvBuffers.size();
  1877. if (!vertbuffer->dynamic) {
  1878. blog(LOG_ERROR, "gs_vertexbuffer_flush: vertex buffer is "
  1879. "not dynamic");
  1880. return;
  1881. }
  1882. if (data->points)
  1883. vertbuffer->FlushBuffer(vertbuffer->vertexBuffer, data->points,
  1884. sizeof(vec3));
  1885. if (vertbuffer->normalBuffer && data->normals)
  1886. vertbuffer->FlushBuffer(vertbuffer->normalBuffer, data->normals,
  1887. sizeof(vec3));
  1888. if (vertbuffer->tangentBuffer && data->tangents)
  1889. vertbuffer->FlushBuffer(vertbuffer->tangentBuffer,
  1890. data->tangents, sizeof(vec3));
  1891. if (vertbuffer->colorBuffer && data->colors)
  1892. vertbuffer->FlushBuffer(vertbuffer->colorBuffer, data->colors,
  1893. sizeof(uint32_t));
  1894. for (size_t i = 0; i < num_tex; i++) {
  1895. gs_tvertarray &tv = data->tvarray[i];
  1896. vertbuffer->FlushBuffer(vertbuffer->uvBuffers[i], tv.array,
  1897. tv.width * sizeof(float));
  1898. }
  1899. }
  1900. void gs_vertexbuffer_flush(gs_vertbuffer_t *vertbuffer)
  1901. {
  1902. gs_vertexbuffer_flush_internal(vertbuffer, vertbuffer->vbd.data);
  1903. }
  1904. void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vertbuffer,
  1905. const gs_vb_data *data)
  1906. {
  1907. gs_vertexbuffer_flush_internal(vertbuffer, data);
  1908. }
  1909. struct gs_vb_data *gs_vertexbuffer_get_data(const gs_vertbuffer_t *vertbuffer)
  1910. {
  1911. return vertbuffer->vbd.data;
  1912. }
  1913. void gs_indexbuffer_destroy(gs_indexbuffer_t *indexbuffer)
  1914. {
  1915. delete indexbuffer;
  1916. }
  1917. static inline void gs_indexbuffer_flush_internal(gs_indexbuffer_t *indexbuffer,
  1918. const void *data)
  1919. {
  1920. HRESULT hr;
  1921. if (!indexbuffer->dynamic)
  1922. return;
  1923. D3D11_MAPPED_SUBRESOURCE map;
  1924. hr = indexbuffer->device->context->Map(
  1925. indexbuffer->indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
  1926. if (FAILED(hr))
  1927. return;
  1928. memcpy(map.pData, data, indexbuffer->num * indexbuffer->indexSize);
  1929. indexbuffer->device->context->Unmap(indexbuffer->indexBuffer, 0);
  1930. }
  1931. void gs_indexbuffer_flush(gs_indexbuffer_t *indexbuffer)
  1932. {
  1933. gs_indexbuffer_flush_internal(indexbuffer, indexbuffer->indices.data);
  1934. }
  1935. void gs_indexbuffer_flush_direct(gs_indexbuffer_t *indexbuffer,
  1936. const void *data)
  1937. {
  1938. gs_indexbuffer_flush_internal(indexbuffer, data);
  1939. }
  1940. void *gs_indexbuffer_get_data(const gs_indexbuffer_t *indexbuffer)
  1941. {
  1942. return indexbuffer->indices.data;
  1943. }
  1944. size_t gs_indexbuffer_get_num_indices(const gs_indexbuffer_t *indexbuffer)
  1945. {
  1946. return indexbuffer->num;
  1947. }
  1948. enum gs_index_type gs_indexbuffer_get_type(const gs_indexbuffer_t *indexbuffer)
  1949. {
  1950. return indexbuffer->type;
  1951. }
  1952. void gs_timer_destroy(gs_timer_t *timer)
  1953. {
  1954. delete timer;
  1955. }
  1956. void gs_timer_begin(gs_timer_t *timer)
  1957. {
  1958. timer->device->context->End(timer->query_begin);
  1959. }
  1960. void gs_timer_end(gs_timer_t *timer)
  1961. {
  1962. timer->device->context->End(timer->query_end);
  1963. }
  1964. bool gs_timer_get_data(gs_timer_t *timer, uint64_t *ticks)
  1965. {
  1966. uint64_t begin, end;
  1967. HRESULT hr_begin, hr_end;
  1968. do {
  1969. hr_begin = timer->device->context->GetData(
  1970. timer->query_begin, &begin, sizeof(begin), 0);
  1971. } while (hr_begin == S_FALSE);
  1972. do {
  1973. hr_end = timer->device->context->GetData(timer->query_end, &end,
  1974. sizeof(end), 0);
  1975. } while (hr_end == S_FALSE);
  1976. const bool succeeded = SUCCEEDED(hr_begin) && SUCCEEDED(hr_end);
  1977. if (succeeded)
  1978. *ticks = end - begin;
  1979. return succeeded;
  1980. }
  1981. void gs_timer_range_destroy(gs_timer_range_t *range)
  1982. {
  1983. delete range;
  1984. }
  1985. void gs_timer_range_begin(gs_timer_range_t *range)
  1986. {
  1987. range->device->context->Begin(range->query_disjoint);
  1988. }
  1989. void gs_timer_range_end(gs_timer_range_t *range)
  1990. {
  1991. range->device->context->End(range->query_disjoint);
  1992. }
  1993. bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint,
  1994. uint64_t *frequency)
  1995. {
  1996. D3D11_QUERY_DATA_TIMESTAMP_DISJOINT timestamp_disjoint;
  1997. HRESULT hr;
  1998. do {
  1999. hr = range->device->context->GetData(range->query_disjoint,
  2000. &timestamp_disjoint,
  2001. sizeof(timestamp_disjoint),
  2002. 0);
  2003. } while (hr == S_FALSE);
  2004. const bool succeeded = SUCCEEDED(hr);
  2005. if (succeeded) {
  2006. *disjoint = timestamp_disjoint.Disjoint;
  2007. *frequency = timestamp_disjoint.Frequency;
  2008. }
  2009. return succeeded;
  2010. }
  2011. gs_timer::gs_timer(gs_device_t *device) : gs_obj(device, gs_type::gs_timer)
  2012. {
  2013. Rebuild(device->device);
  2014. }
  2015. gs_timer_range::gs_timer_range(gs_device_t *device)
  2016. : gs_obj(device, gs_type::gs_timer_range)
  2017. {
  2018. Rebuild(device->device);
  2019. }
  2020. extern "C" EXPORT bool device_gdi_texture_available(void)
  2021. {
  2022. return true;
  2023. }
  2024. extern "C" EXPORT bool device_shared_texture_available(void)
  2025. {
  2026. return true;
  2027. }
  2028. extern "C" EXPORT bool device_nv12_available(gs_device_t *device)
  2029. {
  2030. return device->nv12Supported;
  2031. }
  2032. extern "C" EXPORT void device_debug_marker_begin(gs_device_t *,
  2033. const char *markername,
  2034. const float color[4])
  2035. {
  2036. D3DCOLOR bgra = D3DCOLOR_ARGB((DWORD)(255.0f * color[3]),
  2037. (DWORD)(255.0f * color[0]),
  2038. (DWORD)(255.0f * color[1]),
  2039. (DWORD)(255.0f * color[2]));
  2040. wchar_t wide[64];
  2041. os_utf8_to_wcs(markername, 0, wide, _countof(wide));
  2042. D3DPERF_BeginEvent(bgra, wide);
  2043. }
  2044. extern "C" EXPORT void device_debug_marker_end(gs_device_t *)
  2045. {
  2046. D3DPERF_EndEvent();
  2047. }
  2048. extern "C" EXPORT gs_texture_t *
  2049. device_texture_create_gdi(gs_device_t *device, uint32_t width, uint32_t height)
  2050. {
  2051. gs_texture *texture = nullptr;
  2052. try {
  2053. texture = new gs_texture_2d(device, width, height, GS_BGRA, 1,
  2054. nullptr, GS_RENDER_TARGET,
  2055. GS_TEXTURE_2D, true);
  2056. } catch (const HRError &error) {
  2057. blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s (%08lX)",
  2058. error.str, error.hr);
  2059. LogD3D11ErrorDetails(error, device);
  2060. } catch (const char *error) {
  2061. blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s", error);
  2062. }
  2063. return texture;
  2064. }
  2065. static inline bool TextureGDICompatible(gs_texture_2d *tex2d, const char *func)
  2066. {
  2067. if (!tex2d->isGDICompatible) {
  2068. blog(LOG_ERROR, "%s (D3D11): Texture is not GDI compatible",
  2069. func);
  2070. return false;
  2071. }
  2072. return true;
  2073. }
  2074. extern "C" EXPORT void *gs_texture_get_dc(gs_texture_t *tex)
  2075. {
  2076. HDC hDC = nullptr;
  2077. if (tex->type != GS_TEXTURE_2D)
  2078. return nullptr;
  2079. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2080. if (!TextureGDICompatible(tex2d, "gs_texture_get_dc"))
  2081. return nullptr;
  2082. if (!tex2d->gdiSurface)
  2083. return nullptr;
  2084. tex2d->gdiSurface->GetDC(true, &hDC);
  2085. return hDC;
  2086. }
  2087. extern "C" EXPORT void gs_texture_release_dc(gs_texture_t *tex)
  2088. {
  2089. if (tex->type != GS_TEXTURE_2D)
  2090. return;
  2091. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2092. if (!TextureGDICompatible(tex2d, "gs_texture_release_dc"))
  2093. return;
  2094. tex2d->gdiSurface->ReleaseDC(nullptr);
  2095. }
  2096. extern "C" EXPORT gs_texture_t *device_texture_open_shared(gs_device_t *device,
  2097. uint32_t handle)
  2098. {
  2099. gs_texture *texture = nullptr;
  2100. try {
  2101. texture = new gs_texture_2d(device, handle);
  2102. } catch (const HRError &error) {
  2103. blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s (%08lX)",
  2104. error.str, error.hr);
  2105. LogD3D11ErrorDetails(error, device);
  2106. } catch (const char *error) {
  2107. blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s", error);
  2108. }
  2109. return texture;
  2110. }
  2111. extern "C" EXPORT uint32_t device_texture_get_shared_handle(gs_texture_t *tex)
  2112. {
  2113. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2114. if (tex->type != GS_TEXTURE_2D)
  2115. return GS_INVALID_HANDLE;
  2116. return tex2d->isShared ? tex2d->sharedHandle : GS_INVALID_HANDLE;
  2117. }
  2118. int device_texture_acquire_sync(gs_texture_t *tex, uint64_t key, uint32_t ms)
  2119. {
  2120. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2121. if (tex->type != GS_TEXTURE_2D)
  2122. return -1;
  2123. if (tex2d->acquired)
  2124. return 0;
  2125. ComQIPtr<IDXGIKeyedMutex> keyedMutex(tex2d->texture);
  2126. if (!keyedMutex)
  2127. return -1;
  2128. HRESULT hr = keyedMutex->AcquireSync(key, ms);
  2129. if (hr == S_OK) {
  2130. tex2d->acquired = true;
  2131. return 0;
  2132. } else if (hr == WAIT_TIMEOUT) {
  2133. return ETIMEDOUT;
  2134. }
  2135. return -1;
  2136. }
  2137. extern "C" EXPORT int device_texture_release_sync(gs_texture_t *tex,
  2138. uint64_t key)
  2139. {
  2140. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2141. if (tex->type != GS_TEXTURE_2D)
  2142. return -1;
  2143. if (!tex2d->acquired)
  2144. return 0;
  2145. ComQIPtr<IDXGIKeyedMutex> keyedMutex(tex2d->texture);
  2146. if (!keyedMutex)
  2147. return -1;
  2148. HRESULT hr = keyedMutex->ReleaseSync(key);
  2149. if (hr == S_OK) {
  2150. tex2d->acquired = false;
  2151. return 0;
  2152. }
  2153. return -1;
  2154. }
  2155. extern "C" EXPORT bool
  2156. device_texture_create_nv12(gs_device_t *device, gs_texture_t **p_tex_y,
  2157. gs_texture_t **p_tex_uv, uint32_t width,
  2158. uint32_t height, uint32_t flags)
  2159. {
  2160. if (!device->nv12Supported)
  2161. return false;
  2162. *p_tex_y = nullptr;
  2163. *p_tex_uv = nullptr;
  2164. gs_texture_2d *tex_y;
  2165. gs_texture_2d *tex_uv;
  2166. try {
  2167. tex_y = new gs_texture_2d(device, width, height, GS_R8, 1,
  2168. nullptr, flags, GS_TEXTURE_2D, false,
  2169. true);
  2170. tex_uv = new gs_texture_2d(device, tex_y->texture, flags);
  2171. } catch (const HRError &error) {
  2172. blog(LOG_ERROR, "gs_texture_create_nv12 (D3D11): %s (%08lX)",
  2173. error.str, error.hr);
  2174. LogD3D11ErrorDetails(error, device);
  2175. return false;
  2176. } catch (const char *error) {
  2177. blog(LOG_ERROR, "gs_texture_create_nv12 (D3D11): %s", error);
  2178. return false;
  2179. }
  2180. tex_y->pairedNV12texture = tex_uv;
  2181. tex_uv->pairedNV12texture = tex_y;
  2182. *p_tex_y = tex_y;
  2183. *p_tex_uv = tex_uv;
  2184. return true;
  2185. }
  2186. extern "C" EXPORT gs_stagesurf_t *
  2187. device_stagesurface_create_nv12(gs_device_t *device, uint32_t width,
  2188. uint32_t height)
  2189. {
  2190. gs_stage_surface *surf = NULL;
  2191. try {
  2192. surf = new gs_stage_surface(device, width, height);
  2193. } catch (const HRError &error) {
  2194. blog(LOG_ERROR,
  2195. "device_stagesurface_create (D3D11): %s "
  2196. "(%08lX)",
  2197. error.str, error.hr);
  2198. LogD3D11ErrorDetails(error, device);
  2199. }
  2200. return surf;
  2201. }