FBXConverter.cpp 94 KB

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