assimpShapeLoader.cpp 34 KB

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