FBXConverter.cpp 151 KB

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