FBXConverter.cpp 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2021, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file FBXConverter.cpp
  34. * @brief Implementation of the FBX DOM -> aiScene converter
  35. */
  36. #ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
  37. #include "FBXConverter.h"
  38. #include "FBXDocument.h"
  39. #include "FBXImporter.h"
  40. #include "FBXMeshGeometry.h"
  41. #include "FBXParser.h"
  42. #include "FBXProperties.h"
  43. #include "FBXUtil.h"
  44. #include <assimp/MathFunctions.h>
  45. #include <assimp/StringComparison.h>
  46. #include <assimp/scene.h>
  47. #include <assimp/CreateAnimMesh.h>
  48. #include <assimp/StringUtils.h>
  49. #include <assimp/commonMetaData.h>
  50. #include <stdlib.h>
  51. #include <cstdint>
  52. #include <iomanip>
  53. #include <iostream>
  54. #include <iterator>
  55. #include <memory>
  56. #include <sstream>
  57. #include <tuple>
  58. #include <vector>
  59. namespace Assimp {
  60. namespace FBX {
  61. using namespace Util;
  62. #define MAGIC_NODE_TAG "_$AssimpFbx$"
  63. #define CONVERT_FBX_TIME(time) (static_cast<double>(time) * 1000.0 / 46186158000LL)
  64. FBXConverter::FBXConverter(aiScene *out, const Document &doc, bool removeEmptyBones) :
  65. defaultMaterialIndex(),
  66. mMeshes(),
  67. lights(),
  68. cameras(),
  69. textures(),
  70. materials_converted(),
  71. textures_converted(),
  72. meshes_converted(),
  73. node_anim_chain_bits(),
  74. mNodeNames(),
  75. anim_fps(),
  76. mSceneOut(out),
  77. doc(doc),
  78. mRemoveEmptyBones(removeEmptyBones) {
  79. // animations need to be converted first since this will
  80. // populate the node_anim_chain_bits map, which is needed
  81. // to determine which nodes need to be generated.
  82. ConvertAnimations();
  83. // Embedded textures in FBX could be connected to nothing but to itself,
  84. // for instance Texture -> Video connection only but not to the main graph,
  85. // The idea here is to traverse all objects to find these Textures and convert them,
  86. // so later during material conversion it will find converted texture in the textures_converted array.
  87. if (doc.Settings().readTextures) {
  88. ConvertOrphanedEmbeddedTextures();
  89. }
  90. ConvertRootNode();
  91. if (doc.Settings().readAllMaterials) {
  92. // unfortunately this means we have to evaluate all objects
  93. for (const ObjectMap::value_type &v : doc.Objects()) {
  94. const Object *ob = v.second->Get();
  95. if (!ob) {
  96. continue;
  97. }
  98. const Material *mat = dynamic_cast<const Material *>(ob);
  99. if (mat) {
  100. if (materials_converted.find(mat) == materials_converted.end()) {
  101. ConvertMaterial(*mat, 0);
  102. }
  103. }
  104. }
  105. }
  106. ConvertGlobalSettings();
  107. TransferDataToScene();
  108. // if we didn't read any meshes set the AI_SCENE_FLAGS_INCOMPLETE
  109. // to make sure the scene passes assimp's validation. FBX files
  110. // need not contain geometry (i.e. camera animations, raw armatures).
  111. if (out->mNumMeshes == 0) {
  112. out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  113. }
  114. }
  115. FBXConverter::~FBXConverter() {
  116. std::for_each(mMeshes.begin(), mMeshes.end(), Util::delete_fun<aiMesh>());
  117. std::for_each(materials.begin(), materials.end(), Util::delete_fun<aiMaterial>());
  118. std::for_each(animations.begin(), animations.end(), Util::delete_fun<aiAnimation>());
  119. std::for_each(lights.begin(), lights.end(), Util::delete_fun<aiLight>());
  120. std::for_each(cameras.begin(), cameras.end(), Util::delete_fun<aiCamera>());
  121. std::for_each(textures.begin(), textures.end(), Util::delete_fun<aiTexture>());
  122. }
  123. void FBXConverter::ConvertRootNode() {
  124. mSceneOut->mRootNode = new aiNode();
  125. std::string unique_name;
  126. GetUniqueName("RootNode", unique_name);
  127. mSceneOut->mRootNode->mName.Set(unique_name);
  128. // root has ID 0
  129. ConvertNodes(0L, mSceneOut->mRootNode, mSceneOut->mRootNode);
  130. }
  131. static std::string getAncestorBaseName(const aiNode *node) {
  132. const char *nodeName = nullptr;
  133. size_t length = 0;
  134. while (node && (!nodeName || length == 0)) {
  135. nodeName = node->mName.C_Str();
  136. length = node->mName.length;
  137. node = node->mParent;
  138. }
  139. if (!nodeName || length == 0) {
  140. return {};
  141. }
  142. // could be std::string_view if c++17 available
  143. return std::string(nodeName, length);
  144. }
  145. // Make unique name
  146. std::string FBXConverter::MakeUniqueNodeName(const Model *const model, const aiNode &parent) {
  147. std::string original_name = FixNodeName(model->Name());
  148. if (original_name.empty()) {
  149. original_name = getAncestorBaseName(&parent);
  150. }
  151. std::string unique_name;
  152. GetUniqueName(original_name, unique_name);
  153. return unique_name;
  154. }
  155. /// This struct manages nodes which may or may not end up in the node hierarchy.
  156. /// When a node becomes a child of another node, that node becomes its owner and mOwnership should be released.
  157. struct FBXConverter::PotentialNode
  158. {
  159. PotentialNode() : mOwnership(new aiNode), mNode(mOwnership.get()) {}
  160. PotentialNode(const std::string& name) : mOwnership(new aiNode(name)), mNode(mOwnership.get()) {}
  161. aiNode* operator->() { return mNode; }
  162. std::unique_ptr<aiNode> mOwnership;
  163. aiNode* mNode;
  164. };
  165. /// todo: pre-build node hierarchy
  166. /// todo: get bone from stack
  167. /// todo: make map of aiBone* to aiNode*
  168. /// then update convert clusters to the new format
  169. void FBXConverter::ConvertNodes(uint64_t id, aiNode *parent, aiNode *root_node) {
  170. const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(id, "Model");
  171. std::vector<PotentialNode> nodes;
  172. nodes.reserve(conns.size());
  173. std::vector<PotentialNode> nodes_chain;
  174. std::vector<PotentialNode> post_nodes_chain;
  175. for (const Connection *con : conns) {
  176. // ignore object-property links
  177. if (con->PropertyName().length()) {
  178. // really important we document why this is ignored.
  179. FBXImporter::LogInfo("ignoring property link - no docs on why this is ignored");
  180. continue; //?
  181. }
  182. // convert connection source object into Object base class
  183. const Object *const object = con->SourceObject();
  184. if (nullptr == object) {
  185. FBXImporter::LogError("failed to convert source object for Model link");
  186. continue;
  187. }
  188. // FBX Model::Cube, Model::Bone001, etc elements
  189. // This detects if we can cast the object into this model structure.
  190. const Model *const model = dynamic_cast<const Model *>(object);
  191. if (nullptr != model) {
  192. nodes_chain.clear();
  193. post_nodes_chain.clear();
  194. aiMatrix4x4 new_abs_transform = parent->mTransformation;
  195. std::string node_name = FixNodeName(model->Name());
  196. // even though there is only a single input node, the design of
  197. // assimp (or rather: the complicated transformation chain that
  198. // is employed by fbx) means that we may need multiple aiNode's
  199. // to represent a fbx node's transformation.
  200. // generate node transforms - this includes pivot data
  201. // if need_additional_node is true then you t
  202. const bool need_additional_node = GenerateTransformationNodeChain(*model, node_name, nodes_chain, post_nodes_chain);
  203. // assert that for the current node we must have at least a single transform
  204. ai_assert(nodes_chain.size());
  205. if (need_additional_node) {
  206. nodes_chain.emplace_back(PotentialNode(node_name));
  207. }
  208. //setup metadata on newest node
  209. SetupNodeMetadata(*model, *nodes_chain.back().mNode);
  210. // link all nodes in a row
  211. aiNode *last_parent = parent;
  212. for (PotentialNode& child : nodes_chain) {
  213. ai_assert(child.mNode);
  214. if (last_parent != parent) {
  215. last_parent->mNumChildren = 1;
  216. last_parent->mChildren = new aiNode *[1];
  217. last_parent->mChildren[0] = child.mOwnership.release();
  218. }
  219. child->mParent = last_parent;
  220. last_parent = child.mNode;
  221. new_abs_transform *= child->mTransformation;
  222. }
  223. // attach geometry
  224. ConvertModel(*model, nodes_chain.back().mNode, root_node, new_abs_transform);
  225. // check if there will be any child nodes
  226. const std::vector<const Connection *> &child_conns = doc.GetConnectionsByDestinationSequenced(model->ID(), "Model");
  227. // if so, link the geometric transform inverse nodes
  228. // before we attach any child nodes
  229. if (child_conns.size()) {
  230. for (PotentialNode& postnode : post_nodes_chain) {
  231. ai_assert(postnode.mNode);
  232. if (last_parent != parent) {
  233. last_parent->mNumChildren = 1;
  234. last_parent->mChildren = new aiNode *[1];
  235. last_parent->mChildren[0] = postnode.mOwnership.release();
  236. }
  237. postnode->mParent = last_parent;
  238. last_parent = postnode.mNode;
  239. new_abs_transform *= postnode->mTransformation;
  240. }
  241. } else {
  242. // free the nodes we allocated as we don't need them
  243. post_nodes_chain.clear();
  244. }
  245. // recursion call - child nodes
  246. ConvertNodes(model->ID(), last_parent, root_node);
  247. if (doc.Settings().readLights) {
  248. ConvertLights(*model, node_name);
  249. }
  250. if (doc.Settings().readCameras) {
  251. ConvertCameras(*model, node_name);
  252. }
  253. nodes.push_back(std::move(nodes_chain.front()));
  254. nodes_chain.clear();
  255. }
  256. }
  257. if (nodes.size()) {
  258. parent->mChildren = new aiNode *[nodes.size()]();
  259. parent->mNumChildren = static_cast<unsigned int>(nodes.size());
  260. for (unsigned int i = 0; i < nodes.size(); ++i)
  261. {
  262. parent->mChildren[i] = nodes[i].mOwnership.release();
  263. }
  264. nodes.clear();
  265. } else {
  266. parent->mNumChildren = 0;
  267. parent->mChildren = nullptr;
  268. }
  269. }
  270. void FBXConverter::ConvertLights(const Model &model, const std::string &orig_name) {
  271. const std::vector<const NodeAttribute *> &node_attrs = model.GetAttributes();
  272. for (const NodeAttribute *attr : node_attrs) {
  273. const Light *const light = dynamic_cast<const Light *>(attr);
  274. if (light) {
  275. ConvertLight(*light, orig_name);
  276. }
  277. }
  278. }
  279. void FBXConverter::ConvertCameras(const Model &model, const std::string &orig_name) {
  280. const std::vector<const NodeAttribute *> &node_attrs = model.GetAttributes();
  281. for (const NodeAttribute *attr : node_attrs) {
  282. const Camera *const cam = dynamic_cast<const Camera *>(attr);
  283. if (cam) {
  284. ConvertCamera(*cam, orig_name);
  285. }
  286. }
  287. }
  288. void FBXConverter::ConvertLight(const Light &light, const std::string &orig_name) {
  289. lights.push_back(new aiLight());
  290. aiLight *const out_light = lights.back();
  291. out_light->mName.Set(orig_name);
  292. const float intensity = light.Intensity() / 100.0f;
  293. const aiVector3D &col = light.Color();
  294. out_light->mColorDiffuse = aiColor3D(col.x, col.y, col.z);
  295. out_light->mColorDiffuse.r *= intensity;
  296. out_light->mColorDiffuse.g *= intensity;
  297. out_light->mColorDiffuse.b *= intensity;
  298. out_light->mColorSpecular = out_light->mColorDiffuse;
  299. //lights are defined along negative y direction
  300. out_light->mPosition = aiVector3D(0.0f);
  301. out_light->mDirection = aiVector3D(0.0f, -1.0f, 0.0f);
  302. out_light->mUp = aiVector3D(0.0f, 0.0f, -1.0f);
  303. switch (light.LightType()) {
  304. case Light::Type_Point:
  305. out_light->mType = aiLightSource_POINT;
  306. break;
  307. case Light::Type_Directional:
  308. out_light->mType = aiLightSource_DIRECTIONAL;
  309. break;
  310. case Light::Type_Spot:
  311. out_light->mType = aiLightSource_SPOT;
  312. out_light->mAngleOuterCone = AI_DEG_TO_RAD(light.OuterAngle());
  313. out_light->mAngleInnerCone = AI_DEG_TO_RAD(light.InnerAngle());
  314. break;
  315. case Light::Type_Area:
  316. FBXImporter::LogWarn("cannot represent area light, set to UNDEFINED");
  317. out_light->mType = aiLightSource_UNDEFINED;
  318. break;
  319. case Light::Type_Volume:
  320. FBXImporter::LogWarn("cannot represent volume light, set to UNDEFINED");
  321. out_light->mType = aiLightSource_UNDEFINED;
  322. break;
  323. default:
  324. ai_assert(false);
  325. }
  326. float decay = light.DecayStart();
  327. switch (light.DecayType()) {
  328. case Light::Decay_None:
  329. out_light->mAttenuationConstant = decay;
  330. out_light->mAttenuationLinear = 0.0f;
  331. out_light->mAttenuationQuadratic = 0.0f;
  332. break;
  333. case Light::Decay_Linear:
  334. out_light->mAttenuationConstant = 0.0f;
  335. out_light->mAttenuationLinear = 2.0f / decay;
  336. out_light->mAttenuationQuadratic = 0.0f;
  337. break;
  338. case Light::Decay_Quadratic:
  339. out_light->mAttenuationConstant = 0.0f;
  340. out_light->mAttenuationLinear = 0.0f;
  341. out_light->mAttenuationQuadratic = 2.0f / (decay * decay);
  342. break;
  343. case Light::Decay_Cubic:
  344. FBXImporter::LogWarn("cannot represent cubic attenuation, set to Quadratic");
  345. out_light->mAttenuationQuadratic = 1.0f;
  346. break;
  347. default:
  348. ai_assert(false);
  349. break;
  350. }
  351. }
  352. void FBXConverter::ConvertCamera(const Camera &cam, const std::string &orig_name) {
  353. cameras.push_back(new aiCamera());
  354. aiCamera *const out_camera = cameras.back();
  355. out_camera->mName.Set(orig_name);
  356. out_camera->mAspect = cam.AspectWidth() / cam.AspectHeight();
  357. out_camera->mPosition = aiVector3D(0.0f);
  358. out_camera->mLookAt = aiVector3D(1.0f, 0.0f, 0.0f);
  359. out_camera->mUp = aiVector3D(0.0f, 1.0f, 0.0f);
  360. out_camera->mHorizontalFOV = AI_DEG_TO_RAD(cam.FieldOfView());
  361. out_camera->mClipPlaneNear = cam.NearPlane();
  362. out_camera->mClipPlaneFar = cam.FarPlane();
  363. out_camera->mHorizontalFOV = AI_DEG_TO_RAD(cam.FieldOfView());
  364. out_camera->mClipPlaneNear = cam.NearPlane();
  365. out_camera->mClipPlaneFar = cam.FarPlane();
  366. }
  367. void FBXConverter::GetUniqueName(const std::string &name, std::string &uniqueName) {
  368. uniqueName = name;
  369. auto it_pair = mNodeNames.insert({ name, 0 }); // duplicate node name instance count
  370. unsigned int &i = it_pair.first->second;
  371. while (!it_pair.second) {
  372. i++;
  373. std::ostringstream ext;
  374. ext << name << std::setfill('0') << std::setw(3) << i;
  375. uniqueName = ext.str();
  376. it_pair = mNodeNames.insert({ uniqueName, 0 });
  377. }
  378. }
  379. const char *FBXConverter::NameTransformationComp(TransformationComp comp) {
  380. switch (comp) {
  381. case TransformationComp_Translation:
  382. return "Translation";
  383. case TransformationComp_RotationOffset:
  384. return "RotationOffset";
  385. case TransformationComp_RotationPivot:
  386. return "RotationPivot";
  387. case TransformationComp_PreRotation:
  388. return "PreRotation";
  389. case TransformationComp_Rotation:
  390. return "Rotation";
  391. case TransformationComp_PostRotation:
  392. return "PostRotation";
  393. case TransformationComp_RotationPivotInverse:
  394. return "RotationPivotInverse";
  395. case TransformationComp_ScalingOffset:
  396. return "ScalingOffset";
  397. case TransformationComp_ScalingPivot:
  398. return "ScalingPivot";
  399. case TransformationComp_Scaling:
  400. return "Scaling";
  401. case TransformationComp_ScalingPivotInverse:
  402. return "ScalingPivotInverse";
  403. case TransformationComp_GeometricScaling:
  404. return "GeometricScaling";
  405. case TransformationComp_GeometricRotation:
  406. return "GeometricRotation";
  407. case TransformationComp_GeometricTranslation:
  408. return "GeometricTranslation";
  409. case TransformationComp_GeometricScalingInverse:
  410. return "GeometricScalingInverse";
  411. case TransformationComp_GeometricRotationInverse:
  412. return "GeometricRotationInverse";
  413. case TransformationComp_GeometricTranslationInverse:
  414. return "GeometricTranslationInverse";
  415. case TransformationComp_MAXIMUM: // this is to silence compiler warnings
  416. default:
  417. break;
  418. }
  419. ai_assert(false);
  420. return nullptr;
  421. }
  422. const char *FBXConverter::NameTransformationCompProperty(TransformationComp comp) {
  423. switch (comp) {
  424. case TransformationComp_Translation:
  425. return "Lcl Translation";
  426. case TransformationComp_RotationOffset:
  427. return "RotationOffset";
  428. case TransformationComp_RotationPivot:
  429. return "RotationPivot";
  430. case TransformationComp_PreRotation:
  431. return "PreRotation";
  432. case TransformationComp_Rotation:
  433. return "Lcl Rotation";
  434. case TransformationComp_PostRotation:
  435. return "PostRotation";
  436. case TransformationComp_RotationPivotInverse:
  437. return "RotationPivotInverse";
  438. case TransformationComp_ScalingOffset:
  439. return "ScalingOffset";
  440. case TransformationComp_ScalingPivot:
  441. return "ScalingPivot";
  442. case TransformationComp_Scaling:
  443. return "Lcl Scaling";
  444. case TransformationComp_ScalingPivotInverse:
  445. return "ScalingPivotInverse";
  446. case TransformationComp_GeometricScaling:
  447. return "GeometricScaling";
  448. case TransformationComp_GeometricRotation:
  449. return "GeometricRotation";
  450. case TransformationComp_GeometricTranslation:
  451. return "GeometricTranslation";
  452. case TransformationComp_GeometricScalingInverse:
  453. return "GeometricScalingInverse";
  454. case TransformationComp_GeometricRotationInverse:
  455. return "GeometricRotationInverse";
  456. case TransformationComp_GeometricTranslationInverse:
  457. return "GeometricTranslationInverse";
  458. case TransformationComp_MAXIMUM: // this is to silence compiler warnings
  459. break;
  460. }
  461. ai_assert(false);
  462. return nullptr;
  463. }
  464. aiVector3D FBXConverter::TransformationCompDefaultValue(TransformationComp comp) {
  465. // XXX a neat way to solve the never-ending special cases for scaling
  466. // would be to do everything in log space!
  467. return comp == TransformationComp_Scaling ? aiVector3D(1.f, 1.f, 1.f) : aiVector3D();
  468. }
  469. void FBXConverter::GetRotationMatrix(Model::RotOrder mode, const aiVector3D &rotation, aiMatrix4x4 &out) {
  470. if (mode == Model::RotOrder_SphericXYZ) {
  471. FBXImporter::LogError("Unsupported RotationMode: SphericXYZ");
  472. out = aiMatrix4x4();
  473. return;
  474. }
  475. const float angle_epsilon = Math::getEpsilon<float>();
  476. out = aiMatrix4x4();
  477. bool is_id[3] = { true, true, true };
  478. aiMatrix4x4 temp[3];
  479. if (std::fabs(rotation.z) > angle_epsilon) {
  480. aiMatrix4x4::RotationZ(AI_DEG_TO_RAD(rotation.z), temp[2]);
  481. is_id[2] = false;
  482. }
  483. if (std::fabs(rotation.y) > angle_epsilon) {
  484. aiMatrix4x4::RotationY(AI_DEG_TO_RAD(rotation.y), temp[1]);
  485. is_id[1] = false;
  486. }
  487. if (std::fabs(rotation.x) > angle_epsilon) {
  488. aiMatrix4x4::RotationX(AI_DEG_TO_RAD(rotation.x), temp[0]);
  489. is_id[0] = false;
  490. }
  491. int order[3] = { -1, -1, -1 };
  492. // note: rotation order is inverted since we're left multiplying as is usual in assimp
  493. switch (mode) {
  494. case Model::RotOrder_EulerXYZ:
  495. order[0] = 2;
  496. order[1] = 1;
  497. order[2] = 0;
  498. break;
  499. case Model::RotOrder_EulerXZY:
  500. order[0] = 1;
  501. order[1] = 2;
  502. order[2] = 0;
  503. break;
  504. case Model::RotOrder_EulerYZX:
  505. order[0] = 0;
  506. order[1] = 2;
  507. order[2] = 1;
  508. break;
  509. case Model::RotOrder_EulerYXZ:
  510. order[0] = 2;
  511. order[1] = 0;
  512. order[2] = 1;
  513. break;
  514. case Model::RotOrder_EulerZXY:
  515. order[0] = 1;
  516. order[1] = 0;
  517. order[2] = 2;
  518. break;
  519. case Model::RotOrder_EulerZYX:
  520. order[0] = 0;
  521. order[1] = 1;
  522. order[2] = 2;
  523. break;
  524. default:
  525. ai_assert(false);
  526. break;
  527. }
  528. ai_assert(order[0] >= 0);
  529. ai_assert(order[0] <= 2);
  530. ai_assert(order[1] >= 0);
  531. ai_assert(order[1] <= 2);
  532. ai_assert(order[2] >= 0);
  533. ai_assert(order[2] <= 2);
  534. if (!is_id[order[0]]) {
  535. out = temp[order[0]];
  536. }
  537. if (!is_id[order[1]]) {
  538. out = out * temp[order[1]];
  539. }
  540. if (!is_id[order[2]]) {
  541. out = out * temp[order[2]];
  542. }
  543. }
  544. bool FBXConverter::NeedsComplexTransformationChain(const Model &model) {
  545. const PropertyTable &props = model.Props();
  546. bool ok;
  547. const float zero_epsilon = 1e-6f;
  548. const aiVector3D all_ones(1.0f, 1.0f, 1.0f);
  549. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) {
  550. const TransformationComp comp = static_cast<TransformationComp>(i);
  551. if (comp == TransformationComp_Rotation || comp == TransformationComp_Scaling || comp == TransformationComp_Translation ||
  552. comp == TransformationComp_PreRotation || comp == TransformationComp_PostRotation) {
  553. continue;
  554. }
  555. bool scale_compare = (comp == TransformationComp_GeometricScaling || comp == TransformationComp_Scaling);
  556. const aiVector3D &v = PropertyGet<aiVector3D>(props, NameTransformationCompProperty(comp), ok);
  557. if (ok && scale_compare) {
  558. if ((v - all_ones).SquareLength() > zero_epsilon) {
  559. return true;
  560. }
  561. } else if (ok) {
  562. if (v.SquareLength() > zero_epsilon) {
  563. return true;
  564. }
  565. }
  566. }
  567. return false;
  568. }
  569. std::string FBXConverter::NameTransformationChainNode(const std::string &name, TransformationComp comp) {
  570. return name + std::string(MAGIC_NODE_TAG) + "_" + NameTransformationComp(comp);
  571. }
  572. bool FBXConverter::GenerateTransformationNodeChain(const Model &model, const std::string &name, std::vector<PotentialNode> &output_nodes,
  573. std::vector<PotentialNode> &post_output_nodes) {
  574. const PropertyTable &props = model.Props();
  575. const Model::RotOrder rot = model.RotationOrder();
  576. bool ok;
  577. aiMatrix4x4 chain[TransformationComp_MAXIMUM];
  578. ai_assert(TransformationComp_MAXIMUM < 32);
  579. std::uint32_t chainBits = 0;
  580. // A node won't need a node chain if it only has these.
  581. const std::uint32_t chainMaskSimple = (1 << TransformationComp_Translation) + (1 << TransformationComp_Scaling) + (1 << TransformationComp_Rotation);
  582. // A node will need a node chain if it has any of these.
  583. const std::uint32_t chainMaskComplex = ((1 << (TransformationComp_MAXIMUM)) - 1) - chainMaskSimple;
  584. std::fill_n(chain, static_cast<unsigned int>(TransformationComp_MAXIMUM), aiMatrix4x4());
  585. // generate transformation matrices for all the different transformation components
  586. const float zero_epsilon = Math::getEpsilon<float>();
  587. const aiVector3D all_ones(1.0f, 1.0f, 1.0f);
  588. const aiVector3D &PreRotation = PropertyGet<aiVector3D>(props, "PreRotation", ok);
  589. if (ok && PreRotation.SquareLength() > zero_epsilon) {
  590. chainBits = chainBits | (1 << TransformationComp_PreRotation);
  591. GetRotationMatrix(Model::RotOrder::RotOrder_EulerXYZ, PreRotation, chain[TransformationComp_PreRotation]);
  592. }
  593. const aiVector3D &PostRotation = PropertyGet<aiVector3D>(props, "PostRotation", ok);
  594. if (ok && PostRotation.SquareLength() > zero_epsilon) {
  595. chainBits = chainBits | (1 << TransformationComp_PostRotation);
  596. GetRotationMatrix(Model::RotOrder::RotOrder_EulerXYZ, PostRotation, chain[TransformationComp_PostRotation]);
  597. }
  598. const aiVector3D &RotationPivot = PropertyGet<aiVector3D>(props, "RotationPivot", ok);
  599. if (ok && RotationPivot.SquareLength() > zero_epsilon) {
  600. chainBits = chainBits | (1 << TransformationComp_RotationPivot) | (1 << TransformationComp_RotationPivotInverse);
  601. aiMatrix4x4::Translation(RotationPivot, chain[TransformationComp_RotationPivot]);
  602. aiMatrix4x4::Translation(-RotationPivot, chain[TransformationComp_RotationPivotInverse]);
  603. }
  604. const aiVector3D &RotationOffset = PropertyGet<aiVector3D>(props, "RotationOffset", ok);
  605. if (ok && RotationOffset.SquareLength() > zero_epsilon) {
  606. chainBits = chainBits | (1 << TransformationComp_RotationOffset);
  607. aiMatrix4x4::Translation(RotationOffset, chain[TransformationComp_RotationOffset]);
  608. }
  609. const aiVector3D &ScalingOffset = PropertyGet<aiVector3D>(props, "ScalingOffset", ok);
  610. if (ok && ScalingOffset.SquareLength() > zero_epsilon) {
  611. chainBits = chainBits | (1 << TransformationComp_ScalingOffset);
  612. aiMatrix4x4::Translation(ScalingOffset, chain[TransformationComp_ScalingOffset]);
  613. }
  614. const aiVector3D &ScalingPivot = PropertyGet<aiVector3D>(props, "ScalingPivot", ok);
  615. if (ok && ScalingPivot.SquareLength() > zero_epsilon) {
  616. chainBits = chainBits | (1 << TransformationComp_ScalingPivot) | (1 << TransformationComp_ScalingPivotInverse);
  617. aiMatrix4x4::Translation(ScalingPivot, chain[TransformationComp_ScalingPivot]);
  618. aiMatrix4x4::Translation(-ScalingPivot, chain[TransformationComp_ScalingPivotInverse]);
  619. }
  620. const aiVector3D &Translation = PropertyGet<aiVector3D>(props, "Lcl Translation", ok);
  621. if (ok && Translation.SquareLength() > zero_epsilon) {
  622. chainBits = chainBits | (1 << TransformationComp_Translation);
  623. aiMatrix4x4::Translation(Translation, chain[TransformationComp_Translation]);
  624. }
  625. const aiVector3D &Scaling = PropertyGet<aiVector3D>(props, "Lcl Scaling", ok);
  626. if (ok && (Scaling - all_ones).SquareLength() > zero_epsilon) {
  627. chainBits = chainBits | (1 << TransformationComp_Scaling);
  628. aiMatrix4x4::Scaling(Scaling, chain[TransformationComp_Scaling]);
  629. }
  630. const aiVector3D &Rotation = PropertyGet<aiVector3D>(props, "Lcl Rotation", ok);
  631. if (ok && Rotation.SquareLength() > zero_epsilon) {
  632. chainBits = chainBits | (1 << TransformationComp_Rotation);
  633. GetRotationMatrix(rot, Rotation, chain[TransformationComp_Rotation]);
  634. }
  635. const aiVector3D &GeometricScaling = PropertyGet<aiVector3D>(props, "GeometricScaling", ok);
  636. if (ok && (GeometricScaling - all_ones).SquareLength() > zero_epsilon) {
  637. chainBits = chainBits | (1 << TransformationComp_GeometricScaling);
  638. aiMatrix4x4::Scaling(GeometricScaling, chain[TransformationComp_GeometricScaling]);
  639. aiVector3D GeometricScalingInverse = GeometricScaling;
  640. bool canscale = true;
  641. for (unsigned int i = 0; i < 3; ++i) {
  642. if (std::fabs(GeometricScalingInverse[i]) > zero_epsilon) {
  643. GeometricScalingInverse[i] = 1.0f / GeometricScaling[i];
  644. } else {
  645. FBXImporter::LogError("cannot invert geometric scaling matrix with a 0.0 scale component");
  646. canscale = false;
  647. break;
  648. }
  649. }
  650. if (canscale) {
  651. chainBits = chainBits | (1 << TransformationComp_GeometricScalingInverse);
  652. aiMatrix4x4::Scaling(GeometricScalingInverse, chain[TransformationComp_GeometricScalingInverse]);
  653. }
  654. }
  655. const aiVector3D &GeometricRotation = PropertyGet<aiVector3D>(props, "GeometricRotation", ok);
  656. if (ok && GeometricRotation.SquareLength() > zero_epsilon) {
  657. chainBits = chainBits | (1 << TransformationComp_GeometricRotation) | (1 << TransformationComp_GeometricRotationInverse);
  658. GetRotationMatrix(rot, GeometricRotation, chain[TransformationComp_GeometricRotation]);
  659. GetRotationMatrix(rot, GeometricRotation, chain[TransformationComp_GeometricRotationInverse]);
  660. chain[TransformationComp_GeometricRotationInverse].Inverse();
  661. }
  662. const aiVector3D &GeometricTranslation = PropertyGet<aiVector3D>(props, "GeometricTranslation", ok);
  663. if (ok && GeometricTranslation.SquareLength() > zero_epsilon) {
  664. chainBits = chainBits | (1 << TransformationComp_GeometricTranslation) | (1 << TransformationComp_GeometricTranslationInverse);
  665. aiMatrix4x4::Translation(GeometricTranslation, chain[TransformationComp_GeometricTranslation]);
  666. aiMatrix4x4::Translation(-GeometricTranslation, chain[TransformationComp_GeometricTranslationInverse]);
  667. }
  668. // now, if we have more than just Translation, Scaling and Rotation,
  669. // we need to generate a full node chain to accommodate for assimp's
  670. // lack to express pivots and offsets.
  671. if ((chainBits & chainMaskComplex) && doc.Settings().preservePivots) {
  672. FBXImporter::LogInfo("generating full transformation chain for node: ", name);
  673. // query the anim_chain_bits dictionary to find out which chain elements
  674. // have associated node animation channels. These can not be dropped
  675. // even if they have identity transform in bind pose.
  676. NodeAnimBitMap::const_iterator it = node_anim_chain_bits.find(name);
  677. const unsigned int anim_chain_bitmask = (it == node_anim_chain_bits.end() ? 0 : (*it).second);
  678. unsigned int bit = 0x1;
  679. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i, bit <<= 1) {
  680. const TransformationComp comp = static_cast<TransformationComp>(i);
  681. if ((chainBits & bit) == 0 && (anim_chain_bitmask & bit) == 0) {
  682. continue;
  683. }
  684. if (comp == TransformationComp_PostRotation) {
  685. chain[i] = chain[i].Inverse();
  686. }
  687. PotentialNode nd;
  688. nd->mName.Set(NameTransformationChainNode(name, comp));
  689. nd->mTransformation = chain[i];
  690. // geometric inverses go in a post-node chain
  691. if (comp == TransformationComp_GeometricScalingInverse ||
  692. comp == TransformationComp_GeometricRotationInverse ||
  693. comp == TransformationComp_GeometricTranslationInverse) {
  694. post_output_nodes.emplace_back(std::move(nd));
  695. } else {
  696. output_nodes.emplace_back(std::move(nd));
  697. }
  698. }
  699. ai_assert(output_nodes.size());
  700. return true;
  701. }
  702. // else, we can just multiply the matrices together
  703. PotentialNode nd;
  704. // name passed to the method is already unique
  705. nd->mName.Set(name);
  706. // for (const auto &transform : chain) {
  707. // skip inverse chain for no preservePivots
  708. for (unsigned int i = TransformationComp_Translation; i < TransformationComp_MAXIMUM; i++) {
  709. nd->mTransformation = nd->mTransformation * chain[i];
  710. }
  711. output_nodes.push_back(std::move(nd));
  712. return false;
  713. }
  714. void FBXConverter::SetupNodeMetadata(const Model &model, aiNode &nd) {
  715. const PropertyTable &props = model.Props();
  716. DirectPropertyMap unparsedProperties = props.GetUnparsedProperties();
  717. // create metadata on node
  718. const std::size_t numStaticMetaData = 2;
  719. aiMetadata *data = aiMetadata::Alloc(static_cast<unsigned int>(unparsedProperties.size() + numStaticMetaData));
  720. nd.mMetaData = data;
  721. int index = 0;
  722. // find user defined properties (3ds Max)
  723. data->Set(index++, "UserProperties", aiString(PropertyGet<std::string>(props, "UDP3DSMAX", "")));
  724. // preserve the info that a node was marked as Null node in the original file.
  725. data->Set(index++, "IsNull", model.IsNull() ? true : false);
  726. // add unparsed properties to the node's metadata
  727. for (const DirectPropertyMap::value_type &prop : unparsedProperties) {
  728. // Interpret the property as a concrete type
  729. if (const TypedProperty<bool> *interpretedBool = prop.second->As<TypedProperty<bool>>()) {
  730. data->Set(index++, prop.first, interpretedBool->Value());
  731. } else if (const TypedProperty<int> *interpretedInt = prop.second->As<TypedProperty<int>>()) {
  732. data->Set(index++, prop.first, interpretedInt->Value());
  733. } else if (const TypedProperty<uint64_t> *interpretedUint64 = prop.second->As<TypedProperty<uint64_t>>()) {
  734. data->Set(index++, prop.first, interpretedUint64->Value());
  735. } else if (const TypedProperty<float> *interpretedFloat = prop.second->As<TypedProperty<float>>()) {
  736. data->Set(index++, prop.first, interpretedFloat->Value());
  737. } else if (const TypedProperty<std::string> *interpretedString = prop.second->As<TypedProperty<std::string>>()) {
  738. data->Set(index++, prop.first, aiString(interpretedString->Value()));
  739. } else if (const TypedProperty<aiVector3D> *interpretedVec3 = prop.second->As<TypedProperty<aiVector3D>>()) {
  740. data->Set(index++, prop.first, interpretedVec3->Value());
  741. } else {
  742. ai_assert(false);
  743. }
  744. }
  745. }
  746. void FBXConverter::ConvertModel(const Model &model, aiNode *parent, aiNode *root_node,
  747. const aiMatrix4x4 &absolute_transform) {
  748. const std::vector<const Geometry *> &geos = model.GetGeometry();
  749. std::vector<unsigned int> meshes;
  750. meshes.reserve(geos.size());
  751. for (const Geometry *geo : geos) {
  752. const MeshGeometry *const mesh = dynamic_cast<const MeshGeometry *>(geo);
  753. const LineGeometry *const line = dynamic_cast<const LineGeometry *>(geo);
  754. if (mesh) {
  755. const std::vector<unsigned int> &indices = ConvertMesh(*mesh, model, parent, root_node,
  756. absolute_transform);
  757. std::copy(indices.begin(), indices.end(), std::back_inserter(meshes));
  758. } else if (line) {
  759. const std::vector<unsigned int> &indices = ConvertLine(*line, root_node);
  760. std::copy(indices.begin(), indices.end(), std::back_inserter(meshes));
  761. } else {
  762. FBXImporter::LogWarn("ignoring unrecognized geometry: ", geo->Name());
  763. }
  764. }
  765. if (meshes.size()) {
  766. parent->mMeshes = new unsigned int[meshes.size()]();
  767. parent->mNumMeshes = static_cast<unsigned int>(meshes.size());
  768. std::swap_ranges(meshes.begin(), meshes.end(), parent->mMeshes);
  769. }
  770. }
  771. std::vector<unsigned int>
  772. FBXConverter::ConvertMesh(const MeshGeometry &mesh, const Model &model, aiNode *parent, aiNode *root_node,
  773. const aiMatrix4x4 &absolute_transform) {
  774. std::vector<unsigned int> temp;
  775. MeshMap::const_iterator it = meshes_converted.find(&mesh);
  776. if (it != meshes_converted.end()) {
  777. std::copy((*it).second.begin(), (*it).second.end(), std::back_inserter(temp));
  778. return temp;
  779. }
  780. const std::vector<aiVector3D> &vertices = mesh.GetVertices();
  781. const std::vector<unsigned int> &faces = mesh.GetFaceIndexCounts();
  782. if (vertices.empty() || faces.empty()) {
  783. FBXImporter::LogWarn("ignoring empty geometry: ", mesh.Name());
  784. return temp;
  785. }
  786. // one material per mesh maps easily to aiMesh. Multiple material
  787. // meshes need to be split.
  788. const MatIndexArray &mindices = mesh.GetMaterialIndices();
  789. if (doc.Settings().readMaterials && !mindices.empty()) {
  790. const MatIndexArray::value_type base = mindices[0];
  791. for (MatIndexArray::value_type index : mindices) {
  792. if (index != base) {
  793. return ConvertMeshMultiMaterial(mesh, model, parent, root_node, absolute_transform);
  794. }
  795. }
  796. }
  797. // faster code-path, just copy the data
  798. temp.push_back(ConvertMeshSingleMaterial(mesh, model, absolute_transform, parent, root_node));
  799. return temp;
  800. }
  801. std::vector<unsigned int> FBXConverter::ConvertLine(const LineGeometry &line, aiNode *root_node) {
  802. std::vector<unsigned int> temp;
  803. const std::vector<aiVector3D> &vertices = line.GetVertices();
  804. const std::vector<int> &indices = line.GetIndices();
  805. if (vertices.empty() || indices.empty()) {
  806. FBXImporter::LogWarn("ignoring empty line: ", line.Name());
  807. return temp;
  808. }
  809. aiMesh *const out_mesh = SetupEmptyMesh(line, root_node);
  810. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  811. // copy vertices
  812. out_mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
  813. out_mesh->mVertices = new aiVector3D[out_mesh->mNumVertices];
  814. std::copy(vertices.begin(), vertices.end(), out_mesh->mVertices);
  815. //Number of line segments (faces) is "Number of Points - Number of Endpoints"
  816. //N.B.: Endpoints in FbxLine are denoted by negative indices.
  817. //If such an Index is encountered, add 1 and multiply by -1 to get the real index.
  818. unsigned int epcount = 0;
  819. for (unsigned i = 0; i < indices.size(); i++) {
  820. if (indices[i] < 0) {
  821. epcount++;
  822. }
  823. }
  824. unsigned int pcount = static_cast<unsigned int>(indices.size());
  825. unsigned int scount = out_mesh->mNumFaces = pcount - epcount;
  826. aiFace *fac = out_mesh->mFaces = new aiFace[scount]();
  827. for (unsigned int i = 0; i < pcount; ++i) {
  828. if (indices[i] < 0) continue;
  829. aiFace &f = *fac++;
  830. f.mNumIndices = 2; //2 == aiPrimitiveType_LINE
  831. f.mIndices = new unsigned int[2];
  832. f.mIndices[0] = indices[i];
  833. int segid = indices[(i + 1 == pcount ? 0 : i + 1)]; //If we have reached he last point, wrap around
  834. f.mIndices[1] = (segid < 0 ? (segid + 1) * -1 : segid); //Convert EndPoint Index to normal Index
  835. }
  836. temp.push_back(static_cast<unsigned int>(mMeshes.size() - 1));
  837. return temp;
  838. }
  839. aiMesh *FBXConverter::SetupEmptyMesh(const Geometry &mesh, aiNode *parent) {
  840. aiMesh *const out_mesh = new aiMesh();
  841. mMeshes.push_back(out_mesh);
  842. meshes_converted[&mesh].push_back(static_cast<unsigned int>(mMeshes.size() - 1));
  843. // set name
  844. std::string name = mesh.Name();
  845. if (name.substr(0, 10) == "Geometry::") {
  846. name = name.substr(10);
  847. }
  848. if (name.length()) {
  849. out_mesh->mName.Set(name);
  850. } else {
  851. out_mesh->mName = parent->mName;
  852. }
  853. return out_mesh;
  854. }
  855. unsigned int FBXConverter::ConvertMeshSingleMaterial(const MeshGeometry &mesh, const Model &model,
  856. const aiMatrix4x4 &absolute_transform, aiNode *parent,
  857. aiNode *) {
  858. const MatIndexArray &mindices = mesh.GetMaterialIndices();
  859. aiMesh *const out_mesh = SetupEmptyMesh(mesh, parent);
  860. const std::vector<aiVector3D> &vertices = mesh.GetVertices();
  861. const std::vector<unsigned int> &faces = mesh.GetFaceIndexCounts();
  862. // copy vertices
  863. out_mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
  864. out_mesh->mVertices = new aiVector3D[vertices.size()];
  865. std::copy(vertices.begin(), vertices.end(), out_mesh->mVertices);
  866. // generate dummy faces
  867. out_mesh->mNumFaces = static_cast<unsigned int>(faces.size());
  868. aiFace *fac = out_mesh->mFaces = new aiFace[faces.size()]();
  869. unsigned int cursor = 0;
  870. for (unsigned int pcount : faces) {
  871. aiFace &f = *fac++;
  872. f.mNumIndices = pcount;
  873. f.mIndices = new unsigned int[pcount];
  874. switch (pcount) {
  875. case 1:
  876. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  877. break;
  878. case 2:
  879. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  880. break;
  881. case 3:
  882. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  883. break;
  884. default:
  885. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  886. break;
  887. }
  888. for (unsigned int i = 0; i < pcount; ++i) {
  889. f.mIndices[i] = cursor++;
  890. }
  891. }
  892. // copy normals
  893. const std::vector<aiVector3D> &normals = mesh.GetNormals();
  894. if (normals.size()) {
  895. ai_assert(normals.size() == vertices.size());
  896. out_mesh->mNormals = new aiVector3D[vertices.size()];
  897. std::copy(normals.begin(), normals.end(), out_mesh->mNormals);
  898. }
  899. // copy tangents - assimp requires both tangents and bitangents (binormals)
  900. // to be present, or neither of them. Compute binormals from normals
  901. // and tangents if needed.
  902. const std::vector<aiVector3D> &tangents = mesh.GetTangents();
  903. const std::vector<aiVector3D> *binormals = &mesh.GetBinormals();
  904. if (tangents.size()) {
  905. std::vector<aiVector3D> tempBinormals;
  906. if (!binormals->size()) {
  907. if (normals.size()) {
  908. tempBinormals.resize(normals.size());
  909. for (unsigned int i = 0; i < tangents.size(); ++i) {
  910. tempBinormals[i] = normals[i] ^ tangents[i];
  911. }
  912. binormals = &tempBinormals;
  913. } else {
  914. binormals = nullptr;
  915. }
  916. }
  917. if (binormals) {
  918. ai_assert(tangents.size() == vertices.size());
  919. ai_assert(binormals->size() == vertices.size());
  920. out_mesh->mTangents = new aiVector3D[vertices.size()];
  921. std::copy(tangents.begin(), tangents.end(), out_mesh->mTangents);
  922. out_mesh->mBitangents = new aiVector3D[vertices.size()];
  923. std::copy(binormals->begin(), binormals->end(), out_mesh->mBitangents);
  924. }
  925. }
  926. // copy texture coords
  927. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  928. const std::vector<aiVector2D> &uvs = mesh.GetTextureCoords(i);
  929. if (uvs.empty()) {
  930. break;
  931. }
  932. aiVector3D *out_uv = out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()];
  933. for (const aiVector2D &v : uvs) {
  934. *out_uv++ = aiVector3D(v.x, v.y, 0.0f);
  935. }
  936. out_mesh->mTextureCoordsNames[i] = mesh.GetTextureCoordChannelName(i);
  937. out_mesh->mNumUVComponents[i] = 2;
  938. }
  939. // copy vertex colors
  940. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) {
  941. const std::vector<aiColor4D> &colors = mesh.GetVertexColors(i);
  942. if (colors.empty()) {
  943. break;
  944. }
  945. out_mesh->mColors[i] = new aiColor4D[vertices.size()];
  946. std::copy(colors.begin(), colors.end(), out_mesh->mColors[i]);
  947. }
  948. if (!doc.Settings().readMaterials || mindices.empty()) {
  949. FBXImporter::LogError("no material assigned to mesh, setting default material");
  950. out_mesh->mMaterialIndex = GetDefaultMaterial();
  951. } else {
  952. ConvertMaterialForMesh(out_mesh, model, mesh, mindices[0]);
  953. }
  954. if (doc.Settings().readWeights && mesh.DeformerSkin() != nullptr) {
  955. ConvertWeights(out_mesh, mesh, absolute_transform, parent, NO_MATERIAL_SEPARATION, nullptr);
  956. }
  957. std::vector<aiAnimMesh *> animMeshes;
  958. for (const BlendShape *blendShape : mesh.GetBlendShapes()) {
  959. for (const BlendShapeChannel *blendShapeChannel : blendShape->BlendShapeChannels()) {
  960. const std::vector<const ShapeGeometry *> &shapeGeometries = blendShapeChannel->GetShapeGeometries();
  961. for (size_t i = 0; i < shapeGeometries.size(); i++) {
  962. aiAnimMesh *animMesh = aiCreateAnimMesh(out_mesh);
  963. const ShapeGeometry *shapeGeometry = shapeGeometries.at(i);
  964. const std::vector<aiVector3D> &curVertices = shapeGeometry->GetVertices();
  965. const std::vector<aiVector3D> &curNormals = shapeGeometry->GetNormals();
  966. const std::vector<unsigned int> &curIndices = shapeGeometry->GetIndices();
  967. //losing channel name if using shapeGeometry->Name()
  968. animMesh->mName.Set(FixAnimMeshName(blendShapeChannel->Name()));
  969. for (size_t j = 0; j < curIndices.size(); j++) {
  970. const unsigned int curIndex = curIndices.at(j);
  971. aiVector3D vertex = curVertices.at(j);
  972. aiVector3D normal = curNormals.at(j);
  973. unsigned int count = 0;
  974. const unsigned int *outIndices = mesh.ToOutputVertexIndex(curIndex, count);
  975. for (unsigned int k = 0; k < count; k++) {
  976. unsigned int index = outIndices[k];
  977. animMesh->mVertices[index] += vertex;
  978. if (animMesh->mNormals != nullptr) {
  979. animMesh->mNormals[index] += normal;
  980. animMesh->mNormals[index].NormalizeSafe();
  981. }
  982. }
  983. }
  984. animMesh->mWeight = shapeGeometries.size() > 1 ? blendShapeChannel->DeformPercent() / 100.0f : 1.0f;
  985. animMeshes.push_back(animMesh);
  986. }
  987. }
  988. }
  989. const size_t numAnimMeshes = animMeshes.size();
  990. if (numAnimMeshes > 0) {
  991. out_mesh->mNumAnimMeshes = static_cast<unsigned int>(numAnimMeshes);
  992. out_mesh->mAnimMeshes = new aiAnimMesh *[numAnimMeshes];
  993. for (size_t i = 0; i < numAnimMeshes; i++) {
  994. out_mesh->mAnimMeshes[i] = animMeshes.at(i);
  995. }
  996. }
  997. return static_cast<unsigned int>(mMeshes.size() - 1);
  998. }
  999. std::vector<unsigned int>
  1000. FBXConverter::ConvertMeshMultiMaterial(const MeshGeometry &mesh, const Model &model, aiNode *parent,
  1001. aiNode *root_node,
  1002. const aiMatrix4x4 &absolute_transform) {
  1003. const MatIndexArray &mindices = mesh.GetMaterialIndices();
  1004. ai_assert(mindices.size());
  1005. std::set<MatIndexArray::value_type> had;
  1006. std::vector<unsigned int> indices;
  1007. for (MatIndexArray::value_type index : mindices) {
  1008. if (had.find(index) == had.end()) {
  1009. indices.push_back(ConvertMeshMultiMaterial(mesh, model, index, parent, root_node, absolute_transform));
  1010. had.insert(index);
  1011. }
  1012. }
  1013. return indices;
  1014. }
  1015. unsigned int FBXConverter::ConvertMeshMultiMaterial(const MeshGeometry &mesh, const Model &model,
  1016. MatIndexArray::value_type index,
  1017. aiNode *parent, aiNode *,
  1018. const aiMatrix4x4 &absolute_transform) {
  1019. aiMesh *const out_mesh = SetupEmptyMesh(mesh, parent);
  1020. const MatIndexArray &mindices = mesh.GetMaterialIndices();
  1021. const std::vector<aiVector3D> &vertices = mesh.GetVertices();
  1022. const std::vector<unsigned int> &faces = mesh.GetFaceIndexCounts();
  1023. const bool process_weights = doc.Settings().readWeights && mesh.DeformerSkin() != nullptr;
  1024. unsigned int count_faces = 0;
  1025. unsigned int count_vertices = 0;
  1026. // count faces
  1027. std::vector<unsigned int>::const_iterator itf = faces.begin();
  1028. for (MatIndexArray::const_iterator it = mindices.begin(),
  1029. end = mindices.end();
  1030. it != end; ++it, ++itf) {
  1031. if ((*it) != index) {
  1032. continue;
  1033. }
  1034. ++count_faces;
  1035. count_vertices += *itf;
  1036. }
  1037. ai_assert(count_faces);
  1038. ai_assert(count_vertices);
  1039. // mapping from output indices to DOM indexing, needed to resolve weights or blendshapes
  1040. std::vector<unsigned int> reverseMapping;
  1041. std::map<unsigned int, unsigned int> translateIndexMap;
  1042. if (process_weights || mesh.GetBlendShapes().size() > 0) {
  1043. reverseMapping.resize(count_vertices);
  1044. }
  1045. // allocate output data arrays, but don't fill them yet
  1046. out_mesh->mNumVertices = count_vertices;
  1047. out_mesh->mVertices = new aiVector3D[count_vertices];
  1048. out_mesh->mNumFaces = count_faces;
  1049. aiFace *fac = out_mesh->mFaces = new aiFace[count_faces]();
  1050. // allocate normals
  1051. const std::vector<aiVector3D> &normals = mesh.GetNormals();
  1052. if (normals.size()) {
  1053. ai_assert(normals.size() == vertices.size());
  1054. out_mesh->mNormals = new aiVector3D[vertices.size()];
  1055. }
  1056. // allocate tangents, binormals.
  1057. const std::vector<aiVector3D> &tangents = mesh.GetTangents();
  1058. const std::vector<aiVector3D> *binormals = &mesh.GetBinormals();
  1059. std::vector<aiVector3D> tempBinormals;
  1060. if (tangents.size()) {
  1061. if (!binormals->size()) {
  1062. if (normals.size()) {
  1063. // XXX this computes the binormals for the entire mesh, not only
  1064. // the part for which we need them.
  1065. tempBinormals.resize(normals.size());
  1066. for (unsigned int i = 0; i < tangents.size(); ++i) {
  1067. tempBinormals[i] = normals[i] ^ tangents[i];
  1068. }
  1069. binormals = &tempBinormals;
  1070. } else {
  1071. binormals = nullptr;
  1072. }
  1073. }
  1074. if (binormals) {
  1075. ai_assert(tangents.size() == vertices.size());
  1076. ai_assert(binormals->size() == vertices.size());
  1077. out_mesh->mTangents = new aiVector3D[vertices.size()];
  1078. out_mesh->mBitangents = new aiVector3D[vertices.size()];
  1079. }
  1080. }
  1081. // allocate texture coords
  1082. unsigned int num_uvs = 0;
  1083. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i, ++num_uvs) {
  1084. const std::vector<aiVector2D> &uvs = mesh.GetTextureCoords(i);
  1085. if (uvs.empty()) {
  1086. break;
  1087. }
  1088. out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()];
  1089. out_mesh->mNumUVComponents[i] = 2;
  1090. }
  1091. // allocate vertex colors
  1092. unsigned int num_vcs = 0;
  1093. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i, ++num_vcs) {
  1094. const std::vector<aiColor4D> &colors = mesh.GetVertexColors(i);
  1095. if (colors.empty()) {
  1096. break;
  1097. }
  1098. out_mesh->mColors[i] = new aiColor4D[vertices.size()];
  1099. }
  1100. unsigned int cursor = 0, in_cursor = 0;
  1101. itf = faces.begin();
  1102. for (MatIndexArray::const_iterator it = mindices.begin(), end = mindices.end(); it != end; ++it, ++itf) {
  1103. const unsigned int pcount = *itf;
  1104. if ((*it) != index) {
  1105. in_cursor += pcount;
  1106. continue;
  1107. }
  1108. aiFace &f = *fac++;
  1109. f.mNumIndices = pcount;
  1110. f.mIndices = new unsigned int[pcount];
  1111. switch (pcount) {
  1112. case 1:
  1113. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  1114. break;
  1115. case 2:
  1116. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  1117. break;
  1118. case 3:
  1119. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  1120. break;
  1121. default:
  1122. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  1123. break;
  1124. }
  1125. for (unsigned int i = 0; i < pcount; ++i, ++cursor, ++in_cursor) {
  1126. f.mIndices[i] = cursor;
  1127. if (reverseMapping.size()) {
  1128. reverseMapping[cursor] = in_cursor;
  1129. translateIndexMap[in_cursor] = cursor;
  1130. }
  1131. out_mesh->mVertices[cursor] = vertices[in_cursor];
  1132. if (out_mesh->mNormals) {
  1133. out_mesh->mNormals[cursor] = normals[in_cursor];
  1134. }
  1135. if (out_mesh->mTangents) {
  1136. out_mesh->mTangents[cursor] = tangents[in_cursor];
  1137. out_mesh->mBitangents[cursor] = (*binormals)[in_cursor];
  1138. }
  1139. for (unsigned int j = 0; j < num_uvs; ++j) {
  1140. const std::vector<aiVector2D> &uvs = mesh.GetTextureCoords(j);
  1141. out_mesh->mTextureCoords[j][cursor] = aiVector3D(uvs[in_cursor].x, uvs[in_cursor].y, 0.0f);
  1142. }
  1143. for (unsigned int j = 0; j < num_vcs; ++j) {
  1144. const std::vector<aiColor4D> &cols = mesh.GetVertexColors(j);
  1145. out_mesh->mColors[j][cursor] = cols[in_cursor];
  1146. }
  1147. }
  1148. }
  1149. ConvertMaterialForMesh(out_mesh, model, mesh, index);
  1150. if (process_weights) {
  1151. ConvertWeights(out_mesh, mesh, absolute_transform, parent, index, &reverseMapping);
  1152. }
  1153. std::vector<aiAnimMesh *> animMeshes;
  1154. for (const BlendShape *blendShape : mesh.GetBlendShapes()) {
  1155. for (const BlendShapeChannel *blendShapeChannel : blendShape->BlendShapeChannels()) {
  1156. const std::vector<const ShapeGeometry *> &shapeGeometries = blendShapeChannel->GetShapeGeometries();
  1157. for (size_t i = 0; i < shapeGeometries.size(); i++) {
  1158. aiAnimMesh *animMesh = aiCreateAnimMesh(out_mesh);
  1159. const ShapeGeometry *shapeGeometry = shapeGeometries.at(i);
  1160. const std::vector<aiVector3D> &curVertices = shapeGeometry->GetVertices();
  1161. const std::vector<aiVector3D> &curNormals = shapeGeometry->GetNormals();
  1162. const std::vector<unsigned int> &curIndices = shapeGeometry->GetIndices();
  1163. animMesh->mName.Set(FixAnimMeshName(shapeGeometry->Name()));
  1164. for (size_t j = 0; j < curIndices.size(); j++) {
  1165. unsigned int curIndex = curIndices.at(j);
  1166. aiVector3D vertex = curVertices.at(j);
  1167. aiVector3D normal = curNormals.at(j);
  1168. unsigned int count = 0;
  1169. const unsigned int *outIndices = mesh.ToOutputVertexIndex(curIndex, count);
  1170. for (unsigned int k = 0; k < count; k++) {
  1171. unsigned int outIndex = outIndices[k];
  1172. if (translateIndexMap.find(outIndex) == translateIndexMap.end())
  1173. continue;
  1174. unsigned int transIndex = translateIndexMap[outIndex];
  1175. animMesh->mVertices[transIndex] += vertex;
  1176. if (animMesh->mNormals != nullptr) {
  1177. animMesh->mNormals[transIndex] += normal;
  1178. animMesh->mNormals[transIndex].NormalizeSafe();
  1179. }
  1180. }
  1181. }
  1182. animMesh->mWeight = shapeGeometries.size() > 1 ? blendShapeChannel->DeformPercent() / 100.0f : 1.0f;
  1183. animMeshes.push_back(animMesh);
  1184. }
  1185. }
  1186. }
  1187. const size_t numAnimMeshes = animMeshes.size();
  1188. if (numAnimMeshes > 0) {
  1189. out_mesh->mNumAnimMeshes = static_cast<unsigned int>(numAnimMeshes);
  1190. out_mesh->mAnimMeshes = new aiAnimMesh *[numAnimMeshes];
  1191. for (size_t i = 0; i < numAnimMeshes; i++) {
  1192. out_mesh->mAnimMeshes[i] = animMeshes.at(i);
  1193. }
  1194. }
  1195. return static_cast<unsigned int>(mMeshes.size() - 1);
  1196. }
  1197. void FBXConverter::ConvertWeights(aiMesh *out, const MeshGeometry &geo,
  1198. const aiMatrix4x4 &absolute_transform,
  1199. aiNode *parent, unsigned int materialIndex,
  1200. std::vector<unsigned int> *outputVertStartIndices) {
  1201. ai_assert(geo.DeformerSkin());
  1202. std::vector<size_t> out_indices;
  1203. std::vector<size_t> index_out_indices;
  1204. std::vector<size_t> count_out_indices;
  1205. const Skin &sk = *geo.DeformerSkin();
  1206. std::vector<aiBone *> bones;
  1207. const bool no_mat_check = materialIndex == NO_MATERIAL_SEPARATION;
  1208. ai_assert(no_mat_check || outputVertStartIndices);
  1209. try {
  1210. // iterate over the sub deformers
  1211. for (const Cluster *cluster : sk.Clusters()) {
  1212. ai_assert(cluster);
  1213. const WeightIndexArray &indices = cluster->GetIndices();
  1214. const MatIndexArray &mats = geo.GetMaterialIndices();
  1215. const size_t no_index_sentinel = std::numeric_limits<size_t>::max();
  1216. count_out_indices.clear();
  1217. index_out_indices.clear();
  1218. out_indices.clear();
  1219. // now check if *any* of these weights is contained in the output mesh,
  1220. // taking notes so we don't need to do it twice.
  1221. for (WeightIndexArray::value_type index : indices) {
  1222. unsigned int count = 0;
  1223. const unsigned int *const out_idx = geo.ToOutputVertexIndex(index, count);
  1224. // ToOutputVertexIndex only returns nullptr if index is out of bounds
  1225. // which should never happen
  1226. ai_assert(out_idx != nullptr);
  1227. index_out_indices.push_back(no_index_sentinel);
  1228. count_out_indices.push_back(0);
  1229. for (unsigned int i = 0; i < count; ++i) {
  1230. if (no_mat_check || static_cast<size_t>(mats[geo.FaceForVertexIndex(out_idx[i])]) == materialIndex) {
  1231. if (index_out_indices.back() == no_index_sentinel) {
  1232. index_out_indices.back() = out_indices.size();
  1233. }
  1234. if (no_mat_check) {
  1235. out_indices.push_back(out_idx[i]);
  1236. } else {
  1237. // this extra lookup is in O(logn), so the entire algorithm becomes O(nlogn)
  1238. const std::vector<unsigned int>::iterator it = std::lower_bound(
  1239. outputVertStartIndices->begin(),
  1240. outputVertStartIndices->end(),
  1241. out_idx[i]);
  1242. out_indices.push_back(std::distance(outputVertStartIndices->begin(), it));
  1243. }
  1244. ++count_out_indices.back();
  1245. }
  1246. }
  1247. }
  1248. // if we found at least one, generate the output bones
  1249. // XXX this could be heavily simplified by collecting the bone
  1250. // data in a single step.
  1251. ConvertCluster(bones, cluster, out_indices, index_out_indices,
  1252. count_out_indices, absolute_transform, parent);
  1253. }
  1254. bone_map.clear();
  1255. } catch (std::exception &) {
  1256. std::for_each(bones.begin(), bones.end(), Util::delete_fun<aiBone>());
  1257. throw;
  1258. }
  1259. if (bones.empty()) {
  1260. out->mBones = nullptr;
  1261. out->mNumBones = 0;
  1262. return;
  1263. } else {
  1264. out->mBones = new aiBone *[bones.size()]();
  1265. out->mNumBones = static_cast<unsigned int>(bones.size());
  1266. std::swap_ranges(bones.begin(), bones.end(), out->mBones);
  1267. }
  1268. }
  1269. const aiNode *GetNodeByName(aiNode *current_node) {
  1270. aiNode *iter = current_node;
  1271. //printf("Child count: %d", iter->mNumChildren);
  1272. return iter;
  1273. }
  1274. void FBXConverter::ConvertCluster(std::vector<aiBone *> &local_mesh_bones, const Cluster *cl,
  1275. std::vector<size_t> &out_indices, std::vector<size_t> &index_out_indices,
  1276. std::vector<size_t> &count_out_indices, const aiMatrix4x4 &absolute_transform,
  1277. aiNode *) {
  1278. ai_assert(cl); // make sure cluster valid
  1279. std::string deformer_name = cl->TargetNode()->Name();
  1280. aiString bone_name = aiString(FixNodeName(deformer_name));
  1281. aiBone *bone = nullptr;
  1282. if (bone_map.count(deformer_name)) {
  1283. ASSIMP_LOG_VERBOSE_DEBUG("retrieved bone from lookup ", bone_name.C_Str(), ". Deformer:", deformer_name);
  1284. bone = bone_map[deformer_name];
  1285. } else {
  1286. ASSIMP_LOG_VERBOSE_DEBUG("created new bone ", bone_name.C_Str(), ". Deformer: ", deformer_name);
  1287. bone = new aiBone();
  1288. bone->mName = bone_name;
  1289. // store local transform link for post processing
  1290. bone->mOffsetMatrix = cl->TransformLink();
  1291. bone->mOffsetMatrix.Inverse();
  1292. aiMatrix4x4 matrix = (aiMatrix4x4)absolute_transform;
  1293. bone->mOffsetMatrix = bone->mOffsetMatrix * matrix; // * mesh_offset
  1294. //
  1295. // Now calculate the aiVertexWeights
  1296. //
  1297. aiVertexWeight *cursor = nullptr;
  1298. bone->mNumWeights = static_cast<unsigned int>(out_indices.size());
  1299. cursor = bone->mWeights = new aiVertexWeight[out_indices.size()];
  1300. const size_t no_index_sentinel = std::numeric_limits<size_t>::max();
  1301. const WeightArray &weights = cl->GetWeights();
  1302. const size_t c = index_out_indices.size();
  1303. for (size_t i = 0; i < c; ++i) {
  1304. const size_t index_index = index_out_indices[i];
  1305. if (index_index == no_index_sentinel) {
  1306. continue;
  1307. }
  1308. const size_t cc = count_out_indices[i];
  1309. for (size_t j = 0; j < cc; ++j) {
  1310. // cursor runs from first element relative to the start
  1311. // or relative to the start of the next indexes.
  1312. aiVertexWeight &out_weight = *cursor++;
  1313. out_weight.mVertexId = static_cast<unsigned int>(out_indices[index_index + j]);
  1314. out_weight.mWeight = weights[i];
  1315. }
  1316. }
  1317. bone_map.insert(std::pair<const std::string, aiBone *>(deformer_name, bone));
  1318. }
  1319. ASSIMP_LOG_DEBUG("bone research: Indicies size: ", out_indices.size());
  1320. // lookup must be populated in case something goes wrong
  1321. // this also allocates bones to mesh instance outside
  1322. local_mesh_bones.push_back(bone);
  1323. }
  1324. void FBXConverter::ConvertMaterialForMesh(aiMesh *out, const Model &model, const MeshGeometry &geo,
  1325. MatIndexArray::value_type materialIndex) {
  1326. // locate source materials for this mesh
  1327. const std::vector<const Material *> &mats = model.GetMaterials();
  1328. if (static_cast<unsigned int>(materialIndex) >= mats.size() || materialIndex < 0) {
  1329. FBXImporter::LogError("material index out of bounds, setting default material");
  1330. out->mMaterialIndex = GetDefaultMaterial();
  1331. return;
  1332. }
  1333. const Material *const mat = mats[materialIndex];
  1334. MaterialMap::const_iterator it = materials_converted.find(mat);
  1335. if (it != materials_converted.end()) {
  1336. out->mMaterialIndex = (*it).second;
  1337. return;
  1338. }
  1339. out->mMaterialIndex = ConvertMaterial(*mat, &geo);
  1340. materials_converted[mat] = out->mMaterialIndex;
  1341. }
  1342. unsigned int FBXConverter::GetDefaultMaterial() {
  1343. if (defaultMaterialIndex) {
  1344. return defaultMaterialIndex - 1;
  1345. }
  1346. aiMaterial *out_mat = new aiMaterial();
  1347. materials.push_back(out_mat);
  1348. const aiColor3D diffuse = aiColor3D(0.8f, 0.8f, 0.8f);
  1349. out_mat->AddProperty(&diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  1350. aiString s;
  1351. s.Set(AI_DEFAULT_MATERIAL_NAME);
  1352. out_mat->AddProperty(&s, AI_MATKEY_NAME);
  1353. defaultMaterialIndex = static_cast<unsigned int>(materials.size());
  1354. return defaultMaterialIndex - 1;
  1355. }
  1356. unsigned int FBXConverter::ConvertMaterial(const Material &material, const MeshGeometry *const mesh) {
  1357. const PropertyTable &props = material.Props();
  1358. // generate empty output material
  1359. aiMaterial *out_mat = new aiMaterial();
  1360. materials_converted[&material] = static_cast<unsigned int>(materials.size());
  1361. materials.push_back(out_mat);
  1362. aiString str;
  1363. // strip Material:: prefix
  1364. std::string name = material.Name();
  1365. if (name.substr(0, 10) == "Material::") {
  1366. name = name.substr(10);
  1367. }
  1368. // set material name if not empty - this could happen
  1369. // and there should be no key for it in this case.
  1370. if (name.length()) {
  1371. str.Set(name);
  1372. out_mat->AddProperty(&str, AI_MATKEY_NAME);
  1373. }
  1374. // Set the shading mode as best we can: The FBX specification only mentions Lambert and Phong, and only Phong is mentioned in Assimp's aiShadingMode enum.
  1375. if (material.GetShadingModel() == "phong") {
  1376. aiShadingMode shadingMode = aiShadingMode_Phong;
  1377. out_mat->AddProperty<aiShadingMode>(&shadingMode, 1, AI_MATKEY_SHADING_MODEL);
  1378. }
  1379. // shading stuff and colors
  1380. SetShadingPropertiesCommon(out_mat, props);
  1381. SetShadingPropertiesRaw(out_mat, props, material.Textures(), mesh);
  1382. // texture assignments
  1383. SetTextureProperties(out_mat, material.Textures(), mesh);
  1384. SetTextureProperties(out_mat, material.LayeredTextures(), mesh);
  1385. return static_cast<unsigned int>(materials.size() - 1);
  1386. }
  1387. unsigned int FBXConverter::ConvertVideo(const Video &video) {
  1388. // generate empty output texture
  1389. aiTexture *out_tex = new aiTexture();
  1390. textures.push_back(out_tex);
  1391. // assuming the texture is compressed
  1392. out_tex->mWidth = static_cast<unsigned int>(video.ContentLength()); // total data size
  1393. out_tex->mHeight = 0; // fixed to 0
  1394. // steal the data from the Video to avoid an additional copy
  1395. out_tex->pcData = reinterpret_cast<aiTexel *>(const_cast<Video &>(video).RelinquishContent());
  1396. // try to extract a hint from the file extension
  1397. const std::string &filename = video.RelativeFilename().empty() ? video.FileName() : video.RelativeFilename();
  1398. std::string ext = BaseImporter::GetExtension(filename);
  1399. if (ext == "jpeg") {
  1400. ext = "jpg";
  1401. }
  1402. if (ext.size() <= 3) {
  1403. memcpy(out_tex->achFormatHint, ext.c_str(), ext.size());
  1404. }
  1405. out_tex->mFilename.Set(filename.c_str());
  1406. return static_cast<unsigned int>(textures.size() - 1);
  1407. }
  1408. aiString FBXConverter::GetTexturePath(const Texture *tex) {
  1409. aiString path;
  1410. path.Set(tex->RelativeFilename());
  1411. const Video *media = tex->Media();
  1412. if (media != nullptr) {
  1413. bool textureReady = false; //tells if our texture is ready (if it was loaded or if it was found)
  1414. unsigned int index=0;
  1415. VideoMap::const_iterator it = textures_converted.find(media);
  1416. if (it != textures_converted.end()) {
  1417. index = (*it).second;
  1418. textureReady = true;
  1419. } else {
  1420. if (media->ContentLength() > 0) {
  1421. index = ConvertVideo(*media);
  1422. textures_converted[media] = index;
  1423. textureReady = true;
  1424. }
  1425. }
  1426. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture), if the texture is ready
  1427. if (doc.Settings().useLegacyEmbeddedTextureNaming) {
  1428. if (textureReady) {
  1429. // TODO: check the possibility of using the flag "AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING"
  1430. // In FBX files textures are now stored internally by Assimp with their filename included
  1431. // Now Assimp can lookup through the loaded textures after all data is processed
  1432. // We need to load all textures before referencing them, as FBX file format order may reference a texture before loading it
  1433. // This may occur on this case too, it has to be studied
  1434. path.data[0] = '*';
  1435. path.length = 1 + ASSIMP_itoa10(path.data + 1, MAXLEN - 1, index);
  1436. }
  1437. }
  1438. }
  1439. return path;
  1440. }
  1441. void FBXConverter::TrySetTextureProperties(aiMaterial *out_mat, const TextureMap &_textures,
  1442. const std::string &propName,
  1443. aiTextureType target, const MeshGeometry *const mesh) {
  1444. TextureMap::const_iterator it = _textures.find(propName);
  1445. if (it == _textures.end()) {
  1446. return;
  1447. }
  1448. const Texture *const tex = (*it).second;
  1449. if (tex != nullptr) {
  1450. aiString path = GetTexturePath(tex);
  1451. out_mat->AddProperty(&path, _AI_MATKEY_TEXTURE_BASE, target, 0);
  1452. aiUVTransform uvTrafo;
  1453. // XXX handle all kinds of UV transformations
  1454. uvTrafo.mScaling = tex->UVScaling();
  1455. uvTrafo.mTranslation = tex->UVTranslation();
  1456. out_mat->AddProperty(&uvTrafo, 1, _AI_MATKEY_UVTRANSFORM_BASE, target, 0);
  1457. const PropertyTable &props = tex->Props();
  1458. int uvIndex = 0;
  1459. bool ok;
  1460. const std::string &uvSet = PropertyGet<std::string>(props, "UVSet", ok);
  1461. if (ok) {
  1462. // "default" is the name which usually appears in the FbxFileTexture template
  1463. if (uvSet != "default" && uvSet.length()) {
  1464. // this is a bit awkward - we need to find a mesh that uses this
  1465. // material and scan its UV channels for the given UV name because
  1466. // assimp references UV channels by index, not by name.
  1467. // XXX: the case that UV channels may appear in different orders
  1468. // in meshes is unhandled. A possible solution would be to sort
  1469. // the UV channels alphabetically, but this would have the side
  1470. // effect that the primary (first) UV channel would sometimes
  1471. // be moved, causing trouble when users read only the first
  1472. // UV channel and ignore UV channel assignments altogether.
  1473. const unsigned int matIndex = static_cast<unsigned int>(std::distance(materials.begin(),
  1474. std::find(materials.begin(), materials.end(), out_mat)));
  1475. uvIndex = -1;
  1476. if (!mesh) {
  1477. for (const MeshMap::value_type &v : meshes_converted) {
  1478. const MeshGeometry *const meshGeom = dynamic_cast<const MeshGeometry *>(v.first);
  1479. if (!meshGeom) {
  1480. continue;
  1481. }
  1482. const MatIndexArray &mats = meshGeom->GetMaterialIndices();
  1483. MatIndexArray::const_iterator curIt = std::find(mats.begin(), mats.end(), (int) matIndex);
  1484. if (curIt == mats.end()) {
  1485. continue;
  1486. }
  1487. int index = -1;
  1488. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1489. if (meshGeom->GetTextureCoords(i).empty()) {
  1490. break;
  1491. }
  1492. const std::string &name = meshGeom->GetTextureCoordChannelName(i);
  1493. if (name == uvSet) {
  1494. index = static_cast<int>(i);
  1495. break;
  1496. }
  1497. }
  1498. if (index == -1) {
  1499. FBXImporter::LogWarn("did not find UV channel named ", uvSet, " in a mesh using this material");
  1500. continue;
  1501. }
  1502. if (uvIndex == -1) {
  1503. uvIndex = index;
  1504. } else {
  1505. FBXImporter::LogWarn("the UV channel named ", uvSet,
  1506. " appears at different positions in meshes, results will be wrong");
  1507. }
  1508. }
  1509. } else {
  1510. int index = -1;
  1511. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1512. if (mesh->GetTextureCoords(i).empty()) {
  1513. break;
  1514. }
  1515. const std::string &name = mesh->GetTextureCoordChannelName(i);
  1516. if (name == uvSet) {
  1517. index = static_cast<int>(i);
  1518. break;
  1519. }
  1520. }
  1521. if (index == -1) {
  1522. FBXImporter::LogWarn("did not find UV channel named ", uvSet, " in a mesh using this material");
  1523. }
  1524. if (uvIndex == -1) {
  1525. uvIndex = index;
  1526. }
  1527. }
  1528. if (uvIndex == -1) {
  1529. FBXImporter::LogWarn("failed to resolve UV channel ", uvSet, ", using first UV channel");
  1530. uvIndex = 0;
  1531. }
  1532. }
  1533. }
  1534. out_mat->AddProperty(&uvIndex, 1, _AI_MATKEY_UVWSRC_BASE, target, 0);
  1535. }
  1536. }
  1537. void FBXConverter::TrySetTextureProperties(aiMaterial *out_mat, const LayeredTextureMap &layeredTextures,
  1538. const std::string &propName,
  1539. aiTextureType target, const MeshGeometry *const mesh) {
  1540. LayeredTextureMap::const_iterator it = layeredTextures.find(propName);
  1541. if (it == layeredTextures.end()) {
  1542. return;
  1543. }
  1544. int texCount = (*it).second->textureCount();
  1545. // Set the blend mode for layered textures
  1546. int blendmode = (*it).second->GetBlendMode();
  1547. out_mat->AddProperty(&blendmode, 1, _AI_MATKEY_TEXOP_BASE, target, 0);
  1548. for (int texIndex = 0; texIndex < texCount; texIndex++) {
  1549. const Texture *const tex = (*it).second->getTexture(texIndex);
  1550. aiString path = GetTexturePath(tex);
  1551. out_mat->AddProperty(&path, _AI_MATKEY_TEXTURE_BASE, target, texIndex);
  1552. aiUVTransform uvTrafo;
  1553. // XXX handle all kinds of UV transformations
  1554. uvTrafo.mScaling = tex->UVScaling();
  1555. uvTrafo.mTranslation = tex->UVTranslation();
  1556. out_mat->AddProperty(&uvTrafo, 1, _AI_MATKEY_UVTRANSFORM_BASE, target, texIndex);
  1557. const PropertyTable &props = tex->Props();
  1558. int uvIndex = 0;
  1559. bool ok;
  1560. const std::string &uvSet = PropertyGet<std::string>(props, "UVSet", ok);
  1561. if (ok) {
  1562. // "default" is the name which usually appears in the FbxFileTexture template
  1563. if (uvSet != "default" && uvSet.length()) {
  1564. // this is a bit awkward - we need to find a mesh that uses this
  1565. // material and scan its UV channels for the given UV name because
  1566. // assimp references UV channels by index, not by name.
  1567. // XXX: the case that UV channels may appear in different orders
  1568. // in meshes is unhandled. A possible solution would be to sort
  1569. // the UV channels alphabetically, but this would have the side
  1570. // effect that the primary (first) UV channel would sometimes
  1571. // be moved, causing trouble when users read only the first
  1572. // UV channel and ignore UV channel assignments altogether.
  1573. const unsigned int matIndex = static_cast<unsigned int>(std::distance(materials.begin(),
  1574. std::find(materials.begin(), materials.end(), out_mat)));
  1575. uvIndex = -1;
  1576. if (!mesh) {
  1577. for (const MeshMap::value_type &v : meshes_converted) {
  1578. const MeshGeometry *const meshGeom = dynamic_cast<const MeshGeometry *>(v.first);
  1579. if (!meshGeom) {
  1580. continue;
  1581. }
  1582. const MatIndexArray &mats = meshGeom->GetMaterialIndices();
  1583. MatIndexArray::const_iterator curIt = std::find(mats.begin(), mats.end(), (int) matIndex);
  1584. if ( curIt == mats.end()) {
  1585. continue;
  1586. }
  1587. int index = -1;
  1588. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1589. if (meshGeom->GetTextureCoords(i).empty()) {
  1590. break;
  1591. }
  1592. const std::string &name = meshGeom->GetTextureCoordChannelName(i);
  1593. if (name == uvSet) {
  1594. index = static_cast<int>(i);
  1595. break;
  1596. }
  1597. }
  1598. if (index == -1) {
  1599. FBXImporter::LogWarn("did not find UV channel named ", uvSet, " in a mesh using this material");
  1600. continue;
  1601. }
  1602. if (uvIndex == -1) {
  1603. uvIndex = index;
  1604. } else {
  1605. FBXImporter::LogWarn("the UV channel named ", uvSet,
  1606. " appears at different positions in meshes, results will be wrong");
  1607. }
  1608. }
  1609. } else {
  1610. int index = -1;
  1611. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1612. if (mesh->GetTextureCoords(i).empty()) {
  1613. break;
  1614. }
  1615. const std::string &name = mesh->GetTextureCoordChannelName(i);
  1616. if (name == uvSet) {
  1617. index = static_cast<int>(i);
  1618. break;
  1619. }
  1620. }
  1621. if (index == -1) {
  1622. FBXImporter::LogWarn("did not find UV channel named ", uvSet, " in a mesh using this material");
  1623. }
  1624. if (uvIndex == -1) {
  1625. uvIndex = index;
  1626. }
  1627. }
  1628. if (uvIndex == -1) {
  1629. FBXImporter::LogWarn("failed to resolve UV channel ", uvSet, ", using first UV channel");
  1630. uvIndex = 0;
  1631. }
  1632. }
  1633. }
  1634. out_mat->AddProperty(&uvIndex, 1, _AI_MATKEY_UVWSRC_BASE, target, texIndex);
  1635. }
  1636. }
  1637. void FBXConverter::SetTextureProperties(aiMaterial *out_mat, const TextureMap &_textures, const MeshGeometry *const mesh) {
  1638. TrySetTextureProperties(out_mat, _textures, "DiffuseColor", aiTextureType_DIFFUSE, mesh);
  1639. TrySetTextureProperties(out_mat, _textures, "AmbientColor", aiTextureType_AMBIENT, mesh);
  1640. TrySetTextureProperties(out_mat, _textures, "EmissiveColor", aiTextureType_EMISSIVE, mesh);
  1641. TrySetTextureProperties(out_mat, _textures, "SpecularColor", aiTextureType_SPECULAR, mesh);
  1642. TrySetTextureProperties(out_mat, _textures, "SpecularFactor", aiTextureType_SPECULAR, mesh);
  1643. TrySetTextureProperties(out_mat, _textures, "TransparentColor", aiTextureType_OPACITY, mesh);
  1644. TrySetTextureProperties(out_mat, _textures, "ReflectionColor", aiTextureType_REFLECTION, mesh);
  1645. TrySetTextureProperties(out_mat, _textures, "DisplacementColor", aiTextureType_DISPLACEMENT, mesh);
  1646. TrySetTextureProperties(out_mat, _textures, "NormalMap", aiTextureType_NORMALS, mesh);
  1647. TrySetTextureProperties(out_mat, _textures, "Bump", aiTextureType_HEIGHT, mesh);
  1648. TrySetTextureProperties(out_mat, _textures, "ShininessExponent", aiTextureType_SHININESS, mesh);
  1649. TrySetTextureProperties(out_mat, _textures, "TransparencyFactor", aiTextureType_OPACITY, mesh);
  1650. TrySetTextureProperties(out_mat, _textures, "EmissiveFactor", aiTextureType_EMISSIVE, mesh);
  1651. TrySetTextureProperties(out_mat, _textures, "ReflectionFactor", aiTextureType_METALNESS, mesh);
  1652. //Maya counterparts
  1653. TrySetTextureProperties(out_mat, _textures, "Maya|DiffuseTexture", aiTextureType_DIFFUSE, mesh);
  1654. TrySetTextureProperties(out_mat, _textures, "Maya|NormalTexture", aiTextureType_NORMALS, mesh);
  1655. TrySetTextureProperties(out_mat, _textures, "Maya|SpecularTexture", aiTextureType_SPECULAR, mesh);
  1656. TrySetTextureProperties(out_mat, _textures, "Maya|FalloffTexture", aiTextureType_OPACITY, mesh);
  1657. TrySetTextureProperties(out_mat, _textures, "Maya|ReflectionMapTexture", aiTextureType_REFLECTION, mesh);
  1658. // Maya PBR
  1659. TrySetTextureProperties(out_mat, _textures, "Maya|baseColor", aiTextureType_BASE_COLOR, mesh);
  1660. TrySetTextureProperties(out_mat, _textures, "Maya|normalCamera", aiTextureType_NORMAL_CAMERA, mesh);
  1661. TrySetTextureProperties(out_mat, _textures, "Maya|emissionColor", aiTextureType_EMISSION_COLOR, mesh);
  1662. TrySetTextureProperties(out_mat, _textures, "Maya|metalness", aiTextureType_METALNESS, mesh);
  1663. TrySetTextureProperties(out_mat, _textures, "Maya|diffuseRoughness", aiTextureType_DIFFUSE_ROUGHNESS, mesh);
  1664. // Maya stingray
  1665. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_color_map", aiTextureType_BASE_COLOR, mesh);
  1666. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_normal_map", aiTextureType_NORMAL_CAMERA, mesh);
  1667. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_emissive_map", aiTextureType_EMISSION_COLOR, mesh);
  1668. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_metallic_map", aiTextureType_METALNESS, mesh);
  1669. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_roughness_map", aiTextureType_DIFFUSE_ROUGHNESS, mesh);
  1670. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_ao_map", aiTextureType_AMBIENT_OCCLUSION, mesh);
  1671. // 3DSMax Physical material
  1672. TrySetTextureProperties(out_mat, _textures, "3dsMax|Parameters|base_color_map", aiTextureType_BASE_COLOR, mesh);
  1673. TrySetTextureProperties(out_mat, _textures, "3dsMax|Parameters|bump_map", aiTextureType_NORMAL_CAMERA, mesh);
  1674. TrySetTextureProperties(out_mat, _textures, "3dsMax|Parameters|emission_map", aiTextureType_EMISSION_COLOR, mesh);
  1675. TrySetTextureProperties(out_mat, _textures, "3dsMax|Parameters|metalness_map", aiTextureType_METALNESS, mesh);
  1676. TrySetTextureProperties(out_mat, _textures, "3dsMax|Parameters|roughness_map", aiTextureType_DIFFUSE_ROUGHNESS, mesh);
  1677. // 3DSMax PBR materials
  1678. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|base_color_map", aiTextureType_BASE_COLOR, mesh);
  1679. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|norm_map", aiTextureType_NORMAL_CAMERA, mesh);
  1680. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|emit_color_map", aiTextureType_EMISSION_COLOR, mesh);
  1681. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|ao_map", aiTextureType_AMBIENT_OCCLUSION, mesh);
  1682. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|opacity_map", aiTextureType_OPACITY, mesh);
  1683. // Metalness/Roughness material type
  1684. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|metalness_map", aiTextureType_METALNESS, mesh);
  1685. // Specular/Gloss material type
  1686. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|specular_map", aiTextureType_SPECULAR, mesh);
  1687. // Glossiness vs roughness in 3ds Max Pbr Materials
  1688. int useGlossiness;
  1689. if (out_mat->Get("$raw.3dsMax|main|useGlossiness", aiTextureType_NONE, 0, useGlossiness) == aiReturn_SUCCESS) {
  1690. // These textures swap meaning if ((useGlossiness == 1) != (material type is Specular/Gloss))
  1691. if (useGlossiness == 1) {
  1692. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|roughness_map", aiTextureType_SHININESS, mesh);
  1693. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|glossiness_map", aiTextureType_SHININESS, mesh);
  1694. }
  1695. else if (useGlossiness == 2) {
  1696. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|roughness_map", aiTextureType_DIFFUSE_ROUGHNESS, mesh);
  1697. TrySetTextureProperties(out_mat, _textures, "3dsMax|main|glossiness_map", aiTextureType_DIFFUSE_ROUGHNESS, mesh);
  1698. }
  1699. else {
  1700. FBXImporter::LogWarn("A 3dsMax Pbr Material must have a useGlossiness value to correctly interpret roughness and glossiness textures.");
  1701. }
  1702. }
  1703. }
  1704. void FBXConverter::SetTextureProperties(aiMaterial *out_mat, const LayeredTextureMap &layeredTextures, const MeshGeometry *const mesh) {
  1705. TrySetTextureProperties(out_mat, layeredTextures, "DiffuseColor", aiTextureType_DIFFUSE, mesh);
  1706. TrySetTextureProperties(out_mat, layeredTextures, "AmbientColor", aiTextureType_AMBIENT, mesh);
  1707. TrySetTextureProperties(out_mat, layeredTextures, "EmissiveColor", aiTextureType_EMISSIVE, mesh);
  1708. TrySetTextureProperties(out_mat, layeredTextures, "SpecularColor", aiTextureType_SPECULAR, mesh);
  1709. TrySetTextureProperties(out_mat, layeredTextures, "SpecularFactor", aiTextureType_SPECULAR, mesh);
  1710. TrySetTextureProperties(out_mat, layeredTextures, "TransparentColor", aiTextureType_OPACITY, mesh);
  1711. TrySetTextureProperties(out_mat, layeredTextures, "ReflectionColor", aiTextureType_REFLECTION, mesh);
  1712. TrySetTextureProperties(out_mat, layeredTextures, "DisplacementColor", aiTextureType_DISPLACEMENT, mesh);
  1713. TrySetTextureProperties(out_mat, layeredTextures, "NormalMap", aiTextureType_NORMALS, mesh);
  1714. TrySetTextureProperties(out_mat, layeredTextures, "Bump", aiTextureType_HEIGHT, mesh);
  1715. TrySetTextureProperties(out_mat, layeredTextures, "ShininessExponent", aiTextureType_SHININESS, mesh);
  1716. TrySetTextureProperties(out_mat, layeredTextures, "EmissiveFactor", aiTextureType_EMISSIVE, mesh);
  1717. TrySetTextureProperties(out_mat, layeredTextures, "TransparencyFactor", aiTextureType_OPACITY, mesh);
  1718. }
  1719. aiColor3D FBXConverter::GetColorPropertyFactored(const PropertyTable &props, const std::string &colorName,
  1720. const std::string &factorName, bool &result, bool useTemplate) {
  1721. result = true;
  1722. bool ok;
  1723. aiVector3D BaseColor = PropertyGet<aiVector3D>(props, colorName, ok, useTemplate);
  1724. if (!ok) {
  1725. result = false;
  1726. return aiColor3D(0.0f, 0.0f, 0.0f);
  1727. }
  1728. // if no factor name, return the colour as is
  1729. if (factorName.empty()) {
  1730. return aiColor3D(BaseColor.x, BaseColor.y, BaseColor.z);
  1731. }
  1732. // otherwise it should be multiplied by the factor, if found.
  1733. float factor = PropertyGet<float>(props, factorName, ok, useTemplate);
  1734. if (ok) {
  1735. BaseColor *= factor;
  1736. }
  1737. return aiColor3D(BaseColor.x, BaseColor.y, BaseColor.z);
  1738. }
  1739. aiColor3D FBXConverter::GetColorPropertyFromMaterial(const PropertyTable &props, const std::string &baseName,
  1740. bool &result) {
  1741. return GetColorPropertyFactored(props, baseName + "Color", baseName + "Factor", result, true);
  1742. }
  1743. aiColor3D FBXConverter::GetColorProperty(const PropertyTable &props, const std::string &colorName,
  1744. bool &result, bool useTemplate) {
  1745. result = true;
  1746. bool ok;
  1747. const aiVector3D &ColorVec = PropertyGet<aiVector3D>(props, colorName, ok, useTemplate);
  1748. if (!ok) {
  1749. result = false;
  1750. return aiColor3D(0.0f, 0.0f, 0.0f);
  1751. }
  1752. return aiColor3D(ColorVec.x, ColorVec.y, ColorVec.z);
  1753. }
  1754. void FBXConverter::SetShadingPropertiesCommon(aiMaterial *out_mat, const PropertyTable &props) {
  1755. // Set shading properties.
  1756. // Modern FBX Files have two separate systems for defining these,
  1757. // with only the more comprehensive one described in the property template.
  1758. // Likely the other values are a legacy system,
  1759. // which is still always exported by the official FBX SDK.
  1760. //
  1761. // Blender's FBX import and export mostly ignore this legacy system,
  1762. // and as we only support recent versions of FBX anyway, we can do the same.
  1763. bool ok;
  1764. const aiColor3D &Diffuse = GetColorPropertyFromMaterial(props, "Diffuse", ok);
  1765. if (ok) {
  1766. out_mat->AddProperty(&Diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  1767. }
  1768. const aiColor3D &Emissive = GetColorPropertyFromMaterial(props, "Emissive", ok);
  1769. if (ok) {
  1770. out_mat->AddProperty(&Emissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  1771. } else {
  1772. const aiColor3D &emissiveColor = GetColorPropertyFromMaterial(props, "Maya|emissive", ok);
  1773. if (ok) {
  1774. out_mat->AddProperty(&emissiveColor, 1, AI_MATKEY_COLOR_EMISSIVE);
  1775. }
  1776. }
  1777. const aiColor3D &Ambient = GetColorPropertyFromMaterial(props, "Ambient", ok);
  1778. if (ok) {
  1779. out_mat->AddProperty(&Ambient, 1, AI_MATKEY_COLOR_AMBIENT);
  1780. }
  1781. // we store specular factor as SHININESS_STRENGTH, so just get the color
  1782. const aiColor3D &Specular = GetColorProperty(props, "SpecularColor", ok, true);
  1783. if (ok) {
  1784. out_mat->AddProperty(&Specular, 1, AI_MATKEY_COLOR_SPECULAR);
  1785. }
  1786. // and also try to get SHININESS_STRENGTH
  1787. const float SpecularFactor = PropertyGet<float>(props, "SpecularFactor", ok, true);
  1788. if (ok) {
  1789. out_mat->AddProperty(&SpecularFactor, 1, AI_MATKEY_SHININESS_STRENGTH);
  1790. }
  1791. // and the specular exponent
  1792. const float ShininessExponent = PropertyGet<float>(props, "ShininessExponent", ok);
  1793. if (ok) {
  1794. out_mat->AddProperty(&ShininessExponent, 1, AI_MATKEY_SHININESS);
  1795. }
  1796. // TransparentColor / TransparencyFactor... gee thanks FBX :rolleyes:
  1797. const aiColor3D &Transparent = GetColorPropertyFactored(props, "TransparentColor", "TransparencyFactor", ok);
  1798. float CalculatedOpacity = 1.0f;
  1799. if (ok) {
  1800. out_mat->AddProperty(&Transparent, 1, AI_MATKEY_COLOR_TRANSPARENT);
  1801. // as calculated by FBX SDK 2017:
  1802. CalculatedOpacity = 1.0f - ((Transparent.r + Transparent.g + Transparent.b) / 3.0f);
  1803. }
  1804. // try to get the transparency factor
  1805. const float TransparencyFactor = PropertyGet<float>(props, "TransparencyFactor", ok);
  1806. if (ok) {
  1807. out_mat->AddProperty(&TransparencyFactor, 1, AI_MATKEY_TRANSPARENCYFACTOR);
  1808. }
  1809. // use of TransparencyFactor is inconsistent.
  1810. // Maya always stores it as 1.0,
  1811. // so we can't use it to set AI_MATKEY_OPACITY.
  1812. // Blender is more sensible and stores it as the alpha value.
  1813. // However both the FBX SDK and Blender always write an additional
  1814. // legacy "Opacity" field, so we can try to use that.
  1815. //
  1816. // If we can't find it,
  1817. // we can fall back to the value which the FBX SDK calculates
  1818. // from transparency colour (RGB) and factor (F) as
  1819. // 1.0 - F*((R+G+B)/3).
  1820. //
  1821. // There's no consistent way to interpret this opacity value,
  1822. // so it's up to clients to do the correct thing.
  1823. const float Opacity = PropertyGet<float>(props, "Opacity", ok);
  1824. if (ok) {
  1825. out_mat->AddProperty(&Opacity, 1, AI_MATKEY_OPACITY);
  1826. } else if (CalculatedOpacity != 1.0) {
  1827. out_mat->AddProperty(&CalculatedOpacity, 1, AI_MATKEY_OPACITY);
  1828. }
  1829. // reflection color and factor are stored separately
  1830. const aiColor3D &Reflection = GetColorProperty(props, "ReflectionColor", ok, true);
  1831. if (ok) {
  1832. out_mat->AddProperty(&Reflection, 1, AI_MATKEY_COLOR_REFLECTIVE);
  1833. }
  1834. float ReflectionFactor = PropertyGet<float>(props, "ReflectionFactor", ok, true);
  1835. if (ok) {
  1836. out_mat->AddProperty(&ReflectionFactor, 1, AI_MATKEY_REFLECTIVITY);
  1837. }
  1838. const float BumpFactor = PropertyGet<float>(props, "BumpFactor", ok);
  1839. if (ok) {
  1840. out_mat->AddProperty(&BumpFactor, 1, AI_MATKEY_BUMPSCALING);
  1841. }
  1842. const float DispFactor = PropertyGet<float>(props, "DisplacementFactor", ok);
  1843. if (ok) {
  1844. out_mat->AddProperty(&DispFactor, 1, "$mat.displacementscaling", 0, 0);
  1845. }
  1846. // PBR material information
  1847. const aiColor3D &baseColor = GetColorPropertyFromMaterial(props, "Maya|base_color", ok);
  1848. if (ok) {
  1849. out_mat->AddProperty(&baseColor, 1, AI_MATKEY_BASE_COLOR);
  1850. }
  1851. const float useColorMap = PropertyGet<float>(props, "Maya|use_color_map", ok);
  1852. if (ok) {
  1853. out_mat->AddProperty(&useColorMap, 1, AI_MATKEY_USE_COLOR_MAP);
  1854. }
  1855. const float useMetallicMap = PropertyGet<float>(props, "Maya|use_metallic_map", ok);
  1856. if (ok) {
  1857. out_mat->AddProperty(&useMetallicMap, 1, AI_MATKEY_USE_METALLIC_MAP);
  1858. }
  1859. const float metallicFactor = PropertyGet<float>(props, "Maya|metallic", ok);
  1860. if (ok) {
  1861. out_mat->AddProperty(&metallicFactor, 1, AI_MATKEY_METALLIC_FACTOR);
  1862. }
  1863. const float useRoughnessMap = PropertyGet<float>(props, "Maya|use_roughness_map", ok);
  1864. if (ok) {
  1865. out_mat->AddProperty(&useRoughnessMap, 1, AI_MATKEY_USE_ROUGHNESS_MAP);
  1866. }
  1867. const float roughnessFactor = PropertyGet<float>(props, "Maya|roughness", ok);
  1868. if (ok) {
  1869. out_mat->AddProperty(&roughnessFactor, 1, AI_MATKEY_ROUGHNESS_FACTOR);
  1870. }
  1871. const float useEmissiveMap = PropertyGet<float>(props, "Maya|use_emissive_map", ok);
  1872. if (ok) {
  1873. out_mat->AddProperty(&useEmissiveMap, 1, AI_MATKEY_USE_EMISSIVE_MAP);
  1874. }
  1875. const float emissiveIntensity = PropertyGet<float>(props, "Maya|emissive_intensity", ok);
  1876. if (ok) {
  1877. out_mat->AddProperty(&emissiveIntensity, 1, AI_MATKEY_EMISSIVE_INTENSITY);
  1878. }
  1879. const float useAOMap = PropertyGet<float>(props, "Maya|use_ao_map", ok);
  1880. if (ok) {
  1881. out_mat->AddProperty(&useAOMap, 1, AI_MATKEY_USE_AO_MAP);
  1882. }
  1883. }
  1884. void FBXConverter::SetShadingPropertiesRaw(aiMaterial *out_mat, const PropertyTable &props, const TextureMap &_textures, const MeshGeometry *const mesh) {
  1885. // Add all the unparsed properties with a "$raw." prefix
  1886. const std::string prefix = "$raw.";
  1887. for (const DirectPropertyMap::value_type &prop : props.GetUnparsedProperties()) {
  1888. std::string name = prefix + prop.first;
  1889. if (const TypedProperty<aiVector3D> *interpretedVec3 = prop.second->As<TypedProperty<aiVector3D>>()) {
  1890. out_mat->AddProperty(&interpretedVec3->Value(), 1, name.c_str(), 0, 0);
  1891. } else if (const TypedProperty<aiColor3D> *interpretedCol3 = prop.second->As<TypedProperty<aiColor3D>>()) {
  1892. out_mat->AddProperty(&interpretedCol3->Value(), 1, name.c_str(), 0, 0);
  1893. } else if (const TypedProperty<aiColor4D> *interpretedCol4 = prop.second->As<TypedProperty<aiColor4D>>()) {
  1894. out_mat->AddProperty(&interpretedCol4->Value(), 1, name.c_str(), 0, 0);
  1895. } else if (const TypedProperty<float> *interpretedFloat = prop.second->As<TypedProperty<float>>()) {
  1896. out_mat->AddProperty(&interpretedFloat->Value(), 1, name.c_str(), 0, 0);
  1897. } else if (const TypedProperty<int> *interpretedInt = prop.second->As<TypedProperty<int>>()) {
  1898. out_mat->AddProperty(&interpretedInt->Value(), 1, name.c_str(), 0, 0);
  1899. } else if (const TypedProperty<bool> *interpretedBool = prop.second->As<TypedProperty<bool>>()) {
  1900. int value = interpretedBool->Value() ? 1 : 0;
  1901. out_mat->AddProperty(&value, 1, name.c_str(), 0, 0);
  1902. } else if (const TypedProperty<std::string> *interpretedString = prop.second->As<TypedProperty<std::string>>()) {
  1903. const aiString value = aiString(interpretedString->Value());
  1904. out_mat->AddProperty(&value, name.c_str(), 0, 0);
  1905. }
  1906. }
  1907. // Add the textures' properties
  1908. for (TextureMap::const_iterator it = _textures.begin(); it != _textures.end(); ++it) {
  1909. std::string name = prefix + it->first;
  1910. const Texture *const tex = it->second;
  1911. if (tex != nullptr) {
  1912. aiString path;
  1913. path.Set(tex->RelativeFilename());
  1914. const Video *media = tex->Media();
  1915. if (media != nullptr && media->ContentLength() > 0) {
  1916. unsigned int index;
  1917. VideoMap::const_iterator videoIt = textures_converted.find(media);
  1918. if (videoIt != textures_converted.end()) {
  1919. index = videoIt->second;
  1920. } else {
  1921. index = ConvertVideo(*media);
  1922. textures_converted[media] = index;
  1923. }
  1924. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  1925. path.data[0] = '*';
  1926. path.length = 1 + ASSIMP_itoa10(path.data + 1, MAXLEN - 1, index);
  1927. }
  1928. out_mat->AddProperty(&path, (name + "|file").c_str(), aiTextureType_UNKNOWN, 0);
  1929. aiUVTransform uvTrafo;
  1930. // XXX handle all kinds of UV transformations
  1931. uvTrafo.mScaling = tex->UVScaling();
  1932. uvTrafo.mTranslation = tex->UVTranslation();
  1933. out_mat->AddProperty(&uvTrafo, 1, (name + "|uvtrafo").c_str(), aiTextureType_UNKNOWN, 0);
  1934. int uvIndex = 0;
  1935. bool uvFound = false;
  1936. const std::string &uvSet = PropertyGet<std::string>(tex->Props(), "UVSet", uvFound);
  1937. if (uvFound) {
  1938. // "default" is the name which usually appears in the FbxFileTexture template
  1939. if (uvSet != "default" && uvSet.length()) {
  1940. // this is a bit awkward - we need to find a mesh that uses this
  1941. // material and scan its UV channels for the given UV name because
  1942. // assimp references UV channels by index, not by name.
  1943. // XXX: the case that UV channels may appear in different orders
  1944. // in meshes is unhandled. A possible solution would be to sort
  1945. // the UV channels alphabetically, but this would have the side
  1946. // effect that the primary (first) UV channel would sometimes
  1947. // be moved, causing trouble when users read only the first
  1948. // UV channel and ignore UV channel assignments altogether.
  1949. std::vector<aiMaterial *>::iterator materialIt = std::find(materials.begin(), materials.end(), out_mat);
  1950. const unsigned int matIndex = static_cast<unsigned int>(std::distance(materials.begin(), materialIt));
  1951. uvIndex = -1;
  1952. if (!mesh) {
  1953. for (const MeshMap::value_type &v : meshes_converted) {
  1954. const MeshGeometry *const meshGeom = dynamic_cast<const MeshGeometry *>(v.first);
  1955. if (!meshGeom) {
  1956. continue;
  1957. }
  1958. const MatIndexArray &mats = meshGeom->GetMaterialIndices();
  1959. if (std::find(mats.begin(), mats.end(), (int)matIndex) == mats.end()) {
  1960. continue;
  1961. }
  1962. int index = -1;
  1963. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1964. if (meshGeom->GetTextureCoords(i).empty()) {
  1965. break;
  1966. }
  1967. const std::string &curName = meshGeom->GetTextureCoordChannelName(i);
  1968. if (curName == uvSet) {
  1969. index = static_cast<int>(i);
  1970. break;
  1971. }
  1972. }
  1973. if (index == -1) {
  1974. FBXImporter::LogWarn("did not find UV channel named ", uvSet, " in a mesh using this material");
  1975. continue;
  1976. }
  1977. if (uvIndex == -1) {
  1978. uvIndex = index;
  1979. } else {
  1980. FBXImporter::LogWarn("the UV channel named ", uvSet, " appears at different positions in meshes, results will be wrong");
  1981. }
  1982. }
  1983. } else {
  1984. int index = -1;
  1985. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1986. if (mesh->GetTextureCoords(i).empty()) {
  1987. break;
  1988. }
  1989. const std::string &curName = mesh->GetTextureCoordChannelName(i);
  1990. if (curName == uvSet) {
  1991. index = static_cast<int>(i);
  1992. break;
  1993. }
  1994. }
  1995. if (index == -1) {
  1996. FBXImporter::LogWarn("did not find UV channel named ", uvSet, " in a mesh using this material");
  1997. }
  1998. if (uvIndex == -1) {
  1999. uvIndex = index;
  2000. }
  2001. }
  2002. if (uvIndex == -1) {
  2003. FBXImporter::LogWarn("failed to resolve UV channel ", uvSet, ", using first UV channel");
  2004. uvIndex = 0;
  2005. }
  2006. }
  2007. }
  2008. out_mat->AddProperty(&uvIndex, 1, (name + "|uvwsrc").c_str(), aiTextureType_UNKNOWN, 0);
  2009. }
  2010. }
  2011. }
  2012. double FBXConverter::FrameRateToDouble(FileGlobalSettings::FrameRate fp, double customFPSVal) {
  2013. switch (fp) {
  2014. case FileGlobalSettings::FrameRate_DEFAULT:
  2015. return 1.0;
  2016. case FileGlobalSettings::FrameRate_120:
  2017. return 120.0;
  2018. case FileGlobalSettings::FrameRate_100:
  2019. return 100.0;
  2020. case FileGlobalSettings::FrameRate_60:
  2021. return 60.0;
  2022. case FileGlobalSettings::FrameRate_50:
  2023. return 50.0;
  2024. case FileGlobalSettings::FrameRate_48:
  2025. return 48.0;
  2026. case FileGlobalSettings::FrameRate_30:
  2027. case FileGlobalSettings::FrameRate_30_DROP:
  2028. return 30.0;
  2029. case FileGlobalSettings::FrameRate_NTSC_DROP_FRAME:
  2030. case FileGlobalSettings::FrameRate_NTSC_FULL_FRAME:
  2031. return 29.9700262;
  2032. case FileGlobalSettings::FrameRate_PAL:
  2033. return 25.0;
  2034. case FileGlobalSettings::FrameRate_CINEMA:
  2035. return 24.0;
  2036. case FileGlobalSettings::FrameRate_1000:
  2037. return 1000.0;
  2038. case FileGlobalSettings::FrameRate_CINEMA_ND:
  2039. return 23.976;
  2040. case FileGlobalSettings::FrameRate_CUSTOM:
  2041. return customFPSVal;
  2042. case FileGlobalSettings::FrameRate_MAX: // this is to silence compiler warnings
  2043. break;
  2044. }
  2045. ai_assert(false);
  2046. return -1.0f;
  2047. }
  2048. void FBXConverter::ConvertAnimations() {
  2049. // first of all determine framerate
  2050. const FileGlobalSettings::FrameRate fps = doc.GlobalSettings().TimeMode();
  2051. const float custom = doc.GlobalSettings().CustomFrameRate();
  2052. anim_fps = FrameRateToDouble(fps, custom);
  2053. const std::vector<const AnimationStack *> &curAnimations = doc.AnimationStacks();
  2054. for (const AnimationStack *stack : curAnimations) {
  2055. ConvertAnimationStack(*stack);
  2056. }
  2057. }
  2058. std::string FBXConverter::FixNodeName(const std::string &name) {
  2059. // strip Model:: prefix, avoiding ambiguities (i.e. don't strip if
  2060. // this causes ambiguities, well possible between empty identifiers,
  2061. // such as "Model::" and ""). Make sure the behaviour is consistent
  2062. // across multiple calls to FixNodeName().
  2063. if (name.substr(0, 7) == "Model::") {
  2064. std::string temp = name.substr(7);
  2065. return temp;
  2066. }
  2067. return name;
  2068. }
  2069. std::string FBXConverter::FixAnimMeshName(const std::string &name) {
  2070. if (name.length()) {
  2071. size_t indexOf = name.find_first_of("::");
  2072. if (indexOf != std::string::npos && indexOf < name.size() - 2) {
  2073. return name.substr(indexOf + 2);
  2074. }
  2075. }
  2076. return name.length() ? name : "AnimMesh";
  2077. }
  2078. void FBXConverter::ConvertAnimationStack(const AnimationStack &st) {
  2079. const AnimationLayerList &layers = st.Layers();
  2080. if (layers.empty()) {
  2081. return;
  2082. }
  2083. aiAnimation *const anim = new aiAnimation();
  2084. animations.push_back(anim);
  2085. // strip AnimationStack:: prefix
  2086. std::string name = st.Name();
  2087. if (name.substr(0, 16) == "AnimationStack::") {
  2088. name = name.substr(16);
  2089. } else if (name.substr(0, 11) == "AnimStack::") {
  2090. name = name.substr(11);
  2091. }
  2092. anim->mName.Set(name);
  2093. // need to find all nodes for which we need to generate node animations -
  2094. // it may happen that we need to merge multiple layers, though.
  2095. NodeMap node_map;
  2096. // reverse mapping from curves to layers, much faster than querying
  2097. // the FBX DOM for it.
  2098. LayerMap layer_map;
  2099. const char *prop_whitelist[] = {
  2100. "Lcl Scaling",
  2101. "Lcl Rotation",
  2102. "Lcl Translation",
  2103. "DeformPercent"
  2104. };
  2105. std::map<std::string, morphAnimData *> morphAnimDatas;
  2106. for (const AnimationLayer *layer : layers) {
  2107. ai_assert(layer);
  2108. const AnimationCurveNodeList &nodes = layer->Nodes(prop_whitelist, 4);
  2109. for (const AnimationCurveNode *node : nodes) {
  2110. ai_assert(node);
  2111. const Model *const model = dynamic_cast<const Model *>(node->Target());
  2112. if (model) {
  2113. const std::string &curName = FixNodeName(model->Name());
  2114. node_map[curName].push_back(node);
  2115. layer_map[node] = layer;
  2116. continue;
  2117. }
  2118. const BlendShapeChannel *const bsc = dynamic_cast<const BlendShapeChannel *>(node->Target());
  2119. if (bsc) {
  2120. ProcessMorphAnimDatas(&morphAnimDatas, bsc, node);
  2121. }
  2122. }
  2123. }
  2124. // generate node animations
  2125. std::vector<aiNodeAnim *> node_anims;
  2126. double min_time = 1e10;
  2127. double max_time = -1e10;
  2128. int64_t start_time = st.LocalStart();
  2129. int64_t stop_time = st.LocalStop();
  2130. bool has_local_startstop = start_time != 0 || stop_time != 0;
  2131. if (!has_local_startstop) {
  2132. // no time range given, so accept every keyframe and use the actual min/max time
  2133. // the numbers are INT64_MIN/MAX, the 20000 is for safety because GenerateNodeAnimations uses an epsilon of 10000
  2134. start_time = -9223372036854775807ll + 20000;
  2135. stop_time = 9223372036854775807ll - 20000;
  2136. }
  2137. try {
  2138. for (const NodeMap::value_type &kv : node_map) {
  2139. GenerateNodeAnimations(node_anims,
  2140. kv.first,
  2141. kv.second,
  2142. layer_map,
  2143. start_time, stop_time,
  2144. max_time,
  2145. min_time);
  2146. }
  2147. } catch (std::exception &) {
  2148. std::for_each(node_anims.begin(), node_anims.end(), Util::delete_fun<aiNodeAnim>());
  2149. throw;
  2150. }
  2151. if (node_anims.size() || morphAnimDatas.size()) {
  2152. if (node_anims.size()) {
  2153. anim->mChannels = new aiNodeAnim *[node_anims.size()]();
  2154. anim->mNumChannels = static_cast<unsigned int>(node_anims.size());
  2155. std::swap_ranges(node_anims.begin(), node_anims.end(), anim->mChannels);
  2156. }
  2157. if (morphAnimDatas.size()) {
  2158. unsigned int numMorphMeshChannels = static_cast<unsigned int>(morphAnimDatas.size());
  2159. anim->mMorphMeshChannels = new aiMeshMorphAnim *[numMorphMeshChannels];
  2160. anim->mNumMorphMeshChannels = numMorphMeshChannels;
  2161. unsigned int i = 0;
  2162. for (auto morphAnimIt : morphAnimDatas) {
  2163. morphAnimData *animData = morphAnimIt.second;
  2164. unsigned int numKeys = static_cast<unsigned int>(animData->size());
  2165. aiMeshMorphAnim *meshMorphAnim = new aiMeshMorphAnim();
  2166. meshMorphAnim->mName.Set(morphAnimIt.first);
  2167. meshMorphAnim->mNumKeys = numKeys;
  2168. meshMorphAnim->mKeys = new aiMeshMorphKey[numKeys];
  2169. unsigned int j = 0;
  2170. for (auto animIt : *animData) {
  2171. morphKeyData *keyData = animIt.second;
  2172. unsigned int numValuesAndWeights = static_cast<unsigned int>(keyData->values.size());
  2173. meshMorphAnim->mKeys[j].mNumValuesAndWeights = numValuesAndWeights;
  2174. meshMorphAnim->mKeys[j].mValues = new unsigned int[numValuesAndWeights];
  2175. meshMorphAnim->mKeys[j].mWeights = new double[numValuesAndWeights];
  2176. meshMorphAnim->mKeys[j].mTime = CONVERT_FBX_TIME(animIt.first);
  2177. for (unsigned int k = 0; k < numValuesAndWeights; k++) {
  2178. meshMorphAnim->mKeys[j].mValues[k] = keyData->values.at(k);
  2179. meshMorphAnim->mKeys[j].mWeights[k] = keyData->weights.at(k);
  2180. }
  2181. j++;
  2182. }
  2183. anim->mMorphMeshChannels[i++] = meshMorphAnim;
  2184. }
  2185. }
  2186. } else {
  2187. // empty animations would fail validation, so drop them
  2188. delete anim;
  2189. animations.pop_back();
  2190. FBXImporter::LogInfo("ignoring empty AnimationStack (using IK?): ", name);
  2191. return;
  2192. }
  2193. double start_time_fps = has_local_startstop ? CONVERT_FBX_TIME(start_time) : min_time;
  2194. double stop_time_fps = has_local_startstop ? CONVERT_FBX_TIME(stop_time) : max_time;
  2195. // adjust relative timing for animation
  2196. for (unsigned int c = 0; c < anim->mNumChannels; c++) {
  2197. aiNodeAnim *channel = anim->mChannels[c];
  2198. for (uint32_t i = 0; i < channel->mNumPositionKeys; i++) {
  2199. channel->mPositionKeys[i].mTime -= start_time_fps;
  2200. }
  2201. for (uint32_t i = 0; i < channel->mNumRotationKeys; i++) {
  2202. channel->mRotationKeys[i].mTime -= start_time_fps;
  2203. }
  2204. for (uint32_t i = 0; i < channel->mNumScalingKeys; i++) {
  2205. channel->mScalingKeys[i].mTime -= start_time_fps;
  2206. }
  2207. }
  2208. for (unsigned int c = 0; c < anim->mNumMorphMeshChannels; c++) {
  2209. aiMeshMorphAnim *channel = anim->mMorphMeshChannels[c];
  2210. for (uint32_t i = 0; i < channel->mNumKeys; i++) {
  2211. channel->mKeys[i].mTime -= start_time_fps;
  2212. }
  2213. }
  2214. // for some mysterious reason, mDuration is simply the maximum key -- the
  2215. // validator always assumes animations to start at zero.
  2216. anim->mDuration = stop_time_fps - start_time_fps;
  2217. anim->mTicksPerSecond = anim_fps;
  2218. }
  2219. // ------------------------------------------------------------------------------------------------
  2220. void FBXConverter::ProcessMorphAnimDatas(std::map<std::string, morphAnimData *> *morphAnimDatas, const BlendShapeChannel *bsc, const AnimationCurveNode *node) {
  2221. std::vector<const Connection *> bscConnections = doc.GetConnectionsBySourceSequenced(bsc->ID(), "Deformer");
  2222. for (const Connection *bscConnection : bscConnections) {
  2223. auto bs = dynamic_cast<const BlendShape *>(bscConnection->DestinationObject());
  2224. if (bs) {
  2225. auto channelIt = std::find(bs->BlendShapeChannels().begin(), bs->BlendShapeChannels().end(), bsc);
  2226. if (channelIt != bs->BlendShapeChannels().end()) {
  2227. auto channelIndex = static_cast<unsigned int>(std::distance(bs->BlendShapeChannels().begin(), channelIt));
  2228. std::vector<const Connection *> bsConnections = doc.GetConnectionsBySourceSequenced(bs->ID(), "Geometry");
  2229. for (const Connection *bsConnection : bsConnections) {
  2230. auto geo = dynamic_cast<const Geometry *>(bsConnection->DestinationObject());
  2231. if (geo) {
  2232. std::vector<const Connection *> geoConnections = doc.GetConnectionsBySourceSequenced(geo->ID(), "Model");
  2233. for (const Connection *geoConnection : geoConnections) {
  2234. auto model = dynamic_cast<const Model *>(geoConnection->DestinationObject());
  2235. if (model) {
  2236. auto geoIt = std::find(model->GetGeometry().begin(), model->GetGeometry().end(), geo);
  2237. auto geoIndex = static_cast<unsigned int>(std::distance(model->GetGeometry().begin(), geoIt));
  2238. auto name = aiString(FixNodeName(model->Name() + "*"));
  2239. name.length = 1 + ASSIMP_itoa10(name.data + name.length, MAXLEN - 1, geoIndex);
  2240. morphAnimData *animData;
  2241. auto animIt = morphAnimDatas->find(name.C_Str());
  2242. if (animIt == morphAnimDatas->end()) {
  2243. animData = new morphAnimData();
  2244. morphAnimDatas->insert(std::make_pair(name.C_Str(), animData));
  2245. } else {
  2246. animData = animIt->second;
  2247. }
  2248. for (std::pair<std::string, const AnimationCurve *> curvesIt : node->Curves()) {
  2249. if (curvesIt.first == "d|DeformPercent") {
  2250. const AnimationCurve *animationCurve = curvesIt.second;
  2251. const KeyTimeList &keys = animationCurve->GetKeys();
  2252. const KeyValueList &values = animationCurve->GetValues();
  2253. unsigned int k = 0;
  2254. for (auto key : keys) {
  2255. morphKeyData *keyData;
  2256. auto keyIt = animData->find(key);
  2257. if (keyIt == animData->end()) {
  2258. keyData = new morphKeyData();
  2259. animData->insert(std::make_pair(key, keyData));
  2260. } else {
  2261. keyData = keyIt->second;
  2262. }
  2263. keyData->values.push_back(channelIndex);
  2264. keyData->weights.push_back(values.at(k) / 100.0f);
  2265. k++;
  2266. }
  2267. }
  2268. }
  2269. }
  2270. }
  2271. }
  2272. }
  2273. }
  2274. }
  2275. }
  2276. }
  2277. // ------------------------------------------------------------------------------------------------
  2278. #ifdef ASSIMP_BUILD_DEBUG
  2279. // ------------------------------------------------------------------------------------------------
  2280. // sanity check whether the input is ok
  2281. static void validateAnimCurveNodes(const std::vector<const AnimationCurveNode *> &curves,
  2282. bool strictMode) {
  2283. const Object *target(nullptr);
  2284. for (const AnimationCurveNode *node : curves) {
  2285. if (!target) {
  2286. target = node->Target();
  2287. }
  2288. if (node->Target() != target) {
  2289. FBXImporter::LogWarn("Node target is nullptr type.");
  2290. }
  2291. if (strictMode) {
  2292. ai_assert(node->Target() == target);
  2293. }
  2294. }
  2295. }
  2296. #endif // ASSIMP_BUILD_DEBUG
  2297. // ------------------------------------------------------------------------------------------------
  2298. void FBXConverter::GenerateNodeAnimations(std::vector<aiNodeAnim *> &node_anims,
  2299. const std::string &fixed_name,
  2300. const std::vector<const AnimationCurveNode *> &curves,
  2301. const LayerMap &layer_map,
  2302. int64_t start, int64_t stop,
  2303. double &max_time,
  2304. double &min_time) {
  2305. NodeMap node_property_map;
  2306. ai_assert(curves.size());
  2307. #ifdef ASSIMP_BUILD_DEBUG
  2308. validateAnimCurveNodes(curves, doc.Settings().strictMode);
  2309. #endif
  2310. const AnimationCurveNode *curve_node = nullptr;
  2311. for (const AnimationCurveNode *node : curves) {
  2312. ai_assert(node);
  2313. if (node->TargetProperty().empty()) {
  2314. FBXImporter::LogWarn("target property for animation curve not set: ", node->Name());
  2315. continue;
  2316. }
  2317. curve_node = node;
  2318. if (node->Curves().empty()) {
  2319. FBXImporter::LogWarn("no animation curves assigned to AnimationCurveNode: ", node->Name());
  2320. continue;
  2321. }
  2322. node_property_map[node->TargetProperty()].push_back(node);
  2323. }
  2324. ai_assert(curve_node);
  2325. ai_assert(curve_node->TargetAsModel());
  2326. const Model &target = *curve_node->TargetAsModel();
  2327. // check for all possible transformation components
  2328. NodeMap::const_iterator chain[TransformationComp_MAXIMUM];
  2329. bool has_any = false;
  2330. bool has_complex = false;
  2331. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) {
  2332. const TransformationComp comp = static_cast<TransformationComp>(i);
  2333. // inverse pivots don't exist in the input, we just generate them
  2334. if (comp == TransformationComp_RotationPivotInverse || comp == TransformationComp_ScalingPivotInverse) {
  2335. chain[i] = node_property_map.end();
  2336. continue;
  2337. }
  2338. chain[i] = node_property_map.find(NameTransformationCompProperty(comp));
  2339. if (chain[i] != node_property_map.end()) {
  2340. // check if this curves contains redundant information by looking
  2341. // up the corresponding node's transformation chain.
  2342. if (doc.Settings().optimizeEmptyAnimationCurves &&
  2343. IsRedundantAnimationData(target, comp, (chain[i]->second))) {
  2344. FBXImporter::LogVerboseDebug("dropping redundant animation channel for node ", target.Name());
  2345. continue;
  2346. }
  2347. has_any = true;
  2348. if (comp != TransformationComp_Rotation && comp != TransformationComp_Scaling && comp != TransformationComp_Translation) {
  2349. has_complex = true;
  2350. }
  2351. }
  2352. }
  2353. if (!has_any) {
  2354. FBXImporter::LogWarn("ignoring node animation, did not find any transformation key frames");
  2355. return;
  2356. }
  2357. // this needs to play nicely with GenerateTransformationNodeChain() which will
  2358. // be invoked _later_ (animations come first). If this node has only rotation,
  2359. // scaling and translation _and_ there are no animated other components either,
  2360. // we can use a single node and also a single node animation channel.
  2361. if( !has_complex && !NeedsComplexTransformationChain(target)) {
  2362. aiNodeAnim* const nd = GenerateSimpleNodeAnim(fixed_name, target, chain,
  2363. node_property_map.end(),
  2364. start, stop,
  2365. max_time,
  2366. min_time
  2367. );
  2368. ai_assert(nd);
  2369. if (nd->mNumPositionKeys == 0 && nd->mNumRotationKeys == 0 && nd->mNumScalingKeys == 0) {
  2370. delete nd;
  2371. } else {
  2372. node_anims.push_back(nd);
  2373. }
  2374. return;
  2375. }
  2376. // otherwise, things get gruesome and we need separate animation channels
  2377. // for each part of the transformation chain. Remember which channels
  2378. // we generated and pass this information to the node conversion
  2379. // code to avoid nodes that have identity transform, but non-identity
  2380. // animations, being dropped.
  2381. unsigned int flags = 0, bit = 0x1;
  2382. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i, bit <<= 1) {
  2383. const TransformationComp comp = static_cast<TransformationComp>(i);
  2384. if (chain[i] != node_property_map.end()) {
  2385. flags |= bit;
  2386. ai_assert(comp != TransformationComp_RotationPivotInverse);
  2387. ai_assert(comp != TransformationComp_ScalingPivotInverse);
  2388. const std::string &chain_name = NameTransformationChainNode(fixed_name, comp);
  2389. aiNodeAnim *na = nullptr;
  2390. switch (comp) {
  2391. case TransformationComp_Rotation:
  2392. case TransformationComp_PreRotation:
  2393. case TransformationComp_PostRotation:
  2394. case TransformationComp_GeometricRotation:
  2395. na = GenerateRotationNodeAnim(chain_name,
  2396. target,
  2397. (*chain[i]).second,
  2398. layer_map,
  2399. start, stop,
  2400. max_time,
  2401. min_time);
  2402. break;
  2403. case TransformationComp_RotationOffset:
  2404. case TransformationComp_RotationPivot:
  2405. case TransformationComp_ScalingOffset:
  2406. case TransformationComp_ScalingPivot:
  2407. case TransformationComp_Translation:
  2408. case TransformationComp_GeometricTranslation:
  2409. na = GenerateTranslationNodeAnim(chain_name,
  2410. target,
  2411. (*chain[i]).second,
  2412. layer_map,
  2413. start, stop,
  2414. max_time,
  2415. min_time);
  2416. // pivoting requires us to generate an implicit inverse channel to undo the pivot translation
  2417. if (comp == TransformationComp_RotationPivot) {
  2418. const std::string &invName = NameTransformationChainNode(fixed_name,
  2419. TransformationComp_RotationPivotInverse);
  2420. aiNodeAnim *const inv = GenerateTranslationNodeAnim(invName,
  2421. target,
  2422. (*chain[i]).second,
  2423. layer_map,
  2424. start, stop,
  2425. max_time,
  2426. min_time,
  2427. true);
  2428. ai_assert(inv);
  2429. if (inv->mNumPositionKeys == 0 && inv->mNumRotationKeys == 0 && inv->mNumScalingKeys == 0) {
  2430. delete inv;
  2431. } else {
  2432. node_anims.push_back(inv);
  2433. }
  2434. ai_assert(TransformationComp_RotationPivotInverse > i);
  2435. flags |= bit << (TransformationComp_RotationPivotInverse - i);
  2436. } else if (comp == TransformationComp_ScalingPivot) {
  2437. const std::string &invName = NameTransformationChainNode(fixed_name,
  2438. TransformationComp_ScalingPivotInverse);
  2439. aiNodeAnim *const inv = GenerateTranslationNodeAnim(invName,
  2440. target,
  2441. (*chain[i]).second,
  2442. layer_map,
  2443. start, stop,
  2444. max_time,
  2445. min_time,
  2446. true);
  2447. ai_assert(inv);
  2448. if (inv->mNumPositionKeys == 0 && inv->mNumRotationKeys == 0 && inv->mNumScalingKeys == 0) {
  2449. delete inv;
  2450. } else {
  2451. node_anims.push_back(inv);
  2452. }
  2453. ai_assert(TransformationComp_RotationPivotInverse > i);
  2454. flags |= bit << (TransformationComp_RotationPivotInverse - i);
  2455. }
  2456. break;
  2457. case TransformationComp_Scaling:
  2458. case TransformationComp_GeometricScaling:
  2459. na = GenerateScalingNodeAnim(chain_name,
  2460. target,
  2461. (*chain[i]).second,
  2462. layer_map,
  2463. start, stop,
  2464. max_time,
  2465. min_time);
  2466. break;
  2467. default:
  2468. ai_assert(false);
  2469. }
  2470. ai_assert(na);
  2471. if (na->mNumPositionKeys == 0 && na->mNumRotationKeys == 0 && na->mNumScalingKeys == 0) {
  2472. delete na;
  2473. } else {
  2474. node_anims.push_back(na);
  2475. }
  2476. continue;
  2477. }
  2478. }
  2479. node_anim_chain_bits[fixed_name] = flags;
  2480. }
  2481. bool FBXConverter::IsRedundantAnimationData(const Model &target,
  2482. TransformationComp comp,
  2483. const std::vector<const AnimationCurveNode *> &curves) {
  2484. ai_assert(curves.size());
  2485. // look for animation nodes with
  2486. // * sub channels for all relevant components set
  2487. // * one key/value pair per component
  2488. // * combined values match up the corresponding value in the bind pose node transformation
  2489. // only such nodes are 'redundant' for this function.
  2490. if (curves.size() > 1) {
  2491. return false;
  2492. }
  2493. const AnimationCurveNode &nd = *curves.front();
  2494. const AnimationCurveMap &sub_curves = nd.Curves();
  2495. const AnimationCurveMap::const_iterator dx = sub_curves.find("d|X");
  2496. const AnimationCurveMap::const_iterator dy = sub_curves.find("d|Y");
  2497. const AnimationCurveMap::const_iterator dz = sub_curves.find("d|Z");
  2498. if (dx == sub_curves.end() || dy == sub_curves.end() || dz == sub_curves.end()) {
  2499. return false;
  2500. }
  2501. const KeyValueList &vx = (*dx).second->GetValues();
  2502. const KeyValueList &vy = (*dy).second->GetValues();
  2503. const KeyValueList &vz = (*dz).second->GetValues();
  2504. if (vx.size() != 1 || vy.size() != 1 || vz.size() != 1) {
  2505. return false;
  2506. }
  2507. const aiVector3D dyn_val = aiVector3D(vx[0], vy[0], vz[0]);
  2508. const aiVector3D &static_val = PropertyGet<aiVector3D>(target.Props(),
  2509. NameTransformationCompProperty(comp),
  2510. TransformationCompDefaultValue(comp));
  2511. const float epsilon = Math::getEpsilon<float>();
  2512. return (dyn_val - static_val).SquareLength() < epsilon;
  2513. }
  2514. aiNodeAnim *FBXConverter::GenerateRotationNodeAnim(const std::string &name,
  2515. const Model &target,
  2516. const std::vector<const AnimationCurveNode *> &curves,
  2517. const LayerMap &layer_map,
  2518. int64_t start, int64_t stop,
  2519. double &max_time,
  2520. double &min_time) {
  2521. std::unique_ptr<aiNodeAnim> na(new aiNodeAnim());
  2522. na->mNodeName.Set(name);
  2523. ConvertRotationKeys(na.get(), curves, layer_map, start, stop, max_time, min_time, target.RotationOrder());
  2524. // dummy scaling key
  2525. na->mScalingKeys = new aiVectorKey[1];
  2526. na->mNumScalingKeys = 1;
  2527. na->mScalingKeys[0].mTime = 0.;
  2528. na->mScalingKeys[0].mValue = aiVector3D(1.0f, 1.0f, 1.0f);
  2529. // dummy position key
  2530. na->mPositionKeys = new aiVectorKey[1];
  2531. na->mNumPositionKeys = 1;
  2532. na->mPositionKeys[0].mTime = 0.;
  2533. na->mPositionKeys[0].mValue = aiVector3D();
  2534. return na.release();
  2535. }
  2536. aiNodeAnim *FBXConverter::GenerateScalingNodeAnim(const std::string &name,
  2537. const Model & /*target*/,
  2538. const std::vector<const AnimationCurveNode *> &curves,
  2539. const LayerMap &layer_map,
  2540. int64_t start, int64_t stop,
  2541. double &max_time,
  2542. double &min_time) {
  2543. std::unique_ptr<aiNodeAnim> na(new aiNodeAnim());
  2544. na->mNodeName.Set(name);
  2545. ConvertScaleKeys(na.get(), curves, layer_map, start, stop, max_time, min_time);
  2546. // dummy rotation key
  2547. na->mRotationKeys = new aiQuatKey[1];
  2548. na->mNumRotationKeys = 1;
  2549. na->mRotationKeys[0].mTime = 0.;
  2550. na->mRotationKeys[0].mValue = aiQuaternion();
  2551. // dummy position key
  2552. na->mPositionKeys = new aiVectorKey[1];
  2553. na->mNumPositionKeys = 1;
  2554. na->mPositionKeys[0].mTime = 0.;
  2555. na->mPositionKeys[0].mValue = aiVector3D();
  2556. return na.release();
  2557. }
  2558. aiNodeAnim *FBXConverter::GenerateTranslationNodeAnim(const std::string &name,
  2559. const Model & /*target*/,
  2560. const std::vector<const AnimationCurveNode *> &curves,
  2561. const LayerMap &layer_map,
  2562. int64_t start, int64_t stop,
  2563. double &max_time,
  2564. double &min_time,
  2565. bool inverse) {
  2566. std::unique_ptr<aiNodeAnim> na(new aiNodeAnim());
  2567. na->mNodeName.Set(name);
  2568. ConvertTranslationKeys(na.get(), curves, layer_map, start, stop, max_time, min_time);
  2569. if (inverse) {
  2570. for (unsigned int i = 0; i < na->mNumPositionKeys; ++i) {
  2571. na->mPositionKeys[i].mValue *= -1.0f;
  2572. }
  2573. }
  2574. // dummy scaling key
  2575. na->mScalingKeys = new aiVectorKey[1];
  2576. na->mNumScalingKeys = 1;
  2577. na->mScalingKeys[0].mTime = 0.;
  2578. na->mScalingKeys[0].mValue = aiVector3D(1.0f, 1.0f, 1.0f);
  2579. // dummy rotation key
  2580. na->mRotationKeys = new aiQuatKey[1];
  2581. na->mNumRotationKeys = 1;
  2582. na->mRotationKeys[0].mTime = 0.;
  2583. na->mRotationKeys[0].mValue = aiQuaternion();
  2584. return na.release();
  2585. }
  2586. aiNodeAnim* FBXConverter::GenerateSimpleNodeAnim(const std::string& name,
  2587. const Model& target,
  2588. NodeMap::const_iterator chain[TransformationComp_MAXIMUM],
  2589. NodeMap::const_iterator iterEnd,
  2590. int64_t start, int64_t stop,
  2591. double& maxTime,
  2592. double& minTime)
  2593. {
  2594. std::unique_ptr<aiNodeAnim> na(new aiNodeAnim());
  2595. na->mNodeName.Set(name);
  2596. const PropertyTable &props = target.Props();
  2597. // collect unique times and keyframe lists
  2598. KeyFrameListList keyframeLists[TransformationComp_MAXIMUM];
  2599. KeyTimeList keytimes;
  2600. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) {
  2601. if (chain[i] == iterEnd)
  2602. continue;
  2603. keyframeLists[i] = GetKeyframeList((*chain[i]).second, start, stop);
  2604. for (KeyFrameListList::const_iterator it = keyframeLists[i].begin(); it != keyframeLists[i].end(); ++it) {
  2605. const KeyTimeList& times = *std::get<0>(*it);
  2606. keytimes.insert(keytimes.end(), times.begin(), times.end());
  2607. }
  2608. // remove duplicates
  2609. std::sort(keytimes.begin(), keytimes.end());
  2610. auto last = std::unique(keytimes.begin(), keytimes.end());
  2611. keytimes.erase(last, keytimes.end());
  2612. }
  2613. const Model::RotOrder rotOrder = target.RotationOrder();
  2614. const size_t keyCount = keytimes.size();
  2615. aiVector3D defTranslate = PropertyGet(props, "Lcl Translation", aiVector3D(0.f, 0.f, 0.f));
  2616. aiVector3D defRotation = PropertyGet(props, "Lcl Rotation", aiVector3D(0.f, 0.f, 0.f));
  2617. aiVector3D defScale = PropertyGet(props, "Lcl Scaling", aiVector3D(1.f, 1.f, 1.f));
  2618. aiQuaternion defQuat = EulerToQuaternion(defRotation, rotOrder);
  2619. aiVectorKey* outTranslations = new aiVectorKey[keyCount];
  2620. aiQuatKey* outRotations = new aiQuatKey[keyCount];
  2621. aiVectorKey* outScales = new aiVectorKey[keyCount];
  2622. if (keyframeLists[TransformationComp_Translation].size() > 0) {
  2623. InterpolateKeys(outTranslations, keytimes, keyframeLists[TransformationComp_Translation], defTranslate, maxTime, minTime);
  2624. } else {
  2625. for (size_t i = 0; i < keyCount; ++i) {
  2626. outTranslations[i].mTime = CONVERT_FBX_TIME(keytimes[i]);
  2627. outTranslations[i].mValue = defTranslate;
  2628. }
  2629. }
  2630. if (keyframeLists[TransformationComp_Rotation].size() > 0) {
  2631. InterpolateKeys(outRotations, keytimes, keyframeLists[TransformationComp_Rotation], defRotation, maxTime, minTime, rotOrder);
  2632. } else {
  2633. for (size_t i = 0; i < keyCount; ++i) {
  2634. outRotations[i].mTime = CONVERT_FBX_TIME(keytimes[i]);
  2635. outRotations[i].mValue = defQuat;
  2636. }
  2637. }
  2638. if (keyframeLists[TransformationComp_Scaling].size() > 0) {
  2639. InterpolateKeys(outScales, keytimes, keyframeLists[TransformationComp_Scaling], defScale, maxTime, minTime);
  2640. } else {
  2641. for (size_t i = 0; i < keyCount; ++i) {
  2642. outScales[i].mTime = CONVERT_FBX_TIME(keytimes[i]);
  2643. outScales[i].mValue = defScale;
  2644. }
  2645. }
  2646. bool ok = false;
  2647. const float zero_epsilon = 1e-6f;
  2648. const aiVector3D& preRotation = PropertyGet<aiVector3D>(props, "PreRotation", ok);
  2649. if (ok && preRotation.SquareLength() > zero_epsilon) {
  2650. const aiQuaternion preQuat = EulerToQuaternion(preRotation, Model::RotOrder_EulerXYZ);
  2651. for (size_t i = 0; i < keyCount; ++i) {
  2652. outRotations[i].mValue = preQuat * outRotations[i].mValue;
  2653. }
  2654. }
  2655. const aiVector3D& postRotation = PropertyGet<aiVector3D>(props, "PostRotation", ok);
  2656. if (ok && postRotation.SquareLength() > zero_epsilon) {
  2657. const aiQuaternion postQuat = EulerToQuaternion(postRotation, Model::RotOrder_EulerXYZ);
  2658. for (size_t i = 0; i < keyCount; ++i) {
  2659. outRotations[i].mValue = outRotations[i].mValue * postQuat;
  2660. }
  2661. }
  2662. // convert TRS to SRT
  2663. for (size_t i = 0; i < keyCount; ++i) {
  2664. aiQuaternion& r = outRotations[i].mValue;
  2665. aiVector3D& s = outScales[i].mValue;
  2666. aiVector3D& t = outTranslations[i].mValue;
  2667. aiMatrix4x4 mat, temp;
  2668. aiMatrix4x4::Translation(t, mat);
  2669. mat *= aiMatrix4x4(r.GetMatrix());
  2670. mat *= aiMatrix4x4::Scaling(s, temp);
  2671. mat.Decompose(s, r, t);
  2672. }
  2673. na->mNumScalingKeys = static_cast<unsigned int>(keyCount);
  2674. na->mNumRotationKeys = na->mNumScalingKeys;
  2675. na->mNumPositionKeys = na->mNumScalingKeys;
  2676. na->mScalingKeys = outScales;
  2677. na->mRotationKeys = outRotations;
  2678. na->mPositionKeys = outTranslations;
  2679. return na.release();
  2680. }
  2681. FBXConverter::KeyFrameListList FBXConverter::GetKeyframeList(const std::vector<const AnimationCurveNode *> &nodes, int64_t start, int64_t stop) {
  2682. KeyFrameListList inputs;
  2683. inputs.reserve(nodes.size() * 3);
  2684. //give some breathing room for rounding errors
  2685. int64_t adj_start = start - 10000;
  2686. int64_t adj_stop = stop + 10000;
  2687. for (const AnimationCurveNode *node : nodes) {
  2688. ai_assert(node);
  2689. const AnimationCurveMap &curves = node->Curves();
  2690. for (const AnimationCurveMap::value_type &kv : curves) {
  2691. unsigned int mapto;
  2692. if (kv.first == "d|X") {
  2693. mapto = 0;
  2694. } else if (kv.first == "d|Y") {
  2695. mapto = 1;
  2696. } else if (kv.first == "d|Z") {
  2697. mapto = 2;
  2698. } else {
  2699. FBXImporter::LogWarn("ignoring scale animation curve, did not recognize target component");
  2700. continue;
  2701. }
  2702. const AnimationCurve *const curve = kv.second;
  2703. ai_assert(curve->GetKeys().size() == curve->GetValues().size());
  2704. ai_assert(curve->GetKeys().size());
  2705. //get values within the start/stop time window
  2706. std::shared_ptr<KeyTimeList> Keys(new KeyTimeList());
  2707. std::shared_ptr<KeyValueList> Values(new KeyValueList());
  2708. const size_t count = curve->GetKeys().size();
  2709. Keys->reserve(count);
  2710. Values->reserve(count);
  2711. for (size_t n = 0; n < count; n++) {
  2712. int64_t k = curve->GetKeys().at(n);
  2713. if (k >= adj_start && k <= adj_stop) {
  2714. Keys->push_back(k);
  2715. Values->push_back(curve->GetValues().at(n));
  2716. }
  2717. }
  2718. inputs.push_back(std::make_tuple(Keys, Values, mapto));
  2719. }
  2720. }
  2721. return inputs; // pray for NRVO :-)
  2722. }
  2723. KeyTimeList FBXConverter::GetKeyTimeList(const KeyFrameListList &inputs) {
  2724. ai_assert(!inputs.empty());
  2725. // reserve some space upfront - it is likely that the key-frame lists
  2726. // have matching time values, so max(of all key-frame lists) should
  2727. // be a good estimate.
  2728. KeyTimeList keys;
  2729. size_t estimate = 0;
  2730. for (const KeyFrameList &kfl : inputs) {
  2731. estimate = std::max(estimate, std::get<0>(kfl)->size());
  2732. }
  2733. keys.reserve(estimate);
  2734. std::vector<unsigned int> next_pos;
  2735. next_pos.resize(inputs.size(), 0);
  2736. const size_t count = inputs.size();
  2737. while (true) {
  2738. int64_t min_tick = std::numeric_limits<int64_t>::max();
  2739. for (size_t i = 0; i < count; ++i) {
  2740. const KeyFrameList &kfl = inputs[i];
  2741. if (std::get<0>(kfl)->size() > next_pos[i] && std::get<0>(kfl)->at(next_pos[i]) < min_tick) {
  2742. min_tick = std::get<0>(kfl)->at(next_pos[i]);
  2743. }
  2744. }
  2745. if (min_tick == std::numeric_limits<int64_t>::max()) {
  2746. break;
  2747. }
  2748. keys.push_back(min_tick);
  2749. for (size_t i = 0; i < count; ++i) {
  2750. const KeyFrameList &kfl = inputs[i];
  2751. while (std::get<0>(kfl)->size() > next_pos[i] && std::get<0>(kfl)->at(next_pos[i]) == min_tick) {
  2752. ++next_pos[i];
  2753. }
  2754. }
  2755. }
  2756. return keys;
  2757. }
  2758. void FBXConverter::InterpolateKeys(aiVectorKey *valOut, const KeyTimeList &keys, const KeyFrameListList &inputs,
  2759. const aiVector3D &def_value,
  2760. double &max_time,
  2761. double &min_time) {
  2762. ai_assert(!keys.empty());
  2763. ai_assert(nullptr != valOut);
  2764. std::vector<unsigned int> next_pos;
  2765. const size_t count(inputs.size());
  2766. next_pos.resize(inputs.size(), 0);
  2767. for (KeyTimeList::value_type time : keys) {
  2768. ai_real result[3] = { def_value.x, def_value.y, def_value.z };
  2769. for (size_t i = 0; i < count; ++i) {
  2770. const KeyFrameList &kfl = inputs[i];
  2771. const size_t ksize = std::get<0>(kfl)->size();
  2772. if (ksize == 0) {
  2773. continue;
  2774. }
  2775. if (ksize > next_pos[i] && std::get<0>(kfl)->at(next_pos[i]) == time) {
  2776. ++next_pos[i];
  2777. }
  2778. const size_t id0 = next_pos[i] > 0 ? next_pos[i] - 1 : 0;
  2779. const size_t id1 = next_pos[i] == ksize ? ksize - 1 : next_pos[i];
  2780. // use lerp for interpolation
  2781. const KeyValueList::value_type valueA = std::get<1>(kfl)->at(id0);
  2782. const KeyValueList::value_type valueB = std::get<1>(kfl)->at(id1);
  2783. const KeyTimeList::value_type timeA = std::get<0>(kfl)->at(id0);
  2784. const KeyTimeList::value_type timeB = std::get<0>(kfl)->at(id1);
  2785. const ai_real factor = timeB == timeA ? ai_real(0.) : static_cast<ai_real>((time - timeA)) / (timeB - timeA);
  2786. const ai_real interpValue = static_cast<ai_real>(valueA + (valueB - valueA) * factor);
  2787. result[std::get<2>(kfl)] = interpValue;
  2788. }
  2789. // magic value to convert fbx times to seconds
  2790. valOut->mTime = CONVERT_FBX_TIME(time);
  2791. min_time = std::min(min_time, valOut->mTime);
  2792. max_time = std::max(max_time, valOut->mTime);
  2793. valOut->mValue.x = result[0];
  2794. valOut->mValue.y = result[1];
  2795. valOut->mValue.z = result[2];
  2796. ++valOut;
  2797. }
  2798. }
  2799. void FBXConverter::InterpolateKeys(aiQuatKey *valOut, const KeyTimeList &keys, const KeyFrameListList &inputs,
  2800. const aiVector3D &def_value,
  2801. double &maxTime,
  2802. double &minTime,
  2803. Model::RotOrder order) {
  2804. ai_assert(!keys.empty());
  2805. ai_assert(nullptr != valOut);
  2806. std::unique_ptr<aiVectorKey[]> temp(new aiVectorKey[keys.size()]);
  2807. InterpolateKeys(temp.get(), keys, inputs, def_value, maxTime, minTime);
  2808. aiMatrix4x4 m;
  2809. aiQuaternion lastq;
  2810. for (size_t i = 0, c = keys.size(); i < c; ++i) {
  2811. valOut[i].mTime = temp[i].mTime;
  2812. GetRotationMatrix(order, temp[i].mValue, m);
  2813. aiQuaternion quat = aiQuaternion(aiMatrix3x3(m));
  2814. // take shortest path by checking the inner product
  2815. // http://www.3dkingdoms.com/weekly/weekly.php?a=36
  2816. if (quat.x * lastq.x + quat.y * lastq.y + quat.z * lastq.z + quat.w * lastq.w < 0) {
  2817. quat.Conjugate();
  2818. quat.w = -quat.w;
  2819. }
  2820. lastq = quat;
  2821. valOut[i].mValue = quat;
  2822. }
  2823. }
  2824. aiQuaternion FBXConverter::EulerToQuaternion(const aiVector3D &rot, Model::RotOrder order) {
  2825. aiMatrix4x4 m;
  2826. GetRotationMatrix(order, rot, m);
  2827. return aiQuaternion(aiMatrix3x3(m));
  2828. }
  2829. void FBXConverter::ConvertScaleKeys(aiNodeAnim *na, const std::vector<const AnimationCurveNode *> &nodes, const LayerMap & /*layers*/,
  2830. int64_t start, int64_t stop,
  2831. double &maxTime,
  2832. double &minTime) {
  2833. ai_assert(nodes.size());
  2834. // XXX for now, assume scale should be blended geometrically (i.e. two
  2835. // layers should be multiplied with each other). There is a FBX
  2836. // property in the layer to specify the behaviour, though.
  2837. const KeyFrameListList &inputs = GetKeyframeList(nodes, start, stop);
  2838. const KeyTimeList &keys = GetKeyTimeList(inputs);
  2839. na->mNumScalingKeys = static_cast<unsigned int>(keys.size());
  2840. na->mScalingKeys = new aiVectorKey[keys.size()];
  2841. if (keys.size() > 0) {
  2842. InterpolateKeys(na->mScalingKeys, keys, inputs, aiVector3D(1.0f, 1.0f, 1.0f), maxTime, minTime);
  2843. }
  2844. }
  2845. void FBXConverter::ConvertTranslationKeys(aiNodeAnim *na, const std::vector<const AnimationCurveNode *> &nodes,
  2846. const LayerMap & /*layers*/,
  2847. int64_t start, int64_t stop,
  2848. double &maxTime,
  2849. double &minTime) {
  2850. ai_assert(nodes.size());
  2851. // XXX see notes in ConvertScaleKeys()
  2852. const KeyFrameListList &inputs = GetKeyframeList(nodes, start, stop);
  2853. const KeyTimeList &keys = GetKeyTimeList(inputs);
  2854. na->mNumPositionKeys = static_cast<unsigned int>(keys.size());
  2855. na->mPositionKeys = new aiVectorKey[keys.size()];
  2856. if (keys.size() > 0)
  2857. InterpolateKeys(na->mPositionKeys, keys, inputs, aiVector3D(0.0f, 0.0f, 0.0f), maxTime, minTime);
  2858. }
  2859. void FBXConverter::ConvertRotationKeys(aiNodeAnim *na, const std::vector<const AnimationCurveNode *> &nodes,
  2860. const LayerMap & /*layers*/,
  2861. int64_t start, int64_t stop,
  2862. double &maxTime,
  2863. double &minTime,
  2864. Model::RotOrder order) {
  2865. ai_assert(nodes.size());
  2866. // XXX see notes in ConvertScaleKeys()
  2867. const std::vector<KeyFrameList> &inputs = GetKeyframeList(nodes, start, stop);
  2868. const KeyTimeList &keys = GetKeyTimeList(inputs);
  2869. na->mNumRotationKeys = static_cast<unsigned int>(keys.size());
  2870. na->mRotationKeys = new aiQuatKey[keys.size()];
  2871. if (!keys.empty()) {
  2872. InterpolateKeys(na->mRotationKeys, keys, inputs, aiVector3D(0.0f, 0.0f, 0.0f), maxTime, minTime, order);
  2873. }
  2874. }
  2875. void FBXConverter::ConvertGlobalSettings() {
  2876. if (nullptr == mSceneOut) {
  2877. return;
  2878. }
  2879. const bool hasGenerator = !doc.Creator().empty();
  2880. mSceneOut->mMetaData = aiMetadata::Alloc(16 + (hasGenerator ? 1 : 0));
  2881. mSceneOut->mMetaData->Set(0, "UpAxis", doc.GlobalSettings().UpAxis());
  2882. mSceneOut->mMetaData->Set(1, "UpAxisSign", doc.GlobalSettings().UpAxisSign());
  2883. mSceneOut->mMetaData->Set(2, "FrontAxis", doc.GlobalSettings().FrontAxis());
  2884. mSceneOut->mMetaData->Set(3, "FrontAxisSign", doc.GlobalSettings().FrontAxisSign());
  2885. mSceneOut->mMetaData->Set(4, "CoordAxis", doc.GlobalSettings().CoordAxis());
  2886. mSceneOut->mMetaData->Set(5, "CoordAxisSign", doc.GlobalSettings().CoordAxisSign());
  2887. mSceneOut->mMetaData->Set(6, "OriginalUpAxis", doc.GlobalSettings().OriginalUpAxis());
  2888. mSceneOut->mMetaData->Set(7, "OriginalUpAxisSign", doc.GlobalSettings().OriginalUpAxisSign());
  2889. //const double unitScaleFactor = (double)doc.GlobalSettings().UnitScaleFactor();
  2890. mSceneOut->mMetaData->Set(8, "UnitScaleFactor", doc.GlobalSettings().UnitScaleFactor());
  2891. mSceneOut->mMetaData->Set(9, "OriginalUnitScaleFactor", doc.GlobalSettings().OriginalUnitScaleFactor());
  2892. mSceneOut->mMetaData->Set(10, "AmbientColor", doc.GlobalSettings().AmbientColor());
  2893. mSceneOut->mMetaData->Set(11, "FrameRate", (int)doc.GlobalSettings().TimeMode());
  2894. mSceneOut->mMetaData->Set(12, "TimeSpanStart", doc.GlobalSettings().TimeSpanStart());
  2895. mSceneOut->mMetaData->Set(13, "TimeSpanStop", doc.GlobalSettings().TimeSpanStop());
  2896. mSceneOut->mMetaData->Set(14, "CustomFrameRate", doc.GlobalSettings().CustomFrameRate());
  2897. mSceneOut->mMetaData->Set(15, AI_METADATA_SOURCE_FORMAT_VERSION, aiString(ai_to_string(doc.FBXVersion())));
  2898. if (hasGenerator) {
  2899. mSceneOut->mMetaData->Set(16, AI_METADATA_SOURCE_GENERATOR, aiString(doc.Creator()));
  2900. }
  2901. }
  2902. void FBXConverter::TransferDataToScene() {
  2903. ai_assert(!mSceneOut->mMeshes);
  2904. ai_assert(!mSceneOut->mNumMeshes);
  2905. // note: the trailing () ensures initialization with nullptr - not
  2906. // many C++ users seem to know this, so pointing it out to avoid
  2907. // confusion why this code works.
  2908. if (!mMeshes.empty()) {
  2909. mSceneOut->mMeshes = new aiMesh *[mMeshes.size()]();
  2910. mSceneOut->mNumMeshes = static_cast<unsigned int>(mMeshes.size());
  2911. std::swap_ranges(mMeshes.begin(), mMeshes.end(), mSceneOut->mMeshes);
  2912. }
  2913. if (!materials.empty()) {
  2914. mSceneOut->mMaterials = new aiMaterial *[materials.size()]();
  2915. mSceneOut->mNumMaterials = static_cast<unsigned int>(materials.size());
  2916. std::swap_ranges(materials.begin(), materials.end(), mSceneOut->mMaterials);
  2917. }
  2918. if (!animations.empty()) {
  2919. mSceneOut->mAnimations = new aiAnimation *[animations.size()]();
  2920. mSceneOut->mNumAnimations = static_cast<unsigned int>(animations.size());
  2921. std::swap_ranges(animations.begin(), animations.end(), mSceneOut->mAnimations);
  2922. }
  2923. if (!lights.empty()) {
  2924. mSceneOut->mLights = new aiLight *[lights.size()]();
  2925. mSceneOut->mNumLights = static_cast<unsigned int>(lights.size());
  2926. std::swap_ranges(lights.begin(), lights.end(), mSceneOut->mLights);
  2927. }
  2928. if (!cameras.empty()) {
  2929. mSceneOut->mCameras = new aiCamera *[cameras.size()]();
  2930. mSceneOut->mNumCameras = static_cast<unsigned int>(cameras.size());
  2931. std::swap_ranges(cameras.begin(), cameras.end(), mSceneOut->mCameras);
  2932. }
  2933. if (!textures.empty()) {
  2934. mSceneOut->mTextures = new aiTexture *[textures.size()]();
  2935. mSceneOut->mNumTextures = static_cast<unsigned int>(textures.size());
  2936. std::swap_ranges(textures.begin(), textures.end(), mSceneOut->mTextures);
  2937. }
  2938. }
  2939. void FBXConverter::ConvertOrphanedEmbeddedTextures() {
  2940. // in C++14 it could be:
  2941. // for (auto&& [id, object] : objects)
  2942. for (auto &&id_and_object : doc.Objects()) {
  2943. auto &&id = std::get<0>(id_and_object);
  2944. auto &&object = std::get<1>(id_and_object);
  2945. // If an object doesn't have parent
  2946. if (doc.ConnectionsBySource().count(id) == 0) {
  2947. const Texture *realTexture = nullptr;
  2948. try {
  2949. const auto &element = object->GetElement();
  2950. const Token &key = element.KeyToken();
  2951. const char *obtype = key.begin();
  2952. const size_t length = static_cast<size_t>(key.end() - key.begin());
  2953. if (strncmp(obtype, "Texture", length) == 0) {
  2954. if (const Texture *texture = static_cast<const Texture *>(object->Get())) {
  2955. if (texture->Media() && texture->Media()->ContentLength() > 0) {
  2956. realTexture = texture;
  2957. }
  2958. }
  2959. }
  2960. } catch (...) {
  2961. // do nothing
  2962. }
  2963. if (realTexture) {
  2964. const Video *media = realTexture->Media();
  2965. unsigned int index = ConvertVideo(*media);
  2966. textures_converted[media] = index;
  2967. }
  2968. }
  2969. }
  2970. }
  2971. // ------------------------------------------------------------------------------------------------
  2972. void ConvertToAssimpScene(aiScene *out, const Document &doc, bool removeEmptyBones) {
  2973. FBXConverter converter(out, doc, removeEmptyBones);
  2974. }
  2975. } // namespace FBX
  2976. } // namespace Assimp
  2977. #endif