assimpAppMaterial.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. // assimp include files.
  30. #include <assimp/cimport.h>
  31. #include <assimp/scene.h>
  32. #include <assimp/postprocess.h>
  33. #include <assimp/types.h>
  34. String AppMaterial::cleanString(const String& str)
  35. {
  36. String cleanStr(str);
  37. // Replace invalid characters with underscores
  38. const String badChars(" -,.+=*/[]");
  39. for (String::SizeType i = 0; i < badChars.length(); i++)
  40. cleanStr.replace(badChars[i], '_');
  41. // Prefix with an underscore if string starts with a number
  42. if ((cleanStr[0] >= '0') && (cleanStr[0] <= '9'))
  43. cleanStr.insert(0, '_');
  44. return cleanStr;
  45. }
  46. AssimpAppMaterial::AssimpAppMaterial(const char* matName)
  47. {
  48. name = matName;
  49. // Set some defaults
  50. flags |= TSMaterialList::S_Wrap;
  51. flags |= TSMaterialList::T_Wrap;
  52. }
  53. AssimpAppMaterial::AssimpAppMaterial(aiMaterial* mtl) :
  54. mAIMat(mtl)
  55. {
  56. aiString matName;
  57. mtl->Get(AI_MATKEY_NAME, matName);
  58. name = matName.C_Str();
  59. if (name.isEmpty())
  60. {
  61. name = cleanString(TSShapeLoader::getShapePath().getFileName());;
  62. name += "_defMat";
  63. }
  64. Con::printf("[ASSIMP] Loading Material: %s", name.c_str());
  65. #ifdef TORQUE_DEBUG
  66. enumerateMaterialProperties(mtl);
  67. #endif
  68. }
  69. Material* AssimpAppMaterial::createMaterial(const Torque::Path& path) const
  70. {
  71. // The filename and material name are used as TorqueScript identifiers, so
  72. // clean them up first
  73. String cleanFile = cleanString(TSShapeLoader::getShapePath().getFileName());
  74. String cleanName = cleanString(getName());
  75. // Create the Material definition
  76. const String oldScriptFile = Con::getVariable("$Con::File");
  77. Con::setVariable("$Con::File", path.getFullPath()); // modify current script path so texture lookups are correct
  78. Material *newMat = MATMGR->allocateAndRegister(cleanName, getName());
  79. Con::setVariable("$Con::File", oldScriptFile); // restore script path
  80. initMaterial(path, newMat);
  81. return newMat;
  82. }
  83. void AssimpAppMaterial::initMaterial(const Torque::Path& path, Material* mat) const
  84. {
  85. String cleanFile = cleanString(TSShapeLoader::getShapePath().getFileName());
  86. String cleanName = cleanString(getName());
  87. // Determine the blend mode and transparency for this material
  88. Material::BlendOp blendOp = Material::None;
  89. bool translucent = false;
  90. float opacity = 1.0f;
  91. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_OPACITY, opacity))
  92. {
  93. if (opacity != 1.0f)
  94. {
  95. translucent = true;
  96. int blendInt;
  97. blendOp = Material::LerpAlpha;
  98. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_BLEND_FUNC, blendInt))
  99. {
  100. if (blendInt == aiBlendMode_Additive)
  101. blendOp = Material::Add;
  102. }
  103. }
  104. }
  105. else
  106. { // No opacity key, see if it's defined as a gltf property
  107. aiString opacityMode;
  108. if (AI_SUCCESS == mAIMat->Get("$mat.gltf.alphaMode", 0, 0, opacityMode))
  109. {
  110. if (dStrcmp("MASK", opacityMode.C_Str()) == 0)
  111. {
  112. translucent = true;
  113. blendOp = Material::LerpAlpha;
  114. float cutoff;
  115. if (AI_SUCCESS == mAIMat->Get("$mat.gltf.alphaCutoff", 0, 0, cutoff))
  116. {
  117. mat->mAlphaRef = (U32)(cutoff * 255); // alpha ref 0-255
  118. mat->mAlphaTest = true;
  119. }
  120. }
  121. else if (dStrcmp("OPAQUE", opacityMode.C_Str()) != 0)
  122. {
  123. translucent = true;
  124. blendOp = Material::LerpAlpha;
  125. }
  126. }
  127. }
  128. mat->mTranslucent = translucent;
  129. mat->mTranslucentBlendOp = blendOp;
  130. // Assign color values.
  131. LinearColorF diffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
  132. aiColor3D read_color(1.f, 1.f, 1.f);
  133. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_COLOR_DIFFUSE, read_color))
  134. diffuseColor.set(read_color.r, read_color.g, read_color.b, opacity);
  135. mat->mDiffuse[0] = diffuseColor;
  136. aiString texName;
  137. String torquePath;
  138. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), texName))
  139. {
  140. torquePath = texName.C_Str();
  141. if (!torquePath.isEmpty())
  142. mat->mDiffuseMapFilename[0] = cleanTextureName(torquePath, cleanFile);
  143. }
  144. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), texName))
  145. {
  146. torquePath = texName.C_Str();
  147. if (!torquePath.isEmpty())
  148. mat->mNormalMapFilename[0] = cleanTextureName(torquePath, cleanFile);
  149. }
  150. #ifdef TORQUE_PBR_MATERIALS
  151. float floatVal;
  152. if (AI_SUCCESS == mAIMat->Get("$mat.gltf.pbrMetallicRoughness.roughnessFactor", 0, 0, floatVal))
  153. { // The shape has pbr material definitions
  154. String aoName, rmName; // occlusion and roughness/metalness maps
  155. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), texName))
  156. aoName = texName.C_Str();
  157. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_UNKNOWN, 0), texName))
  158. rmName = texName.C_Str();
  159. //if (aoName.isNotEmpty() && (aoName == rmName))
  160. // mat->mOrmMapFilename[0] = cleanTextureName(aoName, cleanFile); // It's an ORM map
  161. //else if (aoName.isNotEmpty() || rmName.isNotEmpty())
  162. if (aoName.isNotEmpty() || rmName.isNotEmpty())
  163. { // If we have either map, fill all three slots
  164. if (rmName.isNotEmpty())
  165. {
  166. mat->mRoughMapFilename[0] = cleanTextureName(rmName, cleanFile); // Roughness
  167. mat->mSmoothnessChan[0] = 1.0f;
  168. mat->mInvertSmoothness = (floatVal == 1.0f);
  169. mat->mMetalMapFilename[0] = cleanTextureName(rmName, cleanFile); // Metallic
  170. mat->mMetalChan[0] = 2.0f;
  171. }
  172. if (aoName.isNotEmpty())
  173. {
  174. mat->mAOMapFilename[0] = cleanTextureName(aoName, cleanFile); // occlusion
  175. mat->mAOChan[0] = 0.0f;
  176. }
  177. else
  178. {
  179. mat->mAOMapFilename[0] = cleanTextureName(rmName, cleanFile); // occlusion
  180. mat->mAOChan[0] = 0.0f;
  181. }
  182. }
  183. }
  184. #else
  185. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), texName))
  186. {
  187. torquePath = texName.C_Str();
  188. if (!torquePath.isEmpty())
  189. mat->mSpecularMapFilename[0] = cleanTextureName(torquePath, cleanFile);
  190. }
  191. LinearColorF specularColor(1.0f, 1.0f, 1.0f, 1.0f);
  192. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_COLOR_SPECULAR, read_color))
  193. specularColor.set(read_color.r, read_color.g, read_color.b, opacity);
  194. mat->mSpecular[0] = specularColor;
  195. // Specular Power
  196. F32 specularPower = 1.0f;
  197. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_SHININESS_STRENGTH, specularPower))
  198. mat->mSpecularPower[0] = specularPower;
  199. // Specular
  200. F32 specularStrength = 0.0f;
  201. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_SHININESS, specularStrength))
  202. mat->mSpecularStrength[0] = specularStrength;
  203. #endif
  204. // Double-Sided
  205. bool doubleSided = false;
  206. S32 dbl_sided = 0;
  207. if (AI_SUCCESS == mAIMat->Get(AI_MATKEY_TWOSIDED, dbl_sided))
  208. doubleSided = (dbl_sided != 0);
  209. mat->mDoubleSided = doubleSided;
  210. }
  211. String AssimpAppMaterial::cleanTextureName(String& texName, String& shapeName)
  212. {
  213. String cleanStr;
  214. if (texName[0] == '*')
  215. {
  216. cleanStr = shapeName;
  217. cleanStr += "_cachedTex";
  218. cleanStr += texName.substr(1);
  219. }
  220. else
  221. {
  222. cleanStr = texName;
  223. cleanStr.replace('\\', '/');
  224. }
  225. return cleanStr;
  226. }
  227. #ifdef TORQUE_DEBUG
  228. void AssimpAppMaterial::enumerateMaterialProperties(aiMaterial* mtl)
  229. {
  230. for (U32 i = 0; i < mtl->mNumProperties; ++i)
  231. {
  232. aiMaterialProperty* matProp = mtl->mProperties[i];
  233. String outText;
  234. if (matProp)
  235. {
  236. outText = String::ToString(" Key: %s, Index: %d, Semantic: ", matProp->mKey.C_Str(), matProp->mIndex);
  237. switch (matProp->mSemantic)
  238. {
  239. case aiTextureType_NONE:
  240. outText += "aiTextureType_NONE";
  241. break;
  242. case aiTextureType_DIFFUSE:
  243. outText += "aiTextureType_DIFFUSE";
  244. break;
  245. case aiTextureType_SPECULAR:
  246. outText += "aiTextureType_SPECULAR";
  247. break;
  248. case aiTextureType_AMBIENT:
  249. outText += "aiTextureType_AMBIENT";
  250. break;
  251. case aiTextureType_EMISSIVE:
  252. outText += "aiTextureType_EMISSIVE";
  253. break;
  254. case aiTextureType_HEIGHT:
  255. outText += "aiTextureType_HEIGHT";
  256. break;
  257. case aiTextureType_NORMALS:
  258. outText += "aiTextureType_NORMALS";
  259. break;
  260. case aiTextureType_SHININESS:
  261. outText += "aiTextureType_SHININESS";
  262. break;
  263. case aiTextureType_OPACITY:
  264. outText += "aiTextureType_OPACITY";
  265. break;
  266. case aiTextureType_DISPLACEMENT:
  267. outText += "aiTextureType_DISPLACEMENT";
  268. break;
  269. case aiTextureType_LIGHTMAP:
  270. outText += "aiTextureType_LIGHTMAP";
  271. break;
  272. case aiTextureType_REFLECTION:
  273. outText += "aiTextureType_REFLECTION";
  274. break;
  275. default:
  276. outText += "aiTextureType_UNKNOWN";
  277. break;
  278. }
  279. aiString stringProp;
  280. F32* floatProp;
  281. double* doubleProp;
  282. S32* intProp;
  283. switch (matProp->mType)
  284. {
  285. case aiPTI_Float:
  286. floatProp = (F32*)matProp->mData;
  287. for (U32 j = 0; j < matProp->mDataLength / sizeof(F32); ++j)
  288. outText += String::ToString(", %0.4f", floatProp[j]);
  289. break;
  290. case aiPTI_Double:
  291. doubleProp = (double*)matProp->mData;
  292. for (U32 j = 0; j < matProp->mDataLength / sizeof(double); ++j)
  293. outText += String::ToString(", %0.4lf", doubleProp[j]);
  294. break;
  295. case aiPTI_String:
  296. aiGetMaterialString(mtl, matProp->mKey.C_Str(), matProp->mSemantic, matProp->mIndex, &stringProp);
  297. outText += String::ToString(", %s", stringProp.C_Str());
  298. break;
  299. case aiPTI_Integer:
  300. intProp = (S32*)matProp->mData;
  301. for (U32 j = 0; j < matProp->mDataLength / sizeof(S32); ++j)
  302. outText += String::ToString(", %d", intProp[j]);
  303. break;
  304. case aiPTI_Buffer:
  305. outText += ", aiPTI_Buffer format data";
  306. break;
  307. default:
  308. outText += ", Unknown data type";
  309. }
  310. Con::printf("%s", outText.c_str());
  311. }
  312. }
  313. }
  314. #endif