OpenAssetImporter.cpp 49 KB

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