editor_scene_importer_gltf.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278
  1. /*************************************************************************/
  2. /* editor_scene_importer_gltf.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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_gltf.h"
  31. #include "core/io/json.h"
  32. #include "core/math/math_defs.h"
  33. #include "core/os/file_access.h"
  34. #include "core/os/os.h"
  35. #include "scene/3d/camera.h"
  36. #include "scene/3d/mesh_instance.h"
  37. #include "scene/animation/animation_player.h"
  38. #include "scene/resources/surface_tool.h"
  39. #include "thirdparty/misc/base64.h"
  40. uint32_t EditorSceneImporterGLTF::get_import_flags() const {
  41. return IMPORT_SCENE | IMPORT_ANIMATION;
  42. }
  43. void EditorSceneImporterGLTF::get_extensions(List<String> *r_extensions) const {
  44. r_extensions->push_back("gltf");
  45. r_extensions->push_back("glb");
  46. }
  47. Error EditorSceneImporterGLTF::_parse_json(const String &p_path, GLTFState &state) {
  48. Error err;
  49. FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
  50. if (!f) {
  51. return err;
  52. }
  53. Vector<uint8_t> array;
  54. array.resize(f->get_len());
  55. f->get_buffer(array.ptrw(), array.size());
  56. String text;
  57. text.parse_utf8((const char *)array.ptr(), array.size());
  58. String err_txt;
  59. int err_line;
  60. Variant v;
  61. err = JSON::parse(text, v, err_txt, err_line);
  62. if (err != OK) {
  63. _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT);
  64. return err;
  65. }
  66. state.json = v;
  67. return OK;
  68. }
  69. Error EditorSceneImporterGLTF::_parse_glb(const String &p_path, GLTFState &state) {
  70. Error err;
  71. FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
  72. if (!f) {
  73. return err;
  74. }
  75. uint32_t magic = f->get_32();
  76. ERR_FAIL_COND_V(magic != 0x46546C67, ERR_FILE_UNRECOGNIZED); //glTF
  77. f->get_32(); // version
  78. f->get_32(); // length
  79. uint32_t chunk_length = f->get_32();
  80. uint32_t chunk_type = f->get_32();
  81. ERR_FAIL_COND_V(chunk_type != 0x4E4F534A, ERR_PARSE_ERROR); //JSON
  82. Vector<uint8_t> json_data;
  83. json_data.resize(chunk_length);
  84. uint32_t len = f->get_buffer(json_data.ptrw(), chunk_length);
  85. ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
  86. String text;
  87. text.parse_utf8((const char *)json_data.ptr(), json_data.size());
  88. String err_txt;
  89. int err_line;
  90. Variant v;
  91. err = JSON::parse(text, v, err_txt, err_line);
  92. if (err != OK) {
  93. _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT);
  94. return err;
  95. }
  96. state.json = v;
  97. //data?
  98. chunk_length = f->get_32();
  99. chunk_type = f->get_32();
  100. if (f->eof_reached()) {
  101. return OK; //all good
  102. }
  103. ERR_FAIL_COND_V(chunk_type != 0x004E4942, ERR_PARSE_ERROR); //BIN
  104. state.glb_data.resize(chunk_length);
  105. len = f->get_buffer(state.glb_data.ptrw(), chunk_length);
  106. ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
  107. return OK;
  108. }
  109. static Vector3 _arr_to_vec3(const Array &p_array) {
  110. ERR_FAIL_COND_V(p_array.size() != 3, Vector3());
  111. return Vector3(p_array[0], p_array[1], p_array[2]);
  112. }
  113. static Quat _arr_to_quat(const Array &p_array) {
  114. ERR_FAIL_COND_V(p_array.size() != 4, Quat());
  115. return Quat(p_array[0], p_array[1], p_array[2], p_array[3]);
  116. }
  117. static Transform _arr_to_xform(const Array &p_array) {
  118. ERR_FAIL_COND_V(p_array.size() != 16, Transform());
  119. Transform xform;
  120. xform.basis.set_axis(Vector3::AXIS_X, Vector3(p_array[0], p_array[1], p_array[2]));
  121. xform.basis.set_axis(Vector3::AXIS_Y, Vector3(p_array[4], p_array[5], p_array[6]));
  122. xform.basis.set_axis(Vector3::AXIS_Z, Vector3(p_array[8], p_array[9], p_array[10]));
  123. xform.set_origin(Vector3(p_array[12], p_array[13], p_array[14]));
  124. return xform;
  125. }
  126. String EditorSceneImporterGLTF::_gen_unique_name(GLTFState &state, const String &p_name) {
  127. int index = 1;
  128. String name;
  129. while (true) {
  130. name = p_name;
  131. if (index > 1) {
  132. name += " " + itos(index);
  133. }
  134. if (!state.unique_names.has(name)) {
  135. break;
  136. }
  137. index++;
  138. }
  139. state.unique_names.insert(name);
  140. return name;
  141. }
  142. Error EditorSceneImporterGLTF::_parse_scenes(GLTFState &state) {
  143. ERR_FAIL_COND_V(!state.json.has("scenes"), ERR_FILE_CORRUPT);
  144. Array scenes = state.json["scenes"];
  145. for (int i = 0; i < 1; i++) { //only first scene is imported
  146. Dictionary s = scenes[i];
  147. ERR_FAIL_COND_V(!s.has("nodes"), ERR_UNAVAILABLE);
  148. Array nodes = s["nodes"];
  149. for (int j = 0; j < nodes.size(); j++) {
  150. state.root_nodes.push_back(nodes[j]);
  151. }
  152. if (s.has("name")) {
  153. state.scene_name = s["name"];
  154. }
  155. }
  156. return OK;
  157. }
  158. Error EditorSceneImporterGLTF::_parse_nodes(GLTFState &state) {
  159. ERR_FAIL_COND_V(!state.json.has("nodes"), ERR_FILE_CORRUPT);
  160. Array nodes = state.json["nodes"];
  161. for (int i = 0; i < nodes.size(); i++) {
  162. GLTFNode *node = memnew(GLTFNode);
  163. Dictionary n = nodes[i];
  164. if (n.has("name")) {
  165. node->name = n["name"];
  166. }
  167. if (n.has("camera")) {
  168. node->camera = n["camera"];
  169. }
  170. if (n.has("mesh")) {
  171. node->mesh = n["mesh"];
  172. }
  173. if (n.has("skin")) {
  174. node->skin = n["skin"];
  175. /*
  176. if (!state.skin_users.has(node->skin)) {
  177. state.skin_users[node->skin] = Vector<int>();
  178. }
  179. state.skin_users[node->skin].push_back(i);
  180. */
  181. }
  182. if (n.has("matrix")) {
  183. node->xform = _arr_to_xform(n["matrix"]);
  184. } else {
  185. if (n.has("translation")) {
  186. node->translation = _arr_to_vec3(n["translation"]);
  187. }
  188. if (n.has("rotation")) {
  189. node->rotation = _arr_to_quat(n["rotation"]);
  190. }
  191. if (n.has("scale")) {
  192. node->scale = _arr_to_vec3(n["scale"]);
  193. }
  194. node->xform.basis.set_quat_scale(node->rotation, node->scale);
  195. node->xform.origin = node->translation;
  196. }
  197. if (n.has("children")) {
  198. Array children = n["children"];
  199. for (int j = 0; j < children.size(); j++) {
  200. node->children.push_back(children[j]);
  201. }
  202. }
  203. state.nodes.push_back(node);
  204. }
  205. //build the hierarchy
  206. for (int i = 0; i < state.nodes.size(); i++) {
  207. for (int j = 0; j < state.nodes[i]->children.size(); j++) {
  208. int child = state.nodes[i]->children[j];
  209. ERR_FAIL_INDEX_V(child, state.nodes.size(), ERR_FILE_CORRUPT);
  210. ERR_CONTINUE(state.nodes[child]->parent != -1); //node already has a parent, wtf.
  211. state.nodes[child]->parent = i;
  212. }
  213. }
  214. return OK;
  215. }
  216. static Vector<uint8_t> _parse_base64_uri(const String &uri) {
  217. int start = uri.find(",");
  218. ERR_FAIL_COND_V(start == -1, Vector<uint8_t>());
  219. CharString substr = uri.right(start + 1).ascii();
  220. int strlen = substr.length();
  221. Vector<uint8_t> buf;
  222. buf.resize(strlen / 4 * 3 + 1 + 1);
  223. int len = base64_decode((char *)buf.ptr(), (char *)substr.get_data(), strlen);
  224. buf.resize(len);
  225. return buf;
  226. }
  227. Error EditorSceneImporterGLTF::_parse_buffers(GLTFState &state, const String &p_base_path) {
  228. if (!state.json.has("buffers"))
  229. return OK;
  230. Array buffers = state.json["buffers"];
  231. for (int i = 0; i < buffers.size(); i++) {
  232. if (i == 0 && state.glb_data.size()) {
  233. state.buffers.push_back(state.glb_data);
  234. } else {
  235. Dictionary buffer = buffers[i];
  236. if (buffer.has("uri")) {
  237. Vector<uint8_t> buffer_data;
  238. String uri = buffer["uri"];
  239. if (uri.findn("data:application/octet-stream;base64") == 0) {
  240. //embedded data
  241. buffer_data = _parse_base64_uri(uri);
  242. } else {
  243. uri = p_base_path.plus_file(uri).replace("\\", "/"); //fix for windows
  244. buffer_data = FileAccess::get_file_as_array(uri);
  245. ERR_FAIL_COND_V(buffer.size() == 0, ERR_PARSE_ERROR);
  246. }
  247. ERR_FAIL_COND_V(!buffer.has("byteLength"), ERR_PARSE_ERROR);
  248. int byteLength = buffer["byteLength"];
  249. ERR_FAIL_COND_V(byteLength < buffer_data.size(), ERR_PARSE_ERROR);
  250. state.buffers.push_back(buffer_data);
  251. }
  252. }
  253. }
  254. print_verbose("glTF: Total buffers: " + itos(state.buffers.size()));
  255. return OK;
  256. }
  257. Error EditorSceneImporterGLTF::_parse_buffer_views(GLTFState &state) {
  258. ERR_FAIL_COND_V(!state.json.has("bufferViews"), ERR_FILE_CORRUPT);
  259. Array buffers = state.json["bufferViews"];
  260. for (int i = 0; i < buffers.size(); i++) {
  261. Dictionary d = buffers[i];
  262. GLTFBufferView buffer_view;
  263. ERR_FAIL_COND_V(!d.has("buffer"), ERR_PARSE_ERROR);
  264. buffer_view.buffer = d["buffer"];
  265. ERR_FAIL_COND_V(!d.has("byteLength"), ERR_PARSE_ERROR);
  266. buffer_view.byte_length = d["byteLength"];
  267. if (d.has("byteOffset")) {
  268. buffer_view.byte_offset = d["byteOffset"];
  269. }
  270. if (d.has("byteStride")) {
  271. buffer_view.byte_stride = d["byteStride"];
  272. }
  273. if (d.has("target")) {
  274. int target = d["target"];
  275. buffer_view.indices = target == ELEMENT_ARRAY_BUFFER;
  276. }
  277. state.buffer_views.push_back(buffer_view);
  278. }
  279. print_verbose("glTF: Total buffer views: " + itos(state.buffer_views.size()));
  280. return OK;
  281. }
  282. EditorSceneImporterGLTF::GLTFType EditorSceneImporterGLTF::_get_type_from_str(const String &p_string) {
  283. if (p_string == "SCALAR")
  284. return TYPE_SCALAR;
  285. if (p_string == "VEC2")
  286. return TYPE_VEC2;
  287. if (p_string == "VEC3")
  288. return TYPE_VEC3;
  289. if (p_string == "VEC4")
  290. return TYPE_VEC4;
  291. if (p_string == "MAT2")
  292. return TYPE_MAT2;
  293. if (p_string == "MAT3")
  294. return TYPE_MAT3;
  295. if (p_string == "MAT4")
  296. return TYPE_MAT4;
  297. ERR_FAIL_V(TYPE_SCALAR);
  298. }
  299. Error EditorSceneImporterGLTF::_parse_accessors(GLTFState &state) {
  300. ERR_FAIL_COND_V(!state.json.has("accessors"), ERR_FILE_CORRUPT);
  301. Array accessors = state.json["accessors"];
  302. for (int i = 0; i < accessors.size(); i++) {
  303. Dictionary d = accessors[i];
  304. GLTFAccessor accessor;
  305. ERR_FAIL_COND_V(!d.has("componentType"), ERR_PARSE_ERROR);
  306. accessor.component_type = d["componentType"];
  307. ERR_FAIL_COND_V(!d.has("count"), ERR_PARSE_ERROR);
  308. accessor.count = d["count"];
  309. ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
  310. accessor.type = _get_type_from_str(d["type"]);
  311. if (d.has("bufferView")) {
  312. accessor.buffer_view = d["bufferView"]; //optional because it may be sparse...
  313. }
  314. if (d.has("byteOffset")) {
  315. accessor.byte_offset = d["byteOffset"];
  316. }
  317. if (d.has("max")) {
  318. accessor.max = d["max"];
  319. }
  320. if (d.has("min")) {
  321. accessor.min = d["min"];
  322. }
  323. if (d.has("sparse")) {
  324. //eeh..
  325. Dictionary s = d["sparse"];
  326. ERR_FAIL_COND_V(!d.has("count"), ERR_PARSE_ERROR);
  327. accessor.sparse_count = d["count"];
  328. ERR_FAIL_COND_V(!d.has("indices"), ERR_PARSE_ERROR);
  329. Dictionary si = d["indices"];
  330. ERR_FAIL_COND_V(!si.has("bufferView"), ERR_PARSE_ERROR);
  331. accessor.sparse_indices_buffer_view = si["bufferView"];
  332. ERR_FAIL_COND_V(!si.has("componentType"), ERR_PARSE_ERROR);
  333. accessor.sparse_indices_component_type = si["componentType"];
  334. if (si.has("byteOffset")) {
  335. accessor.sparse_indices_byte_offset = si["byteOffset"];
  336. }
  337. ERR_FAIL_COND_V(!d.has("values"), ERR_PARSE_ERROR);
  338. Dictionary sv = d["values"];
  339. ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR);
  340. accessor.sparse_values_buffer_view = sv["bufferView"];
  341. if (sv.has("byteOffset")) {
  342. accessor.sparse_values_byte_offset = sv["byteOffset"];
  343. }
  344. }
  345. state.accessors.push_back(accessor);
  346. }
  347. print_verbose("glTF: Total accessors: " + itos(state.accessors.size()));
  348. return OK;
  349. }
  350. String EditorSceneImporterGLTF::_get_component_type_name(uint32_t p_component) {
  351. switch (p_component) {
  352. case COMPONENT_TYPE_BYTE: return "Byte";
  353. case COMPONENT_TYPE_UNSIGNED_BYTE: return "UByte";
  354. case COMPONENT_TYPE_SHORT: return "Short";
  355. case COMPONENT_TYPE_UNSIGNED_SHORT: return "UShort";
  356. case COMPONENT_TYPE_INT: return "Int";
  357. case COMPONENT_TYPE_FLOAT: return "Float";
  358. }
  359. return "<Error>";
  360. }
  361. String EditorSceneImporterGLTF::_get_type_name(GLTFType p_component) {
  362. static const char *names[] = {
  363. "float",
  364. "vec2",
  365. "vec3",
  366. "vec4",
  367. "mat2",
  368. "mat3",
  369. "mat4"
  370. };
  371. return names[p_component];
  372. }
  373. Error EditorSceneImporterGLTF::_decode_buffer_view(GLTFState &state, int p_buffer_view, double *dst, int skip_every, int skip_bytes, int element_size, int count, GLTFType type, int component_count, int component_type, int component_size, bool normalized, int byte_offset, bool for_vertex) {
  374. const GLTFBufferView &bv = state.buffer_views[p_buffer_view];
  375. int stride = bv.byte_stride ? bv.byte_stride : element_size;
  376. if (for_vertex && stride % 4) {
  377. stride += 4 - (stride % 4); //according to spec must be multiple of 4
  378. }
  379. ERR_FAIL_INDEX_V(bv.buffer, state.buffers.size(), ERR_PARSE_ERROR);
  380. uint32_t offset = bv.byte_offset + byte_offset;
  381. Vector<uint8_t> buffer = state.buffers[bv.buffer]; //copy on write, so no performance hit
  382. const uint8_t *bufptr = buffer.ptr();
  383. //use to debug
  384. print_verbose("glTF: type " + _get_type_name(type) + " component type: " + _get_component_type_name(component_type) + " stride: " + itos(stride) + " amount " + itos(count));
  385. print_verbose("glTF: accessor offset" + itos(byte_offset) + " view offset: " + itos(bv.byte_offset) + " total buffer len: " + itos(buffer.size()) + " view len " + itos(bv.byte_length));
  386. int buffer_end = (stride * (count - 1)) + element_size;
  387. ERR_FAIL_COND_V(buffer_end > bv.byte_length, ERR_PARSE_ERROR);
  388. ERR_FAIL_COND_V((int)(offset + buffer_end) > buffer.size(), ERR_PARSE_ERROR);
  389. //fill everything as doubles
  390. for (int i = 0; i < count; i++) {
  391. const uint8_t *src = &bufptr[offset + i * stride];
  392. for (int j = 0; j < component_count; j++) {
  393. if (skip_every && j > 0 && (j % skip_every) == 0) {
  394. src += skip_bytes;
  395. }
  396. double d = 0;
  397. switch (component_type) {
  398. case COMPONENT_TYPE_BYTE: {
  399. int8_t b = int8_t(*src);
  400. if (normalized) {
  401. d = (double(b) / 128.0);
  402. } else {
  403. d = double(b);
  404. }
  405. } break;
  406. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  407. uint8_t b = *src;
  408. if (normalized) {
  409. d = (double(b) / 255.0);
  410. } else {
  411. d = double(b);
  412. }
  413. } break;
  414. case COMPONENT_TYPE_SHORT: {
  415. int16_t s = *(int16_t *)src;
  416. if (normalized) {
  417. d = (double(s) / 32768.0);
  418. } else {
  419. d = double(s);
  420. }
  421. } break;
  422. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  423. uint16_t s = *(uint16_t *)src;
  424. if (normalized) {
  425. d = (double(s) / 65535.0);
  426. } else {
  427. d = double(s);
  428. }
  429. } break;
  430. case COMPONENT_TYPE_INT: {
  431. d = *(int *)src;
  432. } break;
  433. case COMPONENT_TYPE_FLOAT: {
  434. d = *(float *)src;
  435. } break;
  436. }
  437. *dst++ = d;
  438. src += component_size;
  439. }
  440. }
  441. return OK;
  442. }
  443. int EditorSceneImporterGLTF::_get_component_type_size(int component_type) {
  444. switch (component_type) {
  445. case COMPONENT_TYPE_BYTE: return 1; break;
  446. case COMPONENT_TYPE_UNSIGNED_BYTE: return 1; break;
  447. case COMPONENT_TYPE_SHORT: return 2; break;
  448. case COMPONENT_TYPE_UNSIGNED_SHORT: return 2; break;
  449. case COMPONENT_TYPE_INT: return 4; break;
  450. case COMPONENT_TYPE_FLOAT: return 4; break;
  451. default: {
  452. ERR_FAIL_V(0);
  453. }
  454. }
  455. return 0;
  456. }
  457. Vector<double> EditorSceneImporterGLTF::_decode_accessor(GLTFState &state, int p_accessor, bool p_for_vertex) {
  458. //spec, for reference:
  459. //https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  460. ERR_FAIL_INDEX_V(p_accessor, state.accessors.size(), Vector<double>());
  461. const GLTFAccessor &a = state.accessors[p_accessor];
  462. int component_count_for_type[7] = {
  463. 1, 2, 3, 4, 4, 9, 16
  464. };
  465. int component_count = component_count_for_type[a.type];
  466. int component_size = _get_component_type_size(a.component_type);
  467. ERR_FAIL_COND_V(component_size == 0, Vector<double>());
  468. int element_size = component_count * component_size;
  469. int skip_every = 0;
  470. int skip_bytes = 0;
  471. //special case of alignments, as described in spec
  472. switch (a.component_type) {
  473. case COMPONENT_TYPE_BYTE:
  474. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  475. if (a.type == TYPE_MAT2) {
  476. skip_every = 2;
  477. skip_bytes = 2;
  478. element_size = 8; //override for this case
  479. }
  480. if (a.type == TYPE_MAT3) {
  481. skip_every = 3;
  482. skip_bytes = 1;
  483. element_size = 12; //override for this case
  484. }
  485. } break;
  486. case COMPONENT_TYPE_SHORT:
  487. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  488. if (a.type == TYPE_MAT3) {
  489. skip_every = 6;
  490. skip_bytes = 4;
  491. element_size = 16; //override for this case
  492. }
  493. } break;
  494. default: {
  495. }
  496. }
  497. Vector<double> dst_buffer;
  498. dst_buffer.resize(component_count * a.count);
  499. double *dst = dst_buffer.ptrw();
  500. if (a.buffer_view >= 0) {
  501. ERR_FAIL_INDEX_V(a.buffer_view, state.buffer_views.size(), Vector<double>());
  502. Error err = _decode_buffer_view(state, a.buffer_view, dst, skip_every, skip_bytes, element_size, a.count, a.type, component_count, a.component_type, component_size, a.normalized, a.byte_offset, p_for_vertex);
  503. if (err != OK)
  504. return Vector<double>();
  505. } else {
  506. //fill with zeros, as bufferview is not defined.
  507. for (int i = 0; i < (a.count * component_count); i++) {
  508. dst_buffer.write[i] = 0;
  509. }
  510. }
  511. if (a.sparse_count > 0) {
  512. // I could not find any file using this, so this code is so far untested
  513. Vector<double> indices;
  514. indices.resize(a.sparse_count);
  515. int indices_component_size = _get_component_type_size(a.sparse_indices_component_type);
  516. Error err = _decode_buffer_view(state, a.sparse_indices_buffer_view, indices.ptrw(), 0, 0, indices_component_size, a.sparse_count, TYPE_SCALAR, 1, a.sparse_indices_component_type, indices_component_size, false, a.sparse_indices_byte_offset, false);
  517. if (err != OK)
  518. return Vector<double>();
  519. Vector<double> data;
  520. data.resize(component_count * a.sparse_count);
  521. err = _decode_buffer_view(state, a.sparse_values_buffer_view, data.ptrw(), skip_every, skip_bytes, element_size, a.sparse_count, a.type, component_count, a.component_type, component_size, a.normalized, a.sparse_values_byte_offset, p_for_vertex);
  522. if (err != OK)
  523. return Vector<double>();
  524. for (int i = 0; i < indices.size(); i++) {
  525. int write_offset = int(indices[i]) * component_count;
  526. for (int j = 0; j < component_count; j++) {
  527. dst[write_offset + j] = data[i * component_count + j];
  528. }
  529. }
  530. }
  531. return dst_buffer;
  532. }
  533. PoolVector<int> EditorSceneImporterGLTF::_decode_accessor_as_ints(GLTFState &state, int p_accessor, bool p_for_vertex) {
  534. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  535. PoolVector<int> ret;
  536. if (attribs.size() == 0)
  537. return ret;
  538. const double *attribs_ptr = attribs.ptr();
  539. int ret_size = attribs.size();
  540. ret.resize(ret_size);
  541. {
  542. PoolVector<int>::Write w = ret.write();
  543. for (int i = 0; i < ret_size; i++) {
  544. w[i] = int(attribs_ptr[i]);
  545. }
  546. }
  547. return ret;
  548. }
  549. PoolVector<float> EditorSceneImporterGLTF::_decode_accessor_as_floats(GLTFState &state, int p_accessor, bool p_for_vertex) {
  550. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  551. PoolVector<float> ret;
  552. if (attribs.size() == 0)
  553. return ret;
  554. const double *attribs_ptr = attribs.ptr();
  555. int ret_size = attribs.size();
  556. ret.resize(ret_size);
  557. {
  558. PoolVector<float>::Write w = ret.write();
  559. for (int i = 0; i < ret_size; i++) {
  560. w[i] = float(attribs_ptr[i]);
  561. }
  562. }
  563. return ret;
  564. }
  565. PoolVector<Vector2> EditorSceneImporterGLTF::_decode_accessor_as_vec2(GLTFState &state, int p_accessor, bool p_for_vertex) {
  566. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  567. PoolVector<Vector2> ret;
  568. if (attribs.size() == 0)
  569. return ret;
  570. ERR_FAIL_COND_V(attribs.size() % 2 != 0, ret);
  571. const double *attribs_ptr = attribs.ptr();
  572. int ret_size = attribs.size() / 2;
  573. ret.resize(ret_size);
  574. {
  575. PoolVector<Vector2>::Write w = ret.write();
  576. for (int i = 0; i < ret_size; i++) {
  577. w[i] = Vector2(attribs_ptr[i * 2 + 0], attribs_ptr[i * 2 + 1]);
  578. }
  579. }
  580. return ret;
  581. }
  582. PoolVector<Vector3> EditorSceneImporterGLTF::_decode_accessor_as_vec3(GLTFState &state, int p_accessor, bool p_for_vertex) {
  583. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  584. PoolVector<Vector3> ret;
  585. if (attribs.size() == 0)
  586. return ret;
  587. ERR_FAIL_COND_V(attribs.size() % 3 != 0, ret);
  588. const double *attribs_ptr = attribs.ptr();
  589. int ret_size = attribs.size() / 3;
  590. ret.resize(ret_size);
  591. {
  592. PoolVector<Vector3>::Write w = ret.write();
  593. for (int i = 0; i < ret_size; i++) {
  594. w[i] = Vector3(attribs_ptr[i * 3 + 0], attribs_ptr[i * 3 + 1], attribs_ptr[i * 3 + 2]);
  595. }
  596. }
  597. return ret;
  598. }
  599. PoolVector<Color> EditorSceneImporterGLTF::_decode_accessor_as_color(GLTFState &state, int p_accessor, bool p_for_vertex) {
  600. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  601. PoolVector<Color> ret;
  602. if (attribs.size() == 0)
  603. return ret;
  604. int type = state.accessors[p_accessor].type;
  605. ERR_FAIL_COND_V(!(type == TYPE_VEC3 || type == TYPE_VEC4), ret);
  606. int components;
  607. if (type == TYPE_VEC3) {
  608. components = 3;
  609. } else { // TYPE_VEC4
  610. components = 4;
  611. }
  612. ERR_FAIL_COND_V(attribs.size() % components != 0, ret);
  613. const double *attribs_ptr = attribs.ptr();
  614. int ret_size = attribs.size() / components;
  615. ret.resize(ret_size);
  616. {
  617. PoolVector<Color>::Write w = ret.write();
  618. for (int i = 0; i < ret_size; i++) {
  619. w[i] = Color(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], components == 4 ? attribs_ptr[i * 4 + 3] : 1.0);
  620. }
  621. }
  622. return ret;
  623. }
  624. Vector<Quat> EditorSceneImporterGLTF::_decode_accessor_as_quat(GLTFState &state, int p_accessor, bool p_for_vertex) {
  625. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  626. Vector<Quat> ret;
  627. if (attribs.size() == 0)
  628. return ret;
  629. ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
  630. const double *attribs_ptr = attribs.ptr();
  631. int ret_size = attribs.size() / 4;
  632. ret.resize(ret_size);
  633. {
  634. for (int i = 0; i < ret_size; i++) {
  635. ret.write[i] = Quat(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], attribs_ptr[i * 4 + 3]).normalized();
  636. }
  637. }
  638. return ret;
  639. }
  640. Vector<Transform2D> EditorSceneImporterGLTF::_decode_accessor_as_xform2d(GLTFState &state, int p_accessor, bool p_for_vertex) {
  641. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  642. Vector<Transform2D> ret;
  643. if (attribs.size() == 0)
  644. return ret;
  645. ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
  646. ret.resize(attribs.size() / 4);
  647. for (int i = 0; i < ret.size(); i++) {
  648. ret.write[i][0] = Vector2(attribs[i * 4 + 0], attribs[i * 4 + 1]);
  649. ret.write[i][1] = Vector2(attribs[i * 4 + 2], attribs[i * 4 + 3]);
  650. }
  651. return ret;
  652. }
  653. Vector<Basis> EditorSceneImporterGLTF::_decode_accessor_as_basis(GLTFState &state, int p_accessor, bool p_for_vertex) {
  654. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  655. Vector<Basis> ret;
  656. if (attribs.size() == 0)
  657. return ret;
  658. ERR_FAIL_COND_V(attribs.size() % 9 != 0, ret);
  659. ret.resize(attribs.size() / 9);
  660. for (int i = 0; i < ret.size(); i++) {
  661. ret.write[i].set_axis(0, Vector3(attribs[i * 9 + 0], attribs[i * 9 + 1], attribs[i * 9 + 2]));
  662. ret.write[i].set_axis(1, Vector3(attribs[i * 9 + 3], attribs[i * 9 + 4], attribs[i * 9 + 5]));
  663. ret.write[i].set_axis(2, Vector3(attribs[i * 9 + 6], attribs[i * 9 + 7], attribs[i * 9 + 8]));
  664. }
  665. return ret;
  666. }
  667. Vector<Transform> EditorSceneImporterGLTF::_decode_accessor_as_xform(GLTFState &state, int p_accessor, bool p_for_vertex) {
  668. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  669. Vector<Transform> ret;
  670. if (attribs.size() == 0)
  671. return ret;
  672. ERR_FAIL_COND_V(attribs.size() % 16 != 0, ret);
  673. ret.resize(attribs.size() / 16);
  674. for (int i = 0; i < ret.size(); i++) {
  675. ret.write[i].basis.set_axis(0, Vector3(attribs[i * 16 + 0], attribs[i * 16 + 1], attribs[i * 16 + 2]));
  676. ret.write[i].basis.set_axis(1, Vector3(attribs[i * 16 + 4], attribs[i * 16 + 5], attribs[i * 16 + 6]));
  677. ret.write[i].basis.set_axis(2, Vector3(attribs[i * 16 + 8], attribs[i * 16 + 9], attribs[i * 16 + 10]));
  678. ret.write[i].set_origin(Vector3(attribs[i * 16 + 12], attribs[i * 16 + 13], attribs[i * 16 + 14]));
  679. }
  680. return ret;
  681. }
  682. Error EditorSceneImporterGLTF::_parse_meshes(GLTFState &state) {
  683. if (!state.json.has("meshes"))
  684. return OK;
  685. Array meshes = state.json["meshes"];
  686. for (int i = 0; i < meshes.size(); i++) {
  687. print_verbose("glTF: Parsing mesh: " + itos(i));
  688. Dictionary d = meshes[i];
  689. GLTFMesh mesh;
  690. mesh.mesh.instance();
  691. ERR_FAIL_COND_V(!d.has("primitives"), ERR_PARSE_ERROR);
  692. Array primitives = d["primitives"];
  693. Dictionary extras = d.has("extras") ? (Dictionary)d["extras"] : Dictionary();
  694. for (int j = 0; j < primitives.size(); j++) {
  695. Dictionary p = primitives[j];
  696. Array array;
  697. array.resize(Mesh::ARRAY_MAX);
  698. ERR_FAIL_COND_V(!p.has("attributes"), ERR_PARSE_ERROR);
  699. Dictionary a = p["attributes"];
  700. Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
  701. if (p.has("mode")) {
  702. int mode = p["mode"];
  703. ERR_FAIL_INDEX_V(mode, 7, ERR_FILE_CORRUPT);
  704. static const Mesh::PrimitiveType primitives2[7] = {
  705. Mesh::PRIMITIVE_POINTS,
  706. Mesh::PRIMITIVE_LINES,
  707. Mesh::PRIMITIVE_LINE_LOOP,
  708. Mesh::PRIMITIVE_LINE_STRIP,
  709. Mesh::PRIMITIVE_TRIANGLES,
  710. Mesh::PRIMITIVE_TRIANGLE_STRIP,
  711. Mesh::PRIMITIVE_TRIANGLE_FAN,
  712. };
  713. primitive = primitives2[mode];
  714. }
  715. ERR_FAIL_COND_V(!a.has("POSITION"), ERR_PARSE_ERROR);
  716. if (a.has("POSITION")) {
  717. array[Mesh::ARRAY_VERTEX] = _decode_accessor_as_vec3(state, a["POSITION"], true);
  718. }
  719. if (a.has("NORMAL")) {
  720. array[Mesh::ARRAY_NORMAL] = _decode_accessor_as_vec3(state, a["NORMAL"], true);
  721. }
  722. if (a.has("TANGENT")) {
  723. array[Mesh::ARRAY_TANGENT] = _decode_accessor_as_floats(state, a["TANGENT"], true);
  724. }
  725. if (a.has("TEXCOORD_0")) {
  726. array[Mesh::ARRAY_TEX_UV] = _decode_accessor_as_vec2(state, a["TEXCOORD_0"], true);
  727. }
  728. if (a.has("TEXCOORD_1")) {
  729. array[Mesh::ARRAY_TEX_UV2] = _decode_accessor_as_vec2(state, a["TEXCOORD_1"], true);
  730. }
  731. if (a.has("COLOR_0")) {
  732. array[Mesh::ARRAY_COLOR] = _decode_accessor_as_color(state, a["COLOR_0"], true);
  733. }
  734. if (a.has("JOINTS_0")) {
  735. array[Mesh::ARRAY_BONES] = _decode_accessor_as_ints(state, a["JOINTS_0"], true);
  736. }
  737. if (a.has("WEIGHTS_0")) {
  738. PoolVector<float> weights = _decode_accessor_as_floats(state, a["WEIGHTS_0"], true);
  739. { //gltf does not seem to normalize the weights for some reason..
  740. int wc = weights.size();
  741. PoolVector<float>::Write w = weights.write();
  742. //PoolVector<int> v = array[Mesh::ARRAY_BONES];
  743. //PoolVector<int>::Read r = v.read();
  744. for (int k = 0; k < wc; k += 4) {
  745. float total = 0.0;
  746. total += w[k + 0];
  747. total += w[k + 1];
  748. total += w[k + 2];
  749. total += w[k + 3];
  750. if (total > 0.0) {
  751. w[k + 0] /= total;
  752. w[k + 1] /= total;
  753. w[k + 2] /= total;
  754. w[k + 3] /= total;
  755. }
  756. //print_verbose(itos(j / 4) + ": " + itos(r[j + 0]) + ":" + rtos(w[j + 0]) + ", " + itos(r[j + 1]) + ":" + rtos(w[j + 1]) + ", " + itos(r[j + 2]) + ":" + rtos(w[j + 2]) + ", " + itos(r[j + 3]) + ":" + rtos(w[j + 3]));
  757. }
  758. }
  759. array[Mesh::ARRAY_WEIGHTS] = weights;
  760. }
  761. if (p.has("indices")) {
  762. PoolVector<int> indices = _decode_accessor_as_ints(state, p["indices"], false);
  763. if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  764. //swap around indices, convert ccw to cw for front face
  765. int is = indices.size();
  766. PoolVector<int>::Write w = indices.write();
  767. for (int k = 0; k < is; k += 3) {
  768. SWAP(w[k + 1], w[k + 2]);
  769. }
  770. }
  771. array[Mesh::ARRAY_INDEX] = indices;
  772. } else if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  773. //generate indices because they need to be swapped for CW/CCW
  774. PoolVector<Vector3> vertices = array[Mesh::ARRAY_VERTEX];
  775. ERR_FAIL_COND_V(vertices.size() == 0, ERR_PARSE_ERROR);
  776. PoolVector<int> indices;
  777. int vs = vertices.size();
  778. indices.resize(vs);
  779. {
  780. PoolVector<int>::Write w = indices.write();
  781. for (int k = 0; k < vs; k += 3) {
  782. w[k] = k;
  783. w[k + 1] = k + 2;
  784. w[k + 2] = k + 1;
  785. }
  786. }
  787. array[Mesh::ARRAY_INDEX] = indices;
  788. }
  789. bool generated_tangents = false;
  790. Variant erased_indices;
  791. if (primitive == Mesh::PRIMITIVE_TRIANGLES && !a.has("TANGENT") && a.has("TEXCOORD_0") && a.has("NORMAL")) {
  792. //must generate mikktspace tangents.. ergh..
  793. Ref<SurfaceTool> st;
  794. st.instance();
  795. st->create_from_triangle_arrays(array);
  796. if (p.has("targets")) {
  797. //morph targets should not be reindexed, as array size might differ
  798. //removing indices is the best bet here
  799. st->deindex();
  800. erased_indices = a[Mesh::ARRAY_INDEX];
  801. a[Mesh::ARRAY_INDEX] = Variant();
  802. }
  803. st->generate_tangents();
  804. array = st->commit_to_arrays();
  805. generated_tangents = true;
  806. }
  807. Array morphs;
  808. //blend shapes
  809. if (p.has("targets")) {
  810. print_verbose("glTF: Mesh has targets");
  811. Array targets = p["targets"];
  812. //ideally BLEND_SHAPE_MODE_RELATIVE since gltf2 stores in displacement
  813. //but it could require a larger refactor?
  814. mesh.mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  815. if (j == 0) {
  816. Array target_names = extras.has("targetNames") ? (Array)extras["targetNames"] : Array();
  817. for (int k = 0; k < targets.size(); k++) {
  818. String name = k < target_names.size() ? (String)target_names[k] : String("morph_") + itos(k);
  819. mesh.mesh->add_blend_shape(name);
  820. }
  821. }
  822. for (int k = 0; k < targets.size(); k++) {
  823. Dictionary t = targets[k];
  824. Array array_copy;
  825. array_copy.resize(Mesh::ARRAY_MAX);
  826. for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
  827. array_copy[l] = array[l];
  828. }
  829. array_copy[Mesh::ARRAY_INDEX] = Variant();
  830. if (t.has("POSITION")) {
  831. PoolVector<Vector3> varr = _decode_accessor_as_vec3(state, t["POSITION"], true);
  832. PoolVector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
  833. int size = src_varr.size();
  834. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  835. {
  836. int max_idx = varr.size();
  837. varr.resize(size);
  838. PoolVector<Vector3>::Write w_varr = varr.write();
  839. PoolVector<Vector3>::Read r_varr = varr.read();
  840. PoolVector<Vector3>::Read r_src_varr = src_varr.read();
  841. for (int l = 0; l < size; l++) {
  842. if (l < max_idx) {
  843. w_varr[l] = r_varr[l] + r_src_varr[l];
  844. } else {
  845. w_varr[l] = r_src_varr[l];
  846. }
  847. }
  848. }
  849. array_copy[Mesh::ARRAY_VERTEX] = varr;
  850. }
  851. if (t.has("NORMAL")) {
  852. PoolVector<Vector3> narr = _decode_accessor_as_vec3(state, t["NORMAL"], true);
  853. PoolVector<Vector3> src_narr = array[Mesh::ARRAY_NORMAL];
  854. int size = src_narr.size();
  855. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  856. {
  857. int max_idx = narr.size();
  858. narr.resize(size);
  859. PoolVector<Vector3>::Write w_narr = narr.write();
  860. PoolVector<Vector3>::Read r_narr = narr.read();
  861. PoolVector<Vector3>::Read r_src_narr = src_narr.read();
  862. for (int l = 0; l < size; l++) {
  863. if (l < max_idx) {
  864. w_narr[l] = r_narr[l] + r_src_narr[l];
  865. } else {
  866. w_narr[l] = r_src_narr[l];
  867. }
  868. }
  869. }
  870. array_copy[Mesh::ARRAY_NORMAL] = narr;
  871. }
  872. if (t.has("TANGENT")) {
  873. PoolVector<Vector3> tangents_v3 = _decode_accessor_as_vec3(state, t["TANGENT"], true);
  874. PoolVector<float> tangents_v4;
  875. PoolVector<float> src_tangents = array[Mesh::ARRAY_TANGENT];
  876. ERR_FAIL_COND_V(src_tangents.size() == 0, ERR_PARSE_ERROR);
  877. {
  878. int max_idx = tangents_v3.size();
  879. int size4 = src_tangents.size();
  880. tangents_v4.resize(size4);
  881. PoolVector<float>::Write w4 = tangents_v4.write();
  882. PoolVector<Vector3>::Read r3 = tangents_v3.read();
  883. PoolVector<float>::Read r4 = src_tangents.read();
  884. for (int l = 0; l < size4 / 4; l++) {
  885. if (l < max_idx) {
  886. w4[l * 4 + 0] = r3[l].x + r4[l * 4 + 0];
  887. w4[l * 4 + 1] = r3[l].y + r4[l * 4 + 1];
  888. w4[l * 4 + 2] = r3[l].z + r4[l * 4 + 2];
  889. } else {
  890. w4[l * 4 + 0] = r4[l * 4 + 0];
  891. w4[l * 4 + 1] = r4[l * 4 + 1];
  892. w4[l * 4 + 2] = r4[l * 4 + 2];
  893. }
  894. w4[l * 4 + 3] = r4[l * 4 + 3]; //copy flip value
  895. }
  896. }
  897. array_copy[Mesh::ARRAY_TANGENT] = tangents_v4;
  898. }
  899. if (generated_tangents) {
  900. Ref<SurfaceTool> st;
  901. st.instance();
  902. array_copy[Mesh::ARRAY_INDEX] = erased_indices; //needed for tangent generation, erased by deindex
  903. st->create_from_triangle_arrays(array_copy);
  904. st->deindex();
  905. st->generate_tangents();
  906. array_copy = st->commit_to_arrays();
  907. }
  908. morphs.push_back(array_copy);
  909. }
  910. }
  911. //just add it
  912. mesh.mesh->add_surface_from_arrays(primitive, array, morphs);
  913. if (p.has("material")) {
  914. int material = p["material"];
  915. ERR_FAIL_INDEX_V(material, state.materials.size(), ERR_FILE_CORRUPT);
  916. Ref<Material> mat = state.materials[material];
  917. mesh.mesh->surface_set_material(mesh.mesh->get_surface_count() - 1, mat);
  918. }
  919. }
  920. if (d.has("weights")) {
  921. Array weights = d["weights"];
  922. ERR_FAIL_COND_V(mesh.mesh->get_blend_shape_count() != weights.size(), ERR_PARSE_ERROR);
  923. mesh.blend_weights.resize(weights.size());
  924. for (int j = 0; j < weights.size(); j++) {
  925. mesh.blend_weights.write[j] = weights[j];
  926. }
  927. }
  928. state.meshes.push_back(mesh);
  929. }
  930. print_verbose("glTF: Total meshes: " + itos(state.meshes.size()));
  931. return OK;
  932. }
  933. Error EditorSceneImporterGLTF::_parse_images(GLTFState &state, const String &p_base_path) {
  934. if (!state.json.has("images"))
  935. return OK;
  936. Array images = state.json["images"];
  937. for (int i = 0; i < images.size(); i++) {
  938. Dictionary d = images[i];
  939. String mimetype;
  940. if (d.has("mimeType")) {
  941. mimetype = d["mimeType"];
  942. }
  943. Vector<uint8_t> data;
  944. const uint8_t *data_ptr = NULL;
  945. int data_size = 0;
  946. if (d.has("uri")) {
  947. String uri = d["uri"];
  948. if (uri.findn("data:application/octet-stream;base64") == 0 ||
  949. uri.findn("data:" + mimetype + ";base64") == 0) {
  950. //embedded data
  951. data = _parse_base64_uri(uri);
  952. data_ptr = data.ptr();
  953. data_size = data.size();
  954. } else {
  955. uri = p_base_path.plus_file(uri).replace("\\", "/"); //fix for windows
  956. Ref<Texture> texture = ResourceLoader::load(uri);
  957. state.images.push_back(texture);
  958. continue;
  959. }
  960. }
  961. if (d.has("bufferView")) {
  962. int bvi = d["bufferView"];
  963. ERR_FAIL_INDEX_V(bvi, state.buffer_views.size(), ERR_PARAMETER_RANGE_ERROR);
  964. const GLTFBufferView &bv = state.buffer_views[bvi];
  965. int bi = bv.buffer;
  966. ERR_FAIL_INDEX_V(bi, state.buffers.size(), ERR_PARAMETER_RANGE_ERROR);
  967. ERR_FAIL_COND_V(bv.byte_offset + bv.byte_length > state.buffers[bi].size(), ERR_FILE_CORRUPT);
  968. data_ptr = &state.buffers[bi][bv.byte_offset];
  969. data_size = bv.byte_length;
  970. }
  971. ERR_FAIL_COND_V(mimetype == "", ERR_FILE_CORRUPT);
  972. if (mimetype.findn("png") != -1) {
  973. //is a png
  974. Ref<Image> img = Image::_png_mem_loader_func(data_ptr, data_size);
  975. ERR_FAIL_COND_V(img.is_null(), ERR_FILE_CORRUPT);
  976. Ref<ImageTexture> t;
  977. t.instance();
  978. t->create_from_image(img);
  979. state.images.push_back(t);
  980. continue;
  981. }
  982. if (mimetype.findn("jpeg") != -1) {
  983. //is a jpg
  984. Ref<Image> img = Image::_jpg_mem_loader_func(data_ptr, data_size);
  985. ERR_FAIL_COND_V(img.is_null(), ERR_FILE_CORRUPT);
  986. Ref<ImageTexture> t;
  987. t.instance();
  988. t->create_from_image(img);
  989. state.images.push_back(t);
  990. continue;
  991. }
  992. ERR_FAIL_V(ERR_FILE_CORRUPT);
  993. }
  994. print_verbose("Total images: " + itos(state.images.size()));
  995. return OK;
  996. }
  997. Error EditorSceneImporterGLTF::_parse_textures(GLTFState &state) {
  998. if (!state.json.has("textures"))
  999. return OK;
  1000. Array textures = state.json["textures"];
  1001. for (int i = 0; i < textures.size(); i++) {
  1002. Dictionary d = textures[i];
  1003. ERR_FAIL_COND_V(!d.has("source"), ERR_PARSE_ERROR);
  1004. GLTFTexture t;
  1005. t.src_image = d["source"];
  1006. state.textures.push_back(t);
  1007. }
  1008. return OK;
  1009. }
  1010. Ref<Texture> EditorSceneImporterGLTF::_get_texture(GLTFState &state, int p_texture) {
  1011. ERR_FAIL_INDEX_V(p_texture, state.textures.size(), Ref<Texture>());
  1012. int image = state.textures[p_texture].src_image;
  1013. ERR_FAIL_INDEX_V(image, state.images.size(), Ref<Texture>());
  1014. return state.images[image];
  1015. }
  1016. Error EditorSceneImporterGLTF::_parse_materials(GLTFState &state) {
  1017. if (!state.json.has("materials"))
  1018. return OK;
  1019. Array materials = state.json["materials"];
  1020. for (int i = 0; i < materials.size(); i++) {
  1021. Dictionary d = materials[i];
  1022. Ref<SpatialMaterial> material;
  1023. material.instance();
  1024. if (d.has("name")) {
  1025. material->set_name(d["name"]);
  1026. }
  1027. if (d.has("pbrMetallicRoughness")) {
  1028. Dictionary mr = d["pbrMetallicRoughness"];
  1029. if (mr.has("baseColorFactor")) {
  1030. Array arr = mr["baseColorFactor"];
  1031. ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
  1032. Color c = Color(arr[0], arr[1], arr[2], arr[3]).to_srgb();
  1033. material->set_albedo(c);
  1034. }
  1035. if (mr.has("baseColorTexture")) {
  1036. Dictionary bct = mr["baseColorTexture"];
  1037. if (bct.has("index")) {
  1038. material->set_texture(SpatialMaterial::TEXTURE_ALBEDO, _get_texture(state, bct["index"]));
  1039. }
  1040. if (!mr.has("baseColorFactor")) {
  1041. material->set_albedo(Color(1, 1, 1));
  1042. }
  1043. }
  1044. if (mr.has("metallicFactor")) {
  1045. material->set_metallic(mr["metallicFactor"]);
  1046. } else {
  1047. material->set_metallic(1.0);
  1048. }
  1049. if (mr.has("roughnessFactor")) {
  1050. material->set_roughness(mr["roughnessFactor"]);
  1051. } else {
  1052. material->set_roughness(1.0);
  1053. }
  1054. if (mr.has("metallicRoughnessTexture")) {
  1055. Dictionary bct = mr["metallicRoughnessTexture"];
  1056. if (bct.has("index")) {
  1057. Ref<Texture> t = _get_texture(state, bct["index"]);
  1058. material->set_texture(SpatialMaterial::TEXTURE_METALLIC, t);
  1059. material->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_BLUE);
  1060. material->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, t);
  1061. material->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GREEN);
  1062. if (!mr.has("metallicFactor")) {
  1063. material->set_metallic(1);
  1064. }
  1065. if (!mr.has("roughnessFactor")) {
  1066. material->set_roughness(1);
  1067. }
  1068. }
  1069. }
  1070. }
  1071. if (d.has("normalTexture")) {
  1072. Dictionary bct = d["normalTexture"];
  1073. if (bct.has("index")) {
  1074. material->set_texture(SpatialMaterial::TEXTURE_NORMAL, _get_texture(state, bct["index"]));
  1075. material->set_feature(SpatialMaterial::FEATURE_NORMAL_MAPPING, true);
  1076. }
  1077. if (bct.has("scale")) {
  1078. material->set_normal_scale(bct["scale"]);
  1079. }
  1080. }
  1081. if (d.has("occlusionTexture")) {
  1082. Dictionary bct = d["occlusionTexture"];
  1083. if (bct.has("index")) {
  1084. material->set_texture(SpatialMaterial::TEXTURE_AMBIENT_OCCLUSION, _get_texture(state, bct["index"]));
  1085. material->set_ao_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_RED);
  1086. material->set_feature(SpatialMaterial::FEATURE_AMBIENT_OCCLUSION, true);
  1087. }
  1088. }
  1089. if (d.has("emissiveFactor")) {
  1090. Array arr = d["emissiveFactor"];
  1091. ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
  1092. Color c = Color(arr[0], arr[1], arr[2]).to_srgb();
  1093. material->set_feature(SpatialMaterial::FEATURE_EMISSION, true);
  1094. material->set_emission(c);
  1095. }
  1096. if (d.has("emissiveTexture")) {
  1097. Dictionary bct = d["emissiveTexture"];
  1098. if (bct.has("index")) {
  1099. material->set_texture(SpatialMaterial::TEXTURE_EMISSION, _get_texture(state, bct["index"]));
  1100. material->set_feature(SpatialMaterial::FEATURE_EMISSION, true);
  1101. material->set_emission(Color(0, 0, 0));
  1102. }
  1103. }
  1104. if (d.has("doubleSided")) {
  1105. bool ds = d["doubleSided"];
  1106. if (ds) {
  1107. material->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  1108. }
  1109. }
  1110. if (d.has("alphaMode")) {
  1111. String am = d["alphaMode"];
  1112. if (am != "OPAQUE") {
  1113. material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  1114. }
  1115. }
  1116. state.materials.push_back(material);
  1117. }
  1118. print_verbose("Total materials: " + itos(state.materials.size()));
  1119. return OK;
  1120. }
  1121. Error EditorSceneImporterGLTF::_parse_skins(GLTFState &state) {
  1122. if (!state.json.has("skins"))
  1123. return OK;
  1124. Array skins = state.json["skins"];
  1125. for (int i = 0; i < skins.size(); i++) {
  1126. Dictionary d = skins[i];
  1127. GLTFSkin skin;
  1128. ERR_FAIL_COND_V(!d.has("joints"), ERR_PARSE_ERROR);
  1129. Array joints = d["joints"];
  1130. Vector<Transform> bind_matrices;
  1131. if (d.has("inverseBindMatrices")) {
  1132. bind_matrices = _decode_accessor_as_xform(state, d["inverseBindMatrices"], false);
  1133. ERR_FAIL_COND_V(bind_matrices.size() != joints.size(), ERR_PARSE_ERROR);
  1134. }
  1135. for (int j = 0; j < joints.size(); j++) {
  1136. int index = joints[j];
  1137. ERR_FAIL_INDEX_V(index, state.nodes.size(), ERR_PARSE_ERROR);
  1138. GLTFNode::Joint joint;
  1139. joint.skin = state.skins.size();
  1140. joint.bone = j;
  1141. state.nodes[index]->joints.push_back(joint);
  1142. GLTFSkin::Bone bone;
  1143. bone.node = index;
  1144. if (bind_matrices.size()) {
  1145. bone.inverse_bind = bind_matrices[j];
  1146. }
  1147. skin.bones.push_back(bone);
  1148. }
  1149. print_verbose("glTF: Skin has skeleton? " + itos(d.has("skeleton")));
  1150. if (d.has("skeleton")) {
  1151. int skeleton = d["skeleton"];
  1152. ERR_FAIL_INDEX_V(skeleton, state.nodes.size(), ERR_PARSE_ERROR);
  1153. print_verbose("glTF: Setting skeleton skin to" + itos(skeleton));
  1154. skin.skeleton = skeleton;
  1155. if (!state.skeleton_nodes.has(skeleton)) {
  1156. state.skeleton_nodes[skeleton] = Vector<int>();
  1157. }
  1158. state.skeleton_nodes[skeleton].push_back(i);
  1159. }
  1160. if (d.has("name")) {
  1161. skin.name = d["name"];
  1162. }
  1163. //locate the right place to put a Skeleton node
  1164. /*
  1165. if (state.skin_users.has(i)) {
  1166. Vector<int> users = state.skin_users[i];
  1167. int skin_node = -1;
  1168. for (int j = 0; j < users.size(); j++) {
  1169. int user = state.nodes[users[j]]->parent; //always go from parent
  1170. if (j == 0) {
  1171. skin_node = user;
  1172. } else if (skin_node != -1) {
  1173. bool found = false;
  1174. while (skin_node >= 0) {
  1175. int cuser = user;
  1176. while (cuser != -1) {
  1177. if (cuser == skin_node) {
  1178. found = true;
  1179. break;
  1180. }
  1181. cuser = state.nodes[skin_node]->parent;
  1182. }
  1183. if (found)
  1184. break;
  1185. skin_node = state.nodes[skin_node]->parent;
  1186. }
  1187. if (!found) {
  1188. skin_node = -1; //just leave where it is
  1189. }
  1190. //find a common parent
  1191. }
  1192. }
  1193. if (skin_node != -1) {
  1194. for (int j = 0; j < users.size(); j++) {
  1195. state.nodes[users[j]]->child_of_skeleton = i;
  1196. }
  1197. state.nodes[skin_node]->skeleton_children.push_back(i);
  1198. }
  1199. }
  1200. */
  1201. state.skins.push_back(skin);
  1202. }
  1203. print_verbose("glTF: Total skins: " + itos(state.skins.size()));
  1204. //now
  1205. return OK;
  1206. }
  1207. Error EditorSceneImporterGLTF::_parse_cameras(GLTFState &state) {
  1208. if (!state.json.has("cameras"))
  1209. return OK;
  1210. Array cameras = state.json["cameras"];
  1211. for (int i = 0; i < cameras.size(); i++) {
  1212. Dictionary d = cameras[i];
  1213. GLTFCamera camera;
  1214. ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
  1215. String type = d["type"];
  1216. if (type == "orthographic") {
  1217. camera.perspective = false;
  1218. if (d.has("orthographic")) {
  1219. Dictionary og = d["orthographic"];
  1220. camera.fov_size = og["ymag"];
  1221. camera.zfar = og["zfar"];
  1222. camera.znear = og["znear"];
  1223. } else {
  1224. camera.fov_size = 10;
  1225. }
  1226. } else if (type == "perspective") {
  1227. camera.perspective = true;
  1228. if (d.has("perspective")) {
  1229. Dictionary ppt = d["perspective"];
  1230. // GLTF spec is in radians, Godot's camera is in degrees.
  1231. camera.fov_size = (double)ppt["yfov"] * 180.0 / Math_PI;
  1232. camera.zfar = ppt["zfar"];
  1233. camera.znear = ppt["znear"];
  1234. } else {
  1235. camera.fov_size = 10;
  1236. }
  1237. } else {
  1238. ERR_EXPLAIN("Camera should be in 'orthographic' or 'perspective'");
  1239. ERR_FAIL_V(ERR_PARSE_ERROR);
  1240. }
  1241. state.cameras.push_back(camera);
  1242. }
  1243. print_verbose("glTF: Total cameras: " + itos(state.cameras.size()));
  1244. return OK;
  1245. }
  1246. Error EditorSceneImporterGLTF::_parse_animations(GLTFState &state) {
  1247. if (!state.json.has("animations"))
  1248. return OK;
  1249. Array animations = state.json["animations"];
  1250. for (int i = 0; i < animations.size(); i++) {
  1251. Dictionary d = animations[i];
  1252. GLTFAnimation animation;
  1253. if (!d.has("channels") || !d.has("samplers"))
  1254. continue;
  1255. Array channels = d["channels"];
  1256. Array samplers = d["samplers"];
  1257. if (d.has("name")) {
  1258. animation.name = d["name"];
  1259. }
  1260. for (int j = 0; j < channels.size(); j++) {
  1261. Dictionary c = channels[j];
  1262. if (!c.has("target"))
  1263. continue;
  1264. Dictionary t = c["target"];
  1265. if (!t.has("node") || !t.has("path")) {
  1266. continue;
  1267. }
  1268. ERR_FAIL_COND_V(!c.has("sampler"), ERR_PARSE_ERROR);
  1269. int sampler = c["sampler"];
  1270. ERR_FAIL_INDEX_V(sampler, samplers.size(), ERR_PARSE_ERROR);
  1271. int node = t["node"];
  1272. String path = t["path"];
  1273. ERR_FAIL_INDEX_V(node, state.nodes.size(), ERR_PARSE_ERROR);
  1274. GLTFAnimation::Track *track = NULL;
  1275. if (!animation.tracks.has(node)) {
  1276. animation.tracks[node] = GLTFAnimation::Track();
  1277. }
  1278. track = &animation.tracks[node];
  1279. Dictionary s = samplers[sampler];
  1280. ERR_FAIL_COND_V(!s.has("input"), ERR_PARSE_ERROR);
  1281. ERR_FAIL_COND_V(!s.has("output"), ERR_PARSE_ERROR);
  1282. int input = s["input"];
  1283. int output = s["output"];
  1284. GLTFAnimation::Interpolation interp = GLTFAnimation::INTERP_LINEAR;
  1285. if (s.has("interpolation")) {
  1286. String in = s["interpolation"];
  1287. if (in == "STEP") {
  1288. interp = GLTFAnimation::INTERP_STEP;
  1289. } else if (in == "LINEAR") {
  1290. interp = GLTFAnimation::INTERP_LINEAR;
  1291. } else if (in == "CATMULLROMSPLINE") {
  1292. interp = GLTFAnimation::INTERP_CATMULLROMSPLINE;
  1293. } else if (in == "CUBICSPLINE") {
  1294. interp = GLTFAnimation::INTERP_CUBIC_SPLINE;
  1295. }
  1296. }
  1297. PoolVector<float> times = _decode_accessor_as_floats(state, input, false);
  1298. if (path == "translation") {
  1299. PoolVector<Vector3> translations = _decode_accessor_as_vec3(state, output, false);
  1300. track->translation_track.interpolation = interp;
  1301. track->translation_track.times = Variant(times); //convert via variant
  1302. track->translation_track.values = Variant(translations); //convert via variant
  1303. } else if (path == "rotation") {
  1304. Vector<Quat> rotations = _decode_accessor_as_quat(state, output, false);
  1305. track->rotation_track.interpolation = interp;
  1306. track->rotation_track.times = Variant(times); //convert via variant
  1307. track->rotation_track.values = rotations; //convert via variant
  1308. } else if (path == "scale") {
  1309. PoolVector<Vector3> scales = _decode_accessor_as_vec3(state, output, false);
  1310. track->scale_track.interpolation = interp;
  1311. track->scale_track.times = Variant(times); //convert via variant
  1312. track->scale_track.values = Variant(scales); //convert via variant
  1313. } else if (path == "weights") {
  1314. PoolVector<float> weights = _decode_accessor_as_floats(state, output, false);
  1315. ERR_FAIL_INDEX_V(state.nodes[node]->mesh, state.meshes.size(), ERR_PARSE_ERROR);
  1316. const GLTFMesh *mesh = &state.meshes[state.nodes[node]->mesh];
  1317. ERR_FAIL_COND_V(mesh->blend_weights.size() == 0, ERR_PARSE_ERROR);
  1318. int wc = mesh->blend_weights.size();
  1319. track->weight_tracks.resize(wc);
  1320. int wlen = weights.size() / wc;
  1321. PoolVector<float>::Read r = weights.read();
  1322. for (int k = 0; k < wc; k++) { //separate tracks, having them together is not such a good idea
  1323. GLTFAnimation::Channel<float> cf;
  1324. cf.interpolation = interp;
  1325. cf.times = Variant(times);
  1326. Vector<float> wdata;
  1327. wdata.resize(wlen);
  1328. for (int l = 0; l < wlen; l++) {
  1329. wdata.write[l] = r[l * wc + k];
  1330. }
  1331. cf.values = wdata;
  1332. track->weight_tracks.write[k] = cf;
  1333. }
  1334. } else {
  1335. WARN_PRINTS("Invalid path: " + path);
  1336. }
  1337. }
  1338. state.animations.push_back(animation);
  1339. }
  1340. print_verbose("glTF: Total animations: " + itos(state.animations.size()));
  1341. return OK;
  1342. }
  1343. void EditorSceneImporterGLTF::_assign_scene_names(GLTFState &state) {
  1344. for (int i = 0; i < state.nodes.size(); i++) {
  1345. GLTFNode *n = state.nodes[i];
  1346. if (n->name == "") {
  1347. if (n->mesh >= 0) {
  1348. n->name = "Mesh";
  1349. } else if (n->joints.size()) {
  1350. n->name = "Bone";
  1351. } else {
  1352. n->name = "Node";
  1353. }
  1354. }
  1355. n->name = _gen_unique_name(state, n->name);
  1356. }
  1357. }
  1358. void EditorSceneImporterGLTF::_reparent_skeleton(GLTFState &state, int p_node, Vector<Skeleton *> &skeletons, Node *p_parent_node) {
  1359. //reparent skeletons to proper place
  1360. Vector<int> nodes = state.skeleton_nodes[p_node];
  1361. for (int i = 0; i < nodes.size(); i++) {
  1362. Skeleton *skeleton = skeletons[nodes[i]];
  1363. Node *owner = skeleton->get_owner();
  1364. skeleton->get_parent()->remove_child(skeleton);
  1365. p_parent_node->add_child(skeleton);
  1366. skeleton->set_owner(owner);
  1367. //may have meshes as children, set owner in them too
  1368. for (int j = 0; j < skeleton->get_child_count(); j++) {
  1369. skeleton->get_child(j)->set_owner(owner);
  1370. }
  1371. }
  1372. }
  1373. void EditorSceneImporterGLTF::_generate_node(GLTFState &state, int p_node, Node *p_parent, Node *p_owner, Vector<Skeleton *> &skeletons) {
  1374. ERR_FAIL_INDEX(p_node, state.nodes.size());
  1375. GLTFNode *n = state.nodes[p_node];
  1376. Spatial *node;
  1377. if (n->mesh >= 0) {
  1378. ERR_FAIL_INDEX(n->mesh, state.meshes.size());
  1379. MeshInstance *mi = memnew(MeshInstance);
  1380. print_verbose("glTF: Creating mesh for: " + n->name);
  1381. GLTFMesh &mesh = state.meshes.write[n->mesh];
  1382. mi->set_mesh(mesh.mesh);
  1383. if (mesh.mesh->get_name() == "") {
  1384. mesh.mesh->set_name(n->name);
  1385. }
  1386. for (int i = 0; i < mesh.blend_weights.size(); i++) {
  1387. mi->set("blend_shapes/" + mesh.mesh->get_blend_shape_name(i), mesh.blend_weights[i]);
  1388. }
  1389. node = mi;
  1390. } else if (n->camera >= 0) {
  1391. ERR_FAIL_INDEX(n->camera, state.cameras.size());
  1392. Camera *camera = memnew(Camera);
  1393. const GLTFCamera &c = state.cameras[n->camera];
  1394. if (c.perspective) {
  1395. camera->set_perspective(c.fov_size, c.znear, c.znear);
  1396. } else {
  1397. camera->set_orthogonal(c.fov_size, c.znear, c.znear);
  1398. }
  1399. node = camera;
  1400. } else {
  1401. node = memnew(Spatial);
  1402. }
  1403. node->set_name(n->name);
  1404. n->godot_nodes.push_back(node);
  1405. if (n->skin >= 0 && n->skin < skeletons.size() && Object::cast_to<MeshInstance>(node)) {
  1406. MeshInstance *mi = Object::cast_to<MeshInstance>(node);
  1407. Skeleton *s = skeletons[n->skin];
  1408. s->add_child(node); //According to spec, mesh should actually act as a child of the skeleton, as it inherits its transform
  1409. mi->set_skeleton_path(String(".."));
  1410. } else {
  1411. p_parent->add_child(node);
  1412. node->set_transform(n->xform);
  1413. }
  1414. node->set_owner(p_owner);
  1415. #if 0
  1416. for (int i = 0; i < n->skeleton_children.size(); i++) {
  1417. Skeleton *s = skeletons[n->skeleton_children[i]];
  1418. s->get_parent()->remove_child(s);
  1419. node->add_child(s);
  1420. s->set_owner(p_owner);
  1421. }
  1422. #endif
  1423. for (int i = 0; i < n->children.size(); i++) {
  1424. if (state.nodes[n->children[i]]->joints.size()) {
  1425. _generate_bone(state, n->children[i], skeletons, node);
  1426. } else {
  1427. _generate_node(state, n->children[i], node, p_owner, skeletons);
  1428. }
  1429. }
  1430. if (state.skeleton_nodes.has(p_node)) {
  1431. _reparent_skeleton(state, p_node, skeletons, node);
  1432. }
  1433. }
  1434. void EditorSceneImporterGLTF::_generate_bone(GLTFState &state, int p_node, Vector<Skeleton *> &skeletons, Node *p_parent_node) {
  1435. ERR_FAIL_INDEX(p_node, state.nodes.size());
  1436. if (state.skeleton_nodes.has(p_node)) {
  1437. _reparent_skeleton(state, p_node, skeletons, p_parent_node);
  1438. }
  1439. GLTFNode *n = state.nodes[p_node];
  1440. for (int i = 0; i < n->joints.size(); i++) {
  1441. const int skin = n->joints[i].skin;
  1442. ERR_FAIL_COND(skin < 0);
  1443. Skeleton *s = skeletons[skin];
  1444. const GLTFNode *gltf_bone_node = state.nodes[state.skins[skin].bones[n->joints[i].bone].node];
  1445. const String bone_name = gltf_bone_node->name;
  1446. const int parent = gltf_bone_node->parent;
  1447. const int parent_index = s->find_bone(state.nodes[parent]->name);
  1448. const int bone_index = s->find_bone(bone_name);
  1449. s->set_bone_parent(bone_index, parent_index);
  1450. n->godot_nodes.push_back(s);
  1451. n->joints.write[i].godot_bone_index = bone_index;
  1452. }
  1453. for (int i = 0; i < n->children.size(); i++) {
  1454. _generate_bone(state, n->children[i], skeletons, p_parent_node);
  1455. }
  1456. }
  1457. template <class T>
  1458. struct EditorSceneImporterGLTFInterpolate {
  1459. T lerp(const T &a, const T &b, float c) const {
  1460. return a + (b - a) * c;
  1461. }
  1462. T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
  1463. float t2 = t * t;
  1464. float t3 = t2 * t;
  1465. return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
  1466. }
  1467. T bezier(T start, T control_1, T control_2, T end, float t) {
  1468. /* Formula from Wikipedia article on Bezier curves. */
  1469. real_t omt = (1.0 - t);
  1470. real_t omt2 = omt * omt;
  1471. real_t omt3 = omt2 * omt;
  1472. real_t t2 = t * t;
  1473. real_t t3 = t2 * t;
  1474. return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
  1475. }
  1476. };
  1477. //thank you for existing, partial specialization
  1478. template <>
  1479. struct EditorSceneImporterGLTFInterpolate<Quat> {
  1480. Quat lerp(const Quat &a, const Quat &b, float c) const {
  1481. ERR_FAIL_COND_V(!a.is_normalized(), Quat());
  1482. ERR_FAIL_COND_V(!b.is_normalized(), Quat());
  1483. return a.slerp(b, c).normalized();
  1484. }
  1485. Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, float c) {
  1486. ERR_FAIL_COND_V(!p1.is_normalized(), Quat());
  1487. ERR_FAIL_COND_V(!p2.is_normalized(), Quat());
  1488. return p1.slerp(p2, c).normalized();
  1489. }
  1490. Quat bezier(Quat start, Quat control_1, Quat control_2, Quat end, float t) {
  1491. ERR_FAIL_COND_V(!start.is_normalized(), Quat());
  1492. ERR_FAIL_COND_V(!end.is_normalized(), Quat());
  1493. return start.slerp(end, t).normalized();
  1494. }
  1495. };
  1496. template <class T>
  1497. T EditorSceneImporterGLTF::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time, GLTFAnimation::Interpolation p_interp) {
  1498. //could use binary search, worth it?
  1499. int idx = -1;
  1500. for (int i = 0; i < p_times.size(); i++) {
  1501. if (p_times[i] > p_time)
  1502. break;
  1503. idx++;
  1504. }
  1505. EditorSceneImporterGLTFInterpolate<T> interp;
  1506. switch (p_interp) {
  1507. case GLTFAnimation::INTERP_LINEAR: {
  1508. if (idx == -1) {
  1509. return p_values[0];
  1510. } else if (idx >= p_times.size() - 1) {
  1511. return p_values[p_times.size() - 1];
  1512. }
  1513. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  1514. return interp.lerp(p_values[idx], p_values[idx + 1], c);
  1515. } break;
  1516. case GLTFAnimation::INTERP_STEP: {
  1517. if (idx == -1) {
  1518. return p_values[0];
  1519. } else if (idx >= p_times.size() - 1) {
  1520. return p_values[p_times.size() - 1];
  1521. }
  1522. return p_values[idx];
  1523. } break;
  1524. case GLTFAnimation::INTERP_CATMULLROMSPLINE: {
  1525. if (idx == -1) {
  1526. return p_values[1];
  1527. } else if (idx >= p_times.size() - 1) {
  1528. return p_values[1 + p_times.size() - 1];
  1529. }
  1530. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  1531. return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
  1532. } break;
  1533. case GLTFAnimation::INTERP_CUBIC_SPLINE: {
  1534. if (idx == -1) {
  1535. return p_values[1];
  1536. } else if (idx >= p_times.size() - 1) {
  1537. return p_values[(p_times.size() - 1) * 3 + 1];
  1538. }
  1539. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  1540. T from = p_values[idx * 3 + 1];
  1541. T c1 = from + p_values[idx * 3 + 2];
  1542. T to = p_values[idx * 3 + 4];
  1543. T c2 = to + p_values[idx * 3 + 3];
  1544. return interp.bezier(from, c1, c2, to, c);
  1545. } break;
  1546. }
  1547. ERR_FAIL_V(p_values[0]);
  1548. }
  1549. void EditorSceneImporterGLTF::_import_animation(GLTFState &state, AnimationPlayer *ap, int index, int bake_fps, Vector<Skeleton *> skeletons) {
  1550. const GLTFAnimation &anim = state.animations[index];
  1551. String name = anim.name;
  1552. if (name == "") {
  1553. name = _gen_unique_name(state, "Animation");
  1554. }
  1555. Ref<Animation> animation;
  1556. animation.instance();
  1557. animation->set_name(name);
  1558. float length = 0;
  1559. for (Map<int, GLTFAnimation::Track>::Element *E = anim.tracks.front(); E; E = E->next()) {
  1560. const GLTFAnimation::Track &track = E->get();
  1561. //need to find the path
  1562. NodePath node_path;
  1563. GLTFNode *node = state.nodes[E->key()];
  1564. for (int n = 0; n < node->godot_nodes.size(); n++) {
  1565. if (node->joints.size()) {
  1566. Skeleton *sk = (Skeleton *)node->godot_nodes[n];
  1567. String path = ap->get_parent()->get_path_to(sk);
  1568. String bone = sk->get_bone_name(node->joints[n].godot_bone_index);
  1569. node_path = path + ":" + bone;
  1570. } else {
  1571. node_path = ap->get_parent()->get_path_to(node->godot_nodes[n]);
  1572. }
  1573. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  1574. length = MAX(length, track.rotation_track.times[i]);
  1575. }
  1576. for (int i = 0; i < track.translation_track.times.size(); i++) {
  1577. length = MAX(length, track.translation_track.times[i]);
  1578. }
  1579. for (int i = 0; i < track.scale_track.times.size(); i++) {
  1580. length = MAX(length, track.scale_track.times[i]);
  1581. }
  1582. for (int i = 0; i < track.weight_tracks.size(); i++) {
  1583. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  1584. length = MAX(length, track.weight_tracks[i].times[j]);
  1585. }
  1586. }
  1587. if (track.rotation_track.values.size() || track.translation_track.values.size() || track.scale_track.values.size()) {
  1588. //make transform track
  1589. int track_idx = animation->get_track_count();
  1590. animation->add_track(Animation::TYPE_TRANSFORM);
  1591. animation->track_set_path(track_idx, node_path);
  1592. //first determine animation length
  1593. float increment = 1.0 / float(bake_fps);
  1594. float time = 0.0;
  1595. Vector3 base_pos;
  1596. Quat base_rot;
  1597. Vector3 base_scale = Vector3(1, 1, 1);
  1598. if (!track.rotation_track.values.size()) {
  1599. base_rot = state.nodes[E->key()]->rotation.normalized();
  1600. }
  1601. if (!track.translation_track.values.size()) {
  1602. base_pos = state.nodes[E->key()]->translation;
  1603. }
  1604. if (!track.scale_track.values.size()) {
  1605. base_scale = state.nodes[E->key()]->scale;
  1606. }
  1607. bool last = false;
  1608. while (true) {
  1609. Vector3 pos = base_pos;
  1610. Quat rot = base_rot;
  1611. Vector3 scale = base_scale;
  1612. if (track.translation_track.times.size()) {
  1613. pos = _interpolate_track<Vector3>(track.translation_track.times, track.translation_track.values, time, track.translation_track.interpolation);
  1614. }
  1615. if (track.rotation_track.times.size()) {
  1616. rot = _interpolate_track<Quat>(track.rotation_track.times, track.rotation_track.values, time, track.rotation_track.interpolation);
  1617. }
  1618. if (track.scale_track.times.size()) {
  1619. scale = _interpolate_track<Vector3>(track.scale_track.times, track.scale_track.values, time, track.scale_track.interpolation);
  1620. }
  1621. if (node->joints.size()) {
  1622. Transform xform;
  1623. //xform.basis = Basis(rot);
  1624. //xform.basis.scale(scale);
  1625. xform.basis.set_quat_scale(rot, scale);
  1626. xform.origin = pos;
  1627. Skeleton *skeleton = skeletons[node->joints[n].skin];
  1628. int bone = node->joints[n].godot_bone_index;
  1629. xform = skeleton->get_bone_rest(bone).affine_inverse() * xform;
  1630. rot = xform.basis.get_rotation_quat();
  1631. rot.normalize();
  1632. scale = xform.basis.get_scale();
  1633. pos = xform.origin;
  1634. }
  1635. animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
  1636. if (last) {
  1637. break;
  1638. }
  1639. time += increment;
  1640. if (time >= length) {
  1641. last = true;
  1642. time = length;
  1643. }
  1644. }
  1645. }
  1646. for (int i = 0; i < track.weight_tracks.size(); i++) {
  1647. ERR_CONTINUE(node->mesh < 0 || node->mesh >= state.meshes.size());
  1648. const GLTFMesh &mesh = state.meshes[node->mesh];
  1649. String prop = "blend_shapes/" + mesh.mesh->get_blend_shape_name(i);
  1650. node_path = String(node_path) + ":" + prop;
  1651. int track_idx = animation->get_track_count();
  1652. animation->add_track(Animation::TYPE_VALUE);
  1653. animation->track_set_path(track_idx, node_path);
  1654. if (track.weight_tracks[i].interpolation <= GLTFAnimation::INTERP_STEP) {
  1655. animation->track_set_interpolation_type(track_idx, track.weight_tracks[i].interpolation == GLTFAnimation::INTERP_STEP ? Animation::INTERPOLATION_NEAREST : Animation::INTERPOLATION_NEAREST);
  1656. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  1657. float t = track.weight_tracks[i].times[j];
  1658. float w = track.weight_tracks[i].values[j];
  1659. animation->track_insert_key(track_idx, t, w);
  1660. }
  1661. } else {
  1662. //must bake, apologies.
  1663. float increment = 1.0 / float(bake_fps);
  1664. float time = 0.0;
  1665. bool last = false;
  1666. while (true) {
  1667. _interpolate_track<float>(track.weight_tracks[i].times, track.weight_tracks[i].values, time, track.weight_tracks[i].interpolation);
  1668. if (last) {
  1669. break;
  1670. }
  1671. time += increment;
  1672. if (time >= length) {
  1673. last = true;
  1674. time = length;
  1675. }
  1676. }
  1677. }
  1678. }
  1679. }
  1680. }
  1681. animation->set_length(length);
  1682. ap->add_animation(name, animation);
  1683. }
  1684. Spatial *EditorSceneImporterGLTF::_generate_scene(GLTFState &state, int p_bake_fps) {
  1685. Spatial *root = memnew(Spatial);
  1686. root->set_name(state.scene_name);
  1687. //generate skeletons
  1688. Vector<Skeleton *> skeletons;
  1689. for (int i = 0; i < state.skins.size(); i++) {
  1690. Skeleton *s = memnew(Skeleton);
  1691. s->set_use_bones_in_world_transform(false); //GLTF does not need this since meshes are always local
  1692. String name = state.skins[i].name;
  1693. if (name == "") {
  1694. name = _gen_unique_name(state, "Skeleton");
  1695. }
  1696. for (int j = 0; j < state.skins[i].bones.size(); j++) {
  1697. s->add_bone(state.nodes[state.skins[i].bones[j].node]->name);
  1698. s->set_bone_rest(j, state.skins[i].bones[j].inverse_bind.affine_inverse());
  1699. }
  1700. s->set_name(name);
  1701. root->add_child(s);
  1702. s->set_owner(root);
  1703. skeletons.push_back(s);
  1704. }
  1705. for (int i = 0; i < state.root_nodes.size(); i++) {
  1706. if (state.nodes[state.root_nodes[i]]->joints.size()) {
  1707. _generate_bone(state, state.root_nodes[i], skeletons, root);
  1708. } else {
  1709. _generate_node(state, state.root_nodes[i], root, root, skeletons);
  1710. }
  1711. }
  1712. for (int i = 0; i < skeletons.size(); i++) {
  1713. skeletons[i]->localize_rests();
  1714. }
  1715. if (state.animations.size()) {
  1716. AnimationPlayer *ap = memnew(AnimationPlayer);
  1717. ap->set_name("AnimationPlayer");
  1718. root->add_child(ap);
  1719. ap->set_owner(root);
  1720. for (int i = 0; i < state.animations.size(); i++) {
  1721. _import_animation(state, ap, i, p_bake_fps, skeletons);
  1722. }
  1723. }
  1724. return root;
  1725. }
  1726. Node *EditorSceneImporterGLTF::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err) {
  1727. GLTFState state;
  1728. if (p_path.to_lower().ends_with("glb")) {
  1729. //binary file
  1730. //text file
  1731. Error err = _parse_glb(p_path, state);
  1732. if (err)
  1733. return NULL;
  1734. } else {
  1735. //text file
  1736. Error err = _parse_json(p_path, state);
  1737. if (err)
  1738. return NULL;
  1739. }
  1740. ERR_FAIL_COND_V(!state.json.has("asset"), NULL);
  1741. Dictionary asset = state.json["asset"];
  1742. ERR_FAIL_COND_V(!asset.has("version"), NULL);
  1743. String version = asset["version"];
  1744. state.major_version = version.get_slice(".", 0).to_int();
  1745. state.minor_version = version.get_slice(".", 1).to_int();
  1746. /* STEP 0 PARSE SCENE */
  1747. Error err = _parse_scenes(state);
  1748. if (err != OK)
  1749. return NULL;
  1750. /* STEP 1 PARSE NODES */
  1751. err = _parse_nodes(state);
  1752. if (err != OK)
  1753. return NULL;
  1754. /* STEP 2 PARSE BUFFERS */
  1755. err = _parse_buffers(state, p_path.get_base_dir());
  1756. if (err != OK)
  1757. return NULL;
  1758. /* STEP 3 PARSE BUFFER VIEWS */
  1759. err = _parse_buffer_views(state);
  1760. if (err != OK)
  1761. return NULL;
  1762. /* STEP 4 PARSE ACCESSORS */
  1763. err = _parse_accessors(state);
  1764. if (err != OK)
  1765. return NULL;
  1766. /* STEP 5 PARSE IMAGES */
  1767. err = _parse_images(state, p_path.get_base_dir());
  1768. if (err != OK)
  1769. return NULL;
  1770. /* STEP 6 PARSE TEXTURES */
  1771. err = _parse_textures(state);
  1772. if (err != OK)
  1773. return NULL;
  1774. /* STEP 7 PARSE TEXTURES */
  1775. err = _parse_materials(state);
  1776. if (err != OK)
  1777. return NULL;
  1778. /* STEP 8 PARSE MESHES (we have enough info now) */
  1779. err = _parse_meshes(state);
  1780. if (err != OK)
  1781. return NULL;
  1782. /* STEP 9 PARSE SKINS */
  1783. err = _parse_skins(state);
  1784. if (err != OK)
  1785. return NULL;
  1786. /* STEP 10 PARSE CAMERAS */
  1787. err = _parse_cameras(state);
  1788. if (err != OK)
  1789. return NULL;
  1790. /* STEP 11 PARSE ANIMATIONS */
  1791. err = _parse_animations(state);
  1792. if (err != OK)
  1793. return NULL;
  1794. /* STEP 12 ASSIGN SCENE NAMES */
  1795. _assign_scene_names(state);
  1796. /* STEP 13 MAKE SCENE! */
  1797. Spatial *scene = _generate_scene(state, p_bake_fps);
  1798. return scene;
  1799. }
  1800. Ref<Animation> EditorSceneImporterGLTF::import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  1801. return Ref<Animation>();
  1802. }
  1803. EditorSceneImporterGLTF::EditorSceneImporterGLTF() {
  1804. }