processedCustomMaterial.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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/processedCustomMaterial.h"
  24. #include "gfx/sim/cubemapData.h"
  25. #include "materials/sceneData.h"
  26. #include "shaderGen/shaderGenVars.h"
  27. #include "scene/sceneRenderState.h"
  28. #include "materials/customMaterialDefinition.h"
  29. #include "materials/shaderData.h"
  30. #include "materials/materialManager.h"
  31. #include "materials/matTextureTarget.h"
  32. #include "materials/materialFeatureTypes.h"
  33. #include "materials/materialParameters.h"
  34. #include "gfx/sim/gfxStateBlockData.h"
  35. #include "core/util/safeDelete.h"
  36. #include "gfx/genericConstBuffer.h"
  37. #include "console/simFieldDictionary.h"
  38. #include "console/propertyParsing.h"
  39. #include "gfx/util/screenspace.h"
  40. #include "scene/reflectionManager.h"
  41. #include "renderInstance/renderProbeMgr.h"
  42. ProcessedCustomMaterial::ProcessedCustomMaterial(Material &mat)
  43. {
  44. mMaterial = &mat;
  45. AssertFatal(dynamic_cast<CustomMaterial*>(mMaterial), "Incompatible Material type!");
  46. mCustomMaterial = static_cast<CustomMaterial*>(mMaterial);
  47. mHasSetStageData = false;
  48. mHasGlow = false;
  49. mHasAccumulation = false;
  50. mMaxStages = 0;
  51. mMaxTex = 0;
  52. }
  53. ProcessedCustomMaterial::~ProcessedCustomMaterial()
  54. {
  55. }
  56. void ProcessedCustomMaterial::_setStageData()
  57. {
  58. // Only do this once
  59. if ( mHasSetStageData )
  60. return;
  61. mHasSetStageData = true;
  62. ShaderRenderPassData* rpd = _getRPD(0);
  63. mConditionerMacros.clear();
  64. // Loop through all the possible textures, set the right flags, and load them if needed
  65. for(U32 i=0; i<CustomMaterial::MAX_TEX_PER_PASS; i++ )
  66. {
  67. rpd->mTexType[i] = Material::NoTexture; // Set none as the default in case none of the cases below catch it.
  68. String filename = mCustomMaterial->mTexFilename[i];
  69. if(filename.isEmpty())
  70. continue;
  71. if(filename.equal(String("$dynamiclight"), String::NoCase))
  72. {
  73. rpd->mTexType[i] = Material::DynamicLight;
  74. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  75. mMaxTex = i+1;
  76. continue;
  77. }
  78. if(filename.equal(String("$dynamiclightmask"), String::NoCase))
  79. {
  80. rpd->mTexType[i] = Material::DynamicLightMask;
  81. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  82. mMaxTex = i+1;
  83. continue;
  84. }
  85. if (filename.equal(String("$photometricmask"), String::NoCase))
  86. {
  87. rpd->mTexType[i] = Material::PhotometricMask;
  88. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  89. mMaxTex = i + 1;
  90. continue;
  91. }
  92. if(filename.equal(String("$lightmap"), String::NoCase))
  93. {
  94. rpd->mTexType[i] = Material::Lightmap;
  95. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  96. mMaxTex = i+1;
  97. continue;
  98. }
  99. if(filename.equal(String("$cubemap"), String::NoCase))
  100. {
  101. if( mCustomMaterial->mCubemapData )
  102. {
  103. rpd->mTexType[i] = Material::Cube;
  104. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  105. mMaxTex = i+1;
  106. }
  107. else
  108. {
  109. mCustomMaterial->logError( "Could not find CubemapData - %s", mCustomMaterial->mCubemapName.c_str());
  110. }
  111. continue;
  112. }
  113. if(filename.equal(String("$dynamicCubemap"), String::NoCase))
  114. {
  115. rpd->mTexType[i] = Material::SGCube;
  116. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  117. mMaxTex = i+1;
  118. continue;
  119. }
  120. if(filename.equal(String("$backbuff"), String::NoCase))
  121. {
  122. rpd->mTexType[i] = Material::BackBuff;
  123. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  124. mMaxTex = i+1;
  125. continue;
  126. }
  127. if(filename.equal(String("$reflectbuff"), String::NoCase))
  128. {
  129. rpd->mTexType[i] = Material::ReflectBuff;
  130. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  131. mMaxTex = i+1;
  132. continue;
  133. }
  134. if(filename.equal(String("$miscbuff"), String::NoCase))
  135. {
  136. rpd->mTexType[i] = Material::Misc;
  137. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  138. mMaxTex = i+1;
  139. continue;
  140. }
  141. // Check for a RenderTexTargetBin assignment
  142. if (filename.substr( 0, 1 ).equal("#"))
  143. {
  144. String texTargetBufferName = filename.substr(1, filename.length() - 1);
  145. NamedTexTarget *texTarget = NamedTexTarget::find( texTargetBufferName );
  146. rpd->mTexSlot[i].texTarget = texTarget;
  147. // Get the conditioner macros.
  148. if ( texTarget )
  149. texTarget->getShaderMacros( &mConditionerMacros );
  150. rpd->mTexType[i] = Material::TexTarget;
  151. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  152. mMaxTex = i+1;
  153. continue;
  154. }
  155. rpd->mTexSlot[i].texObject = _createTexture( filename, &GFXStaticTextureSRGBProfile );
  156. if ( !rpd->mTexSlot[i].texObject )
  157. {
  158. mMaterial->logError("Failed to load texture %s", _getTexturePath(filename).c_str());
  159. continue;
  160. }
  161. rpd->mTexType[i] = Material::Standard;
  162. rpd->mSamplerNames[i] = mCustomMaterial->mSamplerNames[i];
  163. mMaxTex = i+1;
  164. }
  165. // We only get one cubemap
  166. if( mCustomMaterial->mCubemapData )
  167. {
  168. mCustomMaterial->mCubemapData->createMap();
  169. rpd->mCubeMap = mMaterial->mCubemapData->mCubemap; // BTRTODO ?
  170. if ( !rpd->mCubeMap )
  171. mMaterial->logError("Failed to load cubemap");
  172. }
  173. // If this has a output target defined, it may be writing
  174. // to a tex target bin with a conditioner, so search for
  175. // one and add its macros.
  176. if ( mCustomMaterial->mOutputTarget.isNotEmpty() )
  177. {
  178. NamedTexTarget *texTarget = NamedTexTarget::find( mCustomMaterial->mOutputTarget );
  179. if ( texTarget )
  180. texTarget->getShaderMacros( &mConditionerMacros );
  181. }
  182. // Copy the glow state over.
  183. mHasGlow = mCustomMaterial->mGlow[0];
  184. }
  185. bool ProcessedCustomMaterial::init( const FeatureSet &features,
  186. const GFXVertexFormat *vertexFormat,
  187. const MatFeaturesDelegate &featuresDelegate )
  188. {
  189. // If we don't have a shader data... we have nothing to do.
  190. if ( !mCustomMaterial->mShaderData )
  191. return true;
  192. // Custom materials only do one pass at the moment... so
  193. // add one for the stage data to fill in.
  194. ShaderRenderPassData *rpd = new ShaderRenderPassData();
  195. mPasses.push_back( rpd );
  196. _setStageData();
  197. _initPassStateBlocks();
  198. mStateHint.clear();
  199. // Note: We don't use the vertex format in a custom
  200. // material at all right now.
  201. //
  202. // Maybe we can add some required semantics and
  203. // validate that the format fits the shader?
  204. // Build a composite list of shader macros from
  205. // the conditioner and the user defined lists.
  206. Vector<GFXShaderMacro> macros;
  207. macros.merge( mConditionerMacros );
  208. macros.merge( mUserMacros );
  209. // Ask the shader data to give us a shader instance.
  210. rpd->shader = mCustomMaterial->mShaderData->getShader( macros );
  211. if ( !rpd->shader )
  212. {
  213. delete rpd;
  214. mPasses.clear();
  215. return false;
  216. }
  217. rpd->shaderHandles.init( rpd->shader, mCustomMaterial );
  218. _initMaterialParameters();
  219. mDefaultParameters = allocMaterialParameters();
  220. setMaterialParameters( mDefaultParameters, 0 );
  221. mStateHint.init( this );
  222. for(int i = 0; i < mMaxTex; i++)
  223. {
  224. ShaderConstHandles *handles = _getShaderConstHandles( mPasses.size()-1 );
  225. AssertFatal(handles,"");
  226. if(rpd->mSamplerNames[i].isEmpty())
  227. continue;
  228. String samplerName = rpd->mSamplerNames[i].startsWith("$") ? rpd->mSamplerNames[i] : String("$") + rpd->mSamplerNames[i];
  229. GFXShaderConstHandle *handle = rpd->shader->getShaderConstHandle( samplerName );
  230. AssertFatal(handle,"");
  231. handles->mTexHandlesSC[i] = handle;
  232. }
  233. return true;
  234. }
  235. void ProcessedCustomMaterial::_initPassStateBlock( RenderPassData *rpd, GFXStateBlockDesc &result )
  236. {
  237. Parent::_initPassStateBlock( rpd, result );
  238. if (mCustomMaterial->getStateBlockData())
  239. result.addDesc(mCustomMaterial->getStateBlockData()->getState());
  240. }
  241. void ProcessedCustomMaterial::_initPassStateBlocks()
  242. {
  243. AssertFatal(mHasSetStageData, "State data must be set before initializing state block!");
  244. ShaderRenderPassData* rpd = _getRPD(0);
  245. _initRenderStateStateBlocks( rpd );
  246. }
  247. bool ProcessedCustomMaterial::_hasCubemap(U32 pass)
  248. {
  249. // If the material doesn't have a cubemap, we don't
  250. if( mMaterial->mCubemapData ) return true;
  251. else return false;
  252. }
  253. bool ProcessedCustomMaterial::setupPass( SceneRenderState *state, const SceneData& sgData, U32 pass )
  254. {
  255. PROFILE_SCOPE( ProcessedCustomMaterial_SetupPass );
  256. // Make sure we have a pass.
  257. if ( pass >= mPasses.size() )
  258. return false;
  259. ShaderRenderPassData* rpd = _getRPD( pass );
  260. U32 currState = _getRenderStateIndex( state, sgData );
  261. GFX->setStateBlock(rpd->mRenderStates[currState]);
  262. // activate shader
  263. if ( rpd->shader )
  264. GFX->setShader( rpd->shader );
  265. else
  266. GFX->setupGenericShaders();
  267. // Set our textures
  268. setTextureStages( state, sgData, pass );
  269. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  270. GFX->setShaderConstBuffer(shaderConsts);
  271. // Set our shader constants.
  272. _setTextureTransforms(pass);
  273. _setShaderConstants(state, sgData, pass);
  274. LightManager* lm = state ? LIGHTMGR : NULL;
  275. if (lm)
  276. lm->setLightInfo(this, NULL, sgData, state, pass, shaderConsts);
  277. RenderProbeMgr* pm = state ? PROBEMGR : NULL;
  278. if (pm)
  279. pm->setProbeInfo(this, NULL, sgData, state, pass, shaderConsts);
  280. shaderConsts->setSafe(rpd->shaderHandles.mAccumTimeSC, MATMGR->getTotalTime());
  281. shaderConsts->setSafe(rpd->shaderHandles.mDampnessSC, MATMGR->getDampnessClamped());
  282. return true;
  283. }
  284. void ProcessedCustomMaterial::setTextureStages( SceneRenderState *state, const SceneData &sgData, U32 pass )
  285. {
  286. LightManager* lm = state ? LIGHTMGR : NULL;
  287. ShaderRenderPassData* rpd = _getRPD(pass);
  288. ShaderConstHandles* handles = _getShaderConstHandles(pass);
  289. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  290. const NamedTexTarget *texTarget;
  291. GFXTextureObject *texObject;
  292. for( U32 i=0; i<mMaxTex; i++ )
  293. {
  294. U32 currTexFlag = rpd->mTexType[i];
  295. if ( !lm || !lm->setTextureStage(sgData, currTexFlag, i, shaderConsts, handles ) )
  296. {
  297. GFXShaderConstHandle* handle = handles->mTexHandlesSC[i];
  298. if ( !handle->isValid() )
  299. continue;
  300. S32 samplerRegister = handle->getSamplerRegister();
  301. switch( currTexFlag )
  302. {
  303. case 0:
  304. default:
  305. break;
  306. case Material::Mask:
  307. case Material::PhotometricMask:
  308. case Material::Standard:
  309. case Material::Bump:
  310. case Material::Detail:
  311. {
  312. GFX->setTexture( samplerRegister, rpd->mTexSlot[i].texObject );
  313. break;
  314. }
  315. case Material::Lightmap:
  316. {
  317. GFX->setTexture( samplerRegister, sgData.lightmap );
  318. break;
  319. }
  320. case Material::Cube:
  321. {
  322. GFX->setCubeTexture( samplerRegister, rpd->mCubeMap );
  323. break;
  324. }
  325. case Material::SGCube:
  326. {
  327. GFX->setCubeTexture( samplerRegister, sgData.cubemap );
  328. break;
  329. }
  330. case Material::BackBuff:
  331. {
  332. GFX->setTexture( samplerRegister, sgData.backBuffTex );
  333. //if ( sgData.reflectTex )
  334. // GFX->setTexture( samplerRegister, sgData.reflectTex );
  335. //else
  336. //{
  337. // GFXTextureObject *refractTex = REFLECTMGR->getRefractTex( true );
  338. // GFX->setTexture( samplerRegister, refractTex );
  339. //}
  340. break;
  341. }
  342. case Material::ReflectBuff:
  343. {
  344. GFX->setTexture( samplerRegister, sgData.reflectTex );
  345. break;
  346. }
  347. case Material::Misc:
  348. {
  349. GFX->setTexture( samplerRegister, sgData.miscTex );
  350. break;
  351. }
  352. case Material::TexTarget:
  353. {
  354. texTarget = rpd->mTexSlot[i].texTarget;
  355. if ( !texTarget )
  356. {
  357. GFX->setTexture( samplerRegister, NULL );
  358. break;
  359. }
  360. texObject = texTarget->getTexture();
  361. // If no texture is available then map the default 2x2
  362. // black texture to it. This at least will ensure that
  363. // we get consistant behavior across GPUs and platforms.
  364. if ( !texObject )
  365. texObject = GFXTexHandle::ZERO;
  366. if ( handles->mRTParamsSC[samplerRegister]->isValid() && texObject )
  367. {
  368. const Point3I &targetSz = texObject->getSize();
  369. const RectI &targetVp = texTarget->getViewport();
  370. Point4F rtParams;
  371. ScreenSpace::RenderTargetParameters(targetSz, targetVp, rtParams);
  372. shaderConsts->set(handles->mRTParamsSC[samplerRegister], rtParams);
  373. }
  374. GFX->setTexture( samplerRegister, texObject );
  375. break;
  376. }
  377. }
  378. }
  379. }
  380. }
  381. template <typename T>
  382. void ProcessedCustomMaterial::setMaterialParameter(MaterialParameters* param,
  383. MaterialParameterHandle* handle,
  384. const String& value)
  385. {
  386. T typedValue;
  387. if (PropertyInfo::default_scan(value, typedValue))
  388. {
  389. param->set(handle, typedValue);
  390. } else {
  391. Con::errorf("Error setting %s, parse error: %s", handle->getName().c_str(), value.c_str());
  392. }
  393. }
  394. void ProcessedCustomMaterial::setMatrixParameter(MaterialParameters* param,
  395. MaterialParameterHandle* handle,
  396. const String& value, GFXShaderConstType matrixType)
  397. {
  398. MatrixF result(true);
  399. F32* m = result;
  400. switch (matrixType)
  401. {
  402. case GFXSCT_Float2x2 :
  403. dSscanf(value.c_str(),"%g %g %g %g",
  404. m[result.idx(0,0)], m[result.idx(0,1)],
  405. m[result.idx(1,0)], m[result.idx(1,1)]);
  406. break;
  407. case GFXSCT_Float3x3 :
  408. dSscanf(value.c_str(),"%g %g %g %g %g %g %g %g %g",
  409. m[result.idx(0,0)], m[result.idx(0,1)], m[result.idx(0,2)],
  410. m[result.idx(1,0)], m[result.idx(1,1)], m[result.idx(1,2)],
  411. m[result.idx(2,0)], m[result.idx(2,1)], m[result.idx(2,2)]);
  412. break;
  413. default:
  414. AssertFatal(false, "Invalid type!");
  415. break;
  416. }
  417. }
  418. // BTRTODO: Support arrays!?
  419. MaterialParameters* ProcessedCustomMaterial::allocMaterialParameters()
  420. {
  421. MaterialParameters* ret = Parent::allocMaterialParameters();
  422. // See if any of the dynamic fields match up with shader constants we have.
  423. SimFieldDictionary* fields = mMaterial->getFieldDictionary();
  424. if (!fields || fields->getNumFields() == 0)
  425. return ret;
  426. const Vector<GFXShaderConstDesc>& consts = ret->getShaderConstDesc();
  427. for (U32 i = 0; i < consts.size(); i++)
  428. {
  429. // strip the dollar sign from the front.
  430. String stripped(consts[i].name);
  431. stripped.erase(0, 1);
  432. SimFieldDictionary::Entry* field = fields->findDynamicField(stripped);
  433. if (field)
  434. {
  435. MaterialParameterHandle* handle = getMaterialParameterHandle(consts[i].name);
  436. switch (consts[i].constType)
  437. {
  438. case GFXSCT_Float :
  439. setMaterialParameter<F32>(ret, handle, field->value);
  440. break;
  441. case GFXSCT_Float2:
  442. setMaterialParameter<Point2F>(ret, handle, field->value);
  443. break;
  444. case GFXSCT_Float3:
  445. setMaterialParameter<Point3F>(ret, handle, field->value);
  446. break;
  447. case GFXSCT_Float4:
  448. setMaterialParameter<Point4F>(ret, handle, field->value);
  449. break;
  450. case GFXSCT_Float2x2:
  451. case GFXSCT_Float3x3:
  452. setMatrixParameter(ret, handle, field->value, consts[i].constType);
  453. break;
  454. case GFXSCT_Float4x4:
  455. setMaterialParameter<MatrixF>(ret, handle, field->value);
  456. break;
  457. case GFXSCT_Int:
  458. setMaterialParameter<S32>(ret, handle, field->value);
  459. break;
  460. case GFXSCT_Int2:
  461. setMaterialParameter<Point2I>(ret, handle, field->value);
  462. break;
  463. case GFXSCT_Int3:
  464. setMaterialParameter<Point3I>(ret, handle, field->value);
  465. break;
  466. case GFXSCT_Int4:
  467. setMaterialParameter<Point4I>(ret, handle, field->value);
  468. break;
  469. // Do we want to ignore these?
  470. case GFXSCT_Sampler:
  471. case GFXSCT_SamplerCube:
  472. default:
  473. break;
  474. }
  475. }
  476. }
  477. return ret;
  478. }