2
0

FBXExporter.cpp 108 KB

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