assimpShapeLoader.cpp 34 KB

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