editor_preview_plugins.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. /**************************************************************************/
  2. /* editor_preview_plugins.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_preview_plugins.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/image.h"
  33. #include "core/io/resource_loader.h"
  34. #include "core/object/script_language.h"
  35. #include "editor/editor_node.h"
  36. #include "editor/editor_paths.h"
  37. #include "editor/editor_settings.h"
  38. #include "editor/themes/editor_scale.h"
  39. #include "main/main.h"
  40. #include "modules/gridmap/grid_map.h"
  41. #include "scene/2d/animated_sprite_2d.h"
  42. #include "scene/2d/camera_2d.h"
  43. #include "scene/2d/line_2d.h"
  44. #include "scene/2d/mesh_instance_2d.h"
  45. #include "scene/2d/multimesh_instance_2d.h"
  46. #include "scene/2d/physics/touch_screen_button.h"
  47. #include "scene/2d/polygon_2d.h"
  48. #include "scene/2d/sprite_2d.h"
  49. #include "scene/2d/tile_map_layer.h"
  50. #include "scene/3d/cpu_particles_3d.h"
  51. #include "scene/3d/gpu_particles_3d.h"
  52. #include "scene/3d/light_3d.h"
  53. #include "scene/3d/mesh_instance_3d.h"
  54. #include "scene/gui/option_button.h"
  55. #include "scene/main/viewport.h"
  56. #include "scene/main/window.h"
  57. #include "scene/resources/atlas_texture.h"
  58. #include "scene/resources/bit_map.h"
  59. #include "scene/resources/font.h"
  60. #include "scene/resources/gradient_texture.h"
  61. #include "scene/resources/image_texture.h"
  62. #include "scene/resources/material.h"
  63. #include "scene/resources/mesh.h"
  64. #include "scene/resources/world_2d.h"
  65. #include "servers/audio/audio_stream.h"
  66. void post_process_preview(Ref<Image> p_image) {
  67. if (p_image->get_format() != Image::FORMAT_RGBA8) {
  68. p_image->convert(Image::FORMAT_RGBA8);
  69. }
  70. const int w = p_image->get_width();
  71. const int h = p_image->get_height();
  72. const int r = MIN(w, h) / 32;
  73. const int r2 = r * r;
  74. Color transparent = Color(0, 0, 0, 0);
  75. for (int i = 0; i < r; i++) {
  76. for (int j = 0; j < r; j++) {
  77. int dx = i - r;
  78. int dy = j - r;
  79. if (dx * dx + dy * dy > r2) {
  80. p_image->set_pixel(i, j, transparent);
  81. p_image->set_pixel(w - 1 - i, j, transparent);
  82. p_image->set_pixel(w - 1 - i, h - 1 - j, transparent);
  83. p_image->set_pixel(i, h - 1 - j, transparent);
  84. } else {
  85. break;
  86. }
  87. }
  88. }
  89. }
  90. bool EditorTexturePreviewPlugin::handles(const String &p_type) const {
  91. return ClassDB::is_parent_class(p_type, "Texture");
  92. }
  93. bool EditorTexturePreviewPlugin::generate_small_preview_automatically() const {
  94. return true;
  95. }
  96. Ref<Texture2D> EditorTexturePreviewPlugin::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  97. Ref<Image> img;
  98. Ref<AtlasTexture> tex_atlas = p_from;
  99. Ref<Texture3D> tex_3d = p_from;
  100. Ref<TextureLayered> tex_lyr = p_from;
  101. if (tex_atlas.is_valid()) {
  102. Ref<Texture2D> tex = tex_atlas->get_atlas();
  103. if (tex.is_null()) {
  104. return Ref<Texture2D>();
  105. }
  106. Ref<Image> atlas = tex->get_image();
  107. if (atlas.is_null()) {
  108. return Ref<Texture2D>();
  109. }
  110. if (atlas->is_compressed()) {
  111. atlas = atlas->duplicate();
  112. if (atlas->decompress() != OK) {
  113. return Ref<Texture2D>();
  114. }
  115. }
  116. if (!tex_atlas->get_region().has_area()) {
  117. return Ref<Texture2D>();
  118. }
  119. img = atlas->get_region(tex_atlas->get_region());
  120. } else if (tex_3d.is_valid()) {
  121. if (tex_3d->get_depth() == 0) {
  122. return Ref<Texture2D>();
  123. }
  124. Vector<Ref<Image>> data = tex_3d->get_data();
  125. if (data.size() != tex_3d->get_depth()) {
  126. return Ref<Texture2D>();
  127. }
  128. // Use the middle slice for the thumbnail.
  129. const int mid_depth = (tex_3d->get_depth() - 1) / 2;
  130. if (!data.is_empty() && data[mid_depth].is_valid()) {
  131. img = data[mid_depth]->duplicate();
  132. }
  133. } else if (tex_lyr.is_valid()) {
  134. if (tex_lyr->get_layers() == 0) {
  135. return Ref<Texture2D>();
  136. }
  137. // Use the middle slice for the thumbnail.
  138. const int mid_layer = (tex_lyr->get_layers() - 1) / 2;
  139. Ref<Image> data = tex_lyr->get_layer_data(mid_layer);
  140. if (data.is_valid()) {
  141. img = data->duplicate();
  142. }
  143. } else {
  144. Ref<Texture2D> tex = p_from;
  145. if (tex.is_valid()) {
  146. img = tex->get_image();
  147. if (img.is_valid()) {
  148. img = img->duplicate();
  149. }
  150. }
  151. }
  152. if (img.is_null() || img->is_empty()) {
  153. return Ref<Texture2D>();
  154. }
  155. p_metadata["dimensions"] = img->get_size();
  156. img->clear_mipmaps();
  157. if (img->is_compressed()) {
  158. if (img->decompress() != OK) {
  159. return Ref<Texture2D>();
  160. }
  161. } else if (img->get_format() != Image::FORMAT_RGB8 && img->get_format() != Image::FORMAT_RGBA8) {
  162. img->convert(Image::FORMAT_RGBA8);
  163. }
  164. Vector2 new_size = img->get_size();
  165. if (new_size.x > p_size.x) {
  166. new_size = Vector2(p_size.x, new_size.y * p_size.x / new_size.x);
  167. }
  168. if (new_size.y > p_size.y) {
  169. new_size = Vector2(new_size.x * p_size.y / new_size.y, p_size.y);
  170. }
  171. Vector2i new_size_i = Vector2i(new_size).maxi(1);
  172. img->resize(new_size_i.x, new_size_i.y, Image::INTERPOLATE_CUBIC);
  173. post_process_preview(img);
  174. return ImageTexture::create_from_image(img);
  175. }
  176. ////////////////////////////////////////////////////////////////////////////
  177. bool EditorImagePreviewPlugin::handles(const String &p_type) const {
  178. return p_type == "Image";
  179. }
  180. Ref<Texture2D> EditorImagePreviewPlugin::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  181. Ref<Image> img = p_from;
  182. if (img.is_null() || img->is_empty()) {
  183. return Ref<Image>();
  184. }
  185. img = img->duplicate();
  186. img->clear_mipmaps();
  187. if (img->is_compressed()) {
  188. if (img->decompress() != OK) {
  189. return Ref<Image>();
  190. }
  191. } else if (img->get_format() != Image::FORMAT_RGB8 && img->get_format() != Image::FORMAT_RGBA8) {
  192. img->convert(Image::FORMAT_RGBA8);
  193. }
  194. Vector2 new_size = img->get_size();
  195. if (new_size.x > p_size.x) {
  196. new_size = Vector2(p_size.x, new_size.y * p_size.x / new_size.x);
  197. }
  198. if (new_size.y > p_size.y) {
  199. new_size = Vector2(new_size.x * p_size.y / new_size.y, p_size.y);
  200. }
  201. img->resize(new_size.x, new_size.y, Image::INTERPOLATE_CUBIC);
  202. post_process_preview(img);
  203. return ImageTexture::create_from_image(img);
  204. }
  205. bool EditorImagePreviewPlugin::generate_small_preview_automatically() const {
  206. return true;
  207. }
  208. ////////////////////////////////////////////////////////////////////////////
  209. bool EditorBitmapPreviewPlugin::handles(const String &p_type) const {
  210. return ClassDB::is_parent_class(p_type, "BitMap");
  211. }
  212. Ref<Texture2D> EditorBitmapPreviewPlugin::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  213. Ref<BitMap> bm = p_from;
  214. if (bm->get_size() == Size2()) {
  215. return Ref<Texture2D>();
  216. }
  217. Vector<uint8_t> data;
  218. data.resize(bm->get_size().width * bm->get_size().height);
  219. {
  220. uint8_t *w = data.ptrw();
  221. for (int i = 0; i < bm->get_size().width; i++) {
  222. for (int j = 0; j < bm->get_size().height; j++) {
  223. if (bm->get_bit(i, j)) {
  224. w[j * (int)bm->get_size().width + i] = 255;
  225. } else {
  226. w[j * (int)bm->get_size().width + i] = 0;
  227. }
  228. }
  229. }
  230. }
  231. Ref<Image> img = Image::create_from_data(bm->get_size().width, bm->get_size().height, false, Image::FORMAT_L8, data);
  232. if (img->is_compressed()) {
  233. if (img->decompress() != OK) {
  234. return Ref<Texture2D>();
  235. }
  236. } else if (img->get_format() != Image::FORMAT_RGB8 && img->get_format() != Image::FORMAT_RGBA8) {
  237. img->convert(Image::FORMAT_RGBA8);
  238. }
  239. Vector2 new_size = img->get_size();
  240. if (new_size.x > p_size.x) {
  241. new_size = Vector2(p_size.x, new_size.y * p_size.x / new_size.x);
  242. }
  243. if (new_size.y > p_size.y) {
  244. new_size = Vector2(new_size.x * p_size.y / new_size.y, p_size.y);
  245. }
  246. img->resize(new_size.x, new_size.y, Image::INTERPOLATE_CUBIC);
  247. post_process_preview(img);
  248. return ImageTexture::create_from_image(img);
  249. }
  250. bool EditorBitmapPreviewPlugin::generate_small_preview_automatically() const {
  251. return true;
  252. }
  253. ///////////////////////////////////////////////////////////////////////////
  254. void EditorPackedScenePreviewPlugin::abort() {
  255. draw_requester.abort();
  256. aborted = true;
  257. }
  258. bool EditorPackedScenePreviewPlugin::handles(const String &p_type) const {
  259. return ClassDB::is_parent_class(p_type, "PackedScene");
  260. }
  261. Ref<Texture2D> EditorPackedScenePreviewPlugin::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  262. return generate_from_path(p_from->get_path(), p_size, p_metadata);
  263. }
  264. Ref<Texture2D> EditorPackedScenePreviewPlugin::generate_from_path(const String &p_path, const Size2 &p_size, Dictionary &p_metadata) const {
  265. ERR_FAIL_COND_V_MSG(!Engine::get_singleton()->is_editor_hint(), Ref<Texture2D>(), "This function can only be called from the editor.");
  266. ERR_FAIL_NULL_V_MSG(EditorNode::get_singleton(), Ref<Texture2D>(), "EditorNode doesn't exist.");
  267. // Lower abort flag
  268. aborted = false;
  269. Error load_error;
  270. Ref<PackedScene> pack = ResourceLoader::load(p_path, "PackedScene", ResourceFormatLoader::CACHE_MODE_IGNORE, &load_error); // no more cache issues?
  271. if (load_error != OK) {
  272. print_error(vformat("Failed to generate scene thumbnail for %s : Loaded with error code %d", p_path, int(load_error)));
  273. return Ref<Texture2D>();
  274. }
  275. if (pack.is_null()) {
  276. print_error(vformat("Failed to generate scene thumbnail for %s : Invalid scene file", p_path));
  277. return Ref<Texture2D>();
  278. }
  279. bool _scene_setup_success = _setup_packed_scene(pack); // We don't want tool scripts to fire off when generating previews
  280. if (!_scene_setup_success) {
  281. 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));
  282. return Ref<Texture2D>();
  283. }
  284. Node *p_scene = pack->instantiate(); // The instantiated preview scene
  285. // Prohibit Viewport class as root when generating thumbnails
  286. if (Object::cast_to<Viewport>(p_scene)) {
  287. p_scene->queue_free();
  288. return Ref<Texture2D>();
  289. }
  290. int count_2d = 0;
  291. int count_3d = 0;
  292. int count_light_3d = 0;
  293. _count_node_types(p_scene, count_2d, count_3d, count_light_3d);
  294. if (count_3d > 0) { // Is 3d scene
  295. // Setup preview viewport
  296. SubViewport *sub_viewport = memnew(SubViewport);
  297. sub_viewport->set_update_mode(SubViewport::UpdateMode::UPDATE_DISABLED);
  298. sub_viewport->set_size(Size2i(Math::round(p_size.x), Math::round(p_size.y)));
  299. sub_viewport->set_transparent_background(false);
  300. sub_viewport->set_disable_3d(false);
  301. if (p_size.x < 2048 && p_size.y < 2048) { // Universal baseline for textures in Godot 4 is 4K
  302. sub_viewport->set_scaling_3d_scale(2.0); // Supersampling x2
  303. }
  304. if (RS::get_singleton()->get_current_rendering_method() != "gl_compatibility") {
  305. sub_viewport->set_msaa_3d(Viewport::MSAA::MSAA_8X);
  306. }
  307. Ref<Environment> environment;
  308. Color default_clear_color = GLOBAL_GET("rendering/environment/defaults/default_clear_color");
  309. environment.instantiate();
  310. environment->set_background(Environment::BGMode::BG_CLEAR_COLOR);
  311. environment->set_bg_color(default_clear_color);
  312. Ref<World3D> world_3d;
  313. sub_viewport->set_world_3d(world_3d);
  314. sub_viewport->set_use_own_world_3d(true);
  315. Camera3D *camera_3d = memnew(Camera3D);
  316. sub_viewport->add_child(camera_3d);
  317. camera_3d->set_perspective(preview_3d_fov, 0.05, 10000.0);
  318. // Add scene to viewport
  319. _setup_scene_3d(p_scene);
  320. sub_viewport->add_child(p_scene);
  321. // Setup preview light
  322. DirectionalLight3D *light_1 = nullptr;
  323. DirectionalLight3D *light_2 = nullptr;
  324. if (count_light_3d == 0) {
  325. light_1 = memnew(DirectionalLight3D);
  326. light_2 = memnew(DirectionalLight3D);
  327. sub_viewport->add_child(light_1);
  328. sub_viewport->add_child(light_2);
  329. light_1->set_color(Color(1.0, 1.0, 1.0, 1.0));
  330. light_2->set_color(Color(0.7, 0.7, 0.7, 1.0));
  331. light_1->set_transform(Transform3D(Basis().rotated(Vector3(0, 1, 0), -Math::PI / 6), Vector3(0.0, 0.0, 0.0)));
  332. light_2->set_transform(Transform3D(Basis().rotated(Vector3(1, 0, 0), -Math::PI / 6), Vector3(0.0, 0.0, 0.0)));
  333. }
  334. // Setup preview camera
  335. AABB scene_aabb;
  336. _calculate_scene_aabb(p_scene, scene_aabb);
  337. float bound_sphere_radius = (scene_aabb.get_end() - scene_aabb.get_position()).length() / 2.0f;
  338. if (bound_sphere_radius <= 0.0f) {
  339. // The scene has zero volume, so just it give a literal
  340. bound_sphere_radius = 1.0f;
  341. }
  342. float cam_distance = bound_sphere_radius / Math::tan(Math::deg_to_rad(preview_3d_fov) / 2.0f);
  343. Transform3D thumbnail_cam_trans_3d;
  344. thumbnail_cam_trans_3d.set_origin(scene_aabb.get_center() + Vector3(1.0f, 0.25f, 1.0f).normalized() * cam_distance);
  345. thumbnail_cam_trans_3d.set_look_at(thumbnail_cam_trans_3d.origin, scene_aabb.get_center());
  346. // Set camera to orthogonal if distance exceeds camera default far (large scene)
  347. if (thumbnail_cam_trans_3d.origin.length() > camera_3d->get_far()) {
  348. real_t distance = thumbnail_cam_trans_3d.origin.length();
  349. camera_3d->set_orthogonal(distance / 2.0, distance / 1000.0, distance); // Approximately contains the whole scene
  350. }
  351. camera_3d->set_transform(thumbnail_cam_trans_3d);
  352. // Attach the preview viewport to MainTree
  353. sub_viewport->set_update_mode(SubViewport::UpdateMode::UPDATE_ONCE);
  354. if (EditorResourcePreview::get_singleton()->is_threaded()) {
  355. callable_mp((Node *)EditorNode::get_singleton(), &Node::add_child).call_deferred(sub_viewport, false, Node::InternalMode::INTERNAL_MODE_DISABLED);
  356. callable_mp(camera_3d, &Camera3D::set_current).call_deferred(true);
  357. } else {
  358. EditorNode::get_singleton()->add_child(sub_viewport);
  359. camera_3d->set_current(true);
  360. }
  361. _wait_frame();
  362. draw_requester.request_and_wait(sub_viewport->get_viewport_rid());
  363. if (aborted) {
  364. sub_viewport->queue_free();
  365. return Ref<Texture2D>();
  366. }
  367. // Retrieve thumbnail image
  368. Ref<ImageTexture> thumbnail;
  369. thumbnail = ImageTexture::create_from_image(sub_viewport->get_texture()->get_image());
  370. // Clean up
  371. sub_viewport->queue_free();
  372. return thumbnail;
  373. }
  374. if (count_2d > 0) { // Is 2d scene
  375. // If anyone want to rewrite this part to call RenderingServer directly, note that at the time of writing,
  376. // there's a limitation where CanvasItem cannot be rendered outside of the tree.
  377. // See CanvasItem::queue_redraw() and RenderingServer::draw()
  378. int texture_filter = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_filter");
  379. int texture_repeat = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_repeat");
  380. SubViewport *sub_viewport = memnew(SubViewport);
  381. sub_viewport->set_update_mode(SubViewport::UpdateMode::UPDATE_DISABLED);
  382. sub_viewport->set_disable_3d(true);
  383. sub_viewport->set_transparent_background(false);
  384. if (RS::get_singleton()->get_current_rendering_method() != "gl_compatibility") {
  385. sub_viewport->set_msaa_2d(Viewport::MSAA::MSAA_8X);
  386. }
  387. sub_viewport->set_default_canvas_item_texture_filter(Viewport::DefaultCanvasItemTextureFilter(texture_filter));
  388. sub_viewport->set_default_canvas_item_texture_repeat(Viewport::DefaultCanvasItemTextureRepeat(texture_repeat));
  389. Ref<World2D> world;
  390. world.instantiate();
  391. sub_viewport->set_world_2d(world);
  392. sub_viewport->add_child(p_scene);
  393. _setup_scene_2d(p_scene);
  394. _hide_gui_in_scene(p_scene);
  395. // Preview camera
  396. Camera2D *camera = memnew(Camera2D);
  397. sub_viewport->add_child(camera);
  398. camera->set_enabled(true);
  399. // Attach subviewport (following process needs scene to be in tree)
  400. if (EditorResourcePreview::get_singleton()->is_threaded()) {
  401. callable_mp((Node *)EditorNode::get_singleton(), &Node::add_child).call_deferred(sub_viewport, false, Node::InternalMode::INTERNAL_MODE_DISABLED);
  402. callable_mp((Camera2D *)camera, &Camera2D::make_current).call_deferred();
  403. } else {
  404. EditorNode::get_singleton()->add_child(sub_viewport);
  405. camera->make_current();
  406. }
  407. _wait_frame();
  408. if (aborted) {
  409. sub_viewport->queue_free();
  410. return Ref<Texture2D>();
  411. }
  412. // Calculate scene rect
  413. Rect2 scene_rect;
  414. _calculate_scene_rect(p_scene, scene_rect);
  415. Vector2 scene_true_center = scene_rect.get_center();
  416. // Place camera 2D
  417. camera->set_position(Point2(scene_true_center));
  418. // Render viewport
  419. uint16_t scene_rect_long = MAX(scene_rect.get_size().x, scene_rect.get_size().y);
  420. if (scene_rect_long == 0) {
  421. scene_rect_long = MAX(p_size.x, p_size.y); // Prevent 0 size rect (which causes error) and defaults to thumbnail size.
  422. }
  423. sub_viewport->set_size(p_size);
  424. camera->set_zoom(Vector2(p_size.x / float(scene_rect_long), p_size.y / float(scene_rect_long)));
  425. sub_viewport->set_update_mode(SubViewport::UpdateMode::UPDATE_ONCE);
  426. _wait_frame();
  427. draw_requester.request_and_wait(sub_viewport->get_viewport_rid());
  428. if (aborted) {
  429. sub_viewport->queue_free();
  430. return Ref<Texture2D>();
  431. }
  432. // Retrieve thumbnail of 2D (No GUI)
  433. Ref<ImageTexture> capture_2d = ImageTexture::create_from_image(sub_viewport->get_texture()->get_image());
  434. capture_2d->get_image()->resize(p_size.x, p_size.y);
  435. capture_2d->get_image()->convert(Image::Format::FORMAT_RGBA8); // ALPHA channel is required for image blending
  436. // Prepare for gui render
  437. callable_mp((Node *)sub_viewport, &Node::remove_child).call_deferred(p_scene);
  438. p_scene->queue_free();
  439. p_scene = pack->instantiate();
  440. _setup_scene_2d(p_scene);
  441. _hide_node_2d_in_scene(p_scene);
  442. SubViewport *sub_viewport_gui = memnew(SubViewport);
  443. sub_viewport_gui->set_size(Size2i(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height")));
  444. sub_viewport_gui->set_update_mode(SubViewport::UpdateMode::UPDATE_DISABLED);
  445. sub_viewport_gui->set_transparent_background(true);
  446. if (RS::get_singleton()->get_current_rendering_method() != "gl_compatibility") {
  447. sub_viewport_gui->set_msaa_2d(Viewport::MSAA::MSAA_8X);
  448. }
  449. sub_viewport_gui->set_default_canvas_item_texture_filter(Viewport::DefaultCanvasItemTextureFilter(texture_filter));
  450. sub_viewport_gui->set_default_canvas_item_texture_repeat(Viewport::DefaultCanvasItemTextureRepeat(texture_repeat));
  451. sub_viewport_gui->set_disable_3d(true);
  452. sub_viewport_gui->add_child(p_scene);
  453. // Render GUI
  454. sub_viewport_gui->set_update_mode(SubViewport::UpdateMode::UPDATE_ONCE);
  455. if (EditorResourcePreview::get_singleton()->is_threaded()) {
  456. callable_mp((Node *)EditorNode::get_singleton(), &Node::add_child).call_deferred(sub_viewport_gui, false, Node::InternalMode::INTERNAL_MODE_DISABLED);
  457. } else {
  458. EditorNode::get_singleton()->add_child(sub_viewport_gui);
  459. }
  460. _wait_frame();
  461. draw_requester.request_and_wait(sub_viewport_gui->get_viewport_rid());
  462. if (aborted) {
  463. sub_viewport->queue_free();
  464. sub_viewport_gui->queue_free();
  465. return Ref<Texture2D>();
  466. }
  467. // Retrieve thumbnail of gui
  468. Ref<ImageTexture> capture_gui = ImageTexture::create_from_image(sub_viewport_gui->get_texture()->get_image());
  469. capture_gui->get_image()->resize(p_size.x, p_size.y);
  470. // Mix 2D, GUI thumbnail images into one
  471. Ref<ImageTexture> thumbnail;
  472. thumbnail.instantiate();
  473. Ref<Image> thumbnail_image = Image::create_empty(p_size.x, p_size.y, false, Image::Format::FORMAT_RGBA8); // blend_rect needs ALPHA channel to work
  474. thumbnail_image->blend_rect(capture_2d->get_image(), capture_2d->get_image()->get_used_rect(), Point2i(0, 0));
  475. thumbnail_image->blend_rect(capture_gui->get_image(), capture_gui->get_image()->get_used_rect(), Point2i(0, 0));
  476. thumbnail->set_image(thumbnail_image);
  477. // Clean up
  478. sub_viewport->queue_free();
  479. sub_viewport_gui->queue_free();
  480. return thumbnail;
  481. }
  482. // Is scene without any visuals (No Node2D, Node3D, Control found)
  483. return Ref<Texture2D>();
  484. }
  485. void EditorPackedScenePreviewPlugin::_setup_scene_3d(Node *p_node) const {
  486. // Do not account any SubViewport at preview scene, as it would not render correctly
  487. if (Object::cast_to<SubViewport>(p_node) && p_node->get_parent()) {
  488. p_node->get_parent()->remove_child(p_node);
  489. callable_mp(p_node, &Node::queue_free).call_deferred();
  490. return;
  491. }
  492. // Don't let window to popup
  493. Window *window = Object::cast_to<Window>(p_node);
  494. if (window) {
  495. window->set_visible(false);
  496. }
  497. // Make sure no Node2D, Control node is visible (Might occupy large proportion of the thumbnail)
  498. Node2D *n2d = Object::cast_to<Node2D>(p_node);
  499. if (n2d) {
  500. n2d->set_visible(false);
  501. }
  502. Control *ctrl = Object::cast_to<Control>(p_node);
  503. if (ctrl) {
  504. ctrl->set_visible(false);
  505. }
  506. // Disable skinning for skeleton meshes (animations and skeleton scaling might disturb aabb calculation)
  507. MeshInstance3D *mesh = Object::cast_to<MeshInstance3D>(p_node);
  508. if (mesh && mesh->is_visible_in_tree()) {
  509. mesh->set_skeleton_path(NodePath());
  510. }
  511. CPUParticles3D *cpu_particles = Object::cast_to<CPUParticles3D>(p_node);
  512. if (cpu_particles && cpu_particles->is_visible_in_tree()) {
  513. cpu_particles->set_pre_process_time(cpu_particles->get_lifetime() * 0.5); // Fast forward the particle emission to make it render something
  514. 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
  515. cpu_particles->restart(true); // Keep seed to make simulation persistent
  516. }
  517. GPUParticles3D *gpu_particles = Object::cast_to<GPUParticles3D>(p_node);
  518. if (gpu_particles && gpu_particles->is_visible_in_tree()) {
  519. // Convert to CPUParticles (As GPUParticles can't be rendered correctly in thumbnails, don't know why)
  520. CPUParticles3D *gtc_particles = memnew(CPUParticles3D); // GPU to CPU particles
  521. gtc_particles->convert_from_particles(gpu_particles);
  522. gpu_particles->add_child(gtc_particles); // So the created CPUParticles instance will be freed later we call queue_free() on the preview scene
  523. // Setup CPUParticles
  524. gtc_particles->set_pre_process_time(gtc_particles->get_lifetime() * 0.5);
  525. gtc_particles->set_use_local_coordinates(true);
  526. gtc_particles->restart(true);
  527. }
  528. for (int i = 0; i < p_node->get_child_count(); i++) {
  529. _setup_scene_3d(p_node->get_child(i));
  530. }
  531. }
  532. void EditorPackedScenePreviewPlugin::_setup_scene_2d(Node *p_node) const {
  533. // Do not account any SubViewport at preview scene, as it would not render correctly
  534. if (Object::cast_to<SubViewport>(p_node) && p_node->get_parent()) {
  535. p_node->get_parent()->remove_child(p_node);
  536. callable_mp(p_node, &Node::queue_free).call_deferred();
  537. return;
  538. }
  539. // Don't let window to popup
  540. Window *window = Object::cast_to<Window>(p_node);
  541. if (window) {
  542. window->set_visible(false);
  543. }
  544. for (int i = 0; i < p_node->get_child_count(); i++) {
  545. _setup_scene_2d(p_node->get_child(i));
  546. }
  547. }
  548. void EditorPackedScenePreviewPlugin::_count_node_types(Node *p_node, int &r_c2d, int &r_c3d, int &r_clight3d) const {
  549. if (p_node->is_class("Control") || p_node->is_class("Node2D")) {
  550. r_c2d++;
  551. }
  552. if (p_node->is_class("Node3D")) {
  553. r_c3d++;
  554. }
  555. if (p_node->is_class("Light3D")) {
  556. r_clight3d++;
  557. }
  558. for (int i = 0; i < p_node->get_child_count(); i++) {
  559. // Do not count anything under SubViewport node, those children are irrelevant for determining if the scene is 2D or 3D.
  560. if (p_node->get_child(i)->is_class("SubViewport")) {
  561. continue;
  562. }
  563. _count_node_types(p_node->get_child(i), r_c2d, r_c3d, r_clight3d);
  564. }
  565. }
  566. void EditorPackedScenePreviewPlugin::_calculate_scene_rect(Node *p_node, Rect2 &r_rect) const {
  567. // NOTE: There's no universal way to get the exact global rect as a Node2D, so we dig into subclasses one by one
  568. // NOTE:
  569. // 1. Sprite2D::position by default is at the **center** of the sprite. (with offset == (0,0) AND centered == true)
  570. // 2. Rect2::position is at the **up-left** of the rect
  571. // 3. AABB::position is at the **bottom-left-forward** of the bounding box
  572. //
  573. // calculation below is done with these in mind.
  574. Rect2 n2d_rect; // The rect of the current iterating Node2D
  575. Sprite2D *sprite = Object::cast_to<Sprite2D>(p_node);
  576. if (sprite && sprite->is_visible_in_tree()) {
  577. n2d_rect.size = sprite->get_global_scale() * sprite->get_rect().size;
  578. n2d_rect.position = sprite->get_global_position() + sprite->get_offset() * sprite->get_global_scale();
  579. if (sprite->is_centered()) {
  580. n2d_rect.position -= n2d_rect.size / 2.0f;
  581. }
  582. }
  583. AnimatedSprite2D *anim_sprite = Object::cast_to<AnimatedSprite2D>(p_node);
  584. if (anim_sprite && anim_sprite->is_visible_in_tree()) {
  585. if (anim_sprite->get_sprite_frames().is_valid()) {
  586. Ref<Texture2D> current_frame_tex = anim_sprite->get_sprite_frames()->get_frame_texture(anim_sprite->get_animation(), anim_sprite->get_frame());
  587. if (current_frame_tex.is_valid()) {
  588. n2d_rect.size = current_frame_tex->get_size() * anim_sprite->get_global_scale();
  589. n2d_rect.position = anim_sprite->get_global_position() + anim_sprite->get_offset() * anim_sprite->get_global_scale();
  590. if (anim_sprite->is_centered()) {
  591. n2d_rect.position -= n2d_rect.size / 2.0f;
  592. }
  593. }
  594. }
  595. }
  596. MeshInstance2D *mesh2d = Object::cast_to<MeshInstance2D>(p_node);
  597. if (mesh2d && mesh2d->is_visible_in_tree()) {
  598. // NOTE: Conversion is 1m = 1px (before 2d scale)
  599. Ref<Mesh> mesh = mesh2d->get_mesh();
  600. if (mesh.is_valid()) {
  601. // Discard z axis (depth) and only get length of mesh in x,y axis
  602. n2d_rect.size.x = (mesh->get_aabb().get_end() - mesh->get_aabb().position).x;
  603. n2d_rect.size.y = (mesh->get_aabb().get_end() - mesh->get_aabb().position).y;
  604. n2d_rect.size *= mesh2d->get_global_scale();
  605. // Account for mesh offset in 3d space when calculating rect2
  606. n2d_rect.position.x = mesh2d->get_global_position().x + mesh->get_aabb().position.x * mesh2d->get_global_scale().x; // AABB::position is bottom-left
  607. n2d_rect.position.y = mesh2d->get_global_position().y + mesh->get_aabb().position.y * mesh2d->get_global_scale().y;
  608. }
  609. }
  610. MultiMeshInstance2D *mmesh2d = Object::cast_to<MultiMeshInstance2D>(p_node);
  611. if (mmesh2d && mmesh2d->is_visible_in_tree()) {
  612. // Basically the same procedure as MeshInstance2D.
  613. Ref<MultiMesh> mmesh = mmesh2d->get_multimesh();
  614. if (mmesh.is_valid()) {
  615. n2d_rect.size.x = (mmesh->get_aabb().get_end() - mmesh->get_aabb().position).x;
  616. n2d_rect.size.y = (mmesh->get_aabb().get_end() - mmesh->get_aabb().position).y;
  617. n2d_rect.size *= mmesh2d->get_global_scale();
  618. n2d_rect.position.x = mmesh2d->get_global_position().x + mmesh->get_aabb().position.x * mmesh2d->get_global_scale().x;
  619. n2d_rect.position.y = mmesh2d->get_global_position().y + mmesh->get_aabb().position.y * mmesh2d->get_global_scale().y;
  620. }
  621. }
  622. TileMapLayer *tile_map = Object::cast_to<TileMapLayer>(p_node);
  623. if (tile_map && tile_map->is_visible_in_tree()) {
  624. // NOTE: TileMapLayer::get_used_rect() only count cells, not their actual pixel size
  625. if (tile_map->get_tile_set().is_valid()) {
  626. Size2 tile_size = tile_map->get_tile_set()->get_tile_size(); // Tile map cell pixel size (x,y).
  627. Rect2 tile_rect = tile_map->get_used_rect(); // Unit is in cells, not pixels!
  628. n2d_rect.position = tile_map->get_global_position() + tile_rect.position * tile_size * tile_map->get_global_scale(); // Accounts tilemap offset
  629. n2d_rect.size = tile_rect.size * tile_size * tile_map->get_global_scale();
  630. }
  631. }
  632. Polygon2D *poly2d = Object::cast_to<Polygon2D>(p_node);
  633. if (poly2d && poly2d->is_visible_in_tree()) {
  634. PackedVector2Array polygon = poly2d->get_polygon();
  635. if (polygon.size() > 2) { // Abort if there's no surface (min = 3 verts)
  636. // Calculate bounds
  637. float max_x = polygon[0].x;
  638. float min_x = polygon[0].x;
  639. float max_y = polygon[0].y;
  640. float min_y = polygon[0].y;
  641. for (int i = 0; i < polygon.size(); i++) {
  642. if (polygon[i].x > max_x) {
  643. max_x = polygon[i].x;
  644. }
  645. if (polygon[i].x < min_x) {
  646. min_x = polygon[i].x;
  647. }
  648. if (polygon[i].y > max_y) {
  649. max_y = polygon[i].y;
  650. }
  651. if (polygon[i].y < min_y) {
  652. min_y = polygon[i].y;
  653. }
  654. }
  655. Rect2 poly_rect = Rect2(min_x, min_y, max_x - min_x, max_y - min_y);
  656. n2d_rect.position = poly2d->get_global_position() + poly2d->get_offset() * poly2d->get_global_scale();
  657. n2d_rect.position += poly_rect.position * poly2d->get_global_scale();
  658. n2d_rect.size = poly_rect.size * poly2d->get_global_scale();
  659. }
  660. }
  661. Line2D *line2d = Object::cast_to<Line2D>(p_node);
  662. if (line2d && line2d->is_visible_in_tree()) {
  663. // The same procedure as Polygon2D
  664. PackedVector2Array points = line2d->get_points();
  665. if (line2d->get_point_count() > 1) { // Abort if there's no line drawn
  666. // Calculate bounds
  667. float max_x = points[0].x;
  668. float min_x = points[0].x;
  669. float max_y = points[0].y;
  670. float min_y = points[0].y;
  671. for (int i = 0; i < points.size(); i++) {
  672. if (points[i].x > max_x) {
  673. max_x = points[i].x;
  674. }
  675. if (points[i].x < min_x) {
  676. min_x = points[i].x;
  677. }
  678. if (points[i].y > max_y) {
  679. max_y = points[i].y;
  680. }
  681. if (points[i].y < min_y) {
  682. min_y = points[i].y;
  683. }
  684. }
  685. Rect2 line2d_rect = Rect2(min_x, min_y, max_x - min_x, max_y - min_y);
  686. n2d_rect.position = line2d->get_global_position();
  687. n2d_rect.position += line2d_rect.position * line2d->get_global_scale();
  688. n2d_rect.size = line2d_rect.size * line2d->get_global_scale();
  689. n2d_rect.size += Size2(line2d->get_width(), line2d->get_width()) / 2.0f; // account for line width
  690. }
  691. }
  692. TouchScreenButton *btn = Object::cast_to<TouchScreenButton>(p_node);
  693. if (btn && btn->is_visible_in_tree()) {
  694. Ref<Texture2D> btn_tex = btn->get_texture_normal();
  695. if (btn_tex.is_valid()) { // Abort if there's no normal texture for this button (won't display anything)
  696. n2d_rect.position = btn->get_global_position(); // It's not possible to offset image in this node
  697. n2d_rect.size = btn_tex->get_size() * btn->get_global_scale();
  698. }
  699. }
  700. // Merge the calculated node 2d rect
  701. if (r_rect.get_size().length_squared() == 0.0f) { // Avoid accounting scene origin (0,0) into scene rect.
  702. r_rect = n2d_rect.abs();
  703. } else {
  704. r_rect = r_rect.merge(n2d_rect.abs());
  705. }
  706. for (int i = 0; i < p_node->get_child_count(); i++) {
  707. _calculate_scene_rect(p_node->get_child(i), r_rect);
  708. }
  709. }
  710. void EditorPackedScenePreviewPlugin::_hide_node_2d_in_scene(Node *p_node) const {
  711. // NOTE: Irreversible (cannot unhide nodes after this)
  712. // We cannot simple hide() since it will affect all its children (may contain Control nodes)
  713. if (p_node->is_class("Node2D")) {
  714. Node2D *n2d = Object::cast_to<Node2D>(p_node);
  715. n2d->set_self_modulate(Color(0.0f, 0.0f, 0.0f, 0.0f));
  716. }
  717. for (int i = 0; i < p_node->get_child_count(); i++) {
  718. _hide_node_2d_in_scene(p_node->get_child(i));
  719. }
  720. }
  721. void EditorPackedScenePreviewPlugin::_hide_gui_in_scene(Node *p_node) const {
  722. // NOTE: Irreversible (cannot unhide nodes after this)
  723. // We cannot simply hide() since it will affect all its children (may contain Node2D nodes)
  724. if (p_node->is_class("Control")) {
  725. Control *ctrl = Object::cast_to<Control>(p_node);
  726. ctrl->set_self_modulate(Color(0.0f, 0.0f, 0.0f, 0.0f));
  727. }
  728. for (int i = 0; i < p_node->get_child_count(); i++) {
  729. _hide_gui_in_scene(p_node->get_child(i));
  730. }
  731. }
  732. // Hacky implementation, remove this when draw_requester.request_and_wait() is sufficient to render previews properly.
  733. // Is needed for 2 reason:
  734. // 1. Scene preview requires adding scene to tree and wait for RenderingServer to redraw.
  735. // 2. To resolve some rendering bugs by waiting extra frames.
  736. void EditorPackedScenePreviewPlugin::_wait_frame() const {
  737. const uint64_t prev_frame = Engine::get_singleton()->get_frames_drawn();
  738. while (Engine::get_singleton()->get_frames_drawn() - prev_frame < 1) {
  739. if (!EditorResourcePreview::get_singleton()->is_threaded()) {
  740. // Is running this on main thread, iterate main loop (or will get stuck here forever)
  741. DisplayServer::get_singleton()->process_events();
  742. Main::iteration();
  743. }
  744. if (aborted) {
  745. break;
  746. }
  747. continue;
  748. }
  749. }
  750. void EditorPackedScenePreviewPlugin::_calculate_scene_aabb(Node *p_node, AABB &r_aabb) const {
  751. GeometryInstance3D *g3d = Object::cast_to<GeometryInstance3D>(p_node);
  752. if (g3d && g3d->is_visible_in_tree()) { // Use this because VisualInstance3D may have derived classes that are non-graphical (probes, volumes)
  753. AABB node_aabb = _get_global_transform_3d(g3d).xform(g3d->get_aabb());
  754. r_aabb.merge_with(node_aabb);
  755. }
  756. CPUParticles3D *cpu_particles = Object::cast_to<CPUParticles3D>(p_node);
  757. if (cpu_particles && cpu_particles->is_visible_in_tree()) { // CPUParticles3D does not calculate particle bounds, so do it here
  758. // Account the furthest position where particles can go
  759. Vector3 particle_destination = _get_global_transform_3d(cpu_particles).origin;
  760. particle_destination += cpu_particles->get_direction() * cpu_particles->get_param_max(CPUParticles3D::PARAM_INITIAL_LINEAR_VELOCITY);
  761. r_aabb.expand_to(particle_destination * 0.5);
  762. r_aabb.expand_to(particle_destination * -0.5);
  763. }
  764. GPUParticles3D *gpu_particles = Object::cast_to<GPUParticles3D>(p_node);
  765. if (gpu_particles && gpu_particles->is_visible_in_tree()) {
  766. r_aabb.merge_with(_get_global_transform_3d(gpu_particles).xform(gpu_particles->get_visibility_aabb()));
  767. }
  768. for (int i = 0; i < p_node->get_child_count(); i++) {
  769. _calculate_scene_aabb(p_node->get_child(i), r_aabb);
  770. }
  771. }
  772. Transform3D EditorPackedScenePreviewPlugin::_get_global_transform_3d(Node *p_n3d) const {
  773. // Designed to work even if node is outside the tree (is_inside_tree() != true)
  774. Transform3D global_transform;
  775. Array parents;
  776. if (!p_n3d->is_class("Node3D")) {
  777. ERR_PRINT("Expected a Node3D node as argument");
  778. return global_transform;
  779. }
  780. Node *p_loop_node = p_n3d;
  781. while (p_loop_node != nullptr) {
  782. if (p_loop_node->is_class("Node3D")) {
  783. parents.append(p_loop_node);
  784. }
  785. p_loop_node = p_loop_node->get_parent();
  786. }
  787. parents.reverse();
  788. for (int i = 0; i < parents.size(); i++) {
  789. Node3D *p_parent = Object::cast_to<Node3D>(parents[i]);
  790. if (i == 0) {
  791. global_transform = p_parent->get_transform();
  792. continue;
  793. }
  794. global_transform *= p_parent->get_transform();
  795. }
  796. return global_transform;
  797. }
  798. bool EditorPackedScenePreviewPlugin::_setup_packed_scene(Ref<PackedScene> p_pack) const {
  799. // Refer to SceneState in packed_scene.cpp to see how PackedScene is managed underhood.
  800. // Sanitize
  801. Dictionary bundle = p_pack->get_state()->get_bundled_scene();
  802. ERR_FAIL_COND_V(!bundle.has("names"), false);
  803. ERR_FAIL_COND_V(!bundle.has("variants"), false);
  804. ERR_FAIL_COND_V(!bundle.has("node_count"), false);
  805. ERR_FAIL_COND_V(!bundle.has("nodes"), false);
  806. ERR_FAIL_COND_V(!bundle.has("conn_count"), false);
  807. ERR_FAIL_COND_V(!bundle.has("conns"), false);
  808. const uint8_t supported_version = 3;
  809. uint8_t current_version = bundle.get("version", 1);
  810. if (current_version > supported_version) {
  811. 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));
  812. // And assume it's safe to continue, there should have no reason to change the main structure of PackedScene
  813. }
  814. // Find and remove variants in scene
  815. const Ref<Script> dummy = 0;
  816. Array edited_variants = bundle["variants"];
  817. if (edited_variants.is_empty()) {
  818. return true; // Scene has no resources at all
  819. }
  820. for (int i = 0; i < edited_variants.size(); i++) {
  821. // Clear script
  822. if (edited_variants[i].get_type() == Variant::OBJECT) {
  823. if (Object::cast_to<Script>(edited_variants[i])) {
  824. edited_variants[i] = dummy;
  825. }
  826. if (Object::cast_to<PackedScene>(edited_variants[i])) {
  827. // Recursively apply to all child scenes
  828. _setup_packed_scene(edited_variants[i]);
  829. }
  830. }
  831. // Clear arrays ( Because leaving array of NodePaths is problematic when scripts are removed )
  832. if (edited_variants[i].get_type() == Variant::ARRAY) {
  833. edited_variants[i] = 0;
  834. }
  835. }
  836. // Remove signal bindings (As scripts are all removed)
  837. bundle["conns"] = Array();
  838. bundle["conn_count"] = Array();
  839. // Create a new scene state
  840. bundle["variants"] = edited_variants;
  841. Ref<SceneState> new_state;
  842. new_state.instantiate();
  843. new_state->set_bundled_scene(bundle);
  844. p_pack->replace_state(new_state);
  845. return true;
  846. }
  847. //////////////////////////////////////////////////////////////////
  848. void EditorMaterialPreviewPlugin::abort() {
  849. draw_requester.abort();
  850. }
  851. bool EditorMaterialPreviewPlugin::handles(const String &p_type) const {
  852. return ClassDB::is_parent_class(p_type, "Material"); // Any material.
  853. }
  854. bool EditorMaterialPreviewPlugin::generate_small_preview_automatically() const {
  855. return true;
  856. }
  857. Ref<Texture2D> EditorMaterialPreviewPlugin::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  858. Ref<Material> material = p_from;
  859. ERR_FAIL_COND_V(material.is_null(), Ref<Texture2D>());
  860. if (material->get_shader_mode() == Shader::MODE_SPATIAL) {
  861. RS::get_singleton()->mesh_surface_set_material(sphere, 0, material->get_rid());
  862. draw_requester.request_and_wait(viewport);
  863. if (EditorResourcePreview::get_singleton()->is_threaded()) {
  864. draw_requester.request_and_wait(viewport); // HACK - Prevents incorrect thumbnail assignment when using Forward or Mobile renderer, comment out this line to see the bug.
  865. }
  866. Ref<Image> img = RS::get_singleton()->texture_2d_get(viewport_texture);
  867. RS::get_singleton()->mesh_surface_set_material(sphere, 0, RID());
  868. ERR_FAIL_COND_V(img.is_null(), Ref<ImageTexture>());
  869. img->convert(Image::FORMAT_RGBA8);
  870. int thumbnail_size = MAX(p_size.x, p_size.y);
  871. img->resize(thumbnail_size, thumbnail_size, Image::INTERPOLATE_CUBIC);
  872. post_process_preview(img);
  873. return ImageTexture::create_from_image(img);
  874. }
  875. return Ref<Texture2D>();
  876. }
  877. EditorMaterialPreviewPlugin::EditorMaterialPreviewPlugin() {
  878. scenario = RS::get_singleton()->scenario_create();
  879. viewport = RS::get_singleton()->viewport_create();
  880. RS::get_singleton()->viewport_set_update_mode(viewport, RS::VIEWPORT_UPDATE_DISABLED);
  881. RS::get_singleton()->viewport_set_scenario(viewport, scenario);
  882. RS::get_singleton()->viewport_set_size(viewport, 128, 128);
  883. RS::get_singleton()->viewport_set_transparent_background(viewport, true);
  884. RS::get_singleton()->viewport_set_active(viewport, true);
  885. viewport_texture = RS::get_singleton()->viewport_get_texture(viewport);
  886. camera = RS::get_singleton()->camera_create();
  887. RS::get_singleton()->viewport_attach_camera(viewport, camera);
  888. RS::get_singleton()->camera_set_transform(camera, Transform3D(Basis(), Vector3(0, 0, 3)));
  889. RS::get_singleton()->camera_set_perspective(camera, 45, 0.1, 10);
  890. if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
  891. camera_attributes = RS::get_singleton()->camera_attributes_create();
  892. RS::get_singleton()->camera_attributes_set_exposure(camera_attributes, 1.0, 0.000032552); // Matches default CameraAttributesPhysical to work well with default DirectionalLight3Ds.
  893. RS::get_singleton()->camera_set_camera_attributes(camera, camera_attributes);
  894. }
  895. light = RS::get_singleton()->directional_light_create();
  896. light_instance = RS::get_singleton()->instance_create2(light, scenario);
  897. RS::get_singleton()->instance_set_transform(light_instance, Transform3D().looking_at(Vector3(-1, -1, -1), Vector3(0, 1, 0)));
  898. light2 = RS::get_singleton()->directional_light_create();
  899. RS::get_singleton()->light_set_color(light2, Color(0.7, 0.7, 0.7));
  900. //RS::get_singleton()->light_set_color(light2, Color(0.7, 0.7, 0.7));
  901. light_instance2 = RS::get_singleton()->instance_create2(light2, scenario);
  902. RS::get_singleton()->instance_set_transform(light_instance2, Transform3D().looking_at(Vector3(0, 1, 0), Vector3(0, 0, 1)));
  903. sphere = RS::get_singleton()->mesh_create();
  904. sphere_instance = RS::get_singleton()->instance_create2(sphere, scenario);
  905. int lats = 32;
  906. int lons = 32;
  907. const double lat_step = Math::TAU / lats;
  908. const double lon_step = Math::TAU / lons;
  909. real_t radius = 1.0;
  910. Vector<Vector3> vertices;
  911. Vector<Vector3> normals;
  912. Vector<Vector2> uvs;
  913. Vector<real_t> tangents;
  914. Basis tt = Basis(Vector3(0, 1, 0), Math::PI * 0.5);
  915. for (int i = 1; i <= lats; i++) {
  916. double lat0 = lat_step * (i - 1) - Math::TAU / 4;
  917. double z0 = Math::sin(lat0);
  918. double zr0 = Math::cos(lat0);
  919. double lat1 = lat_step * i - Math::TAU / 4;
  920. double z1 = Math::sin(lat1);
  921. double zr1 = Math::cos(lat1);
  922. for (int j = lons; j >= 1; j--) {
  923. double lng0 = lon_step * (j - 1);
  924. double x0 = Math::cos(lng0);
  925. double y0 = Math::sin(lng0);
  926. double lng1 = lon_step * j;
  927. double x1 = Math::cos(lng1);
  928. double y1 = Math::sin(lng1);
  929. Vector3 v[4] = {
  930. Vector3(x1 * zr0, z0, y1 * zr0),
  931. Vector3(x1 * zr1, z1, y1 * zr1),
  932. Vector3(x0 * zr1, z1, y0 * zr1),
  933. Vector3(x0 * zr0, z0, y0 * zr0)
  934. };
  935. #define ADD_POINT(m_idx) \
  936. normals.push_back(v[m_idx]); \
  937. vertices.push_back(v[m_idx] * radius); \
  938. { \
  939. Vector2 uv(Math::atan2(v[m_idx].x, v[m_idx].z), Math::atan2(-v[m_idx].y, v[m_idx].z)); \
  940. uv /= Math::PI; \
  941. uv *= 4.0; \
  942. uv = uv * 0.5 + Vector2(0.5, 0.5); \
  943. uvs.push_back(uv); \
  944. } \
  945. { \
  946. Vector3 t = tt.xform(v[m_idx]); \
  947. tangents.push_back(t.x); \
  948. tangents.push_back(t.y); \
  949. tangents.push_back(t.z); \
  950. tangents.push_back(1.0); \
  951. }
  952. ADD_POINT(0);
  953. ADD_POINT(1);
  954. ADD_POINT(2);
  955. ADD_POINT(2);
  956. ADD_POINT(3);
  957. ADD_POINT(0);
  958. }
  959. }
  960. Array arr;
  961. arr.resize(RS::ARRAY_MAX);
  962. arr[RS::ARRAY_VERTEX] = vertices;
  963. arr[RS::ARRAY_NORMAL] = normals;
  964. arr[RS::ARRAY_TANGENT] = tangents;
  965. arr[RS::ARRAY_TEX_UV] = uvs;
  966. RS::get_singleton()->mesh_add_surface_from_arrays(sphere, RS::PRIMITIVE_TRIANGLES, arr);
  967. }
  968. EditorMaterialPreviewPlugin::~EditorMaterialPreviewPlugin() {
  969. ERR_FAIL_NULL(RenderingServer::get_singleton());
  970. RS::get_singleton()->free(sphere);
  971. RS::get_singleton()->free(sphere_instance);
  972. RS::get_singleton()->free(viewport);
  973. RS::get_singleton()->free(light);
  974. RS::get_singleton()->free(light_instance);
  975. RS::get_singleton()->free(light2);
  976. RS::get_singleton()->free(light_instance2);
  977. RS::get_singleton()->free(camera);
  978. RS::get_singleton()->free(camera_attributes);
  979. RS::get_singleton()->free(scenario);
  980. }
  981. ///////////////////////////////////////////////////////////////////////////
  982. bool EditorScriptPreviewPlugin::handles(const String &p_type) const {
  983. return ClassDB::is_parent_class(p_type, "Script");
  984. }
  985. Ref<Texture2D> EditorScriptPreviewPlugin::generate_from_path(const String &p_path, const Size2 &p_size, Dictionary &p_metadata) const {
  986. Error err;
  987. String code = FileAccess::get_file_as_string(p_path, &err);
  988. if (err != OK) {
  989. return Ref<Texture2D>();
  990. }
  991. ScriptLanguage *lang = ScriptServer::get_language_for_extension(p_path.get_extension());
  992. return _generate_from_source_code(lang, code, p_size, p_metadata);
  993. }
  994. Ref<Texture2D> EditorScriptPreviewPlugin::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  995. Ref<Script> scr = p_from;
  996. if (scr.is_null()) {
  997. return Ref<Texture2D>();
  998. }
  999. String code = scr->get_source_code().strip_edges();
  1000. return _generate_from_source_code(scr->get_language(), code, p_size, p_metadata);
  1001. }
  1002. Ref<Texture2D> EditorScriptPreviewPlugin::_generate_from_source_code(const ScriptLanguage *p_language, const String &p_source_code, const Size2 &p_size, Dictionary &p_metadata) const {
  1003. if (p_source_code.is_empty()) {
  1004. return Ref<Texture2D>();
  1005. }
  1006. HashSet<String> control_flow_keywords;
  1007. HashSet<String> keywords;
  1008. if (p_language) {
  1009. for (const String &keyword : p_language->get_reserved_words()) {
  1010. if (p_language->is_control_flow_keyword(keyword)) {
  1011. control_flow_keywords.insert(keyword);
  1012. } else {
  1013. keywords.insert(keyword);
  1014. }
  1015. }
  1016. }
  1017. int line = 0;
  1018. int col = 0;
  1019. int thumbnail_size = MAX(p_size.x, p_size.y);
  1020. Ref<Image> img = Image::create_empty(thumbnail_size, thumbnail_size, false, Image::FORMAT_RGBA8);
  1021. Color bg_color = EDITOR_GET("text_editor/theme/highlighting/background_color");
  1022. Color keyword_color = EDITOR_GET("text_editor/theme/highlighting/keyword_color");
  1023. Color control_flow_keyword_color = EDITOR_GET("text_editor/theme/highlighting/control_flow_keyword_color");
  1024. Color text_color = EDITOR_GET("text_editor/theme/highlighting/text_color");
  1025. Color symbol_color = EDITOR_GET("text_editor/theme/highlighting/symbol_color");
  1026. Color comment_color = EDITOR_GET("text_editor/theme/highlighting/comment_color");
  1027. Color doc_comment_color = EDITOR_GET("text_editor/theme/highlighting/doc_comment_color");
  1028. if (bg_color.a == 0) {
  1029. bg_color = Color(0, 0, 0, 0);
  1030. }
  1031. bg_color.a = MAX(bg_color.a, 0.2); // Ensure we have some background, regardless of the text editor setting.
  1032. img->fill(bg_color);
  1033. const int x0 = thumbnail_size / 8;
  1034. const int y0 = thumbnail_size / 8;
  1035. const int available_height = thumbnail_size - 2 * y0;
  1036. col = x0;
  1037. bool prev_is_text = false;
  1038. bool in_control_flow_keyword = false;
  1039. bool in_keyword = false;
  1040. bool in_comment = false;
  1041. bool in_doc_comment = false;
  1042. for (int i = 0; i < p_source_code.length(); i++) {
  1043. char32_t c = p_source_code[i];
  1044. if (c > 32) {
  1045. if (col < thumbnail_size) {
  1046. Color color = text_color;
  1047. if (c == '#') {
  1048. if (i < p_source_code.length() - 1 && p_source_code[i + 1] == '#') {
  1049. in_doc_comment = true;
  1050. } else {
  1051. in_comment = true;
  1052. }
  1053. }
  1054. if (in_comment) {
  1055. color = comment_color;
  1056. } else if (in_doc_comment) {
  1057. color = doc_comment_color;
  1058. } else {
  1059. if (is_symbol(c)) {
  1060. // Make symbol a little visible.
  1061. color = symbol_color;
  1062. in_control_flow_keyword = false;
  1063. in_keyword = false;
  1064. } else if (!prev_is_text && is_ascii_identifier_char(c)) {
  1065. int pos = i;
  1066. while (is_ascii_identifier_char(p_source_code[pos])) {
  1067. pos++;
  1068. }
  1069. String word = p_source_code.substr(i, pos - i);
  1070. if (control_flow_keywords.has(word)) {
  1071. in_control_flow_keyword = true;
  1072. } else if (keywords.has(word)) {
  1073. in_keyword = true;
  1074. }
  1075. } else if (!is_ascii_identifier_char(c)) {
  1076. in_keyword = false;
  1077. }
  1078. if (in_control_flow_keyword) {
  1079. color = control_flow_keyword_color;
  1080. } else if (in_keyword) {
  1081. color = keyword_color;
  1082. }
  1083. }
  1084. Color ul = color;
  1085. ul.a *= 0.5;
  1086. img->set_pixel(col, y0 + line * 2, bg_color.blend(ul));
  1087. img->set_pixel(col, y0 + line * 2 + 1, color);
  1088. prev_is_text = is_ascii_identifier_char(c);
  1089. }
  1090. col++;
  1091. } else {
  1092. prev_is_text = false;
  1093. in_control_flow_keyword = false;
  1094. in_keyword = false;
  1095. if (c == '\n') {
  1096. in_comment = false;
  1097. in_doc_comment = false;
  1098. col = x0;
  1099. line++;
  1100. if (line >= available_height / 2) {
  1101. break;
  1102. }
  1103. } else if (c == '\t') {
  1104. col += 3;
  1105. } else {
  1106. col++;
  1107. }
  1108. }
  1109. }
  1110. post_process_preview(img);
  1111. return ImageTexture::create_from_image(img);
  1112. }
  1113. ///////////////////////////////////////////////////////////////////
  1114. bool EditorAudioStreamPreviewPlugin::handles(const String &p_type) const {
  1115. return ClassDB::is_parent_class(p_type, "AudioStream");
  1116. }
  1117. Ref<Texture2D> EditorAudioStreamPreviewPlugin::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  1118. Ref<AudioStream> stream = p_from;
  1119. ERR_FAIL_COND_V(stream.is_null(), Ref<Texture2D>());
  1120. Vector<uint8_t> img;
  1121. int w = p_size.x;
  1122. int h = p_size.y;
  1123. img.resize(w * h * 3);
  1124. uint8_t *imgdata = img.ptrw();
  1125. uint8_t *imgw = imgdata;
  1126. Ref<AudioStreamPlayback> playback = stream->instantiate_playback();
  1127. ERR_FAIL_COND_V(playback.is_null(), Ref<Texture2D>());
  1128. real_t len_s = stream->get_length();
  1129. if (len_s == 0) {
  1130. len_s = 60; //one minute audio if no length specified
  1131. }
  1132. int frame_length = AudioServer::get_singleton()->get_mix_rate() * len_s;
  1133. Vector<AudioFrame> frames;
  1134. frames.resize(frame_length);
  1135. playback->start();
  1136. playback->mix(frames.ptrw(), 1, frames.size());
  1137. playback->stop();
  1138. for (int i = 0; i < w; i++) {
  1139. real_t max = -1000;
  1140. real_t min = 1000;
  1141. int from = uint64_t(i) * frame_length / w;
  1142. int to = (uint64_t(i) + 1) * frame_length / w;
  1143. to = MIN(to, frame_length);
  1144. from = MIN(from, frame_length - 1);
  1145. if (to == from) {
  1146. to = from + 1;
  1147. }
  1148. for (int j = from; j < to; j++) {
  1149. max = MAX(max, frames[j].left);
  1150. max = MAX(max, frames[j].right);
  1151. min = MIN(min, frames[j].left);
  1152. min = MIN(min, frames[j].right);
  1153. }
  1154. int pfrom = CLAMP((min * 0.5 + 0.5) * h / 2, 0, h / 2) + h / 4;
  1155. int pto = CLAMP((max * 0.5 + 0.5) * h / 2, 0, h / 2) + h / 4;
  1156. for (int j = 0; j < h; j++) {
  1157. uint8_t *p = &imgw[(j * w + i) * 3];
  1158. if (j < pfrom || j > pto) {
  1159. p[0] = 100;
  1160. p[1] = 100;
  1161. p[2] = 100;
  1162. } else {
  1163. p[0] = 180;
  1164. p[1] = 180;
  1165. p[2] = 180;
  1166. }
  1167. }
  1168. }
  1169. p_metadata["length"] = stream->get_length();
  1170. //post_process_preview(img);
  1171. Ref<Image> image = Image::create_from_data(w, h, false, Image::FORMAT_RGB8, img);
  1172. return ImageTexture::create_from_image(image);
  1173. }
  1174. ///////////////////////////////////////////////////////////////////////////
  1175. void EditorMeshPreviewPlugin::abort() {
  1176. draw_requester.abort();
  1177. }
  1178. bool EditorMeshPreviewPlugin::handles(const String &p_type) const {
  1179. return ClassDB::is_parent_class(p_type, "Mesh"); // Any mesh.
  1180. }
  1181. Ref<Texture2D> EditorMeshPreviewPlugin::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  1182. Ref<Mesh> mesh = p_from;
  1183. ERR_FAIL_COND_V(mesh.is_null(), Ref<Texture2D>());
  1184. RS::get_singleton()->instance_set_base(mesh_instance, mesh->get_rid());
  1185. AABB aabb = mesh->get_aabb();
  1186. Vector3 ofs = aabb.get_center();
  1187. aabb.position -= ofs;
  1188. Transform3D xform;
  1189. xform.basis = Basis().rotated(Vector3(0, 1, 0), -Math::PI * 0.125);
  1190. xform.basis = Basis().rotated(Vector3(1, 0, 0), Math::PI * 0.125) * xform.basis;
  1191. AABB rot_aabb = xform.xform(aabb);
  1192. real_t m = MAX(rot_aabb.size.x, rot_aabb.size.y) * 0.5;
  1193. if (m == 0) {
  1194. return Ref<Texture2D>();
  1195. }
  1196. m = 1.0 / m;
  1197. m *= 0.5;
  1198. xform.basis.scale(Vector3(m, m, m));
  1199. xform.origin = -xform.basis.xform(ofs); //-ofs*m;
  1200. xform.origin.z -= rot_aabb.size.z * 2;
  1201. RS::get_singleton()->instance_set_transform(mesh_instance, xform);
  1202. draw_requester.request_and_wait(viewport);
  1203. if (EditorResourcePreview::get_singleton()->is_threaded()) {
  1204. draw_requester.request_and_wait(viewport); // Wait twice when run on thread, or else won't render correctly. comment this line to see the bug
  1205. }
  1206. Ref<Image> img = RS::get_singleton()->texture_2d_get(viewport_texture);
  1207. ERR_FAIL_COND_V(img.is_null(), Ref<ImageTexture>());
  1208. RS::get_singleton()->instance_set_base(mesh_instance, RID());
  1209. img->convert(Image::FORMAT_RGBA8);
  1210. Vector2 new_size = img->get_size();
  1211. if (new_size.x > p_size.x) {
  1212. new_size = Vector2(p_size.x, new_size.y * p_size.x / new_size.x);
  1213. }
  1214. if (new_size.y > p_size.y) {
  1215. new_size = Vector2(new_size.x * p_size.y / new_size.y, p_size.y);
  1216. }
  1217. img->resize(new_size.x, new_size.y, Image::INTERPOLATE_CUBIC);
  1218. post_process_preview(img);
  1219. return ImageTexture::create_from_image(img);
  1220. }
  1221. EditorMeshPreviewPlugin::EditorMeshPreviewPlugin() {
  1222. scenario = RS::get_singleton()->scenario_create();
  1223. viewport = RS::get_singleton()->viewport_create();
  1224. RS::get_singleton()->viewport_set_update_mode(viewport, RS::VIEWPORT_UPDATE_DISABLED);
  1225. RS::get_singleton()->viewport_set_scenario(viewport, scenario);
  1226. RS::get_singleton()->viewport_set_size(viewport, 128, 128);
  1227. RS::get_singleton()->viewport_set_transparent_background(viewport, true);
  1228. RS::get_singleton()->viewport_set_active(viewport, true);
  1229. viewport_texture = RS::get_singleton()->viewport_get_texture(viewport);
  1230. camera = RS::get_singleton()->camera_create();
  1231. RS::get_singleton()->viewport_attach_camera(viewport, camera);
  1232. RS::get_singleton()->camera_set_transform(camera, Transform3D(Basis(), Vector3(0, 0, 3)));
  1233. //RS::get_singleton()->camera_set_perspective(camera,45,0.1,10);
  1234. RS::get_singleton()->camera_set_orthogonal(camera, 1.0, 0.01, 1000.0);
  1235. if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
  1236. camera_attributes = RS::get_singleton()->camera_attributes_create();
  1237. RS::get_singleton()->camera_attributes_set_exposure(camera_attributes, 1.0, 0.000032552); // Matches default CameraAttributesPhysical to work well with default DirectionalLight3Ds.
  1238. RS::get_singleton()->camera_set_camera_attributes(camera, camera_attributes);
  1239. }
  1240. light = RS::get_singleton()->directional_light_create();
  1241. light_instance = RS::get_singleton()->instance_create2(light, scenario);
  1242. RS::get_singleton()->instance_set_transform(light_instance, Transform3D().looking_at(Vector3(-1, -1, -1), Vector3(0, 1, 0)));
  1243. light2 = RS::get_singleton()->directional_light_create();
  1244. RS::get_singleton()->light_set_color(light2, Color(0.7, 0.7, 0.7));
  1245. //RS::get_singleton()->light_set_color(light2, RS::LIGHT_COLOR_SPECULAR, Color(0.0, 0.0, 0.0));
  1246. light_instance2 = RS::get_singleton()->instance_create2(light2, scenario);
  1247. RS::get_singleton()->instance_set_transform(light_instance2, Transform3D().looking_at(Vector3(0, 1, 0), Vector3(0, 0, 1)));
  1248. //sphere = RS::get_singleton()->mesh_create();
  1249. mesh_instance = RS::get_singleton()->instance_create();
  1250. RS::get_singleton()->instance_set_scenario(mesh_instance, scenario);
  1251. }
  1252. EditorMeshPreviewPlugin::~EditorMeshPreviewPlugin() {
  1253. ERR_FAIL_NULL(RenderingServer::get_singleton());
  1254. //RS::get_singleton()->free(sphere);
  1255. RS::get_singleton()->free(mesh_instance);
  1256. RS::get_singleton()->free(viewport);
  1257. RS::get_singleton()->free(light);
  1258. RS::get_singleton()->free(light_instance);
  1259. RS::get_singleton()->free(light2);
  1260. RS::get_singleton()->free(light_instance2);
  1261. RS::get_singleton()->free(camera);
  1262. RS::get_singleton()->free(camera_attributes);
  1263. RS::get_singleton()->free(scenario);
  1264. }
  1265. ///////////////////////////////////////////////////////////////////////////
  1266. void EditorFontPreviewPlugin::abort() {
  1267. draw_requester.abort();
  1268. }
  1269. bool EditorFontPreviewPlugin::handles(const String &p_type) const {
  1270. return ClassDB::is_parent_class(p_type, "Font");
  1271. }
  1272. Ref<Texture2D> EditorFontPreviewPlugin::generate_from_path(const String &p_path, const Size2 &p_size, Dictionary &p_metadata) const {
  1273. Ref<Font> sampled_font = ResourceLoader::load(p_path);
  1274. ERR_FAIL_COND_V(sampled_font.is_null(), Ref<Texture2D>());
  1275. String sample;
  1276. static const String sample_base = U"12漢字ԱբΑαАбΑαאבابܐܒހށआআਆઆଆஆఆಆആආกิກິༀကႠა한글ሀᎣᐁᚁᚠᜀᜠᝀᝠកᠠᤁᥐAb😀";
  1277. for (int i = 0; i < sample_base.length(); i++) {
  1278. if (sampled_font->has_char(sample_base[i])) {
  1279. sample += sample_base[i];
  1280. }
  1281. }
  1282. if (sample.is_empty()) {
  1283. sample = sampled_font->get_supported_chars().substr(0, 6);
  1284. }
  1285. Vector2 size = sampled_font->get_string_size(sample, HORIZONTAL_ALIGNMENT_LEFT, -1, 50);
  1286. Vector2 pos;
  1287. pos.x = 64 - size.x / 2;
  1288. pos.y = 80;
  1289. const Color c = GLOBAL_GET("rendering/environment/defaults/default_clear_color");
  1290. const float fg = c.get_luminance() < 0.5 ? 1.0 : 0.0;
  1291. sampled_font->draw_string(canvas_item, pos, sample, HORIZONTAL_ALIGNMENT_LEFT, -1.f, 50, Color(fg, fg, fg));
  1292. draw_requester.request_and_wait(viewport);
  1293. RS::get_singleton()->canvas_item_clear(canvas_item);
  1294. Ref<Image> img = RS::get_singleton()->texture_2d_get(viewport_texture);
  1295. ERR_FAIL_COND_V(img.is_null(), Ref<ImageTexture>());
  1296. img->convert(Image::FORMAT_RGBA8);
  1297. Vector2 new_size = img->get_size();
  1298. if (new_size.x > p_size.x) {
  1299. new_size = Vector2(p_size.x, new_size.y * p_size.x / new_size.x);
  1300. }
  1301. if (new_size.y > p_size.y) {
  1302. new_size = Vector2(new_size.x * p_size.y / new_size.y, p_size.y);
  1303. }
  1304. img->resize(new_size.x, new_size.y, Image::INTERPOLATE_CUBIC);
  1305. post_process_preview(img);
  1306. return ImageTexture::create_from_image(img);
  1307. }
  1308. Ref<Texture2D> EditorFontPreviewPlugin::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  1309. String path = p_from->get_path();
  1310. if (!FileAccess::exists(path)) {
  1311. return Ref<Texture2D>();
  1312. }
  1313. return generate_from_path(path, p_size, p_metadata);
  1314. }
  1315. EditorFontPreviewPlugin::EditorFontPreviewPlugin() {
  1316. viewport = RS::get_singleton()->viewport_create();
  1317. RS::get_singleton()->viewport_set_update_mode(viewport, RS::VIEWPORT_UPDATE_DISABLED);
  1318. RS::get_singleton()->viewport_set_size(viewport, 128, 128);
  1319. RS::get_singleton()->viewport_set_active(viewport, true);
  1320. viewport_texture = RS::get_singleton()->viewport_get_texture(viewport);
  1321. canvas = RS::get_singleton()->canvas_create();
  1322. canvas_item = RS::get_singleton()->canvas_item_create();
  1323. RS::get_singleton()->viewport_attach_canvas(viewport, canvas);
  1324. RS::get_singleton()->canvas_item_set_parent(canvas_item, canvas);
  1325. }
  1326. EditorFontPreviewPlugin::~EditorFontPreviewPlugin() {
  1327. ERR_FAIL_NULL(RenderingServer::get_singleton());
  1328. RS::get_singleton()->free(canvas_item);
  1329. RS::get_singleton()->free(canvas);
  1330. RS::get_singleton()->free(viewport);
  1331. }
  1332. ////////////////////////////////////////////////////////////////////////////
  1333. static const real_t GRADIENT_PREVIEW_TEXTURE_SCALE_FACTOR = 4.0;
  1334. bool EditorGradientPreviewPlugin::handles(const String &p_type) const {
  1335. return ClassDB::is_parent_class(p_type, "Gradient");
  1336. }
  1337. bool EditorGradientPreviewPlugin::generate_small_preview_automatically() const {
  1338. return true;
  1339. }
  1340. Ref<Texture2D> EditorGradientPreviewPlugin::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  1341. Ref<Gradient> gradient = p_from;
  1342. if (gradient.is_valid()) {
  1343. Ref<GradientTexture1D> ptex;
  1344. ptex.instantiate();
  1345. ptex->set_width(p_size.width * GRADIENT_PREVIEW_TEXTURE_SCALE_FACTOR * EDSCALE);
  1346. ptex->set_gradient(gradient);
  1347. return ImageTexture::create_from_image(ptex->get_image());
  1348. }
  1349. return Ref<Texture2D>();
  1350. }