materialList.cpp 13 KB

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