gfxD3D11Shader.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  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 "platform/platform.h"
  23. #include "gfx/D3D11/gfxD3D11Shader.h"
  24. #include "core/frameAllocator.h"
  25. #include "core/stream/fileStream.h"
  26. #include "core/util/safeDelete.h"
  27. #include "console/console.h"
  28. extern bool gDisassembleAllShaders;
  29. #pragma comment(lib, "d3dcompiler.lib")
  30. gfxD3DIncludeRef GFXD3D11Shader::smD3DInclude = NULL;
  31. class gfxD3D11Include : public ID3DInclude, public StrongRefBase
  32. {
  33. private:
  34. Vector<String> mLastPath;
  35. public:
  36. void setPath(const String &path)
  37. {
  38. mLastPath.clear();
  39. mLastPath.push_back(path);
  40. }
  41. gfxD3D11Include() {}
  42. virtual ~gfxD3D11Include() {}
  43. STDMETHOD(Open)(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes);
  44. STDMETHOD(Close)(THIS_ LPCVOID pData);
  45. };
  46. HRESULT gfxD3D11Include::Open(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes)
  47. {
  48. using namespace Torque;
  49. // First try making the path relative to the parent.
  50. Torque::Path path = Torque::Path::Join( mLastPath.last(), '/', pFileName );
  51. path = Torque::Path::CompressPath( path );
  52. if ( !Torque::FS::ReadFile( path, (void *&)*ppData, *pBytes, true ) )
  53. {
  54. // Ok... now try using the path as is.
  55. path = String( pFileName );
  56. path = Torque::Path::CompressPath( path );
  57. if ( !Torque::FS::ReadFile( path, (void *&)*ppData, *pBytes, true ) )
  58. {
  59. AssertISV(false, avar( "Failed to open include '%s'.", pFileName));
  60. return E_FAIL;
  61. }
  62. }
  63. // If the data was of zero size then we cannot recurse
  64. // into this file and DX won't call Close() below.
  65. //
  66. // So in this case don't push on the path.
  67. if ( *pBytes > 0 )
  68. mLastPath.push_back( path.getRootAndPath() );
  69. return S_OK;
  70. }
  71. HRESULT gfxD3D11Include::Close( THIS_ LPCVOID pData )
  72. {
  73. // Free the data file and pop its path off the stack.
  74. delete [] (U8*)pData;
  75. mLastPath.pop_back();
  76. return S_OK;
  77. }
  78. GFXD3D11ShaderConstHandle::GFXD3D11ShaderConstHandle()
  79. {
  80. clear();
  81. }
  82. const String& GFXD3D11ShaderConstHandle::getName() const
  83. {
  84. if ( mVertexConstant )
  85. return mVertexHandle.name;
  86. else
  87. return mPixelHandle.name;
  88. }
  89. GFXShaderConstType GFXD3D11ShaderConstHandle::getType() const
  90. {
  91. if ( mVertexConstant )
  92. return mVertexHandle.constType;
  93. else
  94. return mPixelHandle.constType;
  95. }
  96. U32 GFXD3D11ShaderConstHandle::getArraySize() const
  97. {
  98. if ( mVertexConstant )
  99. return mVertexHandle.arraySize;
  100. else
  101. return mPixelHandle.arraySize;
  102. }
  103. S32 GFXD3D11ShaderConstHandle::getSamplerRegister() const
  104. {
  105. if ( !mValid || !isSampler() )
  106. return -1;
  107. // We always store sampler type and register index in the pixelHandle,
  108. // sampler registers are shared between vertex and pixel shaders anyway.
  109. return mPixelHandle.offset;
  110. }
  111. GFXD3D11ConstBufferLayout::GFXD3D11ConstBufferLayout()
  112. {
  113. mSubBuffers.reserve(CBUFFER_MAX);
  114. }
  115. bool GFXD3D11ConstBufferLayout::set(const ParamDesc& pd, const GFXShaderConstType constType, const U32 inSize, const void* data, U8* basePointer)
  116. {
  117. PROFILE_SCOPE(GenericConstBufferLayout_set);
  118. S32 size = inSize;
  119. // Shader compilers like to optimize float4x4 uniforms into float3x3s.
  120. // So long as the real paramater is a matrix of-some-type and the data
  121. // passed in is a MatrixF ( which is will be ), we DO NOT have a
  122. // mismatched const type.
  123. AssertFatal(pd.constType == constType ||
  124. (
  125. (pd.constType == GFXSCT_Float2x2 ||
  126. pd.constType == GFXSCT_Float3x3 ||
  127. pd.constType == GFXSCT_Float4x3 ||
  128. pd.constType == GFXSCT_Float4x4) &&
  129. (constType == GFXSCT_Float2x2 ||
  130. constType == GFXSCT_Float3x3 ||
  131. constType == GFXSCT_Float4x3 ||
  132. constType == GFXSCT_Float4x4)
  133. ), "Mismatched const type!");
  134. // This "cute" bit of code allows us to support 2x3 and 3x3 matrices in shader constants but use our MatrixF class. Yes, a hack. -BTR
  135. switch (pd.constType)
  136. {
  137. case GFXSCT_Float2x2:
  138. case GFXSCT_Float3x3:
  139. case GFXSCT_Float4x3:
  140. case GFXSCT_Float4x4:
  141. return setMatrix(pd, constType, size, data, basePointer);
  142. break;
  143. // TODO add other AlignedVector here
  144. case GFXSCT_Float2:
  145. if (size > sizeof(Point2F))
  146. size = pd.size;
  147. default:
  148. break;
  149. }
  150. AssertFatal(pd.size >= size, "Not enough room in the buffer for this data!");
  151. // Ok, we only set data if it's different than the data we already have, this maybe more expensive than just setting the data, but
  152. // we'll have to do some timings to see. For example, the lighting shader constants rarely change, but we can't assume that at the
  153. // renderInstMgr level, but we can check down here. -BTR
  154. if (dMemcmp(basePointer + pd.offset, data, size) != 0)
  155. {
  156. dMemcpy(basePointer + pd.offset, data, size);
  157. return true;
  158. }
  159. return false;
  160. }
  161. bool GFXD3D11ConstBufferLayout::setMatrix(const ParamDesc& pd, const GFXShaderConstType constType, const U32 size, const void* data, U8* basePointer)
  162. {
  163. PROFILE_SCOPE(GFXD3D11ConstBufferLayout_setMatrix);
  164. if (pd.constType == GFXSCT_Float4x4)
  165. {
  166. // Special case, we can just blast this guy.
  167. AssertFatal(pd.size >= size, "Not enough room in the buffer for this data!");
  168. if (dMemcmp(basePointer+pd.offset, data, size) != 0)
  169. {
  170. dMemcpy(basePointer+pd.offset, data, size);
  171. return true;
  172. }
  173. return false;
  174. }
  175. else if (pd.constType == GFXSCT_Float4x3)
  176. {
  177. const U32 csize = 48;
  178. // Loop through and copy
  179. bool ret = false;
  180. U8* currDestPointer = basePointer + pd.offset;
  181. const U8* currSourcePointer = static_cast<const U8*>(data);
  182. const U8* endData = currSourcePointer + size;
  183. while (currSourcePointer < endData)
  184. {
  185. #ifdef TORQUE_DOUBLE_CHECK_43MATS
  186. Point4F col;
  187. ((MatrixF*)currSourcePointer)->getRow(3, &col);
  188. AssertFatal(col.x == 0.0f && col.y == 0.0f && col.z == 0.0f && col.w == 1.0f, "3rd row used");
  189. #endif
  190. if (dMemcmp(currDestPointer, currSourcePointer, csize) != 0)
  191. {
  192. dMemcpy(currDestPointer, currSourcePointer, csize);
  193. ret = true;
  194. }
  195. else if (pd.constType == GFXSCT_Float4x3)
  196. {
  197. ret = true;
  198. }
  199. currDestPointer += csize;
  200. currSourcePointer += sizeof(MatrixF);
  201. }
  202. return ret;
  203. }
  204. else
  205. {
  206. PROFILE_SCOPE(GFXD3D11ConstBufferLayout_setMatrix_not4x4);
  207. // Figure out how big of a chunk we are copying. We're going to copy 4 columns by N rows of data
  208. U32 csize;
  209. switch (pd.constType)
  210. {
  211. case GFXSCT_Float2x2 :
  212. csize = 24; //this takes up 16+8
  213. break;
  214. case GFXSCT_Float3x3 :
  215. csize = 44; //This takes up 16+16+12
  216. break;
  217. default:
  218. AssertFatal(false, "Unhandled case!");
  219. return false;
  220. break;
  221. }
  222. // Loop through and copy
  223. bool ret = false;
  224. U8* currDestPointer = basePointer+pd.offset;
  225. const U8* currSourcePointer = static_cast<const U8*>(data);
  226. const U8* endData = currSourcePointer + size;
  227. while (currSourcePointer < endData)
  228. {
  229. if (dMemcmp(currDestPointer, currSourcePointer, csize) != 0)
  230. {
  231. dMemcpy(currDestPointer, currSourcePointer, csize);
  232. ret = true;
  233. }
  234. currDestPointer += csize;
  235. currSourcePointer += sizeof(MatrixF);
  236. }
  237. return ret;
  238. }
  239. }
  240. //------------------------------------------------------------------------------
  241. GFXD3D11ShaderConstBuffer::GFXD3D11ShaderConstBuffer( GFXD3D11Shader* shader,
  242. GFXD3D11ConstBufferLayout* vertexLayout,
  243. GFXD3D11ConstBufferLayout* pixelLayout)
  244. {
  245. AssertFatal( shader, "GFXD3D11ShaderConstBuffer() - Got a null shader!" );
  246. // We hold on to this so we don't have to call
  247. // this virtual method during activation.
  248. mShader = shader;
  249. for (U32 i = 0; i < CBUFFER_MAX; ++i)
  250. {
  251. mConstantBuffersV[i] = NULL;
  252. mConstantBuffersP[i] = NULL;
  253. }
  254. // TODO: Remove buffers and layouts that don't exist for performance?
  255. //Mandatory
  256. mVertexConstBufferLayout = vertexLayout;
  257. mVertexConstBuffer = new GenericConstBuffer(vertexLayout);
  258. mPixelConstBufferLayout = pixelLayout;
  259. mPixelConstBuffer = new GenericConstBuffer(pixelLayout);
  260. _createBuffers();
  261. }
  262. GFXD3D11ShaderConstBuffer::~GFXD3D11ShaderConstBuffer()
  263. {
  264. // release constant buffer
  265. for (U32 i = 0; i < CBUFFER_MAX; ++i)
  266. {
  267. SAFE_RELEASE(mConstantBuffersP[i]);
  268. SAFE_RELEASE(mConstantBuffersV[i]);
  269. }
  270. SAFE_DELETE(mVertexConstBuffer);
  271. SAFE_DELETE(mPixelConstBuffer);
  272. if ( mShader )
  273. mShader->_unlinkBuffer( this );
  274. }
  275. void GFXD3D11ShaderConstBuffer::_createBuffers()
  276. {
  277. HRESULT hr;
  278. // Create a vertex constant buffer
  279. if (mVertexConstBufferLayout->getBufferSize() > 0)
  280. {
  281. const Vector<ConstSubBufferDesc> &subBuffers = mVertexConstBufferLayout->getSubBufferDesc();
  282. for (U32 i = 0; i < subBuffers.size(); ++i)
  283. {
  284. D3D11_BUFFER_DESC cbDesc;
  285. cbDesc.ByteWidth = subBuffers[i].size;
  286. cbDesc.Usage = D3D11_USAGE_DEFAULT;
  287. cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  288. cbDesc.CPUAccessFlags = 0;
  289. cbDesc.MiscFlags = 0;
  290. cbDesc.StructureByteStride = 0;
  291. hr = D3D11DEVICE->CreateBuffer(&cbDesc, NULL, &mConstantBuffersV[i]);
  292. if (FAILED(hr))
  293. {
  294. AssertFatal(false, "can't create constant mConstantBuffersV!");
  295. }
  296. }
  297. }
  298. // Create a pixel constant buffer
  299. if (mPixelConstBufferLayout->getBufferSize())
  300. {
  301. const Vector<ConstSubBufferDesc> &subBuffers = mPixelConstBufferLayout->getSubBufferDesc();
  302. for (U32 i = 0; i < subBuffers.size(); ++i)
  303. {
  304. // Create a pixel float constant buffer
  305. D3D11_BUFFER_DESC cbDesc;
  306. cbDesc.ByteWidth = subBuffers[i].size;
  307. cbDesc.Usage = D3D11_USAGE_DEFAULT;
  308. cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  309. cbDesc.CPUAccessFlags = 0;
  310. cbDesc.MiscFlags = 0;
  311. cbDesc.StructureByteStride = 0;
  312. hr = D3D11DEVICE->CreateBuffer(&cbDesc, NULL, &mConstantBuffersP[i]);
  313. if (FAILED(hr))
  314. {
  315. AssertFatal(false, "can't create constant mConstantBuffersP!");
  316. }
  317. }
  318. }
  319. }
  320. GFXShader* GFXD3D11ShaderConstBuffer::getShader()
  321. {
  322. return mShader;
  323. }
  324. // This is kind of cheesy, but I don't think templates would work well here because
  325. // these functions potentially need to be handled differently by other derived types
  326. template<class T>
  327. inline void GFXD3D11ShaderConstBuffer::SET_CONSTANT( GFXShaderConstHandle* handle, const T& fv,
  328. GenericConstBuffer *vBuffer, GenericConstBuffer *pBuffer )
  329. {
  330. AssertFatal(static_cast<const GFXD3D11ShaderConstHandle*>(handle), "Incorrect const buffer type!");
  331. const GFXD3D11ShaderConstHandle* h = static_cast<const GFXD3D11ShaderConstHandle*>(handle);
  332. AssertFatal(h, "Handle is NULL!" );
  333. AssertFatal(h->isValid(), "Handle is not valid!" );
  334. AssertFatal(!h->isSampler(), "Handle is sampler constant!" );
  335. AssertFatal(!mShader.isNull(), "Buffer's shader is null!" );
  336. AssertFatal(!h->mShader.isNull(), "Handle's shader is null!" );
  337. AssertFatal(h->mShader.getPointer() == mShader.getPointer(), "Mismatched shaders!");
  338. if ( h->mInstancingConstant )
  339. {
  340. dMemcpy( mInstPtr+h->mPixelHandle.offset, &fv, sizeof( fv ) );
  341. return;
  342. }
  343. if (h->mVertexConstant)
  344. vBuffer->set(h->mVertexHandle, fv);
  345. if (h->mPixelConstant)
  346. pBuffer->set(h->mPixelHandle, fv);
  347. }
  348. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const F32 fv)
  349. {
  350. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  351. }
  352. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point2F& fv)
  353. {
  354. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  355. }
  356. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point3F& fv)
  357. {
  358. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  359. }
  360. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point4F& fv)
  361. {
  362. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  363. }
  364. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const PlaneF& fv)
  365. {
  366. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  367. }
  368. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const ColorF& fv)
  369. {
  370. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  371. }
  372. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const S32 f)
  373. {
  374. // This is the only type that is allowed to be used
  375. // with a sampler shader constant type, but it is only
  376. // allowed to be set from GLSL.
  377. //
  378. // So we ignore it here... all other cases will assert.
  379. //
  380. if ( ((GFXD3D11ShaderConstHandle*)handle)->isSampler() )
  381. return;
  382. SET_CONSTANT(handle, f, mVertexConstBuffer, mPixelConstBuffer);
  383. }
  384. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point2I& fv)
  385. {
  386. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  387. }
  388. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point3I& fv)
  389. {
  390. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  391. }
  392. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point4I& fv)
  393. {
  394. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  395. }
  396. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<F32>& fv)
  397. {
  398. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  399. }
  400. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point2F>& fv)
  401. {
  402. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  403. }
  404. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point3F>& fv)
  405. {
  406. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  407. }
  408. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point4F>& fv)
  409. {
  410. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  411. }
  412. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<S32>& fv)
  413. {
  414. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  415. }
  416. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point2I>& fv)
  417. {
  418. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  419. }
  420. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point3I>& fv)
  421. {
  422. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  423. }
  424. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point4I>& fv)
  425. {
  426. SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
  427. }
  428. #undef SET_CONSTANT
  429. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const MatrixF& mat, const GFXShaderConstType matrixType)
  430. {
  431. AssertFatal(handle, "Handle is NULL!" );
  432. AssertFatal(handle->isValid(), "Handle is not valid!" );
  433. AssertFatal(static_cast<const GFXD3D11ShaderConstHandle*>(handle), "Incorrect const buffer type!");
  434. const GFXD3D11ShaderConstHandle* h = static_cast<const GFXD3D11ShaderConstHandle*>(handle);
  435. AssertFatal(!h->isSampler(), "Handle is sampler constant!" );
  436. AssertFatal(h->mShader == mShader, "Mismatched shaders!");
  437. MatrixF transposed;
  438. if (matrixType == GFXSCT_Float4x3)
  439. {
  440. transposed = mat;
  441. }
  442. else
  443. {
  444. mat.transposeTo(transposed);
  445. }
  446. if (h->mInstancingConstant)
  447. {
  448. if ( matrixType == GFXSCT_Float4x4 )
  449. dMemcpy( mInstPtr+h->mPixelHandle.offset, mat, sizeof( mat ) );
  450. // TODO: Support 3x3 and 2x2 matricies?
  451. return;
  452. }
  453. if (h->mVertexConstant)
  454. mVertexConstBuffer->set(h->mVertexHandle, transposed, matrixType);
  455. if (h->mPixelConstant)
  456. mPixelConstBuffer->set(h->mPixelHandle, transposed, matrixType);
  457. }
  458. void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const MatrixF* mat, const U32 arraySize, const GFXShaderConstType matrixType)
  459. {
  460. AssertFatal(handle, "Handle is NULL!" );
  461. AssertFatal(handle->isValid(), "Handle is not valid!" );
  462. AssertFatal(static_cast<const GFXD3D11ShaderConstHandle*>(handle), "Incorrect const buffer type!");
  463. const GFXD3D11ShaderConstHandle* h = static_cast<const GFXD3D11ShaderConstHandle*>(handle);
  464. AssertFatal(!h->isSampler(), "Handle is sampler constant!" );
  465. AssertFatal(h->mShader == mShader, "Mismatched shaders!");
  466. static Vector<MatrixF> transposed;
  467. if (arraySize > transposed.size())
  468. transposed.setSize(arraySize);
  469. if (matrixType == GFXSCT_Float4x3)
  470. {
  471. dMemcpy(transposed.address(), mat, arraySize * sizeof(MatrixF));
  472. }
  473. else
  474. {
  475. for (U32 i = 0; i < arraySize; i++)
  476. mat[i].transposeTo(transposed[i]);
  477. }
  478. // TODO: Maybe support this in the future?
  479. if (h->mInstancingConstant)
  480. return;
  481. if (h->mVertexConstant)
  482. mVertexConstBuffer->set(h->mVertexHandle, transposed.begin(), arraySize, matrixType);
  483. if (h->mPixelConstant)
  484. mPixelConstBuffer->set(h->mPixelHandle, transposed.begin(), arraySize, matrixType);
  485. }
  486. const String GFXD3D11ShaderConstBuffer::describeSelf() const
  487. {
  488. String ret;
  489. ret = String(" GFXD3D11ShaderConstBuffer\n");
  490. for (U32 i = 0; i < mVertexConstBufferLayout->getParameterCount(); i++)
  491. {
  492. GenericConstBufferLayout::ParamDesc pd;
  493. mVertexConstBufferLayout->getDesc(i, pd);
  494. ret += String::ToString(" Constant name: %s", pd.name);
  495. }
  496. return ret;
  497. }
  498. void GFXD3D11ShaderConstBuffer::zombify()
  499. {
  500. }
  501. void GFXD3D11ShaderConstBuffer::resurrect()
  502. {
  503. }
  504. bool GFXD3D11ShaderConstBuffer::isDirty()
  505. {
  506. bool ret = mVertexConstBuffer->isDirty();
  507. ret |= mPixelConstBuffer->isDirty();
  508. return ret;
  509. }
  510. void GFXD3D11ShaderConstBuffer::activate( GFXD3D11ShaderConstBuffer *prevShaderBuffer )
  511. {
  512. PROFILE_SCOPE(GFXD3D11ShaderConstBuffer_activate);
  513. // NOTE: This is a really critical function as it gets
  514. // called between every draw call to update the constants.
  515. //
  516. // Alot of the calls here are inlined... be careful
  517. // what you change.
  518. // If the buffer has changed we need to compare it
  519. // with the new buffer to see if we can skip copying
  520. // equal buffer content.
  521. //
  522. // If the buffer hasn't changed then we only will
  523. // be copying the changes that have occured since
  524. // the last activate call.
  525. if ( prevShaderBuffer != this )
  526. {
  527. // If the previous buffer is dirty, than we can't compare
  528. // against it, because it hasn't sent its contents to the
  529. // card yet and must be copied.
  530. if ( prevShaderBuffer && !prevShaderBuffer->isDirty() )
  531. {
  532. PROFILE_SCOPE(GFXD3D11ShaderConstBuffer_activate_dirty_check_1);
  533. // If the buffer content is equal then we set the dirty
  534. // flag to false knowing the current state of the card matches
  535. // the new buffer.
  536. //
  537. // If the content is not equal we set the dirty flag to
  538. // true which causes the full content of the buffer to be
  539. // copied to the card.
  540. //
  541. mVertexConstBuffer->setDirty( !prevShaderBuffer->mVertexConstBuffer->isEqual( mVertexConstBuffer ) );
  542. mPixelConstBuffer->setDirty( !prevShaderBuffer->mPixelConstBuffer->isEqual( mPixelConstBuffer ) );
  543. }
  544. else
  545. {
  546. // This happens rarely... but it can happen.
  547. // We copy the entire dirty state to the card.
  548. PROFILE_SCOPE(GFXD3D11ShaderConstBuffer_activate_dirty_check_2);
  549. mVertexConstBuffer->setDirty( true );
  550. mPixelConstBuffer->setDirty( true );
  551. }
  552. }
  553. ID3D11DeviceContext* devCtx = D3D11DEVICECONTEXT;
  554. D3D11_MAPPED_SUBRESOURCE pConstData;
  555. ZeroMemory(&pConstData, sizeof(D3D11_MAPPED_SUBRESOURCE));
  556. const U8* buf;
  557. U32 nbBuffers = 0;
  558. if(mVertexConstBuffer->isDirty())
  559. {
  560. const Vector<ConstSubBufferDesc> &subBuffers = mVertexConstBufferLayout->getSubBufferDesc();
  561. // TODO: This is not very effecient updating the whole lot, re-implement the dirty system to work with multiple constant buffers.
  562. // TODO: Implement DX 11.1 UpdateSubresource1 which supports updating ranges with constant buffers
  563. buf = mVertexConstBuffer->getEntireBuffer();
  564. for (U32 i = 0; i < subBuffers.size(); ++i)
  565. {
  566. const ConstSubBufferDesc &desc = subBuffers[i];
  567. devCtx->UpdateSubresource(mConstantBuffersV[i], 0, NULL, buf + desc.start, desc.size, 0);
  568. nbBuffers++;
  569. }
  570. devCtx->VSSetConstantBuffers(0, nbBuffers, mConstantBuffersV);
  571. }
  572. nbBuffers = 0;
  573. if(mPixelConstBuffer->isDirty())
  574. {
  575. const Vector<ConstSubBufferDesc> &subBuffers = mPixelConstBufferLayout->getSubBufferDesc();
  576. // TODO: This is not very effecient updating the whole lot, re-implement the dirty system to work with multiple constant buffers.
  577. // TODO: Implement DX 11.1 UpdateSubresource1 which supports updating ranges with constant buffers
  578. buf = mPixelConstBuffer->getEntireBuffer();
  579. for (U32 i = 0; i < subBuffers.size(); ++i)
  580. {
  581. const ConstSubBufferDesc &desc = subBuffers[i];
  582. devCtx->UpdateSubresource(mConstantBuffersP[i], 0, NULL, buf + desc.start, desc.size, 0);
  583. nbBuffers++;
  584. }
  585. devCtx->PSSetConstantBuffers(0, nbBuffers, mConstantBuffersP);
  586. }
  587. #ifdef TORQUE_DEBUG
  588. // Make sure all the constants for this buffer were assigned.
  589. if(mWasLost)
  590. {
  591. mVertexConstBuffer->assertUnassignedConstants( mShader->getVertexShaderFile().c_str() );
  592. mPixelConstBuffer->assertUnassignedConstants( mShader->getPixelShaderFile().c_str() );
  593. }
  594. #endif
  595. // Clear the lost state.
  596. mWasLost = false;
  597. }
  598. void GFXD3D11ShaderConstBuffer::onShaderReload( GFXD3D11Shader *shader )
  599. {
  600. AssertFatal( shader == mShader, "GFXD3D11ShaderConstBuffer::onShaderReload is hosed!" );
  601. // release constant buffers
  602. for (U32 i = 0; i < CBUFFER_MAX; ++i)
  603. {
  604. SAFE_RELEASE(mConstantBuffersP[i]);
  605. SAFE_RELEASE(mConstantBuffersV[i]);
  606. }
  607. SAFE_DELETE( mVertexConstBuffer );
  608. SAFE_DELETE( mPixelConstBuffer );
  609. AssertFatal( mVertexConstBufferLayout == shader->mVertexConstBufferLayout, "GFXD3D11ShaderConstBuffer::onShaderReload is hosed!" );
  610. AssertFatal( mPixelConstBufferLayout == shader->mPixelConstBufferLayout, "GFXD3D11ShaderConstBuffer::onShaderReload is hosed!" );
  611. mVertexConstBuffer = new GenericConstBuffer( mVertexConstBufferLayout );
  612. mPixelConstBuffer = new GenericConstBuffer( mPixelConstBufferLayout );
  613. _createBuffers();
  614. // Set the lost state.
  615. mWasLost = true;
  616. }
  617. //------------------------------------------------------------------------------
  618. GFXD3D11Shader::GFXD3D11Shader()
  619. {
  620. VECTOR_SET_ASSOCIATION( mShaderConsts );
  621. AssertFatal(D3D11DEVICE, "Invalid device for shader.");
  622. mVertShader = NULL;
  623. mPixShader = NULL;
  624. mVertexConstBufferLayout = NULL;
  625. mPixelConstBufferLayout = NULL;
  626. if( smD3DInclude == NULL )
  627. smD3DInclude = new gfxD3D11Include;
  628. }
  629. //------------------------------------------------------------------------------
  630. GFXD3D11Shader::~GFXD3D11Shader()
  631. {
  632. for (HandleMap::Iterator i = mHandles.begin(); i != mHandles.end(); i++)
  633. delete i->value;
  634. // delete const buffer layouts
  635. SAFE_DELETE(mVertexConstBufferLayout);
  636. SAFE_DELETE(mPixelConstBufferLayout);
  637. // release shaders
  638. SAFE_RELEASE(mVertShader);
  639. SAFE_RELEASE(mPixShader);
  640. //maybe add SAFE_RELEASE(mVertexCode) ?
  641. }
  642. bool GFXD3D11Shader::_init()
  643. {
  644. PROFILE_SCOPE( GFXD3D11Shader_Init );
  645. SAFE_RELEASE(mVertShader);
  646. SAFE_RELEASE(mPixShader);
  647. // Create the macro array including the system wide macros.
  648. const U32 macroCount = smGlobalMacros.size() + mMacros.size() + 2;
  649. FrameTemp<D3D_SHADER_MACRO> d3dMacros( macroCount );
  650. for ( U32 i=0; i < smGlobalMacros.size(); i++ )
  651. {
  652. d3dMacros[i].Name = smGlobalMacros[i].name.c_str();
  653. d3dMacros[i].Definition = smGlobalMacros[i].value.c_str();
  654. }
  655. for ( U32 i=0; i < mMacros.size(); i++ )
  656. {
  657. d3dMacros[i+smGlobalMacros.size()].Name = mMacros[i].name.c_str();
  658. d3dMacros[i+smGlobalMacros.size()].Definition = mMacros[i].value.c_str();
  659. }
  660. d3dMacros[macroCount - 2].Name = "TORQUE_SM";
  661. d3dMacros[macroCount - 2].Definition = D3D11->getShaderModel().c_str();
  662. memset(&d3dMacros[macroCount - 1], 0, sizeof(D3D_SHADER_MACRO));
  663. if ( !mVertexConstBufferLayout )
  664. mVertexConstBufferLayout = new GFXD3D11ConstBufferLayout();
  665. else
  666. mVertexConstBufferLayout->clear();
  667. if ( !mPixelConstBufferLayout )
  668. mPixelConstBufferLayout = new GFXD3D11ConstBufferLayout();
  669. else
  670. mPixelConstBufferLayout->clear();
  671. mSamplerDescriptions.clear();
  672. mShaderConsts.clear();
  673. String vertTarget = D3D11->getVertexShaderTarget();
  674. String pixTarget = D3D11->getPixelShaderTarget();
  675. if ( !Con::getBoolVariable( "$shaders::forceLoadCSF", false ) )
  676. {
  677. if (!mVertexFile.isEmpty() && !_compileShader( mVertexFile, vertTarget, d3dMacros, mVertexConstBufferLayout, mSamplerDescriptions ) )
  678. return false;
  679. if (!mPixelFile.isEmpty() && !_compileShader( mPixelFile, pixTarget, d3dMacros, mPixelConstBufferLayout, mSamplerDescriptions ) )
  680. return false;
  681. }
  682. else
  683. {
  684. if ( !_loadCompiledOutput( mVertexFile, vertTarget, mVertexConstBufferLayout, mSamplerDescriptions ) )
  685. {
  686. if ( smLogErrors )
  687. Con::errorf( "GFXD3D11Shader::init - Unable to load precompiled vertex shader for '%s'.", mVertexFile.getFullPath().c_str() );
  688. return false;
  689. }
  690. if ( !_loadCompiledOutput( mPixelFile, pixTarget, mPixelConstBufferLayout, mSamplerDescriptions ) )
  691. {
  692. if ( smLogErrors )
  693. Con::errorf( "GFXD3D11Shader::init - Unable to load precompiled pixel shader for '%s'.", mPixelFile.getFullPath().c_str() );
  694. return false;
  695. }
  696. }
  697. // Existing handles are resored to an uninitialized state.
  698. // Those that are found when parsing the layout parameters
  699. // will then be re-initialized.
  700. HandleMap::Iterator iter = mHandles.begin();
  701. for ( ; iter != mHandles.end(); iter++ )
  702. (iter->value)->clear();
  703. _buildShaderConstantHandles(mVertexConstBufferLayout, true);
  704. _buildShaderConstantHandles(mPixelConstBufferLayout, false);
  705. _buildSamplerShaderConstantHandles( mSamplerDescriptions );
  706. _buildInstancingShaderConstantHandles();
  707. // Notify any existing buffers that the buffer
  708. // layouts have changed and they need to update.
  709. Vector<GFXShaderConstBuffer*>::iterator biter = mActiveBuffers.begin();
  710. for ( ; biter != mActiveBuffers.end(); biter++ )
  711. ((GFXD3D11ShaderConstBuffer*)(*biter))->onShaderReload( this );
  712. return true;
  713. }
  714. bool GFXD3D11Shader::_compileShader( const Torque::Path &filePath,
  715. const String& target,
  716. const D3D_SHADER_MACRO *defines,
  717. GenericConstBufferLayout* bufferLayout,
  718. Vector<GFXShaderConstDesc> &samplerDescriptions )
  719. {
  720. PROFILE_SCOPE( GFXD3D11Shader_CompileShader );
  721. using namespace Torque;
  722. HRESULT res = E_FAIL;
  723. ID3DBlob* code = NULL;
  724. ID3DBlob* errorBuff = NULL;
  725. ID3D11ShaderReflection* reflectionTable = NULL;
  726. #ifdef TORQUE_DEBUG
  727. U32 flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS;
  728. #else
  729. U32 flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3; //TODO double check load times with D3DCOMPILE_OPTIMIZATION_LEVEL3
  730. //recommended flags for NSight, uncomment to use. NSight should be used in release mode only. *Still works with above flags however
  731. //flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_PREFER_FLOW_CONTROL | D3DCOMPILE_SKIP_OPTIMIZATION;
  732. #endif
  733. #ifdef D3D11_DEBUG_SPEW
  734. Con::printf( "Compiling Shader: '%s'", filePath.getFullPath().c_str() );
  735. #endif
  736. // Is it an HLSL shader?
  737. if(filePath.getExtension().equal("hlsl", String::NoCase))
  738. {
  739. // Set this so that the D3DInclude::Open will have this
  740. // information for relative paths.
  741. smD3DInclude->setPath(filePath.getRootAndPath());
  742. FileStream s;
  743. if (!s.open(filePath, Torque::FS::File::Read))
  744. {
  745. AssertISV(false, avar("GFXD3D11Shader::initShader - failed to open shader '%s'.", filePath.getFullPath().c_str()));
  746. if ( smLogErrors )
  747. Con::errorf( "GFXD3D11Shader::_compileShader - Failed to open shader file '%s'.", filePath.getFullPath().c_str() );
  748. return false;
  749. }
  750. // Convert the path which might have virtualized
  751. // mount paths to a real file system path.
  752. Torque::Path realPath;
  753. if (!FS::GetFSPath( filePath, realPath))
  754. realPath = filePath;
  755. U32 bufSize = s.getStreamSize();
  756. FrameAllocatorMarker fam;
  757. char *buffer = NULL;
  758. buffer = (char*)fam.alloc(bufSize + 1);
  759. s.read(bufSize, buffer);
  760. buffer[bufSize] = 0;
  761. res = D3DCompile(buffer, bufSize, realPath.getFullPath().c_str(), defines, smD3DInclude, "main", target, flags, 0, &code, &errorBuff);
  762. }
  763. // Is it a precompiled obj shader?
  764. else if(filePath.getExtension().equal("obj", String::NoCase))
  765. {
  766. FileStream s;
  767. if(!s.open(filePath, Torque::FS::File::Read))
  768. {
  769. AssertISV(false, avar("GFXD3D11Shader::initShader - failed to open shader '%s'.", filePath.getFullPath().c_str()));
  770. if ( smLogErrors )
  771. Con::errorf( "GFXD3D11Shader::_compileShader - Failed to open shader file '%s'.", filePath.getFullPath().c_str() );
  772. return false;
  773. }
  774. res = D3DCreateBlob(s.getStreamSize(), &code);
  775. AssertISV(SUCCEEDED(res), "Unable to create buffer!");
  776. s.read(s.getStreamSize(), code->GetBufferPointer());
  777. }
  778. else
  779. {
  780. if (smLogErrors)
  781. Con::errorf("GFXD3D11Shader::_compileShader - Unsupported shader file type '%s'.", filePath.getFullPath().c_str());
  782. return false;
  783. }
  784. if(errorBuff)
  785. {
  786. // remove \n at end of buffer
  787. U8 *buffPtr = (U8*) errorBuff->GetBufferPointer();
  788. U32 len = dStrlen( (const char*) buffPtr );
  789. buffPtr[len-1] = '\0';
  790. if(FAILED(res))
  791. {
  792. if(smLogErrors)
  793. Con::errorf("failed to compile shader: %s", buffPtr);
  794. }
  795. else
  796. {
  797. if(smLogWarnings)
  798. Con::errorf("shader compiled with warning(s): %s", buffPtr);
  799. }
  800. }
  801. else if (code == NULL && smLogErrors)
  802. Con::errorf( "GFXD3D11Shader::_compileShader - no compiled code produced; possibly missing file '%s'.", filePath.getFullPath().c_str() );
  803. AssertISV(SUCCEEDED(res), "Unable to compile shader!");
  804. if(code != NULL)
  805. {
  806. #ifndef TORQUE_SHIPPING
  807. if(gDisassembleAllShaders)
  808. {
  809. ID3DBlob* disassem = NULL;
  810. D3DDisassemble(code->GetBufferPointer(), code->GetBufferSize(), 0, NULL, &disassem);
  811. mDissasembly = (const char*)disassem->GetBufferPointer();
  812. String filename = filePath.getFullPath();
  813. filename.replace( ".hlsl", "_dis.txt" );
  814. FileStream *fstream = FileStream::createAndOpen( filename, Torque::FS::File::Write );
  815. if ( fstream )
  816. {
  817. fstream->write( mDissasembly );
  818. fstream->close();
  819. delete fstream;
  820. }
  821. SAFE_RELEASE(disassem);
  822. }
  823. #endif
  824. if (target.compare("ps_", 3) == 0)
  825. res = D3D11DEVICE->CreatePixelShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, &mPixShader);
  826. else if (target.compare("vs_", 3) == 0)
  827. res = D3D11DEVICE->CreateVertexShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, &mVertShader);
  828. if (FAILED(res))
  829. {
  830. AssertFatal(false, "D3D11Shader::_compilershader- failed to create shader");
  831. }
  832. if(res == S_OK){
  833. HRESULT reflectionResult = D3DReflect(code->GetBufferPointer(), code->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&reflectionTable);
  834. if(FAILED(reflectionResult))
  835. AssertFatal(false, "D3D11Shader::_compilershader - Failed to get shader reflection table interface");
  836. }
  837. if(res == S_OK)
  838. _getShaderConstants(reflectionTable, bufferLayout, samplerDescriptions);
  839. #ifdef TORQUE_ENABLE_CSF_GENERATION
  840. // Ok, we've got a valid shader and constants, let's write them all out.
  841. if (!_saveCompiledOutput(filePath, code, bufferLayout) && smLogErrors)
  842. Con::errorf( "GFXD3D11Shader::_compileShader - Unable to save shader compile output for: %s",
  843. filePath.getFullPath().c_str());
  844. #endif
  845. if(FAILED(res) && smLogErrors)
  846. Con::errorf("GFXD3D11Shader::_compileShader - Unable to create shader for '%s'.", filePath.getFullPath().c_str());
  847. }
  848. //bool result = code && SUCCEEDED(res) && HasValidConstants;
  849. bool result = code && SUCCEEDED(res);
  850. #ifdef TORQUE_DEBUG
  851. if (target.compare("vs_", 3) == 0)
  852. {
  853. String vertShader = mVertexFile.getFileName();
  854. mVertShader->SetPrivateData(WKPDID_D3DDebugObjectName, vertShader.size(), vertShader.c_str());
  855. }
  856. else if (target.compare("ps_", 3) == 0)
  857. {
  858. String pixelShader = mPixelFile.getFileName();
  859. mPixShader->SetPrivateData(WKPDID_D3DDebugObjectName, pixelShader.size(), pixelShader.c_str());
  860. }
  861. #endif
  862. SAFE_RELEASE(code);
  863. SAFE_RELEASE(reflectionTable);
  864. SAFE_RELEASE(errorBuff);
  865. return result;
  866. }
  867. void GFXD3D11Shader::_getShaderConstants( ID3D11ShaderReflection *pTable,
  868. GenericConstBufferLayout *bufferLayoutIn,
  869. Vector<GFXShaderConstDesc> &samplerDescriptions )
  870. {
  871. PROFILE_SCOPE( GFXD3D11Shader_GetShaderConstants );
  872. AssertFatal(pTable, "NULL constant table not allowed, is this an assembly shader?");
  873. GFXD3D11ConstBufferLayout *bufferLayout = (GFXD3D11ConstBufferLayout*)bufferLayoutIn;
  874. Vector<ConstSubBufferDesc> &subBuffers = bufferLayout->getSubBufferDesc();
  875. subBuffers.clear();
  876. D3D11_SHADER_DESC tableDesc;
  877. HRESULT hr = pTable->GetDesc(&tableDesc);
  878. if (FAILED(hr))
  879. {
  880. AssertFatal(false, "Shader Reflection table unable to be created");
  881. }
  882. //offset for sub constant buffers
  883. U32 bufferOffset = 0;
  884. for (U32 i = 0; i < tableDesc.ConstantBuffers; i++)
  885. {
  886. ID3D11ShaderReflectionConstantBuffer* constantBuffer = pTable->GetConstantBufferByIndex(i);
  887. D3D11_SHADER_BUFFER_DESC constantBufferDesc;
  888. if (constantBuffer->GetDesc(&constantBufferDesc) == S_OK)
  889. {
  890. #ifdef TORQUE_DEBUG
  891. AssertFatal(constantBufferDesc.Type == D3D_CT_CBUFFER, "Only scalar cbuffers supported for now.");
  892. if (dStrcmp(constantBufferDesc.Name, "$Globals") != 0 && dStrcmp(constantBufferDesc.Name, "$Params") != 0)
  893. AssertFatal(false, "Only $Global and $Params cbuffer supported for now.");
  894. #endif
  895. #ifdef D3D11_DEBUG_SPEW
  896. Con::printf("Constant Buffer Name: %s", constantBufferDesc.Name);
  897. #endif
  898. for(U32 j =0; j< constantBufferDesc.Variables; j++)
  899. {
  900. GFXShaderConstDesc desc;
  901. ID3D11ShaderReflectionVariable* variable = constantBuffer->GetVariableByIndex(j);
  902. D3D11_SHADER_VARIABLE_DESC variableDesc;
  903. D3D11_SHADER_TYPE_DESC variableTypeDesc;
  904. variable->GetDesc(&variableDesc);
  905. ID3D11ShaderReflectionType* variableType =variable->GetType();
  906. variableType->GetDesc(&variableTypeDesc);
  907. desc.name = String(variableDesc.Name);
  908. // Prepend a "$" if it doesn't exist. Just to make things consistent.
  909. if (desc.name.find("$") != 0)
  910. desc.name = String::ToString("$%s", desc.name.c_str());
  911. bool unusedVar = variableDesc.uFlags & D3D_SVF_USED ? false : true;
  912. if (variableTypeDesc.Elements == 0)
  913. desc.arraySize = 1;
  914. else
  915. desc.arraySize = variableTypeDesc.Elements;
  916. #ifdef D3D11_DEBUG_SPEW
  917. Con::printf("Variable Name %s:, offset: %d, size: %d, constantDesc.Elements: %d", desc.name.c_str(), variableDesc.StartOffset, variableDesc.Size, desc.arraySize);
  918. #endif
  919. if (_convertShaderVariable(variableTypeDesc, desc))
  920. {
  921. //The HLSL compiler for 4.0 and above doesn't strip out unused registered constants. We'll have to do it manually
  922. if (!unusedVar)
  923. {
  924. mShaderConsts.push_back(desc);
  925. U32 alignBytes = getAlignmentValue(desc.constType);
  926. U32 paramSize = variableDesc.Size;
  927. bufferLayout->addParameter( desc.name,
  928. desc.constType,
  929. variableDesc.StartOffset + bufferOffset,
  930. paramSize,
  931. desc.arraySize,
  932. alignBytes);
  933. } //unusedVar
  934. } //_convertShaderVariable
  935. } //constantBufferDesc.Variables
  936. // fill out our const sub buffer sizes etc
  937. ConstSubBufferDesc subBufferDesc;
  938. subBufferDesc.size = constantBufferDesc.Size;
  939. subBufferDesc.start = bufferOffset;
  940. subBuffers.push_back(subBufferDesc);
  941. // increase our bufferOffset by the constant buffer size
  942. bufferOffset += constantBufferDesc.Size;
  943. }
  944. else
  945. AssertFatal(false, "Unable to get shader constant description! (may need more elements of constantDesc");
  946. }
  947. // Set buffer size to the aligned size
  948. bufferLayout->setSize(bufferOffset);
  949. //get the sampler descriptions from the resource binding description
  950. U32 resourceCount = tableDesc.BoundResources;
  951. for (U32 i = 0; i < resourceCount; i++)
  952. {
  953. GFXShaderConstDesc desc;
  954. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  955. pTable->GetResourceBindingDesc(i, &bindDesc);
  956. switch (bindDesc.Type)
  957. {
  958. case D3D_SIT_SAMPLER:
  959. // Prepend a "$" if it doesn't exist. Just to make things consistent.
  960. desc.name = String(bindDesc.Name);
  961. if (desc.name.find("$") != 0)
  962. desc.name = String::ToString("$%s", desc.name.c_str());
  963. desc.constType = GFXSCT_Sampler;
  964. desc.arraySize = bindDesc.BindPoint;
  965. samplerDescriptions.push_back(desc);
  966. break;
  967. }
  968. }
  969. }
  970. bool GFXD3D11Shader::_convertShaderVariable(const D3D11_SHADER_TYPE_DESC &typeDesc, GFXShaderConstDesc &desc)
  971. {
  972. switch (typeDesc.Type)
  973. {
  974. case D3D_SVT_INT:
  975. {
  976. switch (typeDesc.Class)
  977. {
  978. case D3D_SVC_SCALAR:
  979. desc.constType = GFXSCT_Int;
  980. break;
  981. case D3D_SVC_VECTOR:
  982. {
  983. switch (typeDesc.Columns)
  984. {
  985. case 1:
  986. desc.constType = GFXSCT_Int;
  987. break;
  988. case 2:
  989. desc.constType = GFXSCT_Int2;
  990. break;
  991. case 3:
  992. desc.constType = GFXSCT_Int3;
  993. break;
  994. case 4:
  995. desc.constType = GFXSCT_Int4;
  996. break;
  997. }
  998. }
  999. break;
  1000. }
  1001. break;
  1002. }
  1003. case D3D_SVT_FLOAT:
  1004. {
  1005. switch (typeDesc.Class)
  1006. {
  1007. case D3D_SVC_SCALAR:
  1008. desc.constType = GFXSCT_Float;
  1009. break;
  1010. case D3D_SVC_VECTOR:
  1011. {
  1012. switch (typeDesc.Columns)
  1013. {
  1014. case 1:
  1015. desc.constType = GFXSCT_Float;
  1016. break;
  1017. case 2:
  1018. desc.constType = GFXSCT_Float2;
  1019. break;
  1020. case 3:
  1021. desc.constType = GFXSCT_Float3;
  1022. break;
  1023. case 4:
  1024. desc.constType = GFXSCT_Float4;
  1025. break;
  1026. }
  1027. }
  1028. break;
  1029. case D3D_SVC_MATRIX_ROWS:
  1030. case D3D_SVC_MATRIX_COLUMNS:
  1031. {
  1032. switch (typeDesc.Rows)
  1033. {
  1034. case 3:
  1035. desc.constType = typeDesc.Columns == 4 ? GFXSCT_Float3x4 : GFXSCT_Float3x3;
  1036. break;
  1037. case 4:
  1038. desc.constType = typeDesc.Columns == 3 ? GFXSCT_Float4x3 : GFXSCT_Float4x4;
  1039. break;
  1040. }
  1041. }
  1042. break;
  1043. case D3D_SVC_OBJECT:
  1044. case D3D_SVC_STRUCT:
  1045. return false;
  1046. }
  1047. }
  1048. break;
  1049. default:
  1050. AssertFatal(false, "Unknown shader constant class enum");
  1051. break;
  1052. }
  1053. return true;
  1054. }
  1055. const U32 GFXD3D11Shader::smCompiledShaderTag = MakeFourCC('t','c','s','f');
  1056. bool GFXD3D11Shader::_saveCompiledOutput( const Torque::Path &filePath,
  1057. ID3DBlob *buffer,
  1058. GenericConstBufferLayout *bufferLayout,
  1059. Vector<GFXShaderConstDesc> &samplerDescriptions )
  1060. {
  1061. Torque::Path outputPath(filePath);
  1062. outputPath.setExtension("csf"); // "C"ompiled "S"hader "F"ile (fancy!)
  1063. FileStream f;
  1064. if (!f.open(outputPath, Torque::FS::File::Write))
  1065. return false;
  1066. if (!f.write(smCompiledShaderTag))
  1067. return false;
  1068. // We could reverse engineer the structure in the compiled output, but this
  1069. // is a bit easier because we can just read it into the struct that we want.
  1070. if (!bufferLayout->write(&f))
  1071. return false;
  1072. U32 bufferSize = buffer->GetBufferSize();
  1073. if (!f.write(bufferSize))
  1074. return false;
  1075. if (!f.write(bufferSize, buffer->GetBufferPointer()))
  1076. return false;
  1077. // Write out sampler descriptions.
  1078. f.write( samplerDescriptions.size() );
  1079. for ( U32 i = 0; i < samplerDescriptions.size(); i++ )
  1080. {
  1081. f.write( samplerDescriptions[i].name );
  1082. f.write( (U32)(samplerDescriptions[i].constType) );
  1083. f.write( samplerDescriptions[i].arraySize );
  1084. }
  1085. f.close();
  1086. return true;
  1087. }
  1088. bool GFXD3D11Shader::_loadCompiledOutput( const Torque::Path &filePath,
  1089. const String &target,
  1090. GenericConstBufferLayout *bufferLayout,
  1091. Vector<GFXShaderConstDesc> &samplerDescriptions )
  1092. {
  1093. Torque::Path outputPath(filePath);
  1094. outputPath.setExtension("csf"); // "C"ompiled "S"hader "F"ile (fancy!)
  1095. FileStream f;
  1096. if (!f.open(outputPath, Torque::FS::File::Read))
  1097. return false;
  1098. U32 fileTag;
  1099. if (!f.read(&fileTag))
  1100. return false;
  1101. if (fileTag != smCompiledShaderTag)
  1102. return false;
  1103. if (!bufferLayout->read(&f))
  1104. return false;
  1105. U32 bufferSize;
  1106. if (!f.read(&bufferSize))
  1107. return false;
  1108. U32 waterMark = FrameAllocator::getWaterMark();
  1109. DWORD* buffer = static_cast<DWORD*>(FrameAllocator::alloc(bufferSize));
  1110. if (!f.read(bufferSize, buffer))
  1111. return false;
  1112. // Read sampler descriptions.
  1113. U32 samplerCount;
  1114. f.read( &samplerCount );
  1115. for ( U32 i = 0; i < samplerCount; i++ )
  1116. {
  1117. GFXShaderConstDesc samplerDesc;
  1118. f.read( &(samplerDesc.name) );
  1119. f.read( (U32*)&(samplerDesc.constType) );
  1120. f.read( &(samplerDesc.arraySize) );
  1121. samplerDescriptions.push_back( samplerDesc );
  1122. }
  1123. f.close();
  1124. HRESULT res;
  1125. if (target.compare("ps_", 3) == 0)
  1126. res = D3D11DEVICE->CreatePixelShader(buffer, bufferSize, NULL, &mPixShader);
  1127. else
  1128. res = D3D11DEVICE->CreateVertexShader(buffer, bufferSize, NULL, &mVertShader);
  1129. AssertFatal(SUCCEEDED(res), "Unable to load shader!");
  1130. FrameAllocator::setWaterMark(waterMark);
  1131. return SUCCEEDED(res);
  1132. }
  1133. void GFXD3D11Shader::_buildShaderConstantHandles(GenericConstBufferLayout* layout, bool vertexConst)
  1134. {
  1135. for (U32 i = 0; i < layout->getParameterCount(); i++)
  1136. {
  1137. GenericConstBufferLayout::ParamDesc pd;
  1138. layout->getDesc(i, pd);
  1139. GFXD3D11ShaderConstHandle* handle;
  1140. HandleMap::Iterator j = mHandles.find(pd.name);
  1141. if (j != mHandles.end())
  1142. {
  1143. handle = j->value;
  1144. handle->mShader = this;
  1145. handle->setValid( true );
  1146. }
  1147. else
  1148. {
  1149. handle = new GFXD3D11ShaderConstHandle();
  1150. handle->mShader = this;
  1151. mHandles[pd.name] = handle;
  1152. handle->setValid( true );
  1153. }
  1154. if (vertexConst)
  1155. {
  1156. handle->mVertexConstant = true;
  1157. handle->mVertexHandle = pd;
  1158. }
  1159. else
  1160. {
  1161. handle->mPixelConstant = true;
  1162. handle->mPixelHandle = pd;
  1163. }
  1164. }
  1165. }
  1166. void GFXD3D11Shader::_buildSamplerShaderConstantHandles( Vector<GFXShaderConstDesc> &samplerDescriptions )
  1167. {
  1168. Vector<GFXShaderConstDesc>::iterator iter = samplerDescriptions.begin();
  1169. for ( ; iter != samplerDescriptions.end(); iter++ )
  1170. {
  1171. const GFXShaderConstDesc &desc = *iter;
  1172. AssertFatal( desc.constType == GFXSCT_Sampler ||
  1173. desc.constType == GFXSCT_SamplerCube,
  1174. "GFXD3D11Shader::_buildSamplerShaderConstantHandles - Invalid samplerDescription type!" );
  1175. GFXD3D11ShaderConstHandle *handle;
  1176. HandleMap::Iterator j = mHandles.find(desc.name);
  1177. if ( j != mHandles.end() )
  1178. handle = j->value;
  1179. else
  1180. {
  1181. handle = new GFXD3D11ShaderConstHandle();
  1182. mHandles[desc.name] = handle;
  1183. }
  1184. handle->mShader = this;
  1185. handle->setValid( true );
  1186. handle->mPixelConstant = true;
  1187. handle->mPixelHandle.name = desc.name;
  1188. handle->mPixelHandle.constType = desc.constType;
  1189. handle->mPixelHandle.offset = desc.arraySize;
  1190. }
  1191. }
  1192. void GFXD3D11Shader::_buildInstancingShaderConstantHandles()
  1193. {
  1194. // If we have no instancing than just return
  1195. if (!mInstancingFormat)
  1196. return;
  1197. U32 offset = 0;
  1198. for ( U32 i=0; i < mInstancingFormat->getElementCount(); i++ )
  1199. {
  1200. const GFXVertexElement &element = mInstancingFormat->getElement( i );
  1201. String constName = String::ToString( "$%s", element.getSemantic().c_str() );
  1202. GFXD3D11ShaderConstHandle *handle;
  1203. HandleMap::Iterator j = mHandles.find( constName );
  1204. if ( j != mHandles.end() )
  1205. handle = j->value;
  1206. else
  1207. {
  1208. handle = new GFXD3D11ShaderConstHandle();
  1209. mHandles[ constName ] = handle;
  1210. }
  1211. handle->mShader = this;
  1212. handle->setValid( true );
  1213. handle->mInstancingConstant = true;
  1214. // We shouldn't have an instancing constant that is also
  1215. // a vertex or pixel constant! This means the shader features
  1216. // are confused as to what is instanced.
  1217. //
  1218. AssertFatal( !handle->mVertexConstant &&
  1219. !handle->mPixelConstant,
  1220. "GFXD3D11Shader::_buildInstancingShaderConstantHandles - Bad instanced constant!" );
  1221. // HACK: The GFXD3D11ShaderConstHandle will check mVertexConstant then
  1222. // fall back to reading the mPixelHandle values. We depend on this here
  1223. // and store the data we need in the mPixelHandle constant although its
  1224. // not a pixel shader constant.
  1225. //
  1226. handle->mPixelHandle.name = constName;
  1227. handle->mPixelHandle.offset = offset;
  1228. // If this is a matrix we will have 2 or 3 more of these
  1229. // semantics with the same name after it.
  1230. for ( ; i < mInstancingFormat->getElementCount(); i++ )
  1231. {
  1232. const GFXVertexElement &nextElement = mInstancingFormat->getElement( i );
  1233. if ( nextElement.getSemantic() != element.getSemantic() )
  1234. {
  1235. i--;
  1236. break;
  1237. }
  1238. offset += nextElement.getSizeInBytes();
  1239. }
  1240. }
  1241. }
  1242. GFXShaderConstBufferRef GFXD3D11Shader::allocConstBuffer()
  1243. {
  1244. if (mVertexConstBufferLayout && mPixelConstBufferLayout)
  1245. {
  1246. GFXD3D11ShaderConstBuffer* buffer = new GFXD3D11ShaderConstBuffer(this, mVertexConstBufferLayout, mPixelConstBufferLayout);
  1247. mActiveBuffers.push_back( buffer );
  1248. buffer->registerResourceWithDevice(getOwningDevice());
  1249. return buffer;
  1250. }
  1251. return NULL;
  1252. }
  1253. /// Returns a shader constant handle for name, if the variable doesn't exist NULL is returned.
  1254. GFXShaderConstHandle* GFXD3D11Shader::getShaderConstHandle(const String& name)
  1255. {
  1256. HandleMap::Iterator i = mHandles.find(name);
  1257. if ( i != mHandles.end() )
  1258. {
  1259. return i->value;
  1260. }
  1261. else
  1262. {
  1263. GFXD3D11ShaderConstHandle *handle = new GFXD3D11ShaderConstHandle();
  1264. handle->setValid( false );
  1265. handle->mShader = this;
  1266. mHandles[name] = handle;
  1267. return handle;
  1268. }
  1269. }
  1270. GFXShaderConstHandle* GFXD3D11Shader::findShaderConstHandle(const String& name)
  1271. {
  1272. HandleMap::Iterator i = mHandles.find(name);
  1273. if(i != mHandles.end())
  1274. return i->value;
  1275. else
  1276. {
  1277. return NULL;
  1278. }
  1279. }
  1280. const Vector<GFXShaderConstDesc>& GFXD3D11Shader::getShaderConstDesc() const
  1281. {
  1282. return mShaderConsts;
  1283. }
  1284. U32 GFXD3D11Shader::getAlignmentValue(const GFXShaderConstType constType) const
  1285. {
  1286. const U32 mRowSizeF = 16;
  1287. const U32 mRowSizeI = 16;
  1288. switch (constType)
  1289. {
  1290. case GFXSCT_Float :
  1291. case GFXSCT_Float2 :
  1292. case GFXSCT_Float3 :
  1293. case GFXSCT_Float4 :
  1294. return mRowSizeF;
  1295. break;
  1296. // Matrices
  1297. case GFXSCT_Float2x2 :
  1298. return mRowSizeF * 2;
  1299. break;
  1300. case GFXSCT_Float3x3 :
  1301. return mRowSizeF * 3;
  1302. break;
  1303. case GFXSCT_Float4x3:
  1304. return mRowSizeF * 3;
  1305. break;
  1306. case GFXSCT_Float4x4 :
  1307. return mRowSizeF * 4;
  1308. break;
  1309. //// Scalar
  1310. case GFXSCT_Int :
  1311. case GFXSCT_Int2 :
  1312. case GFXSCT_Int3 :
  1313. case GFXSCT_Int4 :
  1314. return mRowSizeI;
  1315. break;
  1316. default:
  1317. AssertFatal(false, "Unsupported type!");
  1318. return 0;
  1319. break;
  1320. }
  1321. }
  1322. void GFXD3D11Shader::zombify()
  1323. {
  1324. // Shaders don't need zombification
  1325. }
  1326. void GFXD3D11Shader::resurrect()
  1327. {
  1328. // Shaders are never zombies, and therefore don't have to be brought back.
  1329. }