processedMaterial.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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& stateGlow, 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. // Glow
  189. stateGlow.zDefined = true;
  190. stateGlow.zWriteEnable = false;
  191. // Reflect
  192. stateReflect.cullDefined = true;
  193. stateReflect.cullMode = mMaterial->mDoubleSided ? GFXCullNone : GFXCullCW;
  194. }
  195. void ProcessedMaterial::_initRenderPassDataStateBlocks()
  196. {
  197. for (U32 pass = 0; pass < mPasses.size(); pass++)
  198. _initRenderStateStateBlocks( mPasses[pass] );
  199. }
  200. void ProcessedMaterial::_initPassStateBlock( RenderPassData *rpd, GFXStateBlockDesc &result )
  201. {
  202. if ( rpd->mBlendOp != Material::None )
  203. {
  204. result.blendDefined = true;
  205. result.blendEnable = true;
  206. _setBlendState( rpd->mBlendOp, result );
  207. }
  208. if (mMaterial && mMaterial->isDoubleSided())
  209. {
  210. result.cullDefined = true;
  211. result.cullMode = GFXCullNone;
  212. }
  213. if(mMaterial && mMaterial->mAlphaTest)
  214. {
  215. result.alphaDefined = true;
  216. result.alphaTestEnable = mMaterial->mAlphaTest;
  217. result.alphaTestRef = mMaterial->mAlphaRef;
  218. result.alphaTestFunc = GFXCmpGreaterEqual;
  219. }
  220. result.samplersDefined = true;
  221. NamedTexTarget *texTarget;
  222. U32 maxAnisotropy = 1;
  223. if (mMaterial && mMaterial->mUseAnisotropic[ rpd->mStageNum ] )
  224. maxAnisotropy = MATMGR->getDefaultAnisotropy();
  225. for( U32 i=0; i < rpd->mNumTex; i++ )
  226. {
  227. U32 currTexFlag = rpd->mTexType[i];
  228. switch( currTexFlag )
  229. {
  230. default:
  231. {
  232. result.samplers[i].addressModeU = GFXAddressWrap;
  233. result.samplers[i].addressModeV = GFXAddressWrap;
  234. if ( maxAnisotropy > 1 )
  235. {
  236. result.samplers[i].minFilter = GFXTextureFilterAnisotropic;
  237. result.samplers[i].magFilter = GFXTextureFilterAnisotropic;
  238. result.samplers[i].maxAnisotropy = maxAnisotropy;
  239. }
  240. else
  241. {
  242. result.samplers[i].minFilter = GFXTextureFilterLinear;
  243. result.samplers[i].magFilter = GFXTextureFilterLinear;
  244. }
  245. break;
  246. }
  247. case Material::Cube:
  248. case Material::SGCube:
  249. case Material::NormalizeCube:
  250. {
  251. result.samplers[i].addressModeU = GFXAddressClamp;
  252. result.samplers[i].addressModeV = GFXAddressClamp;
  253. result.samplers[i].addressModeW = GFXAddressClamp;
  254. result.samplers[i].minFilter = GFXTextureFilterLinear;
  255. result.samplers[i].magFilter = GFXTextureFilterLinear;
  256. break;
  257. }
  258. case Material::TexTarget:
  259. {
  260. texTarget = mPasses[0]->mTexSlot[i].texTarget;
  261. if ( texTarget )
  262. texTarget->setupSamplerState( &result.samplers[i] );
  263. break;
  264. }
  265. }
  266. }
  267. // The deferred will take care of writing to the
  268. // zbuffer, so we don't have to by default.
  269. if ( MATMGR->getDeferredEnabled() &&
  270. !mFeatures.hasFeature(MFT_ForwardShading))
  271. result.setZReadWrite( result.zEnable, false );
  272. result.addDesc(mUserDefined);
  273. }
  274. /// Creates the default state blocks for a list of render states
  275. void ProcessedMaterial::_initRenderStateStateBlocks( RenderPassData *rpd )
  276. {
  277. GFXStateBlockDesc stateTranslucent;
  278. GFXStateBlockDesc stateGlow;
  279. GFXStateBlockDesc stateReflect;
  280. GFXStateBlockDesc statePass;
  281. _initStateBlockTemplates( stateTranslucent, stateGlow, stateReflect );
  282. _initPassStateBlock( rpd, statePass );
  283. // Ok, we've got our templates set up, let's combine them together based on state and
  284. // create our state blocks.
  285. for (U32 i = 0; i < RenderPassData::STATE_MAX; i++)
  286. {
  287. GFXStateBlockDesc stateFinal;
  288. if (i & RenderPassData::STATE_REFLECT)
  289. stateFinal.addDesc(stateReflect);
  290. if (i & RenderPassData::STATE_TRANSLUCENT)
  291. stateFinal.addDesc(stateTranslucent);
  292. if (i & RenderPassData::STATE_GLOW)
  293. stateFinal.addDesc(stateGlow);
  294. stateFinal.addDesc(statePass);
  295. if (i & RenderPassData::STATE_WIREFRAME)
  296. stateFinal.fillMode = GFXFillWireframe;
  297. GFXStateBlockRef sb = GFX->createStateBlock(stateFinal);
  298. rpd->mRenderStates[i] = sb;
  299. }
  300. }
  301. U32 ProcessedMaterial::_getRenderStateIndex( const SceneRenderState *sceneState,
  302. const SceneData &sgData )
  303. {
  304. // Based on what the state of the world is, get our render state block
  305. U32 currState = 0;
  306. // NOTE: We should only use per-material or per-pass hints to
  307. // change the render state. This is importaint because we
  308. // only change the state blocks between material passes.
  309. //
  310. // For example sgData.visibility would be bad to use
  311. // in here without changing how RenderMeshMgr works.
  312. if ( sgData.binType == SceneData::GlowBin )
  313. currState |= RenderPassData::STATE_GLOW;
  314. if ( sceneState && sceneState->isReflectPass() )
  315. currState |= RenderPassData::STATE_REFLECT;
  316. if ( sgData.binType != SceneData::DeferredBin &&
  317. mMaterial->isTranslucent() )
  318. currState |= RenderPassData::STATE_TRANSLUCENT;
  319. if ( sgData.wireframe )
  320. currState |= RenderPassData::STATE_WIREFRAME;
  321. return currState;
  322. }
  323. void ProcessedMaterial::_setRenderState( const SceneRenderState *state,
  324. const SceneData& sgData,
  325. U32 pass )
  326. {
  327. // Make sure we have the pass
  328. if ( pass >= mPasses.size() )
  329. return;
  330. U32 currState = _getRenderStateIndex( state, sgData );
  331. GFX->setStateBlock(mPasses[pass]->mRenderStates[currState]);
  332. }
  333. void ProcessedMaterial::_setStageData()
  334. {
  335. // Only do this once
  336. if (mHasSetStageData)
  337. return;
  338. mHasSetStageData = true;
  339. U32 i;
  340. // Load up all the textures for every possible stage
  341. for (i = 0; i < Material::MAX_STAGES; i++)
  342. {
  343. // DiffuseMap
  344. if (mMaterial->mDiffuseMapAsset[i] && !mMaterial->mDiffuseMapAsset[i].isNull())
  345. {
  346. mStages[i].setTex(MFT_DiffuseMap, mMaterial->getDiffuseMapResource(i));
  347. //mStages[i].setTex(MFT_DiffuseMap, _createTexture(mMaterial->getDiffuseMap(i), &GFXStaticTextureSRGBProfile));
  348. if (!mStages[i].getTex(MFT_DiffuseMap))
  349. {
  350. // Load a debug texture to make it clear to the user
  351. // that the texture for this stage was missing.
  352. mStages[i].setTex(MFT_DiffuseMap, _createTexture(GFXTextureManager::getMissingTexturePath().c_str(), &GFXStaticTextureSRGBProfile));
  353. }
  354. }
  355. else if (mMaterial->mDiffuseMapName[i] != StringTable->EmptyString())
  356. {
  357. mStages[i].setTex(MFT_DiffuseMap, _createTexture(mMaterial->mDiffuseMapName[i], &GFXStaticTextureSRGBProfile));
  358. if (!mStages[i].getTex(MFT_DiffuseMap))
  359. {
  360. //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
  361. //pass on the error rather than spamming the console
  362. if (!String(mMaterial->mDiffuseMapName[i]).startsWith("#"))
  363. mMaterial->logError("Failed to load diffuse map %s for stage %i", mMaterial->mDiffuseMapName[i], i);
  364. // Load a debug texture to make it clear to the user
  365. // that the texture for this stage was missing.
  366. mStages[i].setTex(MFT_DiffuseMap, _createTexture(GFXTextureManager::getMissingTexturePath().c_str(), &GFXStaticTextureSRGBProfile));
  367. }
  368. }
  369. // OverlayMap
  370. if (mMaterial->getOverlayMap(i) != StringTable->EmptyString())
  371. {
  372. mStages[i].setTex(MFT_OverlayMap, mMaterial->getOverlayMapResource(i));
  373. if (!mStages[i].getTex(MFT_OverlayMap))
  374. mMaterial->logError("Failed to load overlay map %s for stage %i", mMaterial->getOverlayMap(i), i);
  375. }
  376. // LightMap
  377. if (mMaterial->getLightMap(i) != StringTable->EmptyString())
  378. {
  379. mStages[i].setTex(MFT_LightMap, mMaterial->getLightMapResource(i));
  380. if (!mStages[i].getTex(MFT_LightMap))
  381. mMaterial->logError("Failed to load light map %s for stage %i", mMaterial->getLightMap(i), i);
  382. }
  383. // ToneMap
  384. if (mMaterial->getToneMap(i) != StringTable->EmptyString())
  385. {
  386. mStages[i].setTex(MFT_ToneMap, mMaterial->getToneMapResource(i));
  387. if (!mStages[i].getTex(MFT_ToneMap))
  388. mMaterial->logError("Failed to load tone map %s for stage %i", mMaterial->getToneMap(i), i);
  389. }
  390. // DetailMap
  391. if (mMaterial->getDetailMap(i) != StringTable->EmptyString())
  392. {
  393. mStages[i].setTex(MFT_DetailMap, mMaterial->getDetailMapResource(i));
  394. if (!mStages[i].getTex(MFT_DetailMap))
  395. mMaterial->logError("Failed to load detail map %s for stage %i", mMaterial->getDetailMap(i), i);
  396. }
  397. // NormalMap
  398. if (mMaterial->getNormalMap(i) != StringTable->EmptyString())
  399. {
  400. mStages[i].setTex(MFT_NormalMap, mMaterial->getNormalMapResource(i));
  401. if (!mStages[i].getTex(MFT_NormalMap))
  402. mMaterial->logError("Failed to load normal map %s for stage %i", mMaterial->getNormalMap(i), i);
  403. }
  404. // Detail Normal Map
  405. if (mMaterial->getDetailNormalMap(i) != StringTable->EmptyString())
  406. {
  407. mStages[i].setTex(MFT_DetailNormalMap, mMaterial->getDetailNormalMapResource(i));
  408. if (!mStages[i].getTex(MFT_DetailNormalMap))
  409. mMaterial->logError("Failed to load normal map %s for stage %i", mMaterial->getDetailNormalMap(i), i);
  410. }
  411. //depending on creation method this may or may not have been shoved into srgb space eroneously
  412. GFXTextureProfile* profile = &GFXStaticTextureProfile;
  413. if (mMaterial->mIsSRGb[i])
  414. profile = &GFXStaticTextureSRGBProfile;
  415. // ORMConfig
  416. if (mMaterial->getORMConfigMap(i) != StringTable->EmptyString())
  417. {
  418. mStages[i].setTex(MFT_OrmMap, _createTexture(mMaterial->getORMConfigMap(i), profile));
  419. if (!mStages[i].getTex(MFT_OrmMap))
  420. mMaterial->logError("Failed to load PBR Config map %s for stage %i", mMaterial->getORMConfigMap(i), i);
  421. }
  422. else
  423. {
  424. if ((mMaterial->getAOMap(i) != StringTable->EmptyString()) || (mMaterial->getRoughMap(i) != StringTable->EmptyString()) || (mMaterial->getMetalMap(i) != StringTable->EmptyString()))
  425. {
  426. U32 inputKey[4];
  427. inputKey[0] = mMaterial->mAOChan[i];
  428. inputKey[1] = mMaterial->mRoughnessChan[i];
  429. inputKey[2] = mMaterial->mMetalChan[i];
  430. inputKey[3] = 0;
  431. mStages[i].setTex(MFT_OrmMap, _createCompositeTexture( mMaterial->getAOMap(i), mMaterial->getRoughMap(i),
  432. mMaterial->getMetalMap(i), "",
  433. inputKey, profile));
  434. if (!mStages[i].getTex(MFT_OrmMap))
  435. mMaterial->logError("Failed to dynamically create ORM Config map for stage %i", i);
  436. }
  437. }
  438. if (mMaterial->getGlowMap(i) != StringTable->EmptyString())
  439. {
  440. mStages[i].setTex(MFT_GlowMap, mMaterial->getGlowMapResource(i));
  441. if (!mStages[i].getTex(MFT_GlowMap))
  442. mMaterial->logError("Failed to load glow map %s for stage %i", mMaterial->getGlowMap(i), i);
  443. }
  444. }
  445. mMaterial->mCubemapData = dynamic_cast<CubemapData*>(Sim::findObject(mMaterial->mCubemapName));
  446. if (!mMaterial->mCubemapData)
  447. mMaterial->mCubemapData = NULL;
  448. // If we have a cubemap put it on stage 0 (cubemaps only supported on stage 0)
  449. if (mMaterial->mCubemapData)
  450. {
  451. mMaterial->mCubemapData->createMap();
  452. mStages[0].setCubemap(mMaterial->mCubemapData->mCubemap);
  453. if (!mStages[0].getCubemap())
  454. mMaterial->logError("Failed to load cubemap");
  455. }
  456. }