From 45533589e4040bd5684807ac169f801ea5b24049 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Verschelde?= Date: Fri, 20 Jun 2025 23:13:27 +0200 Subject: [PATCH] Revert "Rework scene preview thumbnails" This reverts commit 08343189dc89678bfbb108c78ae923b66d5949af. While the feature is great, a number of issues have been found with the implementation, and we need more time to resolve them. So we roll this back for 4.5, to rework the feature for a later Godot release. --- doc/classes/EditorInterface.xml | 1 - editor/editor_interface.cpp | 155 ++++ editor/editor_interface.h | 3 + editor/editor_node.cpp | 118 ++- editor/editor_node.h | 8 +- editor/editor_resource_preview.cpp | 105 +-- editor/editor_resource_preview.h | 9 +- editor/import/3d/resource_importer_scene.cpp | 11 + editor/import/3d/resource_importer_scene.h | 1 + editor/plugins/editor_preview_plugins.cpp | 732 +------------------ editor/plugins/editor_preview_plugins.h | 17 - 11 files changed, 309 insertions(+), 851 deletions(-) diff --git a/doc/classes/EditorInterface.xml b/doc/classes/EditorInterface.xml index 165eb9ce2dc..d0a7177fb68 100644 --- a/doc/classes/EditorInterface.xml +++ b/doc/classes/EditorInterface.xml @@ -428,7 +428,6 @@ Saves the currently active scene as a file at [param path]. - [b]Note:[/b] The [param with_preview] parameter has no effect. diff --git a/editor/editor_interface.cpp b/editor/editor_interface.cpp index ce7112d64db..082b0ed3c96 100644 --- a/editor/editor_interface.cpp +++ b/editor/editor_interface.cpp @@ -52,6 +52,9 @@ #include "editor/property_selector.h" #include "editor/themes/editor_scale.h" #include "main/main.h" +#include "plugins/editor_preview_plugins.h" +#include "scene/3d/light_3d.h" +#include "scene/3d/mesh_instance_3d.h" #include "scene/gui/box_container.h" #include "scene/gui/control.h" #include "scene/main/window.h" @@ -100,6 +103,27 @@ EditorUndoRedoManager *EditorInterface::get_editor_undo_redo() const { return EditorUndoRedoManager::get_singleton(); } +AABB EditorInterface::_calculate_aabb_for_scene(Node *p_node, AABB &p_scene_aabb) { + MeshInstance3D *mesh_node = Object::cast_to(p_node); + if (mesh_node && mesh_node->get_mesh().is_valid()) { + Transform3D accum_xform; + Node3D *base = mesh_node; + while (base) { + accum_xform = base->get_transform() * accum_xform; + base = Object::cast_to(base->get_parent()); + } + + AABB aabb = accum_xform.xform(mesh_node->get_mesh()->get_aabb()); + p_scene_aabb.merge_with(aabb); + } + + for (int i = 0; i < p_node->get_child_count(); i++) { + p_scene_aabb = _calculate_aabb_for_scene(p_node->get_child(i), p_scene_aabb); + } + + return p_scene_aabb; +} + TypedArray EditorInterface::_make_mesh_previews(const TypedArray &p_meshes, int p_preview_size) { Vector> meshes; @@ -205,6 +229,137 @@ Vector> EditorInterface::make_mesh_previews(const Vectoris_inside_tree(), "The scene must not be inside the tree."); + ERR_FAIL_COND_MSG(!Engine::get_singleton()->is_editor_hint(), "This function can only be called from the editor."); + ERR_FAIL_NULL_MSG(EditorNode::get_singleton(), "EditorNode doesn't exist."); + + SubViewport *sub_viewport_node = memnew(SubViewport); + AABB scene_aabb; + scene_aabb = _calculate_aabb_for_scene(p_scene, scene_aabb); + + sub_viewport_node->set_update_mode(SubViewport::UPDATE_ALWAYS); + sub_viewport_node->set_size(Vector2i(p_preview_size, p_preview_size)); + sub_viewport_node->set_transparent_background(false); + Ref world; + world.instantiate(); + sub_viewport_node->set_world_3d(world); + + EditorNode::get_singleton()->add_child(sub_viewport_node); + Ref env; + env.instantiate(); + env->set_background(Environment::BG_CLEAR_COLOR); + + Ref camera_attributes; + camera_attributes.instantiate(); + + Node3D *root = memnew(Node3D); + root->set_name("Root"); + sub_viewport_node->add_child(root); + + Camera3D *camera = memnew(Camera3D); + camera->set_environment(env); + camera->set_attributes(camera_attributes); + camera->set_name("Camera3D"); + root->add_child(camera); + camera->set_current(true); + + camera->set_position(Vector3(0.0, 0.0, 3.0)); + + DirectionalLight3D *light = memnew(DirectionalLight3D); + light->set_name("Light"); + DirectionalLight3D *light2 = memnew(DirectionalLight3D); + light2->set_name("Light2"); + light2->set_color(Color(0.7, 0.7, 0.7, 1.0)); + + root->add_child(light); + root->add_child(light2); + + sub_viewport_node->add_child(p_scene); + + // Calculate the camera and lighting position based on the size of the scene. + Vector3 center = scene_aabb.get_center(); + float camera_size = scene_aabb.get_longest_axis_size(); + + const float cam_rot_x = -Math::PI / 4; + const float cam_rot_y = -Math::PI / 4; + + camera->set_orthogonal(camera_size * 2.0, 0.0001, camera_size * 2.0); + + Transform3D xf; + xf.basis = Basis(Vector3(0, 1, 0), cam_rot_y) * Basis(Vector3(1, 0, 0), cam_rot_x); + xf.origin = center; + xf.translate_local(0, 0, camera_size); + + camera->set_transform(xf); + + Transform3D xform; + xform.basis = Basis().rotated(Vector3(0, 1, 0), -Math::PI / 6); + xform.basis = Basis().rotated(Vector3(1, 0, 0), Math::PI / 6) * xform.basis; + + light->set_transform(xform * Transform3D().looking_at(Vector3(-2, -1, -1), Vector3(0, 1, 0))); + light2->set_transform(xform * Transform3D().looking_at(Vector3(+1, -1, -2), Vector3(0, 1, 0))); + + // Update the renderer to get the screenshot. + DisplayServer::get_singleton()->process_events(); + Main::iteration(); + Main::iteration(); + + // Get the texture. + Ref texture = sub_viewport_node->get_texture(); + ERR_FAIL_COND_MSG(texture.is_null(), "Failed to get texture from sub_viewport_node."); + + // Remove the initial scene node. + sub_viewport_node->remove_child(p_scene); + + // Cleanup the viewport. + if (sub_viewport_node) { + if (sub_viewport_node->get_parent()) { + sub_viewport_node->get_parent()->remove_child(sub_viewport_node); + } + sub_viewport_node->queue_free(); + sub_viewport_node = nullptr; + } + + // Now generate the cache image. + Ref img = texture->get_image(); + if (img.is_valid() && img->get_width() > 0 && img->get_height() > 0) { + img = img->duplicate(); + + int preview_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size"); + preview_size *= EDSCALE; + + int vp_size = MIN(img->get_width(), img->get_height()); + int x = (img->get_width() - vp_size) / 2; + int y = (img->get_height() - vp_size) / 2; + + if (vp_size < preview_size) { + img->crop_from_point(x, y, vp_size, vp_size); + } else { + int ratio = vp_size / preview_size; + int size = preview_size * MAX(1, ratio / 2); + + x = (img->get_width() - size) / 2; + y = (img->get_height() - size) / 2; + + img->crop_from_point(x, y, size, size); + img->resize(preview_size, preview_size, Image::INTERPOLATE_LANCZOS); + } + img->convert(Image::FORMAT_RGB8); + + String temp_path = EditorPaths::get_singleton()->get_cache_dir(); + String cache_base = ProjectSettings::get_singleton()->globalize_path(p_path).md5_text(); + cache_base = temp_path.path_join("resthumb-" + cache_base); + + post_process_preview(img); + img->save_png(cache_base + ".png"); + } + + EditorResourcePreview::get_singleton()->check_for_invalidation(p_path); + EditorFileSystem::get_singleton()->emit_signal(SNAME("filesystem_changed")); +} + void EditorInterface::set_plugin_enabled(const String &p_plugin, bool p_enabled) { EditorNode::get_singleton()->set_addon_plugin_enabled(p_plugin, p_enabled, true); } diff --git a/editor/editor_interface.h b/editor/editor_interface.h index 3fe52872327..3b95eb0e7d7 100644 --- a/editor/editor_interface.h +++ b/editor/editor_interface.h @@ -79,7 +79,9 @@ class EditorInterface : public Object { void _call_dialog_callback(const Callable &p_callback, const Variant &p_selected, const String &p_context); // Editor tools. + TypedArray _make_mesh_previews(const TypedArray &p_meshes, int p_preview_size); + AABB _calculate_aabb_for_scene(Node *p_node, AABB &p_scene_aabb); protected: static void _bind_methods(); @@ -108,6 +110,7 @@ public: EditorUndoRedoManager *get_editor_undo_redo() const; Vector> make_mesh_previews(const Vector> &p_meshes, Vector *p_transforms, int p_preview_size); + void make_scene_preview(const String &p_path, Node *p_scene, int p_preview_size); void set_plugin_enabled(const String &p_plugin, bool p_enabled); bool is_plugin_enabled(const String &p_plugin) const; diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index 872ce3f608f..f188d8e74f3 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -1901,6 +1901,91 @@ void EditorNode::_find_node_types(Node *p_node, int &count_2d, int &count_3d) { } } +void EditorNode::_save_scene_with_preview(String p_file, int p_idx) { + save_scene_progress = memnew(EditorProgress("save", TTR("Saving Scene"), 4)); + + if (editor_data.get_edited_scene_root() != nullptr) { + save_scene_progress->step(TTR("Analyzing"), 0); + + int c2d = 0; + int c3d = 0; + + _find_node_types(editor_data.get_edited_scene_root(), c2d, c3d); + + save_scene_progress->step(TTR("Creating Thumbnail"), 1); + // Current view? + + Ref img; + // If neither 3D or 2D nodes are present, make a 1x1 black texture. + // We cannot fallback on the 2D editor, because it may not have been used yet, + // which would result in an invalid texture. + if (c3d == 0 && c2d == 0) { + img.instantiate(); + img->initialize_data(1, 1, false, Image::FORMAT_RGB8); + } else if (c3d < c2d) { + Ref viewport_texture = scene_root->get_texture(); + if (viewport_texture->get_width() > 0 && viewport_texture->get_height() > 0) { + img = viewport_texture->get_image(); + } + } else { + // The 3D editor may be disabled as a feature, but scenes can still be opened. + // This check prevents the preview from regenerating in case those scenes are then saved. + // The preview will be generated if no feature profile is set (as the 3D editor is enabled by default). + Ref profile = feature_profile_manager->get_current_profile(); + if (profile.is_null() || !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_3D)) { + img = Node3DEditor::get_singleton()->get_editor_viewport(0)->get_viewport_node()->get_texture()->get_image(); + } + } + + if (img.is_valid() && img->get_width() > 0 && img->get_height() > 0) { + img = img->duplicate(); + + save_scene_progress->step(TTR("Creating Thumbnail"), 3); + + int preview_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size"); + preview_size *= EDSCALE; + + // Consider a square region. + int vp_size = MIN(img->get_width(), img->get_height()); + int x = (img->get_width() - vp_size) / 2; + int y = (img->get_height() - vp_size) / 2; + + if (vp_size < preview_size) { + // Just square it. + img->crop_from_point(x, y, vp_size, vp_size); + } else { + int ratio = vp_size / preview_size; + int size = preview_size * MAX(1, ratio / 2); + + x = (img->get_width() - size) / 2; + y = (img->get_height() - size) / 2; + + img->crop_from_point(x, y, size, size); + img->resize(preview_size, preview_size, Image::INTERPOLATE_LANCZOS); + } + img->convert(Image::FORMAT_RGB8); + + // Save thumbnail directly, as thumbnailer may not update due to actual scene not changing md5. + String temp_path = EditorPaths::get_singleton()->get_cache_dir(); + String cache_base = ProjectSettings::get_singleton()->globalize_path(p_file).md5_text(); + cache_base = temp_path.path_join("resthumb-" + cache_base); + + // Does not have it, try to load a cached thumbnail. + post_process_preview(img); + img->save_png(cache_base + ".png"); + } + } + + save_scene_progress->step(TTR("Saving Scene"), 4); + _save_scene(p_file, p_idx); + + if (!singleton->cmdline_mode) { + EditorResourcePreview::get_singleton()->check_for_invalidation(p_file); + } + + _close_save_scene_progress(); +} + void EditorNode::_close_save_scene_progress() { memdelete_notnull(save_scene_progress); save_scene_progress = nullptr; @@ -2031,18 +2116,13 @@ void EditorNode::_save_scene(String p_file, int idx) { Node *scene = editor_data.get_edited_scene_root(idx); - save_scene_progress = memnew(EditorProgress("save", TTR("Saving Scene"), 3)); - save_scene_progress->step(TTR("Analyzing"), 0); - if (!scene) { show_accept(TTR("This operation can't be done without a tree root."), TTR("OK")); - _close_save_scene_progress(); return; } if (!scene->get_scene_file_path().is_empty() && _validate_scene_recursive(scene->get_scene_file_path(), scene)) { show_accept(TTR("This scene can't be saved because there is a cyclic instance inclusion.\nPlease resolve it and then attempt to save again."), TTR("OK")); - _close_save_scene_progress(); return; } @@ -2054,8 +2134,6 @@ void EditorNode::_save_scene(String p_file, int idx) { _reset_animation_mixers(scene, &anim_backups); _save_editor_states(p_file, idx); - save_scene_progress->step(TTR("Packing Scene"), 1); - Ref sdata; if (ResourceCache::has(p_file)) { @@ -2076,12 +2154,9 @@ void EditorNode::_save_scene(String p_file, int idx) { if (err != OK) { show_accept(TTR("Couldn't save scene. Likely dependencies (instances or inheritance) couldn't be satisfied."), TTR("OK")); - _close_save_scene_progress(); return; } - save_scene_progress->step(TTR("Saving scene"), 2); - int flg = 0; if (EDITOR_GET("filesystem/on_save/compress_binary_resources")) { flg |= ResourceSaver::FLAG_COMPRESS; @@ -2094,8 +2169,6 @@ void EditorNode::_save_scene(String p_file, int idx) { emit_signal(SNAME("scene_saved"), p_file); editor_data.notify_scene_saved(p_file); - save_scene_progress->step(TTR("Saving external resources"), 3); - _save_external_resources(); saving_scene = p_file; // Some editors may save scenes of built-in resources as external data, so avoid saving this scene again. editor_data.save_editor_external_data(); @@ -2120,7 +2193,6 @@ void EditorNode::_save_scene(String p_file, int idx) { scene->propagate_notification(NOTIFICATION_EDITOR_POST_SAVE); _update_unsaved_cache(); - _close_save_scene_progress(); } void EditorNode::save_all_scenes() { @@ -2160,7 +2232,7 @@ void EditorNode::try_autosave() { Node *scene = editor_data.get_edited_scene_root(); if (scene && !scene->get_scene_file_path().is_empty()) { // Only autosave if there is a scene and if it has a path. - _save_scene(scene->get_scene_file_path()); + _save_scene_with_preview(scene->get_scene_file_path()); } } _menu_option(SCENE_SAVE_ALL_SCENES); @@ -2188,7 +2260,7 @@ void EditorNode::_save_all_scenes() { } if (i == editor_data.get_edited_scene()) { - _save_scene(scene_path); + _save_scene_with_preview(scene_path); } else { _save_scene(scene_path, i); } @@ -2282,7 +2354,7 @@ void EditorNode::_dialog_action(String p_file) { } save_default_environment(); - _save_scene(p_file, scene_idx); + _save_scene_with_preview(p_file, scene_idx); _add_to_recent_scenes(p_file); save_editor_layout_delayed(); @@ -2303,7 +2375,7 @@ void EditorNode::_dialog_action(String p_file) { case SAVE_AND_RUN: { if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) { save_default_environment(); - _save_scene(p_file); + _save_scene_with_preview(p_file); project_run_bar->play_custom_scene(p_file); } } break; @@ -2314,7 +2386,7 @@ void EditorNode::_dialog_action(String p_file) { if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) { save_default_environment(); - _save_scene(p_file); + _save_scene_with_preview(p_file); project_run_bar->play_main_scene((bool)pick_main_scene->get_meta("from_native", false)); } } break; @@ -2428,7 +2500,7 @@ void EditorNode::_dialog_action(String p_file) { default: { // Save scene? if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) { - _save_scene(p_file); + _save_scene_with_preview(p_file); } } break; @@ -2978,9 +3050,9 @@ void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) { if (scene && !scene->get_scene_file_path().is_empty()) { if (DirAccess::exists(scene->get_scene_file_path().get_base_dir())) { if (scene_idx != editor_data.get_edited_scene()) { - _save_scene(scene->get_scene_file_path(), scene_idx); + _save_scene_with_preview(scene->get_scene_file_path(), scene_idx); } else { - _save_scene(scene->get_scene_file_path()); + _save_scene_with_preview(scene->get_scene_file_path()); } if (scene_idx != -1) { @@ -3150,7 +3222,7 @@ void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) { confirmation_button->grab_focus(); break; } else { - _save_scene(scene_filename); + _save_scene_with_preview(scene_filename); } } @@ -7543,7 +7615,7 @@ EditorNode::EditorNode() { ResourceLoader::set_dependency_error_notify_func(&EditorNode::_dependency_error_report); SceneState::set_instantiation_warning_notify_func([](const String &p_warning) { - callable_mp_static(EditorNode::add_io_warning).call_deferred(p_warning); + add_io_warning(p_warning); callable_mp(EditorInterface::get_singleton(), &EditorInterface::mark_scene_as_unsaved).call_deferred(); }); diff --git a/editor/editor_node.h b/editor/editor_node.h index 408ba705069..a130334ff7a 100644 --- a/editor/editor_node.h +++ b/editor/editor_node.h @@ -648,6 +648,7 @@ private: bool _is_scene_unsaved(int p_idx); void _find_node_types(Node *p_node, int &count_2d, int &count_3d); + void _save_scene_with_preview(String p_file, int p_idx = -1); void _close_save_scene_progress(); bool _find_scene_in_use(Node *p_node, const String &p_path) const; @@ -944,8 +945,11 @@ public: Control *get_gui_base() { return gui_base; } void save_scene_to_path(String p_file, bool p_with_preview = true) { - // p_with_preview has no effect, now generates preview at EditorPackedScenePreviewPlugin - _save_scene(p_file); + if (p_with_preview) { + _save_scene_with_preview(p_file); + } else { + _save_scene(p_file); + } } bool close_scene(); diff --git a/editor/editor_resource_preview.cpp b/editor/editor_resource_preview.cpp index 8c6f3292c5f..bfb304fe8d5 100644 --- a/editor/editor_resource_preview.cpp +++ b/editor/editor_resource_preview.cpp @@ -97,9 +97,7 @@ void EditorResourcePreviewGenerator::DrawRequester::request_and_wait(RID p_viewp Callable request_vp_update_once = callable_mp(RS::get_singleton(), &RS::viewport_set_update_mode).bind(p_viewport, RS::VIEWPORT_UPDATE_ONCE); if (EditorResourcePreview::get_singleton()->is_threaded()) { - if (!RS::get_singleton()->is_connected(SNAME("frame_pre_draw"), request_vp_update_once)) { - RS::get_singleton()->connect(SNAME("frame_pre_draw"), request_vp_update_once, Object::CONNECT_ONE_SHOT); - } + RS::get_singleton()->connect(SNAME("frame_pre_draw"), request_vp_update_once, Object::CONNECT_ONE_SHOT); RS::get_singleton()->request_frame_drawn_callback(callable_mp(this, &EditorResourcePreviewGenerator::DrawRequester::_post_semaphore)); semaphore.wait(); @@ -129,12 +127,8 @@ Variant EditorResourcePreviewGenerator::DrawRequester::_post_semaphore() { return Variant(); // Needed because of how the callback is used. } -bool EditorResourcePreview::can_run_on_thread() const { - return RSG::rasterizer->can_create_resources_async(); -} - bool EditorResourcePreview::is_threaded() const { - return thread.is_started(); + return RSG::rasterizer->can_create_resources_async(); } void EditorResourcePreview::_thread_func(void *ud) { @@ -275,14 +269,11 @@ void EditorResourcePreview::_iterate() { QueueItem item = queue.front()->get(); queue.pop_front(); - singleton->processing_item = item; - singleton->last_process_msec = OS::get_singleton()->get_ticks_msec(); if (cache.has(item.path)) { Item cached_item = cache[item.path]; // Already has it because someone loaded it, just let it know it's ready. _preview_ready(item.path, cached_item.last_hash, cached_item.preview, cached_item.small_preview, item.id, item.function, item.userdata, cached_item.preview_metadata); - singleton->processing_item = QueueItem(); preview_mutex.unlock(); return; } @@ -298,9 +289,6 @@ void EditorResourcePreview::_iterate() { Dictionary preview_metadata; _generate_preview(texture, small_texture, item, String(), preview_metadata); _preview_ready(item.path, item.resource->hash_edited_version_for_preview(), texture, small_texture, item.id, item.function, item.userdata, preview_metadata); - preview_mutex.lock(); - singleton->processing_item = QueueItem(); - preview_mutex.unlock(); return; } @@ -339,7 +327,7 @@ void EditorResourcePreview::_iterate() { cache_valid = false; f.unref(); } else if (last_modtime != modtime) { - String last_md5 = hash; + String last_md5 = f->get_line(); String md5 = FileAccess::get_md5(item.path); f.unref(); @@ -389,9 +377,6 @@ void EditorResourcePreview::_iterate() { } } _preview_ready(item.path, 0, texture, small_texture, item.id, item.function, item.userdata, preview_metadata); - preview_mutex.lock(); - singleton->processing_item = QueueItem(); - preview_mutex.unlock(); } void EditorResourcePreview::_write_preview_cache(Ref p_file, int p_thumbnail_size, bool p_has_small_texture, uint64_t p_modified_time, const String &p_hash, const Dictionary &p_metadata) { @@ -428,57 +413,11 @@ void EditorResourcePreview::_idle_callback() { return; } - singleton->_update_progress_bar(); - - // Ensure to process one item at a time - singleton->preview_mutex.lock(); - bool processing = singleton->processing_item.path != ""; - singleton->preview_mutex.unlock(); - if (processing) { - return; + // Process preview tasks, trying to leave a little bit of responsiveness worst case. + uint64_t start = OS::get_singleton()->get_ticks_msec(); + while (!singleton->queue.is_empty() && OS::get_singleton()->get_ticks_msec() - start < 100) { + singleton->_iterate(); } - - singleton->_iterate(); -} - -EditorProgress *EditorResourcePreview::thumbnail_progress = nullptr; // it's static - -void EditorResourcePreview::_update_progress_bar() { - DEV_ASSERT(Thread::get_caller_id() == Thread::get_main_id()); // Progress bar can only be updated in main thread - - // Return if nothing is happening - if (singleton->queue.is_empty() && thumbnail_progress == nullptr) { - singleton->progress_total_steps = -1; - return; - } - - // Create progress bar if not present - if (!singleton->queue.is_empty() && thumbnail_progress == nullptr && singleton->progress_total_steps == -1) { - singleton->progress_total_steps = singleton->queue.size(); - thumbnail_progress = memnew(EditorProgress("generate_thumbnails", "Generate Thumbnails", singleton->progress_total_steps)); - } - - // Update progress bar - if (!singleton->queue.is_empty() && thumbnail_progress != nullptr) { - // The full path could be too long to display, show only the file name - String queue_file; - if (singleton->queue.front()->get().path.count("/") > 1) { - queue_file = singleton->queue.front()->get().path.rsplit("/", true, 1)[1]; - } - int queue_steps = singleton->progress_total_steps - singleton->queue.size(); - int queue_total = singleton->progress_total_steps; - String msg = vformat("%s (%d/%d)", queue_file, queue_steps, queue_total); - - // Don't force update or will stuck in infinite loop at _idle_callback(), since ProgressDialog::task_step() iterates the main loop - thumbnail_progress->step(msg, queue_steps, false); - } - - // Destroy progress bar when queue empty - if (singleton->queue.is_empty() && thumbnail_progress != nullptr) { - memdelete(thumbnail_progress); - thumbnail_progress = nullptr; - } - return; } void EditorResourcePreview::_update_thumbnail_sizes() { @@ -617,7 +556,7 @@ void EditorResourcePreview::start() { return; } - if (can_run_on_thread()) { + if (is_threaded()) { ERR_FAIL_COND_MSG(thread.is_started(), "Thread already started."); thread.start(_thread_func, this); } else { @@ -629,21 +568,23 @@ void EditorResourcePreview::start() { void EditorResourcePreview::stop() { if (is_threaded()) { - exiting.set(); - preview_sem.post(); + if (thread.is_started()) { + exiting.set(); + preview_sem.post(); - for (int i = 0; i < preview_generators.size(); i++) { - preview_generators.write[i]->abort(); + for (int i = 0; i < preview_generators.size(); i++) { + preview_generators.write[i]->abort(); + } + + while (!exited.is_set()) { + // Sync pending work. + OS::get_singleton()->delay_usec(10000); + RenderingServer::get_singleton()->sync(); + MessageQueue::get_singleton()->flush(); + } + + thread.wait_to_finish(); } - - while (!exited.is_set()) { - // Sync pending work. - OS::get_singleton()->delay_usec(10000); - RenderingServer::get_singleton()->sync(); - MessageQueue::get_singleton()->flush(); - } - - thread.wait_to_finish(); } } diff --git a/editor/editor_resource_preview.h b/editor/editor_resource_preview.h index 2b7ebeae45a..5b25b5c6113 100644 --- a/editor/editor_resource_preview.h +++ b/editor/editor_resource_preview.h @@ -33,7 +33,6 @@ #include "core/os/semaphore.h" #include "core/os/thread.h" #include "core/templates/safe_refcount.h" -#include "editor/editor_node.h" #include "scene/main/node.h" class ImageTexture; @@ -74,7 +73,7 @@ public: class EditorResourcePreview : public Node { GDCLASS(EditorResourcePreview, Node); - inline static constexpr int CURRENT_METADATA_VERSION = 2; // Increment this number to invalidate all previews. + static constexpr int CURRENT_METADATA_VERSION = 1; // Increment this number to invalidate all previews. inline static EditorResourcePreview *singleton = nullptr; struct QueueItem { @@ -92,10 +91,6 @@ class EditorResourcePreview : public Node { Thread thread; SafeFlag exiting; SafeFlag exited; - QueueItem processing_item; - int last_process_msec = -1; - int progress_total_steps = -1; - static EditorProgress *thumbnail_progress; struct Item { Ref preview; @@ -116,7 +111,6 @@ class EditorResourcePreview : public Node { void _thread(); // For rendering drivers supporting async texture creation. static void _idle_callback(); // For other rendering drivers (i.e., OpenGL). void _iterate(); - void _update_progress_bar(); void _write_preview_cache(Ref p_file, int p_thumbnail_size, bool p_has_small_texture, uint64_t p_modified_time, const String &p_hash, const Dictionary &p_metadata); void _read_preview_cache(Ref p_file, int *r_thumbnail_size, bool *r_has_small_texture, uint64_t *r_modified_time, String *r_hash, Dictionary *r_metadata, bool *r_outdated); @@ -151,7 +145,6 @@ public: void start(); void stop(); - bool can_run_on_thread() const; bool is_threaded() const; EditorResourcePreview(); diff --git a/editor/import/3d/resource_importer_scene.cpp b/editor/import/3d/resource_importer_scene.cpp index 3163cf00c86..eebb8a19550 100644 --- a/editor/import/3d/resource_importer_scene.cpp +++ b/editor/import/3d/resource_importer_scene.cpp @@ -34,6 +34,7 @@ #include "core/io/dir_access.h" #include "core/io/resource_saver.h" #include "core/object/script_language.h" +#include "editor/editor_interface.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" #include "editor/import/3d/scene_import_settings.h" @@ -2955,6 +2956,15 @@ void ResourceImporterScene::_optimize_track_usage(AnimationPlayer *p_player, Ani } } +void ResourceImporterScene::_generate_editor_preview_for_scene(const String &p_path, Node *p_scene) { + if (!Engine::get_singleton()->is_editor_hint()) { + return; + } + ERR_FAIL_COND_MSG(p_path.is_empty(), "Path is empty, cannot generate preview."); + ERR_FAIL_NULL_MSG(p_scene, "Scene is null, cannot generate preview."); + EditorInterface::get_singleton()->make_scene_preview(p_path, p_scene, 1024); +} + Node *ResourceImporterScene::pre_import(const String &p_source_file, const HashMap &p_options) { Ref importer; String ext = p_source_file.get_extension().to_lower(); @@ -3342,6 +3352,7 @@ Error ResourceImporterScene::import(ResourceUID::ID p_source_id, const String &p print_verbose("Saving scene to: " + p_save_path + ".scn"); err = ResourceSaver::save(packer, p_save_path + ".scn", flags); //do not take over, let the changed files reload themselves ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save scene to file '" + p_save_path + ".scn'."); + _generate_editor_preview_for_scene(p_source_file, scene); } else { ERR_FAIL_V_MSG(ERR_FILE_UNRECOGNIZED, "Unknown scene import type: " + _scene_import_type); } diff --git a/editor/import/3d/resource_importer_scene.h b/editor/import/3d/resource_importer_scene.h index 27c68758a19..071d294b0e3 100644 --- a/editor/import/3d/resource_importer_scene.h +++ b/editor/import/3d/resource_importer_scene.h @@ -232,6 +232,7 @@ class ResourceImporterScene : public ResourceImporter { }; void _optimize_track_usage(AnimationPlayer *p_player, AnimationImportTracks *p_track_actions); + void _generate_editor_preview_for_scene(const String &p_path, Node *p_scene); String _scene_import_type = "PackedScene"; diff --git a/editor/plugins/editor_preview_plugins.cpp b/editor/plugins/editor_preview_plugins.cpp index f203c6b21de..5927f9d7363 100644 --- a/editor/plugins/editor_preview_plugins.cpp +++ b/editor/plugins/editor_preview_plugins.cpp @@ -34,28 +34,9 @@ #include "core/io/image.h" #include "core/io/resource_loader.h" #include "core/object/script_language.h" -#include "editor/editor_node.h" #include "editor/editor_paths.h" #include "editor/editor_settings.h" #include "editor/themes/editor_scale.h" -#include "main/main.h" -#include "modules/gridmap/grid_map.h" -#include "scene/2d/animated_sprite_2d.h" -#include "scene/2d/camera_2d.h" -#include "scene/2d/line_2d.h" -#include "scene/2d/mesh_instance_2d.h" -#include "scene/2d/multimesh_instance_2d.h" -#include "scene/2d/physics/touch_screen_button.h" -#include "scene/2d/polygon_2d.h" -#include "scene/2d/sprite_2d.h" -#include "scene/2d/tile_map_layer.h" -#include "scene/3d/cpu_particles_3d.h" -#include "scene/3d/gpu_particles_3d.h" -#include "scene/3d/light_3d.h" -#include "scene/3d/mesh_instance_3d.h" -#include "scene/gui/option_button.h" -#include "scene/main/viewport.h" -#include "scene/main/window.h" #include "scene/resources/atlas_texture.h" #include "scene/resources/bit_map.h" #include "scene/resources/font.h" @@ -63,7 +44,6 @@ #include "scene/resources/image_texture.h" #include "scene/resources/material.h" #include "scene/resources/mesh.h" -#include "scene/resources/world_2d.h" #include "servers/audio/audio_stream.h" void post_process_preview(Ref p_image) { @@ -303,11 +283,6 @@ bool EditorBitmapPreviewPlugin::generate_small_preview_automatically() const { /////////////////////////////////////////////////////////////////////////// -void EditorPackedScenePreviewPlugin::abort() { - draw_requester.abort(); - aborted = true; -} - bool EditorPackedScenePreviewPlugin::handles(const String &p_type) const { return ClassDB::is_parent_class(p_type, "PackedScene"); } @@ -317,701 +292,28 @@ Ref EditorPackedScenePreviewPlugin::generate(const Ref &p_f } Ref EditorPackedScenePreviewPlugin::generate_from_path(const String &p_path, const Size2 &p_size, Dictionary &p_metadata) const { - ERR_FAIL_COND_V_MSG(!Engine::get_singleton()->is_editor_hint(), Ref(), "This function can only be called from the editor."); - ERR_FAIL_NULL_V_MSG(EditorNode::get_singleton(), Ref(), "EditorNode doesn't exist."); + String temp_path = EditorPaths::get_singleton()->get_cache_dir(); + String cache_base = ProjectSettings::get_singleton()->globalize_path(p_path).md5_text(); + cache_base = temp_path.path_join("resthumb-" + cache_base); - // Lower abort flag - aborted = false; + //does not have it, try to load a cached thumbnail - Error load_error; - Ref pack = ResourceLoader::load(p_path, "PackedScene", ResourceFormatLoader::CACHE_MODE_IGNORE, &load_error); // no more cache issues? - if (load_error != OK) { - print_error(vformat("Failed to generate scene thumbnail for %s : Loaded with error code %d", p_path, int(load_error))); - return Ref(); - } - if (pack.is_null()) { - print_error(vformat("Failed to generate scene thumbnail for %s : Invalid scene file", p_path)); + String path = cache_base + ".png"; + + if (!FileAccess::exists(path)) { return Ref(); } - bool _scene_setup_success = _setup_packed_scene(pack); // We don't want tool scripts to fire off when generating previews - if (!_scene_setup_success) { - print_error(vformat("Failed to generate scene thumbnail for %s : error in setting up preview scene, thus not safe to create thumbnail image", p_path)); - return Ref(); - } + Ref img; + img.instantiate(); + Error err = img->load(path); + if (err == OK) { + post_process_preview(img); + return ImageTexture::create_from_image(img); - Node *p_scene = pack->instantiate(); // The instantiated preview scene - - // Prohibit Viewport class as root when generating thumbnails - if (Object::cast_to(p_scene)) { - p_scene->queue_free(); - return Ref(); - } - - int count_2d = 0; - int count_3d = 0; - int count_light_3d = 0; - _count_node_types(p_scene, count_2d, count_3d, count_light_3d); - - if (count_3d > 0) { // Is 3d scene - // Setup preview viewport - SubViewport *sub_viewport = memnew(SubViewport); - sub_viewport->set_update_mode(SubViewport::UpdateMode::UPDATE_DISABLED); - - sub_viewport->set_size(Size2i(Math::round(p_size.x), Math::round(p_size.y))); - sub_viewport->set_transparent_background(false); - sub_viewport->set_disable_3d(false); - - if (p_size.x < 2048 && p_size.y < 2048) { // Universal baseline for textures in Godot 4 is 4K - sub_viewport->set_scaling_3d_scale(2.0); // Supersampling x2 - } - - if (RS::get_singleton()->get_current_rendering_method() != "gl_compatibility") { - sub_viewport->set_msaa_3d(Viewport::MSAA::MSAA_8X); - } - - Ref environment; - Color default_clear_color = GLOBAL_GET("rendering/environment/defaults/default_clear_color"); - environment.instantiate(); - environment->set_background(Environment::BGMode::BG_CLEAR_COLOR); - environment->set_bg_color(default_clear_color); - Ref world_3d; - sub_viewport->set_world_3d(world_3d); - sub_viewport->set_use_own_world_3d(true); - - Camera3D *camera_3d = memnew(Camera3D); - - sub_viewport->add_child(camera_3d); - camera_3d->set_perspective(preview_3d_fov, 0.05, 10000.0); - - // Add scene to viewport - _setup_scene_3d(p_scene); - sub_viewport->add_child(p_scene); - - // Setup preview light - DirectionalLight3D *light_1 = nullptr; - DirectionalLight3D *light_2 = nullptr; - - if (count_light_3d == 0) { - light_1 = memnew(DirectionalLight3D); - light_2 = memnew(DirectionalLight3D); - sub_viewport->add_child(light_1); - sub_viewport->add_child(light_2); - light_1->set_color(Color(1.0, 1.0, 1.0, 1.0)); - light_2->set_color(Color(0.7, 0.7, 0.7, 1.0)); - light_1->set_transform(Transform3D(Basis().rotated(Vector3(0, 1, 0), -Math::PI / 6), Vector3(0.0, 0.0, 0.0))); - light_2->set_transform(Transform3D(Basis().rotated(Vector3(1, 0, 0), -Math::PI / 6), Vector3(0.0, 0.0, 0.0))); - } - - // Setup preview camera - AABB scene_aabb; - _calculate_scene_aabb(p_scene, scene_aabb); - float bound_sphere_radius = (scene_aabb.get_end() - scene_aabb.get_position()).length() / 2.0f; - if (bound_sphere_radius <= 0.0f) { - // The scene has zero volume, so just it give a literal - bound_sphere_radius = 1.0f; - } - - float cam_distance = bound_sphere_radius / Math::tan(Math::deg_to_rad(preview_3d_fov) / 2.0f); - Transform3D thumbnail_cam_trans_3d; - thumbnail_cam_trans_3d.set_origin(scene_aabb.get_center() + Vector3(1.0f, 0.25f, 1.0f).normalized() * cam_distance); - thumbnail_cam_trans_3d.set_look_at(thumbnail_cam_trans_3d.origin, scene_aabb.get_center()); - - // Set camera to orthogonal if distance exceeds camera default far (large scene) - if (thumbnail_cam_trans_3d.origin.length() > camera_3d->get_far()) { - real_t distance = thumbnail_cam_trans_3d.origin.length(); - camera_3d->set_orthogonal(distance / 2.0, distance / 1000.0, distance); // Approximately contains the whole scene - } - - camera_3d->set_transform(thumbnail_cam_trans_3d); - - // Attach the preview viewport to MainTree - sub_viewport->set_update_mode(SubViewport::UpdateMode::UPDATE_ONCE); - if (EditorResourcePreview::get_singleton()->is_threaded()) { - callable_mp((Node *)EditorNode::get_singleton(), &Node::add_child).call_deferred(sub_viewport, false, Node::InternalMode::INTERNAL_MODE_DISABLED); - callable_mp(camera_3d, &Camera3D::set_current).call_deferred(true); - } else { - EditorNode::get_singleton()->add_child(sub_viewport); - camera_3d->set_current(true); - } - _wait_frame(); - draw_requester.request_and_wait(sub_viewport->get_viewport_rid()); - - if (aborted) { - sub_viewport->queue_free(); - return Ref(); - } - - // Retrieve thumbnail image - Ref thumbnail; - thumbnail = ImageTexture::create_from_image(sub_viewport->get_texture()->get_image()); - - // Clean up - sub_viewport->queue_free(); - - return thumbnail; - } - - if (count_2d > 0) { // Is 2d scene - // If anyone want to rewrite this part to call RenderingServer directly, note that at the time of writing, - // there's a limitation where CanvasItem cannot be rendered outside of the tree. - // See CanvasItem::queue_redraw() and RenderingServer::draw() - int texture_filter = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_filter"); - int texture_repeat = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_repeat"); - - SubViewport *sub_viewport = memnew(SubViewport); - sub_viewport->set_update_mode(SubViewport::UpdateMode::UPDATE_DISABLED); - sub_viewport->set_disable_3d(true); - sub_viewport->set_transparent_background(false); - if (RS::get_singleton()->get_current_rendering_method() != "gl_compatibility") { - sub_viewport->set_msaa_2d(Viewport::MSAA::MSAA_8X); - } - sub_viewport->set_default_canvas_item_texture_filter(Viewport::DefaultCanvasItemTextureFilter(texture_filter)); - sub_viewport->set_default_canvas_item_texture_repeat(Viewport::DefaultCanvasItemTextureRepeat(texture_repeat)); - Ref world; - world.instantiate(); - sub_viewport->set_world_2d(world); - sub_viewport->add_child(p_scene); - - _setup_scene_2d(p_scene); - _hide_gui_in_scene(p_scene); - - // Preview camera - Camera2D *camera = memnew(Camera2D); - sub_viewport->add_child(camera); - camera->set_enabled(true); - - // Attach subviewport (following process needs scene to be in tree) - if (EditorResourcePreview::get_singleton()->is_threaded()) { - callable_mp((Node *)EditorNode::get_singleton(), &Node::add_child).call_deferred(sub_viewport, false, Node::InternalMode::INTERNAL_MODE_DISABLED); - callable_mp((Camera2D *)camera, &Camera2D::make_current).call_deferred(); - } else { - EditorNode::get_singleton()->add_child(sub_viewport); - camera->make_current(); - } - _wait_frame(); - - if (aborted) { - sub_viewport->queue_free(); - return Ref(); - } - - // Calculate scene rect - Rect2 scene_rect; - _calculate_scene_rect(p_scene, scene_rect); - Vector2 scene_true_center = scene_rect.get_center(); - - // Place camera 2D - camera->set_position(Point2(scene_true_center)); - - // Render viewport - uint16_t scene_rect_long = MAX(scene_rect.get_size().x, scene_rect.get_size().y); - if (scene_rect_long == 0) { - scene_rect_long = MAX(p_size.x, p_size.y); // Prevent 0 size rect (which causes error) and defaults to thumbnail size. - } - sub_viewport->set_size(p_size); - camera->set_zoom(Vector2(p_size.x / float(scene_rect_long), p_size.y / float(scene_rect_long))); - sub_viewport->set_update_mode(SubViewport::UpdateMode::UPDATE_ONCE); - _wait_frame(); - draw_requester.request_and_wait(sub_viewport->get_viewport_rid()); - - if (aborted) { - sub_viewport->queue_free(); - return Ref(); - } - - // Retrieve thumbnail of 2D (No GUI) - Ref capture_2d = ImageTexture::create_from_image(sub_viewport->get_texture()->get_image()); - capture_2d->get_image()->resize(p_size.x, p_size.y); - capture_2d->get_image()->convert(Image::Format::FORMAT_RGBA8); // ALPHA channel is required for image blending - - // Prepare for gui render - callable_mp((Node *)sub_viewport, &Node::remove_child).call_deferred(p_scene); - p_scene->queue_free(); - p_scene = pack->instantiate(); - _setup_scene_2d(p_scene); - _hide_node_2d_in_scene(p_scene); - SubViewport *sub_viewport_gui = memnew(SubViewport); - sub_viewport_gui->set_size(Size2i(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height"))); - sub_viewport_gui->set_update_mode(SubViewport::UpdateMode::UPDATE_DISABLED); - sub_viewport_gui->set_transparent_background(true); - if (RS::get_singleton()->get_current_rendering_method() != "gl_compatibility") { - sub_viewport_gui->set_msaa_2d(Viewport::MSAA::MSAA_8X); - } - sub_viewport_gui->set_default_canvas_item_texture_filter(Viewport::DefaultCanvasItemTextureFilter(texture_filter)); - sub_viewport_gui->set_default_canvas_item_texture_repeat(Viewport::DefaultCanvasItemTextureRepeat(texture_repeat)); - sub_viewport_gui->set_disable_3d(true); - sub_viewport_gui->add_child(p_scene); - - // Render GUI - sub_viewport_gui->set_update_mode(SubViewport::UpdateMode::UPDATE_ONCE); - if (EditorResourcePreview::get_singleton()->is_threaded()) { - callable_mp((Node *)EditorNode::get_singleton(), &Node::add_child).call_deferred(sub_viewport_gui, false, Node::InternalMode::INTERNAL_MODE_DISABLED); - } else { - EditorNode::get_singleton()->add_child(sub_viewport_gui); - } - _wait_frame(); - draw_requester.request_and_wait(sub_viewport_gui->get_viewport_rid()); - - if (aborted) { - sub_viewport->queue_free(); - sub_viewport_gui->queue_free(); - return Ref(); - } - - // Retrieve thumbnail of gui - Ref capture_gui = ImageTexture::create_from_image(sub_viewport_gui->get_texture()->get_image()); - capture_gui->get_image()->resize(p_size.x, p_size.y); - - // Mix 2D, GUI thumbnail images into one - Ref thumbnail; - thumbnail.instantiate(); - Ref thumbnail_image = Image::create_empty(p_size.x, p_size.y, false, Image::Format::FORMAT_RGBA8); // blend_rect needs ALPHA channel to work - thumbnail_image->blend_rect(capture_2d->get_image(), capture_2d->get_image()->get_used_rect(), Point2i(0, 0)); - thumbnail_image->blend_rect(capture_gui->get_image(), capture_gui->get_image()->get_used_rect(), Point2i(0, 0)); - thumbnail->set_image(thumbnail_image); - - // Clean up - sub_viewport->queue_free(); - sub_viewport_gui->queue_free(); - - return thumbnail; - } - - // Is scene without any visuals (No Node2D, Node3D, Control found) - return Ref(); -} - -void EditorPackedScenePreviewPlugin::_setup_scene_3d(Node *p_node) const { - // Do not account any SubViewport at preview scene, as it would not render correctly - if (Object::cast_to(p_node) && p_node->get_parent()) { - p_node->get_parent()->remove_child(p_node); - callable_mp(p_node, &Node::queue_free).call_deferred(); - return; - } - - // Don't let window to popup - Window *window = Object::cast_to(p_node); - if (window) { - window->set_visible(false); - } - - // Make sure no Node2D, Control node is visible (Might occupy large proportion of the thumbnail) - Node2D *n2d = Object::cast_to(p_node); - if (n2d) { - n2d->set_visible(false); - } - - Control *ctrl = Object::cast_to(p_node); - if (ctrl) { - ctrl->set_visible(false); - } - - // Disable skinning for skeleton meshes (animations and skeleton scaling might disturb aabb calculation) - MeshInstance3D *mesh = Object::cast_to(p_node); - if (mesh && mesh->is_visible_in_tree()) { - mesh->set_skeleton_path(NodePath()); - } - - CPUParticles3D *cpu_particles = Object::cast_to(p_node); - if (cpu_particles && cpu_particles->is_visible_in_tree()) { - cpu_particles->set_pre_process_time(cpu_particles->get_lifetime() * 0.5); // Fast forward the particle emission to make it render something - cpu_particles->set_use_local_coordinates(true); // HACK - Now constructs scene outside of tree, using global coords will cause error, this may introduce visual bugs, but is the best solution now - cpu_particles->restart(true); // Keep seed to make simulation persistent - } - - GPUParticles3D *gpu_particles = Object::cast_to(p_node); - if (gpu_particles && gpu_particles->is_visible_in_tree()) { - // Convert to CPUParticles (As GPUParticles can't be rendered correctly in thumbnails, don't know why) - CPUParticles3D *gtc_particles = memnew(CPUParticles3D); // GPU to CPU particles - gtc_particles->convert_from_particles(gpu_particles); - gpu_particles->add_child(gtc_particles); // So the created CPUParticles instance will be freed later we call queue_free() on the preview scene - - // Setup CPUParticles - gtc_particles->set_pre_process_time(gtc_particles->get_lifetime() * 0.5); - gtc_particles->set_use_local_coordinates(true); - gtc_particles->restart(true); - } - - for (int i = 0; i < p_node->get_child_count(); i++) { - _setup_scene_3d(p_node->get_child(i)); - } -} - -void EditorPackedScenePreviewPlugin::_setup_scene_2d(Node *p_node) const { - // Do not account any SubViewport at preview scene, as it would not render correctly - if (Object::cast_to(p_node) && p_node->get_parent()) { - p_node->get_parent()->remove_child(p_node); - callable_mp(p_node, &Node::queue_free).call_deferred(); - return; - } - - // Don't let window to popup - Window *window = Object::cast_to(p_node); - if (window) { - window->set_visible(false); - } - - for (int i = 0; i < p_node->get_child_count(); i++) { - _setup_scene_2d(p_node->get_child(i)); - } -} - -void EditorPackedScenePreviewPlugin::_count_node_types(Node *p_node, int &r_c2d, int &r_c3d, int &r_clight3d) const { - if (p_node->is_class("Control") || p_node->is_class("Node2D")) { - r_c2d++; - } - if (p_node->is_class("Node3D")) { - r_c3d++; - } - if (p_node->is_class("Light3D")) { - r_clight3d++; - } - for (int i = 0; i < p_node->get_child_count(); i++) { - // Do not count anything under SubViewport node, those children are irrelevant for determining if the scene is 2D or 3D. - if (p_node->get_child(i)->is_class("SubViewport")) { - continue; - } - _count_node_types(p_node->get_child(i), r_c2d, r_c3d, r_clight3d); - } -} - -void EditorPackedScenePreviewPlugin::_calculate_scene_rect(Node *p_node, Rect2 &r_rect) const { - // NOTE: There's no universal way to get the exact global rect as a Node2D, so we dig into subclasses one by one - - // NOTE: - // 1. Sprite2D::position by default is at the **center** of the sprite. (with offset == (0,0) AND centered == true) - // 2. Rect2::position is at the **up-left** of the rect - // 3. AABB::position is at the **bottom-left-forward** of the bounding box - // - // calculation below is done with these in mind. - - Rect2 n2d_rect; // The rect of the current iterating Node2D - - Sprite2D *sprite = Object::cast_to(p_node); - if (sprite && sprite->is_visible_in_tree()) { - n2d_rect.size = sprite->get_global_scale() * sprite->get_rect().size; - n2d_rect.position = sprite->get_global_position() + sprite->get_offset() * sprite->get_global_scale(); - if (sprite->is_centered()) { - n2d_rect.position -= n2d_rect.size / 2.0f; - } - } - - AnimatedSprite2D *anim_sprite = Object::cast_to(p_node); - if (anim_sprite && anim_sprite->is_visible_in_tree()) { - if (anim_sprite->get_sprite_frames().is_valid()) { - Ref current_frame_tex = anim_sprite->get_sprite_frames()->get_frame_texture(anim_sprite->get_animation(), anim_sprite->get_frame()); - - if (current_frame_tex.is_valid()) { - n2d_rect.size = current_frame_tex->get_size() * anim_sprite->get_global_scale(); - n2d_rect.position = anim_sprite->get_global_position() + anim_sprite->get_offset() * anim_sprite->get_global_scale(); - if (anim_sprite->is_centered()) { - n2d_rect.position -= n2d_rect.size / 2.0f; - } - } - } - } - - MeshInstance2D *mesh2d = Object::cast_to(p_node); - if (mesh2d && mesh2d->is_visible_in_tree()) { - // NOTE: Conversion is 1m = 1px (before 2d scale) - Ref mesh = mesh2d->get_mesh(); - - if (mesh.is_valid()) { - // Discard z axis (depth) and only get length of mesh in x,y axis - n2d_rect.size.x = (mesh->get_aabb().get_end() - mesh->get_aabb().position).x; - n2d_rect.size.y = (mesh->get_aabb().get_end() - mesh->get_aabb().position).y; - n2d_rect.size *= mesh2d->get_global_scale(); - - // Account for mesh offset in 3d space when calculating rect2 - n2d_rect.position.x = mesh2d->get_global_position().x + mesh->get_aabb().position.x * mesh2d->get_global_scale().x; // AABB::position is bottom-left - n2d_rect.position.y = mesh2d->get_global_position().y + mesh->get_aabb().position.y * mesh2d->get_global_scale().y; - } - } - - MultiMeshInstance2D *mmesh2d = Object::cast_to(p_node); - if (mmesh2d && mmesh2d->is_visible_in_tree()) { - // Basically the same procedure as MeshInstance2D. - Ref mmesh = mmesh2d->get_multimesh(); - - if (mmesh.is_valid()) { - n2d_rect.size.x = (mmesh->get_aabb().get_end() - mmesh->get_aabb().position).x; - n2d_rect.size.y = (mmesh->get_aabb().get_end() - mmesh->get_aabb().position).y; - n2d_rect.size *= mmesh2d->get_global_scale(); - - n2d_rect.position.x = mmesh2d->get_global_position().x + mmesh->get_aabb().position.x * mmesh2d->get_global_scale().x; - n2d_rect.position.y = mmesh2d->get_global_position().y + mmesh->get_aabb().position.y * mmesh2d->get_global_scale().y; - } - } - - TileMapLayer *tile_map = Object::cast_to(p_node); - if (tile_map && tile_map->is_visible_in_tree()) { - // NOTE: TileMapLayer::get_used_rect() only count cells, not their actual pixel size - - if (tile_map->get_tile_set().is_valid()) { - Size2 tile_size = tile_map->get_tile_set()->get_tile_size(); // Tile map cell pixel size (x,y). - Rect2 tile_rect = tile_map->get_used_rect(); // Unit is in cells, not pixels! - - n2d_rect.position = tile_map->get_global_position() + tile_rect.position * tile_size * tile_map->get_global_scale(); // Accounts tilemap offset - n2d_rect.size = tile_rect.size * tile_size * tile_map->get_global_scale(); - } - } - - Polygon2D *poly2d = Object::cast_to(p_node); - if (poly2d && poly2d->is_visible_in_tree()) { - PackedVector2Array polygon = poly2d->get_polygon(); - - if (polygon.size() > 2) { // Abort if there's no surface (min = 3 verts) - // Calculate bounds - float max_x = polygon[0].x; - float min_x = polygon[0].x; - float max_y = polygon[0].y; - float min_y = polygon[0].y; - for (int i = 0; i < polygon.size(); i++) { - if (polygon[i].x > max_x) { - max_x = polygon[i].x; - } - if (polygon[i].x < min_x) { - min_x = polygon[i].x; - } - - if (polygon[i].y > max_y) { - max_y = polygon[i].y; - } - if (polygon[i].y < min_y) { - min_y = polygon[i].y; - } - } - - Rect2 poly_rect = Rect2(min_x, min_y, max_x - min_x, max_y - min_y); - - n2d_rect.position = poly2d->get_global_position() + poly2d->get_offset() * poly2d->get_global_scale(); - n2d_rect.position += poly_rect.position * poly2d->get_global_scale(); - n2d_rect.size = poly_rect.size * poly2d->get_global_scale(); - } - } - - Line2D *line2d = Object::cast_to(p_node); - if (line2d && line2d->is_visible_in_tree()) { - // The same procedure as Polygon2D - PackedVector2Array points = line2d->get_points(); - - if (line2d->get_point_count() > 1) { // Abort if there's no line drawn - // Calculate bounds - float max_x = points[0].x; - float min_x = points[0].x; - float max_y = points[0].y; - float min_y = points[0].y; - for (int i = 0; i < points.size(); i++) { - if (points[i].x > max_x) { - max_x = points[i].x; - } - if (points[i].x < min_x) { - min_x = points[i].x; - } - - if (points[i].y > max_y) { - max_y = points[i].y; - } - if (points[i].y < min_y) { - min_y = points[i].y; - } - } - - Rect2 line2d_rect = Rect2(min_x, min_y, max_x - min_x, max_y - min_y); - - n2d_rect.position = line2d->get_global_position(); - n2d_rect.position += line2d_rect.position * line2d->get_global_scale(); - n2d_rect.size = line2d_rect.size * line2d->get_global_scale(); - n2d_rect.size += Size2(line2d->get_width(), line2d->get_width()) / 2.0f; // account for line width - } - } - - TouchScreenButton *btn = Object::cast_to(p_node); - if (btn && btn->is_visible_in_tree()) { - Ref btn_tex = btn->get_texture_normal(); - - if (btn_tex.is_valid()) { // Abort if there's no normal texture for this button (won't display anything) - n2d_rect.position = btn->get_global_position(); // It's not possible to offset image in this node - n2d_rect.size = btn_tex->get_size() * btn->get_global_scale(); - } - } - - // Merge the calculated node 2d rect - if (r_rect.get_size().length_squared() == 0.0f) { // Avoid accounting scene origin (0,0) into scene rect. - r_rect = n2d_rect.abs(); } else { - r_rect = r_rect.merge(n2d_rect.abs()); + return Ref(); } - - for (int i = 0; i < p_node->get_child_count(); i++) { - _calculate_scene_rect(p_node->get_child(i), r_rect); - } -} - -void EditorPackedScenePreviewPlugin::_hide_node_2d_in_scene(Node *p_node) const { - // NOTE: Irreversible (cannot unhide nodes after this) - // We cannot simple hide() since it will affect all its children (may contain Control nodes) - - if (p_node->is_class("Node2D")) { - Node2D *n2d = Object::cast_to(p_node); - n2d->set_self_modulate(Color(0.0f, 0.0f, 0.0f, 0.0f)); - } - - for (int i = 0; i < p_node->get_child_count(); i++) { - _hide_node_2d_in_scene(p_node->get_child(i)); - } -} - -void EditorPackedScenePreviewPlugin::_hide_gui_in_scene(Node *p_node) const { - // NOTE: Irreversible (cannot unhide nodes after this) - // We cannot simply hide() since it will affect all its children (may contain Node2D nodes) - - if (p_node->is_class("Control")) { - Control *ctrl = Object::cast_to(p_node); - ctrl->set_self_modulate(Color(0.0f, 0.0f, 0.0f, 0.0f)); - } - - for (int i = 0; i < p_node->get_child_count(); i++) { - _hide_gui_in_scene(p_node->get_child(i)); - } -} - -// Hacky implementation, remove this when draw_requester.request_and_wait() is sufficient to render previews properly. -// Is needed for 2 reason: -// 1. Scene preview requires adding scene to tree and wait for RenderingServer to redraw. -// 2. To resolve some rendering bugs by waiting extra frames. -void EditorPackedScenePreviewPlugin::_wait_frame() const { - const uint64_t prev_frame = Engine::get_singleton()->get_frames_drawn(); - while (Engine::get_singleton()->get_frames_drawn() - prev_frame < 1) { - if (!EditorResourcePreview::get_singleton()->is_threaded()) { - // Is running this on main thread, iterate main loop (or will get stuck here forever) - DisplayServer::get_singleton()->process_events(); - Main::iteration(); - } - if (aborted) { - break; - } - continue; - } -} - -void EditorPackedScenePreviewPlugin::_calculate_scene_aabb(Node *p_node, AABB &r_aabb) const { - GeometryInstance3D *g3d = Object::cast_to(p_node); - if (g3d && g3d->is_visible_in_tree()) { // Use this because VisualInstance3D may have derived classes that are non-graphical (probes, volumes) - AABB node_aabb = _get_global_transform_3d(g3d).xform(g3d->get_aabb()); - r_aabb.merge_with(node_aabb); - } - - CPUParticles3D *cpu_particles = Object::cast_to(p_node); - if (cpu_particles && cpu_particles->is_visible_in_tree()) { // CPUParticles3D does not calculate particle bounds, so do it here - // Account the furthest position where particles can go - Vector3 particle_destination = _get_global_transform_3d(cpu_particles).origin; - particle_destination += cpu_particles->get_direction() * cpu_particles->get_param_max(CPUParticles3D::PARAM_INITIAL_LINEAR_VELOCITY); - r_aabb.expand_to(particle_destination * 0.5); - r_aabb.expand_to(particle_destination * -0.5); - } - - GPUParticles3D *gpu_particles = Object::cast_to(p_node); - if (gpu_particles && gpu_particles->is_visible_in_tree()) { - r_aabb.merge_with(_get_global_transform_3d(gpu_particles).xform(gpu_particles->get_visibility_aabb())); - } - - for (int i = 0; i < p_node->get_child_count(); i++) { - _calculate_scene_aabb(p_node->get_child(i), r_aabb); - } -} - -Transform3D EditorPackedScenePreviewPlugin::_get_global_transform_3d(Node *p_n3d) const { - // Designed to work even if node is outside the tree (is_inside_tree() != true) - Transform3D global_transform; - Array parents; - - if (!p_n3d->is_class("Node3D")) { - ERR_PRINT("Expected a Node3D node as argument"); - return global_transform; - } - - Node *p_loop_node = p_n3d; - while (p_loop_node != nullptr) { - if (p_loop_node->is_class("Node3D")) { - parents.append(p_loop_node); - } - p_loop_node = p_loop_node->get_parent(); - } - - parents.reverse(); - - for (int i = 0; i < parents.size(); i++) { - Node3D *p_parent = Object::cast_to(parents[i]); - if (i == 0) { - global_transform = p_parent->get_transform(); - continue; - } - global_transform *= p_parent->get_transform(); - } - - return global_transform; -} - -bool EditorPackedScenePreviewPlugin::_setup_packed_scene(Ref p_pack) const { - // Refer to SceneState in packed_scene.cpp to see how PackedScene is managed underhood. - - // Sanitize - Dictionary bundle = p_pack->get_state()->get_bundled_scene(); - ERR_FAIL_COND_V(!bundle.has("names"), false); - ERR_FAIL_COND_V(!bundle.has("variants"), false); - ERR_FAIL_COND_V(!bundle.has("node_count"), false); - ERR_FAIL_COND_V(!bundle.has("nodes"), false); - ERR_FAIL_COND_V(!bundle.has("conn_count"), false); - ERR_FAIL_COND_V(!bundle.has("conns"), false); - - const uint8_t supported_version = 3; - uint8_t current_version = bundle.get("version", 1); - - if (current_version > supported_version) { - WARN_PRINT_ONCE(vformat("Scene thumbnail creation was built upon PackedScene with version %d, but the version has changed to %d now.", supported_version, current_version)); - // And assume it's safe to continue, there should have no reason to change the main structure of PackedScene - } - - // Find and remove variants in scene - const Ref