AssetImporter.cpp 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Atomic/Atomic.h>
  23. #include <Atomic/Graphics/AnimatedModel.h>
  24. #include <Atomic/Graphics/Animation.h>
  25. #include <Atomic/Core/Context.h>
  26. #include <Atomic/Graphics/DebugRenderer.h>
  27. #include <Atomic/IO/File.h>
  28. #include <Atomic/IO/FileSystem.h>
  29. #include <Atomic/Graphics/Geometry.h>
  30. #include <Atomic/Graphics/Graphics.h>
  31. #include <Atomic/Graphics/IndexBuffer.h>
  32. #include <Atomic/Graphics/Light.h>
  33. #include <Atomic/Graphics/Material.h>
  34. #include <Atomic/Graphics/Model.h>
  35. #include <Atomic/Graphics/Octree.h>
  36. #ifdef ATOMIC_PHYSICS
  37. #include <Atomic/Physics/PhysicsWorld.h>
  38. #endif
  39. #include <Atomic/Core/ProcessUtils.h>
  40. #include <Atomic/Math/Quaternion.h>
  41. #include <Atomic/Resource/ResourceCache.h>
  42. #include <Atomic/Scene/Scene.h>
  43. #include <Atomic/Core/StringUtils.h>
  44. #include <Atomic/Math/Vector3.h>
  45. #include <Atomic/Graphics/VertexBuffer.h>
  46. #include <Atomic/Core/WorkQueue.h>
  47. #include <Atomic/Resource/XMLFile.h>
  48. #include <Atomic/Graphics/Zone.h>
  49. #include <Atomic/Container/Sort.h>
  50. #ifdef WIN32
  51. #include <windows.h>
  52. #endif
  53. #include <assimp/cimport.h>
  54. #include <assimp/scene.h>
  55. #include <assimp/postprocess.h>
  56. #include <assimp/DefaultLogger.hpp>
  57. #include <cstring>
  58. #include <Atomic/DebugNew.h>
  59. using namespace Atomic;
  60. struct OutModel
  61. {
  62. OutModel() :
  63. rootBone_(0),
  64. totalVertices_(0),
  65. totalIndices_(0)
  66. {
  67. }
  68. String outName_;
  69. aiNode* rootNode_;
  70. HashSet<unsigned> meshIndices_;
  71. PODVector<aiMesh*> meshes_;
  72. PODVector<aiNode*> meshNodes_;
  73. PODVector<aiNode*> bones_;
  74. PODVector<aiAnimation*> animations_;
  75. PODVector<float> boneRadii_;
  76. PODVector<BoundingBox> boneHitboxes_;
  77. aiNode* rootBone_;
  78. unsigned totalVertices_;
  79. unsigned totalIndices_;
  80. };
  81. struct OutScene
  82. {
  83. String outName_;
  84. aiNode* rootNode_;
  85. Vector<OutModel> models_;
  86. PODVector<aiNode*> nodes_;
  87. PODVector<unsigned> nodeModelIndices_;
  88. };
  89. SharedPtr<Context> context_(new Context());
  90. const aiScene* scene_ = 0;
  91. aiNode* rootNode_ = 0;
  92. String inputName_;
  93. String resourcePath_;
  94. String outPath_;
  95. bool useSubdirs_ = true;
  96. bool localIDs_ = false;
  97. bool saveBinary_ = false;
  98. bool createZone_ = true;
  99. bool noAnimations_ = false;
  100. bool noHierarchy_ = false;
  101. bool noMaterials_ = false;
  102. bool noTextures_ = false;
  103. bool noMaterialDiffuseColor_ = false;
  104. bool noEmptyNodes_ = false;
  105. bool saveMaterialList_ = false;
  106. bool includeNonSkinningBones_ = false;
  107. bool verboseLog_ = false;
  108. bool emissiveAO_ = false;
  109. bool noOverwriteMaterial_ = false;
  110. bool noOverwriteTexture_ = false;
  111. bool noOverwriteNewerTexture_ = false;
  112. bool checkUniqueModel_ = true;
  113. unsigned maxBones_ = 64;
  114. Vector<String> nonSkinningBoneIncludes_;
  115. Vector<String> nonSkinningBoneExcludes_;
  116. HashSet<aiAnimation*> allAnimations_;
  117. PODVector<aiAnimation*> sceneAnimations_;
  118. float defaultTicksPerSecond_ = 4800.0f;
  119. int main(int argc, char** argv);
  120. void Run(const Vector<String>& arguments);
  121. void DumpNodes(aiNode* rootNode, unsigned level);
  122. void ExportModel(const String& outName, bool animationOnly);
  123. void CollectMeshes(OutModel& model, aiNode* node);
  124. void CollectBones(OutModel& model, bool animationOnly = false);
  125. void CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node);
  126. void CollectAnimations(OutModel* model = 0);
  127. void BuildBoneCollisionInfo(OutModel& model);
  128. void BuildAndSaveModel(OutModel& model);
  129. void BuildAndSaveAnimations(OutModel* model = 0);
  130. void ExportScene(const String& outName, bool asPrefab);
  131. void CollectSceneModels(OutScene& scene, aiNode* node);
  132. void CreateHierarchy(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping);
  133. Node* CreateSceneNode(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping);
  134. void BuildAndSaveScene(OutScene& scene, bool asPrefab);
  135. void ExportMaterials(HashSet<String>& usedTextures);
  136. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures);
  137. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath);
  138. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName);
  139. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& meshes, aiNode* node);
  140. unsigned GetMeshIndex(aiMesh* mesh);
  141. unsigned GetBoneIndex(OutModel& model, const String& boneName);
  142. aiBone* GetMeshBone(OutModel& model, const String& boneName);
  143. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName);
  144. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  145. blendIndices, Vector<PODVector<float> >& blendWeights);
  146. String GetMeshMaterialName(aiMesh* mesh);
  147. String GetMaterialTextureName(const String& nameIn);
  148. String GenerateMaterialName(aiMaterial* material);
  149. String GenerateTextureName(unsigned texIndex);
  150. unsigned GetNumValidFaces(aiMesh* mesh);
  151. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  152. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  153. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  154. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  155. Vector<PODVector<float> >& blendWeights);
  156. unsigned GetElementMask(aiMesh* mesh);
  157. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive = true);
  158. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode, bool rootInclusive = true);
  159. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode, bool rootInclusive = true);
  160. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode);
  161. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale);
  162. String FromAIString(const aiString& str);
  163. Vector3 ToVector3(const aiVector3D& vec);
  164. Vector2 ToVector2(const aiVector2D& vec);
  165. Quaternion ToQuaternion(const aiQuaternion& quat);
  166. Matrix3x4 ToMatrix3x4(const aiMatrix4x4& mat);
  167. String SanitateAssetName(const String& name);
  168. int main(int argc, char** argv)
  169. {
  170. Vector<String> arguments;
  171. #ifdef WIN32
  172. arguments = ParseArguments(GetCommandLineW());
  173. #else
  174. arguments = ParseArguments(argc, argv);
  175. #endif
  176. Run(arguments);
  177. return 0;
  178. }
  179. void Run(const Vector<String>& arguments)
  180. {
  181. if (arguments.Size() < 2)
  182. {
  183. ErrorExit(
  184. "Usage: AssetImporter <command> <input file> <output file> [options]\n"
  185. "See http://assimp.sourceforge.net/main_features_formats.html for input formats\n\n"
  186. "Commands:\n"
  187. "model Output a model\n"
  188. "scene Output a scene\n"
  189. "node Output a node and its children (prefab)\n"
  190. "dump Dump scene node structure. No output file is generated\n"
  191. "lod Combine several Urho3D models as LOD levels of the output model\n"
  192. " Syntax: lod <dist0> <mdl0> <dist1 <mdl1> ... <output file>\n"
  193. "\n"
  194. "Options:\n"
  195. "-b Save scene in binary format, default format is XML\n"
  196. "-h Generate hard instead of smooth normals if input file has no normals\n"
  197. "-i Use local ID's for scene nodes\n"
  198. "-l Output a material list file for models\n"
  199. "-na Do not output animations\n"
  200. "-nm Do not output materials\n"
  201. "-nt Do not output material textures\n"
  202. "-nc Do not use material diffuse color value, instead output white\n"
  203. "-nh Do not save full node hierarchy (scene mode only)\n"
  204. "-ns Do not create subdirectories for resources\n"
  205. "-nz Do not create a zone and a directional light (scene mode only)\n"
  206. "-nf Do not fix infacing normals\n"
  207. "-ne Do not save empty nodes (scene mode only)\n"
  208. "-mb <x> Maximum number of bones per submesh. Default 64\n"
  209. "-p <path> Set path for scene resources. Default is output file path\n"
  210. "-r <name> Use the named scene node as root node\n"
  211. "-f <freq> Animation tick frequency to use if unspecified. Default 4800\n"
  212. "-o Optimize redundant submeshes. Loses scene hierarchy and animations\n"
  213. "-s <filter> Include non-skinning bones in the model's skeleton. Can be given a\n"
  214. " case-insensitive semicolon separated filter list. Bone is included\n"
  215. " if its name contains any of the filters. Prefix filter with minus\n"
  216. " sign to use as an exclude. For example -s \"Bip01;-Dummy;-Helper\"\n"
  217. "-t Generate tangents\n"
  218. "-v Enable verbose Assimp library logging\n"
  219. "-eao Interpret material emissive texture as ambient occlusion\n"
  220. "-cm Check and do not overwrite if material exists\n"
  221. "-ct Check and do not overwrite if texture exists\n"
  222. "-ctn Check and do not overwrite if texture has newer timestamp\n"
  223. "-am Export all meshes even if identical (scene mode only)\n"
  224. );
  225. }
  226. context_->RegisterSubsystem(new FileSystem(context_));
  227. context_->RegisterSubsystem(new ResourceCache(context_));
  228. context_->RegisterSubsystem(new WorkQueue(context_));
  229. RegisterSceneLibrary(context_);
  230. RegisterGraphicsLibrary(context_);
  231. #ifdef ATOMIC_PHYSICS
  232. RegisterPhysicsLibrary(context_);
  233. #endif
  234. String command = arguments[0].ToLower();
  235. String rootNodeName;
  236. unsigned flags =
  237. aiProcess_ConvertToLeftHanded |
  238. aiProcess_JoinIdenticalVertices |
  239. aiProcess_Triangulate |
  240. aiProcess_GenSmoothNormals |
  241. aiProcess_LimitBoneWeights |
  242. aiProcess_ImproveCacheLocality |
  243. aiProcess_RemoveRedundantMaterials |
  244. aiProcess_FixInfacingNormals |
  245. aiProcess_FindInvalidData |
  246. aiProcess_GenUVCoords |
  247. aiProcess_FindInstances |
  248. aiProcess_OptimizeMeshes;
  249. for (unsigned i = 2; i < arguments.Size(); ++i)
  250. {
  251. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  252. {
  253. String argument = arguments[i].Substring(1).ToLower();
  254. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  255. if (argument == "b")
  256. saveBinary_ = true;
  257. else if (argument == "h")
  258. {
  259. flags &= ~aiProcess_GenSmoothNormals;
  260. flags |= aiProcess_GenNormals;
  261. }
  262. else if (argument == "i")
  263. localIDs_ = true;
  264. else if (argument == "l")
  265. saveMaterialList_ = true;
  266. else if (argument == "t")
  267. flags |= aiProcess_CalcTangentSpace;
  268. else if (argument == "o")
  269. flags |= aiProcess_PreTransformVertices;
  270. else if (argument.Length() == 2 && argument[0] == 'n')
  271. {
  272. switch (tolower(argument[1]))
  273. {
  274. case 'a':
  275. noAnimations_ = true;
  276. break;
  277. case 'c':
  278. noMaterialDiffuseColor_ = true;
  279. break;
  280. case 'm':
  281. noMaterials_ = true;
  282. break;
  283. case 'h':
  284. noHierarchy_ = true;
  285. break;
  286. case 'e':
  287. noEmptyNodes_ = true;
  288. break;
  289. case 's':
  290. useSubdirs_ = false;
  291. break;
  292. case 't':
  293. noTextures_ = true;
  294. break;
  295. case 'z':
  296. createZone_ = false;
  297. break;
  298. case 'f':
  299. flags &= ~aiProcess_FixInfacingNormals;
  300. break;
  301. }
  302. }
  303. else if (argument == "mb" && !value.Empty())
  304. {
  305. maxBones_ = ToUInt(value);
  306. if (maxBones_ < 1)
  307. maxBones_ = 1;
  308. ++i;
  309. }
  310. else if (argument == "p" && !value.Empty())
  311. {
  312. resourcePath_ = AddTrailingSlash(value);
  313. ++i;
  314. }
  315. else if (argument == "r" && !value.Empty())
  316. {
  317. rootNodeName = value;
  318. ++i;
  319. }
  320. else if (argument == "f" && !value.Empty())
  321. {
  322. defaultTicksPerSecond_ = ToFloat(value);
  323. ++i;
  324. }
  325. else if (argument == "s")
  326. {
  327. includeNonSkinningBones_ = true;
  328. if (value.Length() && (value[0] != '-' || value.Length() > 3))
  329. {
  330. Vector<String> filters = value.Split(';');
  331. for (unsigned i = 0; i < filters.Size(); ++i)
  332. {
  333. if (filters[i][0] == '-')
  334. nonSkinningBoneExcludes_.Push(filters[i].Substring(1));
  335. else
  336. nonSkinningBoneIncludes_.Push(filters[i]);
  337. }
  338. }
  339. }
  340. else if (argument == "v")
  341. verboseLog_ = true;
  342. else if (argument == "eao")
  343. emissiveAO_ = true;
  344. else if (argument == "cm")
  345. noOverwriteMaterial_ = true;
  346. else if (argument == "ct")
  347. noOverwriteTexture_ = true;
  348. else if (argument == "ctn")
  349. noOverwriteNewerTexture_ = true;
  350. else if (argument == "am")
  351. checkUniqueModel_ = false;
  352. }
  353. }
  354. if (command == "model" || command == "scene" || command == "node" || command == "dump")
  355. {
  356. String inFile = arguments[1];
  357. String outFile;
  358. if (arguments.Size() > 2 && arguments[2][0] != '-')
  359. outFile = GetInternalPath(arguments[2]);
  360. inputName_ = GetFileName(inFile);
  361. outPath_ = GetPath(outFile);
  362. if (resourcePath_.Empty())
  363. {
  364. resourcePath_ = outPath_;
  365. // If output file already has the Models/ path (model mode), do not take it into the resource path
  366. if (command == "model")
  367. {
  368. if (resourcePath_.EndsWith("Models/", false))
  369. resourcePath_ = resourcePath_.Substring(0, resourcePath_.Length() - 7);
  370. }
  371. if (resourcePath_.Empty())
  372. resourcePath_ = "./";
  373. }
  374. resourcePath_ = AddTrailingSlash(resourcePath_);
  375. if (command != "dump" && outFile.Empty())
  376. ErrorExit("No output file defined");
  377. if (verboseLog_)
  378. Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE, aiDefaultLogStream_STDOUT);
  379. PrintLine("Reading file " + inFile);
  380. scene_ = aiImportFile(GetNativePath(inFile).CString(), flags);
  381. if (!scene_)
  382. ErrorExit("Could not open or parse input file " + inFile + ": " + String(aiGetErrorString()));
  383. if (verboseLog_)
  384. Assimp::DefaultLogger::kill();
  385. rootNode_ = scene_->mRootNode;
  386. if (!rootNodeName.Empty())
  387. {
  388. rootNode_ = GetNode(rootNodeName, rootNode_, false);
  389. if (!rootNode_)
  390. ErrorExit("Could not find scene node " + rootNodeName);
  391. }
  392. if (command == "dump")
  393. {
  394. DumpNodes(rootNode_, 0);
  395. return;
  396. }
  397. if (command == "model")
  398. ExportModel(outFile, scene_->mFlags & AI_SCENE_FLAGS_INCOMPLETE);
  399. if (command == "scene" || command == "node")
  400. {
  401. bool asPrefab = command == "node";
  402. // Saving as prefab requires the hierarchy, especially the root node
  403. if (asPrefab)
  404. noHierarchy_ = false;
  405. ExportScene(outFile, asPrefab);
  406. }
  407. if (!noMaterials_)
  408. {
  409. HashSet<String> usedTextures;
  410. ExportMaterials(usedTextures);
  411. if (!noTextures_)
  412. CopyTextures(usedTextures, GetPath(inFile));
  413. }
  414. }
  415. else if (command == "lod")
  416. {
  417. PODVector<float> lodDistances;
  418. Vector<String> modelNames;
  419. String outFile;
  420. unsigned numLodArguments = 0;
  421. for (unsigned i = 1; i < arguments.Size(); ++i)
  422. {
  423. if (arguments[i][0] == '-')
  424. break;
  425. ++numLodArguments;
  426. }
  427. if (numLodArguments < 4)
  428. ErrorExit("Must define at least 2 LOD levels");
  429. if (!(numLodArguments & 1))
  430. ErrorExit("No output file defined");
  431. for (unsigned i = 1; i < numLodArguments + 1; ++i)
  432. {
  433. if (i == numLodArguments)
  434. outFile = GetInternalPath(arguments[i]);
  435. else
  436. {
  437. if (i & 1)
  438. lodDistances.Push(Max(ToFloat(arguments[i]), 0.0f));
  439. else
  440. modelNames.Push(GetInternalPath(arguments[i]));
  441. }
  442. }
  443. if (lodDistances[0] != 0.0f)
  444. {
  445. PrintLine("Warning: first LOD distance forced to 0");
  446. lodDistances[0] = 0.0f;
  447. }
  448. CombineLods(lodDistances, modelNames, outFile);
  449. }
  450. else
  451. ErrorExit("Unrecognized command " + command);
  452. }
  453. void DumpNodes(aiNode* rootNode, unsigned level)
  454. {
  455. if (!rootNode)
  456. return;
  457. String indent(' ', level * 2);
  458. Vector3 pos, scale;
  459. Quaternion rot;
  460. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  461. GetPosRotScale(transform, pos, rot, scale);
  462. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  463. if (rootNode->mNumMeshes == 1)
  464. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  465. if (rootNode->mNumMeshes > 1)
  466. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  467. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  468. DumpNodes(rootNode->mChildren[i], level + 1);
  469. }
  470. void ExportModel(const String& outName, bool animationOnly)
  471. {
  472. if (outName.Empty())
  473. ErrorExit("No output file defined");
  474. OutModel model;
  475. model.rootNode_ = rootNode_;
  476. model.outName_ = outName;
  477. CollectMeshes(model, model.rootNode_);
  478. CollectBones(model, animationOnly);
  479. BuildBoneCollisionInfo(model);
  480. BuildAndSaveModel(model);
  481. if (!noAnimations_)
  482. {
  483. CollectAnimations(&model);
  484. BuildAndSaveAnimations(&model);
  485. // Save scene-global animations
  486. CollectAnimations();
  487. BuildAndSaveAnimations();
  488. }
  489. }
  490. void CollectMeshes(OutModel& model, aiNode* node)
  491. {
  492. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  493. {
  494. aiMesh* mesh = scene_->mMeshes[node->mMeshes[i]];
  495. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  496. {
  497. if (mesh == model.meshes_[j])
  498. {
  499. PrintLine("Warning: same mesh found multiple times");
  500. break;
  501. }
  502. }
  503. model.meshIndices_.Insert(node->mMeshes[i]);
  504. model.meshes_.Push(mesh);
  505. model.meshNodes_.Push(node);
  506. model.totalVertices_ += mesh->mNumVertices;
  507. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  508. }
  509. for (unsigned i = 0; i < node->mNumChildren; ++i)
  510. CollectMeshes(model, node->mChildren[i]);
  511. }
  512. void CollectBones(OutModel& model, bool animationOnly)
  513. {
  514. HashSet<aiNode*> necessary;
  515. HashSet<aiNode*> rootNodes;
  516. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  517. {
  518. aiMesh* mesh = model.meshes_[i];
  519. aiNode* meshNode = model.meshNodes_[i];
  520. aiNode* meshParentNode = meshNode->mParent;
  521. aiNode* rootNode = 0;
  522. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  523. {
  524. aiBone* bone = mesh->mBones[j];
  525. String boneName(FromAIString(bone->mName));
  526. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  527. if (!boneNode)
  528. ErrorExit("Could not find scene node for bone " + boneName);
  529. necessary.Insert(boneNode);
  530. rootNode = boneNode;
  531. for (;;)
  532. {
  533. boneNode = boneNode->mParent;
  534. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  535. break;
  536. rootNode = boneNode;
  537. necessary.Insert(boneNode);
  538. }
  539. if (rootNodes.Find(rootNode) == rootNodes.End())
  540. rootNodes.Insert(rootNode);
  541. }
  542. }
  543. // If we find multiple root nodes, try to remedy by using their parent instead
  544. if (rootNodes.Size() > 1)
  545. {
  546. aiNode* commonParent = (*rootNodes.Begin())->mParent;
  547. for (HashSet<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  548. {
  549. if (*i != commonParent)
  550. {
  551. if (!commonParent || (*i)->mParent != commonParent)
  552. ErrorExit("Skeleton with multiple root nodes found, not supported");
  553. }
  554. }
  555. rootNodes.Clear();
  556. rootNodes.Insert(commonParent);
  557. necessary.Insert(commonParent);
  558. }
  559. if (rootNodes.Empty())
  560. return;
  561. model.rootBone_ = *rootNodes.Begin();
  562. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  563. // Initialize the bone collision info
  564. model.boneRadii_.Resize(model.bones_.Size());
  565. model.boneHitboxes_.Resize(model.bones_.Size());
  566. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  567. {
  568. model.boneRadii_[i] = 0.0f;
  569. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  570. }
  571. }
  572. void CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node)
  573. {
  574. bool includeBone = necessary.Find(node) != necessary.End();
  575. String boneName = FromAIString(node->mName);
  576. // Check include/exclude filters for non-skinned bones
  577. if (!includeBone && includeNonSkinningBones_)
  578. {
  579. // If no includes specified, include by default but check for excludes
  580. if (nonSkinningBoneIncludes_.Empty())
  581. includeBone = true;
  582. // Check against includes/excludes
  583. for (unsigned i = 0; i < nonSkinningBoneIncludes_.Size(); ++i)
  584. {
  585. if (boneName.Contains(nonSkinningBoneIncludes_[i], false))
  586. {
  587. includeBone = true;
  588. break;
  589. }
  590. }
  591. for (unsigned i = 0; i < nonSkinningBoneExcludes_.Size(); ++i)
  592. {
  593. if (boneName.Contains(nonSkinningBoneExcludes_[i], false))
  594. {
  595. includeBone = false;
  596. break;
  597. }
  598. }
  599. if (includeBone)
  600. PrintLine("Including non-skinning bone " + boneName);
  601. }
  602. if (includeBone)
  603. dest.Push(node);
  604. for (unsigned i = 0; i < node->mNumChildren; ++i)
  605. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  606. }
  607. void CollectAnimations(OutModel* model)
  608. {
  609. const aiScene* scene = scene_;
  610. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  611. {
  612. aiAnimation* anim = scene->mAnimations[i];
  613. if (allAnimations_.Contains(anim))
  614. continue;
  615. if (model)
  616. {
  617. bool modelBoneFound = false;
  618. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  619. {
  620. aiNodeAnim* channel = anim->mChannels[j];
  621. String channelName = FromAIString(channel->mNodeName);
  622. if (GetBoneIndex(*model, channelName) != M_MAX_UNSIGNED)
  623. {
  624. modelBoneFound = true;
  625. break;
  626. }
  627. }
  628. if (modelBoneFound)
  629. {
  630. model->animations_.Push(anim);
  631. allAnimations_.Insert(anim);
  632. }
  633. }
  634. else
  635. {
  636. sceneAnimations_.Push(anim);
  637. allAnimations_.Insert(anim);
  638. }
  639. }
  640. /// \todo Vertex morphs are ignored for now
  641. }
  642. void BuildBoneCollisionInfo(OutModel& model)
  643. {
  644. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  645. {
  646. aiMesh* mesh = model.meshes_[i];
  647. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  648. {
  649. aiBone* bone = mesh->mBones[j];
  650. String boneName = FromAIString(bone->mName);
  651. unsigned boneIndex = GetBoneIndex(model, boneName);
  652. if (boneIndex == M_MAX_UNSIGNED)
  653. continue;
  654. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  655. {
  656. float weight = bone->mWeights[k].mWeight;
  657. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  658. if (weight > 0.33f)
  659. {
  660. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  661. Vector3 vertex = ToVector3(vertexBoneSpace);
  662. float radius = vertex.Length();
  663. if (radius > model.boneRadii_[boneIndex])
  664. model.boneRadii_[boneIndex] = radius;
  665. model.boneHitboxes_[boneIndex].Merge(vertex);
  666. }
  667. }
  668. }
  669. }
  670. }
  671. void BuildAndSaveModel(OutModel& model)
  672. {
  673. if (!model.rootNode_)
  674. ErrorExit("Null root node for model");
  675. String rootNodeName = FromAIString(model.rootNode_->mName);
  676. if (!model.meshes_.Size())
  677. ErrorExit("No geometries found starting from node " + rootNodeName);
  678. PrintLine("Writing model " + rootNodeName);
  679. SharedPtr<Model> outModel(new Model(context_));
  680. Vector<PODVector<unsigned> > allBoneMappings;
  681. BoundingBox box;
  682. unsigned numValidGeometries = 0;
  683. bool combineBuffers = true;
  684. // Check if buffers can be combined (same vertex element mask, under 65535 vertices)
  685. unsigned elementMask = GetElementMask(model.meshes_[0]);
  686. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  687. {
  688. if (GetNumValidFaces(model.meshes_[i]))
  689. {
  690. ++numValidGeometries;
  691. if (i > 0 && GetElementMask(model.meshes_[i]) != elementMask)
  692. combineBuffers = false;
  693. }
  694. }
  695. // Check if keeping separate buffers allows to avoid 32-bit indices
  696. if (combineBuffers && model.totalVertices_ > 65535)
  697. {
  698. bool allUnder65k = true;
  699. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  700. {
  701. if (GetNumValidFaces(model.meshes_[i]))
  702. {
  703. if (model.meshes_[i]->mNumVertices > 65535)
  704. allUnder65k = false;
  705. }
  706. }
  707. if (allUnder65k == true)
  708. combineBuffers = false;
  709. }
  710. SharedPtr<IndexBuffer> ib;
  711. SharedPtr<VertexBuffer> vb;
  712. Vector<SharedPtr<VertexBuffer> > vbVector;
  713. Vector<SharedPtr<IndexBuffer> > ibVector;
  714. unsigned startVertexOffset = 0;
  715. unsigned startIndexOffset = 0;
  716. unsigned destGeomIndex = 0;
  717. outModel->SetNumGeometries(numValidGeometries);
  718. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  719. {
  720. aiMesh* mesh = model.meshes_[i];
  721. unsigned elementMask = GetElementMask(mesh);
  722. unsigned validFaces = GetNumValidFaces(mesh);
  723. if (!validFaces)
  724. continue;
  725. bool largeIndices;
  726. if (combineBuffers)
  727. largeIndices = model.totalIndices_ > 65535;
  728. else
  729. largeIndices = mesh->mNumVertices > 65535;
  730. // Create new buffers if necessary
  731. if (!combineBuffers || vbVector.Empty())
  732. {
  733. vb = new VertexBuffer(context_);
  734. ib = new IndexBuffer(context_);
  735. if (combineBuffers)
  736. {
  737. ib->SetSize(model.totalIndices_, largeIndices);
  738. vb->SetSize(model.totalVertices_, elementMask);
  739. }
  740. else
  741. {
  742. ib->SetSize(validFaces * 3, largeIndices);
  743. vb->SetSize(mesh->mNumVertices, elementMask);
  744. }
  745. vbVector.Push(vb);
  746. ibVector.Push(ib);
  747. startVertexOffset = 0;
  748. startIndexOffset = 0;
  749. }
  750. // Get the world transform of the mesh for baking into the vertices
  751. Matrix3x4 vertexTransform;
  752. Matrix3 normalTransform;
  753. Vector3 pos, scale;
  754. Quaternion rot;
  755. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  756. vertexTransform = Matrix3x4(pos, rot, scale);
  757. normalTransform = rot.RotationMatrix();
  758. SharedPtr<Geometry> geom(new Geometry(context_));
  759. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  760. String(validFaces * 3) + " indices");
  761. unsigned char* vertexData = vb->GetShadowData();
  762. unsigned char* indexData = ib->GetShadowData();
  763. // Build the index data
  764. if (!largeIndices)
  765. {
  766. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  767. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  768. WriteShortIndices(dest, mesh, j, startVertexOffset);
  769. }
  770. else
  771. {
  772. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  773. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  774. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  775. }
  776. // Build the vertex data
  777. // If there are bones, get blend data
  778. Vector<PODVector<unsigned char> > blendIndices;
  779. Vector<PODVector<float> > blendWeights;
  780. PODVector<unsigned> boneMappings;
  781. if (model.bones_.Size())
  782. GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights);
  783. float* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  784. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  785. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  786. // Calculate the geometry center
  787. Vector3 center = Vector3::ZERO;
  788. if (validFaces)
  789. {
  790. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  791. {
  792. if (mesh->mFaces[j].mNumIndices == 3)
  793. {
  794. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  795. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  796. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  797. }
  798. }
  799. center /= (float)validFaces * 3;
  800. }
  801. // Define the geometry
  802. geom->SetIndexBuffer(ib);
  803. geom->SetVertexBuffer(0, vb);
  804. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, validFaces * 3, true);
  805. outModel->SetNumGeometryLodLevels(destGeomIndex, 1);
  806. outModel->SetGeometry(destGeomIndex, 0, geom);
  807. outModel->SetGeometryCenter(destGeomIndex, center);
  808. if (model.bones_.Size() > maxBones_)
  809. allBoneMappings.Push(boneMappings);
  810. startVertexOffset += mesh->mNumVertices;
  811. startIndexOffset += validFaces * 3;
  812. ++destGeomIndex;
  813. }
  814. // Define the model buffers and bounding box
  815. PODVector<unsigned> emptyMorphRange;
  816. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  817. outModel->SetIndexBuffers(ibVector);
  818. outModel->SetBoundingBox(box);
  819. // Build skeleton if necessary
  820. if (model.bones_.Size() && model.rootBone_)
  821. {
  822. PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  823. FromAIString(model.rootBone_->mName));
  824. Skeleton skeleton;
  825. Vector<Bone>& bones = skeleton.GetModifiableBones();
  826. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  827. {
  828. aiNode* boneNode = model.bones_[i];
  829. String boneName(FromAIString(boneNode->mName));
  830. Bone newBone;
  831. newBone.name_ = boneName;
  832. aiMatrix4x4 transform = boneNode->mTransformation;
  833. // Make the root bone transform relative to the model's root node, if it is not already
  834. if (boneNode == model.rootBone_)
  835. transform = GetDerivedTransform(boneNode, model.rootNode_);
  836. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  837. // Get offset information if exists
  838. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  839. newBone.radius_ = model.boneRadii_[i];
  840. newBone.boundingBox_ = model.boneHitboxes_[i];
  841. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  842. newBone.parentIndex_ = i;
  843. bones.Push(newBone);
  844. }
  845. // Set the bone hierarchy
  846. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  847. {
  848. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  849. for (unsigned j = 0; j < bones.Size(); ++j)
  850. {
  851. if (bones[j].name_ == parentName)
  852. {
  853. bones[i].parentIndex_ = j;
  854. break;
  855. }
  856. }
  857. }
  858. outModel->SetSkeleton(skeleton);
  859. if (model.bones_.Size() > maxBones_)
  860. outModel->SetGeometryBoneMappings(allBoneMappings);
  861. }
  862. File outFile(context_);
  863. if (!outFile.Open(model.outName_, FILE_WRITE))
  864. ErrorExit("Could not open output file " + model.outName_);
  865. outModel->Save(outFile);
  866. // If exporting materials, also save material list for use by the editor
  867. if (!noMaterials_ && saveMaterialList_)
  868. {
  869. String materialListName = ReplaceExtension(model.outName_, ".txt");
  870. File listFile(context_);
  871. if (listFile.Open(materialListName, FILE_WRITE))
  872. {
  873. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  874. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  875. }
  876. else
  877. PrintLine("Warning: could not write material list file " + materialListName);
  878. }
  879. }
  880. void BuildAndSaveAnimations(OutModel* model)
  881. {
  882. const PODVector<aiAnimation*>& animations = model ? model->animations_ : sceneAnimations_;
  883. for (unsigned i = 0; i < animations.Size(); ++i)
  884. {
  885. aiAnimation* anim = animations[i];
  886. float duration = (float)anim->mDuration;
  887. String animName = FromAIString(anim->mName);
  888. String animOutName;
  889. if (animName.Empty())
  890. animName = "Anim" + String(i + 1);
  891. if (model)
  892. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + SanitateAssetName(animName) + ".ani";
  893. else
  894. animOutName = outPath_ + SanitateAssetName(animName) + ".ani";
  895. float ticksPerSecond = (float)anim->mTicksPerSecond;
  896. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  897. if (ticksPerSecond < M_EPSILON)
  898. ticksPerSecond = defaultTicksPerSecond_;
  899. float tickConversion = 1.0f / ticksPerSecond;
  900. // Find out the start time of animation from each channel's first keyframe for adjusting the keyframe times
  901. // to start from zero
  902. float startTime = duration;
  903. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  904. {
  905. aiNodeAnim* channel = anim->mChannels[j];
  906. if (channel->mNumPositionKeys > 0)
  907. startTime = Min(startTime, (float)channel->mPositionKeys[0].mTime);
  908. if (channel->mNumRotationKeys > 0)
  909. startTime = Min(startTime, (float)channel->mRotationKeys[0].mTime);
  910. if (channel->mScalingKeys > 0)
  911. startTime = Min(startTime, (float)channel->mScalingKeys[0].mTime);
  912. }
  913. duration -= startTime;
  914. SharedPtr<Animation> outAnim(new Animation(context_));
  915. outAnim->SetAnimationName(animName);
  916. outAnim->SetLength(duration * tickConversion);
  917. PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  918. Vector<AnimationTrack> tracks;
  919. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  920. {
  921. aiNodeAnim* channel = anim->mChannels[j];
  922. String channelName = FromAIString(channel->mNodeName);
  923. aiNode* boneNode = 0;
  924. bool isRootBone = false;
  925. if (model)
  926. {
  927. unsigned boneIndex = GetBoneIndex(*model, channelName);
  928. if (boneIndex == M_MAX_UNSIGNED)
  929. {
  930. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  931. continue;
  932. }
  933. boneNode = model->bones_[boneIndex];
  934. isRootBone = boneIndex == 0;
  935. }
  936. else
  937. {
  938. boneNode = GetNode(channelName, scene_->mRootNode);
  939. if (!boneNode)
  940. {
  941. PrintLine("Warning: skipping animation track " + channelName + " whose scene node was not found");
  942. continue;
  943. }
  944. }
  945. AnimationTrack track;
  946. track.name_ = channelName;
  947. track.nameHash_ = channelName;
  948. // Check which channels are used
  949. track.channelMask_ = 0;
  950. if (channel->mNumPositionKeys > 1)
  951. track.channelMask_ |= CHANNEL_POSITION;
  952. if (channel->mNumRotationKeys > 1)
  953. track.channelMask_ |= CHANNEL_ROTATION;
  954. if (channel->mNumScalingKeys > 1)
  955. track.channelMask_ |= CHANNEL_SCALE;
  956. // Check for redundant identity scale in all keyframes and remove in that case
  957. if (track.channelMask_ & CHANNEL_SCALE)
  958. {
  959. bool redundantScale = true;
  960. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  961. {
  962. float SCALE_EPSILON = 0.000001f;
  963. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  964. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  965. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  966. {
  967. redundantScale = false;
  968. break;
  969. }
  970. }
  971. if (redundantScale)
  972. track.channelMask_ &= ~CHANNEL_SCALE;
  973. }
  974. if (!track.channelMask_)
  975. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  976. // Currently only same amount of keyframes is supported
  977. // Note: should also check the times of individual keyframes for match
  978. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  979. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  980. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  981. {
  982. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  983. continue;
  984. }
  985. unsigned keyFrames = channel->mNumPositionKeys;
  986. if (channel->mNumRotationKeys > keyFrames)
  987. keyFrames = channel->mNumRotationKeys;
  988. if (channel->mNumScalingKeys > keyFrames)
  989. keyFrames = channel->mNumScalingKeys;
  990. for (unsigned k = 0; k < keyFrames; ++k)
  991. {
  992. AnimationKeyFrame kf;
  993. kf.time_ = 0.0f;
  994. kf.position_ = Vector3::ZERO;
  995. kf.rotation_ = Quaternion::IDENTITY;
  996. kf.scale_ = Vector3::ONE;
  997. // Get time for the keyframe. Adjust with animation's start time
  998. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  999. kf.time_ = ((float)channel->mPositionKeys[k].mTime - startTime) * tickConversion;
  1000. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  1001. kf.time_ = ((float)channel->mRotationKeys[k].mTime - startTime) * tickConversion;
  1002. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  1003. kf.time_ = ((float)channel->mScalingKeys[k].mTime - startTime) * tickConversion;
  1004. // Make sure time stays positive
  1005. kf.time_ = Max(kf.time_, 0.0f);
  1006. // Start with the bone's base transform
  1007. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  1008. aiVector3D pos, scale;
  1009. aiQuaternion rot;
  1010. boneTransform.Decompose(scale, rot, pos);
  1011. // Then apply the active channels
  1012. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  1013. pos = channel->mPositionKeys[k].mValue;
  1014. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  1015. rot = channel->mRotationKeys[k].mValue;
  1016. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  1017. scale = channel->mScalingKeys[k].mValue;
  1018. // If root bone, transform with the model root node transform
  1019. if (model && isRootBone)
  1020. {
  1021. aiMatrix4x4 transMat, scaleMat, rotMat;
  1022. aiMatrix4x4::Translation(pos, transMat);
  1023. aiMatrix4x4::Scaling(scale, scaleMat);
  1024. rotMat = aiMatrix4x4(rot.GetMatrix());
  1025. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  1026. tform = GetDerivedTransform(tform, boneNode, model->rootNode_);
  1027. tform.Decompose(scale, rot, pos);
  1028. }
  1029. if (track.channelMask_ & CHANNEL_POSITION)
  1030. kf.position_ = ToVector3(pos);
  1031. if (track.channelMask_ & CHANNEL_ROTATION)
  1032. kf.rotation_ = ToQuaternion(rot);
  1033. if (track.channelMask_ & CHANNEL_SCALE)
  1034. kf.scale_ = ToVector3(scale);
  1035. track.keyFrames_.Push(kf);
  1036. }
  1037. tracks.Push(track);
  1038. }
  1039. outAnim->SetTracks(tracks);
  1040. File outFile(context_);
  1041. if (!outFile.Open(animOutName, FILE_WRITE))
  1042. ErrorExit("Could not open output file " + animOutName);
  1043. outAnim->Save(outFile);
  1044. }
  1045. }
  1046. void ExportScene(const String& outName, bool asPrefab)
  1047. {
  1048. OutScene outScene;
  1049. outScene.outName_ = outName;
  1050. outScene.rootNode_ = rootNode_;
  1051. if (useSubdirs_)
  1052. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Models");
  1053. CollectSceneModels(outScene, rootNode_);
  1054. // Save models, their material lists and animations
  1055. for (unsigned i = 0; i < outScene.models_.Size(); ++i)
  1056. BuildAndSaveModel(outScene.models_[i]);
  1057. // Save scene-global animations
  1058. if (!noAnimations_)
  1059. {
  1060. CollectAnimations();
  1061. BuildAndSaveAnimations();
  1062. }
  1063. // Save scene
  1064. BuildAndSaveScene(outScene, asPrefab);
  1065. }
  1066. void CollectSceneModels(OutScene& scene, aiNode* node)
  1067. {
  1068. Vector<Pair<aiNode*, aiMesh*> > meshes;
  1069. GetMeshesUnderNode(meshes, node);
  1070. if (meshes.Size())
  1071. {
  1072. OutModel model;
  1073. model.rootNode_ = node;
  1074. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  1075. for (unsigned i = 0; i < meshes.Size(); ++i)
  1076. {
  1077. aiMesh* mesh = meshes[i].second_;
  1078. unsigned meshIndex = GetMeshIndex(mesh);
  1079. model.meshIndices_.Insert(meshIndex);
  1080. model.meshes_.Push(mesh);
  1081. model.meshNodes_.Push(meshes[i].first_);
  1082. model.totalVertices_ += mesh->mNumVertices;
  1083. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  1084. }
  1085. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  1086. bool unique = true;
  1087. if (checkUniqueModel_)
  1088. {
  1089. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  1090. {
  1091. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  1092. {
  1093. PrintLine("Added node " + FromAIString(node->mName));
  1094. scene.nodes_.Push(node);
  1095. scene.nodeModelIndices_.Push(i);
  1096. unique = false;
  1097. break;
  1098. }
  1099. }
  1100. }
  1101. if (unique)
  1102. {
  1103. PrintLine("Added model " + model.outName_);
  1104. PrintLine("Added node " + FromAIString(node->mName));
  1105. CollectBones(model);
  1106. BuildBoneCollisionInfo(model);
  1107. if (!noAnimations_)
  1108. {
  1109. CollectAnimations(&model);
  1110. BuildAndSaveAnimations(&model);
  1111. }
  1112. scene.models_.Push(model);
  1113. scene.nodes_.Push(node);
  1114. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  1115. }
  1116. }
  1117. for (unsigned i = 0; i < node->mNumChildren; ++i)
  1118. CollectSceneModels(scene, node->mChildren[i]);
  1119. }
  1120. void CreateHierarchy(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping)
  1121. {
  1122. CreateSceneNode(scene, srcNode, nodeMapping);
  1123. for (unsigned i = 0; i < srcNode->mNumChildren; ++i)
  1124. CreateHierarchy(scene, srcNode->mChildren[i], nodeMapping);
  1125. }
  1126. Node* CreateSceneNode(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping)
  1127. {
  1128. if (nodeMapping.Contains(srcNode))
  1129. return nodeMapping[srcNode];
  1130. // Flatten hierarchy if requested
  1131. if (noHierarchy_)
  1132. {
  1133. Node* outNode = scene->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1134. Vector3 pos, scale;
  1135. Quaternion rot;
  1136. GetPosRotScale(GetDerivedTransform(srcNode, rootNode_), pos, rot, scale);
  1137. outNode->SetTransform(pos, rot, scale);
  1138. nodeMapping[srcNode] = outNode;
  1139. return outNode;
  1140. }
  1141. if (srcNode == rootNode_ || !srcNode->mParent)
  1142. {
  1143. Node* outNode = scene->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1144. Vector3 pos, scale;
  1145. Quaternion rot;
  1146. GetPosRotScale(srcNode->mTransformation, pos, rot, scale);
  1147. outNode->SetTransform(pos, rot, scale);
  1148. nodeMapping[srcNode] = outNode;
  1149. return outNode;
  1150. }
  1151. else
  1152. {
  1153. // Ensure the existence of the parent chain as in the original file
  1154. if (!nodeMapping.Contains(srcNode->mParent))
  1155. CreateSceneNode(scene, srcNode->mParent, nodeMapping);
  1156. Node* parent = nodeMapping[srcNode->mParent];
  1157. Node* outNode = parent->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1158. Vector3 pos, scale;
  1159. Quaternion rot;
  1160. GetPosRotScale(srcNode->mTransformation, pos, rot, scale);
  1161. outNode->SetTransform(pos, rot, scale);
  1162. nodeMapping[srcNode] = outNode;
  1163. return outNode;
  1164. }
  1165. }
  1166. void BuildAndSaveScene(OutScene& scene, bool asPrefab)
  1167. {
  1168. if (!asPrefab)
  1169. PrintLine("Writing scene");
  1170. else
  1171. PrintLine("Writing node hierarchy");
  1172. SharedPtr<Scene> outScene(new Scene(context_));
  1173. if (!asPrefab)
  1174. {
  1175. #ifdef ATOMIC_PHYSICS
  1176. /// \todo Make the physics properties configurable
  1177. outScene->CreateComponent<PhysicsWorld>();
  1178. #endif
  1179. /// \todo Make the octree properties configurable, or detect from the scene contents
  1180. outScene->CreateComponent<Octree>();
  1181. outScene->CreateComponent<DebugRenderer>();
  1182. if (createZone_)
  1183. {
  1184. Node* zoneNode = outScene->CreateChild("Zone", localIDs_ ? LOCAL : REPLICATED);
  1185. Zone* zone = zoneNode->CreateComponent<Zone>();
  1186. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.f));
  1187. zone->SetAmbientColor(Color(0.25f, 0.25f, 0.25f));
  1188. // Create default light only if scene does not define them
  1189. if (!scene_->HasLights())
  1190. {
  1191. Node* lightNode = outScene->CreateChild("GlobalLight", localIDs_ ? LOCAL : REPLICATED);
  1192. Light* light = lightNode->CreateComponent<Light>();
  1193. light->SetLightType(LIGHT_DIRECTIONAL);
  1194. lightNode->SetRotation(Quaternion(60.0f, 30.0f, 0.0f));
  1195. }
  1196. }
  1197. }
  1198. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  1199. HashMap<aiNode*, Node*> nodeMapping;
  1200. Node* outRootNode = 0;
  1201. if (asPrefab)
  1202. outRootNode = CreateSceneNode(outScene, rootNode_, nodeMapping);
  1203. else
  1204. {
  1205. // If not saving as a prefab, associate the root node with the scene first to prevent unnecessary creation of a root
  1206. // However do not do that if the root node does not have an identity matrix, or itself contains a model
  1207. // (models at the Urho scene root are not preferable)
  1208. if (ToMatrix3x4(rootNode_->mTransformation).Equals(Matrix3x4::IDENTITY) && !scene.nodes_.Contains(rootNode_))
  1209. nodeMapping[rootNode_] = outScene;
  1210. }
  1211. // If is allowed to export empty nodes, export the full Assimp node hierarchy first
  1212. if (!noHierarchy_ && !noEmptyNodes_)
  1213. CreateHierarchy(outScene, rootNode_, nodeMapping);
  1214. // Create geometry nodes
  1215. for (unsigned i = 0; i < scene.nodes_.Size(); ++i)
  1216. {
  1217. const OutModel& model = scene.models_[scene.nodeModelIndices_[i]];
  1218. Node* modelNode = CreateSceneNode(outScene, scene.nodes_[i], nodeMapping);
  1219. StaticModel* staticModel = model.bones_.Empty() ? modelNode->CreateComponent<StaticModel>() : modelNode->CreateComponent<AnimatedModel>();
  1220. // Create a dummy model so that the reference can be stored
  1221. String modelName = (useSubdirs_ ? "Models/" : "") + GetFileNameAndExtension(model.outName_);
  1222. if (!cache->Exists(modelName))
  1223. {
  1224. Model* dummyModel = new Model(context_);
  1225. dummyModel->SetName(modelName);
  1226. dummyModel->SetNumGeometries(model.meshes_.Size());
  1227. cache->AddManualResource(dummyModel);
  1228. }
  1229. staticModel->SetModel(cache->GetResource<Model>(modelName));
  1230. // Set materials if they are known
  1231. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  1232. {
  1233. String matName = GetMeshMaterialName(model.meshes_[j]);
  1234. // Create a dummy material so that the reference can be stored
  1235. if (!cache->Exists(matName))
  1236. {
  1237. Material* dummyMat = new Material(context_);
  1238. dummyMat->SetName(matName);
  1239. cache->AddManualResource(dummyMat);
  1240. }
  1241. staticModel->SetMaterial(j, cache->GetResource<Material>(matName));
  1242. }
  1243. }
  1244. // Create lights
  1245. if (!asPrefab)
  1246. {
  1247. for (unsigned i = 0; i < scene_->mNumLights; ++i)
  1248. {
  1249. aiLight* light = scene_->mLights[i];
  1250. aiNode* lightNode = GetNode(FromAIString(light->mName), rootNode_, true);
  1251. if (!lightNode)
  1252. continue;
  1253. Node* outNode = CreateSceneNode(outScene, lightNode, nodeMapping);
  1254. Vector3 lightAdjustPosition = ToVector3(light->mPosition);
  1255. Vector3 lightAdjustDirection = ToVector3(light->mDirection);
  1256. // If light is not aligned at the scene node, an adjustment node needs to be created
  1257. if (!lightAdjustPosition.Equals(Vector3::ZERO) || (light->mType != aiLightSource_POINT &&
  1258. !lightAdjustDirection.Equals(Vector3::FORWARD)))
  1259. {
  1260. outNode = outNode->CreateChild("LightAdjust");
  1261. outNode->SetPosition(lightAdjustPosition);
  1262. outNode->SetDirection(lightAdjustDirection);
  1263. }
  1264. Light* outLight = outNode->CreateComponent<Light>();
  1265. outLight->SetColor(Color(light->mColorDiffuse.r, light->mColorDiffuse.g, light->mColorDiffuse.b));
  1266. switch (light->mType)
  1267. {
  1268. case aiLightSource_DIRECTIONAL:
  1269. outLight->SetLightType(LIGHT_DIRECTIONAL);
  1270. break;
  1271. case aiLightSource_SPOT:
  1272. outLight->SetLightType(LIGHT_SPOT);
  1273. outLight->SetFov(light->mAngleOuterCone * 0.5f * M_RADTODEG);
  1274. break;
  1275. case aiLightSource_POINT:
  1276. outLight->SetLightType(LIGHT_POINT);
  1277. break;
  1278. default:
  1279. break;
  1280. }
  1281. // Calculate range from attenuation parameters so that light intensity has been reduced to 10% at that distance
  1282. if (light->mType != aiLightSource_DIRECTIONAL)
  1283. {
  1284. float a = light->mAttenuationQuadratic;
  1285. float b = light->mAttenuationLinear;
  1286. float c = -10.0f;
  1287. if (!Equals(a, 0.0f))
  1288. {
  1289. float root1 = (-b + sqrtf(b * b - 4.0f * a * c)) / (2.0f * a);
  1290. float root2 = (-b - sqrtf(b * b - 4.0f * a * c)) / (2.0f * a);
  1291. outLight->SetRange(Max(root1, root2));
  1292. }
  1293. else if (!Equals(b, 0.0f))
  1294. outLight->SetRange(-c / b);
  1295. }
  1296. }
  1297. }
  1298. File file(context_);
  1299. if (!file.Open(scene.outName_, FILE_WRITE))
  1300. ErrorExit("Could not open output file " + scene.outName_);
  1301. if (!asPrefab)
  1302. {
  1303. if (!saveBinary_)
  1304. outScene->SaveXML(file);
  1305. else
  1306. outScene->Save(file);
  1307. }
  1308. else
  1309. {
  1310. if (!saveBinary_)
  1311. outRootNode->SaveXML(file);
  1312. else
  1313. outRootNode->Save(file);
  1314. }
  1315. }
  1316. void ExportMaterials(HashSet<String>& usedTextures)
  1317. {
  1318. if (useSubdirs_)
  1319. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Materials");
  1320. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1321. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  1322. }
  1323. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures)
  1324. {
  1325. aiString matNameStr;
  1326. material->Get(AI_MATKEY_NAME, matNameStr);
  1327. String matName = SanitateAssetName(FromAIString(matNameStr));
  1328. if (matName.Trimmed().Empty())
  1329. matName = GenerateMaterialName(material);
  1330. // Do not actually create a material instance, but instead craft an xml file manually
  1331. XMLFile outMaterial(context_);
  1332. XMLElement materialElem = outMaterial.CreateRoot("material");
  1333. String diffuseTexName;
  1334. String normalTexName;
  1335. String specularTexName;
  1336. String lightmapTexName;
  1337. String emissiveTexName;
  1338. Color diffuseColor = Color::WHITE;
  1339. Color specularColor;
  1340. Color emissiveColor = Color::BLACK;
  1341. bool hasAlpha = false;
  1342. bool twoSided = false;
  1343. float specPower = 1.0f;
  1344. aiString stringVal;
  1345. float floatVal;
  1346. int intVal;
  1347. aiColor3D colorVal;
  1348. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1349. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1350. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1351. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1352. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), stringVal) == AI_SUCCESS)
  1353. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1354. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), stringVal) == AI_SUCCESS)
  1355. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1356. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), stringVal) == AI_SUCCESS)
  1357. emissiveTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1358. if (!noMaterialDiffuseColor_)
  1359. {
  1360. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1361. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1362. }
  1363. if (material->Get(AI_MATKEY_COLOR_SPECULAR, colorVal) == AI_SUCCESS)
  1364. specularColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1365. if (!emissiveAO_)
  1366. {
  1367. if (material->Get(AI_MATKEY_COLOR_EMISSIVE, colorVal) == AI_SUCCESS)
  1368. emissiveColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1369. }
  1370. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1371. {
  1372. if (floatVal < 1.0f)
  1373. hasAlpha = true;
  1374. diffuseColor.a_ = floatVal;
  1375. }
  1376. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1377. specPower = floatVal;
  1378. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1379. twoSided = (intVal != 0);
  1380. String techniqueName = "Techniques/NoTexture";
  1381. if (!diffuseTexName.Empty())
  1382. {
  1383. techniqueName = "Techniques/Diff";
  1384. if (!normalTexName.Empty())
  1385. techniqueName += "Normal";
  1386. if (!specularTexName.Empty())
  1387. techniqueName += "Spec";
  1388. // For now lightmap does not coexist with normal & specular
  1389. if (normalTexName.Empty() && specularTexName.Empty() && !lightmapTexName.Empty())
  1390. techniqueName += "LightMap";
  1391. if (lightmapTexName.Empty() && !emissiveTexName.Empty())
  1392. techniqueName += emissiveAO_ ? "AO" : "Emissive";
  1393. }
  1394. if (hasAlpha)
  1395. techniqueName += "Alpha";
  1396. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1397. techniqueElem.SetString("name", techniqueName + ".xml");
  1398. if (!diffuseTexName.Empty())
  1399. {
  1400. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1401. diffuseElem.SetString("unit", "diffuse");
  1402. diffuseElem.SetString("name", GetMaterialTextureName(diffuseTexName));
  1403. usedTextures.Insert(diffuseTexName);
  1404. }
  1405. if (!normalTexName.Empty())
  1406. {
  1407. XMLElement normalElem = materialElem.CreateChild("texture");
  1408. normalElem.SetString("unit", "normal");
  1409. normalElem.SetString("name", GetMaterialTextureName(normalTexName));
  1410. usedTextures.Insert(normalTexName);
  1411. }
  1412. if (!specularTexName.Empty())
  1413. {
  1414. XMLElement specularElem = materialElem.CreateChild("texture");
  1415. specularElem.SetString("unit", "specular");
  1416. specularElem.SetString("name", GetMaterialTextureName(specularTexName));
  1417. usedTextures.Insert(specularTexName);
  1418. }
  1419. if (!lightmapTexName.Empty())
  1420. {
  1421. XMLElement lightmapElem = materialElem.CreateChild("texture");
  1422. lightmapElem.SetString("unit", "emissive");
  1423. lightmapElem.SetString("name", GetMaterialTextureName(lightmapTexName));
  1424. usedTextures.Insert(lightmapTexName);
  1425. }
  1426. if (!emissiveTexName.Empty())
  1427. {
  1428. XMLElement emissiveElem = materialElem.CreateChild("texture");
  1429. emissiveElem.SetString("unit", "emissive");
  1430. emissiveElem.SetString("name", GetMaterialTextureName(emissiveTexName));
  1431. usedTextures.Insert(emissiveTexName);
  1432. }
  1433. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1434. diffuseColorElem.SetString("name", "MatDiffColor");
  1435. diffuseColorElem.SetColor("value", diffuseColor);
  1436. XMLElement specularElem = materialElem.CreateChild("parameter");
  1437. specularElem.SetString("name", "MatSpecColor");
  1438. specularElem.SetVector4("value", Vector4(specularColor.r_, specularColor.g_, specularColor.b_, specPower));
  1439. XMLElement emissiveColorElem = materialElem.CreateChild("parameter");
  1440. emissiveColorElem.SetString("name", "MatEmissiveColor");
  1441. emissiveColorElem.SetColor("value", emissiveColor);
  1442. if (twoSided)
  1443. {
  1444. XMLElement cullElem = materialElem.CreateChild("cull");
  1445. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1446. cullElem.SetString("value", "none");
  1447. shadowCullElem.SetString("value", "none");
  1448. }
  1449. FileSystem* fileSystem = context_->GetSubsystem<FileSystem>();
  1450. String outFileName = resourcePath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".xml";
  1451. if (noOverwriteMaterial_ && fileSystem->FileExists(outFileName))
  1452. {
  1453. PrintLine("Skipping save of existing material " + matName);
  1454. return;
  1455. }
  1456. PrintLine("Writing material " + matName);
  1457. File outFile(context_);
  1458. if (!outFile.Open(outFileName, FILE_WRITE))
  1459. ErrorExit("Could not open output file " + outFileName);
  1460. outMaterial.Save(outFile);
  1461. }
  1462. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath)
  1463. {
  1464. FileSystem* fileSystem = context_->GetSubsystem<FileSystem>();
  1465. if (useSubdirs_)
  1466. fileSystem->CreateDir(resourcePath_ + "Textures");
  1467. for (HashSet<String>::ConstIterator i = usedTextures.Begin(); i != usedTextures.End(); ++i)
  1468. {
  1469. // Handle assimp embedded textures
  1470. if (i->Length() && i->At(0) == '*')
  1471. {
  1472. unsigned texIndex = ToInt(i->Substring(1));
  1473. if (texIndex >= scene_->mNumTextures)
  1474. PrintLine("Skipping out of range texture index " + String(texIndex));
  1475. else
  1476. {
  1477. aiTexture* tex = scene_->mTextures[texIndex];
  1478. String fullDestName = resourcePath_ + GenerateTextureName(texIndex);
  1479. bool destExists = fileSystem->FileExists(fullDestName);
  1480. if (destExists && noOverwriteTexture_)
  1481. {
  1482. PrintLine("Skipping copy of existing embedded texture " + GetFileNameAndExtension(fullDestName));
  1483. continue;
  1484. }
  1485. // Encoded texture
  1486. if (!tex->mHeight)
  1487. {
  1488. PrintLine("Saving embedded texture " + GetFileNameAndExtension(fullDestName));
  1489. File dest(context_, fullDestName, FILE_WRITE);
  1490. dest.Write((const void*)tex->pcData, tex->mWidth);
  1491. }
  1492. // RGBA8 texture
  1493. else
  1494. {
  1495. PrintLine("Saving embedded RGBA texture " + GetFileNameAndExtension(fullDestName));
  1496. Image image(context_);
  1497. image.SetSize(tex->mWidth, tex->mHeight, 4);
  1498. memcpy(image.GetData(), (const void*)tex->pcData, tex->mWidth * tex->mHeight * 4);
  1499. image.SavePNG(fullDestName);
  1500. }
  1501. }
  1502. }
  1503. else
  1504. {
  1505. String fullSourceName = sourcePath + *i;
  1506. String fullDestName = resourcePath_ + (useSubdirs_ ? "Textures/" : "") + *i;
  1507. if (!fileSystem->FileExists(fullSourceName))
  1508. {
  1509. PrintLine("Skipping copy of nonexisting material texture " + *i);
  1510. continue;
  1511. }
  1512. {
  1513. File test(context_, fullSourceName);
  1514. if (!test.GetSize())
  1515. {
  1516. PrintLine("Skipping copy of zero-size material texture " + *i);
  1517. continue;
  1518. }
  1519. }
  1520. bool destExists = fileSystem->FileExists(fullDestName);
  1521. if (destExists && noOverwriteTexture_)
  1522. {
  1523. PrintLine("Skipping copy of existing texture " + *i);
  1524. continue;
  1525. }
  1526. if (destExists && noOverwriteNewerTexture_ && fileSystem->GetLastModifiedTime(fullDestName) >
  1527. fileSystem->GetLastModifiedTime(fullSourceName))
  1528. {
  1529. PrintLine("Skipping copying of material texture " + *i + ", destination is newer");
  1530. continue;
  1531. }
  1532. PrintLine("Copying material texture " + *i);
  1533. fileSystem->Copy(fullSourceName, fullDestName);
  1534. }
  1535. }
  1536. }
  1537. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName)
  1538. {
  1539. // Load models
  1540. Vector<SharedPtr<Model> > srcModels;
  1541. for (unsigned i = 0; i < modelNames.Size(); ++i)
  1542. {
  1543. PrintLine("Reading LOD level " + String(i) + ": model " + modelNames[i] + " distance " + String(lodDistances[i]));
  1544. File srcFile(context_);
  1545. srcFile.Open(modelNames[i]);
  1546. SharedPtr<Model> srcModel(new Model(context_));
  1547. if (!srcModel->Load(srcFile))
  1548. ErrorExit("Could not load input model " + modelNames[i]);
  1549. srcModels.Push(srcModel);
  1550. }
  1551. // Check that none of the models already has LOD levels
  1552. for (unsigned i = 0; i < srcModels.Size(); ++i)
  1553. {
  1554. for (unsigned j = 0; j < srcModels[i]->GetNumGeometries(); ++j)
  1555. {
  1556. if (srcModels[i]->GetNumGeometryLodLevels(j) > 1)
  1557. ErrorExit(modelNames[i] + " already has multiple LOD levels defined");
  1558. }
  1559. }
  1560. // Check for number of geometries (need to have same amount for now)
  1561. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1562. {
  1563. if (srcModels[i]->GetNumGeometries() != srcModels[0]->GetNumGeometries())
  1564. ErrorExit(modelNames[i] + " has different amount of geometries than " + modelNames[0]);
  1565. }
  1566. // If there are bones, check for compatibility (need to have exact match for now)
  1567. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1568. {
  1569. if (srcModels[i]->GetSkeleton().GetNumBones() != srcModels[0]->GetSkeleton().GetNumBones())
  1570. ErrorExit(modelNames[i] + " has different amount of bones than " + modelNames[0]);
  1571. for (unsigned j = 0; j < srcModels[0]->GetSkeleton().GetNumBones(); ++j)
  1572. {
  1573. if (srcModels[i]->GetSkeleton().GetBone(j)->name_ != srcModels[0]->GetSkeleton().GetBone(j)->name_)
  1574. ErrorExit(modelNames[i] + " has different bones than " + modelNames[0]);
  1575. }
  1576. if (srcModels[i]->GetGeometryBoneMappings() != srcModels[0]->GetGeometryBoneMappings())
  1577. ErrorExit(modelNames[i] + " has different per-geometry bone mappings than " + modelNames[0]);
  1578. }
  1579. Vector<SharedPtr<VertexBuffer> > vbVector;
  1580. Vector<SharedPtr<IndexBuffer> > ibVector;
  1581. PODVector<unsigned> emptyMorphRange;
  1582. // Create the final model
  1583. SharedPtr<Model> outModel(new Model(context_));
  1584. outModel->SetNumGeometries(srcModels[0]->GetNumGeometries());
  1585. for (unsigned i = 0; i < srcModels[0]->GetNumGeometries(); ++i)
  1586. {
  1587. outModel->SetNumGeometryLodLevels(i, srcModels.Size());
  1588. for (unsigned j = 0; j < srcModels.Size(); ++j)
  1589. {
  1590. Geometry* geometry = srcModels[j]->GetGeometry(i, 0);
  1591. geometry->SetLodDistance(lodDistances[j]);
  1592. outModel->SetGeometry(i, j, geometry);
  1593. for (unsigned k = 0; k < geometry->GetNumVertexBuffers(); ++k)
  1594. {
  1595. SharedPtr<VertexBuffer> vb(geometry->GetVertexBuffer(k));
  1596. if (!vbVector.Contains(vb))
  1597. vbVector.Push(vb);
  1598. }
  1599. SharedPtr<IndexBuffer> ib(geometry->GetIndexBuffer());
  1600. if (!ibVector.Contains(ib))
  1601. ibVector.Push(ib);
  1602. }
  1603. }
  1604. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  1605. outModel->SetIndexBuffers(ibVector);
  1606. outModel->SetSkeleton(srcModels[0]->GetSkeleton());
  1607. outModel->SetGeometryBoneMappings(srcModels[0]->GetGeometryBoneMappings());
  1608. outModel->SetBoundingBox(srcModels[0]->GetBoundingBox());
  1609. /// \todo Vertex morphs are ignored for now
  1610. // Save the final model
  1611. PrintLine("Writing output model");
  1612. File outFile(context_);
  1613. if (!outFile.Open(outName, FILE_WRITE))
  1614. ErrorExit("Could not open output file " + outName);
  1615. outModel->Save(outFile);
  1616. }
  1617. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& dest, aiNode* node)
  1618. {
  1619. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  1620. dest.Push(MakePair(node, scene_->mMeshes[node->mMeshes[i]]));
  1621. }
  1622. unsigned GetMeshIndex(aiMesh* mesh)
  1623. {
  1624. for (unsigned i = 0; i < scene_->mNumMeshes; ++i)
  1625. {
  1626. if (scene_->mMeshes[i] == mesh)
  1627. return i;
  1628. }
  1629. return M_MAX_UNSIGNED;
  1630. }
  1631. unsigned GetBoneIndex(OutModel& model, const String& boneName)
  1632. {
  1633. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  1634. {
  1635. if (boneName == model.bones_[i]->mName.data)
  1636. return i;
  1637. }
  1638. return M_MAX_UNSIGNED;
  1639. }
  1640. aiBone* GetMeshBone(OutModel& model, const String& boneName)
  1641. {
  1642. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1643. {
  1644. aiMesh* mesh = model.meshes_[i];
  1645. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1646. {
  1647. aiBone* bone = mesh->mBones[j];
  1648. if (boneName == bone->mName.data)
  1649. return bone;
  1650. }
  1651. }
  1652. return 0;
  1653. }
  1654. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName)
  1655. {
  1656. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1657. {
  1658. aiMesh* mesh = model.meshes_[i];
  1659. aiNode* node = model.meshNodes_[i];
  1660. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1661. {
  1662. aiBone* bone = mesh->mBones[j];
  1663. if (boneName == bone->mName.data)
  1664. {
  1665. aiMatrix4x4 offset = bone->mOffsetMatrix;
  1666. aiMatrix4x4 nodeDerivedInverse = GetMeshBakingTransform(node, model.rootNode_);
  1667. nodeDerivedInverse.Inverse();
  1668. offset *= nodeDerivedInverse;
  1669. return ToMatrix3x4(offset);
  1670. }
  1671. }
  1672. }
  1673. return Matrix3x4::IDENTITY;
  1674. }
  1675. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  1676. blendIndices, Vector<PODVector<float> >& blendWeights)
  1677. {
  1678. blendIndices.Resize(mesh->mNumVertices);
  1679. blendWeights.Resize(mesh->mNumVertices);
  1680. boneMappings.Clear();
  1681. // If model has more bones than can fit vertex shader parameters, write the per-geometry mappings
  1682. if (model.bones_.Size() > maxBones_)
  1683. {
  1684. if (mesh->mNumBones > maxBones_)
  1685. {
  1686. ErrorExit(
  1687. "Geometry (submesh) has over " + String(maxBones_) + " bone influences. Try splitting to more submeshes\n"
  1688. "that each stay at " + String(maxBones_) + " bones or below."
  1689. );
  1690. }
  1691. boneMappings.Resize(mesh->mNumBones);
  1692. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1693. {
  1694. aiBone* bone = mesh->mBones[i];
  1695. String boneName = FromAIString(bone->mName);
  1696. unsigned globalIndex = GetBoneIndex(model, boneName);
  1697. if (globalIndex == M_MAX_UNSIGNED)
  1698. ErrorExit("Bone " + boneName + " not found");
  1699. boneMappings[i] = globalIndex;
  1700. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1701. {
  1702. unsigned vertex = bone->mWeights[j].mVertexId;
  1703. blendIndices[vertex].Push(i);
  1704. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1705. if (blendWeights[vertex].Size() > 4)
  1706. ErrorExit("More than 4 bone influences on vertex");
  1707. }
  1708. }
  1709. }
  1710. else
  1711. {
  1712. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1713. {
  1714. aiBone* bone = mesh->mBones[i];
  1715. String boneName = FromAIString(bone->mName);
  1716. unsigned globalIndex = GetBoneIndex(model, boneName);
  1717. if (globalIndex == M_MAX_UNSIGNED)
  1718. ErrorExit("Bone " + boneName + " not found");
  1719. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1720. {
  1721. unsigned vertex = bone->mWeights[j].mVertexId;
  1722. blendIndices[vertex].Push(globalIndex);
  1723. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1724. if (blendWeights[vertex].Size() > 4)
  1725. ErrorExit("More than 4 bone influences on vertex");
  1726. }
  1727. }
  1728. }
  1729. }
  1730. String GetMeshMaterialName(aiMesh* mesh)
  1731. {
  1732. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  1733. aiString matNameStr;
  1734. material->Get(AI_MATKEY_NAME, matNameStr);
  1735. String matName = SanitateAssetName(FromAIString(matNameStr));
  1736. if (matName.Trimmed().Empty())
  1737. matName = GenerateMaterialName(material);
  1738. return (useSubdirs_ ? "Materials/" : "") + matName + ".xml";
  1739. }
  1740. String GenerateMaterialName(aiMaterial* material)
  1741. {
  1742. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1743. {
  1744. if (scene_->mMaterials[i] == material)
  1745. return inputName_ + "_Material" + String(i);
  1746. }
  1747. // Should not go here
  1748. return String::EMPTY;
  1749. }
  1750. String GetMaterialTextureName(const String& nameIn)
  1751. {
  1752. // Detect assimp embedded texture
  1753. if (nameIn.Length() && nameIn[0] == '*')
  1754. return GenerateTextureName(ToInt(nameIn.Substring(1)));
  1755. else
  1756. return (useSubdirs_ ? "Textures/" : "") + nameIn;
  1757. }
  1758. String GenerateTextureName(unsigned texIndex)
  1759. {
  1760. if (texIndex < scene_->mNumTextures)
  1761. {
  1762. // If embedded texture contains encoded data, use the format hint for file extension. Else save RGBA8 data as PNG
  1763. aiTexture* tex = scene_->mTextures[texIndex];
  1764. if (!tex->mHeight)
  1765. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + "." + tex->achFormatHint;
  1766. else
  1767. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + ".png";
  1768. }
  1769. // Should not go here
  1770. return String::EMPTY;
  1771. }
  1772. unsigned GetNumValidFaces(aiMesh* mesh)
  1773. {
  1774. unsigned ret = 0;
  1775. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  1776. {
  1777. if (mesh->mFaces[j].mNumIndices == 3)
  1778. ++ret;
  1779. }
  1780. return ret;
  1781. }
  1782. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1783. {
  1784. if (mesh->mFaces[index].mNumIndices == 3)
  1785. {
  1786. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1787. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1788. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1789. }
  1790. }
  1791. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1792. {
  1793. if (mesh->mFaces[index].mNumIndices == 3)
  1794. {
  1795. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1796. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1797. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1798. }
  1799. }
  1800. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  1801. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  1802. Vector<PODVector<float> >& blendWeights)
  1803. {
  1804. Vector3 vertex = vertexTransform * ToVector3(mesh->mVertices[index]);
  1805. box.Merge(vertex);
  1806. *dest++ = vertex.x_;
  1807. *dest++ = vertex.y_;
  1808. *dest++ = vertex.z_;
  1809. if (elementMask & MASK_NORMAL)
  1810. {
  1811. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1812. *dest++ = normal.x_;
  1813. *dest++ = normal.y_;
  1814. *dest++ = normal.z_;
  1815. }
  1816. if (elementMask & MASK_COLOR)
  1817. {
  1818. *((unsigned*)dest) = Color(mesh->mColors[0][index].r, mesh->mColors[0][index].g, mesh->mColors[0][index].b,
  1819. mesh->mColors[0][index].a).ToUInt();
  1820. ++dest;
  1821. }
  1822. if (elementMask & MASK_TEXCOORD1)
  1823. {
  1824. Vector3 texCoord = ToVector3(mesh->mTextureCoords[0][index]);
  1825. *dest++ = texCoord.x_;
  1826. *dest++ = texCoord.y_;
  1827. }
  1828. if (elementMask & MASK_TEXCOORD2)
  1829. {
  1830. Vector3 texCoord = ToVector3(mesh->mTextureCoords[1][index]);
  1831. *dest++ = texCoord.x_;
  1832. *dest++ = texCoord.y_;
  1833. }
  1834. if (elementMask & MASK_TANGENT)
  1835. {
  1836. Vector3 tangent = normalTransform * ToVector3(mesh->mTangents[index]);
  1837. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1838. Vector3 bitangent = normalTransform * ToVector3(mesh->mBitangents[index]);
  1839. // Check handedness
  1840. float w = 1.0f;
  1841. if ((tangent.CrossProduct(normal)).DotProduct(bitangent) < 0.5f)
  1842. w = -1.0f;
  1843. *dest++ = tangent.x_;
  1844. *dest++ = tangent.y_;
  1845. *dest++ = tangent.z_;
  1846. *dest++ = w;
  1847. }
  1848. if (elementMask & MASK_BLENDWEIGHTS)
  1849. {
  1850. for (unsigned i = 0; i < 4; ++i)
  1851. {
  1852. if (i < blendWeights[index].Size())
  1853. *dest++ = blendWeights[index][i];
  1854. else
  1855. *dest++ = 0.0f;
  1856. }
  1857. }
  1858. if (elementMask & MASK_BLENDINDICES)
  1859. {
  1860. unsigned char* destBytes = (unsigned char*)dest;
  1861. ++dest;
  1862. for (unsigned i = 0; i < 4; ++i)
  1863. {
  1864. if (i < blendIndices[index].Size())
  1865. *destBytes++ = blendIndices[index][i];
  1866. else
  1867. *destBytes++ = 0;
  1868. }
  1869. }
  1870. }
  1871. unsigned GetElementMask(aiMesh* mesh)
  1872. {
  1873. unsigned elementMask = MASK_POSITION;
  1874. if (mesh->HasNormals())
  1875. elementMask |= MASK_NORMAL;
  1876. if (mesh->HasTangentsAndBitangents())
  1877. elementMask |= MASK_TANGENT;
  1878. if (mesh->GetNumColorChannels() > 0)
  1879. elementMask |= MASK_COLOR;
  1880. if (mesh->GetNumUVChannels() > 0)
  1881. elementMask |= MASK_TEXCOORD1;
  1882. if (mesh->GetNumUVChannels() > 1)
  1883. elementMask |= MASK_TEXCOORD2;
  1884. if (mesh->HasBones())
  1885. elementMask |= (MASK_BLENDWEIGHTS | MASK_BLENDINDICES);
  1886. return elementMask;
  1887. }
  1888. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive)
  1889. {
  1890. if (!rootNode)
  1891. return 0;
  1892. if (!name.Compare(rootNode->mName.data, caseSensitive))
  1893. return rootNode;
  1894. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  1895. {
  1896. aiNode* found = GetNode(name, rootNode->mChildren[i], caseSensitive);
  1897. if (found)
  1898. return found;
  1899. }
  1900. return 0;
  1901. }
  1902. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode, bool rootInclusive)
  1903. {
  1904. return GetDerivedTransform(node->mTransformation, node, rootNode, rootInclusive);
  1905. }
  1906. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode, bool rootInclusive)
  1907. {
  1908. // If basenode is defined, go only up to it in the parent chain
  1909. while (node && node != rootNode)
  1910. {
  1911. node = node->mParent;
  1912. if (!rootInclusive && node == rootNode)
  1913. break;
  1914. if (node)
  1915. transform = node->mTransformation * transform;
  1916. }
  1917. return transform;
  1918. }
  1919. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode)
  1920. {
  1921. if (meshNode == modelRootNode)
  1922. return aiMatrix4x4();
  1923. else
  1924. return GetDerivedTransform(meshNode, modelRootNode);
  1925. }
  1926. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale)
  1927. {
  1928. aiVector3D aiPos;
  1929. aiQuaternion aiRot;
  1930. aiVector3D aiScale;
  1931. transform.Decompose(aiScale, aiRot, aiPos);
  1932. pos = ToVector3(aiPos);
  1933. rot = ToQuaternion(aiRot);
  1934. scale = ToVector3(aiScale);
  1935. }
  1936. String FromAIString(const aiString& str)
  1937. {
  1938. return String(str.data);
  1939. }
  1940. Vector3 ToVector3(const aiVector3D& vec)
  1941. {
  1942. return Vector3(vec.x, vec.y, vec.z);
  1943. }
  1944. Vector2 ToVector2(const aiVector2D& vec)
  1945. {
  1946. return Vector2(vec.x, vec.y);
  1947. }
  1948. Quaternion ToQuaternion(const aiQuaternion& quat)
  1949. {
  1950. return Quaternion(quat.w, quat.x, quat.y, quat.z);
  1951. }
  1952. Matrix3x4 ToMatrix3x4(const aiMatrix4x4& mat)
  1953. {
  1954. Matrix3x4 ret;
  1955. memcpy(&ret.m00_, &mat.a1, sizeof(Matrix3x4));
  1956. return ret;
  1957. }
  1958. String SanitateAssetName(const String& name)
  1959. {
  1960. String fixedName = name;
  1961. fixedName.Replace("<", "");
  1962. fixedName.Replace(">", "");
  1963. fixedName.Replace("?", "");
  1964. fixedName.Replace("*", "");
  1965. fixedName.Replace(":", "");
  1966. fixedName.Replace("\"", "");
  1967. fixedName.Replace("/", "");
  1968. fixedName.Replace("\\", "");
  1969. fixedName.Replace("|", "");
  1970. return fixedName;
  1971. }