fbx_document.cpp 92 KB

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