FBXExporter.cpp 99 KB

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