d3d11-subsystem.cpp 72 KB

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