Added Custom Performance Monitor and feature to read intermediate values of Monitor

Custom monitors can be added/removed/checked using `Performance.add_custom_monitor`/`Performance.remove_custom_monitor`/`Performance.has_custom_monitor`

The value can be viewed in the `Monitor` tab of Debugger.

Text before `/` is used to categorize the custom monitor.

`EditorPerformanceProfiler` class is created to separate logic from `ScriptEditorDebugger`

User can click on the graph of monitors to read the value at that point.

Graph includes intermediate base lines.
This commit is contained in:
simpu 2020-06-04 18:48:57 +05:30
parent 9fc65fd1f1
commit bfadb882b1
8 changed files with 708 additions and 242 deletions

View file

@ -373,6 +373,7 @@ struct RemoteDebugger::VisualProfiler {
struct RemoteDebugger::PerformanceProfiler {
Object *performance = nullptr;
int last_perf_time = 0;
uint64_t last_monitor_modification_time = 0;
void toggle(bool p_enable, const Array &p_opts) {}
void add(const Array &p_data) {}
@ -386,12 +387,31 @@ struct RemoteDebugger::PerformanceProfiler {
return;
}
last_perf_time = pt;
Array custom_monitor_names = performance->call("get_custom_monitor_names");
uint64_t monitor_modification_time = performance->call("get_monitor_modification_time");
if (monitor_modification_time > last_monitor_modification_time) {
last_monitor_modification_time = monitor_modification_time;
EngineDebugger::get_singleton()->send_message("performance:profile_names", custom_monitor_names);
}
int max = performance->get("MONITOR_MAX");
Array arr;
arr.resize(max);
arr.resize(max + custom_monitor_names.size());
for (int i = 0; i < max; i++) {
arr[i] = performance->call("get_monitor", i);
}
for (int i = 0; i < custom_monitor_names.size(); i++) {
Variant monitor_value = performance->call("get_custom_monitor", custom_monitor_names[i]);
if (!monitor_value.is_num()) {
ERR_PRINT("Value of custom monitor '" + String(custom_monitor_names[i]) + "' is not a number");
arr[i + max] = Variant();
}
arr[i + max] = monitor_value;
}
EngineDebugger::get_singleton()->send_message("performance:profile_frame", arr);
}

View file

@ -5,12 +5,55 @@
</brief_description>
<description>
This class provides access to a number of different monitors related to performance, such as memory usage, draw calls, and FPS. These are the same as the values displayed in the [b]Monitor[/b] tab in the editor's [b]Debugger[/b] panel. By using the [method get_monitor] method of this class, you can access this data from your code.
You can add custom monitors using the [method add_custom_monitor] method. Custom monitors are available in [b]Monitor[/b] tab in the editor's [b]Debugger[/b] panel together with built-in monitors.
[b]Note:[/b] A few of these monitors are only available in debug mode and will always return 0 when used in a release build.
[b]Note:[/b] Many of these monitors are not updated in real-time, so there may be a short delay between changes.
[b]Note:[/b] Custom monitors do not support negative values. Negative values are clamped to 0.
</description>
<tutorials>
</tutorials>
<methods>
<method name="add_custom_monitor">
<return type="void">
</return>
<argument index="0" name="id" type="StringName">
</argument>
<argument index="1" name="callable" type="Callable">
</argument>
<argument index="2" name="arguments" type="Array" default="[ ]">
</argument>
<description>
Adds a custom monitor with name same as id. You can specify the category of monitor using '/' in id. If there are more than one '/' then default category is used. Default category is "Custom".
[codeblock]
Performance.add_custom_monitor("MyCategory/MyMonitor", some_callable) # Adds monitor with name "MyName" to category "MyCategory"
Performance.add_custom_monitor("MyMonitor", some_callable) # Adds monitor with name "MyName" to category "Custom"
# Note: "MyCategory/MyMonitor" and "MyMonitor" have same name but different ids so above code is valid
Performance.add_custom_monitor("Custom/MyMonitor", some_callable) # Adds monitor with name "MyName" to category "Custom"
# Note: "MyMonitor" and "Custom/MyMonitor" have same name and same category but different ids so above code is valid
Performance.add_custom_monitor("MyCategoryOne/MyCategoryTwo/MyMonitor", some_callable) # Adds monitor with name "MyCategoryOne/MyCategoryTwo/MyMonitor" to category "Custom"
[/codeblock]
The debugger calls the callable to get the value of custom monitor. The callable must return a number.
Callables are called with arguments supplied in argument array.
[b]Note:[/b] It throws an error if given id is already present.
</description>
</method>
<method name="get_custom_monitor">
<return type="Variant">
</return>
<argument index="0" name="id" type="StringName">
</argument>
<description>
Returns the value of custom monitor with given id. The callable is called to get the value of custom monitor.
[b]Note:[/b] It throws an error if the given id is absent.
</description>
</method>
<method name="get_custom_monitor_names">
<return type="Array">
</return>
<description>
Returns the names of active custom monitors in an array.
</description>
</method>
<method name="get_monitor" qualifiers="const">
<return type="float">
</return>
@ -23,6 +66,32 @@
[/codeblock]
</description>
</method>
<method name="get_monitor_modification_time">
<return type="int">
</return>
<description>
Returns the last tick in which custom monitor was added/removed.
</description>
</method>
<method name="has_custom_monitor">
<return type="bool">
</return>
<argument index="0" name="id" type="StringName">
</argument>
<description>
Returns true if custom monitor with the given id is present otherwise returns false.
</description>
</method>
<method name="remove_custom_monitor">
<return type="void">
</return>
<argument index="0" name="id" type="StringName">
</argument>
<description>
Removes the custom monitor with given id.
[b]Note:[/b] It throws an error if the given id is already absent.
</description>
</method>
</methods>
<constants>
<constant name="TIME_FPS" value="0" enum="Monitor">

View file

@ -0,0 +1,394 @@
/*************************************************************************/
/* editor_performance_profiler.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "editor_performance_profiler.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
#include "main/performance.h"
EditorPerformanceProfiler::Monitor::Monitor() {}
EditorPerformanceProfiler::Monitor::Monitor(String p_name, String p_base, int p_frame_index, Performance::MonitorType p_type, TreeItem *p_item) {
type = p_type;
item = p_item;
frame_index = p_frame_index;
name = p_name;
base = p_base;
}
void EditorPerformanceProfiler::Monitor::update_value(float p_value) {
ERR_FAIL_COND(!item);
String label = EditorPerformanceProfiler::_create_label(p_value, type);
String tooltip = label;
switch (type) {
case Performance::MONITOR_TYPE_MEMORY: {
tooltip = label;
} break;
case Performance::MONITOR_TYPE_TIME: {
tooltip = label;
} break;
default: {
tooltip += " " + item->get_text(0);
} break;
}
item->set_text(1, label);
item->set_tooltip(1, tooltip);
if (p_value > max) {
max = p_value;
}
}
void EditorPerformanceProfiler::Monitor::reset() {
history.clear();
max = 0.0f;
if (item) {
item->set_text(1, "");
item->set_tooltip(1, "");
}
}
String EditorPerformanceProfiler::_create_label(float p_value, Performance::MonitorType p_type) {
switch (p_type) {
case Performance::MONITOR_TYPE_MEMORY: {
return String::humanize_size(p_value);
}
case Performance::MONITOR_TYPE_TIME: {
return rtos(p_value * 1000).pad_decimals(2) + " ms";
}
default: {
return rtos(p_value);
}
}
}
void EditorPerformanceProfiler::_monitor_select() {
monitor_draw->update();
}
void EditorPerformanceProfiler::_monitor_draw() {
Vector<StringName> active;
for (OrderedHashMap<StringName, Monitor>::Element i = monitors.front(); i; i = i.next()) {
if (i.value().item->is_checked(0)) {
active.push_back(i.key());
}
}
if (active.empty()) {
info_message->show();
return;
}
info_message->hide();
Ref<StyleBox> graph_style_box = get_theme_stylebox("normal", "TextEdit");
Ref<Font> graph_font = get_theme_font("font", "TextEdit");
int columns = int(Math::ceil(Math::sqrt(float(active.size()))));
int rows = int(Math::ceil(float(active.size()) / float(columns)));
if (active.size() == 1) {
rows = 1;
}
Size2i cell_size = Size2i(monitor_draw->get_size()) / Size2i(columns, rows);
float spacing = float(POINT_SEPARATION) / float(columns);
float value_multiplier = EditorSettings::get_singleton()->is_dark_theme() ? 1.4f : 0.55f;
float hue_shift = 1.0f / float(monitors.size());
for (int i = 0; i < active.size(); i++) {
Monitor &current = monitors[active[i]];
Rect2i rect(Point2i(i % columns, i / columns) * cell_size + Point2i(MARGIN, MARGIN), cell_size - Point2i(MARGIN, MARGIN) * 2);
monitor_draw->draw_style_box(graph_style_box, rect);
rect.position += graph_style_box->get_offset();
rect.size -= graph_style_box->get_minimum_size();
Color draw_color = get_theme_color("accent_color", "Editor");
draw_color.set_hsv(Math::fmod(hue_shift * float(current.frame_index), 0.9f), draw_color.get_s() * 0.9f, draw_color.get_v() * value_multiplier, 0.6f);
monitor_draw->draw_string(graph_font, rect.position + Point2(0, graph_font->get_ascent()), current.item->get_text(0), draw_color, rect.size.x);
draw_color.a = 0.9f;
float value_position = rect.size.width - graph_font->get_string_size(current.item->get_text(1)).width;
if (value_position < 0) {
value_position = 0;
}
monitor_draw->draw_string(graph_font, rect.position + Point2(value_position, graph_font->get_ascent()), current.item->get_text(1), draw_color, rect.size.x);
rect.position.y += graph_font->get_height();
rect.size.height -= graph_font->get_height();
int line_count = rect.size.height / (graph_font->get_height() * 2);
if (line_count > 5) {
line_count = 5;
}
if (line_count > 0) {
Color horizontal_line_color;
horizontal_line_color.set_hsv(draw_color.get_h(), draw_color.get_s() * 0.5f, draw_color.get_v() * 0.5f, 0.3f);
monitor_draw->draw_line(rect.position, rect.position + Vector2(rect.size.width, 0), horizontal_line_color, Math::round(EDSCALE));
monitor_draw->draw_string(graph_font, rect.position + Vector2(0, graph_font->get_ascent()), _create_label(current.max, current.type), horizontal_line_color, rect.size.width);
for (int j = 0; j < line_count; j++) {
Vector2 y_offset = Vector2(0, rect.size.height * (1.0f - float(j) / float(line_count)));
monitor_draw->draw_line(rect.position + y_offset, rect.position + Vector2(rect.size.width, 0) + y_offset, horizontal_line_color, Math::round(EDSCALE));
monitor_draw->draw_string(graph_font, rect.position - Vector2(0, graph_font->get_descent()) + y_offset, _create_label(current.max * float(j) / float(line_count), current.type), horizontal_line_color, rect.size.width);
}
}
float from = rect.size.width;
float prev = -1.0f;
int count = 0;
List<float>::Element *e = current.history.front();
while (from >= 0 && e) {
float m = current.max;
float h2 = 0;
if (m != 0) {
h2 = (e->get() / m);
}
h2 = (1.0f - h2) * float(rect.size.y);
if (e != current.history.front()) {
monitor_draw->draw_line(rect.position + Point2(from, h2), rect.position + Point2(from + spacing, prev), draw_color, Math::round(EDSCALE));
}
if (marker_key == active[i] && count == marker_frame) {
Color line_color;
line_color.set_hsv(draw_color.get_h(), draw_color.get_s() * 0.8f, draw_color.get_v(), 0.5f);
monitor_draw->draw_line(rect.position + Point2(from, 0), rect.position + Point2(from, rect.size.y), line_color, Math::round(EDSCALE));
String label = _create_label(e->get(), current.type);
Size2 size = graph_font->get_string_size(label);
Vector2 text_top_left_position = Vector2(from, h2) - (size + Vector2(MARKER_MARGIN, MARKER_MARGIN));
if (text_top_left_position.x < 0) {
text_top_left_position.x = from + MARKER_MARGIN;
}
if (text_top_left_position.y < 0) {
text_top_left_position.y = h2 + MARKER_MARGIN;
}
monitor_draw->draw_string(graph_font, rect.position + text_top_left_position + Point2(0, graph_font->get_ascent()), label, line_color, rect.size.x);
}
prev = h2;
e = e->next();
from -= spacing;
count++;
}
}
}
void EditorPerformanceProfiler::_build_monitor_tree() {
Set<StringName> monitor_checked;
for (OrderedHashMap<StringName, Monitor>::Element i = monitors.front(); i; i = i.next()) {
if (i.value().item && i.value().item->is_checked(0)) {
monitor_checked.insert(i.key());
}
}
base_map.clear();
monitor_tree->get_root()->clear_children();
for (OrderedHashMap<StringName, Monitor>::Element i = monitors.front(); i; i = i.next()) {
TreeItem *base = _get_monitor_base(i.value().base);
TreeItem *item = _create_monitor_item(i.value().name, base);
item->set_checked(0, monitor_checked.has(i.key()));
i.value().item = item;
if (!i.value().history.empty()) {
i.value().update_value(i.value().history.front()->get());
}
}
}
TreeItem *EditorPerformanceProfiler::_get_monitor_base(const StringName &p_base_name) {
if (base_map.has(p_base_name)) {
return base_map[p_base_name];
}
TreeItem *base = monitor_tree->create_item(monitor_tree->get_root());
base->set_text(0, p_base_name);
base->set_editable(0, false);
base->set_selectable(0, false);
base->set_expand_right(0, true);
base_map.insert(p_base_name, base);
return base;
}
TreeItem *EditorPerformanceProfiler::_create_monitor_item(const StringName &p_monitor_name, TreeItem *p_base) {
TreeItem *item = monitor_tree->create_item(p_base);
item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
item->set_editable(0, true);
item->set_selectable(0, false);
item->set_selectable(1, false);
item->set_text(0, p_monitor_name);
return item;
}
void EditorPerformanceProfiler::_marker_input(const Ref<InputEvent> &p_event) {
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) {
Vector<StringName> active;
for (OrderedHashMap<StringName, Monitor>::Element i = monitors.front(); i; i = i.next()) {
if (i.value().item->is_checked(0)) {
active.push_back(i.key());
}
}
if (active.size() > 0) {
int columns = int(Math::ceil(Math::sqrt(float(active.size()))));
int rows = int(Math::ceil(float(active.size()) / float(columns)));
if (active.size() == 1) {
rows = 1;
}
Size2i cell_size = Size2i(monitor_draw->get_size()) / Size2i(columns, rows);
Vector2i index = mb->get_position() / cell_size;
Rect2i rect(index * cell_size + Point2i(MARGIN, MARGIN), cell_size - Point2i(MARGIN, MARGIN) * 2);
if (rect.has_point(mb->get_position())) {
if (index.x + index.y * columns < active.size()) {
marker_key = active[index.x + index.y * columns];
} else {
marker_key = "";
}
Ref<StyleBox> graph_style_box = get_theme_stylebox("normal", "TextEdit");
rect.position += graph_style_box->get_offset();
rect.size -= graph_style_box->get_minimum_size();
Vector2 point = mb->get_position() - rect.position;
if (point.x >= rect.size.x) {
marker_frame = 0;
} else {
int point_sep = 5;
float spacing = float(point_sep) / float(columns);
marker_frame = (rect.size.x - point.x) / spacing;
}
monitor_draw->update();
return;
}
}
marker_key = "";
monitor_draw->update();
}
}
void EditorPerformanceProfiler::reset() {
for (OrderedHashMap<StringName, Monitor>::Element i = monitors.front(); i; i = i.next()) {
if (String(i.key()).begins_with("custom:")) {
monitors.erase(i);
} else {
i.value().reset();
}
}
_build_monitor_tree();
marker_key = "";
marker_frame = 0;
monitor_draw->update();
}
void EditorPerformanceProfiler::update_monitors(const Vector<StringName> &p_names) {
OrderedHashMap<StringName, int> names;
for (int i = 0; i < p_names.size(); i++) {
names.insert("custom:" + p_names[i], Performance::MONITOR_MAX + i);
}
for (OrderedHashMap<StringName, Monitor>::Element i = monitors.front(); i; i = i.next()) {
if (String(i.key()).begins_with("custom:")) {
if (!names.has(i.key())) {
monitors.erase(i);
} else {
i.value().frame_index = names[i.key()];
names.erase(i.key());
}
}
}
for (OrderedHashMap<StringName, int>::Element i = names.front(); i; i = i.next()) {
String name = String(i.key()).replace_first("custom:", "");
String base = "Custom";
if (name.get_slice_count("/") == 2) {
base = name.get_slicec('/', 0);
name = name.get_slicec('/', 1);
}
monitors.insert(i.key(), Monitor(name, base, i.value(), Performance::MONITOR_TYPE_QUANTITY, nullptr));
}
_build_monitor_tree();
}
void EditorPerformanceProfiler::add_profile_frame(const Vector<float> &p_values) {
for (OrderedHashMap<StringName, Monitor>::Element i = monitors.front(); i; i = i.next()) {
float data = 0.0f;
if (i.value().frame_index >= 0 && i.value().frame_index < p_values.size()) {
data = p_values[i.value().frame_index];
}
i.value().history.push_front(data);
i.value().update_value(data);
}
marker_frame++;
monitor_draw->update();
}
List<float> *EditorPerformanceProfiler::get_monitor_data(const StringName &p_name) {
if (monitors.has(p_name)) {
return &monitors[p_name].history;
}
return nullptr;
}
EditorPerformanceProfiler::EditorPerformanceProfiler() {
set_name(TTR("Monitors"));
set_split_offset(340 * EDSCALE);
monitor_tree = memnew(Tree);
monitor_tree->set_columns(2);
monitor_tree->set_column_title(0, TTR("Monitor"));
monitor_tree->set_column_title(1, TTR("Value"));
monitor_tree->set_column_titles_visible(true);
monitor_tree->connect("item_edited", callable_mp(this, &EditorPerformanceProfiler::_monitor_select));
monitor_tree->create_item();
monitor_tree->set_hide_root(true);
add_child(monitor_tree);
monitor_draw = memnew(Control);
monitor_draw->set_clip_contents(true);
monitor_draw->connect("draw", callable_mp(this, &EditorPerformanceProfiler::_monitor_draw));
monitor_draw->connect("gui_input", callable_mp(this, &EditorPerformanceProfiler::_marker_input));
add_child(monitor_draw);
info_message = memnew(Label);
info_message->set_text(TTR("Pick one or more items from the list to display the graph."));
info_message->set_valign(Label::VALIGN_CENTER);
info_message->set_align(Label::ALIGN_CENTER);
info_message->set_autowrap(true);
info_message->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
info_message->set_anchors_and_margins_preset(PRESET_WIDE, PRESET_MODE_KEEP_SIZE, 8 * EDSCALE);
monitor_draw->add_child(info_message);
for (int i = 0; i < Performance::MONITOR_MAX; i++) {
String base = Performance::get_singleton()->get_monitor_name(Performance::Monitor(i)).get_slicec('/', 0).capitalize();
String name = Performance::get_singleton()->get_monitor_name(Performance::Monitor(i)).get_slicec('/', 1).capitalize();
monitors.insert(Performance::get_singleton()->get_monitor_name(Performance::Monitor(i)), Monitor(name, base, i, Performance::get_singleton()->get_monitor_type(Performance::Monitor(i)), nullptr));
}
_build_monitor_tree();
}

View file

@ -0,0 +1,90 @@
/*************************************************************************/
/* editor_performance_profiler.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef EDITOR_PERFORMANCE_PROFILER_H
#define EDITOR_PERFORMANCE_PROFILER_H
#include "core/map.h"
#include "core/ordered_hash_map.h"
#include "main/performance.h"
#include "scene/gui/control.h"
#include "scene/gui/label.h"
#include "scene/gui/split_container.h"
#include "scene/gui/tree.h"
class EditorPerformanceProfiler : public HSplitContainer {
GDCLASS(EditorPerformanceProfiler, HSplitContainer);
private:
class Monitor {
public:
String name;
String base;
List<float> history;
float max = 0.0f;
TreeItem *item = nullptr;
Performance::MonitorType type = Performance::MONITOR_TYPE_QUANTITY;
int frame_index = 0;
Monitor();
Monitor(String p_name, String p_base, int p_frame_index, Performance::MonitorType p_type, TreeItem *p_item);
void update_value(float p_value);
void reset();
};
OrderedHashMap<StringName, Monitor> monitors;
Map<StringName, TreeItem *> base_map;
Tree *monitor_tree;
Control *monitor_draw;
Label *info_message;
StringName marker_key;
int marker_frame;
const int MARGIN = 4;
const int POINT_SEPARATION = 5;
const int MARKER_MARGIN = 2;
static String _create_label(float p_value, Performance::MonitorType p_type);
void _monitor_select();
void _monitor_draw();
void _build_monitor_tree();
TreeItem *_get_monitor_base(const StringName &p_base_name);
TreeItem *_create_monitor_item(const StringName &p_monitor_name, TreeItem *p_base);
void _marker_input(const Ref<InputEvent> &p_event);
public:
void reset();
void update_monitors(const Vector<StringName> &p_names);
void add_profile_frame(const Vector<float> &p_values);
List<float> *get_monitor_data(const StringName &p_name);
EditorPerformanceProfiler();
};
#endif // EDITOR_PERFORMANCE_PROFILER_H

View file

@ -36,6 +36,7 @@
#include "core/project_settings.h"
#include "core/ustring.h"
#include "editor/debugger/editor_network_profiler.h"
#include "editor/debugger/editor_performance_profiler.h"
#include "editor/debugger/editor_profiler.h"
#include "editor/debugger/editor_visual_profiler.h"
#include "editor/editor_log.h"
@ -172,14 +173,25 @@ void ScriptEditorDebugger::_file_selected(const String &p_file) {
file->store_csv_line(line);
// values
List<Vector<float>>::Element *E = perf_history.back();
while (E) {
Vector<float> &perf_data = E->get();
for (int i = 0; i < perf_data.size(); i++) {
line.write[i] = String::num_real(perf_data[i]);
Vector<List<float>::Element *> iterators;
iterators.resize(Performance::MONITOR_MAX);
bool continue_iteration = false;
for (int i = 0; i < Performance::MONITOR_MAX; i++) {
iterators.write[i] = performance_profiler->get_monitor_data(Performance::get_singleton()->get_monitor_name(Performance::Monitor(i)))->back();
continue_iteration = continue_iteration || iterators[i];
}
while (continue_iteration) {
continue_iteration = false;
for (int i = 0; i < Performance::MONITOR_MAX; i++) {
if (iterators[i]) {
line.write[i] = String::num_real(iterators[i]->get());
iterators.write[i] = iterators[i]->prev();
} else {
line.write[i] = "";
}
continue_iteration = continue_iteration || iterators[i];
}
file->store_csv_line(line);
E = E->prev();
}
file->store_string("\n");
@ -409,37 +421,12 @@ void ScriptEditorDebugger::_parse_message(const String &p_msg, const Array &p_da
EditorNode::get_log()->add_message(output_strings[i], msg_type);
}
} else if (p_msg == "performance:profile_frame") {
Vector<float> p;
p.resize(p_data.size());
Vector<float> frame_data;
frame_data.resize(p_data.size());
for (int i = 0; i < p_data.size(); i++) {
p.write[i] = p_data[i];
if (i < perf_items.size()) {
const float value = p[i];
String label = rtos(value);
String tooltip = label;
switch (Performance::MonitorType((int)perf_items[i]->get_metadata(1))) {
case Performance::MONITOR_TYPE_MEMORY: {
label = String::humanize_size(value);
tooltip = label;
} break;
case Performance::MONITOR_TYPE_TIME: {
label = rtos(value * 1000).pad_decimals(2) + " ms";
tooltip = label;
} break;
default: {
tooltip += " " + perf_items[i]->get_text(0);
} break;
}
perf_items[i]->set_text(1, label);
perf_items[i]->set_tooltip(1, tooltip);
if (p[i] > perf_max[i]) {
perf_max.write[i] = p[i];
}
}
frame_data.write[i] = p_data[i];
}
perf_history.push_front(p);
perf_draw->update();
performance_profiler->add_profile_frame(frame_data);
} else if (p_msg == "visual:profile_frame") {
DebuggerMarshalls::VisualProfilerFrame frame;
@ -704,6 +691,15 @@ void ScriptEditorDebugger::_parse_message(const String &p_msg, const Array &p_da
emit_signal("stop_requested");
_stop_and_notify();
} else if (p_msg == "performance:profile_names") {
Vector<StringName> monitors;
monitors.resize(p_data.size());
for (int i = 0; i < p_data.size(); i++) {
ERR_FAIL_COND(p_data[i].get_type() != Variant::STRING_NAME);
monitors.set(i, p_data[i]);
}
performance_profiler->update_monitors(monitors);
} else {
WARN_PRINT("unknown message " + p_msg);
}
@ -724,141 +720,6 @@ void ScriptEditorDebugger::_set_reason_text(const String &p_reason, MessageType
reason->set_tooltip(p_reason.word_wrap(80));
}
void ScriptEditorDebugger::_performance_select() {
perf_draw->update();
}
void ScriptEditorDebugger::_performance_draw() {
Vector<int> which;
for (int i = 0; i < perf_items.size(); i++) {
if (perf_items[i]->is_checked(0)) {
which.push_back(i);
}
}
if (which.empty()) {
info_message->show();
return;
}
info_message->hide();
const Ref<StyleBox> graph_sb = get_theme_stylebox("normal", "TextEdit");
const Ref<Font> graph_font = get_theme_font("font", "TextEdit");
const int cols = Math::ceil(Math::sqrt((float)which.size()));
int rows = Math::ceil((float)which.size() / cols);
if (which.size() == 1) {
rows = 1;
}
const int margin = 3;
const int point_sep = 5;
const Size2i s = Size2i(perf_draw->get_size()) / Size2i(cols, rows);
for (int i = 0; i < which.size(); i++) {
Point2i p(i % cols, i / cols);
Rect2i r(p * s, s);
r.position += Point2(margin, margin);
r.size -= Point2(margin, margin) * 2.0;
perf_draw->draw_style_box(graph_sb, r);
r.position += graph_sb->get_offset();
r.size -= graph_sb->get_minimum_size();
const int pi = which[i];
// Draw horizontal lines with labels.
int nb_lines = 5;
// Draw less lines if the monitor isn't tall enough to display 5 labels.
if (r.size.height <= 160 * EDSCALE) {
nb_lines = 3;
} else if (r.size.height <= 240 * EDSCALE) {
nb_lines = 4;
}
const float inv_nb_lines = 1.0 / nb_lines;
for (int line = 0; line < nb_lines; line += 1) {
const int from_x = r.position.x;
const int to_x = r.position.x + r.size.width;
const int y = r.position.y + (r.size.height * inv_nb_lines + line * inv_nb_lines * r.size.height);
perf_draw->draw_line(
Point2(from_x, y),
Point2i(to_x, y),
Color(0.5, 0.5, 0.5, 0.25),
Math::round(EDSCALE));
String label;
switch (Performance::MonitorType((int)perf_items[pi]->get_metadata(1))) {
case Performance::MONITOR_TYPE_MEMORY: {
label = String::humanize_size(Math::ceil((1 - inv_nb_lines - inv_nb_lines * line) * perf_max[pi]));
} break;
case Performance::MONITOR_TYPE_TIME: {
label = rtos((1 - inv_nb_lines - inv_nb_lines * line) * perf_max[pi] * 1000).pad_decimals(2) + " ms";
} break;
default: {
label = itos(Math::ceil((1 - inv_nb_lines - inv_nb_lines * line) * perf_max[pi]));
} break;
}
perf_draw->draw_string(
graph_font,
Point2(from_x, y - graph_font->get_ascent() * 0.25),
label,
Color(0.5, 0.5, 0.5, 1.0));
}
const float h = (float)which[i] / (float)(perf_items.size());
// Use a darker color on light backgrounds for better visibility.
const float value_multiplier = EditorSettings::get_singleton()->is_dark_theme() ? 1.4 : 0.55;
Color color = get_theme_color("accent_color", "Editor");
color.set_hsv(Math::fmod(h + 0.4, 0.9), color.get_s() * 0.9, color.get_v() * value_multiplier);
// Draw the monitor name in the top-left corner.
color.a = 0.6;
perf_draw->draw_string(
graph_font,
r.position + Point2(0, graph_font->get_ascent()),
perf_items[pi]->get_text(0),
color,
r.size.x);
// Draw the monitor value in the top-left corner, just below the name.
color.a = 0.9;
perf_draw->draw_string(
graph_font,
r.position + Point2(0, graph_font->get_ascent() + graph_font->get_height()),
perf_items[pi]->get_text(1),
color,
r.size.y);
const float spacing = point_sep / float(cols);
float from = r.size.width;
const List<Vector<float>>::Element *E = perf_history.front();
float prev = -1;
while (from >= 0 && E) {
float m = perf_max[pi];
if (m == 0) {
m = 0.00001;
}
float h2 = E->get()[pi] / m;
h2 = (1.0 - h2) * r.size.y;
if (E != perf_history.front()) {
perf_draw->draw_line(
r.position + Point2(from, h2),
r.position + Point2(from + spacing, prev),
color,
Math::round(EDSCALE));
}
prev = h2;
E = E->next();
from -= spacing;
}
}
}
void ScriptEditorDebugger::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@ -976,10 +837,7 @@ void ScriptEditorDebugger::start(Ref<RemoteDebuggerPeer> p_peer) {
peer = p_peer;
ERR_FAIL_COND(p_peer.is_null());
perf_history.clear();
for (int i = 0; i < Performance::MONITOR_MAX; i++) {
perf_max.write[i] = 0;
}
performance_profiler->reset();
set_process(true);
breaked = false;
@ -1727,63 +1585,8 @@ ScriptEditorDebugger::ScriptEditorDebugger(EditorNode *p_editor) {
}
{ //monitors
HSplitContainer *hsp = memnew(HSplitContainer);
perf_monitors = memnew(Tree);
perf_monitors->set_columns(2);
perf_monitors->set_column_title(0, TTR("Monitor"));
perf_monitors->set_column_title(1, TTR("Value"));
perf_monitors->set_column_titles_visible(true);
perf_monitors->connect("item_edited", callable_mp(this, &ScriptEditorDebugger::_performance_select));
hsp->add_child(perf_monitors);
perf_draw = memnew(Control);
perf_draw->set_clip_contents(true);
perf_draw->connect("draw", callable_mp(this, &ScriptEditorDebugger::_performance_draw));
hsp->add_child(perf_draw);
hsp->set_name(TTR("Monitors"));
hsp->set_split_offset(340 * EDSCALE);
tabs->add_child(hsp);
perf_max.resize(Performance::MONITOR_MAX);
Map<String, TreeItem *> bases;
TreeItem *root = perf_monitors->create_item();
perf_monitors->set_hide_root(true);
for (int i = 0; i < Performance::MONITOR_MAX; i++) {
String n = Performance::get_singleton()->get_monitor_name(Performance::Monitor(i));
Performance::MonitorType mtype = Performance::get_singleton()->get_monitor_type(Performance::Monitor(i));
String base = n.get_slice("/", 0);
String name = n.get_slice("/", 1);
if (!bases.has(base)) {
TreeItem *b = perf_monitors->create_item(root);
b->set_text(0, base.capitalize());
b->set_editable(0, false);
b->set_selectable(0, false);
b->set_expand_right(0, true);
bases[base] = b;
}
TreeItem *it = perf_monitors->create_item(bases[base]);
it->set_metadata(1, mtype);
it->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
it->set_editable(0, true);
it->set_selectable(0, false);
it->set_selectable(1, false);
it->set_text(0, name.capitalize());
perf_items.push_back(it);
perf_max.write[i] = 0;
}
info_message = memnew(Label);
info_message->set_text(TTR("Pick one or more items from the list to display the graph."));
info_message->set_valign(Label::VALIGN_CENTER);
info_message->set_align(Label::ALIGN_CENTER);
info_message->set_autowrap(true);
info_message->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
info_message->set_anchors_and_margins_preset(PRESET_WIDE, PRESET_MODE_KEEP_SIZE, 8 * EDSCALE);
perf_draw->add_child(info_message);
performance_profiler = memnew(EditorPerformanceProfiler);
tabs->add_child(performance_profiler);
}
{ //vmem inspect

View file

@ -52,6 +52,7 @@ class ItemList;
class EditorProfiler;
class EditorVisualProfiler;
class EditorNetworkProfiler;
class EditorPerformanceProfiler;
class SceneDebuggerTree;
class ScriptEditorDebugger : public MarginContainer {
@ -113,16 +114,8 @@ private:
// Each debugger should have it's tree in the future I guess.
const Tree *editor_remote_tree = nullptr;
List<Vector<float>> perf_history;
Vector<float> perf_max;
Vector<TreeItem *> perf_items;
Map<int, String> profiler_signature;
Tree *perf_monitors;
Control *perf_draw;
Label *info_message;
Tree *vmem_tree;
Button *vmem_refresh;
Button *vmem_export;
@ -141,6 +134,7 @@ private:
EditorProfiler *profiler;
EditorVisualProfiler *visual_profiler;
EditorNetworkProfiler *network_profiler;
EditorPerformanceProfiler *performance_profiler;
EditorNode *editor;
@ -152,8 +146,6 @@ private:
EditorDebuggerNode::CameraOverride camera_override;
void _performance_draw();
void _performance_select();
void _stack_dump_frame_selected();
void _file_selected(const String &p_file);

View file

@ -43,6 +43,12 @@ Performance *Performance::singleton = nullptr;
void Performance::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_monitor", "monitor"), &Performance::get_monitor);
ClassDB::bind_method(D_METHOD("add_custom_monitor", "id", "callable", "arguments"), &Performance::add_custom_monitor, DEFVAL(Array()));
ClassDB::bind_method(D_METHOD("remove_custom_monitor", "id"), &Performance::remove_custom_monitor);
ClassDB::bind_method(D_METHOD("has_custom_monitor", "id"), &Performance::has_custom_monitor);
ClassDB::bind_method(D_METHOD("get_custom_monitor", "id"), &Performance::get_custom_monitor);
ClassDB::bind_method(D_METHOD("get_monitor_modification_time"), &Performance::get_monitor_modification_time);
ClassDB::bind_method(D_METHOD("get_custom_monitor_names"), &Performance::get_custom_monitor_names);
BIND_ENUM_CONSTANT(TIME_FPS);
BIND_ENUM_CONSTANT(TIME_PROCESS);
@ -231,8 +237,78 @@ void Performance::set_physics_process_time(float p_pt) {
_physics_process_time = p_pt;
}
void Performance::add_custom_monitor(const StringName &p_id, const Callable &p_callable, const Vector<Variant> &p_args) {
ERR_FAIL_COND_MSG(has_custom_monitor(p_id), "Custom monitor with id '" + String(p_id) + "' already exists.");
_monitor_map.insert(p_id, MonitorCall(p_callable, p_args));
_monitor_modification_time = OS::get_singleton()->get_ticks_usec();
}
void Performance::remove_custom_monitor(const StringName &p_id) {
ERR_FAIL_COND_MSG(!has_custom_monitor(p_id), "Custom monitor with id '" + String(p_id) + "' doesn't exists.");
_monitor_map.erase(p_id);
_monitor_modification_time = OS::get_singleton()->get_ticks_usec();
}
bool Performance::has_custom_monitor(const StringName &p_id) {
return _monitor_map.has(p_id);
}
Variant Performance::get_custom_monitor(const StringName &p_id) {
ERR_FAIL_COND_V_MSG(!has_custom_monitor(p_id), Variant(), "Custom monitor with id '" + String(p_id) + "' doesn't exists.");
bool error;
String error_message;
Variant return_value = _monitor_map[p_id].call(error, error_message);
ERR_FAIL_COND_V_MSG(error, return_value, "Error calling from custom monitor '" + String(p_id) + "' to callable: " + error_message);
return return_value;
}
Array Performance::get_custom_monitor_names() {
if (!_monitor_map.size()) {
return Array();
}
Array return_array;
return_array.resize(_monitor_map.size());
int index = 0;
for (OrderedHashMap<StringName, MonitorCall>::Element i = _monitor_map.front(); i; i = i.next()) {
return_array.set(index, i.key());
index++;
}
return return_array;
}
uint64_t Performance::get_monitor_modification_time() {
return _monitor_modification_time;
}
Performance::Performance() {
_process_time = 0;
_physics_process_time = 0;
_monitor_modification_time = 0;
singleton = this;
}
Performance::MonitorCall::MonitorCall(Callable p_callable, Vector<Variant> p_arguments) {
_callable = p_callable;
_arguments = p_arguments;
}
Performance::MonitorCall::MonitorCall() {
}
Variant Performance::MonitorCall::call(bool &r_error, String &r_error_message) {
Vector<const Variant *> arguments_mem;
arguments_mem.resize(_arguments.size());
for (int i = 0; i < _arguments.size(); i++) {
arguments_mem.write[i] = &_arguments[i];
}
const Variant **args = (const Variant **)arguments_mem.ptr();
int argc = _arguments.size();
Variant return_value;
Callable::CallError error;
_callable.call(args, argc, return_value, error);
r_error = (error.error != Callable::CallError::CALL_OK);
if (r_error) {
r_error_message = Variant::get_callable_error_text(_callable, args, argc, error);
}
return return_value;
}

View file

@ -32,6 +32,7 @@
#define PERFORMANCE_H
#include "core/object.h"
#include "core/ordered_hash_map.h"
#define PERF_WARN_OFFLINE_FUNCTION
#define PERF_WARN_PROCESS_SYNC
@ -47,6 +48,19 @@ class Performance : public Object {
float _process_time;
float _physics_process_time;
class MonitorCall {
Callable _callable;
Vector<Variant> _arguments;
public:
MonitorCall(Callable p_callable, Vector<Variant> p_arguments);
MonitorCall();
Variant call(bool &r_error, String &r_error_message);
};
OrderedHashMap<StringName, MonitorCall> _monitor_map;
uint64_t _monitor_modification_time;
public:
enum Monitor {
@ -95,6 +109,14 @@ public:
void set_process_time(float p_pt);
void set_physics_process_time(float p_pt);
void add_custom_monitor(const StringName &p_id, const Callable &p_callable, const Vector<Variant> &p_args);
void remove_custom_monitor(const StringName &p_id);
bool has_custom_monitor(const StringName &p_id);
Variant get_custom_monitor(const StringName &p_id);
Array get_custom_monitor_names();
uint64_t get_monitor_modification_time();
static Performance *get_singleton() { return singleton; }
Performance();