FBXExporter.cpp 109 KB

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