FBXExporter.cpp 91 KB

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