gfxD3D11Device.cpp 57 KB

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