Path: blob/master/editor/inspector/editor_resource_preview.cpp
9896 views
/**************************************************************************/1/* editor_resource_preview.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "editor_resource_preview.h"3132#include "core/config/project_settings.h"33#include "core/io/file_access.h"34#include "core/io/resource_loader.h"35#include "core/io/resource_saver.h"36#include "core/variant/variant_utility.h"37#include "editor/editor_node.h"38#include "editor/editor_string_names.h"39#include "editor/file_system/editor_paths.h"40#include "editor/settings/editor_settings.h"41#include "editor/themes/editor_scale.h"42#include "scene/main/window.h"43#include "scene/resources/image_texture.h"44#include "servers/rendering/rendering_server_globals.h"4546bool EditorResourcePreviewGenerator::handles(const String &p_type) const {47bool success = false;48if (GDVIRTUAL_CALL(_handles, p_type, success)) {49return success;50}51ERR_FAIL_V_MSG(false, "EditorResourcePreviewGenerator::_handles needs to be overridden.");52}5354Ref<Texture2D> EditorResourcePreviewGenerator::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {55Ref<Texture2D> preview;56if (GDVIRTUAL_CALL(_generate, p_from, p_size, p_metadata, preview)) {57return preview;58}59ERR_FAIL_V_MSG(Ref<Texture2D>(), "EditorResourcePreviewGenerator::_generate needs to be overridden.");60}6162Ref<Texture2D> EditorResourcePreviewGenerator::generate_from_path(const String &p_path, const Size2 &p_size, Dictionary &p_metadata) const {63Ref<Texture2D> preview;64if (GDVIRTUAL_CALL(_generate_from_path, p_path, p_size, p_metadata, preview)) {65return preview;66}6768Ref<Resource> res = ResourceLoader::load(p_path);69if (res.is_null()) {70return res;71}72return generate(res, p_size, p_metadata);73}7475bool EditorResourcePreviewGenerator::generate_small_preview_automatically() const {76bool success = false;77GDVIRTUAL_CALL(_generate_small_preview_automatically, success);78return success;79}8081bool EditorResourcePreviewGenerator::can_generate_small_preview() const {82bool success = false;83GDVIRTUAL_CALL(_can_generate_small_preview, success);84return success;85}8687void EditorResourcePreviewGenerator::_bind_methods() {88GDVIRTUAL_BIND(_handles, "type");89GDVIRTUAL_BIND(_generate, "resource", "size", "metadata");90GDVIRTUAL_BIND(_generate_from_path, "path", "size", "metadata");91GDVIRTUAL_BIND(_generate_small_preview_automatically);92GDVIRTUAL_BIND(_can_generate_small_preview);93}9495void EditorResourcePreviewGenerator::DrawRequester::request_and_wait(RID p_viewport) {96Callable request_vp_update_once = callable_mp(RS::get_singleton(), &RS::viewport_set_update_mode).bind(p_viewport, RS::VIEWPORT_UPDATE_ONCE);9798if (EditorResourcePreview::get_singleton()->is_threaded()) {99RS::get_singleton()->connect(SNAME("frame_pre_draw"), request_vp_update_once, Object::CONNECT_ONE_SHOT);100RS::get_singleton()->request_frame_drawn_callback(callable_mp(this, &EditorResourcePreviewGenerator::DrawRequester::_post_semaphore));101102semaphore.wait();103} else {104// Avoid the main viewport and children being redrawn.105SceneTree *st = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop());106ERR_FAIL_NULL_MSG(st, "Editor's MainLoop is not a SceneTree. This is a bug.");107RID root_vp = st->get_root()->get_viewport_rid();108RenderingServer::get_singleton()->viewport_set_active(root_vp, false);109110request_vp_update_once.call();111RS::get_singleton()->draw(false);112113// Let main viewport and children be drawn again.114RenderingServer::get_singleton()->viewport_set_active(root_vp, true);115}116}117118void EditorResourcePreviewGenerator::DrawRequester::abort() {119if (EditorResourcePreview::get_singleton()->is_threaded()) {120semaphore.post();121}122}123124Variant EditorResourcePreviewGenerator::DrawRequester::_post_semaphore() {125semaphore.post();126return Variant(); // Needed because of how the callback is used.127}128129bool EditorResourcePreview::is_threaded() const {130return RSG::rasterizer->can_create_resources_async();131}132133void EditorResourcePreview::_thread_func(void *ud) {134EditorResourcePreview *erp = (EditorResourcePreview *)ud;135erp->_thread();136}137138void EditorResourcePreview::_preview_ready(const String &p_path, int p_hash, const Ref<Texture2D> &p_texture, const Ref<Texture2D> &p_small_texture, ObjectID id, const StringName &p_func, const Variant &p_ud, const Dictionary &p_metadata) {139{140MutexLock lock(preview_mutex);141142uint64_t modified_time = 0;143144if (!p_path.begins_with("ID:")) {145modified_time = FileAccess::get_modified_time(p_path);146String import_path = p_path + ".import";147if (FileAccess::exists(import_path)) {148modified_time = MAX(modified_time, FileAccess::get_modified_time(import_path));149}150}151152Item item;153item.preview = p_texture;154item.small_preview = p_small_texture;155item.last_hash = p_hash;156item.modified_time = modified_time;157item.preview_metadata = p_metadata;158159cache[p_path] = item;160}161162Callable(id, p_func).call_deferred(p_path, p_texture, p_small_texture, p_ud);163}164165void EditorResourcePreview::_generate_preview(Ref<ImageTexture> &r_texture, Ref<ImageTexture> &r_small_texture, const QueueItem &p_item, const String &cache_base, Dictionary &p_metadata) {166String type;167168uint64_t started_at = OS::get_singleton()->get_ticks_usec();169170if (p_item.resource.is_valid()) {171type = p_item.resource->get_class();172} else {173type = ResourceLoader::get_resource_type(p_item.path);174}175176if (type.is_empty()) {177r_texture = Ref<ImageTexture>();178r_small_texture = Ref<ImageTexture>();179180if (is_print_verbose_enabled()) {181print_line(vformat("Generated '%s' preview in %d usec", p_item.path, OS::get_singleton()->get_ticks_usec() - started_at));182}183return; //could not guess type184}185186int thumbnail_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");187thumbnail_size *= EDSCALE;188189r_texture = Ref<ImageTexture>();190r_small_texture = Ref<ImageTexture>();191192for (int i = 0; i < preview_generators.size(); i++) {193if (!preview_generators[i]->handles(type)) {194continue;195}196197Ref<Texture2D> generated;198if (p_item.resource.is_valid()) {199generated = preview_generators.write[i]->generate(p_item.resource, Vector2(thumbnail_size, thumbnail_size), p_metadata);200} else {201generated = preview_generators.write[i]->generate_from_path(p_item.path, Vector2(thumbnail_size, thumbnail_size), p_metadata);202}203r_texture = generated;204205if (preview_generators[i]->can_generate_small_preview()) {206Ref<Texture2D> generated_small;207Dictionary d;208if (p_item.resource.is_valid()) {209generated_small = preview_generators.write[i]->generate(p_item.resource, Vector2(small_thumbnail_size, small_thumbnail_size), d);210} else {211generated_small = preview_generators.write[i]->generate_from_path(p_item.path, Vector2(small_thumbnail_size, small_thumbnail_size), d);212}213r_small_texture = generated_small;214}215216if (r_small_texture.is_null() && r_texture.is_valid() && preview_generators[i]->generate_small_preview_automatically()) {217Ref<Image> small_image = r_texture->get_image()->duplicate();218Vector2i new_size = Vector2i(1, 1) * small_thumbnail_size;219const real_t aspect = small_image->get_size().aspect();220if (aspect > 1.0) {221new_size.y = MAX(1, new_size.y / aspect);222} else if (aspect < 1.0) {223new_size.x = MAX(1, new_size.x * aspect);224}225small_image->resize(new_size.x, new_size.y, Image::INTERPOLATE_CUBIC);226227// Make sure the image is always square.228if (aspect != 1.0) {229Ref<Image> rect = small_image;230const Vector2i rect_size = rect->get_size();231small_image = Image::create_empty(small_thumbnail_size, small_thumbnail_size, false, rect->get_format());232// Blit the rectangle in the center of the square.233small_image->blit_rect(rect, Rect2i(Vector2i(), rect_size), (Vector2i(1, 1) * small_thumbnail_size - rect_size) / 2);234}235236r_small_texture.instantiate();237r_small_texture->set_image(small_image);238}239240if (generated.is_valid()) {241break;242}243}244245if (p_item.resource.is_null()) {246// Cache the preview in case it's a resource on disk.247if (r_texture.is_valid()) {248// Wow it generated a preview... save cache.249bool has_small_texture = r_small_texture.is_valid();250ResourceSaver::save(r_texture, cache_base + ".png");251if (has_small_texture) {252ResourceSaver::save(r_small_texture, cache_base + "_small.png");253}254Ref<FileAccess> f = FileAccess::open(cache_base + ".txt", FileAccess::WRITE);255ERR_FAIL_COND_MSG(f.is_null(), "Cannot create file '" + cache_base + ".txt'. Check user write permissions.");256257uint64_t modtime = FileAccess::get_modified_time(p_item.path);258String import_path = p_item.path + ".import";259if (FileAccess::exists(import_path)) {260modtime = MAX(modtime, FileAccess::get_modified_time(import_path));261}262263_write_preview_cache(f, thumbnail_size, has_small_texture, modtime, FileAccess::get_md5(p_item.path), p_metadata);264}265}266267if (is_print_verbose_enabled()) {268print_line(vformat("Generated '%s' preview in %d usec", p_item.path, OS::get_singleton()->get_ticks_usec() - started_at));269}270}271272const Dictionary EditorResourcePreview::get_preview_metadata(const String &p_path) const {273ERR_FAIL_COND_V(!cache.has(p_path), Dictionary());274return cache[p_path].preview_metadata;275}276277void EditorResourcePreview::_iterate() {278preview_mutex.lock();279280if (queue.is_empty()) {281preview_mutex.unlock();282return;283}284285QueueItem item = queue.front()->get();286queue.pop_front();287288if (cache.has(item.path)) {289Item cached_item = cache[item.path];290// Already has it because someone loaded it, just let it know it's ready.291_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);292preview_mutex.unlock();293return;294}295preview_mutex.unlock();296297Ref<ImageTexture> texture;298Ref<ImageTexture> small_texture;299300int thumbnail_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");301thumbnail_size *= EDSCALE;302303if (item.resource.is_valid()) {304Dictionary preview_metadata;305_generate_preview(texture, small_texture, item, String(), preview_metadata);306_preview_ready(item.path, item.resource->hash_edited_version_for_preview(), texture, small_texture, item.id, item.function, item.userdata, preview_metadata);307return;308}309310Dictionary preview_metadata;311String temp_path = EditorPaths::get_singleton()->get_cache_dir();312String cache_base = ProjectSettings::get_singleton()->globalize_path(item.path).md5_text();313cache_base = temp_path.path_join("resthumb-" + cache_base);314315// Does not have it, try to load a cached thumbnail.316317String file = cache_base + ".txt";318Ref<FileAccess> f = FileAccess::open(file, FileAccess::READ);319if (f.is_null()) {320// No cache found, generate.321_generate_preview(texture, small_texture, item, cache_base, preview_metadata);322} else {323uint64_t modtime = FileAccess::get_modified_time(item.path);324String import_path = item.path + ".import";325if (FileAccess::exists(import_path)) {326modtime = MAX(modtime, FileAccess::get_modified_time(import_path));327}328329int tsize;330bool has_small_texture;331uint64_t last_modtime;332String hash;333bool outdated;334_read_preview_cache(f, &tsize, &has_small_texture, &last_modtime, &hash, &preview_metadata, &outdated);335336bool cache_valid = true;337338if (tsize != thumbnail_size) {339cache_valid = false;340f.unref();341} else if (outdated) {342cache_valid = false;343f.unref();344} else if (last_modtime != modtime) {345String last_md5 = f->get_line();346String md5 = FileAccess::get_md5(item.path);347f.unref();348349if (last_md5 != md5) {350cache_valid = false;351} else {352// Update modified time.353354Ref<FileAccess> f2 = FileAccess::open(file, FileAccess::WRITE);355if (f2.is_null()) {356// Not returning as this would leave the thread hanging and would require357// some proper cleanup/disabling of resource preview generation.358ERR_PRINT("Cannot create file '" + file + "'. Check user write permissions.");359} else {360_write_preview_cache(f2, thumbnail_size, has_small_texture, modtime, md5, preview_metadata);361}362}363} else {364f.unref();365}366367if (cache_valid) {368Ref<Image> img;369img.instantiate();370Ref<Image> small_img;371small_img.instantiate();372373if (img->load(cache_base + ".png") != OK) {374cache_valid = false;375} else {376texture.instantiate();377texture->set_image(img);378379if (has_small_texture) {380if (small_img->load(cache_base + "_small.png") != OK) {381cache_valid = false;382} else {383small_texture.instantiate();384small_texture->set_image(small_img);385}386}387}388}389390if (!cache_valid) {391_generate_preview(texture, small_texture, item, cache_base, preview_metadata);392}393}394_preview_ready(item.path, 0, texture, small_texture, item.id, item.function, item.userdata, preview_metadata);395}396397void EditorResourcePreview::_write_preview_cache(Ref<FileAccess> p_file, int p_thumbnail_size, bool p_has_small_texture, uint64_t p_modified_time, const String &p_hash, const Dictionary &p_metadata) {398p_file->store_line(itos(p_thumbnail_size));399p_file->store_line(itos(p_has_small_texture));400p_file->store_line(itos(p_modified_time));401p_file->store_line(p_hash);402p_file->store_line(VariantUtilityFunctions::var_to_str(p_metadata).replace_char('\n', ' '));403p_file->store_line(itos(CURRENT_METADATA_VERSION));404}405406void EditorResourcePreview::_read_preview_cache(Ref<FileAccess> 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) {407*r_thumbnail_size = p_file->get_line().to_int();408*r_has_small_texture = p_file->get_line().to_int();409*r_modified_time = p_file->get_line().to_int();410*r_hash = p_file->get_line();411*r_metadata = VariantUtilityFunctions::str_to_var(p_file->get_line());412*r_outdated = p_file->get_line().to_int() < CURRENT_METADATA_VERSION;413}414415void EditorResourcePreview::_thread() {416exited.clear();417while (!exiting.is_set()) {418preview_sem.wait();419_iterate();420}421exited.set();422}423424void EditorResourcePreview::_idle_callback() {425if (!singleton) {426// Just in case the shutdown of the editor involves the deletion of the singleton427// happening while additional idle callbacks can happen.428return;429}430431// Process preview tasks, trying to leave a little bit of responsiveness worst case.432uint64_t start = OS::get_singleton()->get_ticks_msec();433while (!singleton->queue.is_empty() && OS::get_singleton()->get_ticks_msec() - start < 100) {434singleton->_iterate();435}436}437438void EditorResourcePreview::_update_thumbnail_sizes() {439if (small_thumbnail_size == -1) {440// Kind of a workaround to retrieve the default icon size.441small_thumbnail_size = EditorNode::get_singleton()->get_editor_theme()->get_icon(SNAME("Object"), EditorStringName(EditorIcons))->get_width();442}443}444445EditorResourcePreview::PreviewItem EditorResourcePreview::get_resource_preview_if_available(const String &p_path) {446PreviewItem item;447{448MutexLock lock(preview_mutex);449450HashMap<String, EditorResourcePreview::Item>::Iterator I = cache.find(p_path);451if (!I) {452return item;453}454455EditorResourcePreview::Item &cached_item = I->value;456item.preview = cached_item.preview;457item.small_preview = cached_item.small_preview;458}459preview_sem.post();460return item;461}462463void EditorResourcePreview::queue_edited_resource_preview(const Ref<Resource> &p_res, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {464ERR_FAIL_NULL(p_receiver);465ERR_FAIL_COND(p_res.is_null());466_update_thumbnail_sizes();467468{469MutexLock lock(preview_mutex);470471String path_id = "ID:" + itos(p_res->get_instance_id());472473if (cache.has(path_id) && cache[path_id].last_hash == p_res->hash_edited_version_for_preview()) {474p_receiver->call(p_receiver_func, path_id, cache[path_id].preview, cache[path_id].small_preview, p_userdata);475return;476}477478cache.erase(path_id); //erase if exists, since it will be regen479480QueueItem item;481item.function = p_receiver_func;482item.id = p_receiver->get_instance_id();483item.resource = p_res;484item.path = path_id;485item.userdata = p_userdata;486487queue.push_back(item);488}489preview_sem.post();490}491492void EditorResourcePreview::queue_resource_preview(const String &p_path, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {493ERR_FAIL_NULL(p_receiver);494_update_thumbnail_sizes();495496{497MutexLock lock(preview_mutex);498499if (cache.has(p_path)) {500p_receiver->call(p_receiver_func, p_path, cache[p_path].preview, cache[p_path].small_preview, p_userdata);501return;502}503504QueueItem item;505item.function = p_receiver_func;506item.id = p_receiver->get_instance_id();507item.path = p_path;508item.userdata = p_userdata;509510queue.push_back(item);511}512preview_sem.post();513}514515void EditorResourcePreview::add_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {516preview_generators.push_back(p_generator);517}518519void EditorResourcePreview::remove_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {520preview_generators.erase(p_generator);521}522523EditorResourcePreview *EditorResourcePreview::get_singleton() {524return singleton;525}526527void EditorResourcePreview::_bind_methods() {528ClassDB::bind_method(D_METHOD("queue_resource_preview", "path", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_resource_preview);529ClassDB::bind_method(D_METHOD("queue_edited_resource_preview", "resource", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_edited_resource_preview);530ClassDB::bind_method(D_METHOD("add_preview_generator", "generator"), &EditorResourcePreview::add_preview_generator);531ClassDB::bind_method(D_METHOD("remove_preview_generator", "generator"), &EditorResourcePreview::remove_preview_generator);532ClassDB::bind_method(D_METHOD("check_for_invalidation", "path"), &EditorResourcePreview::check_for_invalidation);533534ADD_SIGNAL(MethodInfo("preview_invalidated", PropertyInfo(Variant::STRING, "path")));535}536537void EditorResourcePreview::_notification(int p_what) {538switch (p_what) {539case NOTIFICATION_EXIT_TREE: {540stop();541} break;542}543}544545void EditorResourcePreview::check_for_invalidation(const String &p_path) {546bool call_invalidated = false;547{548MutexLock lock(preview_mutex);549550if (cache.has(p_path)) {551uint64_t modified_time = FileAccess::get_modified_time(p_path);552String import_path = p_path + ".import";553if (FileAccess::exists(import_path)) {554modified_time = MAX(modified_time, FileAccess::get_modified_time(import_path));555}556557if (modified_time != cache[p_path].modified_time) {558cache.erase(p_path);559call_invalidated = true;560}561}562}563564if (call_invalidated) { //do outside mutex565call_deferred(SNAME("emit_signal"), "preview_invalidated", p_path);566}567}568569void EditorResourcePreview::start() {570if (DisplayServer::get_singleton()->get_name() == "headless") {571return;572}573574if (is_threaded()) {575ERR_FAIL_COND_MSG(thread.is_started(), "Thread already started.");576thread.start(_thread_func, this);577} else {578SceneTree *st = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop());579ERR_FAIL_NULL_MSG(st, "Editor's MainLoop is not a SceneTree. This is a bug.");580st->add_idle_callback(&_idle_callback);581}582}583584void EditorResourcePreview::stop() {585if (is_threaded()) {586if (thread.is_started()) {587exiting.set();588preview_sem.post();589590for (int i = 0; i < preview_generators.size(); i++) {591preview_generators.write[i]->abort();592}593594while (!exited.is_set()) {595// Sync pending work.596OS::get_singleton()->delay_usec(10000);597RenderingServer::get_singleton()->sync();598MessageQueue::get_singleton()->flush();599}600601thread.wait_to_finish();602}603}604}605606EditorResourcePreview::EditorResourcePreview() {607singleton = this;608}609610EditorResourcePreview::~EditorResourcePreview() {611stop();612}613614615