OpenAssetImporter.cpp 49 KB

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