AssetImporter.cpp 109 KB

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