FBXConverter.cpp 81 KB

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