editor_resource_preview.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /**************************************************************************/
  2. /* editor_resource_preview.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 "editor_resource_preview.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/file_access.h"
  33. #include "core/io/resource_loader.h"
  34. #include "core/io/resource_saver.h"
  35. #include "core/object/message_queue.h"
  36. #include "core/variant/variant_utility.h"
  37. #include "editor/editor_node.h"
  38. #include "editor/editor_paths.h"
  39. #include "editor/editor_scale.h"
  40. #include "editor/editor_settings.h"
  41. #include "editor/editor_string_names.h"
  42. #include "scene/resources/image_texture.h"
  43. bool EditorResourcePreviewGenerator::handles(const String &p_type) const {
  44. bool success = false;
  45. if (GDVIRTUAL_CALL(_handles, p_type, success)) {
  46. return success;
  47. }
  48. ERR_FAIL_V_MSG(false, "EditorResourcePreviewGenerator::_handles needs to be overridden.");
  49. }
  50. Ref<Texture2D> EditorResourcePreviewGenerator::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  51. Ref<Texture2D> preview;
  52. if (GDVIRTUAL_CALL(_generate, p_from, p_size, p_metadata, preview)) {
  53. return preview;
  54. }
  55. ERR_FAIL_V_MSG(Ref<Texture2D>(), "EditorResourcePreviewGenerator::_generate needs to be overridden.");
  56. }
  57. Ref<Texture2D> EditorResourcePreviewGenerator::generate_from_path(const String &p_path, const Size2 &p_size, Dictionary &p_metadata) const {
  58. Ref<Texture2D> preview;
  59. if (GDVIRTUAL_CALL(_generate_from_path, p_path, p_size, p_metadata, preview)) {
  60. return preview;
  61. }
  62. Ref<Resource> res = ResourceLoader::load(p_path);
  63. if (!res.is_valid()) {
  64. return res;
  65. }
  66. return generate(res, p_size, p_metadata);
  67. }
  68. bool EditorResourcePreviewGenerator::generate_small_preview_automatically() const {
  69. bool success = false;
  70. GDVIRTUAL_CALL(_generate_small_preview_automatically, success);
  71. return success;
  72. }
  73. bool EditorResourcePreviewGenerator::can_generate_small_preview() const {
  74. bool success = false;
  75. GDVIRTUAL_CALL(_can_generate_small_preview, success);
  76. return success;
  77. }
  78. void EditorResourcePreviewGenerator::_bind_methods() {
  79. GDVIRTUAL_BIND(_handles, "type");
  80. GDVIRTUAL_BIND(_generate, "resource", "size", "metadata");
  81. GDVIRTUAL_BIND(_generate_from_path, "path", "size", "metadata");
  82. GDVIRTUAL_BIND(_generate_small_preview_automatically);
  83. GDVIRTUAL_BIND(_can_generate_small_preview);
  84. }
  85. EditorResourcePreviewGenerator::EditorResourcePreviewGenerator() {
  86. }
  87. EditorResourcePreview *EditorResourcePreview::singleton = nullptr;
  88. void EditorResourcePreview::_thread_func(void *ud) {
  89. EditorResourcePreview *erp = (EditorResourcePreview *)ud;
  90. erp->_thread();
  91. }
  92. void 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) {
  93. {
  94. MutexLock lock(preview_mutex);
  95. uint64_t modified_time = 0;
  96. if (!p_path.begins_with("ID:")) {
  97. modified_time = FileAccess::get_modified_time(p_path);
  98. }
  99. Item item;
  100. item.order = order++;
  101. item.preview = p_texture;
  102. item.small_preview = p_small_texture;
  103. item.last_hash = p_hash;
  104. item.modified_time = modified_time;
  105. item.preview_metadata = p_metadata;
  106. cache[p_path] = item;
  107. }
  108. MessageQueue::get_singleton()->push_call(id, p_func, p_path, p_texture, p_small_texture, p_ud);
  109. }
  110. void EditorResourcePreview::_generate_preview(Ref<ImageTexture> &r_texture, Ref<ImageTexture> &r_small_texture, const QueueItem &p_item, const String &cache_base, Dictionary &p_metadata) {
  111. String type;
  112. if (p_item.resource.is_valid()) {
  113. type = p_item.resource->get_class();
  114. } else {
  115. type = ResourceLoader::get_resource_type(p_item.path);
  116. }
  117. if (type.is_empty()) {
  118. r_texture = Ref<ImageTexture>();
  119. r_small_texture = Ref<ImageTexture>();
  120. return; //could not guess type
  121. }
  122. int thumbnail_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");
  123. thumbnail_size *= EDSCALE;
  124. r_texture = Ref<ImageTexture>();
  125. r_small_texture = Ref<ImageTexture>();
  126. for (int i = 0; i < preview_generators.size(); i++) {
  127. if (!preview_generators[i]->handles(type)) {
  128. continue;
  129. }
  130. Ref<Texture2D> generated;
  131. if (p_item.resource.is_valid()) {
  132. generated = preview_generators.write[i]->generate(p_item.resource, Vector2(thumbnail_size, thumbnail_size), p_metadata);
  133. } else {
  134. generated = preview_generators.write[i]->generate_from_path(p_item.path, Vector2(thumbnail_size, thumbnail_size), p_metadata);
  135. }
  136. r_texture = generated;
  137. if (preview_generators[i]->can_generate_small_preview()) {
  138. Ref<Texture2D> generated_small;
  139. Dictionary d;
  140. if (p_item.resource.is_valid()) {
  141. generated_small = preview_generators.write[i]->generate(p_item.resource, Vector2(small_thumbnail_size, small_thumbnail_size), d);
  142. } else {
  143. generated_small = preview_generators.write[i]->generate_from_path(p_item.path, Vector2(small_thumbnail_size, small_thumbnail_size), d);
  144. }
  145. r_small_texture = generated_small;
  146. }
  147. if (!r_small_texture.is_valid() && r_texture.is_valid() && preview_generators[i]->generate_small_preview_automatically()) {
  148. Ref<Image> small_image = r_texture->get_image();
  149. small_image = small_image->duplicate();
  150. small_image->resize(small_thumbnail_size, small_thumbnail_size, Image::INTERPOLATE_CUBIC);
  151. r_small_texture.instantiate();
  152. r_small_texture->set_image(small_image);
  153. }
  154. break;
  155. }
  156. if (!p_item.resource.is_valid()) {
  157. // Cache the preview in case it's a resource on disk.
  158. if (r_texture.is_valid()) {
  159. // Wow it generated a preview... save cache.
  160. bool has_small_texture = r_small_texture.is_valid();
  161. ResourceSaver::save(r_texture, cache_base + ".png");
  162. if (has_small_texture) {
  163. ResourceSaver::save(r_small_texture, cache_base + "_small.png");
  164. }
  165. Ref<FileAccess> f = FileAccess::open(cache_base + ".txt", FileAccess::WRITE);
  166. ERR_FAIL_COND_MSG(f.is_null(), "Cannot create file '" + cache_base + ".txt'. Check user write permissions.");
  167. _write_preview_cache(f, thumbnail_size, has_small_texture, FileAccess::get_modified_time(p_item.path), FileAccess::get_md5(p_item.path), p_metadata);
  168. }
  169. }
  170. }
  171. const Dictionary EditorResourcePreview::get_preview_metadata(const String &p_path) const {
  172. ERR_FAIL_COND_V(!cache.has(p_path), Dictionary());
  173. return cache[p_path].preview_metadata;
  174. }
  175. void EditorResourcePreview::_iterate() {
  176. preview_mutex.lock();
  177. if (queue.size() == 0) {
  178. preview_mutex.unlock();
  179. return;
  180. }
  181. QueueItem item = queue.front()->get();
  182. queue.pop_front();
  183. if (cache.has(item.path)) {
  184. Item cached_item = cache[item.path];
  185. // Already has it because someone loaded it, just let it know it's ready.
  186. _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);
  187. preview_mutex.unlock();
  188. return;
  189. }
  190. preview_mutex.unlock();
  191. Ref<ImageTexture> texture;
  192. Ref<ImageTexture> small_texture;
  193. int thumbnail_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");
  194. thumbnail_size *= EDSCALE;
  195. if (item.resource.is_valid()) {
  196. Dictionary preview_metadata;
  197. _generate_preview(texture, small_texture, item, String(), preview_metadata);
  198. _preview_ready(item.path, item.resource->hash_edited_version(), texture, small_texture, item.id, item.function, item.userdata, preview_metadata);
  199. return;
  200. }
  201. Dictionary preview_metadata;
  202. String temp_path = EditorPaths::get_singleton()->get_cache_dir();
  203. String cache_base = ProjectSettings::get_singleton()->globalize_path(item.path).md5_text();
  204. cache_base = temp_path.path_join("resthumb-" + cache_base);
  205. // Does not have it, try to load a cached thumbnail.
  206. String file = cache_base + ".txt";
  207. Ref<FileAccess> f = FileAccess::open(file, FileAccess::READ);
  208. if (f.is_null()) {
  209. // No cache found, generate.
  210. _generate_preview(texture, small_texture, item, cache_base, preview_metadata);
  211. } else {
  212. uint64_t modtime = FileAccess::get_modified_time(item.path);
  213. int tsize;
  214. bool has_small_texture;
  215. uint64_t last_modtime;
  216. String hash;
  217. _read_preview_cache(f, &tsize, &has_small_texture, &last_modtime, &hash, &preview_metadata);
  218. bool cache_valid = true;
  219. if (tsize != thumbnail_size) {
  220. cache_valid = false;
  221. f.unref();
  222. } else if (last_modtime != modtime) {
  223. String last_md5 = f->get_line();
  224. String md5 = FileAccess::get_md5(item.path);
  225. f.unref();
  226. if (last_md5 != md5) {
  227. cache_valid = false;
  228. } else {
  229. // Update modified time.
  230. Ref<FileAccess> f2 = FileAccess::open(file, FileAccess::WRITE);
  231. if (f2.is_null()) {
  232. // Not returning as this would leave the thread hanging and would require
  233. // some proper cleanup/disabling of resource preview generation.
  234. ERR_PRINT("Cannot create file '" + file + "'. Check user write permissions.");
  235. } else {
  236. _write_preview_cache(f2, thumbnail_size, has_small_texture, modtime, md5, preview_metadata);
  237. }
  238. }
  239. } else {
  240. f.unref();
  241. }
  242. if (cache_valid) {
  243. Ref<Image> img;
  244. img.instantiate();
  245. Ref<Image> small_img;
  246. small_img.instantiate();
  247. if (img->load(cache_base + ".png") != OK) {
  248. cache_valid = false;
  249. } else {
  250. texture.instantiate();
  251. texture->set_image(img);
  252. if (has_small_texture) {
  253. if (small_img->load(cache_base + "_small.png") != OK) {
  254. cache_valid = false;
  255. } else {
  256. small_texture.instantiate();
  257. small_texture->set_image(small_img);
  258. }
  259. }
  260. }
  261. }
  262. if (!cache_valid) {
  263. _generate_preview(texture, small_texture, item, cache_base, preview_metadata);
  264. }
  265. }
  266. _preview_ready(item.path, 0, texture, small_texture, item.id, item.function, item.userdata, preview_metadata);
  267. }
  268. void EditorResourcePreview::_write_preview_cache(Ref<FileAccess> p_file, int p_thumbnail_size, bool p_has_small_texture, uint64_t p_modified_time, String p_hash, const Dictionary &p_metadata) {
  269. p_file->store_line(itos(p_thumbnail_size));
  270. p_file->store_line(itos(p_has_small_texture));
  271. p_file->store_line(itos(p_modified_time));
  272. p_file->store_line(p_hash);
  273. p_file->store_line(VariantUtilityFunctions::var_to_str(p_metadata).replace("\n", " "));
  274. }
  275. void 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) {
  276. *r_thumbnail_size = p_file->get_line().to_int();
  277. *r_has_small_texture = p_file->get_line().to_int();
  278. *r_modified_time = p_file->get_line().to_int();
  279. *r_hash = p_file->get_line();
  280. *r_metadata = VariantUtilityFunctions::str_to_var(p_file->get_line());
  281. }
  282. void EditorResourcePreview::_thread() {
  283. exited.clear();
  284. while (!exiting.is_set()) {
  285. preview_sem.wait();
  286. _iterate();
  287. }
  288. exited.set();
  289. }
  290. void EditorResourcePreview::_update_thumbnail_sizes() {
  291. if (small_thumbnail_size == -1) {
  292. // Kind of a workaround to retrieve the default icon size.
  293. small_thumbnail_size = EditorNode::get_singleton()->get_editor_theme()->get_icon(SNAME("Object"), EditorStringName(EditorIcons))->get_width();
  294. }
  295. }
  296. void EditorResourcePreview::queue_edited_resource_preview(const Ref<Resource> &p_res, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
  297. ERR_FAIL_NULL(p_receiver);
  298. ERR_FAIL_COND(!p_res.is_valid());
  299. _update_thumbnail_sizes();
  300. {
  301. MutexLock lock(preview_mutex);
  302. String path_id = "ID:" + itos(p_res->get_instance_id());
  303. if (cache.has(path_id) && cache[path_id].last_hash == p_res->hash_edited_version()) {
  304. cache[path_id].order = order++;
  305. p_receiver->call(p_receiver_func, path_id, cache[path_id].preview, cache[path_id].small_preview, p_userdata);
  306. return;
  307. }
  308. cache.erase(path_id); //erase if exists, since it will be regen
  309. QueueItem item;
  310. item.function = p_receiver_func;
  311. item.id = p_receiver->get_instance_id();
  312. item.resource = p_res;
  313. item.path = path_id;
  314. item.userdata = p_userdata;
  315. queue.push_back(item);
  316. }
  317. preview_sem.post();
  318. }
  319. void EditorResourcePreview::queue_resource_preview(const String &p_path, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
  320. ERR_FAIL_NULL(p_receiver);
  321. _update_thumbnail_sizes();
  322. {
  323. MutexLock lock(preview_mutex);
  324. if (cache.has(p_path)) {
  325. cache[p_path].order = order++;
  326. p_receiver->call(p_receiver_func, p_path, cache[p_path].preview, cache[p_path].small_preview, p_userdata);
  327. return;
  328. }
  329. QueueItem item;
  330. item.function = p_receiver_func;
  331. item.id = p_receiver->get_instance_id();
  332. item.path = p_path;
  333. item.userdata = p_userdata;
  334. queue.push_back(item);
  335. }
  336. preview_sem.post();
  337. }
  338. void EditorResourcePreview::add_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
  339. preview_generators.push_back(p_generator);
  340. }
  341. void EditorResourcePreview::remove_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
  342. preview_generators.erase(p_generator);
  343. }
  344. EditorResourcePreview *EditorResourcePreview::get_singleton() {
  345. return singleton;
  346. }
  347. void EditorResourcePreview::_bind_methods() {
  348. ClassDB::bind_method(D_METHOD("queue_resource_preview", "path", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_resource_preview);
  349. ClassDB::bind_method(D_METHOD("queue_edited_resource_preview", "resource", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_edited_resource_preview);
  350. ClassDB::bind_method(D_METHOD("add_preview_generator", "generator"), &EditorResourcePreview::add_preview_generator);
  351. ClassDB::bind_method(D_METHOD("remove_preview_generator", "generator"), &EditorResourcePreview::remove_preview_generator);
  352. ClassDB::bind_method(D_METHOD("check_for_invalidation", "path"), &EditorResourcePreview::check_for_invalidation);
  353. ADD_SIGNAL(MethodInfo("preview_invalidated", PropertyInfo(Variant::STRING, "path")));
  354. }
  355. void EditorResourcePreview::check_for_invalidation(const String &p_path) {
  356. bool call_invalidated = false;
  357. {
  358. MutexLock lock(preview_mutex);
  359. if (cache.has(p_path)) {
  360. uint64_t modified_time = FileAccess::get_modified_time(p_path);
  361. if (modified_time != cache[p_path].modified_time) {
  362. cache.erase(p_path);
  363. call_invalidated = true;
  364. }
  365. }
  366. }
  367. if (call_invalidated) { //do outside mutex
  368. call_deferred(SNAME("emit_signal"), "preview_invalidated", p_path);
  369. }
  370. }
  371. void EditorResourcePreview::start() {
  372. if (DisplayServer::get_singleton()->get_name() != "headless") {
  373. ERR_FAIL_COND_MSG(thread.is_started(), "Thread already started.");
  374. thread.start(_thread_func, this);
  375. }
  376. }
  377. void EditorResourcePreview::stop() {
  378. if (thread.is_started()) {
  379. exiting.set();
  380. preview_sem.post();
  381. for (int i = 0; i < preview_generators.size(); i++) {
  382. preview_generators.write[i]->abort();
  383. }
  384. while (!exited.is_set()) {
  385. OS::get_singleton()->delay_usec(10000);
  386. RenderingServer::get_singleton()->sync(); //sync pending stuff, as thread may be blocked on rendering server
  387. }
  388. thread.wait_to_finish();
  389. }
  390. }
  391. EditorResourcePreview::EditorResourcePreview() {
  392. singleton = this;
  393. order = 0;
  394. }
  395. EditorResourcePreview::~EditorResourcePreview() {
  396. stop();
  397. }