fbx_document.cpp 93 KB

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