FBXConverter.cpp 110 KB

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