OpenAssetImporter.cpp 45 KB

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