FBXExporter.cpp 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2024, 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. #ifndef ASSIMP_BUILD_NO_EXPORT
  34. #ifndef ASSIMP_BUILD_NO_FBX_EXPORTER
  35. #include "FBXExporter.h"
  36. #include "FBXExportNode.h"
  37. #include "FBXExportProperty.h"
  38. #include "FBXCommon.h"
  39. #include "FBXUtil.h"
  40. #include <assimp/version.h> // aiGetVersion
  41. #include <assimp/IOSystem.hpp>
  42. #include <assimp/Exporter.hpp>
  43. #include <assimp/DefaultLogger.hpp>
  44. #include <assimp/StreamWriter.h> // StreamWriterLE
  45. #include <assimp/Exceptional.h> // DeadlyExportError
  46. #include <assimp/material.h> // aiTextureType
  47. #include <assimp/scene.h>
  48. #include <assimp/mesh.h>
  49. // Header files, standard library.
  50. #include <array>
  51. #include <ctime> // localtime, tm_*
  52. #include <map>
  53. #include <memory> // shared_ptr
  54. #include <numeric>
  55. #include <set>
  56. #include <sstream> // stringstream
  57. #include <string>
  58. #include <unordered_set>
  59. #include <utility>
  60. #include <vector>
  61. #include <cmath>
  62. // RESOURCES:
  63. // https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  64. // https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  65. using namespace Assimp;
  66. using namespace Assimp::FBX;
  67. // some constants that we'll use for writing metadata
  68. namespace Assimp {
  69. namespace FBX {
  70. const std::string EXPORT_VERSION_STR = "7.5.0";
  71. const uint32_t EXPORT_VERSION_INT = 7500; // 7.5 == 2016+
  72. // FBX files have some hashed values that depend on the creation time field,
  73. // but for now we don't actually know how to generate these.
  74. // what we can do is set them to a known-working version.
  75. // this is the data that Blender uses in their FBX export process.
  76. const std::string GENERIC_CTIME = "1970-01-01 10:00:00:000";
  77. const std::string GENERIC_FILEID =
  78. "\x28\xb3\x2a\xeb\xb6\x24\xcc\xc2\xbf\xc8\xb0\x2a\xa9\x2b\xfc\xf1";
  79. const std::string GENERIC_FOOTID =
  80. "\xfa\xbc\xab\x09\xd0\xc8\xd4\x66\xb1\x76\xfb\x83\x1c\xf7\x26\x7e";
  81. const std::string FOOT_MAGIC =
  82. "\xf8\x5a\x8c\x6a\xde\xf5\xd9\x7e\xec\xe9\x0c\xe3\x75\x8f\x29\x0b";
  83. const std::string COMMENT_UNDERLINE =
  84. ";------------------------------------------------------------------";
  85. }
  86. // ---------------------------------------------------------------------
  87. // Worker function for exporting a scene to binary FBX.
  88. // Prototyped and registered in Exporter.cpp
  89. void ExportSceneFBX (
  90. const char* pFile,
  91. IOSystem* pIOSystem,
  92. const aiScene* pScene,
  93. const ExportProperties* pProperties
  94. ){
  95. // initialize the exporter
  96. FBXExporter exporter(pScene, pProperties);
  97. // perform binary export
  98. exporter.ExportBinary(pFile, pIOSystem);
  99. }
  100. // ---------------------------------------------------------------------
  101. // Worker function for exporting a scene to ASCII FBX.
  102. // Prototyped and registered in Exporter.cpp
  103. void ExportSceneFBXA (
  104. const char* pFile,
  105. IOSystem* pIOSystem,
  106. const aiScene* pScene,
  107. const ExportProperties* pProperties
  108. ){
  109. // initialize the exporter
  110. FBXExporter exporter(pScene, pProperties);
  111. // perform ascii export
  112. exporter.ExportAscii(pFile, pIOSystem);
  113. }
  114. } // end of namespace Assimp
  115. FBXExporter::FBXExporter ( const aiScene* pScene, const ExportProperties* pProperties )
  116. : binary(false)
  117. , mScene(pScene)
  118. , mProperties(pProperties)
  119. , outfile()
  120. , connections()
  121. , mesh_uids()
  122. , material_uids()
  123. , node_uids() {
  124. // will probably need to determine UIDs, connections, etc here.
  125. // basically anything that needs to be known
  126. // before we start writing sections to the stream.
  127. }
  128. void FBXExporter::ExportBinary (
  129. const char* pFile,
  130. IOSystem* pIOSystem
  131. ){
  132. // remember that we're exporting in binary mode
  133. binary = true;
  134. // we're not currently using these preferences,
  135. // but clang will cry about it if we never touch it.
  136. // TODO: some of these might be relevant to export
  137. (void)mProperties;
  138. // open the indicated file for writing (in binary mode)
  139. outfile.reset(pIOSystem->Open(pFile,"wb"));
  140. if (!outfile) {
  141. throw DeadlyExportError(
  142. "could not open output .fbx file: " + std::string(pFile)
  143. );
  144. }
  145. // first a binary-specific file header
  146. WriteBinaryHeader();
  147. // the rest of the file is in node entries.
  148. // we have to serialize each entry before we write to the output,
  149. // as the first thing we write is the byte offset of the _next_ entry.
  150. // Either that or we can skip back to write the offset when we finish.
  151. WriteAllNodes();
  152. // finally we have a binary footer to the file
  153. WriteBinaryFooter();
  154. // explicitly release file pointer,
  155. // so we don't have to rely on class destruction.
  156. outfile.reset();
  157. }
  158. void FBXExporter::ExportAscii (
  159. const char* pFile,
  160. IOSystem* pIOSystem
  161. ){
  162. // remember that we're exporting in ascii mode
  163. binary = false;
  164. // open the indicated file for writing in text mode
  165. outfile.reset(pIOSystem->Open(pFile,"wt"));
  166. if (!outfile) {
  167. throw DeadlyExportError(
  168. "could not open output .fbx file: " + std::string(pFile)
  169. );
  170. }
  171. // write the ascii header
  172. WriteAsciiHeader();
  173. // write all the sections
  174. WriteAllNodes();
  175. // make sure the file ends with a newline.
  176. // note: if the file is opened in text mode,
  177. // this should do the right cross-platform thing.
  178. outfile->Write("\n", 1, 1);
  179. // explicitly release file pointer,
  180. // so we don't have to rely on class destruction.
  181. outfile.reset();
  182. }
  183. void FBXExporter::WriteAsciiHeader()
  184. {
  185. // basically just a comment at the top of the file
  186. std::stringstream head;
  187. head << "; FBX " << EXPORT_VERSION_STR << " project file\n";
  188. head << "; Created by the Open Asset Import Library (Assimp)\n";
  189. head << "; http://assimp.org\n";
  190. head << "; -------------------------------------------------\n";
  191. const std::string ascii_header = head.str();
  192. outfile->Write(ascii_header.c_str(), ascii_header.size(), 1);
  193. }
  194. void FBXExporter::WriteAsciiSectionHeader(const std::string& title)
  195. {
  196. StreamWriterLE outstream(outfile);
  197. std::stringstream s;
  198. s << "\n\n; " << title << '\n';
  199. s << FBX::COMMENT_UNDERLINE << "\n";
  200. outstream.PutString(s.str());
  201. }
  202. void FBXExporter::WriteBinaryHeader()
  203. {
  204. // first a specific sequence of 23 bytes, always the same
  205. const char binary_header[24] = "Kaydara FBX Binary\x20\x20\x00\x1a\x00";
  206. outfile->Write(binary_header, 1, 23);
  207. // then FBX version number, "multiplied" by 1000, as little-endian uint32.
  208. // so 7.3 becomes 7300 == 0x841C0000, 7.4 becomes 7400 == 0xE81C0000, etc
  209. {
  210. StreamWriterLE outstream(outfile);
  211. outstream.PutU4(EXPORT_VERSION_INT);
  212. } // StreamWriter destructor writes the data to the file
  213. // after this the node data starts immediately
  214. // (probably with the FBXHEaderExtension node)
  215. }
  216. void FBXExporter::WriteBinaryFooter()
  217. {
  218. outfile->Write(NULL_RECORD, NumNullRecords, 1);
  219. outfile->Write(GENERIC_FOOTID.c_str(), GENERIC_FOOTID.size(), 1);
  220. // here some padding is added for alignment to 16 bytes.
  221. // if already aligned, the full 16 bytes is added.
  222. size_t pos = outfile->Tell();
  223. size_t pad = 16 - (pos % 16);
  224. for (size_t i = 0; i < pad; ++i) {
  225. outfile->Write("\x00", 1, 1);
  226. }
  227. // not sure what this is, but it seems to always be 0 in modern files
  228. for (size_t i = 0; i < 4; ++i) {
  229. outfile->Write("\x00", 1, 1);
  230. }
  231. // now the file version again
  232. {
  233. StreamWriterLE outstream(outfile);
  234. outstream.PutU4(EXPORT_VERSION_INT);
  235. } // StreamWriter destructor writes the data to the file
  236. // and finally some binary footer added to all files
  237. for (size_t i = 0; i < 120; ++i) {
  238. outfile->Write("\x00", 1, 1);
  239. }
  240. outfile->Write(FOOT_MAGIC.c_str(), FOOT_MAGIC.size(), 1);
  241. }
  242. void FBXExporter::WriteAllNodes ()
  243. {
  244. // header
  245. // (and fileid, creation time, creator, if binary)
  246. WriteHeaderExtension();
  247. // global settings
  248. WriteGlobalSettings();
  249. // documents
  250. WriteDocuments();
  251. // references
  252. WriteReferences();
  253. // definitions
  254. WriteDefinitions();
  255. // objects
  256. WriteObjects();
  257. // connections
  258. WriteConnections();
  259. // WriteTakes? (deprecated since at least 2015 (fbx 7.4))
  260. }
  261. //FBXHeaderExtension top-level node
  262. void FBXExporter::WriteHeaderExtension ()
  263. {
  264. if (!binary) {
  265. // no title, follows directly from the top comment
  266. }
  267. FBX::Node n("FBXHeaderExtension");
  268. StreamWriterLE outstream(outfile);
  269. int indent = 0;
  270. // begin node
  271. n.Begin(outstream, binary, indent);
  272. // write properties
  273. // (none)
  274. // finish properties
  275. n.EndProperties(outstream, binary, indent, 0);
  276. // begin children
  277. n.BeginChildren(outstream, binary, indent);
  278. indent = 1;
  279. // write child nodes
  280. FBX::Node::WritePropertyNode(
  281. "FBXHeaderVersion", int32_t(1003), outstream, binary, indent
  282. );
  283. FBX::Node::WritePropertyNode(
  284. "FBXVersion", int32_t(EXPORT_VERSION_INT), outstream, binary, indent
  285. );
  286. if (binary) {
  287. FBX::Node::WritePropertyNode(
  288. "EncryptionType", int32_t(0), outstream, binary, indent
  289. );
  290. }
  291. FBX::Node CreationTimeStamp("CreationTimeStamp");
  292. time_t rawtime;
  293. time(&rawtime);
  294. struct tm * now = localtime(&rawtime);
  295. CreationTimeStamp.AddChild("Version", int32_t(1000));
  296. CreationTimeStamp.AddChild("Year", int32_t(now->tm_year + 1900));
  297. CreationTimeStamp.AddChild("Month", int32_t(now->tm_mon + 1));
  298. CreationTimeStamp.AddChild("Day", int32_t(now->tm_mday));
  299. CreationTimeStamp.AddChild("Hour", int32_t(now->tm_hour));
  300. CreationTimeStamp.AddChild("Minute", int32_t(now->tm_min));
  301. CreationTimeStamp.AddChild("Second", int32_t(now->tm_sec));
  302. CreationTimeStamp.AddChild("Millisecond", int32_t(0));
  303. CreationTimeStamp.Dump(outstream, binary, indent);
  304. std::stringstream creator;
  305. creator << "Open Asset Import Library (Assimp) " << aiGetVersionMajor()
  306. << "." << aiGetVersionMinor() << "." << aiGetVersionRevision();
  307. FBX::Node::WritePropertyNode(
  308. "Creator", creator.str(), outstream, binary, indent
  309. );
  310. //FBX::Node sceneinfo("SceneInfo");
  311. //sceneinfo.AddProperty("GlobalInfo" + FBX::SEPARATOR + "SceneInfo");
  312. // not sure if any of this is actually needed,
  313. // so just write an empty node for now.
  314. //sceneinfo.Dump(outstream, binary, indent);
  315. indent = 0;
  316. // finish node
  317. n.End(outstream, binary, indent, true);
  318. // that's it for FBXHeaderExtension...
  319. if (!binary) { return; }
  320. // but binary files also need top-level FileID, CreationTime, Creator:
  321. std::vector<uint8_t> raw(GENERIC_FILEID.size());
  322. for (size_t i = 0; i < GENERIC_FILEID.size(); ++i) {
  323. raw[i] = uint8_t(GENERIC_FILEID[i]);
  324. }
  325. FBX::Node::WritePropertyNode(
  326. "FileId", std::move(raw), outstream, binary, indent
  327. );
  328. FBX::Node::WritePropertyNode(
  329. "CreationTime", GENERIC_CTIME, outstream, binary, indent
  330. );
  331. FBX::Node::WritePropertyNode(
  332. "Creator", creator.str(), outstream, binary, indent
  333. );
  334. }
  335. // WriteGlobalSettings helpers
  336. void WritePropInt(const aiScene* scene, FBX::Node& p, const std::string& key, int defaultValue)
  337. {
  338. int value;
  339. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, value)) {
  340. p.AddP70int(key, value);
  341. } else {
  342. p.AddP70int(key, defaultValue);
  343. }
  344. }
  345. void WritePropDouble(const aiScene* scene, FBX::Node& p, const std::string& key, double defaultValue)
  346. {
  347. double value;
  348. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, value)) {
  349. p.AddP70double(key, value);
  350. } else {
  351. // fallback lookup float instead
  352. float floatValue;
  353. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, floatValue)) {
  354. p.AddP70double(key, (double)floatValue);
  355. } else {
  356. p.AddP70double(key, defaultValue);
  357. }
  358. }
  359. }
  360. void WritePropEnum(const aiScene* scene, FBX::Node& p, const std::string& key, int defaultValue)
  361. {
  362. int value;
  363. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, value)) {
  364. p.AddP70enum(key, value);
  365. } else {
  366. p.AddP70enum(key, defaultValue);
  367. }
  368. }
  369. void WritePropColor(const aiScene* scene, FBX::Node& p, const std::string& key, const aiVector3D& defaultValue)
  370. {
  371. aiVector3D value;
  372. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, value)) {
  373. // ai_real can be float or double, cast to avoid warnings
  374. p.AddP70color(key, (double)value.x, (double)value.y, (double)value.z);
  375. } else {
  376. p.AddP70color(key, (double)defaultValue.x, (double)defaultValue.y, (double)defaultValue.z);
  377. }
  378. }
  379. void WritePropString(const aiScene* scene, FBX::Node& p, const std::string& key, const std::string& defaultValue)
  380. {
  381. aiString value; // MetaData doesn't hold std::string
  382. if (scene->mMetaData != nullptr && scene->mMetaData->Get(key, value)) {
  383. p.AddP70string(key, value.C_Str());
  384. } else {
  385. p.AddP70string(key, defaultValue);
  386. }
  387. }
  388. void FBXExporter::WriteGlobalSettings ()
  389. {
  390. if (!binary) {
  391. // no title, follows directly from the header extension
  392. }
  393. FBX::Node gs("GlobalSettings");
  394. gs.AddChild("Version", int32_t(1000));
  395. FBX::Node p("Properties70");
  396. WritePropInt(mScene, p, "UpAxis", 1);
  397. WritePropInt(mScene, p, "UpAxisSign", 1);
  398. WritePropInt(mScene, p, "FrontAxis", 2);
  399. WritePropInt(mScene, p, "FrontAxisSign", 1);
  400. WritePropInt(mScene, p, "CoordAxis", 0);
  401. WritePropInt(mScene, p, "CoordAxisSign", 1);
  402. WritePropInt(mScene, p, "OriginalUpAxis", 1);
  403. WritePropInt(mScene, p, "OriginalUpAxisSign", 1);
  404. WritePropDouble(mScene, p, "UnitScaleFactor", 1.0);
  405. WritePropDouble(mScene, p, "OriginalUnitScaleFactor", 1.0);
  406. WritePropColor(mScene, p, "AmbientColor", aiVector3D((ai_real)0.0, (ai_real)0.0, (ai_real)0.0));
  407. WritePropString(mScene, p,"DefaultCamera", "Producer Perspective");
  408. WritePropEnum(mScene, p, "TimeMode", 11);
  409. WritePropEnum(mScene, p, "TimeProtocol", 2);
  410. WritePropEnum(mScene, p, "SnapOnFrameMode", 0);
  411. p.AddP70time("TimeSpanStart", 0); // TODO: animation support
  412. p.AddP70time("TimeSpanStop", FBX::SECOND); // TODO: animation support
  413. WritePropDouble(mScene, p, "CustomFrameRate", -1.0);
  414. p.AddP70("TimeMarker", "Compound", "", ""); // not sure what this is
  415. WritePropInt(mScene, p, "CurrentTimeMarker", -1);
  416. gs.AddChild(p);
  417. gs.Dump(outfile, binary, 0);
  418. }
  419. void FBXExporter::WriteDocuments ()
  420. {
  421. if (!binary) {
  422. WriteAsciiSectionHeader("Documents Description");
  423. }
  424. // not sure what the use of multiple documents would be,
  425. // or whether any end-application supports it
  426. FBX::Node docs("Documents");
  427. docs.AddChild("Count", int32_t(1));
  428. FBX::Node doc("Document");
  429. // generate uid
  430. int64_t uid = generate_uid();
  431. doc.AddProperties(uid, "", "Scene");
  432. FBX::Node p("Properties70");
  433. p.AddP70("SourceObject", "object", "", ""); // what is this even for?
  434. p.AddP70string("ActiveAnimStackName", ""); // should do this properly?
  435. doc.AddChild(p);
  436. // UID for root node in scene hierarchy.
  437. // always set to 0 in the case of a single document.
  438. // not sure what happens if more than one document exists,
  439. // but that won't matter to us as we're exporting a single scene.
  440. doc.AddChild("RootNode", int64_t(0));
  441. docs.AddChild(doc);
  442. docs.Dump(outfile, binary, 0);
  443. }
  444. void FBXExporter::WriteReferences ()
  445. {
  446. if (!binary) {
  447. WriteAsciiSectionHeader("Document References");
  448. }
  449. // always empty for now.
  450. // not really sure what this is for.
  451. FBX::Node n("References");
  452. n.force_has_children = true;
  453. n.Dump(outfile, binary, 0);
  454. }
  455. // ---------------------------------------------------------------
  456. // some internal helper functions used for writing the definitions
  457. // (before any actual data is written)
  458. // ---------------------------------------------------------------
  459. size_t count_nodes(const aiNode* n, const aiNode* root) {
  460. size_t count;
  461. if (n == root) {
  462. count = n->mNumMeshes; // (not counting root node)
  463. } else if (n->mNumMeshes > 1) {
  464. count = n->mNumMeshes + 1;
  465. } else {
  466. count = 1;
  467. }
  468. for (size_t i = 0; i < n->mNumChildren; ++i) {
  469. count += count_nodes(n->mChildren[i], root);
  470. }
  471. return count;
  472. }
  473. bool has_phong_mat(const aiScene* scene)
  474. {
  475. // just search for any material with a shininess exponent
  476. for (size_t i = 0; i < scene->mNumMaterials; ++i) {
  477. aiMaterial* mat = scene->mMaterials[i];
  478. float shininess = 0;
  479. mat->Get(AI_MATKEY_SHININESS, shininess);
  480. if (shininess > 0) {
  481. return true;
  482. }
  483. }
  484. return false;
  485. }
  486. size_t count_images(const aiScene* scene) {
  487. std::unordered_set<std::string> images;
  488. aiString texpath;
  489. for (size_t i = 0; i < scene->mNumMaterials; ++i) {
  490. aiMaterial* mat = scene->mMaterials[i];
  491. for (
  492. size_t tt = aiTextureType_DIFFUSE;
  493. tt < aiTextureType_UNKNOWN;
  494. ++tt
  495. ){
  496. const aiTextureType textype = static_cast<aiTextureType>(tt);
  497. const size_t texcount = mat->GetTextureCount(textype);
  498. for (unsigned int j = 0; j < texcount; ++j) {
  499. mat->GetTexture(textype, j, &texpath);
  500. images.insert(std::string(texpath.C_Str()));
  501. }
  502. }
  503. }
  504. return images.size();
  505. }
  506. size_t count_textures(const aiScene* scene) {
  507. size_t count = 0;
  508. for (size_t i = 0; i < scene->mNumMaterials; ++i) {
  509. aiMaterial* mat = scene->mMaterials[i];
  510. for (
  511. size_t tt = aiTextureType_DIFFUSE;
  512. tt < aiTextureType_UNKNOWN;
  513. ++tt
  514. ){
  515. // TODO: handle layered textures
  516. if (mat->GetTextureCount(static_cast<aiTextureType>(tt)) > 0) {
  517. count += 1;
  518. }
  519. }
  520. }
  521. return count;
  522. }
  523. size_t count_deformers(const aiScene* scene) {
  524. size_t count = 0;
  525. for (size_t i = 0; i < scene->mNumMeshes; ++i) {
  526. const size_t n = scene->mMeshes[i]->mNumBones;
  527. if (n) {
  528. // 1 main deformer, 1 subdeformer per bone
  529. count += n + 1;
  530. }
  531. }
  532. return count;
  533. }
  534. void FBXExporter::WriteDefinitions ()
  535. {
  536. // basically this is just bookkeeping:
  537. // determining how many of each type of object there are
  538. // and specifying the base properties to use when otherwise unspecified.
  539. // ascii section header
  540. if (!binary) {
  541. WriteAsciiSectionHeader("Object definitions");
  542. }
  543. // we need to count the objects
  544. int32_t count;
  545. int32_t total_count = 0;
  546. // and store them
  547. std::vector<FBX::Node> object_nodes;
  548. FBX::Node n, pt, p;
  549. // GlobalSettings
  550. // this seems to always be here in Maya exports
  551. n = FBX::Node("ObjectType", "GlobalSettings");
  552. count = 1;
  553. n.AddChild("Count", count);
  554. object_nodes.push_back(n);
  555. total_count += count;
  556. // AnimationStack / FbxAnimStack
  557. // this seems to always be here in Maya exports,
  558. // but no harm seems to come of leaving it out.
  559. count = mScene->mNumAnimations;
  560. if (count) {
  561. n = FBX::Node("ObjectType", "AnimationStack");
  562. n.AddChild("Count", count);
  563. pt = FBX::Node("PropertyTemplate", "FbxAnimStack");
  564. p = FBX::Node("Properties70");
  565. p.AddP70string("Description", "");
  566. p.AddP70time("LocalStart", 0);
  567. p.AddP70time("LocalStop", 0);
  568. p.AddP70time("ReferenceStart", 0);
  569. p.AddP70time("ReferenceStop", 0);
  570. pt.AddChild(p);
  571. n.AddChild(pt);
  572. object_nodes.push_back(n);
  573. total_count += count;
  574. }
  575. // AnimationLayer / FbxAnimLayer
  576. // this seems to always be here in Maya exports,
  577. // but no harm seems to come of leaving it out.
  578. // Assimp doesn't support animation layers,
  579. // so there will be one per aiAnimation
  580. count = mScene->mNumAnimations;
  581. if (count) {
  582. n = FBX::Node("ObjectType", "AnimationLayer");
  583. n.AddChild("Count", count);
  584. pt = FBX::Node("PropertyTemplate", "FBXAnimLayer");
  585. p = FBX::Node("Properties70");
  586. p.AddP70("Weight", "Number", "", "A", double(100));
  587. p.AddP70bool("Mute", false);
  588. p.AddP70bool("Solo", false);
  589. p.AddP70bool("Lock", false);
  590. p.AddP70color("Color", 0.8, 0.8, 0.8);
  591. p.AddP70("BlendMode", "enum", "", "", int32_t(0));
  592. p.AddP70("RotationAccumulationMode", "enum", "", "", int32_t(0));
  593. p.AddP70("ScaleAccumulationMode", "enum", "", "", int32_t(0));
  594. p.AddP70("BlendModeBypass", "ULongLong", "", "", int64_t(0));
  595. pt.AddChild(p);
  596. n.AddChild(pt);
  597. object_nodes.push_back(n);
  598. total_count += count;
  599. }
  600. // NodeAttribute
  601. // this is completely absurd.
  602. // there can only be one "NodeAttribute" template,
  603. // but FbxSkeleton, FbxCamera, FbxLight all are "NodeAttributes".
  604. // so if only one exists we should set the template for that,
  605. // otherwise... we just pick one :/.
  606. // the others have to set all their properties every instance,
  607. // because there's no template.
  608. count = 1; // TODO: select properly
  609. if (count) {
  610. // FbxSkeleton
  611. n = FBX::Node("ObjectType", "NodeAttribute");
  612. n.AddChild("Count", count);
  613. pt = FBX::Node("PropertyTemplate", "FbxSkeleton");
  614. p = FBX::Node("Properties70");
  615. p.AddP70color("Color", 0.8, 0.8, 0.8);
  616. p.AddP70double("Size", 33.333333333333);
  617. p.AddP70("LimbLength", "double", "Number", "H", double(1));
  618. // note: not sure what the "H" flag is for - hidden?
  619. pt.AddChild(p);
  620. n.AddChild(pt);
  621. object_nodes.push_back(n);
  622. total_count += count;
  623. }
  624. // Model / FbxNode
  625. // <~~ node hierarchy
  626. count = int32_t(count_nodes(mScene->mRootNode, mScene->mRootNode));
  627. if (count) {
  628. n = FBX::Node("ObjectType", "Model");
  629. n.AddChild("Count", count);
  630. pt = FBX::Node("PropertyTemplate", "FbxNode");
  631. p = FBX::Node("Properties70");
  632. p.AddP70enum("QuaternionInterpolate", 0);
  633. p.AddP70vector("RotationOffset", 0.0, 0.0, 0.0);
  634. p.AddP70vector("RotationPivot", 0.0, 0.0, 0.0);
  635. p.AddP70vector("ScalingOffset", 0.0, 0.0, 0.0);
  636. p.AddP70vector("ScalingPivot", 0.0, 0.0, 0.0);
  637. p.AddP70bool("TranslationActive", false);
  638. p.AddP70vector("TranslationMin", 0.0, 0.0, 0.0);
  639. p.AddP70vector("TranslationMax", 0.0, 0.0, 0.0);
  640. p.AddP70bool("TranslationMinX", false);
  641. p.AddP70bool("TranslationMinY", false);
  642. p.AddP70bool("TranslationMinZ", false);
  643. p.AddP70bool("TranslationMaxX", false);
  644. p.AddP70bool("TranslationMaxY", false);
  645. p.AddP70bool("TranslationMaxZ", false);
  646. p.AddP70enum("RotationOrder", 0);
  647. p.AddP70bool("RotationSpaceForLimitOnly", false);
  648. p.AddP70double("RotationStiffnessX", 0.0);
  649. p.AddP70double("RotationStiffnessY", 0.0);
  650. p.AddP70double("RotationStiffnessZ", 0.0);
  651. p.AddP70double("AxisLen", 10.0);
  652. p.AddP70vector("PreRotation", 0.0, 0.0, 0.0);
  653. p.AddP70vector("PostRotation", 0.0, 0.0, 0.0);
  654. p.AddP70bool("RotationActive", false);
  655. p.AddP70vector("RotationMin", 0.0, 0.0, 0.0);
  656. p.AddP70vector("RotationMax", 0.0, 0.0, 0.0);
  657. p.AddP70bool("RotationMinX", false);
  658. p.AddP70bool("RotationMinY", false);
  659. p.AddP70bool("RotationMinZ", false);
  660. p.AddP70bool("RotationMaxX", false);
  661. p.AddP70bool("RotationMaxY", false);
  662. p.AddP70bool("RotationMaxZ", false);
  663. p.AddP70enum("InheritType", 0);
  664. p.AddP70bool("ScalingActive", false);
  665. p.AddP70vector("ScalingMin", 0.0, 0.0, 0.0);
  666. p.AddP70vector("ScalingMax", 1.0, 1.0, 1.0);
  667. p.AddP70bool("ScalingMinX", false);
  668. p.AddP70bool("ScalingMinY", false);
  669. p.AddP70bool("ScalingMinZ", false);
  670. p.AddP70bool("ScalingMaxX", false);
  671. p.AddP70bool("ScalingMaxY", false);
  672. p.AddP70bool("ScalingMaxZ", false);
  673. p.AddP70vector("GeometricTranslation", 0.0, 0.0, 0.0);
  674. p.AddP70vector("GeometricRotation", 0.0, 0.0, 0.0);
  675. p.AddP70vector("GeometricScaling", 1.0, 1.0, 1.0);
  676. p.AddP70double("MinDampRangeX", 0.0);
  677. p.AddP70double("MinDampRangeY", 0.0);
  678. p.AddP70double("MinDampRangeZ", 0.0);
  679. p.AddP70double("MaxDampRangeX", 0.0);
  680. p.AddP70double("MaxDampRangeY", 0.0);
  681. p.AddP70double("MaxDampRangeZ", 0.0);
  682. p.AddP70double("MinDampStrengthX", 0.0);
  683. p.AddP70double("MinDampStrengthY", 0.0);
  684. p.AddP70double("MinDampStrengthZ", 0.0);
  685. p.AddP70double("MaxDampStrengthX", 0.0);
  686. p.AddP70double("MaxDampStrengthY", 0.0);
  687. p.AddP70double("MaxDampStrengthZ", 0.0);
  688. p.AddP70double("PreferedAngleX", 0.0);
  689. p.AddP70double("PreferedAngleY", 0.0);
  690. p.AddP70double("PreferedAngleZ", 0.0);
  691. p.AddP70("LookAtProperty", "object", "", "");
  692. p.AddP70("UpVectorProperty", "object", "", "");
  693. p.AddP70bool("Show", true);
  694. p.AddP70bool("NegativePercentShapeSupport", true);
  695. p.AddP70int("DefaultAttributeIndex", -1);
  696. p.AddP70bool("Freeze", false);
  697. p.AddP70bool("LODBox", false);
  698. p.AddP70(
  699. "Lcl Translation", "Lcl Translation", "", "A",
  700. double(0), double(0), double(0)
  701. );
  702. p.AddP70(
  703. "Lcl Rotation", "Lcl Rotation", "", "A",
  704. double(0), double(0), double(0)
  705. );
  706. p.AddP70(
  707. "Lcl Scaling", "Lcl Scaling", "", "A",
  708. double(1), double(1), double(1)
  709. );
  710. p.AddP70("Visibility", "Visibility", "", "A", double(1));
  711. p.AddP70(
  712. "Visibility Inheritance", "Visibility Inheritance", "", "",
  713. int32_t(1)
  714. );
  715. pt.AddChild(p);
  716. n.AddChild(pt);
  717. object_nodes.push_back(n);
  718. total_count += count;
  719. }
  720. // Geometry / FbxMesh
  721. // <~~ aiMesh
  722. count = mScene->mNumMeshes;
  723. // Blendshapes are considered Geometry
  724. int32_t bsDeformerCount=0;
  725. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  726. aiMesh* m = mScene->mMeshes[mi];
  727. if (m->mNumAnimMeshes > 0) {
  728. count+=m->mNumAnimMeshes;
  729. bsDeformerCount+=m->mNumAnimMeshes; // One deformer per blendshape
  730. bsDeformerCount++; // Plus one master blendshape deformer
  731. }
  732. }
  733. if (count) {
  734. n = FBX::Node("ObjectType", "Geometry");
  735. n.AddChild("Count", count);
  736. pt = FBX::Node("PropertyTemplate", "FbxMesh");
  737. p = FBX::Node("Properties70");
  738. p.AddP70color("Color", 0, 0, 0);
  739. p.AddP70vector("BBoxMin", 0, 0, 0);
  740. p.AddP70vector("BBoxMax", 0, 0, 0);
  741. p.AddP70bool("Primary Visibility", true);
  742. p.AddP70bool("Casts Shadows", true);
  743. p.AddP70bool("Receive Shadows", true);
  744. pt.AddChild(p);
  745. n.AddChild(pt);
  746. object_nodes.push_back(n);
  747. total_count += count;
  748. }
  749. // Material / FbxSurfacePhong, FbxSurfaceLambert, FbxSurfaceMaterial
  750. // <~~ aiMaterial
  751. // basically if there's any phong material this is defined as phong,
  752. // and otherwise lambert.
  753. // More complex materials cause a bare-bones FbxSurfaceMaterial definition
  754. // and are treated specially, as they're not really supported by FBX.
  755. // TODO: support Maya's Stingray PBS material
  756. count = mScene->mNumMaterials;
  757. if (count) {
  758. bool has_phong = has_phong_mat(mScene);
  759. n = FBX::Node("ObjectType", "Material");
  760. n.AddChild("Count", count);
  761. pt = FBX::Node("PropertyTemplate");
  762. if (has_phong) {
  763. pt.AddProperty("FbxSurfacePhong");
  764. } else {
  765. pt.AddProperty("FbxSurfaceLambert");
  766. }
  767. p = FBX::Node("Properties70");
  768. if (has_phong) {
  769. p.AddP70string("ShadingModel", "Phong");
  770. } else {
  771. p.AddP70string("ShadingModel", "Lambert");
  772. }
  773. p.AddP70bool("MultiLayer", false);
  774. p.AddP70colorA("EmissiveColor", 0.0, 0.0, 0.0);
  775. p.AddP70numberA("EmissiveFactor", 1.0);
  776. p.AddP70colorA("AmbientColor", 0.2, 0.2, 0.2);
  777. p.AddP70numberA("AmbientFactor", 1.0);
  778. p.AddP70colorA("DiffuseColor", 0.8, 0.8, 0.8);
  779. p.AddP70numberA("DiffuseFactor", 1.0);
  780. p.AddP70vector("Bump", 0.0, 0.0, 0.0);
  781. p.AddP70vector("NormalMap", 0.0, 0.0, 0.0);
  782. p.AddP70double("BumpFactor", 1.0);
  783. p.AddP70colorA("TransparentColor", 0.0, 0.0, 0.0);
  784. p.AddP70numberA("TransparencyFactor", 0.0);
  785. p.AddP70color("DisplacementColor", 0.0, 0.0, 0.0);
  786. p.AddP70double("DisplacementFactor", 1.0);
  787. p.AddP70color("VectorDisplacementColor", 0.0, 0.0, 0.0);
  788. p.AddP70double("VectorDisplacementFactor", 1.0);
  789. if (has_phong) {
  790. p.AddP70colorA("SpecularColor", 0.2, 0.2, 0.2);
  791. p.AddP70numberA("SpecularFactor", 1.0);
  792. p.AddP70numberA("ShininessExponent", 20.0);
  793. p.AddP70colorA("ReflectionColor", 0.0, 0.0, 0.0);
  794. p.AddP70numberA("ReflectionFactor", 1.0);
  795. }
  796. pt.AddChild(p);
  797. n.AddChild(pt);
  798. object_nodes.push_back(n);
  799. total_count += count;
  800. }
  801. // Video / FbxVideo
  802. // one for each image file.
  803. count = int32_t(count_images(mScene));
  804. if (count) {
  805. n = FBX::Node("ObjectType", "Video");
  806. n.AddChild("Count", count);
  807. pt = FBX::Node("PropertyTemplate", "FbxVideo");
  808. p = FBX::Node("Properties70");
  809. p.AddP70bool("ImageSequence", false);
  810. p.AddP70int("ImageSequenceOffset", 0);
  811. p.AddP70double("FrameRate", 0.0);
  812. p.AddP70int("LastFrame", 0);
  813. p.AddP70int("Width", 0);
  814. p.AddP70int("Height", 0);
  815. p.AddP70("Path", "KString", "XRefUrl", "", "");
  816. p.AddP70int("StartFrame", 0);
  817. p.AddP70int("StopFrame", 0);
  818. p.AddP70double("PlaySpeed", 0.0);
  819. p.AddP70time("Offset", 0);
  820. p.AddP70enum("InterlaceMode", 0);
  821. p.AddP70bool("FreeRunning", false);
  822. p.AddP70bool("Loop", false);
  823. p.AddP70enum("AccessMode", 0);
  824. pt.AddChild(p);
  825. n.AddChild(pt);
  826. object_nodes.push_back(n);
  827. total_count += count;
  828. }
  829. // Texture / FbxFileTexture
  830. // <~~ aiTexture
  831. count = int32_t(count_textures(mScene));
  832. if (count) {
  833. n = FBX::Node("ObjectType", "Texture");
  834. n.AddChild("Count", count);
  835. pt = FBX::Node("PropertyTemplate", "FbxFileTexture");
  836. p = FBX::Node("Properties70");
  837. p.AddP70enum("TextureTypeUse", 0);
  838. p.AddP70numberA("Texture alpha", 1.0);
  839. p.AddP70enum("CurrentMappingType", 0);
  840. p.AddP70enum("WrapModeU", 0);
  841. p.AddP70enum("WrapModeV", 0);
  842. p.AddP70bool("UVSwap", false);
  843. p.AddP70bool("PremultiplyAlpha", true);
  844. p.AddP70vectorA("Translation", 0.0, 0.0, 0.0);
  845. p.AddP70vectorA("Rotation", 0.0, 0.0, 0.0);
  846. p.AddP70vectorA("Scaling", 1.0, 1.0, 1.0);
  847. p.AddP70vector("TextureRotationPivot", 0.0, 0.0, 0.0);
  848. p.AddP70vector("TextureScalingPivot", 0.0, 0.0, 0.0);
  849. p.AddP70enum("CurrentTextureBlendMode", 1);
  850. p.AddP70string("UVSet", "default");
  851. p.AddP70bool("UseMaterial", false);
  852. p.AddP70bool("UseMipMap", false);
  853. pt.AddChild(p);
  854. n.AddChild(pt);
  855. object_nodes.push_back(n);
  856. total_count += count;
  857. }
  858. // AnimationCurveNode / FbxAnimCurveNode
  859. count = mScene->mNumAnimations * 3;
  860. if (count) {
  861. n = FBX::Node("ObjectType", "AnimationCurveNode");
  862. n.AddChild("Count", count);
  863. pt = FBX::Node("PropertyTemplate", "FbxAnimCurveNode");
  864. p = FBX::Node("Properties70");
  865. p.AddP70("d", "Compound", "", "");
  866. pt.AddChild(p);
  867. n.AddChild(pt);
  868. object_nodes.push_back(n);
  869. total_count += count;
  870. }
  871. // AnimationCurve / FbxAnimCurve
  872. count = mScene->mNumAnimations * 9;
  873. if (count) {
  874. n = FBX::Node("ObjectType", "AnimationCurve");
  875. n.AddChild("Count", count);
  876. object_nodes.push_back(n);
  877. total_count += count;
  878. }
  879. // Pose
  880. count = 0;
  881. for (size_t i = 0; i < mScene->mNumMeshes; ++i) {
  882. aiMesh* mesh = mScene->mMeshes[i];
  883. if (mesh->HasBones()) { ++count; }
  884. }
  885. if (count) {
  886. n = FBX::Node("ObjectType", "Pose");
  887. n.AddChild("Count", count);
  888. object_nodes.push_back(n);
  889. total_count += count;
  890. }
  891. // Deformer
  892. count = int32_t(count_deformers(mScene))+bsDeformerCount;
  893. if (count) {
  894. n = FBX::Node("ObjectType", "Deformer");
  895. n.AddChild("Count", count);
  896. object_nodes.push_back(n);
  897. total_count += count;
  898. }
  899. // (template)
  900. count = 0;
  901. if (count) {
  902. n = FBX::Node("ObjectType", "");
  903. n.AddChild("Count", count);
  904. pt = FBX::Node("PropertyTemplate", "");
  905. p = FBX::Node("Properties70");
  906. pt.AddChild(p);
  907. n.AddChild(pt);
  908. object_nodes.push_back(n);
  909. total_count += count;
  910. }
  911. // now write it all
  912. FBX::Node defs("Definitions");
  913. defs.AddChild("Version", int32_t(100));
  914. defs.AddChild("Count", int32_t(total_count));
  915. for (auto &on : object_nodes) {
  916. defs.AddChild(on);
  917. }
  918. defs.Dump(outfile, binary, 0);
  919. }
  920. // -------------------------------------------------------------------
  921. // some internal helper functions used for writing the objects section
  922. // (which holds the actual data)
  923. // -------------------------------------------------------------------
  924. aiNode* get_node_for_mesh(unsigned int meshIndex, aiNode* node)
  925. {
  926. for (size_t i = 0; i < node->mNumMeshes; ++i) {
  927. if (node->mMeshes[i] == meshIndex) {
  928. return node;
  929. }
  930. }
  931. for (size_t i = 0; i < node->mNumChildren; ++i) {
  932. aiNode* ret = get_node_for_mesh(meshIndex, node->mChildren[i]);
  933. if (ret) { return ret; }
  934. }
  935. return nullptr;
  936. }
  937. aiMatrix4x4 get_world_transform(const aiNode* node, const aiScene* scene)
  938. {
  939. std::vector<const aiNode*> node_chain;
  940. while (node != scene->mRootNode) {
  941. node_chain.push_back(node);
  942. node = node->mParent;
  943. }
  944. aiMatrix4x4 transform;
  945. for (auto n = node_chain.rbegin(); n != node_chain.rend(); ++n) {
  946. transform *= (*n)->mTransformation;
  947. }
  948. return transform;
  949. }
  950. inline int64_t to_ktime(double ticks, const aiAnimation* anim) {
  951. if (FP_ZERO == std::fpclassify(anim->mTicksPerSecond)) {
  952. return static_cast<int64_t>(ticks) * FBX::SECOND;
  953. }
  954. return (static_cast<int64_t>(ticks / anim->mTicksPerSecond)) * FBX::SECOND;
  955. }
  956. inline int64_t to_ktime(double time) {
  957. return (static_cast<int64_t>(time * FBX::SECOND));
  958. }
  959. void FBXExporter::WriteObjects ()
  960. {
  961. if (!binary) {
  962. WriteAsciiSectionHeader("Object properties");
  963. }
  964. // numbers should match those given in definitions! make sure to check
  965. StreamWriterLE outstream(outfile);
  966. FBX::Node object_node("Objects");
  967. int indent = 0;
  968. object_node.Begin(outstream, binary, indent);
  969. object_node.EndProperties(outstream, binary, indent);
  970. object_node.BeginChildren(outstream, binary, indent);
  971. bool bJoinIdenticalVertices = mProperties->GetPropertyBool("bJoinIdenticalVertices", true);
  972. std::vector<std::vector<int32_t>> vVertexIndice;//save vertex_indices as it is needed later
  973. // geometry (aiMesh)
  974. mesh_uids.clear();
  975. indent = 1;
  976. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  977. // it's all about this mesh
  978. aiMesh* m = mScene->mMeshes[mi];
  979. // start the node record
  980. FBX::Node n("Geometry");
  981. int64_t uid = generate_uid();
  982. mesh_uids.push_back(uid);
  983. n.AddProperty(uid);
  984. n.AddProperty(FBX::SEPARATOR + "Geometry");
  985. n.AddProperty("Mesh");
  986. n.Begin(outstream, binary, indent);
  987. n.DumpProperties(outstream, binary, indent);
  988. n.EndProperties(outstream, binary, indent);
  989. n.BeginChildren(outstream, binary, indent);
  990. indent = 2;
  991. // output vertex data - each vertex should be unique (probably)
  992. std::vector<double> flattened_vertices;
  993. // index of original vertex in vertex data vector
  994. std::vector<int32_t> vertex_indices;
  995. // map of vertex value to its index in the data vector
  996. std::map<aiVector3D,size_t> index_by_vertex_value;
  997. if(bJoinIdenticalVertices){
  998. int32_t index = 0;
  999. for (size_t vi = 0; vi < m->mNumVertices; ++vi) {
  1000. aiVector3D vtx = m->mVertices[vi];
  1001. auto elem = index_by_vertex_value.find(vtx);
  1002. if (elem == index_by_vertex_value.end()) {
  1003. vertex_indices.push_back(index);
  1004. index_by_vertex_value[vtx] = index;
  1005. flattened_vertices.push_back(vtx[0]);
  1006. flattened_vertices.push_back(vtx[1]);
  1007. flattened_vertices.push_back(vtx[2]);
  1008. ++index;
  1009. } else {
  1010. vertex_indices.push_back(int32_t(elem->second));
  1011. }
  1012. }
  1013. }
  1014. else { // do not join vertex, respect the export flag
  1015. vertex_indices.resize(m->mNumVertices);
  1016. std::iota(vertex_indices.begin(), vertex_indices.end(), 0);
  1017. for(unsigned int v = 0; v < m->mNumVertices; ++ v) {
  1018. aiVector3D vtx = m->mVertices[v];
  1019. flattened_vertices.push_back(vtx.x);
  1020. flattened_vertices.push_back(vtx.y);
  1021. flattened_vertices.push_back(vtx.z);
  1022. }
  1023. }
  1024. vVertexIndice.push_back(vertex_indices);
  1025. FBX::Node::WritePropertyNode(
  1026. "Vertices", flattened_vertices, outstream, binary, indent
  1027. );
  1028. // output polygon data as a flattened array of vertex indices.
  1029. // the last vertex index of each polygon is negated and - 1
  1030. std::vector<int32_t> polygon_data;
  1031. for (size_t fi = 0; fi < m->mNumFaces; ++fi) {
  1032. const aiFace &f = m->mFaces[fi];
  1033. for (size_t pvi = 0; pvi < f.mNumIndices - 1; ++pvi) {
  1034. polygon_data.push_back(vertex_indices[f.mIndices[pvi]]);
  1035. }
  1036. polygon_data.push_back(
  1037. -1 - vertex_indices[f.mIndices[f.mNumIndices-1]]
  1038. );
  1039. }
  1040. FBX::Node::WritePropertyNode(
  1041. "PolygonVertexIndex", polygon_data, outstream, binary, indent
  1042. );
  1043. // here could be edges but they're insane.
  1044. // it's optional anyway, so let's ignore it.
  1045. FBX::Node::WritePropertyNode(
  1046. "GeometryVersion", int32_t(124), outstream, binary, indent
  1047. );
  1048. // normals, if any
  1049. if (m->HasNormals()) {
  1050. FBX::Node normals("LayerElementNormal", int32_t(0));
  1051. normals.Begin(outstream, binary, indent);
  1052. normals.DumpProperties(outstream, binary, indent);
  1053. normals.EndProperties(outstream, binary, indent);
  1054. normals.BeginChildren(outstream, binary, indent);
  1055. indent = 3;
  1056. FBX::Node::WritePropertyNode(
  1057. "Version", int32_t(101), outstream, binary, indent
  1058. );
  1059. FBX::Node::WritePropertyNode(
  1060. "Name", "", outstream, binary, indent
  1061. );
  1062. FBX::Node::WritePropertyNode(
  1063. "MappingInformationType", "ByPolygonVertex",
  1064. outstream, binary, indent
  1065. );
  1066. // TODO: vertex-normals or indexed normals when appropriate
  1067. FBX::Node::WritePropertyNode(
  1068. "ReferenceInformationType", "Direct",
  1069. outstream, binary, indent
  1070. );
  1071. std::vector<double> normal_data;
  1072. normal_data.reserve(3 * polygon_data.size());
  1073. for (size_t fi = 0; fi < m->mNumFaces; ++fi) {
  1074. const aiFace &f = m->mFaces[fi];
  1075. for (size_t pvi = 0; pvi < f.mNumIndices; ++pvi) {
  1076. const aiVector3D &curN = m->mNormals[f.mIndices[pvi]];
  1077. normal_data.push_back(curN.x);
  1078. normal_data.push_back(curN.y);
  1079. normal_data.push_back(curN.z);
  1080. }
  1081. }
  1082. FBX::Node::WritePropertyNode(
  1083. "Normals", normal_data, outstream, binary, indent
  1084. );
  1085. // note: version 102 has a NormalsW also... not sure what it is,
  1086. // so we can stick with version 101 for now.
  1087. indent = 2;
  1088. normals.End(outstream, binary, indent, true);
  1089. }
  1090. // colors, if any
  1091. // TODO only one color channel currently
  1092. const int32_t colorChannelIndex = 0;
  1093. if (m->HasVertexColors(colorChannelIndex)) {
  1094. FBX::Node vertexcolors("LayerElementColor", int32_t(colorChannelIndex));
  1095. vertexcolors.Begin(outstream, binary, indent);
  1096. vertexcolors.DumpProperties(outstream, binary, indent);
  1097. vertexcolors.EndProperties(outstream, binary, indent);
  1098. vertexcolors.BeginChildren(outstream, binary, indent);
  1099. indent = 3;
  1100. FBX::Node::WritePropertyNode(
  1101. "Version", int32_t(101), outstream, binary, indent
  1102. );
  1103. char layerName[8];
  1104. snprintf(layerName, sizeof(layerName), "COLOR_%d", colorChannelIndex);
  1105. FBX::Node::WritePropertyNode(
  1106. "Name", (const char*)layerName, outstream, binary, indent
  1107. );
  1108. FBX::Node::WritePropertyNode(
  1109. "MappingInformationType", "ByPolygonVertex",
  1110. outstream, binary, indent
  1111. );
  1112. FBX::Node::WritePropertyNode(
  1113. "ReferenceInformationType", "Direct",
  1114. outstream, binary, indent
  1115. );
  1116. std::vector<double> color_data;
  1117. color_data.reserve(4 * polygon_data.size());
  1118. for (size_t fi = 0; fi < m->mNumFaces; ++fi) {
  1119. const aiFace &f = m->mFaces[fi];
  1120. for (size_t pvi = 0; pvi < f.mNumIndices; ++pvi) {
  1121. const aiColor4D &c = m->mColors[colorChannelIndex][f.mIndices[pvi]];
  1122. color_data.push_back(c.r);
  1123. color_data.push_back(c.g);
  1124. color_data.push_back(c.b);
  1125. color_data.push_back(c.a);
  1126. }
  1127. }
  1128. FBX::Node::WritePropertyNode(
  1129. "Colors", color_data, outstream, binary, indent
  1130. );
  1131. indent = 2;
  1132. vertexcolors.End(outstream, binary, indent, true);
  1133. }
  1134. // uvs, if any
  1135. for (size_t uvi = 0; uvi < m->GetNumUVChannels(); ++uvi) {
  1136. if (m->mNumUVComponents[uvi] > 2) {
  1137. // FBX only supports 2-channel UV maps...
  1138. // or at least i'm not sure how to indicate a different number
  1139. std::stringstream err;
  1140. err << "Only 2-channel UV maps supported by FBX,";
  1141. err << " but mesh " << mi;
  1142. if (m->mName.length) {
  1143. err << " (" << m->mName.C_Str() << ")";
  1144. }
  1145. err << " UV map " << uvi;
  1146. err << " has " << m->mNumUVComponents[uvi];
  1147. err << " components! Data will be preserved,";
  1148. err << " but may be incorrectly interpreted on load.";
  1149. ASSIMP_LOG_WARN(err.str());
  1150. }
  1151. FBX::Node uv("LayerElementUV", int32_t(uvi));
  1152. uv.Begin(outstream, binary, indent);
  1153. uv.DumpProperties(outstream, binary, indent);
  1154. uv.EndProperties(outstream, binary, indent);
  1155. uv.BeginChildren(outstream, binary, indent);
  1156. indent = 3;
  1157. FBX::Node::WritePropertyNode(
  1158. "Version", int32_t(101), outstream, binary, indent
  1159. );
  1160. // it doesn't seem like assimp keeps the uv map name,
  1161. // so just leave it blank.
  1162. FBX::Node::WritePropertyNode(
  1163. "Name", "", outstream, binary, indent
  1164. );
  1165. FBX::Node::WritePropertyNode(
  1166. "MappingInformationType", "ByPolygonVertex",
  1167. outstream, binary, indent
  1168. );
  1169. FBX::Node::WritePropertyNode(
  1170. "ReferenceInformationType", "IndexToDirect",
  1171. outstream, binary, indent
  1172. );
  1173. std::vector<double> uv_data;
  1174. std::vector<int32_t> uv_indices;
  1175. std::map<aiVector3D,int32_t> index_by_uv;
  1176. int32_t index = 0;
  1177. for (size_t fi = 0; fi < m->mNumFaces; ++fi) {
  1178. const aiFace &f = m->mFaces[fi];
  1179. for (size_t pvi = 0; pvi < f.mNumIndices; ++pvi) {
  1180. const aiVector3D &curUv =
  1181. m->mTextureCoords[uvi][f.mIndices[pvi]];
  1182. auto elem = index_by_uv.find(curUv);
  1183. if (elem == index_by_uv.end()) {
  1184. index_by_uv[curUv] = index;
  1185. uv_indices.push_back(index);
  1186. for (unsigned int x = 0; x < m->mNumUVComponents[uvi]; ++x) {
  1187. uv_data.push_back(curUv[x]);
  1188. }
  1189. ++index;
  1190. } else {
  1191. uv_indices.push_back(elem->second);
  1192. }
  1193. }
  1194. }
  1195. FBX::Node::WritePropertyNode(
  1196. "UV", uv_data, outstream, binary, indent
  1197. );
  1198. FBX::Node::WritePropertyNode(
  1199. "UVIndex", uv_indices, outstream, binary, indent
  1200. );
  1201. indent = 2;
  1202. uv.End(outstream, binary, indent, true);
  1203. }
  1204. // i'm not really sure why this material section exists,
  1205. // as the material is linked via "Connections".
  1206. // it seems to always have the same "0" value.
  1207. FBX::Node mat("LayerElementMaterial", int32_t(0));
  1208. mat.AddChild("Version", int32_t(101));
  1209. mat.AddChild("Name", "");
  1210. mat.AddChild("MappingInformationType", "AllSame");
  1211. mat.AddChild("ReferenceInformationType", "IndexToDirect");
  1212. std::vector<int32_t> mat_indices = {0};
  1213. mat.AddChild("Materials", mat_indices);
  1214. mat.Dump(outstream, binary, indent);
  1215. // finally we have the layer specifications,
  1216. // which select the normals / UV set / etc to use.
  1217. // TODO: handle multiple uv sets correctly?
  1218. FBX::Node layer("Layer", int32_t(0));
  1219. layer.AddChild("Version", int32_t(100));
  1220. FBX::Node le("LayerElement");
  1221. le.AddChild("Type", "LayerElementNormal");
  1222. le.AddChild("TypedIndex", int32_t(0));
  1223. layer.AddChild(le);
  1224. // TODO only 1 color channel currently
  1225. le = FBX::Node("LayerElement");
  1226. le.AddChild("Type", "LayerElementColor");
  1227. le.AddChild("TypedIndex", int32_t(0));
  1228. layer.AddChild(le);
  1229. le = FBX::Node("LayerElement");
  1230. le.AddChild("Type", "LayerElementMaterial");
  1231. le.AddChild("TypedIndex", int32_t(0));
  1232. layer.AddChild(le);
  1233. le = FBX::Node("LayerElement");
  1234. le.AddChild("Type", "LayerElementUV");
  1235. le.AddChild("TypedIndex", int32_t(0));
  1236. layer.AddChild(le);
  1237. layer.Dump(outstream, binary, indent);
  1238. for(unsigned int lr = 1; lr < m->GetNumUVChannels(); ++ lr)
  1239. {
  1240. FBX::Node layerExtra("Layer", int32_t(lr));
  1241. layerExtra.AddChild("Version", int32_t(100));
  1242. FBX::Node leExtra("LayerElement");
  1243. leExtra.AddChild("Type", "LayerElementUV");
  1244. leExtra.AddChild("TypedIndex", int32_t(lr));
  1245. layerExtra.AddChild(leExtra);
  1246. layerExtra.Dump(outstream, binary, indent);
  1247. }
  1248. // finish the node record
  1249. indent = 1;
  1250. n.End(outstream, binary, indent, true);
  1251. }
  1252. // aiMaterial
  1253. material_uids.clear();
  1254. for (size_t i = 0; i < mScene->mNumMaterials; ++i) {
  1255. // it's all about this material
  1256. aiMaterial* m = mScene->mMaterials[i];
  1257. // these are used to receive material data
  1258. ai_real f; aiColor3D c;
  1259. // start the node record
  1260. FBX::Node n("Material");
  1261. int64_t uid = generate_uid();
  1262. material_uids.push_back(uid);
  1263. n.AddProperty(uid);
  1264. aiString name;
  1265. m->Get(AI_MATKEY_NAME, name);
  1266. n.AddProperty(name.C_Str() + FBX::SEPARATOR + "Material");
  1267. n.AddProperty("");
  1268. n.AddChild("Version", int32_t(102));
  1269. f = 0;
  1270. m->Get(AI_MATKEY_SHININESS, f);
  1271. bool phong = (f > 0);
  1272. if (phong) {
  1273. n.AddChild("ShadingModel", "phong");
  1274. } else {
  1275. n.AddChild("ShadingModel", "lambert");
  1276. }
  1277. n.AddChild("MultiLayer", int32_t(0));
  1278. FBX::Node p("Properties70");
  1279. // materials exported using the FBX SDK have two sets of fields.
  1280. // there are the properties specified in the PropertyTemplate,
  1281. // which are those supported by the modernFBX SDK,
  1282. // and an extra set of properties with simpler names.
  1283. // The extra properties are a legacy material system from pre-2009.
  1284. //
  1285. // In the modern system, each property has "color" and "factor".
  1286. // Generally the interpretation of these seems to be
  1287. // that the colour is multiplied by the factor before use,
  1288. // but this is not always clear-cut.
  1289. //
  1290. // Usually assimp only stores the colour,
  1291. // so we can just leave the factors at the default "1.0".
  1292. // first we can export the "standard" properties
  1293. if (m->Get(AI_MATKEY_COLOR_AMBIENT, c) == aiReturn_SUCCESS) {
  1294. p.AddP70colorA("AmbientColor", c.r, c.g, c.b);
  1295. //p.AddP70numberA("AmbientFactor", 1.0);
  1296. }
  1297. if (m->Get(AI_MATKEY_COLOR_DIFFUSE, c) == aiReturn_SUCCESS) {
  1298. p.AddP70colorA("DiffuseColor", c.r, c.g, c.b);
  1299. //p.AddP70numberA("DiffuseFactor", 1.0);
  1300. }
  1301. if (m->Get(AI_MATKEY_COLOR_TRANSPARENT, c) == aiReturn_SUCCESS) {
  1302. // "TransparentColor" / "TransparencyFactor"...
  1303. // thanks FBX, for your insightful interpretation of consistency
  1304. p.AddP70colorA("TransparentColor", c.r, c.g, c.b);
  1305. // TransparencyFactor defaults to 0.0, so set it to 1.0.
  1306. // note: Maya always sets this to 1.0,
  1307. // so we can't use it sensibly as "Opacity".
  1308. // In stead we rely on the legacy "Opacity" value, below.
  1309. // Blender also relies on "Opacity" not "TransparencyFactor",
  1310. // probably for a similar reason.
  1311. p.AddP70numberA("TransparencyFactor", 1.0);
  1312. }
  1313. if (m->Get(AI_MATKEY_COLOR_REFLECTIVE, c) == aiReturn_SUCCESS) {
  1314. p.AddP70colorA("ReflectionColor", c.r, c.g, c.b);
  1315. }
  1316. if (m->Get(AI_MATKEY_REFLECTIVITY, f) == aiReturn_SUCCESS) {
  1317. p.AddP70numberA("ReflectionFactor", f);
  1318. }
  1319. if (phong) {
  1320. if (m->Get(AI_MATKEY_COLOR_SPECULAR, c) == aiReturn_SUCCESS) {
  1321. p.AddP70colorA("SpecularColor", c.r, c.g, c.b);
  1322. }
  1323. if (m->Get(AI_MATKEY_SHININESS_STRENGTH, f) == aiReturn_SUCCESS) {
  1324. p.AddP70numberA("ShininessFactor", f);
  1325. }
  1326. if (m->Get(AI_MATKEY_SHININESS, f) == aiReturn_SUCCESS) {
  1327. p.AddP70numberA("ShininessExponent", f);
  1328. }
  1329. if (m->Get(AI_MATKEY_REFLECTIVITY, f) == aiReturn_SUCCESS) {
  1330. p.AddP70numberA("ReflectionFactor", f);
  1331. }
  1332. }
  1333. // Now the legacy system.
  1334. // For safety let's include it.
  1335. // thrse values don't exist in the property template,
  1336. // and usually are completely ignored when loading.
  1337. // One notable exception is the "Opacity" property,
  1338. // which Blender uses as (1.0 - alpha).
  1339. c.r = 0.0f; c.g = 0.0f; c.b = 0.0f;
  1340. m->Get(AI_MATKEY_COLOR_EMISSIVE, c);
  1341. p.AddP70vector("Emissive", c.r, c.g, c.b);
  1342. c.r = 0.2f; c.g = 0.2f; c.b = 0.2f;
  1343. m->Get(AI_MATKEY_COLOR_AMBIENT, c);
  1344. p.AddP70vector("Ambient", c.r, c.g, c.b);
  1345. c.r = 0.8f; c.g = 0.8f; c.b = 0.8f;
  1346. m->Get(AI_MATKEY_COLOR_DIFFUSE, c);
  1347. p.AddP70vector("Diffuse", c.r, c.g, c.b);
  1348. // The FBX SDK determines "Opacity" from transparency colour (RGB)
  1349. // and factor (F) as: O = (1.0 - F * ((R + G + B) / 3)).
  1350. // However we actually have an opacity value,
  1351. // so we should take it from AI_MATKEY_OPACITY if possible.
  1352. // It might make more sense to use TransparencyFactor,
  1353. // but Blender actually loads "Opacity" correctly, so let's use it.
  1354. f = 1.0f;
  1355. if (m->Get(AI_MATKEY_COLOR_TRANSPARENT, c) == aiReturn_SUCCESS) {
  1356. f = 1.0f - ((c.r + c.g + c.b) / 3.0f);
  1357. }
  1358. m->Get(AI_MATKEY_OPACITY, f);
  1359. p.AddP70double("Opacity", f);
  1360. if (phong) {
  1361. // specular color is multiplied by shininess_strength
  1362. c.r = 0.2f; c.g = 0.2f; c.b = 0.2f;
  1363. m->Get(AI_MATKEY_COLOR_SPECULAR, c);
  1364. f = 1.0f;
  1365. m->Get(AI_MATKEY_SHININESS_STRENGTH, f);
  1366. p.AddP70vector("Specular", f*c.r, f*c.g, f*c.b);
  1367. f = 20.0f;
  1368. m->Get(AI_MATKEY_SHININESS, f);
  1369. p.AddP70double("Shininess", f);
  1370. // Legacy "Reflectivity" is F*F*((R+G+B)/3),
  1371. // where F is the proportion of light reflected (AKA reflectivity),
  1372. // and RGB is the reflective colour of the material.
  1373. // No idea why, but we might as well set it the same way.
  1374. f = 0.0f;
  1375. m->Get(AI_MATKEY_REFLECTIVITY, f);
  1376. c.r = 1.0f, c.g = 1.0f, c.b = 1.0f;
  1377. m->Get(AI_MATKEY_COLOR_REFLECTIVE, c);
  1378. p.AddP70double("Reflectivity", f*f*((c.r+c.g+c.b)/3.0));
  1379. }
  1380. n.AddChild(p);
  1381. n.Dump(outstream, binary, indent);
  1382. }
  1383. // we need to look up all the images we're using,
  1384. // so we can generate uids, and eliminate duplicates.
  1385. std::map<std::string, int64_t> uid_by_image;
  1386. for (size_t i = 0; i < mScene->mNumMaterials; ++i) {
  1387. aiString texpath;
  1388. aiMaterial* mat = mScene->mMaterials[i];
  1389. for (
  1390. size_t tt = aiTextureType_DIFFUSE;
  1391. tt < aiTextureType_UNKNOWN;
  1392. ++tt
  1393. ){
  1394. const aiTextureType textype = static_cast<aiTextureType>(tt);
  1395. const size_t texcount = mat->GetTextureCount(textype);
  1396. for (size_t j = 0; j < texcount; ++j) {
  1397. mat->GetTexture(textype, (unsigned int)j, &texpath);
  1398. const std::string texstring = texpath.C_Str();
  1399. auto elem = uid_by_image.find(texstring);
  1400. if (elem == uid_by_image.end()) {
  1401. uid_by_image[texstring] = generate_uid();
  1402. }
  1403. }
  1404. }
  1405. }
  1406. // FbxVideo - stores images used by textures.
  1407. for (const auto &it : uid_by_image) {
  1408. FBX::Node n("Video");
  1409. const int64_t& uid = it.second;
  1410. const std::string name = ""; // TODO: ... name???
  1411. n.AddProperties(uid, name + FBX::SEPARATOR + "Video", "Clip");
  1412. n.AddChild("Type", "Clip");
  1413. FBX::Node p("Properties70");
  1414. // TODO: get full path... relative path... etc... ugh...
  1415. // for now just use the same path for everything,
  1416. // and hopefully one of them will work out.
  1417. std::string path = it.first;
  1418. // try get embedded texture
  1419. const aiTexture* embedded_texture = mScene->GetEmbeddedTexture(it.first.c_str());
  1420. if (embedded_texture != nullptr) {
  1421. // change the path (use original filename, if available. If name is empty, concatenate texture index with file extension)
  1422. std::stringstream newPath;
  1423. if (embedded_texture->mFilename.length > 0) {
  1424. newPath << embedded_texture->mFilename.C_Str();
  1425. } else if (embedded_texture->achFormatHint[0]) {
  1426. int texture_index = std::stoi(path.substr(1, path.size() - 1));
  1427. newPath << texture_index << "." << embedded_texture->achFormatHint;
  1428. }
  1429. path = newPath.str();
  1430. // embed the texture
  1431. size_t texture_size = static_cast<size_t>(embedded_texture->mWidth * std::max(embedded_texture->mHeight, 1u));
  1432. if (binary) {
  1433. // embed texture as binary data
  1434. std::vector<uint8_t> tex_data;
  1435. tex_data.resize(texture_size);
  1436. memcpy(&tex_data[0], (char*)embedded_texture->pcData, texture_size);
  1437. n.AddChild("Content", tex_data);
  1438. } else {
  1439. // embed texture in base64 encoding
  1440. std::string encoded_texture = FBX::Util::EncodeBase64((char*)embedded_texture->pcData, texture_size);
  1441. n.AddChild("Content", encoded_texture);
  1442. }
  1443. }
  1444. p.AddP70("Path", "KString", "XRefUrl", "", path);
  1445. n.AddChild(p);
  1446. n.AddChild("UseMipMap", int32_t(0));
  1447. n.AddChild("Filename", path);
  1448. n.AddChild("RelativeFilename", path);
  1449. n.Dump(outstream, binary, indent);
  1450. }
  1451. // Textures
  1452. // referenced by material_index/texture_type pairs.
  1453. std::map<std::pair<size_t,size_t>,int64_t> texture_uids;
  1454. const std::map<aiTextureType,std::string> prop_name_by_tt = {
  1455. {aiTextureType_DIFFUSE, "DiffuseColor"},
  1456. {aiTextureType_SPECULAR, "SpecularColor"},
  1457. {aiTextureType_AMBIENT, "AmbientColor"},
  1458. {aiTextureType_EMISSIVE, "EmissiveColor"},
  1459. {aiTextureType_HEIGHT, "Bump"},
  1460. {aiTextureType_NORMALS, "NormalMap"},
  1461. {aiTextureType_SHININESS, "ShininessExponent"},
  1462. {aiTextureType_OPACITY, "TransparentColor"},
  1463. {aiTextureType_DISPLACEMENT, "DisplacementColor"},
  1464. //{aiTextureType_LIGHTMAP, "???"},
  1465. {aiTextureType_REFLECTION, "ReflectionColor"}
  1466. //{aiTextureType_UNKNOWN, ""}
  1467. };
  1468. for (size_t i = 0; i < mScene->mNumMaterials; ++i) {
  1469. // textures are attached to materials
  1470. aiMaterial* mat = mScene->mMaterials[i];
  1471. int64_t material_uid = material_uids[i];
  1472. for (
  1473. size_t j = aiTextureType_DIFFUSE;
  1474. j < aiTextureType_UNKNOWN;
  1475. ++j
  1476. ) {
  1477. const aiTextureType tt = static_cast<aiTextureType>(j);
  1478. size_t n = mat->GetTextureCount(tt);
  1479. if (n < 1) { // no texture of this type
  1480. continue;
  1481. }
  1482. if (n > 1) {
  1483. // TODO: multilayer textures
  1484. std::stringstream err;
  1485. err << "Multilayer textures not supported (for now),";
  1486. err << " skipping texture type " << j;
  1487. err << " of material " << i;
  1488. ASSIMP_LOG_WARN(err.str());
  1489. }
  1490. // get image path for this (single-image) texture
  1491. aiString tpath;
  1492. if (mat->GetTexture(tt, 0, &tpath) != aiReturn_SUCCESS) {
  1493. std::stringstream err;
  1494. err << "Failed to get texture 0 for texture of type " << tt;
  1495. err << " on material " << i;
  1496. err << ", however GetTextureCount returned 1.";
  1497. throw DeadlyExportError(err.str());
  1498. }
  1499. const std::string texture_path(tpath.C_Str());
  1500. // get connected image uid
  1501. auto elem = uid_by_image.find(texture_path);
  1502. if (elem == uid_by_image.end()) {
  1503. // this should never happen
  1504. std::stringstream err;
  1505. err << "Failed to find video element for texture with path";
  1506. err << " \"" << texture_path << "\"";
  1507. err << ", type " << j << ", material " << i;
  1508. throw DeadlyExportError(err.str());
  1509. }
  1510. const int64_t image_uid = elem->second;
  1511. // get the name of the material property to connect to
  1512. auto elem2 = prop_name_by_tt.find(tt);
  1513. if (elem2 == prop_name_by_tt.end()) {
  1514. // don't know how to handle this type of texture,
  1515. // so skip it.
  1516. std::stringstream err;
  1517. err << "Not sure how to handle texture of type " << j;
  1518. err << " on material " << i;
  1519. err << ", skipping...";
  1520. ASSIMP_LOG_WARN(err.str());
  1521. continue;
  1522. }
  1523. const std::string& prop_name = elem2->second;
  1524. // generate a uid for this texture
  1525. const int64_t texture_uid = generate_uid();
  1526. // link the texture to the material
  1527. connections.emplace_back(
  1528. "C", "OP", texture_uid, material_uid, prop_name
  1529. );
  1530. // link the image data to the texture
  1531. connections.emplace_back("C", "OO", image_uid, texture_uid);
  1532. aiUVTransform trafo;
  1533. unsigned int max = sizeof(aiUVTransform);
  1534. aiGetMaterialFloatArray(mat, AI_MATKEY_UVTRANSFORM(aiTextureType_DIFFUSE, 0), (ai_real *)&trafo, &max);
  1535. // now write the actual texture node
  1536. FBX::Node tnode("Texture");
  1537. // TODO: some way to determine texture name?
  1538. const std::string texture_name = "" + FBX::SEPARATOR + "Texture";
  1539. tnode.AddProperties(texture_uid, texture_name, "");
  1540. // there really doesn't seem to be a better type than this:
  1541. tnode.AddChild("Type", "TextureVideoClip");
  1542. tnode.AddChild("Version", int32_t(202));
  1543. tnode.AddChild("TextureName", texture_name);
  1544. FBX::Node p("Properties70");
  1545. p.AddP70vectorA("Translation", trafo.mTranslation[0], trafo.mTranslation[1], 0.0);
  1546. p.AddP70vectorA("Rotation", 0, 0, trafo.mRotation);
  1547. p.AddP70vectorA("Scaling", trafo.mScaling[0], trafo.mScaling[1], 0.0);
  1548. p.AddP70enum("CurrentTextureBlendMode", 0); // TODO: verify
  1549. //p.AddP70string("UVSet", ""); // TODO: how should this work?
  1550. p.AddP70bool("UseMaterial", true);
  1551. tnode.AddChild(p);
  1552. // can't easily determine which texture path will be correct,
  1553. // so just store what we have in every field.
  1554. // these being incorrect is a common problem with FBX anyway.
  1555. tnode.AddChild("FileName", texture_path);
  1556. tnode.AddChild("RelativeFilename", texture_path);
  1557. tnode.AddChild("ModelUVTranslation", double(0.0), double(0.0));
  1558. tnode.AddChild("ModelUVScaling", double(1.0), double(1.0));
  1559. tnode.AddChild("Texture_Alpha_Source", "None");
  1560. tnode.AddChild(
  1561. "Cropping", int32_t(0), int32_t(0), int32_t(0), int32_t(0)
  1562. );
  1563. tnode.Dump(outstream, binary, indent);
  1564. }
  1565. }
  1566. // Blendshapes, if any
  1567. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1568. const aiMesh* m = mScene->mMeshes[mi];
  1569. if (m->mNumAnimMeshes == 0) {
  1570. continue;
  1571. }
  1572. // make a deformer for this mesh
  1573. int64_t deformer_uid = generate_uid();
  1574. FBX::Node dnode("Deformer");
  1575. dnode.AddProperties(deformer_uid, m->mName.data + FBX::SEPARATOR + "Blendshapes", "BlendShape");
  1576. dnode.AddChild("Version", int32_t(101));
  1577. dnode.Dump(outstream, binary, indent);
  1578. // connect it
  1579. connections.emplace_back("C", "OO", deformer_uid, mesh_uids[mi]);
  1580. std::vector<int32_t> vertex_indices = vVertexIndice[mi];
  1581. for (unsigned int am = 0; am < m->mNumAnimMeshes; ++am) {
  1582. aiAnimMesh *pAnimMesh = m->mAnimMeshes[am];
  1583. std::string blendshape_name = pAnimMesh->mName.data;
  1584. // start the node record
  1585. FBX::Node bsnode("Geometry");
  1586. int64_t blendshape_uid = generate_uid();
  1587. mesh_uids.push_back(blendshape_uid);
  1588. bsnode.AddProperty(blendshape_uid);
  1589. bsnode.AddProperty(blendshape_name + FBX::SEPARATOR + "Geometry");
  1590. bsnode.AddProperty("Shape");
  1591. bsnode.AddChild("Version", int32_t(100));
  1592. bsnode.Begin(outstream, binary, indent);
  1593. bsnode.DumpProperties(outstream, binary, indent);
  1594. bsnode.EndProperties(outstream, binary, indent);
  1595. bsnode.BeginChildren(outstream, binary, indent);
  1596. indent++;
  1597. if (pAnimMesh->HasPositions()) {
  1598. std::vector<int32_t>shape_indices;
  1599. std::vector<double>pPositionDiff;
  1600. std::vector<double>pNormalDiff;
  1601. for (unsigned int vt = 0; vt < vertex_indices.size(); ++vt) {
  1602. aiVector3D pDiff = (pAnimMesh->mVertices[vertex_indices[vt]] - m->mVertices[vertex_indices[vt]]);
  1603. if(pDiff.Length()>1e-8){
  1604. shape_indices.push_back(vertex_indices[vt]);
  1605. pPositionDiff.push_back(pDiff[0]);
  1606. pPositionDiff.push_back(pDiff[1]);
  1607. pPositionDiff.push_back(pDiff[2]);
  1608. if (pAnimMesh->HasNormals()) {
  1609. aiVector3D nDiff = (pAnimMesh->mNormals[vertex_indices[vt]] - m->mNormals[vertex_indices[vt]]);
  1610. pNormalDiff.push_back(nDiff[0]);
  1611. pNormalDiff.push_back(nDiff[1]);
  1612. pNormalDiff.push_back(nDiff[2]);
  1613. }
  1614. }
  1615. }
  1616. FBX::Node::WritePropertyNode(
  1617. "Indexes", shape_indices, outstream, binary, indent
  1618. );
  1619. FBX::Node::WritePropertyNode(
  1620. "Vertices", pPositionDiff, outstream, binary, indent
  1621. );
  1622. if (pNormalDiff.size()>0) {
  1623. FBX::Node::WritePropertyNode(
  1624. "Normals", pNormalDiff, outstream, binary, indent
  1625. );
  1626. }
  1627. }
  1628. indent--;
  1629. bsnode.End(outstream, binary, indent, true);
  1630. // Add blendshape Channel Deformer
  1631. FBX::Node sdnode("Deformer");
  1632. const int64_t blendchannel_uid = generate_uid();
  1633. sdnode.AddProperties(
  1634. blendchannel_uid, blendshape_name + FBX::SEPARATOR + "SubDeformer", "BlendShapeChannel"
  1635. );
  1636. sdnode.AddChild("Version", int32_t(100));
  1637. sdnode.AddChild("DeformPercent", float(0.0));
  1638. FBX::Node p("Properties70");
  1639. p.AddP70numberA("DeformPercent", 0.0);
  1640. sdnode.AddChild(p);
  1641. // TODO: Normally just one weight per channel, adding stub for later development
  1642. std::vector<double>fFullWeights;
  1643. fFullWeights.push_back(100.);
  1644. sdnode.AddChild("FullWeights", fFullWeights);
  1645. sdnode.Dump(outstream, binary, indent);
  1646. connections.emplace_back("C", "OO", blendchannel_uid, deformer_uid);
  1647. connections.emplace_back("C", "OO", blendshape_uid, blendchannel_uid);
  1648. }
  1649. }
  1650. // bones.
  1651. //
  1652. // output structure:
  1653. // subset of node hierarchy that are "skeleton",
  1654. // i.e. do not have meshes but only bones.
  1655. // but.. i'm not sure how anyone could guarantee that...
  1656. //
  1657. // input...
  1658. // well, for each mesh it has "bones",
  1659. // and the bone names correspond to nodes.
  1660. // of course we also need the parent nodes,
  1661. // as they give some of the transform........
  1662. //
  1663. // well. we can assume a sane input, i suppose.
  1664. //
  1665. // so input is the bone node hierarchy,
  1666. // with an extra thing for the transformation of the MESH in BONE space.
  1667. //
  1668. // output is a set of bone nodes,
  1669. // a "bindpose" which indicates the default local transform of all bones,
  1670. // and a set of "deformers".
  1671. // each deformer is parented to a mesh geometry,
  1672. // and has one or more "subdeformer"s as children.
  1673. // each subdeformer has one bone node as a child,
  1674. // and represents the influence of that bone on the grandparent mesh.
  1675. // the subdeformer has a list of indices, and weights,
  1676. // with indices specifying vertex indices,
  1677. // and weights specifying the corresponding influence of this bone.
  1678. // it also has Transform and TransformLink elements,
  1679. // specifying the transform of the MESH in BONE space,
  1680. // and the transformation of the BONE in WORLD space,
  1681. // likely in the bindpose.
  1682. //
  1683. // the input bone structure is different but similar,
  1684. // storing the number of weights for this bone,
  1685. // and an array of (vertex index, weight) pairs.
  1686. //
  1687. // one sticky point is that the number of vertices may not match,
  1688. // because assimp splits vertices by normal, uv, etc.
  1689. // functor for aiNode sorting
  1690. struct SortNodeByName
  1691. {
  1692. bool operator()(const aiNode *lhs, const aiNode *rhs) const
  1693. {
  1694. return strcmp(lhs->mName.C_Str(), rhs->mName.C_Str()) < 0;
  1695. }
  1696. };
  1697. // first we should mark the skeleton for each mesh.
  1698. // the skeleton must include not only the aiBones,
  1699. // but also all their parent nodes.
  1700. // anything that affects the position of any bone node must be included.
  1701. // Use SorNodeByName to make sure the exported result will be the same across all systems
  1702. // Otherwise the aiNodes of the skeleton would be sorted based on the pointer address, which isn't consistent
  1703. std::vector<std::set<const aiNode*, SortNodeByName>> skeleton_by_mesh(mScene->mNumMeshes);
  1704. // at the same time we can build a list of all the skeleton nodes,
  1705. // which will be used later to mark them as type "limbNode".
  1706. std::unordered_set<const aiNode*> limbnodes;
  1707. //actual bone nodes in fbx, without parenting-up
  1708. std::unordered_set<std::string> setAllBoneNamesInScene;
  1709. for(unsigned int m = 0; m < mScene->mNumMeshes; ++ m)
  1710. {
  1711. aiMesh* pMesh = mScene->mMeshes[m];
  1712. for(unsigned int b = 0; b < pMesh->mNumBones; ++ b)
  1713. setAllBoneNamesInScene.insert(pMesh->mBones[b]->mName.data);
  1714. }
  1715. aiMatrix4x4 mxTransIdentity;
  1716. // and a map of nodes by bone name, as finding them is annoying.
  1717. std::map<std::string,aiNode*> node_by_bone;
  1718. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1719. const aiMesh* m = mScene->mMeshes[mi];
  1720. std::set<const aiNode*, SortNodeByName> skeleton;
  1721. for (size_t bi =0; bi < m->mNumBones; ++bi) {
  1722. const aiBone* b = m->mBones[bi];
  1723. const std::string name(b->mName.C_Str());
  1724. auto elem = node_by_bone.find(name);
  1725. aiNode* n;
  1726. if (elem != node_by_bone.end()) {
  1727. n = elem->second;
  1728. } else {
  1729. n = mScene->mRootNode->FindNode(b->mName);
  1730. if (!n) {
  1731. // this should never happen
  1732. std::stringstream err;
  1733. err << "Failed to find node for bone: \"" << name << "\"";
  1734. throw DeadlyExportError(err.str());
  1735. }
  1736. node_by_bone[name] = n;
  1737. limbnodes.insert(n);
  1738. }
  1739. skeleton.insert(n);
  1740. // mark all parent nodes as skeleton as well,
  1741. // up until we find the root node,
  1742. // or else the node containing the mesh,
  1743. // or else the parent of a node containing the mesh.
  1744. for (
  1745. const aiNode* parent = n->mParent;
  1746. parent && parent != mScene->mRootNode;
  1747. parent = parent->mParent
  1748. ) {
  1749. // if we've already done this node we can skip it all
  1750. if (skeleton.count(parent)) {
  1751. break;
  1752. }
  1753. // ignore fbx transform nodes as these will be collapsed later
  1754. // TODO: cache this by aiNode*
  1755. const std::string node_name(parent->mName.C_Str());
  1756. if (node_name.find(MAGIC_NODE_TAG) != std::string::npos) {
  1757. continue;
  1758. }
  1759. //not a bone in scene && no effect in transform
  1760. if(setAllBoneNamesInScene.find(node_name)==setAllBoneNamesInScene.end()
  1761. && parent->mTransformation == mxTransIdentity) {
  1762. continue;
  1763. }
  1764. // otherwise check if this is the root of the skeleton
  1765. bool end = false;
  1766. // is the mesh part of this node?
  1767. for (size_t i = 0; i < parent->mNumMeshes; ++i) {
  1768. if (parent->mMeshes[i] == mi) {
  1769. end = true;
  1770. break;
  1771. }
  1772. }
  1773. // is the mesh in one of the children of this node?
  1774. for (size_t j = 0; j < parent->mNumChildren; ++j) {
  1775. aiNode* child = parent->mChildren[j];
  1776. for (size_t i = 0; i < child->mNumMeshes; ++i) {
  1777. if (child->mMeshes[i] == mi) {
  1778. end = true;
  1779. break;
  1780. }
  1781. }
  1782. if (end) { break; }
  1783. }
  1784. // if it was the skeleton root we can finish here
  1785. if (end) { break; }
  1786. }
  1787. }
  1788. skeleton_by_mesh[mi] = skeleton;
  1789. }
  1790. // we'll need the uids for the bone nodes, so generate them now
  1791. for (size_t i = 0; i < mScene->mNumMeshes; ++i) {
  1792. auto &s = skeleton_by_mesh[i];
  1793. for (const aiNode* n : s) {
  1794. auto elem = node_uids.find(n);
  1795. if (elem == node_uids.end()) {
  1796. node_uids[n] = generate_uid();
  1797. }
  1798. }
  1799. }
  1800. // now, for each aiMesh, we need to export a deformer,
  1801. // and for each aiBone a subdeformer,
  1802. // which should have all the skinning info.
  1803. // these will need to be connected properly to the mesh,
  1804. // and we can do that all now.
  1805. for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1806. const aiMesh* m = mScene->mMeshes[mi];
  1807. if (!m->HasBones()) {
  1808. continue;
  1809. }
  1810. // make a deformer for this mesh
  1811. int64_t deformer_uid = generate_uid();
  1812. FBX::Node dnode("Deformer");
  1813. dnode.AddProperties(deformer_uid, FBX::SEPARATOR + "Deformer", "Skin");
  1814. dnode.AddChild("Version", int32_t(101));
  1815. // "acuracy"... this is not a typo....
  1816. dnode.AddChild("Link_DeformAcuracy", double(50));
  1817. dnode.AddChild("SkinningType", "Linear"); // TODO: other modes?
  1818. dnode.Dump(outstream, binary, indent);
  1819. // connect it
  1820. connections.emplace_back("C", "OO", deformer_uid, mesh_uids[mi]);
  1821. //computed before
  1822. std::vector<int32_t>& vertex_indices = vVertexIndice[mi];
  1823. // TODO, FIXME: this won't work if anything is not in the bind pose.
  1824. // for now if such a situation is detected, we throw an exception.
  1825. std::set<const aiBone*> not_in_bind_pose;
  1826. std::set<const aiNode*> no_offset_matrix;
  1827. // first get this mesh's position in world space,
  1828. // as we'll need it for each subdeformer.
  1829. //
  1830. // ...of course taking the position of the MESH doesn't make sense,
  1831. // as it can be instanced to many nodes.
  1832. // All we can do is assume no instancing,
  1833. // and take the first node we find that contains the mesh.
  1834. aiNode* mesh_node = get_node_for_mesh((unsigned int)mi, mScene->mRootNode);
  1835. aiMatrix4x4 mesh_xform = get_world_transform(mesh_node, mScene);
  1836. // now make a subdeformer for each bone in the skeleton
  1837. const std::set<const aiNode*, SortNodeByName> skeleton= skeleton_by_mesh[mi];
  1838. for (const aiNode* bone_node : skeleton) {
  1839. // if there's a bone for this node, find it
  1840. const aiBone* b = nullptr;
  1841. for (size_t bi = 0; bi < m->mNumBones; ++bi) {
  1842. // TODO: this probably should index by something else
  1843. const std::string name(m->mBones[bi]->mName.C_Str());
  1844. if (node_by_bone[name] == bone_node) {
  1845. b = m->mBones[bi];
  1846. break;
  1847. }
  1848. }
  1849. if (!b) {
  1850. no_offset_matrix.insert(bone_node);
  1851. }
  1852. // start the subdeformer node
  1853. const int64_t subdeformer_uid = generate_uid();
  1854. FBX::Node sdnode("Deformer");
  1855. sdnode.AddProperties(
  1856. subdeformer_uid, FBX::SEPARATOR + "SubDeformer", "Cluster"
  1857. );
  1858. sdnode.AddChild("Version", int32_t(100));
  1859. sdnode.AddChild("UserData", "", "");
  1860. std::set<int32_t> setWeightedVertex;
  1861. // add indices and weights, if any
  1862. if (b) {
  1863. std::vector<int32_t> subdef_indices;
  1864. std::vector<double> subdef_weights;
  1865. int32_t last_index = -1;
  1866. for (size_t wi = 0; wi < b->mNumWeights; ++wi) {
  1867. int32_t vi = vertex_indices[b->mWeights[wi].mVertexId];
  1868. bool bIsWeightedAlready = (setWeightedVertex.find(vi) != setWeightedVertex.end());
  1869. if (vi == last_index || bIsWeightedAlready) {
  1870. // only for vertices we exported to fbx
  1871. // TODO, FIXME: this assumes identically-located vertices
  1872. // will always deform in the same way.
  1873. // as assimp doesn't store a separate list of "positions",
  1874. // there's not much that can be done about this
  1875. // other than assuming that identical position means
  1876. // identical vertex.
  1877. continue;
  1878. }
  1879. setWeightedVertex.insert(vi);
  1880. subdef_indices.push_back(vi);
  1881. subdef_weights.push_back(b->mWeights[wi].mWeight);
  1882. last_index = vi;
  1883. }
  1884. // yes, "indexes"
  1885. sdnode.AddChild("Indexes", subdef_indices);
  1886. sdnode.AddChild("Weights", subdef_weights);
  1887. }
  1888. // transform is the transform of the mesh, but in bone space.
  1889. // if the skeleton is in the bind pose,
  1890. // we can take the inverse of the world-space bone transform
  1891. // and multiply by the world-space transform of the mesh.
  1892. aiMatrix4x4 bone_xform = get_world_transform(bone_node, mScene);
  1893. aiMatrix4x4 inverse_bone_xform = bone_xform;
  1894. inverse_bone_xform.Inverse();
  1895. aiMatrix4x4 tr = inverse_bone_xform * mesh_xform;
  1896. sdnode.AddChild("Transform", tr);
  1897. sdnode.AddChild("TransformLink", bone_xform);
  1898. // note: this means we ALWAYS rely on the mesh node transform
  1899. // being unchanged from the time the skeleton was bound.
  1900. // there's not really any way around this at the moment.
  1901. // done
  1902. sdnode.Dump(outstream, binary, indent);
  1903. // lastly, connect to the parent deformer
  1904. connections.emplace_back(
  1905. "C", "OO", subdeformer_uid, deformer_uid
  1906. );
  1907. // we also need to connect the limb node to the subdeformer.
  1908. connections.emplace_back(
  1909. "C", "OO", node_uids[bone_node], subdeformer_uid
  1910. );
  1911. }
  1912. // if we cannot create a valid FBX file, simply die.
  1913. // this will both prevent unnecessary bug reports,
  1914. // and tell the user what they can do to fix the situation
  1915. // (i.e. export their model in the bind pose).
  1916. if (no_offset_matrix.size() && not_in_bind_pose.size()) {
  1917. std::stringstream err;
  1918. err << "Not enough information to construct bind pose";
  1919. err << " for mesh " << mi << "!";
  1920. err << " Transform matrix for bone \"";
  1921. err << (*not_in_bind_pose.begin())->mName.C_Str() << "\"";
  1922. if (not_in_bind_pose.size() > 1) {
  1923. err << " (and " << not_in_bind_pose.size() - 1 << " more)";
  1924. }
  1925. err << " does not match mOffsetMatrix,";
  1926. err << " and node \"";
  1927. err << (*no_offset_matrix.begin())->mName.C_Str() << "\"";
  1928. if (no_offset_matrix.size() > 1) {
  1929. err << " (and " << no_offset_matrix.size() - 1 << " more)";
  1930. }
  1931. err << " has no offset matrix to rely on.";
  1932. err << " Please ensure bones are in the bind pose to export.";
  1933. throw DeadlyExportError(err.str());
  1934. }
  1935. }
  1936. // BindPose
  1937. //
  1938. // This is a legacy system, which should be unnecessary.
  1939. //
  1940. // Somehow including it slows file loading by the official FBX SDK,
  1941. // and as it can reconstruct it from the deformers anyway,
  1942. // this is not currently included.
  1943. //
  1944. // The code is kept here in case it's useful in the future,
  1945. // but it's pretty much a hack anyway,
  1946. // as assimp doesn't store bindpose information for full skeletons.
  1947. //
  1948. /*for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) {
  1949. aiMesh* mesh = mScene->mMeshes[mi];
  1950. if (! mesh->HasBones()) { continue; }
  1951. int64_t bindpose_uid = generate_uid();
  1952. FBX::Node bpnode("Pose");
  1953. bpnode.AddProperty(bindpose_uid);
  1954. // note: this uid is never linked or connected to anything.
  1955. bpnode.AddProperty(FBX::SEPARATOR + "Pose"); // blank name
  1956. bpnode.AddProperty("BindPose");
  1957. bpnode.AddChild("Type", "BindPose");
  1958. bpnode.AddChild("Version", int32_t(100));
  1959. aiNode* mesh_node = get_node_for_mesh(mi, mScene->mRootNode);
  1960. // next get the whole skeleton for this mesh.
  1961. // we need it all to define the bindpose section.
  1962. // the FBX SDK will complain if it's missing,
  1963. // and also if parents of used bones don't have a subdeformer.
  1964. // order shouldn't matter.
  1965. std::set<aiNode*> skeleton;
  1966. for (size_t bi = 0; bi < mesh->mNumBones; ++bi) {
  1967. // bone node should have already been indexed
  1968. const aiBone* b = mesh->mBones[bi];
  1969. const std::string bone_name(b->mName.C_Str());
  1970. aiNode* parent = node_by_bone[bone_name];
  1971. // insert all nodes down to the root or mesh node
  1972. while (
  1973. parent
  1974. && parent != mScene->mRootNode
  1975. && parent != mesh_node
  1976. ) {
  1977. skeleton.insert(parent);
  1978. parent = parent->mParent;
  1979. }
  1980. }
  1981. // number of pose nodes. includes one for the mesh itself.
  1982. bpnode.AddChild("NbPoseNodes", int32_t(1 + skeleton.size()));
  1983. // the first pose node is always the mesh itself
  1984. FBX::Node pose("PoseNode");
  1985. pose.AddChild("Node", mesh_uids[mi]);
  1986. aiMatrix4x4 mesh_node_xform = get_world_transform(mesh_node, mScene);
  1987. pose.AddChild("Matrix", mesh_node_xform);
  1988. bpnode.AddChild(pose);
  1989. for (aiNode* bonenode : skeleton) {
  1990. // does this node have a uid yet?
  1991. int64_t node_uid;
  1992. auto node_uid_iter = node_uids.find(bonenode);
  1993. if (node_uid_iter != node_uids.end()) {
  1994. node_uid = node_uid_iter->second;
  1995. } else {
  1996. node_uid = generate_uid();
  1997. node_uids[bonenode] = node_uid;
  1998. }
  1999. // make a pose thingy
  2000. pose = FBX::Node("PoseNode");
  2001. pose.AddChild("Node", node_uid);
  2002. aiMatrix4x4 node_xform = get_world_transform(bonenode, mScene);
  2003. pose.AddChild("Matrix", node_xform);
  2004. bpnode.AddChild(pose);
  2005. }
  2006. // now write it
  2007. bpnode.Dump(outstream, binary, indent);
  2008. }*/
  2009. // lights
  2010. indent = 1;
  2011. lights_uids.clear();
  2012. for (size_t li = 0; li < mScene->mNumLights; ++li) {
  2013. aiLight* l = mScene->mLights[li];
  2014. int64_t uid = generate_uid();
  2015. const std::string lightNodeAttributeName = l->mName.C_Str() + FBX::SEPARATOR + "NodeAttribute";
  2016. FBX::Node lna("NodeAttribute");
  2017. lna.AddProperties(uid, lightNodeAttributeName, "Light");
  2018. FBX::Node lnap("Properties70");
  2019. // Light color.
  2020. lnap.AddP70colorA("Color", l->mColorDiffuse.r, l->mColorDiffuse.g, l->mColorDiffuse.b);
  2021. // TODO Assimp light description is quite concise and do not handle light intensity.
  2022. // Default value to 1000W.
  2023. lnap.AddP70numberA("Intensity", 1000);
  2024. // FBXLight::EType conversion
  2025. switch (l->mType) {
  2026. case aiLightSource_POINT:
  2027. lnap.AddP70enum("LightType", 0);
  2028. break;
  2029. case aiLightSource_DIRECTIONAL:
  2030. lnap.AddP70enum("LightType", 1);
  2031. break;
  2032. case aiLightSource_SPOT:
  2033. lnap.AddP70enum("LightType", 2);
  2034. lnap.AddP70numberA("InnerAngle", AI_RAD_TO_DEG(l->mAngleInnerCone));
  2035. lnap.AddP70numberA("OuterAngle", AI_RAD_TO_DEG(l->mAngleOuterCone));
  2036. break;
  2037. // TODO Assimp do not handle 'area' nor 'volume' lights, but FBX does.
  2038. /*case aiLightSource_AREA:
  2039. lnap.AddP70enum("LightType", 3);
  2040. lnap.AddP70enum("AreaLightShape", 0); // 0=Rectangle, 1=Sphere
  2041. break;
  2042. case aiLightSource_VOLUME:
  2043. lnap.AddP70enum("LightType", 4);
  2044. break;*/
  2045. default:
  2046. break;
  2047. }
  2048. // Did not understood how to configure the decay so disabling attenuation.
  2049. lnap.AddP70enum("DecayType", 0);
  2050. // Dump to FBX stream
  2051. lna.AddChild(lnap);
  2052. lna.AddChild("TypeFlags", FBX::FBXExportProperty("Light"));
  2053. lna.AddChild("GeometryVersion", FBX::FBXExportProperty(int32_t(124)));
  2054. lna.Dump(outstream, binary, indent);
  2055. // Store name and uid (will be used later when parsing scene nodes)
  2056. lights_uids[l->mName.C_Str()] = uid;
  2057. }
  2058. // TODO: cameras
  2059. // write nodes (i.e. model hierarchy)
  2060. // start at root node
  2061. WriteModelNodes(
  2062. outstream, mScene->mRootNode, 0, limbnodes
  2063. );
  2064. // animations
  2065. //
  2066. // in FBX there are:
  2067. // * AnimationStack - corresponds to an aiAnimation
  2068. // * AnimationLayer - a combinable animation component
  2069. // * AnimationCurveNode - links the property to be animated
  2070. // * AnimationCurve - defines animation data for a single property value
  2071. //
  2072. // the CurveNode also provides the default value for a property,
  2073. // such as the X, Y, Z coordinates for animatable translation.
  2074. //
  2075. // the Curve only specifies values for one component of the property,
  2076. // so there will be a separate AnimationCurve for X, Y, and Z.
  2077. //
  2078. // Assimp has:
  2079. // * aiAnimation - basically corresponds to an AnimationStack
  2080. // * aiNodeAnim - defines all animation for one aiNode
  2081. // * aiVectorKey/aiQuatKey - define the keyframe data for T/R/S
  2082. //
  2083. // assimp has no equivalent for AnimationLayer,
  2084. // and these are flattened on FBX import.
  2085. // we can assume there will be one per AnimationStack.
  2086. //
  2087. // the aiNodeAnim contains all animation data for a single aiNode,
  2088. // which will correspond to three AnimationCurveNode's:
  2089. // one each for translation, rotation and scale.
  2090. // The data for each of these will be put in 9 AnimationCurve's,
  2091. // T.X, T.Y, T.Z, R.X, R.Y, R.Z, etc.
  2092. // AnimationStack / aiAnimation
  2093. std::vector<int64_t> animation_stack_uids(mScene->mNumAnimations);
  2094. for (size_t ai = 0; ai < mScene->mNumAnimations; ++ai) {
  2095. int64_t animstack_uid = generate_uid();
  2096. animation_stack_uids[ai] = animstack_uid;
  2097. const aiAnimation* anim = mScene->mAnimations[ai];
  2098. FBX::Node asnode("AnimationStack");
  2099. std::string name = anim->mName.C_Str() + FBX::SEPARATOR + "AnimStack";
  2100. asnode.AddProperties(animstack_uid, name, "");
  2101. FBX::Node p("Properties70");
  2102. p.AddP70time("LocalStart", 0); // assimp doesn't store this
  2103. p.AddP70time("LocalStop", to_ktime(anim->mDuration, anim));
  2104. p.AddP70time("ReferenceStart", 0);
  2105. p.AddP70time("ReferenceStop", to_ktime(anim->mDuration, anim));
  2106. asnode.AddChild(p);
  2107. // this node absurdly always pretends it has children
  2108. // (in this case it does, but just in case...)
  2109. asnode.force_has_children = true;
  2110. asnode.Dump(outstream, binary, indent);
  2111. // note: animation stacks are not connected to anything
  2112. }
  2113. // AnimationLayer - one per aiAnimation
  2114. std::vector<int64_t> animation_layer_uids(mScene->mNumAnimations);
  2115. for (size_t ai = 0; ai < mScene->mNumAnimations; ++ai) {
  2116. int64_t animlayer_uid = generate_uid();
  2117. animation_layer_uids[ai] = animlayer_uid;
  2118. FBX::Node alnode("AnimationLayer");
  2119. alnode.AddProperties(animlayer_uid, FBX::SEPARATOR + "AnimLayer", "");
  2120. // this node absurdly always pretends it has children
  2121. alnode.force_has_children = true;
  2122. alnode.Dump(outstream, binary, indent);
  2123. // connect to the relevant animstack
  2124. connections.emplace_back(
  2125. "C", "OO", animlayer_uid, animation_stack_uids[ai]
  2126. );
  2127. }
  2128. // AnimCurveNode - three per aiNodeAnim
  2129. std::vector<std::vector<std::array<int64_t,3>>> curve_node_uids;
  2130. for (size_t ai = 0; ai < mScene->mNumAnimations; ++ai) {
  2131. const aiAnimation* anim = mScene->mAnimations[ai];
  2132. const int64_t layer_uid = animation_layer_uids[ai];
  2133. std::vector<std::array<int64_t,3>> nodeanim_uids;
  2134. for (size_t nai = 0; nai < anim->mNumChannels; ++nai) {
  2135. const aiNodeAnim* na = anim->mChannels[nai];
  2136. // get the corresponding aiNode
  2137. const aiNode* node = mScene->mRootNode->FindNode(na->mNodeName);
  2138. // and its transform
  2139. const aiMatrix4x4 node_xfm = get_world_transform(node, mScene);
  2140. aiVector3D T, R, S;
  2141. node_xfm.Decompose(S, R, T);
  2142. // AnimationCurveNode uids
  2143. std::array<int64_t,3> ids;
  2144. ids[0] = generate_uid(); // T
  2145. ids[1] = generate_uid(); // R
  2146. ids[2] = generate_uid(); // S
  2147. // translation
  2148. WriteAnimationCurveNode(outstream,
  2149. ids[0], "T", T, "Lcl Translation",
  2150. layer_uid, node_uids[node]
  2151. );
  2152. // rotation
  2153. WriteAnimationCurveNode(outstream,
  2154. ids[1], "R", R, "Lcl Rotation",
  2155. layer_uid, node_uids[node]
  2156. );
  2157. // scale
  2158. WriteAnimationCurveNode(outstream,
  2159. ids[2], "S", S, "Lcl Scale",
  2160. layer_uid, node_uids[node]
  2161. );
  2162. // store the uids for later use
  2163. nodeanim_uids.push_back(ids);
  2164. }
  2165. curve_node_uids.push_back(nodeanim_uids);
  2166. }
  2167. // AnimCurve - defines actual keyframe data.
  2168. // there's a separate curve for every component of every vector,
  2169. // for example a transform curvenode will have separate X/Y/Z AnimCurve's
  2170. for (size_t ai = 0; ai < mScene->mNumAnimations; ++ai) {
  2171. const aiAnimation* anim = mScene->mAnimations[ai];
  2172. for (size_t nai = 0; nai < anim->mNumChannels; ++nai) {
  2173. const aiNodeAnim* na = anim->mChannels[nai];
  2174. // get the corresponding aiNode
  2175. const aiNode* node = mScene->mRootNode->FindNode(na->mNodeName);
  2176. // and its transform
  2177. const aiMatrix4x4 node_xfm = get_world_transform(node, mScene);
  2178. aiVector3D T, R, S;
  2179. node_xfm.Decompose(S, R, T);
  2180. const std::array<int64_t,3>& ids = curve_node_uids[ai][nai];
  2181. std::vector<int64_t> times;
  2182. std::vector<float> xval, yval, zval;
  2183. // position/translation
  2184. for (size_t ki = 0; ki < na->mNumPositionKeys; ++ki) {
  2185. const aiVectorKey& k = na->mPositionKeys[ki];
  2186. times.push_back(to_ktime(k.mTime, anim));
  2187. xval.push_back(k.mValue.x);
  2188. yval.push_back(k.mValue.y);
  2189. zval.push_back(k.mValue.z);
  2190. }
  2191. // one curve each for X, Y, Z
  2192. WriteAnimationCurve(outstream, T.x, times, xval, ids[0], "d|X");
  2193. WriteAnimationCurve(outstream, T.y, times, yval, ids[0], "d|Y");
  2194. WriteAnimationCurve(outstream, T.z, times, zval, ids[0], "d|Z");
  2195. // rotation
  2196. times.clear(); xval.clear(); yval.clear(); zval.clear();
  2197. for (size_t ki = 0; ki < na->mNumRotationKeys; ++ki) {
  2198. const aiQuatKey& k = na->mRotationKeys[ki];
  2199. times.push_back(to_ktime(k.mTime, anim));
  2200. // TODO: aiQuaternion method to convert to Euler...
  2201. aiMatrix4x4 m(k.mValue.GetMatrix());
  2202. aiVector3D qs, qr, qt;
  2203. m.Decompose(qs, qr, qt);
  2204. qr = AI_RAD_TO_DEG(qr);
  2205. xval.push_back(qr.x);
  2206. yval.push_back(qr.y);
  2207. zval.push_back(qr.z);
  2208. }
  2209. WriteAnimationCurve(outstream, R.x, times, xval, ids[1], "d|X");
  2210. WriteAnimationCurve(outstream, R.y, times, yval, ids[1], "d|Y");
  2211. WriteAnimationCurve(outstream, R.z, times, zval, ids[1], "d|Z");
  2212. // scaling/scale
  2213. times.clear(); xval.clear(); yval.clear(); zval.clear();
  2214. for (size_t ki = 0; ki < na->mNumScalingKeys; ++ki) {
  2215. const aiVectorKey& k = na->mScalingKeys[ki];
  2216. times.push_back(to_ktime(k.mTime, anim));
  2217. xval.push_back(k.mValue.x);
  2218. yval.push_back(k.mValue.y);
  2219. zval.push_back(k.mValue.z);
  2220. }
  2221. WriteAnimationCurve(outstream, S.x, times, xval, ids[2], "d|X");
  2222. WriteAnimationCurve(outstream, S.y, times, yval, ids[2], "d|Y");
  2223. WriteAnimationCurve(outstream, S.z, times, zval, ids[2], "d|Z");
  2224. }
  2225. }
  2226. indent = 0;
  2227. object_node.End(outstream, binary, indent, true);
  2228. }
  2229. // convenience map of magic node name strings to FBX properties,
  2230. // including the expected type of transform.
  2231. const std::map<std::string,std::pair<std::string,char>> transform_types = {
  2232. {"Translation", {"Lcl Translation", 't'}},
  2233. {"RotationOffset", {"RotationOffset", 't'}},
  2234. {"RotationPivot", {"RotationPivot", 't'}},
  2235. {"PreRotation", {"PreRotation", 'r'}},
  2236. {"Rotation", {"Lcl Rotation", 'r'}},
  2237. {"PostRotation", {"PostRotation", 'r'}},
  2238. {"RotationPivotInverse", {"RotationPivotInverse", 'i'}},
  2239. {"ScalingOffset", {"ScalingOffset", 't'}},
  2240. {"ScalingPivot", {"ScalingPivot", 't'}},
  2241. {"Scaling", {"Lcl Scaling", 's'}},
  2242. {"ScalingPivotInverse", {"ScalingPivotInverse", 'i'}},
  2243. {"GeometricScaling", {"GeometricScaling", 's'}},
  2244. {"GeometricRotation", {"GeometricRotation", 'r'}},
  2245. {"GeometricTranslation", {"GeometricTranslation", 't'}},
  2246. {"GeometricTranslationInverse", {"GeometricTranslationInverse", 'i'}},
  2247. {"GeometricRotationInverse", {"GeometricRotationInverse", 'i'}},
  2248. {"GeometricScalingInverse", {"GeometricScalingInverse", 'i'}}
  2249. };
  2250. // write a single model node to the stream
  2251. void FBXExporter::WriteModelNode(
  2252. StreamWriterLE& outstream,
  2253. bool,
  2254. const aiNode* node,
  2255. int64_t node_uid,
  2256. const std::string& type,
  2257. const std::vector<std::pair<std::string,aiVector3D>>& transform_chain,
  2258. TransformInheritance inherit_type
  2259. ){
  2260. const aiVector3D zero = {0, 0, 0};
  2261. const aiVector3D one = {1, 1, 1};
  2262. FBX::Node m("Model");
  2263. std::string name = node->mName.C_Str() + FBX::SEPARATOR + "Model";
  2264. m.AddProperties(node_uid, std::move(name), type);
  2265. m.AddChild("Version", int32_t(232));
  2266. FBX::Node p("Properties70");
  2267. p.AddP70bool("RotationActive", true);
  2268. p.AddP70int("DefaultAttributeIndex", 0);
  2269. p.AddP70enum("InheritType", inherit_type);
  2270. if (transform_chain.empty()) {
  2271. // decompose 4x4 transform matrix into TRS
  2272. aiVector3D t, r, s;
  2273. node->mTransformation.Decompose(s, r, t);
  2274. if (t != zero) {
  2275. p.AddP70(
  2276. "Lcl Translation", "Lcl Translation", "", "A",
  2277. double(t.x), double(t.y), double(t.z)
  2278. );
  2279. }
  2280. if (r != zero) {
  2281. r = AI_RAD_TO_DEG(r);
  2282. p.AddP70(
  2283. "Lcl Rotation", "Lcl Rotation", "", "A",
  2284. double(r.x), double(r.y), double(r.z)
  2285. );
  2286. }
  2287. if (s != one) {
  2288. p.AddP70(
  2289. "Lcl Scaling", "Lcl Scaling", "", "A",
  2290. double(s.x), double(s.y), double(s.z)
  2291. );
  2292. }
  2293. } else {
  2294. // apply the transformation chain.
  2295. // these transformation elements are created when importing FBX,
  2296. // which has a complex transformation hierarchy for each node.
  2297. // as such we can bake the hierarchy back into the node on export.
  2298. for (auto &item : transform_chain) {
  2299. auto elem = transform_types.find(item.first);
  2300. if (elem == transform_types.end()) {
  2301. // then this is a bug
  2302. std::stringstream err;
  2303. err << "unrecognized FBX transformation type: ";
  2304. err << item.first;
  2305. throw DeadlyExportError(err.str());
  2306. }
  2307. const std::string &cur_name = elem->second.first;
  2308. const aiVector3D &v = item.second;
  2309. if (cur_name.compare(0, 4, "Lcl ") == 0) {
  2310. // special handling for animatable properties
  2311. p.AddP70( cur_name, cur_name, "", "A", double(v.x), double(v.y), double(v.z) );
  2312. } else {
  2313. p.AddP70vector(cur_name, v.x, v.y, v.z);
  2314. }
  2315. }
  2316. }
  2317. m.AddChild(p);
  2318. // not sure what these are for,
  2319. // but they seem to be omnipresent
  2320. m.AddChild("Shading", FBXExportProperty(true));
  2321. m.AddChild("Culling", FBXExportProperty("CullingOff"));
  2322. m.Dump(outstream, binary, 1);
  2323. }
  2324. // wrapper for WriteModelNodes to create and pass a blank transform chain
  2325. void FBXExporter::WriteModelNodes(
  2326. StreamWriterLE& s,
  2327. const aiNode* node,
  2328. int64_t parent_uid,
  2329. const std::unordered_set<const aiNode*>& limbnodes
  2330. ) {
  2331. std::vector<std::pair<std::string,aiVector3D>> chain;
  2332. WriteModelNodes(s, node, parent_uid, limbnodes, chain);
  2333. }
  2334. void FBXExporter::WriteModelNodes(
  2335. StreamWriterLE& outstream,
  2336. const aiNode* node,
  2337. int64_t parent_uid,
  2338. const std::unordered_set<const aiNode*>& limbnodes,
  2339. std::vector<std::pair<std::string,aiVector3D>>& transform_chain
  2340. ) {
  2341. // first collapse any expanded transformation chains created by FBX import.
  2342. std::string node_name(node->mName.C_Str());
  2343. if (node_name.find(MAGIC_NODE_TAG) != std::string::npos) {
  2344. auto pos = node_name.find(MAGIC_NODE_TAG) + MAGIC_NODE_TAG.size() + 1;
  2345. std::string type_name = node_name.substr(pos);
  2346. auto elem = transform_types.find(type_name);
  2347. if (elem == transform_types.end()) {
  2348. // then this is a bug and should be fixed
  2349. std::stringstream err;
  2350. err << "unrecognized FBX transformation node";
  2351. err << " of type " << type_name << " in node " << node_name;
  2352. throw DeadlyExportError(err.str());
  2353. }
  2354. aiVector3D t, r, s;
  2355. node->mTransformation.Decompose(s, r, t);
  2356. switch (elem->second.second) {
  2357. case 'i': // inverse
  2358. // we don't need to worry about the inverse matrices
  2359. break;
  2360. case 't': // translation
  2361. transform_chain.emplace_back(elem->first, t);
  2362. break;
  2363. case 'r': // rotation
  2364. transform_chain.emplace_back(elem->first, AI_RAD_TO_DEG(r));
  2365. break;
  2366. case 's': // scale
  2367. transform_chain.emplace_back(elem->first, s);
  2368. break;
  2369. default:
  2370. // this should never happen
  2371. std::stringstream err;
  2372. err << "unrecognized FBX transformation type code: ";
  2373. err << elem->second.second;
  2374. throw DeadlyExportError(err.str());
  2375. }
  2376. // now continue on to any child nodes
  2377. for (unsigned i = 0; i < node->mNumChildren; ++i) {
  2378. WriteModelNodes(
  2379. outstream,
  2380. node->mChildren[i],
  2381. parent_uid,
  2382. limbnodes,
  2383. transform_chain
  2384. );
  2385. }
  2386. return;
  2387. }
  2388. int64_t node_uid = 0;
  2389. // generate uid and connect to parent, if not the root node,
  2390. if (node != mScene->mRootNode) {
  2391. auto elem = node_uids.find(node);
  2392. if (elem != node_uids.end()) {
  2393. node_uid = elem->second;
  2394. } else {
  2395. node_uid = generate_uid();
  2396. node_uids[node] = node_uid;
  2397. }
  2398. connections.emplace_back("C", "OO", node_uid, parent_uid);
  2399. }
  2400. // what type of node is this?
  2401. if (node == mScene->mRootNode) {
  2402. // handled later
  2403. } else if (node->mNumMeshes == 1) {
  2404. // connect to child mesh, which should have been written previously
  2405. connections.emplace_back(
  2406. "C", "OO", mesh_uids[node->mMeshes[0]], node_uid
  2407. );
  2408. // also connect to the material for the child mesh
  2409. connections.emplace_back(
  2410. "C", "OO",
  2411. material_uids[mScene->mMeshes[node->mMeshes[0]]->mMaterialIndex],
  2412. node_uid
  2413. );
  2414. // write model node
  2415. WriteModelNode(
  2416. outstream, binary, node, node_uid, "Mesh", transform_chain
  2417. );
  2418. } else if (limbnodes.count(node)) {
  2419. WriteModelNode(
  2420. outstream, binary, node, node_uid, "LimbNode", transform_chain
  2421. );
  2422. // we also need to write a nodeattribute to mark it as a skeleton
  2423. int64_t node_attribute_uid = generate_uid();
  2424. FBX::Node na("NodeAttribute");
  2425. na.AddProperties(
  2426. node_attribute_uid, FBX::SEPARATOR + "NodeAttribute", "LimbNode"
  2427. );
  2428. na.AddChild("TypeFlags", FBXExportProperty("Skeleton"));
  2429. na.Dump(outstream, binary, 1);
  2430. // and connect them
  2431. connections.emplace_back("C", "OO", node_attribute_uid, node_uid);
  2432. } else {
  2433. const auto& lightIt = lights_uids.find(node->mName.C_Str());
  2434. if(lightIt != lights_uids.end()) {
  2435. // Node has a light connected to it.
  2436. WriteModelNode(
  2437. outstream, binary, node, node_uid, "Light", transform_chain
  2438. );
  2439. connections.emplace_back("C", "OO", lightIt->second, node_uid);
  2440. } else {
  2441. // generate a null node so we can add children to it
  2442. WriteModelNode(
  2443. outstream, binary, node, node_uid, "Null", transform_chain
  2444. );
  2445. }
  2446. }
  2447. // if more than one child mesh, make nodes for each mesh
  2448. if (node->mNumMeshes > 1 || node == mScene->mRootNode) {
  2449. for (size_t i = 0; i < node->mNumMeshes; ++i) {
  2450. // make a new model node
  2451. int64_t new_node_uid = generate_uid();
  2452. // connect to parent node
  2453. connections.emplace_back("C", "OO", new_node_uid, node_uid);
  2454. // connect to child mesh, which should have been written previously
  2455. connections.emplace_back(
  2456. "C", "OO", mesh_uids[node->mMeshes[i]], new_node_uid
  2457. );
  2458. // also connect to the material for the child mesh
  2459. connections.emplace_back(
  2460. "C", "OO",
  2461. material_uids[
  2462. mScene->mMeshes[node->mMeshes[i]]->mMaterialIndex
  2463. ],
  2464. new_node_uid
  2465. );
  2466. aiNode new_node;
  2467. // take name from mesh name, if it exists
  2468. new_node.mName = mScene->mMeshes[node->mMeshes[i]]->mName;
  2469. // write model node
  2470. WriteModelNode(
  2471. outstream, binary, &new_node, new_node_uid, "Mesh", std::vector<std::pair<std::string,aiVector3D>>()
  2472. );
  2473. }
  2474. }
  2475. // now recurse into children
  2476. for (size_t i = 0; i < node->mNumChildren; ++i) {
  2477. WriteModelNodes(
  2478. outstream, node->mChildren[i], node_uid, limbnodes
  2479. );
  2480. }
  2481. }
  2482. void FBXExporter::WriteAnimationCurveNode(
  2483. StreamWriterLE &outstream,
  2484. int64_t uid,
  2485. const std::string &name, // "T", "R", or "S"
  2486. aiVector3D default_value,
  2487. const std::string &property_name, // "Lcl Translation" etc
  2488. int64_t layer_uid,
  2489. int64_t node_uid) {
  2490. FBX::Node n("AnimationCurveNode");
  2491. n.AddProperties(uid, name + FBX::SEPARATOR + "AnimCurveNode", "");
  2492. FBX::Node p("Properties70");
  2493. p.AddP70numberA("d|X", default_value.x);
  2494. p.AddP70numberA("d|Y", default_value.y);
  2495. p.AddP70numberA("d|Z", default_value.z);
  2496. n.AddChild(p);
  2497. n.Dump(outstream, binary, 1);
  2498. // connect to layer
  2499. this->connections.emplace_back("C", "OO", uid, layer_uid);
  2500. // connect to bone
  2501. this->connections.emplace_back("C", "OP", uid, node_uid, property_name);
  2502. }
  2503. void FBXExporter::WriteAnimationCurve(
  2504. StreamWriterLE& outstream,
  2505. double default_value,
  2506. const std::vector<int64_t>& times,
  2507. const std::vector<float>& values,
  2508. int64_t curvenode_uid,
  2509. const std::string& property_link // "d|X", "d|Y", etc
  2510. ) {
  2511. FBX::Node n("AnimationCurve");
  2512. int64_t curve_uid = generate_uid();
  2513. n.AddProperties(curve_uid, FBX::SEPARATOR + "AnimCurve", "");
  2514. n.AddChild("Default", default_value);
  2515. n.AddChild("KeyVer", int32_t(4009));
  2516. n.AddChild("KeyTime", times);
  2517. n.AddChild("KeyValueFloat", values);
  2518. // TODO: keyattr flags and data (STUB for now)
  2519. n.AddChild("KeyAttrFlags", std::vector<int32_t>{0});
  2520. n.AddChild("KeyAttrDataFloat", std::vector<float>{0,0,0,0});
  2521. n.AddChild(
  2522. "KeyAttrRefCount",
  2523. std::vector<int32_t>{static_cast<int32_t>(times.size())}
  2524. );
  2525. n.Dump(outstream, binary, 1);
  2526. this->connections.emplace_back(
  2527. "C", "OP", curve_uid, curvenode_uid, property_link
  2528. );
  2529. }
  2530. void FBXExporter::WriteConnections ()
  2531. {
  2532. // we should have completed the connection graph already,
  2533. // so basically just dump it here
  2534. if (!binary) {
  2535. WriteAsciiSectionHeader("Object connections");
  2536. }
  2537. // TODO: comments with names in the ascii version
  2538. FBX::Node conn("Connections");
  2539. StreamWriterLE outstream(outfile);
  2540. conn.Begin(outstream, binary, 0);
  2541. conn.BeginChildren(outstream, binary, 0);
  2542. for (auto &n : connections) {
  2543. n.Dump(outstream, binary, 1);
  2544. }
  2545. conn.End(outstream, binary, 0, !connections.empty());
  2546. connections.clear();
  2547. }
  2548. #endif // ASSIMP_BUILD_NO_FBX_EXPORTER
  2549. #endif // ASSIMP_BUILD_NO_EXPORT