processedMaterial.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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() : "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::LerpAlpha:
  116. {
  117. desc.blendSrc = GFXBlendSrcAlpha;
  118. desc.blendDest = GFXBlendInvSrcAlpha;
  119. break;
  120. }
  121. default:
  122. {
  123. // default to LerpAlpha
  124. desc.blendSrc = GFXBlendSrcAlpha;
  125. desc.blendDest = GFXBlendInvSrcAlpha;
  126. break;
  127. }
  128. }
  129. }
  130. void ProcessedMaterial::setBuffers(GFXVertexBufferHandleBase* vertBuffer, GFXPrimitiveBufferHandle* primBuffer)
  131. {
  132. GFX->setVertexBuffer( *vertBuffer );
  133. GFX->setPrimitiveBuffer( *primBuffer );
  134. }
  135. bool ProcessedMaterial::stepInstance()
  136. {
  137. AssertFatal( false, "ProcessedMaterial::stepInstance() - This type of material doesn't support instancing!" );
  138. return false;
  139. }
  140. String ProcessedMaterial::_getTexturePath(const String& filename)
  141. {
  142. // if '/', then path is specified, use it.
  143. if( filename.find('/') != String::NPos )
  144. {
  145. return filename;
  146. }
  147. // otherwise, construct path
  148. return mMaterial->getPath() + filename;
  149. }
  150. GFXTexHandle ProcessedMaterial::_createTexture( const char* filename, GFXTextureProfile *profile)
  151. {
  152. return GFXTexHandle( _getTexturePath(filename), profile, avar("%s() - NA (line %d)", __FUNCTION__, __LINE__) );
  153. }
  154. GFXTexHandle ProcessedMaterial::_createCompositeTexture(const char *filenameR, const char *filenameG, const char *filenameB, const char *filenameA, U32 inputKey[4], GFXTextureProfile *profile)
  155. {
  156. return GFXTexHandle(_getTexturePath(filenameR), _getTexturePath(filenameG), _getTexturePath(filenameB), _getTexturePath(filenameA), inputKey, profile, avar("%s() - NA (line %d)", __FUNCTION__, __LINE__));
  157. }
  158. void ProcessedMaterial::addStateBlockDesc(const GFXStateBlockDesc& sb)
  159. {
  160. mUserDefined = sb;
  161. }
  162. void ProcessedMaterial::_initStateBlockTemplates(GFXStateBlockDesc& stateTranslucent, GFXStateBlockDesc& stateGlow, GFXStateBlockDesc& stateReflect)
  163. {
  164. // Translucency
  165. stateTranslucent.blendDefined = true;
  166. stateTranslucent.blendEnable = mMaterial->mTranslucentBlendOp != Material::None;
  167. _setBlendState(mMaterial->mTranslucentBlendOp, stateTranslucent);
  168. stateTranslucent.zDefined = true;
  169. stateTranslucent.zWriteEnable = mMaterial->mTranslucentZWrite;
  170. stateTranslucent.alphaDefined = true;
  171. stateTranslucent.alphaTestEnable = mMaterial->mAlphaTest;
  172. stateTranslucent.alphaTestRef = mMaterial->mAlphaRef;
  173. stateTranslucent.alphaTestFunc = GFXCmpGreaterEqual;
  174. stateTranslucent.samplersDefined = true;
  175. stateTranslucent.samplers[0].textureColorOp = GFXTOPModulate;
  176. stateTranslucent.samplers[0].alphaOp = GFXTOPModulate;
  177. stateTranslucent.samplers[0].alphaArg1 = GFXTATexture;
  178. stateTranslucent.samplers[0].alphaArg2 = GFXTADiffuse;
  179. // Glow
  180. stateGlow.zDefined = true;
  181. stateGlow.zWriteEnable = false;
  182. // Reflect
  183. stateReflect.cullDefined = true;
  184. stateReflect.cullMode = mMaterial->mDoubleSided ? GFXCullNone : GFXCullCW;
  185. }
  186. void ProcessedMaterial::_initRenderPassDataStateBlocks()
  187. {
  188. for (U32 pass = 0; pass < mPasses.size(); pass++)
  189. _initRenderStateStateBlocks( mPasses[pass] );
  190. }
  191. void ProcessedMaterial::_initPassStateBlock( RenderPassData *rpd, GFXStateBlockDesc &result )
  192. {
  193. if ( rpd->mBlendOp != Material::None )
  194. {
  195. result.blendDefined = true;
  196. result.blendEnable = true;
  197. _setBlendState( rpd->mBlendOp, result );
  198. }
  199. if (mMaterial && mMaterial->isDoubleSided())
  200. {
  201. result.cullDefined = true;
  202. result.cullMode = GFXCullNone;
  203. }
  204. if(mMaterial && mMaterial->mAlphaTest)
  205. {
  206. result.alphaDefined = true;
  207. result.alphaTestEnable = mMaterial->mAlphaTest;
  208. result.alphaTestRef = mMaterial->mAlphaRef;
  209. result.alphaTestFunc = GFXCmpGreaterEqual;
  210. }
  211. result.samplersDefined = true;
  212. NamedTexTarget *texTarget;
  213. U32 maxAnisotropy = 1;
  214. if (mMaterial && mMaterial->mUseAnisotropic[ rpd->mStageNum ] )
  215. maxAnisotropy = MATMGR->getDefaultAnisotropy();
  216. for( U32 i=0; i < rpd->mNumTex; i++ )
  217. {
  218. U32 currTexFlag = rpd->mTexType[i];
  219. switch( currTexFlag )
  220. {
  221. default:
  222. {
  223. result.samplers[i].textureColorOp = GFXTOPModulate;
  224. result.samplers[i].addressModeU = GFXAddressWrap;
  225. result.samplers[i].addressModeV = GFXAddressWrap;
  226. if ( maxAnisotropy > 1 )
  227. {
  228. result.samplers[i].minFilter = GFXTextureFilterAnisotropic;
  229. result.samplers[i].magFilter = GFXTextureFilterAnisotropic;
  230. result.samplers[i].maxAnisotropy = maxAnisotropy;
  231. }
  232. else
  233. {
  234. result.samplers[i].minFilter = GFXTextureFilterLinear;
  235. result.samplers[i].magFilter = GFXTextureFilterLinear;
  236. }
  237. break;
  238. }
  239. case Material::Cube:
  240. case Material::SGCube:
  241. case Material::NormalizeCube:
  242. {
  243. result.samplers[i].addressModeU = GFXAddressClamp;
  244. result.samplers[i].addressModeV = GFXAddressClamp;
  245. result.samplers[i].addressModeW = GFXAddressClamp;
  246. result.samplers[i].minFilter = GFXTextureFilterLinear;
  247. result.samplers[i].magFilter = GFXTextureFilterLinear;
  248. break;
  249. }
  250. case Material::TexTarget:
  251. {
  252. texTarget = mPasses[0]->mTexSlot[i].texTarget;
  253. if ( texTarget )
  254. texTarget->setupSamplerState( &result.samplers[i] );
  255. break;
  256. }
  257. }
  258. }
  259. // The deferred will take care of writing to the
  260. // zbuffer, so we don't have to by default.
  261. if ( MATMGR->getDeferredEnabled() &&
  262. !mFeatures.hasFeature(MFT_ForwardShading))
  263. result.setZReadWrite( result.zEnable, false );
  264. result.addDesc(mUserDefined);
  265. }
  266. /// Creates the default state blocks for a list of render states
  267. void ProcessedMaterial::_initRenderStateStateBlocks( RenderPassData *rpd )
  268. {
  269. GFXStateBlockDesc stateTranslucent;
  270. GFXStateBlockDesc stateGlow;
  271. GFXStateBlockDesc stateReflect;
  272. GFXStateBlockDesc statePass;
  273. _initStateBlockTemplates( stateTranslucent, stateGlow, stateReflect );
  274. _initPassStateBlock( rpd, statePass );
  275. // Ok, we've got our templates set up, let's combine them together based on state and
  276. // create our state blocks.
  277. for (U32 i = 0; i < RenderPassData::STATE_MAX; i++)
  278. {
  279. GFXStateBlockDesc stateFinal;
  280. if (i & RenderPassData::STATE_REFLECT)
  281. stateFinal.addDesc(stateReflect);
  282. if (i & RenderPassData::STATE_TRANSLUCENT)
  283. stateFinal.addDesc(stateTranslucent);
  284. if (i & RenderPassData::STATE_GLOW)
  285. stateFinal.addDesc(stateGlow);
  286. stateFinal.addDesc(statePass);
  287. if (i & RenderPassData::STATE_WIREFRAME)
  288. stateFinal.fillMode = GFXFillWireframe;
  289. GFXStateBlockRef sb = GFX->createStateBlock(stateFinal);
  290. rpd->mRenderStates[i] = sb;
  291. }
  292. }
  293. U32 ProcessedMaterial::_getRenderStateIndex( const SceneRenderState *sceneState,
  294. const SceneData &sgData )
  295. {
  296. // Based on what the state of the world is, get our render state block
  297. U32 currState = 0;
  298. // NOTE: We should only use per-material or per-pass hints to
  299. // change the render state. This is importaint because we
  300. // only change the state blocks between material passes.
  301. //
  302. // For example sgData.visibility would be bad to use
  303. // in here without changing how RenderMeshMgr works.
  304. if ( sgData.binType == SceneData::GlowBin )
  305. currState |= RenderPassData::STATE_GLOW;
  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->mDiffuseMapFilename[i].isNotEmpty())
  337. {
  338. mStages[i].setTex(MFT_DiffuseMap, _createTexture(mMaterial->mDiffuseMapFilename[i], &GFXStaticTextureSRGBProfile));
  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. So we'll
  342. //pass on the error rather than spamming the console
  343. if (!mMaterial->mDiffuseMapFilename[i].startsWith("#"))
  344. mMaterial->logError("Failed to load diffuse map %s for stage %i", _getTexturePath(mMaterial->mDiffuseMapFilename[i]).c_str(), i);
  345. // Load a debug texture to make it clear to the user
  346. // that the texture for this stage was missing.
  347. mStages[i].setTex(MFT_DiffuseMap, _createTexture(GFXTextureManager::getMissingTexturePath().c_str(), &GFXStaticTextureSRGBProfile));
  348. }
  349. }
  350. else if (!mMaterial->mDiffuseMapAsset[i].isNull())
  351. {
  352. mStages[i].setTex(MFT_DiffuseMap, mMaterial->mDiffuseMapAsset[i]->getImage());
  353. if (!mStages[i].getTex(MFT_DiffuseMap))
  354. {
  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->mOverlayMapFilename[i].isNotEmpty())
  362. {
  363. mStages[i].setTex(MFT_OverlayMap, _createTexture(mMaterial->mOverlayMapFilename[i], &GFXStaticTextureSRGBProfile));
  364. if (!mStages[i].getTex(MFT_OverlayMap))
  365. mMaterial->logError("Failed to load overlay map %s for stage %i", _getTexturePath(mMaterial->mOverlayMapFilename[i]).c_str(), i);
  366. }
  367. // LightMap
  368. if (mMaterial->mLightMapFilename[i].isNotEmpty())
  369. {
  370. mStages[i].setTex(MFT_LightMap, _createTexture(mMaterial->mLightMapFilename[i], &GFXStaticTextureSRGBProfile));
  371. if (!mStages[i].getTex(MFT_LightMap))
  372. mMaterial->logError("Failed to load light map %s for stage %i", _getTexturePath(mMaterial->mLightMapFilename[i]).c_str(), i);
  373. }
  374. // ToneMap
  375. if (mMaterial->mToneMapFilename[i].isNotEmpty())
  376. {
  377. mStages[i].setTex(MFT_ToneMap, _createTexture(mMaterial->mToneMapFilename[i], &GFXStaticTextureProfile));
  378. if (!mStages[i].getTex(MFT_ToneMap))
  379. mMaterial->logError("Failed to load tone map %s for stage %i", _getTexturePath(mMaterial->mToneMapFilename[i]).c_str(), i);
  380. }
  381. // DetailMap
  382. if (mMaterial->mDetailMapFilename[i].isNotEmpty())
  383. {
  384. mStages[i].setTex(MFT_DetailMap, _createTexture(mMaterial->mDetailMapFilename[i], &GFXStaticTextureProfile));
  385. if (!mStages[i].getTex(MFT_DetailMap))
  386. mMaterial->logError("Failed to load detail map %s for stage %i", _getTexturePath(mMaterial->mDetailMapFilename[i]).c_str(), i);
  387. }
  388. // NormalMap
  389. if (mMaterial->mNormalMapFilename[i].isNotEmpty())
  390. {
  391. mStages[i].setTex(MFT_NormalMap, _createTexture(mMaterial->mNormalMapFilename[i], &GFXNormalMapProfile));
  392. if (!mStages[i].getTex(MFT_NormalMap))
  393. mMaterial->logError("Failed to load normal map %s for stage %i", _getTexturePath(mMaterial->mNormalMapFilename[i]).c_str(), i);
  394. }
  395. // Detail Normal Map
  396. if (mMaterial->mDetailNormalMapFilename[i].isNotEmpty())
  397. {
  398. mStages[i].setTex(MFT_DetailNormalMap, _createTexture(mMaterial->mDetailNormalMapFilename[i], &GFXNormalMapProfile));
  399. if (!mStages[i].getTex(MFT_DetailNormalMap))
  400. mMaterial->logError("Failed to load normal map %s for stage %i", _getTexturePath(mMaterial->mDetailNormalMapFilename[i]).c_str(), i);
  401. }
  402. GFXTextureProfile* profile = &GFXStaticTextureProfile;
  403. if (mMaterial->mIsSRGb[i])
  404. profile = &GFXStaticTextureSRGBProfile;
  405. // SpecularMap
  406. if (mMaterial->mSpecularMapFilename[i].isNotEmpty())
  407. {
  408. mStages[i].setTex(MFT_SpecularMap, _createTexture(mMaterial->mSpecularMapFilename[i], profile));
  409. if (!mStages[i].getTex(MFT_SpecularMap))
  410. mMaterial->logError("Failed to load specular map %s for stage %i", _getTexturePath(mMaterial->mSpecularMapFilename[i]).c_str(), i);
  411. }
  412. else
  413. {
  414. if (mMaterial->mRoughMapFilename[i].isNotEmpty() && mMaterial->mMetalMapFilename[i].isNotEmpty())
  415. {
  416. U32 inputKey[4];
  417. inputKey[0] = mMaterial->mSmoothnessChan[i];
  418. inputKey[1] = mMaterial->mAOChan[i];
  419. inputKey[2] = mMaterial->mMetalChan[i];
  420. inputKey[3] = NULL;
  421. mStages[i].setTex(MFT_SpecularMap, _createCompositeTexture(mMaterial->mRoughMapFilename[i], mMaterial->mAOMapFilename[i],
  422. mMaterial->mMetalMapFilename[i], "",
  423. inputKey, profile));
  424. if (!mStages[i].getTex(MFT_SpecularMap))
  425. mMaterial->logError("Failed to load specular map %s for stage %i", _getTexturePath(mMaterial->mSpecularMapFilename[i]).c_str(), i);
  426. }
  427. }
  428. }
  429. mMaterial->mCubemapData = dynamic_cast<CubemapData*>(Sim::findObject(mMaterial->mCubemapName));
  430. if (!mMaterial->mCubemapData)
  431. mMaterial->mCubemapData = NULL;
  432. // If we have a cubemap put it on stage 0 (cubemaps only supported on stage 0)
  433. if (mMaterial->mCubemapData)
  434. {
  435. mMaterial->mCubemapData->createMap();
  436. mStages[0].setCubemap(mMaterial->mCubemapData->mCubemap);
  437. if (!mStages[0].getCubemap())
  438. mMaterial->logError("Failed to load cubemap");
  439. }
  440. }