FBXConverter.cpp 119 KB

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