assimpShapeLoader.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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. Resource stream -> Buffer
  24. Buffer -> Collada DOM
  25. Collada DOM -> TSShapeLoader
  26. TSShapeLoader installed into TSShape
  27. */
  28. //-----------------------------------------------------------------------------
  29. #include "platform/platform.h"
  30. #include "ts/assimp/assimpShapeLoader.h"
  31. #include "ts/assimp/assimpAppNode.h"
  32. #include "ts/assimp/assimpAppMesh.h"
  33. #include "ts/assimp/assimpAppMaterial.h"
  34. #include "ts/assimp/assimpAppSequence.h"
  35. #include "core/util/tVector.h"
  36. #include "core/strings/findMatch.h"
  37. #include "core/strings/stringUnit.h"
  38. #include "core/stream/fileStream.h"
  39. #include "core/fileObject.h"
  40. #include "ts/tsShape.h"
  41. #include "ts/tsShapeInstance.h"
  42. #include "materials/materialManager.h"
  43. #include "console/persistenceManager.h"
  44. #include "ts/tsShapeConstruct.h"
  45. #include "core/util/zip/zipVolume.h"
  46. #include "gfx/bitmap/gBitmap.h"
  47. #include "gui/controls/guiTreeViewCtrl.h"
  48. // assimp include files.
  49. #include <assimp/cimport.h>
  50. #include <assimp/scene.h>
  51. #include <assimp/postprocess.h>
  52. #include <assimp/types.h>
  53. #include <assimp/config.h>
  54. #include <exception>
  55. #include <assimp/Importer.hpp>
  56. MODULE_BEGIN( AssimpShapeLoader )
  57. MODULE_INIT_AFTER( ShapeLoader )
  58. MODULE_INIT
  59. {
  60. TSShapeLoader::addFormat("DirectX X", "x");
  61. TSShapeLoader::addFormat("Autodesk FBX", "fbx");
  62. TSShapeLoader::addFormat("Blender 3D", "blend" );
  63. TSShapeLoader::addFormat("3ds Max 3DS", "3ds");
  64. TSShapeLoader::addFormat("3ds Max ASE", "ase");
  65. TSShapeLoader::addFormat("Wavefront Object", "obj");
  66. TSShapeLoader::addFormat("Industry Foundation Classes (IFC/Step)", "ifc");
  67. TSShapeLoader::addFormat("Stanford Polygon Library", "ply");
  68. TSShapeLoader::addFormat("AutoCAD DXF", "dxf");
  69. TSShapeLoader::addFormat("LightWave", "lwo");
  70. TSShapeLoader::addFormat("LightWave Scene", "lws");
  71. TSShapeLoader::addFormat("Modo", "lxo");
  72. TSShapeLoader::addFormat("Stereolithography", "stl");
  73. TSShapeLoader::addFormat("AC3D", "ac");
  74. TSShapeLoader::addFormat("Milkshape 3D", "ms3d");
  75. TSShapeLoader::addFormat("TrueSpace COB", "cob");
  76. TSShapeLoader::addFormat("TrueSpace SCN", "scn");
  77. TSShapeLoader::addFormat("Ogre XML", "xml");
  78. TSShapeLoader::addFormat("Irrlicht Mesh", "irrmesh");
  79. TSShapeLoader::addFormat("Irrlicht Scene", "irr");
  80. TSShapeLoader::addFormat("Quake I", "mdl" );
  81. TSShapeLoader::addFormat("Quake II", "md2" );
  82. TSShapeLoader::addFormat("Quake III Mesh", "md3");
  83. TSShapeLoader::addFormat("Quake III Map/BSP", "pk3");
  84. TSShapeLoader::addFormat("Return to Castle Wolfenstein", "mdc");
  85. TSShapeLoader::addFormat("Doom 3", "md5" );
  86. TSShapeLoader::addFormat("Valve SMD", "smd");
  87. TSShapeLoader::addFormat("Valve VTA", "vta");
  88. TSShapeLoader::addFormat("Starcraft II M3", "m3");
  89. TSShapeLoader::addFormat("Unreal", "3d");
  90. TSShapeLoader::addFormat("BlitzBasic 3D", "b3d" );
  91. TSShapeLoader::addFormat("Quick3D Q3D", "q3d");
  92. TSShapeLoader::addFormat("Quick3D Q3S", "q3s");
  93. TSShapeLoader::addFormat("Neutral File Format", "nff");
  94. TSShapeLoader::addFormat("Object File Format", "off");
  95. TSShapeLoader::addFormat("PovRAY Raw", "raw");
  96. TSShapeLoader::addFormat("Terragen Terrain", "ter");
  97. TSShapeLoader::addFormat("3D GameStudio (3DGS)", "mdl");
  98. TSShapeLoader::addFormat("3D GameStudio (3DGS) Terrain", "hmp");
  99. TSShapeLoader::addFormat("Izware Nendo", "ndo");
  100. TSShapeLoader::addFormat("gltf", "gltf");
  101. TSShapeLoader::addFormat("gltf binary", "glb");
  102. }
  103. MODULE_END;
  104. //-----------------------------------------------------------------------------
  105. AssimpShapeLoader::AssimpShapeLoader()
  106. {
  107. mScene = NULL;
  108. }
  109. AssimpShapeLoader::~AssimpShapeLoader()
  110. {
  111. }
  112. void AssimpShapeLoader::releaseImport()
  113. {
  114. aiReleaseImport(mScene);
  115. }
  116. void AssimpShapeLoader::enumerateScene()
  117. {
  118. TSShapeLoader::updateProgress(TSShapeLoader::Load_ReadFile, "Reading File");
  119. Con::printf("[ASSIMP] Attempting to load file: %s", shapePath.getFullPath().c_str());
  120. // Post-Processing
  121. unsigned int ppsteps =
  122. (ColladaUtils::getOptions().convertLeftHanded ? aiProcess_MakeLeftHanded : 0) |
  123. (ColladaUtils::getOptions().reverseWindingOrder ? aiProcess_FlipWindingOrder : 0) |
  124. (ColladaUtils::getOptions().calcTangentSpace ? aiProcess_CalcTangentSpace : 0) |
  125. (ColladaUtils::getOptions().joinIdenticalVerts ? aiProcess_JoinIdenticalVertices : 0) |
  126. (ColladaUtils::getOptions().removeRedundantMats ? aiProcess_RemoveRedundantMaterials : 0) |
  127. (ColladaUtils::getOptions().genUVCoords ? aiProcess_GenUVCoords : 0) |
  128. (ColladaUtils::getOptions().transformUVCoords ? aiProcess_TransformUVCoords : 0) |
  129. (ColladaUtils::getOptions().flipUVCoords ? aiProcess_FlipUVs : 0) |
  130. (ColladaUtils::getOptions().findInstances ? aiProcess_FindInstances : 0) |
  131. (ColladaUtils::getOptions().limitBoneWeights ? aiProcess_LimitBoneWeights : 0);
  132. if (Con::getBoolVariable("$Assimp::OptimizeMeshes", false))
  133. ppsteps |= aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph;
  134. if (Con::getBoolVariable("$Assimp::SplitLargeMeshes", false))
  135. ppsteps |= aiProcess_SplitLargeMeshes;
  136. // Mandatory options
  137. //ppsteps |= aiProcess_ValidateDataStructure | aiProcess_Triangulate | aiProcess_ImproveCacheLocality;
  138. ppsteps |= aiProcess_Triangulate;
  139. //aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
  140. aiPropertyStore* props = aiCreatePropertyStore();
  141. struct aiLogStream shapeLog = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT, NULL);
  142. shapeLog.callback = assimpLogCallback;
  143. shapeLog.user = 0;
  144. aiAttachLogStream(&shapeLog);
  145. #ifdef TORQUE_DEBUG
  146. aiEnableVerboseLogging(true);
  147. #endif
  148. mScene = (aiScene*)aiImportFileExWithProperties(shapePath.getFullPath().c_str(), ppsteps, NULL, props);
  149. aiReleasePropertyStore(props);
  150. if ( mScene )
  151. {
  152. Con::printf("[ASSIMP] Mesh Count: %d", mScene->mNumMeshes);
  153. Con::printf("[ASSIMP] Material Count: %d", mScene->mNumMaterials);
  154. // Set import options (if they are not set to override)
  155. if (ColladaUtils::getOptions().unit <= 0.0f)
  156. {
  157. F64 unit;
  158. if (!getMetaDouble("UnitScaleFactor", unit))
  159. {
  160. F32 floatVal;
  161. S32 intVal;
  162. if (getMetaFloat("UnitScaleFactor", floatVal))
  163. unit = (F64)floatVal;
  164. else if (getMetaInt("UnitScaleFactor", intVal))
  165. unit = (F64)intVal;
  166. else
  167. unit = 1.0;
  168. }
  169. ColladaUtils::getOptions().unit = (F32)unit;
  170. }
  171. if (ColladaUtils::getOptions().upAxis == UPAXISTYPE_COUNT)
  172. {
  173. S32 upAxis;
  174. if (!getMetaInt("UpAxis", upAxis))
  175. upAxis = UPAXISTYPE_Z_UP;
  176. ColladaUtils::getOptions().upAxis = (domUpAxisType) upAxis;
  177. }
  178. // Extract embedded textures
  179. for (U32 i = 0; i < mScene->mNumTextures; ++i)
  180. extractTexture(i, mScene->mTextures[i]);
  181. // Load all the materials.
  182. AssimpAppMaterial::sDefaultMatNumber = 0;
  183. for ( U32 i = 0; i < mScene->mNumMaterials; i++ )
  184. AppMesh::appMaterials.push_back(new AssimpAppMaterial(mScene->mMaterials[i]));
  185. // Setup LOD checks
  186. detectDetails();
  187. // Define the root node, and process down the chain.
  188. AssimpAppNode* node = new AssimpAppNode(mScene, mScene->mRootNode, 0);
  189. if (!processNode(node))
  190. delete node;
  191. // Check for animations and process those.
  192. processAnimations();
  193. }
  194. else
  195. {
  196. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import failed");
  197. Con::printf("[ASSIMP] Import Error: %s", aiGetErrorString());
  198. }
  199. aiDetachLogStream(&shapeLog);
  200. }
  201. void AssimpShapeLoader::processAnimations()
  202. {
  203. for(U32 n = 0; n < mScene->mNumAnimations; ++n)
  204. {
  205. Con::printf("[ASSIMP] Animation Found: %s", mScene->mAnimations[n]->mName.C_Str());
  206. AssimpAppSequence* newAssimpSeq = new AssimpAppSequence(mScene->mAnimations[n]);
  207. appSequences.push_back(newAssimpSeq);
  208. }
  209. }
  210. void AssimpShapeLoader::computeBounds(Box3F& bounds)
  211. {
  212. TSShapeLoader::computeBounds(bounds);
  213. // Check if the model origin needs adjusting
  214. bool adjustCenter = ColladaUtils::getOptions().adjustCenter;
  215. bool adjustFloor = ColladaUtils::getOptions().adjustFloor;
  216. if (bounds.isValidBox() && (adjustCenter || adjustFloor))
  217. {
  218. // Compute shape offset
  219. Point3F shapeOffset = Point3F::Zero;
  220. if (adjustCenter)
  221. {
  222. bounds.getCenter(&shapeOffset);
  223. shapeOffset = -shapeOffset;
  224. }
  225. if (adjustFloor)
  226. shapeOffset.z = -bounds.minExtents.z;
  227. // Adjust bounds
  228. bounds.minExtents += shapeOffset;
  229. bounds.maxExtents += shapeOffset;
  230. // Now adjust all positions for root level nodes (nodes with no parent)
  231. for (S32 iNode = 0; iNode < shape->nodes.size(); iNode++)
  232. {
  233. if (!appNodes[iNode]->isParentRoot())
  234. continue;
  235. // Adjust default translation
  236. shape->defaultTranslations[iNode] += shapeOffset;
  237. // Adjust animated translations
  238. for (S32 iSeq = 0; iSeq < shape->sequences.size(); iSeq++)
  239. {
  240. const TSShape::Sequence& seq = shape->sequences[iSeq];
  241. if (seq.translationMatters.test(iNode))
  242. {
  243. for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  244. {
  245. S32 index = seq.baseTranslation + seq.translationMatters.count(iNode)*seq.numKeyframes + iFrame;
  246. shape->nodeTranslations[index] += shapeOffset;
  247. }
  248. }
  249. }
  250. }
  251. }
  252. }
  253. bool AssimpShapeLoader::fillGuiTreeView(const char* sourceShapePath, GuiTreeViewCtrl* tree)
  254. {
  255. Assimp::Importer importer;
  256. Torque::Path path(sourceShapePath);
  257. String cleanFile = AppMaterial::cleanString(path.getFileName());
  258. // Attempt to import with Assimp.
  259. const aiScene* shapeScene = importer.ReadFile(path.getFullPath().c_str(), (aiProcessPreset_TargetRealtime_Quality | aiProcess_CalcTangentSpace)
  260. & ~aiProcess_RemoveRedundantMaterials & ~aiProcess_GenSmoothNormals);
  261. if (!shapeScene)
  262. {
  263. Con::printf("AssimpShapeLoader::fillGuiTreeView - Assimp Error: %s", importer.GetErrorString());
  264. return false;
  265. }
  266. mScene = shapeScene;
  267. // Initialize tree
  268. tree->removeItem(0);
  269. S32 meshItem = tree->insertItem(0, "Meshes", String::ToString("%i", shapeScene->mNumMeshes));
  270. S32 matItem = tree->insertItem(0, "Materials", String::ToString("%i", shapeScene->mNumMaterials));
  271. S32 animItem = tree->insertItem(0, "Animations", String::ToString("%i", shapeScene->mNumAnimations));
  272. //S32 lightsItem = tree->insertItem(0, "Lights", String::ToString("%i", shapeScene->mNumLights));
  273. //S32 texturesItem = tree->insertItem(0, "Textures", String::ToString("%i", shapeScene->mNumTextures));
  274. //Details!
  275. U32 numPolys = 0;
  276. U32 numVerts = 0;
  277. for (U32 i = 0; i < shapeScene->mNumMeshes; i++)
  278. {
  279. tree->insertItem(meshItem, String::ToString("%s", shapeScene->mMeshes[i]->mName.C_Str()));
  280. numPolys += shapeScene->mMeshes[i]->mNumFaces;
  281. numVerts += shapeScene->mMeshes[i]->mNumVertices;
  282. }
  283. U32 defaultMatNumber = 0;
  284. for (U32 i = 0; i < shapeScene->mNumMaterials; i++)
  285. {
  286. aiMaterial* aiMat = shapeScene->mMaterials[i];
  287. aiString matName;
  288. aiMat->Get(AI_MATKEY_NAME, matName);
  289. String name = matName.C_Str();
  290. if (name.isEmpty())
  291. {
  292. name = AppMaterial::cleanString(path.getFileName());
  293. name += "_defMat";
  294. name += String::ToString("%d", defaultMatNumber);
  295. defaultMatNumber++;
  296. }
  297. aiString texPath;
  298. aiMat->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &texPath);
  299. String texName = texPath.C_Str();
  300. if (texName.isEmpty())
  301. {
  302. aiColor3D read_color(1.f, 1.f, 1.f);
  303. if (AI_SUCCESS == aiMat->Get(AI_MATKEY_COLOR_DIFFUSE, read_color))
  304. texName = String::ToString("Color: %0.3f %0.3f %0.3f", (F32)read_color.r, (F32)read_color.g, (F32)read_color.b); //formatted as words for easy parsing
  305. else
  306. texName = "No Texture";
  307. }
  308. else
  309. texName = AssimpAppMaterial::cleanTextureName(texName, cleanFile, sourceShapePath, true);
  310. tree->insertItem(matItem, String::ToString("%s", name.c_str()), String::ToString("%s", texName.c_str()));
  311. }
  312. for (U32 i = 0; i < shapeScene->mNumAnimations; i++)
  313. {
  314. String sequenceName = shapeScene->mAnimations[i]->mName.C_Str();
  315. if (sequenceName.isEmpty())
  316. sequenceName = "ambient";
  317. tree->insertItem(animItem, sequenceName.c_str());
  318. }
  319. U32 numNodes = 0;
  320. if (shapeScene->mRootNode)
  321. {
  322. S32 nodesItem = tree->insertItem(0, "Nodes", "");
  323. addNodeToTree(nodesItem, shapeScene->mRootNode, tree, numNodes);
  324. tree->setItemValue(nodesItem, String::ToString("%i", numNodes));
  325. }
  326. U32 numMetaTags = shapeScene->mMetaData ? shapeScene->mMetaData->mNumProperties : 0;
  327. if (numMetaTags)
  328. addMetaDataToTree(shapeScene->mMetaData, tree);
  329. F64 unit;
  330. if (!getMetaDouble("UnitScaleFactor", unit))
  331. unit = 1.0f;
  332. S32 upAxis;
  333. if (!getMetaInt("UpAxis", upAxis))
  334. upAxis = UPAXISTYPE_Z_UP;
  335. /*for (U32 i = 0; i < shapeScene->mNumLights; i++)
  336. {
  337. treeObj->insertItem(lightsItem, String::ToString("%s", shapeScene->mLights[i]->mType));
  338. }*/
  339. // Store shape information in the tree control
  340. tree->setDataField(StringTable->insert("_nodeCount"), 0, avar("%d", numNodes));
  341. tree->setDataField(StringTable->insert("_meshCount"), 0, avar("%d", shapeScene->mNumMeshes));
  342. tree->setDataField(StringTable->insert("_polygonCount"), 0, avar("%d", numPolys));
  343. tree->setDataField(StringTable->insert("_materialCount"), 0, avar("%d", shapeScene->mNumMaterials));
  344. tree->setDataField(StringTable->insert("_lightCount"), 0, avar("%d", shapeScene->mNumLights));
  345. tree->setDataField(StringTable->insert("_animCount"), 0, avar("%d", shapeScene->mNumAnimations));
  346. tree->setDataField(StringTable->insert("_textureCount"), 0, avar("%d", shapeScene->mNumTextures));
  347. tree->setDataField(StringTable->insert("_vertCount"), 0, avar("%d", numVerts));
  348. tree->setDataField(StringTable->insert("_metaTagCount"), 0, avar("%d", numMetaTags));
  349. tree->setDataField(StringTable->insert("_unit"), 0, avar("%g", (F32)unit));
  350. if (upAxis == UPAXISTYPE_X_UP)
  351. tree->setDataField(StringTable->insert("_upAxis"), 0, "X_AXIS");
  352. else if (upAxis == UPAXISTYPE_Y_UP)
  353. tree->setDataField(StringTable->insert("_upAxis"), 0, "Y_AXIS");
  354. else
  355. tree->setDataField(StringTable->insert("_upAxis"), 0, "Z_AXIS");
  356. return true;
  357. }
  358. void AssimpShapeLoader::updateMaterialsScript(const Torque::Path &path)
  359. {
  360. Torque::Path scriptPath(path);
  361. scriptPath.setFileName("materials");
  362. scriptPath.setExtension("cs");
  363. // First see what materials we need to update
  364. PersistenceManager persistMgr;
  365. for ( U32 iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++ )
  366. {
  367. AssimpAppMaterial *mat = dynamic_cast<AssimpAppMaterial*>( AppMesh::appMaterials[iMat] );
  368. if ( mat )
  369. {
  370. Material *mappedMat;
  371. if ( Sim::findObject( MATMGR->getMapEntry( mat->getName() ), mappedMat ) )
  372. {
  373. // Only update existing materials if forced to
  374. if (ColladaUtils::getOptions().forceUpdateMaterials)
  375. {
  376. mat->initMaterial(scriptPath, mappedMat);
  377. persistMgr.setDirty(mappedMat);
  378. }
  379. }
  380. else
  381. {
  382. // Create a new material definition
  383. persistMgr.setDirty( mat->createMaterial( scriptPath ), scriptPath.getFullPath() );
  384. }
  385. }
  386. }
  387. if ( persistMgr.getDirtyList().empty() )
  388. return;
  389. persistMgr.saveDirty();
  390. }
  391. /// Check if an up-to-date cached DTS is available for this DAE file
  392. bool AssimpShapeLoader::canLoadCachedDTS(const Torque::Path& path)
  393. {
  394. // Generate the cached filename
  395. Torque::Path cachedPath(path);
  396. cachedPath.setExtension("cached.dts");
  397. // Check if a cached DTS newer than this file is available
  398. FileTime cachedModifyTime;
  399. if (Platform::getFileTimes(cachedPath.getFullPath(), NULL, &cachedModifyTime))
  400. {
  401. bool forceLoad = Con::getBoolVariable("$assimp::forceLoad", false);
  402. FileTime daeModifyTime;
  403. if (!Platform::getFileTimes(path.getFullPath(), NULL, &daeModifyTime) ||
  404. (!forceLoad && (Platform::compareFileTimes(cachedModifyTime, daeModifyTime) >= 0) ))
  405. {
  406. // Original file not found, or cached DTS is newer
  407. return true;
  408. }
  409. }
  410. return false;
  411. }
  412. void AssimpShapeLoader::assimpLogCallback(const char* message, char* user)
  413. {
  414. Con::printf("[Assimp log message] %s", StringUnit::getUnit(message, 0, "\n"));
  415. }
  416. bool AssimpShapeLoader::ignoreNode(const String& name)
  417. {
  418. // Do not add AssimpFbx dummy nodes to the TSShape. See: Assimp::FBX::ImportSettings::preservePivots
  419. // https://github.com/assimp/assimp/blob/master/code/FBXImportSettings.h#L116-L135
  420. if (name.find("_$AssimpFbx$_") != String::NPos)
  421. return true;
  422. if (FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().alwaysImport, name, false))
  423. return false;
  424. return FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().neverImport, name, false);
  425. }
  426. bool AssimpShapeLoader::ignoreMesh(const String& name)
  427. {
  428. if (FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().alwaysImportMesh, name, false))
  429. return false;
  430. else
  431. return FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().neverImportMesh, name, false);
  432. }
  433. void AssimpShapeLoader::detectDetails()
  434. {
  435. // Set LOD option
  436. bool singleDetail = true;
  437. switch (ColladaUtils::getOptions().lodType)
  438. {
  439. case ColladaUtils::ImportOptions::DetectDTS:
  440. // Check for a baseXX->startXX hierarchy at the top-level, if we find
  441. // one, use trailing numbers for LOD, otherwise use a single size
  442. for (S32 iNode = 0; singleDetail && (iNode < mScene->mRootNode->mNumChildren); iNode++) {
  443. aiNode* node = mScene->mRootNode->mChildren[iNode];
  444. if (node && dStrStartsWith(node->mName.C_Str(), "base")) {
  445. for (S32 iChild = 0; iChild < node->mNumChildren; iChild++) {
  446. aiNode* child = node->mChildren[iChild];
  447. if (child && dStrStartsWith(child->mName.C_Str(), "start")) {
  448. singleDetail = false;
  449. break;
  450. }
  451. }
  452. }
  453. }
  454. break;
  455. case ColladaUtils::ImportOptions::SingleSize:
  456. singleDetail = true;
  457. break;
  458. case ColladaUtils::ImportOptions::TrailingNumber:
  459. singleDetail = false;
  460. break;
  461. default:
  462. break;
  463. }
  464. AssimpAppMesh::fixDetailSize(singleDetail, ColladaUtils::getOptions().singleDetailSize);
  465. }
  466. void AssimpShapeLoader::extractTexture(U32 index, aiTexture* pTex)
  467. { // Cache an embedded texture to disk
  468. updateProgress(Load_EnumerateScene, "Extracting Textures...", mScene->mNumTextures, index);
  469. Con::printf("[Assimp] Extracting Texture %s, W: %d, H: %d, %d of %d, format hint: (%s)", pTex->mFilename.C_Str(),
  470. pTex->mWidth, pTex->mHeight, index, mScene->mNumTextures, pTex->achFormatHint);
  471. // Create the texture filename
  472. String cleanFile = AppMaterial::cleanString(TSShapeLoader::getShapePath().getFileName());
  473. String texName = String::ToString("%s_cachedTex%d", cleanFile.c_str(), index);
  474. Torque::Path texPath = shapePath;
  475. texPath.setFileName(texName);
  476. if (pTex->mHeight == 0)
  477. { // Compressed format, write the data directly to disc
  478. texPath.setExtension(pTex->achFormatHint);
  479. FileStream *outputStream;
  480. if ((outputStream = FileStream::createAndOpen(texPath.getFullPath(), Torque::FS::File::Write)) != NULL)
  481. {
  482. outputStream->setPosition(0);
  483. outputStream->write(pTex->mWidth, pTex->pcData);
  484. outputStream->close();
  485. delete outputStream;
  486. }
  487. }
  488. else
  489. { // Embedded pixel data, fill a bitmap and save it.
  490. GFXTexHandle shapeTex;
  491. shapeTex.set(pTex->mWidth, pTex->mHeight, GFXFormatR8G8B8A8_SRGB, &GFXDynamicTextureSRGBProfile,
  492. String::ToString("AssimpShapeLoader (%s:%i)", __FILE__, __LINE__), 1, 0);
  493. GFXLockedRect *rect = shapeTex.lock();
  494. for (U32 y = 0; y < pTex->mHeight; ++y)
  495. {
  496. for (U32 x = 0; x < pTex->mWidth; ++x)
  497. {
  498. U32 targetIndex = (y * rect->pitch) + (x * 4);
  499. U32 sourceIndex = ((y * pTex->mWidth) + x) * 4;
  500. rect->bits[targetIndex] = pTex->pcData[sourceIndex].r;
  501. rect->bits[targetIndex + 1] = pTex->pcData[sourceIndex].g;
  502. rect->bits[targetIndex + 2] = pTex->pcData[sourceIndex].b;
  503. rect->bits[targetIndex + 3] = pTex->pcData[sourceIndex].a;
  504. }
  505. }
  506. shapeTex.unlock();
  507. texPath.setExtension("png");
  508. shapeTex->dumpToDisk("PNG", texPath.getFullPath());
  509. }
  510. }
  511. void AssimpShapeLoader::addNodeToTree(S32 parentItem, aiNode* node, GuiTreeViewCtrl* tree, U32& nodeCount)
  512. {
  513. // Add this node
  514. S32 nodeItem = parentItem;
  515. String nodeName = node->mName.C_Str();
  516. if (!ignoreNode(nodeName))
  517. {
  518. if (nodeName.isEmpty())
  519. nodeName = "null";
  520. nodeItem = tree->insertItem(parentItem, nodeName.c_str(), String::ToString("%i", node->mNumChildren));
  521. nodeCount++;
  522. }
  523. // Add any child nodes
  524. for (U32 n = 0; n < node->mNumChildren; ++n)
  525. addNodeToTree(nodeItem, node->mChildren[n], tree, nodeCount);
  526. }
  527. void AssimpShapeLoader::addMetaDataToTree(const aiMetadata* metaData, GuiTreeViewCtrl* tree)
  528. {
  529. S32 metaItem = tree->insertItem(0, "MetaData", String::ToString("%i", metaData->mNumProperties));
  530. aiString valString;
  531. aiVector3D valVec;
  532. for (U32 n = 0; n < metaData->mNumProperties; ++n)
  533. {
  534. String keyStr = metaData->mKeys[n].C_Str();
  535. keyStr += ": ";
  536. switch (metaData->mValues[n].mType)
  537. {
  538. case AI_BOOL:
  539. keyStr += ((bool)metaData->mValues[n].mData) ? "true" : "false";
  540. break;
  541. case AI_INT32:
  542. keyStr += String::ToString(*((S32*)(metaData->mValues[n].mData)));
  543. break;
  544. case AI_UINT64:
  545. keyStr += String::ToString("%I64u", *((U64*)metaData->mValues[n].mData));
  546. break;
  547. case AI_FLOAT:
  548. keyStr += String::ToString(*((F32*)metaData->mValues[n].mData));
  549. break;
  550. case AI_DOUBLE:
  551. keyStr += String::ToString(*((F64*)metaData->mValues[n].mData));
  552. break;
  553. case AI_AISTRING:
  554. metaData->Get<aiString>(metaData->mKeys[n], valString);
  555. keyStr += valString.C_Str();
  556. break;
  557. case AI_AIVECTOR3D:
  558. metaData->Get<aiVector3D>(metaData->mKeys[n], valVec);
  559. keyStr += String::ToString("%f, %f, %f", valVec.x, valVec.y, valVec.z);
  560. break;
  561. default:
  562. break;
  563. }
  564. tree->insertItem(metaItem, keyStr.c_str(), String::ToString("%i", n));
  565. }
  566. }
  567. bool AssimpShapeLoader::getMetabool(const char* key, bool& boolVal)
  568. {
  569. if (!mScene || !mScene->mMetaData)
  570. return false;
  571. String keyStr = key;
  572. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  573. {
  574. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  575. {
  576. if (mScene->mMetaData->mValues[n].mType == AI_BOOL)
  577. {
  578. boolVal = (bool)mScene->mMetaData->mValues[n].mData;
  579. return true;
  580. }
  581. }
  582. }
  583. return false;
  584. }
  585. bool AssimpShapeLoader::getMetaInt(const char* key, S32& intVal)
  586. {
  587. if (!mScene || !mScene->mMetaData)
  588. return false;
  589. String keyStr = key;
  590. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  591. {
  592. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  593. {
  594. if (mScene->mMetaData->mValues[n].mType == AI_INT32)
  595. {
  596. intVal = *((S32*)(mScene->mMetaData->mValues[n].mData));
  597. return true;
  598. }
  599. }
  600. }
  601. return false;
  602. }
  603. bool AssimpShapeLoader::getMetaFloat(const char* key, F32& floatVal)
  604. {
  605. if (!mScene || !mScene->mMetaData)
  606. return false;
  607. String keyStr = key;
  608. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  609. {
  610. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  611. {
  612. if (mScene->mMetaData->mValues[n].mType == AI_FLOAT)
  613. {
  614. floatVal = *((F32*)mScene->mMetaData->mValues[n].mData);
  615. return true;
  616. }
  617. }
  618. }
  619. return false;
  620. }
  621. bool AssimpShapeLoader::getMetaDouble(const char* key, F64& doubleVal)
  622. {
  623. if (!mScene || !mScene->mMetaData)
  624. return false;
  625. String keyStr = key;
  626. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  627. {
  628. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  629. {
  630. if (mScene->mMetaData->mValues[n].mType == AI_DOUBLE)
  631. {
  632. doubleVal = *((F64*)mScene->mMetaData->mValues[n].mData);
  633. return true;
  634. }
  635. }
  636. }
  637. return false;
  638. }
  639. //-----------------------------------------------------------------------------
  640. /// This function is invoked by the resource manager based on file extension.
  641. TSShape* assimpLoadShape(const Torque::Path &path)
  642. {
  643. // TODO: add .cached.dts generation.
  644. // Generate the cached filename
  645. Torque::Path cachedPath(path);
  646. cachedPath.setExtension("cached.dts");
  647. // Check if an up-to-date cached DTS version of this file exists, and
  648. // if so, use that instead.
  649. if (AssimpShapeLoader::canLoadCachedDTS(path))
  650. {
  651. FileStream cachedStream;
  652. cachedStream.open(cachedPath.getFullPath(), Torque::FS::File::Read);
  653. if (cachedStream.getStatus() == Stream::Ok)
  654. {
  655. TSShape *shape = new TSShape;
  656. bool readSuccess = shape->read(&cachedStream);
  657. cachedStream.close();
  658. if (readSuccess)
  659. {
  660. #ifdef TORQUE_DEBUG
  661. Con::printf("Loaded cached shape from %s", cachedPath.getFullPath().c_str());
  662. #endif
  663. return shape;
  664. }
  665. else
  666. delete shape;
  667. }
  668. Con::warnf("Failed to load cached shape from %s", cachedPath.getFullPath().c_str());
  669. }
  670. if (!Torque::FS::IsFile(path))
  671. {
  672. // File does not exist, bail.
  673. return NULL;
  674. }
  675. // Allow TSShapeConstructor object to override properties
  676. ColladaUtils::getOptions().reset();
  677. TSShapeConstructor* tscon = TSShapeConstructor::findShapeConstructor(path.getFullPath());
  678. if (tscon)
  679. {
  680. ColladaUtils::getOptions() = tscon->mOptions;
  681. }
  682. AssimpShapeLoader loader;
  683. TSShape* tss = loader.generateShape(path);
  684. if (tss)
  685. {
  686. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import complete");
  687. Con::printf("[ASSIMP] Shape created successfully.");
  688. // Cache the model to a DTS file for faster loading next time.
  689. FileStream dtsStream;
  690. if (dtsStream.open(cachedPath.getFullPath(), Torque::FS::File::Write))
  691. {
  692. Con::printf("Writing cached shape to %s", cachedPath.getFullPath().c_str());
  693. tss->write(&dtsStream);
  694. }
  695. loader.updateMaterialsScript(path);
  696. }
  697. loader.releaseImport();
  698. return tss;
  699. }
  700. DefineEngineFunction(GetShapeInfo, bool, (const char* shapePath, const char* ctrl, bool loadCachedDts), ("", "", true),
  701. "(string shapePath, GuiTreeViewCtrl ctrl) Collect scene information from "
  702. "a shape file and store it in a GuiTreeView control. This function is "
  703. "used by the assimp import gui to show a preview of the scene contents "
  704. "prior to import, and is probably not much use for anything else.\n"
  705. "@param shapePath shape filename\n"
  706. "@param ctrl GuiTreeView control to add elements to\n"
  707. "@return true if successful, false otherwise\n"
  708. "@ingroup Editors\n"
  709. "@internal")
  710. {
  711. GuiTreeViewCtrl* tree;
  712. if (!Sim::findObject(ctrl, tree))
  713. {
  714. Con::errorf("enumColladaScene::Could not find GuiTreeViewCtrl '%s'", ctrl);
  715. return false;
  716. }
  717. // Check if a cached DTS is available => no need to import the source file
  718. // if we can load the DTS instead
  719. Torque::Path path(shapePath);
  720. if (loadCachedDts && AssimpShapeLoader::canLoadCachedDTS(path))
  721. return false;
  722. AssimpShapeLoader loader;
  723. return loader.fillGuiTreeView(shapePath, tree);
  724. }