OpenAssetImporter.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. #include <Atomic/Core/ProcessUtils.h>
  25. #include <Atomic/Core/Context.h>
  26. #include <Atomic/IO/Log.h>
  27. #include <Atomic/IO/File.h>
  28. #include <Atomic/IO/FileSystem.h>
  29. #include <Atomic/Resource/XMLFile.h>
  30. #include <Atomic/Resource/ResourceCache.h>
  31. #include <Atomic/Graphics/AnimatedModel.h>
  32. #include <Atomic/Graphics/Animation.h>
  33. #include <Atomic/Graphics/AnimationController.h>
  34. #include <Atomic/Graphics/Geometry.h>
  35. #include <Atomic/Graphics/IndexBuffer.h>
  36. #include <Atomic/Graphics/VertexBuffer.h>
  37. #include <Atomic/Graphics/Material.h>
  38. #include <ToolCore/Project/Project.h>
  39. #include <ToolCore/ToolSystem.h>
  40. #include <ToolCore/Import/ImportConfig.h>
  41. // BEGIN GLOW FIXME
  42. // This is just here to generate UV2 on mdl's being imported
  43. #include <AtomicGlow/Atlas/MeshLightmapUVGen.h>
  44. using namespace AtomicGlow;
  45. // END GLOW FIXME
  46. #include "OpenAssetImporter.h"
  47. namespace ToolCore
  48. {
  49. OpenAssetImporter::OpenAssetImporter(Context* context) : Object(context) ,
  50. scene_(0),
  51. rootNode_(0),
  52. useSubdirs_(true),
  53. importMaterials_(true),
  54. importMaterialsDefault_(true),
  55. localIDs_(false),
  56. saveBinary_(false),
  57. createZone_(true),
  58. noAnimations_(false),
  59. noHierarchy_(false),
  60. noMaterials_(false),
  61. noTextures_(false),
  62. noMaterialDiffuseColor_(false),
  63. noEmptyNodes_(false),
  64. saveMaterialList_(false),
  65. includeNonSkinningBones_(false),
  66. includeNonSkinningBonesDefault_(false),
  67. verboseLog_(false),
  68. emissiveAO_(false),
  69. noOverwriteMaterial_(true),
  70. noOverwriteTexture_(true),
  71. noOverwriteNewerTexture_(true),
  72. checkUniqueModel_(true),
  73. useVertexColors_(false),
  74. scale_(1.0f),
  75. maxBones_(64),
  76. defaultTicksPerSecond_(4800.0f),
  77. startTime_(-1),
  78. endTime_(-1)
  79. {
  80. aiFlagsDefault_ =
  81. aiProcess_ConvertToLeftHanded |
  82. aiProcess_JoinIdenticalVertices |
  83. aiProcess_Triangulate |
  84. aiProcess_GenSmoothNormals |
  85. aiProcess_LimitBoneWeights |
  86. aiProcess_ImproveCacheLocality |
  87. aiProcess_FixInfacingNormals |
  88. aiProcess_FindInvalidData |
  89. aiProcess_GenUVCoords |
  90. aiProcess_FindInstances |
  91. aiProcess_OptimizeMeshes;
  92. ApplyProjectImportConfig();
  93. // TODO: make this an option on importer
  94. aiFlagsDefault_ |= aiProcess_CalcTangentSpace;
  95. aiCurrentFlags_ = aiFlagsDefault_;
  96. }
  97. OpenAssetImporter::~OpenAssetImporter()
  98. {
  99. if (scene_)
  100. aiReleaseImport(scene_);
  101. }
  102. bool OpenAssetImporter::Load(const String &assetPath)
  103. {
  104. if (verboseLog_)
  105. Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE, aiDefaultLogStream_STDOUT);
  106. //PrintLine("Reading file " + assetPath);
  107. sourceAssetFilename_ = assetPath;
  108. sourceAssetPath_ = GetPath(assetPath);
  109. scene_ = aiImportFile(GetNativePath(assetPath).CString(), aiCurrentFlags_);
  110. if (!scene_)
  111. {
  112. errorMessage_ = "Could not open or parse input file " + assetPath + ": " + String(aiGetErrorString());
  113. return false;
  114. }
  115. if (verboseLog_)
  116. Assimp::DefaultLogger::kill();
  117. rootNode_ = scene_->mRootNode;
  118. ApplyScale();
  119. // DumpNodes(rootNode_, 0);
  120. return true;
  121. }
  122. void OpenAssetImporter::ApplyScale(aiNode* node)
  123. {
  124. if (!node)
  125. return;
  126. aiVector3D pos, scale;
  127. aiQuaternion rot;
  128. node->mTransformation.Decompose(scale, rot, pos);
  129. pos *= scale_;
  130. node->mTransformation = aiMatrix4x4(scale, rot, pos);
  131. for (unsigned i = 0; i < node->mNumChildren; i++)
  132. {
  133. ApplyScale(node->mChildren[i]);
  134. }
  135. }
  136. void OpenAssetImporter::ApplyScale()
  137. {
  138. if (scale_ == 1.0f)
  139. return;
  140. ApplyScale(scene_->mRootNode);
  141. for (unsigned i = 0; i < scene_->mNumMeshes; i++)
  142. {
  143. aiMesh* mesh = scene_->mMeshes[i];
  144. for (unsigned j = 0; j < mesh->mNumVertices; j++)
  145. {
  146. mesh->mVertices[j] *= scale_;
  147. }
  148. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  149. {
  150. aiBone* bone = mesh->mBones[j];
  151. aiVector3D pos, scale;
  152. aiQuaternion rot;
  153. bone->mOffsetMatrix.Decompose(scale, rot, pos);
  154. pos *= scale_;
  155. bone->mOffsetMatrix = aiMatrix4x4(scale, rot, pos);
  156. }
  157. }
  158. for (unsigned i = 0; i < scene_->mNumAnimations; i++)
  159. {
  160. aiAnimation* animation = scene_->mAnimations[i];
  161. for (unsigned j = 0; j < animation->mNumChannels; j++)
  162. {
  163. aiNodeAnim* channel = animation->mChannels[j];
  164. for (unsigned k = 0; k < channel->mNumPositionKeys; k++)
  165. {
  166. channel->mPositionKeys[k].mValue *= scale_;
  167. }
  168. }
  169. }
  170. }
  171. bool OpenAssetImporter::ExportModel(const String& outName, const String &animName, bool animationOnly)
  172. {
  173. if (outName.Empty())
  174. {
  175. errorMessage_ = "No output file defined";
  176. return false;
  177. }
  178. OutModel model;
  179. model.rootNode_ = rootNode_;
  180. model.outName_ = outName + ".mdl";
  181. CollectMeshes(scene_, model, model.rootNode_);
  182. if (!CollectBones(model, animationOnly))
  183. return false;
  184. BuildBoneCollisionInfo(model);
  185. if (!animationOnly)
  186. {
  187. if (!BuildAndSaveModel(model))
  188. return false;
  189. }
  190. if (!noAnimations_)
  191. {
  192. CollectAnimations(&model);
  193. if (!BuildAndSaveAnimations(&model, animName))
  194. return false;
  195. // Save scene-global animations
  196. // CollectAnimations();
  197. // BuildAndSaveAnimations();
  198. }
  199. if (!noMaterials_ && !animationOnly)
  200. {
  201. HashSet<String> usedTextures;
  202. ExportMaterials(usedTextures);
  203. }
  204. if (importNode_.Null())
  205. {
  206. errorMessage_ = "NULL importNode_";
  207. return false;
  208. }
  209. ResourceCache* cache = GetSubsystem<ResourceCache>();
  210. Model* mdl = cache->GetResource<Model>( model.outName_);
  211. // Force a reload, though file watchers will catch this delayed and load again
  212. cache->ReloadResource(mdl);
  213. if (!mdl)
  214. {
  215. errorMessage_ = "Unable to load " + model.outName_ + " from Cache";
  216. return false;
  217. }
  218. StaticModel* modelComponent = 0;
  219. if (!mdl->GetSkeleton().GetNumBones())
  220. {
  221. modelComponent = importNode_->CreateComponent<StaticModel>();
  222. modelComponent->SetModel(mdl);
  223. }
  224. else
  225. {
  226. modelComponent = importNode_->CreateComponent<AnimatedModel>();
  227. importNode_->CreateComponent<AnimationController>();
  228. ((AnimatedModel*)modelComponent)->SetModel(mdl, false);
  229. }
  230. if (!noMaterials_)
  231. {
  232. // Set materials if they are known
  233. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  234. {
  235. String matName = GetMeshMaterialName(model.meshes_[j]);
  236. String materialName = sourceAssetPath_ + matName;
  237. modelComponent->SetMaterial(j, cache->GetResource<Material>(materialName));
  238. }
  239. }
  240. return true;
  241. }
  242. bool OpenAssetImporter::BuildAndSaveModel(OutModel& model)
  243. {
  244. if (!model.rootNode_)
  245. {
  246. errorMessage_ = "Null root node for model";
  247. return false;
  248. }
  249. String rootNodeName = FromAIString(model.rootNode_->mName);
  250. if (!model.meshes_.Size())
  251. {
  252. errorMessage_ = "No geometries found starting from node " + rootNodeName;
  253. return false;
  254. }
  255. //PrintLine("Writing model " + rootNodeName);
  256. SharedPtr<Model> outModel(new Model(context_));
  257. Vector<PODVector<unsigned> > allBoneMappings;
  258. BoundingBox box;
  259. unsigned numValidGeometries = 0;
  260. bool combineBuffers = true;
  261. // Check if buffers can be combined (same vertex element mask, under 65535 vertices)
  262. unsigned elementMask = GetElementMask(model.meshes_[0]);
  263. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  264. {
  265. if (GetNumValidFaces(model.meshes_[i]))
  266. {
  267. ++numValidGeometries;
  268. if (i > 0 && GetElementMask(model.meshes_[i]) != elementMask)
  269. combineBuffers = false;
  270. }
  271. }
  272. // Check if keeping separate buffers allows to avoid 32-bit indices
  273. if (combineBuffers && model.totalVertices_ > 65535)
  274. {
  275. bool allUnder65k = true;
  276. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  277. {
  278. if (GetNumValidFaces(model.meshes_[i]))
  279. {
  280. if (model.meshes_[i]->mNumVertices > 65535)
  281. allUnder65k = false;
  282. }
  283. }
  284. if (allUnder65k == true)
  285. combineBuffers = false;
  286. }
  287. SharedPtr<IndexBuffer> ib;
  288. SharedPtr<VertexBuffer> vb;
  289. Vector<SharedPtr<VertexBuffer> > vbVector;
  290. Vector<SharedPtr<IndexBuffer> > ibVector;
  291. unsigned startVertexOffset = 0;
  292. unsigned startIndexOffset = 0;
  293. unsigned destGeomIndex = 0;
  294. outModel->SetNumGeometries(numValidGeometries);
  295. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  296. {
  297. aiMesh* mesh = model.meshes_[i];
  298. unsigned elementMask = GetElementMask(mesh);
  299. unsigned validFaces = GetNumValidFaces(mesh);
  300. if (!validFaces)
  301. continue;
  302. bool largeIndices;
  303. if (combineBuffers)
  304. largeIndices = model.totalIndices_ > 65535;
  305. else
  306. largeIndices = mesh->mNumVertices > 65535;
  307. // Create new buffers if necessary
  308. if (!combineBuffers || vbVector.Empty())
  309. {
  310. vb = new VertexBuffer(context_);
  311. ib = new IndexBuffer(context_);
  312. vb->SetShadowed(true);
  313. ib->SetShadowed(true);
  314. if (combineBuffers)
  315. {
  316. ib->SetSize(model.totalIndices_, largeIndices);
  317. vb->SetSize(model.totalVertices_, elementMask);
  318. }
  319. else
  320. {
  321. ib->SetSize(validFaces * 3, largeIndices);
  322. vb->SetSize(mesh->mNumVertices, elementMask);
  323. }
  324. vbVector.Push(vb);
  325. ibVector.Push(ib);
  326. startVertexOffset = 0;
  327. startIndexOffset = 0;
  328. }
  329. // Get the world transform of the mesh for baking into the vertices
  330. Matrix3x4 vertexTransform;
  331. Matrix3 normalTransform;
  332. Vector3 pos, scale;
  333. Quaternion rot;
  334. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  335. vertexTransform = Matrix3x4(pos, rot, scale);
  336. normalTransform = rot.RotationMatrix();
  337. SharedPtr<Geometry> geom(new Geometry(context_));
  338. //PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  339. // String(validFaces * 3) + " indices");
  340. unsigned char* vertexData = vb->GetShadowData();
  341. unsigned char* indexData = ib->GetShadowData();
  342. assert(vertexData);
  343. assert(indexData);
  344. // Build the index data
  345. if (!largeIndices)
  346. {
  347. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  348. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  349. WriteShortIndices(dest, mesh, j, startVertexOffset);
  350. }
  351. else
  352. {
  353. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  354. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  355. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  356. }
  357. // Build the vertex data
  358. // If there are bones, get blend data
  359. Vector<PODVector<unsigned char> > blendIndices;
  360. Vector<PODVector<float> > blendWeights;
  361. PODVector<unsigned> boneMappings;
  362. if (model.bones_.Size())
  363. {
  364. if (!GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights, errorMessage_, maxBones_))
  365. return false;
  366. }
  367. float* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  368. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  369. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  370. // Calculate the geometry center
  371. Vector3 center = Vector3::ZERO;
  372. if (validFaces)
  373. {
  374. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  375. {
  376. if (mesh->mFaces[j].mNumIndices == 3)
  377. {
  378. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  379. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  380. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  381. }
  382. }
  383. center /= (float)validFaces * 3;
  384. }
  385. // Define the geometry
  386. geom->SetIndexBuffer(ib);
  387. geom->SetVertexBuffer(0, vb);
  388. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, validFaces * 3, true);
  389. outModel->SetNumGeometryLodLevels(destGeomIndex, 1);
  390. outModel->SetGeometry(destGeomIndex, 0, geom);
  391. outModel->SetGeometryCenter(destGeomIndex, center);
  392. outModel->SetGeometryName(destGeomIndex, FromAIString(model.meshNodes_[i]->mName));
  393. if (model.bones_.Size() > maxBones_)
  394. allBoneMappings.Push(boneMappings);
  395. startVertexOffset += mesh->mNumVertices;
  396. startIndexOffset += validFaces * 3;
  397. ++destGeomIndex;
  398. }
  399. // Define the model buffers and bounding box
  400. PODVector<unsigned> emptyMorphRange;
  401. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  402. outModel->SetIndexBuffers(ibVector);
  403. outModel->SetBoundingBox(box);
  404. // Build skeleton if necessary
  405. if (model.bones_.Size() && model.rootBone_)
  406. {
  407. //PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  408. // FromAIString(model.rootBone_->mName));
  409. Skeleton skeleton;
  410. Vector<Bone>& bones = skeleton.GetModifiableBones();
  411. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  412. {
  413. aiNode* boneNode = model.bones_[i];
  414. String boneName(FromAIString(boneNode->mName));
  415. Bone newBone;
  416. newBone.name_ = boneName;
  417. aiMatrix4x4 transform = boneNode->mTransformation;
  418. // Make the root bone transform relative to the model's root node, if it is not already
  419. if (boneNode == model.rootBone_)
  420. transform = GetDerivedTransform(boneNode, model.rootNode_);
  421. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  422. // Get offset information if exists
  423. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  424. newBone.radius_ = model.boneRadii_[i];
  425. newBone.boundingBox_ = model.boneHitboxes_[i];
  426. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  427. newBone.parentIndex_ = i;
  428. bones.Push(newBone);
  429. }
  430. // Set the bone hierarchy
  431. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  432. {
  433. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  434. for (unsigned j = 0; j < bones.Size(); ++j)
  435. {
  436. if (bones[j].name_ == parentName)
  437. {
  438. bones[i].parentIndex_ = j;
  439. break;
  440. }
  441. }
  442. }
  443. outModel->SetSkeleton(skeleton);
  444. if (model.bones_.Size() > maxBones_)
  445. outModel->SetGeometryBoneMappings(allBoneMappings);
  446. }
  447. String pathName, fileName, extension;
  448. SplitPath(sourceAssetFilename_, pathName, fileName, extension);
  449. MeshLightmapUVGen::Settings uvsettings;
  450. MeshLightmapUVGen uvgen(context_, outModel, fileName, uvsettings);
  451. if (!uvgen.Generate())
  452. {
  453. errorMessage_ = "Failed to generate lightmap UV " + model.outName_;
  454. return false;
  455. }
  456. File outFile(context_);
  457. if (!outFile.Open(model.outName_, FILE_WRITE))
  458. {
  459. errorMessage_ = "Could not open output file " + model.outName_;
  460. return false;
  461. }
  462. outModel->Save(outFile);
  463. // If exporting materials, also save material list for use by the editor
  464. if (!noMaterials_ && saveMaterialList_)
  465. {
  466. String materialListName = ReplaceExtension(model.outName_, ".txt");
  467. File listFile(context_);
  468. if (listFile.Open(materialListName, FILE_WRITE))
  469. {
  470. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  471. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  472. }
  473. else
  474. {
  475. PrintLine("Warning: could not write material list file " + materialListName);
  476. }
  477. }
  478. return true;
  479. }
  480. String OpenAssetImporter::GetMeshMaterialName(aiMesh* mesh)
  481. {
  482. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  483. aiString matNameStr;
  484. material->Get(AI_MATKEY_NAME, matNameStr);
  485. String matName = SanitateAssetName(FromAIString(matNameStr));
  486. if (matName.Trimmed().Empty())
  487. matName = GenerateMaterialName(material);
  488. return (useSubdirs_ ? "Materials/" : "") + matName + ".material";
  489. }
  490. String OpenAssetImporter::GenerateMaterialName(aiMaterial* material)
  491. {
  492. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  493. {
  494. if (scene_->mMaterials[i] == material)
  495. return inputName_ + "_Material" + String(i);
  496. }
  497. // Should not go here
  498. return String::EMPTY;
  499. }
  500. String OpenAssetImporter::GetMaterialTextureName(const String& nameIn)
  501. {
  502. // Detect assimp embedded texture
  503. if (nameIn.Length() && nameIn[0] == '*')
  504. return GenerateTextureName(ToInt(nameIn.Substring(1)));
  505. else
  506. return (useSubdirs_ ? "Textures/" : "") + nameIn;
  507. }
  508. String OpenAssetImporter::GenerateTextureName(unsigned texIndex)
  509. {
  510. if (texIndex < scene_->mNumTextures)
  511. {
  512. // If embedded texture contains encoded data, use the format hint for file extension. Else save RGBA8 data as PNG
  513. aiTexture* tex = scene_->mTextures[texIndex];
  514. if (!tex->mHeight)
  515. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + "." + tex->achFormatHint;
  516. else
  517. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + ".png";
  518. }
  519. // Should not go here
  520. return String::EMPTY;
  521. }
  522. void OpenAssetImporter::CollectSceneModels(OutScene& scene, aiNode* node)
  523. {
  524. Vector<Pair<aiNode*, aiMesh*> > meshes;
  525. GetMeshesUnderNode(scene_, meshes, node);
  526. if (meshes.Size())
  527. {
  528. OutModel model;
  529. model.rootNode_ = node;
  530. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  531. for (unsigned i = 0; i < meshes.Size(); ++i)
  532. {
  533. aiMesh* mesh = meshes[i].second_;
  534. unsigned meshIndex = GetMeshIndex(scene_, mesh);
  535. model.meshIndices_.Insert(meshIndex);
  536. model.meshes_.Push(mesh);
  537. model.meshNodes_.Push(meshes[i].first_);
  538. model.totalVertices_ += mesh->mNumVertices;
  539. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  540. }
  541. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  542. bool unique = true;
  543. if (checkUniqueModel_)
  544. {
  545. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  546. {
  547. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  548. {
  549. //PrintLine("Added node " + FromAIString(node->mName));
  550. scene.nodes_.Push(node);
  551. scene.nodeModelIndices_.Push(i);
  552. unique = false;
  553. break;
  554. }
  555. }
  556. }
  557. if (unique)
  558. {
  559. // PrintLine("Added model " + model.outName_);
  560. // PrintLine("Added node " + FromAIString(node->mName));
  561. CollectBones(model);
  562. BuildBoneCollisionInfo(model);
  563. if (!noAnimations_)
  564. {
  565. CollectAnimations(&model);
  566. BuildAndSaveAnimations(&model);
  567. }
  568. scene.models_.Push(model);
  569. scene.nodes_.Push(node);
  570. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  571. }
  572. }
  573. for (unsigned i = 0; i < node->mNumChildren; ++i)
  574. CollectSceneModels(scene, node->mChildren[i]);
  575. }
  576. bool OpenAssetImporter::CollectBones(OutModel& model, bool animationOnly)
  577. {
  578. HashSet<aiNode*> necessary;
  579. HashSet<aiNode*> rootNodes;
  580. if (animationOnly && !model.meshes_.Size())
  581. {
  582. aiNode* rootNode = 0;
  583. for (unsigned i = 0; i < scene_->mNumAnimations; ++i)
  584. {
  585. aiAnimation* anim = scene_->mAnimations[i];
  586. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  587. {
  588. aiNodeAnim* channel = anim->mChannels[j];
  589. String channelName = FromAIString(channel->mNodeName);
  590. aiNode* boneNode = GetNode(channelName, scene_->mRootNode, true);
  591. necessary.Insert(boneNode);
  592. rootNode = boneNode;
  593. for (;;)
  594. {
  595. boneNode = boneNode->mParent;
  596. if (!boneNode)// || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  597. break;
  598. rootNode = boneNode;
  599. necessary.Insert(boneNode);
  600. }
  601. if (rootNodes.Find(rootNode) == rootNodes.End())
  602. rootNodes.Insert(rootNode);
  603. }
  604. }
  605. }
  606. else
  607. {
  608. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  609. {
  610. aiMesh* mesh = model.meshes_[i];
  611. aiNode* meshNode = model.meshNodes_[i];
  612. aiNode* meshParentNode = meshNode->mParent;
  613. aiNode* rootNode = 0;
  614. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  615. {
  616. aiBone* bone = mesh->mBones[j];
  617. String boneName(FromAIString(bone->mName));
  618. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  619. if (!boneNode)
  620. {
  621. errorMessage_ = "Could not find scene node for bone " + boneName;
  622. return false;
  623. }
  624. necessary.Insert(boneNode);
  625. rootNode = boneNode;
  626. for (;;)
  627. {
  628. boneNode = boneNode->mParent;
  629. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  630. break;
  631. rootNode = boneNode;
  632. necessary.Insert(boneNode);
  633. }
  634. if (rootNodes.Find(rootNode) == rootNodes.End())
  635. rootNodes.Insert(rootNode);
  636. }
  637. }
  638. }
  639. // If we find multiple root nodes, try to remedy by using their parent instead
  640. if (rootNodes.Size() > 1)
  641. {
  642. aiNode* commonParent = (*rootNodes.Begin())->mParent;
  643. for (HashSet<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  644. {
  645. if (*i != commonParent)
  646. {
  647. if (!commonParent || (*i)->mParent != commonParent)
  648. {
  649. errorMessage_ = "Skeleton with multiple root nodes found, not supported";
  650. return false;
  651. }
  652. }
  653. }
  654. rootNodes.Clear();
  655. rootNodes.Insert(commonParent);
  656. necessary.Insert(commonParent);
  657. }
  658. if (rootNodes.Empty())
  659. return true;
  660. model.rootBone_ = *rootNodes.Begin();
  661. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  662. // Initialize the bone collision info
  663. model.boneRadii_.Resize(model.bones_.Size());
  664. model.boneHitboxes_.Resize(model.bones_.Size());
  665. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  666. {
  667. model.boneRadii_[i] = 0.0f;
  668. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  669. }
  670. return true;
  671. }
  672. void OpenAssetImporter::CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node)
  673. {
  674. bool includeBone = necessary.Find(node) != necessary.End();
  675. String boneName = FromAIString(node->mName);
  676. // Check include/exclude filters for non-skinned bones
  677. if (!includeBone && includeNonSkinningBones_)
  678. {
  679. // If no includes specified, include by default but check for excludes
  680. if (nonSkinningBoneIncludes_.Empty())
  681. includeBone = true;
  682. // Check against includes/excludes
  683. for (unsigned i = 0; i < nonSkinningBoneIncludes_.Size(); ++i)
  684. {
  685. if (boneName.Contains(nonSkinningBoneIncludes_[i], false))
  686. {
  687. includeBone = true;
  688. break;
  689. }
  690. }
  691. for (unsigned i = 0; i < nonSkinningBoneExcludes_.Size(); ++i)
  692. {
  693. if (boneName.Contains(nonSkinningBoneExcludes_[i], false))
  694. {
  695. includeBone = false;
  696. break;
  697. }
  698. }
  699. if (includeBone)
  700. {
  701. //PrintLine("Including non-skinning bone " + boneName);
  702. }
  703. }
  704. if (includeBone)
  705. dest.Push(node);
  706. for (unsigned i = 0; i < node->mNumChildren; ++i)
  707. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  708. }
  709. void OpenAssetImporter::CollectAnimations(OutModel* model)
  710. {
  711. const aiScene* scene = scene_;
  712. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  713. {
  714. aiAnimation* anim = scene->mAnimations[i];
  715. if (allAnimations_.Contains(anim))
  716. continue;
  717. if (model)
  718. {
  719. bool modelBoneFound = false;
  720. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  721. {
  722. aiNodeAnim* channel = anim->mChannels[j];
  723. String channelName = FromAIString(channel->mNodeName);
  724. if (GetBoneIndex(*model, channelName) != M_MAX_UNSIGNED)
  725. {
  726. modelBoneFound = true;
  727. break;
  728. }
  729. }
  730. if (modelBoneFound)
  731. {
  732. model->animations_.Push(anim);
  733. allAnimations_.Insert(anim);
  734. }
  735. }
  736. else
  737. {
  738. sceneAnimations_.Push(anim);
  739. allAnimations_.Insert(anim);
  740. }
  741. }
  742. /// \todo Vertex morphs are ignored for now
  743. }
  744. void OpenAssetImporter::ApplyFlag(int flag, bool active)
  745. {
  746. aiFlagsDefault_ &= ~flag;
  747. if (active)
  748. aiFlagsDefault_ |= flag;
  749. }
  750. void OpenAssetImporter::SetOveriddenFlags(VariantMap& aiFlagParameters)
  751. {
  752. VariantMap::ConstIterator itr = aiFlagParameters.Begin();
  753. while (itr != aiFlagParameters.End())
  754. {
  755. if (itr->first_ == "aiProcess_ConvertToLeftHanded")
  756. ApplyFlag(aiProcess_ConvertToLeftHanded, itr->second_.GetBool());
  757. else if (itr->first_ == "aiProcess_JoinIdenticalVertices")
  758. ApplyFlag(aiProcess_JoinIdenticalVertices, itr->second_.GetBool());
  759. else if (itr->first_ == "aiProcess_Triangulate")
  760. ApplyFlag(aiProcess_Triangulate, itr->second_.GetBool());
  761. else if (itr->first_ == "aiProcess_GenSmoothNormals")
  762. ApplyFlag(aiProcess_GenSmoothNormals, itr->second_.GetBool());
  763. else if (itr->first_ == "aiProcess_LimitBoneWeights")
  764. ApplyFlag(aiProcess_LimitBoneWeights, itr->second_.GetBool());
  765. else if (itr->first_ == "aiProcess_ImproveCacheLocality")
  766. ApplyFlag(aiProcess_ImproveCacheLocality, itr->second_.GetBool());
  767. else if (itr->first_ == "aiProcess_FixInfacingNormals")
  768. ApplyFlag(aiProcess_FixInfacingNormals, itr->second_.GetBool());
  769. else if (itr->first_ == "aiProcess_FindInvalidData")
  770. ApplyFlag(aiProcess_FindInvalidData, itr->second_.GetBool());
  771. else if (itr->first_ == "aiProcess_GenUVCoords")
  772. ApplyFlag(aiProcess_GenUVCoords, itr->second_.GetBool());
  773. else if (itr->first_ == "aiProcess_FindInstances")
  774. ApplyFlag(aiProcess_FindInstances, itr->second_.GetBool());
  775. else if (itr->first_ == "aiProcess_OptimizeMeshes")
  776. ApplyFlag(aiProcess_OptimizeMeshes, itr->second_.GetBool());
  777. else if (itr->first_ == "ImportMaterials")
  778. importMaterialsDefault_ = itr->second_.GetBool();
  779. else if (itr->first_ == "IncludeNonSkinningBones")
  780. includeNonSkinningBonesDefault_ = itr->second_.GetBool();
  781. else if (itr->first_ == "useVertexColors")
  782. useVertexColors_ = itr->second_.GetBool();
  783. itr++;
  784. }
  785. }
  786. void OpenAssetImporter::ApplyProjectImportConfig()
  787. {
  788. if (ImportConfig::IsLoaded())
  789. {
  790. VariantMap aiFlagParameters;
  791. ImportConfig::ApplyConfig(aiFlagParameters);
  792. SetOveriddenFlags(aiFlagParameters);
  793. }
  794. }
  795. void OpenAssetImporter::BuildBoneCollisionInfo(OutModel& model)
  796. {
  797. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  798. {
  799. aiMesh* mesh = model.meshes_[i];
  800. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  801. {
  802. aiBone* bone = mesh->mBones[j];
  803. String boneName = FromAIString(bone->mName);
  804. unsigned boneIndex = GetBoneIndex(model, boneName);
  805. if (boneIndex == M_MAX_UNSIGNED)
  806. continue;
  807. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  808. {
  809. float weight = bone->mWeights[k].mWeight;
  810. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  811. if (weight > 0.33f)
  812. {
  813. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  814. Vector3 vertex = ToVector3(vertexBoneSpace);
  815. float radius = vertex.Length();
  816. if (radius > model.boneRadii_[boneIndex])
  817. model.boneRadii_[boneIndex] = radius;
  818. model.boneHitboxes_[boneIndex].Merge(vertex);
  819. }
  820. }
  821. }
  822. }
  823. }
  824. bool OpenAssetImporter::BuildAndSaveAnimations(OutModel* model, const String &animNameOverride)
  825. {
  826. const PODVector<aiAnimation*>& animations = model ? model->animations_ : sceneAnimations_;
  827. for (unsigned i = 0; i < animations.Size(); ++i)
  828. {
  829. aiAnimation* anim = animations[i];
  830. float duration = (float)anim->mDuration;
  831. String animName = FromAIString(anim->mName);
  832. String animOutName;
  833. if (animName.Empty())
  834. animName = "Anim" + String(i + 1);
  835. if (model)
  836. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + SanitateAssetName(animName) + ".ani";
  837. else
  838. animOutName = outPath_ + SanitateAssetName(animName) + ".ani";
  839. if (animNameOverride.Length())
  840. {
  841. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + animNameOverride + ".ani";
  842. }
  843. float ticksPerSecond = (float)anim->mTicksPerSecond;
  844. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  845. if (ticksPerSecond < M_EPSILON)
  846. ticksPerSecond = defaultTicksPerSecond_;
  847. float tickConversion = 1.0f / ticksPerSecond;
  848. float startTime;
  849. if (startTime_ >= 0.0 && endTime_ >= 0.0)
  850. {
  851. startTime = startTime_;
  852. duration = endTime_ - startTime_;
  853. }
  854. else
  855. {
  856. // Find out the start time of animation from each channel's first keyframe for adjusting the keyframe times
  857. // to start from zero
  858. startTime = duration;
  859. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  860. {
  861. aiNodeAnim* channel = anim->mChannels[j];
  862. if (channel->mNumPositionKeys > 0)
  863. startTime = Min(startTime, (float)channel->mPositionKeys[0].mTime);
  864. if (channel->mNumRotationKeys > 0)
  865. startTime = Min(startTime, (float)channel->mRotationKeys[0].mTime);
  866. if (channel->mScalingKeys > 0)
  867. startTime = Min(startTime, (float)channel->mScalingKeys[0].mTime);
  868. }
  869. duration -= startTime;
  870. }
  871. SharedPtr<Animation> outAnim(new Animation(context_));
  872. outAnim->SetAnimationName(!animNameOverride.Length() ? animName : animNameOverride);
  873. outAnim->SetLength(duration * tickConversion);
  874. //PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  875. Vector<AnimationTrack> tracks;
  876. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  877. {
  878. aiNodeAnim* channel = anim->mChannels[j];
  879. String channelName = FromAIString(channel->mNodeName);
  880. aiNode* boneNode = 0;
  881. bool isRootBone = false;
  882. if (model)
  883. {
  884. unsigned boneIndex = GetBoneIndex(*model, channelName);
  885. if (boneIndex == M_MAX_UNSIGNED)
  886. {
  887. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  888. continue;
  889. }
  890. boneNode = model->bones_[boneIndex];
  891. isRootBone = boneIndex == 0;
  892. }
  893. else
  894. {
  895. boneNode = GetNode(channelName, scene_->mRootNode);
  896. if (!boneNode)
  897. {
  898. PrintLine("Warning: skipping animation track " + channelName + " whose scene node was not found");
  899. continue;
  900. }
  901. }
  902. // To export single frame animation, check if first key frame is identical to bone transformation
  903. aiVector3D bonePos, boneScale;
  904. aiQuaternion boneRot;
  905. boneNode->mTransformation.Decompose(boneScale, boneRot, bonePos);
  906. bool posEqual = true;
  907. bool scaleEqual = true;
  908. bool rotEqual = true;
  909. if (channel->mNumPositionKeys > 0 && !ToVector3(bonePos).Equals(ToVector3(channel->mPositionKeys[0].mValue)))
  910. posEqual = false;
  911. if (channel->mNumScalingKeys > 0 && !ToVector3(boneScale).Equals(ToVector3(channel->mScalingKeys[0].mValue)))
  912. scaleEqual = false;
  913. if (channel->mNumRotationKeys > 0 && !ToQuaternion(boneRot).Equals(ToQuaternion(channel->mRotationKeys[0].mValue)))
  914. rotEqual = false;
  915. AnimationTrack track;
  916. track.name_ = channelName;
  917. track.nameHash_ = channelName;
  918. // Check which channels are used
  919. track.channelMask_ = 0;
  920. if (channel->mNumPositionKeys > 1 || !posEqual)
  921. track.channelMask_ |= CHANNEL_POSITION;
  922. if (channel->mNumRotationKeys > 1 || !rotEqual)
  923. track.channelMask_ |= CHANNEL_ROTATION;
  924. if (channel->mNumScalingKeys > 1 || !scaleEqual)
  925. track.channelMask_ |= CHANNEL_SCALE;
  926. // Check for redundant identity scale in all keyframes and remove in that case
  927. if (track.channelMask_ & CHANNEL_SCALE)
  928. {
  929. bool redundantScale = true;
  930. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  931. {
  932. float SCALE_EPSILON = 0.000001f;
  933. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  934. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  935. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  936. {
  937. redundantScale = false;
  938. break;
  939. }
  940. }
  941. if (redundantScale)
  942. track.channelMask_ &= ~CHANNEL_SCALE;
  943. }
  944. if (!track.channelMask_)
  945. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  946. // Currently only same amount of keyframes is supported
  947. // Note: should also check the times of individual keyframes for match
  948. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  949. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  950. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  951. {
  952. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  953. continue;
  954. }
  955. unsigned keyFrames = channel->mNumPositionKeys;
  956. if (channel->mNumRotationKeys > keyFrames)
  957. keyFrames = channel->mNumRotationKeys;
  958. if (channel->mNumScalingKeys > keyFrames)
  959. keyFrames = channel->mNumScalingKeys;
  960. for (unsigned k = 0; k < keyFrames; ++k)
  961. {
  962. AnimationKeyFrame kf;
  963. kf.time_ = 0.0f;
  964. kf.position_ = Vector3::ZERO;
  965. kf.rotation_ = Quaternion::IDENTITY;
  966. kf.scale_ = Vector3::ONE;
  967. // Get time for the keyframe. Adjust with animation's start time
  968. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  969. kf.time_ = ((float)channel->mPositionKeys[k].mTime - startTime) * tickConversion;
  970. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  971. kf.time_ = ((float)channel->mRotationKeys[k].mTime - startTime) * tickConversion;
  972. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  973. kf.time_ = ((float)channel->mScalingKeys[k].mTime - startTime) * tickConversion;
  974. // Make sure time stays positive
  975. kf.time_ = Max(kf.time_, 0.0f);
  976. // Start with the bone's base transform
  977. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  978. aiVector3D pos, scale;
  979. aiQuaternion rot;
  980. boneTransform.Decompose(scale, rot, pos);
  981. // Then apply the active channels
  982. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  983. pos = channel->mPositionKeys[k].mValue;
  984. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  985. rot = channel->mRotationKeys[k].mValue;
  986. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  987. scale = channel->mScalingKeys[k].mValue;
  988. // If root bone, transform with the model root node transform
  989. if (model && isRootBone)
  990. {
  991. aiMatrix4x4 transMat, scaleMat, rotMat;
  992. aiMatrix4x4::Translation(pos, transMat);
  993. aiMatrix4x4::Scaling(scale, scaleMat);
  994. rotMat = aiMatrix4x4(rot.GetMatrix());
  995. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  996. tform = GetDerivedTransform(tform, boneNode, model->rootNode_);
  997. tform.Decompose(scale, rot, pos);
  998. }
  999. if (track.channelMask_ & CHANNEL_POSITION)
  1000. kf.position_ = ToVector3(pos);
  1001. if (track.channelMask_ & CHANNEL_ROTATION)
  1002. kf.rotation_ = ToQuaternion(rot);
  1003. if (track.channelMask_ & CHANNEL_SCALE)
  1004. kf.scale_ = ToVector3(scale);
  1005. track.keyFrames_.Push(kf);
  1006. }
  1007. tracks.Push(track);
  1008. }
  1009. outAnim->SetTracks(tracks);
  1010. File outFile(context_);
  1011. if (!outFile.Open(animOutName, FILE_WRITE))
  1012. {
  1013. errorMessage_ = "Could not open output file " + animOutName;
  1014. return false;
  1015. }
  1016. outAnim->Save(outFile);
  1017. AnimationInfo info;
  1018. info.name_ = SanitateAssetName(animName);
  1019. info.cacheFilename_ = animOutName;
  1020. animationInfos_.Push(info);
  1021. }
  1022. return true;
  1023. }
  1024. // Materials
  1025. void OpenAssetImporter::ExportMaterials(HashSet<String>& usedTextures)
  1026. {
  1027. if (importMaterials_ )
  1028. {
  1029. if (useSubdirs_)
  1030. {
  1031. context_->GetSubsystem<FileSystem>()->CreateDir(sourceAssetPath_ + "Materials");
  1032. }
  1033. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1034. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  1035. }
  1036. }
  1037. bool OpenAssetImporter::BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures)
  1038. {
  1039. aiString matNameStr;
  1040. material->Get(AI_MATKEY_NAME, matNameStr);
  1041. String matName = SanitateAssetName(FromAIString(matNameStr));
  1042. if (matName.Trimmed().Empty())
  1043. matName = GenerateMaterialName(material);
  1044. // Do not actually create a material instance, but instead craft an xml file manually
  1045. XMLFile outMaterial(context_);
  1046. XMLElement materialElem = outMaterial.CreateRoot("material");
  1047. String diffuseTexName;
  1048. String normalTexName;
  1049. String specularTexName;
  1050. String lightmapTexName;
  1051. String emissiveTexName;
  1052. Color diffuseColor = Color::WHITE;
  1053. Color specularColor;
  1054. Color emissiveColor = Color::BLACK;
  1055. bool hasAlpha = false;
  1056. bool twoSided = false;
  1057. float specPower = 1.0f;
  1058. aiString stringVal;
  1059. float floatVal;
  1060. int intVal;
  1061. aiColor3D colorVal;
  1062. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1063. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1064. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1065. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1066. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), stringVal) == AI_SUCCESS)
  1067. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1068. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), stringVal) == AI_SUCCESS)
  1069. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1070. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), stringVal) == AI_SUCCESS)
  1071. emissiveTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1072. diffuseTexName.Replace(".tif", ".png");
  1073. if (!noMaterialDiffuseColor_)
  1074. {
  1075. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1076. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1077. }
  1078. if (material->Get(AI_MATKEY_COLOR_SPECULAR, colorVal) == AI_SUCCESS)
  1079. specularColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1080. if (!emissiveAO_)
  1081. {
  1082. // if (material->Get(AI_MATKEY_COLOR_EMISSIVE, colorVal) == AI_SUCCESS)
  1083. // emissiveColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1084. }
  1085. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1086. {
  1087. if (floatVal < 1.0f)
  1088. hasAlpha = true;
  1089. diffuseColor.a_ = floatVal;
  1090. }
  1091. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1092. specPower = floatVal;
  1093. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1094. twoSided = (intVal != 0);
  1095. String techniqueName = "Techniques/NoTexture";
  1096. if (!diffuseTexName.Empty())
  1097. {
  1098. techniqueName = "Techniques/Diff";
  1099. if (!normalTexName.Empty())
  1100. techniqueName += "Normal";
  1101. if (!specularTexName.Empty())
  1102. techniqueName += "Spec";
  1103. // For now lightmap does not coexist with normal & specular
  1104. if (normalTexName.Empty() && specularTexName.Empty() && !lightmapTexName.Empty())
  1105. techniqueName += "LightMap";
  1106. if (lightmapTexName.Empty() && !emissiveTexName.Empty())
  1107. techniqueName += emissiveAO_ ? "AO" : "Emissive";
  1108. }
  1109. if (hasAlpha)
  1110. techniqueName += "Alpha";
  1111. // See if any mesh that uses this material has vertex colors
  1112. // and set the technique accordingly, if enabled
  1113. for (unsigned i = 0; i < scene_->mNumMeshes && useVertexColors_; i++)
  1114. {
  1115. aiMesh* mesh = scene_->mMeshes[i];
  1116. aiMaterial* mesh_material = scene_->mMaterials[mesh->mMaterialIndex];
  1117. aiString meshMatNameStr;
  1118. mesh_material->Get(AI_MATKEY_NAME, meshMatNameStr);
  1119. if(mesh->GetNumColorChannels() > 0)
  1120. {
  1121. if(matNameStr == meshMatNameStr)
  1122. {
  1123. techniqueName += "VCol";
  1124. break;
  1125. }
  1126. }
  1127. }
  1128. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1129. techniqueElem.SetString("name", techniqueName + ".xml");
  1130. if (!diffuseTexName.Empty())
  1131. {
  1132. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1133. diffuseElem.SetString("unit", "diffuse");
  1134. diffuseElem.SetString("name", GetMaterialTextureName(diffuseTexName));
  1135. usedTextures.Insert(diffuseTexName);
  1136. }
  1137. if (!normalTexName.Empty())
  1138. {
  1139. XMLElement normalElem = materialElem.CreateChild("texture");
  1140. normalElem.SetString("unit", "normal");
  1141. normalElem.SetString("name", GetMaterialTextureName(normalTexName));
  1142. usedTextures.Insert(normalTexName);
  1143. }
  1144. if (!specularTexName.Empty())
  1145. {
  1146. XMLElement specularElem = materialElem.CreateChild("texture");
  1147. specularElem.SetString("unit", "specular");
  1148. specularElem.SetString("name", GetMaterialTextureName(specularTexName));
  1149. usedTextures.Insert(specularTexName);
  1150. }
  1151. if (!lightmapTexName.Empty())
  1152. {
  1153. XMLElement lightmapElem = materialElem.CreateChild("texture");
  1154. lightmapElem.SetString("unit", "emissive");
  1155. lightmapElem.SetString("name", GetMaterialTextureName(lightmapTexName));
  1156. usedTextures.Insert(lightmapTexName);
  1157. }
  1158. if (!emissiveTexName.Empty())
  1159. {
  1160. XMLElement emissiveElem = materialElem.CreateChild("texture");
  1161. emissiveElem.SetString("unit", "emissive");
  1162. emissiveElem.SetString("name", GetMaterialTextureName(emissiveTexName));
  1163. usedTextures.Insert(emissiveTexName);
  1164. }
  1165. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1166. diffuseColorElem.SetString("name", "MatDiffColor");
  1167. diffuseColorElem.SetColor("value", diffuseColor);
  1168. XMLElement specularElem = materialElem.CreateChild("parameter");
  1169. specularElem.SetString("name", "MatSpecColor");
  1170. specularElem.SetVector4("value", Vector4(specularColor.r_, specularColor.g_, specularColor.b_, specPower));
  1171. XMLElement emissiveColorElem = materialElem.CreateChild("parameter");
  1172. emissiveColorElem.SetString("name", "MatEmissiveColor");
  1173. emissiveColorElem.SetColor("value", emissiveColor);
  1174. if (twoSided)
  1175. {
  1176. XMLElement cullElem = materialElem.CreateChild("cull");
  1177. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1178. cullElem.SetString("value", "none");
  1179. shadowCullElem.SetString("value", "none");
  1180. }
  1181. FileSystem* fileSystem = context_->GetSubsystem<FileSystem>();
  1182. String outFileName = sourceAssetPath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".material";
  1183. if (noOverwriteMaterial_ && fileSystem->FileExists(outFileName))
  1184. {
  1185. PrintLine("Skipping save of existing material " + matName);
  1186. return true;
  1187. }
  1188. PrintLine("Writing material " + matName);
  1189. File outFile(context_);
  1190. if (!outFile.Open(outFileName, FILE_WRITE))
  1191. {
  1192. errorMessage_ = "Could not open output file " + outFileName;
  1193. return false;
  1194. }
  1195. outMaterial.Save(outFile);
  1196. return true;
  1197. }
  1198. void OpenAssetImporter::DumpNodes(aiNode* rootNode, unsigned level)
  1199. {
  1200. if (!rootNode)
  1201. return;
  1202. String indent(' ', level * 2);
  1203. Vector3 pos, scale;
  1204. Quaternion rot;
  1205. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  1206. GetPosRotScale(transform, pos, rot, scale);
  1207. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  1208. if (rootNode->mNumMeshes == 1)
  1209. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  1210. if (rootNode->mNumMeshes > 1)
  1211. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  1212. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  1213. DumpNodes(rootNode->mChildren[i], level + 1);
  1214. }
  1215. }