FBXExporter.cpp 93 KB

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