OpenAssetImporter.cpp 48 KB

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