FBXExporter.cpp 106 KB

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