FBXConverter.cpp 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2018, 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 "FBXParser.h"
  39. #include "FBXMeshGeometry.h"
  40. #include "FBXDocument.h"
  41. #include "FBXUtil.h"
  42. #include "FBXProperties.h"
  43. #include "FBXImporter.h"
  44. #include <assimp/StringComparison.h>
  45. #include <assimp/scene.h>
  46. #include <tuple>
  47. #include <memory>
  48. #include <iterator>
  49. #include <vector>
  50. namespace Assimp {
  51. namespace FBX {
  52. using namespace Util;
  53. #define MAGIC_NODE_TAG "_$AssimpFbx$"
  54. #define CONVERT_FBX_TIME(time) static_cast<double>(time) / 46186158000L
  55. // XXX vc9's debugger won't step into anonymous namespaces
  56. //namespace {
  57. Converter::Converter( aiScene* out, const Document& doc )
  58. : defaultMaterialIndex()
  59. , out( out )
  60. , doc( doc ) {
  61. // animations need to be converted first since this will
  62. // populate the node_anim_chain_bits map, which is needed
  63. // to determine which nodes need to be generated.
  64. ConvertAnimations();
  65. ConvertRootNode();
  66. if ( doc.Settings().readAllMaterials ) {
  67. // unfortunately this means we have to evaluate all objects
  68. for( const ObjectMap::value_type& v : doc.Objects() ) {
  69. const Object* ob = v.second->Get();
  70. if ( !ob ) {
  71. continue;
  72. }
  73. const Material* mat = dynamic_cast<const Material*>( ob );
  74. if ( mat ) {
  75. if ( materials_converted.find( mat ) == materials_converted.end() ) {
  76. ConvertMaterial( *mat, 0 );
  77. }
  78. }
  79. }
  80. }
  81. ConvertGlobalSettings();
  82. TransferDataToScene();
  83. // if we didn't read any meshes set the AI_SCENE_FLAGS_INCOMPLETE
  84. // to make sure the scene passes assimp's validation. FBX files
  85. // need not contain geometry (i.e. camera animations, raw armatures).
  86. if ( out->mNumMeshes == 0 ) {
  87. out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  88. }
  89. }
  90. Converter::~Converter() {
  91. std::for_each( meshes.begin(), meshes.end(), Util::delete_fun<aiMesh>() );
  92. std::for_each( materials.begin(), materials.end(), Util::delete_fun<aiMaterial>() );
  93. std::for_each( animations.begin(), animations.end(), Util::delete_fun<aiAnimation>() );
  94. std::for_each( lights.begin(), lights.end(), Util::delete_fun<aiLight>() );
  95. std::for_each( cameras.begin(), cameras.end(), Util::delete_fun<aiCamera>() );
  96. std::for_each( textures.begin(), textures.end(), Util::delete_fun<aiTexture>() );
  97. }
  98. void Converter::ConvertRootNode() {
  99. out->mRootNode = new aiNode();
  100. out->mRootNode->mName.Set( "RootNode" );
  101. // root has ID 0
  102. ConvertNodes( 0L, *out->mRootNode );
  103. }
  104. void Converter::ConvertNodes( uint64_t id, aiNode& parent, const aiMatrix4x4& parent_transform )
  105. {
  106. const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced( id, "Model" );
  107. std::vector<aiNode*> nodes;
  108. nodes.reserve( conns.size() );
  109. std::vector<aiNode*> nodes_chain;
  110. std::vector<aiNode*> post_nodes_chain;
  111. try {
  112. for( const Connection* con : conns ) {
  113. // ignore object-property links
  114. if ( con->PropertyName().length() ) {
  115. continue;
  116. }
  117. const Object* const object = con->SourceObject();
  118. if ( !object ) {
  119. FBXImporter::LogWarn( "failed to convert source object for Model link" );
  120. continue;
  121. }
  122. const Model* const model = dynamic_cast<const Model*>( object );
  123. if ( model ) {
  124. nodes_chain.clear();
  125. post_nodes_chain.clear();
  126. aiMatrix4x4 new_abs_transform = parent_transform;
  127. // even though there is only a single input node, the design of
  128. // assimp (or rather: the complicated transformation chain that
  129. // is employed by fbx) means that we may need multiple aiNode's
  130. // to represent a fbx node's transformation.
  131. GenerateTransformationNodeChain( *model, nodes_chain, post_nodes_chain );
  132. ai_assert( nodes_chain.size() );
  133. const std::string& original_name = FixNodeName( model->Name() );
  134. // check if any of the nodes in the chain has the name the fbx node
  135. // is supposed to have. If there is none, add another node to
  136. // preserve the name - people might have scripts etc. that rely
  137. // on specific node names.
  138. aiNode* name_carrier = NULL;
  139. for( aiNode* prenode : nodes_chain ) {
  140. if ( !strcmp( prenode->mName.C_Str(), original_name.c_str() ) ) {
  141. name_carrier = prenode;
  142. break;
  143. }
  144. }
  145. if ( !name_carrier ) {
  146. nodes_chain.push_back( new aiNode( original_name ) );
  147. }
  148. //setup metadata on newest node
  149. SetupNodeMetadata( *model, *nodes_chain.back() );
  150. // link all nodes in a row
  151. aiNode* last_parent = &parent;
  152. for( aiNode* prenode : nodes_chain ) {
  153. ai_assert( prenode );
  154. if ( last_parent != &parent ) {
  155. last_parent->mNumChildren = 1;
  156. last_parent->mChildren = new aiNode*[ 1 ];
  157. last_parent->mChildren[ 0 ] = prenode;
  158. }
  159. prenode->mParent = last_parent;
  160. last_parent = prenode;
  161. new_abs_transform *= prenode->mTransformation;
  162. }
  163. // attach geometry
  164. ConvertModel( *model, *nodes_chain.back(), new_abs_transform );
  165. // check if there will be any child nodes
  166. const std::vector<const Connection*>& child_conns
  167. = doc.GetConnectionsByDestinationSequenced( model->ID(), "Model" );
  168. // if so, link the geometric transform inverse nodes
  169. // before we attach any child nodes
  170. if (child_conns.size()) {
  171. for( aiNode* postnode : post_nodes_chain ) {
  172. ai_assert( postnode );
  173. if ( last_parent != &parent ) {
  174. last_parent->mNumChildren = 1;
  175. last_parent->mChildren = new aiNode*[ 1 ];
  176. last_parent->mChildren[ 0 ] = postnode;
  177. }
  178. postnode->mParent = last_parent;
  179. last_parent = postnode;
  180. new_abs_transform *= postnode->mTransformation;
  181. }
  182. } else {
  183. // free the nodes we allocated as we don't need them
  184. Util::delete_fun<aiNode> deleter;
  185. std::for_each(
  186. post_nodes_chain.begin(),
  187. post_nodes_chain.end(),
  188. deleter
  189. );
  190. }
  191. // attach sub-nodes (if any)
  192. ConvertNodes( model->ID(), *last_parent, new_abs_transform );
  193. if ( doc.Settings().readLights ) {
  194. ConvertLights( *model );
  195. }
  196. if ( doc.Settings().readCameras ) {
  197. ConvertCameras( *model );
  198. }
  199. nodes.push_back( nodes_chain.front() );
  200. nodes_chain.clear();
  201. }
  202. }
  203. if ( nodes.size() ) {
  204. parent.mChildren = new aiNode*[ nodes.size() ]();
  205. parent.mNumChildren = static_cast<unsigned int>( nodes.size() );
  206. std::swap_ranges( nodes.begin(), nodes.end(), parent.mChildren );
  207. }
  208. }
  209. catch ( std::exception& ) {
  210. Util::delete_fun<aiNode> deleter;
  211. std::for_each( nodes.begin(), nodes.end(), deleter );
  212. std::for_each( nodes_chain.begin(), nodes_chain.end(), deleter );
  213. std::for_each( post_nodes_chain.begin(), post_nodes_chain.end(), deleter );
  214. }
  215. }
  216. void Converter::ConvertLights( const Model& model )
  217. {
  218. const std::vector<const NodeAttribute*>& node_attrs = model.GetAttributes();
  219. for( const NodeAttribute* attr : node_attrs ) {
  220. const Light* const light = dynamic_cast<const Light*>( attr );
  221. if ( light ) {
  222. ConvertLight( model, *light );
  223. }
  224. }
  225. }
  226. void Converter::ConvertCameras( const Model& model )
  227. {
  228. const std::vector<const NodeAttribute*>& node_attrs = model.GetAttributes();
  229. for( const NodeAttribute* attr : node_attrs ) {
  230. const Camera* const cam = dynamic_cast<const Camera*>( attr );
  231. if ( cam ) {
  232. ConvertCamera( model, *cam );
  233. }
  234. }
  235. }
  236. void Converter::ConvertLight( const Model& model, const Light& light )
  237. {
  238. lights.push_back( new aiLight() );
  239. aiLight* const out_light = lights.back();
  240. out_light->mName.Set( FixNodeName( model.Name() ) );
  241. const float intensity = light.Intensity() / 100.0f;
  242. const aiVector3D& col = light.Color();
  243. out_light->mColorDiffuse = aiColor3D( col.x, col.y, col.z );
  244. out_light->mColorDiffuse.r *= intensity;
  245. out_light->mColorDiffuse.g *= intensity;
  246. out_light->mColorDiffuse.b *= intensity;
  247. out_light->mColorSpecular = out_light->mColorDiffuse;
  248. //lights are defined along negative y direction
  249. out_light->mPosition = aiVector3D(0.0f);
  250. out_light->mDirection = aiVector3D(0.0f, -1.0f, 0.0f);
  251. out_light->mUp = aiVector3D(0.0f, 0.0f, -1.0f);
  252. switch ( light.LightType() )
  253. {
  254. case Light::Type_Point:
  255. out_light->mType = aiLightSource_POINT;
  256. break;
  257. case Light::Type_Directional:
  258. out_light->mType = aiLightSource_DIRECTIONAL;
  259. break;
  260. case Light::Type_Spot:
  261. out_light->mType = aiLightSource_SPOT;
  262. out_light->mAngleOuterCone = AI_DEG_TO_RAD( light.OuterAngle() );
  263. out_light->mAngleInnerCone = AI_DEG_TO_RAD( light.InnerAngle() );
  264. break;
  265. case Light::Type_Area:
  266. FBXImporter::LogWarn( "cannot represent area light, set to UNDEFINED" );
  267. out_light->mType = aiLightSource_UNDEFINED;
  268. break;
  269. case Light::Type_Volume:
  270. FBXImporter::LogWarn( "cannot represent volume light, set to UNDEFINED" );
  271. out_light->mType = aiLightSource_UNDEFINED;
  272. break;
  273. default:
  274. ai_assert( false );
  275. }
  276. float decay = light.DecayStart();
  277. switch ( light.DecayType() )
  278. {
  279. case Light::Decay_None:
  280. out_light->mAttenuationConstant = decay;
  281. out_light->mAttenuationLinear = 0.0f;
  282. out_light->mAttenuationQuadratic = 0.0f;
  283. break;
  284. case Light::Decay_Linear:
  285. out_light->mAttenuationConstant = 0.0f;
  286. out_light->mAttenuationLinear = 2.0f / decay;
  287. out_light->mAttenuationQuadratic = 0.0f;
  288. break;
  289. case Light::Decay_Quadratic:
  290. out_light->mAttenuationConstant = 0.0f;
  291. out_light->mAttenuationLinear = 0.0f;
  292. out_light->mAttenuationQuadratic = 2.0f / (decay * decay);
  293. break;
  294. case Light::Decay_Cubic:
  295. FBXImporter::LogWarn( "cannot represent cubic attenuation, set to Quadratic" );
  296. out_light->mAttenuationQuadratic = 1.0f;
  297. break;
  298. default:
  299. ai_assert( false );
  300. }
  301. }
  302. void Converter::ConvertCamera( const Model& model, const Camera& cam )
  303. {
  304. cameras.push_back( new aiCamera() );
  305. aiCamera* const out_camera = cameras.back();
  306. out_camera->mName.Set( FixNodeName( model.Name() ) );
  307. out_camera->mAspect = cam.AspectWidth() / cam.AspectHeight();
  308. //cameras are defined along positive x direction
  309. out_camera->mPosition = cam.Position();
  310. out_camera->mLookAt = ( cam.InterestPosition() - out_camera->mPosition ).Normalize();
  311. out_camera->mUp = cam.UpVector();
  312. out_camera->mHorizontalFOV = AI_DEG_TO_RAD( cam.FieldOfView() );
  313. out_camera->mClipPlaneNear = cam.NearPlane();
  314. out_camera->mClipPlaneFar = cam.FarPlane();
  315. }
  316. const char* Converter::NameTransformationComp( TransformationComp comp )
  317. {
  318. switch ( comp )
  319. {
  320. case TransformationComp_Translation:
  321. return "Translation";
  322. case TransformationComp_RotationOffset:
  323. return "RotationOffset";
  324. case TransformationComp_RotationPivot:
  325. return "RotationPivot";
  326. case TransformationComp_PreRotation:
  327. return "PreRotation";
  328. case TransformationComp_Rotation:
  329. return "Rotation";
  330. case TransformationComp_PostRotation:
  331. return "PostRotation";
  332. case TransformationComp_RotationPivotInverse:
  333. return "RotationPivotInverse";
  334. case TransformationComp_ScalingOffset:
  335. return "ScalingOffset";
  336. case TransformationComp_ScalingPivot:
  337. return "ScalingPivot";
  338. case TransformationComp_Scaling:
  339. return "Scaling";
  340. case TransformationComp_ScalingPivotInverse:
  341. return "ScalingPivotInverse";
  342. case TransformationComp_GeometricScaling:
  343. return "GeometricScaling";
  344. case TransformationComp_GeometricRotation:
  345. return "GeometricRotation";
  346. case TransformationComp_GeometricTranslation:
  347. return "GeometricTranslation";
  348. case TransformationComp_GeometricScalingInverse:
  349. return "GeometricScalingInverse";
  350. case TransformationComp_GeometricRotationInverse:
  351. return "GeometricRotationInverse";
  352. case TransformationComp_GeometricTranslationInverse:
  353. return "GeometricTranslationInverse";
  354. case TransformationComp_MAXIMUM: // this is to silence compiler warnings
  355. default:
  356. break;
  357. }
  358. ai_assert( false );
  359. return NULL;
  360. }
  361. const char* Converter::NameTransformationCompProperty( TransformationComp comp )
  362. {
  363. switch ( comp )
  364. {
  365. case TransformationComp_Translation:
  366. return "Lcl Translation";
  367. case TransformationComp_RotationOffset:
  368. return "RotationOffset";
  369. case TransformationComp_RotationPivot:
  370. return "RotationPivot";
  371. case TransformationComp_PreRotation:
  372. return "PreRotation";
  373. case TransformationComp_Rotation:
  374. return "Lcl Rotation";
  375. case TransformationComp_PostRotation:
  376. return "PostRotation";
  377. case TransformationComp_RotationPivotInverse:
  378. return "RotationPivotInverse";
  379. case TransformationComp_ScalingOffset:
  380. return "ScalingOffset";
  381. case TransformationComp_ScalingPivot:
  382. return "ScalingPivot";
  383. case TransformationComp_Scaling:
  384. return "Lcl Scaling";
  385. case TransformationComp_ScalingPivotInverse:
  386. return "ScalingPivotInverse";
  387. case TransformationComp_GeometricScaling:
  388. return "GeometricScaling";
  389. case TransformationComp_GeometricRotation:
  390. return "GeometricRotation";
  391. case TransformationComp_GeometricTranslation:
  392. return "GeometricTranslation";
  393. case TransformationComp_GeometricScalingInverse:
  394. return "GeometricScalingInverse";
  395. case TransformationComp_GeometricRotationInverse:
  396. return "GeometricRotationInverse";
  397. case TransformationComp_GeometricTranslationInverse:
  398. return "GeometricTranslationInverse";
  399. case TransformationComp_MAXIMUM: // this is to silence compiler warnings
  400. break;
  401. }
  402. ai_assert( false );
  403. return NULL;
  404. }
  405. aiVector3D Converter::TransformationCompDefaultValue( TransformationComp comp )
  406. {
  407. // XXX a neat way to solve the never-ending special cases for scaling
  408. // would be to do everything in log space!
  409. return comp == TransformationComp_Scaling ? aiVector3D( 1.f, 1.f, 1.f ) : aiVector3D();
  410. }
  411. void Converter::GetRotationMatrix( Model::RotOrder mode, const aiVector3D& rotation, aiMatrix4x4& out )
  412. {
  413. if ( mode == Model::RotOrder_SphericXYZ ) {
  414. FBXImporter::LogError( "Unsupported RotationMode: SphericXYZ" );
  415. out = aiMatrix4x4();
  416. return;
  417. }
  418. const float angle_epsilon = 1e-6f;
  419. out = aiMatrix4x4();
  420. bool is_id[ 3 ] = { true, true, true };
  421. aiMatrix4x4 temp[ 3 ];
  422. if ( std::fabs( rotation.z ) > angle_epsilon ) {
  423. aiMatrix4x4::RotationZ( AI_DEG_TO_RAD( rotation.z ), temp[ 2 ] );
  424. is_id[ 2 ] = false;
  425. }
  426. if ( std::fabs( rotation.y ) > angle_epsilon ) {
  427. aiMatrix4x4::RotationY( AI_DEG_TO_RAD( rotation.y ), temp[ 1 ] );
  428. is_id[ 1 ] = false;
  429. }
  430. if ( std::fabs( rotation.x ) > angle_epsilon ) {
  431. aiMatrix4x4::RotationX( AI_DEG_TO_RAD( rotation.x ), temp[ 0 ] );
  432. is_id[ 0 ] = false;
  433. }
  434. int order[ 3 ] = { -1, -1, -1 };
  435. // note: rotation order is inverted since we're left multiplying as is usual in assimp
  436. switch ( mode )
  437. {
  438. case Model::RotOrder_EulerXYZ:
  439. order[ 0 ] = 2;
  440. order[ 1 ] = 1;
  441. order[ 2 ] = 0;
  442. break;
  443. case Model::RotOrder_EulerXZY:
  444. order[ 0 ] = 1;
  445. order[ 1 ] = 2;
  446. order[ 2 ] = 0;
  447. break;
  448. case Model::RotOrder_EulerYZX:
  449. order[ 0 ] = 0;
  450. order[ 1 ] = 2;
  451. order[ 2 ] = 1;
  452. break;
  453. case Model::RotOrder_EulerYXZ:
  454. order[ 0 ] = 2;
  455. order[ 1 ] = 0;
  456. order[ 2 ] = 1;
  457. break;
  458. case Model::RotOrder_EulerZXY:
  459. order[ 0 ] = 1;
  460. order[ 1 ] = 0;
  461. order[ 2 ] = 2;
  462. break;
  463. case Model::RotOrder_EulerZYX:
  464. order[ 0 ] = 0;
  465. order[ 1 ] = 1;
  466. order[ 2 ] = 2;
  467. break;
  468. default:
  469. ai_assert( false );
  470. }
  471. ai_assert( ( order[ 0 ] >= 0 ) && ( order[ 0 ] <= 2 ) );
  472. ai_assert( ( order[ 1 ] >= 0 ) && ( order[ 1 ] <= 2 ) );
  473. ai_assert( ( order[ 2 ] >= 0 ) && ( order[ 2 ] <= 2 ) );
  474. if ( !is_id[ order[ 0 ] ] ) {
  475. out = temp[ order[ 0 ] ];
  476. }
  477. if ( !is_id[ order[ 1 ] ] ) {
  478. out = out * temp[ order[ 1 ] ];
  479. }
  480. if ( !is_id[ order[ 2 ] ] ) {
  481. out = out * temp[ order[ 2 ] ];
  482. }
  483. }
  484. bool Converter::NeedsComplexTransformationChain( const Model& model )
  485. {
  486. const PropertyTable& props = model.Props();
  487. bool ok;
  488. const float zero_epsilon = 1e-6f;
  489. const aiVector3D all_ones(1.0f, 1.0f, 1.0f);
  490. for ( size_t i = 0; i < TransformationComp_MAXIMUM; ++i ) {
  491. const TransformationComp comp = static_cast< TransformationComp >( i );
  492. if ( comp == TransformationComp_Rotation || comp == TransformationComp_Scaling || comp == TransformationComp_Translation ) {
  493. continue;
  494. }
  495. bool scale_compare = ( comp == TransformationComp_GeometricScaling || comp == TransformationComp_Scaling );
  496. const aiVector3D& v = PropertyGet<aiVector3D>( props, NameTransformationCompProperty( comp ), ok );
  497. if ( ok && scale_compare ) {
  498. if ( (v - all_ones).SquareLength() > zero_epsilon ) {
  499. return true;
  500. }
  501. } else if ( ok ) {
  502. if ( v.SquareLength() > zero_epsilon ) {
  503. return true;
  504. }
  505. }
  506. }
  507. return false;
  508. }
  509. std::string Converter::NameTransformationChainNode( const std::string& name, TransformationComp comp )
  510. {
  511. return name + std::string( MAGIC_NODE_TAG ) + "_" + NameTransformationComp( comp );
  512. }
  513. void Converter::GenerateTransformationNodeChain( const Model& model, std::vector<aiNode*>& output_nodes, std::vector<aiNode*>& post_output_nodes )
  514. {
  515. const PropertyTable& props = model.Props();
  516. const Model::RotOrder rot = model.RotationOrder();
  517. bool ok;
  518. aiMatrix4x4 chain[ TransformationComp_MAXIMUM ];
  519. std::fill_n( chain, static_cast<unsigned int>( TransformationComp_MAXIMUM ), aiMatrix4x4() );
  520. // generate transformation matrices for all the different transformation components
  521. const float zero_epsilon = 1e-6f;
  522. const aiVector3D all_ones(1.0f, 1.0f, 1.0f);
  523. bool is_complex = false;
  524. const aiVector3D& PreRotation = PropertyGet<aiVector3D>( props, "PreRotation", ok );
  525. if ( ok && PreRotation.SquareLength() > zero_epsilon ) {
  526. is_complex = true;
  527. GetRotationMatrix( rot, PreRotation, chain[ TransformationComp_PreRotation ] );
  528. }
  529. const aiVector3D& PostRotation = PropertyGet<aiVector3D>( props, "PostRotation", ok );
  530. if ( ok && PostRotation.SquareLength() > zero_epsilon ) {
  531. is_complex = true;
  532. GetRotationMatrix( rot, PostRotation, chain[ TransformationComp_PostRotation ] );
  533. }
  534. const aiVector3D& RotationPivot = PropertyGet<aiVector3D>( props, "RotationPivot", ok );
  535. if ( ok && RotationPivot.SquareLength() > zero_epsilon ) {
  536. is_complex = true;
  537. aiMatrix4x4::Translation( RotationPivot, chain[ TransformationComp_RotationPivot ] );
  538. aiMatrix4x4::Translation( -RotationPivot, chain[ TransformationComp_RotationPivotInverse ] );
  539. }
  540. const aiVector3D& RotationOffset = PropertyGet<aiVector3D>( props, "RotationOffset", ok );
  541. if ( ok && RotationOffset.SquareLength() > zero_epsilon ) {
  542. is_complex = true;
  543. aiMatrix4x4::Translation( RotationOffset, chain[ TransformationComp_RotationOffset ] );
  544. }
  545. const aiVector3D& ScalingOffset = PropertyGet<aiVector3D>( props, "ScalingOffset", ok );
  546. if ( ok && ScalingOffset.SquareLength() > zero_epsilon ) {
  547. is_complex = true;
  548. aiMatrix4x4::Translation( ScalingOffset, chain[ TransformationComp_ScalingOffset ] );
  549. }
  550. const aiVector3D& ScalingPivot = PropertyGet<aiVector3D>( props, "ScalingPivot", ok );
  551. if ( ok && ScalingPivot.SquareLength() > zero_epsilon ) {
  552. is_complex = true;
  553. aiMatrix4x4::Translation( ScalingPivot, chain[ TransformationComp_ScalingPivot ] );
  554. aiMatrix4x4::Translation( -ScalingPivot, chain[ TransformationComp_ScalingPivotInverse ] );
  555. }
  556. const aiVector3D& Translation = PropertyGet<aiVector3D>( props, "Lcl Translation", ok );
  557. if ( ok && Translation.SquareLength() > zero_epsilon ) {
  558. aiMatrix4x4::Translation( Translation, chain[ TransformationComp_Translation ] );
  559. }
  560. const aiVector3D& Scaling = PropertyGet<aiVector3D>( props, "Lcl Scaling", ok );
  561. if ( ok && (Scaling - all_ones).SquareLength() > zero_epsilon ) {
  562. aiMatrix4x4::Scaling( Scaling, chain[ TransformationComp_Scaling ] );
  563. }
  564. const aiVector3D& Rotation = PropertyGet<aiVector3D>( props, "Lcl Rotation", ok );
  565. if ( ok && Rotation.SquareLength() > zero_epsilon ) {
  566. GetRotationMatrix( rot, Rotation, chain[ TransformationComp_Rotation ] );
  567. }
  568. const aiVector3D& GeometricScaling = PropertyGet<aiVector3D>( props, "GeometricScaling", ok );
  569. if ( ok && (GeometricScaling - all_ones).SquareLength() > zero_epsilon ) {
  570. is_complex = true;
  571. aiMatrix4x4::Scaling( GeometricScaling, chain[ TransformationComp_GeometricScaling ] );
  572. aiVector3D GeometricScalingInverse = GeometricScaling;
  573. bool canscale = true;
  574. for (size_t i = 0; i < 3; ++i) {
  575. if ( std::fabs( GeometricScalingInverse[i] ) > zero_epsilon ) {
  576. GeometricScalingInverse[i] = 1.0f / GeometricScaling[i];
  577. } else {
  578. FBXImporter::LogError( "cannot invert geometric scaling matrix with a 0.0 scale component" );
  579. canscale = false;
  580. break;
  581. }
  582. }
  583. if (canscale) {
  584. aiMatrix4x4::Scaling( GeometricScalingInverse, chain[ TransformationComp_GeometricScalingInverse ] );
  585. }
  586. }
  587. const aiVector3D& GeometricRotation = PropertyGet<aiVector3D>( props, "GeometricRotation", ok );
  588. if ( ok && GeometricRotation.SquareLength() > zero_epsilon ) {
  589. is_complex = true;
  590. GetRotationMatrix( rot, GeometricRotation, chain[ TransformationComp_GeometricRotation ] );
  591. GetRotationMatrix( rot, GeometricRotation, chain[ TransformationComp_GeometricRotationInverse ] );
  592. chain[ TransformationComp_GeometricRotationInverse ].Inverse();
  593. }
  594. const aiVector3D& GeometricTranslation = PropertyGet<aiVector3D>( props, "GeometricTranslation", ok );
  595. if ( ok && GeometricTranslation.SquareLength() > zero_epsilon ) {
  596. is_complex = true;
  597. aiMatrix4x4::Translation( GeometricTranslation, chain[ TransformationComp_GeometricTranslation ] );
  598. aiMatrix4x4::Translation( -GeometricTranslation, chain[ TransformationComp_GeometricTranslationInverse ] );
  599. }
  600. // is_complex needs to be consistent with NeedsComplexTransformationChain()
  601. // or the interplay between this code and the animation converter would
  602. // not be guaranteed.
  603. ai_assert( NeedsComplexTransformationChain( model ) == is_complex );
  604. const std::string& name = FixNodeName( model.Name() );
  605. // now, if we have more than just Translation, Scaling and Rotation,
  606. // we need to generate a full node chain to accommodate for assimp's
  607. // lack to express pivots and offsets.
  608. if ( is_complex && doc.Settings().preservePivots ) {
  609. FBXImporter::LogInfo( "generating full transformation chain for node: " + name );
  610. // query the anim_chain_bits dictionary to find out which chain elements
  611. // have associated node animation channels. These can not be dropped
  612. // even if they have identity transform in bind pose.
  613. NodeAnimBitMap::const_iterator it = node_anim_chain_bits.find( name );
  614. const unsigned int anim_chain_bitmask = ( it == node_anim_chain_bits.end() ? 0 : ( *it ).second );
  615. unsigned int bit = 0x1;
  616. for ( size_t i = 0; i < TransformationComp_MAXIMUM; ++i, bit <<= 1 ) {
  617. const TransformationComp comp = static_cast<TransformationComp>( i );
  618. if ( chain[ i ].IsIdentity() && ( anim_chain_bitmask & bit ) == 0 ) {
  619. continue;
  620. }
  621. if ( comp == TransformationComp_PostRotation ) {
  622. chain[ i ] = chain[ i ].Inverse();
  623. }
  624. aiNode* nd = new aiNode();
  625. nd->mName.Set( NameTransformationChainNode( name, comp ) );
  626. nd->mTransformation = chain[ i ];
  627. // geometric inverses go in a post-node chain
  628. if ( comp == TransformationComp_GeometricScalingInverse ||
  629. comp == TransformationComp_GeometricRotationInverse ||
  630. comp == TransformationComp_GeometricTranslationInverse
  631. ) {
  632. post_output_nodes.push_back( nd );
  633. } else {
  634. output_nodes.push_back( nd );
  635. }
  636. }
  637. ai_assert( output_nodes.size() );
  638. return;
  639. }
  640. // else, we can just multiply the matrices together
  641. aiNode* nd = new aiNode();
  642. output_nodes.push_back( nd );
  643. nd->mName.Set( name );
  644. for (const auto &transform : chain) {
  645. nd->mTransformation = nd->mTransformation * transform;
  646. }
  647. }
  648. void Converter::SetupNodeMetadata( const Model& model, aiNode& nd )
  649. {
  650. const PropertyTable& props = model.Props();
  651. DirectPropertyMap unparsedProperties = props.GetUnparsedProperties();
  652. // create metadata on node
  653. const std::size_t numStaticMetaData = 2;
  654. aiMetadata* data = aiMetadata::Alloc( static_cast<unsigned int>(unparsedProperties.size() + numStaticMetaData) );
  655. nd.mMetaData = data;
  656. int index = 0;
  657. // find user defined properties (3ds Max)
  658. data->Set( index++, "UserProperties", aiString( PropertyGet<std::string>( props, "UDP3DSMAX", "" ) ) );
  659. // preserve the info that a node was marked as Null node in the original file.
  660. data->Set( index++, "IsNull", model.IsNull() ? true : false );
  661. // add unparsed properties to the node's metadata
  662. for( const DirectPropertyMap::value_type& prop : unparsedProperties ) {
  663. // Interpret the property as a concrete type
  664. if ( const TypedProperty<bool>* interpreted = prop.second->As<TypedProperty<bool> >() ) {
  665. data->Set( index++, prop.first, interpreted->Value() );
  666. } else if ( const TypedProperty<int>* interpreted = prop.second->As<TypedProperty<int> >() ) {
  667. data->Set( index++, prop.first, interpreted->Value() );
  668. } else if ( const TypedProperty<uint64_t>* interpreted = prop.second->As<TypedProperty<uint64_t> >() ) {
  669. data->Set( index++, prop.first, interpreted->Value() );
  670. } else if ( const TypedProperty<float>* interpreted = prop.second->As<TypedProperty<float> >() ) {
  671. data->Set( index++, prop.first, interpreted->Value() );
  672. } else if ( const TypedProperty<std::string>* interpreted = prop.second->As<TypedProperty<std::string> >() ) {
  673. data->Set( index++, prop.first, aiString( interpreted->Value() ) );
  674. } else if ( const TypedProperty<aiVector3D>* interpreted = prop.second->As<TypedProperty<aiVector3D> >() ) {
  675. data->Set( index++, prop.first, interpreted->Value() );
  676. } else {
  677. ai_assert( false );
  678. }
  679. }
  680. }
  681. void Converter::ConvertModel( const Model& model, aiNode& nd, const aiMatrix4x4& node_global_transform )
  682. {
  683. const std::vector<const Geometry*>& geos = model.GetGeometry();
  684. std::vector<unsigned int> meshes;
  685. meshes.reserve( geos.size() );
  686. for( const Geometry* geo : geos ) {
  687. const MeshGeometry* const mesh = dynamic_cast< const MeshGeometry* >( geo );
  688. if ( mesh ) {
  689. const std::vector<unsigned int>& indices = ConvertMesh( *mesh, model, node_global_transform );
  690. std::copy( indices.begin(), indices.end(), std::back_inserter( meshes ) );
  691. }
  692. else {
  693. FBXImporter::LogWarn( "ignoring unrecognized geometry: " + geo->Name() );
  694. }
  695. }
  696. if ( meshes.size() ) {
  697. nd.mMeshes = new unsigned int[ meshes.size() ]();
  698. nd.mNumMeshes = static_cast< unsigned int >( meshes.size() );
  699. std::swap_ranges( meshes.begin(), meshes.end(), nd.mMeshes );
  700. }
  701. }
  702. std::vector<unsigned int> Converter::ConvertMesh( const MeshGeometry& mesh, const Model& model,
  703. const aiMatrix4x4& node_global_transform )
  704. {
  705. std::vector<unsigned int> temp;
  706. MeshMap::const_iterator it = meshes_converted.find( &mesh );
  707. if ( it != meshes_converted.end() ) {
  708. std::copy( ( *it ).second.begin(), ( *it ).second.end(), std::back_inserter( temp ) );
  709. return temp;
  710. }
  711. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  712. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  713. if ( vertices.empty() || faces.empty() ) {
  714. FBXImporter::LogWarn( "ignoring empty geometry: " + mesh.Name() );
  715. return temp;
  716. }
  717. // one material per mesh maps easily to aiMesh. Multiple material
  718. // meshes need to be split.
  719. const MatIndexArray& mindices = mesh.GetMaterialIndices();
  720. if ( doc.Settings().readMaterials && !mindices.empty() ) {
  721. const MatIndexArray::value_type base = mindices[ 0 ];
  722. for( MatIndexArray::value_type index : mindices ) {
  723. if ( index != base ) {
  724. return ConvertMeshMultiMaterial( mesh, model, node_global_transform );
  725. }
  726. }
  727. }
  728. // faster code-path, just copy the data
  729. temp.push_back( ConvertMeshSingleMaterial( mesh, model, node_global_transform ) );
  730. return temp;
  731. }
  732. aiMesh* Converter::SetupEmptyMesh( const MeshGeometry& mesh )
  733. {
  734. aiMesh* const out_mesh = new aiMesh();
  735. meshes.push_back( out_mesh );
  736. meshes_converted[ &mesh ].push_back( static_cast<unsigned int>( meshes.size() - 1 ) );
  737. // set name
  738. std::string name = mesh.Name();
  739. if ( name.substr( 0, 10 ) == "Geometry::" ) {
  740. name = name.substr( 10 );
  741. }
  742. if ( name.length() ) {
  743. out_mesh->mName.Set( name );
  744. }
  745. return out_mesh;
  746. }
  747. unsigned int Converter::ConvertMeshSingleMaterial( const MeshGeometry& mesh, const Model& model,
  748. const aiMatrix4x4& node_global_transform )
  749. {
  750. const MatIndexArray& mindices = mesh.GetMaterialIndices();
  751. aiMesh* const out_mesh = SetupEmptyMesh( mesh );
  752. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  753. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  754. // copy vertices
  755. out_mesh->mNumVertices = static_cast<unsigned int>( vertices.size() );
  756. out_mesh->mVertices = new aiVector3D[ vertices.size() ];
  757. std::copy( vertices.begin(), vertices.end(), out_mesh->mVertices );
  758. // generate dummy faces
  759. out_mesh->mNumFaces = static_cast<unsigned int>( faces.size() );
  760. aiFace* fac = out_mesh->mFaces = new aiFace[ faces.size() ]();
  761. unsigned int cursor = 0;
  762. for( unsigned int pcount : faces ) {
  763. aiFace& f = *fac++;
  764. f.mNumIndices = pcount;
  765. f.mIndices = new unsigned int[ pcount ];
  766. switch ( pcount )
  767. {
  768. case 1:
  769. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  770. break;
  771. case 2:
  772. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  773. break;
  774. case 3:
  775. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  776. break;
  777. default:
  778. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  779. break;
  780. }
  781. for ( unsigned int i = 0; i < pcount; ++i ) {
  782. f.mIndices[ i ] = cursor++;
  783. }
  784. }
  785. // copy normals
  786. const std::vector<aiVector3D>& normals = mesh.GetNormals();
  787. if ( normals.size() ) {
  788. ai_assert( normals.size() == vertices.size() );
  789. out_mesh->mNormals = new aiVector3D[ vertices.size() ];
  790. std::copy( normals.begin(), normals.end(), out_mesh->mNormals );
  791. }
  792. // copy tangents - assimp requires both tangents and bitangents (binormals)
  793. // to be present, or neither of them. Compute binormals from normals
  794. // and tangents if needed.
  795. const std::vector<aiVector3D>& tangents = mesh.GetTangents();
  796. const std::vector<aiVector3D>* binormals = &mesh.GetBinormals();
  797. if ( tangents.size() ) {
  798. std::vector<aiVector3D> tempBinormals;
  799. if ( !binormals->size() ) {
  800. if ( normals.size() ) {
  801. tempBinormals.resize( normals.size() );
  802. for ( unsigned int i = 0; i < tangents.size(); ++i ) {
  803. tempBinormals[ i ] = normals[ i ] ^ tangents[ i ];
  804. }
  805. binormals = &tempBinormals;
  806. }
  807. else {
  808. binormals = NULL;
  809. }
  810. }
  811. if ( binormals ) {
  812. ai_assert( tangents.size() == vertices.size() );
  813. ai_assert( binormals->size() == vertices.size() );
  814. out_mesh->mTangents = new aiVector3D[ vertices.size() ];
  815. std::copy( tangents.begin(), tangents.end(), out_mesh->mTangents );
  816. out_mesh->mBitangents = new aiVector3D[ vertices.size() ];
  817. std::copy( binormals->begin(), binormals->end(), out_mesh->mBitangents );
  818. }
  819. }
  820. // copy texture coords
  821. for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i ) {
  822. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords( i );
  823. if ( uvs.empty() ) {
  824. break;
  825. }
  826. aiVector3D* out_uv = out_mesh->mTextureCoords[ i ] = new aiVector3D[ vertices.size() ];
  827. for( const aiVector2D& v : uvs ) {
  828. *out_uv++ = aiVector3D( v.x, v.y, 0.0f );
  829. }
  830. out_mesh->mNumUVComponents[ i ] = 2;
  831. }
  832. // copy vertex colors
  833. for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i ) {
  834. const std::vector<aiColor4D>& colors = mesh.GetVertexColors( i );
  835. if ( colors.empty() ) {
  836. break;
  837. }
  838. out_mesh->mColors[ i ] = new aiColor4D[ vertices.size() ];
  839. std::copy( colors.begin(), colors.end(), out_mesh->mColors[ i ] );
  840. }
  841. if ( !doc.Settings().readMaterials || mindices.empty() ) {
  842. FBXImporter::LogError( "no material assigned to mesh, setting default material" );
  843. out_mesh->mMaterialIndex = GetDefaultMaterial();
  844. }
  845. else {
  846. ConvertMaterialForMesh( out_mesh, model, mesh, mindices[ 0 ] );
  847. }
  848. if ( doc.Settings().readWeights && mesh.DeformerSkin() != NULL ) {
  849. ConvertWeights( out_mesh, model, mesh, node_global_transform, NO_MATERIAL_SEPARATION );
  850. }
  851. return static_cast<unsigned int>( meshes.size() - 1 );
  852. }
  853. std::vector<unsigned int> Converter::ConvertMeshMultiMaterial( const MeshGeometry& mesh, const Model& model,
  854. const aiMatrix4x4& node_global_transform )
  855. {
  856. const MatIndexArray& mindices = mesh.GetMaterialIndices();
  857. ai_assert( mindices.size() );
  858. std::set<MatIndexArray::value_type> had;
  859. std::vector<unsigned int> indices;
  860. for( MatIndexArray::value_type index : mindices ) {
  861. if ( had.find( index ) == had.end() ) {
  862. indices.push_back( ConvertMeshMultiMaterial( mesh, model, index, node_global_transform ) );
  863. had.insert( index );
  864. }
  865. }
  866. return indices;
  867. }
  868. unsigned int Converter::ConvertMeshMultiMaterial( const MeshGeometry& mesh, const Model& model,
  869. MatIndexArray::value_type index,
  870. const aiMatrix4x4& node_global_transform )
  871. {
  872. aiMesh* const out_mesh = SetupEmptyMesh( mesh );
  873. const MatIndexArray& mindices = mesh.GetMaterialIndices();
  874. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  875. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  876. const bool process_weights = doc.Settings().readWeights && mesh.DeformerSkin() != NULL;
  877. unsigned int count_faces = 0;
  878. unsigned int count_vertices = 0;
  879. // count faces
  880. std::vector<unsigned int>::const_iterator itf = faces.begin();
  881. for ( MatIndexArray::const_iterator it = mindices.begin(),
  882. end = mindices.end(); it != end; ++it, ++itf )
  883. {
  884. if ( ( *it ) != index ) {
  885. continue;
  886. }
  887. ++count_faces;
  888. count_vertices += *itf;
  889. }
  890. ai_assert( count_faces );
  891. ai_assert( count_vertices );
  892. // mapping from output indices to DOM indexing, needed to resolve weights
  893. std::vector<unsigned int> reverseMapping;
  894. if ( process_weights ) {
  895. reverseMapping.resize( count_vertices );
  896. }
  897. // allocate output data arrays, but don't fill them yet
  898. out_mesh->mNumVertices = count_vertices;
  899. out_mesh->mVertices = new aiVector3D[ count_vertices ];
  900. out_mesh->mNumFaces = count_faces;
  901. aiFace* fac = out_mesh->mFaces = new aiFace[ count_faces ]();
  902. // allocate normals
  903. const std::vector<aiVector3D>& normals = mesh.GetNormals();
  904. if ( normals.size() ) {
  905. ai_assert( normals.size() == vertices.size() );
  906. out_mesh->mNormals = new aiVector3D[ vertices.size() ];
  907. }
  908. // allocate tangents, binormals.
  909. const std::vector<aiVector3D>& tangents = mesh.GetTangents();
  910. const std::vector<aiVector3D>* binormals = &mesh.GetBinormals();
  911. std::vector<aiVector3D> tempBinormals;
  912. if ( tangents.size() ) {
  913. if ( !binormals->size() ) {
  914. if ( normals.size() ) {
  915. // XXX this computes the binormals for the entire mesh, not only
  916. // the part for which we need them.
  917. tempBinormals.resize( normals.size() );
  918. for ( unsigned int i = 0; i < tangents.size(); ++i ) {
  919. tempBinormals[ i ] = normals[ i ] ^ tangents[ i ];
  920. }
  921. binormals = &tempBinormals;
  922. }
  923. else {
  924. binormals = NULL;
  925. }
  926. }
  927. if ( binormals ) {
  928. ai_assert( tangents.size() == vertices.size() && binormals->size() == vertices.size() );
  929. out_mesh->mTangents = new aiVector3D[ vertices.size() ];
  930. out_mesh->mBitangents = new aiVector3D[ vertices.size() ];
  931. }
  932. }
  933. // allocate texture coords
  934. unsigned int num_uvs = 0;
  935. for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i, ++num_uvs ) {
  936. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords( i );
  937. if ( uvs.empty() ) {
  938. break;
  939. }
  940. out_mesh->mTextureCoords[ i ] = new aiVector3D[ vertices.size() ];
  941. out_mesh->mNumUVComponents[ i ] = 2;
  942. }
  943. // allocate vertex colors
  944. unsigned int num_vcs = 0;
  945. for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i, ++num_vcs ) {
  946. const std::vector<aiColor4D>& colors = mesh.GetVertexColors( i );
  947. if ( colors.empty() ) {
  948. break;
  949. }
  950. out_mesh->mColors[ i ] = new aiColor4D[ vertices.size() ];
  951. }
  952. unsigned int cursor = 0, in_cursor = 0;
  953. itf = faces.begin();
  954. for ( MatIndexArray::const_iterator it = mindices.begin(),
  955. end = mindices.end(); it != end; ++it, ++itf )
  956. {
  957. const unsigned int pcount = *itf;
  958. if ( ( *it ) != index ) {
  959. in_cursor += pcount;
  960. continue;
  961. }
  962. aiFace& f = *fac++;
  963. f.mNumIndices = pcount;
  964. f.mIndices = new unsigned int[ pcount ];
  965. switch ( pcount )
  966. {
  967. case 1:
  968. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  969. break;
  970. case 2:
  971. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  972. break;
  973. case 3:
  974. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  975. break;
  976. default:
  977. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  978. break;
  979. }
  980. for ( unsigned int i = 0; i < pcount; ++i, ++cursor, ++in_cursor ) {
  981. f.mIndices[ i ] = cursor;
  982. if ( reverseMapping.size() ) {
  983. reverseMapping[ cursor ] = in_cursor;
  984. }
  985. out_mesh->mVertices[ cursor ] = vertices[ in_cursor ];
  986. if ( out_mesh->mNormals ) {
  987. out_mesh->mNormals[ cursor ] = normals[ in_cursor ];
  988. }
  989. if ( out_mesh->mTangents ) {
  990. out_mesh->mTangents[ cursor ] = tangents[ in_cursor ];
  991. out_mesh->mBitangents[ cursor ] = ( *binormals )[ in_cursor ];
  992. }
  993. for ( unsigned int j = 0; j < num_uvs; ++j ) {
  994. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords( j );
  995. out_mesh->mTextureCoords[ j ][ cursor ] = aiVector3D( uvs[ in_cursor ].x, uvs[ in_cursor ].y, 0.0f );
  996. }
  997. for ( unsigned int j = 0; j < num_vcs; ++j ) {
  998. const std::vector<aiColor4D>& cols = mesh.GetVertexColors( j );
  999. out_mesh->mColors[ j ][ cursor ] = cols[ in_cursor ];
  1000. }
  1001. }
  1002. }
  1003. ConvertMaterialForMesh( out_mesh, model, mesh, index );
  1004. if ( process_weights ) {
  1005. ConvertWeights( out_mesh, model, mesh, node_global_transform, index, &reverseMapping );
  1006. }
  1007. return static_cast<unsigned int>( meshes.size() - 1 );
  1008. }
  1009. void Converter::ConvertWeights( aiMesh* out, const Model& model, const MeshGeometry& geo,
  1010. const aiMatrix4x4& node_global_transform ,
  1011. unsigned int materialIndex,
  1012. std::vector<unsigned int>* outputVertStartIndices )
  1013. {
  1014. ai_assert( geo.DeformerSkin() );
  1015. std::vector<size_t> out_indices;
  1016. std::vector<size_t> index_out_indices;
  1017. std::vector<size_t> count_out_indices;
  1018. const Skin& sk = *geo.DeformerSkin();
  1019. std::vector<aiBone*> bones;
  1020. bones.reserve( sk.Clusters().size() );
  1021. const bool no_mat_check = materialIndex == NO_MATERIAL_SEPARATION;
  1022. ai_assert( no_mat_check || outputVertStartIndices );
  1023. try {
  1024. for( const Cluster* cluster : sk.Clusters() ) {
  1025. ai_assert( cluster );
  1026. const WeightIndexArray& indices = cluster->GetIndices();
  1027. if ( indices.empty() ) {
  1028. continue;
  1029. }
  1030. const MatIndexArray& mats = geo.GetMaterialIndices();
  1031. bool ok = false;
  1032. const size_t no_index_sentinel = std::numeric_limits<size_t>::max();
  1033. count_out_indices.clear();
  1034. index_out_indices.clear();
  1035. out_indices.clear();
  1036. // now check if *any* of these weights is contained in the output mesh,
  1037. // taking notes so we don't need to do it twice.
  1038. for( WeightIndexArray::value_type index : indices ) {
  1039. unsigned int count = 0;
  1040. const unsigned int* const out_idx = geo.ToOutputVertexIndex( index, count );
  1041. // ToOutputVertexIndex only returns NULL if index is out of bounds
  1042. // which should never happen
  1043. ai_assert( out_idx != NULL );
  1044. index_out_indices.push_back( no_index_sentinel );
  1045. count_out_indices.push_back( 0 );
  1046. for ( unsigned int i = 0; i < count; ++i ) {
  1047. if ( no_mat_check || static_cast<size_t>( mats[ geo.FaceForVertexIndex( out_idx[ i ] ) ] ) == materialIndex ) {
  1048. if ( index_out_indices.back() == no_index_sentinel ) {
  1049. index_out_indices.back() = out_indices.size();
  1050. }
  1051. if ( no_mat_check ) {
  1052. out_indices.push_back( out_idx[ i ] );
  1053. }
  1054. else {
  1055. // this extra lookup is in O(logn), so the entire algorithm becomes O(nlogn)
  1056. const std::vector<unsigned int>::iterator it = std::lower_bound(
  1057. outputVertStartIndices->begin(),
  1058. outputVertStartIndices->end(),
  1059. out_idx[ i ]
  1060. );
  1061. out_indices.push_back( std::distance( outputVertStartIndices->begin(), it ) );
  1062. }
  1063. ++count_out_indices.back();
  1064. ok = true;
  1065. }
  1066. }
  1067. }
  1068. // if we found at least one, generate the output bones
  1069. // XXX this could be heavily simplified by collecting the bone
  1070. // data in a single step.
  1071. if ( ok ) {
  1072. ConvertCluster( bones, model, *cluster, out_indices, index_out_indices,
  1073. count_out_indices, node_global_transform );
  1074. }
  1075. }
  1076. }
  1077. catch ( std::exception& ) {
  1078. std::for_each( bones.begin(), bones.end(), Util::delete_fun<aiBone>() );
  1079. throw;
  1080. }
  1081. if ( bones.empty() ) {
  1082. return;
  1083. }
  1084. out->mBones = new aiBone*[ bones.size() ]();
  1085. out->mNumBones = static_cast<unsigned int>( bones.size() );
  1086. std::swap_ranges( bones.begin(), bones.end(), out->mBones );
  1087. }
  1088. void Converter::ConvertCluster( std::vector<aiBone*>& bones, const Model& /*model*/, const Cluster& cl,
  1089. std::vector<size_t>& out_indices,
  1090. std::vector<size_t>& index_out_indices,
  1091. std::vector<size_t>& count_out_indices,
  1092. const aiMatrix4x4& node_global_transform )
  1093. {
  1094. aiBone* const bone = new aiBone();
  1095. bones.push_back( bone );
  1096. bone->mName = FixNodeName( cl.TargetNode()->Name() );
  1097. bone->mOffsetMatrix = cl.TransformLink();
  1098. bone->mOffsetMatrix.Inverse();
  1099. bone->mOffsetMatrix = bone->mOffsetMatrix * node_global_transform;
  1100. bone->mNumWeights = static_cast<unsigned int>( out_indices.size() );
  1101. aiVertexWeight* cursor = bone->mWeights = new aiVertexWeight[ out_indices.size() ];
  1102. const size_t no_index_sentinel = std::numeric_limits<size_t>::max();
  1103. const WeightArray& weights = cl.GetWeights();
  1104. const size_t c = index_out_indices.size();
  1105. for ( size_t i = 0; i < c; ++i ) {
  1106. const size_t index_index = index_out_indices[ i ];
  1107. if ( index_index == no_index_sentinel ) {
  1108. continue;
  1109. }
  1110. const size_t cc = count_out_indices[ i ];
  1111. for ( size_t j = 0; j < cc; ++j ) {
  1112. aiVertexWeight& out_weight = *cursor++;
  1113. out_weight.mVertexId = static_cast<unsigned int>( out_indices[ index_index + j ] );
  1114. out_weight.mWeight = weights[ i ];
  1115. }
  1116. }
  1117. }
  1118. void Converter::ConvertMaterialForMesh( aiMesh* out, const Model& model, const MeshGeometry& geo,
  1119. MatIndexArray::value_type materialIndex )
  1120. {
  1121. // locate source materials for this mesh
  1122. const std::vector<const Material*>& mats = model.GetMaterials();
  1123. if ( static_cast<unsigned int>( materialIndex ) >= mats.size() || materialIndex < 0 ) {
  1124. FBXImporter::LogError( "material index out of bounds, setting default material" );
  1125. out->mMaterialIndex = GetDefaultMaterial();
  1126. return;
  1127. }
  1128. const Material* const mat = mats[ materialIndex ];
  1129. MaterialMap::const_iterator it = materials_converted.find( mat );
  1130. if ( it != materials_converted.end() ) {
  1131. out->mMaterialIndex = ( *it ).second;
  1132. return;
  1133. }
  1134. out->mMaterialIndex = ConvertMaterial( *mat, &geo );
  1135. materials_converted[ mat ] = out->mMaterialIndex;
  1136. }
  1137. unsigned int Converter::GetDefaultMaterial()
  1138. {
  1139. if ( defaultMaterialIndex ) {
  1140. return defaultMaterialIndex - 1;
  1141. }
  1142. aiMaterial* out_mat = new aiMaterial();
  1143. materials.push_back( out_mat );
  1144. const aiColor3D diffuse = aiColor3D( 0.8f, 0.8f, 0.8f );
  1145. out_mat->AddProperty( &diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
  1146. aiString s;
  1147. s.Set( AI_DEFAULT_MATERIAL_NAME );
  1148. out_mat->AddProperty( &s, AI_MATKEY_NAME );
  1149. defaultMaterialIndex = static_cast< unsigned int >( materials.size() );
  1150. return defaultMaterialIndex - 1;
  1151. }
  1152. unsigned int Converter::ConvertMaterial( const Material& material, const MeshGeometry* const mesh )
  1153. {
  1154. const PropertyTable& props = material.Props();
  1155. // generate empty output material
  1156. aiMaterial* out_mat = new aiMaterial();
  1157. materials_converted[ &material ] = static_cast<unsigned int>( materials.size() );
  1158. materials.push_back( out_mat );
  1159. aiString str;
  1160. // strip Material:: prefix
  1161. std::string name = material.Name();
  1162. if ( name.substr( 0, 10 ) == "Material::" ) {
  1163. name = name.substr( 10 );
  1164. }
  1165. // set material name if not empty - this could happen
  1166. // and there should be no key for it in this case.
  1167. if ( name.length() ) {
  1168. str.Set( name );
  1169. out_mat->AddProperty( &str, AI_MATKEY_NAME );
  1170. }
  1171. // shading stuff and colors
  1172. SetShadingPropertiesCommon( out_mat, props );
  1173. // texture assignments
  1174. SetTextureProperties( out_mat, material.Textures(), mesh );
  1175. SetTextureProperties( out_mat, material.LayeredTextures(), mesh );
  1176. return static_cast<unsigned int>( materials.size() - 1 );
  1177. }
  1178. unsigned int Converter::ConvertVideo( const Video& video )
  1179. {
  1180. // generate empty output texture
  1181. aiTexture* out_tex = new aiTexture();
  1182. textures.push_back( out_tex );
  1183. // assuming the texture is compressed
  1184. out_tex->mWidth = static_cast<unsigned int>( video.ContentLength() ); // total data size
  1185. out_tex->mHeight = 0; // fixed to 0
  1186. // steal the data from the Video to avoid an additional copy
  1187. out_tex->pcData = reinterpret_cast<aiTexel*>( const_cast<Video&>( video ).RelinquishContent() );
  1188. // try to extract a hint from the file extension
  1189. const std::string& filename = video.FileName().empty() ? video.RelativeFilename() : video.FileName();
  1190. std::string ext = BaseImporter::GetExtension( filename );
  1191. if ( ext == "jpeg" ) {
  1192. ext = "jpg";
  1193. }
  1194. if ( ext.size() <= 3 ) {
  1195. memcpy( out_tex->achFormatHint, ext.c_str(), ext.size() );
  1196. }
  1197. out_tex->mFilename.Set(video.FileName().c_str());
  1198. return static_cast<unsigned int>( textures.size() - 1 );
  1199. }
  1200. void Converter::TrySetTextureProperties( aiMaterial* out_mat, const TextureMap& textures,
  1201. const std::string& propName,
  1202. aiTextureType target, const MeshGeometry* const mesh )
  1203. {
  1204. TextureMap::const_iterator it = textures.find( propName );
  1205. if ( it == textures.end() ) {
  1206. return;
  1207. }
  1208. const Texture* const tex = ( *it ).second;
  1209. if ( tex != 0 )
  1210. {
  1211. aiString path;
  1212. path.Set( tex->RelativeFilename() );
  1213. const Video* media = tex->Media();
  1214. if (media != 0) {
  1215. bool textureReady = false; //tells if our texture is ready (if it was loaded or if it was found)
  1216. unsigned int index;
  1217. VideoMap::const_iterator it = textures_converted.find(media);
  1218. if (it != textures_converted.end()) {
  1219. index = (*it).second;
  1220. textureReady = true;
  1221. }
  1222. else {
  1223. if (media->ContentLength() > 0) {
  1224. index = ConvertVideo(*media);
  1225. textures_converted[media] = index;
  1226. textureReady = true;
  1227. }
  1228. }
  1229. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture), if the texture is ready
  1230. if (doc.Settings().useLegacyEmbeddedTextureNaming) {
  1231. if (textureReady) {
  1232. // TODO: check the possibility of using the flag "AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING"
  1233. // In FBX files textures are now stored internally by Assimp with their filename included
  1234. // Now Assimp can lookup thru the loaded textures after all data is processed
  1235. // We need to load all textures before referencing them, as FBX file format order may reference a texture before loading it
  1236. // This may occur on this case too, it has to be studied
  1237. path.data[0] = '*';
  1238. path.length = 1 + ASSIMP_itoa10(path.data + 1, MAXLEN - 1, index);
  1239. }
  1240. }
  1241. }
  1242. out_mat->AddProperty( &path, _AI_MATKEY_TEXTURE_BASE, target, 0 );
  1243. aiUVTransform uvTrafo;
  1244. // XXX handle all kinds of UV transformations
  1245. uvTrafo.mScaling = tex->UVScaling();
  1246. uvTrafo.mTranslation = tex->UVTranslation();
  1247. out_mat->AddProperty( &uvTrafo, 1, _AI_MATKEY_UVTRANSFORM_BASE, target, 0 );
  1248. const PropertyTable& props = tex->Props();
  1249. int uvIndex = 0;
  1250. bool ok;
  1251. const std::string& uvSet = PropertyGet<std::string>( props, "UVSet", ok );
  1252. if ( ok ) {
  1253. // "default" is the name which usually appears in the FbxFileTexture template
  1254. if ( uvSet != "default" && uvSet.length() ) {
  1255. // this is a bit awkward - we need to find a mesh that uses this
  1256. // material and scan its UV channels for the given UV name because
  1257. // assimp references UV channels by index, not by name.
  1258. // XXX: the case that UV channels may appear in different orders
  1259. // in meshes is unhandled. A possible solution would be to sort
  1260. // the UV channels alphabetically, but this would have the side
  1261. // effect that the primary (first) UV channel would sometimes
  1262. // be moved, causing trouble when users read only the first
  1263. // UV channel and ignore UV channel assignments altogether.
  1264. const unsigned int matIndex = static_cast<unsigned int>( std::distance( materials.begin(),
  1265. std::find( materials.begin(), materials.end(), out_mat )
  1266. ) );
  1267. uvIndex = -1;
  1268. if ( !mesh )
  1269. {
  1270. for( const MeshMap::value_type& v : meshes_converted ) {
  1271. const MeshGeometry* const mesh = dynamic_cast<const MeshGeometry*> ( v.first );
  1272. if ( !mesh ) {
  1273. continue;
  1274. }
  1275. const MatIndexArray& mats = mesh->GetMaterialIndices();
  1276. if ( std::find( mats.begin(), mats.end(), matIndex ) == mats.end() ) {
  1277. continue;
  1278. }
  1279. int index = -1;
  1280. for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i ) {
  1281. if ( mesh->GetTextureCoords( i ).empty() ) {
  1282. break;
  1283. }
  1284. const std::string& name = mesh->GetTextureCoordChannelName( i );
  1285. if ( name == uvSet ) {
  1286. index = static_cast<int>( i );
  1287. break;
  1288. }
  1289. }
  1290. if ( index == -1 ) {
  1291. FBXImporter::LogWarn( "did not find UV channel named " + uvSet + " in a mesh using this material" );
  1292. continue;
  1293. }
  1294. if ( uvIndex == -1 ) {
  1295. uvIndex = index;
  1296. }
  1297. else {
  1298. FBXImporter::LogWarn( "the UV channel named " + uvSet +
  1299. " appears at different positions in meshes, results will be wrong" );
  1300. }
  1301. }
  1302. }
  1303. else
  1304. {
  1305. int index = -1;
  1306. for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i ) {
  1307. if ( mesh->GetTextureCoords( i ).empty() ) {
  1308. break;
  1309. }
  1310. const std::string& name = mesh->GetTextureCoordChannelName( i );
  1311. if ( name == uvSet ) {
  1312. index = static_cast<int>( i );
  1313. break;
  1314. }
  1315. }
  1316. if ( index == -1 ) {
  1317. FBXImporter::LogWarn( "did not find UV channel named " + uvSet + " in a mesh using this material" );
  1318. }
  1319. if ( uvIndex == -1 ) {
  1320. uvIndex = index;
  1321. }
  1322. }
  1323. if ( uvIndex == -1 ) {
  1324. FBXImporter::LogWarn( "failed to resolve UV channel " + uvSet + ", using first UV channel" );
  1325. uvIndex = 0;
  1326. }
  1327. }
  1328. }
  1329. out_mat->AddProperty( &uvIndex, 1, _AI_MATKEY_UVWSRC_BASE, target, 0 );
  1330. }
  1331. }
  1332. void Converter::TrySetTextureProperties( aiMaterial* out_mat, const LayeredTextureMap& layeredTextures,
  1333. const std::string& propName,
  1334. aiTextureType target, const MeshGeometry* const mesh )
  1335. {
  1336. LayeredTextureMap::const_iterator it = layeredTextures.find( propName );
  1337. if ( it == layeredTextures.end() ) {
  1338. return;
  1339. }
  1340. int texCount = (*it).second->textureCount();
  1341. // Set the blend mode for layered textures
  1342. int blendmode= (*it).second->GetBlendMode();
  1343. out_mat->AddProperty(&blendmode,1,_AI_MATKEY_TEXOP_BASE,target,0);
  1344. for(int texIndex = 0; texIndex < texCount; texIndex++){
  1345. const Texture* const tex = ( *it ).second->getTexture(texIndex);
  1346. aiString path;
  1347. path.Set( tex->RelativeFilename() );
  1348. out_mat->AddProperty( &path, _AI_MATKEY_TEXTURE_BASE, target, texIndex );
  1349. aiUVTransform uvTrafo;
  1350. // XXX handle all kinds of UV transformations
  1351. uvTrafo.mScaling = tex->UVScaling();
  1352. uvTrafo.mTranslation = tex->UVTranslation();
  1353. out_mat->AddProperty( &uvTrafo, 1, _AI_MATKEY_UVTRANSFORM_BASE, target, texIndex );
  1354. const PropertyTable& props = tex->Props();
  1355. int uvIndex = 0;
  1356. bool ok;
  1357. const std::string& uvSet = PropertyGet<std::string>( props, "UVSet", ok );
  1358. if ( ok ) {
  1359. // "default" is the name which usually appears in the FbxFileTexture template
  1360. if ( uvSet != "default" && uvSet.length() ) {
  1361. // this is a bit awkward - we need to find a mesh that uses this
  1362. // material and scan its UV channels for the given UV name because
  1363. // assimp references UV channels by index, not by name.
  1364. // XXX: the case that UV channels may appear in different orders
  1365. // in meshes is unhandled. A possible solution would be to sort
  1366. // the UV channels alphabetically, but this would have the side
  1367. // effect that the primary (first) UV channel would sometimes
  1368. // be moved, causing trouble when users read only the first
  1369. // UV channel and ignore UV channel assignments altogether.
  1370. const unsigned int matIndex = static_cast<unsigned int>( std::distance( materials.begin(),
  1371. std::find( materials.begin(), materials.end(), out_mat )
  1372. ) );
  1373. uvIndex = -1;
  1374. if ( !mesh )
  1375. {
  1376. for( const MeshMap::value_type& v : meshes_converted ) {
  1377. const MeshGeometry* const mesh = dynamic_cast<const MeshGeometry*> ( v.first );
  1378. if ( !mesh ) {
  1379. continue;
  1380. }
  1381. const MatIndexArray& mats = mesh->GetMaterialIndices();
  1382. if ( std::find( mats.begin(), mats.end(), matIndex ) == mats.end() ) {
  1383. continue;
  1384. }
  1385. int index = -1;
  1386. for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i ) {
  1387. if ( mesh->GetTextureCoords( i ).empty() ) {
  1388. break;
  1389. }
  1390. const std::string& name = mesh->GetTextureCoordChannelName( i );
  1391. if ( name == uvSet ) {
  1392. index = static_cast<int>( i );
  1393. break;
  1394. }
  1395. }
  1396. if ( index == -1 ) {
  1397. FBXImporter::LogWarn( "did not find UV channel named " + uvSet + " in a mesh using this material" );
  1398. continue;
  1399. }
  1400. if ( uvIndex == -1 ) {
  1401. uvIndex = index;
  1402. }
  1403. else {
  1404. FBXImporter::LogWarn( "the UV channel named " + uvSet +
  1405. " appears at different positions in meshes, results will be wrong" );
  1406. }
  1407. }
  1408. }
  1409. else
  1410. {
  1411. int index = -1;
  1412. for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i ) {
  1413. if ( mesh->GetTextureCoords( i ).empty() ) {
  1414. break;
  1415. }
  1416. const std::string& name = mesh->GetTextureCoordChannelName( i );
  1417. if ( name == uvSet ) {
  1418. index = static_cast<int>( i );
  1419. break;
  1420. }
  1421. }
  1422. if ( index == -1 ) {
  1423. FBXImporter::LogWarn( "did not find UV channel named " + uvSet + " in a mesh using this material" );
  1424. }
  1425. if ( uvIndex == -1 ) {
  1426. uvIndex = index;
  1427. }
  1428. }
  1429. if ( uvIndex == -1 ) {
  1430. FBXImporter::LogWarn( "failed to resolve UV channel " + uvSet + ", using first UV channel" );
  1431. uvIndex = 0;
  1432. }
  1433. }
  1434. }
  1435. out_mat->AddProperty( &uvIndex, 1, _AI_MATKEY_UVWSRC_BASE, target, texIndex );
  1436. }
  1437. }
  1438. void Converter::SetTextureProperties( aiMaterial* out_mat, const TextureMap& textures, const MeshGeometry* const mesh )
  1439. {
  1440. TrySetTextureProperties( out_mat, textures, "DiffuseColor", aiTextureType_DIFFUSE, mesh );
  1441. TrySetTextureProperties( out_mat, textures, "AmbientColor", aiTextureType_AMBIENT, mesh );
  1442. TrySetTextureProperties( out_mat, textures, "EmissiveColor", aiTextureType_EMISSIVE, mesh );
  1443. TrySetTextureProperties( out_mat, textures, "SpecularColor", aiTextureType_SPECULAR, mesh );
  1444. TrySetTextureProperties( out_mat, textures, "SpecularFactor", aiTextureType_SPECULAR, mesh);
  1445. TrySetTextureProperties( out_mat, textures, "TransparentColor", aiTextureType_OPACITY, mesh );
  1446. TrySetTextureProperties( out_mat, textures, "ReflectionColor", aiTextureType_REFLECTION, mesh );
  1447. TrySetTextureProperties( out_mat, textures, "DisplacementColor", aiTextureType_DISPLACEMENT, mesh );
  1448. TrySetTextureProperties( out_mat, textures, "NormalMap", aiTextureType_NORMALS, mesh );
  1449. TrySetTextureProperties( out_mat, textures, "Bump", aiTextureType_HEIGHT, mesh );
  1450. TrySetTextureProperties( out_mat, textures, "ShininessExponent", aiTextureType_SHININESS, mesh );
  1451. }
  1452. void Converter::SetTextureProperties( aiMaterial* out_mat, const LayeredTextureMap& layeredTextures, const MeshGeometry* const mesh )
  1453. {
  1454. TrySetTextureProperties( out_mat, layeredTextures, "DiffuseColor", aiTextureType_DIFFUSE, mesh );
  1455. TrySetTextureProperties( out_mat, layeredTextures, "AmbientColor", aiTextureType_AMBIENT, mesh );
  1456. TrySetTextureProperties( out_mat, layeredTextures, "EmissiveColor", aiTextureType_EMISSIVE, mesh );
  1457. TrySetTextureProperties( out_mat, layeredTextures, "SpecularColor", aiTextureType_SPECULAR, mesh );
  1458. TrySetTextureProperties( out_mat, layeredTextures, "SpecularFactor", aiTextureType_SPECULAR, mesh);
  1459. TrySetTextureProperties( out_mat, layeredTextures, "TransparentColor", aiTextureType_OPACITY, mesh );
  1460. TrySetTextureProperties( out_mat, layeredTextures, "ReflectionColor", aiTextureType_REFLECTION, mesh );
  1461. TrySetTextureProperties( out_mat, layeredTextures, "DisplacementColor", aiTextureType_DISPLACEMENT, mesh );
  1462. TrySetTextureProperties( out_mat, layeredTextures, "NormalMap", aiTextureType_NORMALS, mesh );
  1463. TrySetTextureProperties( out_mat, layeredTextures, "Bump", aiTextureType_HEIGHT, mesh );
  1464. TrySetTextureProperties( out_mat, layeredTextures, "ShininessExponent", aiTextureType_SHININESS, mesh );
  1465. }
  1466. aiColor3D Converter::GetColorPropertyFactored( const PropertyTable& props, const std::string& colorName,
  1467. const std::string& factorName, bool& result, bool useTemplate )
  1468. {
  1469. result = true;
  1470. bool ok;
  1471. aiVector3D BaseColor = PropertyGet<aiVector3D>( props, colorName, ok, useTemplate );
  1472. if ( ! ok ) {
  1473. result = false;
  1474. return aiColor3D( 0.0f, 0.0f, 0.0f );
  1475. }
  1476. // if no factor name, return the colour as is
  1477. if ( factorName.empty() ) {
  1478. return aiColor3D( BaseColor.x, BaseColor.y, BaseColor.z );
  1479. }
  1480. // otherwise it should be multiplied by the factor, if found.
  1481. float factor = PropertyGet<float>( props, factorName, ok, useTemplate );
  1482. if ( ok ) {
  1483. BaseColor *= factor;
  1484. }
  1485. return aiColor3D( BaseColor.x, BaseColor.y, BaseColor.z );
  1486. }
  1487. aiColor3D Converter::GetColorPropertyFromMaterial( const PropertyTable& props, const std::string& baseName,
  1488. bool& result )
  1489. {
  1490. return GetColorPropertyFactored( props, baseName + "Color", baseName + "Factor", result, true );
  1491. }
  1492. aiColor3D Converter::GetColorProperty( const PropertyTable& props, const std::string& colorName,
  1493. bool& result, bool useTemplate )
  1494. {
  1495. result = true;
  1496. bool ok;
  1497. const aiVector3D& ColorVec = PropertyGet<aiVector3D>( props, colorName, ok, useTemplate );
  1498. if ( ! ok ) {
  1499. result = false;
  1500. return aiColor3D( 0.0f, 0.0f, 0.0f );
  1501. }
  1502. return aiColor3D( ColorVec.x, ColorVec.y, ColorVec.z );
  1503. }
  1504. void Converter::SetShadingPropertiesCommon( aiMaterial* out_mat, const PropertyTable& props )
  1505. {
  1506. // Set shading properties.
  1507. // Modern FBX Files have two separate systems for defining these,
  1508. // with only the more comprehensive one described in the property template.
  1509. // Likely the other values are a legacy system,
  1510. // which is still always exported by the official FBX SDK.
  1511. //
  1512. // Blender's FBX import and export mostly ignore this legacy system,
  1513. // and as we only support recent versions of FBX anyway, we can do the same.
  1514. bool ok;
  1515. const aiColor3D& Diffuse = GetColorPropertyFromMaterial( props, "Diffuse", ok );
  1516. if ( ok ) {
  1517. out_mat->AddProperty( &Diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
  1518. }
  1519. const aiColor3D& Emissive = GetColorPropertyFromMaterial( props, "Emissive", ok );
  1520. if ( ok ) {
  1521. out_mat->AddProperty( &Emissive, 1, AI_MATKEY_COLOR_EMISSIVE );
  1522. }
  1523. const aiColor3D& Ambient = GetColorPropertyFromMaterial( props, "Ambient", ok );
  1524. if ( ok ) {
  1525. out_mat->AddProperty( &Ambient, 1, AI_MATKEY_COLOR_AMBIENT );
  1526. }
  1527. // we store specular factor as SHININESS_STRENGTH, so just get the color
  1528. const aiColor3D& Specular = GetColorProperty( props, "SpecularColor", ok, true );
  1529. if ( ok ) {
  1530. out_mat->AddProperty( &Specular, 1, AI_MATKEY_COLOR_SPECULAR );
  1531. }
  1532. // and also try to get SHININESS_STRENGTH
  1533. const float SpecularFactor = PropertyGet<float>( props, "SpecularFactor", ok, true );
  1534. if ( ok ) {
  1535. out_mat->AddProperty( &SpecularFactor, 1, AI_MATKEY_SHININESS_STRENGTH );
  1536. }
  1537. // and the specular exponent
  1538. const float ShininessExponent = PropertyGet<float>( props, "ShininessExponent", ok );
  1539. if ( ok ) {
  1540. out_mat->AddProperty( &ShininessExponent, 1, AI_MATKEY_SHININESS );
  1541. }
  1542. // TransparentColor / TransparencyFactor... gee thanks FBX :rolleyes:
  1543. const aiColor3D& Transparent = GetColorPropertyFactored( props, "TransparentColor", "TransparencyFactor", ok );
  1544. float CalculatedOpacity = 1.0;
  1545. if ( ok ) {
  1546. out_mat->AddProperty( &Transparent, 1, AI_MATKEY_COLOR_TRANSPARENT );
  1547. // as calculated by FBX SDK 2017:
  1548. CalculatedOpacity = 1.0 - ((Transparent.r + Transparent.g + Transparent.b) / 3.0);
  1549. }
  1550. // use of TransparencyFactor is inconsistent.
  1551. // Maya always stores it as 1.0,
  1552. // so we can't use it to set AI_MATKEY_OPACITY.
  1553. // Blender is more sensible and stores it as the alpha value.
  1554. // However both the FBX SDK and Blender always write an additional
  1555. // legacy "Opacity" field, so we can try to use that.
  1556. //
  1557. // If we can't find it,
  1558. // we can fall back to the value which the FBX SDK calculates
  1559. // from transparency colour (RGB) and factor (F) as
  1560. // 1.0 - F*((R+G+B)/3).
  1561. //
  1562. // There's no consistent way to interpret this opacity value,
  1563. // so it's up to clients to do the correct thing.
  1564. const float Opacity = PropertyGet<float>( props, "Opacity", ok );
  1565. if ( ok ) {
  1566. out_mat->AddProperty( &Opacity, 1, AI_MATKEY_OPACITY );
  1567. }
  1568. else if ( CalculatedOpacity != 1.0 ) {
  1569. out_mat->AddProperty( &CalculatedOpacity, 1, AI_MATKEY_OPACITY );
  1570. }
  1571. // reflection color and factor are stored separately
  1572. const aiColor3D& Reflection = GetColorProperty( props, "ReflectionColor", ok, true );
  1573. if ( ok ) {
  1574. out_mat->AddProperty( &Reflection, 1, AI_MATKEY_COLOR_REFLECTIVE );
  1575. }
  1576. float ReflectionFactor = PropertyGet<float>( props, "ReflectionFactor", ok, true );
  1577. if ( ok ) {
  1578. out_mat->AddProperty( &ReflectionFactor, 1, AI_MATKEY_REFLECTIVITY );
  1579. }
  1580. const float BumpFactor = PropertyGet<float>(props, "BumpFactor", ok);
  1581. if (ok) {
  1582. out_mat->AddProperty(&BumpFactor, 1, AI_MATKEY_BUMPSCALING);
  1583. }
  1584. const float DispFactor = PropertyGet<float>(props, "DisplacementFactor", ok);
  1585. if (ok) {
  1586. out_mat->AddProperty(&DispFactor, 1, "$mat.displacementscaling", 0, 0);
  1587. }
  1588. }
  1589. double Converter::FrameRateToDouble( FileGlobalSettings::FrameRate fp, double customFPSVal )
  1590. {
  1591. switch ( fp ) {
  1592. case FileGlobalSettings::FrameRate_DEFAULT:
  1593. return 1.0;
  1594. case FileGlobalSettings::FrameRate_120:
  1595. return 120.0;
  1596. case FileGlobalSettings::FrameRate_100:
  1597. return 100.0;
  1598. case FileGlobalSettings::FrameRate_60:
  1599. return 60.0;
  1600. case FileGlobalSettings::FrameRate_50:
  1601. return 50.0;
  1602. case FileGlobalSettings::FrameRate_48:
  1603. return 48.0;
  1604. case FileGlobalSettings::FrameRate_30:
  1605. case FileGlobalSettings::FrameRate_30_DROP:
  1606. return 30.0;
  1607. case FileGlobalSettings::FrameRate_NTSC_DROP_FRAME:
  1608. case FileGlobalSettings::FrameRate_NTSC_FULL_FRAME:
  1609. return 29.9700262;
  1610. case FileGlobalSettings::FrameRate_PAL:
  1611. return 25.0;
  1612. case FileGlobalSettings::FrameRate_CINEMA:
  1613. return 24.0;
  1614. case FileGlobalSettings::FrameRate_1000:
  1615. return 1000.0;
  1616. case FileGlobalSettings::FrameRate_CINEMA_ND:
  1617. return 23.976;
  1618. case FileGlobalSettings::FrameRate_CUSTOM:
  1619. return customFPSVal;
  1620. case FileGlobalSettings::FrameRate_MAX: // this is to silence compiler warnings
  1621. break;
  1622. }
  1623. ai_assert( false );
  1624. return -1.0f;
  1625. }
  1626. void Converter::ConvertAnimations()
  1627. {
  1628. // first of all determine framerate
  1629. const FileGlobalSettings::FrameRate fps = doc.GlobalSettings().TimeMode();
  1630. const float custom = doc.GlobalSettings().CustomFrameRate();
  1631. anim_fps = FrameRateToDouble( fps, custom );
  1632. const std::vector<const AnimationStack*>& animations = doc.AnimationStacks();
  1633. for( const AnimationStack* stack : animations ) {
  1634. ConvertAnimationStack( *stack );
  1635. }
  1636. }
  1637. void Converter::RenameNode( const std::string& fixed_name, const std::string& new_name ) {
  1638. if ( node_names.find( fixed_name ) == node_names.end() ) {
  1639. FBXImporter::LogError( "Cannot rename node " + fixed_name + ", not existing.");
  1640. return;
  1641. }
  1642. if ( node_names.find( new_name ) != node_names.end() ) {
  1643. FBXImporter::LogError( "Cannot rename node " + fixed_name + " to " + new_name +", name already existing." );
  1644. return;
  1645. }
  1646. ai_assert( node_names.find( fixed_name ) != node_names.end() );
  1647. ai_assert( node_names.find( new_name ) == node_names.end() );
  1648. renamed_nodes[ fixed_name ] = new_name;
  1649. const aiString fn( fixed_name );
  1650. for( aiCamera* cam : cameras ) {
  1651. if ( cam->mName == fn ) {
  1652. cam->mName.Set( new_name );
  1653. break;
  1654. }
  1655. }
  1656. for( aiLight* light : lights ) {
  1657. if ( light->mName == fn ) {
  1658. light->mName.Set( new_name );
  1659. break;
  1660. }
  1661. }
  1662. for( aiAnimation* anim : animations ) {
  1663. for ( unsigned int i = 0; i < anim->mNumChannels; ++i ) {
  1664. aiNodeAnim* const na = anim->mChannels[ i ];
  1665. if ( na->mNodeName == fn ) {
  1666. na->mNodeName.Set( new_name );
  1667. break;
  1668. }
  1669. }
  1670. }
  1671. }
  1672. std::string Converter::FixNodeName( const std::string& name )
  1673. {
  1674. // strip Model:: prefix, avoiding ambiguities (i.e. don't strip if
  1675. // this causes ambiguities, well possible between empty identifiers,
  1676. // such as "Model::" and ""). Make sure the behaviour is consistent
  1677. // across multiple calls to FixNodeName().
  1678. if ( name.substr( 0, 7 ) == "Model::" ) {
  1679. std::string temp = name.substr( 7 );
  1680. const NodeNameMap::const_iterator it = node_names.find( temp );
  1681. if ( it != node_names.end() ) {
  1682. if ( !( *it ).second ) {
  1683. return FixNodeName( name + "_" );
  1684. }
  1685. }
  1686. node_names[ temp ] = true;
  1687. const NameNameMap::const_iterator rit = renamed_nodes.find( temp );
  1688. return rit == renamed_nodes.end() ? temp : ( *rit ).second;
  1689. }
  1690. const NodeNameMap::const_iterator it = node_names.find( name );
  1691. if ( it != node_names.end() ) {
  1692. if ( ( *it ).second ) {
  1693. return FixNodeName( name + "_" );
  1694. }
  1695. }
  1696. node_names[ name ] = false;
  1697. const NameNameMap::const_iterator rit = renamed_nodes.find( name );
  1698. return rit == renamed_nodes.end() ? name : ( *rit ).second;
  1699. }
  1700. void Converter::ConvertAnimationStack( const AnimationStack& st )
  1701. {
  1702. const AnimationLayerList& layers = st.Layers();
  1703. if ( layers.empty() ) {
  1704. return;
  1705. }
  1706. aiAnimation* const anim = new aiAnimation();
  1707. animations.push_back( anim );
  1708. // strip AnimationStack:: prefix
  1709. std::string name = st.Name();
  1710. if ( name.substr( 0, 16 ) == "AnimationStack::" ) {
  1711. name = name.substr( 16 );
  1712. }
  1713. else if ( name.substr( 0, 11 ) == "AnimStack::" ) {
  1714. name = name.substr( 11 );
  1715. }
  1716. anim->mName.Set( name );
  1717. // need to find all nodes for which we need to generate node animations -
  1718. // it may happen that we need to merge multiple layers, though.
  1719. NodeMap node_map;
  1720. // reverse mapping from curves to layers, much faster than querying
  1721. // the FBX DOM for it.
  1722. LayerMap layer_map;
  1723. const char* prop_whitelist[] = {
  1724. "Lcl Scaling",
  1725. "Lcl Rotation",
  1726. "Lcl Translation"
  1727. };
  1728. for( const AnimationLayer* layer : layers ) {
  1729. ai_assert( layer );
  1730. const AnimationCurveNodeList& nodes = layer->Nodes( prop_whitelist, 3 );
  1731. for( const AnimationCurveNode* node : nodes ) {
  1732. ai_assert( node );
  1733. const Model* const model = dynamic_cast<const Model*>( node->Target() );
  1734. // this can happen - it could also be a NodeAttribute (i.e. for camera animations)
  1735. if ( !model ) {
  1736. continue;
  1737. }
  1738. const std::string& name = FixNodeName( model->Name() );
  1739. node_map[ name ].push_back( node );
  1740. layer_map[ node ] = layer;
  1741. }
  1742. }
  1743. // generate node animations
  1744. std::vector<aiNodeAnim*> node_anims;
  1745. double min_time = 1e10;
  1746. double max_time = -1e10;
  1747. int64_t start_time = st.LocalStart();
  1748. int64_t stop_time = st.LocalStop();
  1749. bool has_local_startstop = start_time != 0 || stop_time != 0;
  1750. if ( !has_local_startstop ) {
  1751. // no time range given, so accept every keyframe and use the actual min/max time
  1752. // the numbers are INT64_MIN/MAX, the 20000 is for safety because GenerateNodeAnimations uses an epsilon of 10000
  1753. start_time = -9223372036854775807ll + 20000;
  1754. stop_time = 9223372036854775807ll - 20000;
  1755. }
  1756. try {
  1757. for( const NodeMap::value_type& kv : node_map ) {
  1758. GenerateNodeAnimations( node_anims,
  1759. kv.first,
  1760. kv.second,
  1761. layer_map,
  1762. start_time, stop_time,
  1763. max_time,
  1764. min_time );
  1765. }
  1766. }
  1767. catch ( std::exception& ) {
  1768. std::for_each( node_anims.begin(), node_anims.end(), Util::delete_fun<aiNodeAnim>() );
  1769. throw;
  1770. }
  1771. if ( node_anims.size() ) {
  1772. anim->mChannels = new aiNodeAnim*[ node_anims.size() ]();
  1773. anim->mNumChannels = static_cast<unsigned int>( node_anims.size() );
  1774. std::swap_ranges( node_anims.begin(), node_anims.end(), anim->mChannels );
  1775. }
  1776. else {
  1777. // empty animations would fail validation, so drop them
  1778. delete anim;
  1779. animations.pop_back();
  1780. FBXImporter::LogInfo( "ignoring empty AnimationStack (using IK?): " + name );
  1781. return;
  1782. }
  1783. double start_time_fps = has_local_startstop ? (CONVERT_FBX_TIME(start_time) * anim_fps) : min_time;
  1784. double stop_time_fps = has_local_startstop ? (CONVERT_FBX_TIME(stop_time) * anim_fps) : max_time;
  1785. // adjust relative timing for animation
  1786. for ( unsigned int c = 0; c < anim->mNumChannels; c++ ) {
  1787. aiNodeAnim* channel = anim->mChannels[ c ];
  1788. for ( uint32_t i = 0; i < channel->mNumPositionKeys; i++ )
  1789. channel->mPositionKeys[ i ].mTime -= start_time_fps;
  1790. for ( uint32_t i = 0; i < channel->mNumRotationKeys; i++ )
  1791. channel->mRotationKeys[ i ].mTime -= start_time_fps;
  1792. for ( uint32_t i = 0; i < channel->mNumScalingKeys; i++ )
  1793. channel->mScalingKeys[ i ].mTime -= start_time_fps;
  1794. }
  1795. // for some mysterious reason, mDuration is simply the maximum key -- the
  1796. // validator always assumes animations to start at zero.
  1797. anim->mDuration = stop_time_fps - start_time_fps;
  1798. anim->mTicksPerSecond = anim_fps;
  1799. }
  1800. #ifdef ASSIMP_BUILD_DEBUG
  1801. // ------------------------------------------------------------------------------------------------
  1802. // sanity check whether the input is ok
  1803. static void validateAnimCurveNodes( const std::vector<const AnimationCurveNode*>& curves,
  1804. bool strictMode ) {
  1805. const Object* target( NULL );
  1806. for( const AnimationCurveNode* node : curves ) {
  1807. if ( !target ) {
  1808. target = node->Target();
  1809. }
  1810. if ( node->Target() != target ) {
  1811. FBXImporter::LogWarn( "Node target is nullptr type." );
  1812. }
  1813. if ( strictMode ) {
  1814. ai_assert( node->Target() == target );
  1815. }
  1816. }
  1817. }
  1818. #endif // ASSIMP_BUILD_DEBUG
  1819. // ------------------------------------------------------------------------------------------------
  1820. void Converter::GenerateNodeAnimations( std::vector<aiNodeAnim*>& node_anims,
  1821. const std::string& fixed_name,
  1822. const std::vector<const AnimationCurveNode*>& curves,
  1823. const LayerMap& layer_map,
  1824. int64_t start, int64_t stop,
  1825. double& max_time,
  1826. double& min_time )
  1827. {
  1828. NodeMap node_property_map;
  1829. ai_assert( curves.size() );
  1830. #ifdef ASSIMP_BUILD_DEBUG
  1831. validateAnimCurveNodes( curves, doc.Settings().strictMode );
  1832. #endif
  1833. const AnimationCurveNode* curve_node = NULL;
  1834. for( const AnimationCurveNode* node : curves ) {
  1835. ai_assert( node );
  1836. if ( node->TargetProperty().empty() ) {
  1837. FBXImporter::LogWarn( "target property for animation curve not set: " + node->Name() );
  1838. continue;
  1839. }
  1840. curve_node = node;
  1841. if ( node->Curves().empty() ) {
  1842. FBXImporter::LogWarn( "no animation curves assigned to AnimationCurveNode: " + node->Name() );
  1843. continue;
  1844. }
  1845. node_property_map[ node->TargetProperty() ].push_back( node );
  1846. }
  1847. ai_assert( curve_node );
  1848. ai_assert( curve_node->TargetAsModel() );
  1849. const Model& target = *curve_node->TargetAsModel();
  1850. // check for all possible transformation components
  1851. NodeMap::const_iterator chain[ TransformationComp_MAXIMUM ];
  1852. bool has_any = false;
  1853. bool has_complex = false;
  1854. for ( size_t i = 0; i < TransformationComp_MAXIMUM; ++i ) {
  1855. const TransformationComp comp = static_cast<TransformationComp>( i );
  1856. // inverse pivots don't exist in the input, we just generate them
  1857. if ( comp == TransformationComp_RotationPivotInverse || comp == TransformationComp_ScalingPivotInverse ) {
  1858. chain[ i ] = node_property_map.end();
  1859. continue;
  1860. }
  1861. chain[ i ] = node_property_map.find( NameTransformationCompProperty( comp ) );
  1862. if ( chain[ i ] != node_property_map.end() ) {
  1863. // check if this curves contains redundant information by looking
  1864. // up the corresponding node's transformation chain.
  1865. if ( doc.Settings().optimizeEmptyAnimationCurves &&
  1866. IsRedundantAnimationData( target, comp, ( *chain[ i ] ).second ) ) {
  1867. FBXImporter::LogDebug( "dropping redundant animation channel for node " + target.Name() );
  1868. continue;
  1869. }
  1870. has_any = true;
  1871. if ( comp != TransformationComp_Rotation && comp != TransformationComp_Scaling && comp != TransformationComp_Translation )
  1872. {
  1873. has_complex = true;
  1874. }
  1875. }
  1876. }
  1877. if ( !has_any ) {
  1878. FBXImporter::LogWarn( "ignoring node animation, did not find any transformation key frames" );
  1879. return;
  1880. }
  1881. // this needs to play nicely with GenerateTransformationNodeChain() which will
  1882. // be invoked _later_ (animations come first). If this node has only rotation,
  1883. // scaling and translation _and_ there are no animated other components either,
  1884. // we can use a single node and also a single node animation channel.
  1885. if ( !has_complex && !NeedsComplexTransformationChain( target ) ) {
  1886. aiNodeAnim* const nd = GenerateSimpleNodeAnim( fixed_name, target, chain,
  1887. node_property_map.end(),
  1888. layer_map,
  1889. start, stop,
  1890. max_time,
  1891. min_time,
  1892. true // input is TRS order, assimp is SRT
  1893. );
  1894. ai_assert( nd );
  1895. if ( nd->mNumPositionKeys == 0 && nd->mNumRotationKeys == 0 && nd->mNumScalingKeys == 0 ) {
  1896. delete nd;
  1897. }
  1898. else {
  1899. node_anims.push_back( nd );
  1900. }
  1901. return;
  1902. }
  1903. // otherwise, things get gruesome and we need separate animation channels
  1904. // for each part of the transformation chain. Remember which channels
  1905. // we generated and pass this information to the node conversion
  1906. // code to avoid nodes that have identity transform, but non-identity
  1907. // animations, being dropped.
  1908. unsigned int flags = 0, bit = 0x1;
  1909. for ( size_t i = 0; i < TransformationComp_MAXIMUM; ++i, bit <<= 1 ) {
  1910. const TransformationComp comp = static_cast<TransformationComp>( i );
  1911. if ( chain[ i ] != node_property_map.end() ) {
  1912. flags |= bit;
  1913. ai_assert( comp != TransformationComp_RotationPivotInverse );
  1914. ai_assert( comp != TransformationComp_ScalingPivotInverse );
  1915. const std::string& chain_name = NameTransformationChainNode( fixed_name, comp );
  1916. aiNodeAnim* na = nullptr;
  1917. switch ( comp )
  1918. {
  1919. case TransformationComp_Rotation:
  1920. case TransformationComp_PreRotation:
  1921. case TransformationComp_PostRotation:
  1922. case TransformationComp_GeometricRotation:
  1923. na = GenerateRotationNodeAnim( chain_name,
  1924. target,
  1925. ( *chain[ i ] ).second,
  1926. layer_map,
  1927. start, stop,
  1928. max_time,
  1929. min_time );
  1930. break;
  1931. case TransformationComp_RotationOffset:
  1932. case TransformationComp_RotationPivot:
  1933. case TransformationComp_ScalingOffset:
  1934. case TransformationComp_ScalingPivot:
  1935. case TransformationComp_Translation:
  1936. case TransformationComp_GeometricTranslation:
  1937. na = GenerateTranslationNodeAnim( chain_name,
  1938. target,
  1939. ( *chain[ i ] ).second,
  1940. layer_map,
  1941. start, stop,
  1942. max_time,
  1943. min_time );
  1944. // pivoting requires us to generate an implicit inverse channel to undo the pivot translation
  1945. if ( comp == TransformationComp_RotationPivot ) {
  1946. const std::string& invName = NameTransformationChainNode( fixed_name,
  1947. TransformationComp_RotationPivotInverse );
  1948. aiNodeAnim* const inv = GenerateTranslationNodeAnim( invName,
  1949. target,
  1950. ( *chain[ i ] ).second,
  1951. layer_map,
  1952. start, stop,
  1953. max_time,
  1954. min_time,
  1955. true );
  1956. ai_assert( inv );
  1957. if ( inv->mNumPositionKeys == 0 && inv->mNumRotationKeys == 0 && inv->mNumScalingKeys == 0 ) {
  1958. delete inv;
  1959. }
  1960. else {
  1961. node_anims.push_back( inv );
  1962. }
  1963. ai_assert( TransformationComp_RotationPivotInverse > i );
  1964. flags |= bit << ( TransformationComp_RotationPivotInverse - i );
  1965. }
  1966. else if ( comp == TransformationComp_ScalingPivot ) {
  1967. const std::string& invName = NameTransformationChainNode( fixed_name,
  1968. TransformationComp_ScalingPivotInverse );
  1969. aiNodeAnim* const inv = GenerateTranslationNodeAnim( invName,
  1970. target,
  1971. ( *chain[ i ] ).second,
  1972. layer_map,
  1973. start, stop,
  1974. max_time,
  1975. min_time,
  1976. true );
  1977. ai_assert( inv );
  1978. if ( inv->mNumPositionKeys == 0 && inv->mNumRotationKeys == 0 && inv->mNumScalingKeys == 0 ) {
  1979. delete inv;
  1980. }
  1981. else {
  1982. node_anims.push_back( inv );
  1983. }
  1984. ai_assert( TransformationComp_RotationPivotInverse > i );
  1985. flags |= bit << ( TransformationComp_RotationPivotInverse - i );
  1986. }
  1987. break;
  1988. case TransformationComp_Scaling:
  1989. case TransformationComp_GeometricScaling:
  1990. na = GenerateScalingNodeAnim( chain_name,
  1991. target,
  1992. ( *chain[ i ] ).second,
  1993. layer_map,
  1994. start, stop,
  1995. max_time,
  1996. min_time );
  1997. break;
  1998. default:
  1999. ai_assert( false );
  2000. }
  2001. ai_assert( na );
  2002. if ( na->mNumPositionKeys == 0 && na->mNumRotationKeys == 0 && na->mNumScalingKeys == 0 ) {
  2003. delete na;
  2004. }
  2005. else {
  2006. node_anims.push_back( na );
  2007. }
  2008. continue;
  2009. }
  2010. }
  2011. node_anim_chain_bits[ fixed_name ] = flags;
  2012. }
  2013. bool Converter::IsRedundantAnimationData( const Model& target,
  2014. TransformationComp comp,
  2015. const std::vector<const AnimationCurveNode*>& curves )
  2016. {
  2017. ai_assert( curves.size() );
  2018. // look for animation nodes with
  2019. // * sub channels for all relevant components set
  2020. // * one key/value pair per component
  2021. // * combined values match up the corresponding value in the bind pose node transformation
  2022. // only such nodes are 'redundant' for this function.
  2023. if ( curves.size() > 1 ) {
  2024. return false;
  2025. }
  2026. const AnimationCurveNode& nd = *curves.front();
  2027. const AnimationCurveMap& sub_curves = nd.Curves();
  2028. const AnimationCurveMap::const_iterator dx = sub_curves.find( "d|X" );
  2029. const AnimationCurveMap::const_iterator dy = sub_curves.find( "d|Y" );
  2030. const AnimationCurveMap::const_iterator dz = sub_curves.find( "d|Z" );
  2031. if ( dx == sub_curves.end() || dy == sub_curves.end() || dz == sub_curves.end() ) {
  2032. return false;
  2033. }
  2034. const KeyValueList& vx = ( *dx ).second->GetValues();
  2035. const KeyValueList& vy = ( *dy ).second->GetValues();
  2036. const KeyValueList& vz = ( *dz ).second->GetValues();
  2037. if ( vx.size() != 1 || vy.size() != 1 || vz.size() != 1 ) {
  2038. return false;
  2039. }
  2040. const aiVector3D dyn_val = aiVector3D( vx[ 0 ], vy[ 0 ], vz[ 0 ] );
  2041. const aiVector3D& static_val = PropertyGet<aiVector3D>( target.Props(),
  2042. NameTransformationCompProperty( comp ),
  2043. TransformationCompDefaultValue( comp )
  2044. );
  2045. const float epsilon = 1e-6f;
  2046. return ( dyn_val - static_val ).SquareLength() < epsilon;
  2047. }
  2048. aiNodeAnim* Converter::GenerateRotationNodeAnim( const std::string& name,
  2049. const Model& target,
  2050. const std::vector<const AnimationCurveNode*>& curves,
  2051. const LayerMap& layer_map,
  2052. int64_t start, int64_t stop,
  2053. double& max_time,
  2054. double& min_time )
  2055. {
  2056. std::unique_ptr<aiNodeAnim> na( new aiNodeAnim() );
  2057. na->mNodeName.Set( name );
  2058. ConvertRotationKeys( na.get(), curves, layer_map, start, stop, max_time, min_time, target.RotationOrder() );
  2059. // dummy scaling key
  2060. na->mScalingKeys = new aiVectorKey[ 1 ];
  2061. na->mNumScalingKeys = 1;
  2062. na->mScalingKeys[ 0 ].mTime = 0.;
  2063. na->mScalingKeys[ 0 ].mValue = aiVector3D( 1.0f, 1.0f, 1.0f );
  2064. // dummy position key
  2065. na->mPositionKeys = new aiVectorKey[ 1 ];
  2066. na->mNumPositionKeys = 1;
  2067. na->mPositionKeys[ 0 ].mTime = 0.;
  2068. na->mPositionKeys[ 0 ].mValue = aiVector3D();
  2069. return na.release();
  2070. }
  2071. aiNodeAnim* Converter::GenerateScalingNodeAnim( const std::string& name,
  2072. const Model& /*target*/,
  2073. const std::vector<const AnimationCurveNode*>& curves,
  2074. const LayerMap& layer_map,
  2075. int64_t start, int64_t stop,
  2076. double& max_time,
  2077. double& min_time )
  2078. {
  2079. std::unique_ptr<aiNodeAnim> na( new aiNodeAnim() );
  2080. na->mNodeName.Set( name );
  2081. ConvertScaleKeys( na.get(), curves, layer_map, start, stop, max_time, min_time );
  2082. // dummy rotation key
  2083. na->mRotationKeys = new aiQuatKey[ 1 ];
  2084. na->mNumRotationKeys = 1;
  2085. na->mRotationKeys[ 0 ].mTime = 0.;
  2086. na->mRotationKeys[ 0 ].mValue = aiQuaternion();
  2087. // dummy position key
  2088. na->mPositionKeys = new aiVectorKey[ 1 ];
  2089. na->mNumPositionKeys = 1;
  2090. na->mPositionKeys[ 0 ].mTime = 0.;
  2091. na->mPositionKeys[ 0 ].mValue = aiVector3D();
  2092. return na.release();
  2093. }
  2094. aiNodeAnim* Converter::GenerateTranslationNodeAnim( const std::string& name,
  2095. const Model& /*target*/,
  2096. const std::vector<const AnimationCurveNode*>& curves,
  2097. const LayerMap& layer_map,
  2098. int64_t start, int64_t stop,
  2099. double& max_time,
  2100. double& min_time,
  2101. bool inverse )
  2102. {
  2103. std::unique_ptr<aiNodeAnim> na( new aiNodeAnim() );
  2104. na->mNodeName.Set( name );
  2105. ConvertTranslationKeys( na.get(), curves, layer_map, start, stop, max_time, min_time );
  2106. if ( inverse ) {
  2107. for ( unsigned int i = 0; i < na->mNumPositionKeys; ++i ) {
  2108. na->mPositionKeys[ i ].mValue *= -1.0f;
  2109. }
  2110. }
  2111. // dummy scaling key
  2112. na->mScalingKeys = new aiVectorKey[ 1 ];
  2113. na->mNumScalingKeys = 1;
  2114. na->mScalingKeys[ 0 ].mTime = 0.;
  2115. na->mScalingKeys[ 0 ].mValue = aiVector3D( 1.0f, 1.0f, 1.0f );
  2116. // dummy rotation key
  2117. na->mRotationKeys = new aiQuatKey[ 1 ];
  2118. na->mNumRotationKeys = 1;
  2119. na->mRotationKeys[ 0 ].mTime = 0.;
  2120. na->mRotationKeys[ 0 ].mValue = aiQuaternion();
  2121. return na.release();
  2122. }
  2123. aiNodeAnim* Converter::GenerateSimpleNodeAnim( const std::string& name,
  2124. const Model& target,
  2125. NodeMap::const_iterator chain[ TransformationComp_MAXIMUM ],
  2126. NodeMap::const_iterator iter_end,
  2127. const LayerMap& layer_map,
  2128. int64_t start, int64_t stop,
  2129. double& max_time,
  2130. double& min_time,
  2131. bool reverse_order )
  2132. {
  2133. std::unique_ptr<aiNodeAnim> na( new aiNodeAnim() );
  2134. na->mNodeName.Set( name );
  2135. const PropertyTable& props = target.Props();
  2136. // need to convert from TRS order to SRT?
  2137. if ( reverse_order ) {
  2138. aiVector3D def_scale = PropertyGet( props, "Lcl Scaling", aiVector3D( 1.f, 1.f, 1.f ) );
  2139. aiVector3D def_translate = PropertyGet( props, "Lcl Translation", aiVector3D( 0.f, 0.f, 0.f ) );
  2140. aiVector3D def_rot = PropertyGet( props, "Lcl Rotation", aiVector3D( 0.f, 0.f, 0.f ) );
  2141. KeyFrameListList scaling;
  2142. KeyFrameListList translation;
  2143. KeyFrameListList rotation;
  2144. if ( chain[ TransformationComp_Scaling ] != iter_end ) {
  2145. scaling = GetKeyframeList( ( *chain[ TransformationComp_Scaling ] ).second, start, stop );
  2146. }
  2147. if ( chain[ TransformationComp_Translation ] != iter_end ) {
  2148. translation = GetKeyframeList( ( *chain[ TransformationComp_Translation ] ).second, start, stop );
  2149. }
  2150. if ( chain[ TransformationComp_Rotation ] != iter_end ) {
  2151. rotation = GetKeyframeList( ( *chain[ TransformationComp_Rotation ] ).second, start, stop );
  2152. }
  2153. KeyFrameListList joined;
  2154. joined.insert( joined.end(), scaling.begin(), scaling.end() );
  2155. joined.insert( joined.end(), translation.begin(), translation.end() );
  2156. joined.insert( joined.end(), rotation.begin(), rotation.end() );
  2157. const KeyTimeList& times = GetKeyTimeList( joined );
  2158. aiQuatKey* out_quat = new aiQuatKey[ times.size() ];
  2159. aiVectorKey* out_scale = new aiVectorKey[ times.size() ];
  2160. aiVectorKey* out_translation = new aiVectorKey[ times.size() ];
  2161. if ( times.size() )
  2162. {
  2163. ConvertTransformOrder_TRStoSRT( out_quat, out_scale, out_translation,
  2164. scaling,
  2165. translation,
  2166. rotation,
  2167. times,
  2168. max_time,
  2169. min_time,
  2170. target.RotationOrder(),
  2171. def_scale,
  2172. def_translate,
  2173. def_rot );
  2174. }
  2175. // XXX remove duplicates / redundant keys which this operation did
  2176. // likely produce if not all three channels were equally dense.
  2177. na->mNumScalingKeys = static_cast<unsigned int>( times.size() );
  2178. na->mNumRotationKeys = na->mNumScalingKeys;
  2179. na->mNumPositionKeys = na->mNumScalingKeys;
  2180. na->mScalingKeys = out_scale;
  2181. na->mRotationKeys = out_quat;
  2182. na->mPositionKeys = out_translation;
  2183. }
  2184. else {
  2185. // if a particular transformation is not given, grab it from
  2186. // the corresponding node to meet the semantics of aiNodeAnim,
  2187. // which requires all of rotation, scaling and translation
  2188. // to be set.
  2189. if ( chain[ TransformationComp_Scaling ] != iter_end ) {
  2190. ConvertScaleKeys( na.get(), ( *chain[ TransformationComp_Scaling ] ).second,
  2191. layer_map,
  2192. start, stop,
  2193. max_time,
  2194. min_time );
  2195. }
  2196. else {
  2197. na->mScalingKeys = new aiVectorKey[ 1 ];
  2198. na->mNumScalingKeys = 1;
  2199. na->mScalingKeys[ 0 ].mTime = 0.;
  2200. na->mScalingKeys[ 0 ].mValue = PropertyGet( props, "Lcl Scaling",
  2201. aiVector3D( 1.f, 1.f, 1.f ) );
  2202. }
  2203. if ( chain[ TransformationComp_Rotation ] != iter_end ) {
  2204. ConvertRotationKeys( na.get(), ( *chain[ TransformationComp_Rotation ] ).second,
  2205. layer_map,
  2206. start, stop,
  2207. max_time,
  2208. min_time,
  2209. target.RotationOrder() );
  2210. }
  2211. else {
  2212. na->mRotationKeys = new aiQuatKey[ 1 ];
  2213. na->mNumRotationKeys = 1;
  2214. na->mRotationKeys[ 0 ].mTime = 0.;
  2215. na->mRotationKeys[ 0 ].mValue = EulerToQuaternion(
  2216. PropertyGet( props, "Lcl Rotation", aiVector3D( 0.f, 0.f, 0.f ) ),
  2217. target.RotationOrder() );
  2218. }
  2219. if ( chain[ TransformationComp_Translation ] != iter_end ) {
  2220. ConvertTranslationKeys( na.get(), ( *chain[ TransformationComp_Translation ] ).second,
  2221. layer_map,
  2222. start, stop,
  2223. max_time,
  2224. min_time );
  2225. }
  2226. else {
  2227. na->mPositionKeys = new aiVectorKey[ 1 ];
  2228. na->mNumPositionKeys = 1;
  2229. na->mPositionKeys[ 0 ].mTime = 0.;
  2230. na->mPositionKeys[ 0 ].mValue = PropertyGet( props, "Lcl Translation",
  2231. aiVector3D( 0.f, 0.f, 0.f ) );
  2232. }
  2233. }
  2234. return na.release();
  2235. }
  2236. Converter::KeyFrameListList Converter::GetKeyframeList( const std::vector<const AnimationCurveNode*>& nodes, int64_t start, int64_t stop )
  2237. {
  2238. KeyFrameListList inputs;
  2239. inputs.reserve( nodes.size() * 3 );
  2240. //give some breathing room for rounding errors
  2241. int64_t adj_start = start - 10000;
  2242. int64_t adj_stop = stop + 10000;
  2243. for( const AnimationCurveNode* node : nodes ) {
  2244. ai_assert( node );
  2245. const AnimationCurveMap& curves = node->Curves();
  2246. for( const AnimationCurveMap::value_type& kv : curves ) {
  2247. unsigned int mapto;
  2248. if ( kv.first == "d|X" ) {
  2249. mapto = 0;
  2250. }
  2251. else if ( kv.first == "d|Y" ) {
  2252. mapto = 1;
  2253. }
  2254. else if ( kv.first == "d|Z" ) {
  2255. mapto = 2;
  2256. }
  2257. else {
  2258. FBXImporter::LogWarn( "ignoring scale animation curve, did not recognize target component" );
  2259. continue;
  2260. }
  2261. const AnimationCurve* const curve = kv.second;
  2262. ai_assert( curve->GetKeys().size() == curve->GetValues().size() && curve->GetKeys().size() );
  2263. //get values within the start/stop time window
  2264. std::shared_ptr<KeyTimeList> Keys( new KeyTimeList() );
  2265. std::shared_ptr<KeyValueList> Values( new KeyValueList() );
  2266. const size_t count = curve->GetKeys().size();
  2267. Keys->reserve( count );
  2268. Values->reserve( count );
  2269. for (size_t n = 0; n < count; n++ )
  2270. {
  2271. int64_t k = curve->GetKeys().at( n );
  2272. if ( k >= adj_start && k <= adj_stop )
  2273. {
  2274. Keys->push_back( k );
  2275. Values->push_back( curve->GetValues().at( n ) );
  2276. }
  2277. }
  2278. inputs.push_back( std::make_tuple( Keys, Values, mapto ) );
  2279. }
  2280. }
  2281. return inputs; // pray for NRVO :-)
  2282. }
  2283. KeyTimeList Converter::GetKeyTimeList( const KeyFrameListList& inputs )
  2284. {
  2285. ai_assert( inputs.size() );
  2286. // reserve some space upfront - it is likely that the keyframe lists
  2287. // have matching time values, so max(of all keyframe lists) should
  2288. // be a good estimate.
  2289. KeyTimeList keys;
  2290. size_t estimate = 0;
  2291. for( const KeyFrameList& kfl : inputs ) {
  2292. estimate = std::max( estimate, std::get<0>(kfl)->size() );
  2293. }
  2294. keys.reserve( estimate );
  2295. std::vector<unsigned int> next_pos;
  2296. next_pos.resize( inputs.size(), 0 );
  2297. const size_t count = inputs.size();
  2298. while ( true ) {
  2299. int64_t min_tick = std::numeric_limits<int64_t>::max();
  2300. for ( size_t i = 0; i < count; ++i ) {
  2301. const KeyFrameList& kfl = inputs[ i ];
  2302. if ( std::get<0>(kfl)->size() > next_pos[ i ] && std::get<0>(kfl)->at( next_pos[ i ] ) < min_tick ) {
  2303. min_tick = std::get<0>(kfl)->at( next_pos[ i ] );
  2304. }
  2305. }
  2306. if ( min_tick == std::numeric_limits<int64_t>::max() ) {
  2307. break;
  2308. }
  2309. keys.push_back( min_tick );
  2310. for ( size_t i = 0; i < count; ++i ) {
  2311. const KeyFrameList& kfl = inputs[ i ];
  2312. while ( std::get<0>(kfl)->size() > next_pos[ i ] && std::get<0>(kfl)->at( next_pos[ i ] ) == min_tick ) {
  2313. ++next_pos[ i ];
  2314. }
  2315. }
  2316. }
  2317. return keys;
  2318. }
  2319. void Converter::InterpolateKeys( aiVectorKey* valOut, const KeyTimeList& keys, const KeyFrameListList& inputs,
  2320. const aiVector3D& def_value,
  2321. double& max_time,
  2322. double& min_time )
  2323. {
  2324. ai_assert( keys.size() );
  2325. ai_assert( valOut );
  2326. std::vector<unsigned int> next_pos;
  2327. const size_t count = inputs.size();
  2328. next_pos.resize( inputs.size(), 0 );
  2329. for( KeyTimeList::value_type time : keys ) {
  2330. ai_real result[ 3 ] = { def_value.x, def_value.y, def_value.z };
  2331. for ( size_t i = 0; i < count; ++i ) {
  2332. const KeyFrameList& kfl = inputs[ i ];
  2333. const size_t ksize = std::get<0>(kfl)->size();
  2334. if ( ksize > next_pos[ i ] && std::get<0>(kfl)->at( next_pos[ i ] ) == time ) {
  2335. ++next_pos[ i ];
  2336. }
  2337. const size_t id0 = next_pos[ i ]>0 ? next_pos[ i ] - 1 : 0;
  2338. const size_t id1 = next_pos[ i ] == ksize ? ksize - 1 : next_pos[ i ];
  2339. // use lerp for interpolation
  2340. const KeyValueList::value_type valueA = std::get<1>(kfl)->at( id0 );
  2341. const KeyValueList::value_type valueB = std::get<1>(kfl)->at( id1 );
  2342. const KeyTimeList::value_type timeA = std::get<0>(kfl)->at( id0 );
  2343. const KeyTimeList::value_type timeB = std::get<0>(kfl)->at( id1 );
  2344. const ai_real factor = timeB == timeA ? ai_real(0.) : static_cast<ai_real>( ( time - timeA ) ) / ( timeB - timeA );
  2345. const ai_real interpValue = static_cast<ai_real>( valueA + ( valueB - valueA ) * factor );
  2346. result[ std::get<2>(kfl) ] = interpValue;
  2347. }
  2348. // magic value to convert fbx times to seconds
  2349. valOut->mTime = CONVERT_FBX_TIME( time ) * anim_fps;
  2350. min_time = std::min( min_time, valOut->mTime );
  2351. max_time = std::max( max_time, valOut->mTime );
  2352. valOut->mValue.x = result[ 0 ];
  2353. valOut->mValue.y = result[ 1 ];
  2354. valOut->mValue.z = result[ 2 ];
  2355. ++valOut;
  2356. }
  2357. }
  2358. void Converter::InterpolateKeys( aiQuatKey* valOut, const KeyTimeList& keys, const KeyFrameListList& inputs,
  2359. const aiVector3D& def_value,
  2360. double& maxTime,
  2361. double& minTime,
  2362. Model::RotOrder order )
  2363. {
  2364. ai_assert( keys.size() );
  2365. ai_assert( valOut );
  2366. std::unique_ptr<aiVectorKey[]> temp( new aiVectorKey[ keys.size() ] );
  2367. InterpolateKeys( temp.get(), keys, inputs, def_value, maxTime, minTime );
  2368. aiMatrix4x4 m;
  2369. aiQuaternion lastq;
  2370. for ( size_t i = 0, c = keys.size(); i < c; ++i ) {
  2371. valOut[ i ].mTime = temp[ i ].mTime;
  2372. GetRotationMatrix( order, temp[ i ].mValue, m );
  2373. aiQuaternion quat = aiQuaternion( aiMatrix3x3( m ) );
  2374. // take shortest path by checking the inner product
  2375. // http://www.3dkingdoms.com/weekly/weekly.php?a=36
  2376. if ( quat.x * lastq.x + quat.y * lastq.y + quat.z * lastq.z + quat.w * lastq.w < 0 )
  2377. {
  2378. quat.x = -quat.x;
  2379. quat.y = -quat.y;
  2380. quat.z = -quat.z;
  2381. quat.w = -quat.w;
  2382. }
  2383. lastq = quat;
  2384. valOut[ i ].mValue = quat;
  2385. }
  2386. }
  2387. void Converter::ConvertTransformOrder_TRStoSRT( aiQuatKey* out_quat, aiVectorKey* out_scale,
  2388. aiVectorKey* out_translation,
  2389. const KeyFrameListList& scaling,
  2390. const KeyFrameListList& translation,
  2391. const KeyFrameListList& rotation,
  2392. const KeyTimeList& times,
  2393. double& maxTime,
  2394. double& minTime,
  2395. Model::RotOrder order,
  2396. const aiVector3D& def_scale,
  2397. const aiVector3D& def_translate,
  2398. const aiVector3D& def_rotation )
  2399. {
  2400. if ( rotation.size() ) {
  2401. InterpolateKeys( out_quat, times, rotation, def_rotation, maxTime, minTime, order );
  2402. }
  2403. else {
  2404. for ( size_t i = 0; i < times.size(); ++i ) {
  2405. out_quat[ i ].mTime = CONVERT_FBX_TIME( times[ i ] ) * anim_fps;
  2406. out_quat[ i ].mValue = EulerToQuaternion( def_rotation, order );
  2407. }
  2408. }
  2409. if ( scaling.size() ) {
  2410. InterpolateKeys( out_scale, times, scaling, def_scale, maxTime, minTime );
  2411. }
  2412. else {
  2413. for ( size_t i = 0; i < times.size(); ++i ) {
  2414. out_scale[ i ].mTime = CONVERT_FBX_TIME( times[ i ] ) * anim_fps;
  2415. out_scale[ i ].mValue = def_scale;
  2416. }
  2417. }
  2418. if ( translation.size() ) {
  2419. InterpolateKeys( out_translation, times, translation, def_translate, maxTime, minTime );
  2420. }
  2421. else {
  2422. for ( size_t i = 0; i < times.size(); ++i ) {
  2423. out_translation[ i ].mTime = CONVERT_FBX_TIME( times[ i ] ) * anim_fps;
  2424. out_translation[ i ].mValue = def_translate;
  2425. }
  2426. }
  2427. const size_t count = times.size();
  2428. for ( size_t i = 0; i < count; ++i ) {
  2429. aiQuaternion& r = out_quat[ i ].mValue;
  2430. aiVector3D& s = out_scale[ i ].mValue;
  2431. aiVector3D& t = out_translation[ i ].mValue;
  2432. aiMatrix4x4 mat, temp;
  2433. aiMatrix4x4::Translation( t, mat );
  2434. mat *= aiMatrix4x4( r.GetMatrix() );
  2435. mat *= aiMatrix4x4::Scaling( s, temp );
  2436. mat.Decompose( s, r, t );
  2437. }
  2438. }
  2439. aiQuaternion Converter::EulerToQuaternion( const aiVector3D& rot, Model::RotOrder order )
  2440. {
  2441. aiMatrix4x4 m;
  2442. GetRotationMatrix( order, rot, m );
  2443. return aiQuaternion( aiMatrix3x3( m ) );
  2444. }
  2445. void Converter::ConvertScaleKeys( aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes, const LayerMap& /*layers*/,
  2446. int64_t start, int64_t stop,
  2447. double& maxTime,
  2448. double& minTime )
  2449. {
  2450. ai_assert( nodes.size() );
  2451. // XXX for now, assume scale should be blended geometrically (i.e. two
  2452. // layers should be multiplied with each other). There is a FBX
  2453. // property in the layer to specify the behaviour, though.
  2454. const KeyFrameListList& inputs = GetKeyframeList( nodes, start, stop );
  2455. const KeyTimeList& keys = GetKeyTimeList( inputs );
  2456. na->mNumScalingKeys = static_cast<unsigned int>( keys.size() );
  2457. na->mScalingKeys = new aiVectorKey[ keys.size() ];
  2458. if ( keys.size() > 0 )
  2459. InterpolateKeys( na->mScalingKeys, keys, inputs, aiVector3D( 1.0f, 1.0f, 1.0f ), maxTime, minTime );
  2460. }
  2461. void Converter::ConvertTranslationKeys( aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes,
  2462. const LayerMap& /*layers*/,
  2463. int64_t start, int64_t stop,
  2464. double& maxTime,
  2465. double& minTime )
  2466. {
  2467. ai_assert( nodes.size() );
  2468. // XXX see notes in ConvertScaleKeys()
  2469. const KeyFrameListList& inputs = GetKeyframeList( nodes, start, stop );
  2470. const KeyTimeList& keys = GetKeyTimeList( inputs );
  2471. na->mNumPositionKeys = static_cast<unsigned int>( keys.size() );
  2472. na->mPositionKeys = new aiVectorKey[ keys.size() ];
  2473. if ( keys.size() > 0 )
  2474. InterpolateKeys( na->mPositionKeys, keys, inputs, aiVector3D( 0.0f, 0.0f, 0.0f ), maxTime, minTime );
  2475. }
  2476. void Converter::ConvertRotationKeys( aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes,
  2477. const LayerMap& /*layers*/,
  2478. int64_t start, int64_t stop,
  2479. double& maxTime,
  2480. double& minTime,
  2481. Model::RotOrder order )
  2482. {
  2483. ai_assert( nodes.size() );
  2484. // XXX see notes in ConvertScaleKeys()
  2485. const std::vector< KeyFrameList >& inputs = GetKeyframeList( nodes, start, stop );
  2486. const KeyTimeList& keys = GetKeyTimeList( inputs );
  2487. na->mNumRotationKeys = static_cast<unsigned int>( keys.size() );
  2488. na->mRotationKeys = new aiQuatKey[ keys.size() ];
  2489. if (!keys.empty()) {
  2490. InterpolateKeys(na->mRotationKeys, keys, inputs, aiVector3D(0.0f, 0.0f, 0.0f), maxTime, minTime, order);
  2491. }
  2492. }
  2493. void Converter::ConvertGlobalSettings() {
  2494. if (nullptr == out) {
  2495. return;
  2496. }
  2497. out->mMetaData = aiMetadata::Alloc(1);
  2498. unsigned int index(0);
  2499. const double unitScalFactor(doc.GlobalSettings().UnitScaleFactor());
  2500. out->mMetaData->Set(index, "UnitScaleFactor", unitScalFactor);
  2501. }
  2502. void Converter::TransferDataToScene()
  2503. {
  2504. ai_assert( !out->mMeshes );
  2505. ai_assert( !out->mNumMeshes );
  2506. // note: the trailing () ensures initialization with NULL - not
  2507. // many C++ users seem to know this, so pointing it out to avoid
  2508. // confusion why this code works.
  2509. if ( meshes.size() ) {
  2510. out->mMeshes = new aiMesh*[ meshes.size() ]();
  2511. out->mNumMeshes = static_cast<unsigned int>( meshes.size() );
  2512. std::swap_ranges( meshes.begin(), meshes.end(), out->mMeshes );
  2513. }
  2514. if ( materials.size() ) {
  2515. out->mMaterials = new aiMaterial*[ materials.size() ]();
  2516. out->mNumMaterials = static_cast<unsigned int>( materials.size() );
  2517. std::swap_ranges( materials.begin(), materials.end(), out->mMaterials );
  2518. }
  2519. if ( animations.size() ) {
  2520. out->mAnimations = new aiAnimation*[ animations.size() ]();
  2521. out->mNumAnimations = static_cast<unsigned int>( animations.size() );
  2522. std::swap_ranges( animations.begin(), animations.end(), out->mAnimations );
  2523. }
  2524. if ( lights.size() ) {
  2525. out->mLights = new aiLight*[ lights.size() ]();
  2526. out->mNumLights = static_cast<unsigned int>( lights.size() );
  2527. std::swap_ranges( lights.begin(), lights.end(), out->mLights );
  2528. }
  2529. if ( cameras.size() ) {
  2530. out->mCameras = new aiCamera*[ cameras.size() ]();
  2531. out->mNumCameras = static_cast<unsigned int>( cameras.size() );
  2532. std::swap_ranges( cameras.begin(), cameras.end(), out->mCameras );
  2533. }
  2534. if ( textures.size() ) {
  2535. out->mTextures = new aiTexture*[ textures.size() ]();
  2536. out->mNumTextures = static_cast<unsigned int>( textures.size() );
  2537. std::swap_ranges( textures.begin(), textures.end(), out->mTextures );
  2538. }
  2539. }
  2540. //} // !anon
  2541. // ------------------------------------------------------------------------------------------------
  2542. void ConvertToAssimpScene(aiScene* out, const Document& doc)
  2543. {
  2544. Converter converter(out,doc);
  2545. }
  2546. } // !FBX
  2547. } // !Assimp
  2548. #endif