2
0

editor_profiler.cpp 27 KB

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