fbx_document.cpp 87 KB

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