AssetImporter.cpp 90 KB

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