OpenAssetImporter.cpp 44 KB

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