editor_resource_preview.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /*************************************************************************/
  2. /* editor_resource_preview.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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 "editor_node.h"
  37. #include "editor_scale.h"
  38. #include "editor_settings.h"
  39. bool EditorResourcePreviewGenerator::handles(const String &p_type) const {
  40. if (get_script_instance() && get_script_instance()->has_method("handles")) {
  41. return get_script_instance()->call("handles", p_type);
  42. }
  43. ERR_FAIL_V_MSG(false, "EditorResourcePreviewGenerator::handles needs to be overridden.");
  44. }
  45. Ref<Texture2D> EditorResourcePreviewGenerator::generate(const RES &p_from, const Size2 &p_size) const {
  46. if (get_script_instance() && get_script_instance()->has_method("generate")) {
  47. return get_script_instance()->call("generate", p_from, p_size);
  48. }
  49. ERR_FAIL_V_MSG(Ref<Texture2D>(), "EditorResourcePreviewGenerator::generate needs to be overridden.");
  50. }
  51. Ref<Texture2D> EditorResourcePreviewGenerator::generate_from_path(const String &p_path, const Size2 &p_size) const {
  52. if (get_script_instance() && get_script_instance()->has_method("generate_from_path")) {
  53. return get_script_instance()->call("generate_from_path", p_path, p_size);
  54. }
  55. RES res = ResourceLoader::load(p_path);
  56. if (!res.is_valid()) {
  57. return res;
  58. }
  59. return generate(res, p_size);
  60. }
  61. bool EditorResourcePreviewGenerator::generate_small_preview_automatically() const {
  62. if (get_script_instance() && get_script_instance()->has_method("generate_small_preview_automatically")) {
  63. return get_script_instance()->call("generate_small_preview_automatically");
  64. }
  65. return false;
  66. }
  67. bool EditorResourcePreviewGenerator::can_generate_small_preview() const {
  68. if (get_script_instance() && get_script_instance()->has_method("can_generate_small_preview")) {
  69. return get_script_instance()->call("can_generate_small_preview");
  70. }
  71. return false;
  72. }
  73. void EditorResourcePreviewGenerator::_bind_methods() {
  74. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "handles", PropertyInfo(Variant::STRING, "type")));
  75. ClassDB::add_virtual_method(get_class_static(), MethodInfo(CLASS_INFO(Texture2D), "generate", PropertyInfo(Variant::OBJECT, "from", PROPERTY_HINT_RESOURCE_TYPE, "Resource"), PropertyInfo(Variant::VECTOR2, "size")));
  76. ClassDB::add_virtual_method(get_class_static(), MethodInfo(CLASS_INFO(Texture2D), "generate_from_path", PropertyInfo(Variant::STRING, "path", PROPERTY_HINT_FILE), PropertyInfo(Variant::VECTOR2, "size")));
  77. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "generate_small_preview_automatically"));
  78. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "can_generate_small_preview"));
  79. }
  80. EditorResourcePreviewGenerator::EditorResourcePreviewGenerator() {
  81. }
  82. EditorResourcePreview *EditorResourcePreview::singleton = nullptr;
  83. void EditorResourcePreview::_thread_func(void *ud) {
  84. EditorResourcePreview *erp = (EditorResourcePreview *)ud;
  85. erp->_thread();
  86. }
  87. void EditorResourcePreview::_preview_ready(const String &p_str, const Ref<Texture2D> &p_texture, const Ref<Texture2D> &p_small_texture, ObjectID id, const StringName &p_func, const Variant &p_ud) {
  88. String path = p_str;
  89. {
  90. MutexLock lock(preview_mutex);
  91. uint32_t hash = 0;
  92. uint64_t modified_time = 0;
  93. if (p_str.begins_with("ID:")) {
  94. hash = uint32_t(p_str.get_slicec(':', 2).to_int());
  95. path = "ID:" + p_str.get_slicec(':', 1);
  96. } else {
  97. modified_time = FileAccess::get_modified_time(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 = hash;
  104. item.modified_time = modified_time;
  105. cache[path] = item;
  106. }
  107. MessageQueue::get_singleton()->push_call(id, p_func, path, p_texture, p_small_texture, p_ud);
  108. }
  109. void EditorResourcePreview::_generate_preview(Ref<ImageTexture> &r_texture, Ref<ImageTexture> &r_small_texture, const QueueItem &p_item, const String &cache_base) {
  110. String type;
  111. if (p_item.resource.is_valid()) {
  112. type = p_item.resource->get_class();
  113. } else {
  114. type = ResourceLoader::get_resource_type(p_item.path);
  115. }
  116. if (type == "") {
  117. r_texture = Ref<ImageTexture>();
  118. r_small_texture = Ref<ImageTexture>();
  119. return; //could not guess type
  120. }
  121. int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
  122. thumbnail_size *= EDSCALE;
  123. r_texture = Ref<ImageTexture>();
  124. r_small_texture = Ref<ImageTexture>();
  125. for (int i = 0; i < preview_generators.size(); i++) {
  126. if (!preview_generators[i]->handles(type)) {
  127. continue;
  128. }
  129. Ref<Texture2D> generated;
  130. if (p_item.resource.is_valid()) {
  131. generated = preview_generators[i]->generate(p_item.resource, Vector2(thumbnail_size, thumbnail_size));
  132. } else {
  133. generated = preview_generators[i]->generate_from_path(p_item.path, Vector2(thumbnail_size, thumbnail_size));
  134. }
  135. r_texture = generated;
  136. int small_thumbnail_size = EditorNode::get_singleton()->get_theme_base()->get_theme_icon("Object", "EditorIcons")->get_width(); // Kind of a workaround to retrieve the default icon size
  137. if (preview_generators[i]->can_generate_small_preview()) {
  138. Ref<Texture2D> generated_small;
  139. if (p_item.resource.is_valid()) {
  140. generated_small = preview_generators[i]->generate(p_item.resource, Vector2(small_thumbnail_size, small_thumbnail_size));
  141. } else {
  142. generated_small = preview_generators[i]->generate_from_path(p_item.path, Vector2(small_thumbnail_size, small_thumbnail_size));
  143. }
  144. r_small_texture = generated_small;
  145. }
  146. if (!r_small_texture.is_valid() && r_texture.is_valid() && preview_generators[i]->generate_small_preview_automatically()) {
  147. Ref<Image> small_image = r_texture->get_image();
  148. small_image = small_image->duplicate();
  149. small_image->resize(small_thumbnail_size, small_thumbnail_size, Image::INTERPOLATE_CUBIC);
  150. r_small_texture.instance();
  151. r_small_texture->create_from_image(small_image);
  152. }
  153. break;
  154. }
  155. if (!p_item.resource.is_valid()) {
  156. // cache the preview in case it's a resource on disk
  157. if (r_texture.is_valid()) {
  158. //wow it generated a preview... save cache
  159. bool has_small_texture = r_small_texture.is_valid();
  160. ResourceSaver::save(cache_base + ".png", r_texture);
  161. if (has_small_texture) {
  162. ResourceSaver::save(cache_base + "_small.png", r_small_texture);
  163. }
  164. FileAccess *f = FileAccess::open(cache_base + ".txt", FileAccess::WRITE);
  165. ERR_FAIL_COND_MSG(!f, "Cannot create file '" + cache_base + ".txt'. Check user write permissions.");
  166. f->store_line(itos(thumbnail_size));
  167. f->store_line(itos(has_small_texture));
  168. f->store_line(itos(FileAccess::get_modified_time(p_item.path)));
  169. f->store_line(FileAccess::get_md5(p_item.path));
  170. f->close();
  171. memdelete(f);
  172. }
  173. }
  174. }
  175. void EditorResourcePreview::_thread() {
  176. exited.clear();
  177. while (!exit.is_set()) {
  178. preview_sem.wait();
  179. preview_mutex.lock();
  180. if (queue.size()) {
  181. QueueItem item = queue.front()->get();
  182. queue.pop_front();
  183. if (cache.has(item.path)) {
  184. //already has it because someone loaded it, just let it know it's ready
  185. String path = item.path;
  186. if (item.resource.is_valid()) {
  187. path += ":" + itos(cache[item.path].last_hash); //keep last hash (see description of what this is in condition below)
  188. }
  189. _preview_ready(path, cache[item.path].preview, cache[item.path].small_preview, item.id, item.function, item.userdata);
  190. preview_mutex.unlock();
  191. } else {
  192. preview_mutex.unlock();
  193. Ref<ImageTexture> texture;
  194. Ref<ImageTexture> small_texture;
  195. int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
  196. thumbnail_size *= EDSCALE;
  197. if (item.resource.is_valid()) {
  198. _generate_preview(texture, small_texture, item, String());
  199. //adding hash to the end of path (should be ID:<objid>:<hash>) because of 5 argument limit to call_deferred
  200. _preview_ready(item.path + ":" + itos(item.resource->hash_edited_version()), texture, small_texture, item.id, item.function, item.userdata);
  201. } else {
  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.plus_file("resthumb-" + cache_base);
  205. //does not have it, try to load a cached thumbnail
  206. String file = cache_base + ".txt";
  207. FileAccess *f = FileAccess::open(file, FileAccess::READ);
  208. if (!f) {
  209. // No cache found, generate
  210. _generate_preview(texture, small_texture, item, cache_base);
  211. } else {
  212. uint64_t modtime = FileAccess::get_modified_time(item.path);
  213. int tsize = f->get_line().to_int();
  214. bool has_small_texture = f->get_line().to_int();
  215. uint64_t last_modtime = f->get_line().to_int();
  216. bool cache_valid = true;
  217. if (tsize != thumbnail_size) {
  218. cache_valid = false;
  219. memdelete(f);
  220. } else if (last_modtime != modtime) {
  221. String last_md5 = f->get_line();
  222. String md5 = FileAccess::get_md5(item.path);
  223. memdelete(f);
  224. if (last_md5 != md5) {
  225. cache_valid = false;
  226. } else {
  227. //update modified time
  228. f = FileAccess::open(file, FileAccess::WRITE);
  229. if (!f) {
  230. // Not returning as this would leave the thread hanging and would require
  231. // some proper cleanup/disabling of resource preview generation.
  232. ERR_PRINT("Cannot create file '" + file + "'. Check user write permissions.");
  233. } else {
  234. f->store_line(itos(thumbnail_size));
  235. f->store_line(itos(has_small_texture));
  236. f->store_line(itos(modtime));
  237. f->store_line(md5);
  238. memdelete(f);
  239. }
  240. }
  241. } else {
  242. memdelete(f);
  243. }
  244. if (cache_valid) {
  245. Ref<Image> img;
  246. img.instance();
  247. Ref<Image> small_img;
  248. small_img.instance();
  249. if (img->load(cache_base + ".png") != OK) {
  250. cache_valid = false;
  251. } else {
  252. texture.instance();
  253. texture->create_from_image(img);
  254. if (has_small_texture) {
  255. if (small_img->load(cache_base + "_small.png") != OK) {
  256. cache_valid = false;
  257. } else {
  258. small_texture.instance();
  259. small_texture->create_from_image(small_img);
  260. }
  261. }
  262. }
  263. }
  264. if (!cache_valid) {
  265. _generate_preview(texture, small_texture, item, cache_base);
  266. }
  267. }
  268. _preview_ready(item.path, texture, small_texture, item.id, item.function, item.userdata);
  269. }
  270. }
  271. } else {
  272. preview_mutex.unlock();
  273. }
  274. }
  275. exited.set();
  276. }
  277. void EditorResourcePreview::queue_edited_resource_preview(const Ref<Resource> &p_res, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
  278. ERR_FAIL_NULL(p_receiver);
  279. ERR_FAIL_COND(!p_res.is_valid());
  280. {
  281. MutexLock lock(preview_mutex);
  282. String path_id = "ID:" + itos(p_res->get_instance_id());
  283. if (cache.has(path_id) && cache[path_id].last_hash == p_res->hash_edited_version()) {
  284. cache[path_id].order = order++;
  285. p_receiver->call(p_receiver_func, path_id, cache[path_id].preview, cache[path_id].small_preview, p_userdata);
  286. return;
  287. }
  288. cache.erase(path_id); //erase if exists, since it will be regen
  289. QueueItem item;
  290. item.function = p_receiver_func;
  291. item.id = p_receiver->get_instance_id();
  292. item.resource = p_res;
  293. item.path = path_id;
  294. item.userdata = p_userdata;
  295. queue.push_back(item);
  296. }
  297. preview_sem.post();
  298. }
  299. void EditorResourcePreview::queue_resource_preview(const String &p_path, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
  300. ERR_FAIL_NULL(p_receiver);
  301. {
  302. MutexLock lock(preview_mutex);
  303. if (cache.has(p_path)) {
  304. cache[p_path].order = order++;
  305. p_receiver->call(p_receiver_func, p_path, cache[p_path].preview, cache[p_path].small_preview, p_userdata);
  306. return;
  307. }
  308. QueueItem item;
  309. item.function = p_receiver_func;
  310. item.id = p_receiver->get_instance_id();
  311. item.path = p_path;
  312. item.userdata = p_userdata;
  313. queue.push_back(item);
  314. }
  315. preview_sem.post();
  316. }
  317. void EditorResourcePreview::add_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
  318. preview_generators.push_back(p_generator);
  319. }
  320. void EditorResourcePreview::remove_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
  321. preview_generators.erase(p_generator);
  322. }
  323. EditorResourcePreview *EditorResourcePreview::get_singleton() {
  324. return singleton;
  325. }
  326. void EditorResourcePreview::_bind_methods() {
  327. ClassDB::bind_method("_preview_ready", &EditorResourcePreview::_preview_ready);
  328. ClassDB::bind_method(D_METHOD("queue_resource_preview", "path", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_resource_preview);
  329. ClassDB::bind_method(D_METHOD("queue_edited_resource_preview", "resource", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_edited_resource_preview);
  330. ClassDB::bind_method(D_METHOD("add_preview_generator", "generator"), &EditorResourcePreview::add_preview_generator);
  331. ClassDB::bind_method(D_METHOD("remove_preview_generator", "generator"), &EditorResourcePreview::remove_preview_generator);
  332. ClassDB::bind_method(D_METHOD("check_for_invalidation", "path"), &EditorResourcePreview::check_for_invalidation);
  333. ADD_SIGNAL(MethodInfo("preview_invalidated", PropertyInfo(Variant::STRING, "path")));
  334. }
  335. void EditorResourcePreview::check_for_invalidation(const String &p_path) {
  336. bool call_invalidated = false;
  337. {
  338. MutexLock lock(preview_mutex);
  339. if (cache.has(p_path)) {
  340. uint64_t modified_time = FileAccess::get_modified_time(p_path);
  341. if (modified_time != cache[p_path].modified_time) {
  342. cache.erase(p_path);
  343. call_invalidated = true;
  344. }
  345. }
  346. }
  347. if (call_invalidated) { //do outside mutex
  348. call_deferred("emit_signal", "preview_invalidated", p_path);
  349. }
  350. }
  351. void EditorResourcePreview::start() {
  352. ERR_FAIL_COND_MSG(thread.is_started(), "Thread already started.");
  353. thread.start(_thread_func, this);
  354. }
  355. void EditorResourcePreview::stop() {
  356. if (thread.is_started()) {
  357. exit.set();
  358. preview_sem.post();
  359. while (!exited.is_set()) {
  360. OS::get_singleton()->delay_usec(10000);
  361. RenderingServer::get_singleton()->sync(); //sync pending stuff, as thread may be blocked on visual server
  362. }
  363. thread.wait_to_finish();
  364. }
  365. }
  366. EditorResourcePreview::EditorResourcePreview() {
  367. singleton = this;
  368. order = 0;
  369. }
  370. EditorResourcePreview::~EditorResourcePreview() {
  371. stop();
  372. }