assimpShapeLoader.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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/stream/fileStream.h"
  38. #include "core/fileObject.h"
  39. #include "ts/tsShape.h"
  40. #include "ts/tsShapeInstance.h"
  41. #include "materials/materialManager.h"
  42. #include "console/persistenceManager.h"
  43. #include "ts/tsShapeConstruct.h"
  44. #include "core/util/zip/zipVolume.h"
  45. #include "gfx/bitmap/gBitmap.h"
  46. #include "gui/controls/guiTreeViewCtrl.h"
  47. // assimp include files.
  48. #include <assimp/cimport.h>
  49. #include <assimp/scene.h>
  50. #include <assimp/postprocess.h>
  51. #include <assimp/types.h>
  52. #include <assimp/config.h>
  53. #include <exception>
  54. #include <assimp/Importer.hpp>
  55. MODULE_BEGIN( AssimpShapeLoader )
  56. MODULE_INIT_AFTER( ShapeLoader )
  57. MODULE_INIT
  58. {
  59. TSShapeLoader::addFormat("DirectX X", "x");
  60. TSShapeLoader::addFormat("Autodesk FBX", "fbx");
  61. TSShapeLoader::addFormat("Blender 3D", "blend" );
  62. TSShapeLoader::addFormat("3ds Max 3DS", "3ds");
  63. TSShapeLoader::addFormat("3ds Max ASE", "ase");
  64. TSShapeLoader::addFormat("Wavefront Object", "obj");
  65. TSShapeLoader::addFormat("Industry Foundation Classes (IFC/Step)", "ifc");
  66. TSShapeLoader::addFormat("Stanford Polygon Library", "ply");
  67. TSShapeLoader::addFormat("AutoCAD DXF", "dxf");
  68. TSShapeLoader::addFormat("LightWave", "lwo");
  69. TSShapeLoader::addFormat("LightWave Scene", "lws");
  70. TSShapeLoader::addFormat("Modo", "lxo");
  71. TSShapeLoader::addFormat("Stereolithography", "stl");
  72. TSShapeLoader::addFormat("AC3D", "ac");
  73. TSShapeLoader::addFormat("Milkshape 3D", "ms3d");
  74. TSShapeLoader::addFormat("TrueSpace COB", "cob");
  75. TSShapeLoader::addFormat("TrueSpace SCN", "scn");
  76. TSShapeLoader::addFormat("Ogre XML", "xml");
  77. TSShapeLoader::addFormat("Irrlicht Mesh", "irrmesh");
  78. TSShapeLoader::addFormat("Irrlicht Scene", "irr");
  79. TSShapeLoader::addFormat("Quake I", "mdl" );
  80. TSShapeLoader::addFormat("Quake II", "md2" );
  81. TSShapeLoader::addFormat("Quake III Mesh", "md3");
  82. TSShapeLoader::addFormat("Quake III Map/BSP", "pk3");
  83. TSShapeLoader::addFormat("Return to Castle Wolfenstein", "mdc");
  84. TSShapeLoader::addFormat("Doom 3", "md5" );
  85. TSShapeLoader::addFormat("Valve SMD", "smd");
  86. TSShapeLoader::addFormat("Valve VTA", "vta");
  87. TSShapeLoader::addFormat("Starcraft II M3", "m3");
  88. TSShapeLoader::addFormat("Unreal", "3d");
  89. TSShapeLoader::addFormat("BlitzBasic 3D", "b3d" );
  90. TSShapeLoader::addFormat("Quick3D Q3D", "q3d");
  91. TSShapeLoader::addFormat("Quick3D Q3S", "q3s");
  92. TSShapeLoader::addFormat("Neutral File Format", "nff");
  93. TSShapeLoader::addFormat("Object File Format", "off");
  94. TSShapeLoader::addFormat("PovRAY Raw", "raw");
  95. TSShapeLoader::addFormat("Terragen Terrain", "ter");
  96. TSShapeLoader::addFormat("3D GameStudio (3DGS)", "mdl");
  97. TSShapeLoader::addFormat("3D GameStudio (3DGS) Terrain", "hmp");
  98. TSShapeLoader::addFormat("Izware Nendo", "ndo");
  99. TSShapeLoader::addFormat("gltf", "gltf");
  100. TSShapeLoader::addFormat("gltf binary", "glb");
  101. }
  102. MODULE_END;
  103. //-----------------------------------------------------------------------------
  104. AssimpShapeLoader::AssimpShapeLoader()
  105. {
  106. mScene = NULL;
  107. }
  108. AssimpShapeLoader::~AssimpShapeLoader()
  109. {
  110. }
  111. void AssimpShapeLoader::releaseImport()
  112. {
  113. aiReleaseImport(mScene);
  114. }
  115. void AssimpShapeLoader::enumerateScene()
  116. {
  117. TSShapeLoader::updateProgress(TSShapeLoader::Load_ReadFile, "Reading File");
  118. Con::printf("[ASSIMP] Attempting to load file: %s", shapePath.getFullPath().c_str());
  119. // Post-Processing
  120. unsigned int ppsteps =
  121. Con::getBoolVariable("$Assimp::ConvertToLeftHanded", false) ? aiProcess_ConvertToLeftHanded : 0 |
  122. Con::getBoolVariable("$Assimp::CalcTangentSpace", false) ? aiProcess_CalcTangentSpace : 0 |
  123. Con::getBoolVariable("$Assimp::JoinIdenticalVertices", false) ? aiProcess_JoinIdenticalVertices : 0 |
  124. Con::getBoolVariable("$Assimp::ValidateDataStructure", false) ? aiProcess_ValidateDataStructure : 0 |
  125. Con::getBoolVariable("$Assimp::ImproveCacheLocality", false) ? aiProcess_ImproveCacheLocality : 0 |
  126. Con::getBoolVariable("$Assimp::RemoveRedundantMaterials", false) ? aiProcess_RemoveRedundantMaterials : 0 |
  127. Con::getBoolVariable("$Assimp::FindDegenerates", false) ? aiProcess_FindDegenerates : 0 |
  128. Con::getBoolVariable("$Assimp::FindInvalidData", false) ? aiProcess_FindInvalidData : 0 |
  129. Con::getBoolVariable("$Assimp::GenUVCoords", false) ? aiProcess_GenUVCoords : 0 |
  130. Con::getBoolVariable("$Assimp::TransformUVCoords", false) ? aiProcess_TransformUVCoords : 0 |
  131. Con::getBoolVariable("$Assimp::FindInstances", false) ? aiProcess_FindInstances : 0 |
  132. Con::getBoolVariable("$Assimp::LimitBoneWeights", false) ? aiProcess_LimitBoneWeights : 0 |
  133. Con::getBoolVariable("$Assimp::OptimizeMeshes", false) ? aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph : 0 |
  134. 0;
  135. if(Con::getBoolVariable("$Assimp::FlipUVs", true))
  136. ppsteps |= aiProcess_FlipUVs;
  137. if(Con::getBoolVariable("$Assimp::FlipWindingOrder", false))
  138. ppsteps |= aiProcess_FlipWindingOrder;
  139. if(Con::getBoolVariable("$Assimp::Triangulate", true))
  140. ppsteps |= aiProcess_Triangulate;
  141. if (Con::getBoolVariable("$Assimp::OptimizeMeshes", false))
  142. ppsteps |= aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph;
  143. if (Con::getBoolVariable("$Assimp::SplitLargeMeshes", false))
  144. ppsteps |= aiProcess_SplitLargeMeshes;
  145. //aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
  146. aiPropertyStore* props = aiCreatePropertyStore();
  147. //aiSetImportPropertyInteger(props, AI_CONFIG_IMPORT_TER_MAKE_UVS, 1);
  148. //aiSetImportPropertyInteger(props, AI_CONFIG_PP_SBP_REMOVE, (aiProcessPreset_TargetRealtime_Quality
  149. // | aiProcess_FlipWindingOrder | aiProcess_FlipUVs
  150. // | aiProcess_CalcTangentSpace
  151. // | aiProcess_FixInfacingNormals)
  152. // & ~aiProcess_RemoveRedundantMaterials);
  153. //aiSetImportPropertyInteger(props, AI_CONFIG_GLOB_MEASURE_TIME, 1);
  154. //aiSetImportPropertyFloat(props, AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE, 80.f);
  155. //aiSetImportPropertyInteger(props,AI_CONFIG_PP_PTV_KEEP_HIERARCHY,1);
  156. struct aiLogStream shapeLog;
  157. shapeLog = aiGetPredefinedLogStream(aiDefaultLogStream_FILE, "assimp.log");
  158. aiAttachLogStream(&shapeLog);
  159. #ifdef TORQUE_DEBUG
  160. aiEnableVerboseLogging(true);
  161. #endif
  162. //c = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT, NULL);
  163. //aiAttachLogStream(&c);
  164. // Attempt to import with Assimp.
  165. //mScene = importer.ReadFile(shapePath.getFullPath().c_str(), (aiProcessPreset_TargetRealtime_Quality | aiProcess_FlipWindingOrder | aiProcess_FlipUVs | aiProcess_CalcTangentSpace)
  166. // & ~aiProcess_RemoveRedundantMaterials);
  167. mScene = (aiScene*)aiImportFileExWithProperties(shapePath.getFullPath().c_str(), ppsteps, NULL, props);
  168. aiReleasePropertyStore(props);
  169. if ( mScene )
  170. {
  171. Con::printf("[ASSIMP] Mesh Count: %d", mScene->mNumMeshes);
  172. Con::printf("[ASSIMP] Material Count: %d", mScene->mNumMaterials);
  173. // Extract embedded textures
  174. for (U32 i = 0; i < mScene->mNumTextures; ++i)
  175. extractTexture(i, mScene->mTextures[i]);
  176. // Load all the materials.
  177. for ( U32 i = 0; i < mScene->mNumMaterials; i++ )
  178. AppMesh::appMaterials.push_back(new AssimpAppMaterial(mScene->mMaterials[i]));
  179. // Setup LOD checks
  180. detectDetails();
  181. // Define the root node, and process down the chain.
  182. AssimpAppNode* node = new AssimpAppNode(mScene, mScene->mRootNode, 0);
  183. if (!processNode(node))
  184. delete node;
  185. // Check for animations and process those.
  186. processAnimations();
  187. }
  188. else
  189. {
  190. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import failed");
  191. Con::printf("[ASSIMP] Import Error: %s", aiGetErrorString());
  192. }
  193. aiDetachLogStream(&shapeLog);
  194. }
  195. void AssimpShapeLoader::processAnimations()
  196. {
  197. for(U32 n = 0; n < mScene->mNumAnimations; ++n)
  198. {
  199. Con::printf("[ASSIMP] Animation Found: %s", mScene->mAnimations[n]->mName.C_Str());
  200. AssimpAppSequence* newAssimpSeq = new AssimpAppSequence(mScene->mAnimations[n]);
  201. appSequences.push_back(newAssimpSeq);
  202. }
  203. }
  204. void AssimpShapeLoader::computeBounds(Box3F& bounds)
  205. {
  206. TSShapeLoader::computeBounds(bounds);
  207. // Check if the model origin needs adjusting
  208. bool adjustCenter = Con::getBoolVariable("$Assimp::adjustCenter", false); //ColladaUtils::getOptions().adjustCenter
  209. bool adjustFloor = Con::getBoolVariable("$Assimp::adjustFloor", false); //ColladaUtils::getOptions().adjustFloor
  210. if (bounds.isValidBox() && (adjustCenter || adjustFloor))
  211. {
  212. // Compute shape offset
  213. Point3F shapeOffset = Point3F::Zero;
  214. if (adjustCenter)
  215. {
  216. bounds.getCenter(&shapeOffset);
  217. shapeOffset = -shapeOffset;
  218. }
  219. if (adjustFloor)
  220. shapeOffset.z = -bounds.minExtents.z;
  221. // Adjust bounds
  222. bounds.minExtents += shapeOffset;
  223. bounds.maxExtents += shapeOffset;
  224. // Now adjust all positions for root level nodes (nodes with no parent)
  225. for (S32 iNode = 0; iNode < shape->nodes.size(); iNode++)
  226. {
  227. if (!appNodes[iNode]->isParentRoot())
  228. continue;
  229. // Adjust default translation
  230. shape->defaultTranslations[iNode] += shapeOffset;
  231. // Adjust animated translations
  232. for (S32 iSeq = 0; iSeq < shape->sequences.size(); iSeq++)
  233. {
  234. const TSShape::Sequence& seq = shape->sequences[iSeq];
  235. if (seq.translationMatters.test(iNode))
  236. {
  237. for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  238. {
  239. S32 index = seq.baseTranslation + seq.translationMatters.count(iNode)*seq.numKeyframes + iFrame;
  240. shape->nodeTranslations[index] += shapeOffset;
  241. }
  242. }
  243. }
  244. }
  245. }
  246. }
  247. void AssimpShapeLoader::updateMaterialsScript(const Torque::Path &path)
  248. {
  249. Torque::Path scriptPath(path);
  250. scriptPath.setFileName("materials");
  251. scriptPath.setExtension("cs");
  252. // First see what materials we need to update
  253. PersistenceManager persistMgr;
  254. for ( U32 iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++ )
  255. {
  256. AssimpAppMaterial *mat = dynamic_cast<AssimpAppMaterial*>( AppMesh::appMaterials[iMat] );
  257. if ( mat )
  258. {
  259. Material *mappedMat;
  260. if ( Sim::findObject( MATMGR->getMapEntry( mat->getName() ), mappedMat ) )
  261. {
  262. // Only update existing materials if forced to
  263. if (Con::getBoolVariable("$Assimp::ForceUpdateMats", false))
  264. {
  265. mat->initMaterial(scriptPath, mappedMat);
  266. persistMgr.setDirty(mappedMat);
  267. }
  268. }
  269. else
  270. {
  271. // Create a new material definition
  272. persistMgr.setDirty( mat->createMaterial( scriptPath ), scriptPath.getFullPath() );
  273. }
  274. }
  275. }
  276. if ( persistMgr.getDirtyList().empty() )
  277. return;
  278. persistMgr.saveDirty();
  279. }
  280. /// Check if an up-to-date cached DTS is available for this DAE file
  281. bool AssimpShapeLoader::canLoadCachedDTS(const Torque::Path& path)
  282. {
  283. return false;
  284. // Generate the cached filename
  285. Torque::Path cachedPath(path);
  286. cachedPath.setExtension("cached.dts");
  287. // Check if a cached DTS newer than this file is available
  288. FileTime cachedModifyTime;
  289. if (Platform::getFileTimes(cachedPath.getFullPath(), NULL, &cachedModifyTime))
  290. {
  291. bool forceLoadDAE = Con::getBoolVariable("$assimp::forceLoad", false);
  292. FileTime daeModifyTime;
  293. if (!Platform::getFileTimes(path.getFullPath(), NULL, &daeModifyTime) ||
  294. (!forceLoadDAE && (Platform::compareFileTimes(cachedModifyTime, daeModifyTime) >= 0) ))
  295. {
  296. // DAE not found, or cached DTS is newer
  297. return true;
  298. }
  299. }
  300. return false;
  301. }
  302. bool AssimpShapeLoader::ignoreNode(const String& name)
  303. {
  304. // Do not add AssimpFbx dummy nodes to the TSShape. See: Assimp::FBX::ImportSettings::preservePivots
  305. // https://github.com/assimp/assimp/blob/master/code/FBXImportSettings.h#L116-L135
  306. if (name.find("_$AssimpFbx$_") != String::NPos)
  307. return true;
  308. return false;
  309. }
  310. void AssimpShapeLoader::detectDetails()
  311. {
  312. // Set LOD option
  313. bool singleDetail = true;
  314. switch (Con::getIntVariable("$Assimp::lodType", 0))
  315. {
  316. case ColladaUtils::ImportOptions::DetectDTS:
  317. // Check for a baseXX->startXX hierarchy at the top-level, if we find
  318. // one, use trailing numbers for LOD, otherwise use a single size
  319. for (S32 iNode = 0; singleDetail && (iNode < mScene->mRootNode->mNumChildren); iNode++) {
  320. aiNode* node = mScene->mRootNode->mChildren[iNode];
  321. if (node && dStrStartsWith(node->mName.C_Str(), "base")) {
  322. for (S32 iChild = 0; iChild < node->mNumChildren; iChild++) {
  323. aiNode* child = node->mChildren[iChild];
  324. if (child && dStrStartsWith(child->mName.C_Str(), "start")) {
  325. singleDetail = false;
  326. break;
  327. }
  328. }
  329. }
  330. }
  331. break;
  332. case ColladaUtils::ImportOptions::SingleSize:
  333. singleDetail = true;
  334. break;
  335. case ColladaUtils::ImportOptions::TrailingNumber:
  336. singleDetail = false;
  337. break;
  338. default:
  339. break;
  340. }
  341. AssimpAppMesh::fixDetailSize(singleDetail, Con::getIntVariable("$Assimp::singleDetailSize", 2));
  342. }
  343. void AssimpShapeLoader::extractTexture(U32 index, aiTexture* pTex)
  344. { // Cache an embedded texture to disk
  345. updateProgress(Load_EnumerateScene, "Extracting Textures...", mScene->mNumTextures, index);
  346. Con::printf("[Assimp] Extracting Texture %s, W: %d, H: %d, %d of %d, format hint: (%s)", pTex->mFilename.C_Str(),
  347. pTex->mWidth, pTex->mHeight, index, mScene->mNumTextures, pTex->achFormatHint);
  348. // Create the texture filename
  349. String cleanFile = AppMaterial::cleanString(TSShapeLoader::getShapePath().getFileName());
  350. String texName = String::ToString("%s_cachedTex%d", cleanFile.c_str(), index);
  351. Torque::Path texPath = shapePath;
  352. texPath.setFileName(texName);
  353. if (pTex->mHeight == 0)
  354. { // Compressed format, write the data directly to disc
  355. texPath.setExtension(pTex->achFormatHint);
  356. FileStream *outputStream;
  357. if ((outputStream = FileStream::createAndOpen(texPath.getFullPath(), Torque::FS::File::Write)) != NULL)
  358. {
  359. outputStream->setPosition(0);
  360. outputStream->write(pTex->mWidth, pTex->pcData);
  361. outputStream->close();
  362. delete outputStream;
  363. }
  364. }
  365. else
  366. { // Embedded pixel data, fill a bitmap and save it.
  367. GFXTexHandle shapeTex;
  368. shapeTex.set(pTex->mWidth, pTex->mHeight, GFXFormatR8G8B8A8_SRGB, &GFXDynamicTextureSRGBProfile,
  369. String::ToString("AssimpShapeLoader (%s:%i)", __FILE__, __LINE__), 1, 0);
  370. GFXLockedRect *rect = shapeTex.lock();
  371. for (U32 y = 0; y < pTex->mHeight; ++y)
  372. {
  373. for (U32 x = 0; x < pTex->mWidth; ++x)
  374. {
  375. U32 targetIndex = (y * rect->pitch) + (x * 4);
  376. U32 sourceIndex = ((y * pTex->mWidth) + x) * 4;
  377. rect->bits[targetIndex] = pTex->pcData[sourceIndex].r;
  378. rect->bits[targetIndex + 1] = pTex->pcData[sourceIndex].g;
  379. rect->bits[targetIndex + 2] = pTex->pcData[sourceIndex].b;
  380. rect->bits[targetIndex + 3] = pTex->pcData[sourceIndex].a;
  381. }
  382. }
  383. shapeTex.unlock();
  384. texPath.setExtension("png");
  385. shapeTex->dumpToDisk("PNG", texPath.getFullPath());
  386. }
  387. }
  388. //-----------------------------------------------------------------------------
  389. /// This function is invoked by the resource manager based on file extension.
  390. TSShape* assimpLoadShape(const Torque::Path &path)
  391. {
  392. // TODO: add .cached.dts generation.
  393. // Generate the cached filename
  394. Torque::Path cachedPath(path);
  395. cachedPath.setExtension("cached.dts");
  396. // Check if an up-to-date cached DTS version of this file exists, and
  397. // if so, use that instead.
  398. if (AssimpShapeLoader::canLoadCachedDTS(path))
  399. {
  400. FileStream cachedStream;
  401. cachedStream.open(cachedPath.getFullPath(), Torque::FS::File::Read);
  402. if (cachedStream.getStatus() == Stream::Ok)
  403. {
  404. TSShape *shape = new TSShape;
  405. bool readSuccess = shape->read(&cachedStream);
  406. cachedStream.close();
  407. if (readSuccess)
  408. {
  409. #ifdef TORQUE_DEBUG
  410. Con::printf("Loaded cached shape from %s", cachedPath.getFullPath().c_str());
  411. #endif
  412. return shape;
  413. }
  414. else
  415. delete shape;
  416. }
  417. Con::warnf("Failed to load cached shape from %s", cachedPath.getFullPath().c_str());
  418. }
  419. if (!Torque::FS::IsFile(path))
  420. {
  421. // File does not exist, bail.
  422. return NULL;
  423. }
  424. AssimpShapeLoader loader;
  425. TSShape* tss = loader.generateShape(path);
  426. if (tss)
  427. {
  428. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import complete");
  429. Con::printf("[ASSIMP] Shape created successfully.");
  430. // Cache the model to a DTS file for faster loading next time.
  431. FileStream dtsStream;
  432. if (dtsStream.open(cachedPath.getFullPath(), Torque::FS::File::Write))
  433. {
  434. Con::printf("Writing cached shape to %s", cachedPath.getFullPath().c_str());
  435. tss->write(&dtsStream);
  436. }
  437. loader.updateMaterialsScript(path);
  438. }
  439. loader.releaseImport();
  440. return tss;
  441. }
  442. DefineEngineFunction(GetShapeInfo, GuiTreeViewCtrl*, (String filePath), ,
  443. "Returns a list of supported shape formats in filter form.\n"
  444. "Example output: DSQ Files|*.dsq|COLLADA Files|*.dae|")
  445. {
  446. Assimp::Importer importer;
  447. GuiTreeViewCtrl* treeObj = new GuiTreeViewCtrl();
  448. treeObj->registerObject();
  449. Torque::Path path = Torque::Path(filePath);
  450. // Attempt to import with Assimp.
  451. const aiScene* shapeScene = importer.ReadFile(path.getFullPath().c_str(), (aiProcessPreset_TargetRealtime_Quality | aiProcess_CalcTangentSpace)
  452. & ~aiProcess_RemoveRedundantMaterials & ~aiProcess_GenSmoothNormals);
  453. //Populate info
  454. S32 meshItem = treeObj->insertItem(0, "Shape", String::ToString("%i", shapeScene->mNumMeshes));
  455. S32 matItem = treeObj->insertItem(0, "Materials", String::ToString("%i", shapeScene->mNumMaterials));
  456. S32 animItem = treeObj->insertItem(0, "Animations", String::ToString("%i", shapeScene->mNumAnimations));
  457. S32 lightsItem = treeObj->insertItem(0, "Lights", String::ToString("%i", shapeScene->mNumLights));
  458. S32 texturesItem = treeObj->insertItem(0, "Textures", String::ToString("%i", shapeScene->mNumTextures));
  459. //S32 meshItem = ->insertItem(0, "Cameras", String::ToString("%s", shapeScene->mNumCameras));
  460. //Details!
  461. for (U32 i = 0; i < shapeScene->mNumMeshes; i++)
  462. {
  463. treeObj->insertItem(meshItem, String::ToString("%s", shapeScene->mMeshes[i]->mName.C_Str()));
  464. }
  465. for (U32 i = 0; i < shapeScene->mNumMaterials; i++)
  466. {
  467. aiMaterial* aiMat = shapeScene->mMaterials[i];
  468. aiString matName;
  469. aiMat->Get(AI_MATKEY_NAME, matName);
  470. aiString texPath;
  471. aiMat->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &texPath);
  472. treeObj->insertItem(matItem, String::ToString("%s", matName.C_Str()), String::ToString("%s", texPath.C_Str()));
  473. }
  474. for (U32 i = 0; i < shapeScene->mNumAnimations; i++)
  475. {
  476. treeObj->insertItem(animItem, String::ToString("%s", shapeScene->mAnimations[i]->mName.C_Str()));
  477. }
  478. /*for (U32 i = 0; i < shapeScene->mNumLights; i++)
  479. {
  480. treeObj->insertItem(lightsItem, String::ToString("%s", shapeScene->mLights[i]->mType));
  481. }*/
  482. return treeObj;
  483. }