FBXConverter.cpp 164 KB

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