gfxD3D11Device.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2015 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "console/console.h"
  23. #include "core/stream/fileStream.h"
  24. #include "core/strings/unicode.h"
  25. #include "core/util/journal/process.h"
  26. #include "gfx/D3D11/gfxD3D11Device.h"
  27. #include "gfx/D3D11/gfxD3D11CardProfiler.h"
  28. #include "gfx/D3D11/gfxD3D11VertexBuffer.h"
  29. #include "gfx/D3D11/gfxD3D11EnumTranslate.h"
  30. #include "gfx/D3D11/gfxD3D11QueryFence.h"
  31. #include "gfx/D3D11/gfxD3D11OcclusionQuery.h"
  32. #include "gfx/D3D11/gfxD3D11Shader.h"
  33. #include "gfx/D3D11/gfxD3D11Target.h"
  34. #include "platformWin32/platformWin32.h"
  35. #include "windowManager/win32/win32Window.h"
  36. #include "windowManager/platformWindow.h"
  37. #include "gfx/D3D11/screenshotD3D11.h"
  38. #include "materials/shaderData.h"
  39. #include "shaderGen/shaderGen.h"
  40. #include <d3d9.h> //d3dperf
  41. #ifdef TORQUE_DEBUG
  42. #include "d3d11sdklayers.h"
  43. #endif
  44. #pragma comment(lib, "dxgi.lib")
  45. #pragma comment(lib, "d3d9.lib") //d3dperf
  46. #pragma comment(lib, "d3d11.lib")
  47. class GFXPCD3D11RegisterDevice
  48. {
  49. public:
  50. GFXPCD3D11RegisterDevice()
  51. {
  52. GFXInit::getRegisterDeviceSignal().notify(&GFXD3D11Device::enumerateAdapters);
  53. }
  54. };
  55. static GFXPCD3D11RegisterDevice pPCD3D11RegisterDevice;
  56. //-----------------------------------------------------------------------------
  57. /// Parse command line arguments for window creation
  58. //-----------------------------------------------------------------------------
  59. static void sgPCD3D11DeviceHandleCommandLine(S32 argc, const char **argv)
  60. {
  61. // useful to pass parameters by command line for d3d (e.g. -dx9 -dx11)
  62. for (U32 i = 1; i < argc; i++)
  63. {
  64. argv[i];
  65. }
  66. }
  67. // Register the command line parsing hook
  68. static ProcessRegisterCommandLine sgCommandLine(sgPCD3D11DeviceHandleCommandLine);
  69. GFXAdapter::CreateDeviceInstanceDelegate GFXD3D11Device::mCreateDeviceInstance(GFXD3D11Device::createInstance);
  70. GFXDevice *GFXD3D11Device::createInstance(U32 adapterIndex)
  71. {
  72. GFXD3D11Device* dev = new GFXD3D11Device(adapterIndex);
  73. return dev;
  74. }
  75. GFXD3D11Device::GFXD3D11Device(U32 index)
  76. {
  77. mDeviceSwizzle32 = &Swizzles::bgra;
  78. GFXVertexColor::setSwizzle(mDeviceSwizzle32);
  79. mDeviceSwizzle24 = &Swizzles::bgr;
  80. mAdapterIndex = index;
  81. mSwapChain = NULL;
  82. mD3DDevice = NULL;
  83. mD3DDeviceContext = NULL;
  84. mVolatileVB = NULL;
  85. mCurrentPB = NULL;
  86. mDynamicPB = NULL;
  87. mLastVertShader = NULL;
  88. mLastPixShader = NULL;
  89. mCanCurrentlyRender = false;
  90. mTextureManager = NULL;
  91. mCurrentStateBlock = NULL;
  92. mResourceListHead = NULL;
  93. mPixVersion = 0.0;
  94. mFeatureLevel = D3D_FEATURE_LEVEL_9_1; //lowest listed. should be overridden by init
  95. mVertexShaderTarget = String::EmptyString;
  96. mPixelShaderTarget = String::EmptyString;
  97. mShaderModel = String::EmptyString;
  98. mDrawInstancesCount = 0;
  99. mCardProfiler = NULL;
  100. mDeviceDepthStencil = NULL;
  101. mDeviceBackbuffer = NULL;
  102. mDeviceBackBufferView = NULL;
  103. mDeviceDepthStencilView = NULL;
  104. mCreateFenceType = -1; // Unknown, test on first allocate
  105. mCurrentConstBuffer = NULL;
  106. mMultisampleDesc.Count = 0;
  107. mMultisampleDesc.Quality = 0;
  108. mOcclusionQuerySupported = false;
  109. mDebugLayers = false;
  110. for (U32 i = 0; i < GS_COUNT; ++i)
  111. mModelViewProjSC[i] = NULL;
  112. // Set up the Enum translation tables
  113. GFXD3D11EnumTranslate::init();
  114. }
  115. GFXD3D11Device::~GFXD3D11Device()
  116. {
  117. // Release our refcount on the current stateblock object
  118. mCurrentStateBlock = NULL;
  119. releaseDefaultPoolResources();
  120. mD3DDeviceContext->ClearState();
  121. mD3DDeviceContext->Flush();
  122. // Free the sampler states
  123. SamplerMap::Iterator sampIter = mSamplersMap.begin();
  124. for (; sampIter != mSamplersMap.end(); ++sampIter)
  125. SAFE_RELEASE(sampIter->value);
  126. // Free the vertex declarations.
  127. VertexDeclMap::Iterator iter = mVertexDecls.begin();
  128. for (; iter != mVertexDecls.end(); ++iter)
  129. delete iter->value;
  130. // Forcibly clean up the pools
  131. mVolatileVBList.setSize(0);
  132. mDynamicPB = NULL;
  133. // And release our D3D resources.
  134. SAFE_RELEASE(mDeviceDepthStencilView);
  135. SAFE_RELEASE(mDeviceBackBufferView);
  136. SAFE_RELEASE(mDeviceDepthStencil);
  137. SAFE_RELEASE(mDeviceBackbuffer);
  138. SAFE_RELEASE(mD3DDeviceContext);
  139. SAFE_DELETE(mCardProfiler);
  140. SAFE_DELETE(gScreenShot);
  141. #ifdef TORQUE_DEBUG
  142. if (mDebugLayers)
  143. {
  144. ID3D11Debug *pDebug = NULL;
  145. mD3DDevice->QueryInterface(IID_PPV_ARGS(&pDebug));
  146. AssertFatal(pDebug, "~GFXD3D11Device- Failed to get debug layer");
  147. pDebug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
  148. SAFE_RELEASE(pDebug);
  149. }
  150. #endif
  151. SAFE_RELEASE(mSwapChain);
  152. SAFE_RELEASE(mD3DDevice);
  153. }
  154. GFXFormat GFXD3D11Device::selectSupportedFormat(GFXTextureProfile *profile, const Vector<GFXFormat> &formats, bool texture, bool mustblend, bool mustfilter)
  155. {
  156. U32 features = 0;
  157. if(texture)
  158. features |= D3D11_FORMAT_SUPPORT_TEXTURE2D;
  159. if(mustblend)
  160. features |= D3D11_FORMAT_SUPPORT_BLENDABLE;
  161. if(mustfilter)
  162. features |= D3D11_FORMAT_SUPPORT_SHADER_SAMPLE;
  163. for(U32 i = 0; i < formats.size(); i++)
  164. {
  165. if(GFXD3D11TextureFormat[formats[i]] == DXGI_FORMAT_UNKNOWN)
  166. continue;
  167. U32 supportFlag = 0;
  168. mD3DDevice->CheckFormatSupport(GFXD3D11TextureFormat[formats[i]],&supportFlag);
  169. if(supportFlag & features)
  170. return formats[i];
  171. }
  172. return GFXFormatR8G8B8A8;
  173. }
  174. DXGI_SWAP_CHAIN_DESC GFXD3D11Device::setupPresentParams(const GFXVideoMode &mode, const HWND &hwnd)
  175. {
  176. DXGI_SWAP_CHAIN_DESC d3dpp;
  177. ZeroMemory(&d3dpp, sizeof(d3dpp));
  178. DXGI_SAMPLE_DESC sampleDesc;
  179. sampleDesc.Count = 1;
  180. sampleDesc.Quality = 0;
  181. mMultisampleDesc = sampleDesc;
  182. d3dpp.BufferCount = !smDisableVSync ? 2 : 1; // triple buffering when vsync is on.
  183. d3dpp.BufferDesc.Width = mode.resolution.x;
  184. d3dpp.BufferDesc.Height = mode.resolution.y;
  185. d3dpp.BufferDesc.Format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
  186. d3dpp.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  187. d3dpp.OutputWindow = hwnd;
  188. d3dpp.SampleDesc = sampleDesc;
  189. d3dpp.Windowed = !mode.fullScreen;
  190. d3dpp.BufferDesc.RefreshRate.Numerator = mode.refreshRate;
  191. d3dpp.BufferDesc.RefreshRate.Denominator = 1;
  192. d3dpp.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  193. if (mode.fullScreen)
  194. {
  195. d3dpp.BufferDesc.Scaling = DXGI_MODE_SCALING_CENTERED;
  196. d3dpp.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  197. d3dpp.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
  198. }
  199. return d3dpp;
  200. }
  201. void GFXD3D11Device::enumerateAdapters(Vector<GFXAdapter*> &adapterList)
  202. {
  203. IDXGIAdapter1* EnumAdapter;
  204. IDXGIFactory1* DXGIFactory;
  205. CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&DXGIFactory));
  206. for(U32 adapterIndex = 0; DXGIFactory->EnumAdapters1(adapterIndex, &EnumAdapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex)
  207. {
  208. GFXAdapter *toAdd = new GFXAdapter;
  209. toAdd->mType = Direct3D11;
  210. toAdd->mIndex = adapterIndex;
  211. toAdd->mCreateDeviceInstanceDelegate = mCreateDeviceInstance;
  212. toAdd->mShaderModel = 5.0f;
  213. DXGI_ADAPTER_DESC1 desc;
  214. EnumAdapter->GetDesc1(&desc);
  215. // LUID identifies adapter for oculus rift
  216. dMemcpy(&toAdd->mLUID, &desc.AdapterLuid, sizeof(toAdd->mLUID));
  217. size_t size=wcslen(desc.Description);
  218. char *str = new char[size+1];
  219. wcstombs(str, desc.Description,size);
  220. str[size]='\0';
  221. String Description=str;
  222. SAFE_DELETE_ARRAY(str);
  223. dStrncpy(toAdd->mName, Description.c_str(), GFXAdapter::MaxAdapterNameLen);
  224. dStrncat(toAdd->mName, " (D3D11)", GFXAdapter::MaxAdapterNameLen);
  225. IDXGIOutput* pOutput = NULL;
  226. HRESULT hr;
  227. hr = EnumAdapter->EnumOutputs(adapterIndex, &pOutput);
  228. if(hr == DXGI_ERROR_NOT_FOUND)
  229. {
  230. SAFE_RELEASE(EnumAdapter);
  231. break;
  232. }
  233. if(FAILED(hr))
  234. AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> EnumOutputs call failure");
  235. UINT numModes = 0;
  236. DXGI_MODE_DESC* displayModes = NULL;
  237. DXGI_FORMAT format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
  238. // Get the number of elements
  239. hr = pOutput->GetDisplayModeList(format, 0, &numModes, NULL);
  240. if(FAILED(hr))
  241. AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> GetDisplayModeList call failure");
  242. displayModes = new DXGI_MODE_DESC[numModes];
  243. // Get the list
  244. hr = pOutput->GetDisplayModeList(format, 0, &numModes, displayModes);
  245. if(FAILED(hr))
  246. AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> GetDisplayModeList call failure");
  247. for(U32 numMode = 0; numMode < numModes; ++numMode)
  248. {
  249. GFXVideoMode vmAdd;
  250. vmAdd.fullScreen = true;
  251. vmAdd.bitDepth = 32;
  252. vmAdd.refreshRate = displayModes[numMode].RefreshRate.Numerator / displayModes[numMode].RefreshRate.Denominator;
  253. vmAdd.resolution.x = displayModes[numMode].Width;
  254. vmAdd.resolution.y = displayModes[numMode].Height;
  255. toAdd->mAvailableModes.push_back(vmAdd);
  256. }
  257. //Check adapater can handle feature level 10_!
  258. D3D_FEATURE_LEVEL deviceFeature;
  259. ID3D11Device *pTmpDevice = nullptr;
  260. // Create temp Direct3D11 device.
  261. bool suitable = true;
  262. UINT createDeviceFlags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  263. hr = D3D11CreateDevice(EnumAdapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, createDeviceFlags, NULL, 0, D3D11_SDK_VERSION, &pTmpDevice, &deviceFeature, NULL);
  264. if (FAILED(hr))
  265. suitable = false;
  266. if (deviceFeature < D3D_FEATURE_LEVEL_10_1)
  267. suitable = false;
  268. //double check we support required bgra format for LEVEL_10_1
  269. if (deviceFeature == D3D_FEATURE_LEVEL_10_1)
  270. {
  271. U32 formatSupported = 0;
  272. pTmpDevice->CheckFormatSupport(DXGI_FORMAT_B8G8R8A8_UNORM, &formatSupported);
  273. U32 flagsRequired = D3D11_FORMAT_SUPPORT_RENDER_TARGET | D3D11_FORMAT_SUPPORT_DISPLAY;
  274. if (!(formatSupported && flagsRequired))
  275. {
  276. Con::printf("DXGI adapter: %s does not support BGRA", Description.c_str());
  277. suitable = false;
  278. }
  279. }
  280. delete[] displayModes;
  281. SAFE_RELEASE(pTmpDevice);
  282. SAFE_RELEASE(pOutput);
  283. SAFE_RELEASE(EnumAdapter);
  284. if (suitable)
  285. {
  286. adapterList.push_back(toAdd);
  287. }
  288. else
  289. {
  290. Con::printf("DXGI adapter: %s does not support D3D11 feature level 10 or better", Description.c_str());
  291. delete toAdd;
  292. }
  293. }
  294. SAFE_RELEASE(DXGIFactory);
  295. }
  296. void GFXD3D11Device::enumerateVideoModes()
  297. {
  298. mVideoModes.clear();
  299. IDXGIAdapter1* EnumAdapter;
  300. IDXGIFactory1* DXGIFactory;
  301. HRESULT hr;
  302. hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&DXGIFactory));
  303. if (FAILED(hr))
  304. AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> CreateDXGIFactory1 call failure");
  305. for(U32 adapterIndex = 0; DXGIFactory->EnumAdapters1(adapterIndex, &EnumAdapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex)
  306. {
  307. IDXGIOutput* pOutput = NULL;
  308. hr = EnumAdapter->EnumOutputs(adapterIndex, &pOutput);
  309. if(hr == DXGI_ERROR_NOT_FOUND)
  310. {
  311. SAFE_RELEASE(EnumAdapter);
  312. break;
  313. }
  314. if(FAILED(hr))
  315. AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> EnumOutputs call failure");
  316. UINT numModes = 0;
  317. DXGI_MODE_DESC* displayModes = NULL;
  318. DXGI_FORMAT format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
  319. // Get the number of elements
  320. hr = pOutput->GetDisplayModeList(format, 0, &numModes, NULL);
  321. if(FAILED(hr))
  322. AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> GetDisplayModeList call failure");
  323. displayModes = new DXGI_MODE_DESC[numModes];
  324. // Get the list
  325. hr = pOutput->GetDisplayModeList(format, 0, &numModes, displayModes);
  326. if(FAILED(hr))
  327. AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> GetDisplayModeList call failure");
  328. for(U32 numMode = 0; numMode < numModes; ++numMode)
  329. {
  330. GFXVideoMode toAdd;
  331. toAdd.fullScreen = false;
  332. toAdd.bitDepth = 32;
  333. toAdd.refreshRate = displayModes[numMode].RefreshRate.Numerator / displayModes[numMode].RefreshRate.Denominator;
  334. toAdd.resolution.x = displayModes[numMode].Width;
  335. toAdd.resolution.y = displayModes[numMode].Height;
  336. mVideoModes.push_back(toAdd);
  337. }
  338. delete[] displayModes;
  339. SAFE_RELEASE(pOutput);
  340. SAFE_RELEASE(EnumAdapter);
  341. }
  342. SAFE_RELEASE(DXGIFactory);
  343. }
  344. void GFXD3D11Device::init(const GFXVideoMode &mode, PlatformWindow *window)
  345. {
  346. AssertFatal(window, "GFXD3D11Device::init - must specify a window!");
  347. //HWND winHwnd = (HWND)window->getSystemWindow( PlatformWindow::WindowSystem_Windows );
  348. //SetFocus(winHwnd);
  349. UINT createDeviceFlags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  350. #ifdef TORQUE_DEBUG
  351. createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
  352. mDebugLayers = true;
  353. #endif
  354. // TODO support at least feature level 10 to match GL
  355. D3D_FEATURE_LEVEL pFeatureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1 };
  356. U32 nFeatureCount = ARRAYSIZE(pFeatureLevels);
  357. D3D_DRIVER_TYPE driverType = D3D_DRIVER_TYPE_HARDWARE;// use D3D_DRIVER_TYPE_REFERENCE for reference device
  358. // create a device, device context and swap chain using the information in the d3dpp struct
  359. HRESULT hres = D3D11CreateDevice(NULL,
  360. driverType,
  361. NULL,
  362. createDeviceFlags,
  363. pFeatureLevels,
  364. nFeatureCount,
  365. D3D11_SDK_VERSION,
  366. &mD3DDevice,
  367. &mFeatureLevel,
  368. &mD3DDeviceContext);
  369. if(FAILED(hres))
  370. {
  371. #ifdef TORQUE_DEBUG
  372. //try again without debug device layer enabled
  373. createDeviceFlags &= ~D3D11_CREATE_DEVICE_DEBUG;
  374. hres = D3D11CreateDevice(NULL,
  375. driverType,
  376. NULL,
  377. createDeviceFlags,
  378. pFeatureLevels,
  379. nFeatureCount,
  380. D3D11_SDK_VERSION,
  381. &mD3DDevice,
  382. &mFeatureLevel,
  383. &mD3DDeviceContext);
  384. //if we failed again than we definitely have a problem
  385. if (FAILED(hres))
  386. AssertFatal(false, "GFXD3D11Device::init - D3D11CreateDeviceAndSwapChain failed!");
  387. Con::warnf("GFXD3D11Device::init - Debug layers not detected!");
  388. mDebugLayers = false;
  389. #else
  390. AssertFatal(false, "GFXD3D11Device::init - D3D11CreateDeviceAndSwapChain failed!");
  391. #endif
  392. }
  393. //set the fullscreen state here if we need to
  394. if(mode.fullScreen)
  395. {
  396. hres = mSwapChain->SetFullscreenState(TRUE, NULL);
  397. if(FAILED(hres))
  398. {
  399. AssertFatal(false, "GFXD3D11Device::init- Failed to set fullscreen state!");
  400. }
  401. }
  402. #ifdef TORQUE_DEBUG
  403. _suppressDebugMessages();
  404. #endif
  405. mTextureManager = new GFXD3D11TextureManager();
  406. // Now reacquire all the resources we trashed earlier
  407. reacquireDefaultPoolResources();
  408. //set vert/pixel shader targets
  409. switch (mFeatureLevel)
  410. {
  411. case D3D_FEATURE_LEVEL_11_1:
  412. case D3D_FEATURE_LEVEL_11_0:
  413. mVertexShaderTarget = "vs_5_0";
  414. mPixelShaderTarget = "ps_5_0";
  415. mPixVersion = 5.0f;
  416. mShaderModel = "50";
  417. break;
  418. case D3D_FEATURE_LEVEL_10_1:
  419. mVertexShaderTarget = "vs_4_1";
  420. mPixelShaderTarget = "ps_4_1";
  421. mPixVersion = 4.1f;
  422. mShaderModel = "41";
  423. break;
  424. default:
  425. AssertFatal(false, "GFXD3D11Device::init - We don't support this feature level");
  426. }
  427. D3D11_QUERY_DESC queryDesc;
  428. queryDesc.Query = D3D11_QUERY_OCCLUSION;
  429. queryDesc.MiscFlags = 0;
  430. ID3D11Query *testQuery = NULL;
  431. // detect occlusion query support
  432. if (SUCCEEDED(mD3DDevice->CreateQuery(&queryDesc, &testQuery))) mOcclusionQuerySupported = true;
  433. SAFE_RELEASE(testQuery);
  434. Con::printf("Hardware occlusion query detected: %s", mOcclusionQuerySupported ? "Yes" : "No");
  435. mCardProfiler = new GFXD3D11CardProfiler();
  436. mCardProfiler->init();
  437. gScreenShot = new ScreenShotD3D11;
  438. mInitialized = true;
  439. deviceInited();
  440. }
  441. // Supress any debug layer messages we don't want to see
  442. void GFXD3D11Device::_suppressDebugMessages()
  443. {
  444. if (mDebugLayers)
  445. {
  446. ID3D11Debug *pDebug = NULL;
  447. if (SUCCEEDED(mD3DDevice->QueryInterface(__uuidof(ID3D11Debug), (void**)&pDebug)))
  448. {
  449. ID3D11InfoQueue *pInfoQueue = NULL;
  450. if (SUCCEEDED(pDebug->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)&pInfoQueue)))
  451. {
  452. //Disable breaking on error or corruption, this can be handy when using VS graphics debugging
  453. pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, false);
  454. pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, false);
  455. D3D11_MESSAGE_ID hide[] =
  456. {
  457. //this is harmless and no need to spam the console
  458. D3D11_MESSAGE_ID_QUERY_BEGIN_ABANDONING_PREVIOUS_RESULTS
  459. };
  460. D3D11_INFO_QUEUE_FILTER filter;
  461. memset(&filter, 0, sizeof(filter));
  462. filter.DenyList.NumIDs = _countof(hide);
  463. filter.DenyList.pIDList = hide;
  464. pInfoQueue->AddStorageFilterEntries(&filter);
  465. SAFE_RELEASE(pInfoQueue);
  466. }
  467. SAFE_RELEASE(pDebug);
  468. }
  469. }
  470. }
  471. bool GFXD3D11Device::beginSceneInternal()
  472. {
  473. mCanCurrentlyRender = true;
  474. return mCanCurrentlyRender;
  475. }
  476. GFXWindowTarget * GFXD3D11Device::allocWindowTarget(PlatformWindow *window)
  477. {
  478. AssertFatal(window,"GFXD3D11Device::allocWindowTarget - no window provided!");
  479. // Set up a new window target...
  480. GFXD3D11WindowTarget *gdwt = new GFXD3D11WindowTarget();
  481. gdwt->mWindow = window;
  482. gdwt->mSize = window->getClientExtent();
  483. gdwt->initPresentationParams();
  484. if (!mInitialized)
  485. {
  486. gdwt->mSecondaryWindow = false;
  487. // Allocate the device.
  488. init(window->getVideoMode(), window);
  489. gdwt->initPresentationParams();
  490. gdwt->createSwapChain();
  491. gdwt->createBuffersAndViews();
  492. mSwapChain = gdwt->getSwapChain();
  493. mDeviceBackbuffer = gdwt->getBackBuffer();
  494. mDeviceDepthStencil = gdwt->getDepthStencil();
  495. mDeviceBackBufferView = gdwt->getBackBufferView();
  496. mDeviceDepthStencilView = gdwt->getDepthStencilView();
  497. }
  498. else //additional window/s
  499. {
  500. gdwt->mSecondaryWindow = true;
  501. gdwt->initPresentationParams();
  502. gdwt->createSwapChain();
  503. gdwt->createBuffersAndViews();
  504. }
  505. return gdwt;
  506. }
  507. GFXTextureTarget* GFXD3D11Device::allocRenderToTextureTarget(bool genMips)
  508. {
  509. GFXD3D11TextureTarget *targ = new GFXD3D11TextureTarget(genMips);
  510. targ->registerResourceWithDevice(this);
  511. return targ;
  512. }
  513. void GFXD3D11Device::beginReset()
  514. {
  515. if (!mD3DDevice)
  516. return;
  517. mInitialized = false;
  518. releaseDefaultPoolResources();
  519. // Clean up some commonly dangling state. This helps prevents issues with
  520. // items that are destroyed by the texture manager callbacks and recreated
  521. // later, but still left bound.
  522. setVertexBuffer(NULL);
  523. setPrimitiveBuffer(NULL);
  524. for (S32 i = 0; i<getNumSamplers(); i++)
  525. setTexture(i, NULL);
  526. mD3DDeviceContext->ClearState();
  527. //release old buffers and views
  528. SAFE_RELEASE(mDeviceDepthStencilView);
  529. SAFE_RELEASE(mDeviceBackBufferView);
  530. SAFE_RELEASE(mDeviceDepthStencil);
  531. SAFE_RELEASE(mDeviceBackbuffer);
  532. }
  533. void GFXD3D11Device::endReset(GFXD3D11WindowTarget* windowTarget)
  534. {
  535. //grab new references
  536. mDeviceBackbuffer = windowTarget->getBackBuffer();
  537. mDeviceDepthStencil = windowTarget->getDepthStencil();
  538. mDeviceBackBufferView = windowTarget->getBackBufferView();
  539. mDeviceDepthStencilView = windowTarget->getDepthStencilView();
  540. mD3DDeviceContext->OMSetRenderTargets(1, &mDeviceBackBufferView, mDeviceDepthStencilView);
  541. // Now reacquire all the resources we trashed earlier
  542. reacquireDefaultPoolResources();
  543. mD3DDeviceContext->PSSetShader(mLastPixShader, NULL, 0);
  544. mD3DDeviceContext->VSSetShader(mLastVertShader, NULL, 0);
  545. mInitialized = true;
  546. // Mark everything dirty and flush to card, for sanity.
  547. updateStates(true);
  548. }
  549. void GFXD3D11Device::setupGenericShaders(GenericShaderType type)
  550. {
  551. AssertFatal(type != GSTargetRestore, ""); //not used
  552. if(mGenericShader[GSColor] == NULL)
  553. {
  554. ShaderData *shaderData;
  555. //shader model 4.0 is enough for the generic shaders
  556. const char* shaderModel = "4.0";
  557. shaderData = new ShaderData();
  558. shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/colorV.hlsl"));
  559. shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/colorP.hlsl"));
  560. shaderData->setField("pixVersion", shaderModel);
  561. shaderData->registerObject();
  562. mGenericShader[GSColor] = shaderData->getShader();
  563. mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
  564. mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle("$modelView");
  565. Sim::getRootGroup()->addObject(shaderData);
  566. shaderData = new ShaderData();
  567. shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/modColorTextureV.hlsl"));
  568. shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/modColorTextureP.hlsl"));
  569. shaderData->setField("pixVersion", shaderModel);
  570. shaderData->registerObject();
  571. mGenericShader[GSModColorTexture] = shaderData->getShader();
  572. mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
  573. mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle("$modelView");
  574. Sim::getRootGroup()->addObject(shaderData);
  575. shaderData = new ShaderData();
  576. shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/addColorTextureV.hlsl"));
  577. shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/addColorTextureP.hlsl"));
  578. shaderData->setField("pixVersion", shaderModel);
  579. shaderData->registerObject();
  580. mGenericShader[GSAddColorTexture] = shaderData->getShader();
  581. mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
  582. mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle("$modelView");
  583. Sim::getRootGroup()->addObject(shaderData);
  584. shaderData = new ShaderData();
  585. shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/textureV.hlsl"));
  586. shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/textureP.hlsl"));
  587. shaderData->setField("pixVersion", shaderModel);
  588. shaderData->registerObject();
  589. mGenericShader[GSTexture] = shaderData->getShader();
  590. mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
  591. mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle("$modelView");
  592. Sim::getRootGroup()->addObject(shaderData);
  593. //Force an update
  594. mViewportDirty = true;
  595. _updateRenderTargets();
  596. }
  597. MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
  598. mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
  599. setShader(mGenericShader[type]);
  600. setShaderConstBuffer(mGenericShaderBuffer[type]);
  601. }
  602. //-----------------------------------------------------------------------------
  603. /// Creates a state block object based on the desc passed in. This object
  604. /// represents an immutable state.
  605. GFXStateBlockRef GFXD3D11Device::createStateBlockInternal(const GFXStateBlockDesc& desc)
  606. {
  607. return GFXStateBlockRef(new GFXD3D11StateBlock(desc));
  608. }
  609. /// Activates a stateblock
  610. void GFXD3D11Device::setStateBlockInternal(GFXStateBlock* block, bool force)
  611. {
  612. AssertFatal(static_cast<GFXD3D11StateBlock*>(block), "Incorrect stateblock type for this device!");
  613. GFXD3D11StateBlock* d3dBlock = static_cast<GFXD3D11StateBlock*>(block);
  614. GFXD3D11StateBlock* d3dCurrent = static_cast<GFXD3D11StateBlock*>(mCurrentStateBlock.getPointer());
  615. if (force)
  616. d3dCurrent = NULL;
  617. d3dBlock->activate(d3dCurrent);
  618. }
  619. /// Called by base GFXDevice to actually set a const buffer
  620. void GFXD3D11Device::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
  621. {
  622. if (buffer)
  623. {
  624. PROFILE_SCOPE(GFXD3D11Device_setShaderConstBufferInternal);
  625. AssertFatal(static_cast<GFXD3D11ShaderConstBuffer*>(buffer), "Incorrect shader const buffer type for this device!");
  626. GFXD3D11ShaderConstBuffer* d3dBuffer = static_cast<GFXD3D11ShaderConstBuffer*>(buffer);
  627. d3dBuffer->activate(mCurrentConstBuffer);
  628. mCurrentConstBuffer = d3dBuffer;
  629. }
  630. else
  631. {
  632. mCurrentConstBuffer = NULL;
  633. }
  634. }
  635. //-----------------------------------------------------------------------------
  636. void GFXD3D11Device::copyResource(GFXTextureObject *pDst, GFXCubemap *pSrc, const U32 face)
  637. {
  638. AssertFatal(pDst, "GFXD3D11Device::copyResource: Destination texture is null");
  639. AssertFatal(pSrc, "GFXD3D11Device::copyResource: Source cubemap is null");
  640. GFXD3D11TextureObject *pD3DDst = static_cast<GFXD3D11TextureObject*>(pDst);
  641. GFXD3D11Cubemap *pD3DSrc = static_cast<GFXD3D11Cubemap*>(pSrc);
  642. const U32 mipLevels = pD3DSrc->getMipMapLevels();
  643. for (U32 mip = 0; mip < mipLevels; mip++)
  644. {
  645. const U32 srcSubResource = D3D11CalcSubresource(mip, face, mipLevels);
  646. const U32 dstSubResource = D3D11CalcSubresource(mip, 0, mipLevels);
  647. mD3DDeviceContext->CopySubresourceRegion(pD3DDst->get2DTex(), dstSubResource, 0, 0, 0, pD3DSrc->get2DTex(), srcSubResource, NULL);
  648. }
  649. }
  650. //-----------------------------------------------------------------------------
  651. void GFXD3D11Device::clear(U32 flags, const LinearColorF& color, F32 z, U32 stencil)
  652. {
  653. // Make sure we have flushed our render target state.
  654. _updateRenderTargets();
  655. UINT depthstencilFlag = 0;
  656. //TODO: current support is 5 render targets, clean this up
  657. ID3D11RenderTargetView* rtView[5] = { NULL };
  658. ID3D11DepthStencilView* dsView = NULL;
  659. mD3DDeviceContext->OMGetRenderTargets(5, rtView, &dsView);
  660. const FLOAT clearColor[4] = { color.red, color.green, color.blue, color.alpha };
  661. if (flags & GFXClearTarget && rtView)
  662. {
  663. for (U32 i = 0; i < 5; i++)
  664. {
  665. if (rtView[i])
  666. mD3DDeviceContext->ClearRenderTargetView(rtView[i], clearColor);
  667. }
  668. }
  669. if (flags & GFXClearZBuffer)
  670. depthstencilFlag |= D3D11_CLEAR_DEPTH;
  671. if (flags & GFXClearStencil)
  672. depthstencilFlag |= D3D11_CLEAR_STENCIL;
  673. if (depthstencilFlag && dsView)
  674. mD3DDeviceContext->ClearDepthStencilView(dsView, depthstencilFlag, z, stencil);
  675. for (U32 i = 0; i < 5; i++)
  676. SAFE_RELEASE(rtView[i]);
  677. SAFE_RELEASE(dsView);
  678. }
  679. void GFXD3D11Device::clearColorAttachment(const U32 attachment, const LinearColorF& color)
  680. {
  681. GFXD3D11TextureTarget *pTarget = static_cast<GFXD3D11TextureTarget*>(mCurrentRT.getPointer());
  682. ID3D11RenderTargetView* rtView = NULL;
  683. if (!pTarget)
  684. {
  685. rtView = mDeviceBackBufferView;// we are using the default backbuffer
  686. }
  687. else
  688. {
  689. //attachment + 1 to skip past DepthStencil which is first in the list
  690. rtView = static_cast<ID3D11RenderTargetView*>(pTarget->mTargetViews[attachment + 1]);
  691. }
  692. const FLOAT clearColor[4] = { color.red, color.green, color.blue, color.alpha };
  693. mD3DDeviceContext->ClearRenderTargetView(rtView, clearColor);
  694. }
  695. void GFXD3D11Device::endSceneInternal()
  696. {
  697. mCanCurrentlyRender = false;
  698. }
  699. void GFXD3D11Device::_updateRenderTargets()
  700. {
  701. if (mRTDirty || (mCurrentRT && mCurrentRT->isPendingState()))
  702. {
  703. if (mRTDeactivate)
  704. {
  705. mRTDeactivate->deactivate();
  706. mRTDeactivate = NULL;
  707. }
  708. // NOTE: The render target changes are not really accurate
  709. // as the GFXTextureTarget supports MRT internally. So when
  710. // we activate a GFXTarget it could result in multiple calls
  711. // to SetRenderTarget on the actual device.
  712. mDeviceStatistics.mRenderTargetChanges++;
  713. mCurrentRT->activate();
  714. mRTDirty = false;
  715. }
  716. if (mViewportDirty)
  717. {
  718. D3D11_VIEWPORT viewport;
  719. viewport.TopLeftX = mViewport.point.x;
  720. viewport.TopLeftY = mViewport.point.y;
  721. viewport.Width = mViewport.extent.x;
  722. viewport.Height = mViewport.extent.y;
  723. viewport.MinDepth = 0.0f;
  724. viewport.MaxDepth = 1.0f;
  725. mD3DDeviceContext->RSSetViewports(1, &viewport);
  726. mViewportDirty = false;
  727. }
  728. }
  729. void GFXD3D11Device::releaseDefaultPoolResources()
  730. {
  731. // Release all the dynamic vertex buffer arrays
  732. // Forcibly clean up the pools
  733. for(U32 i=0; i<mVolatileVBList.size(); i++)
  734. {
  735. SAFE_RELEASE(mVolatileVBList[i]->vb);
  736. mVolatileVBList[i] = NULL;
  737. }
  738. mVolatileVBList.setSize(0);
  739. // We gotta clear the current const buffer else the next
  740. // activate may erroneously think the device is still holding
  741. // this state and fail to set it.
  742. mCurrentConstBuffer = NULL;
  743. // Set current VB to NULL and set state dirty
  744. for (U32 i=0; i < VERTEX_STREAM_COUNT; i++)
  745. {
  746. mCurrentVertexBuffer[i] = NULL;
  747. mVertexBufferDirty[i] = true;
  748. mVertexBufferFrequency[i] = 0;
  749. mVertexBufferFrequencyDirty[i] = true;
  750. }
  751. // Release dynamic index buffer
  752. if(mDynamicPB != NULL)
  753. {
  754. SAFE_RELEASE(mDynamicPB->ib);
  755. }
  756. // Set current PB/IB to NULL and set state dirty
  757. mCurrentPrimitiveBuffer = NULL;
  758. mCurrentPB = NULL;
  759. mPrimitiveBufferDirty = true;
  760. // Zombify texture manager (for D3D this only modifies default pool textures)
  761. if( mTextureManager )
  762. mTextureManager->zombify();
  763. // Set global dirty state so the IB/PB and VB get reset
  764. mStateDirty = true;
  765. // Walk the resource list and zombify everything.
  766. GFXResource *walk = mResourceListHead;
  767. while(walk)
  768. {
  769. walk->zombify();
  770. walk = walk->getNextResource();
  771. }
  772. }
  773. void GFXD3D11Device::reacquireDefaultPoolResources()
  774. {
  775. // Now do the dynamic index buffers
  776. if( mDynamicPB == NULL )
  777. mDynamicPB = new GFXD3D11PrimitiveBuffer(this, 0, 0, GFXBufferTypeDynamic);
  778. D3D11_BUFFER_DESC desc;
  779. desc.ByteWidth = sizeof(U16) * MAX_DYNAMIC_INDICES;
  780. desc.Usage = D3D11_USAGE_DYNAMIC;
  781. desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  782. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  783. desc.MiscFlags = 0;
  784. desc.StructureByteStride = 0;
  785. HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &mDynamicPB->ib);
  786. if(FAILED(hr))
  787. {
  788. AssertFatal(false, "Failed to allocate dynamic IB");
  789. }
  790. // Walk the resource list and zombify everything.
  791. GFXResource *walk = mResourceListHead;
  792. while(walk)
  793. {
  794. walk->resurrect();
  795. walk = walk->getNextResource();
  796. }
  797. if(mTextureManager)
  798. mTextureManager->resurrect();
  799. }
  800. GFXD3D11VertexBuffer* GFXD3D11Device::findVBPool( const GFXVertexFormat *vertexFormat, U32 vertsNeeded )
  801. {
  802. PROFILE_SCOPE( GFXD3D11Device_findVBPool );
  803. for( U32 i=0; i<mVolatileVBList.size(); i++ )
  804. if( mVolatileVBList[i]->mVertexFormat.isEqual( *vertexFormat ) )
  805. return mVolatileVBList[i];
  806. return NULL;
  807. }
  808. GFXD3D11VertexBuffer * GFXD3D11Device::createVBPool( const GFXVertexFormat *vertexFormat, U32 vertSize )
  809. {
  810. PROFILE_SCOPE( GFXD3D11Device_createVBPool );
  811. // this is a bit funky, but it will avoid problems with (lack of) copy constructors
  812. // with a push_back() situation
  813. mVolatileVBList.increment();
  814. StrongRefPtr<GFXD3D11VertexBuffer> newBuff;
  815. mVolatileVBList.last() = new GFXD3D11VertexBuffer();
  816. newBuff = mVolatileVBList.last();
  817. newBuff->mNumVerts = 0;
  818. newBuff->mBufferType = GFXBufferTypeVolatile;
  819. newBuff->mVertexFormat.copy( *vertexFormat );
  820. newBuff->mVertexSize = vertSize;
  821. newBuff->mDevice = this;
  822. // Requesting it will allocate it.
  823. vertexFormat->getDecl();
  824. D3D11_BUFFER_DESC desc;
  825. desc.ByteWidth = vertSize * MAX_DYNAMIC_VERTS;
  826. desc.Usage = D3D11_USAGE_DYNAMIC;
  827. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  828. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  829. desc.MiscFlags = 0;
  830. desc.StructureByteStride = 0;
  831. HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &newBuff->vb);
  832. if(FAILED(hr))
  833. {
  834. AssertFatal(false, "Failed to allocate dynamic VB");
  835. }
  836. return newBuff;
  837. }
  838. //-----------------------------------------------------------------------------
  839. void GFXD3D11Device::setClipRect( const RectI &inRect )
  840. {
  841. // We transform the incoming rect by the view
  842. // matrix first, so that it can be used to pan
  843. // and scale the clip rect.
  844. //
  845. // This is currently used to take tiled screenshots.
  846. Point3F pos( inRect.point.x, inRect.point.y, 0.0f );
  847. Point3F extent( inRect.extent.x, inRect.extent.y, 0.0f );
  848. getViewMatrix().mulP( pos );
  849. getViewMatrix().mulV( extent );
  850. RectI rect( pos.x, pos.y, extent.x, extent.y );
  851. // Clip the rect against the renderable size.
  852. Point2I size = mCurrentRT->getSize();
  853. RectI maxRect(Point2I(0,0), size);
  854. rect.intersect(maxRect);
  855. mClipRect = rect;
  856. F32 l = F32( mClipRect.point.x );
  857. F32 r = F32( mClipRect.point.x + mClipRect.extent.x );
  858. F32 b = F32( mClipRect.point.y + mClipRect.extent.y );
  859. F32 t = F32( mClipRect.point.y );
  860. // Set up projection matrix,
  861. static Point4F pt;
  862. pt.set(2.0f / (r - l), 0.0f, 0.0f, 0.0f);
  863. mTempMatrix.setColumn(0, pt);
  864. pt.set(0.0f, 2.0f/(t - b), 0.0f, 0.0f);
  865. mTempMatrix.setColumn(1, pt);
  866. pt.set(0.0f, 0.0f, 1.0f, 0.0f);
  867. mTempMatrix.setColumn(2, pt);
  868. pt.set((l+r)/(l-r), (t+b)/(b-t), 1.0f, 1.0f);
  869. mTempMatrix.setColumn(3, pt);
  870. setProjectionMatrix( mTempMatrix );
  871. // Set up world/view matrix
  872. mTempMatrix.identity();
  873. setWorldMatrix( mTempMatrix );
  874. setViewport( mClipRect );
  875. }
  876. void GFXD3D11Device::setVertexStream( U32 stream, GFXVertexBuffer *buffer )
  877. {
  878. GFXD3D11VertexBuffer *d3dBuffer = static_cast<GFXD3D11VertexBuffer*>( buffer );
  879. if ( stream == 0 )
  880. {
  881. // Set the volatile buffer which is used to
  882. // offset the start index when doing draw calls.
  883. if ( d3dBuffer && d3dBuffer->mVolatileStart > 0 )
  884. mVolatileVB = d3dBuffer;
  885. else
  886. mVolatileVB = NULL;
  887. }
  888. // NOTE: We do not use the stream offset here for stream 0
  889. // as that feature is *supposedly* not as well supported as
  890. // using the start index in drawPrimitive.
  891. //
  892. // If we can verify that this is not the case then we should
  893. // start using this method exclusively for all streams.
  894. U32 strides[1] = { d3dBuffer ? d3dBuffer->mVertexSize : 0 };
  895. U32 offset = d3dBuffer && stream != 0 ? d3dBuffer->mVolatileStart * d3dBuffer->mVertexSize : 0;
  896. ID3D11Buffer* buff = d3dBuffer ? d3dBuffer->vb : NULL;
  897. getDeviceContext()->IASetVertexBuffers(stream, 1, &buff, strides, &offset);
  898. }
  899. void GFXD3D11Device::setVertexStreamFrequency( U32 stream, U32 frequency )
  900. {
  901. if (stream == 0)
  902. mDrawInstancesCount = frequency; // instances count
  903. }
  904. void GFXD3D11Device::_setPrimitiveBuffer( GFXPrimitiveBuffer *buffer )
  905. {
  906. mCurrentPB = static_cast<GFXD3D11PrimitiveBuffer *>( buffer );
  907. mD3DDeviceContext->IASetIndexBuffer(mCurrentPB->ib, DXGI_FORMAT_R16_UINT, 0);
  908. }
  909. U32 GFXD3D11Device::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount)
  910. {
  911. switch (primType)
  912. {
  913. case GFXPointList:
  914. return primitiveCount;
  915. break;
  916. case GFXLineList:
  917. return primitiveCount * 2;
  918. break;
  919. case GFXLineStrip:
  920. return primitiveCount + 1;
  921. break;
  922. case GFXTriangleList:
  923. return primitiveCount * 3;
  924. break;
  925. case GFXTriangleStrip:
  926. return 2 + primitiveCount;
  927. break;
  928. default:
  929. AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
  930. break;
  931. }
  932. return 0;
  933. }
  934. void GFXD3D11Device::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
  935. {
  936. // This is done to avoid the function call overhead if possible
  937. if( mStateDirty )
  938. updateStates();
  939. if (mCurrentShaderConstBuffer)
  940. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  941. if ( mVolatileVB )
  942. vertexStart += mVolatileVB->mVolatileStart;
  943. mD3DDeviceContext->IASetPrimitiveTopology(GFXD3D11PrimType[primType]);
  944. if ( mDrawInstancesCount )
  945. mD3DDeviceContext->DrawInstanced(primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount, vertexStart, 0);
  946. else
  947. mD3DDeviceContext->Draw(primCountToIndexCount(primType, primitiveCount), vertexStart);
  948. mDeviceStatistics.mDrawCalls++;
  949. if ( mVertexBufferFrequency[0] > 1 )
  950. mDeviceStatistics.mPolyCount += primitiveCount * mVertexBufferFrequency[0];
  951. else
  952. mDeviceStatistics.mPolyCount += primitiveCount;
  953. }
  954. void GFXD3D11Device::drawIndexedPrimitive( GFXPrimitiveType primType,
  955. U32 startVertex,
  956. U32 minIndex,
  957. U32 numVerts,
  958. U32 startIndex,
  959. U32 primitiveCount )
  960. {
  961. // This is done to avoid the function call overhead if possible
  962. if( mStateDirty )
  963. updateStates();
  964. if (mCurrentShaderConstBuffer)
  965. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  966. AssertFatal( mCurrentPB != NULL, "Trying to call drawIndexedPrimitive with no current index buffer, call setIndexBuffer()" );
  967. if ( mVolatileVB )
  968. startVertex += mVolatileVB->mVolatileStart;
  969. mD3DDeviceContext->IASetPrimitiveTopology(GFXD3D11PrimType[primType]);
  970. if ( mDrawInstancesCount )
  971. mD3DDeviceContext->DrawIndexedInstanced(primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount, mCurrentPB->mVolatileStart + startIndex, startVertex, 0);
  972. else
  973. mD3DDeviceContext->DrawIndexed(primCountToIndexCount(primType,primitiveCount), mCurrentPB->mVolatileStart + startIndex, startVertex);
  974. mDeviceStatistics.mDrawCalls++;
  975. if ( mVertexBufferFrequency[0] > 1 )
  976. mDeviceStatistics.mPolyCount += primitiveCount * mVertexBufferFrequency[0];
  977. else
  978. mDeviceStatistics.mPolyCount += primitiveCount;
  979. }
  980. GFXShader* GFXD3D11Device::createShader()
  981. {
  982. GFXD3D11Shader* shader = new GFXD3D11Shader();
  983. shader->registerResourceWithDevice( this );
  984. return shader;
  985. }
  986. //-----------------------------------------------------------------------------
  987. // Set shader - this function exists to make sure this is done in one place,
  988. // and to make sure redundant shader states are not being
  989. // sent to the card.
  990. //-----------------------------------------------------------------------------
  991. void GFXD3D11Device::setShader(GFXShader *shader, bool force)
  992. {
  993. if(shader)
  994. {
  995. GFXD3D11Shader *d3dShader = static_cast<GFXD3D11Shader*>(shader);
  996. if (d3dShader->mPixShader != mLastPixShader || force)
  997. {
  998. mD3DDeviceContext->PSSetShader( d3dShader->mPixShader, NULL, 0);
  999. mLastPixShader = d3dShader->mPixShader;
  1000. }
  1001. if (d3dShader->mVertShader != mLastVertShader || force)
  1002. {
  1003. mD3DDeviceContext->VSSetShader( d3dShader->mVertShader, NULL, 0);
  1004. mLastVertShader = d3dShader->mVertShader;
  1005. }
  1006. }
  1007. else
  1008. {
  1009. setupGenericShaders();
  1010. }
  1011. }
  1012. GFXPrimitiveBuffer * GFXD3D11Device::allocPrimitiveBuffer(U32 numIndices, U32 numPrimitives, GFXBufferType bufferType, void *data )
  1013. {
  1014. // Allocate a buffer to return
  1015. GFXD3D11PrimitiveBuffer * res = new GFXD3D11PrimitiveBuffer(this, numIndices, numPrimitives, bufferType);
  1016. // Determine usage flags
  1017. D3D11_USAGE usage = D3D11_USAGE_DEFAULT;
  1018. // Assumptions:
  1019. // - static buffers are write once, use many
  1020. // - dynamic buffers are write many, use many
  1021. // - volatile buffers are write once, use once
  1022. // You may never read from a buffer.
  1023. //TODO: enable proper support for D3D11_USAGE_IMMUTABLE
  1024. switch(bufferType)
  1025. {
  1026. case GFXBufferTypeImmutable:
  1027. case GFXBufferTypeStatic:
  1028. usage = D3D11_USAGE_DEFAULT; //D3D11_USAGE_IMMUTABLE;
  1029. break;
  1030. case GFXBufferTypeDynamic:
  1031. case GFXBufferTypeVolatile:
  1032. usage = D3D11_USAGE_DYNAMIC;
  1033. break;
  1034. }
  1035. // Register resource
  1036. res->registerResourceWithDevice(this);
  1037. // Create d3d index buffer
  1038. if(bufferType == GFXBufferTypeVolatile)
  1039. {
  1040. // Get it from the pool if it's a volatile...
  1041. AssertFatal(numIndices < MAX_DYNAMIC_INDICES, "Cannot allocate that many indices in a volatile buffer, increase MAX_DYNAMIC_INDICES.");
  1042. res->ib = mDynamicPB->ib;
  1043. res->mVolatileBuffer = mDynamicPB;
  1044. }
  1045. else
  1046. {
  1047. // Otherwise, get it as a seperate buffer...
  1048. D3D11_BUFFER_DESC desc;
  1049. desc.ByteWidth = sizeof(U16) * numIndices;
  1050. desc.Usage = usage;
  1051. if(bufferType == GFXBufferTypeDynamic)
  1052. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // We never allow reading from a primitive buffer.
  1053. else
  1054. desc.CPUAccessFlags = 0;
  1055. desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  1056. desc.MiscFlags = 0;
  1057. desc.StructureByteStride = 0;
  1058. HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &res->ib);
  1059. if(FAILED(hr))
  1060. {
  1061. AssertFatal(false, "Failed to allocate an index buffer.");
  1062. }
  1063. }
  1064. if (data)
  1065. {
  1066. void* dest;
  1067. res->lock(0, numIndices, &dest);
  1068. dMemcpy(dest, data, sizeof(U16) * numIndices);
  1069. res->unlock();
  1070. }
  1071. return res;
  1072. }
  1073. GFXVertexBuffer * GFXD3D11Device::allocVertexBuffer(U32 numVerts, const GFXVertexFormat *vertexFormat, U32 vertSize, GFXBufferType bufferType, void *data)
  1074. {
  1075. PROFILE_SCOPE( GFXD3D11Device_allocVertexBuffer );
  1076. GFXD3D11VertexBuffer *res = new GFXD3D11VertexBuffer( this,
  1077. numVerts,
  1078. vertexFormat,
  1079. vertSize,
  1080. bufferType );
  1081. // Determine usage flags
  1082. D3D11_USAGE usage = D3D11_USAGE_DEFAULT;
  1083. res->mNumVerts = 0;
  1084. // Assumptions:
  1085. // - static buffers are write once, use many
  1086. // - dynamic buffers are write many, use many
  1087. // - volatile buffers are write once, use once
  1088. // You may never read from a buffer.
  1089. //TODO: enable proper support for D3D11_USAGE_IMMUTABLE
  1090. switch(bufferType)
  1091. {
  1092. case GFXBufferTypeImmutable:
  1093. case GFXBufferTypeStatic:
  1094. usage = D3D11_USAGE_DEFAULT;
  1095. break;
  1096. case GFXBufferTypeDynamic:
  1097. case GFXBufferTypeVolatile:
  1098. usage = D3D11_USAGE_DYNAMIC;
  1099. break;
  1100. }
  1101. // Register resource
  1102. res->registerResourceWithDevice(this);
  1103. // Create vertex buffer
  1104. if(bufferType == GFXBufferTypeVolatile)
  1105. {
  1106. // NOTE: Volatile VBs are pooled and will be allocated at lock time.
  1107. AssertFatal(numVerts <= MAX_DYNAMIC_VERTS, "GFXD3D11Device::allocVertexBuffer - Volatile vertex buffer is too big... see MAX_DYNAMIC_VERTS!");
  1108. }
  1109. else
  1110. {
  1111. // Requesting it will allocate it.
  1112. vertexFormat->getDecl(); //-ALEX disabled to postpone until after shader is actually set...
  1113. // Get a new buffer...
  1114. D3D11_BUFFER_DESC desc;
  1115. desc.ByteWidth = vertSize * numVerts;
  1116. desc.Usage = usage;
  1117. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  1118. if(bufferType == GFXBufferTypeDynamic)
  1119. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // We never allow reading from a vertex buffer.
  1120. else
  1121. desc.CPUAccessFlags = 0;
  1122. desc.MiscFlags = 0;
  1123. desc.StructureByteStride = 0;
  1124. HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &res->vb);
  1125. if(FAILED(hr))
  1126. {
  1127. AssertFatal(false, "Failed to allocate VB");
  1128. }
  1129. }
  1130. res->mNumVerts = numVerts;
  1131. if (data)
  1132. {
  1133. void* dest;
  1134. res->lock(0, numVerts, &dest);
  1135. dMemcpy(dest, data, vertSize * numVerts);
  1136. res->unlock();
  1137. }
  1138. return res;
  1139. }
  1140. String GFXD3D11Device::_createTempShaderInternal(const GFXVertexFormat *vertexFormat)
  1141. {
  1142. U32 elemCount = vertexFormat->getElementCount();
  1143. //Input data
  1144. StringBuilder inputData;
  1145. inputData.append("struct VertIn {");
  1146. //Output data
  1147. StringBuilder outputData;
  1148. outputData.append("struct VertOut {");
  1149. // Shader main body data
  1150. StringBuilder mainBodyData;
  1151. //make shader
  1152. mainBodyData.append("VertOut main(VertIn IN){VertOut OUT;");
  1153. for (U32 i = 0; i < elemCount; i++)
  1154. {
  1155. const GFXVertexElement &element = vertexFormat->getElement(i);
  1156. String semantic = element.getSemantic();
  1157. String semanticOut = semantic;
  1158. String type;
  1159. if (element.isSemantic(GFXSemantic::POSITION))
  1160. {
  1161. semantic = "POSITION";
  1162. semanticOut = "SV_Position";
  1163. }
  1164. else if (element.isSemantic(GFXSemantic::NORMAL))
  1165. {
  1166. semantic = "NORMAL";
  1167. semanticOut = semantic;
  1168. }
  1169. else if (element.isSemantic(GFXSemantic::COLOR))
  1170. {
  1171. semantic = "COLOR";
  1172. semanticOut = semantic;
  1173. }
  1174. else if (element.isSemantic(GFXSemantic::TANGENT))
  1175. {
  1176. semantic = "TANGENT";
  1177. semanticOut = semantic;
  1178. }
  1179. else if (element.isSemantic(GFXSemantic::BINORMAL))
  1180. {
  1181. semantic = "BINORMAL";
  1182. semanticOut = semantic;
  1183. }
  1184. else if (element.isSemantic(GFXSemantic::BLENDINDICES))
  1185. {
  1186. semantic = String::ToString("BLENDINDICES%d", element.getSemanticIndex());
  1187. semanticOut = semantic;
  1188. }
  1189. else if (element.isSemantic(GFXSemantic::BLENDWEIGHT))
  1190. {
  1191. semantic = String::ToString("BLENDWEIGHT%d", element.getSemanticIndex());
  1192. semanticOut = semantic;
  1193. }
  1194. else
  1195. {
  1196. //Anything that falls thru to here will be a texture coord.
  1197. semantic = String::ToString("TEXCOORD%d", element.getSemanticIndex());
  1198. semanticOut = semantic;
  1199. }
  1200. switch (GFXD3D11DeclType[element.getType()])
  1201. {
  1202. case DXGI_FORMAT_R32_FLOAT:
  1203. type = "float";
  1204. break;
  1205. case DXGI_FORMAT_R32G32_FLOAT:
  1206. type = "float2";
  1207. break;
  1208. case DXGI_FORMAT_R32G32B32_FLOAT:
  1209. type = "float3";
  1210. break;
  1211. case DXGI_FORMAT_R32G32B32A32_FLOAT:
  1212. case DXGI_FORMAT_B8G8R8A8_UNORM:
  1213. case DXGI_FORMAT_R8G8B8A8_UNORM:
  1214. type = "float4";
  1215. break;
  1216. case DXGI_FORMAT_R8G8B8A8_UINT:
  1217. type = "uint4";
  1218. break;
  1219. }
  1220. StringBuilder in;
  1221. in.format("%s %s%d : %s;", type.c_str(), "var", i, semantic.c_str());
  1222. inputData.append(in.data());
  1223. //SV_Position must be float4
  1224. if (semanticOut == String("SV_Position"))
  1225. {
  1226. StringBuilder out;
  1227. out.format("float4 %s%d : %s;", "var", i, semanticOut.c_str());
  1228. outputData.append(out.data());
  1229. StringBuilder body;
  1230. body.format("OUT.%s%d = float4(IN.%s%d.xyz,1);", "var", i, "var", i);
  1231. mainBodyData.append(body.data());
  1232. }
  1233. else
  1234. {
  1235. StringBuilder out;
  1236. out.format("%s %s%d : %s;", type.c_str(), "var", i, semanticOut.c_str());
  1237. outputData.append(out.data());
  1238. StringBuilder body;
  1239. body.format("OUT.%s%d = IN.%s%d;", "var", i, "var", i);
  1240. mainBodyData.append(body.data());
  1241. }
  1242. }
  1243. inputData.append("};");
  1244. outputData.append("};");
  1245. mainBodyData.append("return OUT;}");
  1246. //final data
  1247. StringBuilder finalData;
  1248. finalData.append(inputData.data());
  1249. finalData.append(outputData.data());
  1250. finalData.append(mainBodyData.data());
  1251. return String(finalData.data());
  1252. }
  1253. GFXVertexDecl* GFXD3D11Device::allocVertexDecl( const GFXVertexFormat *vertexFormat )
  1254. {
  1255. PROFILE_SCOPE( GFXD3D11Device_allocVertexDecl );
  1256. // First check the map... you shouldn't allocate VBs very often
  1257. // if you want performance. The map lookup should never become
  1258. // a performance bottleneck.
  1259. D3D11VertexDecl *decl = mVertexDecls[vertexFormat->getDescription()];
  1260. if ( decl )
  1261. return decl;
  1262. U32 elemCount = vertexFormat->getElementCount();
  1263. ID3DBlob* code = NULL;
  1264. // We have to generate a temporary shader here for now since the input layout creation
  1265. // expects a shader to be already compiled to verify the vertex layout structure. The problem
  1266. // is that most of the time the regular shaders are compiled AFTER allocVertexDecl is called.
  1267. if(!decl)
  1268. {
  1269. //TODO: Perhaps save/cache the ID3DBlob for later use on identical vertex formats,save creating/compiling the temp shader everytime
  1270. String shaderData = _createTempShaderInternal(vertexFormat);
  1271. #ifdef TORQUE_DEBUG
  1272. U32 flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS;
  1273. #else
  1274. U32 flags = D3DCOMPILE_ENABLE_STRICTNESS;
  1275. #endif
  1276. ID3DBlob *errorBlob = NULL;
  1277. HRESULT hr = D3DCompile(shaderData.c_str(), shaderData.length(), NULL, NULL, NULL, "main", "vs_5_0", flags, 0, &code, &errorBlob);
  1278. StringBuilder error;
  1279. if(errorBlob)
  1280. {
  1281. error.append((char*)errorBlob->GetBufferPointer(), errorBlob->GetBufferSize());
  1282. AssertFatal(hr, error.data());
  1283. }
  1284. SAFE_RELEASE(errorBlob);
  1285. }
  1286. AssertFatal(code, "D3D11Device::allocVertexDecl - compiled vert shader code missing!");
  1287. // Setup the declaration struct.
  1288. U32 stream;
  1289. D3D11_INPUT_ELEMENT_DESC *vd = new D3D11_INPUT_ELEMENT_DESC[ elemCount];
  1290. S32 elemIndex = 0;
  1291. for (S32 i = 0; i < elemCount; i++, elemIndex++)
  1292. {
  1293. const GFXVertexElement &element = vertexFormat->getElement(elemIndex);
  1294. stream = element.getStreamIndex();
  1295. vd[i].InputSlot = stream;
  1296. vd[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
  1297. vd[i].Format = GFXD3D11DeclType[element.getType()];
  1298. // If instancing is enabled, the per instance data is only used on stream 1.
  1299. if (vertexFormat->hasInstancing() && stream == 1)
  1300. {
  1301. vd[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA;
  1302. vd[i].InstanceDataStepRate = 1;
  1303. }
  1304. else
  1305. {
  1306. vd[i].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
  1307. vd[i].InstanceDataStepRate = 0;
  1308. }
  1309. // We force the usage index of 0 for everything but
  1310. // texture coords for now... this may change later.
  1311. vd[i].SemanticIndex = 0;
  1312. if (element.isSemantic(GFXSemantic::POSITION))
  1313. vd[i].SemanticName = "POSITION";
  1314. else if (element.isSemantic(GFXSemantic::NORMAL))
  1315. vd[i].SemanticName = "NORMAL";
  1316. else if (element.isSemantic(GFXSemantic::COLOR))
  1317. vd[i].SemanticName = "COLOR";
  1318. else if (element.isSemantic(GFXSemantic::TANGENT))
  1319. vd[i].SemanticName = "TANGENT";
  1320. else if (element.isSemantic(GFXSemantic::BINORMAL))
  1321. vd[i].SemanticName = "BINORMAL";
  1322. else if (element.isSemantic(GFXSemantic::BLENDWEIGHT))
  1323. {
  1324. vd[i].SemanticName = "BLENDWEIGHT";
  1325. vd[i].SemanticIndex = element.getSemanticIndex();
  1326. }
  1327. else if (element.isSemantic(GFXSemantic::BLENDINDICES))
  1328. {
  1329. vd[i].SemanticName = "BLENDINDICES";
  1330. vd[i].SemanticIndex = element.getSemanticIndex();
  1331. }
  1332. else
  1333. {
  1334. //Anything that falls thru to here will be a texture coord.
  1335. vd[i].SemanticName = "TEXCOORD";
  1336. vd[i].SemanticIndex = element.getSemanticIndex();
  1337. }
  1338. }
  1339. decl = new D3D11VertexDecl();
  1340. HRESULT hr = mD3DDevice->CreateInputLayout(vd, elemCount,code->GetBufferPointer(), code->GetBufferSize(), &decl->decl);
  1341. if (FAILED(hr))
  1342. {
  1343. AssertFatal(false, "GFXD3D11Device::allocVertexDecl - Failed to create vertex input layout!");
  1344. }
  1345. delete [] vd;
  1346. SAFE_RELEASE(code);
  1347. // Store it in the cache.
  1348. mVertexDecls[vertexFormat->getDescription()] = decl;
  1349. return decl;
  1350. }
  1351. void GFXD3D11Device::setVertexDecl( const GFXVertexDecl *decl )
  1352. {
  1353. ID3D11InputLayout *dx11Decl = NULL;
  1354. if (decl)
  1355. dx11Decl = static_cast<const D3D11VertexDecl*>(decl)->decl;
  1356. mD3DDeviceContext->IASetInputLayout(dx11Decl);
  1357. }
  1358. //-----------------------------------------------------------------------------
  1359. // This function should ONLY be called from GFXDevice::updateStates() !!!
  1360. //-----------------------------------------------------------------------------
  1361. void GFXD3D11Device::setTextureInternal( U32 textureUnit, const GFXTextureObject *texture)
  1362. {
  1363. if( texture == NULL )
  1364. {
  1365. ID3D11ShaderResourceView *pView = NULL;
  1366. mD3DDeviceContext->PSSetShaderResources(textureUnit, 1, &pView);
  1367. return;
  1368. }
  1369. GFXD3D11TextureObject *tex = (GFXD3D11TextureObject*)(texture);
  1370. mD3DDeviceContext->PSSetShaderResources(textureUnit, 1, tex->getSRViewPtr());
  1371. }
  1372. GFXFence *GFXD3D11Device::createFence()
  1373. {
  1374. // Figure out what fence type we should be making if we don't know
  1375. if( mCreateFenceType == -1 )
  1376. {
  1377. D3D11_QUERY_DESC desc;
  1378. desc.MiscFlags = 0;
  1379. desc.Query = D3D11_QUERY_EVENT;
  1380. ID3D11Query *testQuery = NULL;
  1381. HRESULT hRes = mD3DDevice->CreateQuery(&desc, &testQuery);
  1382. if(FAILED(hRes))
  1383. {
  1384. mCreateFenceType = true;
  1385. }
  1386. else
  1387. {
  1388. mCreateFenceType = false;
  1389. }
  1390. SAFE_RELEASE(testQuery);
  1391. }
  1392. // Cool, use queries
  1393. if(!mCreateFenceType)
  1394. {
  1395. GFXFence* fence = new GFXD3D11QueryFence( this );
  1396. fence->registerResourceWithDevice(this);
  1397. return fence;
  1398. }
  1399. // CodeReview: At some point I would like a specialized implementation of
  1400. // the method used by the general fence, only without the overhead incurred
  1401. // by using the GFX constructs. Primarily the lock() method on texture handles
  1402. // will do a data copy, and this method doesn't require a copy, just a lock
  1403. // [5/10/2007 Pat]
  1404. GFXFence* fence = new GFXGeneralFence( this );
  1405. fence->registerResourceWithDevice(this);
  1406. return fence;
  1407. }
  1408. GFXOcclusionQuery* GFXD3D11Device::createOcclusionQuery()
  1409. {
  1410. GFXOcclusionQuery *query;
  1411. if (mOcclusionQuerySupported)
  1412. query = new GFXD3D11OcclusionQuery( this );
  1413. else
  1414. return NULL;
  1415. query->registerResourceWithDevice(this);
  1416. return query;
  1417. }
  1418. GFXCubemap * GFXD3D11Device::createCubemap()
  1419. {
  1420. GFXD3D11Cubemap* cube = new GFXD3D11Cubemap();
  1421. cube->registerResourceWithDevice(this);
  1422. return cube;
  1423. }
  1424. GFXCubemapArray * GFXD3D11Device::createCubemapArray()
  1425. {
  1426. GFXD3D11CubemapArray* cubeArray = new GFXD3D11CubemapArray();
  1427. cubeArray->registerResourceWithDevice(this);
  1428. return cubeArray;
  1429. }
  1430. // Debug events
  1431. //------------------------------------------------------------------------------
  1432. void GFXD3D11Device::enterDebugEvent(ColorI color, const char *name)
  1433. {
  1434. // BJGFIX
  1435. WCHAR eventName[260];
  1436. MultiByteToWideChar(CP_ACP, 0, name, -1, eventName, 260);
  1437. D3DPERF_BeginEvent(D3DCOLOR_ARGB(color.alpha, color.red, color.green, color.blue),
  1438. (LPCWSTR)&eventName);
  1439. }
  1440. //------------------------------------------------------------------------------
  1441. void GFXD3D11Device::leaveDebugEvent()
  1442. {
  1443. D3DPERF_EndEvent();
  1444. }
  1445. //------------------------------------------------------------------------------
  1446. void GFXD3D11Device::setDebugMarker(ColorI color, const char *name)
  1447. {
  1448. // BJGFIX
  1449. WCHAR eventName[260];
  1450. MultiByteToWideChar(CP_ACP, 0, name, -1, eventName, 260);
  1451. D3DPERF_SetMarker(D3DCOLOR_ARGB(color.alpha, color.red, color.green, color.blue),
  1452. (LPCWSTR)&eventName);
  1453. }
  1454. const char* GFXD3D11Device::interpretDebugResult(long result)
  1455. {
  1456. const char* error;
  1457. switch (result) {
  1458. case S_OK:
  1459. error = "S_OK";
  1460. break;
  1461. case S_FALSE:
  1462. error = "S_FALSE";
  1463. break;
  1464. //generics
  1465. case E_UNEXPECTED:
  1466. error = "E_UNEXPECTED";
  1467. break;
  1468. case E_NOTIMPL:
  1469. error = "E_NOTIMPL";
  1470. break;
  1471. case E_OUTOFMEMORY:
  1472. error = "E_OUTOFMEMORY";
  1473. break;
  1474. case E_INVALIDARG:
  1475. error = "E_INVALIDARG";
  1476. break;
  1477. case E_NOINTERFACE:
  1478. error = "E_NOINTERFACE";
  1479. break;
  1480. case E_POINTER:
  1481. error = "E_POINTER";
  1482. break;
  1483. case E_HANDLE:
  1484. error = "E_HANDLE";
  1485. break;
  1486. case E_ABORT:
  1487. error = "E_ABORT";
  1488. break;
  1489. case E_FAIL:
  1490. error = "E_FAIL";
  1491. break;
  1492. case E_ACCESSDENIED:
  1493. error = "E_ACCESSDENIED";
  1494. break;
  1495. //graphics specific
  1496. case DXGI_ERROR_INVALID_CALL:
  1497. error = "DXGI_ERROR_INVALID_CALL";
  1498. break;
  1499. case DXGI_ERROR_WAS_STILL_DRAWING:
  1500. error = "DXGI_ERROR_WAS_STILL_DRAWING";
  1501. break;
  1502. //dx11 specific
  1503. case D3D11_ERROR_FILE_NOT_FOUND:
  1504. error = "D3D11_ERROR_FILE_NOT_FOUND";
  1505. break;
  1506. case D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS:
  1507. error = "D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS";
  1508. break;
  1509. case D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS:
  1510. error = "D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS";
  1511. break;
  1512. case D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD:
  1513. error = "D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD";
  1514. break;
  1515. default:
  1516. error = "UNKNOWN";
  1517. break;
  1518. }
  1519. return error;
  1520. }