FBXExporter.cpp 93 KB

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