OpenAssetImporter.cpp 45 KB

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