OpenAssetImporter.cpp 45 KB

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