processedMaterial.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 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 "materials/processedMaterial.h"
  24. #include "materials/sceneData.h"
  25. #include "materials/materialParameters.h"
  26. #include "materials/matTextureTarget.h"
  27. #include "materials/materialFeatureTypes.h"
  28. #include "materials/materialManager.h"
  29. #include "scene/sceneRenderState.h"
  30. #include "gfx/gfxPrimitiveBuffer.h"
  31. #include "gfx/gfxTextureManager.h"
  32. #include "gfx/sim/cubemapData.h"
  33. RenderPassData::RenderPassData()
  34. {
  35. reset();
  36. }
  37. void RenderPassData::reset()
  38. {
  39. for( U32 i = 0; i < Material::MAX_TEX_PER_PASS; ++ i )
  40. {
  41. destructInPlace( &mTexSlot[ i ] );
  42. mSamplerNames[ i ].clear();
  43. }
  44. dMemset( &mTexSlot, 0, sizeof(mTexSlot) );
  45. dMemset( &mTexType, 0, sizeof(mTexType) );
  46. mCubeMap = NULL;
  47. mNumTex = mNumTexReg = mStageNum = 0;
  48. mGlow = false;
  49. mBlendOp = Material::None;
  50. mFeatureData.clear();
  51. for (U32 i = 0; i < STATE_MAX; i++)
  52. mRenderStates[i] = NULL;
  53. }
  54. String RenderPassData::describeSelf() const
  55. {
  56. String desc;
  57. // Now write all the textures.
  58. String texName;
  59. for ( U32 i=0; i < Material::MAX_TEX_PER_PASS; i++ )
  60. {
  61. if ( mTexType[i] == Material::TexTarget )
  62. texName = ( mTexSlot[i].texTarget ) ? mTexSlot[i].texTarget->getName() : String("null_texTarget");
  63. else if ( mTexType[i] == Material::Cube && mCubeMap )
  64. texName = mCubeMap->getPath();
  65. else if ( mTexSlot[i].texObject )
  66. texName = mTexSlot[i].texObject->getPath();
  67. else
  68. continue;
  69. desc += String::ToString( "TexSlot %d: %d, %s\n", i, mTexType[i], texName.c_str() );
  70. }
  71. // Write out the first render state which is the
  72. // basis for all the other states and shoud be
  73. // enough to define the pass uniquely.
  74. desc += mRenderStates[0]->getDesc().describeSelf();
  75. return desc;
  76. }
  77. ProcessedMaterial::ProcessedMaterial()
  78. : mMaterial( NULL ),
  79. mCurrentParams( NULL ),
  80. mHasSetStageData( false ),
  81. mHasGlow( false ),
  82. mHasAccumulation( false ),
  83. mMaxStages( 0 ),
  84. mVertexFormat( NULL ),
  85. mUserObject( NULL )
  86. {
  87. VECTOR_SET_ASSOCIATION( mPasses );
  88. }
  89. ProcessedMaterial::~ProcessedMaterial()
  90. {
  91. T3D::for_each( mPasses.begin(), mPasses.end(), T3D::delete_pointer() );
  92. }
  93. void ProcessedMaterial::_setBlendState(Material::BlendOp blendOp, GFXStateBlockDesc& desc )
  94. {
  95. switch( blendOp )
  96. {
  97. case Material::Add:
  98. {
  99. desc.blendSrc = GFXBlendOne;
  100. desc.blendDest = GFXBlendOne;
  101. break;
  102. }
  103. case Material::AddAlpha:
  104. {
  105. desc.blendSrc = GFXBlendSrcAlpha;
  106. desc.blendDest = GFXBlendOne;
  107. break;
  108. }
  109. case Material::Mul:
  110. {
  111. desc.blendSrc = GFXBlendDestColor;
  112. desc.blendDest = GFXBlendInvSrcAlpha;
  113. break;
  114. }
  115. case Material::PreMul:
  116. {
  117. desc.blendSrc = GFXBlendOne;
  118. desc.blendDest = GFXBlendInvSrcAlpha;
  119. break;
  120. }
  121. case Material::LerpAlpha:
  122. {
  123. desc.blendSrc = GFXBlendSrcAlpha;
  124. desc.blendDest = GFXBlendInvSrcAlpha;
  125. break;
  126. }
  127. case Material::Sub:
  128. {
  129. desc.blendOp = GFXBlendOpSubtract;
  130. desc.blendSrc = GFXBlendOne;
  131. desc.blendDest = GFXBlendOne;
  132. break;
  133. }
  134. default:
  135. {
  136. // default to LerpAlpha
  137. desc.blendSrc = GFXBlendSrcAlpha;
  138. desc.blendDest = GFXBlendInvSrcAlpha;
  139. break;
  140. }
  141. }
  142. }
  143. void ProcessedMaterial::setBuffers(GFXVertexBufferHandleBase* vertBuffer, GFXPrimitiveBufferHandle* primBuffer)
  144. {
  145. GFX->setVertexBuffer( *vertBuffer );
  146. GFX->setPrimitiveBuffer( *primBuffer );
  147. }
  148. bool ProcessedMaterial::stepInstance()
  149. {
  150. AssertFatal( false, "ProcessedMaterial::stepInstance() - This type of material doesn't support instancing!" );
  151. return false;
  152. }
  153. String ProcessedMaterial::_getTexturePath(const String& filename)
  154. {
  155. // if '/', then path is specified, use it.
  156. if( filename.find('/') != String::NPos )
  157. {
  158. return filename;
  159. }
  160. // otherwise, construct path
  161. return mMaterial->getPath() + filename;
  162. }
  163. GFXTexHandle ProcessedMaterial::_createTexture( const char* filename, GFXTextureProfile *profile)
  164. {
  165. return GFXTexHandle( _getTexturePath(filename), profile, avar("%s() - NA (line %d)", __FUNCTION__, __LINE__) );
  166. }
  167. GFXTexHandle ProcessedMaterial::_createCompositeTexture(const char *filenameR, const char *filenameG, const char *filenameB, const char *filenameA, U32 inputKey[4], GFXTextureProfile *profile)
  168. {
  169. return GFXTexHandle(_getTexturePath(filenameR), _getTexturePath(filenameG), _getTexturePath(filenameB), _getTexturePath(filenameA), inputKey, profile, avar("%s() - NA (line %d)", __FUNCTION__, __LINE__));
  170. }
  171. void ProcessedMaterial::addStateBlockDesc(const GFXStateBlockDesc& sb)
  172. {
  173. mUserDefined = sb;
  174. }
  175. void ProcessedMaterial::_initStateBlockTemplates(GFXStateBlockDesc& stateTranslucent, GFXStateBlockDesc& stateReflect)
  176. {
  177. // Translucency
  178. stateTranslucent.blendDefined = true;
  179. stateTranslucent.blendEnable = mMaterial->mTranslucentBlendOp != Material::None;
  180. _setBlendState(mMaterial->mTranslucentBlendOp, stateTranslucent);
  181. stateTranslucent.zDefined = true;
  182. stateTranslucent.zWriteEnable = mMaterial->mTranslucentZWrite;
  183. stateTranslucent.alphaDefined = true;
  184. stateTranslucent.alphaTestEnable = mMaterial->mAlphaTest;
  185. stateTranslucent.alphaTestRef = mMaterial->mAlphaRef;
  186. stateTranslucent.alphaTestFunc = GFXCmpGreaterEqual;
  187. stateTranslucent.samplersDefined = true;
  188. // Reflect
  189. stateReflect.cullDefined = true;
  190. stateReflect.cullMode = mMaterial->mDoubleSided ? GFXCullNone : GFXCullCW;
  191. }
  192. void ProcessedMaterial::_initRenderPassDataStateBlocks()
  193. {
  194. for (U32 pass = 0; pass < mPasses.size(); pass++)
  195. _initRenderStateStateBlocks( mPasses[pass] );
  196. }
  197. void ProcessedMaterial::_initPassStateBlock( RenderPassData *rpd, GFXStateBlockDesc &result )
  198. {
  199. if ( rpd->mBlendOp != Material::None )
  200. {
  201. result.blendDefined = true;
  202. result.blendEnable = true;
  203. _setBlendState( rpd->mBlendOp, result );
  204. }
  205. if (mMaterial && mMaterial->isDoubleSided())
  206. {
  207. result.cullDefined = true;
  208. result.cullMode = GFXCullNone;
  209. }
  210. if(mMaterial && mMaterial->mAlphaTest)
  211. {
  212. result.alphaDefined = true;
  213. result.alphaTestEnable = mMaterial->mAlphaTest;
  214. result.alphaTestRef = mMaterial->mAlphaRef;
  215. result.alphaTestFunc = GFXCmpGreaterEqual;
  216. }
  217. result.samplersDefined = true;
  218. NamedTexTarget *texTarget;
  219. U32 maxAnisotropy = 1;
  220. if (mMaterial && mMaterial->mUseAnisotropic[ rpd->mStageNum ] )
  221. maxAnisotropy = MATMGR->getDefaultAnisotropy();
  222. for( U32 i=0; i < rpd->mNumTex; i++ )
  223. {
  224. U32 currTexFlag = rpd->mTexType[i];
  225. switch( currTexFlag )
  226. {
  227. default:
  228. {
  229. result.samplers[i].addressModeU = GFXAddressWrap;
  230. result.samplers[i].addressModeV = GFXAddressWrap;
  231. if ( maxAnisotropy > 1 )
  232. {
  233. result.samplers[i].minFilter = GFXTextureFilterAnisotropic;
  234. result.samplers[i].magFilter = GFXTextureFilterAnisotropic;
  235. result.samplers[i].maxAnisotropy = maxAnisotropy;
  236. }
  237. else
  238. {
  239. result.samplers[i].minFilter = GFXTextureFilterLinear;
  240. result.samplers[i].magFilter = GFXTextureFilterLinear;
  241. }
  242. break;
  243. }
  244. case Material::Cube:
  245. case Material::SGCube:
  246. case Material::NormalizeCube:
  247. {
  248. result.samplers[i].addressModeU = GFXAddressClamp;
  249. result.samplers[i].addressModeV = GFXAddressClamp;
  250. result.samplers[i].addressModeW = GFXAddressClamp;
  251. result.samplers[i].minFilter = GFXTextureFilterLinear;
  252. result.samplers[i].magFilter = GFXTextureFilterLinear;
  253. break;
  254. }
  255. case Material::TexTarget:
  256. {
  257. texTarget = mPasses[0]->mTexSlot[i].texTarget;
  258. if ( texTarget )
  259. texTarget->setupSamplerState( &result.samplers[i] );
  260. break;
  261. }
  262. }
  263. }
  264. // The deferred will take care of writing to the
  265. // zbuffer, so we don't have to by default.
  266. if ( MATMGR->getDeferredEnabled() &&
  267. !mFeatures.hasFeature(MFT_ForwardShading))
  268. result.setZReadWrite( result.zEnable, false );
  269. result.addDesc(mUserDefined);
  270. }
  271. /// Creates the default state blocks for a list of render states
  272. void ProcessedMaterial::_initRenderStateStateBlocks( RenderPassData *rpd )
  273. {
  274. GFXStateBlockDesc stateTranslucent;
  275. GFXStateBlockDesc stateReflect;
  276. GFXStateBlockDesc statePass;
  277. _initStateBlockTemplates( stateTranslucent, stateReflect );
  278. _initPassStateBlock( rpd, statePass );
  279. // Ok, we've got our templates set up, let's combine them together based on state and
  280. // create our state blocks.
  281. for (U32 i = 0; i < RenderPassData::STATE_MAX; i++)
  282. {
  283. GFXStateBlockDesc stateFinal;
  284. if (i & RenderPassData::STATE_REFLECT)
  285. stateFinal.addDesc(stateReflect);
  286. if (i & RenderPassData::STATE_TRANSLUCENT)
  287. stateFinal.addDesc(stateTranslucent);
  288. stateFinal.addDesc(statePass);
  289. if (i & RenderPassData::STATE_WIREFRAME)
  290. stateFinal.fillMode = GFXFillWireframe;
  291. GFXStateBlockRef sb = GFX->createStateBlock(stateFinal);
  292. rpd->mRenderStates[i] = sb;
  293. }
  294. }
  295. U32 ProcessedMaterial::_getRenderStateIndex( const SceneRenderState *sceneState,
  296. const SceneData &sgData )
  297. {
  298. // Based on what the state of the world is, get our render state block
  299. U32 currState = 0;
  300. // NOTE: We should only use per-material or per-pass hints to
  301. // change the render state. This is importaint because we
  302. // only change the state blocks between material passes.
  303. //
  304. // For example sgData.visibility would be bad to use
  305. // in here without changing how RenderMeshMgr works.
  306. if ( sceneState && sceneState->isReflectPass() )
  307. currState |= RenderPassData::STATE_REFLECT;
  308. if ( sgData.binType != SceneData::DeferredBin &&
  309. mMaterial->isTranslucent() )
  310. currState |= RenderPassData::STATE_TRANSLUCENT;
  311. if ( sgData.wireframe )
  312. currState |= RenderPassData::STATE_WIREFRAME;
  313. return currState;
  314. }
  315. void ProcessedMaterial::_setRenderState( const SceneRenderState *state,
  316. const SceneData& sgData,
  317. U32 pass )
  318. {
  319. // Make sure we have the pass
  320. if ( pass >= mPasses.size() )
  321. return;
  322. U32 currState = _getRenderStateIndex( state, sgData );
  323. GFX->setStateBlock(mPasses[pass]->mRenderStates[currState]);
  324. }
  325. void ProcessedMaterial::_setStageData()
  326. {
  327. // Only do this once
  328. if (mHasSetStageData)
  329. return;
  330. mHasSetStageData = true;
  331. U32 i;
  332. // Load up all the textures for every possible stage
  333. for (i = 0; i < Material::MAX_STAGES; i++)
  334. {
  335. // DiffuseMap
  336. if (mMaterial->mDiffuseMapAsset[i] && !mMaterial->mDiffuseMapAsset[i].isNull())
  337. {
  338. mStages[i].setTex(MFT_DiffuseMap, mMaterial->getDiffuseMapResource(i));
  339. if (!mStages[i].getTex(MFT_DiffuseMap))
  340. {
  341. // If we start with a #, we're probably actually attempting to hit a named target and it may not get a hit on the first pass.
  342. if (!String(mMaterial->mDiffuseMapAsset[i]->getImageFileName()).startsWith("#") && !String(mMaterial->mDiffuseMapAsset[i]->getImageFileName()).startsWith("$"))
  343. mMaterial->logError("Failed to load diffuse map %s for stage %i", mMaterial->mDiffuseMapAsset[i]->getImageFileName(), i);
  344. mStages[i].setTex(MFT_DiffuseMap, _createTexture(GFXTextureManager::getMissingTexturePath().c_str(), &GFXStaticTextureSRGBProfile));
  345. }
  346. }
  347. else if (mMaterial->mDiffuseMapName[i] != StringTable->EmptyString())
  348. {
  349. mStages[i].setTex(MFT_DiffuseMap, _createTexture(mMaterial->mDiffuseMapName[i], &GFXStaticTextureSRGBProfile));
  350. if (!mStages[i].getTex(MFT_DiffuseMap))
  351. {
  352. //If we start with a #, we're probably actually attempting to hit a named target and it may not get a hit on the first pass.
  353. if (!String(mMaterial->mDiffuseMapName[i]).startsWith("#") && !String(mMaterial->mDiffuseMapName[i]).startsWith("$"))
  354. mMaterial->logError("Failed to load diffuse map %s for stage %i", mMaterial->mDiffuseMapName[i], i);
  355. // Load a debug texture to make it clear to the user
  356. // that the texture for this stage was missing.
  357. mStages[i].setTex(MFT_DiffuseMap, _createTexture(GFXTextureManager::getMissingTexturePath().c_str(), &GFXStaticTextureSRGBProfile));
  358. }
  359. }
  360. // OverlayMap
  361. if (mMaterial->getOverlayMap(i) != StringTable->EmptyString())
  362. {
  363. mStages[i].setTex(MFT_OverlayMap, mMaterial->getOverlayMapResource(i));
  364. if (!mStages[i].getTex(MFT_OverlayMap))
  365. mMaterial->logError("Failed to load overlay map %s for stage %i", mMaterial->getOverlayMap(i), i);
  366. }
  367. // LightMap
  368. if (mMaterial->getLightMap(i) != StringTable->EmptyString())
  369. {
  370. mStages[i].setTex(MFT_LightMap, mMaterial->getLightMapResource(i));
  371. if (!mStages[i].getTex(MFT_LightMap))
  372. mMaterial->logError("Failed to load light map %s for stage %i", mMaterial->getLightMap(i), i);
  373. }
  374. // ToneMap
  375. if (mMaterial->getToneMap(i) != StringTable->EmptyString())
  376. {
  377. mStages[i].setTex(MFT_ToneMap, mMaterial->getToneMapResource(i));
  378. if (!mStages[i].getTex(MFT_ToneMap))
  379. mMaterial->logError("Failed to load tone map %s for stage %i", mMaterial->getToneMap(i), i);
  380. }
  381. // DetailMap
  382. if (mMaterial->getDetailMap(i) != StringTable->EmptyString())
  383. {
  384. mStages[i].setTex(MFT_DetailMap, mMaterial->getDetailMapResource(i));
  385. if (!mStages[i].getTex(MFT_DetailMap))
  386. mMaterial->logError("Failed to load detail map %s for stage %i", mMaterial->getDetailMap(i), i);
  387. }
  388. // NormalMap
  389. if (mMaterial->mNormalMapAsset[i] && !mMaterial->mNormalMapAsset[i].isNull())
  390. {
  391. mStages[i].setTex(MFT_NormalMap, mMaterial->getNormalMapResource(i));
  392. //mStages[i].setTex(MFT_DiffuseMap, _createTexture(mMaterial->getDiffuseMap(i), &GFXStaticTextureSRGBProfile));
  393. if (!mStages[i].getTex(MFT_NormalMap))
  394. {
  395. // Load a debug texture to make it clear to the user
  396. // that the texture for this stage was missing.
  397. mStages[i].setTex(MFT_NormalMap, _createTexture(GFXTextureManager::getMissingTexturePath().c_str(), &GFXNormalMapProfile));
  398. }
  399. }
  400. else if (mMaterial->mNormalMapName[i] != StringTable->EmptyString())
  401. {
  402. mStages[i].setTex(MFT_NormalMap, _createTexture(mMaterial->mNormalMapName[i], &GFXNormalMapProfile));
  403. if (!mStages[i].getTex(MFT_NormalMap))
  404. {
  405. //If we start with a #, we're probably actually attempting to hit a named target and it may not get a hit on the first pass. So we'll
  406. //pass on the error rather than spamming the console
  407. if (!String(mMaterial->mNormalMapName[i]).startsWith("#"))
  408. mMaterial->logError("Failed to load normal map %s for stage %i", mMaterial->mNormalMapName[i], i);
  409. }
  410. }
  411. // Detail Normal Map
  412. if (mMaterial->getDetailNormalMap(i) != StringTable->EmptyString())
  413. {
  414. mStages[i].setTex(MFT_DetailNormalMap, mMaterial->getDetailNormalMapResource(i));
  415. if (!mStages[i].getTex(MFT_DetailNormalMap))
  416. mMaterial->logError("Failed to load normal map %s for stage %i", mMaterial->getDetailNormalMap(i), i);
  417. }
  418. //depending on creation method this may or may not have been shoved into srgb space eroneously
  419. GFXTextureProfile* profile = &GFXStaticTextureProfile;
  420. if (mMaterial->mIsSRGb[i])
  421. profile = &GFXStaticTextureSRGBProfile;
  422. // ORMConfig
  423. if (mMaterial->getORMConfigMap(i) != StringTable->EmptyString())
  424. {
  425. mStages[i].setTex(MFT_OrmMap, _createTexture(mMaterial->getORMConfigMap(i), profile));
  426. if (!mStages[i].getTex(MFT_OrmMap))
  427. mMaterial->logError("Failed to load PBR Config map %s for stage %i", mMaterial->getORMConfigMap(i), i);
  428. }
  429. else
  430. {
  431. if ((mMaterial->getAOMap(i) != StringTable->EmptyString()) || (mMaterial->getRoughMap(i) != StringTable->EmptyString()) || (mMaterial->getMetalMap(i) != StringTable->EmptyString()))
  432. {
  433. U32 inputKey[4];
  434. inputKey[0] = mMaterial->mAOChan[i];
  435. inputKey[1] = mMaterial->mRoughnessChan[i];
  436. inputKey[2] = mMaterial->mMetalChan[i];
  437. inputKey[3] = 0;
  438. mStages[i].setTex(MFT_OrmMap, _createCompositeTexture( mMaterial->getAOMap(i), mMaterial->getRoughMap(i),
  439. mMaterial->getMetalMap(i), "",
  440. inputKey, profile));
  441. if (!mStages[i].getTex(MFT_OrmMap))
  442. mMaterial->logError("Failed to dynamically create ORM Config map for stage %i", i);
  443. }
  444. }
  445. if (mMaterial->getGlowMap(i) != StringTable->EmptyString())
  446. {
  447. mStages[i].setTex(MFT_GlowMap, mMaterial->getGlowMapResource(i));
  448. if (!mStages[i].getTex(MFT_GlowMap))
  449. mMaterial->logError("Failed to load glow map %s for stage %i", mMaterial->getGlowMap(i), i);
  450. }
  451. }
  452. mMaterial->mCubemapData = dynamic_cast<CubemapData*>(Sim::findObject(mMaterial->mCubemapName));
  453. if (!mMaterial->mCubemapData)
  454. mMaterial->mCubemapData = NULL;
  455. // If we have a cubemap put it on stage 0 (cubemaps only supported on stage 0)
  456. if (mMaterial->mCubemapData)
  457. {
  458. mMaterial->mCubemapData->createMap();
  459. mStages[0].setCubemap(mMaterial->mCubemapData->mCubemap);
  460. if (!mStages[0].getCubemap())
  461. mMaterial->logError("Failed to load cubemap");
  462. }
  463. }