AssetImporter.cpp 85 KB

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