editor_scene_importer_fbxconv.cpp 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. /*************************************************************************/
  2. /* editor_scene_importer_fbxconv.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  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 "editor_scene_importer_fbxconv.h"
  31. #include "editor/editor_settings.h"
  32. #include "os/file_access.h"
  33. #include "os/os.h"
  34. #include "scene/3d/mesh_instance.h"
  35. #include "scene/animation/animation_player.h"
  36. String EditorSceneImporterFBXConv::_id(const String &p_id) const {
  37. return p_id.replace(":", "_").replace("/", "_");
  38. }
  39. uint32_t EditorSceneImporterFBXConv::get_import_flags() const {
  40. return IMPORT_SCENE | IMPORT_ANIMATION;
  41. }
  42. void EditorSceneImporterFBXConv::get_extensions(List<String> *r_extensions) const {
  43. r_extensions->push_back("fbx");
  44. r_extensions->push_back("g3dj");
  45. }
  46. Color EditorSceneImporterFBXConv::_get_color(const Array &a) {
  47. if (a.size() < 3)
  48. return Color();
  49. Color c;
  50. c.r = a[0];
  51. c.g = a[1];
  52. c.b = a[2];
  53. if (a.size() >= 4)
  54. c.a = a[3];
  55. return c;
  56. }
  57. Transform EditorSceneImporterFBXConv::_get_transform_mixed(const Dictionary &d, const Dictionary &dbase) {
  58. Array translation;
  59. if (d.has("translation"))
  60. translation = d["translation"];
  61. else if (dbase.has("translation"))
  62. translation = dbase["translation"];
  63. Array rotation;
  64. if (d.has("rotation"))
  65. rotation = d["rotation"];
  66. else if (dbase.has("rotation"))
  67. rotation = dbase["rotation"];
  68. Array scale;
  69. if (d.has("scale"))
  70. scale = d["scale"];
  71. else if (dbase.has("scale"))
  72. scale = dbase["scale"];
  73. Transform t;
  74. if (translation.size()) {
  75. Array tr = translation;
  76. if (tr.size() >= 3) {
  77. t.origin.x = tr[0];
  78. t.origin.y = tr[1];
  79. t.origin.z = tr[2];
  80. }
  81. }
  82. if (rotation.size()) {
  83. Array r = rotation;
  84. if (r.size() >= 4) {
  85. Quat q;
  86. q.x = r[0];
  87. q.y = r[1];
  88. q.z = r[2];
  89. q.w = r[3];
  90. t.basis = Matrix3(q);
  91. }
  92. }
  93. if (scale.size()) {
  94. Array sc = scale;
  95. if (sc.size() >= 3) {
  96. Vector3 s;
  97. s.x = sc[0];
  98. s.y = sc[1];
  99. s.z = sc[2];
  100. t.basis.scale(s);
  101. }
  102. }
  103. return t;
  104. }
  105. Transform EditorSceneImporterFBXConv::_get_transform(const Dictionary &d) {
  106. Transform t;
  107. if (d.has("translation")) {
  108. Array tr = d["translation"];
  109. if (tr.size() >= 3) {
  110. t.origin.x = tr[0];
  111. t.origin.y = tr[1];
  112. t.origin.z = tr[2];
  113. }
  114. }
  115. if (d.has("rotation")) {
  116. Array r = d["rotation"];
  117. if (r.size() >= 4) {
  118. Quat q;
  119. q.x = r[0];
  120. q.y = r[1];
  121. q.z = r[2];
  122. q.w = r[3];
  123. t.basis = Matrix3(q);
  124. }
  125. }
  126. if (d.has("scale")) {
  127. Array sc = d["scale"];
  128. if (sc.size() >= 3) {
  129. Vector3 s;
  130. s.x = sc[0];
  131. s.y = sc[1];
  132. s.z = sc[2];
  133. t.basis.scale(s);
  134. }
  135. }
  136. return t;
  137. }
  138. void EditorSceneImporterFBXConv::_detect_bones_in_nodes(State &state, const Array &p_nodes) {
  139. for (int i = 0; i < p_nodes.size(); i++) {
  140. Dictionary d = p_nodes[i];
  141. if (d.has("isBone") && bool(d["isBone"])) {
  142. String bone_name = _id(d["id"]);
  143. print_line("IS BONE: " + bone_name);
  144. if (!state.bones.has(bone_name)) {
  145. state.bones.insert(bone_name, BoneInfo());
  146. }
  147. if (!state.bones[bone_name].has_rest) {
  148. state.bones[bone_name].rest = _get_transform(d).affine_inverse();
  149. }
  150. state.bones[bone_name].node = d;
  151. //state.bones[name].rest=_get_transform(b);
  152. }
  153. if (d.has("parts")) {
  154. Array parts = d["parts"];
  155. for (int j = 0; j < parts.size(); j++) {
  156. Dictionary p = parts[j];
  157. if (p.has("bones")) {
  158. Array bones = p["bones"];
  159. //omfg
  160. for (int k = 0; k < bones.size(); k++) {
  161. Dictionary b = bones[k];
  162. if (b.has("node")) {
  163. String name = _id(b["node"]);
  164. if (!state.bones.has(name)) {
  165. state.bones.insert(name, BoneInfo());
  166. }
  167. state.bones[name].rest = _get_transform(b);
  168. state.bones[name].has_rest = true;
  169. }
  170. }
  171. }
  172. }
  173. }
  174. if (d.has("children")) {
  175. _detect_bones_in_nodes(state, d["children"]);
  176. }
  177. }
  178. }
  179. void EditorSceneImporterFBXConv::_parse_skeletons(const String &p_name, State &state, const Array &p_nodes, Skeleton *p_skeleton, int p_parent) {
  180. for (int i = 0; i < p_nodes.size(); i++) {
  181. Dictionary d = p_nodes[i];
  182. int bone_idx = -1;
  183. String id;
  184. Skeleton *skeleton = p_skeleton;
  185. if (d.has("id")) {
  186. id = _id(d["id"]);
  187. if (state.bones.has(id)) {
  188. //BONER
  189. if (!skeleton) {
  190. skeleton = memnew(Skeleton);
  191. state.skeletons[id] = skeleton;
  192. }
  193. bone_idx = skeleton->get_bone_count();
  194. skeleton->add_bone(id);
  195. skeleton->set_bone_parent(bone_idx, p_parent);
  196. skeleton->set_bone_rest(bone_idx, state.bones[id].rest);
  197. state.bones[id].skeleton = skeleton;
  198. }
  199. }
  200. if (d.has("children")) {
  201. _parse_skeletons(id, state, d["children"], skeleton, bone_idx);
  202. }
  203. }
  204. }
  205. void EditorSceneImporterFBXConv::_detect_bones(State &state) {
  206. //This format should mark when a node is a bone,
  207. //which is the only thing that Collada does right.
  208. //think about others implementing a parser.
  209. //Just _one_ string and you avoid loads of lines of code to other people.
  210. for (int i = 0; i < state.animations.size(); i++) {
  211. Dictionary an = state.animations[i];
  212. if (an.has("bones")) {
  213. Array bo = an["bones"];
  214. for (int j = 0; j < bo.size(); j++) {
  215. Dictionary b = bo[j];
  216. if (b.has("boneId")) {
  217. String id = b["boneId"];
  218. if (!state.bones.has(id)) {
  219. state.bones.insert(id, BoneInfo());
  220. }
  221. state.bones[id].has_anim_chan = true; //used in anim
  222. }
  223. }
  224. }
  225. }
  226. _detect_bones_in_nodes(state, state.nodes);
  227. _parse_skeletons("", state, state.nodes, NULL, -1);
  228. print_line("found bones: " + itos(state.bones.size()));
  229. print_line("found skeletons: " + itos(state.skeletons.size()));
  230. }
  231. Error EditorSceneImporterFBXConv::_parse_bones(State &state, const Array &p_bones, Skeleton *p_skeleton) {
  232. return OK;
  233. }
  234. void EditorSceneImporterFBXConv::_add_surface(State &state, Ref<Mesh> &m, const Dictionary &part) {
  235. if (part.has("meshpartid")) {
  236. String id = part["meshpartid"];
  237. ERR_FAIL_COND(!state.surface_cache.has(id));
  238. Ref<Material> mat;
  239. if (part.has("materialid")) {
  240. String matid = part["materialid"];
  241. if (state.material_cache.has(matid)) {
  242. mat = state.material_cache[matid];
  243. }
  244. }
  245. int idx = m->get_surface_count();
  246. Array array = state.surface_cache[id].array;
  247. DVector<float> indices = array[Mesh::ARRAY_BONES];
  248. if (indices.size() && part.has("bones")) {
  249. Map<int, int> index_map;
  250. Array bones = part["bones"];
  251. for (int i = 0; i < bones.size(); i++) {
  252. Dictionary bone = bones[i];
  253. String name = _id(bone["node"]);
  254. if (state.bones.has(name)) {
  255. int idx = state.bones[name].skeleton->find_bone(name);
  256. if (idx == -1)
  257. idx = 0;
  258. index_map[i] = idx;
  259. }
  260. }
  261. int ilen = indices.size();
  262. {
  263. DVector<float>::Write iw = indices.write();
  264. for (int j = 0; j < ilen; j++) {
  265. int b = iw[j];
  266. ERR_CONTINUE(!index_map.has(b));
  267. b = index_map[b];
  268. iw[j] = b;
  269. }
  270. }
  271. array[Mesh::ARRAY_BONES] = indices;
  272. }
  273. m->add_surface(state.surface_cache[id].primitive, array);
  274. m->surface_set_material(idx, mat);
  275. m->surface_set_name(idx, id);
  276. }
  277. }
  278. Error EditorSceneImporterFBXConv::_parse_nodes(State &state, const Array &p_nodes, Node *p_base) {
  279. for (int i = 0; i < p_nodes.size(); i++) {
  280. Dictionary n = p_nodes[i];
  281. Spatial *node = NULL;
  282. bool skip = false;
  283. String id;
  284. if (n.has("id")) {
  285. id = _id(n["id"]);
  286. }
  287. print_line("ID: " + id);
  288. if (state.skeletons.has(id)) {
  289. Skeleton *skeleton = state.skeletons[id];
  290. node = skeleton;
  291. skeleton->localize_rests();
  292. print_line("IS SKELETON! ");
  293. } else if (state.bones.has(id)) {
  294. if (p_base)
  295. node = p_base->cast_to<Spatial>();
  296. if (!state.bones[id].has_anim_chan) {
  297. print_line("no has anim " + id);
  298. }
  299. skip = true;
  300. } else if (n.has("parts")) {
  301. //is a mesh
  302. MeshInstance *mesh = memnew(MeshInstance);
  303. node = mesh;
  304. Array parts = n["parts"];
  305. String long_identifier;
  306. for (int j = 0; j < parts.size(); j++) {
  307. Dictionary part = parts[j];
  308. if (part.has("meshpartid")) {
  309. String partid = part["meshpartid"];
  310. long_identifier += partid;
  311. }
  312. }
  313. Ref<Mesh> m;
  314. if (state.mesh_cache.has(long_identifier)) {
  315. m = state.mesh_cache[long_identifier];
  316. } else {
  317. m = Ref<Mesh>(memnew(Mesh));
  318. //and parts are surfaces
  319. for (int j = 0; j < parts.size(); j++) {
  320. Dictionary part = parts[j];
  321. if (part.has("meshpartid")) {
  322. _add_surface(state, m, part);
  323. }
  324. }
  325. state.mesh_cache[long_identifier] = m;
  326. }
  327. mesh->set_mesh(m);
  328. }
  329. if (!skip) {
  330. if (!node) {
  331. node = memnew(Spatial);
  332. }
  333. node->set_name(id);
  334. node->set_transform(_get_transform(n));
  335. p_base->add_child(node);
  336. node->set_owner(state.scene);
  337. }
  338. if (n.has("children")) {
  339. Error err = _parse_nodes(state, n["children"], node);
  340. if (err)
  341. return err;
  342. }
  343. }
  344. return OK;
  345. }
  346. void EditorSceneImporterFBXConv::_parse_materials(State &state) {
  347. for (int i = 0; i < state.materials.size(); i++) {
  348. Dictionary material = state.materials[i];
  349. ERR_CONTINUE(!material.has("id"));
  350. String id = _id(material["id"]);
  351. Ref<FixedMaterial> mat = memnew(FixedMaterial);
  352. if (material.has("diffuse")) {
  353. mat->set_parameter(FixedMaterial::PARAM_DIFFUSE, _get_color(material["diffuse"]));
  354. }
  355. if (material.has("specular")) {
  356. mat->set_parameter(FixedMaterial::PARAM_SPECULAR, _get_color(material["specular"]));
  357. }
  358. if (material.has("emissive")) {
  359. mat->set_parameter(FixedMaterial::PARAM_EMISSION, _get_color(material["emissive"]));
  360. }
  361. if (material.has("shininess")) {
  362. float exp = material["shininess"];
  363. mat->set_parameter(FixedMaterial::PARAM_SPECULAR_EXP, exp);
  364. }
  365. if (material.has("opacity")) {
  366. Color c = mat->get_parameter(FixedMaterial::PARAM_DIFFUSE);
  367. c.a = material["opacity"];
  368. mat->set_parameter(FixedMaterial::PARAM_DIFFUSE, c);
  369. }
  370. if (material.has("textures")) {
  371. Array textures = material["textures"];
  372. for (int j = 0; j < textures.size(); j++) {
  373. Dictionary texture = textures[j];
  374. Ref<Texture> tex;
  375. if (texture.has("filename")) {
  376. String filename = texture["filename"];
  377. String path = state.base_path + "/" + filename.replace("\\", "/");
  378. if (state.texture_cache.has(path)) {
  379. tex = state.texture_cache[path];
  380. } else {
  381. tex = ResourceLoader::load(path, "ImageTexture");
  382. if (tex.is_null()) {
  383. if (state.missing_deps)
  384. state.missing_deps->push_back(path);
  385. }
  386. state.texture_cache[path] = tex; //add anyway
  387. }
  388. }
  389. if (tex.is_valid() && texture.has("type")) {
  390. String type = texture["type"];
  391. if (type == "DIFFUSE")
  392. mat->set_texture(FixedMaterial::PARAM_DIFFUSE, tex);
  393. else if (type == "SPECULAR")
  394. mat->set_texture(FixedMaterial::PARAM_SPECULAR, tex);
  395. else if (type == "SHININESS")
  396. mat->set_texture(FixedMaterial::PARAM_SPECULAR_EXP, tex);
  397. else if (type == "NORMAL")
  398. mat->set_texture(FixedMaterial::PARAM_NORMAL, tex);
  399. else if (type == "EMISSIVE")
  400. mat->set_texture(FixedMaterial::PARAM_EMISSION, tex);
  401. }
  402. }
  403. }
  404. state.material_cache[id] = mat;
  405. }
  406. }
  407. void EditorSceneImporterFBXConv::_parse_surfaces(State &state) {
  408. for (int i = 0; i < state.meshes.size(); i++) {
  409. Dictionary mesh = state.meshes[i];
  410. ERR_CONTINUE(!mesh.has("attributes"));
  411. ERR_CONTINUE(!mesh.has("vertices"));
  412. ERR_CONTINUE(!mesh.has("parts"));
  413. print_line("MESH #" + itos(i));
  414. Array attrlist = mesh["attributes"];
  415. Array vertices = mesh["vertices"];
  416. bool exists[Mesh::ARRAY_MAX];
  417. int ofs[Mesh::ARRAY_MAX];
  418. int weight_max = 0;
  419. int binormal_ofs = -1;
  420. int weight_ofs[4];
  421. for (int j = 0; j < Mesh::ARRAY_MAX; j++) {
  422. exists[j] = false;
  423. ofs[j] = 0;
  424. }
  425. exists[Mesh::ARRAY_INDEX] = true;
  426. float stride = 0;
  427. for (int j = 0; j < attrlist.size(); j++) {
  428. String attr = attrlist[j];
  429. if (attr == "POSITION") {
  430. exists[Mesh::ARRAY_VERTEX] = true;
  431. ofs[Mesh::ARRAY_VERTEX] = stride;
  432. stride += 3;
  433. } else if (attr == "NORMAL") {
  434. exists[Mesh::ARRAY_NORMAL] = true;
  435. ofs[Mesh::ARRAY_NORMAL] = stride;
  436. stride += 3;
  437. } else if (attr == "COLOR") {
  438. exists[Mesh::ARRAY_COLOR] = true;
  439. ofs[Mesh::ARRAY_COLOR] = stride;
  440. stride += 4;
  441. } else if (attr == "COLORPACKED") {
  442. stride += 1; //ignore
  443. } else if (attr == "TANGENT") {
  444. exists[Mesh::ARRAY_TANGENT] = true;
  445. ofs[Mesh::ARRAY_TANGENT] = stride;
  446. stride += 3;
  447. } else if (attr == "BINORMAL") {
  448. binormal_ofs = stride;
  449. stride += 3;
  450. } else if (attr == "TEXCOORD0") {
  451. exists[Mesh::ARRAY_TEX_UV] = true;
  452. ofs[Mesh::ARRAY_TEX_UV] = stride;
  453. stride += 2;
  454. } else if (attr == "TEXCOORD1") {
  455. exists[Mesh::ARRAY_TEX_UV2] = true;
  456. ofs[Mesh::ARRAY_TEX_UV2] = stride;
  457. stride += 2;
  458. } else if (attr.begins_with("TEXCOORD")) {
  459. stride += 2;
  460. } else if (attr.begins_with("BLENDWEIGHT")) {
  461. int idx = attr.replace("BLENDWEIGHT", "").to_int();
  462. if (idx == 0) {
  463. exists[Mesh::ARRAY_BONES] = true;
  464. ofs[Mesh::ARRAY_BONES] = stride;
  465. exists[Mesh::ARRAY_WEIGHTS] = true;
  466. ofs[Mesh::ARRAY_WEIGHTS] = stride + 1;
  467. }
  468. if (idx < 4) {
  469. weight_ofs[idx] = stride;
  470. weight_max = MAX(weight_max, idx + 1);
  471. }
  472. stride += 2;
  473. }
  474. print_line("ATTR " + attr + " OFS: " + itos(stride));
  475. }
  476. Array parts = mesh["parts"];
  477. for (int j = 0; j < parts.size(); j++) {
  478. Dictionary part = parts[j];
  479. ERR_CONTINUE(!part.has("indices"));
  480. ERR_CONTINUE(!part.has("id"));
  481. print_line("PART: " + String(part["id"]));
  482. Array indices = part["indices"];
  483. Map<int, int> iarray;
  484. Map<int, int> array;
  485. for (int k = 0; k < indices.size(); k++) {
  486. int idx = indices[k];
  487. if (!iarray.has(idx)) {
  488. int map_to = array.size();
  489. iarray[idx] = map_to;
  490. array[map_to] = idx;
  491. }
  492. }
  493. print_line("indices total " + itos(indices.size()) + " vertices used: " + itos(array.size()));
  494. Array arrays;
  495. arrays.resize(Mesh::ARRAY_MAX);
  496. for (int k = 0; k < Mesh::ARRAY_MAX; k++) {
  497. if (!exists[k])
  498. continue;
  499. print_line("exists: " + itos(k));
  500. int lofs = ofs[k];
  501. switch (k) {
  502. case Mesh::ARRAY_VERTEX:
  503. case Mesh::ARRAY_NORMAL: {
  504. DVector<Vector3> vtx;
  505. vtx.resize(array.size());
  506. {
  507. int len = array.size();
  508. DVector<Vector3>::Write w = vtx.write();
  509. for (int l = 0; l < len; l++) {
  510. int pos = array[l];
  511. w[l].x = vertices[pos * stride + lofs + 0];
  512. w[l].y = vertices[pos * stride + lofs + 1];
  513. w[l].z = vertices[pos * stride + lofs + 2];
  514. }
  515. }
  516. arrays[k] = vtx;
  517. } break;
  518. case Mesh::ARRAY_TANGENT: {
  519. if (binormal_ofs < 0)
  520. break;
  521. DVector<float> tangents;
  522. tangents.resize(array.size() * 4);
  523. {
  524. int len = array.size();
  525. DVector<float>::Write w = tangents.write();
  526. for (int l = 0; l < len; l++) {
  527. int pos = array[l];
  528. Vector3 n;
  529. n.x = vertices[pos * stride + ofs[Mesh::ARRAY_NORMAL] + 0];
  530. n.y = vertices[pos * stride + ofs[Mesh::ARRAY_NORMAL] + 1];
  531. n.z = vertices[pos * stride + ofs[Mesh::ARRAY_NORMAL] + 2];
  532. Vector3 t;
  533. t.x = vertices[pos * stride + lofs + 0];
  534. t.y = vertices[pos * stride + lofs + 1];
  535. t.z = vertices[pos * stride + lofs + 2];
  536. Vector3 bi;
  537. bi.x = vertices[pos * stride + binormal_ofs + 0];
  538. bi.y = vertices[pos * stride + binormal_ofs + 1];
  539. bi.z = vertices[pos * stride + binormal_ofs + 2];
  540. float d = bi.dot(n.cross(t));
  541. w[l * 4 + 0] = t.x;
  542. w[l * 4 + 1] = t.y;
  543. w[l * 4 + 2] = t.z;
  544. w[l * 4 + 3] = d;
  545. }
  546. }
  547. arrays[k] = tangents;
  548. } break;
  549. case Mesh::ARRAY_COLOR: {
  550. DVector<Color> cols;
  551. cols.resize(array.size());
  552. {
  553. int len = array.size();
  554. DVector<Color>::Write w = cols.write();
  555. for (int l = 0; l < len; l++) {
  556. int pos = array[l];
  557. w[l].r = vertices[pos * stride + lofs + 0];
  558. w[l].g = vertices[pos * stride + lofs + 1];
  559. w[l].b = vertices[pos * stride + lofs + 2];
  560. w[l].a = vertices[pos * stride + lofs + 3];
  561. }
  562. }
  563. arrays[k] = cols;
  564. } break;
  565. case Mesh::ARRAY_TEX_UV:
  566. case Mesh::ARRAY_TEX_UV2: {
  567. DVector<Vector2> uvs;
  568. uvs.resize(array.size());
  569. {
  570. int len = array.size();
  571. DVector<Vector2>::Write w = uvs.write();
  572. for (int l = 0; l < len; l++) {
  573. int pos = array[l];
  574. w[l].x = vertices[pos * stride + lofs + 0];
  575. w[l].y = vertices[pos * stride + lofs + 1];
  576. w[l].y = 1.0 - w[l].y;
  577. }
  578. }
  579. arrays[k] = uvs;
  580. } break;
  581. case Mesh::ARRAY_BONES:
  582. case Mesh::ARRAY_WEIGHTS: {
  583. DVector<float> arr;
  584. arr.resize(array.size() * 4);
  585. int po = k == Mesh::ARRAY_WEIGHTS ? 1 : 0;
  586. lofs = ofs[Mesh::ARRAY_BONES];
  587. {
  588. int len = array.size();
  589. DVector<float>::Write w = arr.write();
  590. for (int l = 0; l < len; l++) {
  591. int pos = array[l];
  592. for (int m = 0; m < 4; m++) {
  593. float val = 0;
  594. if (m <= weight_max)
  595. val = vertices[pos * stride + lofs + m * 2 + po];
  596. w[l * 4 + m] = val;
  597. }
  598. }
  599. }
  600. arrays[k] = arr;
  601. } break;
  602. case Mesh::ARRAY_INDEX: {
  603. DVector<int> arr;
  604. arr.resize(indices.size());
  605. {
  606. int len = indices.size();
  607. DVector<int>::Write w = arr.write();
  608. for (int l = 0; l < len; l++) {
  609. w[l] = iarray[indices[l]];
  610. }
  611. }
  612. arrays[k] = arr;
  613. } break;
  614. }
  615. }
  616. Mesh::PrimitiveType pt = Mesh::PRIMITIVE_TRIANGLES;
  617. if (part.has("type")) {
  618. String type = part["type"];
  619. if (type == "LINES")
  620. pt = Mesh::PRIMITIVE_LINES;
  621. else if (type == "POINTS")
  622. pt = Mesh::PRIMITIVE_POINTS;
  623. else if (type == "TRIANGLE_STRIP")
  624. pt = Mesh::PRIMITIVE_TRIANGLE_STRIP;
  625. else if (type == "LINE_STRIP")
  626. pt = Mesh::PRIMITIVE_LINE_STRIP;
  627. }
  628. if (pt == Mesh::PRIMITIVE_TRIANGLES) {
  629. DVector<int> ia = arrays[Mesh::ARRAY_INDEX];
  630. int len = ia.size();
  631. {
  632. DVector<int>::Write w = ia.write();
  633. for (int l = 0; l < len; l += 3) {
  634. SWAP(w[l + 1], w[l + 2]);
  635. }
  636. }
  637. arrays[Mesh::ARRAY_INDEX] = ia;
  638. }
  639. SurfaceInfo si;
  640. si.array = arrays;
  641. si.primitive = pt;
  642. state.surface_cache[_id(part["id"])] = si;
  643. }
  644. }
  645. }
  646. Error EditorSceneImporterFBXConv::_parse_animations(State &state) {
  647. AnimationPlayer *ap = memnew(AnimationPlayer);
  648. state.scene->add_child(ap);
  649. ap->set_owner(state.scene);
  650. for (int i = 0; i < state.animations.size(); i++) {
  651. Dictionary anim = state.animations[i];
  652. ERR_CONTINUE(!anim.has("id"));
  653. Ref<Animation> an = memnew(Animation);
  654. an->set_name(_id(anim["id"]));
  655. if (anim.has("bones")) {
  656. Array bone_tracks = anim["bones"];
  657. for (int j = 0; j < bone_tracks.size(); j++) {
  658. Dictionary bone_track = bone_tracks[j];
  659. String bone = bone_track["boneId"];
  660. if (!bone_track.has("keyframes"))
  661. continue;
  662. if (!state.bones.has(bone))
  663. continue;
  664. Skeleton *sk = state.bones[bone].skeleton;
  665. if (!sk)
  666. continue;
  667. int bone_idx = sk->find_bone(bone);
  668. if (bone_idx == -1)
  669. continue;
  670. String path = state.scene->get_path_to(sk);
  671. path += ":" + bone;
  672. an->add_track(Animation::TYPE_TRANSFORM);
  673. int tidx = an->get_track_count() - 1;
  674. an->track_set_path(tidx, path);
  675. Dictionary parent_xform_dict;
  676. Dictionary xform_dict;
  677. if (state.bones.has(bone)) {
  678. xform_dict = state.bones[bone].node;
  679. }
  680. Array parent_keyframes;
  681. if (sk->get_bone_parent(bone_idx) != -1) {
  682. String parent_name = sk->get_bone_name(sk->get_bone_parent(bone_idx));
  683. if (state.bones.has(parent_name)) {
  684. parent_xform_dict = state.bones[parent_name].node;
  685. }
  686. print_line("parent for " + bone + "? " + parent_name + " XFD: " + String(Variant(parent_xform_dict)));
  687. for (int k = 0; k < bone_tracks.size(); k++) {
  688. Dictionary d = bone_tracks[k];
  689. if (d["boneId"] == parent_name) {
  690. parent_keyframes = d["keyframes"];
  691. print_line("found keyframes");
  692. break;
  693. }
  694. }
  695. }
  696. print_line("BONE XFD " + String(Variant(xform_dict)));
  697. Array keyframes = bone_track["keyframes"];
  698. for (int k = 0; k < keyframes.size(); k++) {
  699. Dictionary key = keyframes[k];
  700. Transform xform = _get_transform_mixed(key, xform_dict);
  701. float time = key["keytime"];
  702. time = time / 1000.0;
  703. #if 0
  704. if (parent_keyframes.size()) {
  705. //localize
  706. print_line(itos(k)+" localizate for: "+bone);
  707. float prev_kt=-1;
  708. float kt;
  709. int idx=0;
  710. for(int l=0;l<parent_keyframes.size();l++) {
  711. Dictionary d=parent_keyframes[l];
  712. kt=d["keytime"];
  713. kt=kt/1000.0;
  714. if (kt>time)
  715. break;
  716. prev_kt=kt;
  717. idx++;
  718. }
  719. Transform t;
  720. if (idx==0) {
  721. t=_get_transform_mixed(parent_keyframes[0],parent_xform_dict);
  722. } else if (idx==parent_keyframes.size()){
  723. t=_get_transform_mixed(parent_keyframes[idx-1],parent_xform_dict);
  724. } else {
  725. t=_get_transform_mixed(parent_keyframes[idx-1],parent_xform_dict);
  726. float d = (time-prev_kt)/(kt-prev_kt);
  727. if (d>0) {
  728. Transform t2=_get_transform_mixed(parent_keyframes[idx],parent_xform_dict);
  729. t=t.interpolate_with(t2,d);
  730. } else {
  731. print_line("exact: "+rtos(kt));
  732. }
  733. }
  734. xform = t.affine_inverse() * xform; //localize
  735. } else if (!parent_xform_dict.empty()) {
  736. Transform t = _get_transform(parent_xform_dict);
  737. xform = t.affine_inverse() * xform; //localize
  738. }
  739. #endif
  740. xform = sk->get_bone_rest(bone_idx).affine_inverse() * xform;
  741. Quat q = xform.basis;
  742. q.normalize();
  743. Vector3 s = xform.basis.get_scale();
  744. Vector3 l = xform.origin;
  745. an->transform_track_insert_key(tidx, time, l, q, s);
  746. }
  747. }
  748. }
  749. ap->add_animation(_id(anim["id"]), an);
  750. }
  751. return OK;
  752. }
  753. Error EditorSceneImporterFBXConv::_parse_json(State &state, const String &p_path) {
  754. //not the happiest....
  755. Vector<uint8_t> data = FileAccess::get_file_as_array(p_path);
  756. ERR_FAIL_COND_V(!data.size(), ERR_FILE_CANT_OPEN);
  757. String str;
  758. bool utferr = str.parse_utf8((const char *)data.ptr(), data.size());
  759. ERR_FAIL_COND_V(utferr, ERR_PARSE_ERROR);
  760. Dictionary dict;
  761. Error err = dict.parse_json(str);
  762. str = String(); //free mem immediately
  763. ERR_FAIL_COND_V(err, err);
  764. if (dict.has("meshes"))
  765. state.meshes = dict["meshes"];
  766. if (dict.has("materials"))
  767. state.materials = dict["materials"];
  768. if (dict.has("nodes"))
  769. state.nodes = dict["nodes"];
  770. if (dict.has("animations"))
  771. state.animations = dict["animations"];
  772. state.scene = memnew(Spatial);
  773. _detect_bones(state);
  774. _parse_surfaces(state);
  775. _parse_materials(state);
  776. err = _parse_nodes(state, state.nodes, state.scene);
  777. if (err)
  778. return err;
  779. if (state.import_animations) {
  780. err = _parse_animations(state);
  781. if (err)
  782. return err;
  783. }
  784. print_line("JSON PARSED O-K!");
  785. return OK;
  786. }
  787. Error EditorSceneImporterFBXConv::_parse_fbx(State &state, const String &p_path) {
  788. state.base_path = p_path.get_base_dir();
  789. if (p_path.to_lower().ends_with("g3dj")) {
  790. return _parse_json(state, p_path.basename() + ".g3dj");
  791. }
  792. String tool = EDITOR_DEF("fbxconv/path", "");
  793. ERR_FAIL_COND_V(!FileAccess::exists(tool), ERR_UNCONFIGURED);
  794. String wine = EDITOR_DEF("fbxconv/use_wine", "");
  795. List<String> args;
  796. String path = p_path;
  797. if (wine != "") {
  798. List<String> wpargs;
  799. wpargs.push_back("-w");
  800. wpargs.push_back(p_path);
  801. String pipe; //winepath to convert to windows path
  802. int wpres;
  803. Error wperr = OS::get_singleton()->execute(wine + "path", wpargs, true, NULL, &pipe, &wpres);
  804. ERR_FAIL_COND_V(wperr != OK, ERR_CANT_CREATE);
  805. ERR_FAIL_COND_V(wpres != 0, ERR_CANT_CREATE);
  806. path = pipe.strip_edges();
  807. args.push_back(tool);
  808. tool = wine;
  809. }
  810. args.push_back("-o");
  811. args.push_back("G3DJ");
  812. args.push_back(path);
  813. int res;
  814. Error err = OS::get_singleton()->execute(tool, args, true, NULL, NULL, &res);
  815. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  816. ERR_FAIL_COND_V(res != 0, ERR_CANT_CREATE);
  817. return _parse_json(state, p_path.basename() + ".g3dj");
  818. }
  819. Node *EditorSceneImporterFBXConv::import_scene(const String &p_path, uint32_t p_flags, List<String> *r_missing_deps, Error *r_err) {
  820. State state;
  821. state.scene = NULL;
  822. state.missing_deps = r_missing_deps;
  823. state.import_animations = p_flags & IMPORT_ANIMATION;
  824. Error err = _parse_fbx(state, p_path);
  825. if (err != OK) {
  826. if (r_err)
  827. *r_err = err;
  828. return NULL;
  829. }
  830. return state.scene;
  831. }
  832. Ref<Animation> EditorSceneImporterFBXConv::import_animation(const String &p_path, uint32_t p_flags) {
  833. return Ref<Animation>();
  834. }
  835. EditorSceneImporterFBXConv::EditorSceneImporterFBXConv() {
  836. EDITOR_DEF("fbxconv/path", "");
  837. #ifndef WINDOWS_ENABLED
  838. EDITOR_DEF("fbxconv/use_wine", "");
  839. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "fbxconv/use_wine", PROPERTY_HINT_GLOBAL_FILE));
  840. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "fbxconv/path", PROPERTY_HINT_GLOBAL_FILE));
  841. #else
  842. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "fbxconv/path", PROPERTY_HINT_GLOBAL_FILE, "exe"));
  843. #endif
  844. }