OpenAssetImporter.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  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 (!GenerateLightmapUV(outModel))
  464. {
  465. errorMessage_ = "Failed to generate lightmap UV " + model.outName_;
  466. return false;
  467. }
  468. File outFile(context_);
  469. if (!outFile.Open(model.outName_, FILE_WRITE))
  470. {
  471. errorMessage_ = "Could not open output file " + model.outName_;
  472. return false;
  473. }
  474. outModel->Save(outFile);
  475. // If exporting materials, also save material list for use by the editor
  476. if (!noMaterials_ && saveMaterialList_)
  477. {
  478. String materialListName = ReplaceExtension(model.outName_, ".txt");
  479. File listFile(context_);
  480. if (listFile.Open(materialListName, FILE_WRITE))
  481. {
  482. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  483. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  484. }
  485. else
  486. {
  487. PrintLine("Warning: could not write material list file " + materialListName);
  488. }
  489. }
  490. return true;
  491. }
  492. String OpenAssetImporter::GetMeshMaterialName(aiMesh* mesh)
  493. {
  494. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  495. aiString matNameStr;
  496. material->Get(AI_MATKEY_NAME, matNameStr);
  497. String matName = SanitateAssetName(FromAIString(matNameStr));
  498. if (matName.Trimmed().Empty())
  499. matName = GenerateMaterialName(material);
  500. return (useSubdirs_ ? "Materials/" : "") + matName + ".material";
  501. }
  502. String OpenAssetImporter::GenerateMaterialName(aiMaterial* material)
  503. {
  504. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  505. {
  506. if (scene_->mMaterials[i] == material)
  507. return inputName_ + "_Material" + String(i);
  508. }
  509. // Should not go here
  510. return String::EMPTY;
  511. }
  512. String OpenAssetImporter::GetMaterialTextureName(const String& nameIn)
  513. {
  514. // Detect assimp embedded texture
  515. if (nameIn.Length() && nameIn[0] == '*')
  516. return GenerateTextureName(ToInt(nameIn.Substring(1)));
  517. else
  518. return (useSubdirs_ ? "Textures/" : "") + nameIn;
  519. }
  520. String OpenAssetImporter::GenerateTextureName(unsigned texIndex)
  521. {
  522. if (texIndex < scene_->mNumTextures)
  523. {
  524. // If embedded texture contains encoded data, use the format hint for file extension. Else save RGBA8 data as PNG
  525. aiTexture* tex = scene_->mTextures[texIndex];
  526. if (!tex->mHeight)
  527. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + "." + tex->achFormatHint;
  528. else
  529. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + ".png";
  530. }
  531. // Should not go here
  532. return String::EMPTY;
  533. }
  534. void OpenAssetImporter::CollectSceneModels(OutScene& scene, aiNode* node)
  535. {
  536. Vector<Pair<aiNode*, aiMesh*> > meshes;
  537. GetMeshesUnderNode(scene_, meshes, node);
  538. if (meshes.Size())
  539. {
  540. OutModel model;
  541. model.rootNode_ = node;
  542. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  543. for (unsigned i = 0; i < meshes.Size(); ++i)
  544. {
  545. aiMesh* mesh = meshes[i].second_;
  546. unsigned meshIndex = GetMeshIndex(scene_, mesh);
  547. model.meshIndices_.Insert(meshIndex);
  548. model.meshes_.Push(mesh);
  549. model.meshNodes_.Push(meshes[i].first_);
  550. model.totalVertices_ += mesh->mNumVertices;
  551. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  552. }
  553. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  554. bool unique = true;
  555. if (checkUniqueModel_)
  556. {
  557. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  558. {
  559. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  560. {
  561. //PrintLine("Added node " + FromAIString(node->mName));
  562. scene.nodes_.Push(node);
  563. scene.nodeModelIndices_.Push(i);
  564. unique = false;
  565. break;
  566. }
  567. }
  568. }
  569. if (unique)
  570. {
  571. // PrintLine("Added model " + model.outName_);
  572. // PrintLine("Added node " + FromAIString(node->mName));
  573. CollectBones(model);
  574. BuildBoneCollisionInfo(model);
  575. if (!noAnimations_)
  576. {
  577. CollectAnimations(&model);
  578. BuildAndSaveAnimations(&model);
  579. }
  580. scene.models_.Push(model);
  581. scene.nodes_.Push(node);
  582. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  583. }
  584. }
  585. for (unsigned i = 0; i < node->mNumChildren; ++i)
  586. CollectSceneModels(scene, node->mChildren[i]);
  587. }
  588. bool OpenAssetImporter::CollectBones(OutModel& model, bool animationOnly)
  589. {
  590. HashSet<aiNode*> necessary;
  591. HashSet<aiNode*> rootNodes;
  592. if (animationOnly && !model.meshes_.Size())
  593. {
  594. aiNode* rootNode = 0;
  595. for (unsigned i = 0; i < scene_->mNumAnimations; ++i)
  596. {
  597. aiAnimation* anim = scene_->mAnimations[i];
  598. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  599. {
  600. aiNodeAnim* channel = anim->mChannels[j];
  601. String channelName = FromAIString(channel->mNodeName);
  602. aiNode* boneNode = GetNode(channelName, scene_->mRootNode, true);
  603. necessary.Insert(boneNode);
  604. rootNode = boneNode;
  605. for (;;)
  606. {
  607. boneNode = boneNode->mParent;
  608. if (!boneNode)// || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  609. break;
  610. rootNode = boneNode;
  611. necessary.Insert(boneNode);
  612. }
  613. if (rootNodes.Find(rootNode) == rootNodes.End())
  614. rootNodes.Insert(rootNode);
  615. }
  616. }
  617. }
  618. else
  619. {
  620. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  621. {
  622. aiMesh* mesh = model.meshes_[i];
  623. aiNode* meshNode = model.meshNodes_[i];
  624. aiNode* meshParentNode = meshNode->mParent;
  625. aiNode* rootNode = 0;
  626. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  627. {
  628. aiBone* bone = mesh->mBones[j];
  629. String boneName(FromAIString(bone->mName));
  630. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  631. if (!boneNode)
  632. {
  633. errorMessage_ = "Could not find scene node for bone " + boneName;
  634. return false;
  635. }
  636. necessary.Insert(boneNode);
  637. rootNode = boneNode;
  638. for (;;)
  639. {
  640. boneNode = boneNode->mParent;
  641. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  642. break;
  643. rootNode = boneNode;
  644. necessary.Insert(boneNode);
  645. }
  646. if (rootNodes.Find(rootNode) == rootNodes.End())
  647. rootNodes.Insert(rootNode);
  648. }
  649. }
  650. }
  651. // If we find multiple root nodes, try to remedy by using their parent instead
  652. if (rootNodes.Size() > 1)
  653. {
  654. aiNode* commonParent = (*rootNodes.Begin())->mParent;
  655. for (HashSet<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  656. {
  657. if (*i != commonParent)
  658. {
  659. if (!commonParent || (*i)->mParent != commonParent)
  660. {
  661. errorMessage_ = "Skeleton with multiple root nodes found, not supported";
  662. return false;
  663. }
  664. }
  665. }
  666. rootNodes.Clear();
  667. rootNodes.Insert(commonParent);
  668. necessary.Insert(commonParent);
  669. }
  670. if (rootNodes.Empty())
  671. return true;
  672. model.rootBone_ = *rootNodes.Begin();
  673. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  674. // Initialize the bone collision info
  675. model.boneRadii_.Resize(model.bones_.Size());
  676. model.boneHitboxes_.Resize(model.bones_.Size());
  677. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  678. {
  679. model.boneRadii_[i] = 0.0f;
  680. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  681. }
  682. return true;
  683. }
  684. void OpenAssetImporter::CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node)
  685. {
  686. bool includeBone = necessary.Find(node) != necessary.End();
  687. String boneName = FromAIString(node->mName);
  688. // Check include/exclude filters for non-skinned bones
  689. if (!includeBone && includeNonSkinningBones_)
  690. {
  691. // If no includes specified, include by default but check for excludes
  692. if (nonSkinningBoneIncludes_.Empty())
  693. includeBone = true;
  694. // Check against includes/excludes
  695. for (unsigned i = 0; i < nonSkinningBoneIncludes_.Size(); ++i)
  696. {
  697. if (boneName.Contains(nonSkinningBoneIncludes_[i], false))
  698. {
  699. includeBone = true;
  700. break;
  701. }
  702. }
  703. for (unsigned i = 0; i < nonSkinningBoneExcludes_.Size(); ++i)
  704. {
  705. if (boneName.Contains(nonSkinningBoneExcludes_[i], false))
  706. {
  707. includeBone = false;
  708. break;
  709. }
  710. }
  711. if (includeBone)
  712. {
  713. //PrintLine("Including non-skinning bone " + boneName);
  714. }
  715. }
  716. if (includeBone)
  717. dest.Push(node);
  718. for (unsigned i = 0; i < node->mNumChildren; ++i)
  719. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  720. }
  721. void OpenAssetImporter::CollectAnimations(OutModel* model)
  722. {
  723. const aiScene* scene = scene_;
  724. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  725. {
  726. aiAnimation* anim = scene->mAnimations[i];
  727. if (allAnimations_.Contains(anim))
  728. continue;
  729. if (model)
  730. {
  731. bool modelBoneFound = false;
  732. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  733. {
  734. aiNodeAnim* channel = anim->mChannels[j];
  735. String channelName = FromAIString(channel->mNodeName);
  736. if (GetBoneIndex(*model, channelName) != M_MAX_UNSIGNED)
  737. {
  738. modelBoneFound = true;
  739. break;
  740. }
  741. }
  742. if (modelBoneFound)
  743. {
  744. model->animations_.Push(anim);
  745. allAnimations_.Insert(anim);
  746. }
  747. }
  748. else
  749. {
  750. sceneAnimations_.Push(anim);
  751. allAnimations_.Insert(anim);
  752. }
  753. }
  754. /// \todo Vertex morphs are ignored for now
  755. }
  756. void OpenAssetImporter::ApplyFlag(int flag, bool active)
  757. {
  758. aiFlagsDefault_ &= ~flag;
  759. if (active)
  760. aiFlagsDefault_ |= flag;
  761. }
  762. void OpenAssetImporter::SetOveriddenFlags(VariantMap& aiFlagParameters)
  763. {
  764. VariantMap::ConstIterator itr = aiFlagParameters.Begin();
  765. while (itr != aiFlagParameters.End())
  766. {
  767. if (itr->first_ == "aiProcess_ConvertToLeftHanded")
  768. ApplyFlag(aiProcess_ConvertToLeftHanded, itr->second_.GetBool());
  769. else if (itr->first_ == "aiProcess_JoinIdenticalVertices")
  770. ApplyFlag(aiProcess_JoinIdenticalVertices, itr->second_.GetBool());
  771. else if (itr->first_ == "aiProcess_Triangulate")
  772. ApplyFlag(aiProcess_Triangulate, itr->second_.GetBool());
  773. else if (itr->first_ == "aiProcess_GenSmoothNormals")
  774. ApplyFlag(aiProcess_GenSmoothNormals, itr->second_.GetBool());
  775. else if (itr->first_ == "aiProcess_LimitBoneWeights")
  776. ApplyFlag(aiProcess_LimitBoneWeights, itr->second_.GetBool());
  777. else if (itr->first_ == "aiProcess_ImproveCacheLocality")
  778. ApplyFlag(aiProcess_ImproveCacheLocality, itr->second_.GetBool());
  779. else if (itr->first_ == "aiProcess_FixInfacingNormals")
  780. ApplyFlag(aiProcess_FixInfacingNormals, itr->second_.GetBool());
  781. else if (itr->first_ == "aiProcess_FindInvalidData")
  782. ApplyFlag(aiProcess_FindInvalidData, itr->second_.GetBool());
  783. else if (itr->first_ == "aiProcess_GenUVCoords")
  784. ApplyFlag(aiProcess_GenUVCoords, itr->second_.GetBool());
  785. else if (itr->first_ == "aiProcess_FindInstances")
  786. ApplyFlag(aiProcess_FindInstances, itr->second_.GetBool());
  787. else if (itr->first_ == "aiProcess_OptimizeMeshes")
  788. ApplyFlag(aiProcess_OptimizeMeshes, itr->second_.GetBool());
  789. else if (itr->first_ == "ImportMaterials")
  790. importMaterialsDefault_ = itr->second_.GetBool();
  791. else if (itr->first_ == "IncludeNonSkinningBones")
  792. includeNonSkinningBonesDefault_ = itr->second_.GetBool();
  793. else if (itr->first_ == "useVertexColors")
  794. useVertexColors_ = itr->second_.GetBool();
  795. itr++;
  796. }
  797. }
  798. void OpenAssetImporter::ApplyProjectImportConfig()
  799. {
  800. if (ImportConfig::IsLoaded())
  801. {
  802. VariantMap aiFlagParameters;
  803. ImportConfig::ApplyConfig(aiFlagParameters);
  804. SetOveriddenFlags(aiFlagParameters);
  805. }
  806. }
  807. void OpenAssetImporter::BuildBoneCollisionInfo(OutModel& model)
  808. {
  809. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  810. {
  811. aiMesh* mesh = model.meshes_[i];
  812. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  813. {
  814. aiBone* bone = mesh->mBones[j];
  815. String boneName = FromAIString(bone->mName);
  816. unsigned boneIndex = GetBoneIndex(model, boneName);
  817. if (boneIndex == M_MAX_UNSIGNED)
  818. continue;
  819. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  820. {
  821. float weight = bone->mWeights[k].mWeight;
  822. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  823. if (weight > 0.33f)
  824. {
  825. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  826. Vector3 vertex = ToVector3(vertexBoneSpace);
  827. float radius = vertex.Length();
  828. if (radius > model.boneRadii_[boneIndex])
  829. model.boneRadii_[boneIndex] = radius;
  830. model.boneHitboxes_[boneIndex].Merge(vertex);
  831. }
  832. }
  833. }
  834. }
  835. }
  836. bool OpenAssetImporter::BuildAndSaveAnimations(OutModel* model, const String &animNameOverride)
  837. {
  838. const PODVector<aiAnimation*>& animations = model ? model->animations_ : sceneAnimations_;
  839. for (unsigned i = 0; i < animations.Size(); ++i)
  840. {
  841. aiAnimation* anim = animations[i];
  842. float duration = (float)anim->mDuration;
  843. String animName = FromAIString(anim->mName);
  844. String animOutName;
  845. if (animName.Empty())
  846. animName = "Anim" + String(i + 1);
  847. if (model)
  848. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + SanitateAssetName(animName) + ".ani";
  849. else
  850. animOutName = outPath_ + SanitateAssetName(animName) + ".ani";
  851. if (animNameOverride.Length())
  852. {
  853. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + animNameOverride + ".ani";
  854. }
  855. float ticksPerSecond = (float)anim->mTicksPerSecond;
  856. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  857. if (ticksPerSecond < M_EPSILON)
  858. ticksPerSecond = defaultTicksPerSecond_;
  859. float tickConversion = 1.0f / ticksPerSecond;
  860. float startTime;
  861. if (startTime_ >= 0.0 && endTime_ >= 0.0)
  862. {
  863. startTime = startTime_;
  864. duration = endTime_ - startTime_;
  865. }
  866. else
  867. {
  868. // Find out the start time of animation from each channel's first keyframe for adjusting the keyframe times
  869. // to start from zero
  870. startTime = duration;
  871. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  872. {
  873. aiNodeAnim* channel = anim->mChannels[j];
  874. if (channel->mNumPositionKeys > 0)
  875. startTime = Min(startTime, (float)channel->mPositionKeys[0].mTime);
  876. if (channel->mNumRotationKeys > 0)
  877. startTime = Min(startTime, (float)channel->mRotationKeys[0].mTime);
  878. if (channel->mScalingKeys > 0)
  879. startTime = Min(startTime, (float)channel->mScalingKeys[0].mTime);
  880. }
  881. duration -= startTime;
  882. }
  883. SharedPtr<Animation> outAnim(new Animation(context_));
  884. outAnim->SetAnimationName(!animNameOverride.Length() ? animName : animNameOverride);
  885. outAnim->SetLength(duration * tickConversion);
  886. //PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  887. Vector<AnimationTrack> tracks;
  888. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  889. {
  890. aiNodeAnim* channel = anim->mChannels[j];
  891. String channelName = FromAIString(channel->mNodeName);
  892. aiNode* boneNode = 0;
  893. bool isRootBone = false;
  894. if (model)
  895. {
  896. unsigned boneIndex = GetBoneIndex(*model, channelName);
  897. if (boneIndex == M_MAX_UNSIGNED)
  898. {
  899. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  900. continue;
  901. }
  902. boneNode = model->bones_[boneIndex];
  903. isRootBone = boneIndex == 0;
  904. }
  905. else
  906. {
  907. boneNode = GetNode(channelName, scene_->mRootNode);
  908. if (!boneNode)
  909. {
  910. PrintLine("Warning: skipping animation track " + channelName + " whose scene node was not found");
  911. continue;
  912. }
  913. }
  914. // To export single frame animation, check if first key frame is identical to bone transformation
  915. aiVector3D bonePos, boneScale;
  916. aiQuaternion boneRot;
  917. boneNode->mTransformation.Decompose(boneScale, boneRot, bonePos);
  918. bool posEqual = true;
  919. bool scaleEqual = true;
  920. bool rotEqual = true;
  921. if (channel->mNumPositionKeys > 0 && !ToVector3(bonePos).Equals(ToVector3(channel->mPositionKeys[0].mValue)))
  922. posEqual = false;
  923. if (channel->mNumScalingKeys > 0 && !ToVector3(boneScale).Equals(ToVector3(channel->mScalingKeys[0].mValue)))
  924. scaleEqual = false;
  925. if (channel->mNumRotationKeys > 0 && !ToQuaternion(boneRot).Equals(ToQuaternion(channel->mRotationKeys[0].mValue)))
  926. rotEqual = false;
  927. AnimationTrack track;
  928. track.name_ = channelName;
  929. track.nameHash_ = channelName;
  930. // Check which channels are used
  931. track.channelMask_ = 0;
  932. if (channel->mNumPositionKeys > 1 || !posEqual)
  933. track.channelMask_ |= CHANNEL_POSITION;
  934. if (channel->mNumRotationKeys > 1 || !rotEqual)
  935. track.channelMask_ |= CHANNEL_ROTATION;
  936. if (channel->mNumScalingKeys > 1 || !scaleEqual)
  937. track.channelMask_ |= CHANNEL_SCALE;
  938. // Check for redundant identity scale in all keyframes and remove in that case
  939. if (track.channelMask_ & CHANNEL_SCALE)
  940. {
  941. bool redundantScale = true;
  942. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  943. {
  944. float SCALE_EPSILON = 0.000001f;
  945. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  946. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  947. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  948. {
  949. redundantScale = false;
  950. break;
  951. }
  952. }
  953. if (redundantScale)
  954. track.channelMask_ &= ~CHANNEL_SCALE;
  955. }
  956. if (!track.channelMask_)
  957. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  958. // Currently only same amount of keyframes is supported
  959. // Note: should also check the times of individual keyframes for match
  960. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  961. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  962. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  963. {
  964. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  965. continue;
  966. }
  967. unsigned keyFrames = channel->mNumPositionKeys;
  968. if (channel->mNumRotationKeys > keyFrames)
  969. keyFrames = channel->mNumRotationKeys;
  970. if (channel->mNumScalingKeys > keyFrames)
  971. keyFrames = channel->mNumScalingKeys;
  972. for (unsigned k = 0; k < keyFrames; ++k)
  973. {
  974. AnimationKeyFrame kf;
  975. kf.time_ = 0.0f;
  976. kf.position_ = Vector3::ZERO;
  977. kf.rotation_ = Quaternion::IDENTITY;
  978. kf.scale_ = Vector3::ONE;
  979. // Get time for the keyframe. Adjust with animation's start time
  980. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  981. kf.time_ = ((float)channel->mPositionKeys[k].mTime - startTime) * tickConversion;
  982. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  983. kf.time_ = ((float)channel->mRotationKeys[k].mTime - startTime) * tickConversion;
  984. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  985. kf.time_ = ((float)channel->mScalingKeys[k].mTime - startTime) * tickConversion;
  986. // Make sure time stays positive
  987. kf.time_ = Max(kf.time_, 0.0f);
  988. // Start with the bone's base transform
  989. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  990. aiVector3D pos, scale;
  991. aiQuaternion rot;
  992. boneTransform.Decompose(scale, rot, pos);
  993. // Then apply the active channels
  994. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  995. pos = channel->mPositionKeys[k].mValue;
  996. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  997. rot = channel->mRotationKeys[k].mValue;
  998. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  999. scale = channel->mScalingKeys[k].mValue;
  1000. // If root bone, transform with the model root node transform
  1001. if (model && isRootBone)
  1002. {
  1003. aiMatrix4x4 transMat, scaleMat, rotMat;
  1004. aiMatrix4x4::Translation(pos, transMat);
  1005. aiMatrix4x4::Scaling(scale, scaleMat);
  1006. rotMat = aiMatrix4x4(rot.GetMatrix());
  1007. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  1008. tform = GetDerivedTransform(tform, boneNode, model->rootNode_);
  1009. tform.Decompose(scale, rot, pos);
  1010. }
  1011. if (track.channelMask_ & CHANNEL_POSITION)
  1012. kf.position_ = ToVector3(pos);
  1013. if (track.channelMask_ & CHANNEL_ROTATION)
  1014. kf.rotation_ = ToQuaternion(rot);
  1015. if (track.channelMask_ & CHANNEL_SCALE)
  1016. kf.scale_ = ToVector3(scale);
  1017. track.keyFrames_.Push(kf);
  1018. }
  1019. tracks.Push(track);
  1020. }
  1021. outAnim->SetTracks(tracks);
  1022. File outFile(context_);
  1023. if (!outFile.Open(animOutName, FILE_WRITE))
  1024. {
  1025. errorMessage_ = "Could not open output file " + animOutName;
  1026. return false;
  1027. }
  1028. outAnim->Save(outFile);
  1029. AnimationInfo info;
  1030. info.name_ = SanitateAssetName(animName);
  1031. info.cacheFilename_ = animOutName;
  1032. animationInfos_.Push(info);
  1033. }
  1034. return true;
  1035. }
  1036. // Materials
  1037. void OpenAssetImporter::ExportMaterials(HashSet<String>& usedTextures)
  1038. {
  1039. if (importMaterials_ )
  1040. {
  1041. if (useSubdirs_)
  1042. {
  1043. context_->GetSubsystem<FileSystem>()->CreateDir(sourceAssetPath_ + "Materials");
  1044. }
  1045. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1046. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  1047. }
  1048. }
  1049. bool OpenAssetImporter::BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures)
  1050. {
  1051. aiString matNameStr;
  1052. material->Get(AI_MATKEY_NAME, matNameStr);
  1053. String matName = SanitateAssetName(FromAIString(matNameStr));
  1054. if (matName.Trimmed().Empty())
  1055. matName = GenerateMaterialName(material);
  1056. // Do not actually create a material instance, but instead craft an xml file manually
  1057. XMLFile outMaterial(context_);
  1058. XMLElement materialElem = outMaterial.CreateRoot("material");
  1059. String diffuseTexName;
  1060. String normalTexName;
  1061. String specularTexName;
  1062. String lightmapTexName;
  1063. String emissiveTexName;
  1064. Color diffuseColor = Color::WHITE;
  1065. Color specularColor;
  1066. Color emissiveColor = Color::BLACK;
  1067. bool hasAlpha = false;
  1068. bool twoSided = false;
  1069. float specPower = 1.0f;
  1070. aiString stringVal;
  1071. float floatVal;
  1072. int intVal;
  1073. aiColor3D colorVal;
  1074. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1075. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1076. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1077. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1078. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), stringVal) == AI_SUCCESS)
  1079. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1080. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), stringVal) == AI_SUCCESS)
  1081. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1082. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), stringVal) == AI_SUCCESS)
  1083. emissiveTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1084. diffuseTexName.Replace(".tif", ".png");
  1085. if (!noMaterialDiffuseColor_)
  1086. {
  1087. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1088. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1089. }
  1090. if (material->Get(AI_MATKEY_COLOR_SPECULAR, colorVal) == AI_SUCCESS)
  1091. specularColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1092. if (!emissiveAO_)
  1093. {
  1094. // if (material->Get(AI_MATKEY_COLOR_EMISSIVE, colorVal) == AI_SUCCESS)
  1095. // emissiveColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1096. }
  1097. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1098. {
  1099. if (floatVal < 1.0f)
  1100. hasAlpha = true;
  1101. diffuseColor.a_ = floatVal;
  1102. }
  1103. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1104. specPower = floatVal;
  1105. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1106. twoSided = (intVal != 0);
  1107. String techniqueName = "Techniques/NoTexture";
  1108. if (!diffuseTexName.Empty())
  1109. {
  1110. techniqueName = "Techniques/Diff";
  1111. if (!normalTexName.Empty())
  1112. techniqueName += "Normal";
  1113. if (!specularTexName.Empty())
  1114. techniqueName += "Spec";
  1115. // For now lightmap does not coexist with normal & specular
  1116. if (normalTexName.Empty() && specularTexName.Empty() && !lightmapTexName.Empty())
  1117. techniqueName += "LightMap";
  1118. if (lightmapTexName.Empty() && !emissiveTexName.Empty())
  1119. techniqueName += emissiveAO_ ? "AO" : "Emissive";
  1120. }
  1121. if (hasAlpha)
  1122. techniqueName += "Alpha";
  1123. // See if any mesh that uses this material has vertex colors
  1124. // and set the technique accordingly, if enabled
  1125. for (unsigned i = 0; i < scene_->mNumMeshes && useVertexColors_; i++)
  1126. {
  1127. aiMesh* mesh = scene_->mMeshes[i];
  1128. aiMaterial* mesh_material = scene_->mMaterials[mesh->mMaterialIndex];
  1129. aiString meshMatNameStr;
  1130. mesh_material->Get(AI_MATKEY_NAME, meshMatNameStr);
  1131. if(mesh->GetNumColorChannels() > 0)
  1132. {
  1133. if(matNameStr == meshMatNameStr)
  1134. {
  1135. techniqueName += "VCol";
  1136. break;
  1137. }
  1138. }
  1139. }
  1140. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1141. techniqueElem.SetString("name", techniqueName + ".xml");
  1142. if (!diffuseTexName.Empty())
  1143. {
  1144. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1145. diffuseElem.SetString("unit", "diffuse");
  1146. diffuseElem.SetString("name", GetMaterialTextureName(diffuseTexName));
  1147. usedTextures.Insert(diffuseTexName);
  1148. }
  1149. if (!normalTexName.Empty())
  1150. {
  1151. XMLElement normalElem = materialElem.CreateChild("texture");
  1152. normalElem.SetString("unit", "normal");
  1153. normalElem.SetString("name", GetMaterialTextureName(normalTexName));
  1154. usedTextures.Insert(normalTexName);
  1155. }
  1156. if (!specularTexName.Empty())
  1157. {
  1158. XMLElement specularElem = materialElem.CreateChild("texture");
  1159. specularElem.SetString("unit", "specular");
  1160. specularElem.SetString("name", GetMaterialTextureName(specularTexName));
  1161. usedTextures.Insert(specularTexName);
  1162. }
  1163. if (!lightmapTexName.Empty())
  1164. {
  1165. XMLElement lightmapElem = materialElem.CreateChild("texture");
  1166. lightmapElem.SetString("unit", "emissive");
  1167. lightmapElem.SetString("name", GetMaterialTextureName(lightmapTexName));
  1168. usedTextures.Insert(lightmapTexName);
  1169. }
  1170. if (!emissiveTexName.Empty())
  1171. {
  1172. XMLElement emissiveElem = materialElem.CreateChild("texture");
  1173. emissiveElem.SetString("unit", "emissive");
  1174. emissiveElem.SetString("name", GetMaterialTextureName(emissiveTexName));
  1175. usedTextures.Insert(emissiveTexName);
  1176. }
  1177. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1178. diffuseColorElem.SetString("name", "MatDiffColor");
  1179. diffuseColorElem.SetColor("value", diffuseColor);
  1180. XMLElement specularElem = materialElem.CreateChild("parameter");
  1181. specularElem.SetString("name", "MatSpecColor");
  1182. specularElem.SetVector4("value", Vector4(specularColor.r_, specularColor.g_, specularColor.b_, specPower));
  1183. XMLElement emissiveColorElem = materialElem.CreateChild("parameter");
  1184. emissiveColorElem.SetString("name", "MatEmissiveColor");
  1185. emissiveColorElem.SetColor("value", emissiveColor);
  1186. if (twoSided)
  1187. {
  1188. XMLElement cullElem = materialElem.CreateChild("cull");
  1189. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1190. cullElem.SetString("value", "none");
  1191. shadowCullElem.SetString("value", "none");
  1192. }
  1193. FileSystem* fileSystem = context_->GetSubsystem<FileSystem>();
  1194. String outFileName = sourceAssetPath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".material";
  1195. if (noOverwriteMaterial_ && fileSystem->FileExists(outFileName))
  1196. {
  1197. PrintLine("Skipping save of existing material " + matName);
  1198. return true;
  1199. }
  1200. PrintLine("Writing material " + matName);
  1201. File outFile(context_);
  1202. if (!outFile.Open(outFileName, FILE_WRITE))
  1203. {
  1204. errorMessage_ = "Could not open output file " + outFileName;
  1205. return false;
  1206. }
  1207. outMaterial.Save(outFile);
  1208. return true;
  1209. }
  1210. void OpenAssetImporter::DumpNodes(aiNode* rootNode, unsigned level)
  1211. {
  1212. if (!rootNode)
  1213. return;
  1214. String indent(' ', level * 2);
  1215. Vector3 pos, scale;
  1216. Quaternion rot;
  1217. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  1218. GetPosRotScale(transform, pos, rot, scale);
  1219. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  1220. if (rootNode->mNumMeshes == 1)
  1221. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  1222. if (rootNode->mNumMeshes > 1)
  1223. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  1224. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  1225. DumpNodes(rootNode->mChildren[i], level + 1);
  1226. }
  1227. }