materialList.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "materials/materialList.h"
  28. #include "materials/matInstance.h"
  29. #include "materials/materialManager.h"
  30. #include "materials/materialFeatureTypes.h"
  31. #include "materials/processedMaterial.h"
  32. #include "core/volume.h"
  33. #include "console/simSet.h"
  34. #include "scene/reflectionManager.h"
  35. #include "renderInstance/renderDeferredMgr.h"
  36. #include "lighting/advanced/advancedLightManager.h"
  37. #include "lighting/advanced/advancedLightBinManager.h"
  38. MaterialList::MaterialList()
  39. {
  40. VECTOR_SET_ASSOCIATION(mMatInstList);
  41. VECTOR_SET_ASSOCIATION(mMaterialNames);
  42. }
  43. MaterialList::MaterialList(const MaterialList* pCopy)
  44. {
  45. VECTOR_SET_ASSOCIATION(mMatInstList);
  46. VECTOR_SET_ASSOCIATION(mMaterialNames);
  47. mMaterialNames.setSize(pCopy->mMaterialNames.size());
  48. S32 i;
  49. for (i = 0; i < mMaterialNames.size(); i++)
  50. {
  51. mMaterialNames[i] = pCopy->mMaterialNames[i];
  52. }
  53. clearMatInstList();
  54. mMatInstList.setSize(pCopy->size());
  55. for( i = 0; i < mMatInstList.size(); i++ )
  56. {
  57. if( i < pCopy->mMatInstList.size() && pCopy->mMatInstList[i] )
  58. {
  59. mMatInstList[i] = pCopy->mMatInstList[i]->getMaterial()->createMatInstance();
  60. }
  61. else
  62. {
  63. mMatInstList[i] = NULL;
  64. }
  65. }
  66. }
  67. MaterialList::MaterialList(U32 materialCount, const char **materialNames)
  68. {
  69. VECTOR_SET_ASSOCIATION(mMaterialNames);
  70. set(materialCount, materialNames);
  71. }
  72. //--------------------------------------
  73. void MaterialList::set(U32 materialCount, const char **materialNames)
  74. {
  75. free();
  76. mMaterialNames.setSize(materialCount);
  77. clearMatInstList();
  78. mMatInstList.setSize(materialCount);
  79. for(U32 i = 0; i < materialCount; i++)
  80. {
  81. mMaterialNames[i] = materialNames[i];
  82. mMatInstList[i] = NULL;
  83. }
  84. }
  85. //--------------------------------------
  86. MaterialList::~MaterialList()
  87. {
  88. free();
  89. }
  90. //--------------------------------------
  91. void MaterialList::setMaterialName(U32 index, const String& name)
  92. {
  93. if (index < mMaterialNames.size())
  94. mMaterialNames[index] = name;
  95. }
  96. //--------------------------------------
  97. GFXTextureObject *MaterialList::getDiffuseTexture(U32 index)
  98. {
  99. AssertFatal(index < (U32) mMatInstList.size(), "MaterialList::getDiffuseTex: index lookup out of range.");
  100. MatInstance *matInst = dynamic_cast<MatInstance*>(mMatInstList[index]);
  101. if (matInst && matInst->getProcessedMaterial())
  102. return matInst->getProcessedMaterial()->getStageTexture(0, MFT_DiffuseMap);
  103. else
  104. return NULL;
  105. }
  106. //--------------------------------------
  107. void MaterialList::free()
  108. {
  109. clearMatInstList();
  110. mMatInstList.clear();
  111. mMaterialNames.clear();
  112. }
  113. /*
  114. //--------------------------------------
  115. U32 MaterialList::push_back(GFXTexHandle textureHandle, const String &filename)
  116. {
  117. mMaterialNames.push_back(filename);
  118. mMatInstList.push_back(NULL);
  119. // return the index
  120. return mMaterialNames.size()-1;
  121. }
  122. */
  123. //--------------------------------------
  124. U32 MaterialList::push_back(const String &filename, Material* material)
  125. {
  126. mMaterialNames.push_back(filename);
  127. mMatInstList.push_back(material ? material->createMatInstance() : NULL);
  128. // return the index
  129. return mMaterialNames.size()-1;
  130. }
  131. //--------------------------------------
  132. bool MaterialList::read(Stream &stream)
  133. {
  134. free();
  135. // check the stream version
  136. U8 version;
  137. if ( stream.read(&version) && version != BINARY_FILE_VERSION)
  138. return readText(stream,version);
  139. // how many materials?
  140. U32 count;
  141. if ( !stream.read(&count) )
  142. return false;
  143. // pre-size the vectors for efficiency
  144. mMaterialNames.reserve(count);
  145. // read in the materials
  146. for (U32 i=0; i<count; i++)
  147. {
  148. // Load the bitmap name
  149. char buffer[256];
  150. stream.readString(buffer);
  151. if( !buffer[0] )
  152. {
  153. AssertWarn(0, "MaterialList::read: error reading stream");
  154. return false;
  155. }
  156. // Material paths are a legacy of Tribes tools,
  157. // strip them off...
  158. char *name = &buffer[dStrlen(buffer)];
  159. while (name != buffer && name[-1] != '/' && name[-1] != '\\')
  160. name--;
  161. // Add it to the list
  162. mMaterialNames.push_back(name);
  163. mMatInstList.push_back(NULL);
  164. }
  165. return (stream.getStatus() == Stream::Ok);
  166. }
  167. //--------------------------------------
  168. bool MaterialList::write(Stream &stream)
  169. {
  170. stream.write((U8)BINARY_FILE_VERSION); // version
  171. stream.write((U32)mMaterialNames.size()); // material count
  172. for(S32 i=0; i < mMaterialNames.size(); i++) // material names
  173. stream.writeString(mMaterialNames[i]);
  174. return (stream.getStatus() == Stream::Ok);
  175. }
  176. //--------------------------------------
  177. bool MaterialList::readText(Stream &stream, U8 firstByte)
  178. {
  179. free();
  180. if (!firstByte)
  181. return (stream.getStatus() == Stream::Ok || stream.getStatus() == Stream::EOS);
  182. char buf[1024];
  183. buf[0] = firstByte;
  184. U32 offset = 1;
  185. for(;;)
  186. {
  187. stream.readLine((U8*)(buf+offset), sizeof(buf)-offset);
  188. if(!buf[0])
  189. break;
  190. offset = 0;
  191. // Material paths are a legacy of Tribes tools,
  192. // strip them off...
  193. char *name = &buf[dStrlen(buf)];
  194. while (name != buf && name[-1] != '/' && name[-1] != '\\')
  195. name--;
  196. // Add it to the list
  197. mMaterialNames.push_back(name);
  198. mMatInstList.push_back(NULL);
  199. }
  200. return (stream.getStatus() == Stream::Ok || stream.getStatus() == Stream::EOS);
  201. }
  202. bool MaterialList::readText(Stream &stream)
  203. {
  204. U8 firstByte;
  205. stream.read(&firstByte);
  206. return readText(stream,firstByte);
  207. }
  208. //--------------------------------------
  209. bool MaterialList::writeText(Stream &stream)
  210. {
  211. for(S32 i=0; i < mMaterialNames.size(); i++)
  212. stream.writeLine((U8*)(mMaterialNames[i].c_str()));
  213. stream.writeLine((U8*)"");
  214. return (stream.getStatus() == Stream::Ok);
  215. }
  216. //--------------------------------------------------------------------------
  217. // Clear all materials in the mMatInstList member variable
  218. //--------------------------------------------------------------------------
  219. void MaterialList::clearMatInstList()
  220. {
  221. // clear out old materials. any non null element of the list should be pointing at deletable memory,
  222. // although multiple indexes may be pointing at the same memory so we have to be careful (see
  223. // comment in loop body)
  224. for (U32 i=0; i<mMatInstList.size(); i++)
  225. {
  226. if (mMatInstList[i])
  227. {
  228. BaseMatInstance* current = mMatInstList[i];
  229. // ok, since ts material lists can remap difference indexes to the same object
  230. // we need to make sure that we don't delete the same memory twice. walk the
  231. // rest of the list and null out any pointers that match the one we deleted.
  232. for (U32 j=0; j<mMatInstList.size(); j++)
  233. if (mMatInstList[j] == current)
  234. mMatInstList[j] = NULL;
  235. mMatInstList[i] = NULL;
  236. delete current;
  237. }
  238. }
  239. }
  240. //--------------------------------------------------------------------------
  241. // Map materials - map materials to the textures in the list
  242. //--------------------------------------------------------------------------
  243. void MaterialList::mapMaterials()
  244. {
  245. mMatInstList.setSize( mMaterialNames.size() );
  246. for( U32 i=0; i<mMaterialNames.size(); i++ )
  247. mapMaterial( i );
  248. }
  249. /// Map the material name at the given index to a material instance.
  250. ///
  251. /// @note The material instance that is created will <em>not be initialized.</em>
  252. void MaterialList::mapMaterial( U32 i )
  253. {
  254. AssertFatal( i < size(), "MaterialList::mapMaterialList - index out of bounds" );
  255. if( mMatInstList[i] != NULL )
  256. return;
  257. // lookup a material property entry
  258. const String &matName = getMaterialName(i);
  259. // JMQ: this code assumes that all materials have names.
  260. if( matName.isEmpty() )
  261. {
  262. mMatInstList[i] = NULL;
  263. return;
  264. }
  265. String materialName;
  266. // Skip past a leading '#' marker.
  267. if (matName.compare("#", 1) == 0)
  268. materialName = MATMGR->getMapEntry(matName.substr(1, matName.length()-1));
  269. else
  270. materialName = MATMGR->getMapEntry(matName);
  271. // IF we didn't find it, then look for a PolyStatic generated Material
  272. // [a little cheesy, but we need to allow for user override of generated Materials]
  273. if ( materialName.isEmpty() )
  274. materialName = MATMGR->getMapEntry( String::ToString( "polyMat_%s", matName.c_str() ) );
  275. if ( materialName.isNotEmpty() )
  276. {
  277. Material * mat = MATMGR->getMaterialDefinitionByName( materialName );
  278. mMatInstList[i] = mat ? mat->createMatInstance() : MATMGR->createWarningMatInstance();
  279. }
  280. else
  281. {
  282. if ( Con::getBoolVariable( "$Materials::createMissing", true ) )
  283. {
  284. // No Material found, create new "default" material with just a diffuseMap
  285. // First see if there is a valid diffuse texture
  286. GFXTexHandle texHandle;
  287. if (mLookupPath.isEmpty())
  288. {
  289. texHandle.set( mMaterialNames[i], &GFXStaticTextureSRGBProfile, avar("%s() - handle (line %d)", __FUNCTION__, __LINE__) );
  290. }
  291. else
  292. {
  293. // Should we strip off the extension of the path here before trying
  294. // to load the texture?
  295. String fullPath = String::ToString( "%s/%s", mLookupPath.c_str(), mMaterialNames[i].c_str() );
  296. texHandle.set( fullPath, &GFXStaticTextureSRGBProfile, avar("%s() - handle (line %d)", __FUNCTION__, __LINE__) );
  297. }
  298. if ( texHandle.isValid() )
  299. {
  300. String newMatName = Sim::getUniqueName( "DefaultMaterial" );
  301. Material *newMat = MATMGR->allocateAndRegister( newMatName, mMaterialNames[i] );
  302. // Flag this as an autogenerated Material
  303. newMat->mAutoGenerated = true;
  304. // Overwrite diffuseMap in new material
  305. newMat->_setDiffuseMap(texHandle->mTextureLookupName,0);
  306. // Set up some defaults for transparent textures
  307. if (texHandle->mHasTransparency)
  308. {
  309. newMat->mTranslucent = true;
  310. newMat->mTranslucentBlendOp = Material::LerpAlpha;
  311. newMat->mTranslucentZWrite = true;
  312. newMat->mAlphaRef = 20;
  313. }
  314. // create a MatInstance for the new material
  315. mMatInstList[i] = newMat->createMatInstance();
  316. #ifndef TORQUE_SHIPPING
  317. Con::warnf( "[MaterialList::mapMaterials] Creating missing material for texture: %s", texHandle->mTextureLookupName.c_str() );
  318. #endif
  319. }
  320. else
  321. {
  322. Con::errorf( "[MaterialList::mapMaterials] Unable to find material for texture: %s", mMaterialNames[i].c_str() );
  323. mMatInstList[i] = MATMGR->createWarningMatInstance();
  324. }
  325. }
  326. else
  327. {
  328. mMatInstList[i] = MATMGR->createWarningMatInstance();
  329. }
  330. }
  331. }
  332. void MaterialList::initMatInstances( const FeatureSet &features,
  333. const GFXVertexFormat *vertexFormat )
  334. {
  335. for( U32 i=0; i < mMatInstList.size(); i++ )
  336. {
  337. BaseMatInstance *matInst = mMatInstList[i];
  338. if ( !matInst )
  339. continue;
  340. if ( !matInst->init( features, vertexFormat ) )
  341. {
  342. Con::errorf( "MaterialList::initMatInstances - failed to initialize material instance for '%s'",
  343. matInst->getMaterial()->getName() );
  344. // Fall back to warning material.
  345. SAFE_DELETE( matInst );
  346. matInst = MATMGR->createMatInstance( "WarningMaterial" );
  347. matInst->init( MATMGR->getDefaultFeatures(), vertexFormat );
  348. mMatInstList[ i ] = matInst;
  349. }
  350. else
  351. {
  352. AdvancedLightManager* lightMgr = dynamic_cast<AdvancedLightManager*>(LIGHTMGR);
  353. if (lightMgr)
  354. {
  355. REFLECTMGR->getReflectionMaterial(matInst);
  356. // Hunt for the pre-pass manager/target
  357. lightMgr->getDeferredRenderBin()->getDeferredMaterial(matInst);
  358. }
  359. }
  360. }
  361. }
  362. void MaterialList::setMaterialInst( BaseMatInstance *matInst, U32 texIndex )
  363. {
  364. AssertFatal( texIndex < mMatInstList.size(), "MaterialList::setMaterialInst - index out of bounds" );
  365. mMatInstList[texIndex] = matInst;
  366. }