assimpAppMaterial.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. #define TORQUE_PBR_MATERIALS
  23. #include "platform/platform.h"
  24. #include "ts/loader/appSequence.h"
  25. #include "ts/assimp/assimpAppMaterial.h"
  26. #include "ts/assimp/assimpAppMesh.h"
  27. #include "materials/materialManager.h"
  28. #include "ts/tsMaterialList.h"
  29. #include "core/stream/fileStream.h"
  30. // assimp include files.
  31. #include <assimp/cimport.h>
  32. #include <assimp/scene.h>
  33. #include <assimp/postprocess.h>
  34. #include <assimp/types.h>
  35. U32 AssimpAppMaterial::sDefaultMatNumber = 0;
  36. String AppMaterial::cleanString(const String& str)
  37. {
  38. String cleanStr(str);
  39. // Replace invalid characters with underscores
  40. const String badChars(" -,.+=*/[]%$~;:");
  41. for (String::SizeType i = 0; i < badChars.length(); i++)
  42. cleanStr.replace(badChars[i], '_');
  43. // Prefix with an underscore if string starts with a number
  44. if ((cleanStr[0] >= '0') && (cleanStr[0] <= '9'))
  45. cleanStr.insert(0, '_');
  46. return cleanStr;
  47. }
  48. AssimpAppMaterial::AssimpAppMaterial(const char* matName)
  49. {
  50. name = ColladaUtils::getOptions().matNamePrefix;
  51. name += matName;
  52. mAIMat = NULL;
  53. // Set some defaults
  54. flags |= TSMaterialList::S_Wrap;
  55. flags |= TSMaterialList::T_Wrap;
  56. }
  57. AssimpAppMaterial::AssimpAppMaterial(aiMaterial* mtl) :
  58. mAIMat(mtl)
  59. {
  60. aiString matName;
  61. mtl->Get(AI_MATKEY_NAME, matName);
  62. name = matName.C_Str();
  63. if (name.isEmpty())
  64. {
  65. name = cleanString(TSShapeLoader::getShapePath().getFileName());
  66. name += "_defMat";
  67. name += String::ToString("%d", sDefaultMatNumber);
  68. sDefaultMatNumber++;
  69. }
  70. name = ColladaUtils::getOptions().matNamePrefix + name;
  71. Con::printf("[ASSIMP] Loading Material: %s", name.c_str());
  72. #ifdef TORQUE_DEBUG
  73. enumerateMaterialProperties(mtl);
  74. #endif
  75. }
  76. Material* AssimpAppMaterial::createMaterial(const Torque::Path& path) const
  77. {
  78. // The filename and material name are used as TorqueScript identifiers, so
  79. // clean them up first
  80. String cleanFile = cleanString(TSShapeLoader::getShapePath().getFileName());
  81. String cleanName = cleanString(getName());
  82. // Create the Material definition
  83. const String oldScriptFile = Con::getVariable("$Con::File");
  84. Con::setVariable("$Con::File", path.getFullPath()); // modify current script path so texture lookups are correct
  85. Material *newMat = MATMGR->allocateAndRegister(cleanName, getName());
  86. Con::setVariable("$Con::File", oldScriptFile); // restore script path
  87. initMaterial(path, newMat);
  88. return newMat;
  89. }
  90. void AssimpAppMaterial::initMaterial(const Torque::Path& path, Material* mat) const
  91. {
  92. String cleanFile = cleanString(TSShapeLoader::getShapePath().getFileName());
  93. String cleanName = cleanString(getName());
  94. // Determine the blend mode and transparency for this material
  95. Material::BlendOp blendOp = Material::None;
  96. bool translucent = false;
  97. float opacity = 1.0f;
  98. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_OPACITY, opacity))
  99. {
  100. if (opacity != 1.0f)
  101. {
  102. translucent = true;
  103. int blendInt;
  104. blendOp = Material::LerpAlpha;
  105. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_BLEND_FUNC, blendInt))
  106. {
  107. if (blendInt == aiBlendMode_Additive)
  108. blendOp = Material::Add;
  109. }
  110. }
  111. }
  112. else
  113. { // No opacity key, see if it's defined as a gltf property
  114. aiString opacityMode;
  115. if (AI_SUCCESS == mAIMat->Get("$mat.gltf.alphaMode", 0, 0, opacityMode))
  116. {
  117. if (String::compare("MASK", opacityMode.C_Str()) == 0)
  118. {
  119. translucent = true;
  120. blendOp = Material::None;
  121. float cutoff;
  122. if (AI_SUCCESS == mAIMat->Get("$mat.gltf.alphaCutoff", 0, 0, cutoff))
  123. {
  124. mat->mAlphaRef = (U32)(cutoff * 255); // alpha ref 0-255
  125. mat->mAlphaTest = true;
  126. }
  127. }
  128. else if (String::compare("BLEND", opacityMode.C_Str()) == 0)
  129. {
  130. translucent = true;
  131. blendOp = Material::LerpAlpha;
  132. mat->mAlphaTest = false;
  133. }
  134. else
  135. { // OPAQUE
  136. translucent = false;
  137. blendOp = Material::LerpAlpha; // Make default so it doesn't get written to materials.tscript
  138. }
  139. }
  140. }
  141. mat->mTranslucent = translucent;
  142. mat->mTranslucentBlendOp = blendOp;
  143. // Assign color values.
  144. LinearColorF diffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
  145. aiColor3D read_color(1.f, 1.f, 1.f);
  146. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_COLOR_DIFFUSE, read_color))
  147. diffuseColor.set(read_color.r, read_color.g, read_color.b, opacity);
  148. mat->mDiffuse[0] = diffuseColor;
  149. aiString texName;
  150. String torquePath;
  151. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), texName))
  152. {
  153. torquePath = texName.C_Str();
  154. if (!torquePath.isEmpty())
  155. mat->mDiffuseMapName[0] = cleanTextureName(torquePath, cleanFile, path, false);
  156. }
  157. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), texName))
  158. {
  159. torquePath = texName.C_Str();
  160. if (!torquePath.isEmpty())
  161. mat->mNormalMapName[0] = cleanTextureName(torquePath, cleanFile, path, false);
  162. }
  163. #ifdef TORQUE_PBR_MATERIALS
  164. float floatVal;
  165. if (AI_SUCCESS == mAIMat->Get("$mat.gltf.pbrMetallicRoughness.roughnessFactor", 0, 0, floatVal))
  166. { // The shape has pbr material definitions
  167. String aoName, rmName; // occlusion and roughness/metalness maps
  168. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), texName))
  169. aoName = texName.C_Str();
  170. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_UNKNOWN, 0), texName))
  171. rmName = texName.C_Str();
  172. if (aoName.isNotEmpty() || rmName.isNotEmpty())
  173. { // If we have either map, fill all three slots
  174. if (rmName.isNotEmpty())
  175. {
  176. mat->mRoughMapName[0] = cleanTextureName(rmName, cleanFile, path, false); // Roughness
  177. mat->mRoughnessChan[0] = 1.0f;
  178. mat->mInvertRoughness[0] = (floatVal == 1.0f);
  179. mat->mMetalMapName[0] = cleanTextureName(rmName, cleanFile, path, false); // Metallic
  180. mat->mMetalChan[0] = 2.0f;
  181. }
  182. if (aoName.isNotEmpty())
  183. {
  184. mat->mAOMapName[0] = cleanTextureName(aoName, cleanFile, path, false); // occlusion
  185. mat->mAOChan[0] = 0.0f;
  186. }
  187. else
  188. {
  189. mat->mAOMapName[0] = cleanTextureName(rmName, cleanFile, path, false); // occlusion
  190. mat->mAOChan[0] = 0.0f;
  191. }
  192. }
  193. }
  194. #else
  195. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), texName))
  196. {
  197. torquePath = texName.C_Str();
  198. if (!torquePath.isEmpty())
  199. mat->mSpecularMapFilename[0] = cleanTextureName(torquePath, cleanFile, path, false);
  200. }
  201. /*LinearColorF specularColor(1.0f, 1.0f, 1.0f, 1.0f);
  202. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_COLOR_SPECULAR, read_color))
  203. specularColor.set(read_color.r, read_color.g, read_color.b, opacity);
  204. mat->mMetalness[0] = specularColor;
  205. // Specular Power
  206. F32 specularPower = 1.0f;
  207. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_SHININESS_STRENGTH, specularPower))
  208. mat->mSpecularPower[0] = specularPower;
  209. // Specular
  210. F32 specularStrength = 0.0f;
  211. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_SHININESS, specularStrength))
  212. mat->mSpecularStrength[0] = specularStrength;*/
  213. #endif
  214. // Double-Sided
  215. bool doubleSided = false;
  216. S32 dbl_sided = 0;
  217. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TWOSIDED, dbl_sided))
  218. doubleSided = (dbl_sided != 0);
  219. mat->mDoubleSided = doubleSided;
  220. }
  221. String AssimpAppMaterial::cleanTextureName(String& texName, String& shapeName, const Torque::Path& path, bool nameOnly /*= false*/)
  222. {
  223. Torque::Path foundPath;
  224. String cleanStr;
  225. if (texName[0] == '*')
  226. { // It's an embedded texture reference. Make the cached name and return
  227. cleanStr = shapeName;
  228. cleanStr += "_cachedTex";
  229. cleanStr += texName.substr(1);
  230. return cleanStr;
  231. }
  232. // See if the file exists
  233. bool fileFound = false;
  234. String testPath = path.getPath();
  235. testPath += '/';
  236. testPath += texName;
  237. testPath.replace('\\', '/');
  238. fileFound = Torque::FS::IsFile(testPath);
  239. cleanStr = texName;
  240. cleanStr.replace('\\', '/');
  241. if (fileFound)
  242. {
  243. if (cleanStr.equal(texName))
  244. return cleanStr;
  245. foundPath = testPath;
  246. }
  247. else
  248. {
  249. // See if the file is in a sub-directory of the shape
  250. Vector<String> foundFiles;
  251. Torque::Path inPath(cleanStr);
  252. String mainDotCsDir = Platform::getMainDotCsDir();
  253. mainDotCsDir += "/";
  254. S32 results = Torque::FS::FindByPattern(Torque::Path(mainDotCsDir + path.getPath() + "/"), inPath.getFullFileName(), true, foundFiles);
  255. if (results == 0 || foundFiles.size() == 0) // Not under shape directory, try the full tree
  256. results = Torque::FS::FindByPattern(Torque::Path(mainDotCsDir), inPath.getFullFileName(), true, foundFiles);
  257. if (results > 0 && foundFiles.size() > 0)
  258. {
  259. fileFound = true;
  260. foundPath = foundFiles[0];
  261. }
  262. }
  263. if (fileFound)
  264. {
  265. if (nameOnly)
  266. cleanStr = foundPath.getFullFileName();
  267. else
  268. { // Unless the file is in the same directory as the materials.tscript (covered above)
  269. // we need to set the full path from the root directory. If we use "subdirectory/file.ext",
  270. // the material manager won't find the image file, but it will be found the next time the
  271. // material is loaded from file. If we use "./subdirectory/file.ext", the image will be found
  272. // now, but not the next time it's loaded from file...
  273. S32 rootLength = dStrlen(Platform::getMainDotCsDir());
  274. cleanStr = foundPath.getFullPathWithoutRoot().substr(rootLength-1);
  275. }
  276. }
  277. else if (nameOnly)
  278. cleanStr += " (Not Found)";
  279. return cleanStr;
  280. }
  281. #ifdef TORQUE_DEBUG
  282. void AssimpAppMaterial::enumerateMaterialProperties(aiMaterial* mtl)
  283. {
  284. for (U32 i = 0; i < mtl->mNumProperties; ++i)
  285. {
  286. aiMaterialProperty* matProp = mtl->mProperties[i];
  287. String outText;
  288. if (matProp)
  289. {
  290. outText = String::ToString(" Key: %s, Index: %d, Semantic: ", matProp->mKey.C_Str(), matProp->mIndex);
  291. switch (matProp->mSemantic)
  292. {
  293. case aiTextureType_NONE:
  294. outText += "aiTextureType_NONE";
  295. break;
  296. case aiTextureType_DIFFUSE:
  297. outText += "aiTextureType_DIFFUSE";
  298. break;
  299. case aiTextureType_SPECULAR:
  300. outText += "aiTextureType_SPECULAR";
  301. break;
  302. case aiTextureType_AMBIENT:
  303. outText += "aiTextureType_AMBIENT";
  304. break;
  305. case aiTextureType_EMISSIVE:
  306. outText += "aiTextureType_EMISSIVE";
  307. break;
  308. case aiTextureType_HEIGHT:
  309. outText += "aiTextureType_HEIGHT";
  310. break;
  311. case aiTextureType_NORMALS:
  312. outText += "aiTextureType_NORMALS";
  313. break;
  314. case aiTextureType_SHININESS:
  315. outText += "aiTextureType_SHININESS";
  316. break;
  317. case aiTextureType_OPACITY:
  318. outText += "aiTextureType_OPACITY";
  319. break;
  320. case aiTextureType_DISPLACEMENT:
  321. outText += "aiTextureType_DISPLACEMENT";
  322. break;
  323. case aiTextureType_LIGHTMAP:
  324. outText += "aiTextureType_LIGHTMAP";
  325. break;
  326. case aiTextureType_REFLECTION:
  327. outText += "aiTextureType_REFLECTION";
  328. break;
  329. default:
  330. outText += "aiTextureType_UNKNOWN";
  331. break;
  332. }
  333. aiString stringProp;
  334. F32* floatProp;
  335. double* doubleProp;
  336. S32* intProp;
  337. switch (matProp->mType)
  338. {
  339. case aiPTI_Float:
  340. floatProp = (F32*)matProp->mData;
  341. for (U32 j = 0; j < matProp->mDataLength / sizeof(F32); ++j)
  342. outText += String::ToString(", %0.4f", floatProp[j]);
  343. break;
  344. case aiPTI_Double:
  345. doubleProp = (double*)matProp->mData;
  346. for (U32 j = 0; j < matProp->mDataLength / sizeof(double); ++j)
  347. outText += String::ToString(", %0.4lf", doubleProp[j]);
  348. break;
  349. case aiPTI_String:
  350. aiGetMaterialString(mtl, matProp->mKey.C_Str(), matProp->mSemantic, matProp->mIndex, &stringProp);
  351. outText += String::ToString(", %s", stringProp.C_Str());
  352. break;
  353. case aiPTI_Integer:
  354. intProp = (S32*)matProp->mData;
  355. for (U32 j = 0; j < matProp->mDataLength / sizeof(S32); ++j)
  356. outText += String::ToString(", %d", intProp[j]);
  357. break;
  358. case aiPTI_Buffer:
  359. outText += ", aiPTI_Buffer format data";
  360. break;
  361. default:
  362. outText += ", Unknown data type";
  363. }
  364. Con::printf("%s", outText.c_str());
  365. }
  366. }
  367. }
  368. #endif