editor_profiler.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. /**************************************************************************/
  2. /* editor_profiler.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_profiler.h"
  31. #include "core/io/image.h"
  32. #include "core/os/os.h"
  33. #include "editor/editor_settings.h"
  34. #include "editor/editor_string_names.h"
  35. #include "editor/themes/editor_scale.h"
  36. #include "editor/themes/editor_theme_manager.h"
  37. #include "scene/gui/check_box.h"
  38. #include "scene/resources/image_texture.h"
  39. void EditorProfiler::_make_metric_ptrs(Metric &m) {
  40. for (int i = 0; i < m.categories.size(); i++) {
  41. m.category_ptrs[m.categories[i].signature] = &m.categories.write[i];
  42. for (int j = 0; j < m.categories[i].items.size(); j++) {
  43. m.item_ptrs[m.categories[i].items[j].signature] = &m.categories.write[i].items.write[j];
  44. }
  45. }
  46. }
  47. EditorProfiler::Metric EditorProfiler::_get_frame_metric(int index) {
  48. return frame_metrics[(frame_metrics.size() + last_metric - (total_metrics - 1) + index) % frame_metrics.size()];
  49. }
  50. void EditorProfiler::add_frame_metric(const Metric &p_metric, bool p_final) {
  51. ++last_metric;
  52. if (last_metric >= frame_metrics.size()) {
  53. last_metric = 0;
  54. }
  55. total_metrics++;
  56. if (total_metrics > frame_metrics.size()) {
  57. total_metrics = frame_metrics.size();
  58. }
  59. frame_metrics.write[last_metric] = p_metric;
  60. _make_metric_ptrs(frame_metrics.write[last_metric]);
  61. updating_frame = true;
  62. clear_button->set_disabled(false);
  63. cursor_metric_edit->set_editable(true);
  64. cursor_metric_edit->set_max(p_metric.frame_number);
  65. cursor_metric_edit->set_min(_get_frame_metric(0).frame_number);
  66. if (!seeking) {
  67. cursor_metric_edit->set_value(p_metric.frame_number);
  68. }
  69. updating_frame = false;
  70. if (frame_delay->is_stopped()) {
  71. frame_delay->set_wait_time(p_final ? 0.1 : 1);
  72. frame_delay->start();
  73. }
  74. if (plot_delay->is_stopped()) {
  75. plot_delay->set_wait_time(0.1);
  76. plot_delay->start();
  77. }
  78. }
  79. void EditorProfiler::clear() {
  80. int metric_size = EDITOR_GET("debugger/profiler_frame_history_size");
  81. metric_size = CLAMP(metric_size, 60, 10000);
  82. frame_metrics.clear();
  83. frame_metrics.resize(metric_size);
  84. total_metrics = 0;
  85. last_metric = -1;
  86. variables->clear();
  87. plot_sigs.clear();
  88. plot_sigs.insert("physics_frame_time");
  89. plot_sigs.insert("category_frame_time");
  90. display_internal_profiles->set_visible(EDITOR_GET("debugger/profile_native_calls"));
  91. updating_frame = true;
  92. cursor_metric_edit->set_min(0);
  93. cursor_metric_edit->set_max(100); // Doesn't make much sense, but we can't have min == max. Doesn't hurt.
  94. cursor_metric_edit->set_value(0);
  95. cursor_metric_edit->set_editable(false);
  96. updating_frame = false;
  97. hover_metric = -1;
  98. seeking = false;
  99. // Ensure button text (start, stop) is correct
  100. _update_button_text();
  101. emit_signal(SNAME("enable_profiling"), activate->is_pressed());
  102. }
  103. static String _get_percent_txt(float p_value, float p_total) {
  104. if (p_total == 0) {
  105. p_total = 0.00001;
  106. }
  107. return TS->format_number(String::num((p_value / p_total) * 100, 1)) + TS->percent_sign();
  108. }
  109. String EditorProfiler::_get_time_as_text(const Metric &m, float p_time, int p_calls) {
  110. const int dmode = display_mode->get_selected();
  111. if (dmode == DISPLAY_FRAME_TIME) {
  112. return TS->format_number(rtos(p_time * 1000).pad_decimals(2)) + " " + TTR("ms");
  113. } else if (dmode == DISPLAY_AVERAGE_TIME) {
  114. if (p_calls == 0) {
  115. return TS->format_number("0.00") + " " + TTR("ms");
  116. } else {
  117. return TS->format_number(rtos((p_time / p_calls) * 1000).pad_decimals(2)) + " " + TTR("ms");
  118. }
  119. } else if (dmode == DISPLAY_FRAME_PERCENT) {
  120. return _get_percent_txt(p_time, m.frame_time);
  121. } else if (dmode == DISPLAY_PHYSICS_FRAME_PERCENT) {
  122. return _get_percent_txt(p_time, m.physics_frame_time);
  123. }
  124. return "err";
  125. }
  126. Color EditorProfiler::_get_color_from_signature(const StringName &p_signature) const {
  127. Color bc = get_theme_color(SNAME("error_color"), EditorStringName(Editor));
  128. double rot = ABS(double(p_signature.hash()) / double(0x7FFFFFFF));
  129. Color c;
  130. c.set_hsv(rot, bc.get_s(), bc.get_v());
  131. return c.lerp(get_theme_color(SNAME("base_color"), EditorStringName(Editor)), 0.07);
  132. }
  133. int EditorProfiler::_get_zoom_left_border() const {
  134. const int max_profiles_shown = frame_metrics.size() / Math::exp(graph_zoom);
  135. return CLAMP(zoom_center - max_profiles_shown / 2, 0, frame_metrics.size() - max_profiles_shown);
  136. }
  137. void EditorProfiler::_item_edited() {
  138. if (updating_frame) {
  139. return;
  140. }
  141. TreeItem *item = variables->get_edited();
  142. if (!item) {
  143. return;
  144. }
  145. StringName signature = item->get_metadata(0);
  146. bool checked = item->is_checked(0);
  147. if (checked) {
  148. plot_sigs.insert(signature);
  149. } else {
  150. plot_sigs.erase(signature);
  151. }
  152. if (!frame_delay->is_processing()) {
  153. frame_delay->set_wait_time(0.1);
  154. frame_delay->start();
  155. }
  156. _update_plot();
  157. }
  158. void EditorProfiler::_update_plot() {
  159. const int w = MAX(1, graph->get_size().width); // Clamp to 1 to prevent from crashing when profiler is autostarted.
  160. const int h = MAX(1, graph->get_size().height);
  161. bool reset_texture = false;
  162. const int desired_len = w * h * 4;
  163. if (graph_image.size() != desired_len) {
  164. reset_texture = true;
  165. graph_image.resize(desired_len);
  166. }
  167. uint8_t *wr = graph_image.ptrw();
  168. const Color background_color = get_theme_color(SNAME("dark_color_2"), EditorStringName(Editor));
  169. // Clear the previous frame and set the background color.
  170. for (int i = 0; i < desired_len; i += 4) {
  171. wr[i + 0] = Math::fast_ftoi(background_color.r * 255);
  172. wr[i + 1] = Math::fast_ftoi(background_color.g * 255);
  173. wr[i + 2] = Math::fast_ftoi(background_color.b * 255);
  174. wr[i + 3] = 255;
  175. }
  176. //find highest value
  177. const bool use_self = display_time->get_selected() == DISPLAY_SELF_TIME;
  178. float highest = 0;
  179. for (int i = 0; i < total_metrics; i++) {
  180. const Metric &m = _get_frame_metric(i);
  181. for (const StringName &E : plot_sigs) {
  182. HashMap<StringName, Metric::Category *>::ConstIterator F = m.category_ptrs.find(E);
  183. if (F) {
  184. highest = MAX(F->value->total_time, highest);
  185. }
  186. HashMap<StringName, Metric::Category::Item *>::ConstIterator G = m.item_ptrs.find(E);
  187. if (G) {
  188. if (use_self) {
  189. highest = MAX(G->value->self, highest);
  190. } else {
  191. highest = MAX(G->value->total, highest);
  192. }
  193. }
  194. }
  195. }
  196. if (highest > 0) {
  197. //means some data exists..
  198. highest *= 1.2; //leave some upper room
  199. graph_height = highest;
  200. Vector<int> columnv;
  201. columnv.resize(h * 4);
  202. int *column = columnv.ptrw();
  203. HashMap<StringName, int> prev_plots;
  204. const int max_profiles_shown = frame_metrics.size() / Math::exp(graph_zoom);
  205. const int left_border = _get_zoom_left_border();
  206. const int profiles_drawn = CLAMP(total_metrics - left_border, 0, max_profiles_shown);
  207. const int pixel_cols = (profiles_drawn * w) / max_profiles_shown - 1;
  208. for (int i = 0; i < pixel_cols; i++) {
  209. for (int j = 0; j < h * 4; j++) {
  210. column[j] = 0;
  211. }
  212. int current = (i * max_profiles_shown / w) + left_border;
  213. for (const StringName &E : plot_sigs) {
  214. const Metric &m = _get_frame_metric(current);
  215. float value = 0;
  216. HashMap<StringName, Metric::Category *>::ConstIterator F = m.category_ptrs.find(E);
  217. if (F) {
  218. value = F->value->total_time;
  219. }
  220. HashMap<StringName, Metric::Category::Item *>::ConstIterator G = m.item_ptrs.find(E);
  221. if (G) {
  222. if (use_self) {
  223. value = G->value->self;
  224. } else {
  225. value = G->value->total;
  226. }
  227. }
  228. int plot_pos = CLAMP(int(value * h / highest), 0, h - 1);
  229. int prev_plot = plot_pos;
  230. HashMap<StringName, int>::Iterator H = prev_plots.find(E);
  231. if (H) {
  232. prev_plot = H->value;
  233. H->value = plot_pos;
  234. } else {
  235. prev_plots[E] = plot_pos;
  236. }
  237. plot_pos = h - plot_pos - 1;
  238. prev_plot = h - prev_plot - 1;
  239. if (prev_plot > plot_pos) {
  240. SWAP(prev_plot, plot_pos);
  241. }
  242. Color col = _get_color_from_signature(E);
  243. for (int j = prev_plot; j <= plot_pos; j++) {
  244. column[j * 4 + 0] += Math::fast_ftoi(CLAMP(col.r * 255, 0, 255));
  245. column[j * 4 + 1] += Math::fast_ftoi(CLAMP(col.g * 255, 0, 255));
  246. column[j * 4 + 2] += Math::fast_ftoi(CLAMP(col.b * 255, 0, 255));
  247. column[j * 4 + 3] += 1;
  248. }
  249. }
  250. for (int j = 0; j < h * 4; j += 4) {
  251. const int a = column[j + 3];
  252. if (a > 0) {
  253. column[j + 0] /= a;
  254. column[j + 1] /= a;
  255. column[j + 2] /= a;
  256. }
  257. const uint8_t red = uint8_t(column[j + 0]);
  258. const uint8_t green = uint8_t(column[j + 1]);
  259. const uint8_t blue = uint8_t(column[j + 2]);
  260. const bool is_filled = red >= 1 || green >= 1 || blue >= 1;
  261. const int widx = ((j >> 2) * w + i) * 4;
  262. // If the pixel isn't filled by any profiler line, apply the background color instead.
  263. wr[widx + 0] = is_filled ? red : Math::fast_ftoi(background_color.r * 255);
  264. wr[widx + 1] = is_filled ? green : Math::fast_ftoi(background_color.g * 255);
  265. wr[widx + 2] = is_filled ? blue : Math::fast_ftoi(background_color.b * 255);
  266. wr[widx + 3] = 255;
  267. }
  268. }
  269. }
  270. Ref<Image> img = Image::create_from_data(w, h, false, Image::FORMAT_RGBA8, graph_image);
  271. if (reset_texture) {
  272. if (graph_texture.is_null()) {
  273. graph_texture.instantiate();
  274. }
  275. graph_texture->set_image(img);
  276. }
  277. graph_texture->update(img);
  278. graph->set_texture(graph_texture);
  279. graph->queue_redraw();
  280. }
  281. void EditorProfiler::_update_frame() {
  282. int cursor_metric = cursor_metric_edit->get_value() - _get_frame_metric(0).frame_number;
  283. updating_frame = true;
  284. variables->clear();
  285. TreeItem *root = variables->create_item();
  286. const Metric &m = _get_frame_metric(cursor_metric);
  287. int dtime = display_time->get_selected();
  288. for (int i = 0; i < m.categories.size(); i++) {
  289. TreeItem *category = variables->create_item(root);
  290. category->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
  291. category->set_editable(0, true);
  292. category->set_metadata(0, m.categories[i].signature);
  293. category->set_text(0, String(m.categories[i].name));
  294. category->set_text(1, _get_time_as_text(m, m.categories[i].total_time, 1));
  295. if (plot_sigs.has(m.categories[i].signature)) {
  296. category->set_checked(0, true);
  297. category->set_custom_color(0, _get_color_from_signature(m.categories[i].signature));
  298. }
  299. for (int j = 0; j < m.categories[i].items.size(); j++) {
  300. const Metric::Category::Item &it = m.categories[i].items[j];
  301. if (it.internal == it.total && !display_internal_profiles->is_pressed() && m.categories[i].name == "Script Functions") {
  302. continue;
  303. }
  304. TreeItem *item = variables->create_item(category);
  305. item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
  306. item->set_editable(0, true);
  307. item->set_text(0, it.name);
  308. item->set_metadata(0, it.signature);
  309. item->set_metadata(1, it.script);
  310. item->set_metadata(2, it.line);
  311. item->set_text_alignment(2, HORIZONTAL_ALIGNMENT_RIGHT);
  312. item->set_tooltip_text(0, it.name + "\n" + it.script + ":" + itos(it.line));
  313. float time = dtime == DISPLAY_SELF_TIME ? it.self : it.total;
  314. if (dtime == DISPLAY_SELF_TIME && !display_internal_profiles->is_pressed()) {
  315. time += it.internal;
  316. }
  317. item->set_text(1, _get_time_as_text(m, time, it.calls));
  318. item->set_text(2, itos(it.calls));
  319. if (plot_sigs.has(it.signature)) {
  320. item->set_checked(0, true);
  321. item->set_custom_color(0, _get_color_from_signature(it.signature));
  322. }
  323. }
  324. }
  325. updating_frame = false;
  326. }
  327. void EditorProfiler::_update_button_text() {
  328. if (activate->is_pressed()) {
  329. activate->set_button_icon(get_editor_theme_icon(SNAME("Stop")));
  330. activate->set_text(TTR("Stop"));
  331. } else {
  332. activate->set_button_icon(get_editor_theme_icon(SNAME("Play")));
  333. activate->set_text(TTR("Start"));
  334. }
  335. }
  336. void EditorProfiler::_activate_pressed() {
  337. _update_button_text();
  338. if (activate->is_pressed()) {
  339. _clear_pressed();
  340. }
  341. emit_signal(SNAME("enable_profiling"), activate->is_pressed());
  342. }
  343. void EditorProfiler::_clear_pressed() {
  344. clear_button->set_disabled(true);
  345. clear();
  346. _update_plot();
  347. }
  348. void EditorProfiler::_internal_profiles_pressed() {
  349. _combo_changed(0);
  350. }
  351. void EditorProfiler::_autostart_toggled(bool p_toggled_on) {
  352. EditorSettings::get_singleton()->set_project_metadata("debug_options", "autostart_profiler", p_toggled_on);
  353. }
  354. void EditorProfiler::_notification(int p_what) {
  355. switch (p_what) {
  356. case NOTIFICATION_ENTER_TREE:
  357. case NOTIFICATION_LAYOUT_DIRECTION_CHANGED:
  358. case NOTIFICATION_THEME_CHANGED:
  359. case NOTIFICATION_TRANSLATION_CHANGED: {
  360. activate->set_button_icon(get_editor_theme_icon(SNAME("Play")));
  361. clear_button->set_button_icon(get_editor_theme_icon(SNAME("Clear")));
  362. theme_cache.seek_line_color = get_theme_color(SceneStringName(font_color), EditorStringName(Editor));
  363. theme_cache.seek_line_color.a = 0.8;
  364. theme_cache.seek_line_hover_color = theme_cache.seek_line_color;
  365. theme_cache.seek_line_hover_color.a = 0.4;
  366. if (total_metrics > 0) {
  367. _update_plot();
  368. }
  369. } break;
  370. }
  371. }
  372. void EditorProfiler::_graph_tex_draw() {
  373. if (total_metrics == 0) {
  374. return;
  375. }
  376. if (seeking) {
  377. int frame = cursor_metric_edit->get_value() - _get_frame_metric(0).frame_number;
  378. frame = frame - _get_zoom_left_border() + 1;
  379. int cur_x = (frame * graph->get_size().width * Math::exp(graph_zoom)) / frame_metrics.size();
  380. cur_x = CLAMP(cur_x, 0, graph->get_size().width);
  381. graph->draw_line(Vector2(cur_x, 0), Vector2(cur_x, graph->get_size().y), theme_cache.seek_line_color);
  382. }
  383. if (hover_metric > -1) {
  384. int cur_x = (2 * hover_metric + 1) * graph->get_size().x / (2 * frame_metrics.size()) + 1;
  385. graph->draw_line(Vector2(cur_x, 0), Vector2(cur_x, graph->get_size().y), theme_cache.seek_line_hover_color);
  386. }
  387. }
  388. void EditorProfiler::_graph_tex_mouse_exit() {
  389. hover_metric = -1;
  390. graph->queue_redraw();
  391. }
  392. void EditorProfiler::_cursor_metric_changed(double) {
  393. if (updating_frame) {
  394. return;
  395. }
  396. graph->queue_redraw();
  397. _update_frame();
  398. }
  399. void EditorProfiler::_graph_tex_input(const Ref<InputEvent> &p_ev) {
  400. if (last_metric < 0) {
  401. return;
  402. }
  403. Ref<InputEventMouse> me = p_ev;
  404. Ref<InputEventMouseButton> mb = p_ev;
  405. Ref<InputEventMouseMotion> mm = p_ev;
  406. MouseButton button_idx = mb.is_valid() ? mb->get_button_index() : MouseButton();
  407. if (
  408. (mb.is_valid() && button_idx == MouseButton::LEFT && mb->is_pressed()) ||
  409. (mm.is_valid())) {
  410. int x = me->get_position().x - 1;
  411. hover_metric = x * frame_metrics.size() / graph->get_size().width;
  412. x = x * frame_metrics.size() / graph->get_size().width;
  413. x = x / Math::exp(graph_zoom) + _get_zoom_left_border();
  414. x = CLAMP(x, 0, frame_metrics.size() - 1);
  415. if (mb.is_valid() || (mm->get_button_mask().has_flag(MouseButtonMask::LEFT))) {
  416. updating_frame = true;
  417. if (x < total_metrics) {
  418. cursor_metric_edit->set_value(_get_frame_metric(x).frame_number);
  419. }
  420. updating_frame = false;
  421. if (activate->is_pressed()) {
  422. if (!seeking) {
  423. emit_signal(SNAME("break_request"));
  424. }
  425. }
  426. seeking = true;
  427. if (!frame_delay->is_processing()) {
  428. frame_delay->set_wait_time(0.1);
  429. frame_delay->start();
  430. }
  431. }
  432. }
  433. if (graph_zoom > 0 && mm.is_valid() && (mm->get_button_mask().has_flag(MouseButtonMask::MIDDLE) || mm->get_button_mask().has_flag(MouseButtonMask::RIGHT))) {
  434. // Panning.
  435. const int max_profiles_shown = frame_metrics.size() / Math::exp(graph_zoom);
  436. pan_accumulator += (float)mm->get_relative().x * max_profiles_shown / graph->get_size().width;
  437. if (Math::abs(pan_accumulator) > 1) {
  438. zoom_center = CLAMP(zoom_center - (int)pan_accumulator, max_profiles_shown / 2, frame_metrics.size() - max_profiles_shown / 2);
  439. pan_accumulator -= (int)pan_accumulator;
  440. _update_plot();
  441. }
  442. }
  443. if (button_idx == MouseButton::WHEEL_DOWN) {
  444. // Zooming.
  445. graph_zoom = MAX(-0.05 + graph_zoom, 0);
  446. _update_plot();
  447. } else if (button_idx == MouseButton::WHEEL_UP) {
  448. if (graph_zoom == 0) {
  449. zoom_center = me->get_position().x;
  450. zoom_center = zoom_center * frame_metrics.size() / graph->get_size().width;
  451. }
  452. graph_zoom = MIN(0.05 + graph_zoom, 2);
  453. _update_plot();
  454. }
  455. graph->queue_redraw();
  456. }
  457. void EditorProfiler::disable_seeking() {
  458. seeking = false;
  459. graph->queue_redraw();
  460. }
  461. void EditorProfiler::_combo_changed(int) {
  462. _update_frame();
  463. _update_plot();
  464. }
  465. void EditorProfiler::_bind_methods() {
  466. ADD_SIGNAL(MethodInfo("enable_profiling", PropertyInfo(Variant::BOOL, "enable")));
  467. ADD_SIGNAL(MethodInfo("break_request"));
  468. }
  469. void EditorProfiler::set_enabled(bool p_enable, bool p_clear) {
  470. activate->set_disabled(!p_enable);
  471. if (p_clear) {
  472. clear();
  473. }
  474. }
  475. void EditorProfiler::set_profiling(bool p_pressed) {
  476. activate->set_pressed(p_pressed);
  477. _update_button_text();
  478. emit_signal(SNAME("enable_profiling"), activate->is_pressed());
  479. }
  480. bool EditorProfiler::is_profiling() {
  481. return activate->is_pressed();
  482. }
  483. Vector<Vector<String>> EditorProfiler::get_data_as_csv() const {
  484. Vector<Vector<String>> res;
  485. if (frame_metrics.is_empty()) {
  486. return res;
  487. }
  488. // Different metrics may contain different number of categories.
  489. HashSet<StringName> possible_signatures;
  490. for (int i = 0; i < frame_metrics.size(); i++) {
  491. const Metric &m = frame_metrics[i];
  492. if (!m.valid) {
  493. continue;
  494. }
  495. for (const KeyValue<StringName, Metric::Category *> &E : m.category_ptrs) {
  496. possible_signatures.insert(E.key);
  497. }
  498. for (const KeyValue<StringName, Metric::Category::Item *> &E : m.item_ptrs) {
  499. possible_signatures.insert(E.key);
  500. }
  501. }
  502. // Generate CSV header and cache indices.
  503. HashMap<StringName, int> sig_map;
  504. Vector<String> signatures;
  505. signatures.resize(possible_signatures.size());
  506. int sig_index = 0;
  507. for (const StringName &E : possible_signatures) {
  508. signatures.write[sig_index] = E;
  509. sig_map[E] = sig_index;
  510. sig_index++;
  511. }
  512. res.push_back(signatures);
  513. // values
  514. Vector<String> values;
  515. int index = last_metric;
  516. for (int i = 0; i < frame_metrics.size(); i++) {
  517. ++index;
  518. if (index >= frame_metrics.size()) {
  519. index = 0;
  520. }
  521. const Metric &m = frame_metrics[index];
  522. if (!m.valid) {
  523. continue;
  524. }
  525. // Don't keep old values since there may be empty cells.
  526. values.clear();
  527. values.resize(possible_signatures.size());
  528. for (const KeyValue<StringName, Metric::Category *> &E : m.category_ptrs) {
  529. values.write[sig_map[E.key]] = String::num_real(E.value->total_time);
  530. }
  531. for (const KeyValue<StringName, Metric::Category::Item *> &E : m.item_ptrs) {
  532. values.write[sig_map[E.key]] = String::num_real(E.value->total);
  533. }
  534. res.push_back(values);
  535. }
  536. return res;
  537. }
  538. EditorProfiler::EditorProfiler() {
  539. HBoxContainer *hb = memnew(HBoxContainer);
  540. add_child(hb);
  541. activate = memnew(Button);
  542. activate->set_toggle_mode(true);
  543. activate->set_disabled(true);
  544. activate->set_text(TTR("Start"));
  545. activate->connect(SceneStringName(pressed), callable_mp(this, &EditorProfiler::_activate_pressed));
  546. hb->add_child(activate);
  547. clear_button = memnew(Button);
  548. clear_button->set_text(TTR("Clear"));
  549. clear_button->connect(SceneStringName(pressed), callable_mp(this, &EditorProfiler::_clear_pressed));
  550. clear_button->set_disabled(true);
  551. hb->add_child(clear_button);
  552. CheckBox *autostart_checkbox = memnew(CheckBox);
  553. autostart_checkbox->set_text(TTR("Autostart"));
  554. autostart_checkbox->set_pressed(EditorSettings::get_singleton()->get_project_metadata("debug_options", "autostart_profiler", false));
  555. autostart_checkbox->connect(SceneStringName(toggled), callable_mp(this, &EditorProfiler::_autostart_toggled));
  556. hb->add_child(autostart_checkbox);
  557. hb->add_child(memnew(Label(TTR("Measure:"))));
  558. display_mode = memnew(OptionButton);
  559. display_mode->add_item(TTR("Frame Time (ms)"));
  560. display_mode->add_item(TTR("Average Time (ms)"));
  561. display_mode->add_item(TTR("Frame %"));
  562. display_mode->add_item(TTR("Physics Frame %"));
  563. display_mode->connect(SceneStringName(item_selected), callable_mp(this, &EditorProfiler::_combo_changed));
  564. hb->add_child(display_mode);
  565. hb->add_child(memnew(Label(TTR("Time:"))));
  566. display_time = memnew(OptionButton);
  567. // TRANSLATORS: This is an option in the profiler to display the time spent in a function, including the time spent in other functions called by that function.
  568. display_time->add_item(TTR("Inclusive"));
  569. // TRANSLATORS: This is an option in the profiler to display the time spent in a function, exincluding the time spent in other functions called by that function.
  570. display_time->add_item(TTR("Self"));
  571. display_time->set_tooltip_text(TTR("Inclusive: Includes time from other functions called by this function.\nUse this to spot bottlenecks.\n\nSelf: Only count the time spent in the function itself, not in other functions called by that function.\nUse this to find individual functions to optimize."));
  572. display_time->connect(SceneStringName(item_selected), callable_mp(this, &EditorProfiler::_combo_changed));
  573. hb->add_child(display_time);
  574. display_internal_profiles = memnew(CheckButton(TTR("Display internal functions")));
  575. display_internal_profiles->set_visible(EDITOR_GET("debugger/profile_native_calls"));
  576. display_internal_profiles->set_pressed(false);
  577. display_internal_profiles->connect(SceneStringName(pressed), callable_mp(this, &EditorProfiler::_internal_profiles_pressed));
  578. hb->add_child(display_internal_profiles);
  579. hb->add_spacer();
  580. hb->add_child(memnew(Label(TTR("Frame #:"))));
  581. cursor_metric_edit = memnew(SpinBox);
  582. cursor_metric_edit->set_h_size_flags(SIZE_FILL);
  583. cursor_metric_edit->set_value(0);
  584. cursor_metric_edit->set_editable(false);
  585. hb->add_child(cursor_metric_edit);
  586. cursor_metric_edit->connect(SceneStringName(value_changed), callable_mp(this, &EditorProfiler::_cursor_metric_changed));
  587. hb->add_theme_constant_override("separation", 8 * EDSCALE);
  588. h_split = memnew(HSplitContainer);
  589. add_child(h_split);
  590. h_split->set_v_size_flags(SIZE_EXPAND_FILL);
  591. variables = memnew(Tree);
  592. variables->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  593. variables->set_custom_minimum_size(Size2(320, 0) * EDSCALE);
  594. variables->set_hide_folding(true);
  595. h_split->add_child(variables);
  596. variables->set_hide_root(true);
  597. variables->set_columns(3);
  598. variables->set_column_titles_visible(true);
  599. variables->set_column_title(0, TTR("Name"));
  600. variables->set_column_expand(0, true);
  601. variables->set_column_clip_content(0, true);
  602. variables->set_column_custom_minimum_width(0, 60);
  603. variables->set_column_title(1, TTR("Time"));
  604. variables->set_column_expand(1, false);
  605. variables->set_column_clip_content(1, true);
  606. variables->set_column_custom_minimum_width(1, 75 * EDSCALE);
  607. variables->set_column_title(2, TTR("Calls"));
  608. variables->set_column_expand(2, false);
  609. variables->set_column_clip_content(2, true);
  610. variables->set_column_custom_minimum_width(2, 50 * EDSCALE);
  611. variables->set_theme_type_variation("TreeSecondary");
  612. variables->connect("item_edited", callable_mp(this, &EditorProfiler::_item_edited));
  613. graph = memnew(TextureRect);
  614. graph->set_custom_minimum_size(Size2(250 * EDSCALE, 0));
  615. graph->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE);
  616. graph->set_mouse_filter(MOUSE_FILTER_STOP);
  617. graph->connect(SceneStringName(draw), callable_mp(this, &EditorProfiler::_graph_tex_draw));
  618. graph->connect(SceneStringName(gui_input), callable_mp(this, &EditorProfiler::_graph_tex_input));
  619. graph->connect(SceneStringName(mouse_exited), callable_mp(this, &EditorProfiler::_graph_tex_mouse_exit));
  620. h_split->add_child(graph);
  621. graph->set_h_size_flags(SIZE_EXPAND_FILL);
  622. int metric_size = CLAMP(int(EDITOR_GET("debugger/profiler_frame_history_size")), 60, 10000);
  623. frame_metrics.resize(metric_size);
  624. frame_delay = memnew(Timer);
  625. frame_delay->set_wait_time(0.1);
  626. frame_delay->set_one_shot(true);
  627. add_child(frame_delay);
  628. frame_delay->connect("timeout", callable_mp(this, &EditorProfiler::_update_frame));
  629. plot_delay = memnew(Timer);
  630. plot_delay->set_wait_time(0.1);
  631. plot_delay->set_one_shot(true);
  632. add_child(plot_delay);
  633. plot_delay->connect("timeout", callable_mp(this, &EditorProfiler::_update_plot));
  634. plot_sigs.insert("physics_frame_time");
  635. plot_sigs.insert("category_frame_time");
  636. }