AssetImporter.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Animation.h"
  24. #include "Context.h"
  25. #include "DebugRenderer.h"
  26. #include "File.h"
  27. #include "FileSystem.h"
  28. #include "Geometry.h"
  29. #include "Graphics.h"
  30. #include "IndexBuffer.h"
  31. #include "Light.h"
  32. #include "Material.h"
  33. #include "Model.h"
  34. #include "Octree.h"
  35. #include "PhysicsWorld.h"
  36. #include "ProcessUtils.h"
  37. #include "Quaternion.h"
  38. #include "ResourceCache.h"
  39. #include "Scene.h"
  40. #include "StaticModel.h"
  41. #include "StringUtils.h"
  42. #include "Vector3.h"
  43. #include "VertexBuffer.h"
  44. #include "XMLFile.h"
  45. #include "Zone.h"
  46. #include "Sort.h"
  47. #include "Map.h"
  48. #include "Set.h"
  49. #include <assimp.hpp>
  50. #include <aiScene.h>
  51. #include <aiPostProcess.h>
  52. #include <cstring>
  53. #include "DebugNew.h"
  54. enum Command
  55. {
  56. CMD_NONE = 0,
  57. CMD_MODEL,
  58. CMD_SCENE,
  59. CMD_DUMP,
  60. CMD_LOD
  61. };
  62. struct OutModel
  63. {
  64. OutModel() :
  65. totalVertices_(0),
  66. totalIndices_(0),
  67. rootBone_(0)
  68. {
  69. }
  70. String outName_;
  71. aiNode* rootNode_;
  72. Set<unsigned> meshIndices_;
  73. PODVector<aiMesh*> meshes_;
  74. PODVector<aiNode*> meshNodes_;
  75. PODVector<aiNode*> bones_;
  76. PODVector<aiAnimation*> animations_;
  77. PODVector<float> boneRadii_;
  78. PODVector<BoundingBox> boneHitboxes_;
  79. aiNode* rootBone_;
  80. unsigned totalVertices_;
  81. unsigned totalIndices_;
  82. };
  83. struct OutScene
  84. {
  85. String outName_;
  86. aiNode* rootNode_;
  87. Vector<OutModel> models_;
  88. PODVector<aiNode*> nodes_;
  89. PODVector<unsigned> nodeModelIndices_;
  90. };
  91. SharedPtr<Context> context_(new Context());
  92. SharedPtr<FileSystem> fileSystem_(new FileSystem(context_));
  93. Command command_ = CMD_NONE;
  94. const aiScene* scene_ = 0;
  95. aiNode* rootNode_ = 0;
  96. String materialListName_;
  97. String resourcePath_;
  98. bool useSubdirs_ = true;
  99. bool localIDs_ = false;
  100. bool saveBinary_ = false;
  101. bool createZone_ = true;
  102. bool noAnimations_ = false;
  103. int main(int argc, char** argv);
  104. void Run(const Vector<String>& arguments);
  105. void DumpNodes(aiNode* rootNode, unsigned level);
  106. void ExportModel(const String& outName);
  107. void CollectMeshes(OutModel& model, aiNode* node);
  108. void CollectBones(OutModel& model);
  109. void CollectBonesFinal(PODVector<aiNode*>& dest, const Set<aiNode*>& necessary, aiNode* node);
  110. void CollectAnimations(OutModel& model);
  111. void BuildBoneCollisionInfo(OutModel& model);
  112. void BuildAndSaveModel(OutModel& model);
  113. void BuildAndSaveAnimations(OutModel& model);
  114. void ExportScene(const String& outName);
  115. void CollectSceneModels(OutScene& scene, aiNode* node);
  116. void BuildAndSaveScene(OutScene& scene);
  117. void ExportMaterials(Set<String>& usedTextures);
  118. void BuildAndSaveMaterial(aiMaterial* material, Set<String>& usedTextures);
  119. void CopyTextures(const Set<String>& usedTextures, const String& sourcePath);
  120. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName);
  121. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& meshes, aiNode* node);
  122. unsigned GetMeshIndex(aiMesh* mesh);
  123. unsigned GetBoneIndex(OutModel& model, const String& boneName);
  124. aiBone* GetMeshBone(OutModel& model, const String& boneName);
  125. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName);
  126. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  127. blendIndices, Vector<PODVector<float> >& blendWeights);
  128. String GetMeshMaterialName(aiMesh* mesh);
  129. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  130. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  131. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  132. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  133. Vector<PODVector<float> >& blendWeights);
  134. unsigned GetElementMask(aiMesh* mesh);
  135. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive = true);
  136. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode);
  137. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode);
  138. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode);
  139. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale);
  140. String FromAIString(const aiString& str);
  141. Vector3 ToVector3(const aiVector3D& vec);
  142. Vector2 ToVector2(const aiVector2D& vec);
  143. Quaternion ToQuaternion(const aiQuaternion& quat);
  144. String SanitateAssetName(const String& name);
  145. int main(int argc, char** argv)
  146. {
  147. Vector<String> arguments;
  148. for (int i = 1; i < argc; ++i)
  149. arguments.Push(argv[i]);
  150. Run(arguments);
  151. return 0;
  152. }
  153. void Run(const Vector<String>& arguments)
  154. {
  155. if (arguments.Size() < 2)
  156. {
  157. ErrorExit(
  158. "Usage: AssetImporter <command> <input file> <output file> [options]\n"
  159. "See http://assimp.sourceforge.net/main_features_formats.html for input formats\n\n"
  160. "Commands:\n"
  161. "model Export a model\n"
  162. "scene Export a scene\n"
  163. "dump Dump scene node structure. No output file is generated\n"
  164. "lod Combine several Urho3D models as LOD levels of the output model\n"
  165. " Syntax: lod <dist0> <mdl0> <dist1 <mdl1> ... <output file>\n"
  166. "\n"
  167. "Options:\n"
  168. "-b Save scene in binary format, default format is XML\n"
  169. "-i Use local ID's for scene nodes\n"
  170. "-mX Output a material list file X (model mode only)\n"
  171. "-na Do not export animations\n"
  172. "-nm Do not export materials\n"
  173. "-ns Do not create subdirectories for resources\n"
  174. "-nz Do not create a zone and a directional light (scene mode only)\n"
  175. "-pX Set path X for scene resources. Default is output file path\n"
  176. "-rX Use scene node X as root node\n"
  177. "-t Generate tangents to model(s)\n"
  178. );
  179. }
  180. RegisterSceneLibrary(context_);
  181. RegisterGraphicsLibrary(context_);
  182. RegisterPhysicsLibrary(context_);
  183. context_->RegisterSubsystem(new FileSystem(context_));
  184. context_->RegisterSubsystem(new ResourceCache(context_));
  185. String command = arguments[0].ToLower();
  186. String rootNodeName;
  187. bool noMaterials = false;
  188. unsigned flags =
  189. aiProcess_ConvertToLeftHanded |
  190. aiProcess_JoinIdenticalVertices |
  191. aiProcess_Triangulate |
  192. aiProcess_GenSmoothNormals |
  193. aiProcess_LimitBoneWeights |
  194. aiProcess_ImproveCacheLocality |
  195. aiProcess_FixInfacingNormals |
  196. aiProcess_FindInvalidData |
  197. aiProcess_FindInstances |
  198. aiProcess_OptimizeMeshes;
  199. for (unsigned i = 2; i < arguments.Size(); ++i)
  200. {
  201. if (arguments[i].Length() >= 2 && arguments[i][0] == '-')
  202. {
  203. String parameter;
  204. if (arguments[i].Length() >= 3)
  205. parameter = arguments[i].Substring(2);
  206. switch (tolower(arguments[i][1]))
  207. {
  208. case 'b':
  209. saveBinary_ = true;
  210. break;
  211. case 'i':
  212. localIDs_ = true;
  213. break;
  214. case 'm':
  215. materialListName_ = GetInternalPath(parameter);
  216. break;
  217. case 'p':
  218. resourcePath_ = AddTrailingSlash(parameter);
  219. break;
  220. case 'r':
  221. rootNodeName = parameter;
  222. break;
  223. case 't':
  224. flags |= aiProcess_CalcTangentSpace;
  225. break;
  226. case 'n':
  227. if (!parameter.Empty())
  228. {
  229. switch (tolower(parameter[0]))
  230. {
  231. case 'a':
  232. noAnimations_ = true;
  233. break;
  234. case 'm':
  235. noMaterials = true;
  236. break;
  237. case 's':
  238. useSubdirs_ = false;
  239. break;
  240. case 'z':
  241. createZone_ = false;
  242. break;
  243. }
  244. }
  245. break;
  246. }
  247. }
  248. }
  249. if (command == "model")
  250. command_ = CMD_MODEL;
  251. else if (command == "scene")
  252. command_ = CMD_SCENE;
  253. else if (command == "dump")
  254. command_ = CMD_DUMP;
  255. else if (command == "lod")
  256. command_ = CMD_LOD;
  257. else
  258. ErrorExit("Unrecognized command " + command);
  259. if (command_ != CMD_LOD)
  260. {
  261. String inFile = arguments[1];
  262. String outFile;
  263. if (arguments.Size() > 2 && arguments[2][0] != '-')
  264. outFile = GetInternalPath(arguments[2]);
  265. if (resourcePath_.Empty())
  266. {
  267. resourcePath_ = GetPath(outFile);
  268. // If output file already has the Models/ path (model mode), do not take it into the resource path
  269. if (command_ == CMD_MODEL)
  270. {
  271. String resPathLower = resourcePath_.ToLower();
  272. if (resPathLower.FindLast("models/") == resPathLower.Length() - 7)
  273. resourcePath_ = resourcePath_.Substring(0, resourcePath_.Length() - 7);
  274. }
  275. if (resourcePath_.Empty())
  276. resourcePath_ = "./";
  277. }
  278. resourcePath_ = AddTrailingSlash(resourcePath_);
  279. Assimp::Importer importer;
  280. PrintLine("Reading file " + inFile);
  281. scene_ = importer.ReadFile(GetNativePath(inFile).CString(), flags);
  282. if (!scene_)
  283. ErrorExit("Could not open or parse input file " + inFile);
  284. rootNode_ = scene_->mRootNode;
  285. if (!rootNodeName.Empty())
  286. {
  287. rootNode_ = GetNode(rootNodeName, rootNode_, false);
  288. if (!rootNode_)
  289. ErrorExit("Could not find scene node " + rootNodeName);
  290. }
  291. switch (command_)
  292. {
  293. case CMD_DUMP:
  294. DumpNodes(rootNode_, 0);
  295. return;
  296. case CMD_MODEL:
  297. ExportModel(outFile);
  298. break;
  299. case CMD_SCENE:
  300. ExportScene(outFile);
  301. break;
  302. }
  303. if (!noMaterials)
  304. {
  305. Set<String> usedTextures;
  306. ExportMaterials(usedTextures);
  307. CopyTextures(usedTextures, GetPath(inFile));
  308. }
  309. }
  310. else
  311. {
  312. PODVector<float> lodDistances;
  313. Vector<String> modelNames;
  314. String outFile;
  315. unsigned numLodArguments = 0;
  316. for (unsigned i = 1; i < arguments.Size(); ++i)
  317. {
  318. if (arguments[i][0] == '-')
  319. break;
  320. ++numLodArguments;
  321. }
  322. if (numLodArguments < 4)
  323. ErrorExit("Must define at least 2 LOD levels");
  324. if (!(numLodArguments & 1))
  325. ErrorExit("No output file defined");
  326. for (unsigned i = 1; i < numLodArguments + 1; ++i)
  327. {
  328. if (i == numLodArguments)
  329. outFile = GetInternalPath(arguments[i]);
  330. else
  331. {
  332. if (i & 1)
  333. lodDistances.Push(Max(ToFloat(arguments[i]), 0.0f));
  334. else
  335. modelNames.Push(GetInternalPath(arguments[i]));
  336. }
  337. }
  338. if (lodDistances[0] != 0.0f)
  339. {
  340. PrintLine("Warning: first LOD distance forced to 0");
  341. lodDistances[0] = 0.0f;
  342. }
  343. CombineLods(lodDistances, modelNames, outFile);
  344. }
  345. }
  346. void DumpNodes(aiNode* rootNode, unsigned level)
  347. {
  348. if (!rootNode)
  349. return;
  350. String indent(' ', level * 2);
  351. Vector3 pos, scale;
  352. Quaternion rot;
  353. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  354. GetPosRotScale(transform, pos, rot, scale);
  355. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  356. if (rootNode->mNumMeshes == 1)
  357. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  358. if (rootNode->mNumMeshes > 1)
  359. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  360. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  361. DumpNodes(rootNode->mChildren[i], level + 1);
  362. }
  363. void ExportModel(const String& outName)
  364. {
  365. if (outName.Empty())
  366. ErrorExit("No output file defined");
  367. OutModel model;
  368. model.rootNode_ = rootNode_;
  369. model.outName_ = outName;
  370. CollectMeshes(model, model.rootNode_);
  371. CollectBones(model);
  372. BuildBoneCollisionInfo(model);
  373. BuildAndSaveModel(model);
  374. if (!noAnimations_)
  375. {
  376. CollectAnimations(model);
  377. BuildAndSaveAnimations(model);
  378. }
  379. // Write material references if requested
  380. if (!materialListName_.Empty())
  381. {
  382. File listFile(context_);
  383. if (listFile.Open(materialListName_, FILE_WRITE))
  384. {
  385. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  386. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  387. }
  388. else
  389. PrintLine("Warning: could not write material list file " + materialListName_);
  390. }
  391. }
  392. void CollectMeshes(OutModel& model, aiNode* node)
  393. {
  394. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  395. {
  396. aiMesh* mesh = scene_->mMeshes[node->mMeshes[i]];
  397. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  398. {
  399. if (mesh == model.meshes_[j])
  400. {
  401. PrintLine("Warning: same mesh found multiple times");
  402. break;
  403. }
  404. }
  405. model.meshIndices_.Insert(node->mMeshes[i]);
  406. model.meshes_.Push(mesh);
  407. model.meshNodes_.Push(node);
  408. model.totalVertices_ += mesh->mNumVertices;
  409. model.totalIndices_ += mesh->mNumFaces * 3;
  410. }
  411. for (unsigned i = 0; i < node->mNumChildren; ++i)
  412. CollectMeshes(model, node->mChildren[i]);
  413. }
  414. void CollectBones(OutModel& model)
  415. {
  416. Set<aiNode*> necessary;
  417. Set<aiNode*> rootNodes;
  418. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  419. {
  420. aiMesh* mesh = model.meshes_[i];
  421. aiNode* meshNode = model.meshNodes_[i];
  422. aiNode* meshParentNode = meshNode->mParent;
  423. aiNode* rootNode = 0;
  424. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  425. {
  426. aiBone* bone = mesh->mBones[j];
  427. String boneName(FromAIString(bone->mName));
  428. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  429. if (!boneNode)
  430. ErrorExit("Could not find scene node for bone " + boneName);
  431. necessary.Insert(boneNode);
  432. rootNode = boneNode;
  433. for (;;)
  434. {
  435. boneNode = boneNode->mParent;
  436. if (!boneNode || boneNode == meshNode || boneNode == meshParentNode)
  437. break;
  438. rootNode = boneNode;
  439. necessary.Insert(boneNode);
  440. }
  441. if (rootNodes.Find(rootNode) == rootNodes.End())
  442. rootNodes.Insert(rootNode);
  443. }
  444. }
  445. // If we find multiple root nodes, try to remedy by using their parent instead
  446. if (rootNodes.Size() > 1)
  447. {
  448. aiNode* commonParent = (*rootNodes.Begin())->mParent;
  449. for (Set<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  450. {
  451. if (*i != commonParent)
  452. {
  453. if (!commonParent || (*i)->mParent != commonParent)
  454. ErrorExit("Skeleton with multiple root nodes found, not supported");
  455. }
  456. }
  457. rootNodes.Clear();
  458. rootNodes.Insert(commonParent);
  459. necessary.Insert(commonParent);
  460. }
  461. if (rootNodes.Empty())
  462. return;
  463. model.rootBone_ = *rootNodes.Begin();
  464. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  465. // Initialize the bone collision info
  466. model.boneRadii_.Resize(model.bones_.Size());
  467. model.boneHitboxes_.Resize(model.bones_.Size());
  468. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  469. {
  470. model.boneRadii_[i] = 0.0f;
  471. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  472. }
  473. }
  474. void CollectBonesFinal(PODVector<aiNode*>& dest, const Set<aiNode*>& necessary, aiNode* node)
  475. {
  476. if (necessary.Find(node) != necessary.End())
  477. {
  478. dest.Push(node);
  479. for (unsigned i = 0; i < node->mNumChildren; ++i)
  480. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  481. }
  482. }
  483. void CollectAnimations(OutModel& model)
  484. {
  485. const aiScene* scene = scene_;
  486. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  487. {
  488. aiAnimation* anim = scene->mAnimations[i];
  489. bool modelBoneFound = false;
  490. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  491. {
  492. aiNodeAnim* channel = anim->mChannels[j];
  493. String channelName = FromAIString(channel->mNodeName);
  494. if (GetBoneIndex(model, channelName) != M_MAX_UNSIGNED)
  495. {
  496. modelBoneFound = true;
  497. break;
  498. }
  499. }
  500. if (modelBoneFound)
  501. model.animations_.Push(anim);
  502. }
  503. /// \todo Vertex morphs are ignored for now
  504. }
  505. void BuildBoneCollisionInfo(OutModel& model)
  506. {
  507. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  508. {
  509. aiMesh* mesh = model.meshes_[i];
  510. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  511. {
  512. aiBone* bone = mesh->mBones[j];
  513. String boneName = FromAIString(bone->mName);
  514. unsigned boneIndex = GetBoneIndex(model, boneName);
  515. if (boneIndex == M_MAX_UNSIGNED)
  516. continue;
  517. aiNode* boneNode = model.bones_[boneIndex];
  518. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  519. {
  520. float weight = bone->mWeights[k].mWeight;
  521. if (weight > 0.33f)
  522. {
  523. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  524. Vector3 vertex = ToVector3(vertexBoneSpace);
  525. float radius = vertex.Length();
  526. if (radius > model.boneRadii_[boneIndex])
  527. model.boneRadii_[boneIndex] = radius;
  528. model.boneHitboxes_[boneIndex].Merge(vertex);
  529. }
  530. }
  531. }
  532. }
  533. }
  534. void BuildAndSaveModel(OutModel& model)
  535. {
  536. if (!model.rootNode_)
  537. ErrorExit("Null root node for model");
  538. String rootNodeName = FromAIString(model.rootNode_->mName);
  539. if (!model.meshes_.Size())
  540. ErrorExit("No geometries found starting from node " + rootNodeName);
  541. PrintLine("Writing model " + rootNodeName);
  542. SharedPtr<Model> outModel(new Model(context_));
  543. outModel->SetNumGeometries(model.meshes_.Size());
  544. Vector<PODVector<unsigned> > allBoneMappings;
  545. BoundingBox box;
  546. bool combineBuffers = true;
  547. // Check if buffers can be combined (same vertex element mask, under 65535 vertices)
  548. unsigned elementMask = GetElementMask(model.meshes_[0]);
  549. for (unsigned i = 1; i < model.meshes_.Size(); ++i)
  550. {
  551. if (GetElementMask(model.meshes_[i]) != elementMask)
  552. {
  553. combineBuffers = false;
  554. break;
  555. }
  556. }
  557. // Check if keeping separate buffers allows to avoid 32-bit indices
  558. if (combineBuffers && model.totalVertices_ > 65535)
  559. {
  560. bool allUnder65k = true;
  561. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  562. {
  563. if (model.meshes_[i]->mNumVertices > 65535)
  564. allUnder65k = false;
  565. }
  566. if (allUnder65k == true)
  567. combineBuffers = false;
  568. }
  569. if (!combineBuffers)
  570. {
  571. PrintLine("Writing separate buffers");
  572. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  573. {
  574. // Get the world transform of the mesh for baking into the vertices
  575. Matrix3x4 vertexTransform;
  576. Matrix3 normalTransform;
  577. Vector3 pos, scale;
  578. Quaternion rot;
  579. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  580. vertexTransform = Matrix3x4(pos, rot, scale);
  581. normalTransform = rot.RotationMatrix();
  582. SharedPtr<IndexBuffer> ib(new IndexBuffer(context_));
  583. SharedPtr<VertexBuffer> vb(new VertexBuffer(context_));
  584. SharedPtr<Geometry> geom(new Geometry(context_));
  585. aiMesh* mesh = model.meshes_[i];
  586. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  587. String(mesh->mNumFaces * 3) + " indices");
  588. bool largeIndices = mesh->mNumVertices > 65535;
  589. unsigned elementMask = GetElementMask(mesh);
  590. ib->SetSize(mesh->mNumFaces * 3, largeIndices);
  591. vb->SetSize(mesh->mNumVertices, elementMask);
  592. // Build the index data
  593. void* indexData = ib->Lock(0, ib->GetIndexCount(), LOCK_NORMAL);
  594. if (!largeIndices)
  595. {
  596. unsigned short* dest = (unsigned short*)indexData;
  597. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  598. WriteShortIndices(dest, mesh, j, 0);
  599. }
  600. else
  601. {
  602. unsigned* dest = (unsigned*)indexData;
  603. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  604. WriteLargeIndices(dest, mesh, j, 0);
  605. }
  606. // Build the vertex data
  607. // If there are bones, get blend data
  608. Vector<PODVector<unsigned char> > blendIndices;
  609. Vector<PODVector<float> > blendWeights;
  610. PODVector<unsigned> boneMappings;
  611. if (model.bones_.Size())
  612. GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights);
  613. void* vertexData = vb->Lock(0, vb->GetVertexCount(), LOCK_NORMAL);
  614. float* dest = (float*)vertexData;
  615. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  616. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  617. ib->Unlock();
  618. vb->Unlock();
  619. // Calculate the geometry center
  620. Vector3 center = Vector3::ZERO;
  621. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  622. {
  623. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  624. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  625. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  626. }
  627. if (mesh->mNumFaces)
  628. center /= (float)mesh->mNumFaces * 3;
  629. // Define the geometry
  630. geom->SetIndexBuffer(ib);
  631. geom->SetVertexBuffer(0, vb);
  632. geom->SetDrawRange(TRIANGLE_LIST, 0, mesh->mNumFaces * 3, true);
  633. outModel->SetNumGeometryLodLevels(i, 1);
  634. outModel->SetGeometry(i, 0, geom);
  635. outModel->SetGeometryCenter(i, center);
  636. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  637. allBoneMappings.Push(boneMappings);
  638. }
  639. }
  640. else
  641. {
  642. SharedPtr<IndexBuffer> ib(new IndexBuffer(context_));
  643. SharedPtr<VertexBuffer> vb(new VertexBuffer(context_));
  644. bool largeIndices = model.totalIndices_ > 65535;
  645. ib->SetSize(model.totalIndices_, largeIndices);
  646. vb->SetSize(model.totalVertices_, elementMask);
  647. unsigned startVertexOffset = 0;
  648. unsigned startIndexOffset = 0;
  649. void* indexData = ib->Lock(0, ib->GetIndexCount(), LOCK_NORMAL);
  650. void* vertexData = vb->Lock(0, vb->GetVertexCount(), LOCK_NORMAL);
  651. // The buffer is in CPU memory, and therefore locking is irrelevant. Unlock so that draw range checking can lock again
  652. ib->Unlock();
  653. vb->Unlock();
  654. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  655. {
  656. // Get the world transform of the mesh for baking into the vertices
  657. Matrix3x4 vertexTransform;
  658. Matrix3 normalTransform;
  659. Vector3 pos, scale;
  660. Quaternion rot;
  661. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  662. vertexTransform = Matrix3x4(pos, rot, scale);
  663. normalTransform = rot.RotationMatrix();
  664. SharedPtr<Geometry> geom(new Geometry(context_));
  665. aiMesh* mesh = model.meshes_[i];
  666. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  667. String(mesh->mNumFaces * 3) + " indices");
  668. // Build the index data
  669. if (!largeIndices)
  670. {
  671. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  672. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  673. WriteShortIndices(dest, mesh, j, startVertexOffset);
  674. }
  675. else
  676. {
  677. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  678. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  679. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  680. }
  681. // Build the vertex data
  682. // If there are bones, get blend data
  683. Vector<PODVector<unsigned char> > blendIndices;
  684. Vector<PODVector<float> > blendWeights;
  685. PODVector<unsigned> boneMappings;
  686. if (model.bones_.Size())
  687. GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights);
  688. float* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  689. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  690. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  691. // Calculate the geometry center
  692. Vector3 center = Vector3::ZERO;
  693. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  694. {
  695. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  696. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  697. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  698. }
  699. if (mesh->mNumFaces)
  700. center /= (float)mesh->mNumFaces * 3;
  701. // Define the geometry
  702. geom->SetIndexBuffer(ib);
  703. geom->SetVertexBuffer(0, vb);
  704. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, mesh->mNumFaces * 3, true);
  705. outModel->SetNumGeometryLodLevels(i, 1);
  706. outModel->SetGeometry(i, 0, geom);
  707. outModel->SetGeometryCenter(i, center);
  708. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  709. allBoneMappings.Push(boneMappings);
  710. startVertexOffset += mesh->mNumVertices;
  711. startIndexOffset += mesh->mNumFaces * 3;
  712. }
  713. }
  714. outModel->SetBoundingBox(box);
  715. // Build skeleton if necessary
  716. if (model.bones_.Size() && model.rootBone_)
  717. {
  718. PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  719. FromAIString(model.rootBone_->mName));
  720. Skeleton skeleton;
  721. Vector<Bone>& bones = skeleton.GetModifiableBones();
  722. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  723. {
  724. aiNode* boneNode = model.bones_[i];
  725. String boneName(FromAIString(boneNode->mName));
  726. Bone newBone;
  727. newBone.name_ = boneName;
  728. aiMatrix4x4 transform = boneNode->mTransformation;
  729. // Make the root bone transform relative to the model's root node, if it is not already
  730. if (boneNode == model.rootBone_)
  731. transform = GetDerivedTransform(boneNode, model.rootNode_);
  732. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  733. // Get offset information if exists
  734. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  735. newBone.radius_ = model.boneRadii_[i];
  736. newBone.boundingBox_ = model.boneHitboxes_[i];
  737. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  738. newBone.parentIndex_ = i;
  739. bones.Push(newBone);
  740. }
  741. // Set the bone hierarchy
  742. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  743. {
  744. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  745. for (unsigned j = 0; j < bones.Size(); ++j)
  746. {
  747. if (bones[j].name_ == parentName)
  748. {
  749. bones[i].parentIndex_ = j;
  750. break;
  751. }
  752. }
  753. }
  754. outModel->SetSkeleton(skeleton);
  755. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  756. outModel->SetGeometryBoneMappings(allBoneMappings);
  757. }
  758. File outFile(context_);
  759. if (!outFile.Open(model.outName_, FILE_WRITE))
  760. ErrorExit("Could not open output file " + model.outName_);
  761. outModel->Save(outFile);
  762. }
  763. void BuildAndSaveAnimations(OutModel& model)
  764. {
  765. for (unsigned i = 0; i < model.animations_.Size(); ++i)
  766. {
  767. aiAnimation* anim = model.animations_[i];
  768. String animName = FromAIString(anim->mName);
  769. if (animName.Empty())
  770. animName = "Anim" + String(i + 1);
  771. String animOutName = GetPath(model.outName_) + GetFileName(model.outName_) + "_" + SanitateAssetName(animName) + ".ani";
  772. SharedPtr<Animation> outAnim(new Animation(context_));
  773. float tickConversion = 1.0f / (float)anim->mTicksPerSecond;
  774. outAnim->SetAnimationName(animName);
  775. outAnim->SetLength((float)anim->mDuration * tickConversion);
  776. PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  777. Vector<AnimationTrack> tracks;
  778. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  779. {
  780. aiNodeAnim* channel = anim->mChannels[j];
  781. String channelName = FromAIString(channel->mNodeName);
  782. unsigned boneIndex = GetBoneIndex(model, channelName);
  783. if (boneIndex == M_MAX_UNSIGNED)
  784. {
  785. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  786. continue;
  787. }
  788. aiNode* boneNode = model.bones_[boneIndex];
  789. AnimationTrack track;
  790. track.name_ = channelName;
  791. track.nameHash_ = StringHash(channelName);
  792. // Check which channels are used
  793. track.channelMask_ = 0;
  794. if (channel->mNumPositionKeys > 1)
  795. track.channelMask_ |= CHANNEL_POSITION;
  796. if (channel->mNumRotationKeys > 1)
  797. track.channelMask_ |= CHANNEL_ROTATION;
  798. if (channel->mNumScalingKeys > 1)
  799. track.channelMask_ |= CHANNEL_SCALE;
  800. // Check for redundant identity scale in all keyframes and remove in that case
  801. if (track.channelMask_ & CHANNEL_SCALE)
  802. {
  803. bool redundantScale = true;
  804. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  805. {
  806. float SCALE_EPSILON = 0.000001f;
  807. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  808. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  809. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  810. {
  811. redundantScale = false;
  812. break;
  813. }
  814. }
  815. if (redundantScale)
  816. track.channelMask_ &= ~CHANNEL_SCALE;
  817. }
  818. if (!track.channelMask_)
  819. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  820. // Currently only same amount of keyframes is supported
  821. // Note: should also check the times of individual keyframes for match
  822. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  823. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  824. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  825. {
  826. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  827. continue;
  828. }
  829. unsigned keyFrames = channel->mNumPositionKeys;
  830. if (channel->mNumRotationKeys > keyFrames)
  831. keyFrames = channel->mNumRotationKeys;
  832. if (channel->mNumScalingKeys > keyFrames)
  833. keyFrames = channel->mNumScalingKeys;
  834. for (unsigned k = 0; k < keyFrames; ++k)
  835. {
  836. AnimationKeyFrame kf;
  837. kf.time_ = 0.0f;
  838. kf.position_ = Vector3::ZERO;
  839. kf.rotation_ = Quaternion::IDENTITY;
  840. kf.scale_ = Vector3::ONE;
  841. // Get time for the keyframe
  842. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  843. kf.time_ = (float)channel->mPositionKeys[k].mTime * tickConversion;
  844. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  845. kf.time_ = (float)channel->mRotationKeys[k].mTime * tickConversion;
  846. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  847. kf.time_ = (float)channel->mScalingKeys[k].mTime * tickConversion;
  848. // Start with the bone's base transform
  849. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  850. aiVector3D pos, scale;
  851. aiQuaternion rot;
  852. boneTransform.Decompose(scale, rot, pos);
  853. // Then apply the active channels
  854. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  855. pos = channel->mPositionKeys[k].mValue;
  856. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  857. rot = channel->mRotationKeys[k].mValue;
  858. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  859. scale = channel->mScalingKeys[k].mValue;
  860. // If root bone, transform with the model root node transform
  861. if (!boneIndex)
  862. {
  863. aiMatrix4x4 transMat, scaleMat, rotMat;
  864. aiMatrix4x4::Translation(pos, transMat);
  865. aiMatrix4x4::Scaling(scale, scaleMat);
  866. rotMat = aiMatrix4x4(rot.GetMatrix());
  867. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  868. tform = GetDerivedTransform(tform, boneNode, model.rootNode_);
  869. tform.Decompose(scale, rot, pos);
  870. }
  871. if (track.channelMask_ & CHANNEL_POSITION)
  872. kf.position_ = ToVector3(pos);
  873. if (track.channelMask_ & CHANNEL_ROTATION)
  874. kf.rotation_ = ToQuaternion(rot);
  875. if (track.channelMask_ & CHANNEL_SCALE)
  876. kf.scale_ = ToVector3(scale);
  877. track.keyFrames_.Push(kf);
  878. }
  879. tracks.Push(track);
  880. }
  881. outAnim->SetTracks(tracks);
  882. File outFile(context_);
  883. if (!outFile.Open(animOutName, FILE_WRITE))
  884. ErrorExit("Could not open output file " + animOutName);
  885. outAnim->Save(outFile);
  886. }
  887. }
  888. void ExportScene(const String& outName)
  889. {
  890. OutScene outScene;
  891. outScene.outName_ = outName;
  892. outScene.rootNode_ = rootNode_;
  893. if (useSubdirs_)
  894. fileSystem_->CreateDir(resourcePath_ + "Models");
  895. CollectSceneModels(outScene, rootNode_);
  896. // Save models
  897. for (unsigned i = 0; i < outScene.models_.Size(); ++i)
  898. BuildAndSaveModel(outScene.models_[i]);
  899. // Save scene
  900. BuildAndSaveScene(outScene);
  901. }
  902. void CollectSceneModels(OutScene& scene, aiNode* node)
  903. {
  904. Vector<Pair<aiNode*, aiMesh*> > meshes;
  905. GetMeshesUnderNode(meshes, node);
  906. if (meshes.Size())
  907. {
  908. OutModel model;
  909. model.rootNode_ = node;
  910. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  911. for (unsigned i = 0; i < meshes.Size(); ++i)
  912. {
  913. aiMesh* mesh = meshes[i].second_;
  914. unsigned meshIndex = GetMeshIndex(mesh);
  915. model.meshIndices_.Insert(meshIndex);
  916. model.meshes_.Push(mesh);
  917. model.meshNodes_.Push(meshes[i].first_);
  918. model.totalVertices_ += mesh->mNumVertices;
  919. model.totalIndices_ += mesh->mNumFaces * 3;
  920. }
  921. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  922. bool unique = true;
  923. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  924. {
  925. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  926. {
  927. PrintLine("Added node " + FromAIString(node->mName));
  928. scene.nodes_.Push(node);
  929. scene.nodeModelIndices_.Push(i);
  930. unique = false;
  931. break;
  932. }
  933. }
  934. if (unique)
  935. {
  936. PrintLine("Added model " + model.outName_);
  937. PrintLine("Added node " + FromAIString(node->mName));
  938. CollectBones(model);
  939. BuildBoneCollisionInfo(model);
  940. if (!noAnimations_)
  941. {
  942. CollectAnimations(model);
  943. BuildAndSaveAnimations(model);
  944. }
  945. scene.models_.Push(model);
  946. scene.nodes_.Push(node);
  947. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  948. }
  949. }
  950. for (unsigned i = 0; i < node->mNumChildren; ++i)
  951. CollectSceneModels(scene, node->mChildren[i]);
  952. }
  953. void BuildAndSaveScene(OutScene& scene)
  954. {
  955. PrintLine("Writing scene");
  956. SharedPtr<Scene> outScene(new Scene(context_));
  957. /// \todo Make the physics properties configurable
  958. PhysicsWorld* physicsWorld = outScene->CreateComponent<PhysicsWorld>();
  959. physicsWorld->SetGravity(Vector3(0.0f, -9.81f, 0.0f));
  960. /// \todo Make the octree properties configurable, or detect from the scene contents
  961. Octree* octree = outScene->CreateComponent<Octree>();
  962. DebugRenderer* debug = outScene->CreateComponent<DebugRenderer>();
  963. if (createZone_)
  964. {
  965. Node* zoneNode = outScene->CreateChild("Zone", localIDs_ ? LOCAL : REPLICATED);
  966. Zone* zone = zoneNode->CreateComponent<Zone>();
  967. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.f));
  968. zone->SetAmbientColor(Color(0.25f, 0.25f, 0.25f));
  969. Node* lightNode = outScene->CreateChild("GlobalLight", localIDs_ ? LOCAL : REPLICATED);
  970. Light* light = lightNode->CreateComponent<Light>();
  971. light->SetLightType(LIGHT_DIRECTIONAL);
  972. lightNode->SetRotation(Quaternion(60.0f, 30.0f, 0.0f));
  973. }
  974. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  975. for (unsigned i = 0; i < scene.nodes_.Size(); ++i)
  976. {
  977. const OutModel& model = scene.models_[scene.nodeModelIndices_[i]];
  978. // Create a static model component for each node
  979. Node* modelNode = outScene->CreateChild(FromAIString(scene.nodes_[i]->mName), localIDs_ ? LOCAL : REPLICATED);
  980. StaticModel* staticModel = modelNode->CreateComponent<StaticModel>();
  981. // Create a dummy model so that the reference can be stored
  982. String modelName = (useSubdirs_ ? "Models/" : "") + GetFileNameAndExtension(model.outName_);
  983. if (!cache->Exists(modelName))
  984. {
  985. Model* dummyModel = new Model(context_);
  986. dummyModel->SetName(modelName);
  987. dummyModel->SetNumGeometries(model.meshes_.Size());
  988. cache->AddManualResource(dummyModel);
  989. }
  990. staticModel->SetModel(cache->GetResource<Model>(modelName));
  991. // Set a flattened transform
  992. Vector3 pos, scale;
  993. Quaternion rot;
  994. GetPosRotScale(GetDerivedTransform(scene.nodes_[i], rootNode_), pos, rot, scale);
  995. modelNode->SetTransform(pos, rot, scale);
  996. // Set materials if they are known
  997. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  998. {
  999. String matName = GetMeshMaterialName(model.meshes_[j]);
  1000. if (!matName.Empty())
  1001. {
  1002. // Create a dummy material so that the reference can be stored
  1003. if (!cache->Exists(matName))
  1004. {
  1005. Material* dummyMat = new Material(context_);
  1006. dummyMat->SetName(matName);
  1007. cache->AddManualResource(dummyMat);
  1008. }
  1009. staticModel->SetMaterial(j, cache->GetResource<Material>(matName));
  1010. }
  1011. }
  1012. }
  1013. File file(context_);
  1014. if (!file.Open(scene.outName_, FILE_WRITE))
  1015. ErrorExit("Could not open output file " + scene.outName_);
  1016. if (!saveBinary_)
  1017. outScene->SaveXML(file);
  1018. else
  1019. outScene->Save(file);
  1020. }
  1021. void ExportMaterials(Set<String>& usedTextures)
  1022. {
  1023. if (useSubdirs_)
  1024. fileSystem_->CreateDir(resourcePath_ + "Materials");
  1025. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1026. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  1027. }
  1028. void BuildAndSaveMaterial(aiMaterial* material, Set<String>& usedTextures)
  1029. {
  1030. // Material must have name so it can be successfully saved
  1031. aiString matNameStr;
  1032. material->Get(AI_MATKEY_NAME, matNameStr);
  1033. String matName = SanitateAssetName(FromAIString(matNameStr));
  1034. if (matName.Empty())
  1035. return;
  1036. PrintLine("Writing material " + matName);
  1037. // Do not actually create a material instance, but instead craft an xml file manually
  1038. XMLFile outMaterial(context_);
  1039. XMLElement materialElem = outMaterial.CreateRoot("material");
  1040. String diffuseTexName;
  1041. String normalTexName;
  1042. Color diffuseColor;
  1043. bool hasAlpha = false;
  1044. bool twoSided = false;
  1045. float specIntensity = 0.0f;
  1046. float specPower = 1.0f;
  1047. aiString stringVal;
  1048. float floatVal;
  1049. int intVal;
  1050. aiColor3D colorVal;
  1051. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1052. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1053. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1054. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1055. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1056. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1057. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1058. {
  1059. if (floatVal < 1.0f)
  1060. hasAlpha = true;
  1061. diffuseColor.a_ = floatVal;
  1062. }
  1063. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1064. specPower = floatVal;
  1065. if (material->Get(AI_MATKEY_SHININESS_STRENGTH, floatVal) == AI_SUCCESS)
  1066. specIntensity = floatVal;
  1067. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1068. twoSided = (intVal != 0);
  1069. String techniqueName = "Techniques/NoTexture";
  1070. if (!diffuseTexName.Empty())
  1071. {
  1072. techniqueName = "Techniques/Diff";
  1073. if (!normalTexName.Empty())
  1074. techniqueName += "Normal";
  1075. }
  1076. if (hasAlpha)
  1077. techniqueName += "Alpha";
  1078. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1079. techniqueElem.SetString("name", techniqueName + ".xml");
  1080. if (!diffuseTexName.Empty())
  1081. {
  1082. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1083. diffuseElem.SetString("unit", "diffuse");
  1084. diffuseElem.SetString("name", (useSubdirs_ ? "Textures/" : "") + diffuseTexName);
  1085. usedTextures.Insert(diffuseTexName);
  1086. }
  1087. if (!normalTexName.Empty())
  1088. {
  1089. XMLElement normalElem = materialElem.CreateChild("texture");
  1090. normalElem.SetString("unit", "diffuse");
  1091. normalElem.SetString("name", (useSubdirs_ ? "Textures/" : "") + normalTexName);
  1092. usedTextures.Insert(normalTexName);
  1093. }
  1094. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1095. diffuseColorElem.SetString("name", "MatDiffColor");
  1096. diffuseColorElem.SetColor("value", diffuseColor);
  1097. XMLElement specularElem = materialElem.CreateChild("parameter");
  1098. specularElem.SetString("name", "MatSpecProperties");
  1099. specularElem.SetVector2("value", Vector2(specIntensity, specPower));
  1100. if (twoSided)
  1101. {
  1102. XMLElement cullElem = materialElem.CreateChild("cull");
  1103. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1104. cullElem.SetString("value", "none");
  1105. shadowCullElem.SetString("value", "none");
  1106. }
  1107. File outFile(context_);
  1108. String outFileName = resourcePath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".xml";
  1109. if (!outFile.Open(outFileName, FILE_WRITE))
  1110. ErrorExit("Could not open output file " + outFileName);
  1111. outMaterial.Save(outFile);
  1112. }
  1113. void CopyTextures(const Set<String>& usedTextures, const String& sourcePath)
  1114. {
  1115. if (useSubdirs_)
  1116. fileSystem_->CreateDir(resourcePath_ + "Textures");
  1117. for (Set<String>::ConstIterator i = usedTextures.Begin(); i != usedTextures.End(); ++i)
  1118. {
  1119. PrintLine("Copying texture " + (*i));
  1120. fileSystem_->Copy(sourcePath + *i, resourcePath_ + (useSubdirs_ ? "Textures/" : "") + *i);
  1121. }
  1122. }
  1123. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName)
  1124. {
  1125. // Load models
  1126. Vector<SharedPtr<Model> > srcModels;
  1127. for (unsigned i = 0; i < modelNames.Size(); ++i)
  1128. {
  1129. PrintLine("Reading LOD level " + String(i) + ": model " + modelNames[i] + " distance " + String(lodDistances[i]));
  1130. File srcFile(context_);
  1131. srcFile.Open(modelNames[i]);
  1132. SharedPtr<Model> srcModel(new Model(context_));
  1133. if (!srcModel->Load(srcFile))
  1134. ErrorExit("Could not load input model " + modelNames[i]);
  1135. srcModels.Push(srcModel);
  1136. }
  1137. // Check that none of the models already has LOD levels
  1138. for (unsigned i = 0; i < srcModels.Size(); ++i)
  1139. {
  1140. for (unsigned j = 0; j < srcModels[i]->GetNumGeometries(); ++j)
  1141. {
  1142. if (srcModels[i]->GetNumGeometryLodLevels(j) > 1)
  1143. ErrorExit(modelNames[i] + " already has multiple LOD levels defined");
  1144. }
  1145. }
  1146. // Check for number of geometries (need to have same amount for now)
  1147. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1148. {
  1149. if (srcModels[i]->GetNumGeometries() != srcModels[0]->GetNumGeometries())
  1150. ErrorExit(modelNames[i] + " has different amount of geometries than " + modelNames[0]);
  1151. }
  1152. // If there are bones, check for compatibility (need to have exact match for now)
  1153. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1154. {
  1155. if (srcModels[i]->GetSkeleton().GetNumBones() != srcModels[0]->GetSkeleton().GetNumBones())
  1156. ErrorExit(modelNames[i] + " has different amount of bones than " + modelNames[0]);
  1157. for (unsigned j = 0; j < srcModels[0]->GetSkeleton().GetNumBones(); ++j)
  1158. {
  1159. if (srcModels[i]->GetSkeleton().GetBone(j)->name_ != srcModels[0]->GetSkeleton().GetBone(j)->name_)
  1160. ErrorExit(modelNames[i] + " has different bones than " + modelNames[0]);
  1161. }
  1162. if (srcModels[i]->GetGeometryBoneMappings() != srcModels[0]->GetGeometryBoneMappings())
  1163. ErrorExit(modelNames[i] + " has different per-geometry bone mappings than " + modelNames[0]);
  1164. }
  1165. // Create the final model
  1166. SharedPtr<Model> outModel(new Model(context_));
  1167. outModel->SetNumGeometries(srcModels[0]->GetNumGeometries());
  1168. for (unsigned i = 0; i < srcModels[0]->GetNumGeometries(); ++i)
  1169. {
  1170. outModel->SetNumGeometryLodLevels(i, srcModels.Size());
  1171. for (unsigned j = 0; j < srcModels.Size(); ++j)
  1172. {
  1173. Geometry* geom = srcModels[j]->GetGeometry(i, 0);
  1174. geom->SetLodDistance(lodDistances[j]);
  1175. outModel->SetGeometry(i, j, geom);
  1176. }
  1177. }
  1178. outModel->SetSkeleton(srcModels[0]->GetSkeleton());
  1179. outModel->SetGeometryBoneMappings(srcModels[0]->GetGeometryBoneMappings());
  1180. outModel->SetBoundingBox(srcModels[0]->GetBoundingBox());
  1181. /// \todo Vertex morphs are ignored for now
  1182. // Save the final model
  1183. PrintLine("Writing output model");
  1184. File outFile(context_);
  1185. if (!outFile.Open(outName, FILE_WRITE))
  1186. ErrorExit("Could not open output file " + outName);
  1187. outModel->Save(outFile);
  1188. }
  1189. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& dest, aiNode* node)
  1190. {
  1191. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  1192. dest.Push(MakePair(node, scene_->mMeshes[node->mMeshes[i]]));
  1193. }
  1194. unsigned GetMeshIndex(aiMesh* mesh)
  1195. {
  1196. for (unsigned i = 0; i < scene_->mNumMeshes; ++i)
  1197. {
  1198. if (scene_->mMeshes[i] == mesh)
  1199. return i;
  1200. }
  1201. return M_MAX_UNSIGNED;
  1202. }
  1203. unsigned GetBoneIndex(OutModel& model, const String& boneName)
  1204. {
  1205. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  1206. {
  1207. if (boneName == model.bones_[i]->mName.data)
  1208. return i;
  1209. }
  1210. return M_MAX_UNSIGNED;
  1211. }
  1212. aiBone* GetMeshBone(OutModel& model, const String& boneName)
  1213. {
  1214. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1215. {
  1216. aiMesh* mesh = model.meshes_[i];
  1217. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1218. {
  1219. aiBone* bone = mesh->mBones[j];
  1220. if (boneName == bone->mName.data)
  1221. return bone;
  1222. }
  1223. }
  1224. return 0;
  1225. }
  1226. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName)
  1227. {
  1228. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1229. {
  1230. aiMesh* mesh = model.meshes_[i];
  1231. aiNode* node = model.meshNodes_[i];
  1232. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1233. {
  1234. aiBone* bone = mesh->mBones[j];
  1235. if (boneName == bone->mName.data)
  1236. {
  1237. aiMatrix4x4 offset = bone->mOffsetMatrix;
  1238. aiMatrix4x4 nodeDerivedInverse = GetMeshBakingTransform(node, model.rootNode_);
  1239. nodeDerivedInverse.Inverse();
  1240. offset *= nodeDerivedInverse;
  1241. Matrix3x4 ret;
  1242. memcpy(&ret.m00_, &offset.a1, sizeof(Matrix3x4));
  1243. return ret;
  1244. }
  1245. }
  1246. }
  1247. return Matrix3x4::IDENTITY;
  1248. }
  1249. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  1250. blendIndices, Vector<PODVector<float> >& blendWeights)
  1251. {
  1252. blendIndices.Resize(mesh->mNumVertices);
  1253. blendWeights.Resize(mesh->mNumVertices);
  1254. boneMappings.Clear();
  1255. // If model has more bones than can fit vertex shader parameters, write the per-geometry mappings
  1256. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  1257. {
  1258. if (mesh->mNumBones > MAX_SKIN_MATRICES)
  1259. ErrorExit("Geometry has too many bone influences");
  1260. boneMappings.Resize(mesh->mNumBones);
  1261. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1262. {
  1263. aiBone* bone = mesh->mBones[i];
  1264. String boneName = FromAIString(bone->mName);
  1265. unsigned globalIndex = GetBoneIndex(model, boneName);
  1266. if (globalIndex == M_MAX_UNSIGNED)
  1267. ErrorExit("Bone " + boneName + " not found");
  1268. boneMappings[i] = globalIndex;
  1269. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1270. {
  1271. unsigned vertex = bone->mWeights[j].mVertexId;
  1272. blendIndices[vertex].Push(i);
  1273. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1274. if (blendWeights[vertex].Size() > 4)
  1275. ErrorExit("More than 4 bone influences on vertex");
  1276. }
  1277. }
  1278. }
  1279. else
  1280. {
  1281. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1282. {
  1283. aiBone* bone = mesh->mBones[i];
  1284. String boneName = FromAIString(bone->mName);
  1285. unsigned globalIndex = GetBoneIndex(model, boneName);
  1286. if (globalIndex == M_MAX_UNSIGNED)
  1287. ErrorExit("Bone " + boneName + " not found");
  1288. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1289. {
  1290. unsigned vertex = bone->mWeights[j].mVertexId;
  1291. blendIndices[vertex].Push(globalIndex);
  1292. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1293. if (blendWeights[vertex].Size() > 4)
  1294. ErrorExit("More than 4 bone influences on vertex");
  1295. }
  1296. }
  1297. }
  1298. }
  1299. String GetMeshMaterialName(aiMesh* mesh)
  1300. {
  1301. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  1302. aiString matNameStr;
  1303. material->Get(AI_MATKEY_NAME, matNameStr);
  1304. String matName = SanitateAssetName(FromAIString(matNameStr));
  1305. if (matName.Empty())
  1306. return matName;
  1307. else
  1308. return (useSubdirs_ ? "Materials/" : "") + matName + ".xml";
  1309. }
  1310. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1311. {
  1312. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1313. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1314. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1315. }
  1316. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1317. {
  1318. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1319. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1320. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1321. }
  1322. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  1323. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  1324. Vector<PODVector<float> >& blendWeights)
  1325. {
  1326. Vector3 vertex = vertexTransform * ToVector3(mesh->mVertices[index]);
  1327. box.Merge(vertex);
  1328. *dest++ = vertex.x_;
  1329. *dest++ = vertex.y_;
  1330. *dest++ = vertex.z_;
  1331. if (elementMask & MASK_NORMAL)
  1332. {
  1333. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1334. *dest++ = normal.x_;
  1335. *dest++ = normal.y_;
  1336. *dest++ = normal.z_;
  1337. }
  1338. if (elementMask & MASK_COLOR)
  1339. {
  1340. *((unsigned*)dest) = Color(mesh->mColors[0][index].r, mesh->mColors[0][index].g, mesh->mColors[0][index].b,
  1341. mesh->mColors[0][index].a).ToUInt();
  1342. ++dest;
  1343. }
  1344. if (elementMask & MASK_TEXCOORD1)
  1345. {
  1346. Vector3 texCoord = ToVector3(mesh->mTextureCoords[0][index]);
  1347. *dest++ = texCoord.x_;
  1348. *dest++ = texCoord.y_;
  1349. }
  1350. if (elementMask & MASK_TEXCOORD2)
  1351. {
  1352. Vector3 texCoord = ToVector3(mesh->mTextureCoords[1][index]);
  1353. *dest++ = texCoord.x_;
  1354. *dest++ = texCoord.y_;
  1355. }
  1356. if (elementMask & MASK_TANGENT)
  1357. {
  1358. Vector3 tangent = normalTransform * ToVector3(mesh->mTangents[index]);
  1359. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1360. Vector3 bitangent = normalTransform * ToVector3(mesh->mBitangents[index]);
  1361. // Check handedness
  1362. float w = 1.0f;
  1363. if ((tangent.CrossProduct(normal)).DotProduct(bitangent) < 0.5f)
  1364. w = -1.0f;
  1365. *dest++ = tangent.x_;
  1366. *dest++ = tangent.y_;
  1367. *dest++ = tangent.z_;
  1368. *dest++ = w;
  1369. }
  1370. if (elementMask & MASK_BLENDWEIGHTS)
  1371. {
  1372. for (unsigned i = 0; i < 4; ++i)
  1373. {
  1374. if (i < blendWeights[index].Size())
  1375. *dest++ = blendWeights[index][i];
  1376. else
  1377. *dest++ = 0.0f;
  1378. }
  1379. }
  1380. if (elementMask & MASK_BLENDINDICES)
  1381. {
  1382. unsigned char* destBytes = (unsigned char*)dest;
  1383. ++dest;
  1384. for (unsigned i = 0; i < 4; ++i)
  1385. {
  1386. if (i < blendIndices[index].Size())
  1387. *destBytes++ = blendIndices[index][i];
  1388. else
  1389. *destBytes++ = 0;
  1390. }
  1391. }
  1392. }
  1393. unsigned GetElementMask(aiMesh* mesh)
  1394. {
  1395. unsigned elementMask = MASK_POSITION;
  1396. if (mesh->HasNormals())
  1397. elementMask |= MASK_NORMAL;
  1398. if (mesh->HasTangentsAndBitangents())
  1399. elementMask |= MASK_TANGENT;
  1400. if (mesh->GetNumColorChannels() > 0)
  1401. elementMask |= MASK_COLOR;
  1402. if (mesh->GetNumUVChannels() > 0)
  1403. elementMask |= MASK_TEXCOORD1;
  1404. if (mesh->GetNumUVChannels() > 1)
  1405. elementMask |= MASK_TEXCOORD2;
  1406. if (mesh->HasBones())
  1407. elementMask |= (MASK_BLENDWEIGHTS | MASK_BLENDINDICES);
  1408. return elementMask;
  1409. }
  1410. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive)
  1411. {
  1412. if (!rootNode)
  1413. return 0;
  1414. if (!name.Compare(rootNode->mName.data, caseSensitive))
  1415. return rootNode;
  1416. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  1417. {
  1418. aiNode* found = GetNode(name, rootNode->mChildren[i], caseSensitive);
  1419. if (found)
  1420. return found;
  1421. }
  1422. return 0;
  1423. }
  1424. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode)
  1425. {
  1426. return GetDerivedTransform(node->mTransformation, node, rootNode);
  1427. }
  1428. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode)
  1429. {
  1430. // If basenode is defined, go only up to it in the parent chain
  1431. while (node && node != rootNode)
  1432. {
  1433. node = node->mParent;
  1434. if (node)
  1435. transform = node->mTransformation * transform;
  1436. }
  1437. return transform;
  1438. }
  1439. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode)
  1440. {
  1441. if (meshNode == modelRootNode)
  1442. return aiMatrix4x4();
  1443. else
  1444. return GetDerivedTransform(meshNode, modelRootNode);
  1445. }
  1446. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale)
  1447. {
  1448. aiVector3D aiPos;
  1449. aiQuaternion aiRot;
  1450. aiVector3D aiScale;
  1451. transform.Decompose(aiScale, aiRot, aiPos);
  1452. pos = ToVector3(aiPos);
  1453. rot = ToQuaternion(aiRot);
  1454. scale = ToVector3(aiScale);
  1455. }
  1456. String FromAIString(const aiString& str)
  1457. {
  1458. return String(str.data);
  1459. }
  1460. Vector3 ToVector3(const aiVector3D& vec)
  1461. {
  1462. return Vector3(vec.x, vec.y, vec.z);
  1463. }
  1464. Vector2 ToVector2(const aiVector2D& vec)
  1465. {
  1466. return Vector2(vec.x, vec.y);
  1467. }
  1468. Quaternion ToQuaternion(const aiQuaternion& quat)
  1469. {
  1470. return Quaternion(quat.w, quat.x, quat.y, quat.z);
  1471. }
  1472. String SanitateAssetName(const String& name)
  1473. {
  1474. String fixedName = name;
  1475. fixedName.Replace("<", "");
  1476. fixedName.Replace(">", "");
  1477. fixedName.Replace("?", "");
  1478. fixedName.Replace("*", "");
  1479. fixedName.Replace(":", "");
  1480. fixedName.Replace("\"", "");
  1481. fixedName.Replace("/", "");
  1482. fixedName.Replace("\\", "");
  1483. fixedName.Replace("|", "");
  1484. return fixedName;
  1485. }