resource_importer_scene.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. /**************************************************************************/
  2. /* resource_importer_scene.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "resource_importer_scene.h"
  31. #include "core/io/resource_saver.h"
  32. #include "editor/editor_node.h"
  33. #include "scene/3d/collision_shape.h"
  34. #include "scene/3d/mesh_instance.h"
  35. #include "scene/3d/navigation.h"
  36. #include "scene/3d/physics_body.h"
  37. #include "scene/3d/vehicle_body.h"
  38. #include "scene/animation/animation_player.h"
  39. #include "scene/resources/animation.h"
  40. #include "scene/resources/box_shape.h"
  41. #include "scene/resources/packed_scene.h"
  42. #include "scene/resources/plane_shape.h"
  43. #include "scene/resources/ray_shape.h"
  44. #include "scene/resources/resource_format_text.h"
  45. #include "scene/resources/sphere_shape.h"
  46. uint32_t EditorSceneImporter::get_import_flags() const {
  47. if (get_script_instance()) {
  48. return get_script_instance()->call("_get_import_flags");
  49. }
  50. ERR_FAIL_V(0);
  51. }
  52. void EditorSceneImporter::get_extensions(List<String> *r_extensions) const {
  53. if (get_script_instance()) {
  54. Array arr = get_script_instance()->call("_get_extensions");
  55. for (int i = 0; i < arr.size(); i++) {
  56. r_extensions->push_back(arr[i]);
  57. }
  58. return;
  59. }
  60. ERR_FAIL();
  61. }
  62. Node *EditorSceneImporter::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, uint32_t p_compress_flags, List<String> *r_missing_deps, Error *r_err) {
  63. if (get_script_instance()) {
  64. return get_script_instance()->call("_import_scene", p_path, p_flags, p_bake_fps);
  65. }
  66. ERR_FAIL_V(nullptr);
  67. }
  68. Ref<Animation> EditorSceneImporter::import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  69. if (get_script_instance()) {
  70. return get_script_instance()->call("_import_animation", p_path, p_flags);
  71. }
  72. ERR_FAIL_V(nullptr);
  73. }
  74. //for documenters, these functions are useful when an importer calls an external conversion helper (like, fbx2gltf),
  75. //and you want to load the resulting file
  76. Node *EditorSceneImporter::import_scene_from_other_importer(const String &p_path, uint32_t p_flags, int p_bake_fps, uint32_t p_compress_flags) {
  77. return ResourceImporterScene::get_singleton()->import_scene_from_other_importer(this, p_path, p_flags, p_bake_fps, p_compress_flags);
  78. }
  79. Ref<Animation> EditorSceneImporter::import_animation_from_other_importer(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  80. return ResourceImporterScene::get_singleton()->import_animation_from_other_importer(this, p_path, p_flags, p_bake_fps);
  81. }
  82. void EditorSceneImporter::_bind_methods() {
  83. ClassDB::bind_method(D_METHOD("import_scene_from_other_importer", "path", "flags", "bake_fps", "compress_flags"), &EditorSceneImporter::import_scene_from_other_importer);
  84. ClassDB::bind_method(D_METHOD("import_animation_from_other_importer", "path", "flags", "bake_fps"), &EditorSceneImporter::import_animation_from_other_importer);
  85. BIND_VMETHOD(MethodInfo(Variant::INT, "_get_import_flags"));
  86. BIND_VMETHOD(MethodInfo(Variant::ARRAY, "_get_extensions"));
  87. MethodInfo mi = MethodInfo(Variant::OBJECT, "_import_scene", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::INT, "flags"), PropertyInfo(Variant::INT, "bake_fps"));
  88. mi.return_val.class_name = "Node";
  89. BIND_VMETHOD(mi);
  90. mi = MethodInfo(Variant::OBJECT, "_import_animation", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::INT, "flags"), PropertyInfo(Variant::INT, "bake_fps"));
  91. mi.return_val.class_name = "Animation";
  92. BIND_VMETHOD(mi);
  93. BIND_CONSTANT(IMPORT_SCENE);
  94. BIND_CONSTANT(IMPORT_ANIMATION);
  95. BIND_CONSTANT(IMPORT_ANIMATION_DETECT_LOOP);
  96. BIND_CONSTANT(IMPORT_ANIMATION_OPTIMIZE);
  97. BIND_CONSTANT(IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS);
  98. BIND_CONSTANT(IMPORT_ANIMATION_KEEP_VALUE_TRACKS);
  99. BIND_CONSTANT(IMPORT_GENERATE_TANGENT_ARRAYS);
  100. BIND_CONSTANT(IMPORT_FAIL_ON_MISSING_DEPENDENCIES);
  101. BIND_CONSTANT(IMPORT_MATERIALS_IN_INSTANCES);
  102. }
  103. /////////////////////////////////
  104. void EditorScenePostImport::_bind_methods() {
  105. BIND_VMETHOD(MethodInfo(Variant::OBJECT, "post_import", PropertyInfo(Variant::OBJECT, "scene")));
  106. ClassDB::bind_method(D_METHOD("get_source_folder"), &EditorScenePostImport::get_source_folder);
  107. ClassDB::bind_method(D_METHOD("get_source_file"), &EditorScenePostImport::get_source_file);
  108. }
  109. Node *EditorScenePostImport::post_import(Node *p_scene) {
  110. if (get_script_instance()) {
  111. return get_script_instance()->call("post_import", p_scene);
  112. }
  113. return p_scene;
  114. }
  115. String EditorScenePostImport::get_source_folder() const {
  116. return source_folder;
  117. }
  118. String EditorScenePostImport::get_source_file() const {
  119. return source_file;
  120. }
  121. void EditorScenePostImport::init(const String &p_source_folder, const String &p_source_file) {
  122. source_folder = p_source_folder;
  123. source_file = p_source_file;
  124. }
  125. EditorScenePostImport::EditorScenePostImport() {
  126. }
  127. String ResourceImporterScene::get_importer_name() const {
  128. return "scene";
  129. }
  130. String ResourceImporterScene::get_visible_name() const {
  131. return "Scene";
  132. }
  133. void ResourceImporterScene::get_recognized_extensions(List<String> *p_extensions) const {
  134. for (Set<Ref<EditorSceneImporter>>::Element *E = importers.front(); E; E = E->next()) {
  135. E->get()->get_extensions(p_extensions);
  136. }
  137. }
  138. String ResourceImporterScene::get_save_extension() const {
  139. return "scn";
  140. }
  141. String ResourceImporterScene::get_resource_type() const {
  142. return "PackedScene";
  143. }
  144. bool ResourceImporterScene::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
  145. if (p_option.begins_with("animation/")) {
  146. if (p_option != "animation/import" && !bool(p_options["animation/import"])) {
  147. return false;
  148. }
  149. if (p_option == "animation/keep_custom_tracks" && int(p_options["animation/storage"]) == 0) {
  150. return false;
  151. }
  152. if (p_option.begins_with("animation/optimizer/") && p_option != "animation/optimizer/enabled" && !bool(p_options["animation/optimizer/enabled"])) {
  153. return false;
  154. }
  155. if (p_option.begins_with("animation/clip_")) {
  156. int max_clip = p_options["animation/clips/amount"];
  157. int clip = p_option.get_slice("/", 1).get_slice("_", 1).to_int() - 1;
  158. if (clip >= max_clip) {
  159. return false;
  160. }
  161. }
  162. }
  163. if (p_option == "materials/keep_on_reimport" && int(p_options["materials/storage"]) == 0) {
  164. return false;
  165. }
  166. if (p_option == "meshes/lightmap_texel_size" && int(p_options["meshes/light_baking"]) < 2) {
  167. return false;
  168. }
  169. return true;
  170. }
  171. int ResourceImporterScene::get_preset_count() const {
  172. return PRESET_MAX;
  173. }
  174. String ResourceImporterScene::get_preset_name(int p_idx) const {
  175. switch (p_idx) {
  176. case PRESET_SINGLE_SCENE:
  177. return TTR("Import as Single Scene");
  178. case PRESET_SEPARATE_ANIMATIONS:
  179. return TTR("Import with Separate Animations");
  180. case PRESET_SEPARATE_MATERIALS:
  181. return TTR("Import with Separate Materials");
  182. case PRESET_SEPARATE_MESHES:
  183. return TTR("Import with Separate Objects");
  184. case PRESET_SEPARATE_MESHES_AND_MATERIALS:
  185. return TTR("Import with Separate Objects+Materials");
  186. case PRESET_SEPARATE_MESHES_AND_ANIMATIONS:
  187. return TTR("Import with Separate Objects+Animations");
  188. case PRESET_SEPARATE_MATERIALS_AND_ANIMATIONS:
  189. return TTR("Import with Separate Materials+Animations");
  190. case PRESET_SEPARATE_MESHES_MATERIALS_AND_ANIMATIONS:
  191. return TTR("Import with Separate Objects+Materials+Animations");
  192. case PRESET_MULTIPLE_SCENES:
  193. return TTR("Import as Multiple Scenes");
  194. case PRESET_MULTIPLE_SCENES_AND_MATERIALS:
  195. return TTR("Import as Multiple Scenes+Materials");
  196. }
  197. return "";
  198. }
  199. static bool _teststr(const String &p_what, const String &p_str) {
  200. String what = p_what;
  201. //remove trailing spaces and numbers, some apps like blender add ".number" to duplicates so also compensate for this
  202. while (what.length() && ((what[what.length() - 1] >= '0' && what[what.length() - 1] <= '9') || what[what.length() - 1] <= 32 || what[what.length() - 1] == '.')) {
  203. what = what.substr(0, what.length() - 1);
  204. }
  205. if (what.findn("$" + p_str) != -1) { //blender and other stuff
  206. return true;
  207. }
  208. if (what.to_lower().ends_with("-" + p_str)) { //collada only supports "_" and "-" besides letters
  209. return true;
  210. }
  211. if (what.to_lower().ends_with("_" + p_str)) { //collada only supports "_" and "-" besides letters
  212. return true;
  213. }
  214. return false;
  215. }
  216. static String _fixstr(const String &p_what, const String &p_str) {
  217. String what = p_what;
  218. //remove trailing spaces and numbers, some apps like blender add ".number" to duplicates so also compensate for this
  219. while (what.length() && ((what[what.length() - 1] >= '0' && what[what.length() - 1] <= '9') || what[what.length() - 1] <= 32 || what[what.length() - 1] == '.')) {
  220. what = what.substr(0, what.length() - 1);
  221. }
  222. String end = p_what.substr(what.length(), p_what.length() - what.length());
  223. if (what.findn("$" + p_str) != -1) { //blender and other stuff
  224. return what.replace("$" + p_str, "") + end;
  225. }
  226. if (what.to_lower().ends_with("-" + p_str)) { //collada only supports "_" and "-" besides letters
  227. return what.substr(0, what.length() - (p_str.length() + 1)) + end;
  228. }
  229. if (what.to_lower().ends_with("_" + p_str)) { //collada only supports "_" and "-" besides letters
  230. return what.substr(0, what.length() - (p_str.length() + 1)) + end;
  231. }
  232. return what;
  233. }
  234. static void _gen_shape_list(const Ref<Mesh> &mesh, List<Ref<Shape>> &r_shape_list, bool p_convex) {
  235. if (!p_convex) {
  236. Ref<Shape> shape = mesh->create_trimesh_shape();
  237. r_shape_list.push_back(shape);
  238. } else {
  239. Vector<Ref<Shape>> cd = mesh->convex_decompose();
  240. if (cd.size()) {
  241. for (int i = 0; i < cd.size(); i++) {
  242. r_shape_list.push_back(cd[i]);
  243. }
  244. }
  245. }
  246. }
  247. Node *ResourceImporterScene::_fix_node(Node *p_node, Node *p_root, Map<Ref<Mesh>, List<Ref<Shape>>> &collision_map, LightBakeMode p_light_bake_mode, List<Pair<NodePath, Node *>> &r_node_renames) {
  248. // Children first.
  249. for (int i = 0; i < p_node->get_child_count(); i++) {
  250. Node *r = _fix_node(p_node->get_child(i), p_root, collision_map, p_light_bake_mode, r_node_renames);
  251. if (!r) {
  252. i--; // Was erased.
  253. }
  254. }
  255. String name = p_node->get_name();
  256. NodePath original_path = p_root->get_path_to(p_node); // Used to detect renames due to import hints.
  257. bool isroot = p_node == p_root;
  258. if (!isroot && _teststr(name, "noimp")) {
  259. memdelete(p_node);
  260. return nullptr;
  261. }
  262. if (Object::cast_to<MeshInstance>(p_node)) {
  263. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  264. Ref<ArrayMesh> m = mi->get_mesh();
  265. if (m.is_valid()) {
  266. for (int i = 0; i < m->get_surface_count(); i++) {
  267. Ref<Material3D> mat = m->surface_get_material(i);
  268. if (!mat.is_valid()) {
  269. continue;
  270. }
  271. if (_teststr(mat->get_name(), "alpha")) {
  272. mat->set_feature(Material3D::FEATURE_TRANSPARENT, true);
  273. mat->set_name(_fixstr(mat->get_name(), "alpha"));
  274. }
  275. if (_teststr(mat->get_name(), "vcol")) {
  276. mat->set_flag(Material3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  277. mat->set_flag(Material3D::FLAG_SRGB_VERTEX_COLOR, true);
  278. mat->set_name(_fixstr(mat->get_name(), "vcol"));
  279. }
  280. }
  281. }
  282. if (p_light_bake_mode != LIGHT_BAKE_DISABLED) {
  283. mi->set_flag(GeometryInstance::FLAG_USE_BAKED_LIGHT, true);
  284. }
  285. }
  286. if (Object::cast_to<AnimationPlayer>(p_node)) {
  287. AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
  288. // Node paths in animation tracks are relative to the following path (this is used to fix node paths below).
  289. Node *ap_root = ap->get_node(ap->get_root());
  290. NodePath path_prefix = p_root->get_path_to(ap_root);
  291. bool nodes_were_renamed = r_node_renames.size() != 0;
  292. List<StringName> anims;
  293. ap->get_animation_list(&anims);
  294. for (List<StringName>::Element *E = anims.front(); E; E = E->next()) {
  295. Ref<Animation> anim = ap->get_animation(E->get());
  296. ERR_CONTINUE(anim.is_null());
  297. // Remove animation tracks referencing non-importable nodes
  298. for (int i = 0; i < anim->get_track_count(); i++) {
  299. NodePath path = anim->track_get_path(i);
  300. for (int j = 0; j < path.get_name_count(); j++) {
  301. String node = path.get_name(j);
  302. if (_teststr(node, "noimp")) {
  303. anim->remove_track(i);
  304. i--;
  305. break;
  306. }
  307. }
  308. }
  309. // Fix node paths in animations, in case nodes were renamed earlier due to import hints.
  310. if (nodes_were_renamed) {
  311. for (int i = 0; i < anim->get_track_count(); i++) {
  312. NodePath path = anim->track_get_path(i);
  313. // Convert track path to absolute node path without subnames (some manual work because we are not in the scene tree).
  314. Vector<StringName> absolute_path_names = path_prefix.get_names();
  315. absolute_path_names.append_array(path.get_names());
  316. NodePath absolute_path(absolute_path_names, false);
  317. absolute_path.simplify();
  318. // Fix paths to renamed nodes.
  319. for (const List<Pair<NodePath, Node *>>::Element *F = r_node_renames.front(); F; F = F->next()) {
  320. if (F->get().first == absolute_path) {
  321. NodePath new_path(ap_root->get_path_to(F->get().second).get_names(), path.get_subnames(), false);
  322. print_verbose(vformat("Fix: Correcting node path in animation track: %s should be %s", path, new_path));
  323. anim->track_set_path(i, new_path);
  324. break; // Only one match is possible.
  325. }
  326. }
  327. }
  328. }
  329. }
  330. }
  331. if (_teststr(name, "colonly") || _teststr(name, "convcolonly")) {
  332. if (isroot) {
  333. return p_node;
  334. }
  335. String fixed_name;
  336. if (_teststr(name, "colonly")) {
  337. fixed_name = _fixstr(name, "colonly");
  338. } else if (_teststr(name, "convcolonly")) {
  339. fixed_name = _fixstr(name, "convcolonly");
  340. }
  341. ERR_FAIL_COND_V(fixed_name == String(), nullptr);
  342. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  343. if (mi) {
  344. Ref<Mesh> mesh = mi->get_mesh();
  345. if (mesh.is_valid()) {
  346. List<Ref<Shape>> shapes;
  347. if (collision_map.has(mesh)) {
  348. shapes = collision_map[mesh];
  349. } else if (_teststr(name, "colonly")) {
  350. _gen_shape_list(mesh, shapes, false);
  351. collision_map[mesh] = shapes;
  352. } else if (_teststr(name, "convcolonly")) {
  353. _gen_shape_list(mesh, shapes, true);
  354. collision_map[mesh] = shapes;
  355. }
  356. if (shapes.size()) {
  357. StaticBody *col = memnew(StaticBody);
  358. col->set_transform(mi->get_transform());
  359. col->set_name(fixed_name);
  360. p_node->replace_by(col);
  361. memdelete(p_node);
  362. p_node = col;
  363. _add_shapes(col, shapes);
  364. }
  365. }
  366. } else if (p_node->has_meta("empty_draw_type")) {
  367. String empty_draw_type = String(p_node->get_meta("empty_draw_type"));
  368. StaticBody *sb = memnew(StaticBody);
  369. sb->set_name(fixed_name);
  370. Object::cast_to<Spatial>(sb)->set_transform(Object::cast_to<Spatial>(p_node)->get_transform());
  371. p_node->replace_by(sb);
  372. memdelete(p_node);
  373. p_node = sb;
  374. CollisionShape *colshape = memnew(CollisionShape);
  375. if (empty_draw_type == "CUBE") {
  376. BoxShape *boxShape = memnew(BoxShape);
  377. boxShape->set_extents(Vector3(1, 1, 1));
  378. colshape->set_shape(boxShape);
  379. } else if (empty_draw_type == "SINGLE_ARROW") {
  380. RayShape *rayShape = memnew(RayShape);
  381. rayShape->set_length(1);
  382. colshape->set_shape(rayShape);
  383. Object::cast_to<Spatial>(sb)->rotate_x(Math_PI / 2);
  384. } else if (empty_draw_type == "IMAGE") {
  385. PlaneShape *planeShape = memnew(PlaneShape);
  386. colshape->set_shape(planeShape);
  387. } else {
  388. SphereShape *sphereShape = memnew(SphereShape);
  389. sphereShape->set_radius(1);
  390. colshape->set_shape(sphereShape);
  391. }
  392. sb->add_child(colshape);
  393. colshape->set_owner(sb->get_owner());
  394. }
  395. } else if (_teststr(name, "rigid") && Object::cast_to<MeshInstance>(p_node)) {
  396. if (isroot) {
  397. return p_node;
  398. }
  399. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  400. Ref<Mesh> mesh = mi->get_mesh();
  401. if (mesh.is_valid()) {
  402. List<Ref<Shape>> shapes;
  403. if (collision_map.has(mesh)) {
  404. shapes = collision_map[mesh];
  405. } else {
  406. _gen_shape_list(mesh, shapes, true);
  407. }
  408. RigidBody *rigid_body = memnew(RigidBody);
  409. rigid_body->set_name(_fixstr(name, "rigid"));
  410. p_node->replace_by(rigid_body);
  411. rigid_body->set_transform(mi->get_transform());
  412. p_node = rigid_body;
  413. mi->set_transform(Transform());
  414. rigid_body->add_child(mi);
  415. mi->set_owner(rigid_body->get_owner());
  416. _add_shapes(rigid_body, shapes);
  417. }
  418. } else if ((_teststr(name, "col") || (_teststr(name, "convcol"))) && Object::cast_to<MeshInstance>(p_node)) {
  419. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  420. Ref<Mesh> mesh = mi->get_mesh();
  421. if (mesh.is_valid()) {
  422. List<Ref<Shape>> shapes;
  423. String fixed_name;
  424. if (collision_map.has(mesh)) {
  425. shapes = collision_map[mesh];
  426. } else if (_teststr(name, "col")) {
  427. _gen_shape_list(mesh, shapes, false);
  428. collision_map[mesh] = shapes;
  429. } else if (_teststr(name, "convcol")) {
  430. _gen_shape_list(mesh, shapes, true);
  431. collision_map[mesh] = shapes;
  432. }
  433. if (_teststr(name, "col")) {
  434. fixed_name = _fixstr(name, "col");
  435. } else if (_teststr(name, "convcol")) {
  436. fixed_name = _fixstr(name, "convcol");
  437. }
  438. if (fixed_name != String()) {
  439. if (mi->get_parent() && !mi->get_parent()->has_node(fixed_name)) {
  440. mi->set_name(fixed_name);
  441. }
  442. }
  443. if (shapes.size()) {
  444. StaticBody *col = memnew(StaticBody);
  445. mi->add_child(col);
  446. col->set_owner(mi->get_owner());
  447. _add_shapes(col, shapes);
  448. }
  449. }
  450. } else if (_teststr(name, "navmesh") && Object::cast_to<MeshInstance>(p_node)) {
  451. if (isroot) {
  452. return p_node;
  453. }
  454. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  455. Ref<ArrayMesh> mesh = mi->get_mesh();
  456. ERR_FAIL_COND_V(mesh.is_null(), nullptr);
  457. NavigationMeshInstance *nmi = memnew(NavigationMeshInstance);
  458. nmi->set_name(_fixstr(name, "navmesh"));
  459. Ref<NavigationMesh> nmesh = memnew(NavigationMesh);
  460. nmesh->create_from_mesh(mesh);
  461. nmi->set_navigation_mesh(nmesh);
  462. Object::cast_to<Spatial>(nmi)->set_transform(mi->get_transform());
  463. p_node->replace_by(nmi);
  464. memdelete(p_node);
  465. p_node = nmi;
  466. } else if (_teststr(name, "vehicle")) {
  467. if (isroot) {
  468. return p_node;
  469. }
  470. Node *owner = p_node->get_owner();
  471. Spatial *s = Object::cast_to<Spatial>(p_node);
  472. VehicleBody *bv = memnew(VehicleBody);
  473. String n = _fixstr(p_node->get_name(), "vehicle");
  474. bv->set_name(n);
  475. p_node->replace_by(bv);
  476. p_node->set_name(n);
  477. bv->add_child(p_node);
  478. bv->set_owner(owner);
  479. p_node->set_owner(owner);
  480. bv->set_transform(s->get_transform());
  481. s->set_transform(Transform());
  482. p_node = bv;
  483. } else if (_teststr(name, "wheel")) {
  484. if (isroot) {
  485. return p_node;
  486. }
  487. Node *owner = p_node->get_owner();
  488. Spatial *s = Object::cast_to<Spatial>(p_node);
  489. VehicleWheel *bv = memnew(VehicleWheel);
  490. String n = _fixstr(p_node->get_name(), "wheel");
  491. bv->set_name(n);
  492. p_node->replace_by(bv);
  493. p_node->set_name(n);
  494. bv->add_child(p_node);
  495. bv->set_owner(owner);
  496. p_node->set_owner(owner);
  497. bv->set_transform(s->get_transform());
  498. s->set_transform(Transform());
  499. p_node = bv;
  500. } else if (Object::cast_to<MeshInstance>(p_node)) {
  501. //last attempt, maybe collision inside the mesh data
  502. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  503. Ref<ArrayMesh> mesh = mi->get_mesh();
  504. if (!mesh.is_null()) {
  505. List<Ref<Shape>> shapes;
  506. if (collision_map.has(mesh)) {
  507. shapes = collision_map[mesh];
  508. } else if (_teststr(mesh->get_name(), "col")) {
  509. _gen_shape_list(mesh, shapes, false);
  510. collision_map[mesh] = shapes;
  511. mesh->set_name(_fixstr(mesh->get_name(), "col"));
  512. } else if (_teststr(mesh->get_name(), "convcol")) {
  513. _gen_shape_list(mesh, shapes, true);
  514. collision_map[mesh] = shapes;
  515. mesh->set_name(_fixstr(mesh->get_name(), "convcol"));
  516. }
  517. if (shapes.size()) {
  518. StaticBody *col = memnew(StaticBody);
  519. p_node->add_child(col);
  520. col->set_owner(p_node->get_owner());
  521. _add_shapes(col, shapes);
  522. }
  523. }
  524. }
  525. if (p_node) {
  526. NodePath new_path = p_root->get_path_to(p_node);
  527. if (new_path != original_path) {
  528. print_verbose(vformat("Fix: Renamed %s to %s", original_path, new_path));
  529. r_node_renames.push_back({ original_path, p_node });
  530. }
  531. }
  532. return p_node;
  533. }
  534. void ResourceImporterScene::_create_clips(Node *scene, const Array &p_clips, bool p_bake_all) {
  535. AnimationPlayer *anim = _find_animation_player(scene);
  536. if (!anim) {
  537. WARN_PRINT("Creating clips is enabled, but no animation player was found.");
  538. return;
  539. }
  540. if (!anim->has_animation("default")) {
  541. ERR_FAIL_COND_MSG(p_clips.size() > 0, "To create clips, animations must be named \"default\".");
  542. return;
  543. }
  544. Ref<Animation> default_anim = anim->get_animation("default");
  545. for (int i = 0; i < p_clips.size(); i += 4) {
  546. String name = p_clips[i];
  547. float from = p_clips[i + 1];
  548. float to = p_clips[i + 2];
  549. bool loop = p_clips[i + 3];
  550. if (from >= to) {
  551. continue;
  552. }
  553. Ref<Animation> new_anim = memnew(Animation);
  554. for (int j = 0; j < default_anim->get_track_count(); j++) {
  555. List<float> keys;
  556. int kc = default_anim->track_get_key_count(j);
  557. int dtrack = -1;
  558. for (int k = 0; k < kc; k++) {
  559. float kt = default_anim->track_get_key_time(j, k);
  560. if (kt >= from && kt < to) {
  561. //found a key within range, so create track
  562. if (dtrack == -1) {
  563. new_anim->add_track(default_anim->track_get_type(j));
  564. dtrack = new_anim->get_track_count() - 1;
  565. new_anim->track_set_path(dtrack, default_anim->track_get_path(j));
  566. if (kt > (from + 0.01) && k > 0) {
  567. if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
  568. Quat q;
  569. Vector3 p;
  570. Vector3 s;
  571. default_anim->transform_track_interpolate(j, from, &p, &q, &s);
  572. new_anim->transform_track_insert_key(dtrack, 0, p, q, s);
  573. }
  574. if (default_anim->track_get_type(j) == Animation::TYPE_VALUE) {
  575. Variant var = default_anim->value_track_interpolate(j, from);
  576. new_anim->track_insert_key(dtrack, 0, var);
  577. }
  578. }
  579. }
  580. if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
  581. Quat q;
  582. Vector3 p;
  583. Vector3 s;
  584. default_anim->transform_track_get_key(j, k, &p, &q, &s);
  585. new_anim->transform_track_insert_key(dtrack, kt - from, p, q, s);
  586. }
  587. if (default_anim->track_get_type(j) == Animation::TYPE_VALUE) {
  588. Variant var = default_anim->track_get_key_value(j, k);
  589. new_anim->track_insert_key(dtrack, kt - from, var);
  590. }
  591. }
  592. if (dtrack != -1 && kt >= to) {
  593. if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
  594. Quat q;
  595. Vector3 p;
  596. Vector3 s;
  597. default_anim->transform_track_interpolate(j, to, &p, &q, &s);
  598. new_anim->transform_track_insert_key(dtrack, to - from, p, q, s);
  599. }
  600. if (default_anim->track_get_type(j) == Animation::TYPE_VALUE) {
  601. Variant var = default_anim->value_track_interpolate(j, to);
  602. new_anim->track_insert_key(dtrack, to - from, var);
  603. }
  604. }
  605. }
  606. if (dtrack == -1 && p_bake_all) {
  607. new_anim->add_track(default_anim->track_get_type(j));
  608. dtrack = new_anim->get_track_count() - 1;
  609. new_anim->track_set_path(dtrack, default_anim->track_get_path(j));
  610. if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
  611. Quat q;
  612. Vector3 p;
  613. Vector3 s;
  614. default_anim->transform_track_interpolate(j, from, &p, &q, &s);
  615. new_anim->transform_track_insert_key(dtrack, 0, p, q, s);
  616. default_anim->transform_track_interpolate(j, to, &p, &q, &s);
  617. new_anim->transform_track_insert_key(dtrack, to - from, p, q, s);
  618. }
  619. if (default_anim->track_get_type(j) == Animation::TYPE_VALUE) {
  620. Variant var = default_anim->value_track_interpolate(j, from);
  621. new_anim->track_insert_key(dtrack, 0, var);
  622. Variant to_var = default_anim->value_track_interpolate(j, to);
  623. new_anim->track_insert_key(dtrack, to - from, to_var);
  624. }
  625. }
  626. }
  627. new_anim->set_loop(loop);
  628. new_anim->set_length(to - from);
  629. anim->add_animation(name, new_anim);
  630. }
  631. anim->remove_animation("default"); //remove default (no longer needed)
  632. }
  633. void ResourceImporterScene::_filter_anim_tracks(Ref<Animation> anim, Set<String> &keep) {
  634. Ref<Animation> a = anim;
  635. ERR_FAIL_COND(!a.is_valid());
  636. for (int j = 0; j < a->get_track_count(); j++) {
  637. String path = a->track_get_path(j);
  638. if (!keep.has(path)) {
  639. a->remove_track(j);
  640. j--;
  641. }
  642. }
  643. }
  644. void ResourceImporterScene::_filter_tracks(Node *scene, const String &p_text) {
  645. AnimationPlayer *anim = _find_animation_player(scene);
  646. if (!anim) {
  647. return;
  648. }
  649. Vector<String> strings = p_text.split("\n");
  650. for (int i = 0; i < strings.size(); i++) {
  651. strings.write[i] = strings[i].strip_edges();
  652. }
  653. List<StringName> anim_names;
  654. anim->get_animation_list(&anim_names);
  655. for (List<StringName>::Element *E = anim_names.front(); E; E = E->next()) {
  656. String name = E->get();
  657. bool valid_for_this = false;
  658. bool valid = false;
  659. Set<String> keep;
  660. Set<String> keep_local;
  661. for (int i = 0; i < strings.size(); i++) {
  662. if (strings[i].begins_with("@")) {
  663. valid_for_this = false;
  664. for (Set<String>::Element *F = keep_local.front(); F; F = F->next()) {
  665. keep.insert(F->get());
  666. }
  667. keep_local.clear();
  668. Vector<String> filters = strings[i].substr(1, strings[i].length()).split(",");
  669. for (int j = 0; j < filters.size(); j++) {
  670. String fname = filters[j].strip_edges();
  671. if (fname == "") {
  672. continue;
  673. }
  674. int fc = fname[0];
  675. bool plus;
  676. if (fc == '+') {
  677. plus = true;
  678. } else if (fc == '-') {
  679. plus = false;
  680. } else {
  681. continue;
  682. }
  683. String filter = fname.substr(1, fname.length()).strip_edges();
  684. if (!name.matchn(filter)) {
  685. continue;
  686. }
  687. valid_for_this = plus;
  688. }
  689. if (valid_for_this) {
  690. valid = true;
  691. }
  692. } else if (valid_for_this) {
  693. Ref<Animation> a = anim->get_animation(name);
  694. if (!a.is_valid()) {
  695. continue;
  696. }
  697. for (int j = 0; j < a->get_track_count(); j++) {
  698. String path = a->track_get_path(j);
  699. String tname = strings[i];
  700. if (tname == "") {
  701. continue;
  702. }
  703. int fc = tname[0];
  704. bool plus;
  705. if (fc == '+') {
  706. plus = true;
  707. } else if (fc == '-') {
  708. plus = false;
  709. } else {
  710. continue;
  711. }
  712. String filter = tname.substr(1, tname.length()).strip_edges();
  713. if (!path.matchn(filter)) {
  714. continue;
  715. }
  716. if (plus) {
  717. keep_local.insert(path);
  718. } else if (!keep.has(path)) {
  719. keep_local.erase(path);
  720. }
  721. }
  722. }
  723. }
  724. if (valid) {
  725. for (Set<String>::Element *F = keep_local.front(); F; F = F->next()) {
  726. keep.insert(F->get());
  727. }
  728. _filter_anim_tracks(anim->get_animation(name), keep);
  729. }
  730. }
  731. }
  732. void ResourceImporterScene::_optimize_animations(Node *scene, float p_max_lin_error, float p_max_ang_error, float p_max_angle) {
  733. AnimationPlayer *anim = _find_animation_player(scene);
  734. if (!anim) {
  735. return;
  736. }
  737. List<StringName> anim_names;
  738. anim->get_animation_list(&anim_names);
  739. for (List<StringName>::Element *E = anim_names.front(); E; E = E->next()) {
  740. Ref<Animation> a = anim->get_animation(E->get());
  741. a->optimize(p_max_lin_error, p_max_ang_error, Math::deg2rad(p_max_angle));
  742. }
  743. }
  744. static String _make_extname(const String &p_str) {
  745. String ext_name = p_str.replace(".", "_");
  746. ext_name = ext_name.replace(":", "_");
  747. ext_name = ext_name.replace("\"", "_");
  748. ext_name = ext_name.replace("<", "_");
  749. ext_name = ext_name.replace(">", "_");
  750. ext_name = ext_name.replace("/", "_");
  751. ext_name = ext_name.replace("|", "_");
  752. ext_name = ext_name.replace("\\", "_");
  753. ext_name = ext_name.replace("?", "_");
  754. ext_name = ext_name.replace("*", "_");
  755. return ext_name;
  756. }
  757. AnimationPlayer *ResourceImporterScene::_find_animation_player(Node *p_node) {
  758. // Find a direct child that is an AnimationPlayer.
  759. AnimationPlayer *ret = nullptr;
  760. for (int i = 0; i < p_node->get_child_count(); i++) {
  761. AnimationPlayer *child = Object::cast_to<AnimationPlayer>(p_node->get_child(i));
  762. if (child) {
  763. if (ret == nullptr) {
  764. ret = child;
  765. } else {
  766. WARN_PRINT("More than one animation player: \"" + ret->get_name() + "\" and \"" + child->get_name() + "\".");
  767. }
  768. }
  769. }
  770. return ret;
  771. }
  772. void ResourceImporterScene::_find_meshes(Node *p_node, Map<Ref<ArrayMesh>, Transform> &meshes) {
  773. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  774. if (mi) {
  775. Ref<ArrayMesh> mesh = mi->get_mesh();
  776. if (mesh.is_valid() && !meshes.has(mesh)) {
  777. Spatial *s = Object::cast_to<Spatial>(mi);
  778. Transform transform;
  779. while (s) {
  780. transform = transform * s->get_transform();
  781. s = Object::cast_to<Spatial>(s->get_parent());
  782. }
  783. meshes[mesh] = transform;
  784. }
  785. }
  786. for (int i = 0; i < p_node->get_child_count(); i++) {
  787. _find_meshes(p_node->get_child(i), meshes);
  788. }
  789. }
  790. void ResourceImporterScene::_make_external_resources(Node *p_node, const String &p_base_path, bool p_make_animations, bool p_animations_as_text, bool p_keep_animations, bool p_make_materials, bool p_materials_as_text, bool p_keep_materials, bool p_make_meshes, bool p_meshes_as_text, Map<Ref<Animation>, Ref<Animation>> &p_animations, Map<Ref<Material>, Ref<Material>> &p_materials, Map<Ref<ArrayMesh>, Ref<ArrayMesh>> &p_meshes) {
  791. List<PropertyInfo> pi;
  792. if (p_make_animations) {
  793. if (Object::cast_to<AnimationPlayer>(p_node)) {
  794. AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
  795. List<StringName> anims;
  796. ap->get_animation_list(&anims);
  797. for (List<StringName>::Element *E = anims.front(); E; E = E->next()) {
  798. Ref<Animation> anim = ap->get_animation(E->get());
  799. ERR_CONTINUE(anim.is_null());
  800. if (!p_animations.has(anim)) {
  801. // Tracks from source file should be set as imported, anything else is a custom track.
  802. for (int i = 0; i < anim->get_track_count(); i++) {
  803. anim->track_set_imported(i, true);
  804. }
  805. String ext_name;
  806. if (p_animations_as_text) {
  807. ext_name = p_base_path.plus_file(_make_extname(E->get()) + ".tres");
  808. } else {
  809. ext_name = p_base_path.plus_file(_make_extname(E->get()) + ".anim");
  810. }
  811. if (FileAccess::exists(ext_name) && p_keep_animations) {
  812. // Copy custom animation tracks from previously imported files.
  813. Ref<Animation> old_anim = ResourceLoader::load(ext_name, "Animation", true);
  814. if (old_anim.is_valid()) {
  815. for (int i = 0; i < old_anim->get_track_count(); i++) {
  816. if (!old_anim->track_is_imported(i)) {
  817. old_anim->copy_track(i, anim);
  818. }
  819. }
  820. anim->set_loop(old_anim->has_loop());
  821. }
  822. }
  823. anim->set_path(ext_name, true); // Set path to save externally.
  824. ResourceSaver::save(ext_name, anim, ResourceSaver::FLAG_CHANGE_PATH);
  825. p_animations[anim] = anim;
  826. }
  827. }
  828. }
  829. }
  830. p_node->get_property_list(&pi);
  831. for (List<PropertyInfo>::Element *E = pi.front(); E; E = E->next()) {
  832. if (E->get().type == Variant::OBJECT) {
  833. Ref<Material> mat = p_node->get(E->get().name);
  834. if (p_make_materials && mat.is_valid() && mat->get_name() != "") {
  835. if (!p_materials.has(mat)) {
  836. String ext_name;
  837. if (p_materials_as_text) {
  838. ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".tres");
  839. } else {
  840. ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".material");
  841. }
  842. if (p_keep_materials && FileAccess::exists(ext_name)) {
  843. //if exists, use it
  844. p_materials[mat] = ResourceLoader::load(ext_name);
  845. } else {
  846. ResourceSaver::save(ext_name, mat, ResourceSaver::FLAG_CHANGE_PATH);
  847. p_materials[mat] = ResourceLoader::load(ext_name, "", true); // disable loading from the cache.
  848. }
  849. }
  850. if (p_materials[mat] != mat) {
  851. p_node->set(E->get().name, p_materials[mat]);
  852. }
  853. } else {
  854. Ref<ArrayMesh> mesh = p_node->get(E->get().name);
  855. if (mesh.is_valid()) {
  856. bool mesh_just_added = false;
  857. if (p_make_meshes) {
  858. if (!p_meshes.has(mesh)) {
  859. //meshes are always overwritten, keeping them is not practical
  860. String ext_name;
  861. if (p_meshes_as_text) {
  862. ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".tres");
  863. } else {
  864. ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".mesh");
  865. }
  866. ResourceSaver::save(ext_name, mesh, ResourceSaver::FLAG_CHANGE_PATH);
  867. p_meshes[mesh] = ResourceLoader::load(ext_name);
  868. p_node->set(E->get().name, p_meshes[mesh]);
  869. mesh_just_added = true;
  870. }
  871. }
  872. if (p_make_materials) {
  873. if (mesh_just_added || !p_meshes.has(mesh)) {
  874. for (int i = 0; i < mesh->get_surface_count(); i++) {
  875. mat = mesh->surface_get_material(i);
  876. if (!mat.is_valid()) {
  877. continue;
  878. }
  879. if (mat->get_name() == "") {
  880. continue;
  881. }
  882. if (!p_materials.has(mat)) {
  883. String ext_name;
  884. if (p_materials_as_text) {
  885. ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".tres");
  886. } else {
  887. ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".material");
  888. }
  889. if (p_keep_materials && FileAccess::exists(ext_name)) {
  890. //if exists, use it
  891. p_materials[mat] = ResourceLoader::load(ext_name);
  892. } else {
  893. ResourceSaver::save(ext_name, mat, ResourceSaver::FLAG_CHANGE_PATH);
  894. p_materials[mat] = ResourceLoader::load(ext_name, "", true); // disable loading from the cache.
  895. }
  896. }
  897. if (p_materials[mat] != mat) {
  898. mesh->surface_set_material(i, p_materials[mat]);
  899. //re-save the mesh since a material is now assigned
  900. if (p_make_meshes) {
  901. String ext_name;
  902. if (p_meshes_as_text) {
  903. ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".tres");
  904. } else {
  905. ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".mesh");
  906. }
  907. ResourceSaver::save(ext_name, mesh, ResourceSaver::FLAG_CHANGE_PATH);
  908. p_meshes[mesh] = ResourceLoader::load(ext_name);
  909. }
  910. }
  911. }
  912. if (!p_make_meshes) {
  913. p_meshes[mesh] = Ref<ArrayMesh>(); //save it anyway, so it won't be checked again
  914. }
  915. }
  916. }
  917. }
  918. }
  919. }
  920. }
  921. for (int i = 0; i < p_node->get_child_count(); i++) {
  922. _make_external_resources(p_node->get_child(i), p_base_path, p_make_animations, p_animations_as_text, p_keep_animations, p_make_materials, p_materials_as_text, p_keep_materials, p_make_meshes, p_meshes_as_text, p_animations, p_materials, p_meshes);
  923. }
  924. }
  925. void ResourceImporterScene::get_import_options(List<ImportOption> *r_options, int p_preset) const {
  926. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/root_type", PROPERTY_HINT_TYPE_STRING, "Node"), "Spatial"));
  927. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/root_name"), "Scene Root"));
  928. List<String> script_extentions;
  929. ResourceLoader::get_recognized_extensions_for_type("Script", &script_extentions);
  930. String script_ext_hint;
  931. for (List<String>::Element *E = script_extentions.front(); E; E = E->next()) {
  932. if (script_ext_hint != "") {
  933. script_ext_hint += ",";
  934. }
  935. script_ext_hint += "*." + E->get();
  936. }
  937. bool materials_out = p_preset == PRESET_SEPARATE_MATERIALS || p_preset == PRESET_SEPARATE_MESHES_AND_MATERIALS || p_preset == PRESET_MULTIPLE_SCENES_AND_MATERIALS || p_preset == PRESET_SEPARATE_MATERIALS_AND_ANIMATIONS || p_preset == PRESET_SEPARATE_MESHES_MATERIALS_AND_ANIMATIONS;
  938. bool meshes_out = p_preset == PRESET_SEPARATE_MESHES || p_preset == PRESET_SEPARATE_MESHES_AND_MATERIALS || p_preset == PRESET_SEPARATE_MESHES_AND_ANIMATIONS || p_preset == PRESET_SEPARATE_MESHES_MATERIALS_AND_ANIMATIONS;
  939. bool scenes_out = p_preset == PRESET_MULTIPLE_SCENES || p_preset == PRESET_MULTIPLE_SCENES_AND_MATERIALS;
  940. bool animations_out = p_preset == PRESET_SEPARATE_ANIMATIONS || p_preset == PRESET_SEPARATE_MESHES_AND_ANIMATIONS || p_preset == PRESET_SEPARATE_MATERIALS_AND_ANIMATIONS || p_preset == PRESET_SEPARATE_MESHES_MATERIALS_AND_ANIMATIONS;
  941. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "nodes/root_scale", PROPERTY_HINT_RANGE, "0.001,1000,0.001"), 1.0));
  942. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/custom_script", PROPERTY_HINT_FILE, script_ext_hint), ""));
  943. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "nodes/storage", PROPERTY_HINT_ENUM, "Single Scene,Instanced Sub-Scenes"), scenes_out ? 1 : 0));
  944. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "nodes/use_legacy_names"), true));
  945. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "materials/location", PROPERTY_HINT_ENUM, "Node,Mesh"), (meshes_out || materials_out) ? 1 : 0));
  946. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "materials/storage", PROPERTY_HINT_ENUM, "Built-In,Files (.material),Files (.tres)", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), materials_out ? 1 : 0));
  947. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "materials/keep_on_reimport"), materials_out));
  948. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "meshes/compress", PROPERTY_HINT_FLAGS, "Vertex,Normal,Tangent,Color,TexUV,TexUV2,Bones,Weights,Index"), VS::ARRAY_COMPRESS_DEFAULT >> VS::ARRAY_COMPRESS_BASE));
  949. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/ensure_tangents"), true));
  950. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/octahedral_compression"), true));
  951. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/vertex_cache_optimization"), true));
  952. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "meshes/storage", PROPERTY_HINT_ENUM, "Built-In,Files (.mesh),Files (.tres)"), meshes_out ? 1 : 0));
  953. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "meshes/light_baking", PROPERTY_HINT_ENUM, "Disabled,Enable,Gen Lightmaps", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
  954. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "meshes/lightmap_texel_size", PROPERTY_HINT_RANGE, "0.001,100,0.001"), 0.1));
  955. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "skins/use_named_skins"), true));
  956. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "external_files/store_in_subdir"), false));
  957. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
  958. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/fps", PROPERTY_HINT_RANGE, "1,120,1"), 15));
  959. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "animation/filter_script", PROPERTY_HINT_MULTILINE_TEXT), ""));
  960. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/storage", PROPERTY_HINT_ENUM, "Built-In,Files (.anim),Files (.tres)", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), animations_out));
  961. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/keep_custom_tracks"), animations_out));
  962. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/optimizer/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
  963. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/optimizer/max_linear_error"), 0.05));
  964. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/optimizer/max_angular_error"), 0.01));
  965. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/optimizer/max_angle"), 22));
  966. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/optimizer/remove_unused_tracks"), true));
  967. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/clips/amount", PROPERTY_HINT_RANGE, "0,256,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
  968. for (int i = 0; i < 256; i++) {
  969. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "animation/clip_" + itos(i + 1) + "/name"), ""));
  970. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/clip_" + itos(i + 1) + "/start_frame"), 0));
  971. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/clip_" + itos(i + 1) + "/end_frame"), 0));
  972. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/clip_" + itos(i + 1) + "/loops"), false));
  973. }
  974. }
  975. void ResourceImporterScene::_replace_owner(Node *p_node, Node *p_scene, Node *p_new_owner) {
  976. if (p_node != p_new_owner && p_node->get_owner() == p_scene) {
  977. p_node->set_owner(p_new_owner);
  978. }
  979. for (int i = 0; i < p_node->get_child_count(); i++) {
  980. Node *n = p_node->get_child(i);
  981. _replace_owner(n, p_scene, p_new_owner);
  982. }
  983. }
  984. void ResourceImporterScene::_add_shapes(Node *p_node, const List<Ref<Shape>> &p_shapes) {
  985. for (const List<Ref<Shape>>::Element *E = p_shapes.front(); E; E = E->next()) {
  986. CollisionShape *cshape = memnew(CollisionShape);
  987. cshape->set_shape(E->get());
  988. p_node->add_child(cshape);
  989. cshape->set_owner(p_node->get_owner());
  990. }
  991. }
  992. Node *ResourceImporterScene::import_scene_from_other_importer(EditorSceneImporter *p_exception, const String &p_path, uint32_t p_flags, int p_bake_fps, uint32_t p_compress_flags) {
  993. Ref<EditorSceneImporter> importer;
  994. String ext = p_path.get_extension().to_lower();
  995. for (Set<Ref<EditorSceneImporter>>::Element *E = importers.front(); E; E = E->next()) {
  996. if (E->get().ptr() == p_exception) {
  997. continue;
  998. }
  999. List<String> extensions;
  1000. E->get()->get_extensions(&extensions);
  1001. for (List<String>::Element *F = extensions.front(); F; F = F->next()) {
  1002. if (F->get().to_lower() == ext) {
  1003. importer = E->get();
  1004. break;
  1005. }
  1006. }
  1007. if (importer.is_valid()) {
  1008. break;
  1009. }
  1010. }
  1011. ERR_FAIL_COND_V(!importer.is_valid(), nullptr);
  1012. List<String> missing;
  1013. Error err;
  1014. return importer->import_scene(p_path, p_flags, p_bake_fps, p_compress_flags, &missing, &err);
  1015. }
  1016. Ref<Animation> ResourceImporterScene::import_animation_from_other_importer(EditorSceneImporter *p_exception, const String &p_path, uint32_t p_flags, int p_bake_fps) {
  1017. Ref<EditorSceneImporter> importer;
  1018. String ext = p_path.get_extension().to_lower();
  1019. for (Set<Ref<EditorSceneImporter>>::Element *E = importers.front(); E; E = E->next()) {
  1020. if (E->get().ptr() == p_exception) {
  1021. continue;
  1022. }
  1023. List<String> extensions;
  1024. E->get()->get_extensions(&extensions);
  1025. for (List<String>::Element *F = extensions.front(); F; F = F->next()) {
  1026. if (F->get().to_lower() == ext) {
  1027. importer = E->get();
  1028. break;
  1029. }
  1030. }
  1031. if (importer.is_valid()) {
  1032. break;
  1033. }
  1034. }
  1035. ERR_FAIL_COND_V(!importer.is_valid(), nullptr);
  1036. return importer->import_animation(p_path, p_flags, p_bake_fps);
  1037. }
  1038. Error ResourceImporterScene::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
  1039. const String &src_path = p_source_file;
  1040. Ref<EditorSceneImporter> importer;
  1041. String ext = src_path.get_extension().to_lower();
  1042. EditorProgress progress("import", TTR("Import Scene"), 104);
  1043. progress.step(TTR("Importing Scene..."), 0);
  1044. for (Set<Ref<EditorSceneImporter>>::Element *E = importers.front(); E; E = E->next()) {
  1045. List<String> extensions;
  1046. E->get()->get_extensions(&extensions);
  1047. for (List<String>::Element *F = extensions.front(); F; F = F->next()) {
  1048. if (F->get().to_lower() == ext) {
  1049. importer = E->get();
  1050. break;
  1051. }
  1052. }
  1053. if (importer.is_valid()) {
  1054. break;
  1055. }
  1056. }
  1057. ERR_FAIL_COND_V(!importer.is_valid(), ERR_FILE_UNRECOGNIZED);
  1058. float fps = p_options["animation/fps"];
  1059. int import_flags = EditorSceneImporter::IMPORT_ANIMATION_DETECT_LOOP;
  1060. if (!bool(p_options["animation/optimizer/remove_unused_tracks"])) {
  1061. import_flags |= EditorSceneImporter::IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS;
  1062. }
  1063. if (bool(p_options["animation/import"])) {
  1064. import_flags |= EditorSceneImporter::IMPORT_ANIMATION;
  1065. }
  1066. uint32_t compress_flags = int(p_options["meshes/compress"]) << VS::ARRAY_COMPRESS_BASE;
  1067. if (bool(p_options["meshes/octahedral_compression"])) {
  1068. compress_flags |= VS::ARRAY_FLAG_USE_OCTAHEDRAL_COMPRESSION;
  1069. }
  1070. if (bool(p_options["meshes/vertex_cache_optimization"])) {
  1071. compress_flags |= VS::ARRAY_FLAG_USE_VERTEX_CACHE_OPTIMIZATION;
  1072. }
  1073. if (bool(p_options["meshes/ensure_tangents"])) {
  1074. import_flags |= EditorSceneImporter::IMPORT_GENERATE_TANGENT_ARRAYS;
  1075. }
  1076. if (int(p_options["materials/location"]) == 0) {
  1077. import_flags |= EditorSceneImporter::IMPORT_MATERIALS_IN_INSTANCES;
  1078. }
  1079. if (bool(p_options["skins/use_named_skins"])) {
  1080. import_flags |= EditorSceneImporter::IMPORT_USE_NAMED_SKIN_BINDS;
  1081. }
  1082. if (bool(p_options["nodes/use_legacy_names"])) {
  1083. import_flags |= EditorSceneImporter::IMPORT_USE_LEGACY_NAMES;
  1084. }
  1085. Error err = OK;
  1086. List<String> missing_deps; // for now, not much will be done with this
  1087. Node *scene = importer->import_scene(src_path, import_flags, fps, compress_flags, &missing_deps, &err);
  1088. if (!scene || err != OK) {
  1089. return err;
  1090. }
  1091. String root_type = p_options["nodes/root_type"];
  1092. root_type = root_type.split(" ")[0]; // full root_type is "ClassName (filename.gd)" for a script global class.
  1093. Ref<Script> root_script = nullptr;
  1094. if (ScriptServer::is_global_class(root_type)) {
  1095. root_script = ResourceLoader::load(ScriptServer::get_global_class_path(root_type));
  1096. root_type = ScriptServer::get_global_class_base(root_type);
  1097. }
  1098. if (root_type != "Spatial") {
  1099. Node *base_node = Object::cast_to<Node>(ClassDB::instance(root_type));
  1100. if (base_node) {
  1101. scene->replace_by(base_node);
  1102. memdelete(scene);
  1103. scene = base_node;
  1104. }
  1105. }
  1106. if (root_script.is_valid()) {
  1107. scene->set_script(Variant(root_script));
  1108. }
  1109. if (Object::cast_to<Spatial>(scene)) {
  1110. float root_scale = p_options["nodes/root_scale"];
  1111. Object::cast_to<Spatial>(scene)->scale(Vector3(root_scale, root_scale, root_scale));
  1112. }
  1113. if (p_options["nodes/root_name"] != "Scene Root") {
  1114. scene->set_name(p_options["nodes/root_name"]);
  1115. } else {
  1116. scene->set_name(p_save_path.get_file().get_basename());
  1117. }
  1118. err = OK;
  1119. String animation_filter = String(p_options["animation/filter_script"]).strip_edges();
  1120. bool use_optimizer = p_options["animation/optimizer/enabled"];
  1121. float anim_optimizer_linerr = p_options["animation/optimizer/max_linear_error"];
  1122. float anim_optimizer_angerr = p_options["animation/optimizer/max_angular_error"];
  1123. float anim_optimizer_maxang = p_options["animation/optimizer/max_angle"];
  1124. int light_bake_mode = p_options["meshes/light_baking"];
  1125. Map<Ref<Mesh>, List<Ref<Shape>>> collision_map;
  1126. List<Pair<NodePath, Node *>> node_renames;
  1127. scene = _fix_node(scene, scene, collision_map, LightBakeMode(light_bake_mode), node_renames);
  1128. if (use_optimizer) {
  1129. _optimize_animations(scene, anim_optimizer_linerr, anim_optimizer_angerr, anim_optimizer_maxang);
  1130. }
  1131. Array animation_clips;
  1132. {
  1133. int clip_count = p_options["animation/clips/amount"];
  1134. for (int i = 0; i < clip_count; i++) {
  1135. String name = p_options["animation/clip_" + itos(i + 1) + "/name"];
  1136. int from_frame = p_options["animation/clip_" + itos(i + 1) + "/start_frame"];
  1137. int end_frame = p_options["animation/clip_" + itos(i + 1) + "/end_frame"];
  1138. bool loop = p_options["animation/clip_" + itos(i + 1) + "/loops"];
  1139. animation_clips.push_back(name);
  1140. animation_clips.push_back(from_frame / fps);
  1141. animation_clips.push_back(end_frame / fps);
  1142. animation_clips.push_back(loop);
  1143. }
  1144. }
  1145. if (animation_clips.size()) {
  1146. _create_clips(scene, animation_clips, !bool(p_options["animation/optimizer/remove_unused_tracks"]));
  1147. }
  1148. if (animation_filter != "") {
  1149. _filter_tracks(scene, animation_filter);
  1150. }
  1151. bool external_animations = int(p_options["animation/storage"]) == 1 || int(p_options["animation/storage"]) == 2;
  1152. bool external_animations_as_text = int(p_options["animation/storage"]) == 2;
  1153. bool keep_custom_tracks = p_options["animation/keep_custom_tracks"];
  1154. bool external_materials = int(p_options["materials/storage"]) == 1 || int(p_options["materials/storage"]) == 2;
  1155. bool external_materials_as_text = int(p_options["materials/storage"]) == 2;
  1156. bool external_meshes = int(p_options["meshes/storage"]) == 1 || int(p_options["meshes/storage"]) == 2;
  1157. bool external_meshes_as_text = int(p_options["meshes/storage"]) == 2;
  1158. bool external_scenes = int(p_options["nodes/storage"]) == 1;
  1159. String base_path = p_source_file.get_base_dir();
  1160. if (external_animations || external_materials || external_meshes || external_scenes) {
  1161. if (bool(p_options["external_files/store_in_subdir"])) {
  1162. String subdir_name = p_source_file.get_file().get_basename();
  1163. DirAccess *da = DirAccess::open(base_path);
  1164. Error err2 = da->make_dir(subdir_name);
  1165. memdelete(da);
  1166. ERR_FAIL_COND_V_MSG(err2 != OK && err2 != ERR_ALREADY_EXISTS, err2, "Cannot make directory '" + subdir_name + "'.");
  1167. base_path = base_path.plus_file(subdir_name);
  1168. }
  1169. }
  1170. if (light_bake_mode == 2 /* || generate LOD */) {
  1171. Map<Ref<ArrayMesh>, Transform> meshes;
  1172. _find_meshes(scene, meshes);
  1173. String file_id = src_path.get_file();
  1174. String cache_file_path = base_path.plus_file(file_id + ".unwrap_cache");
  1175. int *cache_data = nullptr;
  1176. uint64_t cache_size = 0;
  1177. if (FileAccess::exists(cache_file_path)) {
  1178. Error err2;
  1179. FileAccess *file = FileAccess::open(cache_file_path, FileAccess::READ, &err2);
  1180. if (!err2) {
  1181. cache_size = file->get_len();
  1182. cache_data = (int *)memalloc(cache_size);
  1183. file->get_buffer((uint8_t *)cache_data, cache_size);
  1184. }
  1185. if (file) {
  1186. memdelete(file);
  1187. }
  1188. }
  1189. float texel_size = p_options["meshes/lightmap_texel_size"];
  1190. texel_size = MAX(0.001, texel_size);
  1191. Map<String, unsigned int> used_meshes;
  1192. EditorProgress progress2("gen_lightmaps", TTR("Generating Lightmaps"), meshes.size());
  1193. int step = 0;
  1194. for (Map<Ref<ArrayMesh>, Transform>::Element *E = meshes.front(); E; E = E->next()) {
  1195. Ref<ArrayMesh> mesh = E->key();
  1196. String name = mesh->get_name();
  1197. if (name == "") { //should not happen but..
  1198. name = "Mesh " + itos(step);
  1199. }
  1200. progress2.step(TTR("Generating for Mesh:") + " " + name + " (" + itos(step) + "/" + itos(meshes.size()) + ")", step);
  1201. int *ret_cache_data = cache_data;
  1202. unsigned int ret_cache_size = cache_size;
  1203. bool ret_used_cache = true; // Tell the unwrapper to use the cache
  1204. Error err2 = mesh->lightmap_unwrap_cached(ret_cache_data, ret_cache_size, ret_used_cache, E->get(), texel_size);
  1205. if (err2 != OK) {
  1206. EditorNode::add_io_error("Mesh '" + name + "' failed lightmap generation. Please fix geometry.");
  1207. } else {
  1208. String hash = String::md5((unsigned char *)ret_cache_data);
  1209. used_meshes.insert(hash, ret_cache_size);
  1210. if (!ret_used_cache) {
  1211. // Cache was not used, add the generated entry to the current cache
  1212. unsigned int new_cache_size = cache_size + ret_cache_size + (cache_size == 0 ? 4 : 0);
  1213. int *new_cache_data = (int *)memalloc(new_cache_size);
  1214. if (cache_size == 0) {
  1215. // Cache was empty
  1216. new_cache_data[0] = 0;
  1217. cache_size = 4;
  1218. } else {
  1219. memcpy(new_cache_data, cache_data, cache_size);
  1220. memfree(cache_data);
  1221. }
  1222. memcpy(&new_cache_data[cache_size / sizeof(int)], ret_cache_data, ret_cache_size);
  1223. cache_data = new_cache_data;
  1224. cache_size = new_cache_size;
  1225. cache_data[0]++; // Increase entry count
  1226. }
  1227. }
  1228. step++;
  1229. }
  1230. Error err2;
  1231. FileAccess *file = FileAccess::open(cache_file_path, FileAccess::WRITE, &err2);
  1232. if (err2) {
  1233. if (file) {
  1234. memdelete(file);
  1235. }
  1236. } else {
  1237. // Store number of entries
  1238. file->store_32(used_meshes.size());
  1239. // Store cache entries
  1240. unsigned int r_idx = 1;
  1241. for (int i = 0; i < cache_data[0]; ++i) {
  1242. unsigned char *entry_start = (unsigned char *)&cache_data[r_idx];
  1243. String entry_hash = String::md5(entry_start);
  1244. if (used_meshes.has(entry_hash)) {
  1245. unsigned int entry_size = used_meshes[entry_hash];
  1246. file->store_buffer(entry_start, entry_size);
  1247. }
  1248. r_idx += 4; // hash
  1249. r_idx += 2; // size hint
  1250. int vertex_count = cache_data[r_idx];
  1251. r_idx += 1; // vertex count
  1252. r_idx += vertex_count; // vertex
  1253. r_idx += vertex_count * 2; // uvs
  1254. int index_count = cache_data[r_idx];
  1255. r_idx += 1; // index count
  1256. r_idx += index_count; // indices
  1257. }
  1258. file->close();
  1259. memfree(cache_data);
  1260. }
  1261. }
  1262. if (external_animations || external_materials || external_meshes) {
  1263. Map<Ref<Animation>, Ref<Animation>> anim_map;
  1264. Map<Ref<Material>, Ref<Material>> mat_map;
  1265. Map<Ref<ArrayMesh>, Ref<ArrayMesh>> mesh_map;
  1266. bool keep_materials = bool(p_options["materials/keep_on_reimport"]);
  1267. _make_external_resources(scene, base_path, external_animations, external_animations_as_text, keep_custom_tracks, external_materials, external_materials_as_text, keep_materials, external_meshes, external_meshes_as_text, anim_map, mat_map, mesh_map);
  1268. }
  1269. progress.step(TTR("Running Custom Script..."), 2);
  1270. String post_import_script_path = p_options["nodes/custom_script"];
  1271. Ref<EditorScenePostImport> post_import_script;
  1272. if (post_import_script_path != "") {
  1273. Ref<Script> scr = ResourceLoader::load(post_import_script_path);
  1274. if (!scr.is_valid()) {
  1275. EditorNode::add_io_error(TTR("Couldn't load post-import script:") + " " + post_import_script_path);
  1276. } else {
  1277. post_import_script = Ref<EditorScenePostImport>(memnew(EditorScenePostImport));
  1278. post_import_script->set_script(scr.get_ref_ptr());
  1279. if (!post_import_script->get_script_instance()) {
  1280. EditorNode::add_io_error(TTR("Invalid/broken script for post-import (check console):") + " " + post_import_script_path);
  1281. post_import_script.unref();
  1282. return ERR_CANT_CREATE;
  1283. }
  1284. }
  1285. }
  1286. if (post_import_script.is_valid()) {
  1287. post_import_script->init(base_path, p_source_file);
  1288. scene = post_import_script->post_import(scene);
  1289. if (!scene) {
  1290. EditorNode::add_io_error(
  1291. TTR("Error running post-import script:") + " " + post_import_script_path + "\n" +
  1292. TTR("Did you return a Node-derived object in the `post_import()` method?"));
  1293. return err;
  1294. }
  1295. }
  1296. progress.step(TTR("Saving..."), 104);
  1297. if (external_scenes) {
  1298. //save sub-scenes as instances!
  1299. for (int i = 0; i < scene->get_child_count(); i++) {
  1300. Node *child = scene->get_child(i);
  1301. if (child->get_owner() != scene) {
  1302. continue; //not a real child probably created by scene type (ig, a scrollbar)
  1303. }
  1304. _replace_owner(child, scene, child);
  1305. String cn = String(child->get_name()).strip_edges().replace(".", "_").replace(":", "_");
  1306. if (cn == String()) {
  1307. cn = "ChildNode" + itos(i);
  1308. }
  1309. String path = base_path.plus_file(cn + ".scn");
  1310. child->set_filename(path);
  1311. Ref<PackedScene> packer = memnew(PackedScene);
  1312. packer->pack(child);
  1313. err = ResourceSaver::save(path, packer); //do not take over, let the changed files reload themselves
  1314. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save scene to file '" + path + "'.");
  1315. }
  1316. }
  1317. Ref<PackedScene> packer = memnew(PackedScene);
  1318. packer->pack(scene);
  1319. print_verbose("Saving scene to: " + p_save_path + ".scn");
  1320. err = ResourceSaver::save(p_save_path + ".scn", packer); //do not take over, let the changed files reload themselves
  1321. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save scene to file '" + p_save_path + ".scn'.");
  1322. memdelete(scene);
  1323. //this is not the time to reimport, wait until import process is done, import file is saved, etc.
  1324. //EditorNode::get_singleton()->reload_scene(p_source_file);
  1325. return OK;
  1326. }
  1327. ResourceImporterScene *ResourceImporterScene::singleton = nullptr;
  1328. ResourceImporterScene::ResourceImporterScene() {
  1329. singleton = this;
  1330. }
  1331. ///////////////////////////////////////
  1332. uint32_t EditorSceneImporterESCN::get_import_flags() const {
  1333. return IMPORT_SCENE;
  1334. }
  1335. void EditorSceneImporterESCN::get_extensions(List<String> *r_extensions) const {
  1336. r_extensions->push_back("escn");
  1337. }
  1338. Node *EditorSceneImporterESCN::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, uint32_t p_compress_flags, List<String> *r_missing_deps, Error *r_err) {
  1339. Error error;
  1340. Ref<PackedScene> ps = ResourceFormatLoaderText::singleton->load(p_path, p_path, &error);
  1341. ERR_FAIL_COND_V_MSG(!ps.is_valid(), nullptr, "Cannot load scene as text resource from path '" + p_path + "'.");
  1342. Node *scene = ps->instance();
  1343. ERR_FAIL_COND_V(!scene, nullptr);
  1344. return scene;
  1345. }
  1346. Ref<Animation> EditorSceneImporterESCN::import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  1347. ERR_FAIL_V(Ref<Animation>());
  1348. }