OpenAssetImporter.cpp 44 KB

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