fbx_document.cpp 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489
  1. /**************************************************************************/
  2. /* fbx_document.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "fbx_document.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/crypto/crypto_core.h"
  33. #include "core/io/config_file.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/file_access_memory.h"
  36. #include "core/io/image.h"
  37. #include "core/math/color.h"
  38. #include "scene/3d/bone_attachment_3d.h"
  39. #include "scene/3d/camera_3d.h"
  40. #include "scene/3d/importer_mesh_instance_3d.h"
  41. #include "scene/3d/light_3d.h"
  42. #include "scene/resources/image_texture.h"
  43. #include "scene/resources/material.h"
  44. #include "scene/resources/portable_compressed_texture.h"
  45. #include "scene/resources/surface_tool.h"
  46. #include "modules/gltf/extensions/gltf_light.h"
  47. #include "modules/gltf/gltf_defines.h"
  48. #include "modules/gltf/skin_tool.h"
  49. #include "modules/gltf/structures/gltf_animation.h"
  50. #include "modules/gltf/structures/gltf_camera.h"
  51. #ifdef TOOLS_ENABLED
  52. #include "editor/editor_file_system.h"
  53. #endif
  54. // FIXME: Hardcoded to avoid editor dependency.
  55. #define FBX_IMPORT_USE_NAMED_SKIN_BINDS 16
  56. #define FBX_IMPORT_DISCARD_MESHES_AND_MATERIALS 32
  57. #define FBX_IMPORT_FORCE_DISABLE_MESH_COMPRESSION 64
  58. #include <ufbx.h>
  59. static size_t _file_access_read_fn(void *user, void *data, size_t size) {
  60. FileAccess *file = static_cast<FileAccess *>(user);
  61. return (size_t)file->get_buffer((uint8_t *)data, (uint64_t)size);
  62. }
  63. static bool _file_access_skip_fn(void *user, size_t size) {
  64. FileAccess *file = static_cast<FileAccess *>(user);
  65. file->seek(file->get_position() + size);
  66. return true;
  67. }
  68. static Vector2 _as_vec2(const ufbx_vec2 &p_vector) {
  69. return Vector2(real_t(p_vector.x), real_t(p_vector.y));
  70. }
  71. static Color _as_color(const ufbx_vec4 &p_vector) {
  72. return Color(real_t(p_vector.x), real_t(p_vector.y), real_t(p_vector.z), real_t(p_vector.w));
  73. }
  74. static Quaternion _as_quaternion(const ufbx_quat &p_quat) {
  75. return Quaternion(real_t(p_quat.x), real_t(p_quat.y), real_t(p_quat.z), real_t(p_quat.w));
  76. }
  77. static Transform3D _as_transform(const ufbx_transform &p_xform) {
  78. Transform3D result;
  79. result.origin = FBXDocument::_as_vec3(p_xform.translation);
  80. result.basis.set_quaternion_scale(_as_quaternion(p_xform.rotation), FBXDocument::_as_vec3(p_xform.scale));
  81. return result;
  82. }
  83. static real_t _relative_error(const Vector3 &p_a, const Vector3 &p_b) {
  84. return p_a.distance_to(p_b) / MAX(p_a.length(), p_b.length());
  85. }
  86. static Color _material_color(const ufbx_material_map &p_map) {
  87. if (p_map.value_components == 1) {
  88. float r = float(p_map.value_real);
  89. return Color(r, r, r);
  90. } else if (p_map.value_components == 3) {
  91. float r = float(p_map.value_vec3.x);
  92. float g = float(p_map.value_vec3.y);
  93. float b = float(p_map.value_vec3.z);
  94. return Color(r, g, b);
  95. } else {
  96. float r = float(p_map.value_vec4.x);
  97. float g = float(p_map.value_vec4.y);
  98. float b = float(p_map.value_vec4.z);
  99. float a = float(p_map.value_vec4.z);
  100. return Color(r, g, b, a);
  101. }
  102. }
  103. static Color _material_color(const ufbx_material_map &p_map, const ufbx_material_map &p_factor) {
  104. Color color = _material_color(p_map);
  105. if (p_factor.has_value) {
  106. float factor = float(p_factor.value_real);
  107. color.r *= factor;
  108. color.g *= factor;
  109. color.b *= factor;
  110. }
  111. return color;
  112. }
  113. static const ufbx_texture *_get_file_texture(const ufbx_texture *p_texture) {
  114. if (!p_texture) {
  115. return nullptr;
  116. }
  117. for (const ufbx_texture *texture : p_texture->file_textures) {
  118. if (texture->file_index != UFBX_NO_INDEX) {
  119. return texture;
  120. }
  121. }
  122. return nullptr;
  123. }
  124. static Ref<Image> _get_decompressed_image(Ref<Texture2D> texture) {
  125. if (texture.is_null()) {
  126. return Ref<Image>();
  127. }
  128. Ref<Image> image = texture->get_image();
  129. if (image.is_null()) {
  130. return Ref<Image>();
  131. }
  132. image = image->duplicate();
  133. image->decompress();
  134. return image;
  135. }
  136. static Vector<Vector2> _decode_vertex_attrib_vec2(const ufbx_vertex_vec2 &p_attrib, const Vector<uint32_t> &p_indices) {
  137. Vector<Vector2> ret;
  138. int num_indices = p_indices.size();
  139. ret.resize(num_indices);
  140. for (int i = 0; i < num_indices; i++) {
  141. ret.write[i] = _as_vec2(p_attrib[p_indices[i]]);
  142. }
  143. return ret;
  144. }
  145. static Vector<Vector3> _decode_vertex_attrib_vec3(const ufbx_vertex_vec3 &p_attrib, const Vector<uint32_t> &p_indices) {
  146. Vector<Vector3> ret;
  147. int num_indices = p_indices.size();
  148. ret.resize(num_indices);
  149. for (int i = 0; i < num_indices; i++) {
  150. ret.write[i] = FBXDocument::_as_vec3(p_attrib[p_indices[i]]);
  151. }
  152. return ret;
  153. }
  154. static Vector<float> _decode_vertex_attrib_vec3_as_tangent(const ufbx_vertex_vec3 &p_attrib, const Vector<uint32_t> &p_indices) {
  155. Vector<float> ret;
  156. int num_indices = p_indices.size();
  157. ret.resize(num_indices * 4);
  158. for (int i = 0; i < num_indices; i++) {
  159. Vector3 v = FBXDocument::_as_vec3(p_attrib[p_indices[i]]);
  160. ret.write[i * 4 + 0] = v.x;
  161. ret.write[i * 4 + 1] = v.y;
  162. ret.write[i * 4 + 2] = v.z;
  163. ret.write[i * 4 + 3] = 1.0f;
  164. }
  165. return ret;
  166. }
  167. static Vector<Color> _decode_vertex_attrib_color(const ufbx_vertex_vec4 &p_attrib, const Vector<uint32_t> &p_indices) {
  168. Vector<Color> ret;
  169. int num_indices = p_indices.size();
  170. ret.resize(num_indices);
  171. for (int i = 0; i < num_indices; i++) {
  172. ret.write[i] = _as_color(p_attrib[p_indices[i]]);
  173. }
  174. return ret;
  175. }
  176. static Vector3 _encode_vertex_index(uint32_t p_index) {
  177. return Vector3(real_t(p_index & 0xffff), real_t(p_index >> 16), 0.0f);
  178. }
  179. static uint32_t _decode_vertex_index(const Vector3 &p_vertex) {
  180. return uint32_t(p_vertex.x) | uint32_t(p_vertex.y) << 16;
  181. }
  182. static ufbx_skin_deformer *_find_skin_deformer(ufbx_skin_cluster *p_cluster) {
  183. for (const ufbx_connection &conn : p_cluster->element.connections_src) {
  184. ufbx_skin_deformer *deformer = ufbx_as_skin_deformer(conn.dst);
  185. if (deformer) {
  186. return deformer;
  187. }
  188. }
  189. return nullptr;
  190. }
  191. static String _find_element_name(ufbx_element *p_element) {
  192. if (p_element->name.length > 0) {
  193. return FBXDocument::_as_string(p_element->name);
  194. } else if (p_element->instances.count > 0) {
  195. return _find_element_name(&p_element->instances[0]->element);
  196. } else {
  197. return "";
  198. }
  199. }
  200. struct ThreadPoolFBX {
  201. struct Group {
  202. ufbx_thread_pool_context ctx = {};
  203. WorkerThreadPool::GroupID task_id = {};
  204. uint32_t start_index = 0;
  205. };
  206. WorkerThreadPool *pool = nullptr;
  207. Group groups[UFBX_THREAD_GROUP_COUNT] = {};
  208. };
  209. static void _thread_pool_task(void *user, uint32_t index) {
  210. ThreadPoolFBX::Group *group = (ThreadPoolFBX::Group *)user;
  211. ufbx_thread_pool_run_task(group->ctx, group->start_index + index);
  212. }
  213. static bool _thread_pool_init_fn(void *user, ufbx_thread_pool_context ctx, const ufbx_thread_pool_info *info) {
  214. ThreadPoolFBX *pool = (ThreadPoolFBX *)user;
  215. for (ThreadPoolFBX::Group &group : pool->groups) {
  216. group.ctx = ctx;
  217. }
  218. return true;
  219. }
  220. static bool _thread_pool_run_fn(void *user, ufbx_thread_pool_context ctx, uint32_t group, uint32_t start_index, uint32_t count) {
  221. ThreadPoolFBX *pool = (ThreadPoolFBX *)user;
  222. ThreadPoolFBX::Group &pool_group = pool->groups[group];
  223. pool_group.start_index = start_index;
  224. pool_group.task_id = pool->pool->add_native_group_task(_thread_pool_task, &pool_group, (int)count, -1, true, "ufbx");
  225. return true;
  226. }
  227. static bool _thread_pool_wait_fn(void *user, ufbx_thread_pool_context ctx, uint32_t group, uint32_t max_index) {
  228. ThreadPoolFBX *pool = (ThreadPoolFBX *)user;
  229. pool->pool->wait_for_group_task_completion(pool->groups[group].task_id);
  230. return true;
  231. }
  232. String FBXDocument::_gen_unique_name(HashSet<String> &unique_names, const String &p_name) {
  233. const String s_name = p_name.validate_node_name();
  234. String u_name;
  235. int index = 1;
  236. while (true) {
  237. u_name = s_name;
  238. if (index > 1) {
  239. u_name += itos(index);
  240. }
  241. if (!unique_names.has(u_name)) {
  242. break;
  243. }
  244. index++;
  245. }
  246. unique_names.insert(u_name);
  247. return u_name;
  248. }
  249. String FBXDocument::_sanitize_animation_name(const String &p_name) {
  250. // Animations disallow the normal node invalid characters as well as "," and "["
  251. // (See animation/animation_player.cpp::add_animation)
  252. // TODO: Consider adding invalid_characters or a validate_animation_name to animation_player to mirror Node.
  253. String anim_name = p_name.validate_node_name();
  254. anim_name = anim_name.replace(",", "");
  255. anim_name = anim_name.replace("[", "");
  256. return anim_name;
  257. }
  258. String FBXDocument::_gen_unique_animation_name(Ref<FBXState> p_state, const String &p_name) {
  259. const String s_name = _sanitize_animation_name(p_name);
  260. String u_name;
  261. int index = 1;
  262. while (true) {
  263. u_name = s_name;
  264. if (index > 1) {
  265. u_name += itos(index);
  266. }
  267. if (!p_state->unique_animation_names.has(u_name)) {
  268. break;
  269. }
  270. index++;
  271. }
  272. p_state->unique_animation_names.insert(u_name);
  273. return u_name;
  274. }
  275. Error FBXDocument::_parse_scenes(Ref<FBXState> p_state) {
  276. p_state->unique_names.insert("Skeleton3D"); // Reserve skeleton name.
  277. const ufbx_scene *fbx_scene = p_state->scene.get();
  278. // TODO: Multi-document support, would need test files for structure
  279. p_state->scene_name = "";
  280. // TODO: Append the root node directly if we use root-based space conversion
  281. for (const ufbx_node *root_node : fbx_scene->root_node->children) {
  282. p_state->root_nodes.push_back(int(root_node->typed_id));
  283. }
  284. return OK;
  285. }
  286. Error FBXDocument::_parse_nodes(Ref<FBXState> p_state) {
  287. const ufbx_scene *fbx_scene = p_state->scene.get();
  288. for (int node_i = 0; node_i < static_cast<int>(fbx_scene->nodes.count); node_i++) {
  289. const ufbx_node *fbx_node = fbx_scene->nodes[node_i];
  290. Ref<GLTFNode> node;
  291. node.instantiate();
  292. node->height = int(fbx_node->node_depth);
  293. if (fbx_node->name.length > 0) {
  294. node->set_name(_as_string(fbx_node->name));
  295. node->set_original_name(node->get_name());
  296. } else if (fbx_node->is_root) {
  297. node->set_name("RootNode");
  298. }
  299. if (fbx_node->camera) {
  300. node->camera = fbx_node->camera->typed_id;
  301. }
  302. if (fbx_node->light) {
  303. node->light = fbx_node->light->typed_id;
  304. }
  305. if (fbx_node->mesh) {
  306. node->mesh = fbx_node->mesh->typed_id;
  307. }
  308. {
  309. node->transform = _as_transform(fbx_node->local_transform);
  310. bool found_rest_xform = false;
  311. bool bad_rest_xform = false;
  312. Transform3D candidate_rest_xform;
  313. if (fbx_node->parent) {
  314. // Attempt to resolve a rest pose for bones: This uses internal FBX connections to find
  315. // all skin clusters connected to the bone.
  316. for (const ufbx_connection &child_conn : fbx_node->element.connections_src) {
  317. ufbx_skin_cluster *child_cluster = ufbx_as_skin_cluster(child_conn.dst);
  318. if (!child_cluster)
  319. continue;
  320. ufbx_skin_deformer *child_deformer = _find_skin_deformer(child_cluster);
  321. if (!child_deformer)
  322. continue;
  323. // Found a skin cluster: Now iterate through all the skin clusters of the parent and
  324. // try to find one that used by the same deformer.
  325. for (const ufbx_connection &parent_conn : fbx_node->parent->element.connections_src) {
  326. ufbx_skin_cluster *parent_cluster = ufbx_as_skin_cluster(parent_conn.dst);
  327. if (!parent_cluster)
  328. continue;
  329. ufbx_skin_deformer *parent_deformer = _find_skin_deformer(parent_cluster);
  330. if (parent_deformer != child_deformer)
  331. continue;
  332. // Success: Found two skin clusters from the same deformer, now we can resolve the
  333. // local bind pose from the difference between the two world-space bind poses.
  334. ufbx_matrix child_to_world = child_cluster->bind_to_world;
  335. ufbx_matrix world_to_parent = ufbx_matrix_invert(&parent_cluster->bind_to_world);
  336. ufbx_matrix child_to_parent = ufbx_matrix_mul(&world_to_parent, &child_to_world);
  337. Transform3D xform = _as_transform(ufbx_matrix_to_transform(&child_to_parent));
  338. if (!found_rest_xform) {
  339. // Found the first bind pose for the node, assume that this one is good
  340. found_rest_xform = true;
  341. candidate_rest_xform = xform;
  342. } else if (!bad_rest_xform) {
  343. // Found another: Let's hope it's similar to the previous one, if not warn and
  344. // use the initial pose, which is used by default if rest pose is not found.
  345. real_t error = 0.0f;
  346. error += _relative_error(candidate_rest_xform.origin, xform.origin);
  347. for (int i = 0; i < 3; i++) {
  348. error += _relative_error(candidate_rest_xform.basis.rows[i], xform.basis.rows[i]);
  349. }
  350. const real_t max_error = 0.01f;
  351. if (error >= max_error) {
  352. WARN_PRINT(vformat("FBX: Node '%s' has multiple bind poses, using initial pose as rest pose.", node->get_name()));
  353. bad_rest_xform = true;
  354. }
  355. }
  356. }
  357. }
  358. }
  359. Transform3D godot_rest_xform = node->transform;
  360. if (found_rest_xform && !bad_rest_xform) {
  361. godot_rest_xform = candidate_rest_xform;
  362. }
  363. node->set_additional_data("GODOT_rest_transform", godot_rest_xform);
  364. }
  365. for (const ufbx_node *child : fbx_node->children) {
  366. node->children.push_back(child->typed_id);
  367. }
  368. p_state->nodes.push_back(node);
  369. }
  370. // build the hierarchy
  371. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); node_i++) {
  372. for (int j = 0; j < p_state->nodes[node_i]->children.size(); j++) {
  373. GLTFNodeIndex child_i = p_state->nodes[node_i]->children[j];
  374. ERR_FAIL_INDEX_V(child_i, p_state->nodes.size(), ERR_FILE_CORRUPT);
  375. ERR_CONTINUE(p_state->nodes[child_i]->parent != -1); //node already has a parent, wtf.
  376. p_state->nodes.write[child_i]->parent = node_i;
  377. }
  378. }
  379. return OK;
  380. }
  381. Error FBXDocument::_parse_meshes(Ref<FBXState> p_state) {
  382. ufbx_scene *fbx_scene = p_state->scene.get();
  383. LocalVector<int> nodes_by_mesh_id;
  384. nodes_by_mesh_id.reserve(fbx_scene->meshes.count);
  385. for (size_t i = 0; i < fbx_scene->meshes.count; i++) {
  386. nodes_by_mesh_id.push_back(-1);
  387. }
  388. for (int i = 0; i < p_state->nodes.size(); i++) {
  389. const Ref<GLTFNode> &node = p_state->nodes[i];
  390. if (node->mesh >= 0 && (unsigned)node->mesh < nodes_by_mesh_id.size()) {
  391. nodes_by_mesh_id[node->mesh] = i;
  392. }
  393. }
  394. for (const ufbx_mesh *fbx_mesh : fbx_scene->meshes) {
  395. print_verbose("FBX: Parsing mesh: " + itos(int64_t(fbx_mesh->typed_id)));
  396. static const Mesh::PrimitiveType primitive_types[] = {
  397. Mesh::PRIMITIVE_TRIANGLES,
  398. Mesh::PRIMITIVE_POINTS,
  399. Mesh::PRIMITIVE_LINES,
  400. };
  401. Ref<ImporterMesh> import_mesh;
  402. import_mesh.instantiate();
  403. String mesh_name = "mesh";
  404. String original_name;
  405. if (fbx_mesh->name.length > 0) {
  406. mesh_name = _as_string(fbx_mesh->name);
  407. original_name = mesh_name;
  408. } else if (fbx_mesh->typed_id < (unsigned)p_state->nodes.size() && nodes_by_mesh_id[fbx_mesh->typed_id] != -1) {
  409. const Ref<GLTFNode> &node = p_state->nodes[nodes_by_mesh_id[fbx_mesh->typed_id]];
  410. original_name = node->get_original_name();
  411. mesh_name = node->get_name();
  412. }
  413. import_mesh->set_name(_gen_unique_name(p_state->unique_mesh_names, mesh_name));
  414. bool use_blend_shapes = false;
  415. if (fbx_mesh->blend_deformers.count > 0) {
  416. use_blend_shapes = true;
  417. }
  418. Vector<float> blend_weights;
  419. Vector<int> blend_channels;
  420. if (use_blend_shapes) {
  421. print_verbose("FBX: Mesh has targets");
  422. import_mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  423. for (const ufbx_blend_deformer *fbx_deformer : fbx_mesh->blend_deformers) {
  424. for (const ufbx_blend_channel *fbx_channel : fbx_deformer->channels) {
  425. if (fbx_channel->keyframes.count == 0) {
  426. continue;
  427. }
  428. String bs_name;
  429. if (fbx_channel->name.length > 0) {
  430. bs_name = _as_string(fbx_channel->name);
  431. } else {
  432. bs_name = String("morph_") + itos(blend_channels.size());
  433. }
  434. import_mesh->add_blend_shape(bs_name);
  435. blend_weights.push_back(float(fbx_channel->weight));
  436. blend_channels.push_back(float(fbx_channel->typed_id));
  437. }
  438. }
  439. }
  440. for (const ufbx_mesh_part &fbx_mesh_part : fbx_mesh->material_parts) {
  441. for (Mesh::PrimitiveType primitive : primitive_types) {
  442. uint32_t num_indices = 0;
  443. switch (primitive) {
  444. case Mesh::PRIMITIVE_POINTS:
  445. num_indices = fbx_mesh_part.num_point_faces * 1;
  446. break;
  447. case Mesh::PRIMITIVE_LINES:
  448. num_indices = fbx_mesh_part.num_line_faces * 2;
  449. break;
  450. case Mesh::PRIMITIVE_TRIANGLES:
  451. num_indices = fbx_mesh_part.num_triangles * 3;
  452. break;
  453. case Mesh::PRIMITIVE_TRIANGLE_STRIP:
  454. // FIXME 2021-09-15 fire
  455. break;
  456. case Mesh::PRIMITIVE_LINE_STRIP:
  457. // FIXME 2021-09-15 fire
  458. break;
  459. default:
  460. // FIXME 2021-09-15 fire
  461. break;
  462. }
  463. if (num_indices == 0) {
  464. continue;
  465. }
  466. Vector<uint32_t> indices;
  467. indices.resize(num_indices);
  468. uint32_t offset = 0;
  469. for (uint32_t face_index : fbx_mesh_part.face_indices) {
  470. ufbx_face face = fbx_mesh->faces[face_index];
  471. switch (primitive) {
  472. case Mesh::PRIMITIVE_POINTS: {
  473. if (face.num_indices == 1) {
  474. indices.write[offset] = face.index_begin;
  475. offset += 1;
  476. }
  477. } break;
  478. case Mesh::PRIMITIVE_LINES:
  479. if (face.num_indices == 2) {
  480. indices.write[offset] = face.index_begin;
  481. indices.write[offset + 1] = face.index_begin + 1;
  482. offset += 2;
  483. }
  484. break;
  485. case Mesh::PRIMITIVE_TRIANGLES:
  486. if (face.num_indices >= 3) {
  487. uint32_t *dst = indices.ptrw() + offset;
  488. size_t space = indices.size() - offset;
  489. uint32_t num_triangles = ufbx_triangulate_face(dst, space, fbx_mesh, face);
  490. offset += num_triangles * 3;
  491. // Godot uses clockwise winding order!
  492. for (uint32_t i = 0; i < num_triangles; i++) {
  493. SWAP(dst[i * 3 + 0], dst[i * 3 + 2]);
  494. }
  495. }
  496. break;
  497. case Mesh::PRIMITIVE_TRIANGLE_STRIP:
  498. // FIXME 2021-09-15 fire
  499. break;
  500. case Mesh::PRIMITIVE_LINE_STRIP:
  501. // FIXME 2021-09-15 fire
  502. break;
  503. default:
  504. // FIXME 2021-09-15 fire
  505. break;
  506. }
  507. }
  508. ERR_CONTINUE((uint64_t)offset != (uint64_t)indices.size());
  509. int32_t vertex_num = indices.size();
  510. bool has_vertex_color = false;
  511. uint32_t flags = 0;
  512. Array array;
  513. array.resize(Mesh::ARRAY_MAX);
  514. // HACK: If we have blend shapes we cannot merge vertices at identical positions
  515. // if they have different indices in the file. To avoid this encode the vertex index
  516. // into the vertex position for the time being.
  517. // Ideally this would be an extra channel in the vertex but as the vertex format is
  518. // fixed and we already use user data for extra UV channels this'll do.
  519. if (use_blend_shapes) {
  520. Vector<Vector3> vertex_indices;
  521. int num_blend_shape_indices = indices.size();
  522. vertex_indices.resize(num_blend_shape_indices);
  523. for (int i = 0; i < num_blend_shape_indices; i++) {
  524. vertex_indices.write[i] = _encode_vertex_index(fbx_mesh->vertex_indices[indices[i]]);
  525. }
  526. array[Mesh::ARRAY_VERTEX] = vertex_indices;
  527. } else {
  528. array[Mesh::ARRAY_VERTEX] = _decode_vertex_attrib_vec3(fbx_mesh->vertex_position, indices);
  529. }
  530. // Normals always exist as they're generated if missing,
  531. // see `ufbx_load_opts.generate_missing_normals`.
  532. Vector<Vector3> normals = _decode_vertex_attrib_vec3(fbx_mesh->vertex_normal, indices);
  533. array[Mesh::ARRAY_NORMAL] = normals;
  534. if (fbx_mesh->vertex_tangent.exists) {
  535. Vector<float> tangents = _decode_vertex_attrib_vec3_as_tangent(fbx_mesh->vertex_tangent, indices);
  536. // Patch bitangent sign if available
  537. if (fbx_mesh->vertex_bitangent.exists) {
  538. for (int i = 0; i < vertex_num; i++) {
  539. Vector3 tangent = Vector3(tangents[i * 4], tangents[i * 4 + 1], tangents[i * 4 + 2]);
  540. Vector3 bitangent = _as_vec3(fbx_mesh->vertex_bitangent[indices[i]]);
  541. Vector3 generated_bitangent = normals[i].cross(tangent);
  542. if (generated_bitangent.dot(bitangent) < 0.0f) {
  543. tangents.write[i * 4 + 3] = -1.0f;
  544. }
  545. }
  546. }
  547. array[Mesh::ARRAY_TANGENT] = tangents;
  548. }
  549. if (fbx_mesh->vertex_uv.exists) {
  550. PackedVector2Array uv_array = _decode_vertex_attrib_vec2(fbx_mesh->vertex_uv, indices);
  551. _process_uv_set(uv_array);
  552. array[Mesh::ARRAY_TEX_UV] = uv_array;
  553. }
  554. if (fbx_mesh->uv_sets.count >= 2 && fbx_mesh->uv_sets[1].vertex_uv.exists) {
  555. PackedVector2Array uv2_array = _decode_vertex_attrib_vec2(fbx_mesh->uv_sets[1].vertex_uv, indices);
  556. _process_uv_set(uv2_array);
  557. array[Mesh::ARRAY_TEX_UV2] = uv2_array;
  558. }
  559. for (int uv_i = 2; uv_i < 8; uv_i += 2) {
  560. Vector<float> cur_custom;
  561. Vector<Vector2> texcoord_first;
  562. Vector<Vector2> texcoord_second;
  563. int texcoord_i = uv_i;
  564. int texcoord_next = texcoord_i + 1;
  565. int num_channels = 0;
  566. if (texcoord_i < static_cast<int>(fbx_mesh->uv_sets.count) && fbx_mesh->uv_sets[texcoord_i].vertex_uv.exists) {
  567. texcoord_first = _decode_vertex_attrib_vec2(fbx_mesh->uv_sets[texcoord_i].vertex_uv, indices);
  568. _process_uv_set(texcoord_first);
  569. num_channels = 2;
  570. }
  571. if (texcoord_next < static_cast<int>(fbx_mesh->uv_sets.count) && fbx_mesh->uv_sets[texcoord_next].vertex_uv.exists) {
  572. texcoord_second = _decode_vertex_attrib_vec2(fbx_mesh->uv_sets[texcoord_next].vertex_uv, indices);
  573. _process_uv_set(texcoord_second);
  574. num_channels = 4;
  575. }
  576. if (!num_channels) {
  577. break;
  578. }
  579. cur_custom.resize(vertex_num * num_channels);
  580. for (int32_t uv_first_i = 0; uv_first_i < texcoord_first.size() && uv_first_i < vertex_num; uv_first_i++) {
  581. int index = uv_first_i * num_channels;
  582. cur_custom.write[index] = texcoord_first[uv_first_i].x;
  583. cur_custom.write[index + 1] = texcoord_first[uv_first_i].y;
  584. }
  585. if (num_channels == 4) {
  586. for (int32_t uv_second_i = 0; uv_second_i < texcoord_second.size() && uv_second_i < vertex_num; uv_second_i++) {
  587. int index = uv_second_i * num_channels;
  588. cur_custom.write[index + 2] = texcoord_second[uv_second_i].x;
  589. cur_custom.write[index + 3] = texcoord_second[uv_second_i].y;
  590. }
  591. _zero_unused_elements(cur_custom, texcoord_second.size(), vertex_num, num_channels);
  592. } else if (num_channels == 2) {
  593. _zero_unused_elements(cur_custom, texcoord_first.size(), vertex_num, num_channels);
  594. }
  595. if (!cur_custom.is_empty()) {
  596. array[Mesh::ARRAY_CUSTOM0 + ((uv_i - 2) / 2)] = cur_custom; // Map uv2-uv7 to custom0-custom2
  597. int custom_shift = Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT + ((uv_i - 2) / 2) * Mesh::ARRAY_FORMAT_CUSTOM_BITS;
  598. flags |= (num_channels == 2 ? Mesh::ARRAY_CUSTOM_RG_FLOAT : Mesh::ARRAY_CUSTOM_RGBA_FLOAT) << custom_shift;
  599. }
  600. }
  601. if (fbx_mesh->vertex_color.exists) {
  602. array[Mesh::ARRAY_COLOR] = _decode_vertex_attrib_color(fbx_mesh->vertex_color, indices);
  603. has_vertex_color = true;
  604. }
  605. int32_t num_skin_weights = 0;
  606. // Find the first imported skin deformer
  607. for (ufbx_skin_deformer *fbx_skin : fbx_mesh->skin_deformers) {
  608. GLTFSkinIndex skin_i = p_state->original_skin_indices[fbx_skin->typed_id];
  609. if (skin_i < 0) {
  610. continue;
  611. }
  612. // Tag all nodes to use the skin
  613. for (const ufbx_node *node : fbx_mesh->instances) {
  614. p_state->nodes[node->typed_id]->skin = skin_i;
  615. }
  616. num_skin_weights = fbx_skin->max_weights_per_vertex > 4 ? 8 : 4;
  617. Vector<int32_t> bones;
  618. Vector<float> weights;
  619. bones.resize(vertex_num * num_skin_weights);
  620. weights.resize(vertex_num * num_skin_weights);
  621. for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
  622. uint32_t fbx_vertex_index = fbx_mesh->vertex_indices[indices[vertex_i]];
  623. ufbx_skin_vertex skin_vertex = fbx_skin->vertices[fbx_vertex_index];
  624. float total_weight = 0.0f;
  625. int32_t num_weights = MIN(int32_t(skin_vertex.num_weights), num_skin_weights);
  626. for (int32_t i = 0; i < num_weights; i++) {
  627. ufbx_skin_weight skin_weight = fbx_skin->weights[skin_vertex.weight_begin + i];
  628. int index = vertex_i * num_skin_weights + i;
  629. float weight = float(skin_weight.weight);
  630. bones.write[index] = int(skin_weight.cluster_index);
  631. weights.write[index] = weight;
  632. total_weight += weight;
  633. }
  634. if (total_weight > 0.0f) {
  635. for (int32_t i = 0; i < num_weights; i++) {
  636. int index = vertex_i * num_skin_weights + i;
  637. weights.write[index] /= total_weight;
  638. }
  639. }
  640. // Pad the rest with empty weights
  641. for (int32_t i = num_weights; i < num_skin_weights; i++) {
  642. int index = vertex_i * num_skin_weights + i;
  643. bones.write[index] = 0; // TODO: What should this be padded with?
  644. weights.write[index] = 0.0f;
  645. }
  646. }
  647. array[Mesh::ARRAY_BONES] = bones;
  648. array[Mesh::ARRAY_WEIGHTS] = weights;
  649. if (num_skin_weights == 8) {
  650. flags |= Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  651. }
  652. // Only use the first found skin
  653. break;
  654. }
  655. bool generate_tangents = (primitive == Mesh::PRIMITIVE_TRIANGLES && !array[Mesh::ARRAY_TANGENT] && array[Mesh::ARRAY_TEX_UV] && array[Mesh::ARRAY_NORMAL]);
  656. Ref<SurfaceTool> mesh_surface_tool;
  657. mesh_surface_tool.instantiate();
  658. mesh_surface_tool->create_from_triangle_arrays(array);
  659. mesh_surface_tool->set_skin_weight_count(num_skin_weights == 8 ? SurfaceTool::SKIN_8_WEIGHTS : SurfaceTool::SKIN_4_WEIGHTS);
  660. mesh_surface_tool->index();
  661. if (generate_tangents) {
  662. //must generate mikktspace tangents.. ergh..
  663. mesh_surface_tool->generate_tangents();
  664. }
  665. array = mesh_surface_tool->commit_to_arrays();
  666. Array morphs;
  667. //blend shapes
  668. if (use_blend_shapes) {
  669. print_verbose("FBX: Mesh has targets");
  670. import_mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  671. for (const ufbx_blend_deformer *fbx_deformer : fbx_mesh->blend_deformers) {
  672. for (const ufbx_blend_channel *fbx_channel : fbx_deformer->channels) {
  673. if (fbx_channel->keyframes.count == 0) {
  674. continue;
  675. }
  676. // Use the last shape keyframe by default
  677. ufbx_blend_shape *fbx_shape = fbx_channel->keyframes[fbx_channel->keyframes.count - 1].shape;
  678. Array array_copy;
  679. array_copy.resize(Mesh::ARRAY_MAX);
  680. for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
  681. array_copy[l] = array[l];
  682. }
  683. Vector<Vector3> varr;
  684. Vector<Vector3> narr;
  685. const Vector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
  686. const Vector<Vector3> src_narr = array[Mesh::ARRAY_NORMAL];
  687. const int size = src_varr.size();
  688. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  689. {
  690. varr.resize(size);
  691. narr.resize(size);
  692. Vector3 *w_varr = varr.ptrw();
  693. Vector3 *w_narr = narr.ptrw();
  694. const Vector3 *r_varr = src_varr.ptr();
  695. const Vector3 *r_narr = src_narr.ptr();
  696. for (int l = 0; l < size; l++) {
  697. uint32_t vertex_index = _decode_vertex_index(r_varr[l]);
  698. uint32_t offset_index = ufbx_get_blend_shape_offset_index(fbx_shape, vertex_index);
  699. Vector3 position = _as_vec3(fbx_mesh->vertices[vertex_index]);
  700. Vector3 normal = r_narr[l];
  701. if (offset_index != UFBX_NO_INDEX && offset_index < fbx_shape->position_offsets.count) {
  702. Vector3 blend_shape_position_offset = _as_vec3(fbx_shape->position_offsets[offset_index]);
  703. w_varr[l] = position + blend_shape_position_offset;
  704. } else {
  705. w_varr[l] = position;
  706. }
  707. if (offset_index != UFBX_NO_INDEX && offset_index < fbx_shape->normal_offsets.count) {
  708. w_narr[l] = (normal.normalized() + _as_vec3(fbx_shape->normal_offsets[offset_index])).normalized();
  709. } else {
  710. w_narr[l] = normal;
  711. }
  712. }
  713. }
  714. array_copy[Mesh::ARRAY_VERTEX] = varr;
  715. array_copy[Mesh::ARRAY_NORMAL] = narr;
  716. Ref<SurfaceTool> blend_surface_tool;
  717. blend_surface_tool.instantiate();
  718. blend_surface_tool->create_from_triangle_arrays(array_copy);
  719. blend_surface_tool->set_skin_weight_count(num_skin_weights == 8 ? SurfaceTool::SKIN_8_WEIGHTS : SurfaceTool::SKIN_4_WEIGHTS);
  720. if (generate_tangents) {
  721. //must generate mikktspace tangents.. ergh..
  722. blend_surface_tool->generate_tangents();
  723. }
  724. array_copy = blend_surface_tool->commit_to_arrays();
  725. // Enforce blend shape mask array format
  726. for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
  727. if (!(Mesh::ARRAY_FORMAT_BLEND_SHAPE_MASK & (static_cast<int64_t>(1) << l))) {
  728. array_copy[l] = Variant();
  729. }
  730. }
  731. morphs.push_back(array_copy);
  732. }
  733. }
  734. }
  735. // Decode the original vertex positions now that we're done processing blend shapes.
  736. if (use_blend_shapes) {
  737. Vector<Vector3> varr = array[Mesh::ARRAY_VERTEX];
  738. Vector3 *w_varr = varr.ptrw();
  739. const int size = varr.size();
  740. for (int i = 0; i < size; i++) {
  741. uint32_t vertex_index = _decode_vertex_index(w_varr[i]);
  742. w_varr[i] = _as_vec3(fbx_mesh->vertices[vertex_index]);
  743. }
  744. array[Mesh::ARRAY_VERTEX] = varr;
  745. }
  746. Ref<Material> mat;
  747. String mat_name;
  748. if (!p_state->discard_meshes_and_materials) {
  749. ufbx_material *fbx_material = nullptr;
  750. if (fbx_mesh_part.index < fbx_mesh->materials.count) {
  751. fbx_material = fbx_mesh->materials[fbx_mesh_part.index];
  752. }
  753. if (fbx_material) {
  754. const int material = int(fbx_material->typed_id);
  755. ERR_FAIL_INDEX_V(material, p_state->materials.size(), ERR_FILE_CORRUPT);
  756. Ref<Material> mat3d = p_state->materials[material];
  757. ERR_FAIL_NULL_V(mat3d, ERR_FILE_CORRUPT);
  758. Ref<BaseMaterial3D> base_material = mat3d;
  759. if (has_vertex_color && base_material.is_valid()) {
  760. base_material->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  761. }
  762. mat = mat3d;
  763. } else {
  764. Ref<StandardMaterial3D> mat3d;
  765. mat3d.instantiate();
  766. if (has_vertex_color) {
  767. mat3d->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  768. }
  769. mat = mat3d;
  770. }
  771. ERR_FAIL_NULL_V(mat, ERR_FILE_CORRUPT);
  772. mat_name = mat->get_name();
  773. }
  774. import_mesh->add_surface(primitive, array, morphs,
  775. Dictionary(), mat, mat_name, flags);
  776. }
  777. }
  778. Ref<GLTFMesh> mesh;
  779. mesh.instantiate();
  780. Dictionary additional_data;
  781. additional_data["blend_channels"] = blend_channels;
  782. mesh->set_additional_data("GODOT_mesh_blend_channels", additional_data);
  783. mesh->set_blend_weights(blend_weights);
  784. mesh->set_mesh(import_mesh);
  785. mesh->set_name(import_mesh->get_name());
  786. mesh->set_original_name(original_name);
  787. p_state->meshes.push_back(mesh);
  788. }
  789. print_verbose("FBX: Total meshes: " + itos(p_state->meshes.size()));
  790. return OK;
  791. }
  792. Ref<Image> FBXDocument::_parse_image_bytes_into_image(Ref<FBXState> p_state, const Vector<uint8_t> &p_bytes, const String &p_filename, int p_index) {
  793. Ref<Image> r_image;
  794. r_image.instantiate();
  795. // Try to import first based on filename.
  796. String filename_lower = p_filename.to_lower();
  797. if (filename_lower.ends_with(".png")) {
  798. r_image->load_png_from_buffer(p_bytes);
  799. } else if (filename_lower.ends_with(".jpg")) {
  800. r_image->load_jpg_from_buffer(p_bytes);
  801. } else if (filename_lower.ends_with(".tga")) {
  802. r_image->load_tga_from_buffer(p_bytes);
  803. }
  804. // If we didn't pass the above tests, try loading as each option.
  805. if (r_image->is_empty()) { // Try PNG first.
  806. r_image->load_png_from_buffer(p_bytes);
  807. }
  808. if (r_image->is_empty()) { // And then JPEG.
  809. r_image->load_jpg_from_buffer(p_bytes);
  810. }
  811. if (r_image->is_empty()) { // And then TGA.
  812. r_image->load_jpg_from_buffer(p_bytes);
  813. }
  814. // If it still can't be loaded, give up and insert an empty image as placeholder.
  815. if (r_image->is_empty()) {
  816. ERR_PRINT(vformat("FBX: Couldn't load image index '%d'", p_index));
  817. }
  818. return r_image;
  819. }
  820. GLTFImageIndex FBXDocument::_parse_image_save_image(Ref<FBXState> p_state, const Vector<uint8_t> &p_bytes, const String &p_file_extension, int p_index, Ref<Image> p_image) {
  821. FBXState::GLTFHandleBinary handling = FBXState::GLTFHandleBinary(p_state->handle_binary_image);
  822. if (p_image->is_empty() || handling == FBXState::GLTFHandleBinary::HANDLE_BINARY_DISCARD_TEXTURES) {
  823. if (p_index < 0) {
  824. return -1;
  825. }
  826. p_state->images.push_back(Ref<Texture2D>());
  827. p_state->source_images.push_back(Ref<Image>());
  828. return p_state->images.size() - 1;
  829. }
  830. #ifdef TOOLS_ENABLED
  831. if (Engine::get_singleton()->is_editor_hint() && handling == FBXState::GLTFHandleBinary::HANDLE_BINARY_EXTRACT_TEXTURES) {
  832. if (p_state->base_path.is_empty()) {
  833. if (p_index < 0) {
  834. return -1;
  835. }
  836. p_state->images.push_back(Ref<Texture2D>());
  837. p_state->source_images.push_back(Ref<Image>());
  838. } else if (p_image->get_name().is_empty()) {
  839. if (p_index < 0) {
  840. return -1;
  841. }
  842. WARN_PRINT(vformat("FBX: Image index '%d' couldn't be named. Skipping it.", p_index));
  843. p_state->images.push_back(Ref<Texture2D>());
  844. p_state->source_images.push_back(Ref<Image>());
  845. } else {
  846. bool must_import = true;
  847. Vector<uint8_t> img_data = p_image->get_data();
  848. Dictionary generator_parameters;
  849. String file_path = p_state->get_base_path().path_join(p_state->filename.get_basename() + "_" + p_image->get_name());
  850. file_path += p_file_extension.is_empty() ? ".png" : p_file_extension;
  851. if (FileAccess::exists(file_path + ".import")) {
  852. Ref<ConfigFile> config;
  853. config.instantiate();
  854. config->load(file_path + ".import");
  855. if (config->has_section_key("remap", "generator_parameters")) {
  856. generator_parameters = (Dictionary)config->get_value("remap", "generator_parameters");
  857. }
  858. if (!generator_parameters.has("md5")) {
  859. must_import = false; // Didn't come from a gltf document; don't overwrite.
  860. }
  861. }
  862. if (must_import) {
  863. String existing_md5 = generator_parameters["md5"];
  864. unsigned char md5_hash[16];
  865. CryptoCore::md5(img_data.ptr(), img_data.size(), md5_hash);
  866. String new_md5 = String::hex_encode_buffer(md5_hash, 16);
  867. generator_parameters["md5"] = new_md5;
  868. if (new_md5 == existing_md5) {
  869. must_import = false;
  870. }
  871. }
  872. if (must_import) {
  873. Error err = OK;
  874. if (p_file_extension.is_empty()) {
  875. // If a file extension was not specified, save the image data to a PNG file.
  876. err = p_image->save_png(file_path);
  877. ERR_FAIL_COND_V(err != OK, -1);
  878. } else {
  879. // If a file extension was specified, save the original bytes to a file with that extension.
  880. Ref<FileAccess> file = FileAccess::open(file_path, FileAccess::WRITE, &err);
  881. ERR_FAIL_COND_V(err != OK, -1);
  882. file->store_buffer(p_bytes);
  883. file->close();
  884. }
  885. // ResourceLoader::import will crash if not is_editor_hint(), so this case is protected above and will fall through to uncompressed.
  886. HashMap<StringName, Variant> custom_options;
  887. custom_options[SNAME("mipmaps/generate")] = true;
  888. // Will only use project settings defaults if custom_importer is empty.
  889. EditorFileSystem::get_singleton()->update_file(file_path);
  890. EditorFileSystem::get_singleton()->reimport_append(file_path, custom_options, String(), generator_parameters);
  891. }
  892. Ref<Texture2D> saved_image = ResourceLoader::load(_get_texture_path(p_state->get_base_path(), file_path), "Texture2D");
  893. if (saved_image.is_valid()) {
  894. p_state->images.push_back(saved_image);
  895. p_state->source_images.push_back(saved_image->get_image());
  896. } else if (p_index < 0) {
  897. return -1;
  898. } else {
  899. WARN_PRINT(vformat("FBX: Image index '%d' couldn't be loaded with the name: %s. Skipping it.", p_index, p_image->get_name()));
  900. // Placeholder to keep count.
  901. p_state->images.push_back(Ref<Texture2D>());
  902. p_state->source_images.push_back(Ref<Image>());
  903. }
  904. }
  905. return p_state->images.size() - 1;
  906. }
  907. #endif // TOOLS_ENABLED
  908. if (handling == FBXState::HANDLE_BINARY_EMBED_AS_BASISU) {
  909. Ref<PortableCompressedTexture2D> tex;
  910. tex.instantiate();
  911. tex->set_name(p_image->get_name());
  912. tex->set_keep_compressed_buffer(true);
  913. tex->create_from_image(p_image, PortableCompressedTexture2D::COMPRESSION_MODE_BASIS_UNIVERSAL);
  914. p_state->images.push_back(tex);
  915. p_state->source_images.push_back(p_image);
  916. return p_state->images.size() - 1;
  917. }
  918. // This handles the case of HANDLE_BINARY_EMBED_AS_UNCOMPRESSED, and it also serves
  919. // as a fallback for HANDLE_BINARY_EXTRACT_TEXTURES when this is not the editor.
  920. Ref<ImageTexture> tex;
  921. tex.instantiate();
  922. tex->set_name(p_image->get_name());
  923. tex->set_image(p_image);
  924. p_state->images.push_back(tex);
  925. p_state->source_images.push_back(p_image);
  926. return p_state->images.size() - 1;
  927. }
  928. Error FBXDocument::_parse_images(Ref<FBXState> p_state, const String &p_base_path) {
  929. ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER);
  930. const ufbx_scene *fbx_scene = p_state->scene.get();
  931. for (int texture_i = 0; texture_i < static_cast<int>(fbx_scene->texture_files.count); texture_i++) {
  932. const ufbx_texture_file &fbx_texture_file = fbx_scene->texture_files[texture_i];
  933. String path = _as_string(fbx_texture_file.filename);
  934. // Use only filename for absolute paths to avoid portability issues.
  935. if (path.is_absolute_path()) {
  936. path = path.get_file();
  937. }
  938. if (!p_base_path.is_empty()) {
  939. path = p_base_path.path_join(path);
  940. }
  941. path = path.simplify_path();
  942. Vector<uint8_t> data;
  943. if (fbx_texture_file.content.size > 0 && fbx_texture_file.content.size <= INT_MAX) {
  944. data.resize(int(fbx_texture_file.content.size));
  945. memcpy(data.ptrw(), fbx_texture_file.content.data, fbx_texture_file.content.size);
  946. } else {
  947. String base_dir = p_state->get_base_path();
  948. Ref<Texture2D> texture = ResourceLoader::load(_get_texture_path(base_dir, path), "Texture2D");
  949. if (texture.is_valid()) {
  950. p_state->images.push_back(texture);
  951. p_state->source_images.push_back(texture->get_image());
  952. continue;
  953. }
  954. // Fallback to loading as byte array.
  955. data = FileAccess::get_file_as_bytes(path);
  956. if (data.size() == 0) {
  957. WARN_PRINT(vformat("FBX: Image index '%d' couldn't be loaded from path: %s because there was no data to load. Skipping it.", texture_i, path));
  958. p_state->images.push_back(Ref<Texture2D>()); // Placeholder to keep count.
  959. p_state->source_images.push_back(Ref<Image>());
  960. continue;
  961. }
  962. }
  963. // Parse the image data from bytes into an Image resource and save if needed.
  964. String file_extension;
  965. Ref<Image> img = _parse_image_bytes_into_image(p_state, data, path, texture_i);
  966. img->set_name(itos(texture_i));
  967. _parse_image_save_image(p_state, data, file_extension, texture_i, img);
  968. }
  969. // Create a texture for each file texture.
  970. for (int texture_file_i = 0; texture_file_i < static_cast<int>(fbx_scene->texture_files.count); texture_file_i++) {
  971. Ref<GLTFTexture> texture;
  972. texture.instantiate();
  973. texture->set_src_image(GLTFImageIndex(texture_file_i));
  974. p_state->textures.push_back(texture);
  975. }
  976. print_verbose("FBX: Total images: " + itos(p_state->images.size()));
  977. return OK;
  978. }
  979. Ref<Texture2D> FBXDocument::_get_texture(Ref<FBXState> p_state, const GLTFTextureIndex p_texture, int p_texture_types) {
  980. ERR_FAIL_INDEX_V(p_texture, p_state->textures.size(), Ref<Texture2D>());
  981. const GLTFImageIndex image = p_state->textures[p_texture]->get_src_image();
  982. ERR_FAIL_INDEX_V(image, p_state->images.size(), Ref<Texture2D>());
  983. if (FBXState::GLTFHandleBinary(p_state->handle_binary_image) == FBXState::HANDLE_BINARY_EMBED_AS_BASISU) {
  984. ERR_FAIL_INDEX_V(image, p_state->source_images.size(), Ref<Texture2D>());
  985. Ref<PortableCompressedTexture2D> portable_texture;
  986. portable_texture.instantiate();
  987. portable_texture->set_keep_compressed_buffer(true);
  988. Ref<Image> new_img = p_state->source_images[image]->duplicate();
  989. ERR_FAIL_COND_V(new_img.is_null(), Ref<Texture2D>());
  990. new_img->generate_mipmaps();
  991. if (p_texture_types) {
  992. portable_texture->create_from_image(new_img, PortableCompressedTexture2D::COMPRESSION_MODE_BASIS_UNIVERSAL, true);
  993. } else {
  994. portable_texture->create_from_image(new_img, PortableCompressedTexture2D::COMPRESSION_MODE_BASIS_UNIVERSAL, false);
  995. }
  996. p_state->images.write[image] = portable_texture;
  997. p_state->source_images.write[image] = new_img;
  998. }
  999. return p_state->images[image];
  1000. }
  1001. Error FBXDocument::_parse_materials(Ref<FBXState> p_state) {
  1002. const ufbx_scene *fbx_scene = p_state->scene.get();
  1003. for (GLTFMaterialIndex material_i = 0; material_i < static_cast<GLTFMaterialIndex>(fbx_scene->materials.count); material_i++) {
  1004. const ufbx_material *fbx_material = fbx_scene->materials[material_i];
  1005. Ref<StandardMaterial3D> material;
  1006. material.instantiate();
  1007. if (fbx_material->name.length > 0) {
  1008. material->set_name(_as_string(fbx_material->name));
  1009. } else {
  1010. material->set_name(vformat("material_%s", itos(material_i)));
  1011. }
  1012. material->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  1013. Dictionary material_extensions;
  1014. if (fbx_material->pbr.base_color.has_value) {
  1015. Color albedo = _material_color(fbx_material->pbr.base_color, fbx_material->pbr.base_factor);
  1016. material->set_albedo(albedo.linear_to_srgb());
  1017. }
  1018. if (fbx_material->features.double_sided.enabled) {
  1019. material->set_cull_mode(BaseMaterial3D::CULL_DISABLED);
  1020. }
  1021. const ufbx_texture *base_texture = _get_file_texture(fbx_material->pbr.base_color.texture);
  1022. if (base_texture) {
  1023. bool wrap = base_texture->wrap_u == UFBX_WRAP_REPEAT && base_texture->wrap_v == UFBX_WRAP_REPEAT;
  1024. material->set_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT, wrap);
  1025. Ref<Texture2D> albedo_texture = _get_texture(p_state, GLTFTextureIndex(base_texture->file_index), TEXTURE_TYPE_GENERIC);
  1026. // Search for transparency map.
  1027. Ref<Texture2D> transparency_texture;
  1028. const ufbx_texture *transparency_sources[] = {
  1029. fbx_material->pbr.opacity.texture,
  1030. fbx_material->fbx.transparency_color.texture,
  1031. };
  1032. for (const ufbx_texture *transparency_source : transparency_sources) {
  1033. const ufbx_texture *fbx_transparency_texture = _get_file_texture(transparency_source);
  1034. if (fbx_transparency_texture) {
  1035. transparency_texture = _get_texture(p_state, GLTFTextureIndex(fbx_transparency_texture->file_index), TEXTURE_TYPE_GENERIC);
  1036. if (transparency_texture.is_valid()) {
  1037. break;
  1038. }
  1039. }
  1040. }
  1041. // Multiply the albedo alpha with the transparency texture if necessary.
  1042. if (albedo_texture.is_valid() && transparency_texture.is_valid() && albedo_texture != transparency_texture) {
  1043. Pair<uint64_t, uint64_t> key = { albedo_texture->get_rid().get_id(), transparency_texture->get_rid().get_id() };
  1044. GLTFTextureIndex *texture_index_ptr = p_state->albedo_transparency_textures.getptr(key);
  1045. if (texture_index_ptr != nullptr) {
  1046. if (*texture_index_ptr >= 0) {
  1047. albedo_texture = _get_texture(p_state, *texture_index_ptr, TEXTURE_TYPE_GENERIC);
  1048. }
  1049. } else {
  1050. Ref<Image> albedo_image = _get_decompressed_image(albedo_texture);
  1051. Ref<Image> transparency_image = _get_decompressed_image(transparency_texture);
  1052. if (albedo_image.is_valid() && transparency_image.is_valid()) {
  1053. albedo_image->convert(Image::Format::FORMAT_RGBA8);
  1054. transparency_image->resize(albedo_texture->get_width(), albedo_texture->get_height(), Image::INTERPOLATE_LANCZOS);
  1055. for (int y = 0; y < albedo_image->get_height(); y++) {
  1056. for (int x = 0; x < albedo_image->get_width(); x++) {
  1057. Color albedo_pixel = albedo_image->get_pixel(x, y);
  1058. Color transparency_pixel = transparency_image->get_pixel(x, y);
  1059. albedo_pixel.a *= transparency_pixel.r;
  1060. albedo_image->set_pixel(x, y, albedo_pixel);
  1061. }
  1062. }
  1063. albedo_image->clear_mipmaps();
  1064. albedo_image->generate_mipmaps();
  1065. albedo_image->set_name(vformat("alpha_%d", p_state->albedo_transparency_textures.size()));
  1066. GLTFImageIndex new_image = _parse_image_save_image(p_state, PackedByteArray(), "", -1, albedo_image);
  1067. if (new_image >= 0) {
  1068. Ref<GLTFTexture> new_texture;
  1069. new_texture.instantiate();
  1070. new_texture->set_src_image(GLTFImageIndex(new_image));
  1071. p_state->textures.push_back(new_texture);
  1072. GLTFTextureIndex texture_index = p_state->textures.size() - 1;
  1073. p_state->albedo_transparency_textures[key] = texture_index;
  1074. albedo_texture = _get_texture(p_state, texture_index, TEXTURE_TYPE_GENERIC);
  1075. } else {
  1076. WARN_PRINT(vformat("FBX: Could not save modified albedo texture from RID (%d, %d).", key.first, key.second));
  1077. p_state->albedo_transparency_textures[key] = -1;
  1078. }
  1079. }
  1080. }
  1081. }
  1082. Image::AlphaMode alpha_mode;
  1083. if (albedo_texture.is_valid()) {
  1084. Image::AlphaMode *alpha_mode_ptr = p_state->alpha_mode_cache.getptr(albedo_texture->get_rid().get_id());
  1085. if (alpha_mode_ptr != nullptr) {
  1086. alpha_mode = *alpha_mode_ptr;
  1087. } else {
  1088. Ref<Image> albedo_image = _get_decompressed_image(albedo_texture);
  1089. alpha_mode = albedo_image->detect_alpha();
  1090. p_state->alpha_mode_cache[albedo_texture->get_rid().get_id()] = alpha_mode;
  1091. }
  1092. if (alpha_mode == Image::ALPHA_BLEND) {
  1093. material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
  1094. } else if (alpha_mode == Image::ALPHA_BIT) {
  1095. material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA_SCISSOR);
  1096. }
  1097. material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, albedo_texture);
  1098. }
  1099. // Combined textures and factors are very unreliable in FBX
  1100. Color albedo_factor = Color(1, 1, 1);
  1101. if (fbx_material->pbr.base_factor.has_value) {
  1102. albedo_factor *= (float)fbx_material->pbr.base_factor.value_real;
  1103. }
  1104. material->set_albedo(albedo_factor.linear_to_srgb());
  1105. // TODO: Does not support rotation, could be inverted?
  1106. material->set_uv1_offset(_as_vec3(base_texture->uv_transform.translation));
  1107. Vector3 scale = _as_vec3(base_texture->uv_transform.scale);
  1108. material->set_uv1_scale(scale);
  1109. }
  1110. if (fbx_material->features.pbr.enabled) {
  1111. if (fbx_material->pbr.metalness.has_value) {
  1112. material->set_metallic(float(fbx_material->pbr.metalness.value_real));
  1113. } else {
  1114. material->set_metallic(1.0);
  1115. }
  1116. if (fbx_material->pbr.roughness.has_value) {
  1117. material->set_roughness(float(fbx_material->pbr.roughness.value_real));
  1118. } else {
  1119. material->set_roughness(1.0);
  1120. }
  1121. const ufbx_texture *metalness_texture = _get_file_texture(fbx_material->pbr.metalness.texture);
  1122. if (metalness_texture) {
  1123. material->set_texture(BaseMaterial3D::TEXTURE_METALLIC, _get_texture(p_state, GLTFTextureIndex(metalness_texture->file_index), TEXTURE_TYPE_GENERIC));
  1124. material->set_metallic_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_RED);
  1125. material->set_metallic(1.0);
  1126. }
  1127. const ufbx_texture *roughness_texture = _get_file_texture(fbx_material->pbr.roughness.texture);
  1128. if (roughness_texture) {
  1129. material->set_texture(BaseMaterial3D::TEXTURE_ROUGHNESS, _get_texture(p_state, GLTFTextureIndex(roughness_texture->file_index), TEXTURE_TYPE_GENERIC));
  1130. material->set_roughness_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_RED);
  1131. material->set_roughness(1.0);
  1132. }
  1133. }
  1134. const ufbx_texture *normal_texture = _get_file_texture(fbx_material->pbr.normal_map.texture);
  1135. if (normal_texture) {
  1136. material->set_texture(BaseMaterial3D::TEXTURE_NORMAL, _get_texture(p_state, GLTFTextureIndex(normal_texture->file_index), TEXTURE_TYPE_NORMAL));
  1137. material->set_feature(BaseMaterial3D::FEATURE_NORMAL_MAPPING, true);
  1138. if (fbx_material->pbr.normal_map.has_value) {
  1139. material->set_normal_scale(fbx_material->pbr.normal_map.value_real);
  1140. }
  1141. }
  1142. const ufbx_texture *occlusion_texture = _get_file_texture(fbx_material->pbr.ambient_occlusion.texture);
  1143. if (occlusion_texture) {
  1144. material->set_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION, _get_texture(p_state, GLTFTextureIndex(occlusion_texture->file_index), TEXTURE_TYPE_GENERIC));
  1145. material->set_ao_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_RED);
  1146. material->set_feature(BaseMaterial3D::FEATURE_AMBIENT_OCCLUSION, true);
  1147. }
  1148. if (fbx_material->pbr.emission_color.has_value) {
  1149. material->set_feature(BaseMaterial3D::FEATURE_EMISSION, true);
  1150. material->set_emission(_material_color(fbx_material->pbr.emission_color).linear_to_srgb());
  1151. material->set_emission_energy_multiplier(float(fbx_material->pbr.emission_factor.value_real));
  1152. }
  1153. const ufbx_texture *emission_texture = _get_file_texture(fbx_material->pbr.emission_color.texture);
  1154. if (emission_texture) {
  1155. material->set_texture(BaseMaterial3D::TEXTURE_EMISSION, _get_texture(p_state, GLTFTextureIndex(emission_texture->file_index), TEXTURE_TYPE_GENERIC));
  1156. material->set_feature(BaseMaterial3D::FEATURE_EMISSION, true);
  1157. material->set_emission(Color(0, 0, 0));
  1158. }
  1159. if (fbx_material->features.double_sided.enabled && fbx_material->features.double_sided.is_explicit) {
  1160. material->set_cull_mode(BaseMaterial3D::CULL_DISABLED);
  1161. }
  1162. p_state->materials.push_back(material);
  1163. }
  1164. print_verbose("Total materials: " + itos(p_state->materials.size()));
  1165. return OK;
  1166. }
  1167. Error FBXDocument::_parse_cameras(Ref<FBXState> p_state) {
  1168. const ufbx_scene *fbx_scene = p_state->scene.get();
  1169. for (GLTFCameraIndex i = 0; i < static_cast<GLTFCameraIndex>(fbx_scene->cameras.count); i++) {
  1170. const ufbx_camera *fbx_camera = fbx_scene->cameras[i];
  1171. Ref<GLTFCamera> camera;
  1172. camera.instantiate();
  1173. camera->set_name(_as_string(fbx_camera->name));
  1174. if (fbx_camera->projection_mode == UFBX_PROJECTION_MODE_PERSPECTIVE) {
  1175. camera->set_perspective(true);
  1176. camera->set_fov(Math::deg_to_rad(real_t(fbx_camera->field_of_view_deg.y)));
  1177. } else {
  1178. camera->set_perspective(false);
  1179. camera->set_size_mag(real_t(fbx_camera->orthographic_size.y * 0.5f));
  1180. }
  1181. if (fbx_camera->near_plane != 0.0f) {
  1182. camera->set_depth_near(fbx_camera->near_plane);
  1183. }
  1184. if (fbx_camera->far_plane != 0.0f) {
  1185. camera->set_depth_far(fbx_camera->far_plane);
  1186. }
  1187. p_state->cameras.push_back(camera);
  1188. }
  1189. print_verbose("FBX: Total cameras: " + itos(p_state->cameras.size()));
  1190. return OK;
  1191. }
  1192. Error FBXDocument::_parse_animations(Ref<FBXState> p_state) {
  1193. const ufbx_scene *fbx_scene = p_state->scene.get();
  1194. for (GLTFAnimationIndex animation_i = 0; animation_i < static_cast<GLTFAnimationIndex>(fbx_scene->anim_stacks.count); animation_i++) {
  1195. const ufbx_anim_stack *fbx_anim_stack = fbx_scene->anim_stacks[animation_i];
  1196. Ref<GLTFAnimation> animation;
  1197. animation.instantiate();
  1198. if (fbx_anim_stack->name.length > 0) {
  1199. const String anim_name = _as_string(fbx_anim_stack->name);
  1200. const String anim_name_lower = anim_name.to_lower();
  1201. if (anim_name_lower.begins_with("loop") || anim_name_lower.ends_with("loop") || anim_name_lower.begins_with("cycle") || anim_name_lower.ends_with("cycle")) {
  1202. animation->set_loop(true);
  1203. }
  1204. animation->set_original_name(anim_name);
  1205. animation->set_name(_gen_unique_animation_name(p_state, anim_name));
  1206. }
  1207. Dictionary additional_data;
  1208. additional_data["time_begin"] = fbx_anim_stack->time_begin;
  1209. additional_data["time_end"] = fbx_anim_stack->time_end;
  1210. animation->set_additional_data("GODOT_animation_time_begin_time_end", additional_data);
  1211. ufbx_bake_opts opts = {};
  1212. opts.resample_rate = p_state->get_bake_fps();
  1213. opts.minimum_sample_rate = p_state->get_bake_fps();
  1214. opts.max_keyframe_segments = 1024;
  1215. ufbx_error error;
  1216. ufbx_unique_ptr<ufbx_baked_anim> fbx_baked_anim{ ufbx_bake_anim(fbx_scene, fbx_anim_stack->anim, &opts, &error) };
  1217. if (!fbx_baked_anim) {
  1218. char err_buf[512];
  1219. ufbx_format_error(err_buf, sizeof(err_buf), &error);
  1220. ERR_FAIL_V_MSG(FAILED, err_buf);
  1221. }
  1222. for (const ufbx_baked_node &fbx_baked_node : fbx_baked_anim->nodes) {
  1223. const GLTFNodeIndex node = fbx_baked_node.typed_id;
  1224. GLTFAnimation::Track &track = animation->get_tracks()[node];
  1225. for (const ufbx_baked_vec3 &key : fbx_baked_node.translation_keys) {
  1226. track.position_track.times.push_back(float(key.time));
  1227. track.position_track.values.push_back(_as_vec3(key.value));
  1228. }
  1229. for (const ufbx_baked_quat &key : fbx_baked_node.rotation_keys) {
  1230. track.rotation_track.times.push_back(float(key.time));
  1231. track.rotation_track.values.push_back(_as_quaternion(key.value));
  1232. }
  1233. for (const ufbx_baked_vec3 &key : fbx_baked_node.scale_keys) {
  1234. track.scale_track.times.push_back(float(key.time));
  1235. track.scale_track.values.push_back(_as_vec3(key.value));
  1236. }
  1237. }
  1238. Dictionary blend_shape_animations;
  1239. for (const ufbx_baked_element &fbx_baked_element : fbx_baked_anim->elements) {
  1240. const ufbx_element *fbx_element = fbx_scene->elements[fbx_baked_element.element_id];
  1241. for (const ufbx_baked_prop &fbx_baked_prop : fbx_baked_element.props) {
  1242. String prop_name = _as_string(fbx_baked_prop.name);
  1243. if (fbx_element->type == UFBX_ELEMENT_BLEND_CHANNEL && prop_name == UFBX_DeformPercent) {
  1244. const ufbx_blend_channel *fbx_blend_channel = ufbx_as_blend_channel(fbx_element);
  1245. int blend_i = fbx_blend_channel->typed_id;
  1246. Vector<real_t> track_times;
  1247. Vector<real_t> track_values;
  1248. for (const ufbx_baked_vec3 &key : fbx_baked_prop.keys) {
  1249. track_times.push_back(float(key.time));
  1250. track_values.push_back(real_t(key.value.x / 100.0));
  1251. }
  1252. Dictionary track;
  1253. track["times"] = track_times;
  1254. track["values"] = track_values;
  1255. blend_shape_animations[blend_i] = track;
  1256. }
  1257. }
  1258. }
  1259. animation->set_additional_data("GODOT_blend_shape_animations", blend_shape_animations);
  1260. p_state->animations.push_back(animation);
  1261. }
  1262. print_verbose("FBX: Total animations '" + itos(p_state->animations.size()) + "'.");
  1263. return OK;
  1264. }
  1265. void FBXDocument::_assign_node_names(Ref<FBXState> p_state) {
  1266. for (int i = 0; i < p_state->nodes.size(); i++) {
  1267. Ref<GLTFNode> fbx_node = p_state->nodes[i];
  1268. // Any joints get unique names generated when the skeleton is made, unique to the skeleton
  1269. if (fbx_node->skeleton >= 0) {
  1270. continue;
  1271. }
  1272. if (fbx_node->get_name().is_empty()) {
  1273. if (fbx_node->mesh >= 0) {
  1274. fbx_node->set_name(_gen_unique_name(p_state->unique_names, "Mesh"));
  1275. } else if (fbx_node->camera >= 0) {
  1276. fbx_node->set_name(_gen_unique_name(p_state->unique_names, "Camera3D"));
  1277. } else {
  1278. fbx_node->set_name(_gen_unique_name(p_state->unique_names, "Node"));
  1279. }
  1280. }
  1281. fbx_node->set_name(_gen_unique_name(p_state->unique_names, fbx_node->get_name()));
  1282. }
  1283. }
  1284. BoneAttachment3D *FBXDocument::_generate_bone_attachment(Ref<FBXState> p_state, Skeleton3D *p_skeleton, const GLTFNodeIndex p_node_index, const GLTFNodeIndex p_bone_index) {
  1285. Ref<GLTFNode> fbx_node = p_state->nodes[p_node_index];
  1286. Ref<GLTFNode> bone_node = p_state->nodes[p_bone_index];
  1287. BoneAttachment3D *bone_attachment = memnew(BoneAttachment3D);
  1288. print_verbose("FBX: Creating bone attachment for: " + fbx_node->get_name());
  1289. ERR_FAIL_COND_V(!bone_node->joint, nullptr);
  1290. bone_attachment->set_bone_name(bone_node->get_name());
  1291. return bone_attachment;
  1292. }
  1293. ImporterMeshInstance3D *FBXDocument::_generate_mesh_instance(Ref<FBXState> p_state, const GLTFNodeIndex p_node_index) {
  1294. Ref<GLTFNode> fbx_node = p_state->nodes[p_node_index];
  1295. ERR_FAIL_INDEX_V(fbx_node->mesh, p_state->meshes.size(), nullptr);
  1296. ImporterMeshInstance3D *mi = memnew(ImporterMeshInstance3D);
  1297. print_verbose("FBX: Creating mesh for: " + fbx_node->get_name());
  1298. p_state->scene_mesh_instances.insert(p_node_index, mi);
  1299. Ref<GLTFMesh> mesh = p_state->meshes.write[fbx_node->mesh];
  1300. if (mesh.is_null()) {
  1301. return mi;
  1302. }
  1303. Ref<ImporterMesh> import_mesh = mesh->get_mesh();
  1304. if (import_mesh.is_null()) {
  1305. return mi;
  1306. }
  1307. mi->set_mesh(import_mesh);
  1308. return mi;
  1309. }
  1310. Camera3D *FBXDocument::_generate_camera(Ref<FBXState> p_state, const GLTFNodeIndex p_node_index) {
  1311. Ref<GLTFNode> fbx_node = p_state->nodes[p_node_index];
  1312. ERR_FAIL_INDEX_V(fbx_node->camera, p_state->cameras.size(), nullptr);
  1313. print_verbose("FBX: Creating camera for: " + fbx_node->get_name());
  1314. Ref<GLTFCamera> c = p_state->cameras[fbx_node->camera];
  1315. return c->to_node();
  1316. }
  1317. Light3D *FBXDocument::_generate_light(Ref<FBXState> p_state, const GLTFNodeIndex p_node_index) {
  1318. Ref<GLTFNode> fbx_node = p_state->nodes[p_node_index];
  1319. ERR_FAIL_INDEX_V(fbx_node->light, p_state->lights.size(), nullptr);
  1320. print_verbose("FBX: Creating light for: " + fbx_node->get_name());
  1321. Ref<GLTFLight> l = p_state->lights[fbx_node->light];
  1322. Light3D *light = nullptr;
  1323. if (l->get_light_type() == "point") {
  1324. light = memnew(OmniLight3D);
  1325. } else if (l->get_light_type() == "directional") {
  1326. light = memnew(DirectionalLight3D);
  1327. } else if (l->get_light_type() == "spot") {
  1328. light = memnew(SpotLight3D);
  1329. } else {
  1330. ERR_FAIL_NULL_V(light, nullptr);
  1331. }
  1332. if (light) {
  1333. light->set_name(l->get_name());
  1334. light->set_color(l->get_color());
  1335. light->set_param(Light3D::PARAM_ENERGY, l->get_intensity());
  1336. Dictionary additional_data = l->get_additional_data("GODOT_fbx_light");
  1337. if (additional_data.has("castShadows")) {
  1338. light->set_shadow(additional_data["castShadows"]);
  1339. }
  1340. if (additional_data.has("castLight")) {
  1341. light->set_visible(additional_data["castLight"]);
  1342. }
  1343. Transform3D transform;
  1344. DirectionalLight3D *dir_light = Object::cast_to<DirectionalLight3D>(light);
  1345. SpotLight3D *spot_light = Object::cast_to<SpotLight3D>(light);
  1346. OmniLight3D *omni_light = Object::cast_to<OmniLight3D>(light);
  1347. if (dir_light) {
  1348. dir_light->set_transform(transform);
  1349. } else if (spot_light) {
  1350. spot_light->set_transform(transform);
  1351. spot_light->set_param(SpotLight3D::PARAM_SPOT_ANGLE, l->get_outer_cone_angle() / 2.0f);
  1352. }
  1353. if (omni_light || spot_light) {
  1354. light->set_param(OmniLight3D::PARAM_RANGE, 4096);
  1355. }
  1356. // This is "correct", but FBX files may have unexpected decay modes.
  1357. // Also does not match with what FBX2glTF does, so it might be better to not do any of this..
  1358. #if 0
  1359. if (omni_light || spot_light) {
  1360. float attenuation = 1.0f;
  1361. if (additional_data.has("decay")) {
  1362. String decay_type = additional_data["decay"];
  1363. if (decay_type == "none") {
  1364. attenuation = 0.001f;
  1365. } else if (decay_type == "linear") {
  1366. attenuation = 1.0f;
  1367. } else if (decay_type == "quadratic") {
  1368. attenuation = 2.0f;
  1369. } else if (decay_type == "cubic") {
  1370. attenuation = 3.0f;
  1371. }
  1372. }
  1373. light->set_param(Light3D::PARAM_ATTENUATION, attenuation);
  1374. }
  1375. #endif
  1376. if (spot_light) {
  1377. // Line of best fit derived from guessing, see https://www.desmos.com/calculator/biiflubp8b
  1378. // The points in desmos are not exact, except for (1, infinity).
  1379. float angle_ratio = l->get_inner_cone_angle() / l->get_outer_cone_angle();
  1380. float angle_attenuation = 0.2 / (1 - angle_ratio) - 0.1;
  1381. light->set_param(SpotLight3D::PARAM_SPOT_ATTENUATION, angle_attenuation);
  1382. }
  1383. }
  1384. return light;
  1385. }
  1386. Node3D *FBXDocument::_generate_spatial(Ref<FBXState> p_state, const GLTFNodeIndex p_node_index) {
  1387. Ref<GLTFNode> fbx_node = p_state->nodes[p_node_index];
  1388. Node3D *spatial = memnew(Node3D);
  1389. print_verbose("FBX: Converting spatial: " + fbx_node->get_name());
  1390. return spatial;
  1391. }
  1392. void FBXDocument::_generate_scene_node(Ref<FBXState> p_state, const GLTFNodeIndex p_node_index, Node *p_scene_parent, Node *p_scene_root) {
  1393. Ref<GLTFNode> fbx_node = p_state->nodes[p_node_index];
  1394. if (fbx_node->skeleton >= 0) {
  1395. _generate_skeleton_bone_node(p_state, p_node_index, p_scene_parent, p_scene_root);
  1396. return;
  1397. }
  1398. Node3D *current_node = nullptr;
  1399. // Is our parent a skeleton
  1400. Skeleton3D *active_skeleton = Object::cast_to<Skeleton3D>(p_scene_parent);
  1401. const bool non_bone_parented_to_skeleton = active_skeleton;
  1402. // skinned meshes must not be placed in a bone attachment.
  1403. if (non_bone_parented_to_skeleton && fbx_node->skin < 0) {
  1404. // Bone Attachment - Parent Case
  1405. BoneAttachment3D *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, fbx_node->parent);
  1406. p_scene_parent->add_child(bone_attachment, true);
  1407. bone_attachment->set_owner(p_scene_root);
  1408. // There is no fbx_node that represent this, so just directly create a unique name
  1409. bone_attachment->set_name(fbx_node->get_name());
  1410. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  1411. // and attach it to the bone_attachment
  1412. p_scene_parent = bone_attachment;
  1413. }
  1414. if (!current_node) {
  1415. if (fbx_node->skin >= 0 && fbx_node->mesh >= 0 && !fbx_node->children.is_empty()) {
  1416. current_node = _generate_spatial(p_state, p_node_index);
  1417. Node3D *mesh_inst = _generate_mesh_instance(p_state, p_node_index);
  1418. mesh_inst->set_name(fbx_node->get_name());
  1419. current_node->add_child(mesh_inst, true);
  1420. } else if (fbx_node->mesh >= 0) {
  1421. current_node = _generate_mesh_instance(p_state, p_node_index);
  1422. } else if (fbx_node->camera >= 0) {
  1423. current_node = _generate_camera(p_state, p_node_index);
  1424. } else if (fbx_node->light >= 0) {
  1425. current_node = _generate_light(p_state, p_node_index);
  1426. } else {
  1427. current_node = _generate_spatial(p_state, p_node_index);
  1428. }
  1429. }
  1430. ERR_FAIL_NULL(current_node);
  1431. // Add the node we generated and set the owner to the scene root.
  1432. p_scene_parent->add_child(current_node, true);
  1433. if (current_node != p_scene_root) {
  1434. Array args;
  1435. args.append(p_scene_root);
  1436. current_node->propagate_call(StringName("set_owner"), args);
  1437. }
  1438. current_node->set_transform(fbx_node->transform);
  1439. current_node->set_name(fbx_node->get_name());
  1440. p_state->scene_nodes.insert(p_node_index, current_node);
  1441. for (int i = 0; i < fbx_node->children.size(); ++i) {
  1442. _generate_scene_node(p_state, fbx_node->children[i], current_node, p_scene_root);
  1443. }
  1444. }
  1445. void FBXDocument::_generate_skeleton_bone_node(Ref<FBXState> p_state, const GLTFNodeIndex p_node_index, Node *p_scene_parent, Node *p_scene_root) {
  1446. Ref<GLTFNode> fbx_node = p_state->nodes[p_node_index];
  1447. Node3D *current_node = nullptr;
  1448. Skeleton3D *skeleton = p_state->skeletons[fbx_node->skeleton]->godot_skeleton;
  1449. // In this case, this node is already a bone in skeleton.
  1450. const bool is_skinned_mesh = (fbx_node->skin >= 0 && fbx_node->mesh >= 0);
  1451. const bool requires_extra_node = (fbx_node->mesh >= 0 || fbx_node->camera >= 0 || fbx_node->light >= 0);
  1452. Skeleton3D *active_skeleton = Object::cast_to<Skeleton3D>(p_scene_parent);
  1453. if (active_skeleton != skeleton) {
  1454. if (active_skeleton) {
  1455. // Should no longer be possible.
  1456. ERR_PRINT(vformat("FBX: Generating scene detected direct parented Skeletons at node %d", p_node_index));
  1457. BoneAttachment3D *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, fbx_node->parent);
  1458. p_scene_parent->add_child(bone_attachment, true);
  1459. bone_attachment->set_owner(p_scene_root);
  1460. // There is no fbx_node that represent this, so just directly create a unique name
  1461. bone_attachment->set_name(_gen_unique_name(p_state->unique_names, "BoneAttachment3D"));
  1462. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  1463. // and attach it to the bone_attachment
  1464. p_scene_parent = bone_attachment;
  1465. }
  1466. if (skeleton->get_parent() == nullptr) {
  1467. p_scene_parent->add_child(skeleton, true);
  1468. skeleton->set_owner(p_scene_root);
  1469. }
  1470. }
  1471. active_skeleton = skeleton;
  1472. current_node = active_skeleton;
  1473. if (active_skeleton) {
  1474. p_scene_parent = active_skeleton;
  1475. }
  1476. if (requires_extra_node) {
  1477. current_node = nullptr;
  1478. // skinned meshes must not be placed in a bone attachment.
  1479. if (!is_skinned_mesh) {
  1480. // Bone Attachment - Same Node Case
  1481. BoneAttachment3D *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, p_node_index);
  1482. p_scene_parent->add_child(bone_attachment, true);
  1483. bone_attachment->set_owner(p_scene_root);
  1484. // There is no fbx_node that represent this, so just directly create a unique name
  1485. bone_attachment->set_name(fbx_node->get_name());
  1486. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  1487. // and attach it to the bone_attachment
  1488. p_scene_parent = bone_attachment;
  1489. }
  1490. // TODO: 20240118 // fire
  1491. // // Check if any GLTFDocumentExtension classes want to generate a node for us.
  1492. // for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  1493. // ERR_CONTINUE(ext.is_null());
  1494. // current_node = ext->generate_scene_node(p_state, fbx_node, p_scene_parent);
  1495. // if (current_node) {
  1496. // break;
  1497. // }
  1498. // }
  1499. // If none of our GLTFDocumentExtension classes generated us a node, we generate one.
  1500. if (!current_node) {
  1501. if (fbx_node->mesh >= 0) {
  1502. current_node = _generate_mesh_instance(p_state, p_node_index);
  1503. } else if (fbx_node->camera >= 0) {
  1504. current_node = _generate_camera(p_state, p_node_index);
  1505. } else {
  1506. current_node = _generate_spatial(p_state, p_node_index);
  1507. }
  1508. }
  1509. // Add the node we generated and set the owner to the scene root.
  1510. p_scene_parent->add_child(current_node, true);
  1511. if (current_node != p_scene_root) {
  1512. Array args;
  1513. args.append(p_scene_root);
  1514. current_node->propagate_call(StringName("set_owner"), args);
  1515. }
  1516. // Do not set transform here. Transform is already applied to our bone.
  1517. current_node->set_name(fbx_node->get_name());
  1518. }
  1519. p_state->scene_nodes.insert(p_node_index, current_node);
  1520. for (int i = 0; i < fbx_node->children.size(); ++i) {
  1521. _generate_scene_node(p_state, fbx_node->children[i], active_skeleton, p_scene_root);
  1522. }
  1523. }
  1524. void FBXDocument::_import_animation(Ref<FBXState> p_state, AnimationPlayer *p_animation_player, const GLTFAnimationIndex p_index, const bool p_trimming, const bool p_remove_immutable_tracks) {
  1525. Ref<GLTFAnimation> anim = p_state->animations[p_index];
  1526. String anim_name = anim->get_name();
  1527. if (anim_name.is_empty()) {
  1528. // No node represent these, and they are not in the hierarchy, so just make a unique name
  1529. anim_name = _gen_unique_name(p_state->unique_names, "Animation");
  1530. }
  1531. Ref<Animation> animation;
  1532. animation.instantiate();
  1533. animation->set_name(anim_name);
  1534. animation->set_step(1.0 / p_state->get_bake_fps());
  1535. if (anim->get_loop()) {
  1536. animation->set_loop_mode(Animation::LOOP_LINEAR);
  1537. }
  1538. Dictionary additional_animation_data = anim->get_additional_data("GODOT_animation_time_begin_time_end");
  1539. double anim_start_offset = p_trimming ? double(additional_animation_data["time_begin"]) : 0.0;
  1540. for (const KeyValue<int, GLTFAnimation::Track> &track_i : anim->get_tracks()) {
  1541. const GLTFAnimation::Track &track = track_i.value;
  1542. //need to find the path: for skeletons, weight tracks will affect the mesh
  1543. NodePath node_path;
  1544. //for skeletons, transform tracks always affect bones
  1545. NodePath transform_node_path;
  1546. GLTFNodeIndex node_index = track_i.key;
  1547. Node *root = p_animation_player->get_parent();
  1548. ERR_FAIL_NULL(root);
  1549. HashMap<GLTFNodeIndex, Node *>::Iterator node_element = p_state->scene_nodes.find(node_index);
  1550. ERR_CONTINUE_MSG(!node_element, vformat("Unable to find node %d for animation.", node_index));
  1551. node_path = root->get_path_to(node_element->value);
  1552. const Ref<GLTFNode> fbx_node = p_state->nodes[track_i.key];
  1553. if (fbx_node->skeleton >= 0) {
  1554. const Skeleton3D *sk = p_state->skeletons[fbx_node->skeleton]->godot_skeleton;
  1555. ERR_FAIL_NULL(sk);
  1556. const String path = p_animation_player->get_parent()->get_path_to(sk);
  1557. const String bone = fbx_node->get_name();
  1558. transform_node_path = path + ":" + bone;
  1559. } else {
  1560. transform_node_path = node_path;
  1561. }
  1562. // Animated TRS properties will not affect a skinned mesh.
  1563. const bool transform_affects_skinned_mesh_instance = fbx_node->skeleton < 0 && fbx_node->skin >= 0;
  1564. if ((track.rotation_track.values.size() || track.position_track.values.size() || track.scale_track.values.size()) && !transform_affects_skinned_mesh_instance) {
  1565. // Make a transform track.
  1566. int base_idx = animation->get_track_count();
  1567. int position_idx = -1;
  1568. int rotation_idx = -1;
  1569. int scale_idx = -1;
  1570. if (track.position_track.values.size()) {
  1571. bool is_default = true; // Discard the track if all it contains is default values.
  1572. if (p_remove_immutable_tracks) {
  1573. Vector3 base_pos = p_state->nodes[track_i.key]->transform.origin;
  1574. for (int i = 0; i < track.position_track.times.size(); i++) {
  1575. Vector3 value = track.position_track.values[track.position_track.interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE ? (1 + i * 3) : i];
  1576. if (!value.is_equal_approx(base_pos)) {
  1577. is_default = false;
  1578. break;
  1579. }
  1580. }
  1581. }
  1582. if (!p_remove_immutable_tracks || !is_default) {
  1583. position_idx = base_idx;
  1584. animation->add_track(Animation::TYPE_POSITION_3D);
  1585. animation->track_set_path(position_idx, transform_node_path);
  1586. animation->track_set_imported(position_idx, true); // Helps merging positions later.
  1587. base_idx++;
  1588. }
  1589. }
  1590. if (track.rotation_track.values.size()) {
  1591. bool is_default = true; // Discard the track if all the track contains is the default values.
  1592. if (p_remove_immutable_tracks) {
  1593. Quaternion base_rot = p_state->nodes[track_i.key]->transform.basis.get_rotation_quaternion();
  1594. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  1595. Quaternion value = track.rotation_track.values[track.rotation_track.interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE ? (1 + i * 3) : i].normalized();
  1596. if (!value.is_equal_approx(base_rot)) {
  1597. is_default = false;
  1598. break;
  1599. }
  1600. }
  1601. }
  1602. if (!p_remove_immutable_tracks || !is_default) {
  1603. rotation_idx = base_idx;
  1604. animation->add_track(Animation::TYPE_ROTATION_3D);
  1605. animation->track_set_path(rotation_idx, transform_node_path);
  1606. animation->track_set_imported(rotation_idx, true); //helps merging later
  1607. base_idx++;
  1608. }
  1609. }
  1610. if (track.scale_track.values.size()) {
  1611. bool is_default = true; // Discard the track if all the track contains is the default values.
  1612. if (p_remove_immutable_tracks) {
  1613. Vector3 base_scale = p_state->nodes[track_i.key]->transform.basis.get_scale();
  1614. for (int i = 0; i < track.scale_track.times.size(); i++) {
  1615. Vector3 value = track.scale_track.values[track.scale_track.interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE ? (1 + i * 3) : i];
  1616. if (!value.is_equal_approx(base_scale)) {
  1617. is_default = false;
  1618. break;
  1619. }
  1620. }
  1621. }
  1622. if (!p_remove_immutable_tracks || !is_default) {
  1623. scale_idx = base_idx;
  1624. animation->add_track(Animation::TYPE_SCALE_3D);
  1625. animation->track_set_path(scale_idx, transform_node_path);
  1626. animation->track_set_imported(scale_idx, true); //helps merging later
  1627. base_idx++;
  1628. }
  1629. }
  1630. if (position_idx != -1) {
  1631. animation->track_set_interpolation_type(position_idx, Animation::INTERPOLATION_LINEAR);
  1632. for (int j = 0; j < track.position_track.times.size(); j++) {
  1633. const float t = track.position_track.times[j] - anim_start_offset;
  1634. const Vector3 value = track.position_track.values[j];
  1635. animation->position_track_insert_key(position_idx, t, value);
  1636. }
  1637. }
  1638. if (rotation_idx != -1) {
  1639. animation->track_set_interpolation_type(rotation_idx, Animation::INTERPOLATION_LINEAR);
  1640. for (int j = 0; j < track.rotation_track.times.size(); j++) {
  1641. const float t = track.rotation_track.times[j] - anim_start_offset;
  1642. const Quaternion value = track.rotation_track.values[j];
  1643. animation->rotation_track_insert_key(rotation_idx, t, value);
  1644. }
  1645. }
  1646. if (scale_idx != -1) {
  1647. animation->track_set_interpolation_type(scale_idx, Animation::INTERPOLATION_LINEAR);
  1648. for (int j = 0; j < track.scale_track.times.size(); j++) {
  1649. const float t = track.scale_track.times[j] - anim_start_offset;
  1650. const Vector3 value = track.scale_track.values[j];
  1651. animation->scale_track_insert_key(scale_idx, t, value);
  1652. }
  1653. }
  1654. }
  1655. }
  1656. Dictionary blend_shape_animations = anim->get_additional_data("GODOT_blend_shape_animations");
  1657. for (GLTFNodeIndex node_index = 0; node_index < p_state->nodes.size(); node_index++) {
  1658. Ref<GLTFNode> node = p_state->nodes[node_index];
  1659. if (node->mesh < 0) {
  1660. continue;
  1661. }
  1662. // For meshes, especially skinned meshes, there are cases where it will be added as a child.
  1663. NodePath mesh_instance_node_path;
  1664. Node *root = p_animation_player->get_parent();
  1665. ERR_FAIL_NULL(root);
  1666. HashMap<GLTFNodeIndex, Node *>::Iterator node_element = p_state->scene_nodes.find(node_index);
  1667. ERR_CONTINUE_MSG(!node_element, vformat("Unable to find node %d for animation.", node_index));
  1668. NodePath node_path = root->get_path_to(node_element->value);
  1669. HashMap<GLTFNodeIndex, ImporterMeshInstance3D *>::Iterator mesh_instance_element = p_state->scene_mesh_instances.find(node_index);
  1670. if (mesh_instance_element) {
  1671. mesh_instance_node_path = root->get_path_to(mesh_instance_element->value);
  1672. } else {
  1673. mesh_instance_node_path = node_path;
  1674. }
  1675. Ref<GLTFMesh> mesh = p_state->meshes[node->mesh];
  1676. ERR_CONTINUE(mesh.is_null());
  1677. ERR_CONTINUE(mesh->get_mesh().is_null());
  1678. ERR_CONTINUE(mesh->get_mesh()->get_mesh().is_null());
  1679. Dictionary mesh_additional_data = mesh->get_additional_data("GODOT_mesh_blend_channels");
  1680. Vector<int> blend_channels = mesh_additional_data["blend_channels"];
  1681. for (int i = 0; i < blend_channels.size(); i++) {
  1682. int blend_i = blend_channels[i];
  1683. if (!blend_shape_animations.has(blend_i)) {
  1684. continue;
  1685. }
  1686. Dictionary blend_track = blend_shape_animations[blend_i];
  1687. GLTFAnimation::Channel<real_t> weights;
  1688. weights.interpolation = GLTFAnimation::INTERP_LINEAR;
  1689. weights.times = blend_track["times"];
  1690. weights.values = blend_track["values"];
  1691. const String blend_path = String(mesh_instance_node_path) + ":" + String(mesh->get_mesh()->get_blend_shape_name(i));
  1692. const int track_idx = animation->get_track_count();
  1693. animation->add_track(Animation::TYPE_BLEND_SHAPE);
  1694. animation->track_set_path(track_idx, blend_path);
  1695. animation->track_set_imported(track_idx, true); // Helps merging later.
  1696. animation->track_set_interpolation_type(track_idx, Animation::INTERPOLATION_LINEAR);
  1697. for (int j = 0; j < weights.times.size(); j++) {
  1698. const double t = weights.times[j] - anim_start_offset;
  1699. const real_t attribs = weights.values[j];
  1700. animation->blend_shape_track_insert_key(track_idx, t, attribs);
  1701. }
  1702. }
  1703. }
  1704. double time_begin = additional_animation_data["time_begin"];
  1705. double time_end = additional_animation_data["time_end"];
  1706. double length = p_trimming ? time_end - time_begin : time_end;
  1707. animation->set_length(length);
  1708. Ref<AnimationLibrary> library;
  1709. if (!p_animation_player->has_animation_library("")) {
  1710. library.instantiate();
  1711. p_animation_player->add_animation_library("", library);
  1712. } else {
  1713. library = p_animation_player->get_animation_library("");
  1714. }
  1715. library->add_animation(anim_name, animation);
  1716. }
  1717. void FBXDocument::_process_mesh_instances(Ref<FBXState> p_state, Node *p_scene_root) {
  1718. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); ++node_i) {
  1719. Ref<GLTFNode> node = p_state->nodes[node_i];
  1720. if (node.is_null() || !(node->skin >= 0 && node->mesh >= 0)) {
  1721. continue;
  1722. }
  1723. const GLTFSkinIndex skin_i = node->skin;
  1724. ImporterMeshInstance3D *mi = nullptr;
  1725. HashMap<GLTFNodeIndex, ImporterMeshInstance3D *>::Iterator mi_element = p_state->scene_mesh_instances.find(node_i);
  1726. if (!mi_element) {
  1727. HashMap<GLTFNodeIndex, Node *>::Iterator si_element = p_state->scene_nodes.find(node_i);
  1728. ERR_CONTINUE_MSG(!si_element, vformat("Unable to find node %d", node_i));
  1729. mi = Object::cast_to<ImporterMeshInstance3D>(si_element->value);
  1730. ERR_CONTINUE_MSG(mi == nullptr, vformat("Unable to cast node %d of type %s to ImporterMeshInstance3D", node_i, si_element->value->get_class_name()));
  1731. } else {
  1732. mi = mi_element->value;
  1733. }
  1734. bool is_skin_valid = node->skin >= 0;
  1735. bool is_skin_accessible = is_skin_valid && node->skin < p_state->skins.size();
  1736. bool is_valid = is_skin_accessible && p_state->skins.write[node->skin]->skeleton >= 0;
  1737. if (!is_valid) {
  1738. continue;
  1739. }
  1740. const GLTFSkeletonIndex skel_i = p_state->skins.write[node->skin]->skeleton;
  1741. Ref<GLTFSkeleton> fbx_skeleton = p_state->skeletons.write[skel_i];
  1742. Skeleton3D *skeleton = fbx_skeleton->godot_skeleton;
  1743. ERR_CONTINUE_MSG(skeleton == nullptr, vformat("Unable to find Skeleton for node %d skin %d", node_i, skin_i));
  1744. mi->get_parent()->remove_child(mi);
  1745. skeleton->add_child(mi, true);
  1746. mi->set_owner(skeleton->get_owner());
  1747. mi->set_skin(p_state->skins.write[skin_i]->godot_skin);
  1748. mi->set_skeleton_path(mi->get_path_to(skeleton));
  1749. mi->set_transform(Transform3D());
  1750. }
  1751. }
  1752. Error FBXDocument::_parse(Ref<FBXState> p_state, String p_path, Ref<FileAccess> p_file) {
  1753. p_state->scene.reset();
  1754. Error err = ERR_INVALID_DATA;
  1755. if (p_file.is_null()) {
  1756. return FAILED;
  1757. }
  1758. ufbx_load_opts opts = {};
  1759. opts.target_axes = ufbx_axes_right_handed_y_up;
  1760. opts.target_unit_meters = 1.0f;
  1761. opts.space_conversion = UFBX_SPACE_CONVERSION_MODIFY_GEOMETRY;
  1762. if (!p_state->get_allow_geometry_helper_nodes()) {
  1763. opts.geometry_transform_handling = UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY_NO_FALLBACK;
  1764. opts.inherit_mode_handling = UFBX_INHERIT_MODE_HANDLING_COMPENSATE_NO_FALLBACK;
  1765. } else {
  1766. opts.geometry_transform_handling = UFBX_GEOMETRY_TRANSFORM_HANDLING_HELPER_NODES;
  1767. opts.inherit_mode_handling = UFBX_INHERIT_MODE_HANDLING_COMPENSATE;
  1768. }
  1769. opts.pivot_handling = UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT;
  1770. opts.geometry_transform_helper_name.data = "GeometryTransformHelper";
  1771. opts.geometry_transform_helper_name.length = SIZE_MAX;
  1772. opts.scale_helper_name.data = "ScaleHelper";
  1773. opts.scale_helper_name.length = SIZE_MAX;
  1774. opts.node_depth_limit = 512;
  1775. opts.target_camera_axes = ufbx_axes_right_handed_y_up;
  1776. opts.target_light_axes = ufbx_axes_right_handed_y_up;
  1777. opts.clean_skin_weights = true;
  1778. if (p_state->discard_meshes_and_materials) {
  1779. opts.ignore_geometry = true;
  1780. opts.ignore_embedded = true;
  1781. }
  1782. opts.generate_missing_normals = true;
  1783. ThreadPoolFBX thread_pool;
  1784. thread_pool.pool = WorkerThreadPool::get_singleton();
  1785. opts.thread_opts.pool.init_fn = &_thread_pool_init_fn;
  1786. opts.thread_opts.pool.run_fn = &_thread_pool_run_fn;
  1787. opts.thread_opts.pool.wait_fn = &_thread_pool_wait_fn;
  1788. opts.thread_opts.pool.user = &thread_pool;
  1789. opts.thread_opts.memory_limit = 64 * 1024 * 1024;
  1790. ufbx_error error;
  1791. ufbx_stream file_stream = {};
  1792. file_stream.read_fn = &_file_access_read_fn;
  1793. file_stream.skip_fn = &_file_access_skip_fn;
  1794. file_stream.user = p_file.ptr();
  1795. p_state->scene.reset(ufbx_load_stream(&file_stream, &opts, &error));
  1796. if (!p_state->scene.get()) {
  1797. char err_buf[512];
  1798. ufbx_format_error(err_buf, sizeof(err_buf), &error);
  1799. ERR_FAIL_V_MSG(ERR_PARSE_ERROR, err_buf);
  1800. }
  1801. const int max_warning_count = 10;
  1802. int warning_count[UFBX_WARNING_TYPE_COUNT] = {};
  1803. int ignored_warning_count = 0;
  1804. for (const ufbx_warning &warning : p_state->scene->metadata.warnings) {
  1805. if (warning_count[warning.type]++ < max_warning_count) {
  1806. if (warning.count > 1) {
  1807. WARN_PRINT(vformat("FBX: ufbx warning: %s (x%d)", _as_string(warning.description), (int)warning.count));
  1808. } else {
  1809. String element_name;
  1810. if (warning.element_id != UFBX_NO_INDEX) {
  1811. element_name = _find_element_name(p_state->scene->elements[warning.element_id]);
  1812. }
  1813. if (!element_name.is_empty()) {
  1814. WARN_PRINT(vformat("FBX: ufbx warning in '%s': %s", element_name, _as_string(warning.description)));
  1815. } else {
  1816. WARN_PRINT(vformat("FBX: ufbx warning: %s", _as_string(warning.description)));
  1817. }
  1818. }
  1819. } else {
  1820. ignored_warning_count++;
  1821. }
  1822. }
  1823. if (ignored_warning_count > 0) {
  1824. WARN_PRINT(vformat("FBX: ignored %d further ufbx warnings", ignored_warning_count));
  1825. }
  1826. err = _parse_fbx_state(p_state, p_path);
  1827. ERR_FAIL_COND_V(err != OK, err);
  1828. return OK;
  1829. }
  1830. void FBXDocument::_bind_methods() {
  1831. }
  1832. Node *FBXDocument::generate_scene(Ref<GLTFState> p_state, float p_bake_fps, bool p_trimming, bool p_remove_immutable_tracks) {
  1833. Ref<FBXState> state = p_state;
  1834. ERR_FAIL_COND_V(state.is_null(), nullptr);
  1835. ERR_FAIL_NULL_V(state, nullptr);
  1836. ERR_FAIL_INDEX_V(0, state->root_nodes.size(), nullptr);
  1837. p_state->set_bake_fps(p_bake_fps);
  1838. GLTFNodeIndex fbx_root = state->root_nodes.write[0];
  1839. Node *fbx_root_node = state->get_scene_node(fbx_root);
  1840. Node *root = fbx_root_node;
  1841. if (root && root->get_owner() && root->get_owner() != root) {
  1842. root = root->get_owner();
  1843. }
  1844. ERR_FAIL_NULL_V(root, nullptr);
  1845. _process_mesh_instances(state, root);
  1846. if (state->get_create_animations() && state->animations.size()) {
  1847. AnimationPlayer *ap = memnew(AnimationPlayer);
  1848. root->add_child(ap, true);
  1849. ap->set_owner(root);
  1850. for (int i = 0; i < state->animations.size(); i++) {
  1851. _import_animation(state, ap, i, p_trimming, p_remove_immutable_tracks);
  1852. }
  1853. }
  1854. ERR_FAIL_NULL_V(root, nullptr);
  1855. return root;
  1856. }
  1857. Error FBXDocument::append_from_buffer(PackedByteArray p_bytes, String p_base_path, Ref<GLTFState> p_state, uint32_t p_flags) {
  1858. Ref<FBXState> state = p_state;
  1859. ERR_FAIL_COND_V(state.is_null(), ERR_INVALID_PARAMETER);
  1860. ERR_FAIL_NULL_V(p_bytes.ptr(), ERR_INVALID_DATA);
  1861. Error err = FAILED;
  1862. state->use_named_skin_binds = p_flags & FBX_IMPORT_USE_NAMED_SKIN_BINDS;
  1863. state->discard_meshes_and_materials = p_flags & FBX_IMPORT_DISCARD_MESHES_AND_MATERIALS;
  1864. Ref<FileAccessMemory> file_access;
  1865. file_access.instantiate();
  1866. file_access->open_custom(p_bytes.ptr(), p_bytes.size());
  1867. state->base_path = p_base_path.get_base_dir();
  1868. err = _parse(state, state->base_path, file_access);
  1869. ERR_FAIL_COND_V(err != OK, err);
  1870. // TODO: 202040118 // fire
  1871. // for (Ref<GLTFDocumentExtension> ext : get_all_gltf_document_extensions()) {
  1872. // ERR_CONTINUE(ext.is_null());
  1873. // err = ext->import_post_parse(state);
  1874. // ERR_FAIL_COND_V(err != OK, err);
  1875. // }
  1876. return OK;
  1877. }
  1878. Error FBXDocument::_parse_fbx_state(Ref<FBXState> p_state, const String &p_search_path) {
  1879. Error err;
  1880. // Abort parsing if the scene is not loaded.
  1881. ERR_FAIL_NULL_V(p_state->scene.get(), ERR_PARSE_ERROR);
  1882. /* PARSE SCENE */
  1883. err = _parse_scenes(p_state);
  1884. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1885. /* PARSE NODES */
  1886. err = _parse_nodes(p_state);
  1887. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1888. if (!p_state->discard_meshes_and_materials) {
  1889. /* PARSE IMAGES */
  1890. err = _parse_images(p_state, p_search_path);
  1891. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1892. /* PARSE MATERIALS */
  1893. err = _parse_materials(p_state);
  1894. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1895. }
  1896. /* PARSE SKINS */
  1897. err = _parse_skins(p_state);
  1898. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1899. /* DETERMINE SKELETONS */
  1900. err = SkinTool::_determine_skeletons(p_state->skins, p_state->nodes, p_state->skeletons, p_state->get_import_as_skeleton_bones() ? p_state->root_nodes : Vector<GLTFNodeIndex>());
  1901. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1902. /* CREATE SKELETONS */
  1903. err = SkinTool::_create_skeletons(p_state->unique_names, p_state->skins, p_state->nodes, p_state->skeleton3d_to_fbx_skeleton, p_state->skeletons, p_state->scene_nodes);
  1904. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1905. /* CREATE SKINS */
  1906. err = SkinTool::_create_skins(p_state->skins, p_state->nodes, p_state->use_named_skin_binds, p_state->unique_names);
  1907. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1908. /* PARSE MESHES (we have enough info now) */
  1909. err = _parse_meshes(p_state);
  1910. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1911. /* PARSE LIGHTS */
  1912. err = _parse_lights(p_state);
  1913. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1914. /* PARSE CAMERAS */
  1915. err = _parse_cameras(p_state);
  1916. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1917. /* PARSE ANIMATIONS */
  1918. err = _parse_animations(p_state);
  1919. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  1920. /* ASSIGN SCENE NAMES */
  1921. _assign_node_names(p_state);
  1922. Node3D *root = memnew(Node3D);
  1923. for (int32_t root_i = 0; root_i < p_state->root_nodes.size(); root_i++) {
  1924. _generate_scene_node(p_state, p_state->root_nodes[root_i], root, root);
  1925. }
  1926. return OK;
  1927. }
  1928. Error FBXDocument::append_from_file(String p_path, Ref<GLTFState> p_state, uint32_t p_flags, String p_base_path) {
  1929. Ref<FBXState> state = p_state;
  1930. ERR_FAIL_COND_V(state.is_null(), ERR_INVALID_PARAMETER);
  1931. ERR_FAIL_COND_V(p_path.is_empty(), ERR_FILE_NOT_FOUND);
  1932. if (p_state == Ref<FBXState>()) {
  1933. p_state.instantiate();
  1934. }
  1935. state->filename = p_path.get_file().get_basename();
  1936. state->use_named_skin_binds = p_flags & FBX_IMPORT_USE_NAMED_SKIN_BINDS;
  1937. state->discard_meshes_and_materials = p_flags & FBX_IMPORT_DISCARD_MESHES_AND_MATERIALS;
  1938. Error err;
  1939. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ, &err);
  1940. ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN);
  1941. ERR_FAIL_NULL_V(file, ERR_FILE_CANT_OPEN);
  1942. String base_path = p_base_path;
  1943. if (base_path.is_empty()) {
  1944. base_path = p_path.get_base_dir();
  1945. }
  1946. state->base_path = base_path;
  1947. err = _parse(p_state, base_path, file);
  1948. ERR_FAIL_COND_V(err != OK, err);
  1949. // TODO: 20240118 // fire
  1950. // for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  1951. // ERR_CONTINUE(ext.is_null());
  1952. // err = ext->import_post_parse(p_state);
  1953. // ERR_FAIL_COND_V(err != OK, err);
  1954. // }
  1955. return OK;
  1956. }
  1957. void FBXDocument::_process_uv_set(PackedVector2Array &uv_array) {
  1958. int uv_size = uv_array.size();
  1959. for (int uv_i = 0; uv_i < uv_size; uv_i++) {
  1960. Vector2 &uv = uv_array.write[uv_i];
  1961. uv.y = 1.0 - uv.y;
  1962. }
  1963. }
  1964. void FBXDocument::_zero_unused_elements(Vector<float> &cur_custom, int start, int end, int num_channels) {
  1965. for (int32_t uv_i = start; uv_i < end; uv_i++) {
  1966. int index = uv_i * num_channels;
  1967. for (int channel = 0; channel < num_channels; channel++) {
  1968. cur_custom.write[index + channel] = 0;
  1969. }
  1970. }
  1971. }
  1972. Error FBXDocument::_parse_lights(Ref<FBXState> p_state) {
  1973. const ufbx_scene *fbx_scene = p_state->scene.get();
  1974. for (size_t i = 0; i < fbx_scene->lights.count; i++) {
  1975. const ufbx_light *fbx_light = fbx_scene->lights.data[i];
  1976. Ref<GLTFLight> light;
  1977. light.instantiate();
  1978. light->set_name(_as_string(fbx_light->name));
  1979. light->set_color(Color(fbx_light->color.x, fbx_light->color.y, fbx_light->color.z));
  1980. light->set_intensity(fbx_light->intensity);
  1981. switch (fbx_light->type) {
  1982. case UFBX_LIGHT_POINT:
  1983. light->set_light_type("point");
  1984. break;
  1985. case UFBX_LIGHT_DIRECTIONAL:
  1986. light->set_light_type("directional");
  1987. break;
  1988. case UFBX_LIGHT_SPOT:
  1989. light->set_light_type("spot");
  1990. break;
  1991. case UFBX_LIGHT_AREA:
  1992. light->set_light_type("area");
  1993. break;
  1994. case UFBX_LIGHT_VOLUME:
  1995. light->set_light_type("volume");
  1996. break;
  1997. default:
  1998. light->set_light_type("unknown");
  1999. break;
  2000. }
  2001. Dictionary additional_data;
  2002. additional_data["shadow"] = fbx_light->cast_shadows;
  2003. if (fbx_light->decay == UFBX_LIGHT_DECAY_NONE) {
  2004. additional_data["decay"] = "none";
  2005. } else if (fbx_light->decay == UFBX_LIGHT_DECAY_LINEAR) {
  2006. additional_data["decay"] = "linear";
  2007. } else if (fbx_light->decay == UFBX_LIGHT_DECAY_QUADRATIC) {
  2008. additional_data["decay"] = "quadratic";
  2009. } else if (fbx_light->decay == UFBX_LIGHT_DECAY_CUBIC) {
  2010. additional_data["decay"] = "cubic";
  2011. }
  2012. if (fbx_light->area_shape == UFBX_LIGHT_AREA_SHAPE_RECTANGLE) {
  2013. additional_data["areaShape"] = "rectangle";
  2014. } else if (fbx_light->area_shape == UFBX_LIGHT_AREA_SHAPE_SPHERE) {
  2015. additional_data["areaShape"] = "sphere";
  2016. }
  2017. light->set_inner_cone_angle(fbx_light->inner_angle);
  2018. light->set_outer_cone_angle(fbx_light->outer_angle);
  2019. additional_data["castLight"] = fbx_light->cast_light;
  2020. additional_data["castShadows"] = fbx_light->cast_shadows;
  2021. light->set_additional_data("GODOT_fbx_light", additional_data);
  2022. p_state->lights.push_back(light);
  2023. }
  2024. print_verbose("FBX: Total lights: " + itos(p_state->lights.size()));
  2025. return OK;
  2026. }
  2027. String FBXDocument::_get_texture_path(const String &p_base_dir, const String &p_source_file_path) const {
  2028. // Check if the original path exists first.
  2029. if (FileAccess::exists(p_source_file_path)) {
  2030. return p_source_file_path.strip_edges();
  2031. }
  2032. const String tex_file_name = p_source_file_path.get_file();
  2033. const Vector<String> subdirs = {
  2034. "", "textures/", "Textures/", "images/",
  2035. "Images/", "materials/", "Materials/",
  2036. "maps/", "Maps/", "tex/", "Tex/"
  2037. };
  2038. String base_dir = p_base_dir;
  2039. const String source_file_name = tex_file_name;
  2040. while (!base_dir.is_empty()) {
  2041. String old_base_dir = base_dir;
  2042. for (int i = 0; i < subdirs.size(); ++i) {
  2043. String full_path = base_dir.path_join(subdirs[i] + source_file_name);
  2044. if (FileAccess::exists(full_path)) {
  2045. return full_path.strip_edges();
  2046. }
  2047. }
  2048. base_dir = base_dir.get_base_dir();
  2049. if (base_dir == old_base_dir) {
  2050. break;
  2051. }
  2052. }
  2053. return String();
  2054. }
  2055. Error FBXDocument::_parse_skins(Ref<FBXState> p_state) {
  2056. const ufbx_scene *fbx_scene = p_state->scene.get();
  2057. HashMap<GLTFNodeIndex, bool> joint_mapping;
  2058. for (const ufbx_skin_deformer *fbx_skin : fbx_scene->skin_deformers) {
  2059. if (fbx_skin->clusters.count == 0 || fbx_skin->weights.count == 0) {
  2060. p_state->skin_indices.push_back(-1);
  2061. continue;
  2062. }
  2063. Ref<GLTFSkin> skin;
  2064. skin.instantiate();
  2065. skin->inverse_binds.resize(fbx_skin->clusters.count);
  2066. for (int skin_i = 0; skin_i < static_cast<int>(fbx_skin->clusters.count); skin_i++) {
  2067. const ufbx_skin_cluster *fbx_cluster = fbx_skin->clusters[skin_i];
  2068. skin->inverse_binds.write[skin_i] = FBXDocument::_as_xform(fbx_cluster->geometry_to_bone);
  2069. const GLTFNodeIndex node = fbx_cluster->bone_node->typed_id;
  2070. skin->joints.push_back(node);
  2071. skin->joints_original.push_back(node);
  2072. p_state->nodes.write[node]->joint = true;
  2073. }
  2074. if (fbx_skin->name.length > 0) {
  2075. skin->set_name(FBXDocument::_as_string(fbx_skin->name));
  2076. } else {
  2077. skin->set_name(vformat("skin_%s", itos(fbx_skin->typed_id)));
  2078. }
  2079. p_state->skin_indices.push_back(p_state->skins.size());
  2080. p_state->skins.push_back(skin);
  2081. }
  2082. for (const ufbx_bone *fbx_bone : fbx_scene->bones) {
  2083. for (const ufbx_node *fbx_node : fbx_bone->instances) {
  2084. const GLTFNodeIndex node = fbx_node->typed_id;
  2085. if (!p_state->nodes.write[node]->joint) {
  2086. p_state->nodes.write[node]->joint = true;
  2087. if (!(fbx_node->parent && fbx_node->parent->attrib_type == UFBX_ELEMENT_BONE)) {
  2088. Ref<GLTFSkin> skin;
  2089. skin.instantiate();
  2090. skin->joints.push_back(node);
  2091. skin->joints_original.push_back(node);
  2092. skin->set_name(vformat("skin_%s", itos(p_state->skins.size())));
  2093. p_state->skin_indices.push_back(p_state->skins.size());
  2094. p_state->skins.push_back(skin);
  2095. }
  2096. }
  2097. }
  2098. }
  2099. p_state->original_skin_indices = p_state->skin_indices.duplicate();
  2100. Error err = SkinTool::_asset_parse_skins(
  2101. p_state->original_skin_indices,
  2102. p_state->skins.duplicate(),
  2103. p_state->nodes.duplicate(),
  2104. p_state->skin_indices,
  2105. p_state->skins,
  2106. joint_mapping);
  2107. if (err != OK) {
  2108. return err;
  2109. }
  2110. for (int i = 0; i < p_state->skins.size(); ++i) {
  2111. Ref<GLTFSkin> skin = p_state->skins.write[i];
  2112. ERR_FAIL_COND_V(skin.is_null(), ERR_PARSE_ERROR);
  2113. // Expand and verify the skin
  2114. ERR_FAIL_COND_V(SkinTool::_expand_skin(p_state->nodes, skin), ERR_PARSE_ERROR);
  2115. ERR_FAIL_COND_V(SkinTool::_verify_skin(p_state->nodes, skin), ERR_PARSE_ERROR);
  2116. }
  2117. print_verbose("FBX: Total skins: " + itos(p_state->skins.size()));
  2118. for (HashMap<GLTFNodeIndex, bool>::Iterator it = joint_mapping.begin(); it != joint_mapping.end(); ++it) {
  2119. GLTFNodeIndex node_index = it->key;
  2120. bool is_joint = it->value;
  2121. if (is_joint) {
  2122. if (p_state->nodes.size() > node_index) {
  2123. p_state->nodes.write[node_index]->joint = true;
  2124. }
  2125. }
  2126. }
  2127. return OK;
  2128. }
  2129. PackedByteArray FBXDocument::generate_buffer(Ref<GLTFState> p_state) {
  2130. return PackedByteArray();
  2131. }
  2132. Error FBXDocument::write_to_filesystem(Ref<GLTFState> p_state, const String &p_path) {
  2133. return ERR_UNAVAILABLE;
  2134. }
  2135. Error FBXDocument::append_from_scene(Node *p_node, Ref<GLTFState> p_state, uint32_t p_flags) {
  2136. return ERR_UNAVAILABLE;
  2137. }
  2138. Vector3 FBXDocument::_as_vec3(const ufbx_vec3 &p_vector) {
  2139. return Vector3(real_t(p_vector.x), real_t(p_vector.y), real_t(p_vector.z));
  2140. }
  2141. String FBXDocument::_as_string(const ufbx_string &p_string) {
  2142. return String::utf8(p_string.data, (int)p_string.length);
  2143. }
  2144. Transform3D FBXDocument::_as_xform(const ufbx_matrix &p_mat) {
  2145. Transform3D xform;
  2146. xform.basis.set_column(Vector3::AXIS_X, _as_vec3(p_mat.cols[0]));
  2147. xform.basis.set_column(Vector3::AXIS_Y, _as_vec3(p_mat.cols[1]));
  2148. xform.basis.set_column(Vector3::AXIS_Z, _as_vec3(p_mat.cols[2]));
  2149. xform.set_origin(_as_vec3(p_mat.cols[3]));
  2150. return xform;
  2151. }