AssetImporter.cpp 80 KB

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