assimpShapeLoader.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  49. #ifdef new
  50. #undef new
  51. #endif
  52. #endif
  53. // assimp include files.
  54. #include <assimp/cimport.h>
  55. #include <assimp/scene.h>
  56. #include <assimp/postprocess.h>
  57. #include <assimp/types.h>
  58. #include <assimp/config.h>
  59. #include <exception>
  60. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  61. # define _new new(__FILE__, __LINE__)
  62. # define new _new
  63. #endif
  64. MODULE_BEGIN( AssimpShapeLoader )
  65. MODULE_INIT_AFTER( ShapeLoader )
  66. MODULE_INIT
  67. {
  68. TSShapeLoader::addFormat("DirectX X", "x");
  69. TSShapeLoader::addFormat("Autodesk FBX", "fbx");
  70. TSShapeLoader::addFormat("Blender 3D", "blend" );
  71. TSShapeLoader::addFormat("3ds Max 3DS", "3ds");
  72. TSShapeLoader::addFormat("3ds Max ASE", "ase");
  73. TSShapeLoader::addFormat("Wavefront Object", "obj");
  74. TSShapeLoader::addFormat("Industry Foundation Classes (IFC/Step)", "ifc");
  75. TSShapeLoader::addFormat("Stanford Polygon Library", "ply");
  76. TSShapeLoader::addFormat("AutoCAD DXF", "dxf");
  77. TSShapeLoader::addFormat("LightWave", "lwo");
  78. TSShapeLoader::addFormat("LightWave Scene", "lws");
  79. TSShapeLoader::addFormat("Modo", "lxo");
  80. TSShapeLoader::addFormat("Stereolithography", "stl");
  81. TSShapeLoader::addFormat("AC3D", "ac");
  82. TSShapeLoader::addFormat("Milkshape 3D", "ms3d");
  83. TSShapeLoader::addFormat("TrueSpace COB", "cob");
  84. TSShapeLoader::addFormat("TrueSpace SCN", "scn");
  85. TSShapeLoader::addFormat("Ogre XML", "xml");
  86. TSShapeLoader::addFormat("Irrlicht Mesh", "irrmesh");
  87. TSShapeLoader::addFormat("Irrlicht Scene", "irr");
  88. TSShapeLoader::addFormat("Quake I", "mdl" );
  89. TSShapeLoader::addFormat("Quake II", "md2" );
  90. TSShapeLoader::addFormat("Quake III Mesh", "md3");
  91. TSShapeLoader::addFormat("Quake III Map/BSP", "pk3");
  92. TSShapeLoader::addFormat("Return to Castle Wolfenstein", "mdc");
  93. TSShapeLoader::addFormat("Doom 3", "md5" );
  94. TSShapeLoader::addFormat("Valve SMD", "smd");
  95. TSShapeLoader::addFormat("Valve VTA", "vta");
  96. TSShapeLoader::addFormat("Starcraft II M3", "m3");
  97. TSShapeLoader::addFormat("Unreal", "3d");
  98. TSShapeLoader::addFormat("BlitzBasic 3D", "b3d" );
  99. TSShapeLoader::addFormat("Quick3D Q3D", "q3d");
  100. TSShapeLoader::addFormat("Quick3D Q3S", "q3s");
  101. TSShapeLoader::addFormat("Neutral File Format", "nff");
  102. TSShapeLoader::addFormat("Object File Format", "off");
  103. TSShapeLoader::addFormat("PovRAY Raw", "raw");
  104. TSShapeLoader::addFormat("Terragen Terrain", "ter");
  105. TSShapeLoader::addFormat("3D GameStudio (3DGS)", "mdl");
  106. TSShapeLoader::addFormat("3D GameStudio (3DGS) Terrain", "hmp");
  107. TSShapeLoader::addFormat("Izware Nendo", "ndo");
  108. TSShapeLoader::addFormat("gltf", "gltf");
  109. TSShapeLoader::addFormat("gltf binary", "glb");
  110. }
  111. MODULE_END;
  112. //-----------------------------------------------------------------------------
  113. AssimpShapeLoader::AssimpShapeLoader()
  114. {
  115. mScene = NULL;
  116. }
  117. AssimpShapeLoader::~AssimpShapeLoader()
  118. {
  119. }
  120. void AssimpShapeLoader::releaseImport()
  121. {
  122. }
  123. void applyTransformation(aiNode* node, const aiMatrix4x4& transform) {
  124. node->mTransformation = transform * node->mTransformation; // Apply transformation to the node
  125. }
  126. void scaleScene(const aiScene* scene, F32 scaleFactor) {
  127. aiMatrix4x4 scaleMatrix;
  128. scaleMatrix = aiMatrix4x4::Scaling(aiVector3D(scaleFactor, scaleFactor, scaleFactor), scaleMatrix);
  129. applyTransformation(scene->mRootNode, scaleMatrix);
  130. }
  131. void debugSceneMetaData(const aiScene* scene) {
  132. if (!scene->mMetaData) {
  133. Con::printf("[ASSIMP] No metadata available.");
  134. return;
  135. }
  136. for (U32 i = 0; i < scene->mMetaData->mNumProperties; ++i) {
  137. const char* key = scene->mMetaData->mKeys[i].C_Str();
  138. aiMetadataType type = scene->mMetaData->mValues[i].mType;
  139. Con::printf("[ASSIMP] Metadata key: %s", key);
  140. switch (type) {
  141. case AI_BOOL:
  142. Con::printf(" Value: %d (bool)", *(bool*)scene->mMetaData->mValues[i].mData);
  143. break;
  144. case AI_INT32:
  145. Con::printf(" Value: %d (int)", *(S32*)scene->mMetaData->mValues[i].mData);
  146. break;
  147. case AI_UINT64:
  148. Con::printf(" Value: %llu (uint64)", *(U64*)scene->mMetaData->mValues[i].mData);
  149. break;
  150. case AI_FLOAT:
  151. Con::printf(" Value: %f (float)", *(F32*)scene->mMetaData->mValues[i].mData);
  152. break;
  153. case AI_DOUBLE:
  154. Con::printf(" Value: %f (double)", *(F64*)scene->mMetaData->mValues[i].mData);
  155. break;
  156. case AI_AISTRING:
  157. Con::printf(" Value: %s (string)", ((aiString*)scene->mMetaData->mValues[i].mData)->C_Str());
  158. break;
  159. case AI_AIVECTOR3D:
  160. {
  161. aiVector3D* vec = (aiVector3D*)scene->mMetaData->mValues[i].mData;
  162. Con::printf(" Value: (%f, %f, %f) (vector3d)", vec->x, vec->y, vec->z);
  163. }
  164. break;
  165. default:
  166. Con::printf(" Unknown metadata type.");
  167. }
  168. }
  169. }
  170. void AssimpShapeLoader::enumerateScene()
  171. {
  172. TSShapeLoader::updateProgress(TSShapeLoader::Load_ReadFile, "Reading File");
  173. Con::printf("[ASSIMP] Attempting to load file: %s", shapePath.getFullPath().c_str());
  174. // Define post-processing steps
  175. U32 ppsteps = aiProcess_Triangulate | /*aiProcess_PreTransformVertices |*/ aiProcess_ConvertToLeftHanded & ~aiProcess_MakeLeftHanded;
  176. const auto& options = ColladaUtils::getOptions();
  177. if (options.calcTangentSpace) ppsteps |= aiProcess_CalcTangentSpace;
  178. if (options.joinIdenticalVerts) ppsteps |= aiProcess_JoinIdenticalVertices;
  179. if (options.removeRedundantMats) ppsteps |= aiProcess_RemoveRedundantMaterials;
  180. if (options.genUVCoords) ppsteps |= aiProcess_GenUVCoords;
  181. if (options.transformUVCoords) ppsteps |= aiProcess_TransformUVCoords;
  182. if (options.findInstances) ppsteps |= aiProcess_FindInstances;
  183. if (options.limitBoneWeights) ppsteps |= aiProcess_LimitBoneWeights;
  184. if (Con::getBoolVariable("$Assimp::OptimizeMeshes", false)) {
  185. ppsteps |= aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph;
  186. }
  187. if (Con::getBoolVariable("$Assimp::SplitLargeMeshes", false)) {
  188. ppsteps |= aiProcess_SplitLargeMeshes;
  189. }
  190. ppsteps |= aiProcess_ValidateDataStructure;
  191. struct aiLogStream shapeLog = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT, NULL);
  192. shapeLog.callback = assimpLogCallback;
  193. shapeLog.user = 0;
  194. aiAttachLogStream(&shapeLog);
  195. #ifdef TORQUE_DEBUG
  196. aiEnableVerboseLogging(true);
  197. #endif
  198. /*mImporter.SetPropertyInteger(AI_CONFIG_PP_PTV_KEEP_HIERARCHY, 1);
  199. mImporter.SetPropertyInteger(AI_CONFIG_PP_PTV_ADD_ROOT_TRANSFORMATION, 1);
  200. mImporter.SetPropertyMatrix(AI_CONFIG_PP_PTV_ROOT_TRANSFORMATION, aiMatrix4x4(1, 0, 0, 0,
  201. 0, 0, -1, 0,
  202. 0, 1, 0, 0,
  203. 0, 0, 0, 1));*/
  204. // Read the file
  205. mScene = mImporter.ReadFile(shapePath.getFullPath().c_str(), ppsteps);
  206. if (!mScene || (mScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) || !mScene->mRootNode) {
  207. Con::errorf("[ASSIMP] ERROR: Could not load file: %s", shapePath.getFullPath().c_str());
  208. Con::errorf("[ASSIMP] Importer error: %s", mImporter.GetErrorString());
  209. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import failed");
  210. return;
  211. }
  212. Con::printf("[ASSIMP] Mesh Count: %d", mScene->mNumMeshes);
  213. Con::printf("[ASSIMP] Material Count: %d", mScene->mNumMaterials);
  214. #ifdef TORQUE_DEBUG
  215. debugSceneMetaData(mScene);
  216. #endif
  217. ColladaUtils::getOptions().upAxis = UPAXISTYPE_Y_UP; // default to Y up for assimp.
  218. // Handle scaling
  219. configureImportUnits();
  220. // Format-specific adjustments
  221. String fileExt = String::ToLower(shapePath.getExtension());
  222. const aiImporterDesc* importerDescription = aiGetImporterDesc(fileExt.c_str());
  223. if (importerDescription && dStrcmp(importerDescription->mName, "Autodesk FBX Importer") == 0) {
  224. Con::printf("[ASSIMP] Detected FBX format, checking unit scale...");
  225. F32 scaleFactor = ColladaUtils::getOptions().unit;
  226. if (scaleFactor != 1.0f) {
  227. Con::printf("[ASSIMP] Applying FBX scale factor: %f", scaleFactor);
  228. scaleScene(mScene, scaleFactor);
  229. }
  230. else
  231. {
  232. scaleScene(mScene, 0.01f);
  233. }
  234. }
  235. for (U32 i = 0; i < mScene->mNumTextures; ++i) {
  236. extractTexture(i, mScene->mTextures[i]);
  237. }
  238. // Load all materials
  239. AssimpAppMaterial::sDefaultMatNumber = 0;
  240. for (U32 i = 0; i < mScene->mNumMaterials; ++i) {
  241. AppMesh::appMaterials.push_back(new AssimpAppMaterial(mScene->mMaterials[i]));
  242. }
  243. // Setup LOD checks
  244. detectDetails();
  245. aiMatrix4x4 sceneRoot = aiMatrix4x4(1, 0, 0, 0,
  246. 0, 0, -1, 0,
  247. 0, 1, 0, 0,
  248. 0, 0, 0, 1);
  249. applyTransformation(mScene->mRootNode, sceneRoot);
  250. // Process the scene graph
  251. AssimpAppNode* rootNode = new AssimpAppNode(mScene, mScene->mRootNode, 0);
  252. if (!processNode(rootNode)) {
  253. delete rootNode;
  254. }
  255. processAssimpNode(mScene->mRootNode, mScene, rootNode);
  256. // Add a bounds node if none exists
  257. if (!boundsNode) {
  258. aiNode* reqNode = new aiNode("bounds");
  259. mScene->mRootNode->addChildren(1, &reqNode);
  260. reqNode->mTransformation = aiMatrix4x4();// *sceneRoot;
  261. AssimpAppNode* appBoundsNode = new AssimpAppNode(mScene, reqNode);
  262. if (!processNode(appBoundsNode)) {
  263. delete appBoundsNode;
  264. }
  265. }
  266. // Process animations if available
  267. processAnimations();
  268. // Clean up log stream
  269. aiDetachLogStream(&shapeLog);
  270. }
  271. void AssimpShapeLoader::configureImportUnits() {
  272. auto& options = ColladaUtils::getOptions();
  273. // Configure unit scaling
  274. if (options.unit <= 0.0f) {
  275. F64 unitScaleFactor = 1.0;
  276. if (!getMetaDouble("UnitScaleFactor", unitScaleFactor)) {
  277. F32 floatVal;
  278. S32 intVal;
  279. if (getMetaFloat("UnitScaleFactor", floatVal)) {
  280. unitScaleFactor = static_cast<F64>(floatVal);
  281. }
  282. else if (getMetaInt("UnitScaleFactor", intVal)) {
  283. unitScaleFactor = static_cast<F64>(intVal);
  284. }
  285. }
  286. options.unit = static_cast<F32>(unitScaleFactor);
  287. }
  288. }
  289. void AssimpShapeLoader::processAssimpNode(const aiNode* node, const aiScene* scene, AssimpAppNode* parentNode)
  290. {
  291. AssimpAppNode* currNode;
  292. if (node == scene->mRootNode)
  293. {
  294. currNode = parentNode;
  295. }
  296. else
  297. {
  298. currNode = new AssimpAppNode(scene, node, parentNode);
  299. if (parentNode)
  300. {
  301. parentNode->addChild(currNode);
  302. }
  303. for (U32 i = 0; i < node->mNumMeshes; i++)
  304. {
  305. U32 meshIdx = node->mMeshes[i];
  306. const aiMesh* mesh = scene->mMeshes[meshIdx];
  307. AssimpAppMesh* curMesh = new AssimpAppMesh(mesh, currNode);
  308. currNode->addMesh(curMesh);
  309. }
  310. }
  311. // Recursively process child nodes
  312. for (U32 i = 0; i < node->mNumChildren; i++)
  313. {
  314. processAssimpNode(node->mChildren[i], scene, currNode);
  315. }
  316. }
  317. void AssimpShapeLoader::processAnimations()
  318. {
  319. // add all animations into 1 ambient animation.
  320. aiAnimation* ambientSeq = new aiAnimation();
  321. ambientSeq->mName = "ambient";
  322. Vector<aiNodeAnim*> ambientChannels;
  323. F32 duration = 0.0f;
  324. F32 ticks = 0.0f;
  325. if (mScene->mNumAnimations > 0)
  326. {
  327. for (U32 i = 0; i < mScene->mNumAnimations; ++i)
  328. {
  329. aiAnimation* anim = mScene->mAnimations[i];
  330. ticks = anim->mTicksPerSecond;
  331. duration = 0.0f;
  332. for (U32 j = 0; j < anim->mNumChannels; j++)
  333. {
  334. aiNodeAnim* nodeAnim = anim->mChannels[j];
  335. // Determine the maximum keyframe time for this animation
  336. F32 maxKeyTime = 0.0f;
  337. for (U32 k = 0; k < nodeAnim->mNumPositionKeys; k++) {
  338. maxKeyTime = getMax(maxKeyTime, (F32)nodeAnim->mPositionKeys[k].mTime);
  339. }
  340. for (U32 k = 0; k < nodeAnim->mNumRotationKeys; k++) {
  341. maxKeyTime = getMax(maxKeyTime, (F32)nodeAnim->mRotationKeys[k].mTime);
  342. }
  343. for (U32 k = 0; k < nodeAnim->mNumScalingKeys; k++) {
  344. maxKeyTime = getMax(maxKeyTime, (F32)nodeAnim->mScalingKeys[k].mTime);
  345. }
  346. ambientChannels.push_back(nodeAnim);
  347. duration = getMax(duration, maxKeyTime);
  348. }
  349. }
  350. ambientSeq->mNumChannels = ambientChannels.size();
  351. ambientSeq->mChannels = ambientChannels.address();
  352. ambientSeq->mDuration = duration;
  353. ambientSeq->mTicksPerSecond = ticks;
  354. AssimpAppSequence* defaultAssimpSeq = new AssimpAppSequence(ambientSeq);
  355. appSequences.push_back(defaultAssimpSeq);
  356. }
  357. }
  358. void AssimpShapeLoader::computeBounds(Box3F& bounds)
  359. {
  360. TSShapeLoader::computeBounds(bounds);
  361. // Check if the model origin needs adjusting
  362. bool adjustCenter = ColladaUtils::getOptions().adjustCenter;
  363. bool adjustFloor = ColladaUtils::getOptions().adjustFloor;
  364. if (bounds.isValidBox() && (adjustCenter || adjustFloor))
  365. {
  366. // Compute shape offset
  367. Point3F shapeOffset = Point3F::Zero;
  368. if (adjustCenter)
  369. {
  370. bounds.getCenter(&shapeOffset);
  371. shapeOffset = -shapeOffset;
  372. }
  373. if (adjustFloor)
  374. shapeOffset.z = -bounds.minExtents.z;
  375. // Adjust bounds
  376. bounds.minExtents += shapeOffset;
  377. bounds.maxExtents += shapeOffset;
  378. // Now adjust all positions for root level nodes (nodes with no parent)
  379. for (S32 iNode = 0; iNode < shape->nodes.size(); iNode++)
  380. {
  381. if (!appNodes[iNode]->isParentRoot())
  382. continue;
  383. // Adjust default translation
  384. shape->defaultTranslations[iNode] += shapeOffset;
  385. // Adjust animated translations
  386. for (S32 iSeq = 0; iSeq < shape->sequences.size(); iSeq++)
  387. {
  388. const TSShape::Sequence& seq = shape->sequences[iSeq];
  389. if (seq.translationMatters.test(iNode))
  390. {
  391. for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
  392. {
  393. S32 index = seq.baseTranslation + seq.translationMatters.count(iNode)*seq.numKeyframes + iFrame;
  394. shape->nodeTranslations[index] += shapeOffset;
  395. }
  396. }
  397. }
  398. }
  399. }
  400. }
  401. bool AssimpShapeLoader::fillGuiTreeView(const char* sourceShapePath, GuiTreeViewCtrl* tree)
  402. {
  403. Assimp::Importer importer;
  404. Torque::Path path(sourceShapePath);
  405. String cleanFile = AppMaterial::cleanString(path.getFileName());
  406. // Attempt to import with Assimp.
  407. const aiScene* shapeScene = importer.ReadFile(path.getFullPath().c_str(), (aiProcessPreset_TargetRealtime_Quality | aiProcess_CalcTangentSpace)
  408. & ~aiProcess_RemoveRedundantMaterials & ~aiProcess_GenSmoothNormals);
  409. if (!shapeScene)
  410. {
  411. Con::printf("AssimpShapeLoader::fillGuiTreeView - Assimp Error: %s", importer.GetErrorString());
  412. return false;
  413. }
  414. mScene = shapeScene;
  415. // Initialize tree
  416. tree->removeItem(0);
  417. S32 meshItem = tree->insertItem(0, "Meshes", String::ToString("%i", shapeScene->mNumMeshes));
  418. S32 matItem = tree->insertItem(0, "Materials", String::ToString("%i", shapeScene->mNumMaterials));
  419. S32 animItem = tree->insertItem(0, "Animations", String::ToString("%i", shapeScene->mNumAnimations));
  420. //S32 lightsItem = tree->insertItem(0, "Lights", String::ToString("%i", shapeScene->mNumLights));
  421. //S32 texturesItem = tree->insertItem(0, "Textures", String::ToString("%i", shapeScene->mNumTextures));
  422. //Details!
  423. U32 numPolys = 0;
  424. U32 numVerts = 0;
  425. for (U32 i = 0; i < shapeScene->mNumMeshes; i++)
  426. {
  427. tree->insertItem(meshItem, String::ToString("%s", shapeScene->mMeshes[i]->mName.C_Str()));
  428. numPolys += shapeScene->mMeshes[i]->mNumFaces;
  429. numVerts += shapeScene->mMeshes[i]->mNumVertices;
  430. }
  431. U32 defaultMatNumber = 0;
  432. for (U32 i = 0; i < shapeScene->mNumMaterials; i++)
  433. {
  434. aiMaterial* aiMat = shapeScene->mMaterials[i];
  435. aiString matName;
  436. aiMat->Get(AI_MATKEY_NAME, matName);
  437. String name = matName.C_Str();
  438. if (name.isEmpty())
  439. {
  440. name = AppMaterial::cleanString(path.getFileName());
  441. name += "_defMat";
  442. name += String::ToString("%d", defaultMatNumber);
  443. defaultMatNumber++;
  444. }
  445. aiString texPath;
  446. aiMat->GetTexture(aiTextureType::aiTextureType_DIFFUSE, 0, &texPath);
  447. String texName = texPath.C_Str();
  448. if (texName.isEmpty())
  449. {
  450. aiColor3D read_color(1.f, 1.f, 1.f);
  451. if (AI_SUCCESS == aiMat->Get(AI_MATKEY_COLOR_DIFFUSE, read_color))
  452. 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
  453. else
  454. texName = "No Texture";
  455. }
  456. else
  457. texName = AssimpAppMaterial::cleanTextureName(texName, cleanFile, sourceShapePath, true);
  458. tree->insertItem(matItem, String::ToString("%s", name.c_str()), String::ToString("%s", texName.c_str()));
  459. }
  460. if (shapeScene->mNumAnimations == 0)
  461. {
  462. tree->insertItem(animItem, "ambient", "animation", "", 0, 0);
  463. }
  464. else
  465. {
  466. for (U32 i = 0; i < shapeScene->mNumAnimations; i++)
  467. {
  468. tree->insertItem(animItem, shapeScene->mAnimations[i]->mName.C_Str(), "animation", "", 0, 0);
  469. }
  470. }
  471. U32 numNodes = 0;
  472. if (shapeScene->mRootNode)
  473. {
  474. S32 nodesItem = tree->insertItem(0, "Nodes", "");
  475. addNodeToTree(nodesItem, shapeScene->mRootNode, tree, numNodes);
  476. tree->setItemValue(nodesItem, String::ToString("%i", numNodes));
  477. }
  478. U32 numMetaTags = shapeScene->mMetaData ? shapeScene->mMetaData->mNumProperties : 0;
  479. if (numMetaTags)
  480. addMetaDataToTree(shapeScene->mMetaData, tree);
  481. F64 unit;
  482. if (!getMetaDouble("UnitScaleFactor", unit))
  483. unit = 1.0f;
  484. S32 upAxis;
  485. if (!getMetaInt("UpAxis", upAxis))
  486. upAxis = UPAXISTYPE_Z_UP;
  487. /*for (U32 i = 0; i < shapeScene->mNumLights; i++)
  488. {
  489. treeObj->insertItem(lightsItem, String::ToString("%s", shapeScene->mLights[i]->mType));
  490. }*/
  491. // Store shape information in the tree control
  492. tree->setDataField(StringTable->insert("_nodeCount"), 0, avar("%d", numNodes));
  493. tree->setDataField(StringTable->insert("_meshCount"), 0, avar("%d", shapeScene->mNumMeshes));
  494. tree->setDataField(StringTable->insert("_polygonCount"), 0, avar("%d", numPolys));
  495. tree->setDataField(StringTable->insert("_materialCount"), 0, avar("%d", shapeScene->mNumMaterials));
  496. tree->setDataField(StringTable->insert("_lightCount"), 0, avar("%d", shapeScene->mNumLights));
  497. tree->setDataField(StringTable->insert("_animCount"), 0, avar("%d", shapeScene->mNumAnimations));
  498. tree->setDataField(StringTable->insert("_textureCount"), 0, avar("%d", shapeScene->mNumTextures));
  499. tree->setDataField(StringTable->insert("_vertCount"), 0, avar("%d", numVerts));
  500. tree->setDataField(StringTable->insert("_metaTagCount"), 0, avar("%d", numMetaTags));
  501. tree->setDataField(StringTable->insert("_unit"), 0, avar("%g", (F32)unit));
  502. if (upAxis == UPAXISTYPE_X_UP)
  503. tree->setDataField(StringTable->insert("_upAxis"), 0, "X_AXIS");
  504. else if (upAxis == UPAXISTYPE_Y_UP)
  505. tree->setDataField(StringTable->insert("_upAxis"), 0, "Y_AXIS");
  506. else
  507. tree->setDataField(StringTable->insert("_upAxis"), 0, "Z_AXIS");
  508. return true;
  509. }
  510. void AssimpShapeLoader::updateMaterialsScript(const Torque::Path &path)
  511. {
  512. return;
  513. /*
  514. Torque::Path scriptPath(path);
  515. scriptPath.setFileName("materials");
  516. scriptPath.setExtension(TORQUE_SCRIPT_EXTENSION);
  517. // First see what materials we need to update
  518. PersistenceManager persistMgr;
  519. for ( U32 iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++ )
  520. {
  521. AssimpAppMaterial *mat = dynamic_cast<AssimpAppMaterial*>( AppMesh::appMaterials[iMat] );
  522. if ( mat )
  523. {
  524. Material *mappedMat;
  525. if ( Sim::findObject( MATMGR->getMapEntry( mat->getName() ), mappedMat ) )
  526. {
  527. // Only update existing materials if forced to
  528. if (ColladaUtils::getOptions().forceUpdateMaterials)
  529. {
  530. mat->initMaterial(scriptPath, mappedMat);
  531. persistMgr.setDirty(mappedMat);
  532. }
  533. }
  534. else
  535. {
  536. // Create a new material definition
  537. persistMgr.setDirty( mat->createMaterial( scriptPath ), scriptPath.getFullPath() );
  538. }
  539. }
  540. }
  541. if ( persistMgr.getDirtyList().empty() )
  542. return;
  543. persistMgr.saveDirty();
  544. */
  545. }
  546. /// Check if an up-to-date cached DTS is available for this DAE file
  547. bool AssimpShapeLoader::canLoadCachedDTS(const Torque::Path& path)
  548. {
  549. // Generate the cached filename
  550. Torque::Path cachedPath(path);
  551. cachedPath.setExtension("cached.dts");
  552. // Check if a cached DTS newer than this file is available
  553. FileTime cachedModifyTime;
  554. if (Platform::getFileTimes(cachedPath.getFullPath(), NULL, &cachedModifyTime))
  555. {
  556. bool forceLoad = Con::getBoolVariable("$assimp::forceLoad", false);
  557. FileTime daeModifyTime;
  558. if (!Platform::getFileTimes(path.getFullPath(), NULL, &daeModifyTime) ||
  559. (!forceLoad && (Platform::compareFileTimes(cachedModifyTime, daeModifyTime) >= 0) ))
  560. {
  561. // Original file not found, or cached DTS is newer
  562. return true;
  563. }
  564. }
  565. return false;
  566. }
  567. void AssimpShapeLoader::assimpLogCallback(const char* message, char* user)
  568. {
  569. Con::printf("[Assimp log message] %s", StringUnit::getUnit(message, 0, "\n"));
  570. }
  571. bool AssimpShapeLoader::ignoreNode(const String& name)
  572. {
  573. // Do not add AssimpFbx dummy nodes to the TSShape. See: Assimp::FBX::ImportSettings::preservePivots
  574. // https://github.com/assimp/assimp/blob/master/code/FBXImportSettings.h#L116-L135
  575. if (name.find("_$AssimpFbx$_") != String::NPos)
  576. return true;
  577. if (FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().alwaysImport, name, false))
  578. return false;
  579. return FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().neverImport, name, false);
  580. }
  581. bool AssimpShapeLoader::ignoreMesh(const String& name)
  582. {
  583. if (FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().alwaysImportMesh, name, false))
  584. return false;
  585. else
  586. return FindMatch::isMatchMultipleExprs(ColladaUtils::getOptions().neverImportMesh, name, false);
  587. }
  588. void AssimpShapeLoader::detectDetails()
  589. {
  590. // Set LOD option
  591. bool singleDetail = true;
  592. switch (ColladaUtils::getOptions().lodType)
  593. {
  594. case ColladaUtils::ImportOptions::DetectDTS:
  595. // Check for a baseXX->startXX hierarchy at the top-level, if we find
  596. // one, use trailing numbers for LOD, otherwise use a single size
  597. for (S32 iNode = 0; singleDetail && (iNode < mScene->mRootNode->mNumChildren); iNode++) {
  598. aiNode* node = mScene->mRootNode->mChildren[iNode];
  599. if (node && dStrStartsWith(node->mName.C_Str(), "base")) {
  600. for (S32 iChild = 0; iChild < node->mNumChildren; iChild++) {
  601. aiNode* child = node->mChildren[iChild];
  602. if (child && dStrStartsWith(child->mName.C_Str(), "start")) {
  603. singleDetail = false;
  604. break;
  605. }
  606. }
  607. }
  608. }
  609. break;
  610. case ColladaUtils::ImportOptions::SingleSize:
  611. singleDetail = true;
  612. break;
  613. case ColladaUtils::ImportOptions::TrailingNumber:
  614. singleDetail = false;
  615. break;
  616. default:
  617. break;
  618. }
  619. AssimpAppMesh::fixDetailSize(singleDetail, ColladaUtils::getOptions().singleDetailSize);
  620. }
  621. void AssimpShapeLoader::extractTexture(U32 index, aiTexture* pTex)
  622. { // Cache an embedded texture to disk
  623. updateProgress(Load_EnumerateScene, "Extracting Textures...", mScene->mNumTextures, index);
  624. Con::printf("[Assimp] Extracting Texture %s, W: %d, H: %d, %d of %d, format hint: (%s)", pTex->mFilename.C_Str(),
  625. pTex->mWidth, pTex->mHeight, index, mScene->mNumTextures, pTex->achFormatHint);
  626. // Create the texture filename
  627. String cleanFile = AppMaterial::cleanString(TSShapeLoader::getShapePath().getFileName());
  628. String texName = String::ToString("%s_cachedTex%d", cleanFile.c_str(), index);
  629. Torque::Path texPath = shapePath;
  630. texPath.setFileName(texName);
  631. if (pTex->mHeight == 0)
  632. { // Compressed format, write the data directly to disc
  633. texPath.setExtension(pTex->achFormatHint);
  634. FileStream *outputStream;
  635. if ((outputStream = FileStream::createAndOpen(texPath.getFullPath(), Torque::FS::File::Write)) != NULL)
  636. {
  637. outputStream->setPosition(0);
  638. outputStream->write(pTex->mWidth, pTex->pcData);
  639. outputStream->close();
  640. delete outputStream;
  641. }
  642. }
  643. else
  644. { // Embedded pixel data, fill a bitmap and save it.
  645. GFXTexHandle shapeTex;
  646. shapeTex.set(pTex->mWidth, pTex->mHeight, GFXFormatR8G8B8A8_SRGB, &GFXDynamicTextureSRGBProfile,
  647. String::ToString("AssimpShapeLoader (%s:%i)", __FILE__, __LINE__), 1, 0);
  648. GFXLockedRect *rect = shapeTex.lock();
  649. for (U32 y = 0; y < pTex->mHeight; ++y)
  650. {
  651. for (U32 x = 0; x < pTex->mWidth; ++x)
  652. {
  653. U32 targetIndex = (y * rect->pitch) + (x * 4);
  654. U32 sourceIndex = ((y * pTex->mWidth) + x) * 4;
  655. rect->bits[targetIndex] = pTex->pcData[sourceIndex].r;
  656. rect->bits[targetIndex + 1] = pTex->pcData[sourceIndex].g;
  657. rect->bits[targetIndex + 2] = pTex->pcData[sourceIndex].b;
  658. rect->bits[targetIndex + 3] = pTex->pcData[sourceIndex].a;
  659. }
  660. }
  661. shapeTex.unlock();
  662. texPath.setExtension("png");
  663. shapeTex->dumpToDisk("PNG", texPath.getFullPath());
  664. }
  665. }
  666. void AssimpShapeLoader::addNodeToTree(S32 parentItem, aiNode* node, GuiTreeViewCtrl* tree, U32& nodeCount)
  667. {
  668. // Add this node
  669. S32 nodeItem = parentItem;
  670. String nodeName = node->mName.C_Str();
  671. if (!ignoreNode(nodeName))
  672. {
  673. if (nodeName.isEmpty())
  674. nodeName = "null";
  675. nodeItem = tree->insertItem(parentItem, nodeName.c_str(), String::ToString("%i", node->mNumChildren));
  676. nodeCount++;
  677. }
  678. // Add any child nodes
  679. for (U32 n = 0; n < node->mNumChildren; ++n)
  680. addNodeToTree(nodeItem, node->mChildren[n], tree, nodeCount);
  681. }
  682. void AssimpShapeLoader::addMetaDataToTree(const aiMetadata* metaData, GuiTreeViewCtrl* tree)
  683. {
  684. S32 metaItem = tree->insertItem(0, "MetaData", String::ToString("%i", metaData->mNumProperties));
  685. aiString valString;
  686. aiVector3D valVec;
  687. for (U32 n = 0; n < metaData->mNumProperties; ++n)
  688. {
  689. String keyStr = metaData->mKeys[n].C_Str();
  690. keyStr += ": ";
  691. switch (metaData->mValues[n].mType)
  692. {
  693. case AI_BOOL:
  694. keyStr += ((bool)metaData->mValues[n].mData) ? "true" : "false";
  695. break;
  696. case AI_INT32:
  697. keyStr += String::ToString(*((S32*)(metaData->mValues[n].mData)));
  698. break;
  699. case AI_UINT64:
  700. keyStr += String::ToString("%I64u", *((U64*)metaData->mValues[n].mData));
  701. break;
  702. case AI_FLOAT:
  703. keyStr += String::ToString(*((F32*)metaData->mValues[n].mData));
  704. break;
  705. case AI_DOUBLE:
  706. keyStr += String::ToString(*((F64*)metaData->mValues[n].mData));
  707. break;
  708. case AI_AISTRING:
  709. metaData->Get<aiString>(metaData->mKeys[n], valString);
  710. keyStr += valString.C_Str();
  711. break;
  712. case AI_AIVECTOR3D:
  713. metaData->Get<aiVector3D>(metaData->mKeys[n], valVec);
  714. keyStr += String::ToString("%f, %f, %f", valVec.x, valVec.y, valVec.z);
  715. break;
  716. default:
  717. break;
  718. }
  719. tree->insertItem(metaItem, keyStr.c_str(), String::ToString("%i", n));
  720. }
  721. }
  722. bool AssimpShapeLoader::getMetabool(const char* key, bool& boolVal)
  723. {
  724. if (!mScene || !mScene->mMetaData)
  725. return false;
  726. String keyStr = key;
  727. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  728. {
  729. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  730. {
  731. if (mScene->mMetaData->mValues[n].mType == AI_BOOL)
  732. {
  733. boolVal = (bool)mScene->mMetaData->mValues[n].mData;
  734. return true;
  735. }
  736. }
  737. }
  738. return false;
  739. }
  740. bool AssimpShapeLoader::getMetaInt(const char* key, S32& intVal)
  741. {
  742. if (!mScene || !mScene->mMetaData)
  743. return false;
  744. String keyStr = key;
  745. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  746. {
  747. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  748. {
  749. if (mScene->mMetaData->mValues[n].mType == AI_INT32)
  750. {
  751. intVal = *((S32*)(mScene->mMetaData->mValues[n].mData));
  752. return true;
  753. }
  754. }
  755. }
  756. return false;
  757. }
  758. bool AssimpShapeLoader::getMetaFloat(const char* key, F32& floatVal)
  759. {
  760. if (!mScene || !mScene->mMetaData)
  761. return false;
  762. String keyStr = key;
  763. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  764. {
  765. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  766. {
  767. if (mScene->mMetaData->mValues[n].mType == AI_FLOAT)
  768. {
  769. floatVal = *((F32*)mScene->mMetaData->mValues[n].mData);
  770. return true;
  771. }
  772. }
  773. }
  774. return false;
  775. }
  776. bool AssimpShapeLoader::getMetaDouble(const char* key, F64& doubleVal)
  777. {
  778. if (!mScene || !mScene->mMetaData)
  779. return false;
  780. String keyStr = key;
  781. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  782. {
  783. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  784. {
  785. if (mScene->mMetaData->mValues[n].mType == AI_DOUBLE)
  786. {
  787. doubleVal = *((F64*)mScene->mMetaData->mValues[n].mData);
  788. return true;
  789. }
  790. }
  791. }
  792. return false;
  793. }
  794. bool AssimpShapeLoader::getMetaString(const char* key, String& stringVal)
  795. {
  796. if (!mScene || !mScene->mMetaData)
  797. return false;
  798. String keyStr = key;
  799. for (U32 n = 0; n < mScene->mMetaData->mNumProperties; ++n)
  800. {
  801. if (keyStr.equal(mScene->mMetaData->mKeys[n].C_Str(), String::NoCase))
  802. {
  803. if (mScene->mMetaData->mValues[n].mType == AI_AISTRING)
  804. {
  805. aiString valString;
  806. mScene->mMetaData->Get<aiString>(mScene->mMetaData->mKeys[n], valString);
  807. stringVal = valString.C_Str();
  808. return true;
  809. }
  810. }
  811. }
  812. return false;
  813. }
  814. //-----------------------------------------------------------------------------
  815. /// This function is invoked by the resource manager based on file extension.
  816. TSShape* assimpLoadShape(const Torque::Path &path)
  817. {
  818. // TODO: add .cached.dts generation.
  819. // Generate the cached filename
  820. Torque::Path cachedPath(path);
  821. cachedPath.setExtension("cached.dts");
  822. // Check if an up-to-date cached DTS version of this file exists, and
  823. // if so, use that instead.
  824. if (AssimpShapeLoader::canLoadCachedDTS(path))
  825. {
  826. FileStream cachedStream;
  827. cachedStream.open(cachedPath.getFullPath(), Torque::FS::File::Read);
  828. if (cachedStream.getStatus() == Stream::Ok)
  829. {
  830. TSShape *shape = new TSShape;
  831. bool readSuccess = shape->read(&cachedStream);
  832. cachedStream.close();
  833. if (readSuccess)
  834. {
  835. #ifdef TORQUE_DEBUG
  836. Con::printf("Loaded cached shape from %s", cachedPath.getFullPath().c_str());
  837. #endif
  838. return shape;
  839. }
  840. else
  841. delete shape;
  842. }
  843. Con::warnf("Failed to load cached shape from %s", cachedPath.getFullPath().c_str());
  844. }
  845. if (!Torque::FS::IsFile(path))
  846. {
  847. // File does not exist, bail.
  848. return NULL;
  849. }
  850. // Allow TSShapeConstructor object to override properties
  851. ColladaUtils::getOptions().reset();
  852. TSShapeConstructor* tscon = TSShapeConstructor::findShapeConstructorByFilename(path.getFullPath());
  853. if (tscon)
  854. {
  855. ColladaUtils::getOptions() = tscon->mOptions;
  856. }
  857. AssimpShapeLoader loader;
  858. TSShape* tss = loader.generateShape(path);
  859. if (tss)
  860. {
  861. TSShapeLoader::updateProgress(TSShapeLoader::Load_Complete, "Import complete");
  862. Con::printf("[ASSIMP] Shape created successfully.");
  863. if (tss->meshes.empty())
  864. {
  865. Torque::Path dsqPath(cachedPath);
  866. dsqPath.setExtension("dsq");
  867. FileStream animOutStream;
  868. for (S32 i = 0; i < tss->sequences.size(); i++)
  869. {
  870. const String& seqName = tss->getName(tss->sequences[i].nameIndex);
  871. Con::printf("Writing DSQ Animation File for sequence '%s'", seqName.c_str());
  872. dsqPath.setFileName(cachedPath.getFileName() + "_" + seqName);
  873. if (animOutStream.open(dsqPath.getFullPath(), Torque::FS::File::Write))
  874. {
  875. tss->exportSequence(&animOutStream, tss->sequences[i], false);
  876. animOutStream.close();
  877. }
  878. }
  879. }
  880. else
  881. {
  882. // Cache the model to a DTS file for faster loading next time.
  883. FileStream dtsStream;
  884. if (dtsStream.open(cachedPath.getFullPath(), Torque::FS::File::Write))
  885. {
  886. Con::printf("Writing cached shape to %s", cachedPath.getFullPath().c_str());
  887. tss->write(&dtsStream);
  888. }
  889. }
  890. loader.updateMaterialsScript(path);
  891. }
  892. loader.releaseImport();
  893. return tss;
  894. }
  895. DefineEngineFunction(GetShapeInfo, bool, (const char* shapePath, const char* ctrl, bool loadCachedDts), ("", "", true),
  896. "(string shapePath, GuiTreeViewCtrl ctrl) Collect scene information from "
  897. "a shape file and store it in a GuiTreeView control. This function is "
  898. "used by the assimp import gui to show a preview of the scene contents "
  899. "prior to import, and is probably not much use for anything else.\n"
  900. "@param shapePath shape filename\n"
  901. "@param ctrl GuiTreeView control to add elements to\n"
  902. "@return true if successful, false otherwise\n"
  903. "@ingroup Editors\n"
  904. "@internal")
  905. {
  906. GuiTreeViewCtrl* tree;
  907. if (!Sim::findObject(ctrl, tree))
  908. {
  909. Con::errorf("enumColladaScene::Could not find GuiTreeViewCtrl '%s'", ctrl);
  910. return false;
  911. }
  912. // Check if a cached DTS is available => no need to import the source file
  913. // if we can load the DTS instead
  914. Torque::Path path(shapePath);
  915. if (loadCachedDts && AssimpShapeLoader::canLoadCachedDTS(path))
  916. return false;
  917. AssimpShapeLoader loader;
  918. return loader.fillGuiTreeView(shapePath, tree);
  919. }