materialDefinition.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  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/materialDefinition.h"
  24. #include "console/consoleTypes.h"
  25. #include "console/engineAPI.h"
  26. #include "math/mathTypes.h"
  27. #include "materials/materialManager.h"
  28. #include "sceneData.h"
  29. #include "gfx/sim/cubemapData.h"
  30. #include "gfx/gfxCubemap.h"
  31. #include "math/mathIO.h"
  32. #include "materials/matInstance.h"
  33. #include "sfx/sfxTrack.h"
  34. #include "sfx/sfxTypes.h"
  35. #include "core/util/safeDelete.h"
  36. #include "T3D/accumulationVolume.h"
  37. #include "gui/controls/guiTreeViewCtrl.h"
  38. IMPLEMENT_CONOBJECT( Material );
  39. ConsoleDocClass( Material,
  40. "@brief A material in Torque 3D is a data structure that describes a surface.\n\n"
  41. "It contains many different types of information for rendering properties. "
  42. "Torque 3D generates shaders from Material definitions. The shaders are compiled "
  43. "at runtime and output into the example/shaders directory. Any errors or warnings "
  44. "generated from compiling the procedurally generated shaders are output to the console "
  45. "as well as the output window in the Visual C IDE.\n\n"
  46. "@tsexample\n"
  47. "singleton Material(DECAL_scorch)\n"
  48. "{\n"
  49. " baseTex[0] = \"./scorch_decal.png\";\n"
  50. " vertColor[ 0 ] = true;\n\n"
  51. " translucent = true;\n"
  52. " translucentBlendOp = None;\n"
  53. " translucentZWrite = true;\n"
  54. " alphaTest = true;\n"
  55. " alphaRef = 84;\n"
  56. "};\n"
  57. "@endtsexample\n\n"
  58. "@see Rendering\n"
  59. "@see ShaderData\n"
  60. "@ingroup GFX\n");
  61. ImplementBitfieldType( MaterialAnimType,
  62. "The type of animation effect to apply to this material.\n"
  63. "@ingroup GFX\n\n")
  64. { Material::Scroll, "Scroll", "Scroll the material along the X/Y axis.\n" },
  65. { Material::Rotate, "Rotate" , "Rotate the material around a point.\n"},
  66. { Material::Wave, "Wave" , "Warps the material with an animation using Sin, Triangle or Square mathematics.\n"},
  67. { Material::Scale, "Scale", "Scales the material larger and smaller with a pulsing effect.\n" },
  68. { Material::Sequence, "Sequence", "Enables the material to have multiple frames of animation in its imagemap.\n" }
  69. EndImplementBitfieldType;
  70. ImplementEnumType( MaterialBlendOp,
  71. "The type of graphical blending operation to apply to this material\n"
  72. "@ingroup GFX\n\n")
  73. { Material::None, "None", "Disable blending for this material." },
  74. { Material::Mul, "Mul", "Multiplicative blending." },
  75. { Material::PreMul, "PreMul", "Premultiplied alpha." },
  76. { Material::Add, "Add", "Adds the color of the material to the frame buffer with full alpha for each pixel." },
  77. { Material::AddAlpha, "AddAlpha", "The color is modulated by the alpha channel before being added to the frame buffer." },
  78. { Material::Sub, "Sub", "Subtractive Blending. Reverses the color model, causing dark colors to have a stronger visual effect." },
  79. { Material::LerpAlpha, "LerpAlpha", "Linearly interpolates between Material color and frame buffer color based on alpha." },
  80. { Material::PreMult, "PreMult", "" }
  81. EndImplementEnumType;
  82. ImplementEnumType( MaterialWaveType,
  83. "When using the Wave material animation, one of these Wave Types will be used to determine the type of wave to display.\n"
  84. "@ingroup GFX\n")
  85. { Material::Sin, "Sin", "Warps the material along a curved Sin Wave." },
  86. { Material::Triangle, "Triangle", "Warps the material along a sharp Triangle Wave." },
  87. { Material::Square, "Square", "Warps the material along a wave which transitions between two oppposite states. As a Square Wave, the transition is quick and sudden." },
  88. EndImplementEnumType;
  89. bool Material::sAllowTextureTargetAssignment = false;
  90. GFXCubemap * Material::GetNormalizeCube()
  91. {
  92. if(smNormalizeCube)
  93. return smNormalizeCube;
  94. smNormalizeCube = GFX->createCubemap();
  95. smNormalizeCube->initNormalize(64);
  96. return smNormalizeCube;
  97. }
  98. GFXCubemapHandle Material::smNormalizeCube;
  99. Material::Material()
  100. {
  101. for( U32 i=0; i<MAX_STAGES; i++ )
  102. {
  103. mDiffuse[i].set( 1.0f, 1.0f, 1.0f, 1.0f );
  104. mDiffuseMapSRGB[i] = true;
  105. mDiffuseMapAsset[i] = StringTable->EmptyString();
  106. mDiffuseMapAssetId[i] = StringTable->EmptyString();
  107. mSmoothness[i] = 0.0f;
  108. mMetalness[i] = 0.0f;
  109. mIsSRGb[i] = false;
  110. mInvertSmoothness[i] = false;
  111. mSmoothnessChan[i] = 0;
  112. mAOChan[i] = 1;
  113. mMetalChan[i] = 2;
  114. mAccuEnabled[i] = false;
  115. mAccuScale[i] = 1.0f;
  116. mAccuDirection[i] = 1.0f;
  117. mAccuStrength[i] = 0.6f;
  118. mAccuCoverage[i] = 0.9f;
  119. mAccuSpecular[i] = 16.0f;
  120. mParallaxScale[i] = 0.0f;
  121. mVertLit[i] = false;
  122. mVertColor[ i ] = false;
  123. mGlow[i] = false;
  124. mEmissive[i] = false;
  125. mDetailScale[i].set( 2.0f, 2.0f );
  126. mDetailNormalMapStrength[i] = 1.0f;
  127. mMinnaertConstant[i] = -1.0f;
  128. mSubSurface[i] = false;
  129. mSubSurfaceColor[i].set( 1.0f, 0.2f, 0.2f, 1.0f );
  130. mSubSurfaceRolloff[i] = 0.2f;
  131. mAnimFlags[i] = 0;
  132. mScrollDir[i].set( 0.0f, 0.0f );
  133. mScrollSpeed[i] = 0.0f;
  134. mScrollOffset[i].set( 0.0f, 0.0f );
  135. mRotSpeed[i] = 0.0f;
  136. mRotPivotOffset[i].set( 0.0f, 0.0f );
  137. mRotPos[i] = 0.0f;
  138. mWavePos[i] = 0.0f;
  139. mWaveFreq[i] = 0.0f;
  140. mWaveAmp[i] = 0.0f;
  141. mWaveType[i] = 0;
  142. mSeqFramePerSec[i] = 0.0f;
  143. mSeqSegSize[i] = 0.0f;
  144. // Deferred Shading
  145. mMatInfoFlags[i] = 0.0f;
  146. mRoughMapFilename[i].clear();
  147. mRoughMapAsset[i] = StringTable->EmptyString();
  148. mAOMapFilename[i].clear();
  149. mMetalMapFilename[i].clear();
  150. mMetalMapAsset[i] = StringTable->EmptyString();
  151. mGlowMapFilename[i].clear();
  152. mGlowMapAsset[i] = StringTable->EmptyString();
  153. mGlowMul[i] = 0.0f;
  154. }
  155. dMemset(mCellIndex, 0, sizeof(mCellIndex));
  156. dMemset(mCellLayout, 0, sizeof(mCellLayout));
  157. dMemset(mCellSize, 0, sizeof(mCellSize));
  158. dMemset(mNormalMapAtlas, 0, sizeof(mNormalMapAtlas));
  159. dMemset(mUseAnisotropic, 1, sizeof(mUseAnisotropic));
  160. mImposterLimits = Point4F::Zero;
  161. mDoubleSided = false;
  162. mTranslucent = false;
  163. mTranslucentBlendOp = LerpAlpha;
  164. mTranslucentZWrite = false;
  165. mAlphaTest = false;
  166. mAlphaRef = 1;
  167. mCastShadows = true;
  168. mCastDynamicShadows = false;
  169. mPlanarReflection = false;
  170. mCubemapData = NULL;
  171. mDynamicCubemap = NULL;
  172. mLastUpdateTime = 0;
  173. mAutoGenerated = false;
  174. mShowDust = false;
  175. mShowFootprints = true;
  176. dMemset( mEffectColor, 0, sizeof( mEffectColor ) );
  177. mFootstepSoundId = -1; mImpactSoundId = -1;
  178. mFootstepSoundCustom = 0; mImpactSoundCustom = 0;
  179. mFriction = 0.0;
  180. mDirectSoundOcclusion = 1.f;
  181. mReverbSoundOcclusion = 1.0;
  182. }
  183. void Material::initPersistFields()
  184. {
  185. addField("mapTo", TypeRealString, Offset(mMapTo, Material),
  186. "Used to map this material to the material name used by TSShape." );
  187. addArray( "Stages", MAX_STAGES );
  188. addField("diffuseColor", TypeColorF, Offset(mDiffuse, Material), MAX_STAGES,
  189. "This color is multiplied against the diffuse texture color. If no diffuse texture "
  190. "is present this is the material color." );
  191. addField("diffuseMap", TypeImageFilename, Offset(mDiffuseMapFilename, Material), MAX_STAGES,
  192. "The diffuse color texture map." );
  193. addField("diffuseMapAsset", TypeImageAssetPtr, Offset(mDiffuseMapAssetId, Material), MAX_STAGES,
  194. "The diffuse color texture map." );
  195. addField("diffuseMapSRGB", TypeBool, Offset(mDiffuseMapSRGB, Material), MAX_STAGES,
  196. "Enable sRGB for the diffuse color texture map.");
  197. addField("overlayMap", TypeImageFilename, Offset(mOverlayMapFilename, Material), MAX_STAGES,
  198. "A secondary diffuse color texture map which will use the second texcoord of a mesh." );
  199. addField("lightMap", TypeImageFilename, Offset(mLightMapFilename, Material), MAX_STAGES,
  200. "The lightmap texture used with pureLight." );
  201. addField("toneMap", TypeImageFilename, Offset(mToneMapFilename, Material), MAX_STAGES,
  202. "The tonemap texture used with pureLight.");
  203. addField("detailMap", TypeImageFilename, Offset(mDetailMapFilename, Material), MAX_STAGES,
  204. "A typically greyscale detail texture additively blended into the material." );
  205. addField("detailScale", TypePoint2F, Offset(mDetailScale, Material), MAX_STAGES,
  206. "The scale factor for the detail map." );
  207. addField( "normalMap", TypeImageFilename, Offset(mNormalMapFilename, Material), MAX_STAGES,
  208. "The normal map texture. You can use the DXTnm format only when per-pixel "
  209. "specular highlights are disabled, or a specular map is in use." );
  210. addField( "detailNormalMap", TypeImageFilename, Offset(mDetailNormalMapFilename, Material), MAX_STAGES,
  211. "A second normal map texture applied at the detail scale. You can use the DXTnm "
  212. "format only when per-pixel specular highlights are disabled." );
  213. addField( "detailNormalMapStrength", TypeF32, Offset(mDetailNormalMapStrength, Material), MAX_STAGES,
  214. "Used to scale the strength of the detail normal map when blended with the base normal map." );
  215. addField("smoothness", TypeF32, Offset(mSmoothness, Material), MAX_STAGES,
  216. "The degree of smoothness when not using a PBRConfigMap." );
  217. addField("metalness", TypeF32, Offset(mMetalness, Material), MAX_STAGES,
  218. "The degree of Metalness when not using a PBRConfigMap." );
  219. addField("glowMul", TypeF32, Offset(mGlowMul, Material), MAX_STAGES,
  220. "glow mask multiplier");
  221. addProtectedField( "accuEnabled", TYPEID< bool >(), Offset( mAccuEnabled, Material ),
  222. &_setAccuEnabled, &defaultProtectedGetFn, MAX_STAGES, "Accumulation texture." );
  223. addField("accuScale", TypeF32, Offset(mAccuScale, Material), MAX_STAGES,
  224. "The scale that is applied to the accu map texture. You can use this to fit the texture to smaller or larger objects.");
  225. addField("accuDirection", TypeF32, Offset(mAccuDirection, Material), MAX_STAGES,
  226. "The direction of the accumulation. Chose whether you want the accu map to go from top to bottom (ie. snow) or upwards (ie. mold).");
  227. addField("accuStrength", TypeF32, Offset(mAccuStrength, Material), MAX_STAGES,
  228. "The strength of the accu map. This changes the transparency of the accu map texture. Make it subtle or add more contrast.");
  229. addField("accuCoverage", TypeF32, Offset(mAccuCoverage, Material), MAX_STAGES,
  230. "The coverage ratio of the accu map texture. Use this to make the entire shape pick up some of the accu map texture or none at all.");
  231. addField("accuSpecular", TypeF32, Offset(mAccuSpecular, Material), MAX_STAGES,
  232. "Changes specularity to this value where the accumulated material is present.");
  233. addField("isSRGb", TypeBool, Offset(mIsSRGb, Material), MAX_STAGES,
  234. "Substance Designer Workaround.");
  235. addField("invertSmoothness", TypeBool, Offset(mInvertSmoothness, Material), MAX_STAGES,
  236. "Treat Smoothness as Roughness");
  237. addField( "PBRConfigMap", TypeImageFilename, Offset(mPBRConfigMapFilename, Material), MAX_STAGES,
  238. "Prepacked specular map texture. The RGB channels of this texture provide per-pixel reference values for: "
  239. "smoothness (R), Ambient Occlusion (G), and metalness(B)");
  240. addField("roughMap", TypeImageFilename, Offset(mRoughMapFilename, Material), MAX_STAGES,
  241. "smoothness map. will be packed into the R channel of a packed 'specular' map");
  242. addField("smoothnessChan", TypeF32, Offset(mSmoothnessChan, Material), MAX_STAGES,
  243. "The input channel smoothness maps use.");
  244. addField("aoMap", TypeImageFilename, Offset(mAOMapFilename, Material), MAX_STAGES,
  245. "Ambient Occlusion map. will be packed into the G channel of a packed 'specular' map");
  246. addField("AOChan", TypeF32, Offset(mAOChan, Material), MAX_STAGES,
  247. "The input channel AO maps use.");
  248. addField("metalMap", TypeImageFilename, Offset(mMetalMapFilename, Material), MAX_STAGES,
  249. "Metalness map. will be packed into the B channel of a packed 'specular' map");
  250. addField("metalChan", TypeF32, Offset(mMetalChan, Material), MAX_STAGES,
  251. "The input channel metalness maps use.");
  252. addField("glowMap", TypeImageFilename, Offset(mGlowMapFilename, Material), MAX_STAGES,
  253. "Metalness map. will be packed into the B channel of a packed 'specular' map");
  254. addField("glowMul", TypeF32, Offset(mGlowMul, Material), MAX_STAGES,
  255. "The input channel metalness maps use.");
  256. addField("glow", TypeBool, Offset(mGlow, Material), MAX_STAGES,
  257. "Enables rendering as glowing.");
  258. addField( "parallaxScale", TypeF32, Offset(mParallaxScale, Material), MAX_STAGES,
  259. "Enables parallax mapping and defines the scale factor for the parallax effect. Typically "
  260. "this value is less than 0.4 else the effect breaks down." );
  261. addField( "useAnisotropic", TypeBool, Offset(mUseAnisotropic, Material), MAX_STAGES,
  262. "Use anisotropic filtering for the textures of this stage." );
  263. addField("vertLit", TypeBool, Offset(mVertLit, Material), MAX_STAGES,
  264. "If true the vertex color is used for lighting." );
  265. addField( "vertColor", TypeBool, Offset( mVertColor, Material ), MAX_STAGES,
  266. "If enabled, vertex colors are premultiplied with diffuse colors." );
  267. addField("minnaertConstant", TypeF32, Offset(mMinnaertConstant, Material), MAX_STAGES,
  268. "The Minnaert shading constant value. Must be greater than 0 to enable the effect." );
  269. addField("subSurface", TypeBool, Offset(mSubSurface, Material), MAX_STAGES,
  270. "Enables the subsurface scattering approximation." );
  271. addField("subSurfaceColor", TypeColorF, Offset(mSubSurfaceColor, Material), MAX_STAGES,
  272. "The color used for the subsurface scattering approximation." );
  273. addField("subSurfaceRolloff", TypeF32, Offset(mSubSurfaceRolloff, Material), MAX_STAGES,
  274. "The 0 to 1 rolloff factor used in the subsurface scattering approximation." );
  275. addField("emissive", TypeBool, Offset(mEmissive, Material), MAX_STAGES,
  276. "Enables emissive lighting for the material." );
  277. addField("doubleSided", TypeBool, Offset(mDoubleSided, Material),
  278. "Disables backface culling casing surfaces to be double sided. "
  279. "Note that the lighting on the backside will be a mirror of the front "
  280. "side of the surface." );
  281. addField("animFlags", TYPEID< AnimType >(), Offset(mAnimFlags, Material), MAX_STAGES,
  282. "The types of animation to play on this material." );
  283. addField("scrollDir", TypePoint2F, Offset(mScrollDir, Material), MAX_STAGES,
  284. "The scroll direction in UV space when scroll animation is enabled." );
  285. addField("scrollSpeed", TypeF32, Offset(mScrollSpeed, Material), MAX_STAGES,
  286. "The speed to scroll the texture in UVs per second when scroll animation is enabled." );
  287. addField("rotSpeed", TypeF32, Offset(mRotSpeed, Material), MAX_STAGES,
  288. "The speed to rotate the texture in degrees per second when rotation animation is enabled." );
  289. addField("rotPivotOffset", TypePoint2F, Offset(mRotPivotOffset, Material), MAX_STAGES,
  290. "The piviot position in UV coordinates to center the rotation animation." );
  291. addField("waveType", TYPEID< WaveType >(), Offset(mWaveType, Material), MAX_STAGES,
  292. "The type of wave animation to perform when wave animation is enabled." );
  293. addField("waveFreq", TypeF32, Offset(mWaveFreq, Material), MAX_STAGES,
  294. "The wave frequency when wave animation is enabled." );
  295. addField("waveAmp", TypeF32, Offset(mWaveAmp, Material), MAX_STAGES,
  296. "The wave amplitude when wave animation is enabled." );
  297. addField("sequenceFramePerSec", TypeF32, Offset(mSeqFramePerSec, Material), MAX_STAGES,
  298. "The number of frames per second for frame based sequence animations if greater than zero." );
  299. addField("sequenceSegmentSize", TypeF32, Offset(mSeqSegSize, Material), MAX_STAGES,
  300. "The size of each frame in UV units for sequence animations." );
  301. // Texture atlasing
  302. addField("cellIndex", TypePoint2I, Offset(mCellIndex, Material), MAX_STAGES,
  303. "@internal" );
  304. addField("cellLayout", TypePoint2I, Offset(mCellLayout, Material), MAX_STAGES,
  305. "@internal");
  306. addField("cellSize", TypeS32, Offset(mCellSize, Material), MAX_STAGES,
  307. "@internal");
  308. addField("bumpAtlas", TypeBool, Offset(mNormalMapAtlas, Material), MAX_STAGES,
  309. "@internal");
  310. // For backwards compatibility.
  311. //
  312. // They point at the new 'map' fields, but reads always return
  313. // an empty string and writes only apply if the value is not empty.
  314. //
  315. addProtectedField("baseTex", TypeImageFilename, Offset(mDiffuseMapFilename, Material),
  316. defaultProtectedSetNotEmptyFn, emptyStringProtectedGetFn, MAX_STAGES,
  317. "For backwards compatibility.\n@see diffuseMap\n" );
  318. addProtectedField("detailTex", TypeImageFilename, Offset(mDetailMapFilename, Material),
  319. defaultProtectedSetNotEmptyFn, emptyStringProtectedGetFn, MAX_STAGES,
  320. "For backwards compatibility.\n@see detailMap\n");
  321. addProtectedField("overlayTex", TypeImageFilename, Offset(mOverlayMapFilename, Material),
  322. defaultProtectedSetNotEmptyFn, emptyStringProtectedGetFn, MAX_STAGES,
  323. "For backwards compatibility.\n@see overlayMap\n");
  324. addProtectedField("bumpTex", TypeImageFilename, Offset(mNormalMapFilename, Material),
  325. defaultProtectedSetNotEmptyFn, emptyStringProtectedGetFn, MAX_STAGES,
  326. "For backwards compatibility.\n@see normalMap\n");
  327. addProtectedField("colorMultiply", TypeColorF, Offset(mDiffuse, Material),
  328. defaultProtectedSetNotEmptyFn, emptyStringProtectedGetFn, MAX_STAGES,
  329. "For backwards compatibility.\n@see diffuseColor\n");
  330. endArray( "Stages" );
  331. addField( "castShadows", TypeBool, Offset(mCastShadows, Material),
  332. "If set to false the lighting system will not cast shadows from this material." );
  333. addField( "castDynamicShadows", TypeBool, Offset(mCastDynamicShadows, Material),
  334. "If set to false the lighting system will not cast dynamic shadows from this material." );
  335. addField("planarReflection", TypeBool, Offset(mPlanarReflection, Material), "@internal" );
  336. addField("translucent", TypeBool, Offset(mTranslucent, Material),
  337. "If true this material is translucent blended." );
  338. addField("translucentBlendOp", TYPEID< BlendOp >(), Offset(mTranslucentBlendOp, Material),
  339. "The type of blend operation to use when the material is translucent." );
  340. addField("translucentZWrite", TypeBool, Offset(mTranslucentZWrite, Material),
  341. "If enabled and the material is translucent it will write into the depth buffer." );
  342. addField("alphaTest", TypeBool, Offset(mAlphaTest, Material),
  343. "Enables alpha test when rendering the material.\n@see alphaRef\n" );
  344. addField("alphaRef", TypeS32, Offset(mAlphaRef, Material),
  345. "The alpha reference value for alpha testing. Must be between 0 to 255.\n@see alphaTest\n" );
  346. addField("cubemap", TypeRealString, Offset(mCubemapName, Material),
  347. "The name of a CubemapData for environment mapping." );
  348. addField("dynamicCubemap", TypeBool, Offset(mDynamicCubemap, Material),
  349. "Enables the material to use the dynamic cubemap from the ShapeBase object its applied to." );
  350. addGroup( "Behavioral" );
  351. addField( "showFootprints", TypeBool, Offset( mShowFootprints, Material ),
  352. "Whether to show player footprint decals on this material.\n\n"
  353. "@see PlayerData::decalData" );
  354. addField( "showDust", TypeBool, Offset( mShowDust, Material ),
  355. "Whether to emit dust particles from a shape moving over the material. This is, for example, used by "
  356. "vehicles or players to decide whether to show dust trails." );
  357. addField( "effectColor", TypeColorF, Offset( mEffectColor, Material ), NUM_EFFECT_COLOR_STAGES,
  358. "If #showDust is true, this is the set of colors to use for the ParticleData of the dust "
  359. "emitter.\n\n"
  360. "@see ParticleData::colors" );
  361. addField( "footstepSoundId", TypeS32, Offset( mFootstepSoundId, Material ),
  362. "What sound to play from the PlayerData sound list when the player walks over the material. -1 (default) to not play any sound.\n"
  363. "\n"
  364. "The IDs are:\n\n"
  365. "- 0: PlayerData::FootSoftSound\n"
  366. "- 1: PlayerData::FootHardSound\n"
  367. "- 2: PlayerData::FootMetalSound\n"
  368. "- 3: PlayerData::FootSnowSound\n"
  369. "- 4: PlayerData::FootShallowSound\n"
  370. "- 5: PlayerData::FootWadingSound\n"
  371. "- 6: PlayerData::FootUnderwaterSound\n"
  372. "- 7: PlayerData::FootBubblesSound\n"
  373. "- 8: PlayerData::movingBubblesSound\n"
  374. "- 9: PlayerData::waterBreathSound\n"
  375. "- 10: PlayerData::impactSoftSound\n"
  376. "- 11: PlayerData::impactHardSound\n"
  377. "- 12: PlayerData::impactMetalSound\n"
  378. "- 13: PlayerData::impactSnowSound\n"
  379. "- 14: PlayerData::impactWaterEasy\n"
  380. "- 15: PlayerData::impactWaterMedium\n"
  381. "- 16: PlayerData::impactWaterHard\n"
  382. "- 17: PlayerData::exitingWater\n" );
  383. addField( "customFootstepSound", TypeSFXTrackName, Offset( mFootstepSoundCustom, Material ),
  384. "The sound to play when the player walks over the material. If this is set, it overrides #footstepSoundId. This field is "
  385. "useful for directly assigning custom footstep sounds to materials without having to rely on the PlayerData sound assignment.\n\n"
  386. "@warn Be aware that materials are client-side objects. This means that the SFXTracks assigned to materials must be client-side, too." );
  387. addField( "impactSoundId", TypeS32, Offset( mImpactSoundId, Material ),
  388. "What sound to play from the PlayerData sound list when the player impacts on the surface with a velocity equal or greater "
  389. "than PlayerData::groundImpactMinSpeed.\n\n"
  390. "For a list of IDs, see #footstepSoundId" );
  391. addField( "customImpactSound", TypeSFXTrackName, Offset( mImpactSoundCustom, Material ),
  392. "The sound to play when the player impacts on the surface with a velocity equal or greater than PlayerData::groundImpactMinSpeed. "
  393. "If this is set, it overrides #impactSoundId. This field is useful for directly assigning custom impact sounds to materials "
  394. "without having to rely on the PlayerData sound assignment.\n\n"
  395. "@warn Be aware that materials are client-side objects. This means that the SFXTracks assigned to materials must be client-side, too." );
  396. //Deactivate these for the moment as they are not used.
  397. #if 0
  398. addField( "friction", TypeF32, Offset( mFriction, Material ) );
  399. addField( "directSoundOcclusion", TypeF32, Offset( mDirectSoundOcclusion, Material ) );
  400. addField( "reverbSoundOcclusion", TypeF32, Offset( mReverbSoundOcclusion, Material ) );
  401. #endif
  402. endGroup( "Behavioral" );
  403. addProtectedField("customShaderFeature", TypeRealString, NULL, &protectedSetCustomShaderFeature, &defaultProtectedGetFn,
  404. "Do not modify, for internal use.", AbstractClassRep::FIELD_HideInInspectors);
  405. addProtectedField("CustomShaderFeatureUniforms", TypeRealString, NULL, &protectedSetCustomShaderFeatureUniforms, &defaultProtectedGetFn,
  406. "Do not modify, for internal use.", AbstractClassRep::FIELD_HideInInspectors);
  407. Parent::initPersistFields();
  408. }
  409. bool Material::writeField( StringTableEntry fieldname, const char *value )
  410. {
  411. // Never allow the old field names to be written.
  412. if ( fieldname == StringTable->insert("baseTex") ||
  413. fieldname == StringTable->insert("detailTex") ||
  414. fieldname == StringTable->insert("overlayTex") ||
  415. fieldname == StringTable->insert("bumpTex") ||
  416. fieldname == StringTable->insert("envTex") ||
  417. fieldname == StringTable->insert("colorMultiply") )
  418. return false;
  419. return Parent::writeField( fieldname, value );
  420. }
  421. bool Material::protectedSetCustomShaderFeature(void *object, const char *index, const char *data)
  422. {
  423. Material *material = static_cast< Material* >(object);
  424. CustomShaderFeatureData* customFeature;
  425. if (!Sim::findObject(data, customFeature))
  426. return false;
  427. material->mCustomShaderFeatures.push_back(customFeature);
  428. return false;
  429. }
  430. bool Material::protectedSetCustomShaderFeatureUniforms(void *object, const char *index, const char *data)
  431. {
  432. Material *material = static_cast< Material* >(object);
  433. if (index != NULL)
  434. {
  435. char featureName[256] = { 0 };
  436. U32 id = 0;
  437. dSscanf(index, "%s_%i", featureName, id);
  438. String uniformName = data;
  439. }
  440. return false;
  441. }
  442. bool Material::onAdd()
  443. {
  444. if (Parent::onAdd() == false)
  445. return false;
  446. mCubemapData = dynamic_cast<CubemapData*>(Sim::findObject( mCubemapName ) );
  447. if( mTranslucentBlendOp >= NumBlendTypes || mTranslucentBlendOp < 0 )
  448. {
  449. Con::errorf( "Invalid blend op in material: %s", getName() );
  450. mTranslucentBlendOp = LerpAlpha;
  451. }
  452. SimSet *matSet = MATMGR->getMaterialSet();
  453. if( matSet )
  454. matSet->addObject( (SimObject*)this );
  455. // save the current script path for texture lookup later
  456. const String scriptFile = Con::getVariable("$Con::File"); // current script file - local materials.cs
  457. String::SizeType slash = scriptFile.find( '/', scriptFile.length(), String::Right );
  458. if ( slash != String::NPos )
  459. mPath = scriptFile.substr( 0, slash + 1 );
  460. //bind any assets we have
  461. for (U32 i = 0; i < MAX_STAGES; i++)
  462. {
  463. if (mDiffuseMapAssetId[i] != StringTable->EmptyString())
  464. {
  465. mDiffuseMapAsset[0] = mDiffuseMapAssetId[0];
  466. }
  467. }
  468. _mapMaterial();
  469. return true;
  470. }
  471. void Material::onRemove()
  472. {
  473. smNormalizeCube = NULL;
  474. Parent::onRemove();
  475. }
  476. void Material::inspectPostApply()
  477. {
  478. Parent::inspectPostApply();
  479. // Reload the material instances which
  480. // use this material.
  481. if ( isProperlyAdded() )
  482. reload();
  483. }
  484. bool Material::isLightmapped() const
  485. {
  486. bool ret = false;
  487. for( U32 i=0; i<MAX_STAGES; i++ )
  488. ret |= mLightMapFilename[i].isNotEmpty() || mToneMapFilename[i].isNotEmpty() || mVertLit[i];
  489. return ret;
  490. }
  491. void Material::updateTimeBasedParams()
  492. {
  493. U32 lastTime = MATMGR->getLastUpdateTime();
  494. F32 dt = MATMGR->getDeltaTime();
  495. if (mLastUpdateTime != lastTime)
  496. {
  497. for (U32 i = 0; i < MAX_STAGES; i++)
  498. {
  499. mScrollOffset[i] += mScrollDir[i] * mScrollSpeed[i] * dt;
  500. mRotPos[i] += mRotSpeed[i] * dt;
  501. mWavePos[i] += mWaveFreq[i] * dt;
  502. }
  503. mLastUpdateTime = lastTime;
  504. }
  505. }
  506. void Material::_mapMaterial()
  507. {
  508. if( String(getName()).isEmpty() )
  509. {
  510. Con::warnf( "[Material::mapMaterial] - Cannot map unnamed Material" );
  511. return;
  512. }
  513. // If mapTo not defined in script, try to use the base texture name instead
  514. if( mMapTo.isEmpty() )
  515. {
  516. if ( mDiffuseMapFilename[0].isEmpty() && mDiffuseMapAsset->isNull())
  517. return;
  518. else
  519. {
  520. // extract filename from base texture
  521. if ( mDiffuseMapFilename[0].isNotEmpty() )
  522. {
  523. U32 slashPos = mDiffuseMapFilename[0].find('/',0,String::Right);
  524. if (slashPos == String::NPos)
  525. // no '/' character, must be no path, just the filename
  526. mMapTo = mDiffuseMapFilename[0];
  527. else
  528. // use everything after the last slash
  529. mMapTo = mDiffuseMapFilename[0].substr(slashPos+1, mDiffuseMapFilename[0].length() - slashPos - 1);
  530. }
  531. else if (!mDiffuseMapAsset->isNull())
  532. {
  533. mMapTo = mDiffuseMapAsset[0]->getImageFileName();
  534. }
  535. }
  536. }
  537. // add mapping
  538. MATMGR->mapMaterial(mMapTo,getName());
  539. }
  540. BaseMatInstance* Material::createMatInstance()
  541. {
  542. return new MatInstance(*this);
  543. }
  544. void Material::flush()
  545. {
  546. MATMGR->flushInstance( this );
  547. }
  548. void Material::reload()
  549. {
  550. MATMGR->reInitInstance( this );
  551. }
  552. void Material::StageData::getFeatureSet( FeatureSet *outFeatures ) const
  553. {
  554. TextureTable::ConstIterator iter = mTextures.begin();
  555. for ( ; iter != mTextures.end(); iter++ )
  556. {
  557. if ( iter->value.isValid() )
  558. outFeatures->addFeature( *iter->key );
  559. }
  560. }
  561. DefineEngineMethod( Material, flush, void, (),,
  562. "Flushes all material instances that use this material." )
  563. {
  564. object->flush();
  565. }
  566. DefineEngineMethod( Material, reload, void, (),,
  567. "Reloads all material instances that use this material." )
  568. {
  569. object->reload();
  570. }
  571. DefineEngineMethod( Material, dumpInstances, void, (),,
  572. "Dumps a formatted list of the currently allocated material instances for this material to the console." )
  573. {
  574. MATMGR->dumpMaterialInstances( object );
  575. }
  576. DefineEngineMethod(Material, getMaterialInstances, void, (GuiTreeViewCtrl* matTree), (nullAsType< GuiTreeViewCtrl*>()),
  577. "Dumps a formatted list of the currently allocated material instances for this material to the console.")
  578. {
  579. MATMGR->getMaterialInstances(object, matTree);
  580. }
  581. DefineEngineMethod( Material, getAnimFlags, const char*, (U32 id), , "" )
  582. {
  583. char * animFlags = Con::getReturnBuffer(512);
  584. if(object->mAnimFlags[ id ] & Material::Scroll)
  585. {
  586. if(dStrcmp( animFlags, "" ) == 0)
  587. dStrcpy( animFlags, "$Scroll", 512 );
  588. }
  589. if(object->mAnimFlags[ id ] & Material::Rotate)
  590. {
  591. if(dStrcmp( animFlags, "" ) == 0)
  592. dStrcpy( animFlags, "$Rotate", 512 );
  593. else
  594. dStrcat( animFlags, " | $Rotate", 512);
  595. }
  596. if(object->mAnimFlags[ id ] & Material::Wave)
  597. {
  598. if(dStrcmp( animFlags, "" ) == 0)
  599. dStrcpy( animFlags, "$Wave", 512 );
  600. else
  601. dStrcat( animFlags, " | $Wave", 512);
  602. }
  603. if(object->mAnimFlags[ id ] & Material::Scale)
  604. {
  605. if(dStrcmp( animFlags, "" ) == 0)
  606. dStrcpy( animFlags, "$Scale", 512 );
  607. else
  608. dStrcat( animFlags, " | $Scale", 512);
  609. }
  610. if(object->mAnimFlags[ id ] & Material::Sequence)
  611. {
  612. if(dStrcmp( animFlags, "" ) == 0)
  613. dStrcpy( animFlags, "$Sequence", 512 );
  614. else
  615. dStrcat( animFlags, " | $Sequence", 512);
  616. }
  617. return animFlags;
  618. }
  619. DefineEngineMethod(Material, getFilename, const char*, (),, "Get filename of material")
  620. {
  621. SimObject *material = static_cast<SimObject *>(object);
  622. return material->getFilename();
  623. }
  624. DefineEngineMethod( Material, isAutoGenerated, bool, (),,
  625. "Returns true if this Material was automatically generated by MaterialList::mapMaterials()" )
  626. {
  627. return object->isAutoGenerated();
  628. }
  629. DefineEngineMethod( Material, setAutoGenerated, void, (bool isAutoGenerated), ,
  630. "setAutoGenerated(bool isAutoGenerated): Set whether or not the Material is autogenerated." )
  631. {
  632. object->setAutoGenerated(isAutoGenerated);
  633. }
  634. DefineEngineMethod(Material, getAutogeneratedFile, const char*, (), , "Get filename of autogenerated shader file")
  635. {
  636. SimObject *material = static_cast<SimObject *>(object);
  637. return material->getFilename();
  638. }
  639. // Accumulation
  640. bool Material::_setAccuEnabled( void *object, const char *index, const char *data )
  641. {
  642. Material* mat = reinterpret_cast< Material* >( object );
  643. if ( index )
  644. {
  645. U32 i = dAtoui(index);
  646. mat->mAccuEnabled[i] = dAtob(data);
  647. AccumulationVolume::refreshVolumes();
  648. }
  649. return true;
  650. }