AssetImporter.cpp 110 KB

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