editor_resource_preview.cpp 17 KB

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