gfxD3D11Shader.cpp 50 KB

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