AssetImporter.cpp 92 KB

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